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