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 # Set this to the name of the view that gathers the row and its relations
36 # e.g. view_name = "view_nodes"
39 # The name of the view that extends objects with tags
40 # e.g. view_tags_name = "view_node_tags"
43 # Set this to the set of tags that can be returned by the Get function
46 def __init__(self, api, fields = {}):
47 dict.__init__(self, fields)
52 Validates values. Will validate a value with a custom function
53 if a function named 'validate_[key]' exists.
56 # Warn about mandatory fields
57 mandatory_fields = self.api.db.fields(self.table_name, notnull = True, hasdef = False)
58 for field in mandatory_fields:
59 if not self.has_key(field) or self[field] is None:
60 raise PLCInvalidArgument, field + " must be specified and cannot be unset in class %s"%self.__class__.__name__
62 # Validate values before committing
63 for key, value in self.iteritems():
64 if value is not None and hasattr(self, 'validate_' + key):
65 validate = getattr(self, 'validate_' + key)
66 self[key] = validate(value)
68 def separate_types(self, items):
70 Separate a list of different typed objects.
71 Return a list for each type (ints, strs and dicts)
74 if isinstance(items, (list, tuple, set)):
75 ints = filter(lambda x: isinstance(x, (int, long)), items)
76 strs = filter(lambda x: isinstance(x, StringTypes), items)
77 dicts = filter(lambda x: isinstance(x, dict), items)
78 return (ints, strs, dicts)
80 raise PLCInvalidArgument, "Can only separate list types"
83 def associate(self, *args):
85 Provides a means for high level api calls to associate objects
86 using low level calls.
90 raise PLCInvalidArgumentCount, "auth, field, value must be specified"
91 elif hasattr(self, 'associate_' + args[1]):
92 associate = getattr(self, 'associate_'+args[1])
95 raise PLCInvalidArguemnt, "No such associate function associate_%s" % args[1]
97 def validate_timestamp(self, timestamp, check_future = False):
99 Validates the specified GMT timestamp string (must be in
100 %Y-%m-%d %H:%M:%S format) or number (seconds since UNIX epoch,
101 i.e., 1970-01-01 00:00:00 GMT). If check_future is True,
102 raises an exception if timestamp is not in the future. Returns
103 a GMT timestamp string.
106 time_format = "%Y-%m-%d %H:%M:%S"
108 if isinstance(timestamp, StringTypes):
109 # calendar.timegm() is the inverse of time.gmtime()
110 timestamp = calendar.timegm(time.strptime(timestamp, time_format))
112 # Human readable timestamp string
113 human = time.strftime(time_format, time.gmtime(timestamp))
115 if check_future and timestamp < time.time():
116 raise PLCInvalidArgument, "'%s' not in the future" % human
120 def add_object(self, classobj, join_table, columns = None):
122 Returns a function that can be used to associate this object
126 def add(self, obj, columns = None, commit = True):
128 Associate with the specified object.
131 # Various sanity checks
132 assert isinstance(self, Row)
133 assert self.primary_key in self
134 assert join_table in self.join_tables
135 assert isinstance(obj, classobj)
136 assert isinstance(obj, Row)
137 assert obj.primary_key in obj
138 assert join_table in obj.join_tables
140 # By default, just insert the primary keys of each object
141 # into the join table.
143 columns = {self.primary_key: self[self.primary_key],
144 obj.primary_key: obj[obj.primary_key]}
147 for name, value in columns.iteritems():
148 params.append(self.api.db.param(name, value))
150 self.api.db.do("INSERT INTO %s (%s) VALUES(%s)" % \
151 (join_table, ", ".join(columns), ", ".join(params)),
159 add_object = classmethod(add_object)
161 def remove_object(self, classobj, join_table):
163 Returns a function that can be used to disassociate this
167 def remove(self, obj, commit = True):
169 Disassociate from the specified object.
172 assert isinstance(self, Row)
173 assert self.primary_key in self
174 assert join_table in self.join_tables
175 assert isinstance(obj, classobj)
176 assert isinstance(obj, Row)
177 assert obj.primary_key in obj
178 assert join_table in obj.join_tables
180 self_id = self[self.primary_key]
181 obj_id = obj[obj.primary_key]
183 self.api.db.do("DELETE FROM %s WHERE %s = %s AND %s = %s" % \
185 self.primary_key, self.api.db.param('self_id', self_id),
186 obj.primary_key, self.api.db.param('obj_id', obj_id)),
194 remove_object = classmethod(remove_object)
196 # convenience: check in dict (self.fields or self.tags) that a key is writable
198 def is_writable (key,value,dict):
199 # if not mentioned, assume it's writable (e.g. deleted ...)
200 if key not in dict: return True
201 # if mentioned but not linked to a Parameter object, idem
202 if not isinstance(dict[key], Parameter): return True
203 # if not marked ro, it's writable
204 if not dict[key].ro: return True
207 def db_fields(self, obj = None):
209 Return only those fields that can be set or updated directly
210 (i.e., those fields that are in the primary table (table_name)
211 for this object, and are not marked as a read-only Parameter.
214 if obj is None: obj = self
216 db_fields = self.api.db.fields(self.table_name)
217 return dict ( [ (key,value) for (key,value) in obj.items()
218 if key in db_fields and
219 Row.is_writable(key,value,self.fields) ] )
221 def tag_fields (self, obj=None):
223 Return the fields of obj that are mentioned in tags
225 if obj is None: obj=self
227 return dict ( [ (key,value) for (key,value) in obj.iteritems()
228 if key in self.tags and Row.is_writable(key,value,self.tags) ] )
230 # takes in input a list of columns, returns three lists
231 # fields, tags, rejected
233 def parse_columns (cls, columns):
234 (fields,tags,rejected)=({},{},{})
235 for column in columns:
236 if column in cls.fields: fields[column]=cls.fields[column]
237 elif column in cls.tags: tags[column]=cls.tags[column]
238 else: rejected.append(column)
239 return (fields,tags,rejected)
242 def tagvalue_view_name (cls, tagname):
243 return "tagvalue_view_%s_%s"%(cls.primary_key,tagname)
246 def tagvalue_view_create (cls,tagname):
248 returns an SQL sentence that creates a view named after the primary_key and tagname,
250 (*) column 1: name=self.primary_key
251 (*) column 2: name=tagname value=tagvalue
254 if not cls.view_tags_name: return ""
256 table_name=cls.table_name
257 primary_key=cls.primary_key
258 view_tags_name=cls.view_tags_name
259 tagvalue_view_name=cls.tagvalue_view_name(tagname)
260 return 'CREATE OR REPLACE VIEW %(tagvalue_view_name)s ' \
261 'as SELECT %(table_name)s.%(primary_key)s,%(view_tags_name)s.tagvalue as "%(tagname)s" ' \
262 'from %(table_name)s right join %(view_tags_name)s using (%(primary_key)s) ' \
263 'WHERE tagname = \'%(tagname)s\';'%locals()
266 def tagvalue_views_create (cls):
267 if not cls.tags: return
269 for (type,type_dict) in cls.tags.iteritems():
270 for (tagname,details) in type_dict.iteritems():
271 sql.append(cls.tagvalue_view_create (tagname))
279 # Filter out fields that cannot be set or updated directly
280 # (and thus would not affect equality for the purposes of
281 # deciding if we should sync() or not).
283 y = self.db_fields(y)
284 return dict.__eq__(x, y)
286 def sync(self, commit = True, insert = None):
288 Flush changes back to the database.
291 # Validate all specified fields
294 # Filter out fields that cannot be set or updated directly
295 db_fields = self.db_fields()
297 # Parameterize for safety
298 keys = db_fields.keys()
299 values = [self.api.db.param(key, value) for (key, value) in db_fields.items()]
301 # If the primary key (usually an auto-incrementing serial
302 # identifier) has not been specified, or the primary key is the
303 # only field in the table, or insert has been forced.
304 if not self.has_key(self.primary_key) or \
305 keys == [self.primary_key] or \
308 # If primary key id is a serial int and it isnt included, get next id
309 if self.fields[self.primary_key].type in (IntType, LongType) and \
310 self.primary_key not in self:
311 pk_id = self.api.db.next_id(self.table_name, self.primary_key)
312 self[self.primary_key] = pk_id
313 db_fields[self.primary_key] = pk_id
314 keys = db_fields.keys()
315 values = [self.api.db.param(key, value) for (key, value) in db_fields.items()]
317 sql = "INSERT INTO %s (%s) VALUES (%s)" % \
318 (self.table_name, ", ".join(keys), ", ".join(values))
320 # Update existing row
321 columns = ["%s = %s" % (key, value) for (key, value) in zip(keys, values)]
322 sql = "UPDATE %s SET " % self.table_name + \
323 ", ".join(columns) + \
326 self.api.db.param(self.primary_key, self[self.primary_key]))
328 self.api.db.do(sql, db_fields)
333 def delete(self, commit = True):
335 Delete row from its primary table, and from any tables that
339 assert self.primary_key in self
341 for table in self.join_tables + [self.table_name]:
342 if isinstance(table, tuple):
346 key = self.primary_key
348 sql = "DELETE FROM %s WHERE %s = %s" % \
350 self.api.db.param(self.primary_key, self[self.primary_key]))
352 self.api.db.do(sql, self)
359 Representation of row(s) in a database table.
362 def __init__(self, api, classobj, columns = None):
364 self.classobj = classobj
368 columns = classobj.fields
371 (columns,tag_columns,rejected) = classobj.parse_columns(columns)
373 raise PLCInvalidArgument, "No valid return fields specified for class %s"%classobj.__name__
375 raise PLCInvalidArgument, "unknown column(s) specified %r in %s"%(rejected,classobj.__name__)
377 self.columns = columns
378 self.tag_columns = tag_columns
380 def sync(self, commit = True):
382 Flush changes back to the database.
388 def selectall(self, sql, params = None):
390 Given a list of rows from the database, fill ourselves with
394 for row in self.api.db.selectall(sql, params):
395 obj = self.classobj(self.api, row)
398 def dict(self, key_field = None):
400 Return ourself as a dict keyed on key_field.
403 if key_field is None:
404 key_field = self.classobj.primary_key
406 return dict([(obj[key_field], obj) for obj in self])