1 from types import StringTypes
5 from PLC.Faults import *
6 from PLC.Parameter import Parameter
10 Representation of a row in a database table. To use, optionally
11 instantiate with a dict of values. Update as you would a
12 dict. Commit to the database with sync().
15 # Set this to the name of the table that stores the row.
18 # Set this to the name of the primary key of the table. It is
19 # assumed that the this key is a sequence if it is not set when
23 # Set this to the names of tables that reference this table's
27 # Set this to a dict of the valid fields of this object and their
28 # types. Not all fields (e.g., joined fields) may be updated via
32 def __init__(self, api, fields = {}):
33 dict.__init__(self, fields)
38 Validates values. Will validate a value with a custom function
39 if a function named 'validate_[key]' exists.
42 # Warn about mandatory fields
43 mandatory_fields = self.api.db.fields(self.table_name, notnull = True, hasdef = False)
44 for field in mandatory_fields:
45 if not self.has_key(field) or self[field] is None:
46 raise PLCInvalidArgument, field + " must be specified and cannot be unset in class %s"%self.__class__.__name__
48 # Validate values before committing
49 for key, value in self.iteritems():
50 if value is not None and hasattr(self, 'validate_' + key):
51 validate = getattr(self, 'validate_' + key)
52 self[key] = validate(value)
54 time_format = "%Y-%m-%d %H:%M:%S"
55 def validate_timestamp (self, timestamp, check_future=False):
56 # in case we try to sync the same object twice
57 if isinstance(timestamp, StringTypes):
58 # calendar.timegm is the inverse of time.gmtime, in that it computes in UTC
59 # surprisingly enough, no other method in the time module behaves this way
60 # this method is documented in the time module's documentation
61 timestamp = calendar.timegm (time.strptime (timestamp,Row.time_format))
62 human = time.strftime (Row.time_format, time.gmtime(timestamp))
63 if check_future and (timestamp < time.time()):
64 raise PLCInvalidArgument, "%s: date must be in the future"%human
68 def add_object(self, classobj, join_table, columns = None):
70 Returns a function that can be used to associate this object
74 def add(self, obj, columns = None, commit = True):
76 Associate with the specified object.
79 # Various sanity checks
80 assert isinstance(self, Row)
81 assert self.primary_key in self
82 assert join_table in self.join_tables
83 assert isinstance(obj, classobj)
84 assert isinstance(obj, Row)
85 assert obj.primary_key in obj
86 assert join_table in obj.join_tables
88 # By default, just insert the primary keys of each object
89 # into the join table.
91 columns = {self.primary_key: self[self.primary_key],
92 obj.primary_key: obj[obj.primary_key]}
95 for name, value in columns.iteritems():
96 params.append(self.api.db.param(name, value))
98 self.api.db.do("INSERT INTO %s (%s) VALUES(%s)" % \
99 (join_table, ", ".join(columns), ", ".join(params)),
108 def remove_object(self, classobj, join_table):
110 Returns a function that can be used to disassociate this
114 def remove(self, obj, commit = True):
116 Disassociate from the specified object.
119 assert isinstance(self, Row)
120 assert self.primary_key in self
121 assert join_table in self.join_tables
122 assert isinstance(obj, classobj)
123 assert isinstance(obj, Row)
124 assert obj.primary_key in obj
125 assert join_table in obj.join_tables
127 self_id = self[self.primary_key]
128 obj_id = obj[obj.primary_key]
130 self.api.db.do("DELETE FROM %s WHERE %s = %s AND %s = %s" % \
132 self.primary_key, self.api.db.param('self_id', self_id),
133 obj.primary_key, self.api.db.param('obj_id', obj_id)),
141 def db_fields(self, obj = None):
143 Return only those fields that can be set or updated directly
144 (i.e., those fields that are in the primary table (table_name)
145 for this object, and are not marked as a read-only Parameter.
151 db_fields = self.api.db.fields(self.table_name)
152 return dict(filter(lambda (key, value): \
153 key in db_fields and \
154 (key not in self.fields or \
155 not isinstance(self.fields[key], Parameter) or \
156 not self.fields[key].ro),
164 # Filter out fields that cannot be set or updated directly
165 # (and thus would not affect equality for the purposes of
166 # deciding if we should sync() or not).
168 y = self.db_fields(y)
169 return dict.__eq__(x, y)
171 def sync(self, commit = True, insert = None):
173 Flush changes back to the database.
176 # Validate all specified fields
179 # Filter out fields that cannot be set or updated directly
180 db_fields = self.db_fields()
182 # Parameterize for safety
183 keys = db_fields.keys()
184 values = [self.api.db.param(key, value) for (key, value) in db_fields.items()]
186 # If the primary key (usually an auto-incrementing serial
187 # identifier) has not been specified, or the primary key is the
188 # only field in the table, or insert has been forced.
189 if not self.has_key(self.primary_key) or \
190 keys == [self.primary_key] or \
193 sql = "INSERT INTO %s (%s) VALUES (%s)" % \
194 (self.table_name, ", ".join(keys), ", ".join(values))
196 # Update existing row
197 columns = ["%s = %s" % (key, value) for (key, value) in zip(keys, values)]
198 sql = "UPDATE %s SET " % self.table_name + \
199 ", ".join(columns) + \
202 self.api.db.param(self.primary_key, self[self.primary_key]))
204 self.api.db.do(sql, db_fields)
206 if not self.has_key(self.primary_key):
207 self[self.primary_key] = self.api.db.last_insert_id(self.table_name, self.primary_key)
212 def delete(self, commit = True):
214 Delete row from its primary table, and from any tables that
218 assert self.primary_key in self
220 for table in self.join_tables + [self.table_name]:
221 if isinstance(table, tuple):
225 key = self.primary_key
227 sql = "DELETE FROM %s WHERE %s = %s" % \
229 self.api.db.param(self.primary_key, self[self.primary_key]))
231 self.api.db.do(sql, self)
238 Representation of row(s) in a database table.
241 def __init__(self, api, classobj, columns = None):
243 self.classobj = classobj
247 columns = classobj.fields
249 columns = filter(lambda x: x in classobj.fields, columns)
251 raise PLCInvalidArgument, "No valid return fields specified"
253 self.columns = columns
255 def sync(self, commit = True):
257 Flush changes back to the database.
263 def selectall(self, sql, params = None):
265 Given a list of rows from the database, fill ourselves with
269 for row in self.api.db.selectall(sql, params):
270 obj = self.classobj(self.api, row)
273 def dict(self, key_field = None):
275 Return ourself as a dict keyed on key_field.
278 if key_field is None:
279 key_field = self.classobj.primary_key
281 return dict([(obj[key_field], obj) for obj in self])