- def sync(self, commit = True):
- """
- Commit changes back to the database.
- """
-
- self.validate()
-
- # Fetch a new person_id if necessary
- if 'person_id' not in self:
- rows = self.api.db.selectall("SELECT NEXTVAL('persons_person_id_seq') AS person_id")
- if not rows:
- raise PLCDBError, "Unable to fetch new person_id"
- self['person_id'] = rows[0]['person_id']
- insert = True
- else:
- insert = False
-
- # Filter out fields that cannot be set or updated directly
- persons_fields = self.api.db.fields('persons')
- fields = dict(filter(lambda (key, value): key in persons_fields,
- self.items()))
- for ro_field in 'date_created', 'last_updated':
- if ro_field in fields:
- del fields[ro_field]
-
- # Parameterize for safety
- keys = fields.keys()
- values = [self.api.db.param(key, value) for (key, value) in fields.items()]
-
- if insert:
- # Insert new row in persons table
- sql = "INSERT INTO persons (%s) VALUES (%s)" % \
- (", ".join(keys), ", ".join(values))
- else:
- # Update existing row in persons table
- columns = ["%s = %s" % (key, value) for (key, value) in zip(keys, values)]
- sql = "UPDATE persons SET " + \
- ", ".join(columns) + \
- " WHERE person_id = %(person_id)d"
-
- self.api.db.do(sql, fields)
-
- if commit:
- self.api.db.commit()
-