SQLAlchemy 2.0.36__cp313-cp313-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (273) hide show
  1. SQLAlchemy-2.0.36.dist-info/LICENSE +19 -0
  2. SQLAlchemy-2.0.36.dist-info/METADATA +243 -0
  3. SQLAlchemy-2.0.36.dist-info/RECORD +273 -0
  4. SQLAlchemy-2.0.36.dist-info/WHEEL +5 -0
  5. SQLAlchemy-2.0.36.dist-info/top_level.txt +1 -0
  6. sqlalchemy/__init__.py +294 -0
  7. sqlalchemy/connectors/__init__.py +18 -0
  8. sqlalchemy/connectors/aioodbc.py +174 -0
  9. sqlalchemy/connectors/asyncio.py +213 -0
  10. sqlalchemy/connectors/pyodbc.py +249 -0
  11. sqlalchemy/cyextension/__init__.py +6 -0
  12. sqlalchemy/cyextension/collections.cp313-win_amd64.pyd +0 -0
  13. sqlalchemy/cyextension/collections.pyx +409 -0
  14. sqlalchemy/cyextension/immutabledict.cp313-win_amd64.pyd +0 -0
  15. sqlalchemy/cyextension/immutabledict.pxd +8 -0
  16. sqlalchemy/cyextension/immutabledict.pyx +133 -0
  17. sqlalchemy/cyextension/processors.cp313-win_amd64.pyd +0 -0
  18. sqlalchemy/cyextension/processors.pyx +68 -0
  19. sqlalchemy/cyextension/resultproxy.cp313-win_amd64.pyd +0 -0
  20. sqlalchemy/cyextension/resultproxy.pyx +102 -0
  21. sqlalchemy/cyextension/util.cp313-win_amd64.pyd +0 -0
  22. sqlalchemy/cyextension/util.pyx +91 -0
  23. sqlalchemy/dialects/__init__.py +61 -0
  24. sqlalchemy/dialects/_typing.py +25 -0
  25. sqlalchemy/dialects/mssql/__init__.py +88 -0
  26. sqlalchemy/dialects/mssql/aioodbc.py +64 -0
  27. sqlalchemy/dialects/mssql/base.py +4010 -0
  28. sqlalchemy/dialects/mssql/information_schema.py +254 -0
  29. sqlalchemy/dialects/mssql/json.py +133 -0
  30. sqlalchemy/dialects/mssql/provision.py +162 -0
  31. sqlalchemy/dialects/mssql/pymssql.py +126 -0
  32. sqlalchemy/dialects/mssql/pyodbc.py +745 -0
  33. sqlalchemy/dialects/mysql/__init__.py +101 -0
  34. sqlalchemy/dialects/mysql/aiomysql.py +333 -0
  35. sqlalchemy/dialects/mysql/asyncmy.py +337 -0
  36. sqlalchemy/dialects/mysql/base.py +3494 -0
  37. sqlalchemy/dialects/mysql/cymysql.py +84 -0
  38. sqlalchemy/dialects/mysql/dml.py +219 -0
  39. sqlalchemy/dialects/mysql/enumerated.py +244 -0
  40. sqlalchemy/dialects/mysql/expression.py +141 -0
  41. sqlalchemy/dialects/mysql/json.py +81 -0
  42. sqlalchemy/dialects/mysql/mariadb.py +32 -0
  43. sqlalchemy/dialects/mysql/mariadbconnector.py +277 -0
  44. sqlalchemy/dialects/mysql/mysqlconnector.py +180 -0
  45. sqlalchemy/dialects/mysql/mysqldb.py +303 -0
  46. sqlalchemy/dialects/mysql/provision.py +110 -0
  47. sqlalchemy/dialects/mysql/pymysql.py +137 -0
  48. sqlalchemy/dialects/mysql/pyodbc.py +138 -0
  49. sqlalchemy/dialects/mysql/reflection.py +677 -0
  50. sqlalchemy/dialects/mysql/reserved_words.py +571 -0
  51. sqlalchemy/dialects/mysql/types.py +774 -0
  52. sqlalchemy/dialects/oracle/__init__.py +67 -0
  53. sqlalchemy/dialects/oracle/base.py +3271 -0
  54. sqlalchemy/dialects/oracle/cx_oracle.py +1483 -0
  55. sqlalchemy/dialects/oracle/dictionary.py +507 -0
  56. sqlalchemy/dialects/oracle/oracledb.py +431 -0
  57. sqlalchemy/dialects/oracle/provision.py +220 -0
  58. sqlalchemy/dialects/oracle/types.py +287 -0
  59. sqlalchemy/dialects/postgresql/__init__.py +167 -0
  60. sqlalchemy/dialects/postgresql/_psycopg_common.py +187 -0
  61. sqlalchemy/dialects/postgresql/array.py +425 -0
  62. sqlalchemy/dialects/postgresql/asyncpg.py +1274 -0
  63. sqlalchemy/dialects/postgresql/base.py +5008 -0
  64. sqlalchemy/dialects/postgresql/dml.py +310 -0
  65. sqlalchemy/dialects/postgresql/ext.py +496 -0
  66. sqlalchemy/dialects/postgresql/hstore.py +397 -0
  67. sqlalchemy/dialects/postgresql/json.py +333 -0
  68. sqlalchemy/dialects/postgresql/named_types.py +509 -0
  69. sqlalchemy/dialects/postgresql/operators.py +129 -0
  70. sqlalchemy/dialects/postgresql/pg8000.py +662 -0
  71. sqlalchemy/dialects/postgresql/pg_catalog.py +300 -0
  72. sqlalchemy/dialects/postgresql/provision.py +175 -0
  73. sqlalchemy/dialects/postgresql/psycopg.py +772 -0
  74. sqlalchemy/dialects/postgresql/psycopg2.py +886 -0
  75. sqlalchemy/dialects/postgresql/psycopg2cffi.py +61 -0
  76. sqlalchemy/dialects/postgresql/ranges.py +1029 -0
  77. sqlalchemy/dialects/postgresql/types.py +303 -0
  78. sqlalchemy/dialects/sqlite/__init__.py +57 -0
  79. sqlalchemy/dialects/sqlite/aiosqlite.py +396 -0
  80. sqlalchemy/dialects/sqlite/base.py +2805 -0
  81. sqlalchemy/dialects/sqlite/dml.py +240 -0
  82. sqlalchemy/dialects/sqlite/json.py +92 -0
  83. sqlalchemy/dialects/sqlite/provision.py +198 -0
  84. sqlalchemy/dialects/sqlite/pysqlcipher.py +155 -0
  85. sqlalchemy/dialects/sqlite/pysqlite.py +756 -0
  86. sqlalchemy/dialects/type_migration_guidelines.txt +145 -0
  87. sqlalchemy/engine/__init__.py +62 -0
  88. sqlalchemy/engine/_py_processors.py +136 -0
  89. sqlalchemy/engine/_py_row.py +128 -0
  90. sqlalchemy/engine/_py_util.py +74 -0
  91. sqlalchemy/engine/base.py +3375 -0
  92. sqlalchemy/engine/characteristics.py +155 -0
  93. sqlalchemy/engine/create.py +875 -0
  94. sqlalchemy/engine/cursor.py +2181 -0
  95. sqlalchemy/engine/default.py +2365 -0
  96. sqlalchemy/engine/events.py +951 -0
  97. sqlalchemy/engine/interfaces.py +3403 -0
  98. sqlalchemy/engine/mock.py +131 -0
  99. sqlalchemy/engine/processors.py +61 -0
  100. sqlalchemy/engine/reflection.py +2098 -0
  101. sqlalchemy/engine/result.py +2382 -0
  102. sqlalchemy/engine/row.py +401 -0
  103. sqlalchemy/engine/strategies.py +19 -0
  104. sqlalchemy/engine/url.py +910 -0
  105. sqlalchemy/engine/util.py +167 -0
  106. sqlalchemy/event/__init__.py +25 -0
  107. sqlalchemy/event/api.py +225 -0
  108. sqlalchemy/event/attr.py +655 -0
  109. sqlalchemy/event/base.py +470 -0
  110. sqlalchemy/event/legacy.py +246 -0
  111. sqlalchemy/event/registry.py +386 -0
  112. sqlalchemy/events.py +17 -0
  113. sqlalchemy/exc.py +830 -0
  114. sqlalchemy/ext/__init__.py +11 -0
  115. sqlalchemy/ext/associationproxy.py +2013 -0
  116. sqlalchemy/ext/asyncio/__init__.py +25 -0
  117. sqlalchemy/ext/asyncio/base.py +279 -0
  118. sqlalchemy/ext/asyncio/engine.py +1466 -0
  119. sqlalchemy/ext/asyncio/exc.py +21 -0
  120. sqlalchemy/ext/asyncio/result.py +961 -0
  121. sqlalchemy/ext/asyncio/scoping.py +1614 -0
  122. sqlalchemy/ext/asyncio/session.py +1936 -0
  123. sqlalchemy/ext/automap.py +1691 -0
  124. sqlalchemy/ext/baked.py +574 -0
  125. sqlalchemy/ext/compiler.py +570 -0
  126. sqlalchemy/ext/declarative/__init__.py +65 -0
  127. sqlalchemy/ext/declarative/extensions.py +548 -0
  128. sqlalchemy/ext/horizontal_shard.py +481 -0
  129. sqlalchemy/ext/hybrid.py +1514 -0
  130. sqlalchemy/ext/indexable.py +341 -0
  131. sqlalchemy/ext/instrumentation.py +450 -0
  132. sqlalchemy/ext/mutable.py +1073 -0
  133. sqlalchemy/ext/mypy/__init__.py +6 -0
  134. sqlalchemy/ext/mypy/apply.py +320 -0
  135. sqlalchemy/ext/mypy/decl_class.py +515 -0
  136. sqlalchemy/ext/mypy/infer.py +590 -0
  137. sqlalchemy/ext/mypy/names.py +335 -0
  138. sqlalchemy/ext/mypy/plugin.py +303 -0
  139. sqlalchemy/ext/mypy/util.py +357 -0
  140. sqlalchemy/ext/orderinglist.py +416 -0
  141. sqlalchemy/ext/serializer.py +181 -0
  142. sqlalchemy/future/__init__.py +16 -0
  143. sqlalchemy/future/engine.py +15 -0
  144. sqlalchemy/inspection.py +174 -0
  145. sqlalchemy/log.py +288 -0
  146. sqlalchemy/orm/__init__.py +170 -0
  147. sqlalchemy/orm/_orm_constructors.py +2571 -0
  148. sqlalchemy/orm/_typing.py +179 -0
  149. sqlalchemy/orm/attributes.py +2835 -0
  150. sqlalchemy/orm/base.py +973 -0
  151. sqlalchemy/orm/bulk_persistence.py +2123 -0
  152. sqlalchemy/orm/clsregistry.py +571 -0
  153. sqlalchemy/orm/collections.py +1620 -0
  154. sqlalchemy/orm/context.py +3268 -0
  155. sqlalchemy/orm/decl_api.py +1883 -0
  156. sqlalchemy/orm/decl_base.py +2190 -0
  157. sqlalchemy/orm/dependency.py +1304 -0
  158. sqlalchemy/orm/descriptor_props.py +1076 -0
  159. sqlalchemy/orm/dynamic.py +300 -0
  160. sqlalchemy/orm/evaluator.py +379 -0
  161. sqlalchemy/orm/events.py +3261 -0
  162. sqlalchemy/orm/exc.py +228 -0
  163. sqlalchemy/orm/identity.py +302 -0
  164. sqlalchemy/orm/instrumentation.py +754 -0
  165. sqlalchemy/orm/interfaces.py +1474 -0
  166. sqlalchemy/orm/loading.py +1682 -0
  167. sqlalchemy/orm/mapped_collection.py +557 -0
  168. sqlalchemy/orm/mapper.py +4432 -0
  169. sqlalchemy/orm/path_registry.py +811 -0
  170. sqlalchemy/orm/persistence.py +1782 -0
  171. sqlalchemy/orm/properties.py +886 -0
  172. sqlalchemy/orm/query.py +3396 -0
  173. sqlalchemy/orm/relationships.py +3500 -0
  174. sqlalchemy/orm/scoping.py +2165 -0
  175. sqlalchemy/orm/session.py +5301 -0
  176. sqlalchemy/orm/state.py +1143 -0
  177. sqlalchemy/orm/state_changes.py +198 -0
  178. sqlalchemy/orm/strategies.py +3473 -0
  179. sqlalchemy/orm/strategy_options.py +2569 -0
  180. sqlalchemy/orm/sync.py +164 -0
  181. sqlalchemy/orm/unitofwork.py +796 -0
  182. sqlalchemy/orm/util.py +2424 -0
  183. sqlalchemy/orm/writeonly.py +678 -0
  184. sqlalchemy/pool/__init__.py +44 -0
  185. sqlalchemy/pool/base.py +1515 -0
  186. sqlalchemy/pool/events.py +370 -0
  187. sqlalchemy/pool/impl.py +581 -0
  188. sqlalchemy/py.typed +0 -0
  189. sqlalchemy/schema.py +70 -0
  190. sqlalchemy/sql/__init__.py +145 -0
  191. sqlalchemy/sql/_dml_constructors.py +140 -0
  192. sqlalchemy/sql/_elements_constructors.py +1850 -0
  193. sqlalchemy/sql/_orm_types.py +20 -0
  194. sqlalchemy/sql/_py_util.py +75 -0
  195. sqlalchemy/sql/_selectable_constructors.py +635 -0
  196. sqlalchemy/sql/_typing.py +460 -0
  197. sqlalchemy/sql/annotation.py +585 -0
  198. sqlalchemy/sql/base.py +2185 -0
  199. sqlalchemy/sql/cache_key.py +1057 -0
  200. sqlalchemy/sql/coercions.py +1405 -0
  201. sqlalchemy/sql/compiler.py +7818 -0
  202. sqlalchemy/sql/crud.py +1669 -0
  203. sqlalchemy/sql/ddl.py +1378 -0
  204. sqlalchemy/sql/default_comparator.py +552 -0
  205. sqlalchemy/sql/dml.py +1817 -0
  206. sqlalchemy/sql/elements.py +5499 -0
  207. sqlalchemy/sql/events.py +455 -0
  208. sqlalchemy/sql/expression.py +162 -0
  209. sqlalchemy/sql/functions.py +2055 -0
  210. sqlalchemy/sql/lambdas.py +1449 -0
  211. sqlalchemy/sql/naming.py +212 -0
  212. sqlalchemy/sql/operators.py +2579 -0
  213. sqlalchemy/sql/roles.py +323 -0
  214. sqlalchemy/sql/schema.py +6158 -0
  215. sqlalchemy/sql/selectable.py +7004 -0
  216. sqlalchemy/sql/sqltypes.py +3827 -0
  217. sqlalchemy/sql/traversals.py +1024 -0
  218. sqlalchemy/sql/type_api.py +2339 -0
  219. sqlalchemy/sql/util.py +1486 -0
  220. sqlalchemy/sql/visitors.py +1165 -0
  221. sqlalchemy/testing/__init__.py +96 -0
  222. sqlalchemy/testing/assertions.py +989 -0
  223. sqlalchemy/testing/assertsql.py +516 -0
  224. sqlalchemy/testing/asyncio.py +135 -0
  225. sqlalchemy/testing/config.py +427 -0
  226. sqlalchemy/testing/engines.py +472 -0
  227. sqlalchemy/testing/entities.py +117 -0
  228. sqlalchemy/testing/exclusions.py +435 -0
  229. sqlalchemy/testing/fixtures/__init__.py +28 -0
  230. sqlalchemy/testing/fixtures/base.py +366 -0
  231. sqlalchemy/testing/fixtures/mypy.py +312 -0
  232. sqlalchemy/testing/fixtures/orm.py +227 -0
  233. sqlalchemy/testing/fixtures/sql.py +503 -0
  234. sqlalchemy/testing/pickleable.py +155 -0
  235. sqlalchemy/testing/plugin/__init__.py +6 -0
  236. sqlalchemy/testing/plugin/bootstrap.py +51 -0
  237. sqlalchemy/testing/plugin/plugin_base.py +779 -0
  238. sqlalchemy/testing/plugin/pytestplugin.py +868 -0
  239. sqlalchemy/testing/profiling.py +324 -0
  240. sqlalchemy/testing/provision.py +496 -0
  241. sqlalchemy/testing/requirements.py +1818 -0
  242. sqlalchemy/testing/schema.py +224 -0
  243. sqlalchemy/testing/suite/__init__.py +19 -0
  244. sqlalchemy/testing/suite/test_cte.py +211 -0
  245. sqlalchemy/testing/suite/test_ddl.py +389 -0
  246. sqlalchemy/testing/suite/test_deprecations.py +153 -0
  247. sqlalchemy/testing/suite/test_dialect.py +740 -0
  248. sqlalchemy/testing/suite/test_insert.py +630 -0
  249. sqlalchemy/testing/suite/test_reflection.py +3225 -0
  250. sqlalchemy/testing/suite/test_results.py +502 -0
  251. sqlalchemy/testing/suite/test_rowcount.py +258 -0
  252. sqlalchemy/testing/suite/test_select.py +1999 -0
  253. sqlalchemy/testing/suite/test_sequence.py +317 -0
  254. sqlalchemy/testing/suite/test_types.py +2141 -0
  255. sqlalchemy/testing/suite/test_unicode_ddl.py +189 -0
  256. sqlalchemy/testing/suite/test_update_delete.py +139 -0
  257. sqlalchemy/testing/util.py +537 -0
  258. sqlalchemy/testing/warnings.py +52 -0
  259. sqlalchemy/types.py +76 -0
  260. sqlalchemy/util/__init__.py +160 -0
  261. sqlalchemy/util/_collections.py +715 -0
  262. sqlalchemy/util/_concurrency_py3k.py +288 -0
  263. sqlalchemy/util/_has_cy.py +40 -0
  264. sqlalchemy/util/_py_collections.py +541 -0
  265. sqlalchemy/util/compat.py +301 -0
  266. sqlalchemy/util/concurrency.py +108 -0
  267. sqlalchemy/util/deprecations.py +401 -0
  268. sqlalchemy/util/langhelpers.py +2218 -0
  269. sqlalchemy/util/preloaded.py +150 -0
  270. sqlalchemy/util/queue.py +322 -0
  271. sqlalchemy/util/tool_support.py +201 -0
  272. sqlalchemy/util/topological.py +120 -0
  273. sqlalchemy/util/typing.py +629 -0
