Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

adodbapi.py 49KB

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