- re-enable return_fields specification
[plcapi.git] / PLC / Table.py
index 4174f10..967bc6d 100644 (file)
@@ -20,8 +20,9 @@ class Row(dict):
     # 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 = {}):
@@ -74,7 +75,7 @@ class Row(dict):
            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
@@ -112,20 +113,42 @@ class Row(dict):
                   (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, row, columns = None):
+        self.api = api
+        self.row = row
+
+        if columns is None:
+            columns = row.fields
+        else:
+            columns = filter(lambda x: x in row.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):
+            self.append(self.row(self.api, row))