- changes to addresses, site_address, address_address_type table config (person_addre...
[plcapi.git] / PLC / Table.py
index 68873b4..9524463 100644 (file)
@@ -118,29 +118,49 @@ class Row(dict):
         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):
+    def __init__(self, api, classobj, columns = None):
         self.api = api
-        self.row = row
+        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 fill(self, rows):
+    def selectall(self, sql, params = None):
         """
         Given a list of rows from the database, fill ourselves with
-        Row objects keyed on the primary key defined by the Row class
-        we were initialized 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
 
-        for row in rows:
-            self[row[self.row.primary_key]] = self.row(self.api, row)
+        return dict([(obj[key_field], obj) for obj in self])