First draft for leases
[plcapi.git] / PLC / Table.py
index 2362d61..c3cf0ec 100644 (file)
@@ -1,10 +1,14 @@
-from types import StringTypes
+# $Id$
+# $URL$
+from types import StringTypes, IntType, LongType
 import time
 import calendar
 
+from PLC.Timestamp import Timestamp
 from PLC.Faults import *
 from PLC.Parameter import Parameter
 
+
 class Row(dict):
     """
     Representation of a row in a database table. To use, optionally
@@ -13,11 +17,13 @@ class Row(dict):
     """
 
     # Set this to the name of the table that stores the row.
+    # e.g. table_name = "nodes"
     table_name = None
 
     # Set this to the name of the primary key of the table. It is
     # assumed that the this key is a sequence if it is not set when
     # sync() is called.
+    # e.g. primary_key="node_id"
     primary_key = None
 
     # Set this to the names of tables that reference this table's
@@ -29,9 +35,21 @@ class Row(dict):
     # sync().
     fields = {}
 
+    # The name of the view that extends objects with tags
+    # e.g. view_tags_name = "view_node_tags"
+    view_tags_name = None
+
+    # Set this to the set of tags that can be returned by the Get function
+    tags = {}
+
     def __init__(self, api, fields = {}):
         dict.__init__(self, fields)
         self.api = api
+        # run the class_init initializer once
+        cls=self.__class__
+        if not hasattr(cls,'class_inited'):
+            cls.class_init (api)
+            cls.class_inited=True # actual value does not matter
 
     def validate(self):
         """
@@ -68,8 +86,8 @@ class Row(dict):
 
     def associate(self, *args):
        """
-       Provides a means for high lvl api calls to associate objects
-        using low lvl calls.
+       Provides a means for high level api calls to associate objects
+        using low level calls.
        """
 
        if len(args) < 3:
@@ -80,28 +98,8 @@ class Row(dict):
        else:
            raise PLCInvalidArguemnt, "No such associate function associate_%s" % args[1]
 
-    def validate_timestamp(self, timestamp, check_future = False):
-        """
-        Validates the specified GMT timestamp string (must be in
-        %Y-%m-%d %H:%M:%S format) or number (seconds since UNIX epoch,
-        i.e., 1970-01-01 00:00:00 GMT). If check_future is True,
-        raises an exception if timestamp is not in the future. Returns
-        a GMT timestamp string.
-        """
-
-        time_format = "%Y-%m-%d %H:%M:%S"
-
-       if isinstance(timestamp, StringTypes):
-           # calendar.timegm() is the inverse of time.gmtime()
-           timestamp = calendar.timegm(time.strptime(timestamp, time_format))
-
-        # Human readable timestamp string
-       human = time.strftime(time_format, time.gmtime(timestamp))
-
-       if check_future and timestamp < time.time():
-            raise PLCInvalidArgument, "'%s' not in the future" % human
-
-       return human
+    def validate_timestamp (self, timestamp):
+        return Timestamp.sql_validate(timestamp)
 
     def add_object(self, classobj, join_table, columns = None):
         """
@@ -179,6 +177,17 @@ class Row(dict):
 
     remove_object = classmethod(remove_object)
 
+    # convenience: check in dict (self.fields or self.tags) that a key is writable
+    @staticmethod
+    def is_writable (key,value,dict):
+        # if not mentioned, assume it's writable (e.g. deleted ...)
+        if key not in dict: return True
+        # if mentioned but not linked to a Parameter object, idem
+        if not isinstance(dict[key], Parameter): return True
+        # if not marked ro, it's writable
+        if not dict[key].ro: return True
+        return False
+
     def db_fields(self, obj = None):
         """
         Return only those fields that can be set or updated directly
@@ -186,16 +195,113 @@ class Row(dict):
         for this object, and are not marked as a read-only Parameter.
         """
 
-        if obj is None:
-            obj = self
+        if obj is None: obj = self
 
         db_fields = self.api.db.fields(self.table_name)
