base.py 119 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366
  1. # engine/base.py
  2. # Copyright (C) 2005-2024 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: https://www.opensource.org/licenses/mit-license.php
  7. """Defines :class:`_engine.Connection` and :class:`_engine.Engine`.
  8. """
  9. from __future__ import annotations
  10. import contextlib
  11. import sys
  12. import typing
  13. from typing import Any
  14. from typing import Callable
  15. from typing import cast
  16. from typing import Iterable
  17. from typing import Iterator
  18. from typing import List
  19. from typing import Mapping
  20. from typing import NoReturn
  21. from typing import Optional
  22. from typing import overload
  23. from typing import Tuple
  24. from typing import Type
  25. from typing import TypeVar
  26. from typing import Union
  27. from .interfaces import BindTyping
  28. from .interfaces import ConnectionEventsTarget
  29. from .interfaces import DBAPICursor
  30. from .interfaces import ExceptionContext
  31. from .interfaces import ExecuteStyle
  32. from .interfaces import ExecutionContext
  33. from .interfaces import IsolationLevel
  34. from .util import _distill_params_20
  35. from .util import _distill_raw_params
  36. from .util import TransactionalContext
  37. from .. import exc
  38. from .. import inspection
  39. from .. import log
  40. from .. import util
  41. from ..sql import compiler
  42. from ..sql import util as sql_util
  43. if typing.TYPE_CHECKING:
  44. from . import CursorResult
  45. from . import ScalarResult
  46. from .interfaces import _AnyExecuteParams
  47. from .interfaces import _AnyMultiExecuteParams
  48. from .interfaces import _CoreAnyExecuteParams
  49. from .interfaces import _CoreMultiExecuteParams
  50. from .interfaces import _CoreSingleExecuteParams
  51. from .interfaces import _DBAPIAnyExecuteParams
  52. from .interfaces import _DBAPISingleExecuteParams
  53. from .interfaces import _ExecuteOptions
  54. from .interfaces import CompiledCacheType
  55. from .interfaces import CoreExecuteOptionsParameter
  56. from .interfaces import Dialect
  57. from .interfaces import SchemaTranslateMapType
  58. from .reflection import Inspector # noqa
  59. from .url import URL
  60. from ..event import dispatcher
  61. from ..log import _EchoFlagType
  62. from ..pool import _ConnectionFairy
  63. from ..pool import Pool
  64. from ..pool import PoolProxiedConnection
  65. from ..sql import Executable
  66. from ..sql._typing import _InfoType
  67. from ..sql.compiler import Compiled
  68. from ..sql.ddl import ExecutableDDLElement
  69. from ..sql.ddl import SchemaDropper
  70. from ..sql.ddl import SchemaGenerator
  71. from ..sql.functions import FunctionElement
  72. from ..sql.schema import DefaultGenerator
  73. from ..sql.schema import HasSchemaAttr
  74. from ..sql.schema import SchemaItem
  75. from ..sql.selectable import TypedReturnsRows
  76. _T = TypeVar("_T", bound=Any)
  77. _EMPTY_EXECUTION_OPTS: _ExecuteOptions = util.EMPTY_DICT
  78. NO_OPTIONS: Mapping[str, Any] = util.EMPTY_DICT
  79. class Connection(ConnectionEventsTarget, inspection.Inspectable["Inspector"]):
  80. """Provides high-level functionality for a wrapped DB-API connection.
  81. The :class:`_engine.Connection` object is procured by calling the
  82. :meth:`_engine.Engine.connect` method of the :class:`_engine.Engine`
  83. object, and provides services for execution of SQL statements as well
  84. as transaction control.
  85. The Connection object is **not** thread-safe. While a Connection can be
  86. shared among threads using properly synchronized access, it is still
  87. possible that the underlying DBAPI connection may not support shared
  88. access between threads. Check the DBAPI documentation for details.
  89. The Connection object represents a single DBAPI connection checked out
  90. from the connection pool. In this state, the connection pool has no
  91. affect upon the connection, including its expiration or timeout state.
  92. For the connection pool to properly manage connections, connections
  93. should be returned to the connection pool (i.e. ``connection.close()``)
  94. whenever the connection is not in use.
  95. .. index::
  96. single: thread safety; Connection
  97. """
  98. dispatch: dispatcher[ConnectionEventsTarget]
  99. _sqla_logger_namespace = "sqlalchemy.engine.Connection"
  100. # used by sqlalchemy.engine.util.TransactionalContext
  101. _trans_context_manager: Optional[TransactionalContext] = None
  102. # legacy as of 2.0, should be eventually deprecated and
  103. # removed. was used in the "pre_ping" recipe that's been in the docs
  104. # a long time
  105. should_close_with_result = False
  106. _dbapi_connection: Optional[PoolProxiedConnection]
  107. _execution_options: _ExecuteOptions
  108. _transaction: Optional[RootTransaction]
  109. _nested_transaction: Optional[NestedTransaction]
  110. def __init__(
  111. self,
  112. engine: Engine,
  113. connection: Optional[PoolProxiedConnection] = None,
  114. _has_events: Optional[bool] = None,
  115. _allow_revalidate: bool = True,
  116. _allow_autobegin: bool = True,
  117. ):
  118. """Construct a new Connection."""
  119. self.engine = engine
  120. self.dialect = dialect = engine.dialect
  121. if connection is None:
  122. try:
  123. self._dbapi_connection = engine.raw_connection()
  124. except dialect.loaded_dbapi.Error as err:
  125. Connection._handle_dbapi_exception_noconnection(
  126. err, dialect, engine
  127. )
  128. raise
  129. else:
  130. self._dbapi_connection = connection
  131. self._transaction = self._nested_transaction = None
  132. self.__savepoint_seq = 0
  133. self.__in_begin = False
  134. self.__can_reconnect = _allow_revalidate
  135. self._allow_autobegin = _allow_autobegin
  136. self._echo = self.engine._should_log_info()
  137. if _has_events is None:
  138. # if _has_events is sent explicitly as False,
  139. # then don't join the dispatch of the engine; we don't
  140. # want to handle any of the engine's events in that case.
  141. self.dispatch = self.dispatch._join(engine.dispatch)
  142. self._has_events = _has_events or (
  143. _has_events is None and engine._has_events
  144. )
  145. self._execution_options = engine._execution_options
  146. if self._has_events or self.engine._has_events:
  147. self.dispatch.engine_connect(self)
  148. @util.memoized_property
  149. def _message_formatter(self) -> Any:
  150. if "logging_token" in self._execution_options:
  151. token = self._execution_options["logging_token"]
  152. return lambda msg: "[%s] %s" % (token, msg)
  153. else:
  154. return None
  155. def _log_info(self, message: str, *arg: Any, **kw: Any) -> None:
  156. fmt = self._message_formatter
  157. if fmt:
  158. message = fmt(message)
  159. if log.STACKLEVEL:
  160. kw["stacklevel"] = 1 + log.STACKLEVEL_OFFSET
  161. self.engine.logger.info(message, *arg, **kw)
  162. def _log_debug(self, message: str, *arg: Any, **kw: Any) -> None:
  163. fmt = self._message_formatter
  164. if fmt:
  165. message = fmt(message)
  166. if log.STACKLEVEL:
  167. kw["stacklevel"] = 1 + log.STACKLEVEL_OFFSET
  168. self.engine.logger.debug(message, *arg, **kw)
  169. @property
  170. def _schema_translate_map(self) -> Optional[SchemaTranslateMapType]:
  171. schema_translate_map: Optional[
  172. SchemaTranslateMapType
  173. ] = self._execution_options.get("schema_translate_map", None)
  174. return schema_translate_map
  175. def schema_for_object(self, obj: HasSchemaAttr) -> Optional[str]:
  176. """Return the schema name for the given schema item taking into
  177. account current schema translate map.
  178. """
  179. name = obj.schema
  180. schema_translate_map: Optional[
  181. SchemaTranslateMapType
  182. ] = self._execution_options.get("schema_translate_map", None)
  183. if (
  184. schema_translate_map
  185. and name in schema_translate_map
  186. and obj._use_schema_map
  187. ):
  188. return schema_translate_map[name]
  189. else:
  190. return name
  191. def __enter__(self) -> Connection:
  192. return self
  193. def __exit__(self, type_: Any, value: Any, traceback: Any) -> None:
  194. self.close()
  195. @overload
  196. def execution_options(
  197. self,
  198. *,
  199. compiled_cache: Optional[CompiledCacheType] = ...,
  200. logging_token: str = ...,
  201. isolation_level: IsolationLevel = ...,
  202. no_parameters: bool = False,
  203. stream_results: bool = False,
  204. max_row_buffer: int = ...,
  205. yield_per: int = ...,
  206. insertmanyvalues_page_size: int = ...,
  207. schema_translate_map: Optional[SchemaTranslateMapType] = ...,
  208. **opt: Any,
  209. ) -> Connection:
  210. ...
  211. @overload
  212. def execution_options(self, **opt: Any) -> Connection:
  213. ...
  214. def execution_options(self, **opt: Any) -> Connection:
  215. r"""Set non-SQL options for the connection which take effect
  216. during execution.
  217. This method modifies this :class:`_engine.Connection` **in-place**;
  218. the return value is the same :class:`_engine.Connection` object
  219. upon which the method is called. Note that this is in contrast
  220. to the behavior of the ``execution_options`` methods on other
  221. objects such as :meth:`_engine.Engine.execution_options` and
  222. :meth:`_sql.Executable.execution_options`. The rationale is that many
  223. such execution options necessarily modify the state of the base
  224. DBAPI connection in any case so there is no feasible means of
  225. keeping the effect of such an option localized to a "sub" connection.
  226. .. versionchanged:: 2.0 The :meth:`_engine.Connection.execution_options`
  227. method, in contrast to other objects with this method, modifies
  228. the connection in-place without creating copy of it.
  229. As discussed elsewhere, the :meth:`_engine.Connection.execution_options`
  230. method accepts any arbitrary parameters including user defined names.
  231. All parameters given are consumable in a number of ways including
  232. by using the :meth:`_engine.Connection.get_execution_options` method.
  233. See the examples at :meth:`_sql.Executable.execution_options`
  234. and :meth:`_engine.Engine.execution_options`.
  235. The keywords that are currently recognized by SQLAlchemy itself
  236. include all those listed under :meth:`.Executable.execution_options`,
  237. as well as others that are specific to :class:`_engine.Connection`.
  238. :param compiled_cache: Available on: :class:`_engine.Connection`,
  239. :class:`_engine.Engine`.
  240. A dictionary where :class:`.Compiled` objects
  241. will be cached when the :class:`_engine.Connection`
  242. compiles a clause
  243. expression into a :class:`.Compiled` object. This dictionary will
  244. supersede the statement cache that may be configured on the
  245. :class:`_engine.Engine` itself. If set to None, caching
  246. is disabled, even if the engine has a configured cache size.
  247. Note that the ORM makes use of its own "compiled" caches for
  248. some operations, including flush operations. The caching
  249. used by the ORM internally supersedes a cache dictionary
  250. specified here.
  251. :param logging_token: Available on: :class:`_engine.Connection`,
  252. :class:`_engine.Engine`, :class:`_sql.Executable`.
  253. Adds the specified string token surrounded by brackets in log
  254. messages logged by the connection, i.e. the logging that's enabled
  255. either via the :paramref:`_sa.create_engine.echo` flag or via the
  256. ``logging.getLogger("sqlalchemy.engine")`` logger. This allows a
  257. per-connection or per-sub-engine token to be available which is
  258. useful for debugging concurrent connection scenarios.
  259. .. versionadded:: 1.4.0b2
  260. .. seealso::
  261. :ref:`dbengine_logging_tokens` - usage example
  262. :paramref:`_sa.create_engine.logging_name` - adds a name to the
  263. name used by the Python logger object itself.
  264. :param isolation_level: Available on: :class:`_engine.Connection`,
  265. :class:`_engine.Engine`.
  266. Set the transaction isolation level for the lifespan of this
  267. :class:`_engine.Connection` object.
  268. Valid values include those string
  269. values accepted by the :paramref:`_sa.create_engine.isolation_level`
  270. parameter passed to :func:`_sa.create_engine`. These levels are
  271. semi-database specific; see individual dialect documentation for
  272. valid levels.
  273. The isolation level option applies the isolation level by emitting
  274. statements on the DBAPI connection, and **necessarily affects the
  275. original Connection object overall**. The isolation level will remain
  276. at the given setting until explicitly changed, or when the DBAPI
  277. connection itself is :term:`released` to the connection pool, i.e. the
  278. :meth:`_engine.Connection.close` method is called, at which time an
  279. event handler will emit additional statements on the DBAPI connection
  280. in order to revert the isolation level change.
  281. .. note:: The ``isolation_level`` execution option may only be
  282. established before the :meth:`_engine.Connection.begin` method is
  283. called, as well as before any SQL statements are emitted which
  284. would otherwise trigger "autobegin", or directly after a call to
  285. :meth:`_engine.Connection.commit` or
  286. :meth:`_engine.Connection.rollback`. A database cannot change the
  287. isolation level on a transaction in progress.
  288. .. note:: The ``isolation_level`` execution option is implicitly
  289. reset if the :class:`_engine.Connection` is invalidated, e.g. via
  290. the :meth:`_engine.Connection.invalidate` method, or if a
  291. disconnection error occurs. The new connection produced after the
  292. invalidation will **not** have the selected isolation level
  293. re-applied to it automatically.
  294. .. seealso::
  295. :ref:`dbapi_autocommit`
  296. :meth:`_engine.Connection.get_isolation_level`
  297. - view current actual level
  298. :param no_parameters: Available on: :class:`_engine.Connection`,
  299. :class:`_sql.Executable`.
  300. When ``True``, if the final parameter
  301. list or dictionary is totally empty, will invoke the
  302. statement on the cursor as ``cursor.execute(statement)``,
  303. not passing the parameter collection at all.
  304. Some DBAPIs such as psycopg2 and mysql-python consider
  305. percent signs as significant only when parameters are
  306. present; this option allows code to generate SQL
  307. containing percent signs (and possibly other characters)
  308. that is neutral regarding whether it's executed by the DBAPI
  309. or piped into a script that's later invoked by
  310. command line tools.
  311. :param stream_results: Available on: :class:`_engine.Connection`,
  312. :class:`_sql.Executable`.
  313. Indicate to the dialect that results should be
  314. "streamed" and not pre-buffered, if possible. For backends
  315. such as PostgreSQL, MySQL and MariaDB, this indicates the use of
  316. a "server side cursor" as opposed to a client side cursor.
  317. Other backends such as that of Oracle may already use server
  318. side cursors by default.
  319. The usage of
  320. :paramref:`_engine.Connection.execution_options.stream_results` is
  321. usually combined with setting a fixed number of rows to to be fetched
  322. in batches, to allow for efficient iteration of database rows while
  323. at the same time not loading all result rows into memory at once;
  324. this can be configured on a :class:`_engine.Result` object using the
  325. :meth:`_engine.Result.yield_per` method, after execution has
  326. returned a new :class:`_engine.Result`. If
  327. :meth:`_engine.Result.yield_per` is not used,
  328. the :paramref:`_engine.Connection.execution_options.stream_results`
  329. mode of operation will instead use a dynamically sized buffer
  330. which buffers sets of rows at a time, growing on each batch
  331. based on a fixed growth size up until a limit which may
  332. be configured using the
  333. :paramref:`_engine.Connection.execution_options.max_row_buffer`
  334. parameter.
  335. When using the ORM to fetch ORM mapped objects from a result,
  336. :meth:`_engine.Result.yield_per` should always be used with
  337. :paramref:`_engine.Connection.execution_options.stream_results`,
  338. so that the ORM does not fetch all rows into new ORM objects at once.
  339. For typical use, the
  340. :paramref:`_engine.Connection.execution_options.yield_per` execution
  341. option should be preferred, which sets up both
  342. :paramref:`_engine.Connection.execution_options.stream_results` and
  343. :meth:`_engine.Result.yield_per` at once. This option is supported
  344. both at a core level by :class:`_engine.Connection` as well as by the
  345. ORM :class:`_engine.Session`; the latter is described at
  346. :ref:`orm_queryguide_yield_per`.
  347. .. seealso::
  348. :ref:`engine_stream_results` - background on
  349. :paramref:`_engine.Connection.execution_options.stream_results`
  350. :paramref:`_engine.Connection.execution_options.max_row_buffer`
  351. :paramref:`_engine.Connection.execution_options.yield_per`
  352. :ref:`orm_queryguide_yield_per` - in the :ref:`queryguide_toplevel`
  353. describing the ORM version of ``yield_per``
  354. :param max_row_buffer: Available on: :class:`_engine.Connection`,
  355. :class:`_sql.Executable`. Sets a maximum
  356. buffer size to use when the
  357. :paramref:`_engine.Connection.execution_options.stream_results`
  358. execution option is used on a backend that supports server side
  359. cursors. The default value if not specified is 1000.
  360. .. seealso::
  361. :paramref:`_engine.Connection.execution_options.stream_results`
  362. :ref:`engine_stream_results`
  363. :param yield_per: Available on: :class:`_engine.Connection`,
  364. :class:`_sql.Executable`. Integer value applied which will
  365. set the :paramref:`_engine.Connection.execution_options.stream_results`
  366. execution option and invoke :meth:`_engine.Result.yield_per`
  367. automatically at once. Allows equivalent functionality as
  368. is present when using this parameter with the ORM.
  369. .. versionadded:: 1.4.40
  370. .. seealso::
  371. :ref:`engine_stream_results` - background and examples
  372. on using server side cursors with Core.
  373. :ref:`orm_queryguide_yield_per` - in the :ref:`queryguide_toplevel`
  374. describing the ORM version of ``yield_per``
  375. :param insertmanyvalues_page_size: Available on: :class:`_engine.Connection`,
  376. :class:`_engine.Engine`. Number of rows to format into an
  377. INSERT statement when the statement uses "insertmanyvalues" mode,
  378. which is a paged form of bulk insert that is used for many backends
  379. when using :term:`executemany` execution typically in conjunction
  380. with RETURNING. Defaults to 1000. May also be modified on a
  381. per-engine basis using the
  382. :paramref:`_sa.create_engine.insertmanyvalues_page_size` parameter.
  383. .. versionadded:: 2.0
  384. .. seealso::
  385. :ref:`engine_insertmanyvalues`
  386. :param schema_translate_map: Available on: :class:`_engine.Connection`,
  387. :class:`_engine.Engine`, :class:`_sql.Executable`.
  388. A dictionary mapping schema names to schema names, that will be
  389. applied to the :paramref:`_schema.Table.schema` element of each
  390. :class:`_schema.Table`
  391. encountered when SQL or DDL expression elements
  392. are compiled into strings; the resulting schema name will be
  393. converted based on presence in the map of the original name.
  394. .. seealso::
  395. :ref:`schema_translating`
  396. .. seealso::
  397. :meth:`_engine.Engine.execution_options`
  398. :meth:`.Executable.execution_options`
  399. :meth:`_engine.Connection.get_execution_options`
  400. :ref:`orm_queryguide_execution_options` - documentation on all
  401. ORM-specific execution options
  402. """ # noqa
  403. if self._has_events or self.engine._has_events:
  404. self.dispatch.set_connection_execution_options(self, opt)
  405. self._execution_options = self._execution_options.union(opt)
  406. self.dialect.set_connection_execution_options(self, opt)
  407. return self
  408. def get_execution_options(self) -> _ExecuteOptions:
  409. """Get the non-SQL options which will take effect during execution.
  410. .. versionadded:: 1.3
  411. .. seealso::
  412. :meth:`_engine.Connection.execution_options`
  413. """
  414. return self._execution_options
  415. @property
  416. def _still_open_and_dbapi_connection_is_valid(self) -> bool:
  417. pool_proxied_connection = self._dbapi_connection
  418. return (
  419. pool_proxied_connection is not None
  420. and pool_proxied_connection.is_valid
  421. )
  422. @property
  423. def closed(self) -> bool:
  424. """Return True if this connection is closed."""
  425. return self._dbapi_connection is None and not self.__can_reconnect
  426. @property
  427. def invalidated(self) -> bool:
  428. """Return True if this connection was invalidated.
  429. This does not indicate whether or not the connection was
  430. invalidated at the pool level, however
  431. """
  432. # prior to 1.4, "invalid" was stored as a state independent of
  433. # "closed", meaning an invalidated connection could be "closed",
  434. # the _dbapi_connection would be None and closed=True, yet the
  435. # "invalid" flag would stay True. This meant that there were
  436. # three separate states (open/valid, closed/valid, closed/invalid)
  437. # when there is really no reason for that; a connection that's
  438. # "closed" does not need to be "invalid". So the state is now
  439. # represented by the two facts alone.
  440. pool_proxied_connection = self._dbapi_connection
  441. return pool_proxied_connection is None and self.__can_reconnect
  442. @property
  443. def connection(self) -> PoolProxiedConnection:
  444. """The underlying DB-API connection managed by this Connection.
  445. This is a SQLAlchemy connection-pool proxied connection
  446. which then has the attribute
  447. :attr:`_pool._ConnectionFairy.dbapi_connection` that refers to the
  448. actual driver connection.
  449. .. seealso::
  450. :ref:`dbapi_connections`
  451. """
  452. if self._dbapi_connection is None:
  453. try:
  454. return self._revalidate_connection()
  455. except (exc.PendingRollbackError, exc.ResourceClosedError):
  456. raise
  457. except BaseException as e:
  458. self._handle_dbapi_exception(e, None, None, None, None)
  459. else:
  460. return self._dbapi_connection
  461. def get_isolation_level(self) -> IsolationLevel:
  462. """Return the current **actual** isolation level that's present on
  463. the database within the scope of this connection.
  464. This attribute will perform a live SQL operation against the database
  465. in order to procure the current isolation level, so the value returned
  466. is the actual level on the underlying DBAPI connection regardless of
  467. how this state was set. This will be one of the four actual isolation
  468. modes ``READ UNCOMMITTED``, ``READ COMMITTED``, ``REPEATABLE READ``,
  469. ``SERIALIZABLE``. It will **not** include the ``AUTOCOMMIT`` isolation
  470. level setting. Third party dialects may also feature additional
  471. isolation level settings.
  472. .. note:: This method **will not report** on the ``AUTOCOMMIT``
  473. isolation level, which is a separate :term:`dbapi` setting that's
  474. independent of **actual** isolation level. When ``AUTOCOMMIT`` is
  475. in use, the database connection still has a "traditional" isolation
  476. mode in effect, that is typically one of the four values
  477. ``READ UNCOMMITTED``, ``READ COMMITTED``, ``REPEATABLE READ``,
  478. ``SERIALIZABLE``.
  479. Compare to the :attr:`_engine.Connection.default_isolation_level`
  480. accessor which returns the isolation level that is present on the
  481. database at initial connection time.
  482. .. seealso::
  483. :attr:`_engine.Connection.default_isolation_level`
  484. - view default level
  485. :paramref:`_sa.create_engine.isolation_level`
  486. - set per :class:`_engine.Engine` isolation level
  487. :paramref:`.Connection.execution_options.isolation_level`
  488. - set per :class:`_engine.Connection` isolation level
  489. """
  490. dbapi_connection = self.connection.dbapi_connection
  491. assert dbapi_connection is not None
  492. try:
  493. return self.dialect.get_isolation_level(dbapi_connection)
  494. except BaseException as e:
  495. self._handle_dbapi_exception(e, None, None, None, None)
  496. @property
  497. def default_isolation_level(self) -> Optional[IsolationLevel]:
  498. """The initial-connection time isolation level associated with the
  499. :class:`_engine.Dialect` in use.
  500. This value is independent of the
  501. :paramref:`.Connection.execution_options.isolation_level` and
  502. :paramref:`.Engine.execution_options.isolation_level` execution
  503. options, and is determined by the :class:`_engine.Dialect` when the
  504. first connection is created, by performing a SQL query against the
  505. database for the current isolation level before any additional commands
  506. have been emitted.
  507. Calling this accessor does not invoke any new SQL queries.
  508. .. seealso::
  509. :meth:`_engine.Connection.get_isolation_level`
  510. - view current actual isolation level
  511. :paramref:`_sa.create_engine.isolation_level`
  512. - set per :class:`_engine.Engine` isolation level
  513. :paramref:`.Connection.execution_options.isolation_level`
  514. - set per :class:`_engine.Connection` isolation level
  515. """
  516. return self.dialect.default_isolation_level
  517. def _invalid_transaction(self) -> NoReturn:
  518. raise exc.PendingRollbackError(
  519. "Can't reconnect until invalid %stransaction is rolled "
  520. "back. Please rollback() fully before proceeding"
  521. % ("savepoint " if self._nested_transaction is not None else ""),
  522. code="8s2b",
  523. )
  524. def _revalidate_connection(self) -> PoolProxiedConnection:
  525. if self.__can_reconnect and self.invalidated:
  526. if self._transaction is not None:
  527. self._invalid_transaction()
  528. self._dbapi_connection = self.engine.raw_connection()
  529. return self._dbapi_connection
  530. raise exc.ResourceClosedError("This Connection is closed")
  531. @property
  532. def info(self) -> _InfoType:
  533. """Info dictionary associated with the underlying DBAPI connection
  534. referred to by this :class:`_engine.Connection`, allowing user-defined
  535. data to be associated with the connection.
  536. The data here will follow along with the DBAPI connection including
  537. after it is returned to the connection pool and used again
  538. in subsequent instances of :class:`_engine.Connection`.
  539. """
  540. return self.connection.info
  541. def invalidate(self, exception: Optional[BaseException] = None) -> None:
  542. """Invalidate the underlying DBAPI connection associated with
  543. this :class:`_engine.Connection`.
  544. An attempt will be made to close the underlying DBAPI connection
  545. immediately; however if this operation fails, the error is logged
  546. but not raised. The connection is then discarded whether or not
  547. close() succeeded.
  548. Upon the next use (where "use" typically means using the
  549. :meth:`_engine.Connection.execute` method or similar),
  550. this :class:`_engine.Connection` will attempt to
  551. procure a new DBAPI connection using the services of the
  552. :class:`_pool.Pool` as a source of connectivity (e.g.
  553. a "reconnection").
  554. If a transaction was in progress (e.g. the
  555. :meth:`_engine.Connection.begin` method has been called) when
  556. :meth:`_engine.Connection.invalidate` method is called, at the DBAPI
  557. level all state associated with this transaction is lost, as
  558. the DBAPI connection is closed. The :class:`_engine.Connection`
  559. will not allow a reconnection to proceed until the
  560. :class:`.Transaction` object is ended, by calling the
  561. :meth:`.Transaction.rollback` method; until that point, any attempt at
  562. continuing to use the :class:`_engine.Connection` will raise an
  563. :class:`~sqlalchemy.exc.InvalidRequestError`.
  564. This is to prevent applications from accidentally
  565. continuing an ongoing transactional operations despite the
  566. fact that the transaction has been lost due to an
  567. invalidation.
  568. The :meth:`_engine.Connection.invalidate` method,
  569. just like auto-invalidation,
  570. will at the connection pool level invoke the
  571. :meth:`_events.PoolEvents.invalidate` event.
  572. :param exception: an optional ``Exception`` instance that's the
  573. reason for the invalidation. is passed along to event handlers
  574. and logging functions.
  575. .. seealso::
  576. :ref:`pool_connection_invalidation`
  577. """
  578. if self.invalidated:
  579. return
  580. if self.closed:
  581. raise exc.ResourceClosedError("This Connection is closed")
  582. if self._still_open_and_dbapi_connection_is_valid:
  583. pool_proxied_connection = self._dbapi_connection
  584. assert pool_proxied_connection is not None
  585. pool_proxied_connection.invalidate(exception)
  586. self._dbapi_connection = None
  587. def detach(self) -> None:
  588. """Detach the underlying DB-API connection from its connection pool.
  589. E.g.::
  590. with engine.connect() as conn:
  591. conn.detach()
  592. conn.execute(text("SET search_path TO schema1, schema2"))
  593. # work with connection
  594. # connection is fully closed (since we used "with:", can
  595. # also call .close())
  596. This :class:`_engine.Connection` instance will remain usable.
  597. When closed
  598. (or exited from a context manager context as above),
  599. the DB-API connection will be literally closed and not
  600. returned to its originating pool.
  601. This method can be used to insulate the rest of an application
  602. from a modified state on a connection (such as a transaction
  603. isolation level or similar).
  604. """
  605. if self.closed:
  606. raise exc.ResourceClosedError("This Connection is closed")
  607. pool_proxied_connection = self._dbapi_connection
  608. if pool_proxied_connection is None:
  609. raise exc.InvalidRequestError(
  610. "Can't detach an invalidated Connection"
  611. )
  612. pool_proxied_connection.detach()
  613. def _autobegin(self) -> None:
  614. if self._allow_autobegin and not self.__in_begin:
  615. self.begin()
  616. def begin(self) -> RootTransaction:
  617. """Begin a transaction prior to autobegin occurring.
  618. E.g.::
  619. with engine.connect() as conn:
  620. with conn.begin() as trans:
  621. conn.execute(table.insert(), {"username": "sandy"})
  622. The returned object is an instance of :class:`_engine.RootTransaction`.
  623. This object represents the "scope" of the transaction,
  624. which completes when either the :meth:`_engine.Transaction.rollback`
  625. or :meth:`_engine.Transaction.commit` method is called; the object
  626. also works as a context manager as illustrated above.
  627. The :meth:`_engine.Connection.begin` method begins a
  628. transaction that normally will be begun in any case when the connection
  629. is first used to execute a statement. The reason this method might be
  630. used would be to invoke the :meth:`_events.ConnectionEvents.begin`
  631. event at a specific time, or to organize code within the scope of a
  632. connection checkout in terms of context managed blocks, such as::
  633. with engine.connect() as conn:
  634. with conn.begin():
  635. conn.execute(...)
  636. conn.execute(...)
  637. with conn.begin():
  638. conn.execute(...)
  639. conn.execute(...)
  640. The above code is not fundamentally any different in its behavior than
  641. the following code which does not use
  642. :meth:`_engine.Connection.begin`; the below style is known
  643. as "commit as you go" style::
  644. with engine.connect() as conn:
  645. conn.execute(...)
  646. conn.execute(...)
  647. conn.commit()
  648. conn.execute(...)
  649. conn.execute(...)
  650. conn.commit()
  651. From a database point of view, the :meth:`_engine.Connection.begin`
  652. method does not emit any SQL or change the state of the underlying
  653. DBAPI connection in any way; the Python DBAPI does not have any
  654. concept of explicit transaction begin.
  655. .. seealso::
  656. :ref:`tutorial_working_with_transactions` - in the
  657. :ref:`unified_tutorial`
  658. :meth:`_engine.Connection.begin_nested` - use a SAVEPOINT
  659. :meth:`_engine.Connection.begin_twophase` -
  660. use a two phase /XID transaction
  661. :meth:`_engine.Engine.begin` - context manager available from
  662. :class:`_engine.Engine`
  663. """
  664. if self._transaction is None:
  665. self._transaction = RootTransaction(self)
  666. return self._transaction
  667. else:
  668. raise exc.InvalidRequestError(
  669. "This connection has already initialized a SQLAlchemy "
  670. "Transaction() object via begin() or autobegin; can't "
  671. "call begin() here unless rollback() or commit() "
  672. "is called first."
  673. )
  674. def begin_nested(self) -> NestedTransaction:
  675. """Begin a nested transaction (i.e. SAVEPOINT) and return a transaction
  676. handle that controls the scope of the SAVEPOINT.
  677. E.g.::
  678. with engine.begin() as connection:
  679. with connection.begin_nested():
  680. connection.execute(table.insert(), {"username": "sandy"})
  681. The returned object is an instance of
  682. :class:`_engine.NestedTransaction`, which includes transactional
  683. methods :meth:`_engine.NestedTransaction.commit` and
  684. :meth:`_engine.NestedTransaction.rollback`; for a nested transaction,
  685. these methods correspond to the operations "RELEASE SAVEPOINT <name>"
  686. and "ROLLBACK TO SAVEPOINT <name>". The name of the savepoint is local
  687. to the :class:`_engine.NestedTransaction` object and is generated
  688. automatically. Like any other :class:`_engine.Transaction`, the
  689. :class:`_engine.NestedTransaction` may be used as a context manager as
  690. illustrated above which will "release" or "rollback" corresponding to
  691. if the operation within the block were successful or raised an
  692. exception.
  693. Nested transactions require SAVEPOINT support in the underlying
  694. database, else the behavior is undefined. SAVEPOINT is commonly used to
  695. run operations within a transaction that may fail, while continuing the
  696. outer transaction. E.g.::
  697. from sqlalchemy import exc
  698. with engine.begin() as connection:
  699. trans = connection.begin_nested()
  700. try:
  701. connection.execute(table.insert(), {"username": "sandy"})
  702. trans.commit()
  703. except exc.IntegrityError: # catch for duplicate username
  704. trans.rollback() # rollback to savepoint
  705. # outer transaction continues
  706. connection.execute( ... )
  707. If :meth:`_engine.Connection.begin_nested` is called without first
  708. calling :meth:`_engine.Connection.begin` or
  709. :meth:`_engine.Engine.begin`, the :class:`_engine.Connection` object
  710. will "autobegin" the outer transaction first. This outer transaction
  711. may be committed using "commit-as-you-go" style, e.g.::
  712. with engine.connect() as connection: # begin() wasn't called
  713. with connection.begin_nested(): will auto-"begin()" first
  714. connection.execute( ... )
  715. # savepoint is released
  716. connection.execute( ... )
  717. # explicitly commit outer transaction
  718. connection.commit()
  719. # can continue working with connection here
  720. .. versionchanged:: 2.0
  721. :meth:`_engine.Connection.begin_nested` will now participate
  722. in the connection "autobegin" behavior that is new as of
  723. 2.0 / "future" style connections in 1.4.
  724. .. seealso::
  725. :meth:`_engine.Connection.begin`
  726. :ref:`session_begin_nested` - ORM support for SAVEPOINT
  727. """
  728. if self._transaction is None:
  729. self._autobegin()
  730. return NestedTransaction(self)
  731. def begin_twophase(self, xid: Optional[Any] = None) -> TwoPhaseTransaction:
  732. """Begin a two-phase or XA transaction and return a transaction
  733. handle.
  734. The returned object is an instance of :class:`.TwoPhaseTransaction`,
  735. which in addition to the methods provided by
  736. :class:`.Transaction`, also provides a
  737. :meth:`~.TwoPhaseTransaction.prepare` method.
  738. :param xid: the two phase transaction id. If not supplied, a
  739. random id will be generated.
  740. .. seealso::
  741. :meth:`_engine.Connection.begin`
  742. :meth:`_engine.Connection.begin_twophase`
  743. """
  744. if self._transaction is not None:
  745. raise exc.InvalidRequestError(
  746. "Cannot start a two phase transaction when a transaction "
  747. "is already in progress."
  748. )
  749. if xid is None:
  750. xid = self.engine.dialect.create_xid()
  751. return TwoPhaseTransaction(self, xid)
  752. def commit(self) -> None:
  753. """Commit the transaction that is currently in progress.
  754. This method commits the current transaction if one has been started.
  755. If no transaction was started, the method has no effect, assuming
  756. the connection is in a non-invalidated state.
  757. A transaction is begun on a :class:`_engine.Connection` automatically
  758. whenever a statement is first executed, or when the
  759. :meth:`_engine.Connection.begin` method is called.
  760. .. note:: The :meth:`_engine.Connection.commit` method only acts upon
  761. the primary database transaction that is linked to the
  762. :class:`_engine.Connection` object. It does not operate upon a
  763. SAVEPOINT that would have been invoked from the
  764. :meth:`_engine.Connection.begin_nested` method; for control of a
  765. SAVEPOINT, call :meth:`_engine.NestedTransaction.commit` on the
  766. :class:`_engine.NestedTransaction` that is returned by the
  767. :meth:`_engine.Connection.begin_nested` method itself.
  768. """
  769. if self._transaction:
  770. self._transaction.commit()
  771. def rollback(self) -> None:
  772. """Roll back the transaction that is currently in progress.
  773. This method rolls back the current transaction if one has been started.
  774. If no transaction was started, the method has no effect. If a
  775. transaction was started and the connection is in an invalidated state,
  776. the transaction is cleared using this method.
  777. A transaction is begun on a :class:`_engine.Connection` automatically
  778. whenever a statement is first executed, or when the
  779. :meth:`_engine.Connection.begin` method is called.
  780. .. note:: The :meth:`_engine.Connection.rollback` method only acts
  781. upon the primary database transaction that is linked to the
  782. :class:`_engine.Connection` object. It does not operate upon a
  783. SAVEPOINT that would have been invoked from the
  784. :meth:`_engine.Connection.begin_nested` method; for control of a
  785. SAVEPOINT, call :meth:`_engine.NestedTransaction.rollback` on the
  786. :class:`_engine.NestedTransaction` that is returned by the
  787. :meth:`_engine.Connection.begin_nested` method itself.
  788. """
  789. if self._transaction:
  790. self._transaction.rollback()
  791. def recover_twophase(self) -> List[Any]:
  792. return self.engine.dialect.do_recover_twophase(self)
  793. def rollback_prepared(self, xid: Any, recover: bool = False) -> None:
  794. self.engine.dialect.do_rollback_twophase(self, xid, recover=recover)
  795. def commit_prepared(self, xid: Any, recover: bool = False) -> None:
  796. self.engine.dialect.do_commit_twophase(self, xid, recover=recover)
  797. def in_transaction(self) -> bool:
  798. """Return True if a transaction is in progress."""
  799. return self._transaction is not None and self._transaction.is_active
  800. def in_nested_transaction(self) -> bool:
  801. """Return True if a transaction is in progress."""
  802. return (
  803. self._nested_transaction is not None
  804. and self._nested_transaction.is_active
  805. )
  806. def _is_autocommit_isolation(self) -> bool:
  807. opt_iso = self._execution_options.get("isolation_level", None)
  808. return bool(
  809. opt_iso == "AUTOCOMMIT"
  810. or (
  811. opt_iso is None
  812. and self.engine.dialect._on_connect_isolation_level
  813. == "AUTOCOMMIT"
  814. )
  815. )
  816. def _get_required_transaction(self) -> RootTransaction:
  817. trans = self._transaction
  818. if trans is None:
  819. raise exc.InvalidRequestError("connection is not in a transaction")
  820. return trans
  821. def _get_required_nested_transaction(self) -> NestedTransaction:
  822. trans = self._nested_transaction
  823. if trans is None:
  824. raise exc.InvalidRequestError(
  825. "connection is not in a nested transaction"
  826. )
  827. return trans
  828. def get_transaction(self) -> Optional[RootTransaction]:
  829. """Return the current root transaction in progress, if any.
  830. .. versionadded:: 1.4
  831. """
  832. return self._transaction
  833. def get_nested_transaction(self) -> Optional[NestedTransaction]:
  834. """Return the current nested transaction in progress, if any.
  835. .. versionadded:: 1.4
  836. """
  837. return self._nested_transaction
  838. def _begin_impl(self, transaction: RootTransaction) -> None:
  839. if self._echo:
  840. if self._is_autocommit_isolation():
  841. self._log_info(
  842. "BEGIN (implicit; DBAPI should not BEGIN due to "
  843. "autocommit mode)"
  844. )
  845. else:
  846. self._log_info("BEGIN (implicit)")
  847. self.__in_begin = True
  848. if self._has_events or self.engine._has_events:
  849. self.dispatch.begin(self)
  850. try:
  851. self.engine.dialect.do_begin(self.connection)
  852. except BaseException as e:
  853. self._handle_dbapi_exception(e, None, None, None, None)
  854. finally:
  855. self.__in_begin = False
  856. def _rollback_impl(self) -> None:
  857. if self._has_events or self.engine._has_events:
  858. self.dispatch.rollback(self)
  859. if self._still_open_and_dbapi_connection_is_valid:
  860. if self._echo:
  861. if self._is_autocommit_isolation():
  862. self._log_info(
  863. "ROLLBACK using DBAPI connection.rollback(), "
  864. "DBAPI should ignore due to autocommit mode"
  865. )
  866. else:
  867. self._log_info("ROLLBACK")
  868. try:
  869. self.engine.dialect.do_rollback(self.connection)
  870. except BaseException as e:
  871. self._handle_dbapi_exception(e, None, None, None, None)
  872. def _commit_impl(self) -> None:
  873. if self._has_events or self.engine._has_events:
  874. self.dispatch.commit(self)
  875. if self._echo:
  876. if self._is_autocommit_isolation():
  877. self._log_info(
  878. "COMMIT using DBAPI connection.commit(), "
  879. "DBAPI should ignore due to autocommit mode"
  880. )
  881. else:
  882. self._log_info("COMMIT")
  883. try:
  884. self.engine.dialect.do_commit(self.connection)
  885. except BaseException as e:
  886. self._handle_dbapi_exception(e, None, None, None, None)
  887. def _savepoint_impl(self, name: Optional[str] = None) -> str:
  888. if self._has_events or self.engine._has_events:
  889. self.dispatch.savepoint(self, name)
  890. if name is None:
  891. self.__savepoint_seq += 1
  892. name = "sa_savepoint_%s" % self.__savepoint_seq
  893. self.engine.dialect.do_savepoint(self, name)
  894. return name
  895. def _rollback_to_savepoint_impl(self, name: str) -> None:
  896. if self._has_events or self.engine._has_events:
  897. self.dispatch.rollback_savepoint(self, name, None)
  898. if self._still_open_and_dbapi_connection_is_valid:
  899. self.engine.dialect.do_rollback_to_savepoint(self, name)
  900. def _release_savepoint_impl(self, name: str) -> None:
  901. if self._has_events or self.engine._has_events:
  902. self.dispatch.release_savepoint(self, name, None)
  903. self.engine.dialect.do_release_savepoint(self, name)
  904. def _begin_twophase_impl(self, transaction: TwoPhaseTransaction) -> None:
  905. if self._echo:
  906. self._log_info("BEGIN TWOPHASE (implicit)")
  907. if self._has_events or self.engine._has_events:
  908. self.dispatch.begin_twophase(self, transaction.xid)
  909. self.__in_begin = True
  910. try:
  911. self.engine.dialect.do_begin_twophase(self, transaction.xid)
  912. except BaseException as e:
  913. self._handle_dbapi_exception(e, None, None, None, None)
  914. finally:
  915. self.__in_begin = False
  916. def _prepare_twophase_impl(self, xid: Any) -> None:
  917. if self._has_events or self.engine._has_events:
  918. self.dispatch.prepare_twophase(self, xid)
  919. assert isinstance(self._transaction, TwoPhaseTransaction)
  920. try:
  921. self.engine.dialect.do_prepare_twophase(self, xid)
  922. except BaseException as e:
  923. self._handle_dbapi_exception(e, None, None, None, None)
  924. def _rollback_twophase_impl(self, xid: Any, is_prepared: bool) -> None:
  925. if self._has_events or self.engine._has_events:
  926. self.dispatch.rollback_twophase(self, xid, is_prepared)
  927. if self._still_open_and_dbapi_connection_is_valid:
  928. assert isinstance(self._transaction, TwoPhaseTransaction)
  929. try:
  930. self.engine.dialect.do_rollback_twophase(
  931. self, xid, is_prepared
  932. )
  933. except BaseException as e:
  934. self._handle_dbapi_exception(e, None, None, None, None)
  935. def _commit_twophase_impl(self, xid: Any, is_prepared: bool) -> None:
  936. if self._has_events or self.engine._has_events:
  937. self.dispatch.commit_twophase(self, xid, is_prepared)
  938. assert isinstance(self._transaction, TwoPhaseTransaction)
  939. try:
  940. self.engine.dialect.do_commit_twophase(self, xid, is_prepared)
  941. except BaseException as e:
  942. self._handle_dbapi_exception(e, None, None, None, None)
  943. def close(self) -> None:
  944. """Close this :class:`_engine.Connection`.
  945. This results in a release of the underlying database
  946. resources, that is, the DBAPI connection referenced
  947. internally. The DBAPI connection is typically restored
  948. back to the connection-holding :class:`_pool.Pool` referenced
  949. by the :class:`_engine.Engine` that produced this
  950. :class:`_engine.Connection`. Any transactional state present on
  951. the DBAPI connection is also unconditionally released via
  952. the DBAPI connection's ``rollback()`` method, regardless
  953. of any :class:`.Transaction` object that may be
  954. outstanding with regards to this :class:`_engine.Connection`.
  955. This has the effect of also calling :meth:`_engine.Connection.rollback`
  956. if any transaction is in place.
  957. After :meth:`_engine.Connection.close` is called, the
  958. :class:`_engine.Connection` is permanently in a closed state,
  959. and will allow no further operations.
  960. """
  961. if self._transaction:
  962. self._transaction.close()
  963. skip_reset = True
  964. else:
  965. skip_reset = False
  966. if self._dbapi_connection is not None:
  967. conn = self._dbapi_connection
  968. # as we just closed the transaction, close the connection
  969. # pool connection without doing an additional reset
  970. if skip_reset:
  971. cast("_ConnectionFairy", conn)._close_special(
  972. transaction_reset=True
  973. )
  974. else:
  975. conn.close()
  976. # There is a slight chance that conn.close() may have
  977. # triggered an invalidation here in which case
  978. # _dbapi_connection would already be None, however usually
  979. # it will be non-None here and in a "closed" state.
  980. self._dbapi_connection = None
  981. self.__can_reconnect = False
  982. @overload
  983. def scalar(
  984. self,
  985. statement: TypedReturnsRows[Tuple[_T]],
  986. parameters: Optional[_CoreSingleExecuteParams] = None,
  987. *,
  988. execution_options: Optional[CoreExecuteOptionsParameter] = None,
  989. ) -> Optional[_T]:
  990. ...
  991. @overload
  992. def scalar(
  993. self,
  994. statement: Executable,
  995. parameters: Optional[_CoreSingleExecuteParams] = None,
  996. *,
  997. execution_options: Optional[CoreExecuteOptionsParameter] = None,
  998. ) -> Any:
  999. ...
  1000. def scalar(
  1001. self,
  1002. statement: Executable,
  1003. parameters: Optional[_CoreSingleExecuteParams] = None,
  1004. *,
  1005. execution_options: Optional[CoreExecuteOptionsParameter] = None,
  1006. ) -> Any:
  1007. r"""Executes a SQL statement construct and returns a scalar object.
  1008. This method is shorthand for invoking the
  1009. :meth:`_engine.Result.scalar` method after invoking the
  1010. :meth:`_engine.Connection.execute` method. Parameters are equivalent.
  1011. :return: a scalar Python value representing the first column of the
  1012. first row returned.
  1013. """
  1014. distilled_parameters = _distill_params_20(parameters)
  1015. try:
  1016. meth = statement._execute_on_scalar
  1017. except AttributeError as err:
  1018. raise exc.ObjectNotExecutableError(statement) from err
  1019. else:
  1020. return meth(
  1021. self,
  1022. distilled_parameters,
  1023. execution_options or NO_OPTIONS,
  1024. )
  1025. @overload
  1026. def scalars(
  1027. self,
  1028. statement: TypedReturnsRows[Tuple[_T]],
  1029. parameters: Optional[_CoreAnyExecuteParams] = None,
  1030. *,
  1031. execution_options: Optional[CoreExecuteOptionsParameter] = None,
  1032. ) -> ScalarResult[_T]:
  1033. ...
  1034. @overload
  1035. def scalars(
  1036. self,
  1037. statement: Executable,
  1038. parameters: Optional[_CoreAnyExecuteParams] = None,
  1039. *,
  1040. execution_options: Optional[CoreExecuteOptionsParameter] = None,
  1041. ) -> ScalarResult[Any]:
  1042. ...
  1043. def scalars(
  1044. self,
  1045. statement: Executable,
  1046. parameters: Optional[_CoreAnyExecuteParams] = None,
  1047. *,
  1048. execution_options: Optional[CoreExecuteOptionsParameter] = None,
  1049. ) -> ScalarResult[Any]:
  1050. """Executes and returns a scalar result set, which yields scalar values
  1051. from the first column of each row.
  1052. This method is equivalent to calling :meth:`_engine.Connection.execute`
  1053. to receive a :class:`_result.Result` object, then invoking the
  1054. :meth:`_result.Result.scalars` method to produce a
  1055. :class:`_result.ScalarResult` instance.
  1056. :return: a :class:`_result.ScalarResult`
  1057. .. versionadded:: 1.4.24
  1058. """
  1059. return self.execute(
  1060. statement, parameters, execution_options=execution_options
  1061. ).scalars()
  1062. @overload
  1063. def execute(
  1064. self,
  1065. statement: TypedReturnsRows[_T],
  1066. parameters: Optional[_CoreAnyExecuteParams] = None,
  1067. *,
  1068. execution_options: Optional[CoreExecuteOptionsParameter] = None,
  1069. ) -> CursorResult[_T]:
  1070. ...
  1071. @overload
  1072. def execute(
  1073. self,
  1074. statement: Executable,
  1075. parameters: Optional[_CoreAnyExecuteParams] = None,
  1076. *,
  1077. execution_options: Optional[CoreExecuteOptionsParameter] = None,
  1078. ) -> CursorResult[Any]:
  1079. ...
  1080. def execute(
  1081. self,
  1082. statement: Executable,
  1083. parameters: Optional[_CoreAnyExecuteParams] = None,
  1084. *,
  1085. execution_options: Optional[CoreExecuteOptionsParameter] = None,
  1086. ) -> CursorResult[Any]:
  1087. r"""Executes a SQL statement construct and returns a
  1088. :class:`_engine.CursorResult`.
  1089. :param statement: The statement to be executed. This is always
  1090. an object that is in both the :class:`_expression.ClauseElement` and
  1091. :class:`_expression.Executable` hierarchies, including:
  1092. * :class:`_expression.Select`
  1093. * :class:`_expression.Insert`, :class:`_expression.Update`,
  1094. :class:`_expression.Delete`
  1095. * :class:`_expression.TextClause` and
  1096. :class:`_expression.TextualSelect`
  1097. * :class:`_schema.DDL` and objects which inherit from
  1098. :class:`_schema.ExecutableDDLElement`
  1099. :param parameters: parameters which will be bound into the statement.
  1100. This may be either a dictionary of parameter names to values,
  1101. or a mutable sequence (e.g. a list) of dictionaries. When a
  1102. list of dictionaries is passed, the underlying statement execution
  1103. will make use of the DBAPI ``cursor.executemany()`` method.
  1104. When a single dictionary is passed, the DBAPI ``cursor.execute()``
  1105. method will be used.
  1106. :param execution_options: optional dictionary of execution options,
  1107. which will be associated with the statement execution. This
  1108. dictionary can provide a subset of the options that are accepted
  1109. by :meth:`_engine.Connection.execution_options`.
  1110. :return: a :class:`_engine.Result` object.
  1111. """
  1112. distilled_parameters = _distill_params_20(parameters)
  1113. try:
  1114. meth = statement._execute_on_connection
  1115. except AttributeError as err:
  1116. raise exc.ObjectNotExecutableError(statement) from err
  1117. else:
  1118. return meth(
  1119. self,
  1120. distilled_parameters,
  1121. execution_options or NO_OPTIONS,
  1122. )
  1123. def _execute_function(
  1124. self,
  1125. func: FunctionElement[Any],
  1126. distilled_parameters: _CoreMultiExecuteParams,
  1127. execution_options: CoreExecuteOptionsParameter,
  1128. ) -> CursorResult[Any]:
  1129. """Execute a sql.FunctionElement object."""
  1130. return self._execute_clauseelement(
  1131. func.select(), distilled_parameters, execution_options
  1132. )
  1133. def _execute_default(
  1134. self,
  1135. default: DefaultGenerator,
  1136. distilled_parameters: _CoreMultiExecuteParams,
  1137. execution_options: CoreExecuteOptionsParameter,
  1138. ) -> Any:
  1139. """Execute a schema.ColumnDefault object."""
  1140. execution_options = self._execution_options.merge_with(
  1141. execution_options
  1142. )
  1143. event_multiparams: Optional[_CoreMultiExecuteParams]
  1144. event_params: Optional[_CoreAnyExecuteParams]
  1145. # note for event handlers, the "distilled parameters" which is always
  1146. # a list of dicts is broken out into separate "multiparams" and
  1147. # "params" collections, which allows the handler to distinguish
  1148. # between an executemany and execute style set of parameters.
  1149. if self._has_events or self.engine._has_events:
  1150. (
  1151. default,
  1152. distilled_parameters,
  1153. event_multiparams,
  1154. event_params,
  1155. ) = self._invoke_before_exec_event(
  1156. default, distilled_parameters, execution_options
  1157. )
  1158. else:
  1159. event_multiparams = event_params = None
  1160. try:
  1161. conn = self._dbapi_connection
  1162. if conn is None:
  1163. conn = self._revalidate_connection()
  1164. dialect = self.dialect
  1165. ctx = dialect.execution_ctx_cls._init_default(
  1166. dialect, self, conn, execution_options
  1167. )
  1168. except (exc.PendingRollbackError, exc.ResourceClosedError):
  1169. raise
  1170. except BaseException as e:
  1171. self._handle_dbapi_exception(e, None, None, None, None)
  1172. ret = ctx._exec_default(None, default, None)
  1173. if self._has_events or self.engine._has_events:
  1174. self.dispatch.after_execute(
  1175. self,
  1176. default,
  1177. event_multiparams,
  1178. event_params,
  1179. execution_options,
  1180. ret,
  1181. )
  1182. return ret
  1183. def _execute_ddl(
  1184. self,
  1185. ddl: ExecutableDDLElement,
  1186. distilled_parameters: _CoreMultiExecuteParams,
  1187. execution_options: CoreExecuteOptionsParameter,
  1188. ) -> CursorResult[Any]:
  1189. """Execute a schema.DDL object."""
  1190. execution_options = ddl._execution_options.merge_with(
  1191. self._execution_options, execution_options
  1192. )
  1193. event_multiparams: Optional[_CoreMultiExecuteParams]
  1194. event_params: Optional[_CoreSingleExecuteParams]
  1195. if self._has_events or self.engine._has_events:
  1196. (
  1197. ddl,
  1198. distilled_parameters,
  1199. event_multiparams,
  1200. event_params,
  1201. ) = self._invoke_before_exec_event(
  1202. ddl, distilled_parameters, execution_options
  1203. )
  1204. else:
  1205. event_multiparams = event_params = None
  1206. exec_opts = self._execution_options.merge_with(execution_options)
  1207. schema_translate_map = exec_opts.get("schema_translate_map", None)
  1208. dialect = self.dialect
  1209. compiled = ddl.compile(
  1210. dialect=dialect, schema_translate_map=schema_translate_map
  1211. )
  1212. ret = self._execute_context(
  1213. dialect,
  1214. dialect.execution_ctx_cls._init_ddl,
  1215. compiled,
  1216. None,
  1217. execution_options,
  1218. compiled,
  1219. )
  1220. if self._has_events or self.engine._has_events:
  1221. self.dispatch.after_execute(
  1222. self,
  1223. ddl,
  1224. event_multiparams,
  1225. event_params,
  1226. execution_options,
  1227. ret,
  1228. )
  1229. return ret
  1230. def _invoke_before_exec_event(
  1231. self,
  1232. elem: Any,
  1233. distilled_params: _CoreMultiExecuteParams,
  1234. execution_options: _ExecuteOptions,
  1235. ) -> Tuple[
  1236. Any,
  1237. _CoreMultiExecuteParams,
  1238. _CoreMultiExecuteParams,
  1239. _CoreSingleExecuteParams,
  1240. ]:
  1241. event_multiparams: _CoreMultiExecuteParams
  1242. event_params: _CoreSingleExecuteParams
  1243. if len(distilled_params) == 1:
  1244. event_multiparams, event_params = [], distilled_params[0]
  1245. else:
  1246. event_multiparams, event_params = distilled_params, {}
  1247. for fn in self.dispatch.before_execute:
  1248. elem, event_multiparams, event_params = fn(
  1249. self,
  1250. elem,
  1251. event_multiparams,
  1252. event_params,
  1253. execution_options,
  1254. )
  1255. if event_multiparams:
  1256. distilled_params = list(event_multiparams)
  1257. if event_params:
  1258. raise exc.InvalidRequestError(
  1259. "Event handler can't return non-empty multiparams "
  1260. "and params at the same time"
  1261. )
  1262. elif event_params:
  1263. distilled_params = [event_params]
  1264. else:
  1265. distilled_params = []
  1266. return elem, distilled_params, event_multiparams, event_params
  1267. def _execute_clauseelement(
  1268. self,
  1269. elem: Executable,
  1270. distilled_parameters: _CoreMultiExecuteParams,
  1271. execution_options: CoreExecuteOptionsParameter,
  1272. ) -> CursorResult[Any]:
  1273. """Execute a sql.ClauseElement object."""
  1274. execution_options = elem._execution_options.merge_with(
  1275. self._execution_options, execution_options
  1276. )
  1277. has_events = self._has_events or self.engine._has_events
  1278. if has_events:
  1279. (
  1280. elem,
  1281. distilled_parameters,
  1282. event_multiparams,
  1283. event_params,
  1284. ) = self._invoke_before_exec_event(
  1285. elem, distilled_parameters, execution_options
  1286. )
  1287. if distilled_parameters:
  1288. # ensure we don't retain a link to the view object for keys()
  1289. # which links to the values, which we don't want to cache
  1290. keys = sorted(distilled_parameters[0])
  1291. for_executemany = len(distilled_parameters) > 1
  1292. else:
  1293. keys = []
  1294. for_executemany = False
  1295. dialect = self.dialect
  1296. schema_translate_map = execution_options.get(
  1297. "schema_translate_map", None
  1298. )
  1299. compiled_cache: Optional[CompiledCacheType] = execution_options.get(
  1300. "compiled_cache", self.engine._compiled_cache
  1301. )
  1302. compiled_sql, extracted_params, cache_hit = elem._compile_w_cache(
  1303. dialect=dialect,
  1304. compiled_cache=compiled_cache,
  1305. column_keys=keys,
  1306. for_executemany=for_executemany,
  1307. schema_translate_map=schema_translate_map,
  1308. linting=self.dialect.compiler_linting | compiler.WARN_LINTING,
  1309. )
  1310. ret = self._execute_context(
  1311. dialect,
  1312. dialect.execution_ctx_cls._init_compiled,
  1313. compiled_sql,
  1314. distilled_parameters,
  1315. execution_options,
  1316. compiled_sql,
  1317. distilled_parameters,
  1318. elem,
  1319. extracted_params,
  1320. cache_hit=cache_hit,
  1321. )
  1322. if has_events:
  1323. self.dispatch.after_execute(
  1324. self,
  1325. elem,
  1326. event_multiparams,
  1327. event_params,
  1328. execution_options,
  1329. ret,
  1330. )
  1331. return ret
  1332. def _execute_compiled(
  1333. self,
  1334. compiled: Compiled,
  1335. distilled_parameters: _CoreMultiExecuteParams,
  1336. execution_options: CoreExecuteOptionsParameter = _EMPTY_EXECUTION_OPTS,
  1337. ) -> CursorResult[Any]:
  1338. """Execute a sql.Compiled object.
  1339. TODO: why do we have this? likely deprecate or remove
  1340. """
  1341. execution_options = compiled.execution_options.merge_with(
  1342. self._execution_options, execution_options
  1343. )
  1344. if self._has_events or self.engine._has_events:
  1345. (
  1346. compiled,
  1347. distilled_parameters,
  1348. event_multiparams,
  1349. event_params,
  1350. ) = self._invoke_before_exec_event(
  1351. compiled, distilled_parameters, execution_options
  1352. )
  1353. dialect = self.dialect
  1354. ret = self._execute_context(
  1355. dialect,
  1356. dialect.execution_ctx_cls._init_compiled,
  1357. compiled,
  1358. distilled_parameters,
  1359. execution_options,
  1360. compiled,
  1361. distilled_parameters,
  1362. None,
  1363. None,
  1364. )
  1365. if self._has_events or self.engine._has_events:
  1366. self.dispatch.after_execute(
  1367. self,
  1368. compiled,
  1369. event_multiparams,
  1370. event_params,
  1371. execution_options,
  1372. ret,
  1373. )
  1374. return ret
  1375. def exec_driver_sql(
  1376. self,
  1377. statement: str,
  1378. parameters: Optional[_DBAPIAnyExecuteParams] = None,
  1379. execution_options: Optional[CoreExecuteOptionsParameter] = None,
  1380. ) -> CursorResult[Any]:
  1381. r"""Executes a string SQL statement on the DBAPI cursor directly,
  1382. without any SQL compilation steps.
  1383. This can be used to pass any string directly to the
  1384. ``cursor.execute()`` method of the DBAPI in use.
  1385. :param statement: The statement str to be executed. Bound parameters
  1386. must use the underlying DBAPI's paramstyle, such as "qmark",
  1387. "pyformat", "format", etc.
  1388. :param parameters: represent bound parameter values to be used in the
  1389. execution. The format is one of: a dictionary of named parameters,
  1390. a tuple of positional parameters, or a list containing either
  1391. dictionaries or tuples for multiple-execute support.
  1392. :return: a :class:`_engine.CursorResult`.
  1393. E.g. multiple dictionaries::
  1394. conn.exec_driver_sql(
  1395. "INSERT INTO table (id, value) VALUES (%(id)s, %(value)s)",
  1396. [{"id":1, "value":"v1"}, {"id":2, "value":"v2"}]
  1397. )
  1398. Single dictionary::
  1399. conn.exec_driver_sql(
  1400. "INSERT INTO table (id, value) VALUES (%(id)s, %(value)s)",
  1401. dict(id=1, value="v1")
  1402. )
  1403. Single tuple::
  1404. conn.exec_driver_sql(
  1405. "INSERT INTO table (id, value) VALUES (?, ?)",
  1406. (1, 'v1')
  1407. )
  1408. .. note:: The :meth:`_engine.Connection.exec_driver_sql` method does
  1409. not participate in the
  1410. :meth:`_events.ConnectionEvents.before_execute` and
  1411. :meth:`_events.ConnectionEvents.after_execute` events. To
  1412. intercept calls to :meth:`_engine.Connection.exec_driver_sql`, use
  1413. :meth:`_events.ConnectionEvents.before_cursor_execute` and
  1414. :meth:`_events.ConnectionEvents.after_cursor_execute`.
  1415. .. seealso::
  1416. :pep:`249`
  1417. """
  1418. distilled_parameters = _distill_raw_params(parameters)
  1419. execution_options = self._execution_options.merge_with(
  1420. execution_options
  1421. )
  1422. dialect = self.dialect
  1423. ret = self._execute_context(
  1424. dialect,
  1425. dialect.execution_ctx_cls._init_statement,
  1426. statement,
  1427. None,
  1428. execution_options,
  1429. statement,
  1430. distilled_parameters,
  1431. )
  1432. return ret
  1433. def _execute_context(
  1434. self,
  1435. dialect: Dialect,
  1436. constructor: Callable[..., ExecutionContext],
  1437. statement: Union[str, Compiled],
  1438. parameters: Optional[_AnyMultiExecuteParams],
  1439. execution_options: _ExecuteOptions,
  1440. *args: Any,
  1441. **kw: Any,
  1442. ) -> CursorResult[Any]:
  1443. """Create an :class:`.ExecutionContext` and execute, returning
  1444. a :class:`_engine.CursorResult`."""
  1445. if execution_options:
  1446. yp = execution_options.get("yield_per", None)
  1447. if yp:
  1448. execution_options = execution_options.union(
  1449. {"stream_results": True, "max_row_buffer": yp}
  1450. )
  1451. try:
  1452. conn = self._dbapi_connection
  1453. if conn is None:
  1454. conn = self._revalidate_connection()
  1455. context = constructor(
  1456. dialect, self, conn, execution_options, *args, **kw
  1457. )
  1458. except (exc.PendingRollbackError, exc.ResourceClosedError):
  1459. raise
  1460. except BaseException as e:
  1461. self._handle_dbapi_exception(
  1462. e, str(statement), parameters, None, None
  1463. )
  1464. if (
  1465. self._transaction
  1466. and not self._transaction.is_active
  1467. or (
  1468. self._nested_transaction
  1469. and not self._nested_transaction.is_active
  1470. )
  1471. ):
  1472. self._invalid_transaction()
  1473. elif self._trans_context_manager:
  1474. TransactionalContext._trans_ctx_check(self)
  1475. if self._transaction is None:
  1476. self._autobegin()
  1477. context.pre_exec()
  1478. if context.execute_style is ExecuteStyle.INSERTMANYVALUES:
  1479. return self._exec_insertmany_context(
  1480. dialect,
  1481. context,
  1482. )
  1483. else:
  1484. return self._exec_single_context(
  1485. dialect, context, statement, parameters
  1486. )
  1487. def _exec_single_context(
  1488. self,
  1489. dialect: Dialect,
  1490. context: ExecutionContext,
  1491. statement: Union[str, Compiled],
  1492. parameters: Optional[_AnyMultiExecuteParams],
  1493. ) -> CursorResult[Any]:
  1494. """continue the _execute_context() method for a single DBAPI
  1495. cursor.execute() or cursor.executemany() call.
  1496. """
  1497. if dialect.bind_typing is BindTyping.SETINPUTSIZES:
  1498. generic_setinputsizes = context._prepare_set_input_sizes()
  1499. if generic_setinputsizes:
  1500. try:
  1501. dialect.do_set_input_sizes(
  1502. context.cursor, generic_setinputsizes, context
  1503. )
  1504. except BaseException as e:
  1505. self._handle_dbapi_exception(
  1506. e, str(statement), parameters, None, context
  1507. )
  1508. cursor, str_statement, parameters = (
  1509. context.cursor,
  1510. context.statement,
  1511. context.parameters,
  1512. )
  1513. effective_parameters: Optional[_AnyExecuteParams]
  1514. if not context.executemany:
  1515. effective_parameters = parameters[0]
  1516. else:
  1517. effective_parameters = parameters
  1518. if self._has_events or self.engine._has_events:
  1519. for fn in self.dispatch.before_cursor_execute:
  1520. str_statement, effective_parameters = fn(
  1521. self,
  1522. cursor,
  1523. str_statement,
  1524. effective_parameters,
  1525. context,
  1526. context.executemany,
  1527. )
  1528. if self._echo:
  1529. self._log_info(str_statement)
  1530. stats = context._get_cache_stats()
  1531. if not self.engine.hide_parameters:
  1532. self._log_info(
  1533. "[%s] %r",
  1534. stats,
  1535. sql_util._repr_params(
  1536. effective_parameters,
  1537. batches=10,
  1538. ismulti=context.executemany,
  1539. ),
  1540. )
  1541. else:
  1542. self._log_info(
  1543. "[%s] [SQL parameters hidden due to hide_parameters=True]",
  1544. stats,
  1545. )
  1546. evt_handled: bool = False
  1547. try:
  1548. if context.execute_style is ExecuteStyle.EXECUTEMANY:
  1549. effective_parameters = cast(
  1550. "_CoreMultiExecuteParams", effective_parameters
  1551. )
  1552. if self.dialect._has_events:
  1553. for fn in self.dialect.dispatch.do_executemany:
  1554. if fn(
  1555. cursor,
  1556. str_statement,
  1557. effective_parameters,
  1558. context,
  1559. ):
  1560. evt_handled = True
  1561. break
  1562. if not evt_handled:
  1563. self.dialect.do_executemany(
  1564. cursor,
  1565. str_statement,
  1566. effective_parameters,
  1567. context,
  1568. )
  1569. elif not effective_parameters and context.no_parameters:
  1570. if self.dialect._has_events:
  1571. for fn in self.dialect.dispatch.do_execute_no_params:
  1572. if fn(cursor, str_statement, context):
  1573. evt_handled = True
  1574. break
  1575. if not evt_handled:
  1576. self.dialect.do_execute_no_params(
  1577. cursor, str_statement, context
  1578. )
  1579. else:
  1580. effective_parameters = cast(
  1581. "_CoreSingleExecuteParams", effective_parameters
  1582. )
  1583. if self.dialect._has_events:
  1584. for fn in self.dialect.dispatch.do_execute:
  1585. if fn(
  1586. cursor,
  1587. str_statement,
  1588. effective_parameters,
  1589. context,
  1590. ):
  1591. evt_handled = True
  1592. break
  1593. if not evt_handled:
  1594. self.dialect.do_execute(
  1595. cursor, str_statement, effective_parameters, context
  1596. )
  1597. if self._has_events or self.engine._has_events:
  1598. self.dispatch.after_cursor_execute(
  1599. self,
  1600. cursor,
  1601. str_statement,
  1602. effective_parameters,
  1603. context,
  1604. context.executemany,
  1605. )
  1606. context.post_exec()
  1607. result = context._setup_result_proxy()
  1608. except BaseException as e:
  1609. self._handle_dbapi_exception(
  1610. e, str_statement, effective_parameters, cursor, context
  1611. )
  1612. return result
  1613. def _exec_insertmany_context(
  1614. self,
  1615. dialect: Dialect,
  1616. context: ExecutionContext,
  1617. ) -> CursorResult[Any]:
  1618. """continue the _execute_context() method for an "insertmanyvalues"
  1619. operation, which will invoke DBAPI
  1620. cursor.execute() one or more times with individual log and
  1621. event hook calls.
  1622. """
  1623. if dialect.bind_typing is BindTyping.SETINPUTSIZES:
  1624. generic_setinputsizes = context._prepare_set_input_sizes()
  1625. else:
  1626. generic_setinputsizes = None
  1627. cursor, str_statement, parameters = (
  1628. context.cursor,
  1629. context.statement,
  1630. context.parameters,
  1631. )
  1632. effective_parameters = parameters
  1633. engine_events = self._has_events or self.engine._has_events
  1634. if self.dialect._has_events:
  1635. do_execute_dispatch: Iterable[
  1636. Any
  1637. ] = self.dialect.dispatch.do_execute
  1638. else:
  1639. do_execute_dispatch = ()
  1640. if self._echo:
  1641. stats = context._get_cache_stats() + " (insertmanyvalues)"
  1642. for imv_batch in dialect._deliver_insertmanyvalues_batches(
  1643. cursor,
  1644. str_statement,
  1645. effective_parameters,
  1646. generic_setinputsizes,
  1647. context,
  1648. ):
  1649. if imv_batch.processed_setinputsizes:
  1650. try:
  1651. dialect.do_set_input_sizes(
  1652. context.cursor,
  1653. imv_batch.processed_setinputsizes,
  1654. context,
  1655. )
  1656. except BaseException as e:
  1657. self._handle_dbapi_exception(
  1658. e,
  1659. sql_util._long_statement(imv_batch.replaced_statement),
  1660. imv_batch.replaced_parameters,
  1661. None,
  1662. context,
  1663. )
  1664. sub_stmt = imv_batch.replaced_statement
  1665. sub_params = imv_batch.replaced_parameters
  1666. if engine_events:
  1667. for fn in self.dispatch.before_cursor_execute:
  1668. sub_stmt, sub_params = fn(
  1669. self,
  1670. cursor,
  1671. sub_stmt,
  1672. sub_params,
  1673. context,
  1674. True,
  1675. )
  1676. if self._echo:
  1677. self._log_info(sql_util._long_statement(sub_stmt))
  1678. imv_stats = f""" {imv_batch.batchnum}/{
  1679. imv_batch.total_batches
  1680. } ({
  1681. 'ordered'
  1682. if imv_batch.rows_sorted else 'unordered'
  1683. }{
  1684. '; batch not supported'
  1685. if imv_batch.is_downgraded
  1686. else ''
  1687. })"""
  1688. if imv_batch.batchnum == 1:
  1689. stats += imv_stats
  1690. else:
  1691. stats = f"insertmanyvalues{imv_stats}"
  1692. if not self.engine.hide_parameters:
  1693. self._log_info(
  1694. "[%s] %r",
  1695. stats,
  1696. sql_util._repr_params(
  1697. sub_params,
  1698. batches=10,
  1699. ismulti=False,
  1700. ),
  1701. )
  1702. else:
  1703. self._log_info(
  1704. "[%s] [SQL parameters hidden due to "
  1705. "hide_parameters=True]",
  1706. stats,
  1707. )
  1708. try:
  1709. for fn in do_execute_dispatch:
  1710. if fn(
  1711. cursor,
  1712. sub_stmt,
  1713. sub_params,
  1714. context,
  1715. ):
  1716. break
  1717. else:
  1718. dialect.do_execute(
  1719. cursor,
  1720. sub_stmt,
  1721. sub_params,
  1722. context,
  1723. )
  1724. except BaseException as e:
  1725. self._handle_dbapi_exception(
  1726. e,
  1727. sql_util._long_statement(sub_stmt),
  1728. sub_params,
  1729. cursor,
  1730. context,
  1731. is_sub_exec=True,
  1732. )
  1733. if engine_events:
  1734. self.dispatch.after_cursor_execute(
  1735. self,
  1736. cursor,
  1737. str_statement,
  1738. effective_parameters,
  1739. context,
  1740. context.executemany,
  1741. )
  1742. try:
  1743. context.post_exec()
  1744. result = context._setup_result_proxy()
  1745. except BaseException as e:
  1746. self._handle_dbapi_exception(
  1747. e, str_statement, effective_parameters, cursor, context
  1748. )
  1749. return result
  1750. def _cursor_execute(
  1751. self,
  1752. cursor: DBAPICursor,
  1753. statement: str,
  1754. parameters: _DBAPISingleExecuteParams,
  1755. context: Optional[ExecutionContext] = None,
  1756. ) -> None:
  1757. """Execute a statement + params on the given cursor.
  1758. Adds appropriate logging and exception handling.
  1759. This method is used by DefaultDialect for special-case
  1760. executions, such as for sequences and column defaults.
  1761. The path of statement execution in the majority of cases
  1762. terminates at _execute_context().
  1763. """
  1764. if self._has_events or self.engine._has_events:
  1765. for fn in self.dispatch.before_cursor_execute:
  1766. statement, parameters = fn(
  1767. self, cursor, statement, parameters, context, False
  1768. )
  1769. if self._echo:
  1770. self._log_info(statement)
  1771. self._log_info("[raw sql] %r", parameters)
  1772. try:
  1773. for fn in (
  1774. ()
  1775. if not self.dialect._has_events
  1776. else self.dialect.dispatch.do_execute
  1777. ):
  1778. if fn(cursor, statement, parameters, context):
  1779. break
  1780. else:
  1781. self.dialect.do_execute(cursor, statement, parameters, context)
  1782. except BaseException as e:
  1783. self._handle_dbapi_exception(
  1784. e, statement, parameters, cursor, context
  1785. )
  1786. if self._has_events or self.engine._has_events:
  1787. self.dispatch.after_cursor_execute(
  1788. self, cursor, statement, parameters, context, False
  1789. )
  1790. def _safe_close_cursor(self, cursor: DBAPICursor) -> None:
  1791. """Close the given cursor, catching exceptions
  1792. and turning into log warnings.
  1793. """
  1794. try:
  1795. cursor.close()
  1796. except Exception:
  1797. # log the error through the connection pool's logger.
  1798. self.engine.pool.logger.error(
  1799. "Error closing cursor", exc_info=True
  1800. )
  1801. _reentrant_error = False
  1802. _is_disconnect = False
  1803. def _handle_dbapi_exception(
  1804. self,
  1805. e: BaseException,
  1806. statement: Optional[str],
  1807. parameters: Optional[_AnyExecuteParams],
  1808. cursor: Optional[DBAPICursor],
  1809. context: Optional[ExecutionContext],
  1810. is_sub_exec: bool = False,
  1811. ) -> NoReturn:
  1812. exc_info = sys.exc_info()
  1813. is_exit_exception = util.is_exit_exception(e)
  1814. if not self._is_disconnect:
  1815. self._is_disconnect = (
  1816. isinstance(e, self.dialect.loaded_dbapi.Error)
  1817. and not self.closed
  1818. and self.dialect.is_disconnect(
  1819. e,
  1820. self._dbapi_connection if not self.invalidated else None,
  1821. cursor,
  1822. )
  1823. ) or (is_exit_exception and not self.closed)
  1824. invalidate_pool_on_disconnect = not is_exit_exception
  1825. ismulti: bool = (
  1826. not is_sub_exec and context.executemany
  1827. if context is not None
  1828. else False
  1829. )
  1830. if self._reentrant_error:
  1831. raise exc.DBAPIError.instance(
  1832. statement,
  1833. parameters,
  1834. e,
  1835. self.dialect.loaded_dbapi.Error,
  1836. hide_parameters=self.engine.hide_parameters,
  1837. dialect=self.dialect,
  1838. ismulti=ismulti,
  1839. ).with_traceback(exc_info[2]) from e
  1840. self._reentrant_error = True
  1841. try:
  1842. # non-DBAPI error - if we already got a context,
  1843. # or there's no string statement, don't wrap it
  1844. should_wrap = isinstance(e, self.dialect.loaded_dbapi.Error) or (
  1845. statement is not None
  1846. and context is None
  1847. and not is_exit_exception
  1848. )
  1849. if should_wrap:
  1850. sqlalchemy_exception = exc.DBAPIError.instance(
  1851. statement,
  1852. parameters,
  1853. cast(Exception, e),
  1854. self.dialect.loaded_dbapi.Error,
  1855. hide_parameters=self.engine.hide_parameters,
  1856. connection_invalidated=self._is_disconnect,
  1857. dialect=self.dialect,
  1858. ismulti=ismulti,
  1859. )
  1860. else:
  1861. sqlalchemy_exception = None
  1862. newraise = None
  1863. if (self.dialect._has_events) and not self._execution_options.get(
  1864. "skip_user_error_events", False
  1865. ):
  1866. ctx = ExceptionContextImpl(
  1867. e,
  1868. sqlalchemy_exception,
  1869. self.engine,
  1870. self.dialect,
  1871. self,
  1872. cursor,
  1873. statement,
  1874. parameters,
  1875. context,
  1876. self._is_disconnect,
  1877. invalidate_pool_on_disconnect,
  1878. False,
  1879. )
  1880. for fn in self.dialect.dispatch.handle_error:
  1881. try:
  1882. # handler returns an exception;
  1883. # call next handler in a chain
  1884. per_fn = fn(ctx)
  1885. if per_fn is not None:
  1886. ctx.chained_exception = newraise = per_fn
  1887. except Exception as _raised:
  1888. # handler raises an exception - stop processing
  1889. newraise = _raised
  1890. break
  1891. if self._is_disconnect != ctx.is_disconnect:
  1892. self._is_disconnect = ctx.is_disconnect
  1893. if sqlalchemy_exception:
  1894. sqlalchemy_exception.connection_invalidated = (
  1895. ctx.is_disconnect
  1896. )
  1897. # set up potentially user-defined value for
  1898. # invalidate pool.
  1899. invalidate_pool_on_disconnect = (
  1900. ctx.invalidate_pool_on_disconnect
  1901. )
  1902. if should_wrap and context:
  1903. context.handle_dbapi_exception(e)
  1904. if not self._is_disconnect:
  1905. if cursor:
  1906. self._safe_close_cursor(cursor)
  1907. # "autorollback" was mostly relevant in 1.x series.
  1908. # It's very unlikely to reach here, as the connection
  1909. # does autobegin so when we are here, we are usually
  1910. # in an explicit / semi-explicit transaction.
  1911. # however we have a test which manufactures this
  1912. # scenario in any case using an event handler.
  1913. # test/engine/test_execute.py-> test_actual_autorollback
  1914. if not self.in_transaction():
  1915. self._rollback_impl()
  1916. if newraise:
  1917. raise newraise.with_traceback(exc_info[2]) from e
  1918. elif should_wrap:
  1919. assert sqlalchemy_exception is not None
  1920. raise sqlalchemy_exception.with_traceback(exc_info[2]) from e
  1921. else:
  1922. assert exc_info[1] is not None
  1923. raise exc_info[1].with_traceback(exc_info[2])
  1924. finally:
  1925. del self._reentrant_error
  1926. if self._is_disconnect:
  1927. del self._is_disconnect
  1928. if not self.invalidated:
  1929. dbapi_conn_wrapper = self._dbapi_connection
  1930. assert dbapi_conn_wrapper is not None
  1931. if invalidate_pool_on_disconnect:
  1932. self.engine.pool._invalidate(dbapi_conn_wrapper, e)
  1933. self.invalidate(e)
  1934. @classmethod
  1935. def _handle_dbapi_exception_noconnection(
  1936. cls,
  1937. e: BaseException,
  1938. dialect: Dialect,
  1939. engine: Optional[Engine] = None,
  1940. is_disconnect: Optional[bool] = None,
  1941. invalidate_pool_on_disconnect: bool = True,
  1942. is_pre_ping: bool = False,
  1943. ) -> NoReturn:
  1944. exc_info = sys.exc_info()
  1945. if is_disconnect is None:
  1946. is_disconnect = isinstance(
  1947. e, dialect.loaded_dbapi.Error
  1948. ) and dialect.is_disconnect(e, None, None)
  1949. should_wrap = isinstance(e, dialect.loaded_dbapi.Error)
  1950. if should_wrap:
  1951. sqlalchemy_exception = exc.DBAPIError.instance(
  1952. None,
  1953. None,
  1954. cast(Exception, e),
  1955. dialect.loaded_dbapi.Error,
  1956. hide_parameters=engine.hide_parameters
  1957. if engine is not None
  1958. else False,
  1959. connection_invalidated=is_disconnect,
  1960. dialect=dialect,
  1961. )
  1962. else:
  1963. sqlalchemy_exception = None
  1964. newraise = None
  1965. if dialect._has_events:
  1966. ctx = ExceptionContextImpl(
  1967. e,
  1968. sqlalchemy_exception,
  1969. engine,
  1970. dialect,
  1971. None,
  1972. None,
  1973. None,
  1974. None,
  1975. None,
  1976. is_disconnect,
  1977. invalidate_pool_on_disconnect,
  1978. is_pre_ping,
  1979. )
  1980. for fn in dialect.dispatch.handle_error:
  1981. try:
  1982. # handler returns an exception;
  1983. # call next handler in a chain
  1984. per_fn = fn(ctx)
  1985. if per_fn is not None:
  1986. ctx.chained_exception = newraise = per_fn
  1987. except Exception as _raised:
  1988. # handler raises an exception - stop processing
  1989. newraise = _raised
  1990. break
  1991. if sqlalchemy_exception and is_disconnect != ctx.is_disconnect:
  1992. sqlalchemy_exception.connection_invalidated = (
  1993. is_disconnect
  1994. ) = ctx.is_disconnect
  1995. if newraise:
  1996. raise newraise.with_traceback(exc_info[2]) from e
  1997. elif should_wrap:
  1998. assert sqlalchemy_exception is not None
  1999. raise sqlalchemy_exception.with_traceback(exc_info[2]) from e
  2000. else:
  2001. assert exc_info[1] is not None
  2002. raise exc_info[1].with_traceback(exc_info[2])
  2003. def _run_ddl_visitor(
  2004. self,
  2005. visitorcallable: Type[Union[SchemaGenerator, SchemaDropper]],
  2006. element: SchemaItem,
  2007. **kwargs: Any,
  2008. ) -> None:
  2009. """run a DDL visitor.
  2010. This method is only here so that the MockConnection can change the
  2011. options given to the visitor so that "checkfirst" is skipped.
  2012. """
  2013. visitorcallable(self.dialect, self, **kwargs).traverse_single(element)
  2014. class ExceptionContextImpl(ExceptionContext):
  2015. """Implement the :class:`.ExceptionContext` interface."""
  2016. __slots__ = (
  2017. "connection",
  2018. "engine",
  2019. "dialect",
  2020. "cursor",
  2021. "statement",
  2022. "parameters",
  2023. "original_exception",
  2024. "sqlalchemy_exception",
  2025. "chained_exception",
  2026. "execution_context",
  2027. "is_disconnect",
  2028. "invalidate_pool_on_disconnect",
  2029. "is_pre_ping",
  2030. )
  2031. def __init__(
  2032. self,
  2033. exception: BaseException,
  2034. sqlalchemy_exception: Optional[exc.StatementError],
  2035. engine: Optional[Engine],
  2036. dialect: Dialect,
  2037. connection: Optional[Connection],
  2038. cursor: Optional[DBAPICursor],
  2039. statement: Optional[str],
  2040. parameters: Optional[_DBAPIAnyExecuteParams],
  2041. context: Optional[ExecutionContext],
  2042. is_disconnect: bool,
  2043. invalidate_pool_on_disconnect: bool,
  2044. is_pre_ping: bool,
  2045. ):
  2046. self.engine = engine
  2047. self.dialect = dialect
  2048. self.connection = connection
  2049. self.sqlalchemy_exception = sqlalchemy_exception
  2050. self.original_exception = exception
  2051. self.execution_context = context
  2052. self.statement = statement
  2053. self.parameters = parameters
  2054. self.is_disconnect = is_disconnect
  2055. self.invalidate_pool_on_disconnect = invalidate_pool_on_disconnect
  2056. self.is_pre_ping = is_pre_ping
  2057. class Transaction(TransactionalContext):
  2058. """Represent a database transaction in progress.
  2059. The :class:`.Transaction` object is procured by
  2060. calling the :meth:`_engine.Connection.begin` method of
  2061. :class:`_engine.Connection`::
  2062. from sqlalchemy import create_engine
  2063. engine = create_engine("postgresql+psycopg2://scott:tiger@localhost/test")
  2064. connection = engine.connect()
  2065. trans = connection.begin()
  2066. connection.execute(text("insert into x (a, b) values (1, 2)"))
  2067. trans.commit()
  2068. The object provides :meth:`.rollback` and :meth:`.commit`
  2069. methods in order to control transaction boundaries. It
  2070. also implements a context manager interface so that
  2071. the Python ``with`` statement can be used with the
  2072. :meth:`_engine.Connection.begin` method::
  2073. with connection.begin():
  2074. connection.execute(text("insert into x (a, b) values (1, 2)"))
  2075. The Transaction object is **not** threadsafe.
  2076. .. seealso::
  2077. :meth:`_engine.Connection.begin`
  2078. :meth:`_engine.Connection.begin_twophase`
  2079. :meth:`_engine.Connection.begin_nested`
  2080. .. index::
  2081. single: thread safety; Transaction
  2082. """ # noqa
  2083. __slots__ = ()
  2084. _is_root: bool = False
  2085. is_active: bool
  2086. connection: Connection
  2087. def __init__(self, connection: Connection):
  2088. raise NotImplementedError()
  2089. @property
  2090. def _deactivated_from_connection(self) -> bool:
  2091. """True if this transaction is totally deactivated from the connection
  2092. and therefore can no longer affect its state.
  2093. """
  2094. raise NotImplementedError()
  2095. def _do_close(self) -> None:
  2096. raise NotImplementedError()
  2097. def _do_rollback(self) -> None:
  2098. raise NotImplementedError()
  2099. def _do_commit(self) -> None:
  2100. raise NotImplementedError()
  2101. @property
  2102. def is_valid(self) -> bool:
  2103. return self.is_active and not self.connection.invalidated
  2104. def close(self) -> None:
  2105. """Close this :class:`.Transaction`.
  2106. If this transaction is the base transaction in a begin/commit
  2107. nesting, the transaction will rollback(). Otherwise, the
  2108. method returns.
  2109. This is used to cancel a Transaction without affecting the scope of
  2110. an enclosing transaction.
  2111. """
  2112. try:
  2113. self._do_close()
  2114. finally:
  2115. assert not self.is_active
  2116. def rollback(self) -> None:
  2117. """Roll back this :class:`.Transaction`.
  2118. The implementation of this may vary based on the type of transaction in
  2119. use:
  2120. * For a simple database transaction (e.g. :class:`.RootTransaction`),
  2121. it corresponds to a ROLLBACK.
  2122. * For a :class:`.NestedTransaction`, it corresponds to a
  2123. "ROLLBACK TO SAVEPOINT" operation.
  2124. * For a :class:`.TwoPhaseTransaction`, DBAPI-specific methods for two
  2125. phase transactions may be used.
  2126. """
  2127. try:
  2128. self._do_rollback()
  2129. finally:
  2130. assert not self.is_active
  2131. def commit(self) -> None:
  2132. """Commit this :class:`.Transaction`.
  2133. The implementation of this may vary based on the type of transaction in
  2134. use:
  2135. * For a simple database transaction (e.g. :class:`.RootTransaction`),
  2136. it corresponds to a COMMIT.
  2137. * For a :class:`.NestedTransaction`, it corresponds to a
  2138. "RELEASE SAVEPOINT" operation.
  2139. * For a :class:`.TwoPhaseTransaction`, DBAPI-specific methods for two
  2140. phase transactions may be used.
  2141. """
  2142. try:
  2143. self._do_commit()
  2144. finally:
  2145. assert not self.is_active
  2146. def _get_subject(self) -> Connection:
  2147. return self.connection
  2148. def _transaction_is_active(self) -> bool:
  2149. return self.is_active
  2150. def _transaction_is_closed(self) -> bool:
  2151. return not self._deactivated_from_connection
  2152. def _rollback_can_be_called(self) -> bool:
  2153. # for RootTransaction / NestedTransaction, it's safe to call
  2154. # rollback() even if the transaction is deactive and no warnings
  2155. # will be emitted. tested in
  2156. # test_transaction.py -> test_no_rollback_in_deactive(?:_savepoint)?
  2157. return True
  2158. class RootTransaction(Transaction):
  2159. """Represent the "root" transaction on a :class:`_engine.Connection`.
  2160. This corresponds to the current "BEGIN/COMMIT/ROLLBACK" that's occurring
  2161. for the :class:`_engine.Connection`. The :class:`_engine.RootTransaction`
  2162. is created by calling upon the :meth:`_engine.Connection.begin` method, and
  2163. remains associated with the :class:`_engine.Connection` throughout its
  2164. active span. The current :class:`_engine.RootTransaction` in use is
  2165. accessible via the :attr:`_engine.Connection.get_transaction` method of
  2166. :class:`_engine.Connection`.
  2167. In :term:`2.0 style` use, the :class:`_engine.Connection` also employs
  2168. "autobegin" behavior that will create a new
  2169. :class:`_engine.RootTransaction` whenever a connection in a
  2170. non-transactional state is used to emit commands on the DBAPI connection.
  2171. The scope of the :class:`_engine.RootTransaction` in 2.0 style
  2172. use can be controlled using the :meth:`_engine.Connection.commit` and
  2173. :meth:`_engine.Connection.rollback` methods.
  2174. """
  2175. _is_root = True
  2176. __slots__ = ("connection", "is_active")
  2177. def __init__(self, connection: Connection):
  2178. assert connection._transaction is None
  2179. if connection._trans_context_manager:
  2180. TransactionalContext._trans_ctx_check(connection)
  2181. self.connection = connection
  2182. self._connection_begin_impl()
  2183. connection._transaction = self
  2184. self.is_active = True
  2185. def _deactivate_from_connection(self) -> None:
  2186. if self.is_active:
  2187. assert self.connection._transaction is self
  2188. self.is_active = False
  2189. elif self.connection._transaction is not self:
  2190. util.warn("transaction already deassociated from connection")
  2191. @property
  2192. def _deactivated_from_connection(self) -> bool:
  2193. return self.connection._transaction is not self
  2194. def _connection_begin_impl(self) -> None:
  2195. self.connection._begin_impl(self)
  2196. def _connection_rollback_impl(self) -> None:
  2197. self.connection._rollback_impl()
  2198. def _connection_commit_impl(self) -> None:
  2199. self.connection._commit_impl()
  2200. def _close_impl(self, try_deactivate: bool = False) -> None:
  2201. try:
  2202. if self.is_active:
  2203. self._connection_rollback_impl()
  2204. if self.connection._nested_transaction:
  2205. self.connection._nested_transaction._cancel()
  2206. finally:
  2207. if self.is_active or try_deactivate:
  2208. self._deactivate_from_connection()
  2209. if self.connection._transaction is self:
  2210. self.connection._transaction = None
  2211. assert not self.is_active
  2212. assert self.connection._transaction is not self
  2213. def _do_close(self) -> None:
  2214. self._close_impl()
  2215. def _do_rollback(self) -> None:
  2216. self._close_impl(try_deactivate=True)
  2217. def _do_commit(self) -> None:
  2218. if self.is_active:
  2219. assert self.connection._transaction is self
  2220. try:
  2221. self._connection_commit_impl()
  2222. finally:
  2223. # whether or not commit succeeds, cancel any
  2224. # nested transactions, make this transaction "inactive"
  2225. # and remove it as a reset agent
  2226. if self.connection._nested_transaction:
  2227. self.connection._nested_transaction._cancel()
  2228. self._deactivate_from_connection()
  2229. # ...however only remove as the connection's current transaction
  2230. # if commit succeeded. otherwise it stays on so that a rollback
  2231. # needs to occur.
  2232. self.connection._transaction = None
  2233. else:
  2234. if self.connection._transaction is self:
  2235. self.connection._invalid_transaction()
  2236. else:
  2237. raise exc.InvalidRequestError("This transaction is inactive")
  2238. assert not self.is_active
  2239. assert self.connection._transaction is not self
  2240. class NestedTransaction(Transaction):
  2241. """Represent a 'nested', or SAVEPOINT transaction.
  2242. The :class:`.NestedTransaction` object is created by calling the
  2243. :meth:`_engine.Connection.begin_nested` method of
  2244. :class:`_engine.Connection`.
  2245. When using :class:`.NestedTransaction`, the semantics of "begin" /
  2246. "commit" / "rollback" are as follows:
  2247. * the "begin" operation corresponds to the "BEGIN SAVEPOINT" command, where
  2248. the savepoint is given an explicit name that is part of the state
  2249. of this object.
  2250. * The :meth:`.NestedTransaction.commit` method corresponds to a
  2251. "RELEASE SAVEPOINT" operation, using the savepoint identifier associated
  2252. with this :class:`.NestedTransaction`.
  2253. * The :meth:`.NestedTransaction.rollback` method corresponds to a
  2254. "ROLLBACK TO SAVEPOINT" operation, using the savepoint identifier
  2255. associated with this :class:`.NestedTransaction`.
  2256. The rationale for mimicking the semantics of an outer transaction in
  2257. terms of savepoints so that code may deal with a "savepoint" transaction
  2258. and an "outer" transaction in an agnostic way.
  2259. .. seealso::
  2260. :ref:`session_begin_nested` - ORM version of the SAVEPOINT API.
  2261. """
  2262. __slots__ = ("connection", "is_active", "_savepoint", "_previous_nested")
  2263. _savepoint: str
  2264. def __init__(self, connection: Connection):
  2265. assert connection._transaction is not None
  2266. if connection._trans_context_manager:
  2267. TransactionalContext._trans_ctx_check(connection)
  2268. self.connection = connection
  2269. self._savepoint = self.connection._savepoint_impl()
  2270. self.is_active = True
  2271. self._previous_nested = connection._nested_transaction
  2272. connection._nested_transaction = self
  2273. def _deactivate_from_connection(self, warn: bool = True) -> None:
  2274. if self.connection._nested_transaction is self:
  2275. self.connection._nested_transaction = self._previous_nested
  2276. elif warn:
  2277. util.warn(
  2278. "nested transaction already deassociated from connection"
  2279. )
  2280. @property
  2281. def _deactivated_from_connection(self) -> bool:
  2282. return self.connection._nested_transaction is not self
  2283. def _cancel(self) -> None:
  2284. # called by RootTransaction when the outer transaction is
  2285. # committed, rolled back, or closed to cancel all savepoints
  2286. # without any action being taken
  2287. self.is_active = False
  2288. self._deactivate_from_connection()
  2289. if self._previous_nested:
  2290. self._previous_nested._cancel()
  2291. def _close_impl(
  2292. self, deactivate_from_connection: bool, warn_already_deactive: bool
  2293. ) -> None:
  2294. try:
  2295. if (
  2296. self.is_active
  2297. and self.connection._transaction
  2298. and self.connection._transaction.is_active
  2299. ):
  2300. self.connection._rollback_to_savepoint_impl(self._savepoint)
  2301. finally:
  2302. self.is_active = False
  2303. if deactivate_from_connection:
  2304. self._deactivate_from_connection(warn=warn_already_deactive)
  2305. assert not self.is_active
  2306. if deactivate_from_connection:
  2307. assert self.connection._nested_transaction is not self
  2308. def _do_close(self) -> None:
  2309. self._close_impl(True, False)
  2310. def _do_rollback(self) -> None:
  2311. self._close_impl(True, True)
  2312. def _do_commit(self) -> None:
  2313. if self.is_active:
  2314. try:
  2315. self.connection._release_savepoint_impl(self._savepoint)
  2316. finally:
  2317. # nested trans becomes inactive on failed release
  2318. # unconditionally. this prevents it from trying to
  2319. # emit SQL when it rolls back.
  2320. self.is_active = False
  2321. # but only de-associate from connection if it succeeded
  2322. self._deactivate_from_connection()
  2323. else:
  2324. if self.connection._nested_transaction is self:
  2325. self.connection._invalid_transaction()
  2326. else:
  2327. raise exc.InvalidRequestError(
  2328. "This nested transaction is inactive"
  2329. )
  2330. class TwoPhaseTransaction(RootTransaction):
  2331. """Represent a two-phase transaction.
  2332. A new :class:`.TwoPhaseTransaction` object may be procured
  2333. using the :meth:`_engine.Connection.begin_twophase` method.
  2334. The interface is the same as that of :class:`.Transaction`
  2335. with the addition of the :meth:`prepare` method.
  2336. """
  2337. __slots__ = ("xid", "_is_prepared")
  2338. xid: Any
  2339. def __init__(self, connection: Connection, xid: Any):
  2340. self._is_prepared = False
  2341. self.xid = xid
  2342. super().__init__(connection)
  2343. def prepare(self) -> None:
  2344. """Prepare this :class:`.TwoPhaseTransaction`.
  2345. After a PREPARE, the transaction can be committed.
  2346. """
  2347. if not self.is_active:
  2348. raise exc.InvalidRequestError("This transaction is inactive")
  2349. self.connection._prepare_twophase_impl(self.xid)
  2350. self._is_prepared = True
  2351. def _connection_begin_impl(self) -> None:
  2352. self.connection._begin_twophase_impl(self)
  2353. def _connection_rollback_impl(self) -> None:
  2354. self.connection._rollback_twophase_impl(self.xid, self._is_prepared)
  2355. def _connection_commit_impl(self) -> None:
  2356. self.connection._commit_twophase_impl(self.xid, self._is_prepared)
  2357. class Engine(
  2358. ConnectionEventsTarget, log.Identified, inspection.Inspectable["Inspector"]
  2359. ):
  2360. """
  2361. Connects a :class:`~sqlalchemy.pool.Pool` and
  2362. :class:`~sqlalchemy.engine.interfaces.Dialect` together to provide a
  2363. source of database connectivity and behavior.
  2364. An :class:`_engine.Engine` object is instantiated publicly using the
  2365. :func:`~sqlalchemy.create_engine` function.
  2366. .. seealso::
  2367. :doc:`/core/engines`
  2368. :ref:`connections_toplevel`
  2369. """
  2370. dispatch: dispatcher[ConnectionEventsTarget]
  2371. _compiled_cache: Optional[CompiledCacheType]
  2372. _execution_options: _ExecuteOptions = _EMPTY_EXECUTION_OPTS
  2373. _has_events: bool = False
  2374. _connection_cls: Type[Connection] = Connection
  2375. _sqla_logger_namespace: str = "sqlalchemy.engine.Engine"
  2376. _is_future: bool = False
  2377. _schema_translate_map: Optional[SchemaTranslateMapType] = None
  2378. _option_cls: Type[OptionEngine]
  2379. dialect: Dialect
  2380. pool: Pool
  2381. url: URL
  2382. hide_parameters: bool
  2383. def __init__(
  2384. self,
  2385. pool: Pool,
  2386. dialect: Dialect,
  2387. url: URL,
  2388. logging_name: Optional[str] = None,
  2389. echo: Optional[_EchoFlagType] = None,
  2390. query_cache_size: int = 500,
  2391. execution_options: Optional[Mapping[str, Any]] = None,
  2392. hide_parameters: bool = False,
  2393. ):
  2394. self.pool = pool
  2395. self.url = url
  2396. self.dialect = dialect
  2397. if logging_name:
  2398. self.logging_name = logging_name
  2399. self.echo = echo
  2400. self.hide_parameters = hide_parameters
  2401. if query_cache_size != 0:
  2402. self._compiled_cache = util.LRUCache(
  2403. query_cache_size, size_alert=self._lru_size_alert
  2404. )
  2405. else:
  2406. self._compiled_cache = None
  2407. log.instance_logger(self, echoflag=echo)
  2408. if execution_options:
  2409. self.update_execution_options(**execution_options)
  2410. def _lru_size_alert(self, cache: util.LRUCache[Any, Any]) -> None:
  2411. if self._should_log_info():
  2412. self.logger.info(
  2413. "Compiled cache size pruning from %d items to %d. "
  2414. "Increase cache size to reduce the frequency of pruning.",
  2415. len(cache),
  2416. cache.capacity,
  2417. )
  2418. @property
  2419. def engine(self) -> Engine:
  2420. """Returns this :class:`.Engine`.
  2421. Used for legacy schemes that accept :class:`.Connection` /
  2422. :class:`.Engine` objects within the same variable.
  2423. """
  2424. return self
  2425. def clear_compiled_cache(self) -> None:
  2426. """Clear the compiled cache associated with the dialect.
  2427. This applies **only** to the built-in cache that is established
  2428. via the :paramref:`_engine.create_engine.query_cache_size` parameter.
  2429. It will not impact any dictionary caches that were passed via the
  2430. :paramref:`.Connection.execution_options.query_cache` parameter.
  2431. .. versionadded:: 1.4
  2432. """
  2433. if self._compiled_cache:
  2434. self._compiled_cache.clear()
  2435. def update_execution_options(self, **opt: Any) -> None:
  2436. r"""Update the default execution_options dictionary
  2437. of this :class:`_engine.Engine`.
  2438. The given keys/values in \**opt are added to the
  2439. default execution options that will be used for
  2440. all connections. The initial contents of this dictionary
  2441. can be sent via the ``execution_options`` parameter
  2442. to :func:`_sa.create_engine`.
  2443. .. seealso::
  2444. :meth:`_engine.Connection.execution_options`
  2445. :meth:`_engine.Engine.execution_options`
  2446. """
  2447. self.dispatch.set_engine_execution_options(self, opt)
  2448. self._execution_options = self._execution_options.union(opt)
  2449. self.dialect.set_engine_execution_options(self, opt)
  2450. @overload
  2451. def execution_options(
  2452. self,
  2453. *,
  2454. compiled_cache: Optional[CompiledCacheType] = ...,
  2455. logging_token: str = ...,
  2456. isolation_level: IsolationLevel = ...,
  2457. insertmanyvalues_page_size: int = ...,
  2458. schema_translate_map: Optional[SchemaTranslateMapType] = ...,
  2459. **opt: Any,
  2460. ) -> OptionEngine:
  2461. ...
  2462. @overload
  2463. def execution_options(self, **opt: Any) -> OptionEngine:
  2464. ...
  2465. def execution_options(self, **opt: Any) -> OptionEngine:
  2466. """Return a new :class:`_engine.Engine` that will provide
  2467. :class:`_engine.Connection` objects with the given execution options.
  2468. The returned :class:`_engine.Engine` remains related to the original
  2469. :class:`_engine.Engine` in that it shares the same connection pool and
  2470. other state:
  2471. * The :class:`_pool.Pool` used by the new :class:`_engine.Engine`
  2472. is the
  2473. same instance. The :meth:`_engine.Engine.dispose`
  2474. method will replace
  2475. the connection pool instance for the parent engine as well
  2476. as this one.
  2477. * Event listeners are "cascaded" - meaning, the new
  2478. :class:`_engine.Engine`
  2479. inherits the events of the parent, and new events can be associated
  2480. with the new :class:`_engine.Engine` individually.
  2481. * The logging configuration and logging_name is copied from the parent
  2482. :class:`_engine.Engine`.
  2483. The intent of the :meth:`_engine.Engine.execution_options` method is
  2484. to implement schemes where multiple :class:`_engine.Engine`
  2485. objects refer to the same connection pool, but are differentiated
  2486. by options that affect some execution-level behavior for each
  2487. engine. One such example is breaking into separate "reader" and
  2488. "writer" :class:`_engine.Engine` instances, where one
  2489. :class:`_engine.Engine`
  2490. has a lower :term:`isolation level` setting configured or is even
  2491. transaction-disabled using "autocommit". An example of this
  2492. configuration is at :ref:`dbapi_autocommit_multiple`.
  2493. Another example is one that
  2494. uses a custom option ``shard_id`` which is consumed by an event
  2495. to change the current schema on a database connection::
  2496. from sqlalchemy import event
  2497. from sqlalchemy.engine import Engine
  2498. primary_engine = create_engine("mysql+mysqldb://")
  2499. shard1 = primary_engine.execution_options(shard_id="shard1")
  2500. shard2 = primary_engine.execution_options(shard_id="shard2")
  2501. shards = {"default": "base", "shard_1": "db1", "shard_2": "db2"}
  2502. @event.listens_for(Engine, "before_cursor_execute")
  2503. def _switch_shard(conn, cursor, stmt,
  2504. params, context, executemany):
  2505. shard_id = conn.get_execution_options().get('shard_id', "default")
  2506. current_shard = conn.info.get("current_shard", None)
  2507. if current_shard != shard_id:
  2508. cursor.execute("use %s" % shards[shard_id])
  2509. conn.info["current_shard"] = shard_id
  2510. The above recipe illustrates two :class:`_engine.Engine` objects that
  2511. will each serve as factories for :class:`_engine.Connection` objects
  2512. that have pre-established "shard_id" execution options present. A
  2513. :meth:`_events.ConnectionEvents.before_cursor_execute` event handler
  2514. then interprets this execution option to emit a MySQL ``use`` statement
  2515. to switch databases before a statement execution, while at the same
  2516. time keeping track of which database we've established using the
  2517. :attr:`_engine.Connection.info` dictionary.
  2518. .. seealso::
  2519. :meth:`_engine.Connection.execution_options`
  2520. - update execution options
  2521. on a :class:`_engine.Connection` object.
  2522. :meth:`_engine.Engine.update_execution_options`
  2523. - update the execution
  2524. options for a given :class:`_engine.Engine` in place.
  2525. :meth:`_engine.Engine.get_execution_options`
  2526. """ # noqa: E501
  2527. return self._option_cls(self, opt)
  2528. def get_execution_options(self) -> _ExecuteOptions:
  2529. """Get the non-SQL options which will take effect during execution.
  2530. .. versionadded: 1.3
  2531. .. seealso::
  2532. :meth:`_engine.Engine.execution_options`
  2533. """
  2534. return self._execution_options
  2535. @property
  2536. def name(self) -> str:
  2537. """String name of the :class:`~sqlalchemy.engine.interfaces.Dialect`
  2538. in use by this :class:`Engine`.
  2539. """
  2540. return self.dialect.name
  2541. @property
  2542. def driver(self) -> str:
  2543. """Driver name of the :class:`~sqlalchemy.engine.interfaces.Dialect`
  2544. in use by this :class:`Engine`.
  2545. """
  2546. return self.dialect.driver
  2547. echo = log.echo_property()
  2548. def __repr__(self) -> str:
  2549. return "Engine(%r)" % (self.url,)
  2550. def dispose(self, close: bool = True) -> None:
  2551. """Dispose of the connection pool used by this
  2552. :class:`_engine.Engine`.
  2553. A new connection pool is created immediately after the old one has been
  2554. disposed. The previous connection pool is disposed either actively, by
  2555. closing out all currently checked-in connections in that pool, or
  2556. passively, by losing references to it but otherwise not closing any
  2557. connections. The latter strategy is more appropriate for an initializer
  2558. in a forked Python process.
  2559. :param close: if left at its default of ``True``, has the
  2560. effect of fully closing all **currently checked in**
  2561. database connections. Connections that are still checked out
  2562. will **not** be closed, however they will no longer be associated
  2563. with this :class:`_engine.Engine`,
  2564. so when they are closed individually, eventually the
  2565. :class:`_pool.Pool` which they are associated with will
  2566. be garbage collected and they will be closed out fully, if
  2567. not already closed on checkin.
  2568. If set to ``False``, the previous connection pool is de-referenced,
  2569. and otherwise not touched in any way.
  2570. .. versionadded:: 1.4.33 Added the :paramref:`.Engine.dispose.close`
  2571. parameter to allow the replacement of a connection pool in a child
  2572. process without interfering with the connections used by the parent
  2573. process.
  2574. .. seealso::
  2575. :ref:`engine_disposal`
  2576. :ref:`pooling_multiprocessing`
  2577. """
  2578. if close:
  2579. self.pool.dispose()
  2580. self.pool = self.pool.recreate()
  2581. self.dispatch.engine_disposed(self)
  2582. @contextlib.contextmanager
  2583. def _optional_conn_ctx_manager(
  2584. self, connection: Optional[Connection] = None
  2585. ) -> Iterator[Connection]:
  2586. if connection is None:
  2587. with self.connect() as conn:
  2588. yield conn
  2589. else:
  2590. yield connection
  2591. @contextlib.contextmanager
  2592. def begin(self) -> Iterator[Connection]:
  2593. """Return a context manager delivering a :class:`_engine.Connection`
  2594. with a :class:`.Transaction` established.
  2595. E.g.::
  2596. with engine.begin() as conn:
  2597. conn.execute(
  2598. text("insert into table (x, y, z) values (1, 2, 3)")
  2599. )
  2600. conn.execute(text("my_special_procedure(5)"))
  2601. Upon successful operation, the :class:`.Transaction`
  2602. is committed. If an error is raised, the :class:`.Transaction`
  2603. is rolled back.
  2604. .. seealso::
  2605. :meth:`_engine.Engine.connect` - procure a
  2606. :class:`_engine.Connection` from
  2607. an :class:`_engine.Engine`.
  2608. :meth:`_engine.Connection.begin` - start a :class:`.Transaction`
  2609. for a particular :class:`_engine.Connection`.
  2610. """
  2611. with self.connect() as conn:
  2612. with conn.begin():
  2613. yield conn
  2614. def _run_ddl_visitor(
  2615. self,
  2616. visitorcallable: Type[Union[SchemaGenerator, SchemaDropper]],
  2617. element: SchemaItem,
  2618. **kwargs: Any,
  2619. ) -> None:
  2620. with self.begin() as conn:
  2621. conn._run_ddl_visitor(visitorcallable, element, **kwargs)
  2622. def connect(self) -> Connection:
  2623. """Return a new :class:`_engine.Connection` object.
  2624. The :class:`_engine.Connection` acts as a Python context manager, so
  2625. the typical use of this method looks like::
  2626. with engine.connect() as connection:
  2627. connection.execute(text("insert into table values ('foo')"))
  2628. connection.commit()
  2629. Where above, after the block is completed, the connection is "closed"
  2630. and its underlying DBAPI resources are returned to the connection pool.
  2631. This also has the effect of rolling back any transaction that
  2632. was explicitly begun or was begun via autobegin, and will
  2633. emit the :meth:`_events.ConnectionEvents.rollback` event if one was
  2634. started and is still in progress.
  2635. .. seealso::
  2636. :meth:`_engine.Engine.begin`
  2637. """
  2638. return self._connection_cls(self)
  2639. def raw_connection(self) -> PoolProxiedConnection:
  2640. """Return a "raw" DBAPI connection from the connection pool.
  2641. The returned object is a proxied version of the DBAPI
  2642. connection object used by the underlying driver in use.
  2643. The object will have all the same behavior as the real DBAPI
  2644. connection, except that its ``close()`` method will result in the
  2645. connection being returned to the pool, rather than being closed
  2646. for real.
  2647. This method provides direct DBAPI connection access for
  2648. special situations when the API provided by
  2649. :class:`_engine.Connection`
  2650. is not needed. When a :class:`_engine.Connection` object is already
  2651. present, the DBAPI connection is available using
  2652. the :attr:`_engine.Connection.connection` accessor.
  2653. .. seealso::
  2654. :ref:`dbapi_connections`
  2655. """
  2656. return self.pool.connect()
  2657. class OptionEngineMixin(log.Identified):
  2658. _sa_propagate_class_events = False
  2659. dispatch: dispatcher[ConnectionEventsTarget]
  2660. _compiled_cache: Optional[CompiledCacheType]
  2661. dialect: Dialect
  2662. pool: Pool
  2663. url: URL
  2664. hide_parameters: bool
  2665. echo: log.echo_property
  2666. def __init__(
  2667. self, proxied: Engine, execution_options: CoreExecuteOptionsParameter
  2668. ):
  2669. self._proxied = proxied
  2670. self.url = proxied.url
  2671. self.dialect = proxied.dialect
  2672. self.logging_name = proxied.logging_name
  2673. self.echo = proxied.echo
  2674. self._compiled_cache = proxied._compiled_cache
  2675. self.hide_parameters = proxied.hide_parameters
  2676. log.instance_logger(self, echoflag=self.echo)
  2677. # note: this will propagate events that are assigned to the parent
  2678. # engine after this OptionEngine is created. Since we share
  2679. # the events of the parent we also disallow class-level events
  2680. # to apply to the OptionEngine class directly.
  2681. #
  2682. # the other way this can work would be to transfer existing
  2683. # events only, using:
  2684. # self.dispatch._update(proxied.dispatch)
  2685. #
  2686. # that might be more appropriate however it would be a behavioral
  2687. # change for logic that assigns events to the parent engine and
  2688. # would like it to take effect for the already-created sub-engine.
  2689. self.dispatch = self.dispatch._join(proxied.dispatch)
  2690. self._execution_options = proxied._execution_options
  2691. self.update_execution_options(**execution_options)
  2692. def update_execution_options(self, **opt: Any) -> None:
  2693. raise NotImplementedError()
  2694. if not typing.TYPE_CHECKING:
  2695. # https://github.com/python/typing/discussions/1095
  2696. @property
  2697. def pool(self) -> Pool:
  2698. return self._proxied.pool
  2699. @pool.setter
  2700. def pool(self, pool: Pool) -> None:
  2701. self._proxied.pool = pool
  2702. @property
  2703. def _has_events(self) -> bool:
  2704. return self._proxied._has_events or self.__dict__.get(
  2705. "_has_events", False
  2706. )
  2707. @_has_events.setter
  2708. def _has_events(self, value: bool) -> None:
  2709. self.__dict__["_has_events"] = value
  2710. class OptionEngine(OptionEngineMixin, Engine):
  2711. def update_execution_options(self, **opt: Any) -> None:
  2712. Engine.update_execution_options(self, **opt)
  2713. Engine._option_cls = OptionEngine