[DB-SIG] column type casting

Dittmar, Daniel daniel.dittmar@sap.com
Fri, 23 Mar 2001 14:49:53 +0100


> What's the API like for your datahandlers?  Are they written 
> in C or Python?  Should we collect a couple examples and present them
> in the PEP?

The datahandler are Callable Objects (they are supposed to be written by the
application programmer)

I supply example handler for the conversion of SAP DB date values to more
pythonic values

# returns a tuple (year, month, day)
def dateTuple (sapdbDate):
    if sapdbDate is None:
        return None
    return int (sapdbDate[:4]), int (sapdbDate[4:6]), int (sapdbDate[6:])

# returns a float as used by the time module
def dateVal (sapdbDate):
    if sapdbDate is None:
        return None
    year, month, day = dateTuple (sapdbDate)
    return time.mktime (year, month, day, -1, -1, -1, -1, -1, -1,)

# allows to translate using strftime format strings
class AbstractTimeFormat:
    def __init__ (self, fmt):
        self.fmt = fmt

    def __call__ (self, sapdbString):
        if sapdbString is None:
            return None
        localtime = time.localtime ( self.toTime(sapdbString))
        return time.strftime (self.fmt, localtime)

class DateFormat (AbstractTimeFormat):
    def toTime (self, sapdbDate):
        return dateVal (sapdbDate)


The handlers can be installed in several ways:

- specific to a cursor: cursor.setTranslation ([None, dateTuple, DateFormat
('%Y')])
the parameter array has one handler per output column, Nones are ignored

- specific to types: cursor.setTypeTranslation ({'Date': dateTuple, 'Time':
timeTuple})
this will install the handler for each column with a specific type (I'm
using SAP DB specific type keys, as I need to distinguish between Date, Time
and Timestamp)

- you can call connection.setTypeTranslation, this will install the handler
for every newly created cursor.

There are ready made dictionaries
tupleTranslation = {
    'Date': dateTuple,
    'Time': timeTuple,
    'Timestamp': timestampTuple,
}
so someone could simply write connection.setTypeTranslation
(sapdbapi.tupleTranslation) and forget afterwards about date/time
conversions.

Daniel

--
Daniel Dittmar
daniel.dittmar@sap.com
SAP DB, SAP Labs Berlin
http://www.sapdb.org/