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