- support new schema
[plcapi.git] / PLC / Table.py
1 class Row(dict):
2     """
3     Representation of a row in a database table. To use, optionally
4     instantiate with a dict of values. Update as you would a
5     dict. Commit to the database with sync().
6     """
7
8     # Set this to a dict of the valid fields of this object. Not all
9     # fields (e.g., joined fields) may be updated via sync().
10     fields = {}
11
12     def __init__(self, fields):
13         self.update(fields)
14
15     def update(self, fields):
16         for key, value in fields.iteritems():
17             self.__setitem__(key, value)
18
19     def __setitem__(self, key, value):
20         """
21         Magically takes care of aggregating certain variables into
22         lists.
23         """
24
25         if key in self.fields:
26             dict.__setitem__(self, key, value)
27
28     def validate(self):
29         """
30         Validates values. Will validate a value with a custom function
31         if a function named 'validate_[key]' exists.
32         """
33
34         # Validate values before committing
35         # XXX Also truncate strings that are too long
36         for key, value in self.iteritems():
37             if value is not None and hasattr(self, 'validate_' + key):
38                 validate = getattr(self, 'validate_' + key)
39                 self[key] = validate(value)
40
41     def sync(self, commit = True):
42         """
43         Flush changes back to the database.
44         """
45
46         pass
47
48 class Table(dict):
49     """
50     Representation of row(s) in a database table.
51     """
52
53     def sync(self, commit = True):
54         """
55         Flush changes back to the database.
56         """
57
58         for row in self.values():
59             row.sync(commit)