[prev in list] [next in list] [prev in thread] [next in thread]
List: python-db-sig
Subject: [DB-SIG] column type casting
From: daniel.dittmar () sap ! com (Dittmar, Daniel)
Date: 2001-03-23 13:49:53
Message-ID: B9A2DDA03044D311BBD40008C75D6968057C1BD3 () dbwdfx24 ! wdf ! sap-ag ! de
[Download RAW message or body]
> 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/
[prev in list] [next in list] [prev in thread] [next in thread]
Configure |
About |
News |
Add a list |
Sponsored by KoreLogic