interfaces.py 112 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464
  1. # engine/interfaces.py
  2. # Copyright (C) 2005-2025 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: https://www.opensource.org/licenses/mit-license.php
  7. """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. _bind_typing_render_casts: bool
  856. _type_memos: MutableMapping[TypeEngine[Any], _TypeMemoDict]
  857. def _builtin_onconnect(self) -> Optional[_ListenerFnType]:
  858. raise NotImplementedError()
  859. def create_connect_args(self, url: URL) -> ConnectArgsType:
  860. """Build DB-API compatible connection arguments.
  861. Given a :class:`.URL` object, returns a tuple
  862. consisting of a ``(*args, **kwargs)`` suitable to send directly
  863. to the dbapi's connect function. The arguments are sent to the
  864. :meth:`.Dialect.connect` method which then runs the DBAPI-level
  865. ``connect()`` function.
  866. The method typically makes use of the
  867. :meth:`.URL.translate_connect_args`
  868. method in order to generate a dictionary of options.
  869. The default implementation is::
  870. def create_connect_args(self, url):
  871. opts = url.translate_connect_args()
  872. opts.update(url.query)
  873. return ([], opts)
  874. :param url: a :class:`.URL` object
  875. :return: a tuple of ``(*args, **kwargs)`` which will be passed to the
  876. :meth:`.Dialect.connect` method.
  877. .. seealso::
  878. :meth:`.URL.translate_connect_args`
  879. """
  880. raise NotImplementedError()
  881. @classmethod
  882. def import_dbapi(cls) -> DBAPIModule:
  883. """Import the DBAPI module that is used by this dialect.
  884. The Python module object returned here will be assigned as an
  885. instance variable to a constructed dialect under the name
  886. ``.dbapi``.
  887. .. versionchanged:: 2.0 The :meth:`.Dialect.import_dbapi` class
  888. method is renamed from the previous method ``.Dialect.dbapi()``,
  889. which would be replaced at dialect instantiation time by the
  890. DBAPI module itself, thus using the same name in two different ways.
  891. If a ``.Dialect.dbapi()`` classmethod is present on a third-party
  892. dialect, it will be used and a deprecation warning will be emitted.
  893. """
  894. raise NotImplementedError()
  895. def type_descriptor(self, typeobj: TypeEngine[_T]) -> TypeEngine[_T]:
  896. """Transform a generic type to a dialect-specific type.
  897. Dialect classes will usually use the
  898. :func:`_types.adapt_type` function in the types module to
  899. accomplish this.
  900. The returned result is cached *per dialect class* so can
  901. contain no dialect-instance state.
  902. """
  903. raise NotImplementedError()
  904. def initialize(self, connection: Connection) -> None:
  905. """Called during strategized creation of the dialect with a
  906. connection.
  907. Allows dialects to configure options based on server version info or
  908. other properties.
  909. The connection passed here is a SQLAlchemy Connection object,
  910. with full capabilities.
  911. The initialize() method of the base dialect should be called via
  912. super().
  913. .. note:: as of SQLAlchemy 1.4, this method is called **before**
  914. any :meth:`_engine.Dialect.on_connect` hooks are called.
  915. """
  916. if TYPE_CHECKING:
  917. def _overrides_default(self, method_name: str) -> bool: ...
  918. def get_columns(
  919. self,
  920. connection: Connection,
  921. table_name: str,
  922. schema: Optional[str] = None,
  923. **kw: Any,
  924. ) -> List[ReflectedColumn]:
  925. """Return information about columns in ``table_name``.
  926. Given a :class:`_engine.Connection`, a string
  927. ``table_name``, and an optional string ``schema``, return column
  928. information as a list of dictionaries
  929. corresponding to the :class:`.ReflectedColumn` dictionary.
  930. This is an internal dialect method. Applications should use
  931. :meth:`.Inspector.get_columns`.
  932. """
  933. raise NotImplementedError()
  934. def get_multi_columns(
  935. self,
  936. connection: Connection,
  937. *,
  938. schema: Optional[str] = None,
  939. filter_names: Optional[Collection[str]] = None,
  940. **kw: Any,
  941. ) -> Iterable[Tuple[TableKey, List[ReflectedColumn]]]:
  942. """Return information about columns in all tables in the
  943. given ``schema``.
  944. This is an internal dialect method. Applications should use
  945. :meth:`.Inspector.get_multi_columns`.
  946. .. note:: The :class:`_engine.DefaultDialect` provides a default
  947. implementation that will call the single table method for
  948. each object returned by :meth:`Dialect.get_table_names`,
  949. :meth:`Dialect.get_view_names` or
  950. :meth:`Dialect.get_materialized_view_names` depending on the
  951. provided ``kind``. Dialects that want to support a faster
  952. implementation should implement this method.
  953. .. versionadded:: 2.0
  954. """
  955. raise NotImplementedError()
  956. def get_pk_constraint(
  957. self,
  958. connection: Connection,
  959. table_name: str,
  960. schema: Optional[str] = None,
  961. **kw: Any,
  962. ) -> ReflectedPrimaryKeyConstraint:
  963. """Return information about the primary key constraint on
  964. table_name`.
  965. Given a :class:`_engine.Connection`, a string
  966. ``table_name``, and an optional string ``schema``, return primary
  967. key information as a dictionary corresponding to the
  968. :class:`.ReflectedPrimaryKeyConstraint` dictionary.
  969. This is an internal dialect method. Applications should use
  970. :meth:`.Inspector.get_pk_constraint`.
  971. """
  972. raise NotImplementedError()
  973. def get_multi_pk_constraint(
  974. self,
  975. connection: Connection,
  976. *,
  977. schema: Optional[str] = None,
  978. filter_names: Optional[Collection[str]] = None,
  979. **kw: Any,
  980. ) -> Iterable[Tuple[TableKey, ReflectedPrimaryKeyConstraint]]:
  981. """Return information about primary key constraints in
  982. all tables in the given ``schema``.
  983. This is an internal dialect method. Applications should use
  984. :meth:`.Inspector.get_multi_pk_constraint`.
  985. .. note:: The :class:`_engine.DefaultDialect` provides a default
  986. implementation that will call the single table method for
  987. each object returned by :meth:`Dialect.get_table_names`,
  988. :meth:`Dialect.get_view_names` or
  989. :meth:`Dialect.get_materialized_view_names` depending on the
  990. provided ``kind``. Dialects that want to support a faster
  991. implementation should implement this method.
  992. .. versionadded:: 2.0
  993. """
  994. raise NotImplementedError()
  995. def get_foreign_keys(
  996. self,
  997. connection: Connection,
  998. table_name: str,
  999. schema: Optional[str] = None,
  1000. **kw: Any,
  1001. ) -> List[ReflectedForeignKeyConstraint]:
  1002. """Return information about foreign_keys in ``table_name``.
  1003. Given a :class:`_engine.Connection`, a string
  1004. ``table_name``, and an optional string ``schema``, return foreign
  1005. key information as a list of dicts corresponding to the
  1006. :class:`.ReflectedForeignKeyConstraint` dictionary.
  1007. This is an internal dialect method. Applications should use
  1008. :meth:`_engine.Inspector.get_foreign_keys`.
  1009. """
  1010. raise NotImplementedError()
  1011. def get_multi_foreign_keys(
  1012. self,
  1013. connection: Connection,
  1014. *,
  1015. schema: Optional[str] = None,
  1016. filter_names: Optional[Collection[str]] = None,
  1017. **kw: Any,
  1018. ) -> Iterable[Tuple[TableKey, List[ReflectedForeignKeyConstraint]]]:
  1019. """Return information about foreign_keys in all tables
  1020. in the given ``schema``.
  1021. This is an internal dialect method. Applications should use
  1022. :meth:`_engine.Inspector.get_multi_foreign_keys`.
  1023. .. note:: The :class:`_engine.DefaultDialect` provides a default
  1024. implementation that will call the single table method for
  1025. each object returned by :meth:`Dialect.get_table_names`,
  1026. :meth:`Dialect.get_view_names` or
  1027. :meth:`Dialect.get_materialized_view_names` depending on the
  1028. provided ``kind``. Dialects that want to support a faster
  1029. implementation should implement this method.
  1030. .. versionadded:: 2.0
  1031. """
  1032. raise NotImplementedError()
  1033. def get_table_names(
  1034. self, connection: Connection, schema: Optional[str] = None, **kw: Any
  1035. ) -> List[str]:
  1036. """Return a list of table names for ``schema``.
  1037. This is an internal dialect method. Applications should use
  1038. :meth:`_engine.Inspector.get_table_names`.
  1039. """
  1040. raise NotImplementedError()
  1041. def get_temp_table_names(
  1042. self, connection: Connection, schema: Optional[str] = None, **kw: Any
  1043. ) -> List[str]:
  1044. """Return a list of temporary table names on the given connection,
  1045. if supported by the underlying backend.
  1046. This is an internal dialect method. Applications should use
  1047. :meth:`_engine.Inspector.get_temp_table_names`.
  1048. """
  1049. raise NotImplementedError()
  1050. def get_view_names(
  1051. self, connection: Connection, schema: Optional[str] = None, **kw: Any
  1052. ) -> List[str]:
  1053. """Return a list of all non-materialized view names available in the
  1054. database.
  1055. This is an internal dialect method. Applications should use
  1056. :meth:`_engine.Inspector.get_view_names`.
  1057. :param schema: schema name to query, if not the default schema.
  1058. """
  1059. raise NotImplementedError()
  1060. def get_materialized_view_names(
  1061. self, connection: Connection, schema: Optional[str] = None, **kw: Any
  1062. ) -> List[str]:
  1063. """Return a list of all materialized view names available in the
  1064. database.
  1065. This is an internal dialect method. Applications should use
  1066. :meth:`_engine.Inspector.get_materialized_view_names`.
  1067. :param schema: schema name to query, if not the default schema.
  1068. .. versionadded:: 2.0
  1069. """
  1070. raise NotImplementedError()
  1071. def get_sequence_names(
  1072. self, connection: Connection, schema: Optional[str] = None, **kw: Any
  1073. ) -> List[str]:
  1074. """Return a list of all sequence names available in the database.
  1075. This is an internal dialect method. Applications should use
  1076. :meth:`_engine.Inspector.get_sequence_names`.
  1077. :param schema: schema name to query, if not the default schema.
  1078. .. versionadded:: 1.4
  1079. """
  1080. raise NotImplementedError()
  1081. def get_temp_view_names(
  1082. self, connection: Connection, schema: Optional[str] = None, **kw: Any
  1083. ) -> List[str]:
  1084. """Return a list of temporary view names on the given connection,
  1085. if supported by the underlying backend.
  1086. This is an internal dialect method. Applications should use
  1087. :meth:`_engine.Inspector.get_temp_view_names`.
  1088. """
  1089. raise NotImplementedError()
  1090. def get_schema_names(self, connection: Connection, **kw: Any) -> List[str]:
  1091. """Return a list of all schema names available in the database.
  1092. This is an internal dialect method. Applications should use
  1093. :meth:`_engine.Inspector.get_schema_names`.
  1094. """
  1095. raise NotImplementedError()
  1096. def get_view_definition(
  1097. self,
  1098. connection: Connection,
  1099. view_name: str,
  1100. schema: Optional[str] = None,
  1101. **kw: Any,
  1102. ) -> str:
  1103. """Return plain or materialized view definition.
  1104. This is an internal dialect method. Applications should use
  1105. :meth:`_engine.Inspector.get_view_definition`.
  1106. Given a :class:`_engine.Connection`, a string
  1107. ``view_name``, and an optional string ``schema``, return the view
  1108. definition.
  1109. """
  1110. raise NotImplementedError()
  1111. def get_indexes(
  1112. self,
  1113. connection: Connection,
  1114. table_name: str,
  1115. schema: Optional[str] = None,
  1116. **kw: Any,
  1117. ) -> List[ReflectedIndex]:
  1118. """Return information about indexes in ``table_name``.
  1119. Given a :class:`_engine.Connection`, a string
  1120. ``table_name`` and an optional string ``schema``, return index
  1121. information as a list of dictionaries corresponding to the
  1122. :class:`.ReflectedIndex` dictionary.
  1123. This is an internal dialect method. Applications should use
  1124. :meth:`.Inspector.get_indexes`.
  1125. """
  1126. raise NotImplementedError()
  1127. def get_multi_indexes(
  1128. self,
  1129. connection: Connection,
  1130. *,
  1131. schema: Optional[str] = None,
  1132. filter_names: Optional[Collection[str]] = None,
  1133. **kw: Any,
  1134. ) -> Iterable[Tuple[TableKey, List[ReflectedIndex]]]:
  1135. """Return information about indexes in in all tables
  1136. in the given ``schema``.
  1137. This is an internal dialect method. Applications should use
  1138. :meth:`.Inspector.get_multi_indexes`.
  1139. .. note:: The :class:`_engine.DefaultDialect` provides a default
  1140. implementation that will call the single table method for
  1141. each object returned by :meth:`Dialect.get_table_names`,
  1142. :meth:`Dialect.get_view_names` or
  1143. :meth:`Dialect.get_materialized_view_names` depending on the
  1144. provided ``kind``. Dialects that want to support a faster
  1145. implementation should implement this method.
  1146. .. versionadded:: 2.0
  1147. """
  1148. raise NotImplementedError()
  1149. def get_unique_constraints(
  1150. self,
  1151. connection: Connection,
  1152. table_name: str,
  1153. schema: Optional[str] = None,
  1154. **kw: Any,
  1155. ) -> List[ReflectedUniqueConstraint]:
  1156. r"""Return information about unique constraints in ``table_name``.
  1157. Given a string ``table_name`` and an optional string ``schema``, return
  1158. unique constraint information as a list of dicts corresponding
  1159. to the :class:`.ReflectedUniqueConstraint` dictionary.
  1160. This is an internal dialect method. Applications should use
  1161. :meth:`.Inspector.get_unique_constraints`.
  1162. """
  1163. raise NotImplementedError()
  1164. def get_multi_unique_constraints(
  1165. self,
  1166. connection: Connection,
  1167. *,
  1168. schema: Optional[str] = None,
  1169. filter_names: Optional[Collection[str]] = None,
  1170. **kw: Any,
  1171. ) -> Iterable[Tuple[TableKey, List[ReflectedUniqueConstraint]]]:
  1172. """Return information about unique constraints in all tables
  1173. in the given ``schema``.
  1174. This is an internal dialect method. Applications should use
  1175. :meth:`.Inspector.get_multi_unique_constraints`.
  1176. .. note:: The :class:`_engine.DefaultDialect` provides a default
  1177. implementation that will call the single table method for
  1178. each object returned by :meth:`Dialect.get_table_names`,
  1179. :meth:`Dialect.get_view_names` or
  1180. :meth:`Dialect.get_materialized_view_names` depending on the
  1181. provided ``kind``. Dialects that want to support a faster
  1182. implementation should implement this method.
  1183. .. versionadded:: 2.0
  1184. """
  1185. raise NotImplementedError()
  1186. def get_check_constraints(
  1187. self,
  1188. connection: Connection,
  1189. table_name: str,
  1190. schema: Optional[str] = None,
  1191. **kw: Any,
  1192. ) -> List[ReflectedCheckConstraint]:
  1193. r"""Return information about check constraints in ``table_name``.
  1194. Given a string ``table_name`` and an optional string ``schema``, return
  1195. check constraint information as a list of dicts corresponding
  1196. to the :class:`.ReflectedCheckConstraint` dictionary.
  1197. This is an internal dialect method. Applications should use
  1198. :meth:`.Inspector.get_check_constraints`.
  1199. """
  1200. raise NotImplementedError()
  1201. def get_multi_check_constraints(
  1202. self,
  1203. connection: Connection,
  1204. *,
  1205. schema: Optional[str] = None,
  1206. filter_names: Optional[Collection[str]] = None,
  1207. **kw: Any,
  1208. ) -> Iterable[Tuple[TableKey, List[ReflectedCheckConstraint]]]:
  1209. """Return information about check constraints in all tables
  1210. in the given ``schema``.
  1211. This is an internal dialect method. Applications should use
  1212. :meth:`.Inspector.get_multi_check_constraints`.
  1213. .. note:: The :class:`_engine.DefaultDialect` provides a default
  1214. implementation that will call the single table method for
  1215. each object returned by :meth:`Dialect.get_table_names`,
  1216. :meth:`Dialect.get_view_names` or
  1217. :meth:`Dialect.get_materialized_view_names` depending on the
  1218. provided ``kind``. Dialects that want to support a faster
  1219. implementation should implement this method.
  1220. .. versionadded:: 2.0
  1221. """
  1222. raise NotImplementedError()
  1223. def get_table_options(
  1224. self,
  1225. connection: Connection,
  1226. table_name: str,
  1227. schema: Optional[str] = None,
  1228. **kw: Any,
  1229. ) -> Dict[str, Any]:
  1230. """Return a dictionary of options specified when ``table_name``
  1231. was created.
  1232. This is an internal dialect method. Applications should use
  1233. :meth:`_engine.Inspector.get_table_options`.
  1234. """
  1235. raise NotImplementedError()
  1236. def get_multi_table_options(
  1237. self,
  1238. connection: Connection,
  1239. *,
  1240. schema: Optional[str] = None,
  1241. filter_names: Optional[Collection[str]] = None,
  1242. **kw: Any,
  1243. ) -> Iterable[Tuple[TableKey, Dict[str, Any]]]:
  1244. """Return a dictionary of options specified when the tables in the
  1245. given schema were created.
  1246. This is an internal dialect method. Applications should use
  1247. :meth:`_engine.Inspector.get_multi_table_options`.
  1248. .. note:: The :class:`_engine.DefaultDialect` provides a default
  1249. implementation that will call the single table method for
  1250. each object returned by :meth:`Dialect.get_table_names`,
  1251. :meth:`Dialect.get_view_names` or
  1252. :meth:`Dialect.get_materialized_view_names` depending on the
  1253. provided ``kind``. Dialects that want to support a faster
  1254. implementation should implement this method.
  1255. .. versionadded:: 2.0
  1256. """
  1257. raise NotImplementedError()
  1258. def get_table_comment(
  1259. self,
  1260. connection: Connection,
  1261. table_name: str,
  1262. schema: Optional[str] = None,
  1263. **kw: Any,
  1264. ) -> ReflectedTableComment:
  1265. r"""Return the "comment" for the table identified by ``table_name``.
  1266. Given a string ``table_name`` and an optional string ``schema``, return
  1267. table comment information as a dictionary corresponding to the
  1268. :class:`.ReflectedTableComment` dictionary.
  1269. This is an internal dialect method. Applications should use
  1270. :meth:`.Inspector.get_table_comment`.
  1271. :raise: ``NotImplementedError`` for dialects that don't support
  1272. comments.
  1273. .. versionadded:: 1.2
  1274. """
  1275. raise NotImplementedError()
  1276. def get_multi_table_comment(
  1277. self,
  1278. connection: Connection,
  1279. *,
  1280. schema: Optional[str] = None,
  1281. filter_names: Optional[Collection[str]] = None,
  1282. **kw: Any,
  1283. ) -> Iterable[Tuple[TableKey, ReflectedTableComment]]:
  1284. """Return information about the table comment in all tables
  1285. in the given ``schema``.
  1286. This is an internal dialect method. Applications should use
  1287. :meth:`_engine.Inspector.get_multi_table_comment`.
  1288. .. note:: The :class:`_engine.DefaultDialect` provides a default
  1289. implementation that will call the single table method for
  1290. each object returned by :meth:`Dialect.get_table_names`,
  1291. :meth:`Dialect.get_view_names` or
  1292. :meth:`Dialect.get_materialized_view_names` depending on the
  1293. provided ``kind``. Dialects that want to support a faster
  1294. implementation should implement this method.
  1295. .. versionadded:: 2.0
  1296. """
  1297. raise NotImplementedError()
  1298. def normalize_name(self, name: str) -> str:
  1299. """convert the given name to lowercase if it is detected as
  1300. case insensitive.
  1301. This method is only used if the dialect defines
  1302. requires_name_normalize=True.
  1303. """
  1304. raise NotImplementedError()
  1305. def denormalize_name(self, name: str) -> str:
  1306. """convert the given name to a case insensitive identifier
  1307. for the backend if it is an all-lowercase name.
  1308. This method is only used if the dialect defines
  1309. requires_name_normalize=True.
  1310. """
  1311. raise NotImplementedError()
  1312. def has_table(
  1313. self,
  1314. connection: Connection,
  1315. table_name: str,
  1316. schema: Optional[str] = None,
  1317. **kw: Any,
  1318. ) -> bool:
  1319. """For internal dialect use, check the existence of a particular table
  1320. or view in the database.
  1321. Given a :class:`_engine.Connection` object, a string table_name and
  1322. optional schema name, return True if the given table exists in the
  1323. database, False otherwise.
  1324. This method serves as the underlying implementation of the
  1325. public facing :meth:`.Inspector.has_table` method, and is also used
  1326. internally to implement the "checkfirst" behavior for methods like
  1327. :meth:`_schema.Table.create` and :meth:`_schema.MetaData.create_all`.
  1328. .. note:: This method is used internally by SQLAlchemy, and is
  1329. published so that third-party dialects may provide an
  1330. implementation. It is **not** the public API for checking for table
  1331. presence. Please use the :meth:`.Inspector.has_table` method.
  1332. .. versionchanged:: 2.0:: :meth:`_engine.Dialect.has_table` now
  1333. formally supports checking for additional table-like objects:
  1334. * any type of views (plain or materialized)
  1335. * temporary tables of any kind
  1336. Previously, these two checks were not formally specified and
  1337. different dialects would vary in their behavior. The dialect
  1338. testing suite now includes tests for all of these object types,
  1339. and dialects to the degree that the backing database supports views
  1340. or temporary tables should seek to support locating these objects
  1341. for full compliance.
  1342. """
  1343. raise NotImplementedError()
  1344. def has_index(
  1345. self,
  1346. connection: Connection,
  1347. table_name: str,
  1348. index_name: str,
  1349. schema: Optional[str] = None,
  1350. **kw: Any,
  1351. ) -> bool:
  1352. """Check the existence of a particular index name in the database.
  1353. Given a :class:`_engine.Connection` object, a string
  1354. ``table_name`` and string index name, return ``True`` if an index of
  1355. the given name on the given table exists, ``False`` otherwise.
  1356. The :class:`.DefaultDialect` implements this in terms of the
  1357. :meth:`.Dialect.has_table` and :meth:`.Dialect.get_indexes` methods,
  1358. however dialects can implement a more performant version.
  1359. This is an internal dialect method. Applications should use
  1360. :meth:`_engine.Inspector.has_index`.
  1361. .. versionadded:: 1.4
  1362. """
  1363. raise NotImplementedError()
  1364. def has_sequence(
  1365. self,
  1366. connection: Connection,
  1367. sequence_name: str,
  1368. schema: Optional[str] = None,
  1369. **kw: Any,
  1370. ) -> bool:
  1371. """Check the existence of a particular sequence in the database.
  1372. Given a :class:`_engine.Connection` object and a string
  1373. `sequence_name`, return ``True`` if the given sequence exists in
  1374. the database, ``False`` otherwise.
  1375. This is an internal dialect method. Applications should use
  1376. :meth:`_engine.Inspector.has_sequence`.
  1377. """
  1378. raise NotImplementedError()
  1379. def has_schema(
  1380. self, connection: Connection, schema_name: str, **kw: Any
  1381. ) -> bool:
  1382. """Check the existence of a particular schema name in the database.
  1383. Given a :class:`_engine.Connection` object, a string
  1384. ``schema_name``, return ``True`` if a schema of the
  1385. given exists, ``False`` otherwise.
  1386. The :class:`.DefaultDialect` implements this by checking
  1387. the presence of ``schema_name`` among the schemas returned by
  1388. :meth:`.Dialect.get_schema_names`,
  1389. however dialects can implement a more performant version.
  1390. This is an internal dialect method. Applications should use
  1391. :meth:`_engine.Inspector.has_schema`.
  1392. .. versionadded:: 2.0
  1393. """
  1394. raise NotImplementedError()
  1395. def _get_server_version_info(self, connection: Connection) -> Any:
  1396. """Retrieve the server version info from the given connection.
  1397. This is used by the default implementation to populate the
  1398. "server_version_info" attribute and is called exactly
  1399. once upon first connect.
  1400. """
  1401. raise NotImplementedError()
  1402. def _get_default_schema_name(self, connection: Connection) -> str:
  1403. """Return the string name of the currently selected schema from
  1404. the given connection.
  1405. This is used by the default implementation to populate the
  1406. "default_schema_name" attribute and is called exactly
  1407. once upon first connect.
  1408. """
  1409. raise NotImplementedError()
  1410. def do_begin(self, dbapi_connection: PoolProxiedConnection) -> None:
  1411. """Provide an implementation of ``connection.begin()``, given a
  1412. DB-API connection.
  1413. The DBAPI has no dedicated "begin" method and it is expected
  1414. that transactions are implicit. This hook is provided for those
  1415. DBAPIs that might need additional help in this area.
  1416. :param dbapi_connection: a DBAPI connection, typically
  1417. proxied within a :class:`.ConnectionFairy`.
  1418. """
  1419. raise NotImplementedError()
  1420. def do_rollback(self, dbapi_connection: PoolProxiedConnection) -> None:
  1421. """Provide an implementation of ``connection.rollback()``, given
  1422. a DB-API connection.
  1423. :param dbapi_connection: a DBAPI connection, typically
  1424. proxied within a :class:`.ConnectionFairy`.
  1425. """
  1426. raise NotImplementedError()
  1427. def do_commit(self, dbapi_connection: PoolProxiedConnection) -> None:
  1428. """Provide an implementation of ``connection.commit()``, given a
  1429. DB-API connection.
  1430. :param dbapi_connection: a DBAPI connection, typically
  1431. proxied within a :class:`.ConnectionFairy`.
  1432. """
  1433. raise NotImplementedError()
  1434. def do_terminate(self, dbapi_connection: DBAPIConnection) -> None:
  1435. """Provide an implementation of ``connection.close()`` that tries as
  1436. much as possible to not block, given a DBAPI
  1437. connection.
  1438. In the vast majority of cases this just calls .close(), however
  1439. for some asyncio dialects may call upon different API features.
  1440. This hook is called by the :class:`_pool.Pool`
  1441. when a connection is being recycled or has been invalidated.
  1442. .. versionadded:: 1.4.41
  1443. """
  1444. raise NotImplementedError()
  1445. def do_close(self, dbapi_connection: DBAPIConnection) -> None:
  1446. """Provide an implementation of ``connection.close()``, given a DBAPI
  1447. connection.
  1448. This hook is called by the :class:`_pool.Pool`
  1449. when a connection has been
  1450. detached from the pool, or is being returned beyond the normal
  1451. capacity of the pool.
  1452. """
  1453. raise NotImplementedError()
  1454. def _do_ping_w_event(self, dbapi_connection: DBAPIConnection) -> bool:
  1455. raise NotImplementedError()
  1456. def do_ping(self, dbapi_connection: DBAPIConnection) -> bool:
  1457. """ping the DBAPI connection and return True if the connection is
  1458. usable."""
  1459. raise NotImplementedError()
  1460. def do_set_input_sizes(
  1461. self,
  1462. cursor: DBAPICursor,
  1463. list_of_tuples: _GenericSetInputSizesType,
  1464. context: ExecutionContext,
  1465. ) -> Any:
  1466. """invoke the cursor.setinputsizes() method with appropriate arguments
  1467. This hook is called if the :attr:`.Dialect.bind_typing` attribute is
  1468. set to the
  1469. :attr:`.BindTyping.SETINPUTSIZES` value.
  1470. Parameter data is passed in a list of tuples (paramname, dbtype,
  1471. sqltype), where ``paramname`` is the key of the parameter in the
  1472. statement, ``dbtype`` is the DBAPI datatype and ``sqltype`` is the
  1473. SQLAlchemy type. The order of tuples is in the correct parameter order.
  1474. .. versionadded:: 1.4
  1475. .. versionchanged:: 2.0 - setinputsizes mode is now enabled by
  1476. setting :attr:`.Dialect.bind_typing` to
  1477. :attr:`.BindTyping.SETINPUTSIZES`. Dialects which accept
  1478. a ``use_setinputsizes`` parameter should set this value
  1479. appropriately.
  1480. """
  1481. raise NotImplementedError()
  1482. def create_xid(self) -> Any:
  1483. """Create a two-phase transaction ID.
  1484. This id will be passed to do_begin_twophase(),
  1485. do_rollback_twophase(), do_commit_twophase(). Its format is
  1486. unspecified.
  1487. """
  1488. raise NotImplementedError()
  1489. def do_savepoint(self, connection: Connection, name: str) -> None:
  1490. """Create a savepoint with the given name.
  1491. :param connection: a :class:`_engine.Connection`.
  1492. :param name: savepoint name.
  1493. """
  1494. raise NotImplementedError()
  1495. def do_rollback_to_savepoint(
  1496. self, connection: Connection, name: str
  1497. ) -> None:
  1498. """Rollback a connection to the named savepoint.
  1499. :param connection: a :class:`_engine.Connection`.
  1500. :param name: savepoint name.
  1501. """
  1502. raise NotImplementedError()
  1503. def do_release_savepoint(self, connection: Connection, name: str) -> None:
  1504. """Release the named savepoint on a connection.
  1505. :param connection: a :class:`_engine.Connection`.
  1506. :param name: savepoint name.
  1507. """
  1508. raise NotImplementedError()
  1509. def do_begin_twophase(self, connection: Connection, xid: Any) -> None:
  1510. """Begin a two phase transaction on the given connection.
  1511. :param connection: a :class:`_engine.Connection`.
  1512. :param xid: xid
  1513. """
  1514. raise NotImplementedError()
  1515. def do_prepare_twophase(self, connection: Connection, xid: Any) -> None:
  1516. """Prepare 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_rollback_twophase(
  1522. self,
  1523. connection: Connection,
  1524. xid: Any,
  1525. is_prepared: bool = True,
  1526. recover: bool = False,
  1527. ) -> None:
  1528. """Rollback a two phase transaction on the given connection.
  1529. :param connection: a :class:`_engine.Connection`.
  1530. :param xid: xid
  1531. :param is_prepared: whether or not
  1532. :meth:`.TwoPhaseTransaction.prepare` was called.
  1533. :param recover: if the recover flag was passed.
  1534. """
  1535. raise NotImplementedError()
  1536. def do_commit_twophase(
  1537. self,
  1538. connection: Connection,
  1539. xid: Any,
  1540. is_prepared: bool = True,
  1541. recover: bool = False,
  1542. ) -> None:
  1543. """Commit a two phase transaction on the given connection.
  1544. :param connection: a :class:`_engine.Connection`.
  1545. :param xid: xid
  1546. :param is_prepared: whether or not
  1547. :meth:`.TwoPhaseTransaction.prepare` was called.
  1548. :param recover: if the recover flag was passed.
  1549. """
  1550. raise NotImplementedError()
  1551. def do_recover_twophase(self, connection: Connection) -> List[Any]:
  1552. """Recover list of uncommitted prepared two phase transaction
  1553. identifiers on the given connection.
  1554. :param connection: a :class:`_engine.Connection`.
  1555. """
  1556. raise NotImplementedError()
  1557. def _deliver_insertmanyvalues_batches(
  1558. self,
  1559. connection: Connection,
  1560. cursor: DBAPICursor,
  1561. statement: str,
  1562. parameters: _DBAPIMultiExecuteParams,
  1563. generic_setinputsizes: Optional[_GenericSetInputSizesType],
  1564. context: ExecutionContext,
  1565. ) -> Iterator[_InsertManyValuesBatch]:
  1566. """convert executemany parameters for an INSERT into an iterator
  1567. of statement/single execute values, used by the insertmanyvalues
  1568. feature.
  1569. """
  1570. raise NotImplementedError()
  1571. def do_executemany(
  1572. self,
  1573. cursor: DBAPICursor,
  1574. statement: str,
  1575. parameters: _DBAPIMultiExecuteParams,
  1576. context: Optional[ExecutionContext] = None,
  1577. ) -> None:
  1578. """Provide an implementation of ``cursor.executemany(statement,
  1579. parameters)``."""
  1580. raise NotImplementedError()
  1581. def do_execute(
  1582. self,
  1583. cursor: DBAPICursor,
  1584. statement: str,
  1585. parameters: Optional[_DBAPISingleExecuteParams],
  1586. context: Optional[ExecutionContext] = None,
  1587. ) -> None:
  1588. """Provide an implementation of ``cursor.execute(statement,
  1589. parameters)``."""
  1590. raise NotImplementedError()
  1591. def do_execute_no_params(
  1592. self,
  1593. cursor: DBAPICursor,
  1594. statement: str,
  1595. context: Optional[ExecutionContext] = None,
  1596. ) -> None:
  1597. """Provide an implementation of ``cursor.execute(statement)``.
  1598. The parameter collection should not be sent.
  1599. """
  1600. raise NotImplementedError()
  1601. def is_disconnect(
  1602. self,
  1603. e: DBAPIModule.Error,
  1604. connection: Optional[Union[PoolProxiedConnection, DBAPIConnection]],
  1605. cursor: Optional[DBAPICursor],
  1606. ) -> bool:
  1607. """Return True if the given DB-API error indicates an invalid
  1608. connection"""
  1609. raise NotImplementedError()
  1610. def connect(self, *cargs: Any, **cparams: Any) -> DBAPIConnection:
  1611. r"""Establish a connection using this dialect's DBAPI.
  1612. The default implementation of this method is::
  1613. def connect(self, *cargs, **cparams):
  1614. return self.dbapi.connect(*cargs, **cparams)
  1615. The ``*cargs, **cparams`` parameters are generated directly
  1616. from this dialect's :meth:`.Dialect.create_connect_args` method.
  1617. This method may be used for dialects that need to perform programmatic
  1618. per-connection steps when a new connection is procured from the
  1619. DBAPI.
  1620. :param \*cargs: positional parameters returned from the
  1621. :meth:`.Dialect.create_connect_args` method
  1622. :param \*\*cparams: keyword parameters returned from the
  1623. :meth:`.Dialect.create_connect_args` method.
  1624. :return: a DBAPI connection, typically from the :pep:`249` module
  1625. level ``.connect()`` function.
  1626. .. seealso::
  1627. :meth:`.Dialect.create_connect_args`
  1628. :meth:`.Dialect.on_connect`
  1629. """
  1630. raise NotImplementedError()
  1631. def on_connect_url(self, url: URL) -> Optional[Callable[[Any], Any]]:
  1632. """return a callable which sets up a newly created DBAPI connection.
  1633. This method is a new hook that supersedes the
  1634. :meth:`_engine.Dialect.on_connect` method when implemented by a
  1635. dialect. When not implemented by a dialect, it invokes the
  1636. :meth:`_engine.Dialect.on_connect` method directly to maintain
  1637. compatibility with existing dialects. There is no deprecation
  1638. for :meth:`_engine.Dialect.on_connect` expected.
  1639. The callable should accept a single argument "conn" which is the
  1640. DBAPI connection itself. The inner callable has no
  1641. return value.
  1642. E.g.::
  1643. class MyDialect(default.DefaultDialect):
  1644. # ...
  1645. def on_connect_url(self, url):
  1646. def do_on_connect(connection):
  1647. connection.execute("SET SPECIAL FLAGS etc")
  1648. return do_on_connect
  1649. This is used to set dialect-wide per-connection options such as
  1650. isolation modes, Unicode modes, etc.
  1651. This method differs from :meth:`_engine.Dialect.on_connect` in that
  1652. it is passed the :class:`_engine.URL` object that's relevant to the
  1653. connect args. Normally the only way to get this is from the
  1654. :meth:`_engine.Dialect.on_connect` hook is to look on the
  1655. :class:`_engine.Engine` itself, however this URL object may have been
  1656. replaced by plugins.
  1657. .. note::
  1658. The default implementation of
  1659. :meth:`_engine.Dialect.on_connect_url` is to invoke the
  1660. :meth:`_engine.Dialect.on_connect` method. Therefore if a dialect
  1661. implements this method, the :meth:`_engine.Dialect.on_connect`
  1662. method **will not be called** unless the overriding dialect calls
  1663. it directly from here.
  1664. .. versionadded:: 1.4.3 added :meth:`_engine.Dialect.on_connect_url`
  1665. which normally calls into :meth:`_engine.Dialect.on_connect`.
  1666. :param url: a :class:`_engine.URL` object representing the
  1667. :class:`_engine.URL` that was passed to the
  1668. :meth:`_engine.Dialect.create_connect_args` method.
  1669. :return: a callable that accepts a single DBAPI connection as an
  1670. argument, or None.
  1671. .. seealso::
  1672. :meth:`_engine.Dialect.on_connect`
  1673. """
  1674. return self.on_connect()
  1675. def on_connect(self) -> Optional[Callable[[Any], None]]:
  1676. """return a callable which sets up a newly created DBAPI connection.
  1677. The callable should accept a single argument "conn" which is the
  1678. DBAPI connection itself. The inner callable has no
  1679. return value.
  1680. E.g.::
  1681. class MyDialect(default.DefaultDialect):
  1682. # ...
  1683. def on_connect(self):
  1684. def do_on_connect(connection):
  1685. connection.execute("SET SPECIAL FLAGS etc")
  1686. return do_on_connect
  1687. This is used to set dialect-wide per-connection options such as
  1688. isolation modes, Unicode modes, etc.
  1689. The "do_on_connect" callable is invoked by using the
  1690. :meth:`_events.PoolEvents.connect` event
  1691. hook, then unwrapping the DBAPI connection and passing it into the
  1692. callable.
  1693. .. versionchanged:: 1.4 the on_connect hook is no longer called twice
  1694. for the first connection of a dialect. The on_connect hook is still
  1695. called before the :meth:`_engine.Dialect.initialize` method however.
  1696. .. versionchanged:: 1.4.3 the on_connect hook is invoked from a new
  1697. method on_connect_url that passes the URL that was used to create
  1698. the connect args. Dialects can implement on_connect_url instead
  1699. of on_connect if they need the URL object that was used for the
  1700. connection in order to get additional context.
  1701. If None is returned, no event listener is generated.
  1702. :return: a callable that accepts a single DBAPI connection as an
  1703. argument, or None.
  1704. .. seealso::
  1705. :meth:`.Dialect.connect` - allows the DBAPI ``connect()`` sequence
  1706. itself to be controlled.
  1707. :meth:`.Dialect.on_connect_url` - supersedes
  1708. :meth:`.Dialect.on_connect` to also receive the
  1709. :class:`_engine.URL` object in context.
  1710. """
  1711. return None
  1712. def reset_isolation_level(self, dbapi_connection: DBAPIConnection) -> None:
  1713. """Given a DBAPI connection, revert its isolation to the default.
  1714. Note that this is a dialect-level method which is used as part
  1715. of the implementation of the :class:`_engine.Connection` and
  1716. :class:`_engine.Engine`
  1717. isolation level facilities; these APIs should be preferred for
  1718. most typical use cases.
  1719. .. seealso::
  1720. :meth:`_engine.Connection.get_isolation_level`
  1721. - view current level
  1722. :attr:`_engine.Connection.default_isolation_level`
  1723. - view default level
  1724. :paramref:`.Connection.execution_options.isolation_level` -
  1725. set per :class:`_engine.Connection` isolation level
  1726. :paramref:`_sa.create_engine.isolation_level` -
  1727. set per :class:`_engine.Engine` isolation level
  1728. """
  1729. raise NotImplementedError()
  1730. def set_isolation_level(
  1731. self, dbapi_connection: DBAPIConnection, level: IsolationLevel
  1732. ) -> None:
  1733. """Given a DBAPI connection, set its isolation level.
  1734. Note that this is a dialect-level method which is used as part
  1735. of the implementation of the :class:`_engine.Connection` and
  1736. :class:`_engine.Engine`
  1737. isolation level facilities; these APIs should be preferred for
  1738. most typical use cases.
  1739. If the dialect also implements the
  1740. :meth:`.Dialect.get_isolation_level_values` method, then the given
  1741. level is guaranteed to be one of the string names within that sequence,
  1742. and the method will not need to anticipate a lookup failure.
  1743. .. seealso::
  1744. :meth:`_engine.Connection.get_isolation_level`
  1745. - view current level
  1746. :attr:`_engine.Connection.default_isolation_level`
  1747. - view default level
  1748. :paramref:`.Connection.execution_options.isolation_level` -
  1749. set per :class:`_engine.Connection` isolation level
  1750. :paramref:`_sa.create_engine.isolation_level` -
  1751. set per :class:`_engine.Engine` isolation level
  1752. """
  1753. raise NotImplementedError()
  1754. def get_isolation_level(
  1755. self, dbapi_connection: DBAPIConnection
  1756. ) -> IsolationLevel:
  1757. """Given a DBAPI connection, return its isolation level.
  1758. When working with a :class:`_engine.Connection` object,
  1759. the corresponding
  1760. DBAPI connection may be procured using the
  1761. :attr:`_engine.Connection.connection` accessor.
  1762. Note that this is a dialect-level method which is used as part
  1763. of the implementation of the :class:`_engine.Connection` and
  1764. :class:`_engine.Engine` isolation level facilities;
  1765. these APIs should be preferred for most typical use cases.
  1766. .. seealso::
  1767. :meth:`_engine.Connection.get_isolation_level`
  1768. - view current level
  1769. :attr:`_engine.Connection.default_isolation_level`
  1770. - view default level
  1771. :paramref:`.Connection.execution_options.isolation_level` -
  1772. set per :class:`_engine.Connection` isolation level
  1773. :paramref:`_sa.create_engine.isolation_level` -
  1774. set per :class:`_engine.Engine` isolation level
  1775. """
  1776. raise NotImplementedError()
  1777. def detect_autocommit_setting(self, dbapi_conn: DBAPIConnection) -> bool:
  1778. """Detect the current autocommit setting for a DBAPI connection.
  1779. :param dbapi_connection: a DBAPI connection object
  1780. :return: True if autocommit is enabled, False if disabled
  1781. :rtype: bool
  1782. This method inspects the given DBAPI connection to determine
  1783. whether autocommit mode is currently enabled. The specific
  1784. mechanism for detecting autocommit varies by database dialect
  1785. and DBAPI driver, however it should be done **without** network
  1786. round trips.
  1787. .. note::
  1788. Not all dialects support autocommit detection. Dialects
  1789. that do not support this feature will raise
  1790. :exc:`NotImplementedError`.
  1791. """
  1792. raise NotImplementedError(
  1793. "This dialect cannot detect autocommit on a DBAPI connection"
  1794. )
  1795. def get_default_isolation_level(
  1796. self, dbapi_conn: DBAPIConnection
  1797. ) -> IsolationLevel:
  1798. """Given a DBAPI connection, return its isolation level, or
  1799. a default isolation level if one cannot be retrieved.
  1800. This method may only raise NotImplementedError and
  1801. **must not raise any other exception**, as it is used implicitly upon
  1802. first connect.
  1803. The method **must return a value** for a dialect that supports
  1804. isolation level settings, as this level is what will be reverted
  1805. towards when a per-connection isolation level change is made.
  1806. The method defaults to using the :meth:`.Dialect.get_isolation_level`
  1807. method unless overridden by a dialect.
  1808. .. versionadded:: 1.3.22
  1809. """
  1810. raise NotImplementedError()
  1811. def get_isolation_level_values(
  1812. self, dbapi_conn: DBAPIConnection
  1813. ) -> Sequence[IsolationLevel]:
  1814. """return a sequence of string isolation level names that are accepted
  1815. by this dialect.
  1816. The available names should use the following conventions:
  1817. * use UPPERCASE names. isolation level methods will accept lowercase
  1818. names but these are normalized into UPPERCASE before being passed
  1819. along to the dialect.
  1820. * separate words should be separated by spaces, not underscores, e.g.
  1821. ``REPEATABLE READ``. isolation level names will have underscores
  1822. converted to spaces before being passed along to the dialect.
  1823. * The names for the four standard isolation names to the extent that
  1824. they are supported by the backend should be ``READ UNCOMMITTED``,
  1825. ``READ COMMITTED``, ``REPEATABLE READ``, ``SERIALIZABLE``
  1826. * if the dialect supports an autocommit option it should be provided
  1827. using the isolation level name ``AUTOCOMMIT``.
  1828. * Other isolation modes may also be present, provided that they
  1829. are named in UPPERCASE and use spaces not underscores.
  1830. This function is used so that the default dialect can check that
  1831. a given isolation level parameter is valid, else raises an
  1832. :class:`_exc.ArgumentError`.
  1833. A DBAPI connection is passed to the method, in the unlikely event that
  1834. the dialect needs to interrogate the connection itself to determine
  1835. this list, however it is expected that most backends will return
  1836. a hardcoded list of values. If the dialect supports "AUTOCOMMIT",
  1837. that value should also be present in the sequence returned.
  1838. The method raises ``NotImplementedError`` by default. If a dialect
  1839. does not implement this method, then the default dialect will not
  1840. perform any checking on a given isolation level value before passing
  1841. it onto the :meth:`.Dialect.set_isolation_level` method. This is
  1842. to allow backwards-compatibility with third party dialects that may
  1843. not yet be implementing this method.
  1844. .. versionadded:: 2.0
  1845. """
  1846. raise NotImplementedError()
  1847. def _assert_and_set_isolation_level(
  1848. self, dbapi_conn: DBAPIConnection, level: IsolationLevel
  1849. ) -> None:
  1850. raise NotImplementedError()
  1851. @classmethod
  1852. def get_dialect_cls(cls, url: URL) -> Type[Dialect]:
  1853. """Given a URL, return the :class:`.Dialect` that will be used.
  1854. This is a hook that allows an external plugin to provide functionality
  1855. around an existing dialect, by allowing the plugin to be loaded
  1856. from the url based on an entrypoint, and then the plugin returns
  1857. the actual dialect to be used.
  1858. By default this just returns the cls.
  1859. """
  1860. return cls
  1861. @classmethod
  1862. def get_async_dialect_cls(cls, url: URL) -> Type[Dialect]:
  1863. """Given a URL, return the :class:`.Dialect` that will be used by
  1864. an async engine.
  1865. By default this is an alias of :meth:`.Dialect.get_dialect_cls` and
  1866. just returns the cls. It may be used if a dialect provides
  1867. both a sync and async version under the same name, like the
  1868. ``psycopg`` driver.
  1869. .. versionadded:: 2
  1870. .. seealso::
  1871. :meth:`.Dialect.get_dialect_cls`
  1872. """
  1873. return cls.get_dialect_cls(url)
  1874. @classmethod
  1875. def load_provisioning(cls) -> None:
  1876. """set up the provision.py module for this dialect.
  1877. For dialects that include a provision.py module that sets up
  1878. provisioning followers, this method should initiate that process.
  1879. A typical implementation would be::
  1880. @classmethod
  1881. def load_provisioning(cls):
  1882. __import__("mydialect.provision")
  1883. The default method assumes a module named ``provision.py`` inside
  1884. the owning package of the current dialect, based on the ``__module__``
  1885. attribute::
  1886. @classmethod
  1887. def load_provisioning(cls):
  1888. package = ".".join(cls.__module__.split(".")[0:-1])
  1889. try:
  1890. __import__(package + ".provision")
  1891. except ImportError:
  1892. pass
  1893. .. versionadded:: 1.3.14
  1894. """
  1895. @classmethod
  1896. def engine_created(cls, engine: Engine) -> None:
  1897. """A convenience hook called before returning the final
  1898. :class:`_engine.Engine`.
  1899. If the dialect returned a different class from the
  1900. :meth:`.get_dialect_cls`
  1901. method, then the hook is called on both classes, first on
  1902. the dialect class returned by the :meth:`.get_dialect_cls` method and
  1903. then on the class on which the method was called.
  1904. The hook should be used by dialects and/or wrappers to apply special
  1905. events to the engine or its components. In particular, it allows
  1906. a dialect-wrapping class to apply dialect-level events.
  1907. """
  1908. def get_driver_connection(self, connection: DBAPIConnection) -> Any:
  1909. """Returns the connection object as returned by the external driver
  1910. package.
  1911. For normal dialects that use a DBAPI compliant driver this call
  1912. will just return the ``connection`` passed as argument.
  1913. For dialects that instead adapt a non DBAPI compliant driver, like
  1914. when adapting an asyncio driver, this call will return the
  1915. connection-like object as returned by the driver.
  1916. .. versionadded:: 1.4.24
  1917. """
  1918. raise NotImplementedError()
  1919. def set_engine_execution_options(
  1920. self, engine: Engine, opts: CoreExecuteOptionsParameter
  1921. ) -> None:
  1922. """Establish execution options for a given engine.
  1923. This is implemented by :class:`.DefaultDialect` to establish
  1924. event hooks for new :class:`.Connection` instances created
  1925. by the given :class:`.Engine` which will then invoke the
  1926. :meth:`.Dialect.set_connection_execution_options` method for that
  1927. connection.
  1928. """
  1929. raise NotImplementedError()
  1930. def set_connection_execution_options(
  1931. self, connection: Connection, opts: CoreExecuteOptionsParameter
  1932. ) -> None:
  1933. """Establish execution options for a given connection.
  1934. This is implemented by :class:`.DefaultDialect` in order to implement
  1935. the :paramref:`_engine.Connection.execution_options.isolation_level`
  1936. execution option. Dialects can intercept various execution options
  1937. which may need to modify state on a particular DBAPI connection.
  1938. .. versionadded:: 1.4
  1939. """
  1940. raise NotImplementedError()
  1941. def get_dialect_pool_class(self, url: URL) -> Type[Pool]:
  1942. """return a Pool class to use for a given URL"""
  1943. raise NotImplementedError()
  1944. def validate_identifier(self, ident: str) -> None:
  1945. """Validates an identifier name, raising an exception if invalid"""
  1946. class CreateEnginePlugin:
  1947. """A set of hooks intended to augment the construction of an
  1948. :class:`_engine.Engine` object based on entrypoint names in a URL.
  1949. The purpose of :class:`_engine.CreateEnginePlugin` is to allow third-party
  1950. systems to apply engine, pool and dialect level event listeners without
  1951. the need for the target application to be modified; instead, the plugin
  1952. names can be added to the database URL. Target applications for
  1953. :class:`_engine.CreateEnginePlugin` include:
  1954. * connection and SQL performance tools, e.g. which use events to track
  1955. number of checkouts and/or time spent with statements
  1956. * connectivity plugins such as proxies
  1957. A rudimentary :class:`_engine.CreateEnginePlugin` that attaches a logger
  1958. to an :class:`_engine.Engine` object might look like::
  1959. import logging
  1960. from sqlalchemy.engine import CreateEnginePlugin
  1961. from sqlalchemy import event
  1962. class LogCursorEventsPlugin(CreateEnginePlugin):
  1963. def __init__(self, url, kwargs):
  1964. # consume the parameter "log_cursor_logging_name" from the
  1965. # URL query
  1966. logging_name = url.query.get(
  1967. "log_cursor_logging_name", "log_cursor"
  1968. )
  1969. self.log = logging.getLogger(logging_name)
  1970. def update_url(self, url):
  1971. "update the URL to one that no longer includes our parameters"
  1972. return url.difference_update_query(["log_cursor_logging_name"])
  1973. def engine_created(self, engine):
  1974. "attach an event listener after the new Engine is constructed"
  1975. event.listen(engine, "before_cursor_execute", self._log_event)
  1976. def _log_event(
  1977. self,
  1978. conn,
  1979. cursor,
  1980. statement,
  1981. parameters,
  1982. context,
  1983. executemany,
  1984. ):
  1985. self.log.info("Plugin logged cursor event: %s", statement)
  1986. Plugins are registered using entry points in a similar way as that
  1987. of dialects::
  1988. entry_points = {
  1989. "sqlalchemy.plugins": [
  1990. "log_cursor_plugin = myapp.plugins:LogCursorEventsPlugin"
  1991. ]
  1992. }
  1993. A plugin that uses the above names would be invoked from a database
  1994. URL as in::
  1995. from sqlalchemy import create_engine
  1996. engine = create_engine(
  1997. "mysql+pymysql://scott:tiger@localhost/test?"
  1998. "plugin=log_cursor_plugin&log_cursor_logging_name=mylogger"
  1999. )
  2000. The ``plugin`` URL parameter supports multiple instances, so that a URL
  2001. may specify multiple plugins; they are loaded in the order stated
  2002. in the URL::
  2003. engine = create_engine(
  2004. "mysql+pymysql://scott:tiger@localhost/test?"
  2005. "plugin=plugin_one&plugin=plugin_twp&plugin=plugin_three"
  2006. )
  2007. The plugin names may also be passed directly to :func:`_sa.create_engine`
  2008. using the :paramref:`_sa.create_engine.plugins` argument::
  2009. engine = create_engine(
  2010. "mysql+pymysql://scott:tiger@localhost/test", plugins=["myplugin"]
  2011. )
  2012. .. versionadded:: 1.2.3 plugin names can also be specified
  2013. to :func:`_sa.create_engine` as a list
  2014. A plugin may consume plugin-specific arguments from the
  2015. :class:`_engine.URL` object as well as the ``kwargs`` dictionary, which is
  2016. the dictionary of arguments passed to the :func:`_sa.create_engine`
  2017. call. "Consuming" these arguments includes that they must be removed
  2018. when the plugin initializes, so that the arguments are not passed along
  2019. to the :class:`_engine.Dialect` constructor, where they will raise an
  2020. :class:`_exc.ArgumentError` because they are not known by the dialect.
  2021. As of version 1.4 of SQLAlchemy, arguments should continue to be consumed
  2022. from the ``kwargs`` dictionary directly, by removing the values with a
  2023. method such as ``dict.pop``. Arguments from the :class:`_engine.URL` object
  2024. should be consumed by implementing the
  2025. :meth:`_engine.CreateEnginePlugin.update_url` method, returning a new copy
  2026. of the :class:`_engine.URL` with plugin-specific parameters removed::
  2027. class MyPlugin(CreateEnginePlugin):
  2028. def __init__(self, url, kwargs):
  2029. self.my_argument_one = url.query["my_argument_one"]
  2030. self.my_argument_two = url.query["my_argument_two"]
  2031. self.my_argument_three = kwargs.pop("my_argument_three", None)
  2032. def update_url(self, url):
  2033. return url.difference_update_query(
  2034. ["my_argument_one", "my_argument_two"]
  2035. )
  2036. Arguments like those illustrated above would be consumed from a
  2037. :func:`_sa.create_engine` call such as::
  2038. from sqlalchemy import create_engine
  2039. engine = create_engine(
  2040. "mysql+pymysql://scott:tiger@localhost/test?"
  2041. "plugin=myplugin&my_argument_one=foo&my_argument_two=bar",
  2042. my_argument_three="bat",
  2043. )
  2044. .. versionchanged:: 1.4
  2045. The :class:`_engine.URL` object is now immutable; a
  2046. :class:`_engine.CreateEnginePlugin` that needs to alter the
  2047. :class:`_engine.URL` should implement the newly added
  2048. :meth:`_engine.CreateEnginePlugin.update_url` method, which
  2049. is invoked after the plugin is constructed.
  2050. For migration, construct the plugin in the following way, checking
  2051. for the existence of the :meth:`_engine.CreateEnginePlugin.update_url`
  2052. method to detect which version is running::
  2053. class MyPlugin(CreateEnginePlugin):
  2054. def __init__(self, url, kwargs):
  2055. if hasattr(CreateEnginePlugin, "update_url"):
  2056. # detect the 1.4 API
  2057. self.my_argument_one = url.query["my_argument_one"]
  2058. self.my_argument_two = url.query["my_argument_two"]
  2059. else:
  2060. # detect the 1.3 and earlier API - mutate the
  2061. # URL directly
  2062. self.my_argument_one = url.query.pop("my_argument_one")
  2063. self.my_argument_two = url.query.pop("my_argument_two")
  2064. self.my_argument_three = kwargs.pop("my_argument_three", None)
  2065. def update_url(self, url):
  2066. # this method is only called in the 1.4 version
  2067. return url.difference_update_query(
  2068. ["my_argument_one", "my_argument_two"]
  2069. )
  2070. .. seealso::
  2071. :ref:`change_5526` - overview of the :class:`_engine.URL` change which
  2072. also includes notes regarding :class:`_engine.CreateEnginePlugin`.
  2073. When the engine creation process completes and produces the
  2074. :class:`_engine.Engine` object, it is again passed to the plugin via the
  2075. :meth:`_engine.CreateEnginePlugin.engine_created` hook. In this hook, additional
  2076. changes can be made to the engine, most typically involving setup of
  2077. events (e.g. those defined in :ref:`core_event_toplevel`).
  2078. """ # noqa: E501
  2079. def __init__(self, url: URL, kwargs: Dict[str, Any]):
  2080. """Construct a new :class:`.CreateEnginePlugin`.
  2081. The plugin object is instantiated individually for each call
  2082. to :func:`_sa.create_engine`. A single :class:`_engine.
  2083. Engine` will be
  2084. passed to the :meth:`.CreateEnginePlugin.engine_created` method
  2085. corresponding to this URL.
  2086. :param url: the :class:`_engine.URL` object. The plugin may inspect
  2087. the :class:`_engine.URL` for arguments. Arguments used by the
  2088. plugin should be removed, by returning an updated :class:`_engine.URL`
  2089. from the :meth:`_engine.CreateEnginePlugin.update_url` method.
  2090. .. versionchanged:: 1.4
  2091. The :class:`_engine.URL` object is now immutable, so a
  2092. :class:`_engine.CreateEnginePlugin` that needs to alter the
  2093. :class:`_engine.URL` object should implement the
  2094. :meth:`_engine.CreateEnginePlugin.update_url` method.
  2095. :param kwargs: The keyword arguments passed to
  2096. :func:`_sa.create_engine`.
  2097. """
  2098. self.url = url
  2099. def update_url(self, url: URL) -> URL:
  2100. """Update the :class:`_engine.URL`.
  2101. A new :class:`_engine.URL` should be returned. This method is
  2102. typically used to consume configuration arguments from the
  2103. :class:`_engine.URL` which must be removed, as they will not be
  2104. recognized by the dialect. The
  2105. :meth:`_engine.URL.difference_update_query` method is available
  2106. to remove these arguments. See the docstring at
  2107. :class:`_engine.CreateEnginePlugin` for an example.
  2108. .. versionadded:: 1.4
  2109. """
  2110. raise NotImplementedError()
  2111. def handle_dialect_kwargs(
  2112. self, dialect_cls: Type[Dialect], dialect_args: Dict[str, Any]
  2113. ) -> None:
  2114. """parse and modify dialect kwargs"""
  2115. def handle_pool_kwargs(
  2116. self, pool_cls: Type[Pool], pool_args: Dict[str, Any]
  2117. ) -> None:
  2118. """parse and modify pool kwargs"""
  2119. def engine_created(self, engine: Engine) -> None:
  2120. """Receive the :class:`_engine.Engine`
  2121. object when it is fully constructed.
  2122. The plugin may make additional changes to the engine, such as
  2123. registering engine or connection pool events.
  2124. """
  2125. class ExecutionContext:
  2126. """A messenger object for a Dialect that corresponds to a single
  2127. execution.
  2128. """
  2129. engine: Engine
  2130. """engine which the Connection is associated with"""
  2131. connection: Connection
  2132. """Connection object which can be freely used by default value
  2133. generators to execute SQL. This Connection should reference the
  2134. same underlying connection/transactional resources of
  2135. root_connection."""
  2136. root_connection: Connection
  2137. """Connection object which is the source of this ExecutionContext."""
  2138. dialect: Dialect
  2139. """dialect which created this ExecutionContext."""
  2140. cursor: DBAPICursor
  2141. """DB-API cursor procured from the connection"""
  2142. compiled: Optional[Compiled]
  2143. """if passed to constructor, sqlalchemy.engine.base.Compiled object
  2144. being executed"""
  2145. statement: str
  2146. """string version of the statement to be executed. Is either
  2147. passed to the constructor, or must be created from the
  2148. sql.Compiled object by the time pre_exec() has completed."""
  2149. invoked_statement: Optional[Executable]
  2150. """The Executable statement object that was given in the first place.
  2151. This should be structurally equivalent to compiled.statement, but not
  2152. necessarily the same object as in a caching scenario the compiled form
  2153. will have been extracted from the cache.
  2154. """
  2155. parameters: _AnyMultiExecuteParams
  2156. """bind parameters passed to the execute() or exec_driver_sql() methods.
  2157. These are always stored as a list of parameter entries. A single-element
  2158. list corresponds to a ``cursor.execute()`` call and a multiple-element
  2159. list corresponds to ``cursor.executemany()``, except in the case
  2160. of :attr:`.ExecuteStyle.INSERTMANYVALUES` which will use
  2161. ``cursor.execute()`` one or more times.
  2162. """
  2163. no_parameters: bool
  2164. """True if the execution style does not use parameters"""
  2165. isinsert: bool
  2166. """True if the statement is an INSERT."""
  2167. isupdate: bool
  2168. """True if the statement is an UPDATE."""
  2169. execute_style: ExecuteStyle
  2170. """the style of DBAPI cursor method that will be used to execute
  2171. a statement.
  2172. .. versionadded:: 2.0
  2173. """
  2174. executemany: bool
  2175. """True if the context has a list of more than one parameter set.
  2176. Historically this attribute links to whether ``cursor.execute()`` or
  2177. ``cursor.executemany()`` will be used. It also can now mean that
  2178. "insertmanyvalues" may be used which indicates one or more
  2179. ``cursor.execute()`` calls.
  2180. """
  2181. prefetch_cols: util.generic_fn_descriptor[Optional[Sequence[Column[Any]]]]
  2182. """a list of Column objects for which a client-side default
  2183. was fired off. Applies to inserts and updates."""
  2184. postfetch_cols: util.generic_fn_descriptor[Optional[Sequence[Column[Any]]]]
  2185. """a list of Column objects for which a server-side default or
  2186. inline SQL expression value was fired off. Applies to inserts
  2187. and updates."""
  2188. execution_options: _ExecuteOptions
  2189. """Execution options associated with the current statement execution"""
  2190. @classmethod
  2191. def _init_ddl(
  2192. cls,
  2193. dialect: Dialect,
  2194. connection: Connection,
  2195. dbapi_connection: PoolProxiedConnection,
  2196. execution_options: _ExecuteOptions,
  2197. compiled_ddl: DDLCompiler,
  2198. ) -> ExecutionContext:
  2199. raise NotImplementedError()
  2200. @classmethod
  2201. def _init_compiled(
  2202. cls,
  2203. dialect: Dialect,
  2204. connection: Connection,
  2205. dbapi_connection: PoolProxiedConnection,
  2206. execution_options: _ExecuteOptions,
  2207. compiled: SQLCompiler,
  2208. parameters: _CoreMultiExecuteParams,
  2209. invoked_statement: Executable,
  2210. extracted_parameters: Optional[Sequence[BindParameter[Any]]],
  2211. cache_hit: CacheStats = CacheStats.CACHING_DISABLED,
  2212. ) -> ExecutionContext:
  2213. raise NotImplementedError()
  2214. @classmethod
  2215. def _init_statement(
  2216. cls,
  2217. dialect: Dialect,
  2218. connection: Connection,
  2219. dbapi_connection: PoolProxiedConnection,
  2220. execution_options: _ExecuteOptions,
  2221. statement: str,
  2222. parameters: _DBAPIMultiExecuteParams,
  2223. ) -> ExecutionContext:
  2224. raise NotImplementedError()
  2225. @classmethod
  2226. def _init_default(
  2227. cls,
  2228. dialect: Dialect,
  2229. connection: Connection,
  2230. dbapi_connection: PoolProxiedConnection,
  2231. execution_options: _ExecuteOptions,
  2232. ) -> ExecutionContext:
  2233. raise NotImplementedError()
  2234. def _exec_default(
  2235. self,
  2236. column: Optional[Column[Any]],
  2237. default: DefaultGenerator,
  2238. type_: Optional[TypeEngine[Any]],
  2239. ) -> Any:
  2240. raise NotImplementedError()
  2241. def _prepare_set_input_sizes(
  2242. self,
  2243. ) -> Optional[List[Tuple[str, Any, TypeEngine[Any]]]]:
  2244. raise NotImplementedError()
  2245. def _get_cache_stats(self) -> str:
  2246. raise NotImplementedError()
  2247. def _setup_result_proxy(self) -> CursorResult[Any]:
  2248. raise NotImplementedError()
  2249. def fire_sequence(self, seq: Sequence_SchemaItem, type_: Integer) -> int:
  2250. """given a :class:`.Sequence`, invoke it and return the next int
  2251. value"""
  2252. raise NotImplementedError()
  2253. def create_cursor(self) -> DBAPICursor:
  2254. """Return a new cursor generated from this ExecutionContext's
  2255. connection.
  2256. Some dialects may wish to change the behavior of
  2257. connection.cursor(), such as postgresql which may return a PG
  2258. "server side" cursor.
  2259. """
  2260. raise NotImplementedError()
  2261. def pre_exec(self) -> None:
  2262. """Called before an execution of a compiled statement.
  2263. If a compiled statement was passed to this ExecutionContext,
  2264. the `statement` and `parameters` datamembers must be
  2265. initialized after this statement is complete.
  2266. """
  2267. raise NotImplementedError()
  2268. def get_out_parameter_values(
  2269. self, out_param_names: Sequence[str]
  2270. ) -> Sequence[Any]:
  2271. """Return a sequence of OUT parameter values from a cursor.
  2272. For dialects that support OUT parameters, this method will be called
  2273. when there is a :class:`.SQLCompiler` object which has the
  2274. :attr:`.SQLCompiler.has_out_parameters` flag set. This flag in turn
  2275. will be set to True if the statement itself has :class:`.BindParameter`
  2276. objects that have the ``.isoutparam`` flag set which are consumed by
  2277. the :meth:`.SQLCompiler.visit_bindparam` method. If the dialect
  2278. compiler produces :class:`.BindParameter` objects with ``.isoutparam``
  2279. set which are not handled by :meth:`.SQLCompiler.visit_bindparam`, it
  2280. should set this flag explicitly.
  2281. The list of names that were rendered for each bound parameter
  2282. is passed to the method. The method should then return a sequence of
  2283. values corresponding to the list of parameter objects. Unlike in
  2284. previous SQLAlchemy versions, the values can be the **raw values** from
  2285. the DBAPI; the execution context will apply the appropriate type
  2286. handler based on what's present in self.compiled.binds and update the
  2287. values. The processed dictionary will then be made available via the
  2288. ``.out_parameters`` collection on the result object. Note that
  2289. SQLAlchemy 1.4 has multiple kinds of result object as part of the 2.0
  2290. transition.
  2291. .. versionadded:: 1.4 - added
  2292. :meth:`.ExecutionContext.get_out_parameter_values`, which is invoked
  2293. automatically by the :class:`.DefaultExecutionContext` when there
  2294. are :class:`.BindParameter` objects with the ``.isoutparam`` flag
  2295. set. This replaces the practice of setting out parameters within
  2296. the now-removed ``get_result_proxy()`` method.
  2297. """
  2298. raise NotImplementedError()
  2299. def post_exec(self) -> None:
  2300. """Called after the execution of a compiled statement.
  2301. If a compiled statement was passed to this ExecutionContext,
  2302. the `last_insert_ids`, `last_inserted_params`, etc.
  2303. datamembers should be available after this method completes.
  2304. """
  2305. raise NotImplementedError()
  2306. def handle_dbapi_exception(self, e: BaseException) -> None:
  2307. """Receive a DBAPI exception which occurred upon execute, result
  2308. fetch, etc."""
  2309. raise NotImplementedError()
  2310. def lastrow_has_defaults(self) -> bool:
  2311. """Return True if the last INSERT or UPDATE row contained
  2312. inlined or database-side defaults.
  2313. """
  2314. raise NotImplementedError()
  2315. def get_rowcount(self) -> Optional[int]:
  2316. """Return the DBAPI ``cursor.rowcount`` value, or in some
  2317. cases an interpreted value.
  2318. See :attr:`_engine.CursorResult.rowcount` for details on this.
  2319. """
  2320. raise NotImplementedError()
  2321. def fetchall_for_returning(self, cursor: DBAPICursor) -> Sequence[Any]:
  2322. """For a RETURNING result, deliver cursor.fetchall() from the
  2323. DBAPI cursor.
  2324. This is a dialect-specific hook for dialects that have special
  2325. considerations when calling upon the rows delivered for a
  2326. "RETURNING" statement. Default implementation is
  2327. ``cursor.fetchall()``.
  2328. This hook is currently used only by the :term:`insertmanyvalues`
  2329. feature. Dialects that don't set ``use_insertmanyvalues=True``
  2330. don't need to consider this hook.
  2331. .. versionadded:: 2.0.10
  2332. """
  2333. raise NotImplementedError()
  2334. class ConnectionEventsTarget(EventTarget):
  2335. """An object which can accept events from :class:`.ConnectionEvents`.
  2336. Includes :class:`_engine.Connection` and :class:`_engine.Engine`.
  2337. .. versionadded:: 2.0
  2338. """
  2339. dispatch: dispatcher[ConnectionEventsTarget]
  2340. Connectable = ConnectionEventsTarget
  2341. class ExceptionContext:
  2342. """Encapsulate information about an error condition in progress.
  2343. This object exists solely to be passed to the
  2344. :meth:`_events.DialectEvents.handle_error` event,
  2345. supporting an interface that
  2346. can be extended without backwards-incompatibility.
  2347. """
  2348. __slots__ = ()
  2349. dialect: Dialect
  2350. """The :class:`_engine.Dialect` in use.
  2351. This member is present for all invocations of the event hook.
  2352. .. versionadded:: 2.0
  2353. """
  2354. connection: Optional[Connection]
  2355. """The :class:`_engine.Connection` in use during the exception.
  2356. This member is present, except in the case of a failure when
  2357. first connecting.
  2358. .. seealso::
  2359. :attr:`.ExceptionContext.engine`
  2360. """
  2361. engine: Optional[Engine]
  2362. """The :class:`_engine.Engine` in use during the exception.
  2363. This member is present in all cases except for when handling an error
  2364. within the connection pool "pre-ping" process.
  2365. """
  2366. cursor: Optional[DBAPICursor]
  2367. """The DBAPI cursor object.
  2368. May be None.
  2369. """
  2370. statement: Optional[str]
  2371. """String SQL statement that was emitted directly to the DBAPI.
  2372. May be None.
  2373. """
  2374. parameters: Optional[_DBAPIAnyExecuteParams]
  2375. """Parameter collection that was emitted directly to the DBAPI.
  2376. May be None.
  2377. """
  2378. original_exception: BaseException
  2379. """The exception object which was caught.
  2380. This member is always present.
  2381. """
  2382. sqlalchemy_exception: Optional[StatementError]
  2383. """The :class:`sqlalchemy.exc.StatementError` which wraps the original,
  2384. and will be raised if exception handling is not circumvented by the event.
  2385. May be None, as not all exception types are wrapped by SQLAlchemy.
  2386. For DBAPI-level exceptions that subclass the dbapi's Error class, this
  2387. field will always be present.
  2388. """
  2389. chained_exception: Optional[BaseException]
  2390. """The exception that was returned by the previous handler in the
  2391. exception chain, if any.
  2392. If present, this exception will be the one ultimately raised by
  2393. SQLAlchemy unless a subsequent handler replaces it.
  2394. May be None.
  2395. """
  2396. execution_context: Optional[ExecutionContext]
  2397. """The :class:`.ExecutionContext` corresponding to the execution
  2398. operation in progress.
  2399. This is present for statement execution operations, but not for
  2400. operations such as transaction begin/end. It also is not present when
  2401. the exception was raised before the :class:`.ExecutionContext`
  2402. could be constructed.
  2403. Note that the :attr:`.ExceptionContext.statement` and
  2404. :attr:`.ExceptionContext.parameters` members may represent a
  2405. different value than that of the :class:`.ExecutionContext`,
  2406. potentially in the case where a
  2407. :meth:`_events.ConnectionEvents.before_cursor_execute` event or similar
  2408. modified the statement/parameters to be sent.
  2409. May be None.
  2410. """
  2411. is_disconnect: bool
  2412. """Represent whether the exception as occurred represents a "disconnect"
  2413. condition.
  2414. This flag will always be True or False within the scope of the
  2415. :meth:`_events.DialectEvents.handle_error` handler.
  2416. SQLAlchemy will defer to this flag in order to determine whether or not
  2417. the connection should be invalidated subsequently. That is, by
  2418. assigning to this flag, a "disconnect" event which then results in
  2419. a connection and pool invalidation can be invoked or prevented by
  2420. changing this flag.
  2421. .. note:: The pool "pre_ping" handler enabled using the
  2422. :paramref:`_sa.create_engine.pool_pre_ping` parameter does **not**
  2423. consult this event before deciding if the "ping" returned false,
  2424. as opposed to receiving an unhandled error. For this use case, the
  2425. :ref:`legacy recipe based on engine_connect() may be used
  2426. <pool_disconnects_pessimistic_custom>`. A future API allow more
  2427. comprehensive customization of the "disconnect" detection mechanism
  2428. across all functions.
  2429. """
  2430. invalidate_pool_on_disconnect: bool
  2431. """Represent whether all connections in the pool should be invalidated
  2432. when a "disconnect" condition is in effect.
  2433. Setting this flag to False within the scope of the
  2434. :meth:`_events.DialectEvents.handle_error`
  2435. event will have the effect such
  2436. that the full collection of connections in the pool will not be
  2437. invalidated during a disconnect; only the current connection that is the
  2438. subject of the error will actually be invalidated.
  2439. The purpose of this flag is for custom disconnect-handling schemes where
  2440. the invalidation of other connections in the pool is to be performed
  2441. based on other conditions, or even on a per-connection basis.
  2442. """
  2443. is_pre_ping: bool
  2444. """Indicates if this error is occurring within the "pre-ping" step
  2445. performed when :paramref:`_sa.create_engine.pool_pre_ping` is set to
  2446. ``True``. In this mode, the :attr:`.ExceptionContext.engine` attribute
  2447. will be ``None``. The dialect in use is accessible via the
  2448. :attr:`.ExceptionContext.dialect` attribute.
  2449. .. versionadded:: 2.0.5
  2450. """
  2451. class AdaptedConnection:
  2452. """Interface of an adapted connection object to support the DBAPI protocol.
  2453. Used by asyncio dialects to provide a sync-style pep-249 facade on top
  2454. of the asyncio connection/cursor API provided by the driver.
  2455. .. versionadded:: 1.4.24
  2456. """
  2457. __slots__ = ("_connection",)
  2458. _connection: AsyncIODBAPIConnection
  2459. @property
  2460. def driver_connection(self) -> Any:
  2461. """The connection object as returned by the driver after a connect."""
  2462. return self._connection
  2463. def run_async(self, fn: Callable[[Any], Awaitable[_T]]) -> _T:
  2464. """Run the awaitable returned by the given function, which is passed
  2465. the raw asyncio driver connection.
  2466. This is used to invoke awaitable-only methods on the driver connection
  2467. within the context of a "synchronous" method, like a connection
  2468. pool event handler.
  2469. E.g.::
  2470. engine = create_async_engine(...)
  2471. @event.listens_for(engine.sync_engine, "connect")
  2472. def register_custom_types(
  2473. dbapi_connection, # ...
  2474. ):
  2475. dbapi_connection.run_async(
  2476. lambda connection: connection.set_type_codec(
  2477. "MyCustomType", encoder, decoder, ...
  2478. )
  2479. )
  2480. .. versionadded:: 1.4.30
  2481. .. seealso::
  2482. :ref:`asyncio_events_run_async`
  2483. """
  2484. return await_only(fn(self._connection))
  2485. def __repr__(self) -> str:
  2486. return "<AdaptedConnection %s>" % self._connection