auto init for row classes
[plcapi.git] / PLC / Table.py
1 # $Id$
2 from types import StringTypes, IntType, LongType
3 import time
4 import calendar
5
6 from PLC.Faults import *
7 from PLC.Parameter import Parameter
8
9 class Row(dict):
10     """
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().
14     """
15
16     # Set this to the name of the table that stores the row.
17     # e.g. table_name = "nodes"
18     table_name = None
19
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
22     # sync() is called.
23     # e.g. primary_key="node_id"
24     primary_key = None
25
26     # Set this to the names of tables that reference this table's
27     # primary key.
28     join_tables = []
29
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
32     # sync().
33     fields = {}
34
35     # The name of the view that extends objects with tags
36     # e.g. view_tags_name = "view_node_tags"
37     view_tags_name = None
38
39     # Set this to the set of tags that can be returned by the Get function
40     tags = {}
41
42     def __init__(self, api, fields = {}):
43         dict.__init__(self, fields)
44         self.api = api
45         # run the class_init initializer once
46         cls=self.__class__
47         if not hasattr(cls,'class_inited'):
48             cls.class_init (api)
49             cls.class_inited=True # actual value does not matter
50
51     def validate(self):
52         """
53         Validates values. Will validate a value with a custom function
54         if a function named 'validate_[key]' exists.
55         """
56
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__
62
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)
68         
69     def separate_types(self, items):
70         """
71         Separate a list of different typed objects. 
72         Return a list for each type (ints, strs and dicts)
73         """
74         
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)          
80         else:
81             raise PLCInvalidArgument, "Can only separate list types" 
82                 
83
84     def associate(self, *args):
85         """
86         Provides a means for high level api calls to associate objects
87         using low level calls.
88         """
89
90         if len(args) < 3:
91             raise PLCInvalidArgumentCount, "auth, field, value must be specified"
92         elif hasattr(self, 'associate_' + args[1]):
93             associate = getattr(self, 'associate_'+args[1])
94             associate(*args)
95         else:
96             raise PLCInvalidArguemnt, "No such associate function associate_%s" % args[1]
97
98     def validate_timestamp(self, timestamp, check_future = False):
99         """
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.
105         """
106
107         time_format = "%Y-%m-%d %H:%M:%S"
108
109         if isinstance(timestamp, StringTypes):
110             # calendar.timegm() is the inverse of time.gmtime()
111             timestamp = calendar.timegm(time.strptime(timestamp, time_format))
112
113         # Human readable timestamp string
114         human = time.strftime(time_format, time.gmtime(timestamp))
115
116         if check_future and timestamp < time.time():
117             raise PLCInvalidArgument, "'%s' not in the future" % human
118
119         return human
120
121     def add_object(self, classobj, join_table, columns = None):
122         """
123         Returns a function that can be used to associate this object
124         with another.
125         """
126
127         def add(self, obj, columns = None, commit = True):
128             """
129             Associate with the specified object.
130             """
131
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
140
141             # By default, just insert the primary keys of each object
142             # into the join table.
143             if columns is None:
144                 columns = {self.primary_key: self[self.primary_key],
145                            obj.primary_key: obj[obj.primary_key]}
146
147             params = []
148             for name, value in columns.iteritems():
149                 params.append(self.api.db.param(name, value))
150
151             self.api.db.do("INSERT INTO %s (%s) VALUES(%s)" % \
152                            (join_table, ", ".join(columns), ", ".join(params)),
153                            columns)
154
155             if commit:
156                 self.api.db.commit()
157     
158         return add
159
160     add_object = classmethod(add_object)
161
162     def remove_object(self, classobj, join_table):
163         """
164         Returns a function that can be used to disassociate this
165         object with another.
166         """
167
168         def remove(self, obj, commit = True):
169             """
170             Disassociate from the specified object.
171             """
172     
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
180     
181             self_id = self[self.primary_key]
182             obj_id = obj[obj.primary_key]
183     
184             self.api.db.do("DELETE FROM %s WHERE %s = %s AND %s = %s" % \
185                            (join_table,
186                             self.primary_key, self.api.db.param('self_id', self_id),
187                             obj.primary_key, self.api.db.param('obj_id', obj_id)),
188                            locals())
189
190             if commit:
191                 self.api.db.commit()
192
193         return remove
194
195     remove_object = classmethod(remove_object)
196
197     # convenience: check in dict (self.fields or self.tags) that a key is writable
198     @staticmethod
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
206         return False
207
208     def db_fields(self, obj = None):
209         """
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.
213         """
214
215         if obj is None: obj = self
216
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) ] )
221
222     def tag_fields (self, obj=None):
223         """
224         Return the fields of obj that are mentioned in tags
225         """
226         if obj is None: obj=self
227         
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) ] )
230     
231     # takes in input a list of columns, returns 2 dicts and one list
232     # fields, tags, rejected
233     @classmethod
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)
241
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
245     @staticmethod
246     def split_fields (fields, dicts):
247         result=[]
248         for x in dicts: result.append({})
249         rejected={}
250         for (field,value) in fields.iteritems():
251             found=False
252             for i in range(len(dicts)):
253                 candidate_dict=dicts[i]
254                 if field in candidate_dict.keys():
255                     result[i][field]=value
256                     found=True
257                     break 
258             if not found: rejected[field]=value
259         result.append(rejected)
260         return result
261
262     # compute the accepts part of an update method from a list of column names, and a (list of) field dict
263     @staticmethod
264     def accepted_fields (can_update_columns, fields):
265         result={}
266         if not isinstance(fields,list): fields = [fields]
267         for dict in fields:
268             for (k,v) in dict.iteritems():
269                 if k in can_update_columns:
270                     result[k]=v
271         return result
272
273     ### class initialization : create tag-dependent cross view if needed
274     @classmethod
275     def tagvalue_view_name (cls, tagname):
276         return "tagvalue_view_%s_%s"%(cls.primary_key,tagname)
277
278     @classmethod
279     def tagvalue_view_create_sql (cls,tagname):
280         """
281         returns a SQL sentence that creates a view named after the primary_key and tagname, 
282         with 2 columns
283         (*) column 1: name=self.primary_key 
284         (*) column 2: name=tagname value=tagvalue
285         """
286
287         if not cls.view_tags_name: return ""
288
289         table_name=cls.table_name
290         primary_key=cls.primary_key
291         view_tags_name=cls.view_tags_name
292         tagvalue_view_name=cls.tagvalue_view_name(tagname)
293         return 'CREATE OR REPLACE VIEW %(tagvalue_view_name)s ' \
294             'as SELECT %(table_name)s.%(primary_key)s,%(view_tags_name)s.tagvalue as "%(tagname)s" ' \
295             'from %(table_name)s right join %(view_tags_name)s using (%(primary_key)s) ' \
296             'WHERE tagname = \'%(tagname)s\';'%locals()
297
298     @classmethod
299     def class_init (cls,api):
300         cls.tagvalue_views_create (api)
301
302     @classmethod
303     def tagvalue_views_create (cls,api):
304         if not cls.tags: return
305         for tagname in cls.tags.keys():
306             api.db.do(cls.tagvalue_view_create_sql (tagname))
307         api.db.commit()
308
309     def __eq__(self, y):
310         """
311         Compare two objects.
312         """
313
314         # Filter out fields that cannot be set or updated directly
315         # (and thus would not affect equality for the purposes of
316         # deciding if we should sync() or not).
317         x = self.db_fields()
318         y = self.db_fields(y)
319         return dict.__eq__(x, y)
320
321     def sync(self, commit = True, insert = None):
322         """
323         Flush changes back to the database.
324         """
325
326         # Validate all specified fields
327         self.validate()
328
329         # Filter out fields that cannot be set or updated directly
330         db_fields = self.db_fields()
331
332         # Parameterize for safety
333         keys = db_fields.keys()
334         values = [self.api.db.param(key, value) for (key, value) in db_fields.items()]
335
336         # If the primary key (usually an auto-incrementing serial
337         # identifier) has not been specified, or the primary key is the
338         # only field in the table, or insert has been forced.
339         if not self.has_key(self.primary_key) or \
340            keys == [self.primary_key] or \
341            insert is True:
342             
343             # If primary key id is a serial int and it isnt included, get next id
344             if self.fields[self.primary_key].type in (IntType, LongType) and \
345                self.primary_key not in self:
346                 pk_id = self.api.db.next_id(self.table_name, self.primary_key)
347                 self[self.primary_key] = pk_id
348                 db_fields[self.primary_key] = pk_id
349                 keys = db_fields.keys()
350                 values = [self.api.db.param(key, value) for (key, value) in db_fields.items()]
351             # Insert new row
352             sql = "INSERT INTO %s (%s) VALUES (%s)" % \
353                   (self.table_name, ", ".join(keys), ", ".join(values))
354         else:
355             # Update existing row
356             columns = ["%s = %s" % (key, value) for (key, value) in zip(keys, values)]
357             sql = "UPDATE %s SET " % self.table_name + \
358                   ", ".join(columns) + \
359                   " WHERE %s = %s" % \
360                   (self.primary_key,
361                    self.api.db.param(self.primary_key, self[self.primary_key]))
362
363         self.api.db.do(sql, db_fields)
364
365         if commit:
366             self.api.db.commit()
367
368     def delete(self, commit = True):
369         """
370         Delete row from its primary table, and from any tables that
371         reference it.
372         """
373
374         assert self.primary_key in self
375
376         for table in self.join_tables + [self.table_name]:
377             if isinstance(table, tuple):
378                 key = table[1]
379                 table = table[0]
380             else:
381                 key = self.primary_key
382
383             sql = "DELETE FROM %s WHERE %s = %s" % \
384                   (table, key,
385                    self.api.db.param(self.primary_key, self[self.primary_key]))
386
387             self.api.db.do(sql, self)
388
389         if commit:
390             self.api.db.commit()
391
392 class Table(list):
393     """
394     Representation of row(s) in a database table.
395     """
396
397     def __init__(self, api, classobj, columns = None):
398         self.api = api
399         self.classobj = classobj
400         self.rows = {}
401
402         if columns is None:
403             columns = classobj.fields
404             tag_columns={}
405         else:
406             (columns,tag_columns,rejected) = classobj.parse_columns(columns)
407             if not columns:
408                 raise PLCInvalidArgument, "No valid return fields specified for class %s"%classobj.__name__
409             if rejected:
410                 raise PLCInvalidArgument, "unknown column(s) specified %r in %s"%(rejected,classobj.__name__)
411
412         self.columns = columns
413         self.tag_columns = tag_columns
414
415     def sync(self, commit = True):
416         """
417         Flush changes back to the database.
418         """
419
420         for row in self:
421             row.sync(commit)
422
423     def selectall(self, sql, params = None):
424         """
425         Given a list of rows from the database, fill ourselves with
426         Row objects.
427         """
428
429         for row in self.api.db.selectall(sql, params):
430             obj = self.classobj(self.api, row)
431             self.append(obj)
432
433     def dict(self, key_field = None):
434         """
435         Return ourself as a dict keyed on key_field.
436         """
437
438         if key_field is None:
439             key_field = self.classobj.primary_key
440
441         return dict([(obj[key_field], obj) for obj in self])