commit-gnue
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

gnue appserver/src/geasList.py appserver/src/ge...


From: Jan Ischebeck
Subject: gnue appserver/src/geasList.py appserver/src/ge...
Date: Tue, 04 Jun 2002 11:02:07 -0400

CVSROOT:        /cvsroot/gnue
Module name:    gnue
Changes by:     Jan Ischebeck <address@hidden>  02/06/04 11:02:07

Modified files:
        appserver/src  : geasList.py geasSession.py 
        common/src     : GConditions.py 
        common/src/dbdrivers/appserver: DBdriver.py 

Log message:
        add condition tree <-> token list (prefix notation) conversion routines
        add condition support to appserver

CVSWeb URLs:
http://savannah.gnu.org/cgi-bin/viewcvs/gnue/gnue/appserver/src/geasList.py.diff?tr1=1.7&tr2=1.8&r1=text&r2=text
http://savannah.gnu.org/cgi-bin/viewcvs/gnue/gnue/appserver/src/geasSession.py.diff?tr1=1.7&tr2=1.8&r1=text&r2=text
http://savannah.gnu.org/cgi-bin/viewcvs/gnue/gnue/common/src/GConditions.py.diff?tr1=1.14&tr2=1.15&r1=text&r2=text
http://savannah.gnu.org/cgi-bin/viewcvs/gnue/gnue/common/src/dbdrivers/appserver/DBdriver.py.diff?tr1=1.5&tr2=1.6&r1=text&r2=text

Patches:
Index: gnue/appserver/src/geasList.py
diff -c gnue/appserver/src/geasList.py:1.7 gnue/appserver/src/geasList.py:1.8
*** gnue/appserver/src/geasList.py:1.7  Wed May 29 08:35:58 2002
--- gnue/appserver/src/geasList.py      Tue Jun  4 11:02:07 2002
***************
*** 19,27 ****
  # write to the Free Software Foundation, Inc., 59 Temple Place 
  # - Suite 330, Boston, MA 02111-1307, USA.
  #
! # $Id: geasList.py,v 1.7 2002/05/29 12:35:58 siesel Exp $
  
! from gnue.common import GDataSource
  import geasInstance
  import string
  
--- 19,27 ----
  # write to the Free Software Foundation, Inc., 59 Temple Place 
  # - Suite 330, Boston, MA 02111-1307, USA.
  #
! # $Id: geasList.py,v 1.8 2002/06/04 15:02:07 siesel Exp $
  
! from gnue.common import GDataSource,GConditions
  import geasInstance
  import string
  
***************
*** 48,55 ****
    def setPrefetch (self, prefetch):
      self._prefetch = prefetch
      
!   def setConditions (self, conditions):
      self._conditions = conditions
        
    def setSort (self, sort):
      self._sort = sort
--- 48,66 ----
    def setPrefetch (self, prefetch):
      self._prefetch = prefetch
      
! 
!   # conditions = an list consisting of condition elements written down in
!   # prefix  notation i.e. (a=12) AND (c=121) -> AND = a 12 = c 121
!   # every element of the list is a tuple containing the following parts:
!   # type (eq,and,const...)  value  i.e. ('eq','') or ('const',12)
! 
!   def setConditions (self, conditions):    
      self._conditions = conditions
+     
+     # now building GCondition tree
+     self._conditionTree = GConditions.buildTreeFromPrefix(conditions)
+ 
+     
        
    def setSort (self, sort):
      self._sort = sort
***************
*** 77,84 ****
      # TODO: get the column names from the prefetch field names
      for field in self._prefetch:
        self._datasource.referenceField (field)
        
-     self._resultset = self._datasource.createResultSet ()
  
    # 
---------------------------------------------------------------------------
    # Get the first instance in the list
--- 88,99 ----
      # TODO: get the column names from the prefetch field names
      for field in self._prefetch:
        self._datasource.referenceField (field)
+ 
+     if hasattr(self,"_conditionTree"):
+       self._resultset = self._datasource.createResultSet(self._conditionTree)
+     else:
+       self._resultset = self._datasource.createResultSet()
        
  
    # 
---------------------------------------------------------------------------
    # Get the first instance in the list
