1# engine/interfaces.py
2# Copyright (C) 2005-2024 the SQLAlchemy authors and contributors
3# <see AUTHORS file>
4#
5# This module is part of SQLAlchemy and is released under
6# the MIT License: https://www.opensource.org/licenses/mit-license.php
7
8"""Define core interfaces used by the engine system."""
9
10from __future__ import annotations
11
12from enum import Enum
13from types import ModuleType
14from typing import Any
15from typing import Awaitable
16from typing import Callable
17from typing import ClassVar
18from typing import Collection
19from typing import Dict
20from typing import Iterable
21from typing import Iterator
22from typing import List
23from typing import Mapping
24from typing import MutableMapping
25from typing import Optional
26from typing import Protocol
27from typing import Sequence
28from typing import Set
29from typing import Tuple
30from typing import Type
31from typing import TYPE_CHECKING
32from typing import TypedDict
33from typing import TypeVar
34from typing import Union
35
36from .. import util
37from ..event import EventTarget
38from ..pool import Pool
39from ..pool import PoolProxiedConnection
40from ..sql.compiler import Compiled as Compiled
41from ..sql.compiler import Compiled # noqa
42from ..sql.compiler import TypeCompiler as TypeCompiler
43from ..sql.compiler import TypeCompiler # noqa
44from ..util import immutabledict
45from ..util.concurrency import await_
46from ..util.typing import Literal
47from ..util.typing import NotRequired
48
49if TYPE_CHECKING:
50 from .base import Connection
51 from .base import Engine
52 from .cursor import CursorResult
53 from .url import URL
54 from ..event import _ListenerFnType
55 from ..event import dispatcher
56 from ..exc import StatementError
57 from ..sql import Executable
58 from ..sql.compiler import _InsertManyValuesBatch
59 from ..sql.compiler import DDLCompiler
60 from ..sql.compiler import IdentifierPreparer
61 from ..sql.compiler import InsertmanyvaluesSentinelOpts
62 from ..sql.compiler import Linting
63 from ..sql.compiler import SQLCompiler
64 from ..sql.elements import BindParameter
65 from ..sql.elements import ClauseElement
66 from ..sql.schema import Column
67 from ..sql.schema import DefaultGenerator
68 from ..sql.schema import SchemaItem
69 from ..sql.schema import Sequence as Sequence_SchemaItem
70 from ..sql.sqltypes import Integer
71 from ..sql.type_api import _TypeMemoDict
72 from ..sql.type_api import TypeEngine
73
74ConnectArgsType = Tuple[Sequence[str], MutableMapping[str, Any]]
75
76_T = TypeVar("_T", bound="Any")
77
78
79class CacheStats(Enum):
80 CACHE_HIT = 0
81 CACHE_MISS = 1
82 CACHING_DISABLED = 2
83 NO_CACHE_KEY = 3
84 NO_DIALECT_SUPPORT = 4
85
86
87class ExecuteStyle(Enum):
88 """indicates the :term:`DBAPI` cursor method that will be used to invoke
89 a statement."""
90
91 EXECUTE = 0
92 """indicates cursor.execute() will be used"""
93
94 EXECUTEMANY = 1
95 """indicates cursor.executemany() will be used."""
96
97 INSERTMANYVALUES = 2
98 """indicates cursor.execute() will be used with an INSERT where the
99 VALUES expression will be expanded to accommodate for multiple
100 parameter sets
101
102 .. seealso::
103
104 :ref:`engine_insertmanyvalues`
105
106 """
107
108
109class DBAPIConnection(Protocol):
110 """protocol representing a :pep:`249` database connection.
111
112 .. versionadded:: 2.0
113
114 .. seealso::
115
116 `Connection Objects <https://www.python.org/dev/peps/pep-0249/#connection-objects>`_
117 - in :pep:`249`
118
119 """ # noqa: E501
120
121 def close(self) -> None: ...
122
123 def commit(self) -> None: ...
124
125 def cursor(self) -> DBAPICursor: ...
126
127 def rollback(self) -> None: ...
128
129 autocommit: bool
130
131
132class DBAPIType(Protocol):
133 """protocol representing a :pep:`249` database type.
134
135 .. versionadded:: 2.0
136
137 .. seealso::
138
139 `Type Objects <https://www.python.org/dev/peps/pep-0249/#type-objects>`_
140 - in :pep:`249`
141
142 """ # noqa: E501
143
144
145class DBAPICursor(Protocol):
146 """protocol representing a :pep:`249` database cursor.
147
148 .. versionadded:: 2.0
149
150 .. seealso::
151
152 `Cursor Objects <https://www.python.org/dev/peps/pep-0249/#cursor-objects>`_
153 - in :pep:`249`
154
155 """ # noqa: E501
156
157 @property
158 def description(
159 self,
160 ) -> _DBAPICursorDescription:
161 """The description attribute of the Cursor.
162
163 .. seealso::
164
165 `cursor.description <https://www.python.org/dev/peps/pep-0249/#description>`_
166 - in :pep:`249`
167
168
169 """ # noqa: E501
170 ...
171
172 @property
173 def rowcount(self) -> int: ...
174
175 arraysize: int
176
177 lastrowid: int
178
179 def close(self) -> None: ...
180
181 def execute(
182 self,
183 operation: Any,
184 parameters: Optional[_DBAPISingleExecuteParams] = None,
185 ) -> Any: ...
186
187 def executemany(
188 self,
189 operation: Any,
190 parameters: _DBAPIMultiExecuteParams,
191 ) -> Any: ...
192
193 def fetchone(self) -> Optional[Any]: ...
194
195 def fetchmany(self, size: int = ...) -> Sequence[Any]: ...
196
197 def fetchall(self) -> Sequence[Any]: ...
198
199 def setinputsizes(self, sizes: Sequence[Any]) -> None: ...
200
201 def setoutputsize(self, size: Any, column: Any) -> None: ...
202
203 def callproc(
204 self, procname: str, parameters: Sequence[Any] = ...
205 ) -> Any: ...
206
207 def nextset(self) -> Optional[bool]: ...
208
209 def __getattr__(self, key: str) -> Any: ...
210
211
212_CoreSingleExecuteParams = Mapping[str, Any]
213_MutableCoreSingleExecuteParams = MutableMapping[str, Any]
214_CoreMultiExecuteParams = Sequence[_CoreSingleExecuteParams]
215_CoreAnyExecuteParams = Union[
216 _CoreMultiExecuteParams, _CoreSingleExecuteParams
217]
218
219_DBAPISingleExecuteParams = Union[Sequence[Any], _CoreSingleExecuteParams]
220
221_DBAPIMultiExecuteParams = Union[
222 Sequence[Sequence[Any]], _CoreMultiExecuteParams
223]
224_DBAPIAnyExecuteParams = Union[
225 _DBAPIMultiExecuteParams, _DBAPISingleExecuteParams
226]
227_DBAPICursorDescription = Sequence[
228 Tuple[
229 str,
230 "DBAPIType",
231 Optional[int],
232 Optional[int],
233 Optional[int],
234 Optional[int],
235 Optional[bool],
236 ]
237]
238
239_AnySingleExecuteParams = _DBAPISingleExecuteParams
240_AnyMultiExecuteParams = _DBAPIMultiExecuteParams
241_AnyExecuteParams = _DBAPIAnyExecuteParams
242
243CompiledCacheType = MutableMapping[Any, "Compiled"]
244SchemaTranslateMapType = Mapping[Optional[str], Optional[str]]
245
246_ImmutableExecuteOptions = immutabledict[str, Any]
247
248_ParamStyle = Literal[
249 "qmark", "numeric", "named", "format", "pyformat", "numeric_dollar"
250]
251
252_GenericSetInputSizesType = List[Tuple[str, Any, "TypeEngine[Any]"]]
253
254IsolationLevel = Literal[
255 "SERIALIZABLE",
256 "REPEATABLE READ",
257 "READ COMMITTED",
258 "READ UNCOMMITTED",
259 "AUTOCOMMIT",
260]
261
262
263class _CoreKnownExecutionOptions(TypedDict, total=False):
264 compiled_cache: Optional[CompiledCacheType]
265 logging_token: str
266 isolation_level: IsolationLevel
267 no_parameters: bool
268 stream_results: bool
269 max_row_buffer: int
270 yield_per: int
271 insertmanyvalues_page_size: int
272 schema_translate_map: Optional[SchemaTranslateMapType]
273 preserve_rowcount: bool
274 driver_column_names: bool
275
276
277_ExecuteOptions = immutabledict[str, Any]
278CoreExecuteOptionsParameter = Union[
279 _CoreKnownExecutionOptions, Mapping[str, Any]
280]
281
282
283class ReflectedIdentity(TypedDict):
284 """represent the reflected IDENTITY structure of a column, corresponding
285 to the :class:`_schema.Identity` construct.
286
287 The :class:`.ReflectedIdentity` structure is part of the
288 :class:`.ReflectedColumn` structure, which is returned by the
289 :meth:`.Inspector.get_columns` method.
290
291 """
292
293 always: bool
294 """type of identity column"""
295
296 on_null: bool
297 """indicates ON NULL"""
298
299 start: int
300 """starting index of the sequence"""
301
302 increment: int
303 """increment value of the sequence"""
304
305 minvalue: int
306 """the minimum value of the sequence."""
307
308 maxvalue: int
309 """the maximum value of the sequence."""
310
311 nominvalue: bool
312 """no minimum value of the sequence."""
313
314 nomaxvalue: bool
315 """no maximum value of the sequence."""
316
317 cycle: bool
318 """allows the sequence to wrap around when the maxvalue
319 or minvalue has been reached."""
320
321 cache: Optional[int]
322 """number of future values in the
323 sequence which are calculated in advance."""
324
325 order: bool
326 """if true, renders the ORDER keyword."""
327
328
329class ReflectedComputed(TypedDict):
330 """Represent the reflected elements of a computed column, corresponding
331 to the :class:`_schema.Computed` construct.
332
333 The :class:`.ReflectedComputed` structure is part of the
334 :class:`.ReflectedColumn` structure, which is returned by the
335 :meth:`.Inspector.get_columns` method.
336
337 """
338
339 sqltext: str
340 """the expression used to generate this column returned
341 as a string SQL expression"""
342
343 persisted: NotRequired[bool]
344 """indicates if the value is stored in the table or computed on demand"""
345
346
347class ReflectedColumn(TypedDict):
348 """Dictionary representing the reflected elements corresponding to
349 a :class:`_schema.Column` object.
350
351 The :class:`.ReflectedColumn` structure is returned by the
352 :class:`.Inspector.get_columns` method.
353
354 """
355
356 name: str
357 """column name"""
358
359 type: TypeEngine[Any]
360 """column type represented as a :class:`.TypeEngine` instance."""
361
362 nullable: bool
363 """boolean flag if the column is NULL or NOT NULL"""
364
365 default: Optional[str]
366 """column default expression as a SQL string"""
367
368 autoincrement: NotRequired[bool]
369 """database-dependent autoincrement flag.
370
371 This flag indicates if the column has a database-side "autoincrement"
372 flag of some kind. Within SQLAlchemy, other kinds of columns may
373 also act as an "autoincrement" column without necessarily having
374 such a flag on them.
375
376 See :paramref:`_schema.Column.autoincrement` for more background on
377 "autoincrement".
378
379 """
380
381 comment: NotRequired[Optional[str]]
382 """comment for the column, if present.
383 Only some dialects return this key
384 """
385
386 computed: NotRequired[ReflectedComputed]
387 """indicates that this column is computed by the database.
388 Only some dialects return this key.
389
390 .. versionadded:: 1.3.16 - added support for computed reflection.
391 """
392
393 identity: NotRequired[ReflectedIdentity]
394 """indicates this column is an IDENTITY column.
395 Only some dialects return this key.
396
397 .. versionadded:: 1.4 - added support for identity column reflection.
398 """
399
400 dialect_options: NotRequired[Dict[str, Any]]
401 """Additional dialect-specific options detected for this reflected
402 object"""
403
404
405class ReflectedConstraint(TypedDict):
406 """Dictionary representing the reflected elements corresponding to
407 :class:`.Constraint`
408
409 A base class for all constraints
410 """
411
412 name: Optional[str]
413 """constraint name"""
414
415 comment: NotRequired[Optional[str]]
416 """comment for the constraint, if present"""
417
418
419class ReflectedCheckConstraint(ReflectedConstraint):
420 """Dictionary representing the reflected elements corresponding to
421 :class:`.CheckConstraint`.
422
423 The :class:`.ReflectedCheckConstraint` structure is returned by the
424 :meth:`.Inspector.get_check_constraints` method.
425
426 """
427
428 sqltext: str
429 """the check constraint's SQL expression"""
430
431 dialect_options: NotRequired[Dict[str, Any]]
432 """Additional dialect-specific options detected for this check constraint
433
434 .. versionadded:: 1.3.8
435 """
436
437
438class ReflectedUniqueConstraint(ReflectedConstraint):
439 """Dictionary representing the reflected elements corresponding to
440 :class:`.UniqueConstraint`.
441
442 The :class:`.ReflectedUniqueConstraint` structure is returned by the
443 :meth:`.Inspector.get_unique_constraints` method.
444
445 """
446
447 column_names: List[str]
448 """column names which comprise the unique constraint"""
449
450 duplicates_index: NotRequired[Optional[str]]
451 "Indicates if this unique constraint duplicates an index with this name"
452
453 dialect_options: NotRequired[Dict[str, Any]]
454 """Additional dialect-specific options detected for this unique
455 constraint"""
456
457
458class ReflectedPrimaryKeyConstraint(ReflectedConstraint):
459 """Dictionary representing the reflected elements corresponding to
460 :class:`.PrimaryKeyConstraint`.
461
462 The :class:`.ReflectedPrimaryKeyConstraint` structure is returned by the
463 :meth:`.Inspector.get_pk_constraint` method.
464
465 """
466
467 constrained_columns: List[str]
468 """column names which comprise the primary key"""
469
470 dialect_options: NotRequired[Dict[str, Any]]
471 """Additional dialect-specific options detected for this primary key"""
472
473
474class ReflectedForeignKeyConstraint(ReflectedConstraint):
475 """Dictionary representing the reflected elements corresponding to
476 :class:`.ForeignKeyConstraint`.
477
478 The :class:`.ReflectedForeignKeyConstraint` structure is returned by
479 the :meth:`.Inspector.get_foreign_keys` method.
480
481 """
482
483 constrained_columns: List[str]
484 """local column names which comprise the foreign key"""
485
486 referred_schema: Optional[str]
487 """schema name of the table being referred"""
488
489 referred_table: str
490 """name of the table being referred"""
491
492 referred_columns: List[str]
493 """referred column names that correspond to ``constrained_columns``"""
494
495 options: NotRequired[Dict[str, Any]]
496 """Additional options detected for this foreign key constraint"""
497
498
499class ReflectedIndex(TypedDict):
500 """Dictionary representing the reflected elements corresponding to
501 :class:`.Index`.
502
503 The :class:`.ReflectedIndex` structure is returned by the
504 :meth:`.Inspector.get_indexes` method.
505
506 """
507
508 name: Optional[str]
509 """index name"""
510
511 column_names: List[Optional[str]]
512 """column names which the index references.
513 An element of this list is ``None`` if it's an expression and is
514 returned in the ``expressions`` list.
515 """
516
517 expressions: NotRequired[List[str]]
518 """Expressions that compose the index. This list, when present, contains
519 both plain column names (that are also in ``column_names``) and
520 expressions (that are ``None`` in ``column_names``).
521 """
522
523 unique: bool
524 """whether or not the index has a unique flag"""
525
526 duplicates_constraint: NotRequired[Optional[str]]
527 "Indicates if this index mirrors a constraint with this name"
528
529 include_columns: NotRequired[List[str]]
530 """columns to include in the INCLUDE clause for supporting databases.
531
532 .. deprecated:: 2.0
533
534 Legacy value, will be replaced with
535 ``index_dict["dialect_options"]["<dialect name>_include"]``
536
537 """
538
539 column_sorting: NotRequired[Dict[str, Tuple[str]]]
540 """optional dict mapping column names or expressions to tuple of sort
541 keywords, which may include ``asc``, ``desc``, ``nulls_first``,
542 ``nulls_last``.
543
544 .. versionadded:: 1.3.5
545 """
546
547 dialect_options: NotRequired[Dict[str, Any]]
548 """Additional dialect-specific options detected for this index"""
549
550
551class ReflectedTableComment(TypedDict):
552 """Dictionary representing the reflected comment corresponding to
553 the :attr:`_schema.Table.comment` attribute.
554
555 The :class:`.ReflectedTableComment` structure is returned by the
556 :meth:`.Inspector.get_table_comment` method.
557
558 """
559
560 text: Optional[str]
561 """text of the comment"""
562
563
564class BindTyping(Enum):
565 """Define different methods of passing typing information for
566 bound parameters in a statement to the database driver.
567
568 .. versionadded:: 2.0
569
570 """
571
572 NONE = 1
573 """No steps are taken to pass typing information to the database driver.
574
575 This is the default behavior for databases such as SQLite, MySQL / MariaDB,
576 SQL Server.
577
578 """
579
580 SETINPUTSIZES = 2
581 """Use the pep-249 setinputsizes method.
582
583 This is only implemented for DBAPIs that support this method and for which
584 the SQLAlchemy dialect has the appropriate infrastructure for that
585 dialect set up. Current dialects include cx_Oracle as well as
586 optional support for SQL Server using pyodbc.
587
588 When using setinputsizes, dialects also have a means of only using the
589 method for certain datatypes using include/exclude lists.
590
591 When SETINPUTSIZES is used, the :meth:`.Dialect.do_set_input_sizes` method
592 is called for each statement executed which has bound parameters.
593
594 """
595
596 RENDER_CASTS = 3
597 """Render casts or other directives in the SQL string.
598
599 This method is used for all PostgreSQL dialects, including asyncpg,
600 pg8000, psycopg, psycopg2. Dialects which implement this can choose
601 which kinds of datatypes are explicitly cast in SQL statements and which
602 aren't.
603
604 When RENDER_CASTS is used, the compiler will invoke the
605 :meth:`.SQLCompiler.render_bind_cast` method for the rendered
606 string representation of each :class:`.BindParameter` object whose
607 dialect-level type sets the :attr:`.TypeEngine.render_bind_cast` attribute.
608
609 The :meth:`.SQLCompiler.render_bind_cast` is also used to render casts
610 for one form of "insertmanyvalues" query, when both
611 :attr:`.InsertmanyvaluesSentinelOpts.USE_INSERT_FROM_SELECT` and
612 :attr:`.InsertmanyvaluesSentinelOpts.RENDER_SELECT_COL_CASTS` are set,
613 where the casts are applied to the intermediary columns e.g.
614 "INSERT INTO t (a, b, c) SELECT p0::TYP, p1::TYP, p2::TYP "
615 "FROM (VALUES (?, ?), (?, ?), ...)".
616
617 .. versionadded:: 2.0.10 - :meth:`.SQLCompiler.render_bind_cast` is now
618 used within some elements of the "insertmanyvalues" implementation.
619
620
621 """
622
623
624VersionInfoType = Tuple[Union[int, str], ...]
625TableKey = Tuple[Optional[str], str]
626
627
628class Dialect(EventTarget):
629 """Define the behavior of a specific database and DB-API combination.
630
631 Any aspect of metadata definition, SQL query generation,
632 execution, result-set handling, or anything else which varies
633 between databases is defined under the general category of the
634 Dialect. The Dialect acts as a factory for other
635 database-specific object implementations including
636 ExecutionContext, Compiled, DefaultGenerator, and TypeEngine.
637
638 .. note:: Third party dialects should not subclass :class:`.Dialect`
639 directly. Instead, subclass :class:`.default.DefaultDialect` or
640 descendant class.
641
642 """
643
644 CACHE_HIT = CacheStats.CACHE_HIT
645 CACHE_MISS = CacheStats.CACHE_MISS
646 CACHING_DISABLED = CacheStats.CACHING_DISABLED
647 NO_CACHE_KEY = CacheStats.NO_CACHE_KEY
648 NO_DIALECT_SUPPORT = CacheStats.NO_DIALECT_SUPPORT
649
650 dispatch: dispatcher[Dialect]
651
652 name: str
653 """identifying name for the dialect from a DBAPI-neutral point of view
654 (i.e. 'sqlite')
655 """
656
657 driver: str
658 """identifying name for the dialect's DBAPI"""
659
660 dialect_description: str
661
662 dbapi: Optional[ModuleType]
663 """A reference to the DBAPI module object itself.
664
665 SQLAlchemy dialects import DBAPI modules using the classmethod
666 :meth:`.Dialect.import_dbapi`. The rationale is so that any dialect
667 module can be imported and used to generate SQL statements without the
668 need for the actual DBAPI driver to be installed. Only when an
669 :class:`.Engine` is constructed using :func:`.create_engine` does the
670 DBAPI get imported; at that point, the creation process will assign
671 the DBAPI module to this attribute.
672
673 Dialects should therefore implement :meth:`.Dialect.import_dbapi`
674 which will import the necessary module and return it, and then refer
675 to ``self.dbapi`` in dialect code in order to refer to the DBAPI module
676 contents.
677
678 .. versionchanged:: The :attr:`.Dialect.dbapi` attribute is exclusively
679 used as the per-:class:`.Dialect`-instance reference to the DBAPI
680 module. The previous not-fully-documented ``.Dialect.dbapi()``
681 classmethod is deprecated and replaced by :meth:`.Dialect.import_dbapi`.
682
683 """
684
685 @util.non_memoized_property
686 def loaded_dbapi(self) -> ModuleType:
687 """same as .dbapi, but is never None; will raise an error if no
688 DBAPI was set up.
689
690 .. versionadded:: 2.0
691
692 """
693 raise NotImplementedError()
694
695 positional: bool
696 """True if the paramstyle for this Dialect is positional."""
697
698 paramstyle: str
699 """the paramstyle to be used (some DB-APIs support multiple
700 paramstyles).
701 """
702
703 compiler_linting: Linting
704
705 statement_compiler: Type[SQLCompiler]
706 """a :class:`.Compiled` class used to compile SQL statements"""
707
708 ddl_compiler: Type[DDLCompiler]
709 """a :class:`.Compiled` class used to compile DDL statements"""
710
711 type_compiler_cls: ClassVar[Type[TypeCompiler]]
712 """a :class:`.Compiled` class used to compile SQL type objects
713
714 .. versionadded:: 2.0
715
716 """
717
718 type_compiler_instance: TypeCompiler
719 """instance of a :class:`.Compiled` class used to compile SQL type
720 objects
721
722 .. versionadded:: 2.0
723
724 """
725
726 type_compiler: Any
727 """legacy; this is a TypeCompiler class at the class level, a
728 TypeCompiler instance at the instance level.
729
730 Refer to type_compiler_instance instead.
731
732 """
733
734 preparer: Type[IdentifierPreparer]
735 """a :class:`.IdentifierPreparer` class used to
736 quote identifiers.
737 """
738
739 identifier_preparer: IdentifierPreparer
740 """This element will refer to an instance of :class:`.IdentifierPreparer`
741 once a :class:`.DefaultDialect` has been constructed.
742
743 """
744
745 server_version_info: Optional[Tuple[Any, ...]]
746 """a tuple containing a version number for the DB backend in use.
747
748 This value is only available for supporting dialects, and is
749 typically populated during the initial connection to the database.
750 """
751
752 default_schema_name: Optional[str]
753 """the name of the default schema. This value is only available for
754 supporting dialects, and is typically populated during the
755 initial connection to the database.
756
757 """
758
759 # NOTE: this does not take into effect engine-level isolation level.
760 # not clear if this should be changed, seems like it should
761 default_isolation_level: Optional[IsolationLevel]
762 """the isolation that is implicitly present on new connections"""
763
764 # create_engine() -> isolation_level currently goes here
765 _on_connect_isolation_level: Optional[IsolationLevel]
766
767 execution_ctx_cls: Type[ExecutionContext]
768 """a :class:`.ExecutionContext` class used to handle statement execution"""
769
770 execute_sequence_format: Union[
771 Type[Tuple[Any, ...]], Type[Tuple[List[Any]]]
772 ]
773 """either the 'tuple' or 'list' type, depending on what cursor.execute()
774 accepts for the second argument (they vary)."""
775
776 supports_alter: bool
777 """``True`` if the database supports ``ALTER TABLE`` - used only for
778 generating foreign key constraints in certain circumstances
779 """
780
781 max_identifier_length: int
782 """The maximum length of identifier names."""
783
784 supports_server_side_cursors: bool
785 """indicates if the dialect supports server side cursors"""
786
787 server_side_cursors: bool
788 """deprecated; indicates if the dialect should attempt to use server
789 side cursors by default"""
790
791 supports_sane_rowcount: bool
792 """Indicate whether the dialect properly implements rowcount for
793 ``UPDATE`` and ``DELETE`` statements.
794 """
795
796 supports_sane_multi_rowcount: bool
797 """Indicate whether the dialect properly implements rowcount for
798 ``UPDATE`` and ``DELETE`` statements when executed via
799 executemany.
800 """
801
802 supports_empty_insert: bool
803 """dialect supports INSERT () VALUES (), i.e. a plain INSERT with no
804 columns in it.
805
806 This is not usually supported; an "empty" insert is typically
807 suited using either "INSERT..DEFAULT VALUES" or
808 "INSERT ... (col) VALUES (DEFAULT)".
809
810 """
811
812 supports_default_values: bool
813 """dialect supports INSERT... DEFAULT VALUES syntax"""
814
815 supports_default_metavalue: bool
816 """dialect supports INSERT...(col) VALUES (DEFAULT) syntax.
817
818 Most databases support this in some way, e.g. SQLite supports it using
819 ``VALUES (NULL)``. MS SQL Server supports the syntax also however
820 is the only included dialect where we have this disabled, as
821 MSSQL does not support the field for the IDENTITY column, which is
822 usually where we like to make use of the feature.
823
824 """
825
826 default_metavalue_token: str = "DEFAULT"
827 """for INSERT... VALUES (DEFAULT) syntax, the token to put in the
828 parenthesis.
829
830 E.g. for SQLite this is the keyword "NULL".
831
832 """
833
834 supports_multivalues_insert: bool
835 """Target database supports INSERT...VALUES with multiple value
836 sets, i.e. INSERT INTO table (cols) VALUES (...), (...), (...), ...
837
838 """
839
840 insert_executemany_returning: bool
841 """dialect / driver / database supports some means of providing
842 INSERT...RETURNING support when dialect.do_executemany() is used.
843
844 """
845
846 insert_executemany_returning_sort_by_parameter_order: bool
847 """dialect / driver / database supports some means of providing
848 INSERT...RETURNING support when dialect.do_executemany() is used
849 along with the :paramref:`_dml.Insert.returning.sort_by_parameter_order`
850 parameter being set.
851
852 """
853
854 update_executemany_returning: bool
855 """dialect supports UPDATE..RETURNING with executemany."""
856
857 delete_executemany_returning: bool
858 """dialect supports DELETE..RETURNING with executemany."""
859
860 use_insertmanyvalues: bool
861 """if True, indicates "insertmanyvalues" functionality should be used
862 to allow for ``insert_executemany_returning`` behavior, if possible.
863
864 In practice, setting this to True means:
865
866 if ``supports_multivalues_insert``, ``insert_returning`` and
867 ``use_insertmanyvalues`` are all True, the SQL compiler will produce
868 an INSERT that will be interpreted by the :class:`.DefaultDialect`
869 as an :attr:`.ExecuteStyle.INSERTMANYVALUES` execution that allows
870 for INSERT of many rows with RETURNING by rewriting a single-row
871 INSERT statement to have multiple VALUES clauses, also executing
872 the statement multiple times for a series of batches when large numbers
873 of rows are given.
874
875 The parameter is False for the default dialect, and is set to
876 True for SQLAlchemy internal dialects SQLite, MySQL/MariaDB, PostgreSQL,
877 SQL Server. It remains at False for Oracle, which provides native
878 "executemany with RETURNING" support and also does not support
879 ``supports_multivalues_insert``. For MySQL/MariaDB, those MySQL
880 dialects that don't support RETURNING will not report
881 ``insert_executemany_returning`` as True.
882
883 .. versionadded:: 2.0
884
885 .. seealso::
886
887 :ref:`engine_insertmanyvalues`
888
889 """
890
891 use_insertmanyvalues_wo_returning: bool
892 """if True, and use_insertmanyvalues is also True, INSERT statements
893 that don't include RETURNING will also use "insertmanyvalues".
894
895 .. versionadded:: 2.0
896
897 .. seealso::
898
899 :ref:`engine_insertmanyvalues`
900
901 """
902
903 insertmanyvalues_implicit_sentinel: InsertmanyvaluesSentinelOpts
904 """Options indicating the database supports a form of bulk INSERT where
905 the autoincrement integer primary key can be reliably used as an ordering
906 for INSERTed rows.
907
908 .. versionadded:: 2.0.10
909
910 .. seealso::
911
912 :ref:`engine_insertmanyvalues_returning_order`
913
914 """
915
916 insertmanyvalues_page_size: int
917 """Number of rows to render into an individual INSERT..VALUES() statement
918 for :attr:`.ExecuteStyle.INSERTMANYVALUES` executions.
919
920 The default dialect defaults this to 1000.
921
922 .. versionadded:: 2.0
923
924 .. seealso::
925
926 :paramref:`_engine.Connection.execution_options.insertmanyvalues_page_size` -
927 execution option available on :class:`_engine.Connection`, statements
928
929 """ # noqa: E501
930
931 insertmanyvalues_max_parameters: int
932 """Alternate to insertmanyvalues_page_size, will additionally limit
933 page size based on number of parameters total in the statement.
934
935
936 """
937
938 preexecute_autoincrement_sequences: bool
939 """True if 'implicit' primary key functions must be executed separately
940 in order to get their value, if RETURNING is not used.
941
942 This is currently oriented towards PostgreSQL when the
943 ``implicit_returning=False`` parameter is used on a :class:`.Table`
944 object.
945
946 """
947
948 insert_returning: bool
949 """if the dialect supports RETURNING with INSERT
950
951 .. versionadded:: 2.0
952
953 """
954
955 update_returning: bool
956 """if the dialect supports RETURNING with UPDATE
957
958 .. versionadded:: 2.0
959
960 """
961
962 update_returning_multifrom: bool
963 """if the dialect supports RETURNING with UPDATE..FROM
964
965 .. versionadded:: 2.0
966
967 """
968
969 delete_returning: bool
970 """if the dialect supports RETURNING with DELETE
971
972 .. versionadded:: 2.0
973
974 """
975
976 delete_returning_multifrom: bool
977 """if the dialect supports RETURNING with DELETE..FROM
978
979 .. versionadded:: 2.0
980
981 """
982
983 favor_returning_over_lastrowid: bool
984 """for backends that support both a lastrowid and a RETURNING insert
985 strategy, favor RETURNING for simple single-int pk inserts.
986
987 cursor.lastrowid tends to be more performant on most backends.
988
989 """
990
991 supports_identity_columns: bool
992 """target database supports IDENTITY"""
993
994 cte_follows_insert: bool
995 """target database, when given a CTE with an INSERT statement, needs
996 the CTE to be below the INSERT"""
997
998 colspecs: MutableMapping[Type[TypeEngine[Any]], Type[TypeEngine[Any]]]
999 """A dictionary of TypeEngine classes from sqlalchemy.types mapped
1000 to subclasses that are specific to the dialect class. This
1001 dictionary is class-level only and is not accessed from the
1002 dialect instance itself.
1003 """
1004
1005 supports_sequences: bool
1006 """Indicates if the dialect supports CREATE SEQUENCE or similar."""
1007
1008 sequences_optional: bool
1009 """If True, indicates if the :paramref:`_schema.Sequence.optional`
1010 parameter on the :class:`_schema.Sequence` construct
1011 should signal to not generate a CREATE SEQUENCE. Applies only to
1012 dialects that support sequences. Currently used only to allow PostgreSQL
1013 SERIAL to be used on a column that specifies Sequence() for usage on
1014 other backends.
1015 """
1016
1017 default_sequence_base: int
1018 """the default value that will be rendered as the "START WITH" portion of
1019 a CREATE SEQUENCE DDL statement.
1020
1021 """
1022
1023 supports_native_enum: bool
1024 """Indicates if the dialect supports a native ENUM construct.
1025 This will prevent :class:`_types.Enum` from generating a CHECK
1026 constraint when that type is used in "native" mode.
1027 """
1028
1029 supports_native_boolean: bool
1030 """Indicates if the dialect supports a native boolean construct.
1031 This will prevent :class:`_types.Boolean` from generating a CHECK
1032 constraint when that type is used.
1033 """
1034
1035 supports_native_decimal: bool
1036 """indicates if Decimal objects are handled and returned for precision
1037 numeric types, or if floats are returned"""
1038
1039 supports_native_uuid: bool
1040 """indicates if Python UUID() objects are handled natively by the
1041 driver for SQL UUID datatypes.
1042
1043 .. versionadded:: 2.0
1044
1045 """
1046
1047 returns_native_bytes: bool
1048 """indicates if Python bytes() objects are returned natively by the
1049 driver for SQL "binary" datatypes.
1050
1051 .. versionadded:: 2.0.11
1052
1053 """
1054
1055 construct_arguments: Optional[
1056 List[Tuple[Type[Union[SchemaItem, ClauseElement]], Mapping[str, Any]]]
1057 ] = None
1058 """Optional set of argument specifiers for various SQLAlchemy
1059 constructs, typically schema items.
1060
1061 To implement, establish as a series of tuples, as in::
1062
1063 construct_arguments = [
1064 (schema.Index, {
1065 "using": False,
1066 "where": None,
1067 "ops": None
1068 })
1069 ]
1070
1071 If the above construct is established on the PostgreSQL dialect,
1072 the :class:`.Index` construct will now accept the keyword arguments
1073 ``postgresql_using``, ``postgresql_where``, nad ``postgresql_ops``.
1074 Any other argument specified to the constructor of :class:`.Index`
1075 which is prefixed with ``postgresql_`` will raise :class:`.ArgumentError`.
1076
1077 A dialect which does not include a ``construct_arguments`` member will
1078 not participate in the argument validation system. For such a dialect,
1079 any argument name is accepted by all participating constructs, within
1080 the namespace of arguments prefixed with that dialect name. The rationale
1081 here is so that third-party dialects that haven't yet implemented this
1082 feature continue to function in the old way.
1083
1084 .. seealso::
1085
1086 :class:`.DialectKWArgs` - implementing base class which consumes
1087 :attr:`.DefaultDialect.construct_arguments`
1088
1089
1090 """
1091
1092 reflection_options: Sequence[str] = ()
1093 """Sequence of string names indicating keyword arguments that can be
1094 established on a :class:`.Table` object which will be passed as
1095 "reflection options" when using :paramref:`.Table.autoload_with`.
1096
1097 Current example is "oracle_resolve_synonyms" in the Oracle dialect.
1098
1099 """
1100
1101 dbapi_exception_translation_map: Mapping[str, str] = util.EMPTY_DICT
1102 """A dictionary of names that will contain as values the names of
1103 pep-249 exceptions ("IntegrityError", "OperationalError", etc)
1104 keyed to alternate class names, to support the case where a
1105 DBAPI has exception classes that aren't named as they are
1106 referred to (e.g. IntegrityError = MyException). In the vast
1107 majority of cases this dictionary is empty.
1108 """
1109
1110 supports_comments: bool
1111 """Indicates the dialect supports comment DDL on tables and columns."""
1112
1113 inline_comments: bool
1114 """Indicates the dialect supports comment DDL that's inline with the
1115 definition of a Table or Column. If False, this implies that ALTER must
1116 be used to set table and column comments."""
1117
1118 supports_constraint_comments: bool
1119 """Indicates if the dialect supports comment DDL on constraints.
1120
1121 .. versionadded: 2.0
1122 """
1123
1124 _has_events = False
1125
1126 supports_statement_cache: bool = True
1127 """indicates if this dialect supports caching.
1128
1129 All dialects that are compatible with statement caching should set this
1130 flag to True directly on each dialect class and subclass that supports
1131 it. SQLAlchemy tests that this flag is locally present on each dialect
1132 subclass before it will use statement caching. This is to provide
1133 safety for legacy or new dialects that are not yet fully tested to be
1134 compliant with SQL statement caching.
1135
1136 .. versionadded:: 1.4.5
1137
1138 .. seealso::
1139
1140 :ref:`engine_thirdparty_caching`
1141
1142 """
1143
1144 _supports_statement_cache: bool
1145 """internal evaluation for supports_statement_cache"""
1146
1147 bind_typing = BindTyping.NONE
1148 """define a means of passing typing information to the database and/or
1149 driver for bound parameters.
1150
1151 See :class:`.BindTyping` for values.
1152
1153 .. versionadded:: 2.0
1154
1155 """
1156
1157 is_async: bool
1158 """Whether or not this dialect is intended for asyncio use."""
1159
1160 has_terminate: bool
1161 """Whether or not this dialect has a separate "terminate" implementation
1162 that does not block or require awaiting."""
1163
1164 engine_config_types: Mapping[str, Any]
1165 """a mapping of string keys that can be in an engine config linked to
1166 type conversion functions.
1167
1168 """
1169
1170 label_length: Optional[int]
1171 """optional user-defined max length for SQL labels"""
1172
1173 include_set_input_sizes: Optional[Set[Any]]
1174 """set of DBAPI type objects that should be included in
1175 automatic cursor.setinputsizes() calls.
1176
1177 This is only used if bind_typing is BindTyping.SET_INPUT_SIZES
1178
1179 """
1180
1181 exclude_set_input_sizes: Optional[Set[Any]]
1182 """set of DBAPI type objects that should be excluded in
1183 automatic cursor.setinputsizes() calls.
1184
1185 This is only used if bind_typing is BindTyping.SET_INPUT_SIZES
1186
1187 """
1188
1189 supports_simple_order_by_label: bool
1190 """target database supports ORDER BY <labelname>, where <labelname>
1191 refers to a label in the columns clause of the SELECT"""
1192
1193 div_is_floordiv: bool
1194 """target database treats the / division operator as "floor division" """
1195
1196 tuple_in_values: bool
1197 """target database supports tuple IN, i.e. (x, y) IN ((q, p), (r, z))"""
1198
1199 _bind_typing_render_casts: bool
1200
1201 _type_memos: MutableMapping[TypeEngine[Any], _TypeMemoDict]
1202
1203 def _builtin_onconnect(self) -> Optional[_ListenerFnType]:
1204 raise NotImplementedError()
1205
1206 def create_connect_args(self, url: URL) -> ConnectArgsType:
1207 """Build DB-API compatible connection arguments.
1208
1209 Given a :class:`.URL` object, returns a tuple
1210 consisting of a ``(*args, **kwargs)`` suitable to send directly
1211 to the dbapi's connect function. The arguments are sent to the
1212 :meth:`.Dialect.connect` method which then runs the DBAPI-level
1213 ``connect()`` function.
1214
1215 The method typically makes use of the
1216 :meth:`.URL.translate_connect_args`
1217 method in order to generate a dictionary of options.
1218
1219 The default implementation is::
1220
1221 def create_connect_args(self, url):
1222 opts = url.translate_connect_args()
1223 opts.update(url.query)
1224 return ([], opts)
1225
1226 :param url: a :class:`.URL` object
1227
1228 :return: a tuple of ``(*args, **kwargs)`` which will be passed to the
1229 :meth:`.Dialect.connect` method.
1230
1231 .. seealso::
1232
1233 :meth:`.URL.translate_connect_args`
1234
1235 """
1236
1237 raise NotImplementedError()
1238
1239 @classmethod
1240 def import_dbapi(cls) -> ModuleType:
1241 """Import the DBAPI module that is used by this dialect.
1242
1243 The Python module object returned here will be assigned as an
1244 instance variable to a constructed dialect under the name
1245 ``.dbapi``.
1246
1247 .. versionchanged:: 2.0 The :meth:`.Dialect.import_dbapi` class
1248 method is renamed from the previous method ``.Dialect.dbapi()``,
1249 which would be replaced at dialect instantiation time by the
1250 DBAPI module itself, thus using the same name in two different ways.
1251 If a ``.Dialect.dbapi()`` classmethod is present on a third-party
1252 dialect, it will be used and a deprecation warning will be emitted.
1253
1254 """
1255 raise NotImplementedError()
1256
1257 def type_descriptor(self, typeobj: TypeEngine[_T]) -> TypeEngine[_T]:
1258 """Transform a generic type to a dialect-specific type.
1259
1260 Dialect classes will usually use the
1261 :func:`_types.adapt_type` function in the types module to
1262 accomplish this.
1263
1264 The returned result is cached *per dialect class* so can
1265 contain no dialect-instance state.
1266
1267 """
1268
1269 raise NotImplementedError()
1270
1271 def initialize(self, connection: Connection) -> None:
1272 """Called during strategized creation of the dialect with a
1273 connection.
1274
1275 Allows dialects to configure options based on server version info or
1276 other properties.
1277
1278 The connection passed here is a SQLAlchemy Connection object,
1279 with full capabilities.
1280
1281 The initialize() method of the base dialect should be called via
1282 super().
1283
1284 .. note:: as of SQLAlchemy 1.4, this method is called **before**
1285 any :meth:`_engine.Dialect.on_connect` hooks are called.
1286
1287 """
1288
1289 pass
1290
1291 if TYPE_CHECKING:
1292
1293 def _overrides_default(self, method_name: str) -> bool: ...
1294
1295 def get_columns(
1296 self,
1297 connection: Connection,
1298 table_name: str,
1299 schema: Optional[str] = None,
1300 **kw: Any,
1301 ) -> List[ReflectedColumn]:
1302 """Return information about columns in ``table_name``.
1303
1304 Given a :class:`_engine.Connection`, a string
1305 ``table_name``, and an optional string ``schema``, return column
1306 information as a list of dictionaries
1307 corresponding to the :class:`.ReflectedColumn` dictionary.
1308
1309 This is an internal dialect method. Applications should use
1310 :meth:`.Inspector.get_columns`.
1311
1312 """
1313
1314 raise NotImplementedError()
1315
1316 def get_multi_columns(
1317 self,
1318 connection: Connection,
1319 *,
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 ) -> List[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
2664class CreateEnginePlugin:
2665 """A set of hooks intended to augment the construction of an
2666 :class:`_engine.Engine` object based on entrypoint names in a URL.
2667
2668 The purpose of :class:`_engine.CreateEnginePlugin` is to allow third-party
2669 systems to apply engine, pool and dialect level event listeners without
2670 the need for the target application to be modified; instead, the plugin
2671 names can be added to the database URL. Target applications for
2672 :class:`_engine.CreateEnginePlugin` include:
2673
2674 * connection and SQL performance tools, e.g. which use events to track
2675 number of checkouts and/or time spent with statements
2676
2677 * connectivity plugins such as proxies
2678
2679 A rudimentary :class:`_engine.CreateEnginePlugin` that attaches a logger
2680 to an :class:`_engine.Engine` object might look like::
2681
2682
2683 import logging
2684
2685 from sqlalchemy.engine import CreateEnginePlugin
2686 from sqlalchemy import event
2687
2688 class LogCursorEventsPlugin(CreateEnginePlugin):
2689 def __init__(self, url, kwargs):
2690 # consume the parameter "log_cursor_logging_name" from the
2691 # URL query
2692 logging_name = url.query.get("log_cursor_logging_name", "log_cursor")
2693
2694 self.log = logging.getLogger(logging_name)
2695
2696 def update_url(self, url):
2697 "update the URL to one that no longer includes our parameters"
2698 return url.difference_update_query(["log_cursor_logging_name"])
2699
2700 def engine_created(self, engine):
2701 "attach an event listener after the new Engine is constructed"
2702 event.listen(engine, "before_cursor_execute", self._log_event)
2703
2704
2705 def _log_event(
2706 self,
2707 conn,
2708 cursor,
2709 statement,
2710 parameters,
2711 context,
2712 executemany):
2713
2714 self.log.info("Plugin logged cursor event: %s", statement)
2715
2716
2717
2718 Plugins are registered using entry points in a similar way as that
2719 of dialects::
2720
2721 entry_points={
2722 'sqlalchemy.plugins': [
2723 'log_cursor_plugin = myapp.plugins:LogCursorEventsPlugin'
2724 ]
2725
2726 A plugin that uses the above names would be invoked from a database
2727 URL as in::
2728
2729 from sqlalchemy import create_engine
2730
2731 engine = create_engine(
2732 "mysql+pymysql://scott:tiger@localhost/test?"
2733 "plugin=log_cursor_plugin&log_cursor_logging_name=mylogger"
2734 )
2735
2736 The ``plugin`` URL parameter supports multiple instances, so that a URL
2737 may specify multiple plugins; they are loaded in the order stated
2738 in the URL::
2739
2740 engine = create_engine(
2741 "mysql+pymysql://scott:tiger@localhost/test?"
2742 "plugin=plugin_one&plugin=plugin_twp&plugin=plugin_three")
2743
2744 The plugin names may also be passed directly to :func:`_sa.create_engine`
2745 using the :paramref:`_sa.create_engine.plugins` argument::
2746
2747 engine = create_engine(
2748 "mysql+pymysql://scott:tiger@localhost/test",
2749 plugins=["myplugin"])
2750
2751 .. versionadded:: 1.2.3 plugin names can also be specified
2752 to :func:`_sa.create_engine` as a list
2753
2754 A plugin may consume plugin-specific arguments from the
2755 :class:`_engine.URL` object as well as the ``kwargs`` dictionary, which is
2756 the dictionary of arguments passed to the :func:`_sa.create_engine`
2757 call. "Consuming" these arguments includes that they must be removed
2758 when the plugin initializes, so that the arguments are not passed along
2759 to the :class:`_engine.Dialect` constructor, where they will raise an
2760 :class:`_exc.ArgumentError` because they are not known by the dialect.
2761
2762 As of version 1.4 of SQLAlchemy, arguments should continue to be consumed
2763 from the ``kwargs`` dictionary directly, by removing the values with a
2764 method such as ``dict.pop``. Arguments from the :class:`_engine.URL` object
2765 should be consumed by implementing the
2766 :meth:`_engine.CreateEnginePlugin.update_url` method, returning a new copy
2767 of the :class:`_engine.URL` with plugin-specific parameters removed::
2768
2769 class MyPlugin(CreateEnginePlugin):
2770 def __init__(self, url, kwargs):
2771 self.my_argument_one = url.query['my_argument_one']
2772 self.my_argument_two = url.query['my_argument_two']
2773 self.my_argument_three = kwargs.pop('my_argument_three', None)
2774
2775 def update_url(self, url):
2776 return url.difference_update_query(
2777 ["my_argument_one", "my_argument_two"]
2778 )
2779
2780 Arguments like those illustrated above would be consumed from a
2781 :func:`_sa.create_engine` call such as::
2782
2783 from sqlalchemy import create_engine
2784
2785 engine = create_engine(
2786 "mysql+pymysql://scott:tiger@localhost/test?"
2787 "plugin=myplugin&my_argument_one=foo&my_argument_two=bar",
2788 my_argument_three='bat'
2789 )
2790
2791 .. versionchanged:: 1.4
2792
2793 The :class:`_engine.URL` object is now immutable; a
2794 :class:`_engine.CreateEnginePlugin` that needs to alter the
2795 :class:`_engine.URL` should implement the newly added
2796 :meth:`_engine.CreateEnginePlugin.update_url` method, which
2797 is invoked after the plugin is constructed.
2798
2799 For migration, construct the plugin in the following way, checking
2800 for the existence of the :meth:`_engine.CreateEnginePlugin.update_url`
2801 method to detect which version is running::
2802
2803 class MyPlugin(CreateEnginePlugin):
2804 def __init__(self, url, kwargs):
2805 if hasattr(CreateEnginePlugin, "update_url"):
2806 # detect the 1.4 API
2807 self.my_argument_one = url.query['my_argument_one']
2808 self.my_argument_two = url.query['my_argument_two']
2809 else:
2810 # detect the 1.3 and earlier API - mutate the
2811 # URL directly
2812 self.my_argument_one = url.query.pop('my_argument_one')
2813 self.my_argument_two = url.query.pop('my_argument_two')
2814
2815 self.my_argument_three = kwargs.pop('my_argument_three', None)
2816
2817 def update_url(self, url):
2818 # this method is only called in the 1.4 version
2819 return url.difference_update_query(
2820 ["my_argument_one", "my_argument_two"]
2821 )
2822
2823 .. seealso::
2824
2825 :ref:`change_5526` - overview of the :class:`_engine.URL` change which
2826 also includes notes regarding :class:`_engine.CreateEnginePlugin`.
2827
2828
2829 When the engine creation process completes and produces the
2830 :class:`_engine.Engine` object, it is again passed to the plugin via the
2831 :meth:`_engine.CreateEnginePlugin.engine_created` hook. In this hook, additional
2832 changes can be made to the engine, most typically involving setup of
2833 events (e.g. those defined in :ref:`core_event_toplevel`).
2834
2835 """ # noqa: E501
2836
2837 def __init__(self, url: URL, kwargs: Dict[str, Any]):
2838 """Construct a new :class:`.CreateEnginePlugin`.
2839
2840 The plugin object is instantiated individually for each call
2841 to :func:`_sa.create_engine`. A single :class:`_engine.
2842 Engine` will be
2843 passed to the :meth:`.CreateEnginePlugin.engine_created` method
2844 corresponding to this URL.
2845
2846 :param url: the :class:`_engine.URL` object. The plugin may inspect
2847 the :class:`_engine.URL` for arguments. Arguments used by the
2848 plugin should be removed, by returning an updated :class:`_engine.URL`
2849 from the :meth:`_engine.CreateEnginePlugin.update_url` method.
2850
2851 .. versionchanged:: 1.4
2852
2853 The :class:`_engine.URL` object is now immutable, so a
2854 :class:`_engine.CreateEnginePlugin` that needs to alter the
2855 :class:`_engine.URL` object should implement the
2856 :meth:`_engine.CreateEnginePlugin.update_url` method.
2857
2858 :param kwargs: The keyword arguments passed to
2859 :func:`_sa.create_engine`.
2860
2861 """
2862 self.url = url
2863
2864 def update_url(self, url: URL) -> URL:
2865 """Update the :class:`_engine.URL`.
2866
2867 A new :class:`_engine.URL` should be returned. This method is
2868 typically used to consume configuration arguments from the
2869 :class:`_engine.URL` which must be removed, as they will not be
2870 recognized by the dialect. The
2871 :meth:`_engine.URL.difference_update_query` method is available
2872 to remove these arguments. See the docstring at
2873 :class:`_engine.CreateEnginePlugin` for an example.
2874
2875
2876 .. versionadded:: 1.4
2877
2878 """
2879 raise NotImplementedError()
2880
2881 def handle_dialect_kwargs(
2882 self, dialect_cls: Type[Dialect], dialect_args: Dict[str, Any]
2883 ) -> None:
2884 """parse and modify dialect kwargs"""
2885
2886 def handle_pool_kwargs(
2887 self, pool_cls: Type[Pool], pool_args: Dict[str, Any]
2888 ) -> None:
2889 """parse and modify pool kwargs"""
2890
2891 def engine_created(self, engine: Engine) -> None:
2892 """Receive the :class:`_engine.Engine`
2893 object when it is fully constructed.
2894
2895 The plugin may make additional changes to the engine, such as
2896 registering engine or connection pool events.
2897
2898 """
2899
2900
2901class ExecutionContext:
2902 """A messenger object for a Dialect that corresponds to a single
2903 execution.
2904
2905 """
2906
2907 engine: Engine
2908 """engine which the Connection is associated with"""
2909
2910 connection: Connection
2911 """Connection object which can be freely used by default value
2912 generators to execute SQL. This Connection should reference the
2913 same underlying connection/transactional resources of
2914 root_connection."""
2915
2916 root_connection: Connection
2917 """Connection object which is the source of this ExecutionContext."""
2918
2919 dialect: Dialect
2920 """dialect which created this ExecutionContext."""
2921
2922 cursor: DBAPICursor
2923 """DB-API cursor procured from the connection"""
2924
2925 compiled: Optional[Compiled]
2926 """if passed to constructor, sqlalchemy.engine.base.Compiled object
2927 being executed"""
2928
2929 statement: str
2930 """string version of the statement to be executed. Is either
2931 passed to the constructor, or must be created from the
2932 sql.Compiled object by the time pre_exec() has completed."""
2933
2934 invoked_statement: Optional[Executable]
2935 """The Executable statement object that was given in the first place.
2936
2937 This should be structurally equivalent to compiled.statement, but not
2938 necessarily the same object as in a caching scenario the compiled form
2939 will have been extracted from the cache.
2940
2941 """
2942
2943 parameters: _AnyMultiExecuteParams
2944 """bind parameters passed to the execute() or exec_driver_sql() methods.
2945
2946 These are always stored as a list of parameter entries. A single-element
2947 list corresponds to a ``cursor.execute()`` call and a multiple-element
2948 list corresponds to ``cursor.executemany()``, except in the case
2949 of :attr:`.ExecuteStyle.INSERTMANYVALUES` which will use
2950 ``cursor.execute()`` one or more times.
2951
2952 """
2953
2954 no_parameters: bool
2955 """True if the execution style does not use parameters"""
2956
2957 isinsert: bool
2958 """True if the statement is an INSERT."""
2959
2960 isupdate: bool
2961 """True if the statement is an UPDATE."""
2962
2963 execute_style: ExecuteStyle
2964 """the style of DBAPI cursor method that will be used to execute
2965 a statement.
2966
2967 .. versionadded:: 2.0
2968
2969 """
2970
2971 executemany: bool
2972 """True if the context has a list of more than one parameter set.
2973
2974 Historically this attribute links to whether ``cursor.execute()`` or
2975 ``cursor.executemany()`` will be used. It also can now mean that
2976 "insertmanyvalues" may be used which indicates one or more
2977 ``cursor.execute()`` calls.
2978
2979 """
2980
2981 prefetch_cols: util.generic_fn_descriptor[Optional[Sequence[Column[Any]]]]
2982 """a list of Column objects for which a client-side default
2983 was fired off. Applies to inserts and updates."""
2984
2985 postfetch_cols: util.generic_fn_descriptor[Optional[Sequence[Column[Any]]]]
2986 """a list of Column objects for which a server-side default or
2987 inline SQL expression value was fired off. Applies to inserts
2988 and updates."""
2989
2990 execution_options: _ExecuteOptions
2991 """Execution options associated with the current statement execution"""
2992
2993 @classmethod
2994 def _init_ddl(
2995 cls,
2996 dialect: Dialect,
2997 connection: Connection,
2998 dbapi_connection: PoolProxiedConnection,
2999 execution_options: _ExecuteOptions,
3000 compiled_ddl: DDLCompiler,
3001 ) -> ExecutionContext:
3002 raise NotImplementedError()
3003
3004 @classmethod
3005 def _init_compiled(
3006 cls,
3007 dialect: Dialect,
3008 connection: Connection,
3009 dbapi_connection: PoolProxiedConnection,
3010 execution_options: _ExecuteOptions,
3011 compiled: SQLCompiler,
3012 parameters: _CoreMultiExecuteParams,
3013 invoked_statement: Executable,
3014 extracted_parameters: Optional[Sequence[BindParameter[Any]]],
3015 cache_hit: CacheStats = CacheStats.CACHING_DISABLED,
3016 ) -> ExecutionContext:
3017 raise NotImplementedError()
3018
3019 @classmethod
3020 def _init_statement(
3021 cls,
3022 dialect: Dialect,
3023 connection: Connection,
3024 dbapi_connection: PoolProxiedConnection,
3025 execution_options: _ExecuteOptions,
3026 statement: str,
3027 parameters: _DBAPIMultiExecuteParams,
3028 ) -> ExecutionContext:
3029 raise NotImplementedError()
3030
3031 @classmethod
3032 def _init_default(
3033 cls,
3034 dialect: Dialect,
3035 connection: Connection,
3036 dbapi_connection: PoolProxiedConnection,
3037 execution_options: _ExecuteOptions,
3038 ) -> ExecutionContext:
3039 raise NotImplementedError()
3040
3041 def _exec_default(
3042 self,
3043 column: Optional[Column[Any]],
3044 default: DefaultGenerator,
3045 type_: Optional[TypeEngine[Any]],
3046 ) -> Any:
3047 raise NotImplementedError()
3048
3049 def _prepare_set_input_sizes(
3050 self,
3051 ) -> Optional[List[Tuple[str, Any, TypeEngine[Any]]]]:
3052 raise NotImplementedError()
3053
3054 def _get_cache_stats(self) -> str:
3055 raise NotImplementedError()
3056
3057 def _setup_result_proxy(self) -> CursorResult[Any]:
3058 raise NotImplementedError()
3059
3060 def fire_sequence(self, seq: Sequence_SchemaItem, type_: Integer) -> int:
3061 """given a :class:`.Sequence`, invoke it and return the next int
3062 value"""
3063 raise NotImplementedError()
3064
3065 def create_cursor(self) -> DBAPICursor:
3066 """Return a new cursor generated from this ExecutionContext's
3067 connection.
3068
3069 Some dialects may wish to change the behavior of
3070 connection.cursor(), such as postgresql which may return a PG
3071 "server side" cursor.
3072 """
3073
3074 raise NotImplementedError()
3075
3076 def pre_exec(self) -> None:
3077 """Called before an execution of a compiled statement.
3078
3079 If a compiled statement was passed to this ExecutionContext,
3080 the `statement` and `parameters` datamembers must be
3081 initialized after this statement is complete.
3082 """
3083
3084 raise NotImplementedError()
3085
3086 def get_out_parameter_values(
3087 self, out_param_names: Sequence[str]
3088 ) -> Sequence[Any]:
3089 """Return a sequence of OUT parameter values from a cursor.
3090
3091 For dialects that support OUT parameters, this method will be called
3092 when there is a :class:`.SQLCompiler` object which has the
3093 :attr:`.SQLCompiler.has_out_parameters` flag set. This flag in turn
3094 will be set to True if the statement itself has :class:`.BindParameter`
3095 objects that have the ``.isoutparam`` flag set which are consumed by
3096 the :meth:`.SQLCompiler.visit_bindparam` method. If the dialect
3097 compiler produces :class:`.BindParameter` objects with ``.isoutparam``
3098 set which are not handled by :meth:`.SQLCompiler.visit_bindparam`, it
3099 should set this flag explicitly.
3100
3101 The list of names that were rendered for each bound parameter
3102 is passed to the method. The method should then return a sequence of
3103 values corresponding to the list of parameter objects. Unlike in
3104 previous SQLAlchemy versions, the values can be the **raw values** from
3105 the DBAPI; the execution context will apply the appropriate type
3106 handler based on what's present in self.compiled.binds and update the
3107 values. The processed dictionary will then be made available via the
3108 ``.out_parameters`` collection on the result object. Note that
3109 SQLAlchemy 1.4 has multiple kinds of result object as part of the 2.0
3110 transition.
3111
3112 .. versionadded:: 1.4 - added
3113 :meth:`.ExecutionContext.get_out_parameter_values`, which is invoked
3114 automatically by the :class:`.DefaultExecutionContext` when there
3115 are :class:`.BindParameter` objects with the ``.isoutparam`` flag
3116 set. This replaces the practice of setting out parameters within
3117 the now-removed ``get_result_proxy()`` method.
3118
3119 """
3120 raise NotImplementedError()
3121
3122 def post_exec(self) -> None:
3123 """Called after the execution of a compiled statement.
3124
3125 If a compiled statement was passed to this ExecutionContext,
3126 the `last_insert_ids`, `last_inserted_params`, etc.
3127 datamembers should be available after this method completes.
3128 """
3129
3130 raise NotImplementedError()
3131
3132 def handle_dbapi_exception(self, e: BaseException) -> None:
3133 """Receive a DBAPI exception which occurred upon execute, result
3134 fetch, etc."""
3135
3136 raise NotImplementedError()
3137
3138 def lastrow_has_defaults(self) -> bool:
3139 """Return True if the last INSERT or UPDATE row contained
3140 inlined or database-side defaults.
3141 """
3142
3143 raise NotImplementedError()
3144
3145 def get_rowcount(self) -> Optional[int]:
3146 """Return the DBAPI ``cursor.rowcount`` value, or in some
3147 cases an interpreted value.
3148
3149 See :attr:`_engine.CursorResult.rowcount` for details on this.
3150
3151 """
3152
3153 raise NotImplementedError()
3154
3155 def fetchall_for_returning(self, cursor: DBAPICursor) -> Sequence[Any]:
3156 """For a RETURNING result, deliver cursor.fetchall() from the
3157 DBAPI cursor.
3158
3159 This is a dialect-specific hook for dialects that have special
3160 considerations when calling upon the rows delivered for a
3161 "RETURNING" statement. Default implementation is
3162 ``cursor.fetchall()``.
3163
3164 This hook is currently used only by the :term:`insertmanyvalues`
3165 feature. Dialects that don't set ``use_insertmanyvalues=True``
3166 don't need to consider this hook.
3167
3168 .. versionadded:: 2.0.10
3169
3170 """
3171 raise NotImplementedError()
3172
3173
3174class ConnectionEventsTarget(EventTarget):
3175 """An object which can accept events from :class:`.ConnectionEvents`.
3176
3177 Includes :class:`_engine.Connection` and :class:`_engine.Engine`.
3178
3179 .. versionadded:: 2.0
3180
3181 """
3182
3183 dispatch: dispatcher[ConnectionEventsTarget]
3184
3185
3186Connectable = ConnectionEventsTarget
3187
3188
3189class ExceptionContext:
3190 """Encapsulate information about an error condition in progress.
3191
3192 This object exists solely to be passed to the
3193 :meth:`_events.DialectEvents.handle_error` event,
3194 supporting an interface that
3195 can be extended without backwards-incompatibility.
3196
3197
3198 """
3199
3200 __slots__ = ()
3201
3202 dialect: Dialect
3203 """The :class:`_engine.Dialect` in use.
3204
3205 This member is present for all invocations of the event hook.
3206
3207 .. versionadded:: 2.0
3208
3209 """
3210
3211 connection: Optional[Connection]
3212 """The :class:`_engine.Connection` in use during the exception.
3213
3214 This member is present, except in the case of a failure when
3215 first connecting.
3216
3217 .. seealso::
3218
3219 :attr:`.ExceptionContext.engine`
3220
3221
3222 """
3223
3224 engine: Optional[Engine]
3225 """The :class:`_engine.Engine` in use during the exception.
3226
3227 This member is present in all cases except for when handling an error
3228 within the connection pool "pre-ping" process.
3229
3230 """
3231
3232 cursor: Optional[DBAPICursor]
3233 """The DBAPI cursor object.
3234
3235 May be None.
3236
3237 """
3238
3239 statement: Optional[str]
3240 """String SQL statement that was emitted directly to the DBAPI.
3241
3242 May be None.
3243
3244 """
3245
3246 parameters: Optional[_DBAPIAnyExecuteParams]
3247 """Parameter collection that was emitted directly to the DBAPI.
3248
3249 May be None.
3250
3251 """
3252
3253 original_exception: BaseException
3254 """The exception object which was caught.
3255
3256 This member is always present.
3257
3258 """
3259
3260 sqlalchemy_exception: Optional[StatementError]
3261 """The :class:`sqlalchemy.exc.StatementError` which wraps the original,
3262 and will be raised if exception handling is not circumvented by the event.
3263
3264 May be None, as not all exception types are wrapped by SQLAlchemy.
3265 For DBAPI-level exceptions that subclass the dbapi's Error class, this
3266 field will always be present.
3267
3268 """
3269
3270 chained_exception: Optional[BaseException]
3271 """The exception that was returned by the previous handler in the
3272 exception chain, if any.
3273
3274 If present, this exception will be the one ultimately raised by
3275 SQLAlchemy unless a subsequent handler replaces it.
3276
3277 May be None.
3278
3279 """
3280
3281 execution_context: Optional[ExecutionContext]
3282 """The :class:`.ExecutionContext` corresponding to the execution
3283 operation in progress.
3284
3285 This is present for statement execution operations, but not for
3286 operations such as transaction begin/end. It also is not present when
3287 the exception was raised before the :class:`.ExecutionContext`
3288 could be constructed.
3289
3290 Note that the :attr:`.ExceptionContext.statement` and
3291 :attr:`.ExceptionContext.parameters` members may represent a
3292 different value than that of the :class:`.ExecutionContext`,
3293 potentially in the case where a
3294 :meth:`_events.ConnectionEvents.before_cursor_execute` event or similar
3295 modified the statement/parameters to be sent.
3296
3297 May be None.
3298
3299 """
3300
3301 is_disconnect: bool
3302 """Represent whether the exception as occurred represents a "disconnect"
3303 condition.
3304
3305 This flag will always be True or False within the scope of the
3306 :meth:`_events.DialectEvents.handle_error` handler.
3307
3308 SQLAlchemy will defer to this flag in order to determine whether or not
3309 the connection should be invalidated subsequently. That is, by
3310 assigning to this flag, a "disconnect" event which then results in
3311 a connection and pool invalidation can be invoked or prevented by
3312 changing this flag.
3313
3314
3315 .. note:: The pool "pre_ping" handler enabled using the
3316 :paramref:`_sa.create_engine.pool_pre_ping` parameter does **not**
3317 consult this event before deciding if the "ping" returned false,
3318 as opposed to receiving an unhandled error. For this use case, the
3319 :ref:`legacy recipe based on engine_connect() may be used
3320 <pool_disconnects_pessimistic_custom>`. A future API allow more
3321 comprehensive customization of the "disconnect" detection mechanism
3322 across all functions.
3323
3324 """
3325
3326 invalidate_pool_on_disconnect: bool
3327 """Represent whether all connections in the pool should be invalidated
3328 when a "disconnect" condition is in effect.
3329
3330 Setting this flag to False within the scope of the
3331 :meth:`_events.DialectEvents.handle_error`
3332 event will have the effect such
3333 that the full collection of connections in the pool will not be
3334 invalidated during a disconnect; only the current connection that is the
3335 subject of the error will actually be invalidated.
3336
3337 The purpose of this flag is for custom disconnect-handling schemes where
3338 the invalidation of other connections in the pool is to be performed
3339 based on other conditions, or even on a per-connection basis.
3340
3341 """
3342
3343 is_pre_ping: bool
3344 """Indicates if this error is occurring within the "pre-ping" step
3345 performed when :paramref:`_sa.create_engine.pool_pre_ping` is set to
3346 ``True``. In this mode, the :attr:`.ExceptionContext.engine` attribute
3347 will be ``None``. The dialect in use is accessible via the
3348 :attr:`.ExceptionContext.dialect` attribute.
3349
3350 .. versionadded:: 2.0.5
3351
3352 """
3353
3354
3355class AdaptedConnection:
3356 """Interface of an adapted connection object to support the DBAPI protocol.
3357
3358 Used by asyncio dialects to provide a sync-style pep-249 facade on top
3359 of the asyncio connection/cursor API provided by the driver.
3360
3361 .. versionadded:: 1.4.24
3362
3363 """
3364
3365 __slots__ = ("_connection",)
3366
3367 _connection: Any
3368
3369 @property
3370 def driver_connection(self) -> Any:
3371 """The connection object as returned by the driver after a connect."""
3372 return self._connection
3373
3374 def run_async(self, fn: Callable[[Any], Awaitable[_T]]) -> _T:
3375 """Run the awaitable returned by the given function, which is passed
3376 the raw asyncio driver connection.
3377
3378 This is used to invoke awaitable-only methods on the driver connection
3379 within the context of a "synchronous" method, like a connection
3380 pool event handler.
3381
3382 E.g.::
3383
3384 engine = create_async_engine(...)
3385
3386 @event.listens_for(engine.sync_engine, "connect")
3387 def register_custom_types(dbapi_connection, ...):
3388 dbapi_connection.run_async(
3389 lambda connection: connection.set_type_codec(
3390 'MyCustomType', encoder, decoder, ...
3391 )
3392 )
3393
3394 .. versionadded:: 1.4.30
3395
3396 .. seealso::
3397
3398 :ref:`asyncio_events_run_async`
3399
3400 """
3401 return await_(fn(self._connection))
3402
3403 def __repr__(self) -> str:
3404 return "<AdaptedConnection %s>" % self._connection