[DB-SIG] (Database Abstraction Layer) Wrapping DBAPI Exceptions

Peter L. Buschman plblists at iotk.com
Fri Sep 26 07:06:18 EDT 2003

Here's the next challenge in my ongoing quest to write a DBAPI 
2.0-compliant abstraction layer.... wrapping exceptions.

For this example, let's assume I am using mysqldb as the underlying driver.

class DriverBase(object):

     def __init__( self, paramstyle=None ):

         if paramstyle == None:
             self.paramstyle = 'qmark'                   # Default public 
             self.paramstyle = paramstyle

import MySQLdb as driver

class Driver(DriverBase):

     name = 'mysqldb'

     def __init__( self, paramstyle=None ):

         self._driver        = driver                    # Link to the 
underlying MySQLdb driver namespace
         super(Driver, self).__init__(paramstyle)

         self.version        = driver.__version__
         self._paramstyle    = driver.paramstyle # Underlying private 
         self.apilevel       = driver.apilevel
         self.threadsafety   = driver.threadsafety

The next thing I want to do is wrap the DPABI exceptions of the underlying 
driver and raise my own equivalents ( which will handle
exception arguments consistently... ) whenever they occur.  Here is the 
strategy that comes to mind, but I am wondering how the rest of you might
handle a case like this?

# First define our own DBAPI exeptions... this example is limited to only 
three for brevity.
import exceptions
class Error(exceptions.StandardError):
         # DAL-specific stuff

class DatabaseError(Error):
         # DAL-specific stuff

class InternalError(DatabaseError):
         # DAL-specific stuff

With the exceptions defined, I want to raise them whenever a wrapped method 
call raises an exception in the
underlying driver.  Here is how I might do this with the connect() function 
in the main driver ( this example returns
a Connection object from the underlying driver... the final implementation 
will wrap those objects as well. )

def connect( **kwargs ):
                 return driver.connect(**kwargs)
         except driver.Error, args:
                 raise Error, args
         except driver.DatabaseError, args:
                 raise DatabaseError, args
         except driver.InternalError, args:
                 raise InternalError, args

Is this type of brute-force exception checking around every wrapped method 
call necessary or am I missing a much simpler and elegant solution?

Thanks again for everyone's great feedback.

         Peter Buschman
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/db-sig/attachments/20030926/0de9bf5f/attachment-0001.html

More information about the DB-SIG mailing list