Index: gnue/appserver/src/geasSession.py
diff -c gnue/appserver/src/geasSession.py:1.7 
gnue/appserver/src/geasSession.py:1.8
*** gnue/appserver/src/geasSession.py:1.7       Wed May 29 08:35:58 2002
--- gnue/appserver/src/geasSession.py   Tue Jun  4 11:02:07 2002
***************
*** 19,25 ****
  # write to the Free Software Foundation, Inc., 59 Temple Place 
  # - Suite 330, Boston, MA 02111-1307, USA.
  #
! # $Id: geasSession.py,v 1.7 2002/05/29 12:35:58 siesel Exp $
  
  import geasList
  
--- 19,25 ----
  # write to the Free Software Foundation, Inc., 59 Temple Place 
  # - Suite 330, Boston, MA 02111-1307, USA.
  #
! # $Id: geasSession.py,v 1.8 2002/06/04 15:02:07 siesel Exp $
  
  import geasList
  
***************
*** 81,84 ****
  
    def rollback (self):  
      for l in self._activelists:
!       l._datasource.rollback()    
--- 81,85 ----
  
    def rollback (self):  
      for l in self._activelists:
!       if hasattr(l,"_datasource"):
!         l._datasource.rollback()    
Index: gnue/common/src/GConditions.py
diff -c gnue/common/src/GConditions.py:1.14 gnue/common/src/GConditions.py:1.15
*** gnue/common/src/GConditions.py:1.14 Fri May  3 19:07:18 2002
--- gnue/common/src/GConditions.py      Tue Jun  4 11:02:07 2002
***************
*** 31,36 ****
--- 31,37 ----
  
  from GObjects import GObj
  import GTypecast
+ import types,string
  
  class ConditionError (StandardError):
    pass
***************
*** 88,93 ****
--- 89,202 ----
  
    return cond1
  
+ 
+ # creates an GCondition Tree out of an list of tokens in a prefix
+ # order.  
+ 
+ def buildTreeFromPrefix(term):
+ 
+   # create a GCondition object as top object in the object stack
+   parent={0:(GCondition())}
+ 
+   # GCondition will have only one parameter
+   # add paramcount=1 to the parameter count stack
+   paramcount={0:1}
+ 
+   # set start level for stack to zero
+   level=0
+   for i in term:
+         
+     # convert type into an object
+     if conditionElements.has_key(i[0]):
+       e=conditionElements[i[0]][2](parent[level])
+       level=level+1
+       # get parameter count
+       paramcount[level]=conditionElements[i[0]][0] 
+       parent[level]=e
+     elif i[0]=="field":       
+       e=GCField(parent[level], i[1])
+       paramcount[level]=paramcount[level]-1
+       if paramcount[level]==0:
+         level=level-1
+     elif i[0]=="const":
+       e=GCConst(parent[level], i[1])
+       paramcount.update({level:(paramcount[level]-1)})
+       if paramcount[level]==0:
+         level=level-1    
+     print "NAME: %s  VALUE: %s  LEVEL: %s PCOUNT: %s" % \
+           (i[0],i[1],level,paramcount[level])
+     
+   return parent[0];
+ 
+ 
+ def buildPrefixFromTree(conditionTree):
+   if type(conditionTree) != types.InstanceType:
+     raise ConditionError, "No valid condition tree"
+   else:        
+     otype = string.lower(conditionTree._type[2:])
+ 
+     #
+     #  care for objects without children
+     #
+     if otype == 'cfield':          
+       return [('field',"%s" % conditionTree.name)]
+ 
+     elif otype == 'cconst':
+       return [('const',conditionTree.value)]
+ 
+     elif otype == 'param':
+       return [('param', conditionTree.getValue())]
+           
+     #
+     #  if its an conditional object, then process it's children
+     # 
+     elif conditionElements.has_key(otype):
+       result=[]
+       
+       # first add operator to the list
+       result.append((otype,''));  #  ,None));
+       
+ 
+       # change operations with more than there minimal element no into
+       # multiple operations with minimal elements
+       # reason: to prevent a b c d AND OR being not well defined
+       # because it can be a"a b c d AND AND OR" or "a b c d AND OR OR"
+       paramcount=len(conditionTree._children)
+       while (paramcount > \
+              conditionElements[otype][0]):
+         paramcount=paramcount-1
+         result.append((otype,''));
+               
+ 
+       # then add children
+       for i in range(0, len(conditionTree._children)):
+         result = result + \
+                  buildPrefixFromTree(conditionTree._children[i])
+ 
+       #  
+       #  check for integrity of condition
+       #
+       if len(conditionTree._children) < conditionElements[otype][0]:
+         raise GConditions.ConditionError, \
+               _('Condition element "%s" expects at least %s arguments; found 
%s') % \
+               (otype, conditionElements[otype][0], 
len(conditionTree._children))            
+       
+       if len(conditionTree._children) > conditionElements[otype][1]:
+         raise GConditions.ConditionError, \
+               _('Condition element "%s" expects at most %s arguments; found 
%s') % \
+               (otype, conditionElements[otype][1], 
len(conditionTree._children))
+             
+                         
+       # return combination
+       return result;
+             
+     else:
+       raise GConditions.ConditionNotSupported, \
+             _('Condition clause "%s" is not supported '+
+             'by the condition to prefix table conversion.') % otype
+   
+ 
+ 
  class GCondition(GObj):
    def __init__(self, parent=None, type="GCCondition"):
      GObj.__init__(self, parent, type=type)
