434db2e9c291136554baf62efb1dbede3d37403a
[plcapi.git] / PLC / Table.py
1 # $Id$
2 # $URL$
3 from types import StringTypes, IntType, LongType
4 import time
5 import calendar
6
7 from PLC.Faults import *
8 from PLC.Parameter import Parameter
9
10 class Row(dict):
11     """
12     Representation of a row in a database table. To use, optionally
13     instantiate with a dict of values. Update as you would a
14     dict. Commit to the database with sync().
15     """
16
17     # Set this to the name of the table that stores the row.
18     # e.g. table_name = "nodes"
19     table_name = None
20
21     # Set this to the name of the primary key of the table. It is
22     # assumed that the this key is a sequence if it is not set when
23     # sync() is called.
24     # e.g. primary_key="node_id"
25     primary_key = None
26
27     # Set this to the names of tables that reference this table's
28     # primary key.
29     join_tables = []
30
31     # Set this to a dict of the valid fields of this object and their
32     # types. Not all fields (e.g., joined fields) may be updated via
33     # sync().
34     fields = {}
35
36     # The name of the view that extends objects with tags
37     # e.g. view_tags_name = "view_node_tags"
38     view_tags_name = None
39
40     # Set this to the set of tags that can be returned by the Get function
41     tags = {}
42
43     def __init__(self, api, fields = {}):
44         dict.__init__(self, fields)
45         self.api = api
46         # run the class_init initializer once
47         cls=self.__class__
48         if not hasattr(cls,'class_inited'):
49             cls.class_init (api)
50             cls.class_inited=True # actual value does not matter
51
52     def validate(self):
53         """
54         Validates values. Will validate a value with a custom function
55         if a function named 'validate_[key]' exists.
56         """
57
58         # Warn about mandatory fields
59         mandatory_fields = self.api.db.fields(self.table_name, notnull = True, hasdef = False)
60         for field in mandatory_fields:
61             if not self.has_key(field) or self[field] is None:
62                 raise PLCInvalidArgument, field + " must be specified and cannot be unset in class %s"%self.__class__.__name__
63
64         # Validate values before committing
65         for key, value in self.iteritems():
66             if value is not None and hasattr(self, 'validate_' + key):
67                 validate = getattr(self, 'validate_' + key)
68                 self[key] = validate(value)
69         
70     def separate_types(self, items):
71         """
72         Separate a list of different typed objects. 
73         Return a list for each type (ints, strs and dicts)
74         """
75         
76         if isinstance(items, (list, tuple, set)):
77             ints = filter(lambda x: isinstance(x, (int, long)), items)
78             strs = filter(lambda x: isinstance(x, StringTypes), items)
79             dicts = filter(lambda x: isinstance(x, dict), items)
80             return (ints, strs, dicts)          
81         else:
82             raise PLCInvalidArgument, "Can only separate list types" 
83                 
84
85     def associate(self, *args):
86         """
87         Provides a means for high level api calls to associate objects
88         using low level calls.
89         """
90
91         if len(args) < 3:
92             raise PLCInvalidArgumentCount, "auth, field, value must be specified"
93         elif hasattr(self, 'associate_' + args[1]):
94             associate = getattr(self, 'associate_'+args[1])
95             associate(*args)
96         else:
97             raise PLCInvalidArguemnt, "No such associate function associate_%s" % args[1]
98
99     def validate_timestamp(self, timestamp, check_future = False):
100         """
101         Validates the specified GMT timestamp string (must be in
102         %Y-%m-%d %H:%M:%S format) or number (seconds since UNIX epoch,
103         i.e., 1970-01-01 00:00:00 GMT). If check_future is True,
104         raises an exception if timestamp is not in the future. Returns
105         a GMT timestamp string.
106         """
107
108         time_format = "%Y-%m-%d %H:%M:%S"
109
110         if isinstance(timestamp, StringTypes):
111             # calendar.timegm() is the inverse of time.gmtime()
112             timestamp = calendar.timegm(time.strptime(timestamp, time_format))
113
114         # Human readable timestamp string
115         human = time.strftime(time_format, time.gmtime(timestamp))
116
117         if check_future and timestamp < time.time():
118             raise PLCInvalidArgument, "'%s' not in the future" % human
119
120         return human
121
122     def add_object(self, classobj, join_table, columns = None):
123         """
124         Returns a function that can be used to associate this object
125         with another.
126         """
127
128         def add(self, obj, columns = None, commit = True):
129             """
130             Associate with the specified object.
131             """
132
133             # Various sanity checks
134             assert isinstance(self, Row)
135             assert self.primary_key in self
136             assert join_table in self.join_tables
137             assert isinstance(obj, classobj)
138             assert isinstance(obj, Row)
139             assert obj.primary_key in obj
140             assert join_table in obj.join_tables
141
142             # By default, just insert the primary keys of each object
143             # into the join table.
144             if columns is None:
145                 columns = {self.primary_key: self[self.primary_key],
146                            obj.primary_key: obj[obj.primary_key]}
147
148             params = []
149             for name, value in columns.iteritems():
150                 params.append(self.api.db.param(name, value))
151
152             self.api.db.do("INSERT INTO %s (%s) VALUES(%s)" % \
153                            (join_table, ", ".join(columns), ", ".join(params)),
154                            columns)
155
156             if commit:
157                 self.api.db.commit()
158     
159         return add
160
161     add_object = classmethod(add_object)
162
163     def remove_object(self, classobj, join_table):
164         """
165         Returns a function that can be used to disassociate this
166         object with another.
167         """
168
169         def remove(self, obj, commit = True):
170             """
171             Disassociate from the specified object.
172             """
173     
174             assert isinstance(self, Row)
175             assert self.primary_key in self
176             assert join_table in self.join_tables
177             assert isinstance(obj, classobj)
178             assert isinstance(obj, Row)
179             assert obj.primary_key in obj
180             assert join_table in obj.join_tables
181     
182             self_id = self[self.primary_key]
183             obj_id = obj[obj.primary_key]
184     
185             self.api.db.do("DELETE FROM %s WHERE %s = %s AND %s = %s" % \
186                            (join_table,
187                             self.primary_key, self.api.db.param('self_id', self_id),
188                             obj.primary_key, self.api.db.param('obj_id', obj_id)),
189                            locals())
190
191             if commit:
192                 self.api.db.commit()
193
194         return remove
195
196     remove_object = classmethod(remove_object)
197
198     # convenience: check in dict (self.fields or self.tags) that a key is writable
199     @staticmethod
200     def is_writable (key,value,dict):
201         # if not mentioned, assume it's writable (e.g. deleted ...)
202         if key not in dict: return True
203         # if mentioned but not linked to a Parameter object, idem
204         if not isinstance(dict[key], Parameter): return True
205         # if not marked ro, it's writable
206         if not dict[key].ro: return True
207         return False
208
209     def db_fields(self, obj = None):
210         """
211         Return only those fields that can be set or updated directly
212         (i.e., those fields that are in the primary table (table_name)
213         for this object, and are not marked as a read-only Parameter.
214         """
215
216         if obj is None: obj = self
217
218         db_fields = self.api.db.fields(self.table_name)
219         return dict ( [ (key,value) for (key,value) in obj.items()
220                         if key in db_fields and
221                         Row.is_writable(key,value,self.fields) ] )
222
223     def tag_fields (self, obj=None):
224         """
225         Return the fields of obj that are mentioned in tags
226         """
227         if obj is None: obj=self
228         
229         return dict ( [ (key,value) for (key,value) in obj.iteritems() 
230                         if key in self.tags and Row.is_writable(key,value,self.tags) ] )
231     
232     # takes as input a list of columns, sort native fields from tags
233     # returns 2 dicts and one list : fields, tags, rejected
234     @classmethod
235     def parse_columns (cls, columns):
236         (fields,tags,rejected)=({},{},[])
237         for column in columns:
238             if column in cls.fields: fields[column]=cls.fields[column]
239             elif column in cls.tags: tags[column]=cls.tags[column]
240             else: rejected.append(column)
241         return (fields,tags,rejected)
242
243     # compute the 'accepts' part of a method, from a list of column names, and a fields dict
244     # use exclude=True to exclude the column names instead
245     # typically accepted_fields (Node.fields,['hostname','model',...])
246     @staticmethod
247     def accepted_fields (update_columns, fields_dict, exclude=False):
248         result={}
249         for (k,v) in fields_dict.iteritems():
250             if (not exclude and k in update_columns) or (exclude and k not in update_columns):
251                 result[k]=v
252         return result
253
254     # filter out user-provided fields that are not part of the declared acceptance list
255     # keep it separate from split_fields for simplicity
256     # typically check_fields (<user_provided_dict>,{'hostname':Parameter(str,...),'model':Parameter(..)...})
257     @staticmethod
258     def check_fields (user_dict, accepted_fields):
259 # avoid the simple, but silent, version
260 #        return dict ([ (k,v) for (k,v) in user_dict.items() if k in accepted_fields ])
261         result={}
262         for (k,v) in user_dict.items():
263             if k in accepted_fields: result[k]=v
264             else: raise PLCInvalidArgument ('Trying to set/change unaccepted key %s'%k)
265         return result
266
267     # given a dict (typically passed to an Update method), we check and sort
268     # them against a list of dicts, e.g. [Node.fields, Node.related_fields]
269     # return is a list that contains n+1 dicts, last one has the rejected fields
270     @staticmethod
271     def split_fields (fields, dicts):
272         result=[]
273         for x in dicts: result.append({})
274         rejected={}
275         for (field,value) in fields.iteritems():
276             found=False
277             for i in range(len(dicts)):
278                 candidate_dict=dicts[i]
279                 if field in candidate_dict.keys():
280                     result[i][field]=value
281                     found=True
282                     break 
283             if not found: rejected[field]=value
284         result.append(rejected)
285         return result
286
287     ### class initialization : create tag-dependent cross view if needed
288     @classmethod
289     def tagvalue_view_name (cls, tagname):
290         return "tagvalue_view_%s_%s"%(cls.primary_key,tagname)
291
292     @classmethod
293     def tagvalue_view_create_sql (cls,tagname):
294         """
295         returns a SQL sentence that creates a view named after the primary_key and tagname, 
296         with 2 columns
297         (*) column 1: primary_key 
298         (*) column 2: actual tag value, renamed into tagname
299         """
300
301         if not cls.view_tags_name: 
302             raise Exception, 'WARNING: class %s needs to set view_tags_name'%cls.__name__
303
304         table_name=cls.table_name
305         primary_key=cls.primary_key
306         view_tags_name=cls.view_tags_name
307         tagvalue_view_name=cls.tagvalue_view_name(tagname)
308         return 'CREATE OR REPLACE VIEW %(tagvalue_view_name)s ' \
309             'as SELECT %(table_name)s.%(primary_key)s,%(view_tags_name)s.value as "%(tagname)s" ' \
310             'from %(table_name)s right join %(view_tags_name)s using (%(primary_key)s) ' \
311             'WHERE tagname = \'%(tagname)s\';'%locals()
312
313     @classmethod
314     def class_init (cls,api):
315         cls.tagvalue_views_create (api)
316
317     @classmethod
318     def tagvalue_views_create (cls,api):
319         if not cls.tags: return
320         for tagname in cls.tags.keys():
321             api.db.do(cls.tagvalue_view_create_sql (tagname))
322         api.db.commit()
323
324     def __eq__(self, y):
325         """
326         Compare two objects.
327         """
328
329         # Filter out fields that cannot be set or updated directly
330         # (and thus would not affect equality for the purposes of
331         # deciding if we should sync() or not).
332         x = self.db_fields()
333         y = self.db_fields(y)
334         return dict.__eq__(x, y)
335
336     def sync(self, commit = True, insert = None):
337         """
338         Flush changes back to the database.
339         """
340
341         # Validate all specified fields
342         self.validate()
343
344         # Filter out fields that cannot be set or updated directly
345         db_fields = self.db_fields()
346
347         # Parameterize for safety
348         keys = db_fields.keys()
349         values = [self.api.db.param(key, value) for (key, value) in db_fields.items()]
350
351         # If the primary key (usually an auto-incrementing serial
352         # identifier) has not been specified, or the primary key is the
353         # only field in the table, or insert has been forced.
354         if not self.has_key(self.primary_key) or \
355            keys == [self.primary_key] or \
356            insert is True:
357             
358             # If primary key id is a serial int and it isnt included, get next id
359             if self.fields[self.primary_key].type in (IntType, LongType) and \
360                self.primary_key not in self:
361                 pk_id = self.api.db.next_id(self.table_name, self.primary_key)
362                 self[self.primary_key] = pk_id
363                 db_fields[self.primary_key] = pk_id
364                 keys = db_fields.keys()
365                 values = [self.api.db.param(key, value) for (key, value) in db_fields.items()]
366             # Insert new row
367             sql = "INSERT INTO %s (%s) VALUES (%s)" % \
368                   (self.table_name, ", ".join(keys), ", ".join(values))
369         else:
370             # Update existing row
371             columns = ["%s = %s" % (key, value) for (key, value) in zip(keys, values)]
372             sql = "UPDATE %s SET " % self.table_name + \
373                   ", ".join(columns) + \
374                   " WHERE %s = %s" % \
375                   (self.primary_key,
376                    self.api.db.param(self.primary_key, self[self.primary_key]))
377
378         self.api.db.do(sql, db_fields)
379
380         if commit:
381             self.api.db.commit()
382
383     def delete(self, commit = True):
384         """
385         Delete row from its primary table, and from any tables that
386         reference it.
387         """
388
389         assert self.primary_key in self
390
391         for table in self.join_tables + [self.table_name]:
392             if isinstance(table, tuple):
393                 key = table[1]
394                 table = table[0]
395             else:
396                 key = self.primary_key
397
398             sql = "DELETE FROM %s WHERE %s = %s" % \
399                   (table, key,
400                    self.api.db.param(self.primary_key, self[self.primary_key]))
401
402             self.api.db.do(sql, self)
403
404         if commit:
405             self.api.db.commit()
406
407 class Table(list):
408     """
409     Representation of row(s) in a database table.
410     """
411
412     def __init__(self, api, classobj, columns = None):
413         self.api = api
414         self.classobj = classobj
415         self.rows = {}
416
417         if columns is None:
418             columns = classobj.fields
419             tag_columns={}
420         else:
421             (columns,tag_columns,rejected) = classobj.parse_columns(columns)
422             if not columns and not tag_columns:
423                 raise PLCInvalidArgument, "No valid return fields specified for class %s"%classobj.__name__
424             if rejected:
425                 raise PLCInvalidArgument, "unknown column(s) specified %r in %s"%(rejected,classobj.__name__)
426
427         self.columns = columns
428         self.tag_columns = tag_columns
429
430     def sync(self, commit = True):
431         """
432         Flush changes back to the database.
433         """
434
435         for row in self:
436             row.sync(commit)
437
438     def selectall(self, sql, params = None):
439         """
440         Given a list of rows from the database, fill ourselves with
441         Row objects.
442         """
443
444         for row in self.api.db.selectall(sql, params):
445             obj = self.classobj(self.api, row)
446             self.append(obj)
447
448     def dict(self, key_field = None):
449         """
450         Return ourself as a dict keyed on key_field.
451         """
452
453         if key_field is None:
454             key_field = self.classobj.primary_key
455
456         return dict([(obj[key_field], obj) for obj in self])