- foreign_fields = {'role_ids': ('role_id', 'person_role'),
- 'roles': ('name', 'roles'),
- 'site_ids': ('site_id', 'person_site'),
- 'key_ids': ('key_id', 'person_key'),
- 'slice_ids': ('slice_id', 'slice_person')
- }
- foreign_keys = {}
- db_fields = filter(lambda field: field not in foreign_fields.keys(), Person.fields.keys())
- all_fields = db_fields + [value[0] for value in foreign_fields.values()]
- fields = []
- _select = "SELECT "
- _from = " FROM persons "
- _join = " LEFT JOIN peer_person USING (person_id) "
- _where = " WHERE deleted IS False "
-
- if not columns:
- # include all columns
- fields = all_fields
- tables = [value[1] for value in foreign_fields.values()]
- tables.sort()
- for key in foreign_fields.keys():
- foreign_keys[foreign_fields[key][0]] = key
- for table in tables:
- if table in ['roles']:
- _join += " LEFT JOIN roles USING(role_id) "
- else:
- _join += " LEFT JOIN %s USING (person_id) " % (table)
- else:
- tables = set()
- columns = filter(lambda column: column in db_fields+foreign_fields.keys(), columns)
- columns.sort()
- for column in columns:
- if column in foreign_fields.keys():
- (field, table) = foreign_fields[column]
- foreign_keys[field] = column
- fields += [field]
- tables.add(table)
- if column in ['roles']:
- _join += " LEFT JOIN roles USING(role_id) "
- else:
- _join += " LEFT JOIN %s USING (person_id)" % \
- (foreign_fields[column][1])
-
- else:
- fields += [column]
-
- # postgres will return timestamps as datetime objects.
- # XMLPRC cannot marshal datetime so convert to int
- timestamps = ['date_created', 'last_updated', 'verification_expires']
- for field in fields:
- if field in timestamps:
- fields[fields.index(field)] = \
- "CAST(date_part('epoch', %s) AS bigint) AS %s" % (field, field)
-
- _select += ", ".join(fields)
- sql = _select + _from + _join + _where
-
- # deal with filter