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 three lists
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)
238 def tagvalue_view_name (cls, tagname):
239 return "tagvalue_view_%s_%s"%(cls.primary_key,tagname)
242 def tagvalue_view_create (cls,tagname):
244 returns an SQL sentence that creates a view named after the primary_key and tagname,
246 (*) column 1: name=self.primary_key
247 (*) column 2: name=tagname value=tagvalue
250 if not cls.view_tags_name: return ""
252 table_name=cls.table_name
253 primary_key=cls.primary_key
254 view_tags_name=cls.view_tags_name
255 tagvalue_view_name=cls.tagvalue_view_name(tagname)
256 return 'CREATE OR REPLACE VIEW %(tagvalue_view_name)s ' \
257 'as SELECT %(table_name)s.%(primary_key)s,%(view_tags_name)s.tagvalue as "%(tagname)s" ' \
258 'from %(table_name)s right join %(view_tags_name)s using (%(primary_key)s) ' \
259 'WHERE tagname = \'%(tagname)s\';'%locals()
262 def tagvalue_views_create (cls):
263 if not cls.tags: return
265 for (type,type_dict) in cls.tags.iteritems():
266 for (tagname,details) in type_dict.iteritems():
267 sql.append(cls.tagvalue_view_create (tagname))
275 # Filter out fields that cannot be set or updated directly
276 # (and thus would not affect equality for the purposes of
277 # deciding if we should sync() or not).
279 y = self.db_fields(y)
280 return dict.__eq__(x, y)
282 def sync(self, commit = True, insert = None):
284 Flush changes back to the database.
287 # Validate all specified fields
290 # Filter out fields that cannot be set or updated directly
291 db_fields = self.db_fields()
293 # Parameterize for safety
294 keys = db_fields.keys()
295 values = [self.api.db.param(key, value) for (key, value) in db_fields.items()]
297 # If the primary key (usually an auto-incrementing serial
298 # identifier) has not been specified, or the primary key is the
299 # only field in the table, or insert has been forced.
300 if not self.has_key(self.primary_key) or \
301 keys == [self.primary_key] or \
304 # If primary key id is a serial int and it isnt included, get next id
305 if self.fields[self.primary_key].type in (IntType, LongType) and \
306 self.primary_key not in self:
307 pk_id = self.api.db.next_id(self.table_name, self.primary_key)
308 self[self.primary_key] = pk_id
309 db_fields[self.primary_key] = pk_id
310 keys = db_fields.keys()
311 values = [self.api.db.param(key, value) for (key, value) in db_fields.items()]
313 sql = "INSERT INTO %s (%s) VALUES (%s)" % \
314 (self.table_name, ", ".join(keys), ", ".join(values))
316 # Update existing row
317 columns = ["%s = %s" % (key, value) for (key, value) in zip(keys, values)]
318 sql = "UPDATE %s SET " % self.table_name + \
319 ", ".join(columns) + \
322 self.api.db.param(self.primary_key, self[self.primary_key]))
324 self.api.db.do(sql, db_fields)
329 def delete(self, commit = True):
331 Delete row from its primary table, and from any tables that
335 assert self.primary_key in self
337 for table in self.join_tables + [self.table_name]:
338 if isinstance(table, tuple):
342 key = self.primary_key
344 sql = "DELETE FROM %s WHERE %s = %s" % \
346 self.api.db.param(self.primary_key, self[self.primary_key]))
348 self.api.db.do(sql, self)
355 Representation of row(s) in a database table.
358 def __init__(self, api, classobj, columns = None):
360 self.classobj = classobj
364 columns = classobj.fields
367 (columns,tag_columns,rejected) = classobj.parse_columns(columns)
369 raise PLCInvalidArgument, "No valid return fields specified for class %s"%classobj.__name__
371 raise PLCInvalidArgument, "unknown column(s) specified %r in %s"%(rejected,classobj.__name__)
373 self.columns = columns
374 self.tag_columns = tag_columns
376 def sync(self, commit = True):
378 Flush changes back to the database.
384 def selectall(self, sql, params = None):
386 Given a list of rows from the database, fill ourselves with
390 for row in self.api.db.selectall(sql, params):
391 obj = self.classobj(self.api, row)
394 def dict(self, key_field = None):
396 Return ourself as a dict keyed on key_field.
399 if key_field is None:
400 key_field = self.classobj.primary_key
402 return dict([(obj[key_field], obj) for obj in self])