- no need to override __setitem__() anymore, all helper classes query
[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 validate(self):
13         """
14         Validates values. Will validate a value with a custom function
15         if a function named 'validate_[key]' exists.
16         """
17
18         # Validate values before committing
19         # XXX Also truncate strings that are too long
20         for key, value in self.iteritems():
21             if value is not None and hasattr(self, 'validate_' + key):
22                 validate = getattr(self, 'validate_' + key)
23                 self[key] = validate(value)
24
25     def sync(self, commit = True):
26         """
27         Flush changes back to the database.
28         """
29
30         pass
31
32 class Table(dict):
33     """
34     Representation of row(s) in a database table.
35     """
36
37     def sync(self, commit = True):
38         """
39         Flush changes back to the database.
40         """
41
42         for row in self.values():
43             row.sync(commit)