|
From: <de...@us...> - 2003-12-18 00:36:30
|
Update of /cvsroot/pymerase/pymerase/pymerase/output/dbAPI
In directory sc8-pr-cvs1:/tmp/cvs-serv25609
Modified Files:
init.pyt
Log Message:
Moved as much as possible out of init.pyt. This allows outgenerating it completely in CreateDBAPI instead of using the string substitution template.
Index: init.pyt
===================================================================
RCS file: /cvsroot/pymerase/pymerase/pymerase/output/dbAPI/init.pyt,v
retrieving revision 1.2
retrieving revision 1.3
diff -C2 -d -r1.2 -r1.3
*** init.pyt 4 Dec 2003 03:16:03 -0000 1.2
--- init.pyt 18 Dec 2003 00:36:27 -0000 1.3
***************
*** 8,264 ****
import pgdb as db_api
! %%IMPORT_MODULES%%
!
!
! def moduleReload():
! """Reload all support modules
!
! This is needed if you want to reimport an API after regenerating it
! within the same python session.
! """
! # if we're being reinitialized reload all of our modules
! modules = %%MODULES_LIST%%
! for module in modules:
! if sys.modules.has_key(module.__name__):
! #print "reloading module %s" % (module.__name__)
! reload(module)
!
! class Functor:
! def __init__(self, function, *args, **kargs):
! assert callable(function), "function should be a callable obj"
! self._function = function
! self._args = args
! self._kargs = kargs
!
! def __call__(self, *args, **kargs):
! """call function"""
! _args = list(self._args)
! _args.extend(args)
! _kargs = self._kargs.copy()
! _kargs.update(kargs)
! return apply(self._function,_args,_kargs)
! class DBSession:
! """Manages creating and closing a database session.
! """
! default_dsn = "localhost"
! try:
! default_user = os.getlogin()
! except:
! default_user = None
! default_database = None
! default_password=None
!
def __init__(self, dsn=None, database=None, user=None, password=None):
- if dsn is None:
- self.dsn = os.environ.get('DBHOST', DBSession.default_dsn)
- else:
- self.dsn = dsn
- if database is None:
- self.database = os.environ.get('DBDATABASE', DBSession.default_database)
- else:
- self.database = database
- if user is None:
- self.user = os.environ.get('DBUSER', DBSession.default_user)
- else:
- self.user = user
- if password is None:
- self.password = os.environ.get('DBPASSWORD', DBSession.default_password)
- else:
- self.password = password
-
- # object pointing to the low level database api
- self.db = None
-
- # class references is used to lookup the table class variable information
- # in getObjects and getAllObjects
- self.class_references = {}
-
classes_to_load = %%CLASSES_LIST%%
-
- self.__loadClasses(classes_to_load)
self.connect()
- def __del__(self):
- if self.db is not None:
- self.db.close()
-
- #############################
- # Database session management
- def connect(self):
- if self.db is None:
- self.db = db_api.connect(dsn=self.dsn,
- user=self.user,
- database=self.database,
- password=self.password)
-
- def cursor(self):
- #if self.db is None:
- # self.connect()
- return self.db.cursor()
-
- def rollback(self):
- if self.db is not None:
- self.db.rollback()
-
- def commit(self):
- if self.db is not None:
- self.db.commit()
-
- def close(self):
- if self.db is not None:
- self.db.close()
-
- ############################
- # attribute access
- def __loadClasses(self, module_list):
- for className, classRef in module_list:
- # construct arguments for functor
- _args = [classRef]
- kargs = {'db_session': self}
-
- # create class factory application function
- functor = apply(Functor, _args, kargs)
-
- # store reference to class reference, so we can
- # get access to the class variables when doing
- # certain types of lookups. (Yes this seems icky)
- self.class_references[functor] = classRef
-
- # add constructor to our class object
- setattr(self, className, functor)
-
- return
- for m in module_list:
- self.__loadClass(m)
-
-
- def __getClassRef(self, class_functor):
- """Given a class or class factory reference return a class reference
- """
-
- if type(class_functor) == types.ClassType:
- class_ref = class_functor
- elif isinstance(class_functor, Functor):
- class_ref = self.class_references[class_functor]
- else:
- raise ValueError("unrecognized class type")
-
- return class_ref
-
- def getObjects(self, class_functor, keys):
- """Returns a list of objects from a list of primary keys.
- """
- if keys is None or len(keys) == 0:
- # FIXME: Should this raise an error instead?
- return None
-
- class_ref = self.__getClassRef(class_functor)
- class_inst = class_ref()
-
- sql = "SELECT * FROM \"%s\" where \"%s\" in (" % (
- class_ref.table_name,
- class_inst.getPrimaryKeyName())
- sql += keys[0]
- for k in keys[1:]:
- sql += ", %s" % (k)
- sql += ")"
-
- return self.loadRecords(class_ref, sql)
-
- def getAllObjects(self, class_functor):
- """Return all records of type class_ref as a list.
- """
- class_ref = self.__getClassRef(class_functor)
-
- sql = "SELECT * FROM \"%s\"" % (class_ref.table_name)
- return self.loadRecords(class_ref, sql)
-
- def getObjectsWhere(self, class_functor, where_clause):
- """Returns all records of type class ref that matches the sql where expr.
- """
- class_ref = self.__getClassRef(class_functor)
-
- sql = "SELECT * FROM \"%s\" where %s" % (class_ref.table_name, where_clause)
- return self.loadRecords(class_ref, sql)
-
- def getObjectCount(self, class_functor):
- """
- Returns the number of objects which exist for a given class
- """
- class_ref = self.__getClassRef(class_functor)
-
- sql = "SELECT count(*) FROM \"%s\"" % (class_ref.table_name)
-
- try:
- cursor = self.db.cursor()
- try:
- cursor.execute(sql)
- record = cursor.fetchone()
- finally:
- cursor.close()
- except Exception, e:
- # pgdb isn't too informative about exception
- sys.stderr.write(str(e))
- sys.stderr.write(os.linesep)
-
- return record.pop()
-
- def getObjectCountWhere(self, class_functor, where_clause):
- """
- Returns the number of objects which exist for a given class,
- given a where clause.
- """
- class_ref = self.__getClassRef(class_functor)
-
- sql = "SELECT count(*) FROM \"%s\" where %s" % (class_ref.table_name,
- where_clause)
-
- try:
- cursor = self.db.cursor()
- try:
- cursor.execute(sql)
- record = cursor.fetchone()
- finally:
- cursor.close()
- except Exception, e:
- # pgdb isn't too informative about exception
- sys.stderr.write(str(e))
- sys.stderr.write(os.linesep)
-
- return record.pop()
-
- def loadRecords(self, class_ref, sql):
- """Returns a list of objects selected by an sql statement.
-
- Given a class_reference and an sql statement for each record returned
- bind the values to an object instantiated from the class_ref.
- """
- objects = []
- try:
- cursor = self.db.cursor()
- try:
- cursor.execute(sql)
-
- record = cursor.fetchone()
- while record is not None:
- o = class_ref(db_session=self)
- # tag this object as having been loaded from the database
- o.loaded = 1
- o.bindFields(cursor.description, record)
- objects.append(o)
- record = cursor.fetchone()
- finally:
- cursor.close()
- except Exception, e:
- # pgdb isn't too informative about exception
- sys.stderr.write(str(e))
- sys.stderr.write(os.linesep)
- self.rollback()
- else:
- self.commit()
-
- return objects
--- 8,24 ----
import pgdb as db_api
! from dbAPI import Functor
! from dbAPI import reloadModuleList
! %%IMPORT_MODULES%%
! moduleReload = Functor(reloadModuleList, (%%MODULES_LIST%%))
! class DBSession(DBSessionImpl):
def __init__(self, dsn=None, database=None, user=None, password=None):
classes_to_load = %%CLASSES_LIST%%
+ DBSessionImpl.__init__(self, dsn, database, user, password)
+ self.loadClasses(classes_to_load)
self.connect()
|