***************
*** 121,126 ****
--- 230,251 ----
      self.type = datatype
      self.value = value
  
+ class GCadd(GConditionElement):
+   def __init__(self, parent=None):
+     GConditionElement.__init__(self, parent, 'GCadd')
+ 
+ class GCsub(GConditionElement):
+   def __init__(self, parent=None):
+     GConditionElement.__init__(self, parent, 'GCsub')
+ 
+ class GCmul(GConditionElement):
+   def __init__(self, parent=None):
+     GConditionElement.__init__(self, parent, 'GCmul')
+ 
+ class GCdiv(GConditionElement):
+   def __init__(self, parent=None):
+     GConditionElement.__init__(self, parent, 'GCdiv')
+ 
  class GCand(GConditionElement):
    def __init__(self, parent=None):
      GConditionElement.__init__(self, parent, 'GCand')
***************
*** 177,182 ****
--- 302,312 ----
    def __init__(self, parent=None):
      GConditionElement.__init__(self, parent, 'GCnotbetween')
  
+ # build an impossible condition  GCondition={0=1}
+ GCimpossible=GCondition()
+ _h=GCeq(GCimpossible)
+ GCConst(_h,1)
+ GCConst(_h,2)
  
  
  def getXMLelements(updates={}):
***************
*** 270,272 ****
--- 400,427 ----
      xmlElements[alteration].update(updates[alteration])
  
    return xmlElements
+ 
+ 
+ #
+ # a table with extra information about the different condition types
+ #  (needed for condition tree <-> prefix table conversion)
+ #
+ conditionElements = {
+   'add':             (2, 999, GCadd ),
+   'sub':             (2, 999, GCsub ),
+   'mul':             (2, 999, GCmul ),
+   'div':             (2, 999, GCdiv ),
+   'and':             (1, 999, GCand ),
+   'or':              (2, 999, GCor  ),
+   'not':             (1,   1, GCnot ),
+   'negate':          (1,   1, GCnegate ),
+   'eq':              (2,   2, GCeq  ),
+   'ne':              (2,   2, GCne  ),
+   'gt':              (2,   2, GCgt  ),
+   'ge':              (2,   2, GCge  ),
+   'lt':              (2,   2, GClt  ),
+   'le':              (2,   2, GCle  ),
+   'like':            (2,   2, GClike ),
+   'notlike':         (2,   2, GCnotlike ),
+   'between':         (3,   3, GCbetween )
+   }
Index: gnue/common/src/dbdrivers/appserver/DBdriver.py
diff -c gnue/common/src/dbdrivers/appserver/DBdriver.py:1.5 
gnue/common/src/dbdrivers/appserver/DBdriver.py:1.6
*** gnue/common/src/dbdrivers/appserver/DBdriver.py:1.5 Mon Jun  3 06:41:57 2002
--- gnue/common/src/dbdrivers/appserver/DBdriver.py     Tue Jun  4 11:02:07 2002
***************
*** 43,54 ****
      
    def _postChanges(self):
      if self._deleteFlag:
