e56f316f5d8deab8f8ce111c215ba92dfc8b1750
[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 as input a list of columns, sort native fields from tags
232     # returns 2 dicts and one list : 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     # 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',...])
245     @staticmethod
246     def accepted_fields (update_columns, fields_dict, exclude=False):
247         result={}
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):
250                 result[k]=v
251         return result
252
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(..)...})
256     @staticmethod
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 ])
260         result={}
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)
264         return result
265
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
269     @staticmethod
270     def split_fields (fields, dicts):
271         result=[]
272         for x in dicts: result.append({})
273         rejected={}
274         for (field,value) in fields.iteritems():
275             found=False
276             for i in range(len(dicts)):
277                 candidate_dict=dicts[i]
278                 if field in candidate_dict.keys():
279                     result[i][field]=value
280                     found=True
281                     break 
282             if not found: rejected[field]=value
283         result.append(rejected)
284         return result
285
286     ### class initialization : create tag-dependent cross view if needed
287     @classmethod
288     def tagvalue_view_name (cls, tagname):
289         return "tagvalue_view_%s_%s"%(cls.primary_key,tagname)
290
291     @classmethod
292     def tagvalue_view_create_sql (cls,tagname):
293         """
294         returns a SQL sentence that creates a view named after the primary_key and tagname, 
295         with 2 columns
296         (*) column 1: primary_key 
297         (*) column 2: actual tag value, renamed into tagname
298         """
299
300         if not cls.view_tags_name: 
301             raise Exception, 'WARNING: class %s needs to set view_tags_name'%cls.__name__
302
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()
311
312     @classmethod
313     def class_init (cls,api):
314         cls.tagvalue_views_create (api)
315
316     @classmethod
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))
321         api.db.commit()
322
323     def __eq__(self, y):
324         """
325         Compare two objects.
326         """
327
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).
331         x = self.db_fields()
332         y = self.db_fields(y)
333         return dict.__eq__(x, y)
334
335     def sync(self, commit = True, insert = None):
336         """
337         Flush changes back to the database.
338         """
339
340         # Validate all specified fields
341         self.validate()
342
343         # Filter out fields that cannot be set or updated directly
344         db_fields = self.db_fields()
345
346         # Parameterize for safety
347         keys = db_fields.keys()
348         values = [self.api.db.param(key, value) for (key, value) in db_fields.items()]
349
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 \
355            insert is True:
356             
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()]
365             # Insert new row
366             sql = "INSERT INTO %s (%s) VALUES (%s)" % \
367                   (self.table_name, ", ".join(keys), ", ".join(values))
368         else:
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) + \
373                   " WHERE %s = %s" % \
374                   (self.primary_key,
375                    self.api.db.param(self.primary_key, self[self.primary_key]))
376
377         self.api.db.do(sql, db_fields)
378
379         if commit:
380             self.api.db.commit()
381
382     def delete(self, commit = True):
383         """
384         Delete row from its primary table, and from any tables that
385         reference it.
386         """
387
388         assert self.primary_key in self
389
390         for table in self.join_tables + [self.table_name]:
391             if isinstance(table, tuple):
392                 key = table[1]
393                 table = table[0]
394             else:
395                 key = self.primary_key
396
397             sql = "DELETE FROM %s WHERE %s = %s" % \
398                   (table, key,
399                    self.api.db.param(self.primary_key, self[self.primary_key]))
400
401             self.api.db.do(sql, self)
402
403         if commit:
404             self.api.db.commit()
405
406 class Table(list):
407     """
408     Representation of row(s) in a database table.
409     """
410
411     def __init__(self, api, classobj, columns = None):
412         self.api = api
413         self.classobj = classobj
414         self.rows = {}
415
416         if columns is None:
417             columns = classobj.fields
418             tag_columns={}
419         else:
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__
423             if rejected:
424                 raise PLCInvalidArgument, "unknown column(s) specified %r in %s"%(rejected,classobj.__name__)
425
426         self.columns = columns
427         self.tag_columns = tag_columns
428
429     def sync(self, commit = True):
430         """
431         Flush changes back to the database.
432         """
433
434         for row in self:
435             row.sync(commit)
436
437     def selectall(self, sql, params = None):
438         """
439         Given a list of rows from the database, fill ourselves with
440         Row objects.
441         """
442
443         for row in self.api.db.selectall(sql, params):
444             obj = self.classobj(self.api, row)
445             self.append(obj)
446
447     def dict(self, key_field = None):
448         """
449         Return ourself as a dict keyed on key_field.
450         """
451
452         if key_field is None:
453             key_field = self.classobj.primary_key
454
455         return dict([(obj[key_field], obj) for obj in self])