interfaces.py 111 KB

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