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.
17 # e.g. table_name = "nodes"
20 # Set this to the name of the primary key of the table. It is
21 # assumed that the this key is a sequence if it is not set when
23 # e.g. primary_key="node_id"
26 # Set this to the names of tables that reference this table's
30 # Set this to a dict of the valid fields of this object and their
31 # types. Not all fields (e.g., joined fields) may be updated via
35 # The name of the view that extends objects with tags
36 # e.g. view_tags_name = "view_node_tags"
39 # Set this to the set of tags that can be returned by the Get function
42 def __init__(self, api, fields = {}):
43 dict.__init__(self, fields)
48 Validates values. Will validate a value with a custom function
49 if a function named 'validate_[key]' exists.
52 # Warn about mandatory fields
53 mandatory_fields = self.api.db.fields(self.table_name, notnull = True, hasdef = False)
54 for field in mandatory_fields:
55 if not self.has_key(field) or self[field] is None:
56 raise PLCInvalidArgument, field + " must be specified and cannot be unset in class %s"%self.__class__.__name__
58 # Validate values before committing
59 for key, value in self.iteritems():
60 if value is not None and hasattr(self, 'validate_' + key):
61 validate = getattr(self, 'validate_' + key)
62 self[key] = validate(value)
64 def separate_types(self, items):
66 Separate a list of different typed objects.
67 Return a list for each type (ints, strs and dicts)
70 if isinstance(items, (list, tuple, set)):
71 ints = filter(lambda x: isinstance(x, (int, long)), items)
72 strs = filter(lambda x: isinstance(x, StringTypes), items)
73 dicts = filter(lambda x: isinstance(x, dict), items)
74 return (ints, strs, dicts)
76 raise PLCInvalidArgument, "Can only separate list types"
79 def associate(self, *args):
81 Provides a means for high level api calls to associate objects
82 using low level calls.
86 raise PLCInvalidArgumentCount, "auth, field, value must be specified"
87 elif hasattr(self, 'associate_' + args[1]):
88 associate = getattr(self, 'associate_'+args[1])
91 raise PLCInvalidArguemnt, "No such associate function associate_%s" % args[1]
93 def validate_timestamp(self, timestamp, check_future = False):
95 Validates the specified GMT timestamp string (must be in
96 %Y-%m-%d %H:%M:%S format) or number (seconds since UNIX epoch,
97 i.e., 1970-01-01 00:00:00 GMT). If check_future is True,
98 raises an exception if timestamp is not in the future. Returns
99 a GMT timestamp string.
102 time_format = "%Y-%m-%d %H:%M:%S"
104 if isinstance(timestamp, StringTypes):
105 # calendar.timegm() is the inverse of time.gmtime()
106 timestamp = calendar.timegm(time.strptime(timestamp, time_format))
108 # Human readable timestamp string
109 human = time.strftime(time_format, time.gmtime(timestamp))
111 if check_future and timestamp < time.time():
112 raise PLCInvalidArgument, "'%s' not in the future" % human
116 def add_object(self, classobj, join_table, columns = None):
118 Returns a function that can be used to associate this object
122 def add(self, obj, columns = None, commit = True):
124 Associate with the specified object.
127 # Various sanity checks
128 assert isinstance(self, Row)
129 assert self.primary_key in self
130 assert join_table in self.join_tables
131 assert isinstance(obj, classobj)
132 assert isinstance(obj, Row)
133 assert obj.primary_key in obj
134 assert join_table in obj.join_tables
136 # By default, just insert the primary keys of each object
137 # into the join table.
139 columns = {self.primary_key: self[self.primary_key],
140 obj.primary_key: obj[obj.primary_key]}
143 for name, value in columns.iteritems():
144 params.append(self.api.db.param(name, value))
146 self.api.db.do("INSERT INTO %s (%s) VALUES(%s)" % \
147 (join_table, ", ".join(columns), ", ".join(params)),
155 add_object = classmethod(add_object)
157 def remove_object(self, classobj, join_table):
159 Returns a function that can be used to disassociate this
163 def remove(self, obj, commit = True):
165 Disassociate from the specified object.
168 assert isinstance(self, Row)
169 assert self.primary_key in self
170 assert join_table in self.join_tables
171 assert isinstance(obj, classobj)
172 assert isinstance(obj, Row)
173 assert obj.primary_key in obj
174 assert join_table in obj.join_tables
176 self_id = self[self.primary_key]
177 obj_id = obj[obj.primary_key]
179 self.api.db.do("DELETE FROM %s WHERE %s = %s AND %s = %s" % \
181 self.primary_key, self.api.db.param('self_id', self_id),
182 obj.primary_key, self.api.db.param('obj_id', obj_id)),
190 remove_object = classmethod(remove_object)
192 # convenience: check in dict (self.fields or self.tags) that a key is writable
194 def is_writable (key,value,dict):
195 # if not mentioned, assume it's writable (e.g. deleted ...)
196 if key not in dict: return True
197 # if mentioned but not linked to a Parameter object, idem
198 if not isinstance(dict[key], Parameter): return True
199 # if not marked ro, it's writable
200 if not dict[key].ro: return True
203 def db_fields(self, obj = None):
205 Return only those fields that can be set or updated directly
206 (i.e., those fields that are in the primary table (table_name)
207 for this object, and are not marked as a read-only Parameter.
210 if obj is None: obj = self
212 db_fields = self.api.db.fields(self.table_name)
213 return dict ( [ (key,value) for (key,value) in obj.items()
214 if key in db_fields and
215 Row.is_writable(key,value,self.fields) ] )
217 def tag_fields (self, obj=None):
219 Return the fields of obj that are mentioned in tags
221 if obj is None: obj=self
223 return dict ( [ (key,value) for (key,value) in obj.iteritems()
224 if key in self.tags and Row.is_writable(key,value,self.tags) ] )
226 # takes in input a list of columns, returns 2 dicts and one list
227 # fields, tags, rejected
229 def parse_columns (cls, columns):
230 (fields,tags,rejected)=({},{},[])
231 for column in columns:
232 if column in cls.fields: fields[column]=cls.fields[column]
233 elif column in cls.tags: tags[column]=cls.tags[column]
234 else: rejected.append(column)
235 return (fields,tags,rejected)
237 # given a dict (typically passed to an Update method), we check and sort
238 # them against a list of dicts, e.g. [Node.fields, Node.related_fields]
239 # return is a list that contains n+1 dicts, last one has the rejected fields
241 def split_fields (fields, dicts):
243 for x in dicts: result.append({})
245 for (field,value) in fields.iteritems():
247 for i in range(len(dicts)):
248 candidate_dict=dicts[i]
249 if field in candidate_dict.keys():
250 result[i][field]=value
253 if not found: rejected[field]=value
254 result.append(rejected)
257 # compute the accepts part of an update method from a list of column names, and a (list of) field dict
259 def accepted_fields (can_update_columns, fields):
261 if not isinstance(fields,list): fields = [fields]
263 for (k,v) in dict.iteritems():
264 if k in can_update_columns:
269 def tagvalue_view_name (cls, tagname):
270 return "tagvalue_view_%s_%s"%(cls.primary_key,tagname)
273 def tagvalue_view_create (cls,tagname):
275 returns an SQL sentence that creates a view named after the primary_key and tagname,
277 (*) column 1: name=self.primary_key
278 (*) column 2: name=tagname value=tagvalue
281 if not cls.view_tags_name: return ""
283 table_name=cls.table_name
284 primary_key=cls.primary_key
285 view_tags_name=cls.view_tags_name
286 tagvalue_view_name=cls.tagvalue_view_name(tagname)
287 return 'CREATE OR REPLACE VIEW %(tagvalue_view_name)s ' \
288 'as SELECT %(table_name)s.%(primary_key)s,%(view_tags_name)s.tagvalue as "%(tagname)s" ' \
289 'from %(table_name)s right join %(view_tags_name)s using (%(primary_key)s) ' \
290 'WHERE tagname = \'%(tagname)s\';'%locals()
293 def tagvalue_views_create (cls):
294 if not cls.tags: return
296 for (type,type_dict) in cls.tags.iteritems():
297 for (tagname,details) in type_dict.iteritems():
298 sql.append(cls.tagvalue_view_create (tagname))
306 # Filter out fields that cannot be set or updated directly
307 # (and thus would not affect equality for the purposes of
308 # deciding if we should sync() or not).
310 y = self.db_fields(y)
311 return dict.__eq__(x, y)
313 def sync(self, commit = True, insert = None):
315 Flush changes back to the database.
318 # Validate all specified fields
321 # Filter out fields that cannot be set or updated directly
322 db_fields = self.db_fields()
324 # Parameterize for safety
325 keys = db_fields.keys()
326 values = [self.api.db.param(key, value) for (key, value) in db_fields.items()]
328 # If the primary key (usually an auto-incrementing serial
329 # identifier) has not been specified, or the primary key is the
330 # only field in the table, or insert has been forced.
331 if not self.has_key(self.primary_key) or \
332 keys == [self.primary_key] or \
335 # If primary key id is a serial int and it isnt included, get next id
336 if self.fields[self.primary_key].type in (IntType, LongType) and \
337 self.primary_key not in self:
338 pk_id = self.api.db.next_id(self.table_name, self.primary_key)
339 self[self.primary_key] = pk_id
340 db_fields[self.primary_key] = pk_id
341 keys = db_fields.keys()
342 values = [self.api.db.param(key, value) for (key, value) in db_fields.items()]
344 sql = "INSERT INTO %s (%s) VALUES (%s)" % \
345 (self.table_name, ", ".join(keys), ", ".join(values))
347 # Update existing row
348 columns = ["%s = %s" % (key, value) for (key, value) in zip(keys, values)]
349 sql = "UPDATE %s SET " % self.table_name + \
350 ", ".join(columns) + \
353 self.api.db.param(self.primary_key, self[self.primary_key]))
355 self.api.db.do(sql, db_fields)
360 def delete(self, commit = True):
362 Delete row from its primary table, and from any tables that
366 assert self.primary_key in self
368 for table in self.join_tables + [self.table_name]:
369 if isinstance(table, tuple):
373 key = self.primary_key
375 sql = "DELETE FROM %s WHERE %s = %s" % \
377 self.api.db.param(self.primary_key, self[self.primary_key]))
379 self.api.db.do(sql, self)
386 Representation of row(s) in a database table.
389 def __init__(self, api, classobj, columns = None):
391 self.classobj = classobj
395 columns = classobj.fields
398 (columns,tag_columns,rejected) = classobj.parse_columns(columns)
400 raise PLCInvalidArgument, "No valid return fields specified for class %s"%classobj.__name__
402 raise PLCInvalidArgument, "unknown column(s) specified %r in %s"%(rejected,classobj.__name__)
404 self.columns = columns
405 self.tag_columns = tag_columns
407 def sync(self, commit = True):
409 Flush changes back to the database.
415 def selectall(self, sql, params = None):
417 Given a list of rows from the database, fill ourselves with
421 for row in self.api.db.selectall(sql, params):
422 obj = self.classobj(self.api, row)
425 def dict(self, key_field = None):
427 Return ourself as a dict keyed on key_field.
430 if key_field is None:
431 key_field = self.classobj.primary_key
433 return dict([(obj[key_field], obj) for obj in self])