prettified
[plcapi.git] / PLC / Table.py
1 from types import StringTypes, IntType, LongType
2 import time
3 import calendar
4
5 from PLC.Timestamp import Timestamp
6 from PLC.Faults import *
7 from PLC.Parameter import Parameter
8
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):
100         return Timestamp.sql_validate(timestamp)
101
102     def add_object(self, classobj, join_table, columns = None):
103         """
104         Returns a function that can be used to associate this object
105         with another.
106         """
107
108         def add(self, obj, columns = None, commit = True):
109             """
110             Associate with the specified object.
111             """
112
113             # Various sanity checks
114             assert isinstance(self, Row)
115             assert self.primary_key in self
116             assert join_table in self.join_tables
117             assert isinstance(obj, classobj)
118             assert isinstance(obj, Row)
119             assert obj.primary_key in obj
120             assert join_table in obj.join_tables
121
122             # By default, just insert the primary keys of each object
123             # into the join table.
124             if columns is None:
125                 columns = {self.primary_key: self[self.primary_key],
126                            obj.primary_key: obj[obj.primary_key]}
127
128             params = []
129             for name, value in columns.iteritems():
130                 params.append(self.api.db.param(name, value))
131
132             self.api.db.do("INSERT INTO %s (%s) VALUES(%s)" % \
133                            (join_table, ", ".join(columns), ", ".join(params)),
134                            columns)
135
136             if commit:
137                 self.api.db.commit()
138
139         return add
140
141     add_object = classmethod(add_object)
142
143     def remove_object(self, classobj, join_table):
144         """
145         Returns a function that can be used to disassociate this
146         object with another.
147         """
148
149         def remove(self, obj, commit = True):
150             """
151             Disassociate from the specified object.
152             """
153
154             assert isinstance(self, Row)
155             assert self.primary_key in self
156             assert join_table in self.join_tables
157             assert isinstance(obj, classobj)
158             assert isinstance(obj, Row)
159             assert obj.primary_key in obj
160             assert join_table in obj.join_tables
161
162             self_id = self[self.primary_key]
163             obj_id = obj[obj.primary_key]
164
165             self.api.db.do("DELETE FROM %s WHERE %s = %s AND %s = %s" % \
166                            (join_table,
167                             self.primary_key, self.api.db.param('self_id', self_id),
168                             obj.primary_key, self.api.db.param('obj_id', obj_id)),
169                            locals())
170
171             if commit:
172                 self.api.db.commit()
173
174         return remove
175
176     remove_object = classmethod(remove_object)
177
178     # convenience: check in dict (self.fields or self.tags) that a key is writable
179     @staticmethod
180     def is_writable (key,value,dict):
181         # if not mentioned, assume it's writable (e.g. deleted ...)
182         if key not in dict: return True
183         # if mentioned but not linked to a Parameter object, idem
184         if not isinstance(dict[key], Parameter): return True
185         # if not marked ro, it's writable
186         if not dict[key].ro: return True
187         return False
188
189     def db_fields(self, obj = None):
190         """
191         Return only those fields that can be set or updated directly
192         (i.e., those fields that are in the primary table (table_name)
193         for this object, and are not marked as a read-only Parameter.
194         """
195
196         if obj is None:
197             obj = self
198
199         db_fields = self.api.db.fields(self.table_name)
200         return dict ( [ (key, value) for (key, value) in obj.items()
201                         if key in db_fields and
202                         Row.is_writable(key, value, self.fields) ] )
203
204     def tag_fields (self, obj=None):
205         """
206         Return the fields of obj that are mentioned in tags
207         """
208         if obj is None: obj=self
209
210         return dict ( [ (key,value) for (key,value) in obj.iteritems()
211                         if key in self.tags and Row.is_writable(key,value,self.tags) ] )
212
213     # takes as input a list of columns, sort native fields from tags
214     # returns 2 dicts and one list : fields, tags, rejected
215     @classmethod
216     def parse_columns (cls, columns):
217         (fields,tags,rejected)=({},{},[])
218         for column in columns:
219             if column in cls.fields: fields[column]=cls.fields[column]
220             elif column in cls.tags: tags[column]=cls.tags[column]
221             else: rejected.append(column)
222         return (fields,tags,rejected)
223
224     # compute the 'accepts' part of a method, from a list of column names, and a fields dict
225     # use exclude=True to exclude the column names instead
226     # typically accepted_fields (Node.fields,['hostname','model',...])
227     @staticmethod
228     def accepted_fields (update_columns, fields_dict, exclude=False):
229         result={}
230         for (k,v) in fields_dict.iteritems():
231             if (not exclude and k in update_columns) or (exclude and k not in update_columns):
232                 result[k]=v
233         return result
234
235     # filter out user-provided fields that are not part of the declared acceptance list
236     # keep it separate from split_fields for simplicity
237     # typically check_fields (<user_provided_dict>,{'hostname':Parameter(str,...),'model':Parameter(..)...})
238     @staticmethod
239     def check_fields (user_dict, accepted_fields):
240 # avoid the simple, but silent, version
241 #        return dict ([ (k,v) for (k,v) in user_dict.items() if k in accepted_fields ])
242         result={}
243         for (k,v) in user_dict.items():
244             if k in accepted_fields: result[k]=v
245             else: raise PLCInvalidArgument ('Trying to set/change unaccepted key %s'%k)
246         return result
247
248     # given a dict (typically passed to an Update method), we check and sort
249     # them against a list of dicts, e.g. [Node.fields, Node.related_fields]
250     # return is a list that contains n+1 dicts, last one has the rejected fields
251     @staticmethod
252     def split_fields (fields, dicts):
253         result=[]
254         for x in dicts: result.append({})
255         rejected={}
256         for (field,value) in fields.iteritems():
257             found=False
258             for i in range(len(dicts)):
259                 candidate_dict=dicts[i]
260                 if field in candidate_dict.keys():
261                     result[i][field]=value
262                     found=True
263                     break
264             if not found: rejected[field]=value
265         result.append(rejected)
266         return result
267
268     ### class initialization : create tag-dependent cross view if needed
269     @classmethod
270     def tagvalue_view_name (cls, tagname):
271         return "tagvalue_view_%s_%s"%(cls.primary_key,tagname)
272
273     @classmethod
274     def tagvalue_view_create_sql (cls,tagname):
275         """
276         returns a SQL sentence that creates a view named after the primary_key and tagname,
277         with 2 columns
278         (*) column 1: primary_key
279         (*) column 2: actual tag value, renamed into tagname
280         """
281
282         if not cls.view_tags_name:
283             raise Exception, 'WARNING: class %s needs to set view_tags_name'%cls.__name__
284
285         table_name=cls.table_name
286         primary_key=cls.primary_key
287         view_tags_name=cls.view_tags_name
288         tagvalue_view_name=cls.tagvalue_view_name(tagname)
289         return 'CREATE OR REPLACE VIEW %(tagvalue_view_name)s ' \
290             'as SELECT %(table_name)s.%(primary_key)s,%(view_tags_name)s.value as "%(tagname)s" ' \
291             'from %(table_name)s right join %(view_tags_name)s using (%(primary_key)s) ' \
292             'WHERE tagname = \'%(tagname)s\';'%locals()
293
294     @classmethod
295     def class_init (cls,api):
296         cls.tagvalue_views_create (api)
297
298     @classmethod
299     def tagvalue_views_create (cls,api):
300         if not cls.tags: return
301         for tagname in cls.tags.keys():
302             api.db.do(cls.tagvalue_view_create_sql (tagname))
303         api.db.commit()
304
305     def __eq__(self, y):
306         """
307         Compare two objects.
308         """
309
310         # Filter out fields that cannot be set or updated directly
311         # (and thus would not affect equality for the purposes of
312         # deciding if we should sync() or not).
313         x = self.db_fields()
314         y = self.db_fields(y)
315         return dict.__eq__(x, y)
316
317     # validate becomes optional on sept. 2010
318     # we find it useful to use DeletePerson on duplicated entries
319     def sync(self, commit = True, insert = None, validate=True):
320         """
321         Flush changes back to the database.
322         """
323
324         # Validate all specified fields
325         if validate: self.validate()
326
327         # Filter out fields that cannot be set or updated directly
328         db_fields = self.db_fields()
329
330         # Parameterize for safety
331         keys = db_fields.keys()
332         values = [self.api.db.param(key, value) for (key, value) in db_fields.items()]
333
334         # If the primary key (usually an auto-incrementing serial
335         # identifier) has not been specified, or the primary key is the
336         # only field in the table, or insert has been forced.
337         if not self.has_key(self.primary_key) or \
338            keys == [self.primary_key] or \
339            insert is True:
340
341             # If primary key id is a serial int and it isnt included, get next id
342             if self.fields[self.primary_key].type in (IntType, LongType) and \
343                self.primary_key not in self:
344                 pk_id = self.api.db.next_id(self.table_name, self.primary_key)
345                 self[self.primary_key] = pk_id
346                 db_fields[self.primary_key] = pk_id
347                 keys = db_fields.keys()
348                 values = [self.api.db.param(key, value) for (key, value) in db_fields.items()]
349             # Insert new row
350             sql = "INSERT INTO %s (%s) VALUES (%s)" % \
351                   (self.table_name, ", ".join(keys), ", ".join(values))
352         else:
353             # Update existing row
354             columns = ["%s = %s" % (key, value) for (key, value) in zip(keys, values)]
355             sql = "UPDATE {} SET {} WHERE {} = {}"\
356                   .format(self.table_name,
357                           ", ".join(columns),
358                           self.primary_key,
359                           self.api.db.param(self.primary_key, self[self.primary_key]))                                               
360
361         self.api.db.do(sql, db_fields)
362
363         if commit:
364             self.api.db.commit()
365
366     def delete(self, commit = True):
367         """
368         Delete row from its primary table, and from any tables that
369         reference it.
370         """
371
372         assert self.primary_key in self
373
374         for table in self.join_tables + [self.table_name]:
375             if isinstance(table, tuple):
376                 key = table[1]
377                 table = table[0]
378             else:
379                 key = self.primary_key
380
381             sql = "DELETE FROM %s WHERE %s = %s" % \
382                   (table, key,
383                    self.api.db.param(self.primary_key, self[self.primary_key]))
384
385             self.api.db.do(sql, self)
386
387         if commit:
388             self.api.db.commit()
389
390 class Table(list):
391     """
392     Representation of row(s) in a database table.
393     """
394
395     def __init__(self, api, classobj, columns = None):
396         self.api = api
397         self.classobj = classobj
398         self.rows = {}
399
400         if columns is None:
401             columns = classobj.fields
402             tag_columns={}
403         else:
404             (columns,tag_columns,rejected) = classobj.parse_columns(columns)
405             if not columns and not tag_columns:
406                 raise PLCInvalidArgument, "No valid return fields specified for class %s"%classobj.__name__
407             if rejected:
408                 raise PLCInvalidArgument, "unknown column(s) specified %r in %s"%(rejected,classobj.__name__)
409
410         self.columns = columns
411         self.tag_columns = tag_columns
412
413     def sync(self, commit = True):
414         """
415         Flush changes back to the database.
416         """
417
418         for row in self:
419             row.sync(commit)
420
421     def selectall(self, sql, params = None):
422         """
423         Given a list of rows from the database, fill ourselves with
424         Row objects.
425         """
426
427         for row in self.api.db.selectall(sql, params):
428             obj = self.classobj(self.api, row)
429             self.append(obj)
430
431     def dict(self, key_field = None):
432         """
433         Return ourself as a dict keyed on key_field.
434         """
435
436         if key_field is None:
437             key_field = self.classobj.primary_key
438
439         return dict([(obj[key_field], obj) for obj in self])