-        return dict(filter(lambda (key, value): \
-                           key in db_fields and \
-                           (key not in self.fields or \
-                            not isinstance(self.fields[key], Parameter) or \
-                            not self.fields[key].ro),
-                           obj.items()))
+        return dict ( [ (key,value) for (key,value) in obj.items()
+                        if key in db_fields and
+                        Row.is_writable(key,value,self.fields) ] )
+
+    def tag_fields (self, obj=None):
+        """
+        Return the fields of obj that are mentioned in tags
+        """
+        if obj is None: obj=self
+        
+        return dict ( [ (key,value) for (key,value) in obj.iteritems() 
+                        if key in self.tags and Row.is_writable(key,value,self.tags) ] )
+    
+    # takes as input a list of columns, sort native fields from tags
+    # returns 2 dicts and one list : fields, tags, rejected
+    @classmethod
+    def parse_columns (cls, columns):
+        (fields,tags,rejected)=({},{},[])
+        for column in columns:
+            if column in cls.fields: fields[column]=cls.fields[column]
+            elif column in cls.tags: tags[column]=cls.tags[column]
+            else: rejected.append(column)
+        return (fields,tags,rejected)
+
+    # compute the 'accepts' part of a method, from a list of column names, and a fields dict
+    # use exclude=True to exclude the column names instead
+    # typically accepted_fields (Node.fields,['hostname','model',...])
+    @staticmethod
+    def accepted_fields (update_columns, fields_dict, exclude=False):
+        result={}
+        for (k,v) in fields_dict.iteritems():
+            if (not exclude and k in update_columns) or (exclude and k not in update_columns):
+                result[k]=v
+        return result
+
+    # filter out user-provided fields that are not part of the declared acceptance list
+    # keep it separate from split_fields for simplicity
+    # typically check_fields (<user_provided_dict>,{'hostname':Parameter(str,...),'model':Parameter(..)...})
+    @staticmethod
+    def check_fields (user_dict, accepted_fields):
+# avoid the simple, but silent, version
+#        return dict ([ (k,v) for (k,v) in user_dict.items() if k in accepted_fields ])
+        result={}
+        for (k,v) in user_dict.items():
+            if k in accepted_fields: result[k]=v
+            else: raise PLCInvalidArgument ('Trying to set/change unaccepted key %s'%k)
+        return result
+
+    # given a dict (typically passed to an Update method), we check and sort
+    # them against a list of dicts, e.g. [Node.fields, Node.related_fields]
+    # return is a list that contains n+1 dicts, last one has the rejected fields
+    @staticmethod
+    def split_fields (fields, dicts):
+        result=[]
+        for x in dicts: result.append({})
+        rejected={}
+        for (field,value) in fields.iteritems():
+            found=False
+            for i in range(len(dicts)):
+                candidate_dict=dicts[i]
+                if field in candidate_dict.keys():
+                    result[i][field]=value
+                    found=True
+                    break 
+            if not found: rejected[field]=value
+        result.append(rejected)
+        return result
+
+    ### class initialization : create tag-dependent cross view if needed
+    @classmethod
+    def tagvalue_view_name (cls, tagname):
+        return "tagvalue_view_%s_%s"%(cls.primary_key,tagname)
+
+    @classmethod
+    def tagvalue_view_create_sql (cls,tagname):
+        """
+        returns a SQL sentence that creates a view named after the primary_key and tagname, 
+        with 2 columns
+        (*) column 1: primary_key 
+        (*) column 2: actual tag value, renamed into tagname
+        """
+
+        if not cls.view_tags_name: 
+            raise Exception, 'WARNING: class %s needs to set view_tags_name'%cls.__name__
+
+        table_name=cls.table_name
+        primary_key=cls.primary_key
+        view_tags_name=cls.view_tags_name
+        tagvalue_view_name=cls.tagvalue_view_name(tagname)
+        return 'CREATE OR REPLACE VIEW %(tagvalue_view_name)s ' \
+            'as SELECT %(table_name)s.%(primary_key)s,%(view_tags_name)s.value as "%(tagname)s" ' \
+            'from %(table_name)s right join %(view_tags_name)s using (%(primary_key)s) ' \
+            'WHERE tagname = \'%(tagname)s\';'%locals()
+
+    @classmethod
+    def class_init (cls,api):
+        cls.tagvalue_views_create (api)
+
+    @classmethod
+    def tagvalue_views_create (cls,api):
+        if not cls.tags: return
+        for tagname in cls.tags.keys():
+            api.db.do(cls.tagvalue_view_create_sql (tagname))
+        api.db.commit()
 
     def __eq__(self, y):
         """
@@ -230,6 +336,15 @@ class Row(dict):
         if not self.has_key(self.primary_key) or \
            keys == [self.primary_key] or \
            insert is True:
+           
+           # If primary key id is a serial int and it isnt included, get next id
+           if self.fields[self.primary_key].type in (IntType, LongType) and \
+              self.primary_key not in self:
+               pk_id = self.api.db.next_id(self.table_name, self.primary_key)
+               self[self.primary_key] = pk_id
+               db_fields[self.primary_key] = pk_id
+               keys = db_fields.keys()
+               values = [self.api.db.param(key, value) for (key, value) in db_fields.items()]
             # Insert new row
             sql = "INSERT INTO %s (%s) VALUES (%s)" % \
                   (self.table_name, ", ".join(keys), ", ".join(values))
@@ -244,9 +359,6 @@ class Row(dict):
 
         self.api.db.do(sql, db_fields)
 
-        if not self.has_key(self.primary_key):
-            self[self.primary_key] = self.api.db.last_insert_id(self.table_name, self.primary_key)
-
         if commit:
             self.api.db.commit()
 
@@ -286,12 +398,16 @@ class Table(list):
 
         if columns is None:
             columns = classobj.fields
+            tag_columns={}
         else:
-            columns = filter(lambda x: x in classobj.fields, columns)
-            if not columns:
-                raise PLCInvalidArgument, "No valid return fields specified"
+            (columns,tag_columns,rejected) = classobj.parse_columns(columns)
+            if not columns and not tag_columns:
+                raise PLCInvalidArgument, "No valid return fields specified for class %s"%classobj.__name__
+            if rejected:
+                raise PLCInvalidArgument, "unknown column(s) specified %r in %s"%(rejected,classobj.__name__)
 
         self.columns = columns
+        self.tag_columns = tag_columns
 
     def sync(self, commit = True):
         """