- overloading verification_key for account verification as well (i.e.,
[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     def validate_timestamp(self, timestamp, check_future = False):
55         """
56         Validates the specified GMT timestamp string (must be in
57         %Y-%m-%d %H:%M:%S format) or number (seconds since UNIX epoch,
58         i.e., 1970-01-01 00:00:00 GMT). If check_future is True,
59         raises an exception if timestamp is not in the future. Returns
60         a GMT timestamp string.
61         """
62
63         time_format = "%Y-%m-%d %H:%M:%S"
64
65         if isinstance(timestamp, StringTypes):
66             # calendar.timegm() is the inverse of time.gmtime()
67             timestamp = calendar.timegm(time.strptime(timestamp, time_format))
68
69         # Human readable timestamp string
70         human = time.strftime(time_format, time.gmtime(timestamp))
71
72         if check_future and timestamp < time.time():
73             raise PLCInvalidArgument, "'%s' not in the future" % human
74
75         return human
76
77     def add_object(self, classobj, join_table, columns = None):
78         """
79         Returns a function that can be used to associate this object
80         with another.
81         """
82
83         def add(self, obj, columns = None, commit = True):
84             """
85             Associate with the specified object.
86             """
87
88             # Various sanity checks
89             assert isinstance(self, Row)
90             assert self.primary_key in self
91             assert join_table in self.join_tables
92             assert isinstance(obj, classobj)
93             assert isinstance(obj, Row)
94             assert obj.primary_key in obj
95             assert join_table in obj.join_tables
96
97             # By default, just insert the primary keys of each object
98             # into the join table.
99             if columns is None:
100                 columns = {self.primary_key: self[self.primary_key],
101                            obj.primary_key: obj[obj.primary_key]}
102
103             params = []
104             for name, value in columns.iteritems():
105                 params.append(self.api.db.param(name, value))
106
107             self.api.db.do("INSERT INTO %s (%s) VALUES(%s)" % \
108                            (join_table, ", ".join(columns), ", ".join(params)),
109                            columns)
110
111             if commit:
112                 self.api.db.commit()
113     
114         return add
115
116     add_object = classmethod(add_object)
117
118     def remove_object(self, classobj, join_table):
119         """
120         Returns a function that can be used to disassociate this
121         object with another.
122         """
123
124         def remove(self, obj, commit = True):
125             """
126             Disassociate from the specified object.
127             """
128     
129             assert isinstance(self, Row)
130             assert self.primary_key in self
131             assert join_table in self.join_tables
132             assert isinstance(obj, classobj)
133             assert isinstance(obj, Row)
134             assert obj.primary_key in obj
135             assert join_table in obj.join_tables
136     
137             self_id = self[self.primary_key]
138             obj_id = obj[obj.primary_key]
139     
140             self.api.db.do("DELETE FROM %s WHERE %s = %s AND %s = %s" % \
141                            (join_table,
142                             self.primary_key, self.api.db.param('self_id', self_id),
143                             obj.primary_key, self.api.db.param('obj_id', obj_id)),
144                            locals())
145
146             if commit:
147                 self.api.db.commit()
148
149         return remove
150
151     remove_object = classmethod(remove_object)
152
153     def db_fields(self, obj = None):
154         """
155         Return only those fields that can be set or updated directly
156         (i.e., those fields that are in the primary table (table_name)
157         for this object, and are not marked as a read-only Parameter.
158         """
159
160         if obj is None:
161             obj = self
162
163         db_fields = self.api.db.fields(self.table_name)
164         return dict(filter(lambda (key, value): \
165                            key in db_fields and \
166                            (key not in self.fields or \
167                             not isinstance(self.fields[key], Parameter) or \
168                             not self.fields[key].ro),
169                            obj.items()))
170
171     def __eq__(self, y):
172         """
173         Compare two objects.
174         """
175
176         # Filter out fields that cannot be set or updated directly
177         # (and thus would not affect equality for the purposes of
178         # deciding if we should sync() or not).
179         x = self.db_fields()
180         y = self.db_fields(y)
181         return dict.__eq__(x, y)
182
183     def sync(self, commit = True, insert = None):
184         """
185         Flush changes back to the database.
186         """
187
188         # Validate all specified fields
189         self.validate()
190
191         # Filter out fields that cannot be set or updated directly
192         db_fields = self.db_fields()
193
194         # Parameterize for safety
195         keys = db_fields.keys()
196         values = [self.api.db.param(key, value) for (key, value) in db_fields.items()]
197
198         # If the primary key (usually an auto-incrementing serial
199         # identifier) has not been specified, or the primary key is the
200         # only field in the table, or insert has been forced.
201         if not self.has_key(self.primary_key) or \
202            keys == [self.primary_key] or \
203            insert is True:
204             # Insert new row
205             sql = "INSERT INTO %s (%s) VALUES (%s)" % \
206                   (self.table_name, ", ".join(keys), ", ".join(values))
207         else:
208             # Update existing row
209             columns = ["%s = %s" % (key, value) for (key, value) in zip(keys, values)]
210             sql = "UPDATE %s SET " % self.table_name + \
211                   ", ".join(columns) + \
212                   " WHERE %s = %s" % \
213                   (self.primary_key,
214                    self.api.db.param(self.primary_key, self[self.primary_key]))
215
216         self.api.db.do(sql, db_fields)
217
218         if not self.has_key(self.primary_key):
219             self[self.primary_key] = self.api.db.last_insert_id(self.table_name, self.primary_key)
220
221         if commit:
222             self.api.db.commit()
223
224     def delete(self, commit = True):
225         """
226         Delete row from its primary table, and from any tables that
227         reference it.
228         """
229
230         assert self.primary_key in self
231
232         for table in self.join_tables + [self.table_name]:
233             if isinstance(table, tuple):
234                 key = table[1]
235                 table = table[0]
236             else:
237                 key = self.primary_key
238
239             sql = "DELETE FROM %s WHERE %s = %s" % \
240                   (table, key,
241                    self.api.db.param(self.primary_key, self[self.primary_key]))
242
243             self.api.db.do(sql, self)
244
245         if commit:
246             self.api.db.commit()
247
248 class Table(list):
249     """
250     Representation of row(s) in a database table.
251     """
252
253     def __init__(self, api, classobj, columns = None):
254         self.api = api
255         self.classobj = classobj
256         self.rows = {}
257
258         if columns is None:
259             columns = classobj.fields
260         else:
261             columns = filter(lambda x: x in classobj.fields, columns)
262             if not columns:
263                 raise PLCInvalidArgument, "No valid return fields specified"
264
265         self.columns = columns
266
267     def sync(self, commit = True):
268         """
269         Flush changes back to the database.
270         """
271
272         for row in self:
273             row.sync(commit)
274
275     def selectall(self, sql, params = None):
276         """
277         Given a list of rows from the database, fill ourselves with
278         Row objects.
279         """
280
281         for row in self.api.db.selectall(sql, params):
282             obj = self.classobj(self.api, row)
283             self.append(obj)
284
285     def dict(self, key_field = None):
286         """
287         Return ourself as a dict keyed on key_field.
288         """
289
290         if key_field is None:
291             key_field = self.classobj.primary_key
292
293         return dict([(obj[key_field], obj) for obj in self])