!       GDebug.printMesg(5, 'GEASv2: Instance deleted')
        self._instance.delete()
  #      self._instance._close()
  
      if self._insertFlag:      
!       GDebug.printMesg(5, 'GEASv2: new Instance created and inserted')
        self._instance=self._parent._cursor.insertNewInstance()
        
      for field in (self._modifiedFlags.keys()):      
--- 43,55 ----
      
    def _postChanges(self):
      if self._deleteFlag:
!       GDebug.printMesg(5, 'AppServer database driver: Instance deleted')
        self._instance.delete()
  #      self._instance._close()
  
      if self._insertFlag:      
!       GDebug.printMesg(5, 'AppServer database driver: new Instance '+\
!                        'created and inserted')
        self._instance=self._parent._cursor.insertNewInstance()
        
      for field in (self._modifiedFlags.keys()):      
***************
*** 171,198 ****
         'or':              (2, 999, None,                   'None'      ),
         'not':             (1,   1, None,                   'None'      ),
         'negate':          (1,   1, None,                   'None'      ),
!        'eq':              (2,   2, 'queryObject.addField(GEAS.Query.Field( 
field="%s", test=GEAS.Query.equals,' + \
!                                    
'invert=CORBA.FALSE,casesensitive=CORBA.FALSE,value=%s))',                None  
   ),
! #       'ne':              (2,   2, '(%s != %s)',             None     ),
! #       'gt':              (2,   2, '(%s > %s)',              None     ),
! #       'ge':              (2,   2, '(%s >= %s)',                None     ),
! #       'lt':              (2,   2, '(%s < %s)',                 None     ),
! #       'le':              (2,   2, '(%s <= %s)',                None     ),
!        'like':            (2,   2, 'queryObject.addField(GEAS.Query.Field( 
field="%s", test=GEAS.Query.equals,' + \
!                                    
'invert=CORBA.FALSE,casesensitive=CORBA.FALSE,value=%s))',                None  
   ),
! #       'notlike':         (2,   2, '%s NOT LIKE %s',            None     ),
! #       'between':         (3,   3, '%s BETWEEN %s AND %s',      None     )
         }
  
    def __init__(self):
      GDataObjects.DataObject.__init__(self)
  
!     GDebug.printMesg (1,"GEASv2 database driver backend initializing")
      self._resultSetClass = GEASv2_ResultSet
! #    self._DatabaseError = GEAS.ServerError
  
    def connect(self, connectData={}): 
!     GDebug.printMesg(1,"GEAS database driver connecting...")
      # Extract the username and password...
      user = connectData['_username']
      passwd = connectData['_password']
--- 172,197 ----
         'or':              (2, 999, None,                   'None'      ),
         'not':             (1,   1, None,                   'None'      ),
         'negate':          (1,   1, None,                   'None'      ),
!        'eq':              (2,   2, '(%s == %s)',                None     ),
!        'ne':              (2,   2, '(%s != %s)',             None     ),
!        'gt':              (2,   2, '(%s > %s)',              None     ),
!        'ge':              (2,   2, '(%s >= %s)',                None     ),
!        'lt':              (2,   2, '(%s < %s)',                 None     ),
!        'le':              (2,   2, '(%s <= %s)',                None     ),
!        'like':            (2,   2, '(%s LIKE %s)',               None     ),
!        'notlike':         (2,   2, '%s NOT LIKE %s',            None     ),
!        'between':         (3,   3, '%s BETWEEN %s AND %s',      None     )
         }
  
    def __init__(self):
      GDataObjects.DataObject.__init__(self)
  
!     GDebug.printMesg (1,"AppServer database driver backend initializing")
      self._resultSetClass = GEASv2_ResultSet
!     self._DatabaseError = GComm.Error
  
    def connect(self, connectData={}): 
!     GDebug.printMesg(1,"AppServer database driver connecting...")
      # Extract the username and password...
      user = connectData['_username']
      passwd = connectData['_password']
***************
*** 213,219 ****
      self._session=sessionManager.getNewSession()
  
      try:
!       GDebug.printMesg(1,"Logging into geas as %s" % (user))
        if (user == 'guest') or (user == ''):
  
          # TODO: (jcater) I'm not so sure about guest logins. This
