base.py 120 KB

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