1 from PLC.Faults import *
2 from PLC.Parameter import Parameter
6 Representation of a row in a database table. To use, optionally
7 instantiate with a dict of values. Update as you would a
8 dict. Commit to the database with sync().
11 # Set this to the name of the table that stores the row.
14 # Set this to the name of the primary key of the table. It is
15 # assumed that the this key is a sequence if it is not set when
19 # Set this to a dict of the valid fields of this object. Not all
20 # fields (e.g., joined fields) may be updated via sync().
25 Validates values. Will validate a value with a custom function
26 if a function named 'validate_[key]' exists.
29 # Warn about mandatory fields
30 mandatory_fields = self.api.db.fields(self.table_name, notnull = True, hasdef = False)
31 for field in mandatory_fields:
32 if not self.has_key(field) or self[field] is None:
33 raise PLCInvalidArgument, field + " must be specified and cannot be unset"
35 # Validate values before committing
36 for key, value in self.iteritems():
37 if value is not None and hasattr(self, 'validate_' + key):
38 validate = getattr(self, 'validate_' + key)
39 self[key] = validate(value)
41 def sync(self, commit = True):
43 Flush changes back to the database.
46 # Validate all specified fields
49 # Filter out fields that cannot be set or updated directly
50 all_fields = self.api.db.fields(self.table_name)
51 fields = dict(filter(lambda (key, value): \
52 key in all_fields and \
53 (key not in self.fields or \
54 not isinstance(self.fields[key], Parameter) or \
55 not self.fields[key].ro),
58 # Parameterize for safety
60 values = [self.api.db.param(key, value) for (key, value) in fields.items()]
62 if not self.has_key(self.primary_key):
64 sql = "INSERT INTO %s (%s) VALUES (%s);" % \
65 (self.table_name, ", ".join(keys), ", ".join(values))
68 columns = ["%s = %s" % (key, value) for (key, value) in zip(keys, values)]
69 sql = "UPDATE %s SET " % self.table_name + \
70 ", ".join(columns) + \
73 self.api.db.param(self.primary_key, self[self.primary_key]))
75 self.api.db.do(sql, fields)
77 if not self.has_key(self.primary_key):
78 self[self.primary_key] = self.api.db.last_insert_id(self.table_name, self.primary_key)
83 def delete(self, commit = True):
85 Delete row from its primary table.
88 assert self.primary_key in self
90 sql = "DELETE FROM %s" % self.table_name + \
93 self.api.db.param(self.primary_key, self[self.primary_key]))
95 self.api.db.do(sql, self)
102 Representation of row(s) in a database table.
105 def sync(self, commit = True):
107 Flush changes back to the database.
110 for row in self.values():