apibase.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  1. """adodbapi.apibase - A python DB API 2.0 (PEP 249) interface to Microsoft ADO
  2. Copyright (C) 2002 Henrik Ekelund, version 2.1 by Vernon Cole
  3. * http://sourceforge.net/projects/pywin32
  4. * http://sourceforge.net/projects/adodbapi
  5. """
  6. import sys
  7. import time
  8. import datetime
  9. import decimal
  10. import numbers
  11. # noinspection PyUnresolvedReferences
  12. from . import ado_consts as adc
  13. verbose = False # debugging flag
  14. onIronPython = sys.platform == 'cli'
  15. if onIronPython: # we need type definitions for odd data we may need to convert
  16. # noinspection PyUnresolvedReferences
  17. from System import DBNull, DateTime
  18. NullTypes = (type(None), DBNull)
  19. else:
  20. DateTime = type(NotImplemented) # should never be seen on win32
  21. NullTypes = type(None)
  22. # --- define objects to smooth out Python3 <-> Python 2.x differences
  23. unicodeType = str
  24. longType = int
  25. StringTypes = str
  26. makeByteBuffer = bytes
  27. memoryViewType = memoryview
  28. _BaseException = Exception
  29. try: #jdhardy -- handle bytes under IronPython & Py3
  30. bytes
  31. except NameError:
  32. bytes = str # define it for old Pythons
  33. # ------- Error handlers ------
  34. def standardErrorHandler(connection, cursor, errorclass, errorvalue):
  35. err = (errorclass, errorvalue)
  36. try:
  37. connection.messages.append(err)
  38. except: pass
  39. if cursor is not None:
  40. try:
  41. cursor.messages.append(err)
  42. except: pass
  43. raise errorclass(errorvalue)
  44. # Note: _BaseException is defined differently between Python 2.x and 3.x
  45. class Error(_BaseException):
  46. pass #Exception that is the base class of all other error
  47. #exceptions. You can use this to catch all errors with one
  48. #single 'except' statement. Warnings are not considered
  49. #errors and thus should not use this class as base. It must
  50. #be a subclass of the Python StandardError (defined in the
  51. #module exceptions).
  52. class Warning(_BaseException):
  53. pass
  54. class InterfaceError(Error):
  55. pass
  56. class DatabaseError(Error):
  57. pass
  58. class InternalError(DatabaseError):
  59. pass
  60. class OperationalError(DatabaseError):
  61. pass
  62. class ProgrammingError(DatabaseError):
  63. pass
  64. class IntegrityError(DatabaseError):
  65. pass
  66. class DataError(DatabaseError):
  67. pass
  68. class NotSupportedError(DatabaseError):
  69. pass
  70. class FetchFailedError(OperationalError):
  71. """
  72. Error is used by RawStoredProcedureQuerySet to determine when a fetch
  73. failed due to a connection being closed or there is no record set
  74. returned. (Non-standard, added especially for django)
  75. """
  76. pass
  77. # # # # # ----- Type Objects and Constructors ----- # # # # #
  78. #Many databases need to have the input in a particular format for binding to an operation's input parameters.
  79. #For example, if an input is destined for a DATE column, then it must be bound to the database in a particular
  80. #string format. Similar problems exist for "Row ID" columns or large binary items (e.g. blobs or RAW columns).
  81. #This presents problems for Python since the parameters to the executeXXX() method are untyped.
  82. #When the database module sees a Python string object, it doesn't know if it should be bound as a simple CHAR
  83. #column, as a raw BINARY item, or as a DATE.
  84. #
  85. #To overcome this problem, a module must provide the constructors defined below to create objects that can
  86. #hold special values. When passed to the cursor methods, the module can then detect the proper type of
  87. #the input parameter and bind it accordingly.
  88. #A Cursor Object's description attribute returns information about each of the result columns of a query.
  89. #The type_code must compare equal to one of Type Objects defined below. Type Objects may be equal to more than
  90. #one type code (e.g. DATETIME could be equal to the type codes for date, time and timestamp columns;
  91. #see the Implementation Hints below for details).
  92. #SQL NULL values are represented by the Python None singleton on input and output.
  93. #Note: Usage of Unix ticks for database interfacing can cause troubles because of the limited date range they cover.
  94. # def Date(year,month,day):
  95. # "This function constructs an object holding a date value. "
  96. # return dateconverter.date(year,month,day) #dateconverter.Date(year,month,day)
  97. #
  98. # def Time(hour,minute,second):
  99. # "This function constructs an object holding a time value. "
  100. # return dateconverter.time(hour, minute, second) # dateconverter.Time(hour,minute,second)
  101. #
  102. # def Timestamp(year,month,day,hour,minute,second):
  103. # "This function constructs an object holding a time stamp value. "
  104. # return dateconverter.datetime(year,month,day,hour,minute,second)
  105. #
  106. # def DateFromTicks(ticks):
  107. # """This function constructs an object holding a date value from the given ticks value
  108. # (number of seconds since the epoch; see the documentation of the standard Python time module for details). """
  109. # return Date(*time.gmtime(ticks)[:3])
  110. #
  111. # def TimeFromTicks(ticks):
  112. # """This function constructs an object holding a time value from the given ticks value
  113. # (number of seconds since the epoch; see the documentation of the standard Python time module for details). """
  114. # return Time(*time.gmtime(ticks)[3:6])
  115. #
  116. # def TimestampFromTicks(ticks):
  117. # """This function constructs an object holding a time stamp value from the given
  118. # ticks value (number of seconds since the epoch;
  119. # see the documentation of the standard Python time module for details). """
  120. # return Timestamp(*time.gmtime(ticks)[:6])
  121. #
  122. # def Binary(aString):
  123. # """This function constructs an object capable of holding a binary (long) string value. """
  124. # b = makeByteBuffer(aString)
  125. # return b
  126. # ----- Time converters ----------------------------------------------
  127. class TimeConverter(object): # this is a generic time converter skeleton
  128. def __init__(self): # the details will be filled in by instances
  129. self._ordinal_1899_12_31=datetime.date(1899,12,31).toordinal()-1
  130. # Use cls.types to compare if an input parameter is a datetime
  131. self.types = {type(self.Date(2000,1,1)),
  132. type(self.Time(12,1,1)),
  133. type(self.Timestamp(2000,1,1,12,1,1)),
  134. datetime.datetime,
  135. datetime.time,
  136. datetime.date}
  137. def COMDate(self,obj):
  138. '''Returns a ComDate from a date-time'''
  139. try: # most likely a datetime
  140. tt=obj.timetuple()
  141. try:
  142. ms=obj.microsecond
  143. except:
  144. ms=0
  145. return self.ComDateFromTuple(tt, ms)
  146. except: # might be a tuple
  147. try:
  148. return self.ComDateFromTuple(obj)
  149. except: # try an mxdate
  150. try:
  151. return obj.COMDate()
  152. except:
  153. raise ValueError('Cannot convert "%s" to COMdate.' % repr(obj))
  154. def ComDateFromTuple(self, t, microseconds=0):
  155. d = datetime.date(t[0],t[1],t[2])
  156. integerPart = d.toordinal() - self._ordinal_1899_12_31
  157. ms = (t[3]*3600 + t[4]*60 + t[5]) * 1000000 + microseconds
  158. fractPart = float(ms) / 86400000000.0
  159. return integerPart + fractPart
  160. def DateObjectFromCOMDate(self,comDate):
  161. 'Returns an object of the wanted type from a ComDate'
  162. raise NotImplementedError #"Abstract class"
  163. def Date(self,year,month,day):
  164. "This function constructs an object holding a date value. "
  165. raise NotImplementedError #"Abstract class"
  166. def Time(self,hour,minute,second):
  167. "This function constructs an object holding a time value. "
  168. raise NotImplementedError #"Abstract class"
  169. def Timestamp(self,year,month,day,hour,minute,second):
  170. "This function constructs an object holding a time stamp value. "
  171. raise NotImplementedError #"Abstract class"
  172. # all purpose date to ISO format converter
  173. def DateObjectToIsoFormatString(self, obj):
  174. "This function should return a string in the format 'YYYY-MM-dd HH:MM:SS:ms' (ms optional) "
  175. try: # most likely, a datetime.datetime
  176. s = obj.isoformat(' ')
  177. except (TypeError, AttributeError):
  178. if isinstance(obj, datetime.date):
  179. s = obj.isoformat() + ' 00:00:00' # return exact midnight
  180. else:
  181. try: # maybe it has a strftime method, like mx
  182. s = obj.strftime('%Y-%m-%d %H:%M:%S')
  183. except AttributeError:
  184. try: #but may be time.struct_time
  185. s = time.strftime('%Y-%m-%d %H:%M:%S', obj)
  186. except:
  187. raise ValueError('Cannot convert "%s" to isoformat' % repr(obj))
  188. return s
  189. # -- Optional: if mx extensions are installed you may use mxDateTime ----
  190. try:
  191. import mx.DateTime
  192. mxDateTime = True
  193. except:
  194. mxDateTime = False
  195. if mxDateTime:
  196. class mxDateTimeConverter(TimeConverter): # used optionally if installed
  197. def __init__(self):
  198. TimeConverter.__init__(self)
  199. self.types.add(type(mx.DateTime))
  200. def DateObjectFromCOMDate(self,comDate):
  201. return mx.DateTime.DateTimeFromCOMDate(comDate)
  202. def Date(self,year,month,day):
  203. return mx.DateTime.Date(year,month,day)
  204. def Time(self,hour,minute,second):
  205. return mx.DateTime.Time(hour,minute,second)
  206. def Timestamp(self,year,month,day,hour,minute,second):
  207. return mx.DateTime.Timestamp(year,month,day,hour,minute,second)
  208. else:
  209. class mxDateTimeConverter(TimeConverter):
  210. pass # if no mx is installed
  211. class pythonDateTimeConverter(TimeConverter): # standard since Python 2.3
  212. def __init__(self):
  213. TimeConverter.__init__(self)
  214. def DateObjectFromCOMDate(self, comDate):
  215. if isinstance(comDate, datetime.datetime):
  216. odn = comDate.toordinal()
  217. tim = comDate.time()
  218. new = datetime.datetime.combine(datetime.datetime.fromordinal(odn), tim)
  219. return new
  220. # return comDate.replace(tzinfo=None) # make non aware
  221. elif isinstance(comDate, DateTime):
  222. fComDate = comDate.ToOADate() # ironPython clr Date/Time
  223. else:
  224. fComDate=float(comDate) #ComDate is number of days since 1899-12-31
  225. integerPart = int(fComDate)
  226. floatpart=fComDate-integerPart
  227. ##if floatpart == 0.0:
  228. ## return datetime.date.fromordinal(integerPart + self._ordinal_1899_12_31)
  229. dte=datetime.datetime.fromordinal(integerPart + self._ordinal_1899_12_31) \
  230. + datetime.timedelta(milliseconds=floatpart*86400000)
  231. # millisecondsperday=86400000 # 24*60*60*1000
  232. return dte
  233. def Date(self,year,month,day):
  234. return datetime.date(year,month,day)
  235. def Time(self,hour,minute,second):
  236. return datetime.time(hour,minute,second)
  237. def Timestamp(self,year,month,day,hour,minute,second):
  238. return datetime.datetime(year,month,day,hour,minute,second)
  239. class pythonTimeConverter(TimeConverter): # the old, ?nix type date and time
  240. def __init__(self): #caution: this Class gets confised by timezones and DST
  241. TimeConverter.__init__(self)
  242. self.types.add(time.struct_time)
  243. def DateObjectFromCOMDate(self,comDate):
  244. 'Returns ticks since 1970'
  245. if isinstance(comDate,datetime.datetime):
  246. return comDate.timetuple()
  247. elif isinstance(comDate, DateTime): # ironPython clr date/time
  248. fcomDate = comDate.ToOADate()
  249. else:
  250. fcomDate = float(comDate)
  251. secondsperday=86400 # 24*60*60
  252. #ComDate is number of days since 1899-12-31, gmtime epoch is 1970-1-1 = 25569 days
  253. t=time.gmtime(secondsperday*(fcomDate-25569.0))
  254. return t #year,month,day,hour,minute,second,weekday,julianday,daylightsaving=t
  255. def Date(self,year,month,day):
  256. return self.Timestamp(year,month,day,0,0,0)
  257. def Time(self,hour,minute,second):
  258. return time.gmtime((hour*60+minute)*60 + second)
  259. def Timestamp(self,year,month,day,hour,minute,second):
  260. return time.localtime(time.mktime((year,month,day,hour,minute,second,0,0,-1)))
  261. base_dateconverter = pythonDateTimeConverter()
  262. # ------ DB API required module attributes ---------------------
  263. threadsafety=1 # TODO -- find out whether this module is actually BETTER than 1.
  264. apilevel='2.0' #String constant stating the supported DB API level.
  265. paramstyle='qmark' # the default parameter style
  266. # ------ control for an extension which may become part of DB API 3.0 ---
  267. accepted_paramstyles = ('qmark', 'named', 'format', 'pyformat', 'dynamic')
  268. #------------------------------------------------------------------------------------------
  269. # define similar types for generic conversion routines
  270. adoIntegerTypes=(adc.adInteger,adc.adSmallInt,adc.adTinyInt,adc.adUnsignedInt,
  271. adc.adUnsignedSmallInt,adc.adUnsignedTinyInt,
  272. adc.adBoolean,adc.adError) #max 32 bits
  273. adoRowIdTypes=(adc.adChapter,) #v2.1 Rose
  274. adoLongTypes=(adc.adBigInt,adc.adFileTime,adc.adUnsignedBigInt)
  275. adoExactNumericTypes=(adc.adDecimal,adc.adNumeric,adc.adVarNumeric,adc.adCurrency) #v2.3 Cole
  276. adoApproximateNumericTypes=(adc.adDouble,adc.adSingle) #v2.1 Cole
  277. adoStringTypes=(adc.adBSTR,adc.adChar,adc.adLongVarChar,adc.adLongVarWChar,
  278. adc.adVarChar,adc.adVarWChar,adc.adWChar)
  279. adoBinaryTypes=(adc.adBinary,adc.adLongVarBinary,adc.adVarBinary)
  280. adoDateTimeTypes=(adc.adDBTime, adc.adDBTimeStamp, adc.adDate, adc.adDBDate)
  281. adoRemainingTypes=(adc.adEmpty,adc.adIDispatch,adc.adIUnknown,
  282. adc.adPropVariant,adc.adArray,adc.adUserDefined,
  283. adc.adVariant,adc.adGUID)
  284. # this class is a trick to determine whether a type is a member of a related group of types. see PEP notes
  285. class DBAPITypeObject(object):
  286. def __init__(self,valuesTuple):
  287. self.values = frozenset(valuesTuple)
  288. def __eq__(self,other):
  289. return other in self.values
  290. def __ne__(self, other):
  291. return other not in self.values
  292. """This type object is used to describe columns in a database that are string-based (e.g. CHAR). """
  293. STRING = DBAPITypeObject(adoStringTypes)
  294. """This type object is used to describe (long) binary columns in a database (e.g. LONG, RAW, BLOBs). """
  295. BINARY = DBAPITypeObject(adoBinaryTypes)
  296. """This type object is used to describe numeric columns in a database. """
  297. NUMBER = DBAPITypeObject(adoIntegerTypes + adoLongTypes + \
  298. adoExactNumericTypes + adoApproximateNumericTypes)
  299. """This type object is used to describe date/time columns in a database. """
  300. DATETIME = DBAPITypeObject(adoDateTimeTypes)
  301. """This type object is used to describe the "Row ID" column in a database. """
  302. ROWID = DBAPITypeObject(adoRowIdTypes)
  303. OTHER = DBAPITypeObject(adoRemainingTypes)
  304. # ------- utilities for translating python data types to ADO data types ---------------------------------
  305. typeMap = { memoryViewType : adc.adVarBinary,
  306. float : adc.adDouble,
  307. type(None) : adc.adEmpty,
  308. str : adc.adBSTR,
  309. bool :adc.adBoolean, #v2.1 Cole
  310. decimal.Decimal : adc.adDecimal,
  311. int: adc.adBigInt,
  312. bytes: adc.adVarBinary }
  313. def pyTypeToADOType(d):
  314. tp=type(d)
  315. try:
  316. return typeMap[tp]
  317. except KeyError: # The type was not defined in the pre-computed Type table
  318. from . import dateconverter
  319. if tp in dateconverter.types: # maybe it is one of our supported Date/Time types
  320. return adc.adDate
  321. # otherwise, attempt to discern the type by probing the data object itself -- to handle duck typing
  322. if isinstance(d, StringTypes):
  323. return adc.adBSTR
  324. if isinstance(d, numbers.Integral):
  325. return adc.adBigInt
  326. if isinstance(d, numbers.Real):
  327. return adc.adDouble
  328. raise DataError('cannot convert "%s" (type=%s) to ADO'%(repr(d),tp))
  329. # # # # # # # # # # # # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  330. # functions to convert database values to Python objects
  331. #------------------------------------------------------------------------
  332. # variant type : function converting variant to Python value
  333. def variantConvertDate(v):
  334. from . import dateconverter # this function only called when adodbapi is running
  335. return dateconverter.DateObjectFromCOMDate(v)
  336. def cvtString(variant): # use to get old action of adodbapi v1 if desired
  337. if onIronPython:
  338. try:
  339. return variant.ToString()
  340. except:
  341. pass
  342. return str(variant)
  343. def cvtDecimal(variant): #better name
  344. return _convertNumberWithCulture(variant, decimal.Decimal)
  345. def cvtNumeric(variant): #older name - don't break old code
  346. return cvtDecimal(variant)
  347. def cvtFloat(variant):
  348. return _convertNumberWithCulture(variant, float)
  349. def _convertNumberWithCulture(variant, f):
  350. try:
  351. return f(variant)
  352. except (ValueError,TypeError,decimal.InvalidOperation):
  353. try:
  354. europeVsUS = str(variant).replace(",",".")
  355. return f(europeVsUS)
  356. except (ValueError,TypeError,decimal.InvalidOperation): pass
  357. def cvtInt(variant):
  358. return int(variant)
  359. def cvtLong(variant): # only important in old versions where long and int differ
  360. return int(variant)
  361. def cvtBuffer(variant):
  362. return bytes(variant)
  363. def cvtUnicode(variant):
  364. return str(variant)
  365. def identity(x): return x
  366. def cvtUnusual(variant):
  367. if verbose > 1:
  368. sys.stderr.write('Conversion called for Unusual data=%s\n' % repr(variant))
  369. if isinstance(variant, DateTime): # COMdate or System.Date
  370. from .adodbapi import dateconverter # this will only be called when adodbapi is in use, and very rarely
  371. return dateconverter.DateObjectFromCOMDate(variant)
  372. return variant # cannot find conversion function -- just give the data to the user
  373. def convert_to_python(variant, func): # convert DB value into Python value
  374. if isinstance(variant, NullTypes): # IronPython Null or None
  375. return None
  376. return func(variant) # call the appropriate conversion function
  377. class MultiMap(dict): #builds a dictionary from {(sequence,of,keys) : function}
  378. """A dictionary of ado.type : function -- but you can set multiple items by passing a sequence of keys"""
  379. #useful for defining conversion functions for groups of similar data types.
  380. def __init__(self, aDict):
  381. for k, v in list(aDict.items()):
  382. self[k] = v # we must call __setitem__
  383. def __setitem__(self, adoType, cvtFn):
  384. "set a single item, or a whole sequence of items"
  385. try: # user passed us a sequence, set them individually
  386. for type in adoType:
  387. dict.__setitem__(self, type, cvtFn)
  388. except TypeError: # a single value fails attempt to iterate
  389. dict.__setitem__(self, adoType, cvtFn)
  390. #initialize variantConversions dictionary used to convert SQL to Python
  391. # this is the dictionary of default conversion functions, built by the class above.
  392. # this becomes a class attribute for the Connection, and that attribute is used
  393. # to build the list of column conversion functions for the Cursor
  394. variantConversions = MultiMap( {
  395. adoDateTimeTypes : variantConvertDate,
  396. adoApproximateNumericTypes: cvtFloat,
  397. adoExactNumericTypes: cvtDecimal, # use to force decimal rather than unicode
  398. adoLongTypes : cvtLong,
  399. adoIntegerTypes: cvtInt,
  400. adoRowIdTypes: cvtInt,
  401. adoStringTypes: identity,
  402. adoBinaryTypes: cvtBuffer,
  403. adoRemainingTypes: cvtUnusual })
  404. # # # # # classes to emulate the result of cursor.fetchxxx() as a sequence of sequences # # # # #
  405. # "an ENUM of how my low level records are laid out"
  406. RS_WIN_32, RS_ARRAY, RS_REMOTE = list(range(1,4))
  407. class SQLrow(object): # a single database row
  408. # class to emulate a sequence, so that a column may be retrieved by either number or name
  409. def __init__(self, rows, index): # "rows" is an _SQLrows object, index is which row
  410. self.rows = rows # parent 'fetch' container object
  411. self.index = index # my row number within parent
  412. def __getattr__(self, name): # used for row.columnName type of value access
  413. try:
  414. return self._getValue(self.rows.columnNames[name.lower()])
  415. except KeyError:
  416. raise AttributeError('Unknown column name "{}"'.format(name))
  417. def _getValue(self,key): # key must be an integer
  418. if self.rows.recordset_format == RS_ARRAY: # retrieve from two-dimensional array
  419. v = self.rows.ado_results[key,self.index]
  420. elif self.rows.recordset_format == RS_REMOTE:
  421. v = self.rows.ado_results[self.index][key]
  422. else:# pywin32 - retrieve from tuple of tuples
  423. v = self.rows.ado_results[key][self.index]
  424. if self.rows.converters is NotImplemented:
  425. return v
  426. return convert_to_python(v, self.rows.converters[key])
  427. def __len__(self):
  428. return self.rows.numberOfColumns
  429. def __getitem__(self,key): # used for row[key] type of value access
  430. if isinstance(key,int): # normal row[1] designation
  431. try:
  432. return self._getValue(key)
  433. except IndexError:
  434. raise
  435. if isinstance(key, slice):
  436. indices = key.indices(self.rows.numberOfColumns)
  437. vl = [self._getValue(i) for i in range(*indices)]
  438. return tuple(vl)
  439. try:
  440. return self._getValue(self.rows.columnNames[key.lower()]) # extension row[columnName] designation
  441. except (KeyError, TypeError):
  442. er, st, tr = sys.exc_info()
  443. raise er('No such key as "%s" in %s'%(repr(key),self.__repr__())).with_traceback(tr)
  444. def __iter__(self):
  445. return iter(self.__next__())
  446. def __next__(self):
  447. for n in range(self.rows.numberOfColumns):
  448. yield self._getValue(n)
  449. def __repr__(self): # create a human readable representation
  450. taglist = sorted(list(self.rows.columnNames.items()), key=lambda x: x[1])
  451. s = "<SQLrow={"
  452. for name, i in taglist:
  453. s += name + ':' + repr(self._getValue(i)) + ', '
  454. return s[:-2] + '}>'
  455. def __str__(self): # create a pretty human readable representation
  456. return str(tuple(str(self._getValue(i)) for i in range(self.rows.numberOfColumns)))
  457. # TO-DO implement pickling an SQLrow directly
  458. #def __getstate__(self): return self.__dict__
  459. #def __setstate__(self, d): self.__dict__.update(d)
  460. # which basically tell pickle to treat your class just like a normal one,
  461. # taking self.__dict__ as representing the whole of the instance state,
  462. # despite the existence of the __getattr__.
  463. # # # #
  464. class SQLrows(object):
  465. # class to emulate a sequence for multiple rows using a container object
  466. def __init__(self, ado_results, numberOfRows, cursor):
  467. self.ado_results = ado_results # raw result of SQL get
  468. try:
  469. self.recordset_format = cursor.recordset_format
  470. self.numberOfColumns = cursor.numberOfColumns
  471. self.converters = cursor.converters
  472. self.columnNames = cursor.columnNames
  473. except AttributeError:
  474. self.recordset_format = RS_ARRAY
  475. self.numberOfColumns = 0
  476. self.converters = []
  477. self.columnNames = {}
  478. self.numberOfRows = numberOfRows
  479. def __len__(self):
  480. return self.numberOfRows
  481. def __getitem__(self, item): # used for row or row,column access
  482. if not self.ado_results:
  483. return []
  484. if isinstance(item, slice): # will return a list of row objects
  485. indices = item.indices(self.numberOfRows)
  486. return [SQLrow(self, k) for k in range(*indices)]
  487. elif isinstance(item, tuple) and len(item)==2:
  488. # d = some_rowsObject[i,j] will return a datum from a two-dimension address
  489. i, j = item
  490. if not isinstance(j, int):
  491. try:
  492. j = self.columnNames[j.lower()] # convert named column to numeric
  493. except KeyError:
  494. raise KeyError('adodbapi: no such column name as "%s"'%repr(j))
  495. if self.recordset_format == RS_ARRAY: # retrieve from two-dimensional array
  496. v = self.ado_results[j,i]
  497. elif self.recordset_format == RS_REMOTE:
  498. v = self.ado_results[i][j]
  499. else: # pywin32 - retrieve from tuple of tuples
  500. v = self.ado_results[j][i]
  501. if self.converters is NotImplemented:
  502. return v
  503. return convert_to_python(v, self.converters[j])
  504. else:
  505. row = SQLrow(self, item) # new row descriptor
  506. return row
  507. def __iter__(self):
  508. return iter(self.__next__())
  509. def __next__(self):
  510. for n in range(self.numberOfRows):
  511. row = SQLrow(self, n)
  512. yield row
  513. # # # # #
  514. # # # # # functions to re-format SQL requests to other paramstyle requirements # # # # # # # # # #
  515. def changeNamedToQmark(op): #convert from 'named' paramstyle to ADO required '?'mark parameters
  516. outOp = ''
  517. outparms=[]
  518. chunks = op.split("'") #quote all literals -- odd numbered list results are literals.
  519. inQuotes = False
  520. for chunk in chunks:
  521. if inQuotes: # this is inside a quote
  522. if chunk == '': # double apostrophe to quote one apostrophe
  523. outOp = outOp[:-1] # so take one away
  524. else:
  525. outOp += "'"+chunk+"'" # else pass the quoted string as is.
  526. else: # is SQL code -- look for a :namedParameter
  527. while chunk: # some SQL string remains
  528. sp = chunk.split(':',1)
  529. outOp += sp[0] # concat the part up to the :
  530. s = ''
  531. try:
  532. chunk = sp[1]
  533. except IndexError:
  534. chunk = None
  535. if chunk: # there was a parameter - parse it out
  536. i = 0
  537. c = chunk[0]
  538. while c.isalnum() or c == '_':
  539. i += 1
  540. try:
  541. c = chunk[i]
  542. except IndexError:
  543. break
  544. s = chunk[:i]
  545. chunk = chunk[i:]
  546. if s:
  547. outparms.append(s) # list the parameters in order
  548. outOp += '?' # put in the Qmark
  549. inQuotes = not inQuotes
  550. return outOp, outparms
  551. def changeFormatToQmark(op): #convert from 'format' paramstyle to ADO required '?'mark parameters
  552. outOp = ''
  553. outparams = []
  554. chunks = op.split("'") #quote all literals -- odd numbered list results are literals.
  555. inQuotes = False
  556. for chunk in chunks:
  557. if inQuotes:
  558. if outOp != '' and chunk=='': # he used a double apostrophe to quote one apostrophe
  559. outOp = outOp[:-1] # so take one away
  560. else:
  561. outOp += "'"+chunk+"'" # else pass the quoted string as is.
  562. else: # is SQL code -- look for a %s parameter
  563. if '%(' in chunk: # ugh! pyformat!
  564. while chunk: # some SQL string remains
  565. sp = chunk.split('%(', 1)
  566. outOp += sp[0] # concat the part up to the %
  567. if len(sp) > 1:
  568. try:
  569. s, chunk = sp[1].split(')s', 1) # find the ')s'
  570. except ValueError:
  571. raise ProgrammingError('Pyformat SQL has incorrect format near "%s"' % chunk)
  572. outparams.append(s)
  573. outOp += '?' # put in the Qmark
  574. else:
  575. chunk = None
  576. else: # proper '%s' format
  577. sp = chunk.split('%s') # make each %s
  578. outOp += "?".join(sp) # into ?
  579. inQuotes = not inQuotes # every other chunk is a quoted string
  580. return outOp, outparams