# primary key.
join_tables = []
- # Set this to a dict of the valid fields of this object. Not all
- # fields (e.g., joined fields) may be updated via sync().
+ # Set this to a dict of the valid fields of this object and their
+ # types. Not all fields (e.g., joined fields) may be updated via
+ # sync().
fields = {}
def __init__(self, api, fields = {}):
mandatory_fields = self.api.db.fields(self.table_name, notnull = True, hasdef = False)
for field in mandatory_fields:
if not self.has_key(field) or self[field] is None:
- raise PLCInvalidArgument, field + " must be specified and cannot be unset"
+ raise PLCInvalidArgument, field + " must be specified and cannot be unset in class %s"%self.__class__.__name__
# Validate values before committing
for key, value in self.iteritems():
all_fields == [self.primary_key] or \
insert is True:
# Insert new row
- sql = "INSERT INTO %s (%s) VALUES (%s);" % \
+ sql = "INSERT INTO %s (%s) VALUES (%s)" % \
(self.table_name, ", ".join(keys), ", ".join(values))
else:
# Update existing row
if commit:
self.api.db.commit()
-class Table(dict):
+class Table(list):
"""
Representation of row(s) in a database table.
"""
+ def __init__(self, api, classobj, columns = None):
+ self.api = api
+ self.classobj = classobj
+ self.rows = {}
+
+ if columns is None:
+ columns = classobj.fields
+ else:
+ columns = filter(lambda x: x in classobj.fields, columns)
+ if not columns:
+ raise PLCInvalidArgument, "No valid return fields specified"
+
+ self.columns = columns
+
def sync(self, commit = True):
"""
Flush changes back to the database.
"""
- for row in self.values():
+ for row in self:
row.sync(commit)
+
+ def selectall(self, sql, params = None):
+ """
+ Given a list of rows from the database, fill ourselves with
+ Row objects.
+ """
+
+ for row in self.api.db.selectall(sql, params):
+ obj = self.classobj(self.api, row)
+ self.append(obj)
+
+ def dict(self, key_field = None):
+ """
+ Return ourself as a dict keyed on key_field.
+ """
+
+ if key_field is None:
+ key_field = self.classobj.primary_key
+
+ return dict([(obj[key_field], obj) for obj in self])