f37f20657dc481f4e0ef581c4d9e603490ba34ec
[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) fields 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: primary_key 
284         (*) column 2: actual tag value, renamed into tagname
285         """
286
287         if not cls.view_tags_name: 
288             raise Exception, 'WARNING: class %s needs to set view_tags_name'%cls.__name__
289
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()
298
299     @classmethod
300     def class_init (cls,api):
301         cls.tagvalue_views_create (api)
302
303     @classmethod
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))
308         api.db.commit()
309
310     def __eq__(self, y):
311         """
312         Compare two objects.
313         """
314
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).
318         x = self.db_fields()
319         y = self.db_fields(y)
320         return dict.__eq__(x, y)
321
322     def sync(self, commit = True, insert = None):
323         """
324         Flush changes back to the database.
325         """
326
327         # Validate all specified fields
328         self.validate()
329
330         # Filter out fields that cannot be set or updated directly
331         db_fields = self.db_fields()
332
333         # Parameterize for safety
334         keys = db_fields.keys()
335         values = [self.api.db.param(key, value) for (key, value) in db_fields.items()]
336
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 \
342            insert is True:
343             
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()]
352             # Insert new row
353             sql = "INSERT INTO %s (%s) VALUES (%s)" % \
354                   (self.table_name, ", ".join(keys), ", ".join(values))
355         else:
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) + \
360                   " WHERE %s = %s" % \
361                   (self.primary_key,
362                    self.api.db.param(self.primary_key, self[self.primary_key]))
363
364         self.api.db.do(sql, db_fields)
365
366         if commit:
367             self.api.db.commit()
368
369     def delete(self, commit = True):
370         """
371         Delete row from its primary table, and from any tables that
372         reference it.
373         """
374
375         assert self.primary_key in self
376
377         for table in self.join_tables + [self.table_name]:
378             if isinstance(table, tuple):
379                 key = table[1]
380                 table = table[0]
381             else:
382                 key = self.primary_key
383
384             sql = "DELETE FROM %s WHERE %s = %s" % \
385                   (table, key,
386                    self.api.db.param(self.primary_key, self[self.primary_key]))
387
388             self.api.db.do(sql, self)
389
390         if commit:
391             self.api.db.commit()
392
393 class Table(list):
394     """
395     Representation of row(s) in a database table.
396     """
397
398     def __init__(self, api, classobj, columns = None):
399         self.api = api
400         self.classobj = classobj
401         self.rows = {}
402
403         if columns is None:
404             columns = classobj.fields
405             tag_columns={}
406         else:
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__
410             if rejected:
411                 raise PLCInvalidArgument, "unknown column(s) specified %r in %s"%(rejected,classobj.__name__)
412
413         self.columns = columns
414         self.tag_columns = tag_columns
415
416     def sync(self, commit = True):
417         """
418         Flush changes back to the database.
419         """
420
421         for row in self:
422             row.sync(commit)
423
424     def selectall(self, sql, params = None):
425         """
426         Given a list of rows from the database, fill ourselves with
427         Row objects.
428         """
429
430         for row in self.api.db.selectall(sql, params):
431             obj = self.classobj(self.api, row)
432             self.append(obj)
433
434     def dict(self, key_field = None):
435         """
436         Return ourself as a dict keyed on key_field.
437         """
438
439         if key_field is None:
440             key_field = self.classobj.primary_key
441
442         return dict([(obj[key_field], obj) for obj in self])