--- 212,218 ----
      self._session=sessionManager.getNewSession()
  
      try:
!       GDebug.printMesg(1,"Logging into appserver as user '%s'" % (user))
        if (user == 'guest') or (user == ''):
  
          # TODO: (jcater) I'm not so sure about guest logins. This
***************
*** 255,261 ****
      return [['_username', 'User Name',0],['_password', 'Password',1]]
  
    def _buildQuery(self, conditions={}):
!     # Standardize incomming conditions as a GConditions sturcutre
      if type(conditions) == types.DictType:
          cond = GConditions.buildConditionFromDict(conditions)
      else:
--- 254,260 ----
      return [['_username', 'User Name',0],['_password', 'Password',1]]
  
    def _buildQuery(self, conditions={}):
!     # Standardize incomming conditions as a GConditions structre
      if type(conditions) == types.DictType:
          cond = GConditions.buildConditionFromDict(conditions)
      else:
***************
*** 263,344 ****
  
      # Construct query object
      GDebug.printMesg(7,'Implicit Fields: %s' % self._fieldReferences)
!     query = self._dataConnection.newQuery()
!     query.classname = "%s" % self.table
!     query.orderby = "name"
!     #query.reverse = CORBA.FALSE
!     query.logic = GEAS.Query.AND
      
      # Add conditionals
!     self.__conditionToGEASQuery(query, cond._children[0])
      
      return query
  
-   def __conditionToGEASQuery(self, queryObject, conditionTree, count=1):
-       if type(conditionTree) != types.InstanceType:
-           return "%s" % conditionTree # This is usless in this driver as it 
won't be a string
-       else:
-           print ":"*count, conditionTree._type
-           otype = string.lower(conditionTree._type[2:])
-           if otype == 'cfield':
-               return "%s" % conditionTree.name
-           elif otype == 'cconst':
-               if conditionTree.value == None:
-                   return "NULL"
-               elif conditionTree.type == 'number':
-                   return "%s" % conditionTree.value
-               else:
-                   return "'%s'" % conditionTree.value
-           elif otype == 'param':
-               v = conditionTree.getValue()
-               return (v == None and "NULL") or ("'%s'" % 
conditionTree.getValue())
-           
-           # If the object is a conditional object then process it's children 
to build query
-           elif self.conditionElements.has_key(otype):
-               for i in range(0, len(conditionTree._children)):
-                   conditionTree._children[i] = 
self.__conditionToGEASQuery(queryObject,conditionTree._children[i])
-               if len(conditionTree._children) < 
self.conditionElements[otype][0]:
-                   raise GConditions.ConditionError, \
-                         _('Condition element "%s" expects at least %s 
arguments; found %s') % \
-                         (otype, self.conditionElements[otype][0], 
len(conditionTree._children))
-               if len(conditionTree._children) > 
self.conditionElements[otype][1]:
-                   raise GConditions.ConditionError, \
-                         _('Condition element "%s" expects at most %s 
arguments; found %s') % \
-                         (otype, self.conditionElements[otype][0], 
len(conditionTree._children))
-               if self.conditionElements[otype][3] == None:
-                   eval(self.conditionElements[otype][2] % 
tuple(conditionTree._children))
-               else:
-                   eval(self.conditionElements[otype][3])
-                             # It's an unsupported condition so flag an error
-           else:
-               raise GConditions.ConditionNotSupported, \
-                     _('Condition clause "%s" is not supported by this db 
driver.') % otype
-               
-           #print " "*count, conditionTree._type," : ", 
conditionTree.getValue()
-           #for i in range(0, len(conditionTree._children)):
-           #    self.__conditionToGEASQuery(queryObject, 
conditionTree._children[i],count+1)
- 
-         ##f = GEAS.Query.Field( field=fieldname, 
test=GEAS.Query.equals,invert=CORBA.FALSE,
-         ##                      
casesensitive=CORBA.FALSE,value=str(conditions[fieldname]))
-         ##query.addField( f )
                        
    def _createEmptyResultSet(self, readOnly=0, masterRecordSet=None):
!     return self.createResultSet(readOnly=readOnly, 
masterRecordSet=masterRecordSet)
  
    def _createResultSet(self, conditions={}, readOnly=0, masterRecordSet=None):
