Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 
 

3433 řádky
111 KiB

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