- python < 2.4 does not support function decorators
[plcapi.git] / PLC / Table.py
1 from types import StringTypes
2 import time
3 import calendar
4
5 from PLC.Faults import *
6 from PLC.Parameter import Parameter
7
8 class Row(dict):
9     """
10     Representation of a row in a database table. To use, optionally
11     instantiate with a dict of values. Update as you would a
12     dict. Commit to the database with sync().
13     """
14
15     # Set this to the name of the table that stores the row.
16     table_name = None
17
18     # Set this to the name of the primary key of the table. It is
19     # assumed that the this key is a sequence if it is not set when
20     # sync() is called.
21     primary_key = None
22
23     # Set this to the names of tables that reference this table's
24     # primary key.
25     join_tables = []
26
27     # Set this to a dict of the valid fields of this object and their
28     # types. Not all fields (e.g., joined fields) may be updated via
29     # sync().
30     fields = {}
31
32     def __init__(self, api, fields = {}):
33         dict.__init__(self, fields)
34         self.api = api
35
36     def validate(self):
37         """
38         Validates values. Will validate a value with a custom function
39         if a function named 'validate_[key]' exists.
40         """
41
42         # Warn about mandatory fields
43         mandatory_fields = self.api.db.fields(self.table_name, notnull = True, hasdef = False)
44         for field in mandatory_fields:
45             if not self.has_key(field) or self[field] is None:
46                 raise PLCInvalidArgument, field + " must be specified and cannot be unset in class %s"%self.__class__.__name__
47
48         # Validate values before committing
49         for key, value in self.iteritems():
50             if value is not None and hasattr(self, 'validate_' + key):
51                 validate = getattr(self, 'validate_' + key)
52                 self[key] = validate(value)
53
54     time_format = "%Y-%m-%d %H:%M:%S"
55     def validate_timestamp (self, timestamp, check_future=False):
56         # in case we try to sync the same object twice
57         if isinstance(timestamp, StringTypes):
58             # calendar.timegm is the inverse of time.gmtime, in that it computes in UTC
59             # surprisingly enough, no other method in the time module behaves this way
60             # this method is documented in the time module's documentation
61             timestamp = calendar.timegm (time.strptime (timestamp,Row.time_format))
62         human = time.strftime (Row.time_format, time.gmtime(timestamp))
63         if check_future and (timestamp < time.time()):
64             raise PLCInvalidArgument, "%s: date must be in the future"%human
65         return human
66
67     def add_object(self, classobj, join_table, columns = None):
68         """
69         Returns a function that can be used to associate this object
70         with another.
71         """
72
73         def add(self, obj, columns = None, commit = True):
74             """
75             Associate with the specified object.
76             """
77
78             # Various sanity checks
79             assert isinstance(self, Row)
80             assert self.primary_key in self
81             assert join_table in self.join_tables
82             assert isinstance(obj, classobj)
83             assert isinstance(obj, Row)
84             assert obj.primary_key in obj
85             assert join_table in obj.join_tables
86
87             # By default, just insert the primary keys of each object
88             # into the join table.
89             if columns is None:
90                 columns = {self.primary_key: self[self.primary_key],
91                            obj.primary_key: obj[obj.primary_key]}
92
93             params = []
94             for name, value in columns.iteritems():
95                 params.append(self.api.db.param(name, value))
96
97             self.api.db.do("INSERT INTO %s (%s) VALUES(%s)" % \
98                            (join_table, ", ".join(columns), ", ".join(params)),
99                            columns)
100
101             if commit:
102                 self.api.db.commit()
103     
104         return add
105
106     add_object = classmethod(add_object)
107
108     def remove_object(self, classobj, join_table):
109         """
110         Returns a function that can be used to disassociate this
111         object with another.
112         """
113
114         def remove(self, obj, commit = True):
115             """
116             Disassociate from the specified object.
117             """
118     
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             self_id = self[self.primary_key]
128             obj_id = obj[obj.primary_key]
129     
130             self.api.db.do("DELETE FROM %s WHERE %s = %s AND %s = %s" % \
131                            (join_table,
132                             self.primary_key, self.api.db.param('self_id', self_id),
133                             obj.primary_key, self.api.db.param('obj_id', obj_id)),
134                            locals())
135
136             if commit:
137                 self.api.db.commit()
138
139         return remove
140
141     remove_object = classmethod(remove_object)
142
143     def db_fields(self, obj = None):
144         """
145         Return only those fields that can be set or updated directly
146         (i.e., those fields that are in the primary table (table_name)
147         for this object, and are not marked as a read-only Parameter.
148         """
149
150         if obj is None:
151             obj = self
152
153         db_fields = self.api.db.fields(self.table_name)
154         return dict(filter(lambda (key, value): \
155                            key in db_fields and \
156                            (key not in self.fields or \
157                             not isinstance(self.fields[key], Parameter) or \
158                             not self.fields[key].ro),
159                            obj.items()))
160
161     def __eq__(self, y):
162         """
163         Compare two objects.
164         """
165
166         # Filter out fields that cannot be set or updated directly
167         # (and thus would not affect equality for the purposes of
168         # deciding if we should sync() or not).
169         x = self.db_fields()
170         y = self.db_fields(y)
171         return dict.__eq__(x, y)
172
173     def sync(self, commit = True, insert = None):
174         """
175         Flush changes back to the database.
176         """
177
178         # Validate all specified fields
179         self.validate()
180
181         # Filter out fields that cannot be set or updated directly
182         db_fields = self.db_fields()
183
184         # Parameterize for safety
185         keys = db_fields.keys()
186         values = [self.api.db.param(key, value) for (key, value) in db_fields.items()]
187
188         # If the primary key (usually an auto-incrementing serial
189         # identifier) has not been specified, or the primary key is the
190         # only field in the table, or insert has been forced.
191         if not self.has_key(self.primary_key) or \
192            keys == [self.primary_key] or \
193            insert is True:
194             # Insert new row
195             sql = "INSERT INTO %s (%s) VALUES (%s)" % \
196                   (self.table_name, ", ".join(keys), ", ".join(values))
197         else:
198             # Update existing row
199             columns = ["%s = %s" % (key, value) for (key, value) in zip(keys, values)]
200             sql = "UPDATE %s SET " % self.table_name + \
201                   ", ".join(columns) + \
202                   " WHERE %s = %s" % \
203                   (self.primary_key,
204                    self.api.db.param(self.primary_key, self[self.primary_key]))
205
206         self.api.db.do(sql, db_fields)
207
208         if not self.has_key(self.primary_key):
209             self[self.primary_key] = self.api.db.last_insert_id(self.table_name, self.primary_key)
210
211         if commit:
212             self.api.db.commit()
213
214     def delete(self, commit = True):
215         """
216         Delete row from its primary table, and from any tables that
217         reference it.
218         """
219
220         assert self.primary_key in self
221
222         for table in self.join_tables + [self.table_name]:
223             if isinstance(table, tuple):
224                 key = table[1]
225                 table = table[0]
226             else:
227                 key = self.primary_key
228
229             sql = "DELETE FROM %s WHERE %s = %s" % \
230                   (table, key,
231                    self.api.db.param(self.primary_key, self[self.primary_key]))
232
233             self.api.db.do(sql, self)
234
235         if commit:
236             self.api.db.commit()
237
238 class Table(list):
239     """
240     Representation of row(s) in a database table.
241     """
242
243     def __init__(self, api, classobj, columns = None):
244         self.api = api
245         self.classobj = classobj
246         self.rows = {}
247
248         if columns is None:
249             columns = classobj.fields
250         else:
251             columns = filter(lambda x: x in classobj.fields, columns)
252             if not columns:
253                 raise PLCInvalidArgument, "No valid return fields specified"
254
255         self.columns = columns
256
257     def sync(self, commit = True):
258         """
259         Flush changes back to the database.
260         """
261
262         for row in self:
263             row.sync(commit)
264
265     def selectall(self, sql, params = None):
266         """
267         Given a list of rows from the database, fill ourselves with
268         Row objects.
269         """
270
271         for row in self.api.db.selectall(sql, params):
272             obj = self.classobj(self.api, row)
273             self.append(obj)
274
275     def dict(self, key_field = None):
276         """
277         Return ourself as a dict keyed on key_field.
278         """
279
280         if key_field is None:
281             key_field = self.classobj.primary_key
282
283         return dict([(obj[key_field], obj) for obj in self])