-     print _("Conditions"), conditions # self._buildQuery(conditions)
      try:
          self._list = self._session.createList (self.table)
      except:
          raise GDataObjects.ConnectionError, "Error during creation of object 
list"
-     try:
-       if conditions:
-           self._list.setConditions(self._buildQuery(conditions))      
-     except self._DatabaseError, err: 
-       raise GDataObjects.ConnectionError, err
    
      GDebug.printMesg (5,"Setting up list object ...");
!     
      # the fieldnames seem to be stored in _fieldReferences
      fieldlist=self._fieldReferences.keys()
      self._list.setPrefetch (fieldlist);
--- 262,290 ----
  
      # Construct query object
      GDebug.printMesg(7,'Implicit Fields: %s' % self._fieldReferences)
!     query = []
      
      # Add conditionals
!     query = GConditions.buildPrefixFromTree(cond._children[0] )
!     
!     GDebug.printMesg(7,'Full query in prefix notation: %s' % query)
      
      return query
  
                        
    def _createEmptyResultSet(self, readOnly=0, masterRecordSet=None):
!     return self.createResultSet(readOnly=readOnly,\
!                                 conditions=GConditions.GCimpossible,\
!                                 masterRecordSet=masterRecordSet)
  
    def _createResultSet(self, conditions={}, readOnly=0, masterRecordSet=None):
      try:
          self._list = self._session.createList (self.table)
      except:
          raise GDataObjects.ConnectionError, "Error during creation of object 
list"
    
      GDebug.printMesg (5,"Setting up list object ...");
! 
      # the fieldnames seem to be stored in _fieldReferences
      fieldlist=self._fieldReferences.keys()
      self._list.setPrefetch (fieldlist);
***************
*** 349,355 ****
        GDebug.printMesg (5,"Sorting list by fields '"+self.order_by+"'");
        sort=string.splitfields(self.order_by,",")
        self._list.setSort (sort)
!     
  
      GDebug.printMesg (5,"Populating list ...");
      self._list.populate ()
--- 295,308 ----
        GDebug.printMesg (5,"Sorting list by fields '"+self.order_by+"'");
        sort=string.splitfields(self.order_by,",")
        self._list.setSort (sort)
! 
!     try:
!       if conditions:
!         GDebug.printMesg (5,"Setting Conditions ...");
!         self._list.setConditions(self._buildQuery(conditions))      
!     except self._DatabaseError, err: 
!       raise GDataObjects.ConnectionError, err
!   
  
      GDebug.printMesg (5,"Populating list ...");
      self._list.populate ()
***************
*** 361,367 ****
      return rs
  
    def commit(self): 
!     GDebug.printMesg (5,"GEASv2 database driver: commit()")
   
      try:
          # at the moment there is only commit on session layer
--- 314,320 ----
      return rs
  
    def commit(self): 
!     GDebug.printMesg (5,"AppServer database driver: commit()")
   
      try:
          # at the moment there is only commit on session layer
***************
*** 370,376 ****
        raise GDataObjects.ConnectionError, value
  
    def rollback(self): 
!     GDebug.printMesg (5,"GEASv2 database driver: rollback()")
  
      try:
        # at the moment there is only rollback on session layer
--- 323,329 ----
        raise GDataObjects.ConnectionError, value
  
    def rollback(self): 
!     GDebug.printMesg (5,"AppServer database driver: rollback()")
  
      try:
        # at the moment there is only rollback on session layer
***************
*** 409,421 ****
        c = con.getFullClassDefinition( classnames[idx-1] )
        
    def getFields(self, name):
!       return ["name", "street", "city","zip"]
!       list = []
!       classdef = self._dataConnection.getFullClassDefinition(str(name))
!       for field in classdef.fields:
!           list.append(field.name)
! 
!       return list
  
  supportedDataObjects = { 
    'object': GEASv2_DataObject
--- 362,369 ----
        c = con.getFullClassDefinition( classnames[idx-1] )
        
    def getFields(self, name):
!       # no introspection support for now
!       return self._fieldReferences.keys()
  
  supportedDataObjects = { 
    'object': GEASv2_DataObject



reply via email to

[Prev in Thread] Current Thread [Next in Thread]