2 from types import StringTypes, IntType, LongType
6 from PLC.Faults import *
7 from PLC.Parameter import Parameter
11 Representation of a row in a database table. To use, optionally
12 instantiate with a dict of values. Update as you would a
13 dict. Commit to the database with sync().
16 # Set this to the name of the table that stores the row.
19 # Set this to the name of the primary key of the table. It is
20 # assumed that the this key is a sequence if it is not set when
24 # Set this to the names of tables that reference this table's
28 # Set this to a dict of the valid fields of this object and their
29 # types. Not all fields (e.g., joined fields) may be updated via
33 def __init__(self, api, fields = {}):
34 dict.__init__(self, fields)
39 Validates values. Will validate a value with a custom function
40 if a function named 'validate_[key]' exists.
43 # Warn about mandatory fields
44 mandatory_fields = self.api.db.fields(self.table_name, notnull = True, hasdef = False)
45 for field in mandatory_fields:
46 if not self.has_key(field) or self[field] is None:
47 raise PLCInvalidArgument, field + " must be specified and cannot be unset in class %s"%self.__class__.__name__
49 # Validate values before committing
50 for key, value in self.iteritems():
51 if value is not None and hasattr(self, 'validate_' + key):
52 validate = getattr(self, 'validate_' + key)
53 self[key] = validate(value)
55 def separate_types(self, items):
57 Separate a list of different typed objects.
58 Return a list for each type (ints, strs and dicts)
61 if isinstance(items, (list, tuple, set)):
62 ints = filter(lambda x: isinstance(x, (int, long)), items)
63 strs = filter(lambda x: isinstance(x, StringTypes), items)
64 dicts = filter(lambda x: isinstance(x, dict), items)
65 return (ints, strs, dicts)
67 raise PLCInvalidArgument, "Can only separate list types"
70 def associate(self, *args):
72 Provides a means for high lvl api calls to associate objects
77 raise PLCInvalidArgumentCount, "auth, field, value must be specified"
78 elif hasattr(self, 'associate_' + args[1]):
79 associate = getattr(self, 'associate_'+args[1])
82 raise PLCInvalidArguemnt, "No such associate function associate_%s" % args[1]
84 def validate_timestamp(self, timestamp, check_future = False):
86 Validates the specified GMT timestamp string (must be in
87 %Y-%m-%d %H:%M:%S format) or number (seconds since UNIX epoch,
88 i.e., 1970-01-01 00:00:00 GMT). If check_future is True,
89 raises an exception if timestamp is not in the future. Returns
90 a GMT timestamp string.
93 time_format = "%Y-%m-%d %H:%M:%S"
95 if isinstance(timestamp, StringTypes):
96 # calendar.timegm() is the inverse of time.gmtime()
97 timestamp = calendar.timegm(time.strptime(timestamp, time_format))
99 # Human readable timestamp string
100 human = time.strftime(time_format, time.gmtime(timestamp))
102 if check_future and timestamp < time.time():
103 raise PLCInvalidArgument, "'%s' not in the future" % human
107 def add_object(self, classobj, join_table, columns = None):
109 Returns a function that can be used to associate this object
113 def add(self, obj, columns = None, commit = True):
115 Associate with the specified object.
118 # Various sanity checks
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 # By default, just insert the primary keys of each object
128 # into the join table.
130 columns = {self.primary_key: self[self.primary_key],
131 obj.primary_key: obj[obj.primary_key]}
134 for name, value in columns.iteritems():
135 params.append(self.api.db.param(name, value))
137 self.api.db.do("INSERT INTO %s (%s) VALUES(%s)" % \
138 (join_table, ", ".join(columns), ", ".join(params)),
146 add_object = classmethod(add_object)
148 def remove_object(self, classobj, join_table):
150 Returns a function that can be used to disassociate this
154 def remove(self, obj, commit = True):
156 Disassociate from the specified object.
159 assert isinstance(self, Row)
160 assert self.primary_key in self
161 assert join_table in self.join_tables
162 assert isinstance(obj, classobj)
163 assert isinstance(obj, Row)
164 assert obj.primary_key in obj
165 assert join_table in obj.join_tables
167 self_id = self[self.primary_key]
168 obj_id = obj[obj.primary_key]
170 self.api.db.do("DELETE FROM %s WHERE %s = %s AND %s = %s" % \
172 self.primary_key, self.api.db.param('self_id', self_id),
173 obj.primary_key, self.api.db.param('obj_id', obj_id)),
181 remove_object = classmethod(remove_object)
183 def db_fields(self, obj = None):
185 Return only those fields that can be set or updated directly
186 (i.e., those fields that are in the primary table (table_name)
187 for this object, and are not marked as a read-only Parameter.
193 db_fields = self.api.db.fields(self.table_name)
194 return dict(filter(lambda (key, value): \
195 key in db_fields and \
196 (key not in self.fields or \
197 not isinstance(self.fields[key], Parameter) or \
198 not self.fields[key].ro),
206 # Filter out fields that cannot be set or updated directly
207 # (and thus would not affect equality for the purposes of
208 # deciding if we should sync() or not).
210 y = self.db_fields(y)
211 return dict.__eq__(x, y)
213 def sync(self, commit = True, insert = None):
215 Flush changes back to the database.
218 # Validate all specified fields
221 # Filter out fields that cannot be set or updated directly
222 db_fields = self.db_fields()
224 # Parameterize for safety
225 keys = db_fields.keys()
226 values = [self.api.db.param(key, value) for (key, value) in db_fields.items()]
228 # If the primary key (usually an auto-incrementing serial
229 # identifier) has not been specified, or the primary key is the
230 # only field in the table, or insert has been forced.
231 if not self.has_key(self.primary_key) or \
232 keys == [self.primary_key] or \
235 # If primary key id is a serial int and it isnt included, get next id
236 if self.fields[self.primary_key].type in (IntType, LongType) and \
237 self.primary_key not in self:
238 pk_id = self.api.db.next_id(self.table_name, self.primary_key)
239 self[self.primary_key] = pk_id
240 db_fields[self.primary_key] = pk_id
241 keys = db_fields.keys()
242 values = [self.api.db.param(key, value) for (key, value) in db_fields.items()]
244 sql = "INSERT INTO %s (%s) VALUES (%s)" % \
245 (self.table_name, ", ".join(keys), ", ".join(values))
247 # Update existing row
248 columns = ["%s = %s" % (key, value) for (key, value) in zip(keys, values)]
249 sql = "UPDATE %s SET " % self.table_name + \
250 ", ".join(columns) + \
253 self.api.db.param(self.primary_key, self[self.primary_key]))
255 self.api.db.do(sql, db_fields)
260 def delete(self, commit = True):
262 Delete row from its primary table, and from any tables that
266 assert self.primary_key in self
268 for table in self.join_tables + [self.table_name]:
269 if isinstance(table, tuple):
273 key = self.primary_key
275 sql = "DELETE FROM %s WHERE %s = %s" % \
277 self.api.db.param(self.primary_key, self[self.primary_key]))
279 self.api.db.do(sql, self)
286 Representation of row(s) in a database table.
289 def __init__(self, api, classobj, columns = None):
291 self.classobj = classobj
295 columns = classobj.fields
297 columns = filter(lambda x: x in classobj.fields, columns)
299 raise PLCInvalidArgument, "No valid return fields specified"
301 self.columns = columns
303 def sync(self, commit = True):
305 Flush changes back to the database.
311 def selectall(self, sql, params = None):
313 Given a list of rows from the database, fill ourselves with
317 for row in self.api.db.selectall(sql, params):
318 obj = self.classobj(self.api, row)
321 def dict(self, key_field = None):
323 Return ourself as a dict keyed on key_field.
326 if key_field is None:
327 key_field = self.classobj.primary_key
329 return dict([(obj[key_field], obj) for obj in self])