SQLAlchemy 2.1.0b1__cp313-cp313-win_arm64.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 (267) hide show
  1. sqlalchemy/__init__.py +295 -0
  2. sqlalchemy/connectors/__init__.py +18 -0
  3. sqlalchemy/connectors/aioodbc.py +161 -0
  4. sqlalchemy/connectors/asyncio.py +476 -0
  5. sqlalchemy/connectors/pyodbc.py +250 -0
  6. sqlalchemy/dialects/__init__.py +62 -0
  7. sqlalchemy/dialects/_typing.py +30 -0
  8. sqlalchemy/dialects/mssql/__init__.py +88 -0
  9. sqlalchemy/dialects/mssql/aioodbc.py +63 -0
  10. sqlalchemy/dialects/mssql/base.py +4110 -0
  11. sqlalchemy/dialects/mssql/information_schema.py +285 -0
  12. sqlalchemy/dialects/mssql/json.py +129 -0
  13. sqlalchemy/dialects/mssql/provision.py +185 -0
  14. sqlalchemy/dialects/mssql/pymssql.py +126 -0
  15. sqlalchemy/dialects/mssql/pyodbc.py +758 -0
  16. sqlalchemy/dialects/mysql/__init__.py +106 -0
  17. sqlalchemy/dialects/mysql/_mariadb_shim.py +312 -0
  18. sqlalchemy/dialects/mysql/aiomysql.py +226 -0
  19. sqlalchemy/dialects/mysql/asyncmy.py +214 -0
  20. sqlalchemy/dialects/mysql/base.py +3870 -0
  21. sqlalchemy/dialects/mysql/cymysql.py +106 -0
  22. sqlalchemy/dialects/mysql/dml.py +279 -0
  23. sqlalchemy/dialects/mysql/enumerated.py +277 -0
  24. sqlalchemy/dialects/mysql/expression.py +146 -0
  25. sqlalchemy/dialects/mysql/json.py +91 -0
  26. sqlalchemy/dialects/mysql/mariadb.py +67 -0
  27. sqlalchemy/dialects/mysql/mariadbconnector.py +330 -0
  28. sqlalchemy/dialects/mysql/mysqlconnector.py +296 -0
  29. sqlalchemy/dialects/mysql/mysqldb.py +312 -0
  30. sqlalchemy/dialects/mysql/provision.py +147 -0
  31. sqlalchemy/dialects/mysql/pymysql.py +157 -0
  32. sqlalchemy/dialects/mysql/pyodbc.py +156 -0
  33. sqlalchemy/dialects/mysql/reflection.py +724 -0
  34. sqlalchemy/dialects/mysql/reserved_words.py +570 -0
  35. sqlalchemy/dialects/mysql/types.py +845 -0
  36. sqlalchemy/dialects/oracle/__init__.py +83 -0
  37. sqlalchemy/dialects/oracle/base.py +3871 -0
  38. sqlalchemy/dialects/oracle/cx_oracle.py +1522 -0
  39. sqlalchemy/dialects/oracle/dictionary.py +507 -0
  40. sqlalchemy/dialects/oracle/oracledb.py +894 -0
  41. sqlalchemy/dialects/oracle/provision.py +288 -0
  42. sqlalchemy/dialects/oracle/types.py +350 -0
  43. sqlalchemy/dialects/oracle/vector.py +368 -0
  44. sqlalchemy/dialects/postgresql/__init__.py +171 -0
  45. sqlalchemy/dialects/postgresql/_psycopg_common.py +193 -0
  46. sqlalchemy/dialects/postgresql/array.py +534 -0
  47. sqlalchemy/dialects/postgresql/asyncpg.py +1331 -0
  48. sqlalchemy/dialects/postgresql/base.py +5729 -0
  49. sqlalchemy/dialects/postgresql/bitstring.py +327 -0
  50. sqlalchemy/dialects/postgresql/dml.py +360 -0
  51. sqlalchemy/dialects/postgresql/ext.py +593 -0
  52. sqlalchemy/dialects/postgresql/hstore.py +413 -0
  53. sqlalchemy/dialects/postgresql/json.py +407 -0
  54. sqlalchemy/dialects/postgresql/named_types.py +521 -0
  55. sqlalchemy/dialects/postgresql/operators.py +130 -0
  56. sqlalchemy/dialects/postgresql/pg8000.py +672 -0
  57. sqlalchemy/dialects/postgresql/pg_catalog.py +344 -0
  58. sqlalchemy/dialects/postgresql/provision.py +175 -0
  59. sqlalchemy/dialects/postgresql/psycopg.py +815 -0
  60. sqlalchemy/dialects/postgresql/psycopg2.py +887 -0
  61. sqlalchemy/dialects/postgresql/psycopg2cffi.py +61 -0
  62. sqlalchemy/dialects/postgresql/ranges.py +1002 -0
  63. sqlalchemy/dialects/postgresql/types.py +388 -0
  64. sqlalchemy/dialects/sqlite/__init__.py +57 -0
  65. sqlalchemy/dialects/sqlite/aiosqlite.py +321 -0
  66. sqlalchemy/dialects/sqlite/base.py +3050 -0
  67. sqlalchemy/dialects/sqlite/dml.py +279 -0
  68. sqlalchemy/dialects/sqlite/json.py +89 -0
  69. sqlalchemy/dialects/sqlite/provision.py +223 -0
  70. sqlalchemy/dialects/sqlite/pysqlcipher.py +157 -0
  71. sqlalchemy/dialects/sqlite/pysqlite.py +754 -0
  72. sqlalchemy/dialects/type_migration_guidelines.txt +145 -0
  73. sqlalchemy/engine/__init__.py +62 -0
  74. sqlalchemy/engine/_processors_cy.cp313-win_arm64.pyd +0 -0
  75. sqlalchemy/engine/_processors_cy.py +92 -0
  76. sqlalchemy/engine/_result_cy.cp313-win_arm64.pyd +0 -0
  77. sqlalchemy/engine/_result_cy.py +633 -0
  78. sqlalchemy/engine/_row_cy.cp313-win_arm64.pyd +0 -0
  79. sqlalchemy/engine/_row_cy.py +232 -0
  80. sqlalchemy/engine/_util_cy.cp313-win_arm64.pyd +0 -0
  81. sqlalchemy/engine/_util_cy.py +136 -0
  82. sqlalchemy/engine/base.py +3334 -0
  83. sqlalchemy/engine/characteristics.py +155 -0
  84. sqlalchemy/engine/create.py +869 -0
  85. sqlalchemy/engine/cursor.py +2416 -0
  86. sqlalchemy/engine/default.py +2393 -0
  87. sqlalchemy/engine/events.py +965 -0
  88. sqlalchemy/engine/interfaces.py +3465 -0
  89. sqlalchemy/engine/mock.py +134 -0
  90. sqlalchemy/engine/processors.py +82 -0
  91. sqlalchemy/engine/reflection.py +2100 -0
  92. sqlalchemy/engine/result.py +1932 -0
  93. sqlalchemy/engine/row.py +397 -0
  94. sqlalchemy/engine/strategies.py +16 -0
  95. sqlalchemy/engine/url.py +922 -0
  96. sqlalchemy/engine/util.py +156 -0
  97. sqlalchemy/event/__init__.py +26 -0
  98. sqlalchemy/event/api.py +220 -0
  99. sqlalchemy/event/attr.py +674 -0
  100. sqlalchemy/event/base.py +472 -0
  101. sqlalchemy/event/legacy.py +258 -0
  102. sqlalchemy/event/registry.py +390 -0
  103. sqlalchemy/events.py +17 -0
  104. sqlalchemy/exc.py +922 -0
  105. sqlalchemy/ext/__init__.py +11 -0
  106. sqlalchemy/ext/associationproxy.py +2072 -0
  107. sqlalchemy/ext/asyncio/__init__.py +29 -0
  108. sqlalchemy/ext/asyncio/base.py +281 -0
  109. sqlalchemy/ext/asyncio/engine.py +1475 -0
  110. sqlalchemy/ext/asyncio/exc.py +21 -0
  111. sqlalchemy/ext/asyncio/result.py +994 -0
  112. sqlalchemy/ext/asyncio/scoping.py +1667 -0
  113. sqlalchemy/ext/asyncio/session.py +1993 -0
  114. sqlalchemy/ext/automap.py +1701 -0
  115. sqlalchemy/ext/baked.py +559 -0
  116. sqlalchemy/ext/compiler.py +600 -0
  117. sqlalchemy/ext/declarative/__init__.py +65 -0
  118. sqlalchemy/ext/declarative/extensions.py +560 -0
  119. sqlalchemy/ext/horizontal_shard.py +481 -0
  120. sqlalchemy/ext/hybrid.py +1877 -0
  121. sqlalchemy/ext/indexable.py +364 -0
  122. sqlalchemy/ext/instrumentation.py +450 -0
  123. sqlalchemy/ext/mutable.py +1081 -0
  124. sqlalchemy/ext/orderinglist.py +439 -0
  125. sqlalchemy/ext/serializer.py +185 -0
  126. sqlalchemy/future/__init__.py +16 -0
  127. sqlalchemy/future/engine.py +15 -0
  128. sqlalchemy/inspection.py +174 -0
  129. sqlalchemy/log.py +283 -0
  130. sqlalchemy/orm/__init__.py +175 -0
  131. sqlalchemy/orm/_orm_constructors.py +2694 -0
  132. sqlalchemy/orm/_typing.py +179 -0
  133. sqlalchemy/orm/attributes.py +2868 -0
  134. sqlalchemy/orm/base.py +970 -0
  135. sqlalchemy/orm/bulk_persistence.py +2152 -0
  136. sqlalchemy/orm/clsregistry.py +582 -0
  137. sqlalchemy/orm/collections.py +1568 -0
  138. sqlalchemy/orm/context.py +3471 -0
  139. sqlalchemy/orm/decl_api.py +2257 -0
  140. sqlalchemy/orm/decl_base.py +2304 -0
  141. sqlalchemy/orm/dependency.py +1306 -0
  142. sqlalchemy/orm/descriptor_props.py +1183 -0
  143. sqlalchemy/orm/dynamic.py +300 -0
  144. sqlalchemy/orm/evaluator.py +379 -0
  145. sqlalchemy/orm/events.py +3386 -0
  146. sqlalchemy/orm/exc.py +237 -0
  147. sqlalchemy/orm/identity.py +302 -0
  148. sqlalchemy/orm/instrumentation.py +746 -0
  149. sqlalchemy/orm/interfaces.py +1589 -0
  150. sqlalchemy/orm/loading.py +1684 -0
  151. sqlalchemy/orm/mapped_collection.py +557 -0
  152. sqlalchemy/orm/mapper.py +4406 -0
  153. sqlalchemy/orm/path_registry.py +814 -0
  154. sqlalchemy/orm/persistence.py +1789 -0
  155. sqlalchemy/orm/properties.py +973 -0
  156. sqlalchemy/orm/query.py +3521 -0
  157. sqlalchemy/orm/relationships.py +3570 -0
  158. sqlalchemy/orm/scoping.py +2220 -0
  159. sqlalchemy/orm/session.py +5389 -0
  160. sqlalchemy/orm/state.py +1175 -0
  161. sqlalchemy/orm/state_changes.py +196 -0
  162. sqlalchemy/orm/strategies.py +3480 -0
  163. sqlalchemy/orm/strategy_options.py +2544 -0
  164. sqlalchemy/orm/sync.py +164 -0
  165. sqlalchemy/orm/unitofwork.py +798 -0
  166. sqlalchemy/orm/util.py +2435 -0
  167. sqlalchemy/orm/writeonly.py +694 -0
  168. sqlalchemy/pool/__init__.py +41 -0
  169. sqlalchemy/pool/base.py +1514 -0
  170. sqlalchemy/pool/events.py +372 -0
  171. sqlalchemy/pool/impl.py +582 -0
  172. sqlalchemy/py.typed +0 -0
  173. sqlalchemy/schema.py +72 -0
  174. sqlalchemy/sql/__init__.py +153 -0
  175. sqlalchemy/sql/_dml_constructors.py +132 -0
  176. sqlalchemy/sql/_elements_constructors.py +2147 -0
  177. sqlalchemy/sql/_orm_types.py +20 -0
  178. sqlalchemy/sql/_selectable_constructors.py +773 -0
  179. sqlalchemy/sql/_typing.py +486 -0
  180. sqlalchemy/sql/_util_cy.cp313-win_arm64.pyd +0 -0
  181. sqlalchemy/sql/_util_cy.py +127 -0
  182. sqlalchemy/sql/annotation.py +590 -0
  183. sqlalchemy/sql/base.py +2602 -0
  184. sqlalchemy/sql/cache_key.py +1066 -0
  185. sqlalchemy/sql/coercions.py +1373 -0
  186. sqlalchemy/sql/compiler.py +8259 -0
  187. sqlalchemy/sql/crud.py +1807 -0
  188. sqlalchemy/sql/ddl.py +1928 -0
  189. sqlalchemy/sql/default_comparator.py +654 -0
  190. sqlalchemy/sql/dml.py +1974 -0
  191. sqlalchemy/sql/elements.py +6016 -0
  192. sqlalchemy/sql/events.py +458 -0
  193. sqlalchemy/sql/expression.py +170 -0
  194. sqlalchemy/sql/functions.py +2257 -0
  195. sqlalchemy/sql/lambdas.py +1443 -0
  196. sqlalchemy/sql/naming.py +209 -0
  197. sqlalchemy/sql/operators.py +2897 -0
  198. sqlalchemy/sql/roles.py +332 -0
  199. sqlalchemy/sql/schema.py +6560 -0
  200. sqlalchemy/sql/selectable.py +7497 -0
  201. sqlalchemy/sql/sqltypes.py +4050 -0
  202. sqlalchemy/sql/traversals.py +1042 -0
  203. sqlalchemy/sql/type_api.py +2425 -0
  204. sqlalchemy/sql/util.py +1495 -0
  205. sqlalchemy/sql/visitors.py +1157 -0
  206. sqlalchemy/testing/__init__.py +96 -0
  207. sqlalchemy/testing/assertions.py +1007 -0
  208. sqlalchemy/testing/assertsql.py +519 -0
  209. sqlalchemy/testing/asyncio.py +128 -0
  210. sqlalchemy/testing/config.py +440 -0
  211. sqlalchemy/testing/engines.py +478 -0
  212. sqlalchemy/testing/entities.py +117 -0
  213. sqlalchemy/testing/exclusions.py +476 -0
  214. sqlalchemy/testing/fixtures/__init__.py +30 -0
  215. sqlalchemy/testing/fixtures/base.py +366 -0
  216. sqlalchemy/testing/fixtures/mypy.py +247 -0
  217. sqlalchemy/testing/fixtures/orm.py +227 -0
  218. sqlalchemy/testing/fixtures/sql.py +538 -0
  219. sqlalchemy/testing/pickleable.py +155 -0
  220. sqlalchemy/testing/plugin/__init__.py +6 -0
  221. sqlalchemy/testing/plugin/bootstrap.py +51 -0
  222. sqlalchemy/testing/plugin/plugin_base.py +828 -0
  223. sqlalchemy/testing/plugin/pytestplugin.py +892 -0
  224. sqlalchemy/testing/profiling.py +329 -0
  225. sqlalchemy/testing/provision.py +596 -0
  226. sqlalchemy/testing/requirements.py +1973 -0
  227. sqlalchemy/testing/schema.py +198 -0
  228. sqlalchemy/testing/suite/__init__.py +19 -0
  229. sqlalchemy/testing/suite/test_cte.py +237 -0
  230. sqlalchemy/testing/suite/test_ddl.py +420 -0
  231. sqlalchemy/testing/suite/test_dialect.py +776 -0
  232. sqlalchemy/testing/suite/test_insert.py +630 -0
  233. sqlalchemy/testing/suite/test_reflection.py +3557 -0
  234. sqlalchemy/testing/suite/test_results.py +660 -0
  235. sqlalchemy/testing/suite/test_rowcount.py +258 -0
  236. sqlalchemy/testing/suite/test_select.py +2112 -0
  237. sqlalchemy/testing/suite/test_sequence.py +317 -0
  238. sqlalchemy/testing/suite/test_table_via_select.py +686 -0
  239. sqlalchemy/testing/suite/test_types.py +2253 -0
  240. sqlalchemy/testing/suite/test_unicode_ddl.py +189 -0
  241. sqlalchemy/testing/suite/test_update_delete.py +139 -0
  242. sqlalchemy/testing/util.py +535 -0
  243. sqlalchemy/testing/warnings.py +52 -0
  244. sqlalchemy/types.py +76 -0
  245. sqlalchemy/util/__init__.py +157 -0
  246. sqlalchemy/util/_collections.py +693 -0
  247. sqlalchemy/util/_collections_cy.cp313-win_arm64.pyd +0 -0
  248. sqlalchemy/util/_collections_cy.pxd +8 -0
  249. sqlalchemy/util/_collections_cy.py +516 -0
  250. sqlalchemy/util/_has_cython.py +46 -0
  251. sqlalchemy/util/_immutabledict_cy.cp313-win_arm64.pyd +0 -0
  252. sqlalchemy/util/_immutabledict_cy.py +240 -0
  253. sqlalchemy/util/compat.py +287 -0
  254. sqlalchemy/util/concurrency.py +322 -0
  255. sqlalchemy/util/cython.py +79 -0
  256. sqlalchemy/util/deprecations.py +401 -0
  257. sqlalchemy/util/langhelpers.py +2256 -0
  258. sqlalchemy/util/preloaded.py +152 -0
  259. sqlalchemy/util/queue.py +304 -0
  260. sqlalchemy/util/tool_support.py +201 -0
  261. sqlalchemy/util/topological.py +120 -0
  262. sqlalchemy/util/typing.py +711 -0
  263. sqlalchemy-2.1.0b1.dist-info/METADATA +267 -0
  264. sqlalchemy-2.1.0b1.dist-info/RECORD +267 -0
  265. sqlalchemy-2.1.0b1.dist-info/WHEEL +5 -0
  266. sqlalchemy-2.1.0b1.dist-info/licenses/LICENSE +19 -0
  267. sqlalchemy-2.1.0b1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,478 @@
