adodbapi.py 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014
  1. """adodbapi - A python DB API 2.0 (PEP 249) interface to Microsoft ADO
  2. Copyright (C) 2002 Henrik Ekelund, versions 2.1 and later by Vernon Cole
  3. * http://sourceforge.net/projects/pywin32
  4. * https://github.com/mhammond/pywin32
  5. * http://sourceforge.net/projects/adodbapi
  6. This library is free software; you can redistribute it and/or
  7. modify it under the terms of the GNU Lesser General Public
  8. License as published by the Free Software Foundation; either
  9. version 2.1 of the License, or (at your option) any later version.
  10. This library is distributed in the hope that it will be useful,
  11. but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  13. Lesser General Public License for more details.
  14. You should have received a copy of the GNU Lesser General Public
  15. License along with this library; if not, write to the Free Software
  16. Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  17. django adaptations and refactoring by Adam Vandenberg
  18. DB-API 2.0 specification: http://www.python.org/dev/peps/pep-0249/
  19. This module source should run correctly in CPython versions 2.7 and later,
  20. or IronPython version 2.7 and later,
  21. or, after running through 2to3.py, CPython 3.4 or later.
  22. """
  23. from __future__ import print_function
  24. __version__ = '2.6.2.0'
  25. version = 'adodbapi v' + __version__
  26. import sys
  27. import copy
  28. import decimal
  29. import os
  30. import weakref
  31. from . import process_connect_string
  32. from . import ado_consts as adc
  33. from . import apibase as api
  34. try:
  35. verbose = int(os.environ['ADODBAPI_VERBOSE'])
  36. except:
  37. verbose = False
  38. if verbose:
  39. print(version)
  40. # --- define objects to smooth out IronPython <-> CPython differences
  41. onWin32 = False # assume the worst
  42. if api.onIronPython:
  43. from System import Activator, Type, DBNull, DateTime, Array, Byte
  44. from System import Decimal as SystemDecimal
  45. from clr import Reference
  46. def Dispatch(dispatch):
  47. type = Type.GetTypeFromProgID(dispatch)
  48. return Activator.CreateInstance(type)
  49. def getIndexedValue(obj,index):
  50. return obj.Item[index]
  51. else: # try pywin32
  52. try:
  53. import win32com.client
  54. import pythoncom
  55. import pywintypes
  56. onWin32 = True
  57. def Dispatch(dispatch):
  58. return win32com.client.Dispatch(dispatch)
  59. except ImportError:
  60. import warnings
  61. warnings.warn("pywin32 package (or IronPython) required for adodbapi.",ImportWarning)
  62. def getIndexedValue(obj,index):
  63. return obj(index)
  64. try:
  65. from collections import Mapping
  66. except ImportError: # Python 2.5
  67. Mapping = dict # this will handle the most common case
  68. # --- define objects to smooth out Python3000 <-> Python 2.x differences
  69. unicodeType = unicode #this line will be altered by 2to3.py to '= str'
  70. longType = long #this line will be altered by 2to3.py to '= int'
  71. if sys.version_info >= (3,0): #python 3.x
  72. StringTypes = str
  73. maxint = sys.maxsize
  74. else: #python 2.x
  75. StringTypes = (str,unicode) # will be messed up by 2to3 but never used
  76. maxint = sys.maxint
  77. # ----------------- The .connect method -----------------
  78. def make_COM_connecter():
  79. try:
  80. if onWin32:
  81. pythoncom.CoInitialize() #v2.1 Paj
  82. c = Dispatch('ADODB.Connection') #connect _after_ CoIninialize v2.1.1 adamvan
  83. except:
  84. raise api.InterfaceError ("Windows COM Error: Dispatch('ADODB.Connection') failed.")
  85. return c
  86. def connect(*args, **kwargs): # --> a db-api connection object
  87. """Connect to a database.
  88. call using:
  89. :connection_string -- An ADODB formatted connection string, see:
  90. * http://www.connectionstrings.com
  91. * http://www.asp101.com/articles/john/connstring/default.asp
  92. :timeout -- A command timeout value, in seconds (default 30 seconds)
  93. """
  94. co = Connection() # make an empty connection object
  95. kwargs = process_connect_string.process(args, kwargs, True)
  96. try: # connect to the database, using the connection information in kwargs
  97. co.connect(kwargs)
  98. return co
  99. except (Exception) as e:
  100. message = 'Error opening connection to "%s"' % co.connection_string
  101. raise api.OperationalError(e, message)
  102. # so you could use something like:
  103. # myConnection.paramstyle = 'named'
  104. # The programmer may also change the default.
  105. # For example, if I were using django, I would say:
  106. # import adodbapi as Database
  107. # Database.adodbapi.paramstyle = 'format'
  108. # ------- other module level defaults --------
  109. defaultIsolationLevel = adc.adXactReadCommitted
  110. # Set defaultIsolationLevel on module level before creating the connection.
  111. # For example:
  112. # import adodbapi, ado_consts
  113. # adodbapi.adodbapi.defaultIsolationLevel=ado_consts.adXactBrowse"
  114. #
  115. # Set defaultCursorLocation on module level before creating the connection.
  116. # It may be one of the "adUse..." consts.
  117. defaultCursorLocation = adc.adUseClient # changed from adUseServer as of v 2.3.0
  118. dateconverter = api.pythonDateTimeConverter() # default
  119. def format_parameters(ADOparameters, show_value=False):
  120. """Format a collection of ADO Command Parameters.
  121. Used by error reporting in _execute_command.
  122. """
  123. try:
  124. if show_value:
  125. desc = [
  126. "Name: %s, Dir.: %s, Type: %s, Size: %s, Value: \"%s\", Precision: %s, NumericScale: %s" %\
  127. (p.Name, adc.directions[p.Direction], adc.adTypeNames.get(p.Type, str(p.Type)+' (unknown type)'), p.Size, p.Value, p.Precision, p.NumericScale)
  128. for p in ADOparameters ]
  129. else:
  130. desc = [
  131. "Name: %s, Dir.: %s, Type: %s, Size: %s, Precision: %s, NumericScale: %s" %\
  132. (p.Name, adc.directions[p.Direction], adc.adTypeNames.get(p.Type, str(p.Type)+' (unknown type)'), p.Size, p.Precision, p.NumericScale)
  133. for p in ADOparameters ]
  134. return '[' + '\n'.join(desc) + ']'
  135. except:
  136. return '[]'
  137. def _configure_parameter(p, value, adotype, settings_known):
  138. """Configure the given ADO Parameter 'p' with the Python 'value'."""
  139. if adotype in api.adoBinaryTypes:
  140. p.Size = len(value)
  141. p.AppendChunk(value)
  142. elif isinstance(value,StringTypes): #v2.1 Jevon
  143. L = len(value)
  144. if adotype in api.adoStringTypes: #v2.2.1 Cole
  145. if settings_known: L = min(L,p.Size) #v2.1 Cole limit data to defined size
  146. p.Value = value[:L] #v2.1 Jevon & v2.1 Cole
  147. else:
  148. p.Value = value # dont limit if db column is numeric
  149. if L>0: #v2.1 Cole something does not like p.Size as Zero
  150. p.Size = L #v2.1 Jevon
  151. elif isinstance(value, decimal.Decimal):
  152. if api.onIronPython:
  153. s = str(value)
  154. p.Value = s
  155. p.Size = len(s)
  156. else:
  157. p.Value = value
  158. exponent = value.as_tuple()[2]
  159. digit_count = len(value.as_tuple()[1])
  160. p.Precision = digit_count
  161. if exponent == 0:
  162. p.NumericScale = 0
  163. elif exponent < 0:
  164. p.NumericScale = -exponent
  165. if p.Precision < p.NumericScale:
  166. p.Precision = p.NumericScale
  167. else: # exponent > 0:
  168. p.NumericScale = 0
  169. p.Precision = digit_count + exponent
  170. elif type(value) in dateconverter.types:
  171. if settings_known and adotype in api.adoDateTimeTypes:
  172. p.Value = dateconverter.COMDate(value)
  173. else: #probably a string
  174. # provide the date as a string in the format 'YYYY-MM-dd'
  175. s = dateconverter.DateObjectToIsoFormatString(value)
  176. p.Value = s
  177. p.Size = len(s)
  178. elif api.onIronPython and isinstance(value, longType): # Iron Python Long
  179. s = str(value) # feature workaround for IPy 2.0
  180. p.Value = s
  181. elif adotype == adc.adEmpty: # ADO will not let you specify a null column
  182. p.Type = adc.adInteger # so we will fake it to be an integer (just to have something)
  183. p.Value = None # and pass in a Null *value*
  184. # For any other type, set the value and let pythoncom do the right thing.
  185. else:
  186. p.Value = value
  187. # # # # # ----- the Class that defines a connection ----- # # # # #
  188. class Connection(object):
  189. # include connection attributes as class attributes required by api definition.
  190. Warning = api.Warning
  191. Error = api.Error
  192. InterfaceError = api.InterfaceError
  193. DataError = api.DataError
  194. DatabaseError = api.DatabaseError
  195. OperationalError = api.OperationalError
  196. IntegrityError = api.IntegrityError
  197. InternalError = api.InternalError
  198. NotSupportedError = api.NotSupportedError
  199. ProgrammingError = api.ProgrammingError
  200. FetchFailedError = api.FetchFailedError # (special for django)
  201. # ...class attributes... (can be overridden by instance attributes)
  202. verbose = api.verbose
  203. @property
  204. def dbapi(self): # a proposed db-api version 3 extension.
  205. "Return a reference to the DBAPI module for this Connection."
  206. return api
  207. def __init__(self): # now define the instance attributes
  208. self.connector = None
  209. self.paramstyle = api.paramstyle
  210. self.supportsTransactions = False
  211. self.connection_string = ''
  212. self.cursors = weakref.WeakValueDictionary()
  213. self.dbms_name = ''
  214. self.dbms_version = ''
  215. self.errorhandler = None # use the standard error handler for this instance
  216. self.transaction_level = 0 # 0 == Not in a transaction, at the top level
  217. self._autocommit = False
  218. def connect(self, kwargs, connection_maker=make_COM_connecter):
  219. if verbose > 9:
  220. print('kwargs=', repr(kwargs))
  221. try:
  222. self.connection_string = kwargs['connection_string'] % kwargs # insert keyword arguments
  223. except (Exception) as e:
  224. self._raiseConnectionError(KeyError,'Python string format error in connection string->')
  225. self.timeout = kwargs.get('timeout', 30)
  226. self.kwargs = kwargs
  227. if verbose:
  228. print('%s attempting: "%s"' % (version, self.connection_string))
  229. self.connector = connection_maker()
  230. self.connector.ConnectionTimeout = self.timeout
  231. self.connector.ConnectionString = self.connection_string
  232. try:
  233. self.connector.Open() # Open the ADO connection
  234. except api.Error:
  235. self._raiseConnectionError(api.DatabaseError, 'ADO error trying to Open=%s' % self.connection_string)
  236. try: # Stefan Fuchs; support WINCCOLEDBProvider
  237. if getIndexedValue(self.connector.Properties,'Transaction DDL').Value != 0:
  238. self.supportsTransactions=True
  239. except pywintypes.com_error:
  240. pass # Stefan Fuchs
  241. self.dbms_name = getIndexedValue(self.connector.Properties,'DBMS Name').Value
  242. try: # Stefan Fuchs
  243. self.dbms_version = getIndexedValue(self.connector.Properties,'DBMS Version').Value
  244. except pywintypes.com_error:
  245. pass # Stefan Fuchs
  246. self.connector.CursorLocation = defaultCursorLocation #v2.1 Rose
  247. if self.supportsTransactions:
  248. self.connector.IsolationLevel=defaultIsolationLevel
  249. self._autocommit = bool(kwargs.get('autocommit', False))
  250. if not self._autocommit:
  251. self.transaction_level = self.connector.BeginTrans() #Disables autocommit & inits transaction_level
  252. else:
  253. self._autocommit = True
  254. if 'paramstyle' in kwargs:
  255. self.paramstyle = kwargs['paramstyle'] # let setattr do the error checking
  256. self.messages=[]
  257. if verbose:
  258. print('adodbapi New connection at %X' % id(self))
  259. def _raiseConnectionError(self, errorclass, errorvalue):
  260. eh = self.errorhandler
  261. if eh is None:
  262. eh = api.standardErrorHandler
  263. eh(self, None, errorclass, errorvalue)
  264. def _closeAdoConnection(self): #all v2.1 Rose
  265. """close the underlying ADO Connection object,
  266. rolling it back first if it supports transactions."""
  267. if self.connector is None:
  268. return
  269. if not self._autocommit:
  270. if self.transaction_level:
  271. try: self.connector.RollbackTrans()
  272. except: pass
  273. self.connector.Close()
  274. if verbose:
  275. print('adodbapi Closed connection at %X' % id(self))
  276. def close(self):
  277. """Close the connection now (rather than whenever __del__ is called).
  278. The connection will be unusable from this point forward;
  279. an Error (or subclass) exception will be raised if any operation is attempted with the connection.
  280. The same applies to all cursor objects trying to use the connection.
  281. """
  282. for crsr in self.cursors.values()[:]: # copy the list, then close each one
  283. crsr.close(dont_tell_me=True) # close without back-link clearing
  284. self.messages = []
  285. try:
  286. self._closeAdoConnection() #v2.1 Rose
  287. except (Exception) as e:
  288. self._raiseConnectionError(sys.exc_info()[0], sys.exc_info()[1])
  289. self.connector = None #v2.4.2.2 fix subtle timeout bug
  290. # per M.Hammond: "I expect the benefits of uninitializing are probably fairly small,
  291. # so never uninitializing will probably not cause any problems."
  292. def commit(self):
  293. """Commit any pending transaction to the database.
  294. Note that if the database supports an auto-commit feature,
  295. this must be initially off. An interface method may be provided to turn it back on.
  296. Database modules that do not support transactions should implement this method with void functionality.
  297. """
  298. self.messages = []
  299. if not self.supportsTransactions:
  300. return
  301. try:
  302. self.transaction_level = self.connector.CommitTrans()
  303. if verbose > 1:
  304. print('commit done on connection at %X' % id(self))
  305. if not (self._autocommit or (self.connector.Attributes & adc.adXactAbortRetaining)):
  306. #If attributes has adXactCommitRetaining it performs retaining commits that is,
  307. #calling CommitTrans automatically starts a new transaction. Not all providers support this.
  308. #If not, we will have to start a new transaction by this command:
  309. self.transaction_level = self.connector.BeginTrans()
  310. except Exception as e:
  311. self._raiseConnectionError(api.ProgrammingError, e)
  312. def _rollback(self):
  313. """In case a database does provide transactions this method causes the the database to roll back to
  314. the start of any pending transaction. Closing a connection without committing the changes first will
  315. cause an implicit rollback to be performed.
  316. If the database does not support the functionality required by the method, the interface should
  317. throw an exception in case the method is used.
  318. The preferred approach is to not implement the method and thus have Python generate
  319. an AttributeError in case the method is requested. This allows the programmer to check for database
  320. capabilities using the standard hasattr() function.
  321. For some dynamically configured interfaces it may not be appropriate to require dynamically making
  322. the method available. These interfaces should then raise a NotSupportedError to indicate the
  323. non-ability to perform the roll back when the method is invoked.
  324. """
  325. self.messages=[]
  326. if self.transaction_level: # trying to roll back with no open transaction causes an error
  327. try:
  328. self.transaction_level = self.connector.RollbackTrans()
  329. if verbose > 1:
  330. print('rollback done on connection at %X' % id(self))
  331. if not self._autocommit and not(self.connector.Attributes & adc.adXactAbortRetaining):
  332. #If attributes has adXactAbortRetaining it performs retaining aborts that is,
  333. #calling RollbackTrans automatically starts a new transaction. Not all providers support this.
  334. #If not, we will have to start a new transaction by this command:
  335. if not self.transaction_level: # if self.transaction_level == 0 or self.transaction_level is None:
  336. self.transaction_level = self.connector.BeginTrans()
  337. except Exception as e:
  338. self._raiseConnectionError(api.ProgrammingError, e)
  339. def __setattr__(self, name, value):
  340. if name == 'autocommit': # extension: allow user to turn autocommit on or off
  341. if self.supportsTransactions:
  342. object.__setattr__(self, '_autocommit', bool(value))
  343. try: self._rollback() # must clear any outstanding transactions
  344. except: pass
  345. return
  346. elif name == 'paramstyle':
  347. if value not in api.accepted_paramstyles:
  348. self._raiseConnectionError(api.NotSupportedError,
  349. 'paramstyle="%s" not in:%s' % (value, repr(api.accepted_paramstyles)))
  350. elif name == 'variantConversions':
  351. value = copy.copy(value) # make a new copy -- no changes in the default, please
  352. object.__setattr__(self, name, value)
  353. def __getattr__(self, item):
  354. if item == 'rollback': # the rollback method only appears if the database supports transactions
  355. if self.supportsTransactions:
  356. return self._rollback # return the rollback method so the caller can execute it.
  357. else:
  358. raise AttributeError ('this data provider does not support Rollback')
  359. elif item == 'autocommit':
  360. return self._autocommit
  361. else:
  362. raise AttributeError('no such attribute in ADO connection object as="%s"' % item)
  363. def cursor(self):
  364. "Return a new Cursor Object using the connection."
  365. self.messages = []
  366. c = Cursor(self)
  367. return c
  368. def _i_am_here(self, crsr):
  369. "message from a new cursor proclaiming its existence"
  370. oid = id(crsr)
  371. self.cursors[oid] = crsr
  372. def _i_am_closing(self,crsr):
  373. "message from a cursor giving connection a chance to clean up"
  374. try:
  375. del self.cursors[id(crsr)]
  376. except:
  377. pass
  378. def printADOerrors(self):
  379. j=self.connector.Errors.Count
  380. if j:
  381. print('ADO Errors:(%i)' % j)
  382. for e in self.connector.Errors:
  383. print('Description: %s' % e.Description)
  384. print('Error: %s %s ' % (e.Number, adc.adoErrors.get(e.Number, "unknown")))
  385. if e.Number == adc.ado_error_TIMEOUT:
  386. print('Timeout Error: Try using adodbpi.connect(constr,timeout=Nseconds)')
  387. print('Source: %s' % e.Source)
  388. print('NativeError: %s' % e.NativeError)
  389. print('SQL State: %s' % e.SQLState)
  390. def _suggest_error_class(self):
  391. """Introspect the current ADO Errors and determine an appropriate error class.
  392. Error.SQLState is a SQL-defined error condition, per the SQL specification:
  393. http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt
  394. The 23000 class of errors are integrity errors.
  395. Error 40002 is a transactional integrity error.
  396. """
  397. if self.connector is not None:
  398. for e in self.connector.Errors:
  399. state = str(e.SQLState)
  400. if state.startswith('23') or state=='40002':
  401. return api.IntegrityError
  402. return api.DatabaseError
  403. def __del__(self):
  404. try:
  405. self._closeAdoConnection() #v2.1 Rose
  406. except:
  407. pass
  408. self.connector = None
  409. def __enter__(self): # Connections are context managers
  410. return(self)
  411. def __exit__(self, exc_type, exc_val, exc_tb):
  412. if exc_type:
  413. self._rollback() #automatic rollback on errors
  414. else:
  415. self.commit()
  416. def get_table_names(self):
  417. schema = self.connector.OpenSchema(20) # constant = adSchemaTables
  418. tables = []
  419. while not schema.EOF:
  420. name = getIndexedValue(schema.Fields,'TABLE_NAME').Value
  421. tables.append(name)
  422. schema.MoveNext()
  423. del schema
  424. return tables
  425. # # # # # ----- the Class that defines a cursor ----- # # # # #
  426. class Cursor(object):
  427. ## ** api required attributes:
  428. ## description...
  429. ## This read-only attribute is a sequence of 7-item sequences.
  430. ## Each of these sequences contains information describing one result column:
  431. ## (name, type_code, display_size, internal_size, precision, scale, null_ok).
  432. ## This attribute will be None for operations that do not return rows or if the
  433. ## cursor has not had an operation invoked via the executeXXX() method yet.
  434. ## The type_code can be interpreted by comparing it to the Type Objects specified in the section below.
  435. ## rowcount...
  436. ## This read-only attribute specifies the number of rows that the last executeXXX() produced
  437. ## (for DQL statements like select) or affected (for DML statements like update or insert).
  438. ## The attribute is -1 in case no executeXXX() has been performed on the cursor or
  439. ## the rowcount of the last operation is not determinable by the interface.[7]
  440. ## arraysize...
  441. ## This read/write attribute specifies the number of rows to fetch at a time with fetchmany().
  442. ## It defaults to 1 meaning to fetch a single row at a time.
  443. ## Implementations must observe this value with respect to the fetchmany() method,
  444. ## but are free to interact with the database a single row at a time.
  445. ## It may also be used in the implementation of executemany().
  446. ## ** extension attributes:
  447. ## paramstyle...
  448. ## allows the programmer to override the connection's default paramstyle
  449. ## errorhandler...
  450. ## allows the programmer to override the connection's default error handler
  451. def __init__(self,connection):
  452. self.command = None
  453. self._ado_prepared = False
  454. self.messages=[]
  455. self.connection = connection
  456. self.paramstyle = connection.paramstyle # used for overriding the paramstyle
  457. self._parameter_names = []
  458. self.recordset_is_remote = False
  459. self.rs = None # the ADO recordset for this cursor
  460. self.converters = [] # conversion function for each column
  461. self.columnNames = {} # names of columns {lowercase name : number,...}
  462. self.numberOfColumns = 0
  463. self._description = None
  464. self.rowcount = -1
  465. self.errorhandler = connection.errorhandler
  466. self.arraysize = 1
  467. connection._i_am_here(self)
  468. if verbose:
  469. print('%s New cursor at %X on conn %X' % (version, id(self), id(self.connection)))
  470. def __iter__(self): # [2.1 Zamarev]
  471. return iter(self.fetchone, None) # [2.1 Zamarev]
  472. def prepare(self, operation):
  473. self.command = operation
  474. self._description = None
  475. self._ado_prepared = 'setup'
  476. def next(self):
  477. r = self.fetchone()
  478. if r:
  479. return r
  480. raise StopIteration
  481. def __enter__(self):
  482. "Allow database cursors to be used with context managers."
  483. return self
  484. def __exit__(self, exc_type, exc_val, exc_tb):
  485. "Allow database cursors to be used with context managers."
  486. self.close()
  487. def _raiseCursorError(self, errorclass, errorvalue):
  488. eh = self.errorhandler
  489. if eh is None:
  490. eh = api.standardErrorHandler
  491. eh(self.connection, self, errorclass, errorvalue)
  492. def build_column_info(self, recordset):
  493. self.converters = [] # convertion function for each column
  494. self.columnNames = {} # names of columns {lowercase name : number,...}
  495. self._description = None
  496. # if EOF and BOF are true at the same time, there are no records in the recordset
  497. if (recordset is None) or (recordset.State == adc.adStateClosed):
  498. self.rs = None
  499. self.numberOfColumns = 0
  500. return
  501. self.rs = recordset #v2.1.1 bkline
  502. self.recordset_format = api.RS_ARRAY if api.onIronPython else api.RS_WIN_32
  503. self.numberOfColumns = recordset.Fields.Count
  504. try:
  505. varCon = self.connection.variantConversions
  506. except AttributeError:
  507. varCon = api.variantConversions
  508. for i in range(self.numberOfColumns):
  509. f = getIndexedValue(self.rs.Fields, i)
  510. try:
  511. self.converters.append(varCon[f.Type]) # conversion function for this column
  512. except KeyError:
  513. self._raiseCursorError(api.InternalError, 'Data column of Unknown ADO type=%s' % f.Type)
  514. self.columnNames[f.Name.lower()] = i # columnNames lookup
  515. def _makeDescriptionFromRS(self):
  516. # Abort if closed or no recordset.
  517. if self.rs is None:
  518. self._description = None
  519. return
  520. desc = []
  521. for i in range(self.numberOfColumns):
  522. f = getIndexedValue(self.rs.Fields, i)
  523. if self.rs.EOF or self.rs.BOF:
  524. display_size=None
  525. else:
  526. display_size=f.ActualSize #TODO: Is this the correct defintion according to the DB API 2 Spec ?
  527. null_ok= bool(f.Attributes & adc.adFldMayBeNull) #v2.1 Cole
  528. desc.append((f.Name, f.Type, display_size, f.DefinedSize, f.Precision, f.NumericScale, null_ok))
  529. self._description = desc
  530. def get_description(self):
  531. if not self._description:
  532. self._makeDescriptionFromRS()
  533. return self._description
  534. def __getattr__(self, item):
  535. if item == 'description':
  536. return self.get_description()
  537. object.__getattribute__(self, item) # may get here on Remote attribute calls for existing attributes
  538. def format_description(self,d):
  539. """Format db_api description tuple for printing."""
  540. if self.description is None:
  541. self._makeDescriptionFromRS()
  542. if isinstance(d,int):
  543. d = self.description[d]
  544. desc = "Name= %s, Type= %s, DispSize= %s, IntSize= %s, Precision= %s, Scale= %s NullOK=%s" % \
  545. (d[0], adc.adTypeNames.get(d[1], str(d[1])+' (unknown type)'),
  546. d[2], d[3], d[4], d[5], d[6])
  547. return desc
  548. def close(self, dont_tell_me=False):
  549. """Close the cursor now (rather than whenever __del__ is called).
  550. The cursor will be unusable from this point forward; an Error (or subclass)
  551. exception will be raised if any operation is attempted with the cursor.
  552. """
  553. if self.connection is None:
  554. return
  555. self.messages = []
  556. if self.rs and self.rs.State != adc.adStateClosed: # rs exists and is open #v2.1 Rose
  557. self.rs.Close() #v2.1 Rose
  558. self.rs = None # let go of the recordset so ADO will let it be disposed #v2.1 Rose
  559. if not dont_tell_me:
  560. self.connection._i_am_closing(self) # take me off the connection's cursors list
  561. self.connection = None #this will make all future method calls on me throw an exception
  562. if verbose:
  563. print('adodbapi Closed cursor at %X' % id(self))
  564. def __del__(self):
  565. try:
  566. self.close()
  567. except:
  568. pass
  569. def _new_command(self, command_type=adc.adCmdText):
  570. self.cmd = None
  571. self.messages = []
  572. if self.connection is None:
  573. self._raiseCursorError(api.InterfaceError, None)
  574. return
  575. try:
  576. self.cmd = Dispatch("ADODB.Command")
  577. self.cmd.ActiveConnection = self.connection.connector
  578. self.cmd.CommandTimeout = self.connection.timeout
  579. self.cmd.CommandType = command_type
  580. self.cmd.CommandText = self.commandText
  581. self.cmd.Prepared = bool(self._ado_prepared)
  582. except:
  583. self._raiseCursorError(api.DatabaseError,
  584. 'Error creating new ADODB.Command object for "%s"' % repr(self.commandText))
  585. def _execute_command(self):
  586. # Stored procedures may have an integer return value
  587. self.return_value = None
  588. recordset = None
  589. count = -1 #default value
  590. if verbose:
  591. print('Executing command="%s"'%self.commandText)
  592. try:
  593. # ----- the actual SQL is executed here ---
  594. if api.onIronPython:
  595. ra = Reference[int]()
  596. recordset = self.cmd.Execute(ra)
  597. count = ra.Value
  598. else: #pywin32
  599. recordset, count = self.cmd.Execute()
  600. # ----- ------------------------------- ---
  601. except (Exception) as e:
  602. _message = ""
  603. if hasattr(e, 'args'): _message += str(e.args)+"\n"
  604. _message += "Command:\n%s\nParameters:\n%s" % (self.commandText,
  605. format_parameters(self.cmd.Parameters, True))
  606. klass = self.connection._suggest_error_class()
  607. self._raiseCursorError(klass, _message)
  608. try:
  609. self.rowcount = recordset.RecordCount
  610. except:
  611. self.rowcount = count
  612. self.build_column_info(recordset)
  613. # The ADO documentation hints that obtaining the recordcount may be timeconsuming
  614. # "If the Recordset object does not support approximate positioning, this property
  615. # may be a significant drain on resources # [ekelund]
  616. # Therefore, COM will not return rowcount for server-side cursors. [Cole]
  617. # Client-side cursors (the default since v2.8) will force a static
  618. # cursor, and rowcount will then be set accurately [Cole]
  619. def get_rowcount(self):
  620. return self.rowcount
  621. def get_returned_parameters(self):
  622. """with some providers, returned parameters and the .return_value are not available until
  623. after the last recordset has been read. In that case, you must coll nextset() until it
  624. returns None, then call this method to get your returned information."""
  625. retLst=[] # store procedures may return altered parameters, including an added "return value" item
  626. for p in tuple(self.cmd.Parameters):
  627. if verbose > 2:
  628. print('Returned=Name: %s, Dir.: %s, Type: %s, Size: %s, Value: "%s",' \
  629. " Precision: %s, NumericScale: %s" % \
  630. (p.Name, adc.directions[p.Direction],
  631. adc.adTypeNames.get(p.Type, str(p.Type)+' (unknown type)'),
  632. p.Size, p.Value, p.Precision, p.NumericScale))
  633. pyObject = api.convert_to_python(p.Value, api.variantConversions[p.Type])
  634. if p.Direction == adc.adParamReturnValue:
  635. self.returnValue = pyObject # also load the undocumented attribute (Vernon's Error!)
  636. self.return_value = pyObject
  637. else:
  638. retLst.append(pyObject)
  639. return retLst # return the parameter list to the caller
  640. def callproc(self, procname, parameters=None):
  641. """Call a stored database procedure with the given name.
  642. The sequence of parameters must contain one entry for each
  643. argument that the sproc expects. The result of the
  644. call is returned as modified copy of the input
  645. sequence. Input parameters are left untouched, output and
  646. input/output parameters replaced with possibly new values.
  647. The sproc may also provide a result set as output,
  648. which is available through the standard .fetch*() methods.
  649. Extension: A "return_value" property may be set on the
  650. cursor if the sproc defines an integer return value.
  651. """
  652. self._parameter_names = []
  653. self.commandText = procname
  654. self._new_command(command_type=adc.adCmdStoredProc)
  655. self._buildADOparameterList(parameters, sproc=True)
  656. if verbose > 2:
  657. print('Calling Stored Proc with Params=', format_parameters(self.cmd.Parameters, True))
  658. self._execute_command()
  659. return self.get_returned_parameters()
  660. def _reformat_operation(self, operation, parameters):
  661. if self.paramstyle in ('format', 'pyformat'): # convert %s to ?
  662. operation, self._parameter_names = api.changeFormatToQmark(operation)
  663. elif self.paramstyle == 'named' or (self.paramstyle == 'dynamic' and isinstance(parameters, Mapping)):
  664. operation, self._parameter_names = api.changeNamedToQmark(operation) # convert :name to ?
  665. return operation
  666. def _buildADOparameterList(self, parameters, sproc=False):
  667. self.parameters = parameters
  668. if parameters is None:
  669. parameters = []
  670. # Note: ADO does not preserve the parameter list, even if "Prepared" is True, so we must build every time.
  671. parameters_known = False
  672. if sproc: # needed only if we are calling a stored procedure
  673. try: # attempt to use ADO's parameter list
  674. self.cmd.Parameters.Refresh()
  675. if verbose > 2:
  676. print('ADO detected Params=', format_parameters(self.cmd.Parameters, True))
  677. print('Program Parameters=', repr(parameters))
  678. parameters_known = True
  679. except api.Error:
  680. if verbose:
  681. print('ADO Parameter Refresh failed')
  682. pass
  683. else:
  684. if len(parameters) != self.cmd.Parameters.Count - 1:
  685. raise api.ProgrammingError('You must supply %d parameters for this stored procedure' % \
  686. (self.cmd.Parameters.Count - 1))
  687. if sproc or parameters != []:
  688. i = 0
  689. if parameters_known: # use ado parameter list
  690. if self._parameter_names: # named parameters
  691. for i, pm_name in enumerate(self._parameter_names):
  692. p = getIndexedValue(self.cmd.Parameters, i)
  693. try:
  694. _configure_parameter(p, parameters[pm_name], p.Type, parameters_known)
  695. except (Exception) as e:
  696. _message = u'Error Converting Parameter %s: %s, %s <- %s\n' % \
  697. (p.Name, adc.ado_type_name(p.Type), p.Value, repr(parameters[pm_name]))
  698. self._raiseCursorError(api.DataError, _message+'->'+repr(e.args))
  699. else: # regular sequence of parameters
  700. for value in parameters:
  701. p = getIndexedValue(self.cmd.Parameters,i)
  702. if p.Direction == adc.adParamReturnValue: # this is an extra parameter added by ADO
  703. i += 1 # skip the extra
  704. p=getIndexedValue(self.cmd.Parameters,i)
  705. try:
  706. _configure_parameter(p, value, p.Type, parameters_known)
  707. except Exception as e:
  708. _message = u'Error Converting Parameter %s: %s, %s <- %s\n' % \
  709. (p.Name, adc.ado_type_name(p.Type), p.Value, repr(value))
  710. self._raiseCursorError(api.DataError, _message+'->'+repr(e.args))
  711. i += 1
  712. else: #-- build own parameter list
  713. if self._parameter_names: # we expect a dictionary of parameters, this is the list of expected names
  714. for parm_name in self._parameter_names:
  715. elem = parameters[parm_name]
  716. adotype = api.pyTypeToADOType(elem)
  717. p = self.cmd.CreateParameter(parm_name, adotype, adc.adParamInput)
  718. _configure_parameter(p, elem, adotype, parameters_known)
  719. try:
  720. self.cmd.Parameters.Append(p)
  721. except Exception as e:
  722. _message = u'Error Building Parameter %s: %s, %s <- %s\n' % \
  723. (p.Name, adc.ado_type_name(p.Type), p.Value, repr(elem))
  724. self._raiseCursorError(api.DataError, _message+'->'+repr(e.args))
  725. else : # expecting the usual sequence of parameters
  726. if sproc:
  727. p = self.cmd.CreateParameter('@RETURN_VALUE', adc.adInteger, adc.adParamReturnValue)
  728. self.cmd.Parameters.Append(p)
  729. for elem in parameters:
  730. name='p%i' % i
  731. adotype = api.pyTypeToADOType(elem)
  732. p=self.cmd.CreateParameter(name, adotype, adc.adParamInput) # Name, Type, Direction, Size, Value
  733. _configure_parameter(p, elem, adotype, parameters_known)
  734. try:
  735. self.cmd.Parameters.Append(p)
  736. except Exception as e:
  737. _message = u'Error Building Parameter %s: %s, %s <- %s\n' % \
  738. (p.Name, adc.ado_type_name(p.Type), p.Value, repr(elem))
  739. self._raiseCursorError(api.DataError, _message+'->'+repr(e.args))
  740. i += 1
  741. if self._ado_prepared == 'setup':
  742. self._ado_prepared = True # parameters will be "known" by ADO next loop
  743. def execute(self, operation, parameters=None):
  744. """Prepare and execute a database operation (query or command).
  745. Parameters may be provided as sequence or mapping and will be bound to variables in the operation.
  746. Variables are specified in a database-specific notation
  747. (see the module's paramstyle attribute for details). [5]
  748. A reference to the operation will be retained by the cursor.
  749. If the same operation object is passed in again, then the cursor
  750. can optimize its behavior. This is most effective for algorithms
  751. where the same operation is used, but different parameters are bound to it (many times).
  752. For maximum efficiency when reusing an operation, it is best to use
  753. the setinputsizes() method to specify the parameter types and sizes ahead of time.
  754. It is legal for a parameter to not match the predefined information;
  755. the implementation should compensate, possibly with a loss of efficiency.
  756. The parameters may also be specified as list of tuples to e.g. insert multiple rows in
  757. a single operation, but this kind of usage is depreciated: executemany() should be used instead.
  758. Return value is not defined.
  759. [5] The module will use the __getitem__ method of the parameters object to map either positions
  760. (integers) or names (strings) to parameter values. This allows for both sequences and mappings
  761. to be used as input.
  762. The term "bound" refers to the process of binding an input value to a database execution buffer.
  763. In practical terms, this means that the input value is directly used as a value in the operation.
  764. The client should not be required to "escape" the value so that it can be used -- the value
  765. should be equal to the actual database value. """
  766. if self.command is not operation or self._ado_prepared == 'setup' or not hasattr(self, 'commandText'):
  767. if self.command is not operation:
  768. self._ado_prepared = False
  769. self.command = operation
  770. self._parameter_names = []
  771. self.commandText = operation if (self.paramstyle == 'qmark' or not parameters) \
  772. else self._reformat_operation(operation, parameters)
  773. self._new_command()
  774. self._buildADOparameterList(parameters)
  775. if verbose > 3:
  776. print('Params=', format_parameters(self.cmd.Parameters, True))
  777. self._execute_command()
  778. def executemany(self, operation, seq_of_parameters):
  779. """Prepare a database operation (query or command)
  780. and then execute it against all parameter sequences or mappings found in the sequence seq_of_parameters.
  781. Return values are not defined.
  782. """
  783. self.messages = list()
  784. total_recordcount = 0
  785. self.prepare(operation)
  786. for params in seq_of_parameters:
  787. self.execute(self.command, params)
  788. if self.rowcount == -1:
  789. total_recordcount = -1
  790. if total_recordcount != -1:
  791. total_recordcount += self.rowcount
  792. self.rowcount = total_recordcount
  793. def _fetch(self, limit=None):
  794. """Fetch rows from the current recordset.
  795. limit -- Number of rows to fetch, or None (default) to fetch all rows.
  796. """
  797. if self.connection is None or self.rs is None:
  798. self._raiseCursorError(api.FetchFailedError, 'fetch() on closed connection or empty query set')
  799. return
  800. if self.rs.State == adc.adStateClosed or self.rs.BOF or self.rs.EOF:
  801. return list()
  802. if limit: # limit number of rows retrieved
  803. ado_results = self.rs.GetRows(limit)
  804. else: # get all rows
  805. ado_results = self.rs.GetRows()
  806. if self.recordset_format == api.RS_ARRAY: # result of GetRows is a two-dimension array
  807. length = len(ado_results) // self.numberOfColumns # length of first dimension
  808. else: #pywin32
  809. length = len(ado_results[0]) #result of GetRows is tuples in a tuple
  810. fetchObject = api.SQLrows(ado_results, length, self) # new object to hold the results of the fetch
  811. return fetchObject
  812. def fetchone(self):
  813. """ Fetch the next row of a query result set, returning a single sequence,
  814. or None when no more data is available.
  815. An Error (or subclass) exception is raised if the previous call to executeXXX()
  816. did not produce any result set or no call was issued yet.
  817. """
  818. self.messages = []
  819. result = self._fetch(1)
  820. if result: # return record (not list of records)
  821. return result[0]
  822. return None
  823. def fetchmany(self, size=None):
  824. """Fetch the next set of rows of a query result, returning a list of tuples. An empty sequence is returned when no more rows are available.
  825. The number of rows to fetch per call is specified by the parameter.
  826. If it is not given, the cursor's arraysize determines the number of rows to be fetched.
  827. The method should try to fetch as many rows as indicated by the size parameter.
  828. If this is not possible due to the specified number of rows not being available,
  829. fewer rows may be returned.
  830. An Error (or subclass) exception is raised if the previous call to executeXXX()
  831. did not produce any result set or no call was issued yet.
  832. Note there are performance considerations involved with the size parameter.
  833. For optimal performance, it is usually best to use the arraysize attribute.
  834. If the size parameter is used, then it is best for it to retain the same value from
  835. one fetchmany() call to the next.
  836. """
  837. self.messages=[]
  838. if size is None:
  839. size = self.arraysize
  840. return self._fetch(size)
  841. def fetchall(self):
  842. """Fetch all (remaining) rows of a query result, returning them as a sequence of sequences (e.g. a list of tuples).
  843. Note that the cursor's arraysize attribute
  844. can affect the performance of this operation.
  845. An Error (or subclass) exception is raised if the previous call to executeXXX()
  846. did not produce any result set or no call was issued yet.
  847. """
  848. self.messages=[]
  849. return self._fetch()
  850. def nextset(self):
  851. """Skip to the next available recordset, discarding any remaining rows from the current recordset.
  852. If there are no more sets, the method returns None. Otherwise, it returns a true
  853. value and subsequent calls to the fetch methods will return rows from the next result set.
  854. An Error (or subclass) exception is raised if the previous call to executeXXX()
  855. did not produce any result set or no call was issued yet.
  856. """
  857. self.messages=[]
  858. if self.connection is None or self.rs is None:
  859. self._raiseCursorError(api.OperationalError, ('nextset() on closed connection or empty query set'))
  860. return None
  861. if api.onIronPython:
  862. try:
  863. recordset = self.rs.NextRecordset()
  864. except TypeError:
  865. recordset = None
  866. except api.Error as exc:
  867. self._raiseCursorError(api.NotSupportedError, exc.args)
  868. else: #pywin32
  869. try: #[begin 2.1 ekelund]
  870. rsTuple=self.rs.NextRecordset() #
  871. except pywintypes.com_error as exc: # return appropriate error
  872. self._raiseCursorError(api.NotSupportedError, exc.args)#[end 2.1 ekelund]
  873. recordset = rsTuple[0]
  874. if recordset is None:
  875. return None
  876. self.build_column_info(recordset)
  877. return True
  878. def setinputsizes(self,sizes):
  879. pass
  880. def setoutputsize(self, size, column=None):
  881. pass
  882. def _last_query(self): # let the programmer see what query we actually used
  883. try:
  884. if self.parameters == None:
  885. ret = self.commandText
  886. else:
  887. ret = "%s,parameters=%s" % (self.commandText,repr(self.parameters))
  888. except:
  889. ret = None
  890. return ret
  891. query = property(_last_query, None, None,
  892. "returns the last query executed")
  893. if __name__ == '__main__':
  894. raise api.ProgrammingError(version + ' cannot be run as a main program.')