interfaces.py 110 KB

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