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