StringTypes has gone
[plcapi.git] / PLC / Table.py
1 import time
2 import calendar
3
4 from PLC.Timestamp import Timestamp
5 from PLC.Faults import *
6 from PLC.Parameter import Parameter
7
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 field not in self 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.items():
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 = [x for x in items if isinstance(x, int)]
77             strs = [x for x in items if isinstance(x, str)]
78             dicts = [x for x in items if isinstance(x, dict)]
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):
99         return Timestamp.sql_validate(timestamp)
100
101     def add_object(self, classobj, join_table, columns = None):
102         """
103         Returns a function that can be used to associate this object
104         with another.
105         """
106
107         def add(self, obj, columns = None, commit = True):
108             """
109             Associate with the specified object.
110             """
111
112             # Various sanity checks
113             assert isinstance(self, Row)
114             assert self.primary_key in self
115             assert join_table in self.join_tables
116             assert isinstance(obj, classobj)
117             assert isinstance(obj, Row)
118             assert obj.primary_key in obj
119             assert join_table in obj.join_tables
120
121             # By default, just insert the primary keys of each object
122             # into the join table.
123             if columns is None:
124                 columns = {self.primary_key: self[self.primary_key],
125                            obj.primary_key: obj[obj.primary_key]}
126
127             params = []
128             for name, value in columns.items():
129                 params.append(self.api.db.param(name, value))
130
131             self.api.db.do("INSERT INTO %s (%s) VALUES(%s)" % \
132                            (join_table, ", ".join(columns), ", ".join(params)),
133                            columns)
134
135             if commit:
136                 self.api.db.commit()
137
138         return add
139
140     add_object = classmethod(add_object)
141
142     def remove_object(self, classobj, join_table):
143         """
144         Returns a function that can be used to disassociate this
145         object with another.
146         """
147
148         def remove(self, obj, commit = True):
149             """
150             Disassociate from the specified object.
151             """
152
153             assert isinstance(self, Row)
154             assert self.primary_key in self
155             assert join_table in self.join_tables
156             assert isinstance(obj, classobj)
157             assert isinstance(obj, Row)
158             assert obj.primary_key in obj
159             assert join_table in obj.join_tables
160
161             self_id = self[self.primary_key]
162             obj_id = obj[obj.primary_key]
163
164             self.api.db.do("DELETE FROM %s WHERE %s = %s AND %s = %s" % \
165                            (join_table,
166                             self.primary_key, self.api.db.param('self_id', self_id),
167                             obj.primary_key, self.api.db.param('obj_id', obj_id)),
168                            locals())
169
170             if commit:
171                 self.api.db.commit()
172
173         return remove
174
175     remove_object = classmethod(remove_object)
176
177     # convenience: check in dict (self.fields or self.tags) that a key is writable
178     @staticmethod
179     def is_writable (key,value,dict):
180         # if not mentioned, assume it's writable (e.g. deleted ...)
181         if key not in dict: return True
182         # if mentioned but not linked to a Parameter object, idem
183         if not isinstance(dict[key], Parameter): return True
184         # if not marked ro, it's writable
185         if not dict[key].ro: return True
186         return False
187
188     def db_fields(self, obj = None):
189         """
190         Return only those fields that can be set or updated directly
191         (i.e., those fields that are in the primary table (table_name)
192         for this object, and are not marked as a read-only Parameter.
193         """
194
195         if obj is None:
196             obj = self
197
198         db_fields = self.api.db.fields(self.table_name)
199         return dict ( [ (key, value) for (key, value) in list(obj.items())
200                         if key in db_fields and
201                         Row.is_writable(key, value, self.fields) ] )
202
203     def tag_fields (self, obj=None):
204         """
205         Return the fields of obj that are mentioned in tags
206         """
207         if obj is None: obj=self
208
209         return dict ( [ (key,value) for (key,value) in obj.items()
210                         if key in self.tags and Row.is_writable(key,value,self.tags) ] )
211
212     # takes as input a list of columns, sort native fields from tags
213     # returns 2 dicts and one list : fields, tags, rejected
214     @classmethod
215     def parse_columns (cls, columns):
216         (fields,tags,rejected)=({},{},[])
217         for column in columns:
218             if column in cls.fields: fields[column]=cls.fields[column]
219             elif column in cls.tags: tags[column]=cls.tags[column]
220             else: rejected.append(column)
221         return (fields,tags,rejected)
222
223     # compute the 'accepts' part of a method, from a list of column names, and a fields dict
224     # use exclude=True to exclude the column names instead
225     # typically accepted_fields (Node.fields,['hostname','model',...])
226     @staticmethod
227     def accepted_fields (update_columns, fields_dict, exclude=False):
228         result={}
229         for (k,v) in fields_dict.items():
230             if (not exclude and k in update_columns) or (exclude and k not in update_columns):
231                 result[k]=v
232         return result
233
234     # filter out user-provided fields that are not part of the declared acceptance list
235     # keep it separate from split_fields for simplicity
236     # typically check_fields (<user_provided_dict>,{'hostname':Parameter(str,...),'model':Parameter(..)...})
237     @staticmethod
238     def check_fields (user_dict, accepted_fields):
239 # avoid the simple, but silent, version
240 #        return dict ([ (k,v) for (k,v) in user_dict.items() if k in accepted_fields ])
241         result={}
242         for (k,v) in list(user_dict.items()):
243             if k in accepted_fields: result[k]=v
244             else: raise PLCInvalidArgument ('Trying to set/change unaccepted key %s'%k)
245         return result
246
247     # given a dict (typically passed to an Update method), we check and sort
248     # them against a list of dicts, e.g. [Node.fields, Node.related_fields]
249     # return is a list that contains n+1 dicts, last one has the rejected fields
250     @staticmethod
251     def split_fields (fields, dicts):
252         result=[]
253         for x in dicts: result.append({})
254         rejected={}
255         for (field,value) in fields.items():
256             found=False
257             for i in range(len(dicts)):
258                 candidate_dict=dicts[i]
259                 if field in list(candidate_dict.keys()):
260                     result[i][field]=value
261                     found=True
262                     break
263             if not found: rejected[field]=value
264         result.append(rejected)
265         return result
266
267     ### class initialization : create tag-dependent cross view if needed
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_sql (cls,tagname):
274         """
275         returns a SQL sentence that creates a view named after the primary_key and tagname,
276         with 2 columns
277         (*) column 1: primary_key
278         (*) column 2: actual tag value, renamed into tagname
279         """
280
281         if not cls.view_tags_name:
282             raise Exception('WARNING: class %s needs to set view_tags_name'%cls.__name__)
283
284         table_name=cls.table_name
285         primary_key=cls.primary_key
286         view_tags_name=cls.view_tags_name
287         tagvalue_view_name=cls.tagvalue_view_name(tagname)
288         return 'CREATE OR REPLACE VIEW %(tagvalue_view_name)s ' \
289             'as SELECT %(table_name)s.%(primary_key)s,%(view_tags_name)s.value as "%(tagname)s" ' \
290             'from %(table_name)s right join %(view_tags_name)s using (%(primary_key)s) ' \
291             'WHERE tagname = \'%(tagname)s\';'%locals()
292
293     @classmethod
294     def class_init (cls,api):
295         cls.tagvalue_views_create (api)
296
297     @classmethod
298     def tagvalue_views_create (cls,api):
299         if not cls.tags: return
300         for tagname in list(cls.tags.keys()):
301             api.db.do(cls.tagvalue_view_create_sql (tagname))
302         api.db.commit()
303
304     def __eq__(self, y):
305         """
306         Compare two objects.
307         """
308
309         # Filter out fields that cannot be set or updated directly
310         # (and thus would not affect equality for the purposes of
311         # deciding if we should sync() or not).
312         x = self.db_fields()
313         y = self.db_fields(y)
314         return dict.__eq__(x, y)
315
316     # validate becomes optional on sept. 2010
317     # we find it useful to use DeletePerson on duplicated entries
318     def sync(self, commit = True, insert = None, validate=True):
319         """
320         Flush changes back to the database.
321         """
322
323         # Validate all specified fields
324         if validate: 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 = list(db_fields.keys())
331         values = [self.api.db.param(key, value) for (key, value) in list(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 self.primary_key not in self 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 is int
342                     and 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 = list(db_fields.keys())
347                 values = [self.api.db.param(key, value) for (key, value) in list(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 {} SET {} WHERE {} = {}"\
355                   .format(self.table_name,
356                           ", ".join(columns),
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])