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