sync: insert if the primary key (usually an auto-incrementing serial
[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 the primary key (usually an auto-incrementing serial
63         # identifier) has not been specified, or the primary key is the
64         # only field in the table.
65         if not self.has_key(self.primary_key) or all_fields == [self.primary_key]:
66             # Insert new row
67             sql = "INSERT INTO %s (%s) VALUES (%s);" % \
68                   (self.table_name, ", ".join(keys), ", ".join(values))
69         else:
70             # Update existing row
71             columns = ["%s = %s" % (key, value) for (key, value) in zip(keys, values)]
72             sql = "UPDATE %s SET " % self.table_name + \
73                   ", ".join(columns) + \
74                   " WHERE %s = %s" % \
75                   (self.primary_key,
76                    self.api.db.param(self.primary_key, self[self.primary_key]))
77
78         self.api.db.do(sql, fields)
79
80         if not self.has_key(self.primary_key):
81             self[self.primary_key] = self.api.db.last_insert_id(self.table_name, self.primary_key)
82
83         if commit:
84             self.api.db.commit()
85
86     def delete(self, commit = True):
87         """
88         Delete row from its primary table.
89         """
90
91         assert self.primary_key in self
92
93         sql = "DELETE FROM %s" % self.table_name + \
94               " WHERE %s = %s" % \
95               (self.primary_key,
96                self.api.db.param(self.primary_key, self[self.primary_key]))
97
98         self.api.db.do(sql, self)
99
100         if commit:
101             self.api.db.commit()
102
103 class Table(dict):
104     """
105     Representation of row(s) in a database table.
106     """
107
108     def sync(self, commit = True):
109         """
110         Flush changes back to the database.
111         """
112
113         for row in self.values():
114             row.sync(commit)