- validate: check for attempt to unset non-null values
[plcapi.git] / PLC / Table.py
1 from PLC.Faults import *
2 from PLC.Parameter import Parameter
3
4 class Row(dict):
5     """
6     Representation of a row in a database table. To use, optionally
7     instantiate with a dict of values. Update as you would a
8     dict. Commit to the database with sync().
9     """
10
11     # Set this to the name of the table that stores the row.
12     table_name = None
13
14     # Set this to the name of the primary key of the table. It is
15     # assumed that the this key is a sequence if it is not set when
16     # sync() is called.
17     primary_key = None
18
19     # Set this to a dict of the valid fields of this object. Not all
20     # fields (e.g., joined fields) may be updated via sync().
21     fields = {}
22
23     def validate(self):
24         """
25         Validates values. Will validate a value with a custom function
26         if a function named 'validate_[key]' exists.
27         """
28
29         # Warn about mandatory fields
30         mandatory_fields = self.api.db.fields(self.table_name, notnull = True, hasdef = False)
31         for field in mandatory_fields:
32             if not self.has_key(field) or self[field] is None:
33                 raise PLCInvalidArgument, field + " must be specified and cannot be unset"
34
35         # Validate values before committing
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         # Validate all specified fields
47         self.validate()
48
49         # Filter out fields that cannot be set or updated directly
50         all_fields = self.api.db.fields(self.table_name)
51         fields = dict(filter(lambda (key, value): \
52                              key in all_fields and \
53                              (key not in self.fields or \
54                               not isinstance(self.fields[key], Parameter) or \
55                               not self.fields[key].ro),
56                              self.items()))
57
58         # Parameterize for safety
59         keys = fields.keys()
60         values = [self.api.db.param(key, value) for (key, value) in fields.items()]
61
62         if not self.has_key(self.primary_key):
63             # Insert new row
64             sql = "INSERT INTO %s (%s) VALUES (%s);" % \
65                   (self.table_name, ", ".join(keys), ", ".join(values))
66         else:
67             # Update existing row
68             columns = ["%s = %s" % (key, value) for (key, value) in zip(keys, values)]
69             sql = "UPDATE %s SET " % self.table_name + \
70                   ", ".join(columns) + \
71                   " WHERE %s = %s" % \
72                   (self.primary_key,
73                    self.api.db.param(self.primary_key, self[self.primary_key]))
74
75         self.api.db.do(sql, fields)
76
77         if not self.has_key(self.primary_key):
78             self[self.primary_key] = self.api.db.last_insert_id(self.table_name, self.primary_key)
79
80         if commit:
81             self.api.db.commit()
82
83     def delete(self, commit = True):
84         """
85         Delete row from its primary table.
86         """
87
88         assert self.primary_key in self
89
90         sql = "DELETE FROM %s" % self.table_name + \
91               " WHERE %s = %s" % \
92               (self.primary_key,
93                self.api.db.param(self.primary_key, self[self.primary_key]))
94
95         self.api.db.do(sql, self)
96
97         if commit:
98             self.api.db.commit()
99
100 class Table(dict):
101     """
102     Representation of row(s) in a database table.
103     """
104
105     def sync(self, commit = True):
106         """
107         Flush changes back to the database.
108         """
109
110         for row in self.values():
111             row.sync(commit)