[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
r5083 - trunk/gnue-common/src/datasources/drivers/appserver/appserver
From: |
jan |
Subject: |
r5083 - trunk/gnue-common/src/datasources/drivers/appserver/appserver |
Date: |
Mon, 9 Feb 2004 13:48:51 -0600 (CST) |
Author: jan
Date: 2004-02-09 13:48:51 -0600 (Mon, 09 Feb 2004)
New Revision: 5083
Removed:
trunk/gnue-common/src/datasources/drivers/appserver/appserver/Driver.py
Log:
remove pre-datasource-API-update stuff
Deleted: trunk/gnue-common/src/datasources/drivers/appserver/appserver/Driver.py
===================================================================
--- trunk/gnue-common/src/datasources/drivers/appserver/appserver/Driver.py
2004-02-09 19:25:01 UTC (rev 5082)
+++ trunk/gnue-common/src/datasources/drivers/appserver/appserver/Driver.py
2004-02-09 19:48:51 UTC (rev 5083)
@@ -1,566 +0,0 @@
-#
-# This file is part of GNU Enterprise.
-#
-# GNU Enterprise is free software; you can redistribute it
-# and/or modify it under the terms of the GNU General Public
-# License as published by the Free Software Foundation; either
-# version 2, or (at your option) any later version.
-#
-# GNU Enterprise is distributed in the hope that it will be
-# useful, but WITHOUT ANY WARRANTY; without even the implied
-# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
-# PURPOSE. See the GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public
-# License along with program; see the file COPYING. If not,
-# write to the Free Software Foundation, Inc., 59 Temple Place
-# - Suite 330, Boston, MA 02111-1307, USA.
-#
-# Copyright 2000-2004 Free Software Foundation
-#
-# FILE:
-# appserver/DBdriver.py
-#
-# DESCRIPTION:
-# Implementation of dbdriver for use with GNUe Application Server.
-#
-# NOTES:
-#
-# HISTORY:
-#
-
-VERSION="0.0.1"
-
-try:
- from gnue.common import GDebug,GDataObjects,GConditions,GComm
-except:
- from gnue.common.datasources import GDataObjects, GConditions
- from gnue.common.apps import GDebug
- from gnue.common.rpc import GComm
-
-import string
-import types
-import md5
-import sys
-import mx.DateTime, mx.DateTime.ISO
-
-class Appserver_Connector:
- def __init__(self, connectData):
-
- user = connectData['_username']
- passwd = connectData['_password']
-
- params = { 'host': connectData['host'],
- 'port': connectData['port'],
- 'transport': connectData['transport']}
-
- self._server = GComm.attach(connectData['rpctype'],params)
-
- GDebug.printMesg(3,"Setup the link to the session manager")
- self._sm = self._server.request("Session")
-
- if connectData.has_key('encoding'):
- GDebug.printMesg(1,"Appserver's dbdriver doesn't 'encoding' parameter,
as the transport"+\
- " encoding has to be 'utf-8'.")
-
- #GDebug.printMesg(3,"Get the status of the session manager")
- #GDebug.printMesg(3,"Status: "+sessionManager.Status())
-
- try:
- GDebug.printMesg(3,"Open Session ...")
- GDebug.printMesg(1,"Logging into appserver as user '%s'" % (user))
- self._sess_id = self._sm.open({'user':user,'password':passwd})
- except Exception,msg:
- tmsg = _("Error loging into appserver: %s") % msg
- raise GDataObjects.ConnectionError, tmsg
-
- if self._sess_id == 0:
- tmsg = _("Error loging into appserver")
- raise GDataObjects.ConnectionError, tmsg
-
- self._updateCursor = Appserver_UpdateCursor(self)
-
- def cursor(self):
- return self._updateCursor
-
- def request(self,table,filter,sort,fieldlist,unicodeMode=0):
- listid = self._sm.request(self._sess_id,table,filter,sort,fieldlist)
- return Appserver_ListCursor(self,listid,table,fieldlist,unicodeMode)
-
- def call(self,classname,obj_id_list,methodname,parameters):
- self._sm.call(self._sess_id,classname,obj_id_list,methodname,parameters)
-
- def commit(self,classname):
- self._updateCursor.execute(classname)
- self._sm.commit(self._sess_id)
-
- def rollback(self,classname):
- self._updateCursor.revert(classname)
- self._sm.rollback(self._sess_id)
-
- def close(self,commit):
- self._sm.close(self._sess_id,commit)
-
-class Appserver_ListCursor:
- def __init__(self,dataCon,listid,classname,fieldlist,unicodeMode=0):
- self._dataCon=dataCon
- self._listid=listid
- self._fieldlist=fieldlist
- self._stackpos=0
- self._unicodeMode=unicodeMode
- self._fieldtypes = self._dataCon._sm.load (self._dataCon._sess_id,
- classname, [''],
self._fieldlist)
- self._fieldtypes = self._fieldtypes [0]
-
- # convert a value retrieved from RPC to the correct native Python type
- def __rpc_to_native (self, value, type):
-
- # Empty strings indicate None
- if value == '':
- return None
-
- # String: convert to unicode or local encoding
- elif type [:7] == 'string(':
- value = unicode (value, 'utf-8')
- if self._unicodeMode:
- return value
- else:
- return value.encode (gConfig ('textEncoding'))
-
- # Date: convert to mx.DateTime object
- elif type == 'date':
- return mx.DateTime.ISO.ParseDate (value)
-
- # Time: convert to mx.DateTime object
- elif type == 'time':
- return mx.DateTime.ISO.ParseTime (value)
-
- # DateTime: convert to mx.DateTime object
- elif type == 'datetime':
- return mx.DateTime.ISO.ParseDateTime (value)
-
- # All others (id, number, boolean, reference): no need to convert
- else:
- return value
-
- def fetch(self,count=5):
- if self._stackpos == -1:
- return []
-
- result = self._dataCon._sm.fetch(self._dataCon._sess_id,
- self._listid,self._stackpos,count)
- if len(result)<count:
- self._stackpos=-1
-
- else:
- self._stackpos=self._stackpos+len(result)
-
- list = []
- for i in result:
- dict = {}
- j = 0
- for fieldName in self._fieldlist:
- dict [fieldName] = self.__rpc_to_native (i [j+1], self._fieldtypes [j])
- j += 1
-
- dict["gnue_id"]=i[0]
- list.append(dict)
- return list
-
- def count(self):
- if not hasattr(self,"_count"):
- self._count =
self._dataCon._sm.count(self._dataCon._sess_id,self._listid)
-
- return self._count
-
- def close(self):
- pass
- # TODO: Implement List Close command
-
-class Appserver_UpdateCursor:
- def __init__(self,dataCon,unicodeMode=0):
- self._dataCon=dataCon
- self._deleteList={}
- self._updateList={}
- self._updateKeyList={}
- self._unicodeMode=unicodeMode
-
- def delete(self,classname,id):
- if not self._deleteList.has_key(classname):
- self._deleteList[classname]=[]
-
- self._deleteList[classname].append(id)
-
- def update(self, classname, id, fieldDict):
- if not self._updateList.has_key(classname):
- self._updateList[classname]=[]
- self._updateKeyList[classname]=[]
-
- self._updateList[classname].append(fieldDict)
- self._updateKeyList[classname].append(id)
-
- # convert a native Python type into something transportable by RPC
- def __native_to_rpc (self, s):
- if type (s) == types.StringType:
- if self._unicodeMode:
- msg = 'WARNING: non-unicode passed to the dbdriver (%s)' % value
- GDebug.printMesg (0, msg)
- s = unicode (s, gConfig ('textEncoding'))
- if type (s) == types.UnicodeType:
- s = s.encode ('utf-8')
- elif type (s) == mx.DateTime.DateTimeType:
- s = s.date + ' ' + s.time
- elif s is None:
- s = ''
- return s
-
- def execute (self, classname):
- if self._deleteList.has_key (classname):
- self._dataCon._sm.delete (self._dataCon._sess_id, classname,
- self._deleteList [classname])
- del self._deleteList [classname]
-
- if self._updateList.has_key (classname):
- while len (self._updateList [classname]):
- id = self._updateKeyList[classname].pop()
- dict = self._updateList[classname].pop()
- # TODO: merge calls with similar updated fields (=dict.values())
- data = [self.__native_to_rpc (x) for x in dict.values ()]
- new_ids = self._dataCon._sm.store (self._dataCon._sess_id, classname,
- [id], dict.keys(), [data])
- dict ["gnue_id"] = new_ids [0]
- del self._updateList [classname]
- del self._updateKeyList [classname]
-
- def revert (self, classname):
- if self._deleteList.has_key (classname):
- del self._deleteList [classname]
- if self._updateList.has_key (classname):
- del self._updateList [classname]
- del self._updateKeyList [classname]
-
-
-class Appserver_RecordSet(GDataObjects.RecordSet):
- def _postChanges(self):
- if self._deleteFlag:
- GDebug.printMesg(5, 'AppServer database driver: Instance deleted')
- self._parent._update_cursor.delete(self._parent._dataObject.table,
- self._fields["gnue_id"])
-
- if self._insertFlag:
- GDebug.printMesg(5, 'AppServer database driver: new Instance '+\
- 'created and inserted')
- ## Set __id__ to "0" for new instances
- self._parent._update_cursor.update(self._parent._dataObject.table,
- 0, self._fields)
-
- elif self._updateFlag:
- modifiedFields={}
- for field in (self._modifiedFlags.keys()):
- modifiedFields[field]=self._fields[field]
-
- self._parent._update_cursor.update(self._parent._dataObject.table,
- self._fields["gnue_id"],
modifiedFields)
-
- self._updateFlag = 0
- self._insertFlag = 0
- self._deleteFlag = 0
-
- # this function calls a per entry function on server side
- def callFunc(self,name,params):
- if self._insertFlag:
- # store record on server
- GDebug.printMesg(0, 'FIXME: record has to be stored on appserver '+\
- 'and its gnue_id should be returned')
- return
-
-
self._parent._dataObject._dataConnection.call(self._parent._dataObject.table,
- [self._fields["gnue_id"]],
- name,params)
-
-
-# Appserver_ResultSet
-#
-# Notes:
-# In the Appserver driver a CURSOR is simply the List handle returned
-# via the query interface
-#
-class Appserver_ResultSet(GDataObjects.ResultSet):
- def __init__(self, dataObject, cursor=None, \
- defaultValues={}, masterRecordSet=None):
- GDataObjects.ResultSet.__init__(
- self,dataObject,cursor,defaultValues,masterRecordSet)
- self._recordSetClass = Appserver_RecordSet
- GDebug.printMesg(5, 'ResultSet created')
-
- def _loadNextRecord(self):
-
- more = 0
- if self._cursor:
-
- # load next records into local cache
-
- instances=self._cursor.fetch()
- for i in instances:
-
- more = 1
-
- record=self._recordSetClass(parent=self,initialData=i)
-
- self._cachedRecords.append (record)
-
- self._recordCount=self._recordCount+1
-
- # if no record returned return a zero
- return more
-
-
-class Appserver_DataObject(GDataObjects.DataObject):
-
- def __init__(self):
- GDataObjects.DataObject.__init__(self)
-
- GDebug.printMesg (1,"AppServer database driver backend initializing")
- self._resultSetClass = Appserver_ResultSet
- self._DatabaseError = GComm.Error
-
- def connect(self, connectData={}):
- GDebug.printMesg(1,"AppServer database driver connecting...")
-
- self._dataConnection = Appserver_Connector(connectData)
-
- self.triggerExtensions = Appserver_TriggerExtensions(self._dataConnection)
-
- # We only need the basics -- username and password -- to log in
- def getLoginFields(self):
- return [['_username', 'User Name',0],['_password', 'Password',1]]
-
- def _buildQuery(self, conditions={},forDetail=None,additionalSQL=""):
- # Standardize incomming conditions as a GConditions structre
- if type(conditions) == types.DictType:
- cond = GConditions.buildConditionFromDict(conditions)
- else:
- cond = conditions
-
- # 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, sql=""):
-
- GDebug.printMesg (5,"Setting up list object ...");
-
- sort=[]
- filter=[]
-
- # the fieldnames seem to be stored in _fieldReferences
- fieldlist=self._fieldReferences.keys()
-
- GDebug.printMesg (5,"Using "+str(fieldlist)+" as fieldlist");
-
- if hasattr(self,"order_by"):
- GDebug.printMesg (5,"Sorting list by fields '"+self.order_by+"'");
- sort=string.splitfields(self.order_by,",")
-
- try:
- if conditions:
- GDebug.printMesg (5,"Setting Conditions ...");
- filter = self._buildQuery(conditions)
- except self._DatabaseError, err:
- raise GDataObjects.ConnectionError, err
-
- try:
- listcursor =
self._dataConnection.request(self.table,filter,sort,fieldlist,\
- self._unicodeMode)
- except Exception, msg:
- tmsg = _("Error during creation of object list \n\n --- %s ---)") % msg
- raise GDataObjects.ConnectionError, tmsg
-
- rs = self._resultSetClass(self, cursor=listcursor, masterRecordSet=None)
-
- if readOnly:
- rs._readonly = readOnly
-
- return rs
-
- def commit(self):
- GDebug.printMesg (5,"AppServer database driver: commit()")
-
- try:
- self._dataConnection.commit(self.table)
- except self._DatabaseError, value:
- raise GDataObjects.ConnectionError, value
-
- def rollback(self):
- GDebug.printMesg (5,"AppServer database driver: rollback()")
-
- try:
- self._dataConnection.rollback(self.table)
- except:
- tmsg = _("Error during Rollback")
- raise GDataObjects.ConnectionError, tmsg
-
- ####
- #
- # Introspection support (works through direct access on gnue_module,
gnue_class und gnue_property tables
- #
- # TODO: Move to Introspection Subdir
-
- def getSchemaTypes(self):
- return [('object',_('Business Object Class'),1)]
-
- #############
- #
- # get list of all business classes
- #
-
- def getSchemaList(self, type=None):
- if not(type in ('object',None)):
- return []
-
- try:
- listcursor =
self._dataConnection.request('gnue_class',[],['gnue_module'],['gnue_name','gnue_comment','gnue_module'])
- except Exception, msg:
- print "error %s" %msg
- GDebug.printMesg(1,_("Error creating introspection module list \n\n
--- %s ---)") % msg)
- return []
-
- list = []
- data = ['1']
- while len(data):
- data = listcursor.fetch()
- for classdef in data:
- print classdef
- schema =
GDataObjects.Schema(attrs={'id':string.lower(classdef['gnue_name']),
- 'name':classdef['gnue_name'],
- 'type':'object',
- 'gnue_id':classdef['gnue_id']},
- getChildSchema=self.__getChildSchema)
- list.append(schema)
-
-
- listcursor.close()
-
- return list
-
- #############
- #
- # get schema for one single business class
- #
-
- def getSchemaByName(self, name, type=None):
- try:
- listcursor = self._dataConnection.request('gnue_class', [["eq", ""],
["field", "gnue_name"], ["const", name]],
-
['gnue_module'],['gnue_name','gnue_comment','gnue_module'])
- except Exception, msg:
- print "error %s" %msg
- GDebug.printMesg(1,_("Error fetching class %s \n\n --- %s ---)") %
(name,msg))
- return []
-
- data = listcursor.fetch()
- if len(data):
- classdef = data[0]
- print classdef
- schema =
GDataObjects.Schema(attrs={'id':string.lower(classdef['gnue_name']),
- 'name':classdef['gnue_name'],
- 'type':'object',
- 'gnue_id':classdef['gnue_id']},
- getChildSchema=self.__getChildSchema)
- listcursor.close()
-
- return schema
-
- #############
- #
- # get schema for one single business class
- #
-
- def __getChildSchema(self, parent):
- try:
- # fetch all properties used by class "parent"
- listcursor = self._dataConnection.request('gnue_property', # class
- [["eq", ""], ["field",
"gnue_class"],
- ["const",
parent.gnue_id]], # condition
- ['gnue_module'], # sort
-
['gnue_name','gnue_comment','gnue_module','gnue_class','gnue_type',
-
'gnue_length','gnue_scale'])
-
- except Exception, msg:
- print "error %s" %msg
- GDebug.printMesg(1,_("Error while loading class properties for class
%s \n\n --- %s ---)") % (parent.name,msg))
- return []
-
- list = []
- data = ['1']
- while len(data):
- data = listcursor.fetch()
- for propdef in data:
- print propdef
- attrs={'id': "%s.%s" % (parent.id,
string.lower(propdef['gnue_name'])),
- 'name': propdef['gnue_name'],
- 'precision': propdef['gnue_scale'], # TODO: check if scale
and precision is the same
- 'datatype':propdef['gnue_type'],
- 'nativetype': 'unknown',
- 'required': 0 } # TODO: classrep has no
'required' field
-
- # TODO: make classrep types a bit more straigtforward
- if propdef['gnue_type'] =='id' or propdef['gnue_type']
=='gnue_module' \
- or propdef['gnue_type'] =='gnue_class':
- attrs['length'] = 32
- else:
- attrs['length'] = propdef['gnue_length']
-
- list.append(GDataObjects.Schema(attrs=attrs))
-
- listcursor.close()
-
- return list
-
- def getFields(self, name):
- # no introspection support for now
- return self._fieldReferences.keys()
-
-supportedDataObjects = {
- 'object': Appserver_DataObject
-}
-
-
-#
-# Extensions to Trigger Namespaces
-#
-class Appserver_TriggerExtensions:
-
- def __init__(self, dataConnection):
- self._dataCon = dataConnection
-
- # Return a sequence number from sequence 'name'
- # def getSequence(self, name):
- # !!! has to be emulated !!!
- # return self.__singleQuery("select nextval('%s')" % name)
-
- # Run the SQL statement 'statement'
- #def sql(self, statement):
- # !!! has to be emulated !!!
- # cursor = self.__connection.cursor()
- # try:
- # cursor.execute(statement)
- # cursor.close()
- # except:
- # cursor.close()
- # raise
-
-
[Prev in Thread] |
Current Thread |
[Next in Thread] |
- r5083 - trunk/gnue-common/src/datasources/drivers/appserver/appserver,
jan <=