You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1722 lines
58KB

  1. # engine/interfaces.py
  2. # Copyright (C) 2005-2021 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: http://www.opensource.org/licenses/mit-license.php
  7. """Define core interfaces used by the engine system."""
  8. from .. import util
  9. from ..sql.compiler import Compiled # noqa
  10. from ..sql.compiler import TypeCompiler # noqa
  11. class Dialect(object):
  12. """Define the behavior of a specific database and DB-API combination.
  13. Any aspect of metadata definition, SQL query generation,
  14. execution, result-set handling, or anything else which varies
  15. between databases is defined under the general category of the
  16. Dialect. The Dialect acts as a factory for other
  17. database-specific object implementations including
  18. ExecutionContext, Compiled, DefaultGenerator, and TypeEngine.
  19. .. note:: Third party dialects should not subclass :class:`.Dialect`
  20. directly. Instead, subclass :class:`.default.DefaultDialect` or
  21. descendant class.
  22. All dialects include the following attributes. There are many other
  23. attributes that may be supported as well:
  24. ``name``
  25. identifying name for the dialect from a DBAPI-neutral point of view
  26. (i.e. 'sqlite')
  27. ``driver``
  28. identifying name for the dialect's DBAPI
  29. ``positional``
  30. True if the paramstyle for this Dialect is positional.
  31. ``paramstyle``
  32. the paramstyle to be used (some DB-APIs support multiple
  33. paramstyles).
  34. ``encoding``
  35. type of encoding to use for unicode, usually defaults to
  36. 'utf-8'.
  37. ``statement_compiler``
  38. a :class:`.Compiled` class used to compile SQL statements
  39. ``ddl_compiler``
  40. a :class:`.Compiled` class used to compile DDL statements
  41. ``server_version_info``
  42. a tuple containing a version number for the DB backend in use.
  43. This value is only available for supporting dialects, and is
  44. typically populated during the initial connection to the database.
  45. ``default_schema_name``
  46. the name of the default schema. This value is only available for
  47. supporting dialects, and is typically populated during the
  48. initial connection to the database.
  49. ``execution_ctx_cls``
  50. a :class:`.ExecutionContext` class used to handle statement execution
  51. ``execute_sequence_format``
  52. either the 'tuple' or 'list' type, depending on what cursor.execute()
  53. accepts for the second argument (they vary).
  54. ``preparer``
  55. a :class:`~sqlalchemy.sql.compiler.IdentifierPreparer` class used to
  56. quote identifiers.
  57. ``supports_alter``
  58. ``True`` if the database supports ``ALTER TABLE`` - used only for
  59. generating foreign key constraints in certain circumstances
  60. ``max_identifier_length``
  61. The maximum length of identifier names.
  62. ``supports_sane_rowcount``
  63. Indicate whether the dialect properly implements rowcount for
  64. ``UPDATE`` and ``DELETE`` statements.
  65. ``supports_sane_multi_rowcount``
  66. Indicate whether the dialect properly implements rowcount for
  67. ``UPDATE`` and ``DELETE`` statements when executed via
  68. executemany.
  69. ``preexecute_autoincrement_sequences``
  70. True if 'implicit' primary key functions must be executed separately
  71. in order to get their value. This is currently oriented towards
  72. PostgreSQL.
  73. ``implicit_returning``
  74. use RETURNING or equivalent during INSERT execution in order to load
  75. newly generated primary keys and other column defaults in one execution,
  76. which are then available via inserted_primary_key.
  77. If an insert statement has returning() specified explicitly,
  78. the "implicit" functionality is not used and inserted_primary_key
  79. will not be available.
  80. ``colspecs``
  81. A dictionary of TypeEngine classes from sqlalchemy.types mapped
  82. to subclasses that are specific to the dialect class. This
  83. dictionary is class-level only and is not accessed from the
  84. dialect instance itself.
  85. ``supports_default_values``
  86. Indicates if the construct ``INSERT INTO tablename DEFAULT
  87. VALUES`` is supported
  88. ``supports_sequences``
  89. Indicates if the dialect supports CREATE SEQUENCE or similar.
  90. ``sequences_optional``
  91. If True, indicates if the "optional" flag on the Sequence() construct
  92. should signal to not generate a CREATE SEQUENCE. Applies only to
  93. dialects that support sequences. Currently used only to allow PostgreSQL
  94. SERIAL to be used on a column that specifies Sequence() for usage on
  95. other backends.
  96. ``supports_native_enum``
  97. Indicates if the dialect supports a native ENUM construct.
  98. This will prevent types.Enum from generating a CHECK
  99. constraint when that type is used.
  100. ``supports_native_boolean``
  101. Indicates if the dialect supports a native boolean construct.
  102. This will prevent types.Boolean from generating a CHECK
  103. constraint when that type is used.
  104. ``dbapi_exception_translation_map``
  105. A dictionary of names that will contain as values the names of
  106. pep-249 exceptions ("IntegrityError", "OperationalError", etc)
  107. keyed to alternate class names, to support the case where a
  108. DBAPI has exception classes that aren't named as they are
  109. referred to (e.g. IntegrityError = MyException). In the vast
  110. majority of cases this dictionary is empty.
  111. .. versionadded:: 1.0.5
  112. """
  113. _has_events = False
  114. supports_statement_cache = True
  115. """indicates if this dialect supports caching.
  116. All dialects that are compatible with statement caching should set this
  117. flag to True directly on each dialect class and subclass that supports
  118. it. SQLAlchemy tests that this flag is locally present on each dialect
  119. subclass before it will use statement caching. This is to provide
  120. safety for legacy or new dialects that are not yet fully tested to be
  121. compliant with SQL statement caching.
  122. .. versionadded:: 1.4.5
  123. .. seealso::
  124. :ref:`engine_thirdparty_caching`
  125. """
  126. def create_connect_args(self, url):
  127. """Build DB-API compatible connection arguments.
  128. Given a :class:`.URL` object, returns a tuple
  129. consisting of a ``(*args, **kwargs)`` suitable to send directly
  130. to the dbapi's connect function. The arguments are sent to the
  131. :meth:`.Dialect.connect` method which then runs the DBAPI-level
  132. ``connect()`` function.
  133. The method typically makes use of the
  134. :meth:`.URL.translate_connect_args`
  135. method in order to generate a dictionary of options.
  136. The default implementation is::
  137. def create_connect_args(self, url):
  138. opts = url.translate_connect_args()
  139. opts.update(url.query)
  140. return [[], opts]
  141. :param url: a :class:`.URL` object
  142. :return: a tuple of ``(*args, **kwargs)`` which will be passed to the
  143. :meth:`.Dialect.connect` method.
  144. .. seealso::
  145. :meth:`.URL.translate_connect_args`
  146. """
  147. raise NotImplementedError()
  148. @classmethod
  149. def type_descriptor(cls, typeobj):
  150. """Transform a generic type to a dialect-specific type.
  151. Dialect classes will usually use the
  152. :func:`_types.adapt_type` function in the types module to
  153. accomplish this.
  154. The returned result is cached *per dialect class* so can
  155. contain no dialect-instance state.
  156. """
  157. raise NotImplementedError()
  158. def initialize(self, connection):
  159. """Called during strategized creation of the dialect with a
  160. connection.
  161. Allows dialects to configure options based on server version info or
  162. other properties.
  163. The connection passed here is a SQLAlchemy Connection object,
  164. with full capabilities.
  165. The initialize() method of the base dialect should be called via
  166. super().
  167. .. note:: as of SQLAlchemy 1.4, this method is called **before**
  168. any :meth:`_engine.Dialect.on_connect` hooks are called.
  169. """
  170. pass
  171. def get_columns(self, connection, table_name, schema=None, **kw):
  172. """Return information about columns in `table_name`.
  173. Given a :class:`_engine.Connection`, a string
  174. `table_name`, and an optional string `schema`, return column
  175. information as a list of dictionaries with these keys:
  176. name
  177. the column's name
  178. type
  179. [sqlalchemy.types#TypeEngine]
  180. nullable
  181. boolean
  182. default
  183. the column's default value
  184. autoincrement
  185. boolean
  186. sequence
  187. a dictionary of the form
  188. {'name' : str, 'start' :int, 'increment': int, 'minvalue': int,
  189. 'maxvalue': int, 'nominvalue': bool, 'nomaxvalue': bool,
  190. 'cycle': bool, 'cache': int, 'order': bool}
  191. Additional column attributes may be present.
  192. """
  193. raise NotImplementedError()
  194. def get_pk_constraint(self, connection, table_name, schema=None, **kw):
  195. """Return information about the primary key constraint on
  196. table_name`.
  197. Given a :class:`_engine.Connection`, a string
  198. `table_name`, and an optional string `schema`, return primary
  199. key information as a dictionary with these keys:
  200. constrained_columns
  201. a list of column names that make up the primary key
  202. name
  203. optional name of the primary key constraint.
  204. """
  205. raise NotImplementedError()
  206. def get_foreign_keys(self, connection, table_name, schema=None, **kw):
  207. """Return information about foreign_keys in `table_name`.
  208. Given a :class:`_engine.Connection`, a string
  209. `table_name`, and an optional string `schema`, return foreign
  210. key information as a list of dicts with these keys:
  211. name
  212. the constraint's name
  213. constrained_columns
  214. a list of column names that make up the foreign key
  215. referred_schema
  216. the name of the referred schema
  217. referred_table
  218. the name of the referred table
  219. referred_columns
  220. a list of column names in the referred table that correspond to
  221. constrained_columns
  222. """
  223. raise NotImplementedError()
  224. def get_table_names(self, connection, schema=None, **kw):
  225. """Return a list of table names for `schema`."""
  226. raise NotImplementedError()
  227. def get_temp_table_names(self, connection, schema=None, **kw):
  228. """Return a list of temporary table names on the given connection,
  229. if supported by the underlying backend.
  230. """
  231. raise NotImplementedError()
  232. def get_view_names(self, connection, schema=None, **kw):
  233. """Return a list of all view names available in the database.
  234. :param schema: schema name to query, if not the default schema.
  235. """
  236. raise NotImplementedError()
  237. def get_sequence_names(self, connection, schema=None, **kw):
  238. """Return a list of all sequence names available in the database.
  239. :param schema: schema name to query, if not the default schema.
  240. .. versionadded:: 1.4
  241. """
  242. raise NotImplementedError()
  243. def get_temp_view_names(self, connection, schema=None, **kw):
  244. """Return a list of temporary view names on the given connection,
  245. if supported by the underlying backend.
  246. """
  247. raise NotImplementedError()
  248. def get_view_definition(self, connection, view_name, schema=None, **kw):
  249. """Return view definition.
  250. Given a :class:`_engine.Connection`, a string
  251. `view_name`, and an optional string `schema`, return the view
  252. definition.
  253. """
  254. raise NotImplementedError()
  255. def get_indexes(self, connection, table_name, schema=None, **kw):
  256. """Return information about indexes in `table_name`.
  257. Given a :class:`_engine.Connection`, a string
  258. `table_name` and an optional string `schema`, return index
  259. information as a list of dictionaries with these keys:
  260. name
  261. the index's name
  262. column_names
  263. list of column names in order
  264. unique
  265. boolean
  266. """
  267. raise NotImplementedError()
  268. def get_unique_constraints(
  269. self, connection, table_name, schema=None, **kw
  270. ):
  271. r"""Return information about unique constraints in `table_name`.
  272. Given a string `table_name` and an optional string `schema`, return
  273. unique constraint information as a list of dicts with these keys:
  274. name
  275. the unique constraint's name
  276. column_names
  277. list of column names in order
  278. \**kw
  279. other options passed to the dialect's get_unique_constraints()
  280. method.
  281. .. versionadded:: 0.9.0
  282. """
  283. raise NotImplementedError()
  284. def get_check_constraints(self, connection, table_name, schema=None, **kw):
  285. r"""Return information about check constraints in `table_name`.
  286. Given a string `table_name` and an optional string `schema`, return
  287. check constraint information as a list of dicts with these keys:
  288. * ``name`` -
  289. the check constraint's name
  290. * ``sqltext`` -
  291. the check constraint's SQL expression
  292. * ``**kw`` -
  293. other options passed to the dialect's get_check_constraints()
  294. method.
  295. .. versionadded:: 1.1.0
  296. """
  297. raise NotImplementedError()
  298. def get_table_comment(self, connection, table_name, schema=None, **kw):
  299. r"""Return the "comment" for the table identified by `table_name`.
  300. Given a string `table_name` and an optional string `schema`, return
  301. table comment information as a dictionary with this key:
  302. text
  303. text of the comment
  304. Raises ``NotImplementedError`` for dialects that don't support
  305. comments.
  306. .. versionadded:: 1.2
  307. """
  308. raise NotImplementedError()
  309. def normalize_name(self, name):
  310. """convert the given name to lowercase if it is detected as
  311. case insensitive.
  312. This method is only used if the dialect defines
  313. requires_name_normalize=True.
  314. """
  315. raise NotImplementedError()
  316. def denormalize_name(self, name):
  317. """convert the given name to a case insensitive identifier
  318. for the backend if it is an all-lowercase name.
  319. This method is only used if the dialect defines
  320. requires_name_normalize=True.
  321. """
  322. raise NotImplementedError()
  323. def has_table(self, connection, table_name, schema=None, **kw):
  324. """For internal dialect use, check the existence of a particular table
  325. in the database.
  326. Given a :class:`_engine.Connection` object, a string table_name and
  327. optional schema name, return True if the given table exists in the
  328. database, False otherwise.
  329. This method serves as the underlying implementation of the
  330. public facing :meth:`.Inspector.has_table` method, and is also used
  331. internally to implement the "checkfirst" behavior for methods like
  332. :meth:`_schema.Table.create` and :meth:`_schema.MetaData.create_all`.
  333. .. note:: This method is used internally by SQLAlchemy, and is
  334. published so that third-party dialects may provide an
  335. implementation. It is **not** the public API for checking for table
  336. presence. Please use the :meth:`.Inspector.has_table` method.
  337. Alternatively, for legacy cross-compatibility, the
  338. :meth:`_engine.Engine.has_table` method may be used.
  339. """
  340. raise NotImplementedError()
  341. def has_index(self, connection, table_name, index_name, schema=None):
  342. """Check the existence of a particular index name in the database.
  343. Given a :class:`_engine.Connection` object, a string
  344. `table_name` and string index name, return True if an index of the
  345. given name on the given table exists, false otherwise.
  346. The :class:`.DefaultDialect` implements this in terms of the
  347. :meth:`.Dialect.has_table` and :meth:`.Dialect.get_indexes` methods,
  348. however dialects can implement a more performant version.
  349. .. versionadded:: 1.4
  350. """
  351. raise NotImplementedError()
  352. def has_sequence(self, connection, sequence_name, schema=None, **kw):
  353. """Check the existence of a particular sequence in the database.
  354. Given a :class:`_engine.Connection` object and a string
  355. `sequence_name`, return True if the given sequence exists in
  356. the database, False otherwise.
  357. """
  358. raise NotImplementedError()
  359. def _get_server_version_info(self, connection):
  360. """Retrieve the server version info from the given connection.
  361. This is used by the default implementation to populate the
  362. "server_version_info" attribute and is called exactly
  363. once upon first connect.
  364. """
  365. raise NotImplementedError()
  366. def _get_default_schema_name(self, connection):
  367. """Return the string name of the currently selected schema from
  368. the given connection.
  369. This is used by the default implementation to populate the
  370. "default_schema_name" attribute and is called exactly
  371. once upon first connect.
  372. """
  373. raise NotImplementedError()
  374. def do_begin(self, dbapi_connection):
  375. """Provide an implementation of ``connection.begin()``, given a
  376. DB-API connection.
  377. The DBAPI has no dedicated "begin" method and it is expected
  378. that transactions are implicit. This hook is provided for those
  379. DBAPIs that might need additional help in this area.
  380. Note that :meth:`.Dialect.do_begin` is not called unless a
  381. :class:`.Transaction` object is in use. The
  382. :meth:`.Dialect.do_autocommit`
  383. hook is provided for DBAPIs that need some extra commands emitted
  384. after a commit in order to enter the next transaction, when the
  385. SQLAlchemy :class:`_engine.Connection`
  386. is used in its default "autocommit"
  387. mode.
  388. :param dbapi_connection: a DBAPI connection, typically
  389. proxied within a :class:`.ConnectionFairy`.
  390. """
  391. raise NotImplementedError()
  392. def do_rollback(self, dbapi_connection):
  393. """Provide an implementation of ``connection.rollback()``, given
  394. a DB-API connection.
  395. :param dbapi_connection: a DBAPI connection, typically
  396. proxied within a :class:`.ConnectionFairy`.
  397. """
  398. raise NotImplementedError()
  399. def do_commit(self, dbapi_connection):
  400. """Provide an implementation of ``connection.commit()``, given a
  401. DB-API connection.
  402. :param dbapi_connection: a DBAPI connection, typically
  403. proxied within a :class:`.ConnectionFairy`.
  404. """
  405. raise NotImplementedError()
  406. def do_close(self, dbapi_connection):
  407. """Provide an implementation of ``connection.close()``, given a DBAPI
  408. connection.
  409. This hook is called by the :class:`_pool.Pool`
  410. when a connection has been
  411. detached from the pool, or is being returned beyond the normal
  412. capacity of the pool.
  413. """
  414. raise NotImplementedError()
  415. def do_set_input_sizes(self, cursor, list_of_tuples, context):
  416. """invoke the cursor.setinputsizes() method with appropriate arguments
  417. This hook is called if the dialect.use_inputsizes flag is set to True.
  418. Parameter data is passed in a list of tuples (paramname, dbtype,
  419. sqltype), where ``paramname`` is the key of the parameter in the
  420. statement, ``dbtype`` is the DBAPI datatype and ``sqltype`` is the
  421. SQLAlchemy type. The order of tuples is in the correct parameter order.
  422. .. versionadded:: 1.4
  423. """
  424. raise NotImplementedError()
  425. def create_xid(self):
  426. """Create a two-phase transaction ID.
  427. This id will be passed to do_begin_twophase(),
  428. do_rollback_twophase(), do_commit_twophase(). Its format is
  429. unspecified.
  430. """
  431. raise NotImplementedError()
  432. def do_savepoint(self, connection, name):
  433. """Create a savepoint with the given name.
  434. :param connection: a :class:`_engine.Connection`.
  435. :param name: savepoint name.
  436. """
  437. raise NotImplementedError()
  438. def do_rollback_to_savepoint(self, connection, name):
  439. """Rollback a connection to the named savepoint.
  440. :param connection: a :class:`_engine.Connection`.
  441. :param name: savepoint name.
  442. """
  443. raise NotImplementedError()
  444. def do_release_savepoint(self, connection, name):
  445. """Release the named savepoint on a connection.
  446. :param connection: a :class:`_engine.Connection`.
  447. :param name: savepoint name.
  448. """
  449. raise NotImplementedError()
  450. def do_begin_twophase(self, connection, xid):
  451. """Begin a two phase transaction on the given connection.
  452. :param connection: a :class:`_engine.Connection`.
  453. :param xid: xid
  454. """
  455. raise NotImplementedError()
  456. def do_prepare_twophase(self, connection, xid):
  457. """Prepare a two phase transaction on the given connection.
  458. :param connection: a :class:`_engine.Connection`.
  459. :param xid: xid
  460. """
  461. raise NotImplementedError()
  462. def do_rollback_twophase(
  463. self, connection, xid, is_prepared=True, recover=False
  464. ):
  465. """Rollback a two phase transaction on the given connection.
  466. :param connection: a :class:`_engine.Connection`.
  467. :param xid: xid
  468. :param is_prepared: whether or not
  469. :meth:`.TwoPhaseTransaction.prepare` was called.
  470. :param recover: if the recover flag was passed.
  471. """
  472. raise NotImplementedError()
  473. def do_commit_twophase(
  474. self, connection, xid, is_prepared=True, recover=False
  475. ):
  476. """Commit a two phase transaction on the given connection.
  477. :param connection: a :class:`_engine.Connection`.
  478. :param xid: xid
  479. :param is_prepared: whether or not
  480. :meth:`.TwoPhaseTransaction.prepare` was called.
  481. :param recover: if the recover flag was passed.
  482. """
  483. raise NotImplementedError()
  484. def do_recover_twophase(self, connection):
  485. """Recover list of uncommitted prepared two phase transaction
  486. identifiers on the given connection.
  487. :param connection: a :class:`_engine.Connection`.
  488. """
  489. raise NotImplementedError()
  490. def do_executemany(self, cursor, statement, parameters, context=None):
  491. """Provide an implementation of ``cursor.executemany(statement,
  492. parameters)``."""
  493. raise NotImplementedError()
  494. def do_execute(self, cursor, statement, parameters, context=None):
  495. """Provide an implementation of ``cursor.execute(statement,
  496. parameters)``."""
  497. raise NotImplementedError()
  498. def do_execute_no_params(
  499. self, cursor, statement, parameters, context=None
  500. ):
  501. """Provide an implementation of ``cursor.execute(statement)``.
  502. The parameter collection should not be sent.
  503. """
  504. raise NotImplementedError()
  505. def is_disconnect(self, e, connection, cursor):
  506. """Return True if the given DB-API error indicates an invalid
  507. connection"""
  508. raise NotImplementedError()
  509. def connect(self, *cargs, **cparams):
  510. r"""Establish a connection using this dialect's DBAPI.
  511. The default implementation of this method is::
  512. def connect(self, *cargs, **cparams):
  513. return self.dbapi.connect(*cargs, **cparams)
  514. The ``*cargs, **cparams`` parameters are generated directly
  515. from this dialect's :meth:`.Dialect.create_connect_args` method.
  516. This method may be used for dialects that need to perform programmatic
  517. per-connection steps when a new connection is procured from the
  518. DBAPI.
  519. :param \*cargs: positional parameters returned from the
  520. :meth:`.Dialect.create_connect_args` method
  521. :param \*\*cparams: keyword parameters returned from the
  522. :meth:`.Dialect.create_connect_args` method.
  523. :return: a DBAPI connection, typically from the :pep:`249` module
  524. level ``.connect()`` function.
  525. .. seealso::
  526. :meth:`.Dialect.create_connect_args`
  527. :meth:`.Dialect.on_connect`
  528. """
  529. def on_connect_url(self, url):
  530. """return a callable which sets up a newly created DBAPI connection.
  531. This method is a new hook that supersedes the
  532. :meth:`_engine.Dialect.on_connect` method when implemented by a
  533. dialect. When not implemented by a dialect, it invokes the
  534. :meth:`_engine.Dialect.on_connect` method directly to maintain
  535. compatibility with existing dialects. There is no deprecation
  536. for :meth:`_engine.Dialect.on_connect` expected.
  537. The callable should accept a single argument "conn" which is the
  538. DBAPI connection itself. The inner callable has no
  539. return value.
  540. E.g.::
  541. class MyDialect(default.DefaultDialect):
  542. # ...
  543. def on_connect_url(self, url):
  544. def do_on_connect(connection):
  545. connection.execute("SET SPECIAL FLAGS etc")
  546. return do_on_connect
  547. This is used to set dialect-wide per-connection options such as
  548. isolation modes, Unicode modes, etc.
  549. This method differs from :meth:`_engine.Dialect.on_connect` in that
  550. it is passed the :class:`_engine.URL` object that's relevant to the
  551. connect args. Normally the only way to get this is from the
  552. :meth:`_engine.Dialect.on_connect` hook is to look on the
  553. :class:`_engine.Engine` itself, however this URL object may have been
  554. replaced by plugins.
  555. .. note::
  556. The default implementation of
  557. :meth:`_engine.Dialect.on_connect_url` is to invoke the
  558. :meth:`_engine.Dialect.on_connect` method. Therefore if a dialect
  559. implements this method, the :meth:`_engine.Dialect.on_connect`
  560. method **will not be called** unless the overriding dialect calls
  561. it directly from here.
  562. .. versionadded:: 1.4.3 added :meth:`_engine.Dialect.on_connect_url`
  563. which normally calls into :meth:`_engine.Dialect.on_connect`.
  564. :param url: a :class:`_engine.URL` object representing the
  565. :class:`_engine.URL` that was passed to the
  566. :meth:`_engine.Dialect.create_connect_args` method.
  567. :return: a callable that accepts a single DBAPI connection as an
  568. argument, or None.
  569. .. seealso::
  570. :meth:`_engine.Dialect.on_connect`
  571. """
  572. return self.on_connect()
  573. def on_connect(self):
  574. """return a callable which sets up a newly created DBAPI connection.
  575. The callable should accept a single argument "conn" which is the
  576. DBAPI connection itself. The inner callable has no
  577. return value.
  578. E.g.::
  579. class MyDialect(default.DefaultDialect):
  580. # ...
  581. def on_connect(self):
  582. def do_on_connect(connection):
  583. connection.execute("SET SPECIAL FLAGS etc")
  584. return do_on_connect
  585. This is used to set dialect-wide per-connection options such as
  586. isolation modes, Unicode modes, etc.
  587. The "do_on_connect" callable is invoked by using the
  588. :meth:`_events.PoolEvents.connect` event
  589. hook, then unwrapping the DBAPI connection and passing it into the
  590. callable.
  591. .. versionchanged:: 1.4 the on_connect hook is no longer called twice
  592. for the first connection of a dialect. The on_connect hook is still
  593. called before the :meth:`_engine.Dialect.initialize` method however.
  594. .. versionchanged:: 1.4.3 the on_connect hook is invoked from a new
  595. method on_connect_url that passes the URL that was used to create
  596. the connect args. Dialects can implement on_connect_url instead
  597. of on_connect if they need the URL object that was used for the
  598. connection in order to get additional context.
  599. If None is returned, no event listener is generated.
  600. :return: a callable that accepts a single DBAPI connection as an
  601. argument, or None.
  602. .. seealso::
  603. :meth:`.Dialect.connect` - allows the DBAPI ``connect()`` sequence
  604. itself to be controlled.
  605. :meth:`.Dialect.on_connect_url` - supersedes
  606. :meth:`.Dialect.on_connect` to also receive the
  607. :class:`_engine.URL` object in context.
  608. """
  609. return None
  610. def reset_isolation_level(self, dbapi_conn):
  611. """Given a DBAPI connection, revert its isolation to the default.
  612. Note that this is a dialect-level method which is used as part
  613. of the implementation of the :class:`_engine.Connection` and
  614. :class:`_engine.Engine`
  615. isolation level facilities; these APIs should be preferred for
  616. most typical use cases.
  617. .. seealso::
  618. :meth:`_engine.Connection.get_isolation_level`
  619. - view current level
  620. :attr:`_engine.Connection.default_isolation_level`
  621. - view default level
  622. :paramref:`.Connection.execution_options.isolation_level` -
  623. set per :class:`_engine.Connection` isolation level
  624. :paramref:`_sa.create_engine.isolation_level` -
  625. set per :class:`_engine.Engine` isolation level
  626. """
  627. raise NotImplementedError()
  628. def set_isolation_level(self, dbapi_conn, level):
  629. """Given a DBAPI connection, set its isolation level.
  630. Note that this is a dialect-level method which is used as part
  631. of the implementation of the :class:`_engine.Connection` and
  632. :class:`_engine.Engine`
  633. isolation level facilities; these APIs should be preferred for
  634. most typical use cases.
  635. .. seealso::
  636. :meth:`_engine.Connection.get_isolation_level`
  637. - view current level
  638. :attr:`_engine.Connection.default_isolation_level`
  639. - view default level
  640. :paramref:`.Connection.execution_options.isolation_level` -
  641. set per :class:`_engine.Connection` isolation level
  642. :paramref:`_sa.create_engine.isolation_level` -
  643. set per :class:`_engine.Engine` isolation level
  644. """
  645. raise NotImplementedError()
  646. def get_isolation_level(self, dbapi_conn):
  647. """Given a DBAPI connection, return its isolation level.
  648. When working with a :class:`_engine.Connection` object,
  649. the corresponding
  650. DBAPI connection may be procured using the
  651. :attr:`_engine.Connection.connection` accessor.
  652. Note that this is a dialect-level method which is used as part
  653. of the implementation of the :class:`_engine.Connection` and
  654. :class:`_engine.Engine` isolation level facilities;
  655. these APIs should be preferred for most typical use cases.
  656. .. seealso::
  657. :meth:`_engine.Connection.get_isolation_level`
  658. - view current level
  659. :attr:`_engine.Connection.default_isolation_level`
  660. - view default level
  661. :paramref:`.Connection.execution_options.isolation_level` -
  662. set per :class:`_engine.Connection` isolation level
  663. :paramref:`_sa.create_engine.isolation_level` -
  664. set per :class:`_engine.Engine` isolation level
  665. """
  666. raise NotImplementedError()
  667. def get_default_isolation_level(self, dbapi_conn):
  668. """Given a DBAPI connection, return its isolation level, or
  669. a default isolation level if one cannot be retrieved.
  670. This method may only raise NotImplementedError and
  671. **must not raise any other exception**, as it is used implicitly upon
  672. first connect.
  673. The method **must return a value** for a dialect that supports
  674. isolation level settings, as this level is what will be reverted
  675. towards when a per-connection isolation level change is made.
  676. The method defaults to using the :meth:`.Dialect.get_isolation_level`
  677. method unless overridden by a dialect.
  678. .. versionadded:: 1.3.22
  679. """
  680. raise NotImplementedError()
  681. @classmethod
  682. def get_dialect_cls(cls, url):
  683. """Given a URL, return the :class:`.Dialect` that will be used.
  684. This is a hook that allows an external plugin to provide functionality
  685. around an existing dialect, by allowing the plugin to be loaded
  686. from the url based on an entrypoint, and then the plugin returns
  687. the actual dialect to be used.
  688. By default this just returns the cls.
  689. .. versionadded:: 1.0.3
  690. """
  691. return cls
  692. @classmethod
  693. def load_provisioning(cls):
  694. """set up the provision.py module for this dialect.
  695. For dialects that include a provision.py module that sets up
  696. provisioning followers, this method should initiate that process.
  697. A typical implementation would be::
  698. @classmethod
  699. def load_provisioning(cls):
  700. __import__("mydialect.provision")
  701. The default method assumes a module named ``provision.py`` inside
  702. the owning package of the current dialect, based on the ``__module__``
  703. attribute::
  704. @classmethod
  705. def load_provisioning(cls):
  706. package = ".".join(cls.__module__.split(".")[0:-1])
  707. try:
  708. __import__(package + ".provision")
  709. except ImportError:
  710. pass
  711. .. versionadded:: 1.3.14
  712. """
  713. @classmethod
  714. def engine_created(cls, engine):
  715. """A convenience hook called before returning the final
  716. :class:`_engine.Engine`.
  717. If the dialect returned a different class from the
  718. :meth:`.get_dialect_cls`
  719. method, then the hook is called on both classes, first on
  720. the dialect class returned by the :meth:`.get_dialect_cls` method and
  721. then on the class on which the method was called.
  722. The hook should be used by dialects and/or wrappers to apply special
  723. events to the engine or its components. In particular, it allows
  724. a dialect-wrapping class to apply dialect-level events.
  725. .. versionadded:: 1.0.3
  726. """
  727. pass
  728. class CreateEnginePlugin(object):
  729. """A set of hooks intended to augment the construction of an
  730. :class:`_engine.Engine` object based on entrypoint names in a URL.
  731. The purpose of :class:`_engine.CreateEnginePlugin` is to allow third-party
  732. systems to apply engine, pool and dialect level event listeners without
  733. the need for the target application to be modified; instead, the plugin
  734. names can be added to the database URL. Target applications for
  735. :class:`_engine.CreateEnginePlugin` include:
  736. * connection and SQL performance tools, e.g. which use events to track
  737. number of checkouts and/or time spent with statements
  738. * connectivity plugins such as proxies
  739. A rudimentary :class:`_engine.CreateEnginePlugin` that attaches a logger
  740. to an :class:`_engine.Engine` object might look like::
  741. import logging
  742. from sqlalchemy.engine import CreateEnginePlugin
  743. from sqlalchemy import event
  744. class LogCursorEventsPlugin(CreateEnginePlugin):
  745. def __init__(self, url, kwargs):
  746. # consume the parameter "log_cursor_logging_name" from the
  747. # URL query
  748. logging_name = url.query.get("log_cursor_logging_name", "log_cursor")
  749. self.log = logging.getLogger(logging_name)
  750. def update_url(self, url):
  751. "update the URL to one that no longer includes our parameters"
  752. return url.difference_update_query(["log_cursor_logging_name"])
  753. def engine_created(self, engine):
  754. "attach an event listener after the new Engine is constructed"
  755. event.listen(engine, "before_cursor_execute", self._log_event)
  756. def _log_event(
  757. self,
  758. conn,
  759. cursor,
  760. statement,
  761. parameters,
  762. context,
  763. executemany):
  764. self.log.info("Plugin logged cursor event: %s", statement)
  765. Plugins are registered using entry points in a similar way as that
  766. of dialects::
  767. entry_points={
  768. 'sqlalchemy.plugins': [
  769. 'log_cursor_plugin = myapp.plugins:LogCursorEventsPlugin'
  770. ]
  771. A plugin that uses the above names would be invoked from a database
  772. URL as in::
  773. from sqlalchemy import create_engine
  774. engine = create_engine(
  775. "mysql+pymysql://scott:tiger@localhost/test?"
  776. "plugin=log_cursor_plugin&log_cursor_logging_name=mylogger"
  777. )
  778. The ``plugin`` URL parameter supports multiple instances, so that a URL
  779. may specify multiple plugins; they are loaded in the order stated
  780. in the URL::
  781. engine = create_engine(
  782. "mysql+pymysql://scott:tiger@localhost/test?"
  783. "plugin=plugin_one&plugin=plugin_twp&plugin=plugin_three")
  784. The plugin names may also be passed directly to :func:`_sa.create_engine`
  785. using the :paramref:`_sa.create_engine.plugins` argument::
  786. engine = create_engine(
  787. "mysql+pymysql://scott:tiger@localhost/test",
  788. plugins=["myplugin"])
  789. .. versionadded:: 1.2.3 plugin names can also be specified
  790. to :func:`_sa.create_engine` as a list
  791. A plugin may consume plugin-specific arguments from the
  792. :class:`_engine.URL` object as well as the ``kwargs`` dictionary, which is
  793. the dictionary of arguments passed to the :func:`_sa.create_engine`
  794. call. "Consuming" these arguments includes that they must be removed
  795. when the plugin initializes, so that the arguments are not passed along
  796. to the :class:`_engine.Dialect` constructor, where they will raise an
  797. :class:`_exc.ArgumentError` because they are not known by the dialect.
  798. As of version 1.4 of SQLAlchemy, arguments should continue to be consumed
  799. from the ``kwargs`` dictionary directly, by removing the values with a
  800. method such as ``dict.pop``. Arguments from the :class:`_engine.URL` object
  801. should be consumed by implementing the
  802. :meth:`_engine.CreateEnginePlugin.update_url` method, returning a new copy
  803. of the :class:`_engine.URL` with plugin-specific parameters removed::
  804. class MyPlugin(CreateEnginePlugin):
  805. def __init__(self, url, kwargs):
  806. self.my_argument_one = url.query['my_argument_one']
  807. self.my_argument_two = url.query['my_argument_two']
  808. self.my_argument_three = kwargs.pop('my_argument_three', None)
  809. def update_url(self, url):
  810. return url.difference_update_query(
  811. ["my_argument_one", "my_argument_two"]
  812. )
  813. Arguments like those illustrated above would be consumed from a
  814. :func:`_sa.create_engine` call such as::
  815. from sqlalchemy import create_engine
  816. engine = create_engine(
  817. "mysql+pymysql://scott:tiger@localhost/test?"
  818. "plugin=myplugin&my_argument_one=foo&my_argument_two=bar",
  819. my_argument_three='bat'
  820. )
  821. .. versionchanged:: 1.4
  822. The :class:`_engine.URL` object is now immutable; a
  823. :class:`_engine.CreateEnginePlugin` that needs to alter the
  824. :class:`_engine.URL` should implement the newly added
  825. :meth:`_engine.CreateEnginePlugin.update_url` method, which
  826. is invoked after the plugin is constructed.
  827. For migration, construct the plugin in the following way, checking
  828. for the existence of the :meth:`_engine.CreateEnginePlugin.update_url`
  829. method to detect which version is running::
  830. class MyPlugin(CreateEnginePlugin):
  831. def __init__(self, url, kwargs):
  832. if hasattr(CreateEnginePlugin, "update_url"):
  833. # detect the 1.4 API
  834. self.my_argument_one = url.query['my_argument_one']
  835. self.my_argument_two = url.query['my_argument_two']
  836. else:
  837. # detect the 1.3 and earlier API - mutate the
  838. # URL directly
  839. self.my_argument_one = url.query.pop('my_argument_one')
  840. self.my_argument_two = url.query.pop('my_argument_two')
  841. self.my_argument_three = kwargs.pop('my_argument_three', None)
  842. def update_url(self, url):
  843. # this method is only called in the 1.4 version
  844. return url.difference_update_query(
  845. ["my_argument_one", "my_argument_two"]
  846. )
  847. .. seealso::
  848. :ref:`change_5526` - overview of the :class:`_engine.URL` change which
  849. also includes notes regarding :class:`_engine.CreateEnginePlugin`.
  850. When the engine creation process completes and produces the
  851. :class:`_engine.Engine` object, it is again passed to the plugin via the
  852. :meth:`_engine.CreateEnginePlugin.engine_created` hook. In this hook, additional
  853. changes can be made to the engine, most typically involving setup of
  854. events (e.g. those defined in :ref:`core_event_toplevel`).
  855. .. versionadded:: 1.1
  856. """ # noqa: E501
  857. def __init__(self, url, kwargs):
  858. """Construct a new :class:`.CreateEnginePlugin`.
  859. The plugin object is instantiated individually for each call
  860. to :func:`_sa.create_engine`. A single :class:`_engine.
  861. Engine` will be
  862. passed to the :meth:`.CreateEnginePlugin.engine_created` method
  863. corresponding to this URL.
  864. :param url: the :class:`_engine.URL` object. The plugin may inspect
  865. the :class:`_engine.URL` for arguments. Arguments used by the
  866. plugin should be removed, by returning an updated :class:`_engine.URL`
  867. from the :meth:`_engine.CreateEnginePlugin.update_url` method.
  868. .. versionchanged:: 1.4
  869. The :class:`_engine.URL` object is now immutable, so a
  870. :class:`_engine.CreateEnginePlugin` that needs to alter the
  871. :class:`_engine.URL` object should implement the
  872. :meth:`_engine.CreateEnginePlugin.update_url` method.
  873. :param kwargs: The keyword arguments passed to
  874. :func:`_sa.create_engine`.
  875. """
  876. self.url = url
  877. def update_url(self, url):
  878. """Update the :class:`_engine.URL`.
  879. A new :class:`_engine.URL` should be returned. This method is
  880. typically used to consume configuration arguments from the
  881. :class:`_engine.URL` which must be removed, as they will not be
  882. recognized by the dialect. The
  883. :meth:`_engine.URL.difference_update_query` method is available
  884. to remove these arguments. See the docstring at
  885. :class:`_engine.CreateEnginePlugin` for an example.
  886. .. versionadded:: 1.4
  887. """
  888. def handle_dialect_kwargs(self, dialect_cls, dialect_args):
  889. """parse and modify dialect kwargs"""
  890. def handle_pool_kwargs(self, pool_cls, pool_args):
  891. """parse and modify pool kwargs"""
  892. def engine_created(self, engine):
  893. """Receive the :class:`_engine.Engine`
  894. object when it is fully constructed.
  895. The plugin may make additional changes to the engine, such as
  896. registering engine or connection pool events.
  897. """
  898. class ExecutionContext(object):
  899. """A messenger object for a Dialect that corresponds to a single
  900. execution.
  901. ExecutionContext should have these data members:
  902. connection
  903. Connection object which can be freely used by default value
  904. generators to execute SQL. This Connection should reference the
  905. same underlying connection/transactional resources of
  906. root_connection.
  907. root_connection
  908. Connection object which is the source of this ExecutionContext. This
  909. Connection may have close_with_result=True set, in which case it can
  910. only be used once.
  911. dialect
  912. dialect which created this ExecutionContext.
  913. cursor
  914. DB-API cursor procured from the connection,
  915. compiled
  916. if passed to constructor, sqlalchemy.engine.base.Compiled object
  917. being executed,
  918. statement
  919. string version of the statement to be executed. Is either
  920. passed to the constructor, or must be created from the
  921. sql.Compiled object by the time pre_exec() has completed.
  922. parameters
  923. bind parameters passed to the execute() method. For compiled
  924. statements, this is a dictionary or list of dictionaries. For
  925. textual statements, it should be in a format suitable for the
  926. dialect's paramstyle (i.e. dict or list of dicts for non
  927. positional, list or list of lists/tuples for positional).
  928. isinsert
  929. True if the statement is an INSERT.
  930. isupdate
  931. True if the statement is an UPDATE.
  932. should_autocommit
  933. True if the statement is a "committable" statement.
  934. prefetch_cols
  935. a list of Column objects for which a client-side default
  936. was fired off. Applies to inserts and updates.
  937. postfetch_cols
  938. a list of Column objects for which a server-side default or
  939. inline SQL expression value was fired off. Applies to inserts
  940. and updates.
  941. """
  942. def create_cursor(self):
  943. """Return a new cursor generated from this ExecutionContext's
  944. connection.
  945. Some dialects may wish to change the behavior of
  946. connection.cursor(), such as postgresql which may return a PG
  947. "server side" cursor.
  948. """
  949. raise NotImplementedError()
  950. def pre_exec(self):
  951. """Called before an execution of a compiled statement.
  952. If a compiled statement was passed to this ExecutionContext,
  953. the `statement` and `parameters` datamembers must be
  954. initialized after this statement is complete.
  955. """
  956. raise NotImplementedError()
  957. def get_out_parameter_values(self, out_param_names):
  958. """Return a sequence of OUT parameter values from a cursor.
  959. For dialects that support OUT parameters, this method will be called
  960. when there is a :class:`.SQLCompiler` object which has the
  961. :attr:`.SQLCompiler.has_out_parameters` flag set. This flag in turn
  962. will be set to True if the statement itself has :class:`.BindParameter`
  963. objects that have the ``.isoutparam`` flag set which are consumed by
  964. the :meth:`.SQLCompiler.visit_bindparam` method. If the dialect
  965. compiler produces :class:`.BindParameter` objects with ``.isoutparam``
  966. set which are not handled by :meth:`.SQLCompiler.visit_bindparam`, it
  967. should set this flag explicitly.
  968. The list of names that were rendered for each bound parameter
  969. is passed to the method. The method should then return a sequence of
  970. values corresponding to the list of parameter objects. Unlike in
  971. previous SQLAlchemy versions, the values can be the **raw values** from
  972. the DBAPI; the execution context will apply the appropriate type
  973. handler based on what's present in self.compiled.binds and update the
  974. values. The processed dictionary will then be made available via the
  975. ``.out_parameters`` collection on the result object. Note that
  976. SQLAlchemy 1.4 has multiple kinds of result object as part of the 2.0
  977. transition.
  978. .. versionadded:: 1.4 - added
  979. :meth:`.ExecutionContext.get_out_parameter_values`, which is invoked
  980. automatically by the :class:`.DefaultExecutionContext` when there
  981. are :class:`.BindParameter` objects with the ``.isoutparam`` flag
  982. set. This replaces the practice of setting out parameters within
  983. the now-removed ``get_result_proxy()`` method.
  984. .. seealso::
  985. :meth:`.ExecutionContext.get_result_cursor_strategy`
  986. """
  987. raise NotImplementedError()
  988. def post_exec(self):
  989. """Called after the execution of a compiled statement.
  990. If a compiled statement was passed to this ExecutionContext,
  991. the `last_insert_ids`, `last_inserted_params`, etc.
  992. datamembers should be available after this method completes.
  993. """
  994. raise NotImplementedError()
  995. def get_result_cursor_strategy(self, result):
  996. """Return a result cursor strategy for a given result object.
  997. This method is implemented by the :class:`.DefaultDialect` and is
  998. only needed by implementing dialects in the case where some special
  999. steps regarding the cursor must be taken, such as manufacturing
  1000. fake results from some other element of the cursor, or pre-buffering
  1001. the cursor's results.
  1002. A simplified version of the default implementation is::
  1003. from sqlalchemy.engine.result import DefaultCursorFetchStrategy
  1004. class MyExecutionContext(DefaultExecutionContext):
  1005. def get_result_cursor_strategy(self, result):
  1006. return DefaultCursorFetchStrategy.create(result)
  1007. Above, the :class:`.DefaultCursorFetchStrategy` will be applied
  1008. to the result object. For results that are pre-buffered from a
  1009. cursor that might be closed, an implementation might be::
  1010. from sqlalchemy.engine.result import (
  1011. FullyBufferedCursorFetchStrategy
  1012. )
  1013. class MyExecutionContext(DefaultExecutionContext):
  1014. _pre_buffered_result = None
  1015. def pre_exec(self):
  1016. if self.special_condition_prebuffer_cursor():
  1017. self._pre_buffered_result = (
  1018. self.cursor.description,
  1019. self.cursor.fetchall()
  1020. )
  1021. def get_result_cursor_strategy(self, result):
  1022. if self._pre_buffered_result:
  1023. description, cursor_buffer = self._pre_buffered_result
  1024. return (
  1025. FullyBufferedCursorFetchStrategy.
  1026. create_from_buffer(
  1027. result, description, cursor_buffer
  1028. )
  1029. )
  1030. else:
  1031. return DefaultCursorFetchStrategy.create(result)
  1032. This method replaces the previous not-quite-documented
  1033. ``get_result_proxy()`` method.
  1034. .. versionadded:: 1.4 - result objects now interpret cursor results
  1035. based on a pluggable "strategy" object, which is delivered
  1036. by the :class:`.ExecutionContext` via the
  1037. :meth:`.ExecutionContext.get_result_cursor_strategy` method.
  1038. .. seealso::
  1039. :meth:`.ExecutionContext.get_out_parameter_values`
  1040. """
  1041. raise NotImplementedError()
  1042. def handle_dbapi_exception(self, e):
  1043. """Receive a DBAPI exception which occurred upon execute, result
  1044. fetch, etc."""
  1045. raise NotImplementedError()
  1046. def should_autocommit_text(self, statement):
  1047. """Parse the given textual statement and return True if it refers to
  1048. a "committable" statement"""
  1049. raise NotImplementedError()
  1050. def lastrow_has_defaults(self):
  1051. """Return True if the last INSERT or UPDATE row contained
  1052. inlined or database-side defaults.
  1053. """
  1054. raise NotImplementedError()
  1055. def get_rowcount(self):
  1056. """Return the DBAPI ``cursor.rowcount`` value, or in some
  1057. cases an interpreted value.
  1058. See :attr:`_engine.CursorResult.rowcount` for details on this.
  1059. """
  1060. raise NotImplementedError()
  1061. @util.deprecated_20_cls(
  1062. ":class:`.Connectable`",
  1063. alternative=(
  1064. "The :class:`_engine.Engine` will be the only Core "
  1065. "object that features a .connect() method, and the "
  1066. ":class:`_engine.Connection` will be the only object that features "
  1067. "an .execute() method."
  1068. ),
  1069. constructor=None,
  1070. )
  1071. class Connectable(object):
  1072. """Interface for an object which supports execution of SQL constructs.
  1073. The two implementations of :class:`.Connectable` are
  1074. :class:`_engine.Connection` and :class:`_engine.Engine`.
  1075. Connectable must also implement the 'dialect' member which references a
  1076. :class:`.Dialect` instance.
  1077. """
  1078. def connect(self, **kwargs):
  1079. """Return a :class:`_engine.Connection` object.
  1080. Depending on context, this may be ``self`` if this object
  1081. is already an instance of :class:`_engine.Connection`, or a newly
  1082. procured :class:`_engine.Connection` if this object is an instance
  1083. of :class:`_engine.Engine`.
  1084. """
  1085. engine = None
  1086. """The :class:`_engine.Engine` instance referred to by this
  1087. :class:`.Connectable`.
  1088. May be ``self`` if this is already an :class:`_engine.Engine`.
  1089. """
  1090. def execute(self, object_, *multiparams, **params):
  1091. """Executes the given construct and returns a
  1092. :class:`_engine.CursorResult`.
  1093. """
  1094. raise NotImplementedError()
  1095. def scalar(self, object_, *multiparams, **params):
  1096. """Executes and returns the first column of the first row.
  1097. The underlying cursor is closed after execution.
  1098. """
  1099. raise NotImplementedError()
  1100. def _run_visitor(self, visitorcallable, element, **kwargs):
  1101. raise NotImplementedError()
  1102. def _execute_clauseelement(self, elem, multiparams=None, params=None):
  1103. raise NotImplementedError()
  1104. class ExceptionContext(object):
  1105. """Encapsulate information about an error condition in progress.
  1106. This object exists solely to be passed to the
  1107. :meth:`_events.ConnectionEvents.handle_error` event,
  1108. supporting an interface that
  1109. can be extended without backwards-incompatibility.
  1110. .. versionadded:: 0.9.7
  1111. """
  1112. connection = None
  1113. """The :class:`_engine.Connection` in use during the exception.
  1114. This member is present, except in the case of a failure when
  1115. first connecting.
  1116. .. seealso::
  1117. :attr:`.ExceptionContext.engine`
  1118. """
  1119. engine = None
  1120. """The :class:`_engine.Engine` in use during the exception.
  1121. This member should always be present, even in the case of a failure
  1122. when first connecting.
  1123. .. versionadded:: 1.0.0
  1124. """
  1125. cursor = None
  1126. """The DBAPI cursor object.
  1127. May be None.
  1128. """
  1129. statement = None
  1130. """String SQL statement that was emitted directly to the DBAPI.
  1131. May be None.
  1132. """
  1133. parameters = None
  1134. """Parameter collection that was emitted directly to the DBAPI.
  1135. May be None.
  1136. """
  1137. original_exception = None
  1138. """The exception object which was caught.
  1139. This member is always present.
  1140. """
  1141. sqlalchemy_exception = None
  1142. """The :class:`sqlalchemy.exc.StatementError` which wraps the original,
  1143. and will be raised if exception handling is not circumvented by the event.
  1144. May be None, as not all exception types are wrapped by SQLAlchemy.
  1145. For DBAPI-level exceptions that subclass the dbapi's Error class, this
  1146. field will always be present.
  1147. """
  1148. chained_exception = None
  1149. """The exception that was returned by the previous handler in the
  1150. exception chain, if any.
  1151. If present, this exception will be the one ultimately raised by
  1152. SQLAlchemy unless a subsequent handler replaces it.
  1153. May be None.
  1154. """
  1155. execution_context = None
  1156. """The :class:`.ExecutionContext` corresponding to the execution
  1157. operation in progress.
  1158. This is present for statement execution operations, but not for
  1159. operations such as transaction begin/end. It also is not present when
  1160. the exception was raised before the :class:`.ExecutionContext`
  1161. could be constructed.
  1162. Note that the :attr:`.ExceptionContext.statement` and
  1163. :attr:`.ExceptionContext.parameters` members may represent a
  1164. different value than that of the :class:`.ExecutionContext`,
  1165. potentially in the case where a
  1166. :meth:`_events.ConnectionEvents.before_cursor_execute` event or similar
  1167. modified the statement/parameters to be sent.
  1168. May be None.
  1169. """
  1170. is_disconnect = None
  1171. """Represent whether the exception as occurred represents a "disconnect"
  1172. condition.
  1173. This flag will always be True or False within the scope of the
  1174. :meth:`_events.ConnectionEvents.handle_error` handler.
  1175. SQLAlchemy will defer to this flag in order to determine whether or not
  1176. the connection should be invalidated subsequently. That is, by
  1177. assigning to this flag, a "disconnect" event which then results in
  1178. a connection and pool invalidation can be invoked or prevented by
  1179. changing this flag.
  1180. .. note:: The pool "pre_ping" handler enabled using the
  1181. :paramref:`_sa.create_engine.pool_pre_ping` parameter does **not**
  1182. consult this event before deciding if the "ping" returned false,
  1183. as opposed to receiving an unhandled error. For this use case, the
  1184. :ref:`legacy recipe based on engine_connect() may be used
  1185. <pool_disconnects_pessimistic_custom>`. A future API allow more
  1186. comprehensive customization of the "disconnect" detection mechanism
  1187. across all functions.
  1188. """
  1189. invalidate_pool_on_disconnect = True
  1190. """Represent whether all connections in the pool should be invalidated
  1191. when a "disconnect" condition is in effect.
  1192. Setting this flag to False within the scope of the
  1193. :meth:`_events.ConnectionEvents.handle_error`
  1194. event will have the effect such
  1195. that the full collection of connections in the pool will not be
  1196. invalidated during a disconnect; only the current connection that is the
  1197. subject of the error will actually be invalidated.
  1198. The purpose of this flag is for custom disconnect-handling schemes where
  1199. the invalidation of other connections in the pool is to be performed
  1200. based on other conditions, or even on a per-connection basis.
  1201. .. versionadded:: 1.0.3
  1202. """