interfaces.py 113 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471
  1. # engine/interfaces.py
  2. # Copyright (C) 2005-2026 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. """Define core interfaces used by the engine system."""
  8. from __future__ import annotations
  9. from enum import Enum
  10. from typing import Any
  11. from typing import Awaitable
  12. from typing import Callable
  13. from typing import ClassVar
  14. from typing import Collection
  15. from typing import Dict
  16. from typing import Iterable
  17. from typing import Iterator
  18. from typing import List
  19. from typing import Mapping
  20. from typing import MutableMapping
  21. from typing import Optional
  22. from typing import Sequence
  23. from typing import Set
  24. from typing import Tuple
  25. from typing import Type
  26. from typing import TYPE_CHECKING
  27. from typing import TypeVar
  28. from typing import Union
  29. from .. import util
  30. from ..event import EventTarget
  31. from ..pool import Pool
  32. from ..pool import PoolProxiedConnection as PoolProxiedConnection
  33. from ..sql.compiler import Compiled as Compiled
  34. from ..sql.compiler import Compiled # noqa
  35. from ..sql.compiler import TypeCompiler as TypeCompiler
  36. from ..sql.compiler import TypeCompiler # noqa
  37. from ..util import immutabledict
  38. from ..util.concurrency import await_only
  39. from ..util.typing import Literal
  40. from ..util.typing import NotRequired
  41. from ..util.typing import Protocol
  42. from ..util.typing import TypedDict
  43. if TYPE_CHECKING:
  44. from .base import Connection
  45. from .base import Engine
  46. from .cursor import CursorResult
  47. from .url import URL
  48. from ..connectors.asyncio import AsyncIODBAPIConnection
  49. from ..event import _ListenerFnType
  50. from ..event import dispatcher
  51. from ..exc import StatementError
  52. from ..sql import Executable
  53. from ..sql.compiler import _InsertManyValuesBatch
  54. from ..sql.compiler import DDLCompiler
  55. from ..sql.compiler import IdentifierPreparer
  56. from ..sql.compiler import InsertmanyvaluesSentinelOpts
  57. from ..sql.compiler import Linting
  58. from ..sql.compiler import SQLCompiler
  59. from ..sql.elements import BindParameter
  60. from ..sql.elements import ClauseElement
  61. from ..sql.schema import Column
  62. from ..sql.schema import DefaultGenerator
  63. from ..sql.schema import SchemaItem
  64. from ..sql.schema import Sequence as Sequence_SchemaItem
  65. from ..sql.sqltypes import Integer
  66. from ..sql.type_api import _TypeMemoDict
  67. from ..sql.type_api import TypeEngine
  68. from ..util.langhelpers import generic_fn_descriptor
  69. ConnectArgsType = Tuple[Sequence[str], MutableMapping[str, Any]]
  70. _T = TypeVar("_T", bound="Any")
  71. class CacheStats(Enum):
  72. CACHE_HIT = 0
  73. CACHE_MISS = 1
  74. CACHING_DISABLED = 2
  75. NO_CACHE_KEY = 3
  76. NO_DIALECT_SUPPORT = 4
  77. class ExecuteStyle(Enum):
  78. """indicates the :term:`DBAPI` cursor method that will be used to invoke
  79. a statement."""
  80. EXECUTE = 0
  81. """indicates cursor.execute() will be used"""
  82. EXECUTEMANY = 1
  83. """indicates cursor.executemany() will be used."""
  84. INSERTMANYVALUES = 2
  85. """indicates cursor.execute() will be used with an INSERT where the
  86. VALUES expression will be expanded to accommodate for multiple
  87. parameter sets
  88. .. seealso::
  89. :ref:`engine_insertmanyvalues`
  90. """
  91. class DBAPIModule(Protocol):
  92. class Error(Exception):
  93. def __getattr__(self, key: str) -> Any: ...
  94. class OperationalError(Error):
  95. pass
  96. class InterfaceError(Error):
  97. pass
  98. class IntegrityError(Error):
  99. pass
  100. def __getattr__(self, key: str) -> Any: ...
  101. class DBAPIConnection(Protocol):
  102. """protocol representing a :pep:`249` database connection.
  103. .. versionadded:: 2.0
  104. .. seealso::
  105. `Connection Objects <https://www.python.org/dev/peps/pep-0249/#connection-objects>`_
  106. - in :pep:`249`
  107. """ # noqa: E501
  108. def close(self) -> None: ...
  109. def commit(self) -> None: ...
  110. def cursor(self, *args: Any, **kwargs: Any) -> DBAPICursor: ...
  111. def rollback(self) -> None: ...
  112. def __getattr__(self, key: str) -> Any: ...
  113. def __setattr__(self, key: str, value: Any) -> None: ...
  114. class DBAPIType(Protocol):
  115. """protocol representing a :pep:`249` database type.
  116. .. versionadded:: 2.0
  117. .. seealso::
  118. `Type Objects <https://www.python.org/dev/peps/pep-0249/#type-objects>`_
  119. - in :pep:`249`
  120. """ # noqa: E501
  121. class DBAPICursor(Protocol):
  122. """protocol representing a :pep:`249` database cursor.
  123. .. versionadded:: 2.0
  124. .. seealso::
  125. `Cursor Objects <https://www.python.org/dev/peps/pep-0249/#cursor-objects>`_
  126. - in :pep:`249`
  127. """ # noqa: E501
  128. @property
  129. def description(
  130. self,
  131. ) -> _DBAPICursorDescription:
  132. """The description attribute of the Cursor.
  133. .. seealso::
  134. `cursor.description <https://www.python.org/dev/peps/pep-0249/#description>`_
  135. - in :pep:`249`
  136. """ # noqa: E501
  137. ...
  138. @property
  139. def rowcount(self) -> int: ...
  140. arraysize: int
  141. lastrowid: int
  142. def close(self) -> None: ...
  143. def execute(
  144. self,
  145. operation: Any,
  146. parameters: Optional[_DBAPISingleExecuteParams] = None,
  147. ) -> Any: ...
  148. def executemany(
  149. self,
  150. operation: Any,
  151. parameters: _DBAPIMultiExecuteParams,
  152. ) -> Any: ...
  153. def fetchone(self) -> Optional[Any]: ...
  154. def fetchmany(self, size: int = ...) -> Sequence[Any]: ...
  155. def fetchall(self) -> Sequence[Any]: ...
  156. def setinputsizes(self, sizes: Sequence[Any]) -> None: ...
  157. def setoutputsize(self, size: Any, column: Any) -> None: ...
  158. def callproc(
  159. self, procname: str, parameters: Sequence[Any] = ...
  160. ) -> Any: ...
  161. def nextset(self) -> Optional[bool]: ...
  162. def __getattr__(self, key: str) -> Any: ...
  163. _CoreSingleExecuteParams = Mapping[str, Any]
  164. _MutableCoreSingleExecuteParams = MutableMapping[str, Any]
  165. _CoreMultiExecuteParams = Sequence[_CoreSingleExecuteParams]
  166. _CoreAnyExecuteParams = Union[
  167. _CoreMultiExecuteParams, _CoreSingleExecuteParams
  168. ]
  169. _DBAPISingleExecuteParams = Union[Sequence[Any], _CoreSingleExecuteParams]
  170. _DBAPIMultiExecuteParams = Union[
  171. Sequence[Sequence[Any]], _CoreMultiExecuteParams
  172. ]
  173. _DBAPIAnyExecuteParams = Union[
  174. _DBAPIMultiExecuteParams, _DBAPISingleExecuteParams
  175. ]
  176. _DBAPICursorDescription = Sequence[
  177. Tuple[
  178. str,
  179. "DBAPIType",
  180. Optional[int],
  181. Optional[int],
  182. Optional[int],
  183. Optional[int],
  184. Optional[bool],
  185. ]
  186. ]
  187. _AnySingleExecuteParams = _DBAPISingleExecuteParams
  188. _AnyMultiExecuteParams = _DBAPIMultiExecuteParams
  189. _AnyExecuteParams = _DBAPIAnyExecuteParams
  190. CompiledCacheType = MutableMapping[Any, "Compiled"]
  191. SchemaTranslateMapType = Mapping[Optional[str], Optional[str]]
  192. _ImmutableExecuteOptions = immutabledict[str, Any]
  193. _ParamStyle = Literal[
  194. "qmark", "numeric", "named", "format", "pyformat", "numeric_dollar"
  195. ]
  196. _GenericSetInputSizesType = List[Tuple[str, Any, "TypeEngine[Any]"]]
  197. IsolationLevel = Literal[
  198. "SERIALIZABLE",
  199. "REPEATABLE READ",
  200. "READ COMMITTED",
  201. "READ UNCOMMITTED",
  202. "AUTOCOMMIT",
  203. ]
  204. class _CoreKnownExecutionOptions(TypedDict, total=False):
  205. compiled_cache: Optional[CompiledCacheType]
  206. logging_token: str
  207. isolation_level: IsolationLevel
  208. no_parameters: bool
  209. stream_results: bool
  210. max_row_buffer: int
  211. yield_per: int
  212. insertmanyvalues_page_size: int
  213. schema_translate_map: Optional[SchemaTranslateMapType]
  214. preserve_rowcount: bool
  215. _ExecuteOptions = immutabledict[str, Any]
  216. CoreExecuteOptionsParameter = Union[
  217. _CoreKnownExecutionOptions, Mapping[str, Any]
  218. ]
  219. class ReflectedIdentity(TypedDict):
  220. """represent the reflected IDENTITY structure of a column, corresponding
  221. to the :class:`_schema.Identity` construct.
  222. The :class:`.ReflectedIdentity` structure is part of the
  223. :class:`.ReflectedColumn` structure, which is returned by the
  224. :meth:`.Inspector.get_columns` method.
  225. """
  226. always: bool
  227. """type of identity column"""
  228. on_null: bool
  229. """indicates ON NULL"""
  230. start: int
  231. """starting index of the sequence"""
  232. increment: int
  233. """increment value of the sequence"""
  234. minvalue: int
  235. """the minimum value of the sequence."""
  236. maxvalue: int
  237. """the maximum value of the sequence."""
  238. nominvalue: bool
  239. """no minimum value of the sequence."""
  240. nomaxvalue: bool
  241. """no maximum value of the sequence."""
  242. cycle: bool
  243. """allows the sequence to wrap around when the maxvalue
  244. or minvalue has been reached."""
  245. cache: Optional[int]
  246. """number of future values in the
  247. sequence which are calculated in advance."""
  248. order: bool
  249. """if true, renders the ORDER keyword."""
  250. class ReflectedComputed(TypedDict):
  251. """Represent the reflected elements of a computed column, corresponding
  252. to the :class:`_schema.Computed` construct.
  253. The :class:`.ReflectedComputed` structure is part of the
  254. :class:`.ReflectedColumn` structure, which is returned by the
  255. :meth:`.Inspector.get_columns` method.
  256. """
  257. sqltext: str
  258. """the expression used to generate this column returned
  259. as a string SQL expression"""
  260. persisted: NotRequired[bool]
  261. """indicates if the value is stored in the table or computed on demand"""
  262. class ReflectedColumn(TypedDict):
  263. """Dictionary representing the reflected elements corresponding to
  264. a :class:`_schema.Column` object.
  265. The :class:`.ReflectedColumn` structure is returned by the
  266. :class:`.Inspector.get_columns` method.
  267. """
  268. name: str
  269. """column name"""
  270. type: TypeEngine[Any]
  271. """column type represented as a :class:`.TypeEngine` instance."""
  272. nullable: bool
  273. """boolean flag if the column is NULL or NOT NULL"""
  274. default: Optional[str]
  275. """column default expression as a SQL string"""
  276. autoincrement: NotRequired[bool]
  277. """database-dependent autoincrement flag.
  278. This flag indicates if the column has a database-side "autoincrement"
  279. flag of some kind. Within SQLAlchemy, other kinds of columns may
  280. also act as an "autoincrement" column without necessarily having
  281. such a flag on them.
  282. See :paramref:`_schema.Column.autoincrement` for more background on
  283. "autoincrement".
  284. """
  285. comment: NotRequired[Optional[str]]
  286. """comment for the column, if present.
  287. Only some dialects return this key
  288. """
  289. computed: NotRequired[ReflectedComputed]
  290. """indicates that this column is computed by the database.
  291. Only some dialects return this key.
  292. .. versionadded:: 1.3.16 - added support for computed reflection.
  293. """
  294. identity: NotRequired[ReflectedIdentity]
  295. """indicates this column is an IDENTITY column.
  296. Only some dialects return this key.
  297. .. versionadded:: 1.4 - added support for identity column reflection.
  298. """
  299. dialect_options: NotRequired[Dict[str, Any]]
  300. """Additional dialect-specific options detected for this reflected
  301. object"""
  302. class ReflectedConstraint(TypedDict):
  303. """Dictionary representing the reflected elements corresponding to
  304. :class:`.Constraint`
  305. A base class for all constraints
  306. """
  307. name: Optional[str]
  308. """constraint name"""
  309. comment: NotRequired[Optional[str]]
  310. """comment for the constraint, if present"""
  311. class ReflectedCheckConstraint(ReflectedConstraint):
  312. """Dictionary representing the reflected elements corresponding to
  313. :class:`.CheckConstraint`.
  314. The :class:`.ReflectedCheckConstraint` structure is returned by the
  315. :meth:`.Inspector.get_check_constraints` method.
  316. """
  317. sqltext: str
  318. """the check constraint's SQL expression"""
  319. dialect_options: NotRequired[Dict[str, Any]]
  320. """Additional dialect-specific options detected for this check constraint
  321. .. versionadded:: 1.3.8
  322. """
  323. class ReflectedUniqueConstraint(ReflectedConstraint):
  324. """Dictionary representing the reflected elements corresponding to
  325. :class:`.UniqueConstraint`.
  326. The :class:`.ReflectedUniqueConstraint` structure is returned by the
  327. :meth:`.Inspector.get_unique_constraints` method.
  328. """
  329. column_names: List[str]
  330. """column names which comprise the unique constraint"""
  331. duplicates_index: NotRequired[Optional[str]]
  332. "Indicates if this unique constraint duplicates an index with this name"
  333. dialect_options: NotRequired[Dict[str, Any]]
  334. """Additional dialect-specific options detected for this unique
  335. constraint"""
  336. class ReflectedPrimaryKeyConstraint(ReflectedConstraint):
  337. """Dictionary representing the reflected elements corresponding to
  338. :class:`.PrimaryKeyConstraint`.
  339. The :class:`.ReflectedPrimaryKeyConstraint` structure is returned by the
  340. :meth:`.Inspector.get_pk_constraint` method.
  341. """
  342. constrained_columns: List[str]
  343. """column names which comprise the primary key"""
  344. dialect_options: NotRequired[Dict[str, Any]]
  345. """Additional dialect-specific options detected for this primary key"""
  346. class ReflectedForeignKeyConstraint(ReflectedConstraint):
  347. """Dictionary representing the reflected elements corresponding to
  348. :class:`.ForeignKeyConstraint`.
  349. The :class:`.ReflectedForeignKeyConstraint` structure is returned by
  350. the :meth:`.Inspector.get_foreign_keys` method.
  351. """
  352. constrained_columns: List[str]
  353. """local column names which comprise the foreign key"""
  354. referred_schema: Optional[str]
  355. """schema name of the table being referred"""
  356. referred_table: str
  357. """name of the table being referred"""
  358. referred_columns: List[str]
  359. """referred column names that correspond to ``constrained_columns``"""
  360. options: NotRequired[Dict[str, Any]]
  361. """Additional options detected for this foreign key constraint"""
  362. class ReflectedIndex(TypedDict):
  363. """Dictionary representing the reflected elements corresponding to
  364. :class:`.Index`.
  365. The :class:`.ReflectedIndex` structure is returned by the
  366. :meth:`.Inspector.get_indexes` method.
  367. """
  368. name: Optional[str]
  369. """index name"""
  370. column_names: List[Optional[str]]
  371. """column names which the index references.
  372. An element of this list is ``None`` if it's an expression and is
  373. returned in the ``expressions`` list.
  374. """
  375. expressions: NotRequired[List[str]]
  376. """Expressions that compose the index. This list, when present, contains
  377. both plain column names (that are also in ``column_names``) and
  378. expressions (that are ``None`` in ``column_names``).
  379. """
  380. unique: bool
  381. """whether or not the index has a unique flag"""
  382. duplicates_constraint: NotRequired[Optional[str]]
  383. "Indicates if this index mirrors a constraint with this name"
  384. include_columns: NotRequired[List[str]]
  385. """columns to include in the INCLUDE clause for supporting databases.
  386. .. deprecated:: 2.0
  387. Legacy value, will be replaced with
  388. ``index_dict["dialect_options"]["<dialect name>_include"]``
  389. """
  390. column_sorting: NotRequired[Dict[str, Tuple[str]]]
  391. """optional dict mapping column names or expressions to tuple of sort
  392. keywords, which may include ``asc``, ``desc``, ``nulls_first``,
  393. ``nulls_last``.
  394. .. versionadded:: 1.3.5
  395. """
  396. dialect_options: NotRequired[Dict[str, Any]]
  397. """Additional dialect-specific options detected for this index"""
  398. class ReflectedTableComment(TypedDict):
  399. """Dictionary representing the reflected comment corresponding to
  400. the :attr:`_schema.Table.comment` attribute.
  401. The :class:`.ReflectedTableComment` structure is returned by the
  402. :meth:`.Inspector.get_table_comment` method.
  403. """
  404. text: Optional[str]
  405. """text of the comment"""
  406. class BindTyping(Enum):
  407. """Define different methods of passing typing information for
  408. bound parameters in a statement to the database driver.
  409. .. versionadded:: 2.0
  410. """
  411. NONE = 1
  412. """No steps are taken to pass typing information to the database driver.
  413. This is the default behavior for databases such as SQLite, MySQL / MariaDB,
  414. SQL Server.
  415. """
  416. SETINPUTSIZES = 2
  417. """Use the pep-249 setinputsizes method.
  418. This is only implemented for DBAPIs that support this method and for which
  419. the SQLAlchemy dialect has the appropriate infrastructure for that dialect
  420. set up. Current dialects include python-oracledb, cx_Oracle as well as
  421. optional support for SQL Server using pyodbc.
  422. When using setinputsizes, dialects also have a means of only using the
  423. method for certain datatypes using include/exclude lists.
  424. When SETINPUTSIZES is used, the :meth:`.Dialect.do_set_input_sizes` method
  425. is called for each statement executed which has bound parameters.
  426. """
  427. RENDER_CASTS = 3
  428. """Render casts or other directives in the SQL string.
  429. This method is used for all PostgreSQL dialects, including asyncpg,
  430. pg8000, psycopg, psycopg2. Dialects which implement this can choose
  431. which kinds of datatypes are explicitly cast in SQL statements and which
  432. aren't.
  433. When RENDER_CASTS is used, the compiler will invoke the
  434. :meth:`.SQLCompiler.render_bind_cast` method for the rendered
  435. string representation of each :class:`.BindParameter` object whose
  436. dialect-level type sets the :attr:`.TypeEngine.render_bind_cast` attribute.
  437. The :meth:`.SQLCompiler.render_bind_cast` is also used to render casts
  438. for one form of "insertmanyvalues" query, when both
  439. :attr:`.InsertmanyvaluesSentinelOpts.USE_INSERT_FROM_SELECT` and
  440. :attr:`.InsertmanyvaluesSentinelOpts.RENDER_SELECT_COL_CASTS` are set,
  441. where the casts are applied to the intermediary columns e.g.
  442. "INSERT INTO t (a, b, c) SELECT p0::TYP, p1::TYP, p2::TYP "
  443. "FROM (VALUES (?, ?), (?, ?), ...)".
  444. .. versionadded:: 2.0.10 - :meth:`.SQLCompiler.render_bind_cast` is now
  445. used within some elements of the "insertmanyvalues" implementation.
  446. """
  447. VersionInfoType = Tuple[Union[int, str], ...]
  448. TableKey = Tuple[Optional[str], str]
  449. class Dialect(EventTarget):
  450. """Define the behavior of a specific database and DB-API combination.
  451. Any aspect of metadata definition, SQL query generation,
  452. execution, result-set handling, or anything else which varies
  453. between databases is defined under the general category of the
  454. Dialect. The Dialect acts as a factory for other
  455. database-specific object implementations including
  456. ExecutionContext, Compiled, DefaultGenerator, and TypeEngine.
  457. .. note:: Third party dialects should not subclass :class:`.Dialect`
  458. directly. Instead, subclass :class:`.default.DefaultDialect` or
  459. descendant class.
  460. """
  461. CACHE_HIT = CacheStats.CACHE_HIT
  462. CACHE_MISS = CacheStats.CACHE_MISS
  463. CACHING_DISABLED = CacheStats.CACHING_DISABLED
  464. NO_CACHE_KEY = CacheStats.NO_CACHE_KEY
  465. NO_DIALECT_SUPPORT = CacheStats.NO_DIALECT_SUPPORT
  466. dispatch: dispatcher[Dialect]
  467. name: str
  468. """identifying name for the dialect from a DBAPI-neutral point of view
  469. (i.e. 'sqlite')
  470. """
  471. driver: str
  472. """identifying name for the dialect's DBAPI"""
  473. dialect_description: str
  474. dbapi: Optional[DBAPIModule]
  475. """A reference to the DBAPI module object itself.
  476. SQLAlchemy dialects import DBAPI modules using the classmethod
  477. :meth:`.Dialect.import_dbapi`. The rationale is so that any dialect
  478. module can be imported and used to generate SQL statements without the
  479. need for the actual DBAPI driver to be installed. Only when an
  480. :class:`.Engine` is constructed using :func:`.create_engine` does the
  481. DBAPI get imported; at that point, the creation process will assign
  482. the DBAPI module to this attribute.
  483. Dialects should therefore implement :meth:`.Dialect.import_dbapi`
  484. which will import the necessary module and return it, and then refer
  485. to ``self.dbapi`` in dialect code in order to refer to the DBAPI module
  486. contents.
  487. .. versionchanged:: The :attr:`.Dialect.dbapi` attribute is exclusively
  488. used as the per-:class:`.Dialect`-instance reference to the DBAPI
  489. module. The previous not-fully-documented ``.Dialect.dbapi()``
  490. classmethod is deprecated and replaced by :meth:`.Dialect.import_dbapi`.
  491. """
  492. @util.non_memoized_property
  493. def loaded_dbapi(self) -> DBAPIModule:
  494. """same as .dbapi, but is never None; will raise an error if no
  495. DBAPI was set up.
  496. .. versionadded:: 2.0
  497. """
  498. raise NotImplementedError()
  499. positional: bool
  500. """True if the paramstyle for this Dialect is positional."""
  501. paramstyle: str
  502. """the paramstyle to be used (some DB-APIs support multiple
  503. paramstyles).
  504. """
  505. compiler_linting: Linting
  506. statement_compiler: Type[SQLCompiler]
  507. """a :class:`.Compiled` class used to compile SQL statements"""
  508. ddl_compiler: Type[DDLCompiler]
  509. """a :class:`.Compiled` class used to compile DDL statements"""
  510. type_compiler_cls: ClassVar[Type[TypeCompiler]]
  511. """a :class:`.Compiled` class used to compile SQL type objects
  512. .. versionadded:: 2.0
  513. """
  514. type_compiler_instance: TypeCompiler
  515. """instance of a :class:`.Compiled` class used to compile SQL type
  516. objects
  517. .. versionadded:: 2.0
  518. """
  519. type_compiler: Any
  520. """legacy; this is a TypeCompiler class at the class level, a
  521. TypeCompiler instance at the instance level.
  522. Refer to type_compiler_instance instead.
  523. """
  524. preparer: Type[IdentifierPreparer]
  525. """a :class:`.IdentifierPreparer` class used to
  526. quote identifiers.
  527. """
  528. identifier_preparer: IdentifierPreparer
  529. """This element will refer to an instance of :class:`.IdentifierPreparer`
  530. once a :class:`.DefaultDialect` has been constructed.
  531. """
  532. server_version_info: Optional[Tuple[Any, ...]]
  533. """a tuple containing a version number for the DB backend in use.
  534. This value is only available for supporting dialects, and is
  535. typically populated during the initial connection to the database.
  536. """
  537. default_schema_name: Optional[str]
  538. """the name of the default schema. This value is only available for
  539. supporting dialects, and is typically populated during the
  540. initial connection to the database.
  541. """
  542. # NOTE: this does not take into effect engine-level isolation level.
  543. # not clear if this should be changed, seems like it should
  544. default_isolation_level: Optional[IsolationLevel]
  545. """the isolation that is implicitly present on new connections"""
  546. skip_autocommit_rollback: bool
  547. """Whether or not the :paramref:`.create_engine.skip_autocommit_rollback`
  548. parameter was set.
  549. .. versionadded:: 2.0.43
  550. """
  551. # create_engine() -> isolation_level currently goes here
  552. _on_connect_isolation_level: Optional[IsolationLevel]
  553. execution_ctx_cls: Type[ExecutionContext]
  554. """a :class:`.ExecutionContext` class used to handle statement execution"""
  555. execute_sequence_format: Union[
  556. Type[Tuple[Any, ...]], Type[Tuple[List[Any]]]
  557. ]
  558. """either the 'tuple' or 'list' type, depending on what cursor.execute()
  559. accepts for the second argument (they vary)."""
  560. supports_alter: bool
  561. """``True`` if the database supports ``ALTER TABLE`` - used only for
  562. generating foreign key constraints in certain circumstances
  563. """
  564. max_identifier_length: int
  565. """The maximum length of identifier names."""
  566. max_index_name_length: Optional[int]
  567. """The maximum length of index names if different from
  568. ``max_identifier_length``."""
  569. max_constraint_name_length: Optional[int]
  570. """The maximum length of constraint names if different from
  571. ``max_identifier_length``."""
  572. supports_server_side_cursors: Union[generic_fn_descriptor[bool], bool]
  573. """indicates if the dialect supports server side cursors"""
  574. server_side_cursors: bool
  575. """deprecated; indicates if the dialect should attempt to use server
  576. side cursors by default"""
  577. supports_sane_rowcount: bool
  578. """Indicate whether the dialect properly implements rowcount for
  579. ``UPDATE`` and ``DELETE`` statements.
  580. """
  581. supports_sane_multi_rowcount: bool
  582. """Indicate whether the dialect properly implements rowcount for
  583. ``UPDATE`` and ``DELETE`` statements when executed via
  584. executemany.
  585. """
  586. supports_empty_insert: bool
  587. """dialect supports INSERT () VALUES (), i.e. a plain INSERT with no
  588. columns in it.
  589. This is not usually supported; an "empty" insert is typically
  590. suited using either "INSERT..DEFAULT VALUES" or
  591. "INSERT ... (col) VALUES (DEFAULT)".
  592. """
  593. supports_default_values: bool
  594. """dialect supports INSERT... DEFAULT VALUES syntax"""
  595. supports_default_metavalue: bool
  596. """dialect supports INSERT...(col) VALUES (DEFAULT) syntax.
  597. Most databases support this in some way, e.g. SQLite supports it using
  598. ``VALUES (NULL)``. MS SQL Server supports the syntax also however
  599. is the only included dialect where we have this disabled, as
  600. MSSQL does not support the field for the IDENTITY column, which is
  601. usually where we like to make use of the feature.
  602. """
  603. default_metavalue_token: str = "DEFAULT"
  604. """for INSERT... VALUES (DEFAULT) syntax, the token to put in the
  605. parenthesis.
  606. E.g. for SQLite this is the keyword "NULL".
  607. """
  608. supports_multivalues_insert: bool
  609. """Target database supports INSERT...VALUES with multiple value
  610. sets, i.e. INSERT INTO table (cols) VALUES (...), (...), (...), ...
  611. """
  612. insert_executemany_returning: bool
  613. """dialect / driver / database supports some means of providing
  614. INSERT...RETURNING support when dialect.do_executemany() is used.
  615. """
  616. insert_executemany_returning_sort_by_parameter_order: bool
  617. """dialect / driver / database supports some means of providing
  618. INSERT...RETURNING support when dialect.do_executemany() is used
  619. along with the :paramref:`_dml.Insert.returning.sort_by_parameter_order`
  620. parameter being set.
  621. """
  622. update_executemany_returning: bool
  623. """dialect supports UPDATE..RETURNING with executemany."""
  624. delete_executemany_returning: bool
  625. """dialect supports DELETE..RETURNING with executemany."""
  626. use_insertmanyvalues: bool
  627. """if True, indicates "insertmanyvalues" functionality should be used
  628. to allow for ``insert_executemany_returning`` behavior, if possible.
  629. In practice, setting this to True means:
  630. if ``supports_multivalues_insert``, ``insert_returning`` and
  631. ``use_insertmanyvalues`` are all True, the SQL compiler will produce
  632. an INSERT that will be interpreted by the :class:`.DefaultDialect`
  633. as an :attr:`.ExecuteStyle.INSERTMANYVALUES` execution that allows
  634. for INSERT of many rows with RETURNING by rewriting a single-row
  635. INSERT statement to have multiple VALUES clauses, also executing
  636. the statement multiple times for a series of batches when large numbers
  637. of rows are given.
  638. The parameter is False for the default dialect, and is set to True for
  639. SQLAlchemy internal dialects SQLite, MySQL/MariaDB, PostgreSQL, SQL Server.
  640. It remains at False for Oracle Database, which provides native "executemany
  641. with RETURNING" support and also does not support
  642. ``supports_multivalues_insert``. For MySQL/MariaDB, those MySQL dialects
  643. that don't support RETURNING will not report
  644. ``insert_executemany_returning`` as True.
  645. .. versionadded:: 2.0
  646. .. seealso::
  647. :ref:`engine_insertmanyvalues`
  648. """
  649. use_insertmanyvalues_wo_returning: bool
  650. """if True, and use_insertmanyvalues is also True, INSERT statements
  651. that don't include RETURNING will also use "insertmanyvalues".
  652. .. versionadded:: 2.0
  653. .. seealso::
  654. :ref:`engine_insertmanyvalues`
  655. """
  656. insertmanyvalues_implicit_sentinel: InsertmanyvaluesSentinelOpts
  657. """Options indicating the database supports a form of bulk INSERT where
  658. the autoincrement integer primary key can be reliably used as an ordering
  659. for INSERTed rows.
  660. .. versionadded:: 2.0.10
  661. .. seealso::
  662. :ref:`engine_insertmanyvalues_returning_order`
  663. """
  664. insertmanyvalues_page_size: int
  665. """Number of rows to render into an individual INSERT..VALUES() statement
  666. for :attr:`.ExecuteStyle.INSERTMANYVALUES` executions.
  667. The default dialect defaults this to 1000.
  668. .. versionadded:: 2.0
  669. .. seealso::
  670. :paramref:`_engine.Connection.execution_options.insertmanyvalues_page_size` -
  671. execution option available on :class:`_engine.Connection`, statements
  672. """ # noqa: E501
  673. insertmanyvalues_max_parameters: int
  674. """Alternate to insertmanyvalues_page_size, will additionally limit
  675. page size based on number of parameters total in the statement.
  676. """
  677. preexecute_autoincrement_sequences: bool
  678. """True if 'implicit' primary key functions must be executed separately
  679. in order to get their value, if RETURNING is not used.
  680. This is currently oriented towards PostgreSQL when the
  681. ``implicit_returning=False`` parameter is used on a :class:`.Table`
  682. object.
  683. """
  684. insert_returning: bool
  685. """if the dialect supports RETURNING with INSERT
  686. .. versionadded:: 2.0
  687. """
  688. update_returning: bool
  689. """if the dialect supports RETURNING with UPDATE
  690. .. versionadded:: 2.0
  691. """
  692. update_returning_multifrom: bool
  693. """if the dialect supports RETURNING with UPDATE..FROM
  694. .. versionadded:: 2.0
  695. """
  696. delete_returning: bool
  697. """if the dialect supports RETURNING with DELETE
  698. .. versionadded:: 2.0
  699. """
  700. delete_returning_multifrom: bool
  701. """if the dialect supports RETURNING with DELETE..FROM
  702. .. versionadded:: 2.0
  703. """
  704. favor_returning_over_lastrowid: bool
  705. """for backends that support both a lastrowid and a RETURNING insert
  706. strategy, favor RETURNING for simple single-int pk inserts.
  707. cursor.lastrowid tends to be more performant on most backends.
  708. """
  709. supports_identity_columns: bool
  710. """target database supports IDENTITY"""
  711. cte_follows_insert: bool
  712. """target database, when given a CTE with an INSERT statement, needs
  713. the CTE to be below the INSERT"""
  714. colspecs: MutableMapping[Type[TypeEngine[Any]], Type[TypeEngine[Any]]]
  715. """A dictionary of TypeEngine classes from sqlalchemy.types mapped
  716. to subclasses that are specific to the dialect class. This
  717. dictionary is class-level only and is not accessed from the
  718. dialect instance itself.
  719. """
  720. supports_sequences: bool
  721. """Indicates if the dialect supports CREATE SEQUENCE or similar."""
  722. sequences_optional: bool
  723. """If True, indicates if the :paramref:`_schema.Sequence.optional`
  724. parameter on the :class:`_schema.Sequence` construct
  725. should signal to not generate a CREATE SEQUENCE. Applies only to
  726. dialects that support sequences. Currently used only to allow PostgreSQL
  727. SERIAL to be used on a column that specifies Sequence() for usage on
  728. other backends.
  729. """
  730. default_sequence_base: int
  731. """the default value that will be rendered as the "START WITH" portion of
  732. a CREATE SEQUENCE DDL statement.
  733. """
  734. supports_native_enum: bool
  735. """Indicates if the dialect supports a native ENUM construct.
  736. This will prevent :class:`_types.Enum` from generating a CHECK
  737. constraint when that type is used in "native" mode.
  738. """
  739. supports_native_boolean: bool
  740. """Indicates if the dialect supports a native boolean construct.
  741. This will prevent :class:`_types.Boolean` from generating a CHECK
  742. constraint when that type is used.
  743. """
  744. supports_native_decimal: bool
  745. """indicates if Decimal objects are handled and returned for precision
  746. numeric types, or if floats are returned"""
  747. supports_native_uuid: bool
  748. """indicates if Python UUID() objects are handled natively by the
  749. driver for SQL UUID datatypes.
  750. .. versionadded:: 2.0
  751. """
  752. returns_native_bytes: bool
  753. """indicates if Python bytes() objects are returned natively by the
  754. driver for SQL "binary" datatypes.
  755. .. versionadded:: 2.0.11
  756. """
  757. construct_arguments: Optional[
  758. List[Tuple[Type[Union[SchemaItem, ClauseElement]], Mapping[str, Any]]]
  759. ] = None
  760. """Optional set of argument specifiers for various SQLAlchemy
  761. constructs, typically schema items.
  762. To implement, establish as a series of tuples, as in::
  763. construct_arguments = [
  764. (schema.Index, {"using": False, "where": None, "ops": None}),
  765. ]
  766. If the above construct is established on the PostgreSQL dialect,
  767. the :class:`.Index` construct will now accept the keyword arguments
  768. ``postgresql_using``, ``postgresql_where``, nad ``postgresql_ops``.
  769. Any other argument specified to the constructor of :class:`.Index`
  770. which is prefixed with ``postgresql_`` will raise :class:`.ArgumentError`.
  771. A dialect which does not include a ``construct_arguments`` member will
  772. not participate in the argument validation system. For such a dialect,
  773. any argument name is accepted by all participating constructs, within
  774. the namespace of arguments prefixed with that dialect name. The rationale
  775. here is so that third-party dialects that haven't yet implemented this
  776. feature continue to function in the old way.
  777. .. seealso::
  778. :class:`.DialectKWArgs` - implementing base class which consumes
  779. :attr:`.DefaultDialect.construct_arguments`
  780. """
  781. reflection_options: Sequence[str] = ()
  782. """Sequence of string names indicating keyword arguments that can be
  783. established on a :class:`.Table` object which will be passed as
  784. "reflection options" when using :paramref:`.Table.autoload_with`.
  785. Current example is "oracle_resolve_synonyms" in the Oracle Database
  786. dialects.
  787. """
  788. dbapi_exception_translation_map: Mapping[str, str] = util.EMPTY_DICT
  789. """A dictionary of names that will contain as values the names of
  790. pep-249 exceptions ("IntegrityError", "OperationalError", etc)
  791. keyed to alternate class names, to support the case where a
  792. DBAPI has exception classes that aren't named as they are
  793. referred to (e.g. IntegrityError = MyException). In the vast
  794. majority of cases this dictionary is empty.
  795. """
  796. supports_comments: bool
  797. """Indicates the dialect supports comment DDL on tables and columns."""
  798. inline_comments: bool
  799. """Indicates the dialect supports comment DDL that's inline with the
  800. definition of a Table or Column. If False, this implies that ALTER must
  801. be used to set table and column comments."""
  802. supports_constraint_comments: bool
  803. """Indicates if the dialect supports comment DDL on constraints.
  804. .. versionadded:: 2.0
  805. """
  806. _has_events = False
  807. supports_statement_cache: bool = True
  808. """indicates if this dialect supports caching.
  809. All dialects that are compatible with statement caching should set this
  810. flag to True directly on each dialect class and subclass that supports
  811. it. SQLAlchemy tests that this flag is locally present on each dialect
  812. subclass before it will use statement caching. This is to provide
  813. safety for legacy or new dialects that are not yet fully tested to be
  814. compliant with SQL statement caching.
  815. .. versionadded:: 1.4.5
  816. .. seealso::
  817. :ref:`engine_thirdparty_caching`
  818. """
  819. _supports_statement_cache: bool
  820. """internal evaluation for supports_statement_cache"""
  821. bind_typing = BindTyping.NONE
  822. """define a means of passing typing information to the database and/or
  823. driver for bound parameters.
  824. See :class:`.BindTyping` for values.
  825. .. versionadded:: 2.0
  826. """
  827. is_async: bool
  828. """Whether or not this dialect is intended for asyncio use."""
  829. has_terminate: bool
  830. """Whether or not this dialect has a separate "terminate" implementation
  831. that does not block or require awaiting."""
  832. engine_config_types: Mapping[str, Any]
  833. """a mapping of string keys that can be in an engine config linked to
  834. type conversion functions.
  835. """
  836. label_length: Optional[int]
  837. """optional user-defined max length for SQL labels"""
  838. include_set_input_sizes: Optional[Set[Any]]
  839. """set of DBAPI type objects that should be included in
  840. automatic cursor.setinputsizes() calls.
  841. This is only used if bind_typing is BindTyping.SET_INPUT_SIZES
  842. """
  843. exclude_set_input_sizes: Optional[Set[Any]]
  844. """set of DBAPI type objects that should be excluded in
  845. automatic cursor.setinputsizes() calls.
  846. This is only used if bind_typing is BindTyping.SET_INPUT_SIZES
  847. """
  848. supports_simple_order_by_label: bool
  849. """target database supports ORDER BY <labelname>, where <labelname>
  850. refers to a label in the columns clause of the SELECT"""
  851. div_is_floordiv: bool
  852. """target database treats the / division operator as "floor division" """
  853. tuple_in_values: bool
  854. """target database supports tuple IN, i.e. (x, y) IN ((q, p), (r, z))"""
  855. requires_name_normalize: bool
  856. """Indicates symbol names are returned by the database in
  857. UPPERCASED if they are case insensitive within the database.
  858. If this is True, the methods normalize_name()
  859. and denormalize_name() must be provided.
  860. """
  861. _bind_typing_render_casts: bool
  862. _type_memos: MutableMapping[TypeEngine[Any], _TypeMemoDict]
  863. def _builtin_onconnect(self) -> Optional[_ListenerFnType]:
  864. raise NotImplementedError()
  865. def create_connect_args(self, url: URL) -> ConnectArgsType:
  866. """Build DB-API compatible connection arguments.
  867. Given a :class:`.URL` object, returns a tuple
  868. consisting of a ``(*args, **kwargs)`` suitable to send directly
  869. to the dbapi's connect function. The arguments are sent to the
  870. :meth:`.Dialect.connect` method which then runs the DBAPI-level
  871. ``connect()`` function.
  872. The method typically makes use of the
  873. :meth:`.URL.translate_connect_args`
  874. method in order to generate a dictionary of options.
  875. The default implementation is::
  876. def create_connect_args(self, url):
  877. opts = url.translate_connect_args()
  878. opts.update(url.query)
  879. return ([], opts)
  880. :param url: a :class:`.URL` object
  881. :return: a tuple of ``(*args, **kwargs)`` which will be passed to the
  882. :meth:`.Dialect.connect` method.
  883. .. seealso::
  884. :meth:`.URL.translate_connect_args`
  885. """
  886. raise NotImplementedError()
  887. @classmethod
  888. def import_dbapi(cls) -> DBAPIModule:
  889. """Import the DBAPI module that is used by this dialect.
  890. The Python module object returned here will be assigned as an
  891. instance variable to a constructed dialect under the name
  892. ``.dbapi``.
  893. .. versionchanged:: 2.0 The :meth:`.Dialect.import_dbapi` class
  894. method is renamed from the previous method ``.Dialect.dbapi()``,
  895. which would be replaced at dialect instantiation time by the
  896. DBAPI module itself, thus using the same name in two different ways.
  897. If a ``.Dialect.dbapi()`` classmethod is present on a third-party
  898. dialect, it will be used and a deprecation warning will be emitted.
  899. """
  900. raise NotImplementedError()
  901. def type_descriptor(self, typeobj: TypeEngine[_T]) -> TypeEngine[_T]:
  902. """Transform a generic type to a dialect-specific type.
  903. Dialect classes will usually use the
  904. :func:`_types.adapt_type` function in the types module to
  905. accomplish this.
  906. The returned result is cached *per dialect class* so can
  907. contain no dialect-instance state.
  908. """
  909. raise NotImplementedError()
  910. def initialize(self, connection: Connection) -> None:
  911. """Called during strategized creation of the dialect with a
  912. connection.
  913. Allows dialects to configure options based on server version info or
  914. other properties.
  915. The connection passed here is a SQLAlchemy Connection object,
  916. with full capabilities.
  917. The initialize() method of the base dialect should be called via
  918. super().
  919. .. note:: as of SQLAlchemy 1.4, this method is called **before**
  920. any :meth:`_engine.Dialect.on_connect` hooks are called.
  921. """
  922. if TYPE_CHECKING:
  923. def _overrides_default(self, method_name: str) -> bool: ...
  924. def get_columns(
  925. self,
  926. connection: Connection,
  927. table_name: str,
  928. schema: Optional[str] = None,
  929. **kw: Any,
  930. ) -> List[ReflectedColumn]:
  931. """Return information about columns in ``table_name``.
  932. Given a :class:`_engine.Connection`, a string
  933. ``table_name``, and an optional string ``schema``, return column
  934. information as a list of dictionaries
  935. corresponding to the :class:`.ReflectedColumn` dictionary.
  936. This is an internal dialect method. Applications should use
  937. :meth:`.Inspector.get_columns`.
  938. """
  939. raise NotImplementedError()
  940. def get_multi_columns(
  941. self,
  942. connection: Connection,
  943. *,
  944. schema: Optional[str] = None,
  945. filter_names: Optional[Collection[str]] = None,
  946. **kw: Any,
  947. ) -> Iterable[Tuple[TableKey, List[ReflectedColumn]]]:
  948. """Return information about columns in all tables in the
  949. given ``schema``.
  950. This is an internal dialect method. Applications should use
  951. :meth:`.Inspector.get_multi_columns`.
  952. .. note:: The :class:`_engine.DefaultDialect` provides a default
  953. implementation that will call the single table method for
  954. each object returned by :meth:`Dialect.get_table_names`,
  955. :meth:`Dialect.get_view_names` or
  956. :meth:`Dialect.get_materialized_view_names` depending on the
  957. provided ``kind``. Dialects that want to support a faster
  958. implementation should implement this method.
  959. .. versionadded:: 2.0
  960. """
  961. raise NotImplementedError()
  962. def get_pk_constraint(
  963. self,
  964. connection: Connection,
  965. table_name: str,
  966. schema: Optional[str] = None,
  967. **kw: Any,
  968. ) -> ReflectedPrimaryKeyConstraint:
  969. """Return information about the primary key constraint on
  970. table_name`.
  971. Given a :class:`_engine.Connection`, a string
  972. ``table_name``, and an optional string ``schema``, return primary
  973. key information as a dictionary corresponding to the
  974. :class:`.ReflectedPrimaryKeyConstraint` dictionary.
  975. This is an internal dialect method. Applications should use
  976. :meth:`.Inspector.get_pk_constraint`.
  977. """
  978. raise NotImplementedError()
  979. def get_multi_pk_constraint(
  980. self,
  981. connection: Connection,
  982. *,
  983. schema: Optional[str] = None,
  984. filter_names: Optional[Collection[str]] = None,
  985. **kw: Any,
  986. ) -> Iterable[Tuple[TableKey, ReflectedPrimaryKeyConstraint]]:
  987. """Return information about primary key constraints in
  988. all tables in the given ``schema``.
  989. This is an internal dialect method. Applications should use
  990. :meth:`.Inspector.get_multi_pk_constraint`.
  991. .. note:: The :class:`_engine.DefaultDialect` provides a default
  992. implementation that will call the single table method for
  993. each object returned by :meth:`Dialect.get_table_names`,
  994. :meth:`Dialect.get_view_names` or
  995. :meth:`Dialect.get_materialized_view_names` depending on the
  996. provided ``kind``. Dialects that want to support a faster
  997. implementation should implement this method.
  998. .. versionadded:: 2.0
  999. """
  1000. raise NotImplementedError()
  1001. def get_foreign_keys(
  1002. self,
  1003. connection: Connection,
  1004. table_name: str,
  1005. schema: Optional[str] = None,
  1006. **kw: Any,
  1007. ) -> List[ReflectedForeignKeyConstraint]:
  1008. """Return information about foreign_keys in ``table_name``.
  1009. Given a :class:`_engine.Connection`, a string
  1010. ``table_name``, and an optional string ``schema``, return foreign
  1011. key information as a list of dicts corresponding to the
  1012. :class:`.ReflectedForeignKeyConstraint` dictionary.
  1013. This is an internal dialect method. Applications should use
  1014. :meth:`_engine.Inspector.get_foreign_keys`.
  1015. """
  1016. raise NotImplementedError()
  1017. def get_multi_foreign_keys(
  1018. self,
  1019. connection: Connection,
  1020. *,
  1021. schema: Optional[str] = None,
  1022. filter_names: Optional[Collection[str]] = None,
  1023. **kw: Any,
  1024. ) -> Iterable[Tuple[TableKey, List[ReflectedForeignKeyConstraint]]]:
  1025. """Return information about foreign_keys in all tables
  1026. in the given ``schema``.
  1027. This is an internal dialect method. Applications should use
  1028. :meth:`_engine.Inspector.get_multi_foreign_keys`.
  1029. .. note:: The :class:`_engine.DefaultDialect` provides a default
  1030. implementation that will call the single table method for
  1031. each object returned by :meth:`Dialect.get_table_names`,
  1032. :meth:`Dialect.get_view_names` or
  1033. :meth:`Dialect.get_materialized_view_names` depending on the
  1034. provided ``kind``. Dialects that want to support a faster
  1035. implementation should implement this method.
  1036. .. versionadded:: 2.0
  1037. """
  1038. raise NotImplementedError()
  1039. def get_table_names(
  1040. self, connection: Connection, schema: Optional[str] = None, **kw: Any
  1041. ) -> List[str]:
  1042. """Return a list of table names for ``schema``.
  1043. This is an internal dialect method. Applications should use
  1044. :meth:`_engine.Inspector.get_table_names`.
  1045. """
  1046. raise NotImplementedError()
  1047. def get_temp_table_names(
  1048. self, connection: Connection, schema: Optional[str] = None, **kw: Any
  1049. ) -> List[str]:
  1050. """Return a list of temporary table names on the given connection,
  1051. if supported by the underlying backend.
  1052. This is an internal dialect method. Applications should use
  1053. :meth:`_engine.Inspector.get_temp_table_names`.
  1054. """
  1055. raise NotImplementedError()
  1056. def get_view_names(
  1057. self, connection: Connection, schema: Optional[str] = None, **kw: Any
  1058. ) -> List[str]:
  1059. """Return a list of all non-materialized view names available in the
  1060. database.
  1061. This is an internal dialect method. Applications should use
  1062. :meth:`_engine.Inspector.get_view_names`.
  1063. :param schema: schema name to query, if not the default schema.
  1064. """
  1065. raise NotImplementedError()
  1066. def get_materialized_view_names(
  1067. self, connection: Connection, schema: Optional[str] = None, **kw: Any
  1068. ) -> List[str]:
  1069. """Return a list of all materialized view names available in the
  1070. database.
  1071. This is an internal dialect method. Applications should use
  1072. :meth:`_engine.Inspector.get_materialized_view_names`.
  1073. :param schema: schema name to query, if not the default schema.
  1074. .. versionadded:: 2.0
  1075. """
  1076. raise NotImplementedError()
  1077. def get_sequence_names(
  1078. self, connection: Connection, schema: Optional[str] = None, **kw: Any
  1079. ) -> List[str]:
  1080. """Return a list of all sequence names available in the database.
  1081. This is an internal dialect method. Applications should use
  1082. :meth:`_engine.Inspector.get_sequence_names`.
  1083. :param schema: schema name to query, if not the default schema.
  1084. .. versionadded:: 1.4
  1085. """
  1086. raise NotImplementedError()
  1087. def get_temp_view_names(
  1088. self, connection: Connection, schema: Optional[str] = None, **kw: Any
  1089. ) -> List[str]:
  1090. """Return a list of temporary view names on the given connection,
  1091. if supported by the underlying backend.
  1092. This is an internal dialect method. Applications should use
  1093. :meth:`_engine.Inspector.get_temp_view_names`.
  1094. """
  1095. raise NotImplementedError()
  1096. def get_schema_names(self, connection: Connection, **kw: Any) -> List[str]:
  1097. """Return a list of all schema names available in the database.
  1098. This is an internal dialect method. Applications should use
  1099. :meth:`_engine.Inspector.get_schema_names`.
  1100. """
  1101. raise NotImplementedError()
  1102. def get_view_definition(
  1103. self,
  1104. connection: Connection,
  1105. view_name: str,
  1106. schema: Optional[str] = None,
  1107. **kw: Any,
  1108. ) -> str:
  1109. """Return plain or materialized view definition.
  1110. This is an internal dialect method. Applications should use
  1111. :meth:`_engine.Inspector.get_view_definition`.
  1112. Given a :class:`_engine.Connection`, a string
  1113. ``view_name``, and an optional string ``schema``, return the view
  1114. definition.
  1115. """
  1116. raise NotImplementedError()
  1117. def get_indexes(
  1118. self,
  1119. connection: Connection,
  1120. table_name: str,
  1121. schema: Optional[str] = None,
  1122. **kw: Any,
  1123. ) -> List[ReflectedIndex]:
  1124. """Return information about indexes in ``table_name``.
  1125. Given a :class:`_engine.Connection`, a string
  1126. ``table_name`` and an optional string ``schema``, return index
  1127. information as a list of dictionaries corresponding to the
  1128. :class:`.ReflectedIndex` dictionary.
  1129. This is an internal dialect method. Applications should use
  1130. :meth:`.Inspector.get_indexes`.
  1131. """
  1132. raise NotImplementedError()
  1133. def get_multi_indexes(
  1134. self,
  1135. connection: Connection,
  1136. *,
  1137. schema: Optional[str] = None,
  1138. filter_names: Optional[Collection[str]] = None,
  1139. **kw: Any,
  1140. ) -> Iterable[Tuple[TableKey, List[ReflectedIndex]]]:
  1141. """Return information about indexes in in all tables
  1142. in the given ``schema``.
  1143. This is an internal dialect method. Applications should use
  1144. :meth:`.Inspector.get_multi_indexes`.
  1145. .. note:: The :class:`_engine.DefaultDialect` provides a default
  1146. implementation that will call the single table method for
  1147. each object returned by :meth:`Dialect.get_table_names`,
  1148. :meth:`Dialect.get_view_names` or
  1149. :meth:`Dialect.get_materialized_view_names` depending on the
  1150. provided ``kind``. Dialects that want to support a faster
  1151. implementation should implement this method.
  1152. .. versionadded:: 2.0
  1153. """
  1154. raise NotImplementedError()
  1155. def get_unique_constraints(
  1156. self,
  1157. connection: Connection,
  1158. table_name: str,
  1159. schema: Optional[str] = None,
  1160. **kw: Any,
  1161. ) -> List[ReflectedUniqueConstraint]:
  1162. r"""Return information about unique constraints in ``table_name``.
  1163. Given a string ``table_name`` and an optional string ``schema``, return
  1164. unique constraint information as a list of dicts corresponding
  1165. to the :class:`.ReflectedUniqueConstraint` dictionary.
  1166. This is an internal dialect method. Applications should use
  1167. :meth:`.Inspector.get_unique_constraints`.
  1168. """
  1169. raise NotImplementedError()
  1170. def get_multi_unique_constraints(
  1171. self,
  1172. connection: Connection,
  1173. *,
  1174. schema: Optional[str] = None,
  1175. filter_names: Optional[Collection[str]] = None,
  1176. **kw: Any,
  1177. ) -> Iterable[Tuple[TableKey, List[ReflectedUniqueConstraint]]]:
  1178. """Return information about unique constraints in all tables
  1179. in the given ``schema``.
  1180. This is an internal dialect method. Applications should use
  1181. :meth:`.Inspector.get_multi_unique_constraints`.
  1182. .. note:: The :class:`_engine.DefaultDialect` provides a default
  1183. implementation that will call the single table method for
  1184. each object returned by :meth:`Dialect.get_table_names`,
  1185. :meth:`Dialect.get_view_names` or
  1186. :meth:`Dialect.get_materialized_view_names` depending on the
  1187. provided ``kind``. Dialects that want to support a faster
  1188. implementation should implement this method.
  1189. .. versionadded:: 2.0
  1190. """
  1191. raise NotImplementedError()
  1192. def get_check_constraints(
  1193. self,
  1194. connection: Connection,
  1195. table_name: str,
  1196. schema: Optional[str] = None,
  1197. **kw: Any,
  1198. ) -> List[ReflectedCheckConstraint]:
  1199. r"""Return information about check constraints in ``table_name``.
  1200. Given a string ``table_name`` and an optional string ``schema``, return
  1201. check constraint information as a list of dicts corresponding
  1202. to the :class:`.ReflectedCheckConstraint` dictionary.
  1203. This is an internal dialect method. Applications should use
  1204. :meth:`.Inspector.get_check_constraints`.
  1205. """
  1206. raise NotImplementedError()
  1207. def get_multi_check_constraints(
  1208. self,
  1209. connection: Connection,
  1210. *,
  1211. schema: Optional[str] = None,
  1212. filter_names: Optional[Collection[str]] = None,
  1213. **kw: Any,
  1214. ) -> Iterable[Tuple[TableKey, List[ReflectedCheckConstraint]]]:
  1215. """Return information about check constraints in all tables
  1216. in the given ``schema``.
  1217. This is an internal dialect method. Applications should use
  1218. :meth:`.Inspector.get_multi_check_constraints`.
  1219. .. note:: The :class:`_engine.DefaultDialect` provides a default
  1220. implementation that will call the single table method for
  1221. each object returned by :meth:`Dialect.get_table_names`,
  1222. :meth:`Dialect.get_view_names` or
  1223. :meth:`Dialect.get_materialized_view_names` depending on the
  1224. provided ``kind``. Dialects that want to support a faster
  1225. implementation should implement this method.
  1226. .. versionadded:: 2.0
  1227. """
  1228. raise NotImplementedError()
  1229. def get_table_options(
  1230. self,
  1231. connection: Connection,
  1232. table_name: str,
  1233. schema: Optional[str] = None,
  1234. **kw: Any,
  1235. ) -> Dict[str, Any]:
  1236. """Return a dictionary of options specified when ``table_name``
  1237. was created.
  1238. This is an internal dialect method. Applications should use
  1239. :meth:`_engine.Inspector.get_table_options`.
  1240. """
  1241. raise NotImplementedError()
  1242. def get_multi_table_options(
  1243. self,
  1244. connection: Connection,
  1245. *,
  1246. schema: Optional[str] = None,
  1247. filter_names: Optional[Collection[str]] = None,
  1248. **kw: Any,
  1249. ) -> Iterable[Tuple[TableKey, Dict[str, Any]]]:
  1250. """Return a dictionary of options specified when the tables in the
  1251. given schema were created.
  1252. This is an internal dialect method. Applications should use
  1253. :meth:`_engine.Inspector.get_multi_table_options`.
  1254. .. note:: The :class:`_engine.DefaultDialect` provides a default
  1255. implementation that will call the single table method for
  1256. each object returned by :meth:`Dialect.get_table_names`,
  1257. :meth:`Dialect.get_view_names` or
  1258. :meth:`Dialect.get_materialized_view_names` depending on the
  1259. provided ``kind``. Dialects that want to support a faster
  1260. implementation should implement this method.
  1261. .. versionadded:: 2.0
  1262. """
  1263. raise NotImplementedError()
  1264. def get_table_comment(
  1265. self,
  1266. connection: Connection,
  1267. table_name: str,
  1268. schema: Optional[str] = None,
  1269. **kw: Any,
  1270. ) -> ReflectedTableComment:
  1271. r"""Return the "comment" for the table identified by ``table_name``.
  1272. Given a string ``table_name`` and an optional string ``schema``, return
  1273. table comment information as a dictionary corresponding to the
  1274. :class:`.ReflectedTableComment` dictionary.
  1275. This is an internal dialect method. Applications should use
  1276. :meth:`.Inspector.get_table_comment`.
  1277. :raise: ``NotImplementedError`` for dialects that don't support
  1278. comments.
  1279. .. versionadded:: 1.2
  1280. """
  1281. raise NotImplementedError()
  1282. def get_multi_table_comment(
  1283. self,
  1284. connection: Connection,
  1285. *,
  1286. schema: Optional[str] = None,
  1287. filter_names: Optional[Collection[str]] = None,
  1288. **kw: Any,
  1289. ) -> Iterable[Tuple[TableKey, ReflectedTableComment]]:
  1290. """Return information about the table comment in all tables
  1291. in the given ``schema``.
  1292. This is an internal dialect method. Applications should use
  1293. :meth:`_engine.Inspector.get_multi_table_comment`.
  1294. .. note:: The :class:`_engine.DefaultDialect` provides a default
  1295. implementation that will call the single table method for
  1296. each object returned by :meth:`Dialect.get_table_names`,
  1297. :meth:`Dialect.get_view_names` or
  1298. :meth:`Dialect.get_materialized_view_names` depending on the
  1299. provided ``kind``. Dialects that want to support a faster
  1300. implementation should implement this method.
  1301. .. versionadded:: 2.0
  1302. """
  1303. raise NotImplementedError()
  1304. def normalize_name(self, name: str) -> str:
  1305. """convert the given name to lowercase if it is detected as
  1306. case insensitive.
  1307. This method is only used if the dialect defines
  1308. requires_name_normalize=True.
  1309. """
  1310. raise NotImplementedError()
  1311. def denormalize_name(self, name: str) -> str:
  1312. """convert the given name to a case insensitive identifier
  1313. for the backend if it is an all-lowercase name.
  1314. This method is only used if the dialect defines
  1315. requires_name_normalize=True.
  1316. """
  1317. raise NotImplementedError()
  1318. def has_table(
  1319. self,
  1320. connection: Connection,
  1321. table_name: str,
  1322. schema: Optional[str] = None,
  1323. **kw: Any,
  1324. ) -> bool:
  1325. """For internal dialect use, check the existence of a particular table
  1326. or view in the database.
  1327. Given a :class:`_engine.Connection` object, a string table_name and
  1328. optional schema name, return True if the given table exists in the
  1329. database, False otherwise.
  1330. This method serves as the underlying implementation of the
  1331. public facing :meth:`.Inspector.has_table` method, and is also used
  1332. internally to implement the "checkfirst" behavior for methods like
  1333. :meth:`_schema.Table.create` and :meth:`_schema.MetaData.create_all`.
  1334. .. note:: This method is used internally by SQLAlchemy, and is
  1335. published so that third-party dialects may provide an
  1336. implementation. It is **not** the public API for checking for table
  1337. presence. Please use the :meth:`.Inspector.has_table` method.
  1338. .. versionchanged:: 2.0:: :meth:`_engine.Dialect.has_table` now
  1339. formally supports checking for additional table-like objects:
  1340. * any type of views (plain or materialized)
  1341. * temporary tables of any kind
  1342. Previously, these two checks were not formally specified and
  1343. different dialects would vary in their behavior. The dialect
  1344. testing suite now includes tests for all of these object types,
  1345. and dialects to the degree that the backing database supports views
  1346. or temporary tables should seek to support locating these objects
  1347. for full compliance.
  1348. """
  1349. raise NotImplementedError()
  1350. def has_index(
  1351. self,
  1352. connection: Connection,
  1353. table_name: str,
  1354. index_name: str,
  1355. schema: Optional[str] = None,
  1356. **kw: Any,
  1357. ) -> bool:
  1358. """Check the existence of a particular index name in the database.
  1359. Given a :class:`_engine.Connection` object, a string
  1360. ``table_name`` and string index name, return ``True`` if an index of
  1361. the given name on the given table exists, ``False`` otherwise.
  1362. The :class:`.DefaultDialect` implements this in terms of the
  1363. :meth:`.Dialect.has_table` and :meth:`.Dialect.get_indexes` methods,
  1364. however dialects can implement a more performant version.
  1365. This is an internal dialect method. Applications should use
  1366. :meth:`_engine.Inspector.has_index`.
  1367. .. versionadded:: 1.4
  1368. """
  1369. raise NotImplementedError()
  1370. def has_sequence(
  1371. self,
  1372. connection: Connection,
  1373. sequence_name: str,
  1374. schema: Optional[str] = None,
  1375. **kw: Any,
  1376. ) -> bool:
  1377. """Check the existence of a particular sequence in the database.
  1378. Given a :class:`_engine.Connection` object and a string
  1379. `sequence_name`, return ``True`` if the given sequence exists in
  1380. the database, ``False`` otherwise.
  1381. This is an internal dialect method. Applications should use
  1382. :meth:`_engine.Inspector.has_sequence`.
  1383. """
  1384. raise NotImplementedError()
  1385. def has_schema(
  1386. self, connection: Connection, schema_name: str, **kw: Any
  1387. ) -> bool:
  1388. """Check the existence of a particular schema name in the database.
  1389. Given a :class:`_engine.Connection` object, a string
  1390. ``schema_name``, return ``True`` if a schema of the
  1391. given exists, ``False`` otherwise.
  1392. The :class:`.DefaultDialect` implements this by checking
  1393. the presence of ``schema_name`` among the schemas returned by
  1394. :meth:`.Dialect.get_schema_names`,
  1395. however dialects can implement a more performant version.
  1396. This is an internal dialect method. Applications should use
  1397. :meth:`_engine.Inspector.has_schema`.
  1398. .. versionadded:: 2.0
  1399. """
  1400. raise NotImplementedError()
  1401. def _get_server_version_info(self, connection: Connection) -> Any:
  1402. """Retrieve the server version info from the given connection.
  1403. This is used by the default implementation to populate the
  1404. "server_version_info" attribute and is called exactly
  1405. once upon first connect.
  1406. """
  1407. raise NotImplementedError()
  1408. def _get_default_schema_name(self, connection: Connection) -> str:
  1409. """Return the string name of the currently selected schema from
  1410. the given connection.
  1411. This is used by the default implementation to populate the
  1412. "default_schema_name" attribute and is called exactly
  1413. once upon first connect.
  1414. """
  1415. raise NotImplementedError()
  1416. def do_begin(self, dbapi_connection: PoolProxiedConnection) -> None:
  1417. """Provide an implementation of ``connection.begin()``, given a
  1418. DB-API connection.
  1419. The DBAPI has no dedicated "begin" method and it is expected
  1420. that transactions are implicit. This hook is provided for those
  1421. DBAPIs that might need additional help in this area.
  1422. :param dbapi_connection: a DBAPI connection, typically
  1423. proxied within a :class:`.ConnectionFairy`.
  1424. """
  1425. raise NotImplementedError()
  1426. def do_rollback(self, dbapi_connection: PoolProxiedConnection) -> None:
  1427. """Provide an implementation of ``connection.rollback()``, given
  1428. a DB-API connection.
  1429. :param dbapi_connection: a DBAPI connection, typically
  1430. proxied within a :class:`.ConnectionFairy`.
  1431. """
  1432. raise NotImplementedError()
  1433. def do_commit(self, dbapi_connection: PoolProxiedConnection) -> None:
  1434. """Provide an implementation of ``connection.commit()``, given a
  1435. DB-API connection.
  1436. :param dbapi_connection: a DBAPI connection, typically
  1437. proxied within a :class:`.ConnectionFairy`.
  1438. """
  1439. raise NotImplementedError()
  1440. def do_terminate(self, dbapi_connection: DBAPIConnection) -> None:
  1441. """Provide an implementation of ``connection.close()`` that tries as
  1442. much as possible to not block, given a DBAPI
  1443. connection.
  1444. In the vast majority of cases this just calls .close(), however
  1445. for some asyncio dialects may call upon different API features.
  1446. This hook is called by the :class:`_pool.Pool`
  1447. when a connection is being recycled or has been invalidated.
  1448. .. versionadded:: 1.4.41
  1449. """
  1450. raise NotImplementedError()
  1451. def do_close(self, dbapi_connection: DBAPIConnection) -> None:
  1452. """Provide an implementation of ``connection.close()``, given a DBAPI
  1453. connection.
  1454. This hook is called by the :class:`_pool.Pool`
  1455. when a connection has been
  1456. detached from the pool, or is being returned beyond the normal
  1457. capacity of the pool.
  1458. """
  1459. raise NotImplementedError()
  1460. def _do_ping_w_event(self, dbapi_connection: DBAPIConnection) -> bool:
  1461. raise NotImplementedError()
  1462. def do_ping(self, dbapi_connection: DBAPIConnection) -> bool:
  1463. """ping the DBAPI connection and return True if the connection is
  1464. usable."""
  1465. raise NotImplementedError()
  1466. def do_set_input_sizes(
  1467. self,
  1468. cursor: DBAPICursor,
  1469. list_of_tuples: _GenericSetInputSizesType,
  1470. context: ExecutionContext,
  1471. ) -> Any:
  1472. """invoke the cursor.setinputsizes() method with appropriate arguments
  1473. This hook is called if the :attr:`.Dialect.bind_typing` attribute is
  1474. set to the
  1475. :attr:`.BindTyping.SETINPUTSIZES` value.
  1476. Parameter data is passed in a list of tuples (paramname, dbtype,
  1477. sqltype), where ``paramname`` is the key of the parameter in the
  1478. statement, ``dbtype`` is the DBAPI datatype and ``sqltype`` is the
  1479. SQLAlchemy type. The order of tuples is in the correct parameter order.
  1480. .. versionadded:: 1.4
  1481. .. versionchanged:: 2.0 - setinputsizes mode is now enabled by
  1482. setting :attr:`.Dialect.bind_typing` to
  1483. :attr:`.BindTyping.SETINPUTSIZES`. Dialects which accept
  1484. a ``use_setinputsizes`` parameter should set this value
  1485. appropriately.
  1486. """
  1487. raise NotImplementedError()
  1488. def create_xid(self) -> Any:
  1489. """Create a two-phase transaction ID.
  1490. This id will be passed to do_begin_twophase(),
  1491. do_rollback_twophase(), do_commit_twophase(). Its format is
  1492. unspecified.
  1493. """
  1494. raise NotImplementedError()
  1495. def do_savepoint(self, connection: Connection, name: str) -> None:
  1496. """Create a savepoint with the given name.
  1497. :param connection: a :class:`_engine.Connection`.
  1498. :param name: savepoint name.
  1499. """
  1500. raise NotImplementedError()
  1501. def do_rollback_to_savepoint(
  1502. self, connection: Connection, name: str
  1503. ) -> None:
  1504. """Rollback a connection to the named savepoint.
  1505. :param connection: a :class:`_engine.Connection`.
  1506. :param name: savepoint name.
  1507. """
  1508. raise NotImplementedError()
  1509. def do_release_savepoint(self, connection: Connection, name: str) -> None:
  1510. """Release the named savepoint on a connection.
  1511. :param connection: a :class:`_engine.Connection`.
  1512. :param name: savepoint name.
  1513. """
  1514. raise NotImplementedError()
  1515. def do_begin_twophase(self, connection: Connection, xid: Any) -> None:
  1516. """Begin a two phase transaction on the given connection.
  1517. :param connection: a :class:`_engine.Connection`.
  1518. :param xid: xid
  1519. """
  1520. raise NotImplementedError()
  1521. def do_prepare_twophase(self, connection: Connection, xid: Any) -> None:
  1522. """Prepare a two phase transaction on the given connection.
  1523. :param connection: a :class:`_engine.Connection`.
  1524. :param xid: xid
  1525. """
  1526. raise NotImplementedError()
  1527. def do_rollback_twophase(
  1528. self,
  1529. connection: Connection,
  1530. xid: Any,
  1531. is_prepared: bool = True,
  1532. recover: bool = False,
  1533. ) -> None:
  1534. """Rollback a two phase transaction on the given connection.
  1535. :param connection: a :class:`_engine.Connection`.
  1536. :param xid: xid
  1537. :param is_prepared: whether or not
  1538. :meth:`.TwoPhaseTransaction.prepare` was called.
  1539. :param recover: if the recover flag was passed.
  1540. """
  1541. raise NotImplementedError()
  1542. def do_commit_twophase(
  1543. self,
  1544. connection: Connection,
  1545. xid: Any,
  1546. is_prepared: bool = True,
  1547. recover: bool = False,
  1548. ) -> None:
  1549. """Commit a two phase transaction on the given connection.
  1550. :param connection: a :class:`_engine.Connection`.
  1551. :param xid: xid
  1552. :param is_prepared: whether or not
  1553. :meth:`.TwoPhaseTransaction.prepare` was called.
  1554. :param recover: if the recover flag was passed.
  1555. """
  1556. raise NotImplementedError()
  1557. def do_recover_twophase(self, connection: Connection) -> List[Any]:
  1558. """Recover list of uncommitted prepared two phase transaction
  1559. identifiers on the given connection.
  1560. :param connection: a :class:`_engine.Connection`.
  1561. """
  1562. raise NotImplementedError()
  1563. def _deliver_insertmanyvalues_batches(
  1564. self,
  1565. connection: Connection,
  1566. cursor: DBAPICursor,
  1567. statement: str,
  1568. parameters: _DBAPIMultiExecuteParams,
  1569. generic_setinputsizes: Optional[_GenericSetInputSizesType],
  1570. context: ExecutionContext,
  1571. ) -> Iterator[_InsertManyValuesBatch]:
  1572. """convert executemany parameters for an INSERT into an iterator
  1573. of statement/single execute values, used by the insertmanyvalues
  1574. feature.
  1575. """
  1576. raise NotImplementedError()
  1577. def do_executemany(
  1578. self,
  1579. cursor: DBAPICursor,
  1580. statement: str,
  1581. parameters: _DBAPIMultiExecuteParams,
  1582. context: Optional[ExecutionContext] = None,
  1583. ) -> None:
  1584. """Provide an implementation of ``cursor.executemany(statement,
  1585. parameters)``."""
  1586. raise NotImplementedError()
  1587. def do_execute(
  1588. self,
  1589. cursor: DBAPICursor,
  1590. statement: str,
  1591. parameters: Optional[_DBAPISingleExecuteParams],
  1592. context: Optional[ExecutionContext] = None,
  1593. ) -> None:
  1594. """Provide an implementation of ``cursor.execute(statement,
  1595. parameters)``."""
  1596. raise NotImplementedError()
  1597. def do_execute_no_params(
  1598. self,
  1599. cursor: DBAPICursor,
  1600. statement: str,
  1601. context: Optional[ExecutionContext] = None,
  1602. ) -> None:
  1603. """Provide an implementation of ``cursor.execute(statement)``.
  1604. The parameter collection should not be sent.
  1605. """
  1606. raise NotImplementedError()
  1607. def is_disconnect(
  1608. self,
  1609. e: DBAPIModule.Error,
  1610. connection: Optional[Union[PoolProxiedConnection, DBAPIConnection]],
  1611. cursor: Optional[DBAPICursor],
  1612. ) -> bool:
  1613. """Return True if the given DB-API error indicates an invalid
  1614. connection"""
  1615. raise NotImplementedError()
  1616. def connect(self, *cargs: Any, **cparams: Any) -> DBAPIConnection:
  1617. r"""Establish a connection using this dialect's DBAPI.
  1618. The default implementation of this method is::
  1619. def connect(self, *cargs, **cparams):
  1620. return self.dbapi.connect(*cargs, **cparams)
  1621. The ``*cargs, **cparams`` parameters are generated directly
  1622. from this dialect's :meth:`.Dialect.create_connect_args` method.
  1623. This method may be used for dialects that need to perform programmatic
  1624. per-connection steps when a new connection is procured from the
  1625. DBAPI.
  1626. :param \*cargs: positional parameters returned from the
  1627. :meth:`.Dialect.create_connect_args` method
  1628. :param \*\*cparams: keyword parameters returned from the
  1629. :meth:`.Dialect.create_connect_args` method.
  1630. :return: a DBAPI connection, typically from the :pep:`249` module
  1631. level ``.connect()`` function.
  1632. .. seealso::
  1633. :meth:`.Dialect.create_connect_args`
  1634. :meth:`.Dialect.on_connect`
  1635. """
  1636. raise NotImplementedError()
  1637. def on_connect_url(self, url: URL) -> Optional[Callable[[Any], Any]]:
  1638. """return a callable which sets up a newly created DBAPI connection.
  1639. This method is a new hook that supersedes the
  1640. :meth:`_engine.Dialect.on_connect` method when implemented by a
  1641. dialect. When not implemented by a dialect, it invokes the
  1642. :meth:`_engine.Dialect.on_connect` method directly to maintain
  1643. compatibility with existing dialects. There is no deprecation
  1644. for :meth:`_engine.Dialect.on_connect` expected.
  1645. The callable should accept a single argument "conn" which is the
  1646. DBAPI connection itself. The inner callable has no
  1647. return value.
  1648. E.g.::
  1649. class MyDialect(default.DefaultDialect):
  1650. # ...
  1651. def on_connect_url(self, url):
  1652. def do_on_connect(connection):
  1653. connection.execute("SET SPECIAL FLAGS etc")
  1654. return do_on_connect
  1655. This is used to set dialect-wide per-connection options such as
  1656. isolation modes, Unicode modes, etc.
  1657. This method differs from :meth:`_engine.Dialect.on_connect` in that
  1658. it is passed the :class:`_engine.URL` object that's relevant to the
  1659. connect args. Normally the only way to get this is from the
  1660. :meth:`_engine.Dialect.on_connect` hook is to look on the
  1661. :class:`_engine.Engine` itself, however this URL object may have been
  1662. replaced by plugins.
  1663. .. note::
  1664. The default implementation of
  1665. :meth:`_engine.Dialect.on_connect_url` is to invoke the
  1666. :meth:`_engine.Dialect.on_connect` method. Therefore if a dialect
  1667. implements this method, the :meth:`_engine.Dialect.on_connect`
  1668. method **will not be called** unless the overriding dialect calls
  1669. it directly from here.
  1670. .. versionadded:: 1.4.3 added :meth:`_engine.Dialect.on_connect_url`
  1671. which normally calls into :meth:`_engine.Dialect.on_connect`.
  1672. :param url: a :class:`_engine.URL` object representing the
  1673. :class:`_engine.URL` that was passed to the
  1674. :meth:`_engine.Dialect.create_connect_args` method.
  1675. :return: a callable that accepts a single DBAPI connection as an
  1676. argument, or None.
  1677. .. seealso::
  1678. :meth:`_engine.Dialect.on_connect`
  1679. """
  1680. return self.on_connect()
  1681. def on_connect(self) -> Optional[Callable[[Any], None]]:
  1682. """return a callable which sets up a newly created DBAPI connection.
  1683. The callable should accept a single argument "conn" which is the
  1684. DBAPI connection itself. The inner callable has no
  1685. return value.
  1686. E.g.::
  1687. class MyDialect(default.DefaultDialect):
  1688. # ...
  1689. def on_connect(self):
  1690. def do_on_connect(connection):
  1691. connection.execute("SET SPECIAL FLAGS etc")
  1692. return do_on_connect
  1693. This is used to set dialect-wide per-connection options such as
  1694. isolation modes, Unicode modes, etc.
  1695. The "do_on_connect" callable is invoked by using the
  1696. :meth:`_events.PoolEvents.connect` event
  1697. hook, then unwrapping the DBAPI connection and passing it into the
  1698. callable.
  1699. .. versionchanged:: 1.4 the on_connect hook is no longer called twice
  1700. for the first connection of a dialect. The on_connect hook is still
  1701. called before the :meth:`_engine.Dialect.initialize` method however.
  1702. .. versionchanged:: 1.4.3 the on_connect hook is invoked from a new
  1703. method on_connect_url that passes the URL that was used to create
  1704. the connect args. Dialects can implement on_connect_url instead
  1705. of on_connect if they need the URL object that was used for the
  1706. connection in order to get additional context.
  1707. If None is returned, no event listener is generated.
  1708. :return: a callable that accepts a single DBAPI connection as an
  1709. argument, or None.
  1710. .. seealso::
  1711. :meth:`.Dialect.connect` - allows the DBAPI ``connect()`` sequence
  1712. itself to be controlled.
  1713. :meth:`.Dialect.on_connect_url` - supersedes
  1714. :meth:`.Dialect.on_connect` to also receive the
  1715. :class:`_engine.URL` object in context.
  1716. """
  1717. return None
  1718. def reset_isolation_level(self, dbapi_connection: DBAPIConnection) -> None:
  1719. """Given a DBAPI connection, revert its isolation to the default.
  1720. Note that this is a dialect-level method which is used as part
  1721. of the implementation of the :class:`_engine.Connection` and
  1722. :class:`_engine.Engine`
  1723. isolation level facilities; these APIs should be preferred for
  1724. most typical use cases.
  1725. .. seealso::
  1726. :meth:`_engine.Connection.get_isolation_level`
  1727. - view current level
  1728. :attr:`_engine.Connection.default_isolation_level`
  1729. - view default level
  1730. :paramref:`.Connection.execution_options.isolation_level` -
  1731. set per :class:`_engine.Connection` isolation level
  1732. :paramref:`_sa.create_engine.isolation_level` -
  1733. set per :class:`_engine.Engine` isolation level
  1734. """
  1735. raise NotImplementedError()
  1736. def set_isolation_level(
  1737. self, dbapi_connection: DBAPIConnection, level: IsolationLevel
  1738. ) -> None:
  1739. """Given a DBAPI connection, set its isolation level.
  1740. Note that this is a dialect-level method which is used as part
  1741. of the implementation of the :class:`_engine.Connection` and
  1742. :class:`_engine.Engine`
  1743. isolation level facilities; these APIs should be preferred for
  1744. most typical use cases.
  1745. If the dialect also implements the
  1746. :meth:`.Dialect.get_isolation_level_values` method, then the given
  1747. level is guaranteed to be one of the string names within that sequence,
  1748. and the method will not need to anticipate a lookup failure.
  1749. .. seealso::
  1750. :meth:`_engine.Connection.get_isolation_level`
  1751. - view current level
  1752. :attr:`_engine.Connection.default_isolation_level`
  1753. - view default level
  1754. :paramref:`.Connection.execution_options.isolation_level` -
  1755. set per :class:`_engine.Connection` isolation level
  1756. :paramref:`_sa.create_engine.isolation_level` -
  1757. set per :class:`_engine.Engine` isolation level
  1758. """
  1759. raise NotImplementedError()
  1760. def get_isolation_level(
  1761. self, dbapi_connection: DBAPIConnection
  1762. ) -> IsolationLevel:
  1763. """Given a DBAPI connection, return its isolation level.
  1764. When working with a :class:`_engine.Connection` object,
  1765. the corresponding
  1766. DBAPI connection may be procured using the
  1767. :attr:`_engine.Connection.connection` accessor.
  1768. Note that this is a dialect-level method which is used as part
  1769. of the implementation of the :class:`_engine.Connection` and
  1770. :class:`_engine.Engine` isolation level facilities;
  1771. these APIs should be preferred for most typical use cases.
  1772. .. seealso::
  1773. :meth:`_engine.Connection.get_isolation_level`
  1774. - view current level
  1775. :attr:`_engine.Connection.default_isolation_level`
  1776. - view default level
  1777. :paramref:`.Connection.execution_options.isolation_level` -
  1778. set per :class:`_engine.Connection` isolation level
  1779. :paramref:`_sa.create_engine.isolation_level` -
  1780. set per :class:`_engine.Engine` isolation level
  1781. """
  1782. raise NotImplementedError()
  1783. def detect_autocommit_setting(self, dbapi_conn: DBAPIConnection) -> bool:
  1784. """Detect the current autocommit setting for a DBAPI connection.
  1785. :param dbapi_connection: a DBAPI connection object
  1786. :return: True if autocommit is enabled, False if disabled
  1787. :rtype: bool
  1788. This method inspects the given DBAPI connection to determine
  1789. whether autocommit mode is currently enabled. The specific
  1790. mechanism for detecting autocommit varies by database dialect
  1791. and DBAPI driver, however it should be done **without** network
  1792. round trips.
  1793. .. note::
  1794. Not all dialects support autocommit detection. Dialects
  1795. that do not support this feature will raise
  1796. :exc:`NotImplementedError`.
  1797. """
  1798. raise NotImplementedError(
  1799. "This dialect cannot detect autocommit on a DBAPI connection"
  1800. )
  1801. def get_default_isolation_level(
  1802. self, dbapi_conn: DBAPIConnection
  1803. ) -> IsolationLevel:
  1804. """Given a DBAPI connection, return its isolation level, or
  1805. a default isolation level if one cannot be retrieved.
  1806. This method may only raise NotImplementedError and
  1807. **must not raise any other exception**, as it is used implicitly upon
  1808. first connect.
  1809. The method **must return a value** for a dialect that supports
  1810. isolation level settings, as this level is what will be reverted
  1811. towards when a per-connection isolation level change is made.
  1812. The method defaults to using the :meth:`.Dialect.get_isolation_level`
  1813. method unless overridden by a dialect.
  1814. .. versionadded:: 1.3.22
  1815. """
  1816. raise NotImplementedError()
  1817. def get_isolation_level_values(
  1818. self, dbapi_conn: DBAPIConnection
  1819. ) -> Sequence[IsolationLevel]:
  1820. """return a sequence of string isolation level names that are accepted
  1821. by this dialect.
  1822. The available names should use the following conventions:
  1823. * use UPPERCASE names. isolation level methods will accept lowercase
  1824. names but these are normalized into UPPERCASE before being passed
  1825. along to the dialect.
  1826. * separate words should be separated by spaces, not underscores, e.g.
  1827. ``REPEATABLE READ``. isolation level names will have underscores
  1828. converted to spaces before being passed along to the dialect.
  1829. * The names for the four standard isolation names to the extent that
  1830. they are supported by the backend should be ``READ UNCOMMITTED``,
  1831. ``READ COMMITTED``, ``REPEATABLE READ``, ``SERIALIZABLE``
  1832. * if the dialect supports an autocommit option it should be provided
  1833. using the isolation level name ``AUTOCOMMIT``.
  1834. * Other isolation modes may also be present, provided that they
  1835. are named in UPPERCASE and use spaces not underscores.
  1836. This function is used so that the default dialect can check that
  1837. a given isolation level parameter is valid, else raises an
  1838. :class:`_exc.ArgumentError`.
  1839. A DBAPI connection is passed to the method, in the unlikely event that
  1840. the dialect needs to interrogate the connection itself to determine
  1841. this list, however it is expected that most backends will return
  1842. a hardcoded list of values. If the dialect supports "AUTOCOMMIT",
  1843. that value should also be present in the sequence returned.
  1844. The method raises ``NotImplementedError`` by default. If a dialect
  1845. does not implement this method, then the default dialect will not
  1846. perform any checking on a given isolation level value before passing
  1847. it onto the :meth:`.Dialect.set_isolation_level` method. This is
  1848. to allow backwards-compatibility with third party dialects that may
  1849. not yet be implementing this method.
  1850. .. versionadded:: 2.0
  1851. """
  1852. raise NotImplementedError()
  1853. def _assert_and_set_isolation_level(
  1854. self, dbapi_conn: DBAPIConnection, level: IsolationLevel
  1855. ) -> None:
  1856. raise NotImplementedError()
  1857. @classmethod
  1858. def get_dialect_cls(cls, url: URL) -> Type[Dialect]:
  1859. """Given a URL, return the :class:`.Dialect` that will be used.
  1860. This is a hook that allows an external plugin to provide functionality
  1861. around an existing dialect, by allowing the plugin to be loaded
  1862. from the url based on an entrypoint, and then the plugin returns
  1863. the actual dialect to be used.
  1864. By default this just returns the cls.
  1865. """
  1866. return cls
  1867. @classmethod
  1868. def get_async_dialect_cls(cls, url: URL) -> Type[Dialect]:
  1869. """Given a URL, return the :class:`.Dialect` that will be used by
  1870. an async engine.
  1871. By default this is an alias of :meth:`.Dialect.get_dialect_cls` and
  1872. just returns the cls. It may be used if a dialect provides
  1873. both a sync and async version under the same name, like the
  1874. ``psycopg`` driver.
  1875. .. versionadded:: 2
  1876. .. seealso::
  1877. :meth:`.Dialect.get_dialect_cls`
  1878. """
  1879. return cls.get_dialect_cls(url)
  1880. @classmethod
  1881. def load_provisioning(cls) -> None:
  1882. """set up the provision.py module for this dialect.
  1883. For dialects that include a provision.py module that sets up
  1884. provisioning followers, this method should initiate that process.
  1885. A typical implementation would be::
  1886. @classmethod
  1887. def load_provisioning(cls):
  1888. __import__("mydialect.provision")
  1889. The default method assumes a module named ``provision.py`` inside
  1890. the owning package of the current dialect, based on the ``__module__``
  1891. attribute::
  1892. @classmethod
  1893. def load_provisioning(cls):
  1894. package = ".".join(cls.__module__.split(".")[0:-1])
  1895. try:
  1896. __import__(package + ".provision")
  1897. except ImportError:
  1898. pass
  1899. .. versionadded:: 1.3.14
  1900. """
  1901. @classmethod
  1902. def engine_created(cls, engine: Engine) -> None:
  1903. """A convenience hook called before returning the final
  1904. :class:`_engine.Engine`.
  1905. If the dialect returned a different class from the
  1906. :meth:`.get_dialect_cls`
  1907. method, then the hook is called on both classes, first on
  1908. the dialect class returned by the :meth:`.get_dialect_cls` method and
  1909. then on the class on which the method was called.
  1910. The hook should be used by dialects and/or wrappers to apply special
  1911. events to the engine or its components. In particular, it allows
  1912. a dialect-wrapping class to apply dialect-level events.
  1913. """
  1914. def get_driver_connection(self, connection: DBAPIConnection) -> Any:
  1915. """Returns the connection object as returned by the external driver
  1916. package.
  1917. For normal dialects that use a DBAPI compliant driver this call
  1918. will just return the ``connection`` passed as argument.
  1919. For dialects that instead adapt a non DBAPI compliant driver, like
  1920. when adapting an asyncio driver, this call will return the
  1921. connection-like object as returned by the driver.
  1922. .. versionadded:: 1.4.24
  1923. """
  1924. raise NotImplementedError()
  1925. def set_engine_execution_options(
  1926. self, engine: Engine, opts: CoreExecuteOptionsParameter
  1927. ) -> None:
  1928. """Establish execution options for a given engine.
  1929. This is implemented by :class:`.DefaultDialect` to establish
  1930. event hooks for new :class:`.Connection` instances created
  1931. by the given :class:`.Engine` which will then invoke the
  1932. :meth:`.Dialect.set_connection_execution_options` method for that
  1933. connection.
  1934. """
  1935. raise NotImplementedError()
  1936. def set_connection_execution_options(
  1937. self, connection: Connection, opts: CoreExecuteOptionsParameter
  1938. ) -> None:
  1939. """Establish execution options for a given connection.
  1940. This is implemented by :class:`.DefaultDialect` in order to implement
  1941. the :paramref:`_engine.Connection.execution_options.isolation_level`
  1942. execution option. Dialects can intercept various execution options
  1943. which may need to modify state on a particular DBAPI connection.
  1944. .. versionadded:: 1.4
  1945. """
  1946. raise NotImplementedError()
  1947. def get_dialect_pool_class(self, url: URL) -> Type[Pool]:
  1948. """return a Pool class to use for a given URL"""
  1949. raise NotImplementedError()
  1950. def validate_identifier(self, ident: str) -> None:
  1951. """Validates an identifier name, raising an exception if invalid"""
  1952. class CreateEnginePlugin:
  1953. """A set of hooks intended to augment the construction of an
  1954. :class:`_engine.Engine` object based on entrypoint names in a URL.
  1955. The purpose of :class:`_engine.CreateEnginePlugin` is to allow third-party
  1956. systems to apply engine, pool and dialect level event listeners without
  1957. the need for the target application to be modified; instead, the plugin
  1958. names can be added to the database URL. Target applications for
  1959. :class:`_engine.CreateEnginePlugin` include:
  1960. * connection and SQL performance tools, e.g. which use events to track
  1961. number of checkouts and/or time spent with statements
  1962. * connectivity plugins such as proxies
  1963. A rudimentary :class:`_engine.CreateEnginePlugin` that attaches a logger
  1964. to an :class:`_engine.Engine` object might look like::
  1965. import logging
  1966. from sqlalchemy.engine import CreateEnginePlugin
  1967. from sqlalchemy import event
  1968. class LogCursorEventsPlugin(CreateEnginePlugin):
  1969. def __init__(self, url, kwargs):
  1970. # consume the parameter "log_cursor_logging_name" from the
  1971. # URL query
  1972. logging_name = url.query.get(
  1973. "log_cursor_logging_name", "log_cursor"
  1974. )
  1975. self.log = logging.getLogger(logging_name)
  1976. def update_url(self, url):
  1977. "update the URL to one that no longer includes our parameters"
  1978. return url.difference_update_query(["log_cursor_logging_name"])
  1979. def engine_created(self, engine):
  1980. "attach an event listener after the new Engine is constructed"
  1981. event.listen(engine, "before_cursor_execute", self._log_event)
  1982. def _log_event(
  1983. self,
  1984. conn,
  1985. cursor,
  1986. statement,
  1987. parameters,
  1988. context,
  1989. executemany,
  1990. ):
  1991. self.log.info("Plugin logged cursor event: %s", statement)
  1992. Plugins are registered using entry points in a similar way as that
  1993. of dialects::
  1994. entry_points = {
  1995. "sqlalchemy.plugins": [
  1996. "log_cursor_plugin = myapp.plugins:LogCursorEventsPlugin"
  1997. ]
  1998. }
  1999. A plugin that uses the above names would be invoked from a database
  2000. URL as in::
  2001. from sqlalchemy import create_engine
  2002. engine = create_engine(
  2003. "mysql+pymysql://scott:tiger@localhost/test?"
  2004. "plugin=log_cursor_plugin&log_cursor_logging_name=mylogger"
  2005. )
  2006. The ``plugin`` URL parameter supports multiple instances, so that a URL
  2007. may specify multiple plugins; they are loaded in the order stated
  2008. in the URL::
  2009. engine = create_engine(
  2010. "mysql+pymysql://scott:tiger@localhost/test?"
  2011. "plugin=plugin_one&plugin=plugin_twp&plugin=plugin_three"
  2012. )
  2013. The plugin names may also be passed directly to :func:`_sa.create_engine`
  2014. using the :paramref:`_sa.create_engine.plugins` argument::
  2015. engine = create_engine(
  2016. "mysql+pymysql://scott:tiger@localhost/test", plugins=["myplugin"]
  2017. )
  2018. .. versionadded:: 1.2.3 plugin names can also be specified
  2019. to :func:`_sa.create_engine` as a list
  2020. A plugin may consume plugin-specific arguments from the
  2021. :class:`_engine.URL` object as well as the ``kwargs`` dictionary, which is
  2022. the dictionary of arguments passed to the :func:`_sa.create_engine`
  2023. call. "Consuming" these arguments includes that they must be removed
  2024. when the plugin initializes, so that the arguments are not passed along
  2025. to the :class:`_engine.Dialect` constructor, where they will raise an
  2026. :class:`_exc.ArgumentError` because they are not known by the dialect.
  2027. As of version 1.4 of SQLAlchemy, arguments should continue to be consumed
  2028. from the ``kwargs`` dictionary directly, by removing the values with a
  2029. method such as ``dict.pop``. Arguments from the :class:`_engine.URL` object
  2030. should be consumed by implementing the
  2031. :meth:`_engine.CreateEnginePlugin.update_url` method, returning a new copy
  2032. of the :class:`_engine.URL` with plugin-specific parameters removed::
  2033. class MyPlugin(CreateEnginePlugin):
  2034. def __init__(self, url, kwargs):
  2035. self.my_argument_one = url.query["my_argument_one"]
  2036. self.my_argument_two = url.query["my_argument_two"]
  2037. self.my_argument_three = kwargs.pop("my_argument_three", None)
  2038. def update_url(self, url):
  2039. return url.difference_update_query(
  2040. ["my_argument_one", "my_argument_two"]
  2041. )
  2042. Arguments like those illustrated above would be consumed from a
  2043. :func:`_sa.create_engine` call such as::
  2044. from sqlalchemy import create_engine
  2045. engine = create_engine(
  2046. "mysql+pymysql://scott:tiger@localhost/test?"
  2047. "plugin=myplugin&my_argument_one=foo&my_argument_two=bar",
  2048. my_argument_three="bat",
  2049. )
  2050. .. versionchanged:: 1.4
  2051. The :class:`_engine.URL` object is now immutable; a
  2052. :class:`_engine.CreateEnginePlugin` that needs to alter the
  2053. :class:`_engine.URL` should implement the newly added
  2054. :meth:`_engine.CreateEnginePlugin.update_url` method, which
  2055. is invoked after the plugin is constructed.
  2056. For migration, construct the plugin in the following way, checking
  2057. for the existence of the :meth:`_engine.CreateEnginePlugin.update_url`
  2058. method to detect which version is running::
  2059. class MyPlugin(CreateEnginePlugin):
  2060. def __init__(self, url, kwargs):
  2061. if hasattr(CreateEnginePlugin, "update_url"):
  2062. # detect the 1.4 API
  2063. self.my_argument_one = url.query["my_argument_one"]
  2064. self.my_argument_two = url.query["my_argument_two"]
  2065. else:
  2066. # detect the 1.3 and earlier API - mutate the
  2067. # URL directly
  2068. self.my_argument_one = url.query.pop("my_argument_one")
  2069. self.my_argument_two = url.query.pop("my_argument_two")
  2070. self.my_argument_three = kwargs.pop("my_argument_three", None)
  2071. def update_url(self, url):
  2072. # this method is only called in the 1.4 version
  2073. return url.difference_update_query(
  2074. ["my_argument_one", "my_argument_two"]
  2075. )
  2076. .. seealso::
  2077. :ref:`change_5526` - overview of the :class:`_engine.URL` change which
  2078. also includes notes regarding :class:`_engine.CreateEnginePlugin`.
  2079. When the engine creation process completes and produces the
  2080. :class:`_engine.Engine` object, it is again passed to the plugin via the
  2081. :meth:`_engine.CreateEnginePlugin.engine_created` hook. In this hook, additional
  2082. changes can be made to the engine, most typically involving setup of
  2083. events (e.g. those defined in :ref:`core_event_toplevel`).
  2084. """ # noqa: E501
  2085. def __init__(self, url: URL, kwargs: Dict[str, Any]):
  2086. """Construct a new :class:`.CreateEnginePlugin`.
  2087. The plugin object is instantiated individually for each call
  2088. to :func:`_sa.create_engine`. A single :class:`_engine.
  2089. Engine` will be
  2090. passed to the :meth:`.CreateEnginePlugin.engine_created` method
  2091. corresponding to this URL.
  2092. :param url: the :class:`_engine.URL` object. The plugin may inspect
  2093. the :class:`_engine.URL` for arguments. Arguments used by the
  2094. plugin should be removed, by returning an updated :class:`_engine.URL`
  2095. from the :meth:`_engine.CreateEnginePlugin.update_url` method.
  2096. .. versionchanged:: 1.4
  2097. The :class:`_engine.URL` object is now immutable, so a
  2098. :class:`_engine.CreateEnginePlugin` that needs to alter the
  2099. :class:`_engine.URL` object should implement the
  2100. :meth:`_engine.CreateEnginePlugin.update_url` method.
  2101. :param kwargs: The keyword arguments passed to
  2102. :func:`_sa.create_engine`.
  2103. """
  2104. self.url = url
  2105. def update_url(self, url: URL) -> URL:
  2106. """Update the :class:`_engine.URL`.
  2107. A new :class:`_engine.URL` should be returned. This method is
  2108. typically used to consume configuration arguments from the
  2109. :class:`_engine.URL` which must be removed, as they will not be
  2110. recognized by the dialect. The
  2111. :meth:`_engine.URL.difference_update_query` method is available
  2112. to remove these arguments. See the docstring at
  2113. :class:`_engine.CreateEnginePlugin` for an example.
  2114. .. versionadded:: 1.4
  2115. """
  2116. raise NotImplementedError()
  2117. def handle_dialect_kwargs(
  2118. self, dialect_cls: Type[Dialect], dialect_args: Dict[str, Any]
  2119. ) -> None:
  2120. """parse and modify dialect kwargs"""
  2121. def handle_pool_kwargs(
  2122. self, pool_cls: Type[Pool], pool_args: Dict[str, Any]
  2123. ) -> None:
  2124. """parse and modify pool kwargs"""
  2125. def engine_created(self, engine: Engine) -> None:
  2126. """Receive the :class:`_engine.Engine`
  2127. object when it is fully constructed.
  2128. The plugin may make additional changes to the engine, such as
  2129. registering engine or connection pool events.
  2130. """
  2131. class ExecutionContext:
  2132. """A messenger object for a Dialect that corresponds to a single
  2133. execution.
  2134. """
  2135. engine: Engine
  2136. """engine which the Connection is associated with"""
  2137. connection: Connection
  2138. """Connection object which can be freely used by default value
  2139. generators to execute SQL. This Connection should reference the
  2140. same underlying connection/transactional resources of
  2141. root_connection."""
  2142. root_connection: Connection
  2143. """Connection object which is the source of this ExecutionContext."""
  2144. dialect: Dialect
  2145. """dialect which created this ExecutionContext."""
  2146. cursor: DBAPICursor
  2147. """DB-API cursor procured from the connection"""
  2148. compiled: Optional[Compiled]
  2149. """if passed to constructor, sqlalchemy.engine.base.Compiled object
  2150. being executed"""
  2151. statement: str
  2152. """string version of the statement to be executed. Is either
  2153. passed to the constructor, or must be created from the
  2154. sql.Compiled object by the time pre_exec() has completed."""
  2155. invoked_statement: Optional[Executable]
  2156. """The Executable statement object that was given in the first place.
  2157. This should be structurally equivalent to compiled.statement, but not
  2158. necessarily the same object as in a caching scenario the compiled form
  2159. will have been extracted from the cache.
  2160. """
  2161. parameters: _AnyMultiExecuteParams
  2162. """bind parameters passed to the execute() or exec_driver_sql() methods.
  2163. These are always stored as a list of parameter entries. A single-element
  2164. list corresponds to a ``cursor.execute()`` call and a multiple-element
  2165. list corresponds to ``cursor.executemany()``, except in the case
  2166. of :attr:`.ExecuteStyle.INSERTMANYVALUES` which will use
  2167. ``cursor.execute()`` one or more times.
  2168. """
  2169. no_parameters: bool
  2170. """True if the execution style does not use parameters"""
  2171. isinsert: bool
  2172. """True if the statement is an INSERT."""
  2173. isupdate: bool
  2174. """True if the statement is an UPDATE."""
  2175. execute_style: ExecuteStyle
  2176. """the style of DBAPI cursor method that will be used to execute
  2177. a statement.
  2178. .. versionadded:: 2.0
  2179. """
  2180. executemany: bool
  2181. """True if the context has a list of more than one parameter set.
  2182. Historically this attribute links to whether ``cursor.execute()`` or
  2183. ``cursor.executemany()`` will be used. It also can now mean that
  2184. "insertmanyvalues" may be used which indicates one or more
  2185. ``cursor.execute()`` calls.
  2186. """
  2187. prefetch_cols: util.generic_fn_descriptor[Optional[Sequence[Column[Any]]]]
  2188. """a list of Column objects for which a client-side default
  2189. was fired off. Applies to inserts and updates."""
  2190. postfetch_cols: util.generic_fn_descriptor[Optional[Sequence[Column[Any]]]]
  2191. """a list of Column objects for which a server-side default or
  2192. inline SQL expression value was fired off. Applies to inserts
  2193. and updates."""
  2194. execution_options: _ExecuteOptions
  2195. """Execution options associated with the current statement execution"""
  2196. @classmethod
  2197. def _init_ddl(
  2198. cls,
  2199. dialect: Dialect,
  2200. connection: Connection,
  2201. dbapi_connection: PoolProxiedConnection,
  2202. execution_options: _ExecuteOptions,
  2203. compiled_ddl: DDLCompiler,
  2204. ) -> ExecutionContext:
  2205. raise NotImplementedError()
  2206. @classmethod
  2207. def _init_compiled(
  2208. cls,
  2209. dialect: Dialect,
  2210. connection: Connection,
  2211. dbapi_connection: PoolProxiedConnection,
  2212. execution_options: _ExecuteOptions,
  2213. compiled: SQLCompiler,
  2214. parameters: _CoreMultiExecuteParams,
  2215. invoked_statement: Executable,
  2216. extracted_parameters: Optional[Sequence[BindParameter[Any]]],
  2217. cache_hit: CacheStats = CacheStats.CACHING_DISABLED,
  2218. ) -> ExecutionContext:
  2219. raise NotImplementedError()
  2220. @classmethod
  2221. def _init_statement(
  2222. cls,
  2223. dialect: Dialect,
  2224. connection: Connection,
  2225. dbapi_connection: PoolProxiedConnection,
  2226. execution_options: _ExecuteOptions,
  2227. statement: str,
  2228. parameters: _DBAPIMultiExecuteParams,
  2229. ) -> ExecutionContext:
  2230. raise NotImplementedError()
  2231. @classmethod
  2232. def _init_default(
  2233. cls,
  2234. dialect: Dialect,
  2235. connection: Connection,
  2236. dbapi_connection: PoolProxiedConnection,
  2237. execution_options: _ExecuteOptions,
  2238. ) -> ExecutionContext:
  2239. raise NotImplementedError()
  2240. def _exec_default(
  2241. self,
  2242. column: Optional[Column[Any]],
  2243. default: DefaultGenerator,
  2244. type_: Optional[TypeEngine[Any]],
  2245. ) -> Any:
  2246. raise NotImplementedError()
  2247. def _prepare_set_input_sizes(
  2248. self,
  2249. ) -> Optional[List[Tuple[str, Any, TypeEngine[Any]]]]:
  2250. raise NotImplementedError()
  2251. def _get_cache_stats(self) -> str:
  2252. raise NotImplementedError()
  2253. def _setup_result_proxy(self) -> CursorResult[Any]:
  2254. raise NotImplementedError()
  2255. def fire_sequence(self, seq: Sequence_SchemaItem, type_: Integer) -> int:
  2256. """given a :class:`.Sequence`, invoke it and return the next int
  2257. value"""
  2258. raise NotImplementedError()
  2259. def create_cursor(self) -> DBAPICursor:
  2260. """Return a new cursor generated from this ExecutionContext's
  2261. connection.
  2262. Some dialects may wish to change the behavior of
  2263. connection.cursor(), such as postgresql which may return a PG
  2264. "server side" cursor.
  2265. """
  2266. raise NotImplementedError()
  2267. def pre_exec(self) -> None:
  2268. """Called before an execution of a compiled statement.
  2269. If a compiled statement was passed to this ExecutionContext,
  2270. the `statement` and `parameters` datamembers must be
  2271. initialized after this statement is complete.
  2272. """
  2273. raise NotImplementedError()
  2274. def get_out_parameter_values(
  2275. self, out_param_names: Sequence[str]
  2276. ) -> Sequence[Any]:
  2277. """Return a sequence of OUT parameter values from a cursor.
  2278. For dialects that support OUT parameters, this method will be called
  2279. when there is a :class:`.SQLCompiler` object which has the
  2280. :attr:`.SQLCompiler.has_out_parameters` flag set. This flag in turn
  2281. will be set to True if the statement itself has :class:`.BindParameter`
  2282. objects that have the ``.isoutparam`` flag set which are consumed by
  2283. the :meth:`.SQLCompiler.visit_bindparam` method. If the dialect
  2284. compiler produces :class:`.BindParameter` objects with ``.isoutparam``
  2285. set which are not handled by :meth:`.SQLCompiler.visit_bindparam`, it
  2286. should set this flag explicitly.
  2287. The list of names that were rendered for each bound parameter
  2288. is passed to the method. The method should then return a sequence of
  2289. values corresponding to the list of parameter objects. Unlike in
  2290. previous SQLAlchemy versions, the values can be the **raw values** from
  2291. the DBAPI; the execution context will apply the appropriate type
  2292. handler based on what's present in self.compiled.binds and update the
  2293. values. The processed dictionary will then be made available via the
  2294. ``.out_parameters`` collection on the result object. Note that
  2295. SQLAlchemy 1.4 has multiple kinds of result object as part of the 2.0
  2296. transition.
  2297. .. versionadded:: 1.4 - added
  2298. :meth:`.ExecutionContext.get_out_parameter_values`, which is invoked
  2299. automatically by the :class:`.DefaultExecutionContext` when there
  2300. are :class:`.BindParameter` objects with the ``.isoutparam`` flag
  2301. set. This replaces the practice of setting out parameters within
  2302. the now-removed ``get_result_proxy()`` method.
  2303. """
  2304. raise NotImplementedError()
  2305. def post_exec(self) -> None:
  2306. """Called after the execution of a compiled statement.
  2307. If a compiled statement was passed to this ExecutionContext,
  2308. the `last_insert_ids`, `last_inserted_params`, etc.
  2309. datamembers should be available after this method completes.
  2310. """
  2311. raise NotImplementedError()
  2312. def handle_dbapi_exception(self, e: BaseException) -> None:
  2313. """Receive a DBAPI exception which occurred upon execute, result
  2314. fetch, etc."""
  2315. raise NotImplementedError()
  2316. def lastrow_has_defaults(self) -> bool:
  2317. """Return True if the last INSERT or UPDATE row contained
  2318. inlined or database-side defaults.
  2319. """
  2320. raise NotImplementedError()
  2321. def get_rowcount(self) -> Optional[int]:
  2322. """Return the DBAPI ``cursor.rowcount`` value, or in some
  2323. cases an interpreted value.
  2324. See :attr:`_engine.CursorResult.rowcount` for details on this.
  2325. """
  2326. raise NotImplementedError()
  2327. def fetchall_for_returning(self, cursor: DBAPICursor) -> Sequence[Any]:
  2328. """For a RETURNING result, deliver cursor.fetchall() from the
  2329. DBAPI cursor.
  2330. This is a dialect-specific hook for dialects that have special
  2331. considerations when calling upon the rows delivered for a
  2332. "RETURNING" statement. Default implementation is
  2333. ``cursor.fetchall()``.
  2334. This hook is currently used only by the :term:`insertmanyvalues`
  2335. feature. Dialects that don't set ``use_insertmanyvalues=True``
  2336. don't need to consider this hook.
  2337. .. versionadded:: 2.0.10
  2338. """
  2339. raise NotImplementedError()
  2340. class ConnectionEventsTarget(EventTarget):
  2341. """An object which can accept events from :class:`.ConnectionEvents`.
  2342. Includes :class:`_engine.Connection` and :class:`_engine.Engine`.
  2343. .. versionadded:: 2.0
  2344. """
  2345. dispatch: dispatcher[ConnectionEventsTarget]
  2346. Connectable = ConnectionEventsTarget
  2347. class ExceptionContext:
  2348. """Encapsulate information about an error condition in progress.
  2349. This object exists solely to be passed to the
  2350. :meth:`_events.DialectEvents.handle_error` event,
  2351. supporting an interface that
  2352. can be extended without backwards-incompatibility.
  2353. """
  2354. __slots__ = ()
  2355. dialect: Dialect
  2356. """The :class:`_engine.Dialect` in use.
  2357. This member is present for all invocations of the event hook.
  2358. .. versionadded:: 2.0
  2359. """
  2360. connection: Optional[Connection]
  2361. """The :class:`_engine.Connection` in use during the exception.
  2362. This member is present, except in the case of a failure when
  2363. first connecting.
  2364. .. seealso::
  2365. :attr:`.ExceptionContext.engine`
  2366. """
  2367. engine: Optional[Engine]
  2368. """The :class:`_engine.Engine` in use during the exception.
  2369. This member is present in all cases except for when handling an error
  2370. within the connection pool "pre-ping" process.
  2371. """
  2372. cursor: Optional[DBAPICursor]
  2373. """The DBAPI cursor object.
  2374. May be None.
  2375. """
  2376. statement: Optional[str]
  2377. """String SQL statement that was emitted directly to the DBAPI.
  2378. May be None.
  2379. """
  2380. parameters: Optional[_DBAPIAnyExecuteParams]
  2381. """Parameter collection that was emitted directly to the DBAPI.
  2382. May be None.
  2383. """
  2384. original_exception: BaseException
  2385. """The exception object which was caught.
  2386. This member is always present.
  2387. """
  2388. sqlalchemy_exception: Optional[StatementError]
  2389. """The :class:`sqlalchemy.exc.StatementError` which wraps the original,
  2390. and will be raised if exception handling is not circumvented by the event.
  2391. May be None, as not all exception types are wrapped by SQLAlchemy.
  2392. For DBAPI-level exceptions that subclass the dbapi's Error class, this
  2393. field will always be present.
  2394. """
  2395. chained_exception: Optional[BaseException]
  2396. """The exception that was returned by the previous handler in the
  2397. exception chain, if any.
  2398. If present, this exception will be the one ultimately raised by
  2399. SQLAlchemy unless a subsequent handler replaces it.
  2400. May be None.
  2401. """
  2402. execution_context: Optional[ExecutionContext]
  2403. """The :class:`.ExecutionContext` corresponding to the execution
  2404. operation in progress.
  2405. This is present for statement execution operations, but not for
  2406. operations such as transaction begin/end. It also is not present when
  2407. the exception was raised before the :class:`.ExecutionContext`
  2408. could be constructed.
  2409. Note that the :attr:`.ExceptionContext.statement` and
  2410. :attr:`.ExceptionContext.parameters` members may represent a
  2411. different value than that of the :class:`.ExecutionContext`,
  2412. potentially in the case where a
  2413. :meth:`_events.ConnectionEvents.before_cursor_execute` event or similar
  2414. modified the statement/parameters to be sent.
  2415. May be None.
  2416. """
  2417. is_disconnect: bool
  2418. """Represent whether the exception as occurred represents a "disconnect"
  2419. condition.
  2420. This flag will always be True or False within the scope of the
  2421. :meth:`_events.DialectEvents.handle_error` handler.
  2422. SQLAlchemy will defer to this flag in order to determine whether or not
  2423. the connection should be invalidated subsequently. That is, by
  2424. assigning to this flag, a "disconnect" event which then results in
  2425. a connection and pool invalidation can be invoked or prevented by
  2426. changing this flag.
  2427. .. note:: The pool "pre_ping" handler enabled using the
  2428. :paramref:`_sa.create_engine.pool_pre_ping` parameter does **not**
  2429. consult this event before deciding if the "ping" returned false,
  2430. as opposed to receiving an unhandled error. For this use case, the
  2431. :ref:`legacy recipe based on engine_connect() may be used
  2432. <pool_disconnects_pessimistic_custom>`. A future API allow more
  2433. comprehensive customization of the "disconnect" detection mechanism
  2434. across all functions.
  2435. """
  2436. invalidate_pool_on_disconnect: bool
  2437. """Represent whether all connections in the pool should be invalidated
  2438. when a "disconnect" condition is in effect.
  2439. Setting this flag to False within the scope of the
  2440. :meth:`_events.DialectEvents.handle_error`
  2441. event will have the effect such
  2442. that the full collection of connections in the pool will not be
  2443. invalidated during a disconnect; only the current connection that is the
  2444. subject of the error will actually be invalidated.
  2445. The purpose of this flag is for custom disconnect-handling schemes where
  2446. the invalidation of other connections in the pool is to be performed
  2447. based on other conditions, or even on a per-connection basis.
  2448. """
  2449. is_pre_ping: bool
  2450. """Indicates if this error is occurring within the "pre-ping" step
  2451. performed when :paramref:`_sa.create_engine.pool_pre_ping` is set to
  2452. ``True``. In this mode, the :attr:`.ExceptionContext.engine` attribute
  2453. will be ``None``. The dialect in use is accessible via the
  2454. :attr:`.ExceptionContext.dialect` attribute.
  2455. .. versionadded:: 2.0.5
  2456. """
  2457. class AdaptedConnection:
  2458. """Interface of an adapted connection object to support the DBAPI protocol.
  2459. Used by asyncio dialects to provide a sync-style pep-249 facade on top
  2460. of the asyncio connection/cursor API provided by the driver.
  2461. .. versionadded:: 1.4.24
  2462. """
  2463. __slots__ = ("_connection",)
  2464. _connection: AsyncIODBAPIConnection
  2465. @property
  2466. def driver_connection(self) -> Any:
  2467. """The connection object as returned by the driver after a connect."""
  2468. return self._connection
  2469. def run_async(self, fn: Callable[[Any], Awaitable[_T]]) -> _T:
  2470. """Run the awaitable returned by the given function, which is passed
  2471. the raw asyncio driver connection.
  2472. This is used to invoke awaitable-only methods on the driver connection
  2473. within the context of a "synchronous" method, like a connection
  2474. pool event handler.
  2475. E.g.::
  2476. engine = create_async_engine(...)
  2477. @event.listens_for(engine.sync_engine, "connect")
  2478. def register_custom_types(
  2479. dbapi_connection, # ...
  2480. ):
  2481. dbapi_connection.run_async(
  2482. lambda connection: connection.set_type_codec(
  2483. "MyCustomType", encoder, decoder, ...
  2484. )
  2485. )
  2486. .. versionadded:: 1.4.30
  2487. .. seealso::
  2488. :ref:`asyncio_events_run_async`
  2489. """
  2490. return await_only(fn(self._connection))
  2491. def __repr__(self) -> str:
  2492. return "<AdaptedConnection %s>" % self._connection