adodbapi.py 46 KB

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