add svn keyword
[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     table_name = None
18
19     # Set this to the name of the primary key of the table. It is
20     # assumed that the this key is a sequence if it is not set when
21     # sync() is called.
22     primary_key = None
23
24     # Set this to the names of tables that reference this table's
25     # primary key.
26     join_tables = []
27
28     # Set this to a dict of the valid fields of this object and their
29     # types. Not all fields (e.g., joined fields) may be updated via
30     # sync().
31     fields = {}
32
33     def __init__(self, api, fields = {}):
34         dict.__init__(self, fields)
35         self.api = api
36
37     def validate(self):
38         """
39         Validates values. Will validate a value with a custom function
40         if a function named 'validate_[key]' exists.
41         """
42
43         # Warn about mandatory fields
44         mandatory_fields = self.api.db.fields(self.table_name, notnull = True, hasdef = False)
45         for field in mandatory_fields:
46             if not self.has_key(field) or self[field] is None:
47                 raise PLCInvalidArgument, field + " must be specified and cannot be unset in class %s"%self.__class__.__name__
48
49         # Validate values before committing
50         for key, value in self.iteritems():
51             if value is not None and hasattr(self, 'validate_' + key):
52                 validate = getattr(self, 'validate_' + key)
53                 self[key] = validate(value)
54         
55     def separate_types(self, items):
56         """
57         Separate a list of different typed objects. 
58         Return a list for each type (ints, strs and dicts)
59         """
60         
61         if isinstance(items, (list, tuple, set)):
62             ints = filter(lambda x: isinstance(x, (int, long)), items)
63             strs = filter(lambda x: isinstance(x, StringTypes), items)
64             dicts = filter(lambda x: isinstance(x, dict), items)
65             return (ints, strs, dicts)          
66         else:
67             raise PLCInvalidArgument, "Can only separate list types" 
68                 
69
70     def associate(self, *args):
71         """
72         Provides a means for high lvl api calls to associate objects
73         using low lvl calls.
74         """
75
76         if len(args) < 3:
77             raise PLCInvalidArgumentCount, "auth, field, value must be specified"
78         elif hasattr(self, 'associate_' + args[1]):
79             associate = getattr(self, 'associate_'+args[1])
80             associate(*args)
81         else:
82             raise PLCInvalidArguemnt, "No such associate function associate_%s" % args[1]
83
84     def validate_timestamp(self, timestamp, check_future = False):
85         """
86         Validates the specified GMT timestamp string (must be in
87         %Y-%m-%d %H:%M:%S format) or number (seconds since UNIX epoch,
88         i.e., 1970-01-01 00:00:00 GMT). If check_future is True,
89         raises an exception if timestamp is not in the future. Returns
90         a GMT timestamp string.
91         """
92
93         time_format = "%Y-%m-%d %H:%M:%S"
94
95         if isinstance(timestamp, StringTypes):
96             # calendar.timegm() is the inverse of time.gmtime()
97             timestamp = calendar.timegm(time.strptime(timestamp, time_format))
98
99         # Human readable timestamp string
100         human = time.strftime(time_format, time.gmtime(timestamp))
101
102         if check_future and timestamp < time.time():
103             raise PLCInvalidArgument, "'%s' not in the future" % human
104
105         return human
106
107     def add_object(self, classobj, join_table, columns = None):
108         """
109         Returns a function that can be used to associate this object
110         with another.
111         """
112
113         def add(self, obj, columns = None, commit = True):
114             """
115             Associate with the specified object.
116             """
117
118             # Various sanity checks
119             assert isinstance(self, Row)
120             assert self.primary_key in self
121             assert join_table in self.join_tables
122             assert isinstance(obj, classobj)
123             assert isinstance(obj, Row)
124             assert obj.primary_key in obj
125             assert join_table in obj.join_tables
126
127             # By default, just insert the primary keys of each object
128             # into the join table.
129             if columns is None:
130                 columns = {self.primary_key: self[self.primary_key],
131                            obj.primary_key: obj[obj.primary_key]}
132
133             params = []
134             for name, value in columns.iteritems():
135                 params.append(self.api.db.param(name, value))
136
137             self.api.db.do("INSERT INTO %s (%s) VALUES(%s)" % \
138                            (join_table, ", ".join(columns), ", ".join(params)),
139                            columns)
140
141             if commit:
142                 self.api.db.commit()
143     
144         return add
145
146     add_object = classmethod(add_object)
147
148     def remove_object(self, classobj, join_table):
149         """
150         Returns a function that can be used to disassociate this
151         object with another.
152         """
153
154         def remove(self, obj, commit = True):
155             """
156             Disassociate from the specified object.
157             """
158     
159             assert isinstance(self, Row)
160             assert self.primary_key in self
161             assert join_table in self.join_tables
162             assert isinstance(obj, classobj)
163             assert isinstance(obj, Row)
164             assert obj.primary_key in obj
165             assert join_table in obj.join_tables
166     
167             self_id = self[self.primary_key]
168             obj_id = obj[obj.primary_key]
169     
170             self.api.db.do("DELETE FROM %s WHERE %s = %s AND %s = %s" % \
171                            (join_table,
172                             self.primary_key, self.api.db.param('self_id', self_id),
173                             obj.primary_key, self.api.db.param('obj_id', obj_id)),
174                            locals())
175
176             if commit:
177                 self.api.db.commit()
178
179         return remove
180
181     remove_object = classmethod(remove_object)
182
183     def db_fields(self, obj = None):
184         """
185         Return only those fields that can be set or updated directly
186         (i.e., those fields that are in the primary table (table_name)
187         for this object, and are not marked as a read-only Parameter.
188         """
189
190         if obj is None:
191             obj = self
192
193         db_fields = self.api.db.fields(self.table_name)
194         return dict(filter(lambda (key, value): \
195                            key in db_fields and \
196                            (key not in self.fields or \
197                             not isinstance(self.fields[key], Parameter) or \
198                             not self.fields[key].ro),
199                            obj.items()))
200
201     def __eq__(self, y):
202         """
203         Compare two objects.
204         """
205
206         # Filter out fields that cannot be set or updated directly
207         # (and thus would not affect equality for the purposes of
208         # deciding if we should sync() or not).
209         x = self.db_fields()
210         y = self.db_fields(y)
211         return dict.__eq__(x, y)
212
213     def sync(self, commit = True, insert = None):
214         """
215         Flush changes back to the database.
216         """
217
218         # Validate all specified fields
219         self.validate()
220
221         # Filter out fields that cannot be set or updated directly
222         db_fields = self.db_fields()
223
224         # Parameterize for safety
225         keys = db_fields.keys()
226         values = [self.api.db.param(key, value) for (key, value) in db_fields.items()]
227
228         # If the primary key (usually an auto-incrementing serial
229         # identifier) has not been specified, or the primary key is the
230         # only field in the table, or insert has been forced.
231         if not self.has_key(self.primary_key) or \
232            keys == [self.primary_key] or \
233            insert is True:
234             
235             # If primary key id is a serial int and it isnt included, get next id
236             if self.fields[self.primary_key].type in (IntType, LongType) and \
237                self.primary_key not in self:
238                 pk_id = self.api.db.next_id(self.table_name, self.primary_key)
239                 self[self.primary_key] = pk_id
240                 db_fields[self.primary_key] = pk_id
241                 keys = db_fields.keys()
242                 values = [self.api.db.param(key, value) for (key, value) in db_fields.items()]
243             # Insert new row
244             sql = "INSERT INTO %s (%s) VALUES (%s)" % \
245                   (self.table_name, ", ".join(keys), ", ".join(values))
246         else:
247             # Update existing row
248             columns = ["%s = %s" % (key, value) for (key, value) in zip(keys, values)]
249             sql = "UPDATE %s SET " % self.table_name + \
250                   ", ".join(columns) + \
251                   " WHERE %s = %s" % \
252                   (self.primary_key,
253                    self.api.db.param(self.primary_key, self[self.primary_key]))
254
255         self.api.db.do(sql, db_fields)
256
257         if commit:
258             self.api.db.commit()
259
260     def delete(self, commit = True):
261         """
262         Delete row from its primary table, and from any tables that
263         reference it.
264         """
265
266         assert self.primary_key in self
267
268         for table in self.join_tables + [self.table_name]:
269             if isinstance(table, tuple):
270                 key = table[1]
271                 table = table[0]
272             else:
273                 key = self.primary_key
274
275             sql = "DELETE FROM %s WHERE %s = %s" % \
276                   (table, key,
277                    self.api.db.param(self.primary_key, self[self.primary_key]))
278
279             self.api.db.do(sql, self)
280
281         if commit:
282             self.api.db.commit()
283
284 class Table(list):
285     """
286     Representation of row(s) in a database table.
287     """
288
289     def __init__(self, api, classobj, columns = None):
290         self.api = api
291         self.classobj = classobj
292         self.rows = {}
293
294         if columns is None:
295             columns = classobj.fields
296         else:
297             columns = filter(lambda x: x in classobj.fields, columns)
298             if not columns:
299                 raise PLCInvalidArgument, "No valid return fields specified"
300
301         self.columns = columns
302
303     def sync(self, commit = True):
304         """
305         Flush changes back to the database.
306         """
307
308         for row in self:
309             row.sync(commit)
310
311     def selectall(self, sql, params = None):
312         """
313         Given a list of rows from the database, fill ourselves with
314         Row objects.
315         """
316
317         for row in self.api.db.selectall(sql, params):
318             obj = self.classobj(self.api, row)
319             self.append(obj)
320
321     def dict(self, key_field = None):
322         """
323         Return ourself as a dict keyed on key_field.
324         """
325
326         if key_field is None:
327             key_field = self.classobj.primary_key
328
329         return dict([(obj[key_field], obj) for obj in self])