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 as input a list of columns, sort native fields from tags
232 # returns 2 dicts and one list : 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 # compute the 'accepts' part of a method, from a list of column names, and a fields dict
243 # use exclude=True to exclude the column names instead
244 # typically accepted_fields (Node.fields,['hostname','model',...])
246 def accepted_fields (update_columns, fields_dict, exclude=False):
248 for (k,v) in fields_dict.iteritems():
249 if (not exclude and k in update_columns) or (exclude and k not in update_columns):
253 # filter out user-provided fields that are not part of the declared acceptance list
254 # keep it separate from split_fields for simplicity
255 # typically check_fields (<user_provided_dict>,{'hostname':Parameter(str,...),'model':Parameter(..)...})
257 def check_fields (user_dict, accepted_fields):
258 # avoid the simple, but silent, version
259 # return dict ([ (k,v) for (k,v) in user_dict.items() if k in accepted_fields ])
261 for (k,v) in user_dict.items():
262 if k in accepted_fields: result[k]=v
263 else: raise PLCInvalidArgument ('Trying to set/change unaccepted key %s'%k)
266 # given a dict (typically passed to an Update method), we check and sort
267 # them against a list of dicts, e.g. [Node.fields, Node.related_fields]
268 # return is a list that contains n+1 dicts, last one has the rejected fields
270 def split_fields (fields, dicts):
272 for x in dicts: result.append({})
274 for (field,value) in fields.iteritems():
276 for i in range(len(dicts)):
277 candidate_dict=dicts[i]
278 if field in candidate_dict.keys():
279 result[i][field]=value
282 if not found: rejected[field]=value
283 result.append(rejected)
286 ### class initialization : create tag-dependent cross view if needed
288 def tagvalue_view_name (cls, tagname):
289 return "tagvalue_view_%s_%s"%(cls.primary_key,tagname)
292 def tagvalue_view_create_sql (cls,tagname):
294 returns a SQL sentence that creates a view named after the primary_key and tagname,
296 (*) column 1: primary_key
297 (*) column 2: actual tag value, renamed into tagname
300 if not cls.view_tags_name:
301 raise Exception, 'WARNING: class %s needs to set view_tags_name'%cls.__name__
303 table_name=cls.table_name
304 primary_key=cls.primary_key
305 view_tags_name=cls.view_tags_name
306 tagvalue_view_name=cls.tagvalue_view_name(tagname)
307 return 'CREATE OR REPLACE VIEW %(tagvalue_view_name)s ' \
308 'as SELECT %(table_name)s.%(primary_key)s,%(view_tags_name)s.value as "%(tagname)s" ' \
309 'from %(table_name)s right join %(view_tags_name)s using (%(primary_key)s) ' \
310 'WHERE tagname = \'%(tagname)s\';'%locals()
313 def class_init (cls,api):
314 cls.tagvalue_views_create (api)
317 def tagvalue_views_create (cls,api):
318 if not cls.tags: return
319 for tagname in cls.tags.keys():
320 api.db.do(cls.tagvalue_view_create_sql (tagname))
328 # Filter out fields that cannot be set or updated directly
329 # (and thus would not affect equality for the purposes of
330 # deciding if we should sync() or not).
332 y = self.db_fields(y)
333 return dict.__eq__(x, y)
335 def sync(self, commit = True, insert = None):
337 Flush changes back to the database.
340 # Validate all specified fields
343 # Filter out fields that cannot be set or updated directly
344 db_fields = self.db_fields()
346 # Parameterize for safety
347 keys = db_fields.keys()
348 values = [self.api.db.param(key, value) for (key, value) in db_fields.items()]
350 # If the primary key (usually an auto-incrementing serial
351 # identifier) has not been specified, or the primary key is the
352 # only field in the table, or insert has been forced.
353 if not self.has_key(self.primary_key) or \
354 keys == [self.primary_key] or \
357 # If primary key id is a serial int and it isnt included, get next id
358 if self.fields[self.primary_key].type in (IntType, LongType) and \
359 self.primary_key not in self:
360 pk_id = self.api.db.next_id(self.table_name, self.primary_key)
361 self[self.primary_key] = pk_id
362 db_fields[self.primary_key] = pk_id
363 keys = db_fields.keys()
364 values = [self.api.db.param(key, value) for (key, value) in db_fields.items()]
366 sql = "INSERT INTO %s (%s) VALUES (%s)" % \
367 (self.table_name, ", ".join(keys), ", ".join(values))
369 # Update existing row
370 columns = ["%s = %s" % (key, value) for (key, value) in zip(keys, values)]
371 sql = "UPDATE %s SET " % self.table_name + \
372 ", ".join(columns) + \
375 self.api.db.param(self.primary_key, self[self.primary_key]))
377 self.api.db.do(sql, db_fields)
382 def delete(self, commit = True):
384 Delete row from its primary table, and from any tables that
388 assert self.primary_key in self
390 for table in self.join_tables + [self.table_name]:
391 if isinstance(table, tuple):
395 key = self.primary_key
397 sql = "DELETE FROM %s WHERE %s = %s" % \
399 self.api.db.param(self.primary_key, self[self.primary_key]))
401 self.api.db.do(sql, self)
408 Representation of row(s) in a database table.
411 def __init__(self, api, classobj, columns = None):
413 self.classobj = classobj
417 columns = classobj.fields
420 (columns,tag_columns,rejected) = classobj.parse_columns(columns)
421 if not columns and not tag_columns:
422 raise PLCInvalidArgument, "No valid return fields specified for class %s"%classobj.__name__
424 raise PLCInvalidArgument, "unknown column(s) specified %r in %s"%(rejected,classobj.__name__)
426 self.columns = columns
427 self.tag_columns = tag_columns
429 def sync(self, commit = True):
431 Flush changes back to the database.
437 def selectall(self, sql, params = None):
439 Given a list of rows from the database, fill ourselves with
443 for row in self.api.db.selectall(sql, params):
444 obj = self.classobj(self.api, row)
447 def dict(self, key_field = None):
449 Return ourself as a dict keyed on key_field.
452 if key_field is None:
453 key_field = self.classobj.primary_key
455 return dict([(obj[key_field], obj) for obj in self])