1
+ # testing/engines.py
2
+ # Copyright (C) 2005-2026 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
+ # mypy: ignore-errors
8
+
9
+
10
+ from __future__ import annotations
11
+
12
+ import collections
13
+ import re
14
+ import typing
15
+ from typing import Any
16
+ from typing import Dict
17
+ from typing import Literal
18
+ from typing import Optional
19
+ from typing import Union
20
+ import warnings
21
+ import weakref
22
+
23
+ from . import config
24
+ from .util import decorator
25
+ from .util import gc_collect
26
+ from .. import event
27
+ from .. import pool
28
+ from ..util import await_
29
+
30
+
31
+ if typing.TYPE_CHECKING:
32
+ from ..engine import Engine
33
+ from ..engine.url import URL
34
+ from ..ext.asyncio import AsyncEngine
35
+
36
+
37
+ class ConnectionKiller:
38
+ def __init__(self):
39
+ self.proxy_refs = weakref.WeakKeyDictionary()
40
+ self.testing_engines = collections.defaultdict(set)
41
+ self.dbapi_connections = set()
42
+
43
+ def add_pool(self, pool):
44
+ event.listen(pool, "checkout", self._add_conn)
45
+ event.listen(pool, "checkin", self._remove_conn)
46
+ event.listen(pool, "close", self._remove_conn)
47
+ event.listen(pool, "close_detached", self._remove_conn)
48
+ # note we are keeping "invalidated" here, as those are still
49
+ # opened connections we would like to roll back
50
+
51
+ def _add_conn(self, dbapi_con, con_record, con_proxy):
52
+ self.dbapi_connections.add(dbapi_con)
53
+ self.proxy_refs[con_proxy] = True
54
+
55
+ def _remove_conn(self, dbapi_conn, *arg):
56
+ self.dbapi_connections.discard(dbapi_conn)
57
+
58
+ def add_engine(self, engine, scope):
59
+ self.add_pool(engine.pool)
60
+
61
+ assert scope in ("class", "global", "function", "fixture")
62
+ self.testing_engines[scope].add(engine)
63
+
64
+ def _safe(self, fn):
65
+ try:
66
+ fn()
67
+ except Exception as e:
68
+ warnings.warn(
69
+ "testing_reaper couldn't rollback/close connection: %s" % e
70
+ )
71
+
72
+ def rollback_all(self):
73
+ for rec in list(self.proxy_refs):
74
+ if rec is not None and rec.is_valid:
75
+ self._safe(rec.rollback)
76
+
77
+ def checkin_all(self):
78
+ # run pool.checkin() for all ConnectionFairy instances we have
79
+ # tracked.
80
+
81
+ for rec in list(self.proxy_refs):
82
+ if rec is not None and rec.is_valid:
83
+ self.dbapi_connections.discard(rec.dbapi_connection)
84
+ self._safe(rec._checkin)
85
+
86
+ # for fairy refs that were GCed and could not close the connection,
87
+ # such as asyncio, roll back those remaining connections
88
+ for con in self.dbapi_connections:
89
+ self._safe(con.rollback)
90
+ self.dbapi_connections.clear()
91
+
92
+ def close_all(self):
93
+ self.checkin_all()
94
+
95
+ def prepare_for_drop_tables(self, connection):
96
+ # don't do aggressive checks for third party test suites
97
+ if not config.bootstrapped_as_sqlalchemy:
98
+ return
99
+
100
+ from . import provision
101
+
102
+ provision.prepare_for_drop_tables(connection.engine.url, connection)
103
+
104
+ def _drop_testing_engines(self, scope):
105
+ eng = self.testing_engines[scope]
106
+ for rec in list(eng):
107
+ for proxy_ref in list(self.proxy_refs):
108
+ if proxy_ref is not None and proxy_ref.is_valid:
109
+ if (
110
+ proxy_ref._pool is not None
111
+ and proxy_ref._pool is rec.pool
112
+ ):
113
+ self._safe(proxy_ref._checkin)
114
+
115
+ if hasattr(rec, "sync_engine"):
116
+ await_(rec.dispose())
117
+ else:
118
+ rec.dispose()
119
+
120
+ eng.clear()
121
+
122
+ def _dispose_testing_engines(self, scope):
123
+ eng = self.testing_engines[scope]
124
+ for rec in list(eng):
125
+ if hasattr(rec, "sync_engine"):
126
+ await_(rec.dispose())
127
+ else:
128
+ rec.dispose()
129
+
130
+ def after_test(self):
131
+ self._drop_testing_engines("function")
132
+
133
+ def after_test_outside_fixtures(self, test):
134
+ # don't do aggressive checks for third party test suites
135
+ if not config.bootstrapped_as_sqlalchemy:
136
+ return
137
+
138
+ if test.__class__.__leave_connections_for_teardown__:
139
+ return
140
+
141
+ self.checkin_all()
142
+
143
+ # on PostgreSQL, this will test for any "idle in transaction"
144
+ # connections. useful to identify tests with unusual patterns
145
+ # that can't be cleaned up correctly.
146
+ from . import provision
147
+
148
+ with config.db.connect() as conn:
149
+ provision.prepare_for_drop_tables(conn.engine.url, conn)
150
+
151
+ def stop_test_class_inside_fixtures(self):
152
+ self.checkin_all()
153
+ self._drop_testing_engines("function")
154
+ self._drop_testing_engines("class")
155
+
156
+ def stop_test_class_outside_fixtures(self):
157
+ # ensure no refs to checked out connections at all.
158
+
159
+ if pool.base._strong_ref_connection_records:
160
+ gc_collect()
161
+
162
+ if pool.base._strong_ref_connection_records:
163
+ ln = len(pool.base._strong_ref_connection_records)
164
+ pool.base._strong_ref_connection_records.clear()
165
+ assert (
166
+ False
167
+ ), "%d connection recs not cleared after test suite" % (ln)
168
+ if config.options and config.options.low_connections:
169
+ # for suites running with --low-connections, dispose the "global"
170
+ # engines to disconnect everything before making a testing engine
171
+ self._dispose_testing_engines("global")
172
+
173
+ def final_cleanup(self):
174
+ self.checkin_all()
175
+ for scope in self.testing_engines:
176
+ self._drop_testing_engines(scope)
177
+
178
+ def assert_all_closed(self):
179
+ for rec in self.proxy_refs:
180
+ if rec.is_valid:
181
+ assert False
182
+
183
+
184
+ testing_reaper = ConnectionKiller()
185
+
186
+
187
+ @decorator
188
+ def assert_conns_closed(fn, *args, **kw):
189
+ try:
190
+ fn(*args, **kw)
191
+ finally:
192
+ testing_reaper.assert_all_closed()
193
+
194
+
195
+ @decorator
196
+ def rollback_open_connections(fn, *args, **kw):
197
+ """Decorator that rolls back all open connections after fn execution."""
198
+
199
+ try:
200
+ fn(*args, **kw)
201
+ finally:
202
+ testing_reaper.rollback_all()
203
+
204
+
205
+ @decorator
206
+ def close_first(fn, *args, **kw):
207
+ """Decorator that closes all connections before fn execution."""
208
+
209
+ testing_reaper.checkin_all()
210
+ fn(*args, **kw)
211
+
212
+
213
+ @decorator
214
+ def close_open_connections(fn, *args, **kw):
215
+ """Decorator that closes all connections after fn execution."""
216
+ try:
217
+ fn(*args, **kw)
218
+ finally:
219
+ testing_reaper.checkin_all()
220
+
221
+
222
+ def all_dialects(exclude=None):
223
+ import sqlalchemy.dialects as d
224
+
225
+ for name in d.__all__:
226
+ # TEMPORARY
227
+ if exclude and name in exclude:
228
+ continue
229
+ mod = getattr(d, name, None)
230
+ if not mod:
231
+ mod = getattr(
232
+ __import__("sqlalchemy.dialects.%s" % name).dialects, name
233
+ )
234
+ yield mod.dialect()
235
+
236
+
237
+ class ReconnectFixture:
238
+ def __init__(self, dbapi):
239
+ self.dbapi = dbapi
240
+ self.connections = []
241
+ self.is_stopped = False
242
+
243
+ def __getattr__(self, key):
244
+ return getattr(self.dbapi, key)
245
+
246
+ def connect(self, *args, **kwargs):
247
+ conn = self.dbapi.connect(*args, **kwargs)
248
+ if self.is_stopped:
249
+ self._safe(conn.close)
250
+ curs = conn.cursor() # should fail on Oracle etc.
251
+ # should fail for everything that didn't fail
252
+ # above, connection is closed
253
+ curs.execute("select 1")
254
+ assert False, "simulated connect failure didn't work"
255
+ else:
256
+ self.connections.append(conn)
257
+ return conn
258
+
259
+ def _safe(self, fn):
260
+ try:
261
+ fn()
262
+ except Exception as e:
263
+ warnings.warn("ReconnectFixture couldn't close connection: %s" % e)
264
+
265
+ def shutdown(self, stop=False):
266
+ # TODO: this doesn't cover all cases
267
+ # as nicely as we'd like, namely MySQLdb.
268
+ # would need to implement R. Brewer's
269
+ # proxy server idea to get better
270
+ # coverage.
271
+ self.is_stopped = stop
272
+ for c in list(self.connections):
273
+ self._safe(c.close)
274
+ self.connections = []
275
+
276
+ def restart(self):
277
+ self.is_stopped = False
278
+
279
+
280
+ def reconnecting_engine(url=None, options=None):
281
+ url = url or config.db.url
282
+ dbapi = config.db.dialect.dbapi
283
+ if not options:
284
+ options = {}
285
+ options["module"] = ReconnectFixture(dbapi)
286
+ engine = testing_engine(url, options)
287
+ _dispose = engine.dispose
288
+
289
+ def dispose():
290
+ engine.dialect.dbapi.shutdown()
291
+ engine.dialect.dbapi.is_stopped = False
292
+ _dispose()
293
+
294
+ engine.test_shutdown = engine.dialect.dbapi.shutdown
295
+ engine.test_restart = engine.dialect.dbapi.restart
296
+ engine.dispose = dispose
297
+ return engine
298
+
299
+
300
+ @typing.overload
301
+ def testing_engine(
302
+ url: Optional[URL] = ...,
303
+ options: Optional[Dict[str, Any]] = ...,
304
+ *,
305
+ asyncio: Literal[False],
306
+ ) -> Engine: ...
307
+
308
+
309
+ @typing.overload
310
+ def testing_engine(
311
+ url: Optional[URL] = ...,
312
+ options: Optional[Dict[str, Any]] = ...,
313
+ *,
314
+ asyncio: Literal[True],
315
+ ) -> AsyncEngine: ...
316
+
317
+
318
+ def testing_engine(
319
+ url: Optional[URL] = None,
320
+ options: Optional[Dict[str, Any]] = None,
321
+ *,
322
+ asyncio: bool = False,
323
+ ) -> Union[Engine, AsyncEngine]:
324
+
325
+ if asyncio:
326
+ from sqlalchemy.ext.asyncio import (
327
+ create_async_engine as create_engine,
328
+ )
329
+ else:
330
+ from sqlalchemy import create_engine
331
+ from sqlalchemy.engine.url import make_url
332
+
333
+ url = make_url(url if url else config.db.url)
334
+
335
+ if not options:
336
+ options = {}
337
+
338
+ use_options = {}
339
+
340
+ for opt_dict in (config.db_opts, options):
341
+ if not opt_dict:
342
+ continue
343
+ use_options.update(
344
+ {
345
+ opt: value
346
+ for opt, value in opt_dict.items()
347
+ if opt not in ("scope", "use_reaper")
348
+ and not opt.startswith("sqlite_")
349
+ }
350
+ )
351
+
352
+ engine = create_engine(url, **use_options)
353
+
354
+ if config.options and config.options.low_connections:
355
+ # for suites running with --low-connections, dispose the "global"
356
+ # engines to disconnect everything before making a testing engine
357
+ testing_reaper._dispose_testing_engines("global")
358
+
359
+ scope = options.get("scope", "function")
360
+ if scope == "global":
361
+ if asyncio:
362
+ engine.sync_engine._has_events = True
363
+ else:
364
+ engine._has_events = (
365
+ True # enable event blocks, helps with profiling
366
+ )
367
+
368
+ from . import provision
369
+
370
+ provision.post_configure_testing_engine(engine.url, engine, options, scope)
371
+
372
+ # post_configure_testing_engine may have modified the options dictionary
373
+ # in place; consume additional post arguments afterwards
374
+
375
+ use_reaper = options.get("use_reaper", True)
376
+ if use_reaper:
377
+ testing_reaper.add_engine(engine, scope)
378
+
379
+ if (
380
+ isinstance(engine.pool, pool.QueuePool)
381
+ and "pool" not in options
382
+ and "pool_timeout" not in options
383
+ and "max_overflow" not in options
384
+ ):
385
+ engine.pool._timeout = 0
386
+ engine.pool._max_overflow = 0
387
+
388
+ return engine
389
+
390
+
391
+ def mock_engine(dialect_name=None):
392
+ """Provides a mocking engine based on the current testing.db.
393
+
394
+ This is normally used to test DDL generation flow as emitted
395
+ by an Engine.
396
+
397
+ It should not be used in other cases, as assert_compile() and
398
+ assert_sql_execution() are much better choices with fewer
399
+ moving parts.
400
+
401
+ """
402
+
403
+ from sqlalchemy import create_mock_engine
404
+
405
+ if not dialect_name:
406
+ dialect_name = config.db.name
407
+
408
+ buffer = []
409
+
410
+ def executor(sql, *a, **kw):
411
+ buffer.append(sql)
412
+
413
+ def assert_sql(stmts):
414
+ recv = [re.sub(r"[\n\t]", "", str(s)) for s in buffer]
415
+ assert recv == stmts, recv
416
+
417
+ def print_sql():
418
+ d = engine.dialect
419
+ return "\n".join(str(s.compile(dialect=d)) for s in engine.mock)
420
+
421
+ engine = create_mock_engine(dialect_name + "://", executor)
422
+ assert not hasattr(engine, "mock")
423
+ engine.mock = buffer
424
+ engine.assert_sql = assert_sql
425
+ engine.print_sql = print_sql
426
+ return engine
427
+
428
+
429
+ class DBAPIProxyCursor:
430
+ """Proxy a DBAPI cursor.
431
+
432
+ Tests can provide subclasses of this to intercept
433
+ DBAPI-level cursor operations.
434
+
435
+ """
436
+
437
+ def __init__(self, engine, conn, *args, **kwargs):
438
+ self.engine = engine
439
+ self.connection = conn
440
+ self.cursor = conn.cursor(*args, **kwargs)
441
+
442
+ def execute(self, stmt, parameters=None, **kw):
443
+ if parameters:
444
+ return self.cursor.execute(stmt, parameters, **kw)
445
+ else:
446
+ return self.cursor.execute(stmt, **kw)
447
+
448
+ def executemany(self, stmt, params, **kw):
449
+ return self.cursor.executemany(stmt, params, **kw)
450
+
451
+ def __iter__(self):
452
+ return iter(self.cursor)
453
+
454
+ def __getattr__(self, key):
455
+ return getattr(self.cursor, key)
456
+
457
+
458
+ class DBAPIProxyConnection:
459
+ """Proxy a DBAPI connection.
460
+
461
+ Tests can provide subclasses of this to intercept
462
+ DBAPI-level connection operations.
463
+
464
+ """
465
+
466
+ def __init__(self, engine, conn, cursor_cls):
467
+ self.conn = conn
468
+ self.engine = engine
469
+ self.cursor_cls = cursor_cls
470
+
471
+ def cursor(self, *args, **kwargs):
472
+ return self.cursor_cls(self.engine, self.conn, *args, **kwargs)
473
+
474
+ def close(self):
475
+ self.conn.close()
476
+
477
+ def __getattr__(self, key):
478
+ return getattr(self.conn, key)
@@ -0,0 +1,117 @@
1
+ # testing/entities.py
2
+ # Copyright (C) 2005-2026 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
+ # mypy: ignore-errors
8
+
9
+
10
+ from __future__ import annotations
11
+
12
+ import sqlalchemy as sa
13
+ from .. import exc as sa_exc
14
+ from ..orm.writeonly import WriteOnlyCollection
15
+
16
+ _repr_stack = set()
17
+
18
+
19
+ class BasicEntity:
20
+ def __init__(self, **kw):
21
+ for key, value in kw.items():
22
+ setattr(self, key, value)
23
+
24
+ def __repr__(self):
25
+ if id(self) in _repr_stack:
26
+ return object.__repr__(self)
27
+ _repr_stack.add(id(self))
28
+ try:
29
+ return "%s(%s)" % (
30
+ (self.__class__.__name__),
31
+ ", ".join(
32
+ [
33
+ "%s=%r" % (key, getattr(self, key))
34
+ for key in sorted(self.__dict__.keys())
35
+ if not key.startswith("_")
36
+ ]
37
+ ),
38
+ )
39
+ finally:
40
+ _repr_stack.remove(id(self))
41
+
42
+
43
+ _recursion_stack = set()
44
+
45
+
46
+ class ComparableMixin:
47
+ def __ne__(self, other):
48
+ return not self.__eq__(other)
49
+
50
+ def __eq__(self, other):
51
+ """'Deep, sparse compare.
52
+
53
+ Deeply compare two entities, following the non-None attributes of the
54
+ non-persisted object, if possible.
55
+
56
+ """
57
+ if other is self:
58
+ return True
59
+ elif not self.__class__ == other.__class__:
60
+ return False
61
+
62
+ if id(self) in _recursion_stack:
63
+ return True
64
+ _recursion_stack.add(id(self))
65
+
66
+ try:
67
+ # pick the entity that's not SA persisted as the source
68
+ try:
69
+ self_key = sa.orm.attributes.instance_state(self).key
70
+ except sa.orm.exc.NO_STATE:
71
+ self_key = None
72
+
73
+ if other is None:
74
+ a = self
75
+ b = other
76
+ elif self_key is not None:
77
+ a = other
78
+ b = self
79
+ else:
80
+ a = self
81
+ b = other
82
+
83
+ for attr in list(a.__dict__):
84
+ if attr.startswith("_"):
85
+ continue
86
+
87
+ value = getattr(a, attr)
88
+
89
+ if isinstance(value, WriteOnlyCollection):
90
+ continue
91
+
92
+ try:
93
+ # handle lazy loader errors
94
+ battr = getattr(b, attr)
95
+ except (AttributeError, sa_exc.UnboundExecutionError):
96
+ return False
97
+
98
+ if hasattr(value, "__iter__") and not isinstance(value, str):
99
+ if hasattr(value, "__getitem__") and not hasattr(
100
+ value, "keys"
101
+ ):
102
+ if list(value) != list(battr):
103
+ return False
104
+ else:
105
+ if set(value) != set(battr):
106
+ return False
107
+ else:
108
+ if value is not None and value != battr:
109
+ return False
110
+ return True
111
+ finally:
112
+ _recursion_stack.remove(id(self))
113
+
114
+
115
+ class ComparableEntity(ComparableMixin, BasicEntity):
116
+ def __hash__(self):
117
+ return hash(self.__class__)