defining view_name in the Row class does not work, as Table does not know about its...
[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 three lists
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     @classmethod
238     def tagvalue_view_name (cls, tagname):
239         return "tagvalue_view_%s_%s"%(cls.primary_key,tagname)
240
241     @classmethod
242     def tagvalue_view_create (cls,tagname):
243         """
244         returns an SQL sentence that creates a view named after the primary_key and tagname, 
245         with 2 columns
246         (*) column 1: name=self.primary_key 
247         (*) column 2: name=tagname value=tagvalue
248         """
249
250         if not cls.view_tags_name: return ""
251
252         table_name=cls.table_name
253         primary_key=cls.primary_key
254         view_tags_name=cls.view_tags_name
255         tagvalue_view_name=cls.tagvalue_view_name(tagname)
256         return 'CREATE OR REPLACE VIEW %(tagvalue_view_name)s ' \
257             'as SELECT %(table_name)s.%(primary_key)s,%(view_tags_name)s.tagvalue as "%(tagname)s" ' \
258             'from %(table_name)s right join %(view_tags_name)s using (%(primary_key)s) ' \
259             'WHERE tagname = \'%(tagname)s\';'%locals()
260
261     @classmethod
262     def tagvalue_views_create (cls):
263         if not cls.tags: return
264         sql = []
265         for (type,type_dict) in cls.tags.iteritems():
266             for (tagname,details) in type_dict.iteritems():
267                 sql.append(cls.tagvalue_view_create (tagname))
268         return sql
269
270     def __eq__(self, y):
271         """
272         Compare two objects.
273         """
274
275         # Filter out fields that cannot be set or updated directly
276         # (and thus would not affect equality for the purposes of
277         # deciding if we should sync() or not).
278         x = self.db_fields()
279         y = self.db_fields(y)
280         return dict.__eq__(x, y)
281
282     def sync(self, commit = True, insert = None):
283         """
284         Flush changes back to the database.
285         """
286
287         # Validate all specified fields
288         self.validate()
289
290         # Filter out fields that cannot be set or updated directly
291         db_fields = self.db_fields()
292
293         # Parameterize for safety
294         keys = db_fields.keys()
295         values = [self.api.db.param(key, value) for (key, value) in db_fields.items()]
296
297         # If the primary key (usually an auto-incrementing serial
298         # identifier) has not been specified, or the primary key is the
299         # only field in the table, or insert has been forced.
300         if not self.has_key(self.primary_key) or \
301            keys == [self.primary_key] or \
302            insert is True:
303             
304             # If primary key id is a serial int and it isnt included, get next id
305             if self.fields[self.primary_key].type in (IntType, LongType) and \
306                self.primary_key not in self:
307                 pk_id = self.api.db.next_id(self.table_name, self.primary_key)
308                 self[self.primary_key] = pk_id
309                 db_fields[self.primary_key] = pk_id
310                 keys = db_fields.keys()
311                 values = [self.api.db.param(key, value) for (key, value) in db_fields.items()]
312             # Insert new row
313             sql = "INSERT INTO %s (%s) VALUES (%s)" % \
314                   (self.table_name, ", ".join(keys), ", ".join(values))
315         else:
316             # Update existing row
317             columns = ["%s = %s" % (key, value) for (key, value) in zip(keys, values)]
318             sql = "UPDATE %s SET " % self.table_name + \
319                   ", ".join(columns) + \
320                   " WHERE %s = %s" % \
321                   (self.primary_key,
322                    self.api.db.param(self.primary_key, self[self.primary_key]))
323
324         self.api.db.do(sql, db_fields)
325
326         if commit:
327             self.api.db.commit()
328
329     def delete(self, commit = True):
330         """
331         Delete row from its primary table, and from any tables that
332         reference it.
333         """
334
335         assert self.primary_key in self
336
337         for table in self.join_tables + [self.table_name]:
338             if isinstance(table, tuple):
339                 key = table[1]
340                 table = table[0]
341             else:
342                 key = self.primary_key
343
344             sql = "DELETE FROM %s WHERE %s = %s" % \
345                   (table, key,
346                    self.api.db.param(self.primary_key, self[self.primary_key]))
347
348             self.api.db.do(sql, self)
349
350         if commit:
351             self.api.db.commit()
352
353 class Table(list):
354     """
355     Representation of row(s) in a database table.
356     """
357
358     def __init__(self, api, classobj, columns = None):
359         self.api = api
360         self.classobj = classobj
361         self.rows = {}
362
363         if columns is None:
364             columns = classobj.fields
365             tag_columns={}
366         else:
367             (columns,tag_columns,rejected) = classobj.parse_columns(columns)
368             if not columns:
369                 raise PLCInvalidArgument, "No valid return fields specified for class %s"%classobj.__name__
370             if rejected:
371                 raise PLCInvalidArgument, "unknown column(s) specified %r in %s"%(rejected,classobj.__name__)
372
373         self.columns = columns
374         self.tag_columns = tag_columns
375
376     def sync(self, commit = True):
377         """
378         Flush changes back to the database.
379         """
380
381         for row in self:
382             row.sync(commit)
383
384     def selectall(self, sql, params = None):
385         """
386         Given a list of rows from the database, fill ourselves with
387         Row objects.
388         """
389
390         for row in self.api.db.selectall(sql, params):
391             obj = self.classobj(self.api, row)
392             self.append(obj)
393
394     def dict(self, key_field = None):
395         """
396         Return ourself as a dict keyed on key_field.
397         """
398
399         if key_field is None:
400             key_field = self.classobj.primary_key
401
402         return dict([(obj[key_field], obj) for obj in self])