- removed anything having to with event_type/event_object
[plcapi.git] / PLC / Table.py
index be126a6..328c1d2 100644 (file)
@@ -16,10 +16,19 @@ class Row(dict):
     # sync() is called.
     primary_key = None
 
-    # 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 the names of tables that reference this table's
+    # primary key.
+    join_tables = []
+
+    # 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 = {}):
+        dict.__init__(self, fields)
+        self.api = api
+
     def validate(self):
         """
         Validates values. Will validate a value with a custom function
@@ -30,7 +39,7 @@ class Row(dict):
         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():
@@ -38,7 +47,7 @@ class Row(dict):
                 validate = getattr(self, 'validate_' + key)
                 self[key] = validate(value)
 
-    def sync(self, commit = True):
+    def sync(self, commit = True, insert = None):
         """
         Flush changes back to the database.
         """
@@ -61,10 +70,12 @@ class Row(dict):
 
         # If the primary key (usually an auto-incrementing serial
         # identifier) has not been specified, or the primary key is the
-        # only field in the table.
-        if not self.has_key(self.primary_key) or all_fields == [self.primary_key]:
+        # only field in the table, or insert has been forced.
+        if not self.has_key(self.primary_key) or \
+           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
@@ -85,30 +96,71 @@ class Row(dict):
 
     def delete(self, commit = True):
         """
-        Delete row from its primary table.
+        Delete row from its primary table, and from any tables that
+        reference it.
         """
 
         assert self.primary_key in self
 
-        sql = "DELETE FROM %s" % self.table_name + \
-              " WHERE %s = %s" % \
-              (self.primary_key,
-               self.api.db.param(self.primary_key, self[self.primary_key]))
+        for table in self.join_tables + [self.table_name]:
+            if isinstance(table, tuple):
+                key = table[1]
+                table = table[0]
+            else:
+                key = self.primary_key
+
+            sql = "DELETE FROM %s WHERE %s = %s" % \
+                  (table, key,
+                   self.api.db.param(self.primary_key, self[self.primary_key]))
 
-        self.api.db.do(sql, self)
+            self.api.db.do(sql, self)
 
         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])