interfaces.py 61 KB

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