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