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