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