@@ -0,0 +1,951 @@
1
+ # engine/events.py
2
+ # Copyright (C) 2005-2024 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+
8
+
9
+ from __future__ import annotations
10
+
11
+ import typing
12
+ from typing import Any
13
+ from typing import Dict
14
+ from typing import Optional
15
+ from typing import Tuple
16
+ from typing import Type
17
+ from typing import Union
18
+
19
+ from .base import Connection
20
+ from .base import Engine
21
+ from .interfaces import ConnectionEventsTarget
22
+ from .interfaces import DBAPIConnection
23
+ from .interfaces import DBAPICursor
24
+ from .interfaces import Dialect
25
+ from .. import event
26
+ from .. import exc
27
+ from ..util.typing import Literal
28
+
29
+ if typing.TYPE_CHECKING:
30
+ from .interfaces import _CoreMultiExecuteParams
31
+ from .interfaces import _CoreSingleExecuteParams
32
+ from .interfaces import _DBAPIAnyExecuteParams
33
+ from .interfaces import _DBAPIMultiExecuteParams
34
+ from .interfaces import _DBAPISingleExecuteParams
35
+ from .interfaces import _ExecuteOptions
36
+ from .interfaces import ExceptionContext
37
+ from .interfaces import ExecutionContext
38
+ from .result import Result
39
+ from ..pool import ConnectionPoolEntry
40
+ from ..sql import Executable
41
+ from ..sql.elements import BindParameter
42
+
43
+
44
+ class ConnectionEvents(event.Events[ConnectionEventsTarget]):
45
+ """Available events for
46
+ :class:`_engine.Connection` and :class:`_engine.Engine`.
47
+
48
+ The methods here define the name of an event as well as the names of
49
+ members that are passed to listener functions.
50
+
51
+ An event listener can be associated with any
52
+ :class:`_engine.Connection` or :class:`_engine.Engine`
53
+ class or instance, such as an :class:`_engine.Engine`, e.g.::
54
+
55
+ from sqlalchemy import event, create_engine
56
+
57
+ def before_cursor_execute(conn, cursor, statement, parameters, context,
58
+ executemany):
59
+ log.info("Received statement: %s", statement)
60
+
61
+ engine = create_engine('postgresql+psycopg2://scott:tiger@localhost/test')
62
+ event.listen(engine, "before_cursor_execute", before_cursor_execute)
63
+
64
+ or with a specific :class:`_engine.Connection`::
65
+
66
+ with engine.begin() as conn:
67
+ @event.listens_for(conn, 'before_cursor_execute')
68
+ def before_cursor_execute(conn, cursor, statement, parameters,
69
+ context, executemany):
70
+ log.info("Received statement: %s", statement)
71
+
72
+ When the methods are called with a `statement` parameter, such as in
73
+ :meth:`.after_cursor_execute` or :meth:`.before_cursor_execute`,
74
+ the statement is the exact SQL string that was prepared for transmission
75
+ to the DBAPI ``cursor`` in the connection's :class:`.Dialect`.
76
+
77
+ The :meth:`.before_execute` and :meth:`.before_cursor_execute`
78
+ events can also be established with the ``retval=True`` flag, which
79
+ allows modification of the statement and parameters to be sent
80
+ to the database. The :meth:`.before_cursor_execute` event is
81
+ particularly useful here to add ad-hoc string transformations, such
82
+ as comments, to all executions::
83
+
84
+ from sqlalchemy.engine import Engine
85
+ from sqlalchemy import event
86
+
87
+ @event.listens_for(Engine, "before_cursor_execute", retval=True)
88
+ def comment_sql_calls(conn, cursor, statement, parameters,
89
+ context, executemany):
90
+ statement = statement + " -- some comment"
91
+ return statement, parameters
92
+
93
+ .. note:: :class:`_events.ConnectionEvents` can be established on any
94
+ combination of :class:`_engine.Engine`, :class:`_engine.Connection`,
95
+ as well
96
+ as instances of each of those classes. Events across all
97
+ four scopes will fire off for a given instance of
98
+ :class:`_engine.Connection`. However, for performance reasons, the
99
+ :class:`_engine.Connection` object determines at instantiation time
100
+ whether or not its parent :class:`_engine.Engine` has event listeners
101
+ established. Event listeners added to the :class:`_engine.Engine`
102
+ class or to an instance of :class:`_engine.Engine`
103
+ *after* the instantiation
104
+ of a dependent :class:`_engine.Connection` instance will usually
105
+ *not* be available on that :class:`_engine.Connection` instance.
106
+ The newly
107
+ added listeners will instead take effect for
108
+ :class:`_engine.Connection`
109
+ instances created subsequent to those event listeners being
110
+ established on the parent :class:`_engine.Engine` class or instance.
111
+
112
+ :param retval=False: Applies to the :meth:`.before_execute` and
113
+ :meth:`.before_cursor_execute` events only. When True, the
114
+ user-defined event function must have a return value, which
115
+ is a tuple of parameters that replace the given statement
116
+ and parameters. See those methods for a description of
117
+ specific return arguments.
118
+
119
+ """ # noqa
120
+
121
+ _target_class_doc = "SomeEngine"
122
+ _dispatch_target = ConnectionEventsTarget
123
+
124
+ @classmethod
125
+ def _accept_with(
126
+ cls,
127
+ target: Union[ConnectionEventsTarget, Type[ConnectionEventsTarget]],
128
+ identifier: str,
129
+ ) -> Optional[Union[ConnectionEventsTarget, Type[ConnectionEventsTarget]]]:
130
+ default_dispatch = super()._accept_with(target, identifier)
131
+ if default_dispatch is None and hasattr(
132
+ target, "_no_async_engine_events"
133
+ ):
134
+ target._no_async_engine_events()
135
+
136
+ return default_dispatch
137
+
138
+ @classmethod
139
+ def _listen(
140
+ cls,
141
+ event_key: event._EventKey[ConnectionEventsTarget],
142
+ *,
143
+ retval: bool = False,
144
+ **kw: Any,
145
+ ) -> None:
146
+ target, identifier, fn = (
147
+ event_key.dispatch_target,
148
+ event_key.identifier,
149
+ event_key._listen_fn,
150
+ )
151
+ target._has_events = True
152
+
153
+ if not retval:
154
+ if identifier == "before_execute":
155
+ orig_fn = fn
156
+
157
+ def wrap_before_execute( # type: ignore
158
+ conn, clauseelement, multiparams, params, execution_options
159
+ ):
160
+ orig_fn(
161
+ conn,
162
+ clauseelement,
163
+ multiparams,
164
+ params,
165
+ execution_options,
166
+ )
167
+ return clauseelement, multiparams, params
168
+
169
+ fn = wrap_before_execute
170
+ elif identifier == "before_cursor_execute":
171
+ orig_fn = fn
172
+
173
+ def wrap_before_cursor_execute( # type: ignore
174
+ conn, cursor, statement, parameters, context, executemany
175
+ ):
176
+ orig_fn(
177
+ conn,
178
+ cursor,
179
+ statement,
180
+ parameters,
181
+ context,
182
+ executemany,
183
+ )
184
+ return statement, parameters
185
+
186
+ fn = wrap_before_cursor_execute
187
+ elif retval and identifier not in (
188
+ "before_execute",
189
+ "before_cursor_execute",
190
+ ):
191
+ raise exc.ArgumentError(
192
+ "Only the 'before_execute', "
193
+ "'before_cursor_execute' and 'handle_error' engine "
194
+ "event listeners accept the 'retval=True' "
195
+ "argument."
196
+ )
197
+ event_key.with_wrapper(fn).base_listen()
198
+
199
+ @event._legacy_signature(
200
+ "1.4",
201
+ ["conn", "clauseelement", "multiparams", "params"],
202
+ lambda conn, clauseelement, multiparams, params, execution_options: (
203
+ conn,
204
+ clauseelement,
205
+ multiparams,
206
+ params,
207
+ ),
208
+ )
209
+ def before_execute(
210
+ self,
211
+ conn: Connection,
212
+ clauseelement: Executable,
213
+ multiparams: _CoreMultiExecuteParams,
214
+ params: _CoreSingleExecuteParams,
215
+ execution_options: _ExecuteOptions,
216
+ ) -> Optional[
217
+ Tuple[Executable, _CoreMultiExecuteParams, _CoreSingleExecuteParams]
218
+ ]:
219
+ """Intercept high level execute() events, receiving uncompiled
220
+ SQL constructs and other objects prior to rendering into SQL.
221
+
222
+ This event is good for debugging SQL compilation issues as well
223
+ as early manipulation of the parameters being sent to the database,
224
+ as the parameter lists will be in a consistent format here.
225
+
226
+ This event can be optionally established with the ``retval=True``
227
+ flag. The ``clauseelement``, ``multiparams``, and ``params``
228
+ arguments should be returned as a three-tuple in this case::
229
+
230
+ @event.listens_for(Engine, "before_execute", retval=True)
231
+ def before_execute(conn, clauseelement, multiparams, params):
232
+ # do something with clauseelement, multiparams, params
233
+ return clauseelement, multiparams, params
234
+
235
+ :param conn: :class:`_engine.Connection` object
236
+ :param clauseelement: SQL expression construct, :class:`.Compiled`
237
+ instance, or string statement passed to
238
+ :meth:`_engine.Connection.execute`.
239
+ :param multiparams: Multiple parameter sets, a list of dictionaries.
240
+ :param params: Single parameter set, a single dictionary.
241
+ :param execution_options: dictionary of execution
242
+ options passed along with the statement, if any. This is a merge
243
+ of all options that will be used, including those of the statement,
244
+ the connection, and those passed in to the method itself for
245
+ the 2.0 style of execution.
246
+
247
+ .. versionadded: 1.4
248
+
249
+ .. seealso::
250
+
251
+ :meth:`.before_cursor_execute`
252
+
253
+ """
254
+
255
+ @event._legacy_signature(
256
+ "1.4",
257
+ ["conn", "clauseelement", "multiparams", "params", "result"],
258
+ lambda conn, clauseelement, multiparams, params, execution_options, result: ( # noqa
259
+ conn,
260
+ clauseelement,
261
+ multiparams,
262
+ params,
263
+ result,
264
+ ),
265
+ )
266
+ def after_execute(
267
+ self,
268
+ conn: Connection,
269
+ clauseelement: Executable,
270
+ multiparams: _CoreMultiExecuteParams,
271
+ params: _CoreSingleExecuteParams,
272
+ execution_options: _ExecuteOptions,
273
+ result: Result[Any],
274
+ ) -> None:
275
+ """Intercept high level execute() events after execute.
276
+
277
+
278
+ :param conn: :class:`_engine.Connection` object
279
+ :param clauseelement: SQL expression construct, :class:`.Compiled`
280
+ instance, or string statement passed to
281
+ :meth:`_engine.Connection.execute`.
282
+ :param multiparams: Multiple parameter sets, a list of dictionaries.
283
+ :param params: Single parameter set, a single dictionary.
284
+ :param execution_options: dictionary of execution
285
+ options passed along with the statement, if any. This is a merge
286
+ of all options that will be used, including those of the statement,
287
+ the connection, and those passed in to the method itself for
288
+ the 2.0 style of execution.
289
+
290
+ .. versionadded: 1.4
291
+
292
+ :param result: :class:`_engine.CursorResult` generated by the
293
+ execution.
294
+
295
+ """
296
+
297
+ def before_cursor_execute(
298
+ self,
299
+ conn: Connection,
300
+ cursor: DBAPICursor,
301
+ statement: str,
302
+ parameters: _DBAPIAnyExecuteParams,
303
+ context: Optional[ExecutionContext],
304
+ executemany: bool,
305
+ ) -> Optional[Tuple[str, _DBAPIAnyExecuteParams]]:
306
+ """Intercept low-level cursor execute() events before execution,
307
+ receiving the string SQL statement and DBAPI-specific parameter list to
308
+ be invoked against a cursor.
309
+
310
+ This event is a good choice for logging as well as late modifications
311
+ to the SQL string. It's less ideal for parameter modifications except
312
+ for those which are specific to a target backend.
313
+
314
+ This event can be optionally established with the ``retval=True``
315
+ flag. The ``statement`` and ``parameters`` arguments should be
316
+ returned as a two-tuple in this case::
317
+
318
+ @event.listens_for(Engine, "before_cursor_execute", retval=True)
319
+ def before_cursor_execute(conn, cursor, statement,
320
+ parameters, context, executemany):
321
+ # do something with statement, parameters
322
+ return statement, parameters
323
+
324
+ See the example at :class:`_events.ConnectionEvents`.
325
+
326
+ :param conn: :class:`_engine.Connection` object
327
+ :param cursor: DBAPI cursor object
328
+ :param statement: string SQL statement, as to be passed to the DBAPI
329
+ :param parameters: Dictionary, tuple, or list of parameters being
330
+ passed to the ``execute()`` or ``executemany()`` method of the
331
+ DBAPI ``cursor``. In some cases may be ``None``.
332
+ :param context: :class:`.ExecutionContext` object in use. May
333
+ be ``None``.
334
+ :param executemany: boolean, if ``True``, this is an ``executemany()``
335
+ call, if ``False``, this is an ``execute()`` call.
336
+
337
+ .. seealso::
338
+
339
+ :meth:`.before_execute`
340
+
341
+ :meth:`.after_cursor_execute`
342
+
343
+ """
344
+
345
+ def after_cursor_execute(
346
+ self,
347
+ conn: Connection,
348
+ cursor: DBAPICursor,
349
+ statement: str,
350
+ parameters: _DBAPIAnyExecuteParams,
351
+ context: Optional[ExecutionContext],
352
+ executemany: bool,
353
+ ) -> None:
354
+ """Intercept low-level cursor execute() events after execution.
355
+
356
+ :param conn: :class:`_engine.Connection` object
357
+ :param cursor: DBAPI cursor object. Will have results pending
358
+ if the statement was a SELECT, but these should not be consumed
359
+ as they will be needed by the :class:`_engine.CursorResult`.
360
+ :param statement: string SQL statement, as passed to the DBAPI
361
+ :param parameters: Dictionary, tuple, or list of parameters being
362
+ passed to the ``execute()`` or ``executemany()`` method of the
363
+ DBAPI ``cursor``. In some cases may be ``None``.
364
+ :param context: :class:`.ExecutionContext` object in use. May
365
+ be ``None``.
366
+ :param executemany: boolean, if ``True``, this is an ``executemany()``
367
+ call, if ``False``, this is an ``execute()`` call.
368
+
369
+ """
370
+
371
+ @event._legacy_signature(
372
+ "2.0", ["conn", "branch"], converter=lambda conn: (conn, False)
373
+ )
374
+ def engine_connect(self, conn: Connection) -> None:
375
+ """Intercept the creation of a new :class:`_engine.Connection`.
376
+
377
+ This event is called typically as the direct result of calling
378
+ the :meth:`_engine.Engine.connect` method.
379
+
380
+ It differs from the :meth:`_events.PoolEvents.connect` method, which
381
+ refers to the actual connection to a database at the DBAPI level;
382
+ a DBAPI connection may be pooled and reused for many operations.
383
+ In contrast, this event refers only to the production of a higher level
384
+ :class:`_engine.Connection` wrapper around such a DBAPI connection.
385
+
386
+ It also differs from the :meth:`_events.PoolEvents.checkout` event
387
+ in that it is specific to the :class:`_engine.Connection` object,
388
+ not the
389
+ DBAPI connection that :meth:`_events.PoolEvents.checkout` deals with,
390
+ although
391
+ this DBAPI connection is available here via the
392
+ :attr:`_engine.Connection.connection` attribute.
393
+ But note there can in fact
394
+ be multiple :meth:`_events.PoolEvents.checkout`
395
+ events within the lifespan
396
+ of a single :class:`_engine.Connection` object, if that
397
+ :class:`_engine.Connection`
398
+ is invalidated and re-established.
399
+
400
+ :param conn: :class:`_engine.Connection` object.
401
+
402
+ .. seealso::
403
+
404
+ :meth:`_events.PoolEvents.checkout`
405
+ the lower-level pool checkout event
406
+ for an individual DBAPI connection
407
+
408
+ """
409
+
410
+ def set_connection_execution_options(
411
+ self, conn: Connection, opts: Dict[str, Any]
412
+ ) -> None:
413
+ """Intercept when the :meth:`_engine.Connection.execution_options`
414
+ method is called.
415
+
416
+ This method is called after the new :class:`_engine.Connection`
417
+ has been
418
+ produced, with the newly updated execution options collection, but
419
+ before the :class:`.Dialect` has acted upon any of those new options.
420
+
421
+ Note that this method is not called when a new
422
+ :class:`_engine.Connection`
423
+ is produced which is inheriting execution options from its parent
424
+ :class:`_engine.Engine`; to intercept this condition, use the
425
+ :meth:`_events.ConnectionEvents.engine_connect` event.
426
+
427
+ :param conn: The newly copied :class:`_engine.Connection` object
428
+
429
+ :param opts: dictionary of options that were passed to the
430
+ :meth:`_engine.Connection.execution_options` method.
431
+ This dictionary may be modified in place to affect the ultimate
432
+ options which take effect.
433
+
434
+ .. versionadded:: 2.0 the ``opts`` dictionary may be modified
435
+ in place.
436
+
437
+
438
+ .. seealso::
439
+
440
+ :meth:`_events.ConnectionEvents.set_engine_execution_options`
441
+ - event
442
+ which is called when :meth:`_engine.Engine.execution_options`
443
+ is called.
444
+
445
+
446
+ """
447
+
448
+ def set_engine_execution_options(
449
+ self, engine: Engine, opts: Dict[str, Any]
450
+ ) -> None:
451
+ """Intercept when the :meth:`_engine.Engine.execution_options`
452
+ method is called.
453
+
454
+ The :meth:`_engine.Engine.execution_options` method produces a shallow
455
+ copy of the :class:`_engine.Engine` which stores the new options.
456
+ That new
457
+ :class:`_engine.Engine` is passed here.
458
+ A particular application of this
459
+ method is to add a :meth:`_events.ConnectionEvents.engine_connect`
460
+ event
461
+ handler to the given :class:`_engine.Engine`
462
+ which will perform some per-
463
+ :class:`_engine.Connection` task specific to these execution options.
464
+
465
+ :param conn: The newly copied :class:`_engine.Engine` object
466
+
467
+ :param opts: dictionary of options that were passed to the
468
+ :meth:`_engine.Connection.execution_options` method.
469
+ This dictionary may be modified in place to affect the ultimate
470
+ options which take effect.
471
+
472
+ .. versionadded:: 2.0 the ``opts`` dictionary may be modified
473
+ in place.
474
+
475
+ .. seealso::
476
+
477
+ :meth:`_events.ConnectionEvents.set_connection_execution_options`
478
+ - event
479
+ which is called when :meth:`_engine.Connection.execution_options`
480
+ is
481
+ called.
482
+
483
+ """
484
+
485
+ def engine_disposed(self, engine: Engine) -> None:
486
+ """Intercept when the :meth:`_engine.Engine.dispose` method is called.
487
+
488
+ The :meth:`_engine.Engine.dispose` method instructs the engine to
489
+ "dispose" of it's connection pool (e.g. :class:`_pool.Pool`), and
490
+ replaces it with a new one. Disposing of the old pool has the
491
+ effect that existing checked-in connections are closed. The new
492
+ pool does not establish any new connections until it is first used.
493
+
494
+ This event can be used to indicate that resources related to the
495
+ :class:`_engine.Engine` should also be cleaned up,
496
+ keeping in mind that the
497
+ :class:`_engine.Engine`
498
+ can still be used for new requests in which case
499
+ it re-acquires connection resources.
500
+
501
+ """
502
+
503
+ def begin(self, conn: Connection) -> None:
504
+ """Intercept begin() events.
505
+
506
+ :param conn: :class:`_engine.Connection` object
507
+
508
+ """
509
+
510
+ def rollback(self, conn: Connection) -> None:
511
+ """Intercept rollback() events, as initiated by a
512
+ :class:`.Transaction`.
513
+
514
+ Note that the :class:`_pool.Pool` also "auto-rolls back"
515
+ a DBAPI connection upon checkin, if the ``reset_on_return``
516
+ flag is set to its default value of ``'rollback'``.
517
+ To intercept this
518
+ rollback, use the :meth:`_events.PoolEvents.reset` hook.
519
+
520
+ :param conn: :class:`_engine.Connection` object
521
+
522
+ .. seealso::
523
+
524
+ :meth:`_events.PoolEvents.reset`
525
+
526
+ """
527
+
528
+ def commit(self, conn: Connection) -> None:
529
+ """Intercept commit() events, as initiated by a
530
+ :class:`.Transaction`.
531
+
532
+ Note that the :class:`_pool.Pool` may also "auto-commit"
533
+ a DBAPI connection upon checkin, if the ``reset_on_return``
534
+ flag is set to the value ``'commit'``. To intercept this
535
+ commit, use the :meth:`_events.PoolEvents.reset` hook.
536
+
537
+ :param conn: :class:`_engine.Connection` object
538
+ """
539
+
540
+ def savepoint(self, conn: Connection, name: str) -> None:
541
+ """Intercept savepoint() events.
542
+
543
+ :param conn: :class:`_engine.Connection` object
544
+ :param name: specified name used for the savepoint.
545
+
546
+ """
547
+
548
+ def rollback_savepoint(
549
+ self, conn: Connection, name: str, context: None
550
+ ) -> None:
551
+ """Intercept rollback_savepoint() events.
552
+
553
+ :param conn: :class:`_engine.Connection` object
554
+ :param name: specified name used for the savepoint.
555
+ :param context: not used
556
+
557
+ """
558
+ # TODO: deprecate "context"
559
+
560
+ def release_savepoint(
561
+ self, conn: Connection, name: str, context: None
562
+ ) -> None:
563
+ """Intercept release_savepoint() events.
564
+
565
+ :param conn: :class:`_engine.Connection` object
566
+ :param name: specified name used for the savepoint.
567
+ :param context: not used
568
+
569
+ """
570
+ # TODO: deprecate "context"
571
+
572
+ def begin_twophase(self, conn: Connection, xid: Any) -> None:
573
+ """Intercept begin_twophase() events.
574
+
575
+ :param conn: :class:`_engine.Connection` object
576
+ :param xid: two-phase XID identifier
577
+
578
+ """
579
+
580
+ def prepare_twophase(self, conn: Connection, xid: Any) -> None:
581
+ """Intercept prepare_twophase() events.
582
+
583
+ :param conn: :class:`_engine.Connection` object
584
+ :param xid: two-phase XID identifier
585
+ """
586
+
587
+ def rollback_twophase(
588
+ self, conn: Connection, xid: Any, is_prepared: bool
589
+ ) -> None:
590
+ """Intercept rollback_twophase() events.
591
+
592
+ :param conn: :class:`_engine.Connection` object
593
+ :param xid: two-phase XID identifier
594
+ :param is_prepared: boolean, indicates if
595
+ :meth:`.TwoPhaseTransaction.prepare` was called.
596
+
597
+ """
598
+
599
+ def commit_twophase(
600
+ self, conn: Connection, xid: Any, is_prepared: bool
601
+ ) -> None:
602
+ """Intercept commit_twophase() events.
603
+
604
+ :param conn: :class:`_engine.Connection` object
605
+ :param xid: two-phase XID identifier
606
+ :param is_prepared: boolean, indicates if
607
+ :meth:`.TwoPhaseTransaction.prepare` was called.
608
+
609
+ """
610
+
611
+
612
+ class DialectEvents(event.Events[Dialect]):
613
+ """event interface for execution-replacement functions.
614
+
615
+ These events allow direct instrumentation and replacement
616
+ of key dialect functions which interact with the DBAPI.
617
+
618
+ .. note::
619
+
620
+ :class:`.DialectEvents` hooks should be considered **semi-public**
621
+ and experimental.
622
+ These hooks are not for general use and are only for those situations
623
+ where intricate re-statement of DBAPI mechanics must be injected onto
624
+ an existing dialect. For general-use statement-interception events,
625
+ please use the :class:`_events.ConnectionEvents` interface.
626
+
627
+ .. seealso::
628
+
629
+ :meth:`_events.ConnectionEvents.before_cursor_execute`
630
+
631
+ :meth:`_events.ConnectionEvents.before_execute`
632
+
633
+ :meth:`_events.ConnectionEvents.after_cursor_execute`
634
+
635
+ :meth:`_events.ConnectionEvents.after_execute`
636
+
637
+ """
638
+
639
+ _target_class_doc = "SomeEngine"
640
+ _dispatch_target = Dialect
641
+
642
+ @classmethod
643
+ def _listen(
644
+ cls,
645
+ event_key: event._EventKey[Dialect],
646
+ *,
647
+ retval: bool = False,
648
+ **kw: Any,
649
+ ) -> None:
650
+ target = event_key.dispatch_target
651
+
652
+ target._has_events = True
653
+ event_key.base_listen()
654
+
655
+ @classmethod
656
+ def _accept_with(
657
+ cls,
658
+ target: Union[Engine, Type[Engine], Dialect, Type[Dialect]],
659
+ identifier: str,
660
+ ) -> Optional[Union[Dialect, Type[Dialect]]]:
661
+ if isinstance(target, type):
662
+ if issubclass(target, Engine):
663
+ return Dialect
664
+ elif issubclass(target, Dialect):
665
+ return target
666
+ elif isinstance(target, Engine):
667
+ return target.dialect
668
+ elif isinstance(target, Dialect):
669
+ return target
670
+ elif isinstance(target, Connection) and identifier == "handle_error":
671
+ raise exc.InvalidRequestError(
672
+ "The handle_error() event hook as of SQLAlchemy 2.0 is "
673
+ "established on the Dialect, and may only be applied to the "
674
+ "Engine as a whole or to a specific Dialect as a whole, "
675
+ "not on a per-Connection basis."
676
+ )
677
+ elif hasattr(target, "_no_async_engine_events"):
678
+ target._no_async_engine_events()
679
+ else:
680
+ return None
681
+
682
+ def handle_error(
683
+ self, exception_context: ExceptionContext
684
+ ) -> Optional[BaseException]:
685
+ r"""Intercept all exceptions processed by the
686
+ :class:`_engine.Dialect`, typically but not limited to those
687
+ emitted within the scope of a :class:`_engine.Connection`.
688
+
689
+ .. versionchanged:: 2.0 the :meth:`.DialectEvents.handle_error` event
690
+ is moved to the :class:`.DialectEvents` class, moved from the
691
+ :class:`.ConnectionEvents` class, so that it may also participate in
692
+ the "pre ping" operation configured with the
693
+ :paramref:`_sa.create_engine.pool_pre_ping` parameter. The event
694
+ remains registered by using the :class:`_engine.Engine` as the event
695
+ target, however note that using the :class:`_engine.Connection` as
696
+ an event target for :meth:`.DialectEvents.handle_error` is no longer
697
+ supported.
698
+
699
+ This includes all exceptions emitted by the DBAPI as well as
700
+ within SQLAlchemy's statement invocation process, including
701
+ encoding errors and other statement validation errors. Other areas
702
+ in which the event is invoked include transaction begin and end,
703
+ result row fetching, cursor creation.
704
+
705
+ Note that :meth:`.handle_error` may support new kinds of exceptions
706
+ and new calling scenarios at *any time*. Code which uses this
707
+ event must expect new calling patterns to be present in minor
708
+ releases.
709
+
710
+ To support the wide variety of members that correspond to an exception,
711
+ as well as to allow extensibility of the event without backwards
712
+ incompatibility, the sole argument received is an instance of
713
+ :class:`.ExceptionContext`. This object contains data members
714
+ representing detail about the exception.
715
+
716
+ Use cases supported by this hook include:
717
+
718
+ * read-only, low-level exception handling for logging and
719
+ debugging purposes
720
+ * Establishing whether a DBAPI connection error message indicates
721
+ that the database connection needs to be reconnected, including
722
+ for the "pre_ping" handler used by **some** dialects
723
+ * Establishing or disabling whether a connection or the owning
724
+ connection pool is invalidated or expired in response to a
725
+ specific exception
726
+ * exception re-writing
727
+
728
+ The hook is called while the cursor from the failed operation
729
+ (if any) is still open and accessible. Special cleanup operations
730
+ can be called on this cursor; SQLAlchemy will attempt to close
731
+ this cursor subsequent to this hook being invoked.
732
+
733
+ As of SQLAlchemy 2.0, the "pre_ping" handler enabled using the
734
+ :paramref:`_sa.create_engine.pool_pre_ping` parameter will also
735
+ participate in the :meth:`.handle_error` process, **for those dialects
736
+ that rely upon disconnect codes to detect database liveness**. Note
737
+ that some dialects such as psycopg, psycopg2, and most MySQL dialects
738
+ make use of a native ``ping()`` method supplied by the DBAPI which does
739
+ not make use of disconnect codes.
740
+
741
+ .. versionchanged:: 2.0.0 The :meth:`.DialectEvents.handle_error`
742
+ event hook participates in connection pool "pre-ping" operations.
743
+ Within this usage, the :attr:`.ExceptionContext.engine` attribute
744
+ will be ``None``, however the :class:`.Dialect` in use is always
745
+ available via the :attr:`.ExceptionContext.dialect` attribute.
746
+
747
+ .. versionchanged:: 2.0.5 Added :attr:`.ExceptionContext.is_pre_ping`
748
+ attribute which will be set to ``True`` when the
749
+ :meth:`.DialectEvents.handle_error` event hook is triggered within
750
+ a connection pool pre-ping operation.
751
+
752
+ .. versionchanged:: 2.0.5 An issue was repaired that allows for the
753
+ PostgreSQL ``psycopg`` and ``psycopg2`` drivers, as well as all
754
+ MySQL drivers, to properly participate in the
755
+ :meth:`.DialectEvents.handle_error` event hook during
756
+ connection pool "pre-ping" operations; previously, the
757
+ implementation was non-working for these drivers.
758
+
759
+
760
+ A handler function has two options for replacing
761
+ the SQLAlchemy-constructed exception into one that is user
762
+ defined. It can either raise this new exception directly, in
763
+ which case all further event listeners are bypassed and the
764
+ exception will be raised, after appropriate cleanup as taken
765
+ place::
766
+
767
+ @event.listens_for(Engine, "handle_error")
768
+ def handle_exception(context):
769
+ if isinstance(context.original_exception,
770
+ psycopg2.OperationalError) and \
771
+ "failed" in str(context.original_exception):
772
+ raise MySpecialException("failed operation")
773
+
774
+ .. warning:: Because the
775
+ :meth:`_events.DialectEvents.handle_error`
776
+ event specifically provides for exceptions to be re-thrown as
777
+ the ultimate exception raised by the failed statement,
778
+ **stack traces will be misleading** if the user-defined event
779
+ handler itself fails and throws an unexpected exception;
780
+ the stack trace may not illustrate the actual code line that
781
+ failed! It is advised to code carefully here and use
782
+ logging and/or inline debugging if unexpected exceptions are
783
+ occurring.
784
+
785
+ Alternatively, a "chained" style of event handling can be
786
+ used, by configuring the handler with the ``retval=True``
787
+ modifier and returning the new exception instance from the
788
+ function. In this case, event handling will continue onto the
789
+ next handler. The "chained" exception is available using
790
+ :attr:`.ExceptionContext.chained_exception`::
791
+
792
+ @event.listens_for(Engine, "handle_error", retval=True)
793
+ def handle_exception(context):
794
+ if context.chained_exception is not None and \
795
+ "special" in context.chained_exception.message:
796
+ return MySpecialException("failed",
797
+ cause=context.chained_exception)
798
+
799
+ Handlers that return ``None`` may be used within the chain; when
800
+ a handler returns ``None``, the previous exception instance,
801
+ if any, is maintained as the current exception that is passed onto the
802
+ next handler.
803
+
804
+ When a custom exception is raised or returned, SQLAlchemy raises
805
+ this new exception as-is, it is not wrapped by any SQLAlchemy
806
+ object. If the exception is not a subclass of
807
+ :class:`sqlalchemy.exc.StatementError`,
808
+ certain features may not be available; currently this includes
809
+ the ORM's feature of adding a detail hint about "autoflush" to
810
+ exceptions raised within the autoflush process.
811
+
812
+ :param context: an :class:`.ExceptionContext` object. See this
813
+ class for details on all available members.
814
+
815
+
816
+ .. seealso::
817
+
818
+ :ref:`pool_new_disconnect_codes`
819
+
820
+ """
821
+
822
+ def do_connect(
823
+ self,
824
+ dialect: Dialect,
825
+ conn_rec: ConnectionPoolEntry,
826
+ cargs: Tuple[Any, ...],
827
+ cparams: Dict[str, Any],
828
+ ) -> Optional[DBAPIConnection]:
829
+ """Receive connection arguments before a connection is made.
830
+
831
+ This event is useful in that it allows the handler to manipulate the
832
+ cargs and/or cparams collections that control how the DBAPI
833
+ ``connect()`` function will be called. ``cargs`` will always be a
834
+ Python list that can be mutated in-place, and ``cparams`` a Python
835
+ dictionary that may also be mutated::
836
+
837
+ e = create_engine("postgresql+psycopg2://user@host/dbname")
838
+
839
+ @event.listens_for(e, 'do_connect')
840
+ def receive_do_connect(dialect, conn_rec, cargs, cparams):
841
+ cparams["password"] = "some_password"
842
+
843
+ The event hook may also be used to override the call to ``connect()``
844
+ entirely, by returning a non-``None`` DBAPI connection object::
845
+
846
+ e = create_engine("postgresql+psycopg2://user@host/dbname")
847
+
848
+ @event.listens_for(e, 'do_connect')
849
+ def receive_do_connect(dialect, conn_rec, cargs, cparams):
850
+ return psycopg2.connect(*cargs, **cparams)
851
+
852
+ .. seealso::
853
+
854
+ :ref:`custom_dbapi_args`
855
+
856
+ """
857
+
858
+ def do_executemany(
859
+ self,
860
+ cursor: DBAPICursor,
861
+ statement: str,
862
+ parameters: _DBAPIMultiExecuteParams,
863
+ context: ExecutionContext,
864
+ ) -> Optional[Literal[True]]:
865
+ """Receive a cursor to have executemany() called.
866
+
867
+ Return the value True to halt further events from invoking,
868
+ and to indicate that the cursor execution has already taken
869
+ place within the event handler.
870
+
871
+ """
872
+
873
+ def do_execute_no_params(
874
+ self, cursor: DBAPICursor, statement: str, context: ExecutionContext
875
+ ) -> Optional[Literal[True]]:
876
+ """Receive a cursor to have execute() with no parameters called.
877
+
878
+ Return the value True to halt further events from invoking,
879
+ and to indicate that the cursor execution has already taken
880
+ place within the event handler.
881
+
882
+ """
883
+
884
+ def do_execute(
885
+ self,
886
+ cursor: DBAPICursor,
887
+ statement: str,
888
+ parameters: _DBAPISingleExecuteParams,
889
+ context: ExecutionContext,
890
+ ) -> Optional[Literal[True]]:
891
+ """Receive a cursor to have execute() called.
892
+
893
+ Return the value True to halt further events from invoking,
894
+ and to indicate that the cursor execution has already taken
895
+ place within the event handler.
896
+
897
+ """
898
+
899
+ def do_setinputsizes(
900
+ self,
901
+ inputsizes: Dict[BindParameter[Any], Any],
902
+ cursor: DBAPICursor,
903
+ statement: str,
904
+ parameters: _DBAPIAnyExecuteParams,
905
+ context: ExecutionContext,
906
+ ) -> None:
907
+ """Receive the setinputsizes dictionary for possible modification.
908
+
909
+ This event is emitted in the case where the dialect makes use of the
910
+ DBAPI ``cursor.setinputsizes()`` method which passes information about
911
+ parameter binding for a particular statement. The given
912
+ ``inputsizes`` dictionary will contain :class:`.BindParameter` objects
913
+ as keys, linked to DBAPI-specific type objects as values; for
914
+ parameters that are not bound, they are added to the dictionary with
915
+ ``None`` as the value, which means the parameter will not be included
916
+ in the ultimate setinputsizes call. The event may be used to inspect
917
+ and/or log the datatypes that are being bound, as well as to modify the
918
+ dictionary in place. Parameters can be added, modified, or removed
919
+ from this dictionary. Callers will typically want to inspect the
920
+ :attr:`.BindParameter.type` attribute of the given bind objects in
921
+ order to make decisions about the DBAPI object.
922
+
923
+ After the event, the ``inputsizes`` dictionary is converted into
924
+ an appropriate datastructure to be passed to ``cursor.setinputsizes``;
925
+ either a list for a positional bound parameter execution style,
926
+ or a dictionary of string parameter keys to DBAPI type objects for
927
+ a named bound parameter execution style.
928
+
929
+ The setinputsizes hook overall is only used for dialects which include
930
+ the flag ``use_setinputsizes=True``. Dialects which use this
931
+ include cx_Oracle, pg8000, asyncpg, and pyodbc dialects.
932
+
933
+ .. note::
934
+
935
+ For use with pyodbc, the ``use_setinputsizes`` flag
936
+ must be passed to the dialect, e.g.::
937
+
938
+ create_engine("mssql+pyodbc://...", use_setinputsizes=True)
939
+
940
+ .. seealso::
941
+
942
+ :ref:`mssql_pyodbc_setinputsizes`
943
+
944
+ .. versionadded:: 1.2.9
945
+
946
+ .. seealso::
947
+
948
+ :ref:`cx_oracle_setinputsizes`
949
+
950
+ """
951
+ pass