[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
gnue/gnue-common/src/dbdrivers/geas DBdriver.py
From: |
Jason Cater |
Subject: |
gnue/gnue-common/src/dbdrivers/geas DBdriver.py |
Date: |
Tue, 21 Aug 2001 01:16:01 -0700 |
CVSROOT: /home/cvs
Module name: gnue
Changes by: Jason Cater <address@hidden> 01/08/21 01:15:36
Modified files:
gnue-common/src/dbdrivers/geas: DBdriver.py
Log message:
synching machines (neilt: don't get your hopes up :)
CVSWeb URLs:
http://savannah.gnu.org/cgi-bin/viewcvs/gnue/gnue-common/src/dbdrivers/geas/DBdriver.py.diff?cvsroot=OldCVS&tr1=1.6&tr2=1.7&r1=text&r2=text
Patches:
Index: gnue/gnue-common/src/dbdrivers/geas/DBdriver.py
diff -u gnue/gnue-common/src/dbdrivers/geas/DBdriver.py:1.6
gnue/gnue-common/src/dbdrivers/geas/DBdriver.py:1.7
--- gnue/gnue-common/src/dbdrivers/geas/DBdriver.py:1.6 Thu Jul 12 20:56:31 2001
+++ gnue/gnue-common/src/dbdrivers/geas/DBdriver.py Tue Aug 21 01:15:36 2001
@@ -16,22 +16,297 @@
# write to the Free Software Foundation, Inc., 59 Temple Place
# - Suite 330, Boston, MA 02111-1307, USA.
#
-# Copyright 2000 Free Software Foundation
+# Copyright 2000, 2001 Free Software Foundation
#
+# FILE:
+# geas/DBdriver.py
#
-# GEAS database driver
+# DESCRIPTION:
+# Implementation of dbdriver for use with GNUe Application Server.
#
-# $Id: DBdriver.py,v 1.6 2001/07/13 03:56:31 jcater Exp $
+# NOTES:
+# This implementation currently requires the use of python-orbit
+# bindings.
#
+# HISTORY:
+#
-import sys
-import md5
+from gnue.common import GDataObjects, GDebug, GConditions
import string
-from gnue.common import GDebug
-#from gnue.forms import GFOptions
-from gnue.common import GConfig
-from gnue.forms.GFError import DBError
+import types
+import md5
+
+
+class GEAS_RecordSet(GDataObjects.RecordSet):
+ def _postChanges(self):
+ values = []
+ fields = []
+ fieldString = ""
+ for field in (self._modifiedFields.keys()):
+ fields.append(field + " = %s")
+ values.append(self._fields[field])
+
+ statement = 'UPDATE %s SET %s WHERE %s = %s'
+
+
+class GEAS_ResultSet(GDataObjects.ResultSet):
+ def __init__(self, dataObject, cursor=None, \
+ defaultValues={}, masterRecordSet=None):
+ GDataObjects.ResultSet.__init__(
+ self,dataObject,cursor,defaultValues,masterRecordSet)
+ self._recordSetClass = GEAS_RecordSet
+ self._fieldNames = None
+ GDebug.printMesg(5, 'ResultSet created')
+
+ def _loadNextRecord(self):
+ if self._cursor:
+
+ try:
+ rs = self._cursor.fetchone()
+ except self._DatabaseError, err:
+ raise GDataObjects.ConnectionError, err
+
+ GDebug.printMesg(5, rs)
+ if not self._fieldNames:
+ self._fieldNames = []
+ for t in (self._cursor.description):
+ self._fieldNames.append (t[0])
+ self._boundFields[string.lower[t[0]]] = ""
+ if rs:
+ i = 0
+ dict = {}
+ for f in (rs):
+ dict[self._fieldNames[i]] = f
+ i = i + 1
+ self._cachedRecords.append (self._recordSetClass(parent=self, \
+ initialData=dict))
+ return 1
+ else:
+ return 0
+ else:
+ return 0
+
+
+class GEAS_DataObject(GDataObjects.DataObject):
+
+ conditionElements = {
+ 'add': (1, 2, 999, '(%s)', '+' ),
+ 'sub': (1, 2, 999, '(%s)', '-' ),
+ 'mul': (1, 2, 999, '(%s)', '*' ),
+ 'div': (1, 2, 999, '(%s)', '/' ),
+ 'and': (1, 2, 999, '(%s)', ' AND ' ),
+ 'or': (1, 2, 999, '(%s)', ' OR ' ),
+ 'not': (1, 1, 1, '(NOT %s)', None ),
+ 'negate': (1, 1, 1, '-%s', None ),
+ 'eq': (1, 2, 2, '(%s = %s)', None ),
+ 'ne': (1, 2, 2, '(%s != %s)', None ),
+ 'gt': (1, 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,"GEAS database driver backend initializing")
+
+ self._resultSetClass = GEAS_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']
+
+ # find the object server base object
+ self.orb = CORBA.ORB_init(() , CORBA.ORB_ID)
+ try:
+ self.ior =
open(GConfig.get('GEASDIR')+"/var/run/geas-server.ior").readline()
+ except (IOError), ex:
+ GDebug.printMesg(1, "*** Error: ior file for geas was not found... is
geas running?")
+ raise GDataObjects.ConnectionError, 'Unable to connect to GEAS. Is it
running?'
+
+ self._factory = self.orb.string_to_object(self.ior)
+ 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
+ # TODO: (jcater) should be discussed. At a minimum, I think
+ # TODO: (jcater) we need gnue.conf flags:
+ # TODO: (jcater) allowGuestLogin = [0|1]
+ # TODO: (jcater) guestLogin = guest
+ # TODO: (jcater) allowBlankLogin = [0|1]
+
+ GDebug.printMesg(1,'Logging in as guest')
+ self._databaseConnection = self._factory.guestLogin()
+ else:
+
+ # TODO: (jcater) The GEAS docs say this is not supported and
+ # TODO: (jcater) CORBA-based security should instead be used.
+ # TODO: (jcater) As I don't know jack about CORBA security,
+ # TODO: (jcater) this will have to do for now (even though,
+ # TODO: (jcater) IIRC, is does nothing to validate the user/pass
+ # TODO: (jcater) supplied to it.)
+
+ GDebug.printMesg(1,'Logging in as user "%s"' % user)
+ self._databaseConnection = self._factory.unsecureLogin(user,passwd)
+
+ ## Now make connection
+ #self.database.connect()
+
+ self.triggerExtensions = TriggerExtensions(self._databaseConnection)
+
+ except (GEAS.ServerError,
+ GEAS.AuthenticationError), ex:
+ raise GDataObjects.ConnectionError, ex
+
+ #
+ # Enter transactional mode...
+ # TODO: (jcater) As transaction support does not yet exist in GEAS,
+ # TODO: (jcater) I have no idea if this works, if it will change,
+ # TODO: (jcater) or, well, anything for that matter. Think of it
+ # TODO: (jcater) as a placeholder.
+ self._transaction = self._databaseConnection.new()
+
+
+ # We only need the basics -- username and password -- to log in
+ def getLoginFields(self):
+ return [['_username', 'User Name',0],['_password', 'Password',1]]
+
+
+ def createResultSet(self, conditions={}, readOnly=0):
+ try:
+ cursor = self._dataConnection.cursor()
+ cursor.execute(self._buildQuery(conditions))
+ except self._DatabaseError, err:
+ raise GDataObjects.ConnectionError, err
+ rs = self._resultSetClass(self, cursor=cursor)
+ if readOnly:
+ rs._readonly = readOnly
+ return rs
+
+ def commit(self):
+ GDebug.printMesg (5,"GEAS database driver: commit()")
+
+ try:
+ connection.rollback()
+ except self._DatabaseError, value:
+ raise GDataObjects.ConnectionError, value
+
+ def rollback(self):
+ GDebug.printMesg (5,"GEAS database driver: rollback()")
+
+ try:
+ connection.rollback()
+ except:
+ pass # I'm SURE this isn't right (jcater)
+ # But not all db's support transactions
+
+ def _buildQuery(self, conditions={}):
+ return None
+
+
+ # Used to convert a condition tree to an sql where clause
+ def _conditionToSQL (self, condition):
+ if condition == {} or condition == None:
+ return ""
+ elif type(condition) == types.DictType:
+ cond = GConditions.buildConditionFromDict(condition)
+ else:
+ cond = condition
+
+ if not len(cond._children):
+ return ""
+ elif len(cond._children) > 1:
+ chillun = cond._children
+ cond._children = []
+ _and = GConditions.GCand(cond)
+ _and._children = chillun
+
+ return " WHERE (%s)" % (self.__conditionToSQL (cond._children[0]))
+
+ # Used internally by _conditionToSQL
+ def __conditionToSQL (self, element):
+ if type(element) != types.InstanceType:
+ return "%s" % element
+ else:
+ otype = string.lower(element.getObjectType()[2:])
+ if otype == 'field':
+ return "%s" % element.name
+ elif otype == 'const':
+ return "'%s'" % element.value
+ elif otype == 'param':
+ return "'%s'" % element.getValue()
+ elif self.conditionElements.has_key(otype):
+ for i in range(0, len(element._children)):
+ element._children[i] = self.__conditionToSQL(element._children[i])
+ if len(element._children) < self.conditionElements[otype][0]:
+ raise GConditions.ConditionError, \
+ 'Condition element "%s" expects at least %s arguments; found %s' %
\
+ (otype, self.conditionElements[otype][0],
len(element._children))
+ if len(element._children[i]) < self.conditionElements[otype][1]:
+ raise GConditions.ConditionError, \
+ 'Condition element "%s" expects at most %s arguments; found %s' % \
+ (otype, self.conditionElements[otype][0],
len(element._children))
+ if self.conditionElements[otype][4] == None:
+ return self.conditionElements[otype][3] % tuple(element._children)
+ else:
+ return self.conditionElements[otype][3] % \
+ (string.join(element._children, self.conditionElements[otype][4]))
+ else:
+ raise GConditions.ConditionNotSupported, \
+ 'Condition clause "%s" is not supported by this db driver.' % otype
+
+
+
+
+
+class GEAS_DataObject_Object(GEAS_DataObject):
+ def _buildQuery(self, conditions={}):
+ GDebug.printMesg(7,'Implicit Fields: %s' % self._fieldReferences)
+ if len(self._fieldReferences):
+ q = "SELECT %s FROM %s%s" % \
+ (string.join(self._fieldReferences.keys(),","), self.table,
+ self._conditionToSQL(conditions))
+ else:
+ q = "SELECT * FROM %s%s" % (self.table, self._conditionToSQL(conditions))
+
+ GDebug.printMesg(5,q)
+
+ return q
+
+
+
+class GEAS_DataObject_SQL(GEAS_DataObject):
+ def _buildQuery(self, conditions={}):
+ # Obviously, this is in a pre-alpha state :)
+ return "select zipcode, city, state from zipcode order by zipcode desc"
+
+
+
+supportedDataObjects = {
+ 'object': GEAS_DataObject_Object
+}
+
+
+
+
+
+##############################################################
+#
+# Beginning of runtime initialization code...
+# (load corba bindings, etc)
+#
+##############################################################
+
try:
import CORBA
idlFiles=GConfig.get('GEASDIR')+"/share/idl/geas.idl"
@@ -50,233 +325,5 @@
print "Failed to load CORBA module."
print "Please see http://projects.sault.org/orbit-python/ for the required
python CORBA bindings"
sys.exit(0)
-
-class DBdriver:
- def __init__ (self):
- GDebug.printMesg(1,"GNU Enterprise Application Server driver
initializing")
- self.database = None
- self.orb = None
- self.ior = None
- self.factory = None
- self.uniqueKey = "objectID"
- self.fieldlist = []
- self.objlist = {}
-
- def connect(self, host, dbname, user, passwd):
- # find the object server base object
- self.orb = CORBA.ORB_init(() , CORBA.ORB_ID)
- try:
- self.ior =
open(GConfig.get('GEASDIR')+"/var/run/geas-server.ior").readline()
- except (IOError), ex:
- print "*** Error: ior file for geas was not found... is geas
running?"
- print
- sys.exit(1)
- self.factory = self.orb.string_to_object(self.ior)
- try:
- GDebug.printMesg(1,"Logging into geas as %s" % (user))
- if (user == 'guest') or (user == ''):
- self.database = self.factory.guestLogin()
- else:
- # NOTE: this will change again
- self.database = self.factory.unsecureLogin(user,passwd)
-
- ## Now make connection
- #self.database.connect()
- self.triggerExtensions = TriggerExtensions(self.database)
- except (GEAS.ServerError,
- GEAS.AuthenticationError),ex:
- print "Failed to connect to database. Exiting."
- print ex.detail;
- sys.exit(0)
-
- def disconnect(self):
- print "disconnect"
- self.database.logout();
-
- def beginTransaction(self):
- pass
-
-
- def commit(self):
- pass
-
-
- def rollback(self):
- pass
-
-
- def query(self, table, mask = None, order_by=None):
- GDebug.printMesg(3, "query mask %s " % mask)
- (objectID, mask) = self.filterMask(mask)
- self.objlist = {}
- rs = []
-
- try:
- if mask or objectID:
- maskfield = None
- maskdata = None
- for k in mask.keys():
- if mask[k]:
- maskfield = k
- maskdata = mask[k]
-
-
- if not maskfield and objectID:
- maskfield = "objectID"
- maskdata = str(objectID)
-
- if maskfield:
- self.data = self.database.loadObjects(table, maskfield,
maskdata)
- else:
- self.data = self.database.loadAll(table);
- else:
- self.data = self.database.loadAll(table);
-
- if self.data:
- for obj in self.data.objects:
- self.objlist[obj.objectID] = obj
- r = self.buildMask(obj)
- rs.append(r)
-
- # Handle any errors from the search functions above
- except GEAS.UnknownClass,ex:
- self.data = NULL
- print ex.detail
- except GEAS.UnknownField,ex:
- self.data = NULL
- print ex.detail
-
- return rs
-
- def commit(self):
- pass
-
- def rollback(self):
- pass
-
- def get_object_field(self,obj,field):
- retval = ""
- try:
- retval = obj.getField(field)
- except (GEAS.UnknownField,GEAS.NotReadable,GEAS.ServerError,
- GEAS.Interrupted,GEAS.NotDataField,GEAS.Locked,
- GEAS.TransactionNotInProgress),ex:
- # pass error message on
- raise DBError , ex.detail
- except GEAS.NullField,ex:
- # allowed, the field defaults to 'empty'
- pass
- return retval
-
- def set_object_field(self,obj,field,value):
- try:
- if field != "objectid":
- obj.setField(field,value)
- except (GEAS.UnknownField,GEAS.NotWriteable,
- GEAS.ServerError,GEAS.Interrupted,GEAS.NotDataField,
- GEAS.Locked,GEAS.TransactionNotInProgress,GEAS.Format),ex:
- raise DBError , ex.detail
-
- def insert(self,table,mask):
- (objectID, mask) = self.filterMask(mask)
-
- try:
- obj = self.database.newObject(table)
- except GEAS.UnknownClass,ex: print ex.detail
- for m in mask.keys():
- self.set_object_field(obj,m,mask[m])
-
- mask["objectID"] = obj.objectID
-
- self.objlist[obj.objectID] = obj
-
- return mask
-
- def delete(self,table,mask):
- (objectID, mask) = self.filterMask(mask)
- obj = self.objlist[objectID]
- if obj:
- obj.delete()
-
- def update(self,table,mask):
- (objectID, mask) = self.filterMask(mask)
- obj = self.objlist[objectID]
- if obj:
- for k in mask.keys():
- self.set_object_field(obj,k,mask[k])
-
- return [self.buildMask(obj)]
-
- def getFieldList(self,table):
- list = {}
- self.fieldlist = {}
- cd = self.database.getFullClassDefinition(table)
- if cd:
- for field in cd.fields:
- if field.type == GEAS.basic:
- list[field.name] = field.type
- list["objectid"] = GEAS.Char
-
- self.fieldlist = list
- return list
-
- def getUniqueKey(self, table):
- return self.uniqueKey
-
- def filterMask(self, mask):
- objectID = None
- nmask = {}
- if mask != None:
- for k in mask.keys():
- if k == 'objectID':
- objectID = mask[k]
- else:
- nmask[k] = mask[k]
-
- return (objectID, nmask)
-
- def buildMask(self, obj):
- r = {}
- # add objectID into field list
- r[self.uniqueKey] = obj.objectID
- for f in self.fieldlist.keys():
- r[f] = self.get_object_field(obj,f)
- return r
-
- def _make_passkey(self, user, passwd, random):
- m = md5.new(user + '-' + passwd + '-' + random)
- return self._hexstr(m.digest())
-
- def _hexstr(self, s):
- h = string.hexdigits
- r = ''
- for c in s:
- i = ord(c)
- r = r + h[(i >> 4) & 0xF] + h[i & 0xF]
- return r
-
-
-
-#
-# Extensions to Trigger Namespaces
-#
-class TriggerExtensions:
-
- def __init__(self, connection):
- self.__connection = connection
-
- # Return the current date, according to database
-# def getDate(self):
-# pass
-
- # Return a sequence number from sequence 'name'
-# def getSequence(self, name):
-# pass
-
- # Run the SQL statement 'statement'
-# def sql(self, statement):
-# pass
-
-
[Prev in Thread] |
Current Thread |
[Next in Thread] |
- gnue/gnue-common/src/dbdrivers/geas DBdriver.py,
Jason Cater <=