[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[gnue] r7785 - trunk/gnue-common/src/datasources/drivers/DBSIG2
From: |
reinhard |
Subject: |
[gnue] r7785 - trunk/gnue-common/src/datasources/drivers/DBSIG2 |
Date: |
Fri, 5 Aug 2005 05:02:55 -0500 (CDT) |
Author: reinhard
Date: 2005-08-05 05:02:54 -0500 (Fri, 05 Aug 2005)
New Revision: 7785
Modified:
trunk/gnue-common/src/datasources/drivers/DBSIG2/Connection.py
Log:
Cleanup, docstrings, comments.
Modified: trunk/gnue-common/src/datasources/drivers/DBSIG2/Connection.py
===================================================================
--- trunk/gnue-common/src/datasources/drivers/DBSIG2/Connection.py
2005-08-04 18:35:28 UTC (rev 7784)
+++ trunk/gnue-common/src/datasources/drivers/DBSIG2/Connection.py
2005-08-05 10:02:54 UTC (rev 7785)
@@ -21,6 +21,10 @@
#
# $Id$
+"""
+Generic Connection class for DBSIG2 based database driver plugins.
+"""
+
__all__ = ['Connection']
import sys
@@ -85,11 +89,7 @@
Base.Connection.__init__ (self, connections, name, parameters)
- try:
- self._driver = __import__ (self._drivername_, None, None, '*')
- except ImportError:
- raise Exceptions.ConnectError, u_(
- "The '%s' python module is not installed.") % self._drivername_
+ self._driver = __import__ (self._drivername_, None, None, '*')
# Encoding used to communicate with the database (not used by all drivers)
if parameters.has_key ('encoding'):
@@ -101,10 +101,285 @@
# ---------------------------------------------------------------------------
+ # Implementations of virtual methods
+ # ---------------------------------------------------------------------------
+
+ def _getLoginFields_ (self):
+ return [(u_('User Name'), '_username', 'string', None, None, []),
+ (u_('Password'), '_password', 'password', None, None, [])]
+
+ # ---------------------------------------------------------------------------
+
+ def _connect_ (self, connectData):
+ (params, kwargs) = self._getConnectParams_ (connectData)
+ gDebug (3, 'DBSIG2 Connect')
+ try:
+ self._native = self._driver.connect (*params, **kwargs)
+ except self._driver.DatabaseError:
+ raise Exceptions.LoginError, errors.getException () [2]
+
+ # ---------------------------------------------------------------------------
+
+ def _insert_ (self, table, newfields):
+ fields = []
+ values = []
+ parameters = {}
+ for (field, value) in newfields.items ():
+ key = 'new_' + field
+ fields.append (field)
+ values.append ('%%(%s)s' % key)
+ parameters [key] = value
+ statement = "INSERT INTO %s (%s) VALUES (%s)" % (table, ', '.join (fields),
+ ', '.join (values))
+ return self.__execute (statement, parameters)
+
+ # ---------------------------------------------------------------------------
+
+ def _update_ (self, table, oldfields, newfields):
+ (where, parameters) = self.__where (oldfields)
+ updates = []
+ for (field, value) in newfields.items ():
+ key = 'new_' + field
+ updates.append ("%s=%%(%s)s" % (field, key))
+ parameters [key] = value
+ statement = "UPDATE %s SET %s WHERE %s" % (table, ', '.join (updates),
+ where)
+ self.__execute (statement, parameters)
+
+ # ---------------------------------------------------------------------------
+
+ def _delete_ (self, table, oldfields):
+ (where, parameters) = self.__where (oldfields)
+ statement = 'DELETE FROM %s WHERE %s' % (table, where)
+ self.__execute (statement, parameters)
+
+ # ---------------------------------------------------------------------------
+
+ def _requery_ (self, table, oldfields, fields):
+ (where, parameters) = self.__where (oldfields)
+ statement = "SELECT %s FROM %s WHERE %s" % (', '.join (fields), table,
+ where)
+ try:
+ rows = self.sql (statement, parameters)
+ except self._driver.DatabaseError:
+ raise Exceptions.ConnectionError, errors.getException () [2]
+ if len (rows):
+ row = rows [0]
+ result = {}
+ for i in range (len (fields)):
+ if isinstance (row [i], str):
+ result [fields [i]] = unicode (row [i], self._encoding)
+ else:
+ result [fields [i]] = row [i]
+ return result
+ else:
+ raise Exceptions.RecordNotFoundError
+
+ # ---------------------------------------------------------------------------
+
+ def _commit_ (self):
+ gDebug (3, 'DBSIG2 Commit')
+ try:
+ self._native.commit ()
+ except self._driver.DatabaseError:
+ raise Exceptions.ConnectionError, errors.getException () [2]
+
+ # ---------------------------------------------------------------------------
+
+ def _rollback_ (self):
+ gDebug (3, 'DBSIG2 Rollback')
+ if hasattr (self._native, 'rollback'):
+ self._native.rollback ()
+
+ # ---------------------------------------------------------------------------
+
+ def _close_ (self):
+ gDebug (3, 'DBSIG2 Close')
+ if self._native:
+ self._native.close ()
+
+
+ # ---------------------------------------------------------------------------
+ # Build WHERE-Clause based on a dictionary of fieldname/value pairs
+ # ---------------------------------------------------------------------------
+
+ def __where (self, oldfields):
+
+ where = []
+ parameters = {}
+ for (field, value) in oldfields.items ():
+ if value is None:
+ where.append ("%s IS NULL" % field)
+ else:
+ key = 'old_' + field
+ where.append ("%s=%%(%s)s" % (field, key))
+ parameters [key] = value
+
+ return (' AND '.join (where), parameters)
+
+
+ # ---------------------------------------------------------------------------
+ # Execute an insert, update, or delete statement
+ # ---------------------------------------------------------------------------
+
+ def __execute (self, statement, parameters):
+
+ try:
+ return self.sql0 (statement, parameters)
+ except self._driver.DatabaseError:
+ raise Exceptions.ConnectionError, errors.getException () [2]
+
+
+ # ---------------------------------------------------------------------------
+ # Execute the given SQL statement and return the result matrix
+ # ---------------------------------------------------------------------------
+
+ def sql (self, statement, parameters = None):
+ """
+ Execute the given SQL statement and return the result matrix.
+
+ @param statement: The SQL statement as either 8-bit or unicode string. Can
+ contain %(name)s style placeholders for parameters.
+ @param parameters: A dictionary with the parameter values. The values of
+ the dictionary can be 8-bit strings, unicode strings, integer or floating
+ point numbers, booleans or mx.DateTime values.
+ @return: A 2-dimensional matrix holding the complete result of the query.
+ """
+
+ cursor = self.makecursor (statement, parameters)
+ try:
+ result = cursor.fetchall ()
+ finally:
+ cursor.close ()
+ return result
+
+
+ # ---------------------------------------------------------------------------
+ # Execute the given SQL statement that is expected to return a single value
+ # ---------------------------------------------------------------------------
+
+ def sql1 (self, statement, parameters = None):
+ """
+ Execute the given SQL statement that is expected to return a single value.
+
+ If the query returns nothing, None is returned.
+
+ @param statement: The SQL statement as either 8-bit or unicode string. Can
+ contain %(name)s style placeholders for parameters.
+ @param parameters: A dictionary with the parameter values. The values of
+ the dictionary can be 8-bit strings, unicode strings, integer or floating
+ point numbers, booleans or mx.DateTime values.
+ @return: The value returned by the query. If the query returns more than a
+ single value, the first column of the first row is returned.
+ """
+
+ cursor = self.makecursor (statement, parameters)
+ try:
+ result = cursor.fetchone ()
+ finally:
+ cursor.close ()
+ return result [0]
+
+
+ # ---------------------------------------------------------------------------
+ # Execute the given SQL statement that is expected to return nothing
+ # ---------------------------------------------------------------------------
+
+ def sql0 (self, statement, parameters = None):
+ """
+ Execute the given SQL statement and return the rowid of the affected row
+ (in case the statement was an insert).
+
+ @param statement: The SQL statement as either 8-bit or unicode string. Can
+ contain %(name)s style placeholders for parameters.
+ @param parameters: A dictionary with the parameter values. The values of
+ the dictionary can be 8-bit strings, unicode strings, integer or floating
+ point numbers, booleans or mx.DateTime values.
+ @return: For INSERT statements, the rowid of the newly inserted record, if
+ the database supports rowids and the DBSIG2 module supports the
+ cursor.lastrowid extension, and None otherwise. For other statements,
+ undefined.
+ """
+
+ cursor = self.makecursor (statement, parameters)
+ if hasattr (cursor, 'lastrowid'):
+ result = cursor.lastrowid
+ else:
+ result = None
+ cursor.close ()
+ return result
+
+
+ # ---------------------------------------------------------------------------
+ # Create a new DBSIG2 cursor object and execute the given SQL statement
+ # ---------------------------------------------------------------------------
+
+ def makecursor (self, statement, parameters = None):
+ """
+ Create a new DBSIG2 cursor object and execute the given SQL statement.
+
+ @param statement: The SQL statement as either 8-bit or unicode string. Can
+ contain %(name)s style placeholders for parameters.
+ @param parameters: A dictionary with the parameter values. The values of
+ the dictionary can be 8-bit strings, unicode strings, integer or floating
+ point numbers, booleans or mx.DateTime values.
+ @return: A DBSIG2 cursor object holding the result of the query.
+ """
+
+ checktype (statement, basestring)
+ checktype (parameters, [dict, None])
+
+ if parameters:
+ for (parameters_key, parameters_value) in parameters.items ():
+ checktype (parameters_key, basestring)
+ # checktype (parameters_value, .....) -- too many valid types :-)
+
+ # Convert to encoded string for database
+ if isinstance (statement, unicode):
+ s = statement.encode (self._encoding)
+ else:
+ s = statement
+
+ if parameters:
+ # convert parameter dictionary to encoded strings
+ p = {}
+ for (key, value) in parameters.items ():
+ if isinstance (key, unicode):
+ k = key.encode (self._encoding)
+ else:
+ k = key
+ p [k] = self.__makeparam (value)
+
+ # Convert parameters into correct style
+ paramstyle = self._driver.paramstyle
+ if paramstyle != 'pyformat':
+ (s, p) = getattr (self, '_Connection__param_' + paramstyle) (s, p)
+
+ else:
+ p = None
+
+ gDebug (3, "DBSIG2 Statement: %s" % s)
+ gDebug (3, "DBSIG2 Parameters: %s" % p)
+
+ # Create DBSIG2 cursor and execute statement
+ cursor = self._native.cursor ()
+ try:
+ if p is not None:
+ cursor.execute (s, p)
+ else:
+ cursor.execute (s)
+ except:
+ cursor.close ()
+ raise
+
+ return cursor
+
+
+ # ---------------------------------------------------------------------------
# Convert type into what the DBSIG2 driver wants as parameter
# ---------------------------------------------------------------------------
- def _makeparam (self, value):
+ def __makeparam (self, value):
"""
Convert any given value into the datatype that must be passed as parameter
to the DBSIG2 cursor.execute() function.
@@ -235,181 +510,9 @@
# ---------------------------------------------------------------------------
- # Create a new DBSIG2 cursor object and execute the given SQL statement
+ # Virtual methods to be implemented by descendants
# ---------------------------------------------------------------------------
- def makecursor (self, statement, parameters = None):
- """
- Create a new DBSIG2 cursor object and execute the given SQL statement.
-
- @param statement: The SQL statement as either 8-bit or unicode string. Can
- contain %(name)s style placeholders for parameters.
- @param parameters: A dictionary with the parameter values. The values of
- the dictionary can be 8-bit strings, unicode strings, integer or floating
- point numbers, booleans or mx.DateTime values.
- @return: A DBSIG2 cursor object holding the result of the query.
- """
- checktype (statement, basestring)
- checktype (parameters, [dict, None])
-
- if parameters:
- for (parameters_key, parameters_value) in parameters.items ():
- checktype (parameters_key, basestring)
- # checktype (parameters_value, .....) -- too many valid types :-)
-
- # Convert to encoded string for database
- if isinstance (statement, unicode):
- s = statement.encode (self._encoding)
- else:
- s = statement
-
- if parameters:
- # convert parameter dictionary to encoded strings
- p = {}
- for (key, value) in parameters.items ():
- if isinstance (key, unicode):
- k = key.encode (self._encoding)
- else:
- k = key
- p [k] = self._makeparam (value)
-
- # Convert parameters into correct style
- paramstyle = self._driver.paramstyle
- if paramstyle != 'pyformat':
- (s, p) = getattr (self, '_Connection__param_' + paramstyle) (s, p)
-
- else:
- p = None
-
- gDebug (3, "DBSIG2 Statement: %s" % s)
- gDebug (3, "DBSIG2 Parameters: %s" % p)
-
- # Create DBSIG2 cursor and execute statement
- cursor = self._native.cursor ()
- try:
- if p is not None:
- cursor.execute (s, p)
- else:
- cursor.execute (s)
- except:
- cursor.close ()
- raise
-
- return cursor
-
-
- # ---------------------------------------------------------------------------
- # Execute the given SQL statement and return the result matrix
- # ---------------------------------------------------------------------------
-
- def sql (self, statement, parameters = None):
- """
- Execute the given SQL statement and return the result matrix.
-
- @param statement: The SQL statement as either 8-bit or unicode string. Can
- contain %(name)s style placeholders for parameters.
- @param parameters: A dictionary with the parameter values. The values of
- the dictionary can be 8-bit strings, unicode strings, integer or floating
- point numbers, booleans or mx.DateTime values.
- @return: A 2-dimensional matrix holding the complete result of the query.
- """
- cursor = self.makecursor (statement, parameters)
- try:
- result = cursor.fetchall ()
- finally:
- cursor.close ()
- return result
-
-
- # ---------------------------------------------------------------------------
- # Execute the given SQL statement that is expected to return a single value
- # ---------------------------------------------------------------------------
-
- def sql1 (self, statement, parameters = None):
- """
- Execute the given SQL statement that is expected to return a single value.
-
- If the query returns nothing, None is returned.
-
- @param statement: The SQL statement as either 8-bit or unicode string. Can
- contain %(name)s style placeholders for parameters.
- @param parameters: A dictionary with the parameter values. The values of
- the dictionary can be 8-bit strings, unicode strings, integer or floating
- point numbers, booleans or mx.DateTime values.
- @return: The value returned by the query. If the query returns more than a
- single value, the first column of the first row is returned.
- """
- cursor = self.makecursor (statement, parameters)
- try:
- result = cursor.fetchone ()
- finally:
- cursor.close ()
- return result [0]
-
-
- # ---------------------------------------------------------------------------
- # Execute the given SQL statement that is expected to return nothing
- # ---------------------------------------------------------------------------
-
- def sql0 (self, statement, parameters = None):
- """
- Execute the given SQL statement and return the rowid of the affected row
- (in case the statement was an insert).
-
- @param statement: The SQL statement as either 8-bit or unicode string. Can
- contain %(name)s style placeholders for parameters.
- @param parameters: A dictionary with the parameter values. The values of
- the dictionary can be 8-bit strings, unicode strings, integer or floating
- point numbers, booleans or mx.DateTime values.
- @return: For INSERT statements, the rowid of the newly inserted record, if
- the database supports rowids and the DBSIG2 module supports the
- cursor.lastrowid extension, and None otherwise. For other statements,
- undefined.
- """
- cursor = self.makecursor (statement, parameters)
- if hasattr (cursor, 'lastrowid'):
- result = cursor.lastrowid
- else:
- result = None
- cursor.close ()
- return result
-
-
- # ---------------------------------------------------------------------------
- # Build WHERE-Clause based on a dictionary of fieldname/value pairs
- # ---------------------------------------------------------------------------
-
- def __where (self, oldfields):
-
- where = []
- parameters = {}
- for (field, value) in oldfields.items ():
- if value is None:
- where.append ("%s IS NULL" % field)
- else:
- key = 'old_' + field
- where.append ("%s=%%(%s)s" % (field, key))
- parameters [key] = value
-
- return (' AND '.join (where), parameters)
-
-
- # ---------------------------------------------------------------------------
- # Execute an insert, update, or delete statement
- # ---------------------------------------------------------------------------
-
- def __execute (self, statement, parameters):
-
- try:
- return self.sql0 (statement, parameters)
- except self._driver.DatabaseError:
- raise Exceptions.ConnectionError, errors.getException () [2]
-
-
- # ---------------------------------------------------------------------------
- # This method has to be overwritten by descendants
- # ---------------------------------------------------------------------------
-
def _getConnectParams_ (self, connectData):
"""
Return a tuple with a list and a dictionary, being the parameters and
@@ -420,15 +523,15 @@
"""
return ([], {})
-
# ---------------------------------------------------------------------------
- # Create an apropriate timestamp object for the given values
- # ---------------------------------------------------------------------------
def _createTimestamp_ (self, year, month, day, hour, minute, secs, msec = 0):
"""
Create a timestamp object for the given point in time.
+ This function doesn't have to be overwritten unless the handling of time
+ values is weird.
+
@param year: Year number
@param year: Month number (1 - 12)
@param day: Day of the month (1 - 31)
@@ -457,6 +560,9 @@
"""
Create a time object for the given point in time.
+ This function doesn't have to be overwritten unless the handling of time
+ values is weird.
+
@param hour: Hour (0 - 23)
@param minute: Minute (0 - 59)
@param secs: Whole seconds (integer)
@@ -472,102 +578,3 @@
else:
return self._driver.Time (hour, minute, psec)
-
-
- # ---------------------------------------------------------------------------
- # Implementations of virtual methods
- # ---------------------------------------------------------------------------
-
- def _getLoginFields_ (self):
- return [(u_('User Name'), '_username', 'string', None, None, []),
- (u_('Password'), '_password', 'password', None, None, [])]
-
- # ---------------------------------------------------------------------------
-
- def _connect_ (self, connectData):
- (params, kwargs) = self._getConnectParams_ (connectData)
- gDebug (3, 'DBSIG2 Connect')
- try:
- self._native = self._driver.connect (*params, **kwargs)
- except self._driver.DatabaseError:
- raise Exceptions.LoginError, errors.getException () [2]
-
- # ---------------------------------------------------------------------------
-
- def _insert_ (self, table, newfields):
- fields = []
- values = []
- parameters = {}
- for (field, value) in newfields.items ():
- key = 'new_' + field
- fields.append (field)
- values.append ('%%(%s)s' % key)
- parameters [key] = value
- statement = "INSERT INTO %s (%s) VALUES (%s)" % (table, ', '.join (fields),
- ', '.join (values))
- return self.__execute (statement, parameters)
-
- # ---------------------------------------------------------------------------
-
- def _update_ (self, table, oldfields, newfields):
- (where, parameters) = self.__where (oldfields)
- updates = []
- for (field, value) in newfields.items ():
- key = 'new_' + field
- updates.append ("%s=%%(%s)s" % (field, key))
- parameters [key] = value
- statement = "UPDATE %s SET %s WHERE %s" % (table, ', '.join (updates),
- where)
- self.__execute (statement, parameters)
-
- # ---------------------------------------------------------------------------
-
- def _delete_ (self, table, oldfields):
- (where, parameters) = self.__where (oldfields)
- statement = 'DELETE FROM %s WHERE %s' % (table, where)
- self.__execute (statement, parameters)
-
- # ---------------------------------------------------------------------------
-
- def _requery_ (self, table, oldfields, fields):
- (where, parameters) = self.__where (oldfields)
- statement = "SELECT %s FROM %s WHERE %s" % (', '.join (fields), table,
- where)
- try:
- rows = self.sql (statement, parameters)
- except self._driver.DatabaseError:
- raise Exceptions.ConnectionError, errors.getException () [2]
- if len (rows):
- row = rows [0]
- result = {}
- for i in range (len (fields)):
- if isinstance (row [i], str):
- result [fields [i]] = unicode (row [i], self._encoding)
- else:
- result [fields [i]] = row [i]
- return result
- else:
- raise Exceptions.RecordNotFoundError
-
- # ---------------------------------------------------------------------------
-
- def _commit_ (self):
- gDebug (3, 'DBSIG2 Commit')
- try:
- self._native.commit ()
- except self._driver.DatabaseError:
- raise Exceptions.ConnectionError, errors.getException () [2]
-
- # ---------------------------------------------------------------------------
-
- def _rollback_ (self):
- gDebug (3, 'DBSIG2 Rollback')
- if hasattr (self._native, 'rollback'):
- self._native.rollback ()
-
- # ---------------------------------------------------------------------------
-
- def _close_ (self):
- gDebug (3, 'DBSIG2 Close')
- if self._native:
- self._native.close ()
[Prev in Thread] |
Current Thread |
[Next in Thread] |
- [gnue] r7785 - trunk/gnue-common/src/datasources/drivers/DBSIG2,
reinhard <=