SQLAlchemy 2.0.36__cp313-cp313-win32.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-win32.pyd +0 -0
  13. sqlalchemy/cyextension/collections.pyx +409 -0
  14. sqlalchemy/cyextension/immutabledict.cp313-win32.pyd +0 -0
  15. sqlalchemy/cyextension/immutabledict.pxd +8 -0
  16. sqlalchemy/cyextension/immutabledict.pyx +133 -0
  17. sqlalchemy/cyextension/processors.cp313-win32.pyd +0 -0
  18. sqlalchemy/cyextension/processors.pyx +68 -0
  19. sqlalchemy/cyextension/resultproxy.cp313-win32.pyd +0 -0
  20. sqlalchemy/cyextension/resultproxy.pyx +102 -0
  21. sqlalchemy/cyextension/util.cp313-win32.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,472 @@
1
+ # testing/engines.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
+ # 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 Optional
18
+ import warnings
19
+ import weakref
20
+
21
+ from . import config
22
+ from .util import decorator
23
+ from .util import gc_collect
24
+ from .. import event
25
+ from .. import pool
26
+ from ..util import await_only
27
+ from ..util.typing import Literal
28
+
29
+
30
+ if typing.TYPE_CHECKING:
31
+ from ..engine import Engine
32
+ from ..engine.url import URL
33
+ from ..ext.asyncio import AsyncEngine
34
+
35
+
36
+ class ConnectionKiller:
37
+ def __init__(self):
38
+ self.proxy_refs = weakref.WeakKeyDictionary()
39
+ self.testing_engines = collections.defaultdict(set)
40
+ self.dbapi_connections = set()
41
+
42
+ def add_pool(self, pool):
43
+ event.listen(pool, "checkout", self._add_conn)
44
+ event.listen(pool, "checkin", self._remove_conn)
45
+ event.listen(pool, "close", self._remove_conn)
46
+ event.listen(pool, "close_detached", self._remove_conn)
47
+ # note we are keeping "invalidated" here, as those are still
48
+ # opened connections we would like to roll back
49
+
50
+ def _add_conn(self, dbapi_con, con_record, con_proxy):
51
+ self.dbapi_connections.add(dbapi_con)
52
+ self.proxy_refs[con_proxy] = True
53
+
54
+ def _remove_conn(self, dbapi_conn, *arg):
55
+ self.dbapi_connections.discard(dbapi_conn)
56
+
57
+ def add_engine(self, engine, scope):
58
+ self.add_pool(engine.pool)
59
+
60
+ assert scope in ("class", "global", "function", "fixture")
61
+ self.testing_engines[scope].add(engine)
62
+
63
+ def _safe(self, fn):
64
+ try:
65
+ fn()
66
+ except Exception as e:
67
+ warnings.warn(
68
+ "testing_reaper couldn't rollback/close connection: %s" % e
69
+ )
70
+
71
+ def rollback_all(self):
72
+ for rec in list(self.proxy_refs):
73
+ if rec is not None and rec.is_valid:
74
+ self._safe(rec.rollback)
75
+
76
+ def checkin_all(self):
77
+ # run pool.checkin() for all ConnectionFairy instances we have
78
+ # tracked.
79
+
80
+ for rec in list(self.proxy_refs):
81
+ if rec is not None and rec.is_valid:
82
+ self.dbapi_connections.discard(rec.dbapi_connection)
83
+ self._safe(rec._checkin)
84
+
85
+ # for fairy refs that were GCed and could not close the connection,
86
+ # such as asyncio, roll back those remaining connections
87
+ for con in self.dbapi_connections:
88
+ self._safe(con.rollback)
89
+ self.dbapi_connections.clear()
90
+
91
+ def close_all(self):
92
+ self.checkin_all()
93
+
94
+ def prepare_for_drop_tables(self, connection):
95
+ # don't do aggressive checks for third party test suites
96
+ if not config.bootstrapped_as_sqlalchemy:
97
+ return
98
+
99
+ from . import provision
100
+
101
+ provision.prepare_for_drop_tables(connection.engine.url, connection)
102
+
103
+ def _drop_testing_engines(self, scope):
104
+ eng = self.testing_engines[scope]
105
+ for rec in list(eng):
106
+ for proxy_ref in list(self.proxy_refs):
107
+ if proxy_ref is not None and proxy_ref.is_valid:
108
+ if (
109
+ proxy_ref._pool is not None
110
+ and proxy_ref._pool is rec.pool
111
+ ):
112
+ self._safe(proxy_ref._checkin)
113
+
114
+ if hasattr(rec, "sync_engine"):
115
+ await_only(rec.dispose())
116
+ else:
117
+ rec.dispose()
118
+ eng.clear()
119
+
120
+ def after_test(self):
121
+ self._drop_testing_engines("function")
122
+
123
+ def after_test_outside_fixtures(self, test):
124
+ # don't do aggressive checks for third party test suites
125
+ if not config.bootstrapped_as_sqlalchemy:
126
+ return
127
+
128
+ if test.__class__.__leave_connections_for_teardown__:
129
+ return
130
+
131
+ self.checkin_all()
132
+
133
+ # on PostgreSQL, this will test for any "idle in transaction"
134
+ # connections. useful to identify tests with unusual patterns
135
+ # that can't be cleaned up correctly.
136
+ from . import provision
137
+
138
+ with config.db.connect() as conn:
139
+ provision.prepare_for_drop_tables(conn.engine.url, conn)
140
+
141
+ def stop_test_class_inside_fixtures(self):
142
+ self.checkin_all()
143
+ self._drop_testing_engines("function")
144
+ self._drop_testing_engines("class")
145
+
146
+ def stop_test_class_outside_fixtures(self):
147
+ # ensure no refs to checked out connections at all.
148
+
149
+ if pool.base._strong_ref_connection_records:
150
+ gc_collect()
151
+
152
+ if pool.base._strong_ref_connection_records:
153
+ ln = len(pool.base._strong_ref_connection_records)
154
+ pool.base._strong_ref_connection_records.clear()
155
+ assert (
156
+ False
157
+ ), "%d connection recs not cleared after test suite" % (ln)
158
+
159
+ def final_cleanup(self):
160
+ self.checkin_all()
161
+ for scope in self.testing_engines:
162
+ self._drop_testing_engines(scope)
163
+
164
+ def assert_all_closed(self):
165
+ for rec in self.proxy_refs:
166
+ if rec.is_valid:
167
+ assert False
168
+
169
+
170
+ testing_reaper = ConnectionKiller()
171
+
172
+
173
+ @decorator
174
+ def assert_conns_closed(fn, *args, **kw):
175
+ try:
176
+ fn(*args, **kw)
177
+ finally:
178
+ testing_reaper.assert_all_closed()
179
+
180
+
181
+ @decorator
182
+ def rollback_open_connections(fn, *args, **kw):
183
+ """Decorator that rolls back all open connections after fn execution."""
184
+
185
+ try:
186
+ fn(*args, **kw)
187
+ finally:
188
+ testing_reaper.rollback_all()
189
+
190
+
191
+ @decorator
192
+ def close_first(fn, *args, **kw):
193
+ """Decorator that closes all connections before fn execution."""
194
+
195
+ testing_reaper.checkin_all()
196
+ fn(*args, **kw)
197
+
198
+
199
+ @decorator
200
+ def close_open_connections(fn, *args, **kw):
201
+ """Decorator that closes all connections after fn execution."""
202
+ try:
203
+ fn(*args, **kw)
204
+ finally:
205
+ testing_reaper.checkin_all()
206
+
207
+
208
+ def all_dialects(exclude=None):
209
+ import sqlalchemy.dialects as d
210
+
211
+ for name in d.__all__:
212
+ # TEMPORARY
213
+ if exclude and name in exclude:
214
+ continue
215
+ mod = getattr(d, name, None)
216
+ if not mod:
217
+ mod = getattr(
218
+ __import__("sqlalchemy.dialects.%s" % name).dialects, name
219
+ )
220
+ yield mod.dialect()
221
+
222
+
223
+ class ReconnectFixture:
224
+ def __init__(self, dbapi):
225
+ self.dbapi = dbapi
226
+ self.connections = []
227
+ self.is_stopped = False
228
+
229
+ def __getattr__(self, key):
230
+ return getattr(self.dbapi, key)
231
+
232
+ def connect(self, *args, **kwargs):
233
+ conn = self.dbapi.connect(*args, **kwargs)
234
+ if self.is_stopped:
235
+ self._safe(conn.close)
236
+ curs = conn.cursor() # should fail on Oracle etc.
237
+ # should fail for everything that didn't fail
238
+ # above, connection is closed
239
+ curs.execute("select 1")
240
+ assert False, "simulated connect failure didn't work"
241
+ else:
242
+ self.connections.append(conn)
243
+ return conn
244
+
245
+ def _safe(self, fn):
246
+ try:
247
+ fn()
248
+ except Exception as e:
249
+ warnings.warn("ReconnectFixture couldn't close connection: %s" % e)
250
+
251
+ def shutdown(self, stop=False):
252
+ # TODO: this doesn't cover all cases
253
+ # as nicely as we'd like, namely MySQLdb.
254
+ # would need to implement R. Brewer's
255
+ # proxy server idea to get better
256
+ # coverage.
257
+ self.is_stopped = stop
258
+ for c in list(self.connections):
259
+ self._safe(c.close)
260
+ self.connections = []
261
+
262
+ def restart(self):
263
+ self.is_stopped = False
264
+
265
+
266
+ def reconnecting_engine(url=None, options=None):
267
+ url = url or config.db.url
268
+ dbapi = config.db.dialect.dbapi
269
+ if not options:
270
+ options = {}
271
+ options["module"] = ReconnectFixture(dbapi)
272
+ engine = testing_engine(url, options)
273
+ _dispose = engine.dispose
274
+
275
+ def dispose():
276
+ engine.dialect.dbapi.shutdown()
277
+ engine.dialect.dbapi.is_stopped = False
278
+ _dispose()
279
+
280
+ engine.test_shutdown = engine.dialect.dbapi.shutdown
281
+ engine.test_restart = engine.dialect.dbapi.restart
282
+ engine.dispose = dispose
283
+ return engine
284
+
285
+
286
+ @typing.overload
287
+ def testing_engine(
288
+ url: Optional[URL] = None,
289
+ options: Optional[Dict[str, Any]] = None,
290
+ asyncio: Literal[False] = False,
291
+ transfer_staticpool: bool = False,
292
+ ) -> Engine: ...
293
+
294
+
295
+ @typing.overload
296
+ def testing_engine(
297
+ url: Optional[URL] = None,
298
+ options: Optional[Dict[str, Any]] = None,
299
+ asyncio: Literal[True] = True,
300
+ transfer_staticpool: bool = False,
301
+ ) -> AsyncEngine: ...
302
+
303
+
304
+ def testing_engine(
305
+ url=None,
306
+ options=None,
307
+ asyncio=False,
308
+ transfer_staticpool=False,
309
+ share_pool=False,
310
+ _sqlite_savepoint=False,
311
+ ):
312
+ if asyncio:
313
+ assert not _sqlite_savepoint
314
+ from sqlalchemy.ext.asyncio import (
315
+ create_async_engine as create_engine,
316
+ )
317
+ else:
318
+ from sqlalchemy import create_engine
319
+ from sqlalchemy.engine.url import make_url
320
+
321
+ if not options:
322
+ use_reaper = True
323
+ scope = "function"
324
+ sqlite_savepoint = False
325
+ else:
326
+ use_reaper = options.pop("use_reaper", True)
327
+ scope = options.pop("scope", "function")
328
+ sqlite_savepoint = options.pop("sqlite_savepoint", False)
329
+
330
+ url = url or config.db.url
331
+
332
+ url = make_url(url)
333
+ if options is None:
334
+ if config.db is None or url.drivername == config.db.url.drivername:
335
+ options = config.db_opts
336
+ else:
337
+ options = {}
338
+ elif config.db is not None and url.drivername == config.db.url.drivername:
339
+ default_opt = config.db_opts.copy()
340
+ default_opt.update(options)
341
+
342
+ engine = create_engine(url, **options)
343
+
344
+ if sqlite_savepoint and engine.name == "sqlite":
345
+ # apply SQLite savepoint workaround
346
+ @event.listens_for(engine, "connect")
347
+ def do_connect(dbapi_connection, connection_record):
348
+ dbapi_connection.isolation_level = None
349
+
350
+ @event.listens_for(engine, "begin")
351
+ def do_begin(conn):
352
+ conn.exec_driver_sql("BEGIN")
353
+
354
+ if transfer_staticpool:
355
+ from sqlalchemy.pool import StaticPool
356
+
357
+ if config.db is not None and isinstance(config.db.pool, StaticPool):
358
+ use_reaper = False
359
+ engine.pool._transfer_from(config.db.pool)
360
+ elif share_pool:
361
+ engine.pool = config.db.pool
362
+
363
+ if scope == "global":
364
+ if asyncio:
365
+ engine.sync_engine._has_events = True
366
+ else:
367
+ engine._has_events = (
368
+ True # enable event blocks, helps with profiling
369
+ )
370
+
371
+ if (
372
+ isinstance(engine.pool, pool.QueuePool)
373
+ and "pool" not in options
374
+ and "pool_timeout" not in options
375
+ and "max_overflow" not in options
376
+ ):
377
+ engine.pool._timeout = 0
378
+ engine.pool._max_overflow = 0
379
+ if use_reaper:
380
+ testing_reaper.add_engine(engine, scope)
381
+
382
+ return engine
383
+
384
+
385
+ def mock_engine(dialect_name=None):
386
+ """Provides a mocking engine based on the current testing.db.
387
+
388
+ This is normally used to test DDL generation flow as emitted
389
+ by an Engine.
390
+
391
+ It should not be used in other cases, as assert_compile() and
392
+ assert_sql_execution() are much better choices with fewer
393
+ moving parts.
394
+
395
+ """
396
+
397
+ from sqlalchemy import create_mock_engine
398
+
399
+ if not dialect_name:
400
+ dialect_name = config.db.name
401
+
402
+ buffer = []
403
+
404
+ def executor(sql, *a, **kw):
405
+ buffer.append(sql)
406
+
407
+ def assert_sql(stmts):
408
+ recv = [re.sub(r"[\n\t]", "", str(s)) for s in buffer]
409
+ assert recv == stmts, recv
410
+
411
+ def print_sql():
412
+ d = engine.dialect
413
+ return "\n".join(str(s.compile(dialect=d)) for s in engine.mock)
414
+
415
+ engine = create_mock_engine(dialect_name + "://", executor)
416
+ assert not hasattr(engine, "mock")
417
+ engine.mock = buffer
418
+ engine.assert_sql = assert_sql
419
+ engine.print_sql = print_sql
420
+ return engine
421
+
422
+
423
+ class DBAPIProxyCursor:
424
+ """Proxy a DBAPI cursor.
425
+
426
+ Tests can provide subclasses of this to intercept
427
+ DBAPI-level cursor operations.
428
+
429
+ """
430
+
431
+ def __init__(self, engine, conn, *args, **kwargs):
432
+ self.engine = engine
433
+ self.connection = conn
434
+ self.cursor = conn.cursor(*args, **kwargs)
435
+
436
+ def execute(self, stmt, parameters=None, **kw):
437
+ if parameters:
438
+ return self.cursor.execute(stmt, parameters, **kw)
439
+ else:
440
+ return self.cursor.execute(stmt, **kw)
441
+
442
+ def executemany(self, stmt, params, **kw):
443
+ return self.cursor.executemany(stmt, params, **kw)
444
+
445
+ def __iter__(self):
446
+ return iter(self.cursor)
447
+
448
+ def __getattr__(self, key):
449
+ return getattr(self.cursor, key)
450
+
451
+
452
+ class DBAPIProxyConnection:
453
+ """Proxy a DBAPI connection.
454
+
455
+ Tests can provide subclasses of this to intercept
456
+ DBAPI-level connection operations.
457
+
458
+ """
459
+
460
+ def __init__(self, engine, conn, cursor_cls):
461
+ self.conn = conn
462
+ self.engine = engine
463
+ self.cursor_cls = cursor_cls
464
+
465
+ def cursor(self, *args, **kwargs):
466
+ return self.cursor_cls(self.engine, self.conn, *args, **kwargs)
467
+
468
+ def close(self):
469
+ self.conn.close()
470
+
471
+ def __getattr__(self, key):
472
+ return getattr(self.conn, key)
@@ -0,0 +1,117 @@
1
+ # testing/entities.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
+ # 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__)