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)
45 # run the class_init initializer once
47 if not hasattr(cls,'class_inited'):
49 cls.class_inited=True # actual value does not matter
53 Validates values. Will validate a value with a custom function
54 if a function named 'validate_[key]' exists.
57 # Warn about mandatory fields
58 mandatory_fields = self.api.db.fields(self.table_name, notnull = True, hasdef = False)
59 for field in mandatory_fields:
60 if not self.has_key(field) or self[field] is None:
61 raise PLCInvalidArgument, field + " must be specified and cannot be unset in class %s"%self.__class__.__name__
63 # Validate values before committing
64 for key, value in self.iteritems():
65 if value is not None and hasattr(self, 'validate_' + key):
66 validate = getattr(self, 'validate_' + key)
67 self[key] = validate(value)
69 def separate_types(self, items):
71 Separate a list of different typed objects.
72 Return a list for each type (ints, strs and dicts)
75 if isinstance(items, (list, tuple, set)):
76 ints = filter(lambda x: isinstance(x, (int, long)), items)
77 strs = filter(lambda x: isinstance(x, StringTypes), items)
78 dicts = filter(lambda x: isinstance(x, dict), items)
79 return (ints, strs, dicts)
81 raise PLCInvalidArgument, "Can only separate list types"
84 def associate(self, *args):
86 Provides a means for high level api calls to associate objects
87 using low level calls.
91 raise PLCInvalidArgumentCount, "auth, field, value must be specified"
92 elif hasattr(self, 'associate_' + args[1]):
93 associate = getattr(self, 'associate_'+args[1])
96 raise PLCInvalidArguemnt, "No such associate function associate_%s" % args[1]
98 def validate_timestamp(self, timestamp, check_future = False):
100 Validates the specified GMT timestamp string (must be in
101 %Y-%m-%d %H:%M:%S format) or number (seconds since UNIX epoch,
102 i.e., 1970-01-01 00:00:00 GMT). If check_future is True,
103 raises an exception if timestamp is not in the future. Returns
104 a GMT timestamp string.
107 time_format = "%Y-%m-%d %H:%M:%S"
109 if isinstance(timestamp, StringTypes):
110 # calendar.timegm() is the inverse of time.gmtime()
111 timestamp = calendar.timegm(time.strptime(timestamp, time_format))
113 # Human readable timestamp string
114 human = time.strftime(time_format, time.gmtime(timestamp))
116 if check_future and timestamp < time.time():
117 raise PLCInvalidArgument, "'%s' not in the future" % human
121 def add_object(self, classobj, join_table, columns = None):
123 Returns a function that can be used to associate this object
127 def add(self, obj, columns = None, commit = True):
129 Associate with the specified object.
132 # Various sanity checks
133 assert isinstance(self, Row)
134 assert self.primary_key in self
135 assert join_table in self.join_tables
136 assert isinstance(obj, classobj)
137 assert isinstance(obj, Row)
138 assert obj.primary_key in obj
139 assert join_table in obj.join_tables
141 # By default, just insert the primary keys of each object
142 # into the join table.
144 columns = {self.primary_key: self[self.primary_key],
145 obj.primary_key: obj[obj.primary_key]}
148 for name, value in columns.iteritems():
149 params.append(self.api.db.param(name, value))
151 self.api.db.do("INSERT INTO %s (%s) VALUES(%s)" % \
152 (join_table, ", ".join(columns), ", ".join(params)),
160 add_object = classmethod(add_object)
162 def remove_object(self, classobj, join_table):
164 Returns a function that can be used to disassociate this
168 def remove(self, obj, commit = True):
170 Disassociate from the specified object.
173 assert isinstance(self, Row)
174 assert self.primary_key in self
175 assert join_table in self.join_tables
176 assert isinstance(obj, classobj)
177 assert isinstance(obj, Row)
178 assert obj.primary_key in obj
179 assert join_table in obj.join_tables
181 self_id = self[self.primary_key]
182 obj_id = obj[obj.primary_key]
184 self.api.db.do("DELETE FROM %s WHERE %s = %s AND %s = %s" % \
186 self.primary_key, self.api.db.param('self_id', self_id),
187 obj.primary_key, self.api.db.param('obj_id', obj_id)),
195 remove_object = classmethod(remove_object)
197 # convenience: check in dict (self.fields or self.tags) that a key is writable
199 def is_writable (key,value,dict):
200 # if not mentioned, assume it's writable (e.g. deleted ...)
201 if key not in dict: return True
202 # if mentioned but not linked to a Parameter object, idem
203 if not isinstance(dict[key], Parameter): return True
204 # if not marked ro, it's writable
205 if not dict[key].ro: return True
208 def db_fields(self, obj = None):
210 Return only those fields that can be set or updated directly
211 (i.e., those fields that are in the primary table (table_name)
212 for this object, and are not marked as a read-only Parameter.
215 if obj is None: obj = self
217 db_fields = self.api.db.fields(self.table_name)
218 return dict ( [ (key,value) for (key,value) in obj.items()
219 if key in db_fields and
220 Row.is_writable(key,value,self.fields) ] )
222 def tag_fields (self, obj=None):
224 Return the fields of obj that are mentioned in tags
226 if obj is None: obj=self
228 return dict ( [ (key,value) for (key,value) in obj.iteritems()
229 if key in self.tags and Row.is_writable(key,value,self.tags) ] )
231 # takes in input a list of columns, returns 2 dicts and one list
232 # fields, tags, rejected
234 def parse_columns (cls, columns):
235 (fields,tags,rejected)=({},{},[])
236 for column in columns:
237 if column in cls.fields: fields[column]=cls.fields[column]
238 elif column in cls.tags: tags[column]=cls.tags[column]
239 else: rejected.append(column)
240 return (fields,tags,rejected)
242 # given a dict (typically passed to an Update method), we check and sort
243 # them against a list of dicts, e.g. [Node.fields, Node.related_fields]
244 # return is a list that contains n+1 dicts, last one has the rejected fields
246 def split_fields (fields, dicts):
248 for x in dicts: result.append({})
250 for (field,value) in fields.iteritems():
252 for i in range(len(dicts)):
253 candidate_dict=dicts[i]
254 if field in candidate_dict.keys():
255 result[i][field]=value
258 if not found: rejected[field]=value
259 result.append(rejected)
262 # compute the accepts part of an update method from a list of column names, and a (list of) fields dict
264 def accepted_fields (can_update_columns, fields):
266 if not isinstance(fields,list): fields = [fields]
268 for (k,v) in dict.iteritems():
269 if k in can_update_columns:
273 ### class initialization : create tag-dependent cross view if needed
275 def tagvalue_view_name (cls, tagname):
276 return "tagvalue_view_%s_%s"%(cls.primary_key,tagname)
279 def tagvalue_view_create_sql (cls,tagname):
281 returns a SQL sentence that creates a view named after the primary_key and tagname,
283 (*) column 1: primary_key
284 (*) column 2: actual tag value, renamed into tagname
287 if not cls.view_tags_name:
288 raise Exception, 'WARNING: class %s needs to set view_tags_name'%cls.__name__
290 table_name=cls.table_name
291 primary_key=cls.primary_key
292 view_tags_name=cls.view_tags_name
293 tagvalue_view_name=cls.tagvalue_view_name(tagname)
294 return 'CREATE OR REPLACE VIEW %(tagvalue_view_name)s ' \
295 'as SELECT %(table_name)s.%(primary_key)s,%(view_tags_name)s.value as "%(tagname)s" ' \
296 'from %(table_name)s right join %(view_tags_name)s using (%(primary_key)s) ' \
297 'WHERE tagname = \'%(tagname)s\';'%locals()
300 def class_init (cls,api):
301 cls.tagvalue_views_create (api)
304 def tagvalue_views_create (cls,api):
305 if not cls.tags: return
306 for tagname in cls.tags.keys():
307 api.db.do(cls.tagvalue_view_create_sql (tagname))
315 # Filter out fields that cannot be set or updated directly
316 # (and thus would not affect equality for the purposes of
317 # deciding if we should sync() or not).
319 y = self.db_fields(y)
320 return dict.__eq__(x, y)
322 def sync(self, commit = True, insert = None):
324 Flush changes back to the database.
327 # Validate all specified fields
330 # Filter out fields that cannot be set or updated directly
331 db_fields = self.db_fields()
333 # Parameterize for safety
334 keys = db_fields.keys()
335 values = [self.api.db.param(key, value) for (key, value) in db_fields.items()]
337 # If the primary key (usually an auto-incrementing serial
338 # identifier) has not been specified, or the primary key is the
339 # only field in the table, or insert has been forced.
340 if not self.has_key(self.primary_key) or \
341 keys == [self.primary_key] or \
344 # If primary key id is a serial int and it isnt included, get next id
345 if self.fields[self.primary_key].type in (IntType, LongType) and \
346 self.primary_key not in self:
347 pk_id = self.api.db.next_id(self.table_name, self.primary_key)
348 self[self.primary_key] = pk_id
349 db_fields[self.primary_key] = pk_id
350 keys = db_fields.keys()
351 values = [self.api.db.param(key, value) for (key, value) in db_fields.items()]
353 sql = "INSERT INTO %s (%s) VALUES (%s)" % \
354 (self.table_name, ", ".join(keys), ", ".join(values))
356 # Update existing row
357 columns = ["%s = %s" % (key, value) for (key, value) in zip(keys, values)]
358 sql = "UPDATE %s SET " % self.table_name + \
359 ", ".join(columns) + \
362 self.api.db.param(self.primary_key, self[self.primary_key]))
364 self.api.db.do(sql, db_fields)
369 def delete(self, commit = True):
371 Delete row from its primary table, and from any tables that
375 assert self.primary_key in self
377 for table in self.join_tables + [self.table_name]:
378 if isinstance(table, tuple):
382 key = self.primary_key
384 sql = "DELETE FROM %s WHERE %s = %s" % \
386 self.api.db.param(self.primary_key, self[self.primary_key]))
388 self.api.db.do(sql, self)
395 Representation of row(s) in a database table.
398 def __init__(self, api, classobj, columns = None):
400 self.classobj = classobj
404 columns = classobj.fields
407 (columns,tag_columns,rejected) = classobj.parse_columns(columns)
408 if not columns and not tag_columns:
409 raise PLCInvalidArgument, "No valid return fields specified for class %s"%classobj.__name__
411 raise PLCInvalidArgument, "unknown column(s) specified %r in %s"%(rejected,classobj.__name__)
413 self.columns = columns
414 self.tag_columns = tag_columns
416 def sync(self, commit = True):
418 Flush changes back to the database.
424 def selectall(self, sql, params = None):
426 Given a list of rows from the database, fill ourselves with
430 for row in self.api.db.selectall(sql, params):
431 obj = self.classobj(self.api, row)
434 def dict(self, key_field = None):
436 Return ourself as a dict keyed on key_field.
439 if key_field is None:
440 key_field = self.classobj.primary_key
442 return dict([(obj[key_field], obj) for obj in self])