SQLAlchemy 2.1.0rc1__cp315-cp315-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 (276) hide show
  1. sqlalchemy/__init__.py +299 -0
  2. sqlalchemy/connectors/__init__.py +18 -0
  3. sqlalchemy/connectors/aioodbc.py +171 -0
  4. sqlalchemy/connectors/asyncio.py +476 -0
  5. sqlalchemy/connectors/pyodbc.py +248 -0
  6. sqlalchemy/dialects/__init__.py +62 -0
  7. sqlalchemy/dialects/_typing.py +29 -0
  8. sqlalchemy/dialects/mssql/__init__.py +88 -0
  9. sqlalchemy/dialects/mssql/aioodbc.py +63 -0
  10. sqlalchemy/dialects/mssql/base.py +4833 -0
  11. sqlalchemy/dialects/mssql/information_schema.py +345 -0
  12. sqlalchemy/dialects/mssql/json.py +140 -0
  13. sqlalchemy/dialects/mssql/mssqlpython.py +242 -0
  14. sqlalchemy/dialects/mssql/provision.py +196 -0
  15. sqlalchemy/dialects/mssql/pymssql.py +130 -0
  16. sqlalchemy/dialects/mssql/pyodbc.py +697 -0
  17. sqlalchemy/dialects/mysql/__init__.py +106 -0
  18. sqlalchemy/dialects/mysql/_mariadb_shim.py +312 -0
  19. sqlalchemy/dialects/mysql/aiomysql.py +260 -0
  20. sqlalchemy/dialects/mysql/asyncmy.py +241 -0
  21. sqlalchemy/dialects/mysql/base.py +3896 -0
  22. sqlalchemy/dialects/mysql/cymysql.py +107 -0
  23. sqlalchemy/dialects/mysql/dml.py +279 -0
  24. sqlalchemy/dialects/mysql/enumerated.py +277 -0
  25. sqlalchemy/dialects/mysql/expression.py +146 -0
  26. sqlalchemy/dialects/mysql/json.py +92 -0
  27. sqlalchemy/dialects/mysql/mariadb.py +67 -0
  28. sqlalchemy/dialects/mysql/mariadbconnector.py +314 -0
  29. sqlalchemy/dialects/mysql/mysqlconnector.py +291 -0
  30. sqlalchemy/dialects/mysql/mysqldb.py +318 -0
  31. sqlalchemy/dialects/mysql/provision.py +153 -0
  32. sqlalchemy/dialects/mysql/pymysql.py +188 -0
  33. sqlalchemy/dialects/mysql/pyodbc.py +157 -0
  34. sqlalchemy/dialects/mysql/reflection.py +724 -0
  35. sqlalchemy/dialects/mysql/reserved_words.py +570 -0
  36. sqlalchemy/dialects/mysql/types.py +845 -0
  37. sqlalchemy/dialects/oracle/__init__.py +85 -0
  38. sqlalchemy/dialects/oracle/base.py +3847 -0
  39. sqlalchemy/dialects/oracle/cx_oracle.py +1736 -0
  40. sqlalchemy/dialects/oracle/dictionary.py +507 -0
  41. sqlalchemy/dialects/oracle/json.py +157 -0
  42. sqlalchemy/dialects/oracle/oracledb.py +898 -0
  43. sqlalchemy/dialects/oracle/provision.py +288 -0
  44. sqlalchemy/dialects/oracle/types.py +367 -0
  45. sqlalchemy/dialects/oracle/vector.py +366 -0
  46. sqlalchemy/dialects/postgresql/__init__.py +170 -0
  47. sqlalchemy/dialects/postgresql/_psycopg_common.py +232 -0
  48. sqlalchemy/dialects/postgresql/array.py +534 -0
  49. sqlalchemy/dialects/postgresql/asyncpg.py +1318 -0
  50. sqlalchemy/dialects/postgresql/base.py +5935 -0
  51. sqlalchemy/dialects/postgresql/bitstring.py +327 -0
  52. sqlalchemy/dialects/postgresql/dml.py +360 -0
  53. sqlalchemy/dialects/postgresql/ext.py +599 -0
  54. sqlalchemy/dialects/postgresql/hstore.py +422 -0
  55. sqlalchemy/dialects/postgresql/json.py +411 -0
  56. sqlalchemy/dialects/postgresql/named_types.py +535 -0
  57. sqlalchemy/dialects/postgresql/operators.py +129 -0
  58. sqlalchemy/dialects/postgresql/pg8000.py +655 -0
  59. sqlalchemy/dialects/postgresql/pg_catalog.py +345 -0
  60. sqlalchemy/dialects/postgresql/provision.py +202 -0
  61. sqlalchemy/dialects/postgresql/psycopg.py +800 -0
  62. sqlalchemy/dialects/postgresql/psycopg2.py +860 -0
  63. sqlalchemy/dialects/postgresql/psycopg2cffi.py +62 -0
  64. sqlalchemy/dialects/postgresql/ranges.py +1002 -0
  65. sqlalchemy/dialects/postgresql/types.py +388 -0
  66. sqlalchemy/dialects/sqlite/__init__.py +59 -0
  67. sqlalchemy/dialects/sqlite/aiosqlite.py +375 -0
  68. sqlalchemy/dialects/sqlite/base.py +3103 -0
  69. sqlalchemy/dialects/sqlite/dml.py +314 -0
  70. sqlalchemy/dialects/sqlite/json.py +134 -0
  71. sqlalchemy/dialects/sqlite/provision.py +237 -0
  72. sqlalchemy/dialects/sqlite/pysqlcipher.py +166 -0
  73. sqlalchemy/dialects/sqlite/pysqlite.py +959 -0
  74. sqlalchemy/dialects/type_migration_guidelines.txt +145 -0
  75. sqlalchemy/engine/__init__.py +62 -0
  76. sqlalchemy/engine/_processors_cy.cp315-win32.pyd +0 -0
  77. sqlalchemy/engine/_processors_cy.py +92 -0
  78. sqlalchemy/engine/_result_cy.cp315-win32.pyd +0 -0
  79. sqlalchemy/engine/_result_cy.py +711 -0
  80. sqlalchemy/engine/_row_cy.cp315-win32.pyd +0 -0
  81. sqlalchemy/engine/_row_cy.py +232 -0
  82. sqlalchemy/engine/_util_cy.cp315-win32.pyd +0 -0
  83. sqlalchemy/engine/_util_cy.py +136 -0
  84. sqlalchemy/engine/base.py +3357 -0
  85. sqlalchemy/engine/characteristics.py +155 -0
  86. sqlalchemy/engine/create.py +877 -0
  87. sqlalchemy/engine/cursor.py +2425 -0
  88. sqlalchemy/engine/default.py +2627 -0
  89. sqlalchemy/engine/events.py +965 -0
  90. sqlalchemy/engine/interfaces.py +3636 -0
  91. sqlalchemy/engine/mock.py +133 -0
  92. sqlalchemy/engine/processors.py +83 -0
  93. sqlalchemy/engine/reflection.py +2141 -0
  94. sqlalchemy/engine/result.py +2012 -0
  95. sqlalchemy/engine/row.py +397 -0
  96. sqlalchemy/engine/strategies.py +16 -0
  97. sqlalchemy/engine/url.py +922 -0
  98. sqlalchemy/engine/util.py +164 -0
  99. sqlalchemy/event/__init__.py +26 -0
  100. sqlalchemy/event/api.py +220 -0
  101. sqlalchemy/event/attr.py +675 -0
  102. sqlalchemy/event/base.py +473 -0
  103. sqlalchemy/event/legacy.py +259 -0
  104. sqlalchemy/event/registry.py +391 -0
  105. sqlalchemy/events.py +17 -0
  106. sqlalchemy/exc.py +939 -0
  107. sqlalchemy/ext/__init__.py +10 -0
  108. sqlalchemy/ext/associationproxy.py +2073 -0
  109. sqlalchemy/ext/asyncio/__init__.py +29 -0
  110. sqlalchemy/ext/asyncio/base.py +281 -0
  111. sqlalchemy/ext/asyncio/engine.py +1487 -0
  112. sqlalchemy/ext/asyncio/exc.py +21 -0
  113. sqlalchemy/ext/asyncio/result.py +994 -0
  114. sqlalchemy/ext/asyncio/scoping.py +1679 -0
  115. sqlalchemy/ext/asyncio/session.py +2006 -0
  116. sqlalchemy/ext/automap.py +1702 -0
  117. sqlalchemy/ext/baked.py +558 -0
  118. sqlalchemy/ext/compiler.py +601 -0
  119. sqlalchemy/ext/declarative/__init__.py +65 -0
  120. sqlalchemy/ext/declarative/extensions.py +561 -0
  121. sqlalchemy/ext/horizontal_shard.py +481 -0
  122. sqlalchemy/ext/hybrid.py +1877 -0
  123. sqlalchemy/ext/indexable.py +364 -0
  124. sqlalchemy/ext/instrumentation.py +450 -0
  125. sqlalchemy/ext/mutable.py +1081 -0
  126. sqlalchemy/ext/orderinglist.py +440 -0
  127. sqlalchemy/ext/serializer.py +184 -0
  128. sqlalchemy/future/__init__.py +17 -0
  129. sqlalchemy/future/engine.py +15 -0
  130. sqlalchemy/inspection.py +188 -0
  131. sqlalchemy/log.py +279 -0
  132. sqlalchemy/orm/__init__.py +176 -0
  133. sqlalchemy/orm/_orm_constructors.py +2694 -0
  134. sqlalchemy/orm/_typing.py +180 -0
  135. sqlalchemy/orm/attributes.py +2868 -0
  136. sqlalchemy/orm/base.py +991 -0
  137. sqlalchemy/orm/bulk_persistence.py +2168 -0
  138. sqlalchemy/orm/clsregistry.py +630 -0
  139. sqlalchemy/orm/collections.py +1569 -0
  140. sqlalchemy/orm/context.py +3475 -0
  141. sqlalchemy/orm/decl_api.py +2283 -0
  142. sqlalchemy/orm/decl_base.py +2320 -0
  143. sqlalchemy/orm/dependency.py +1306 -0
  144. sqlalchemy/orm/descriptor_props.py +1183 -0
  145. sqlalchemy/orm/dynamic.py +306 -0
  146. sqlalchemy/orm/evaluator.py +378 -0
  147. sqlalchemy/orm/events.py +3387 -0
  148. sqlalchemy/orm/exc.py +237 -0
  149. sqlalchemy/orm/identity.py +302 -0
  150. sqlalchemy/orm/instrumentation.py +749 -0
  151. sqlalchemy/orm/interfaces.py +1595 -0
  152. sqlalchemy/orm/loading.py +1712 -0
  153. sqlalchemy/orm/mapped_collection.py +557 -0
  154. sqlalchemy/orm/mapper.py +4465 -0
  155. sqlalchemy/orm/path_registry.py +907 -0
  156. sqlalchemy/orm/persistence.py +1790 -0
  157. sqlalchemy/orm/properties.py +972 -0
  158. sqlalchemy/orm/query.py +3528 -0
  159. sqlalchemy/orm/relationships.py +3608 -0
  160. sqlalchemy/orm/scoping.py +2233 -0
  161. sqlalchemy/orm/session.py +5468 -0
  162. sqlalchemy/orm/state.py +1175 -0
  163. sqlalchemy/orm/state_changes.py +196 -0
  164. sqlalchemy/orm/strategies.py +3552 -0
  165. sqlalchemy/orm/strategy_options.py +2648 -0
  166. sqlalchemy/orm/sync.py +164 -0
  167. sqlalchemy/orm/unitofwork.py +797 -0
  168. sqlalchemy/orm/util.py +2461 -0
  169. sqlalchemy/orm/writeonly.py +701 -0
  170. sqlalchemy/pool/__init__.py +41 -0
  171. sqlalchemy/pool/base.py +1540 -0
  172. sqlalchemy/pool/events.py +375 -0
  173. sqlalchemy/pool/impl.py +583 -0
  174. sqlalchemy/py.typed +0 -0
  175. sqlalchemy/schema.py +75 -0
  176. sqlalchemy/sql/__init__.py +156 -0
  177. sqlalchemy/sql/_annotated_cols.py +402 -0
  178. sqlalchemy/sql/_cache_key_cy.cp315-win32.pyd +0 -0
  179. sqlalchemy/sql/_cache_key_cy.py +363 -0
  180. sqlalchemy/sql/_dml_constructors.py +132 -0
  181. sqlalchemy/sql/_elements_constructors.py +2190 -0
  182. sqlalchemy/sql/_orm_types.py +19 -0
  183. sqlalchemy/sql/_selectable_constructors.py +840 -0
  184. sqlalchemy/sql/_typing.py +500 -0
  185. sqlalchemy/sql/_util_cy.cp315-win32.pyd +0 -0
  186. sqlalchemy/sql/_util_cy.pxd +11 -0
  187. sqlalchemy/sql/_util_cy.py +127 -0
  188. sqlalchemy/sql/annotation.py +590 -0
  189. sqlalchemy/sql/base.py +2702 -0
  190. sqlalchemy/sql/cache_key.py +915 -0
  191. sqlalchemy/sql/coercions.py +1373 -0
  192. sqlalchemy/sql/compiler.py +8453 -0
  193. sqlalchemy/sql/crud.py +1816 -0
  194. sqlalchemy/sql/ddl.py +1962 -0
  195. sqlalchemy/sql/default_comparator.py +660 -0
  196. sqlalchemy/sql/dml.py +2018 -0
  197. sqlalchemy/sql/elements.py +6057 -0
  198. sqlalchemy/sql/events.py +458 -0
  199. sqlalchemy/sql/expression.py +171 -0
  200. sqlalchemy/sql/functions.py +2380 -0
  201. sqlalchemy/sql/lambdas.py +1442 -0
  202. sqlalchemy/sql/naming.py +204 -0
  203. sqlalchemy/sql/operators.py +2909 -0
  204. sqlalchemy/sql/roles.py +332 -0
  205. sqlalchemy/sql/schema.py +7075 -0
  206. sqlalchemy/sql/selectable.py +7634 -0
  207. sqlalchemy/sql/sqltypes.py +4130 -0
  208. sqlalchemy/sql/traversals.py +1041 -0
  209. sqlalchemy/sql/type_api.py +2450 -0
  210. sqlalchemy/sql/util.py +1496 -0
  211. sqlalchemy/sql/visitors.py +1153 -0
  212. sqlalchemy/testing/__init__.py +97 -0
  213. sqlalchemy/testing/assertions.py +1007 -0
  214. sqlalchemy/testing/assertsql.py +519 -0
  215. sqlalchemy/testing/asyncio.py +128 -0
  216. sqlalchemy/testing/cancellation.py +237 -0
  217. sqlalchemy/testing/config.py +440 -0
  218. sqlalchemy/testing/engines.py +482 -0
  219. sqlalchemy/testing/entities.py +117 -0
  220. sqlalchemy/testing/exclusions.py +501 -0
  221. sqlalchemy/testing/fixtures/__init__.py +30 -0
  222. sqlalchemy/testing/fixtures/base.py +426 -0
  223. sqlalchemy/testing/fixtures/mypy.py +247 -0
  224. sqlalchemy/testing/fixtures/orm.py +227 -0
  225. sqlalchemy/testing/fixtures/sql.py +538 -0
  226. sqlalchemy/testing/pickleable.py +155 -0
  227. sqlalchemy/testing/plugin/__init__.py +6 -0
  228. sqlalchemy/testing/plugin/bootstrap.py +50 -0
  229. sqlalchemy/testing/plugin/plugin_base.py +828 -0
  230. sqlalchemy/testing/plugin/pytestplugin.py +896 -0
  231. sqlalchemy/testing/profiles_file.py +350 -0
  232. sqlalchemy/testing/profiling.py +294 -0
  233. sqlalchemy/testing/provision.py +633 -0
  234. sqlalchemy/testing/requirements.py +1971 -0
  235. sqlalchemy/testing/schema.py +198 -0
  236. sqlalchemy/testing/suite/__init__.py +19 -0
  237. sqlalchemy/testing/suite/test_cte.py +237 -0
  238. sqlalchemy/testing/suite/test_ddl.py +420 -0
  239. sqlalchemy/testing/suite/test_dialect.py +776 -0
  240. sqlalchemy/testing/suite/test_insert.py +630 -0
  241. sqlalchemy/testing/suite/test_reflection.py +3815 -0
  242. sqlalchemy/testing/suite/test_results.py +660 -0
  243. sqlalchemy/testing/suite/test_rowcount.py +258 -0
  244. sqlalchemy/testing/suite/test_select.py +2112 -0
  245. sqlalchemy/testing/suite/test_sequence.py +317 -0
  246. sqlalchemy/testing/suite/test_table_via_select.py +686 -0
  247. sqlalchemy/testing/suite/test_types.py +2271 -0
  248. sqlalchemy/testing/suite/test_unicode_ddl.py +189 -0
  249. sqlalchemy/testing/suite/test_update_delete.py +139 -0
  250. sqlalchemy/testing/util.py +575 -0
  251. sqlalchemy/testing/warnings.py +52 -0
  252. sqlalchemy/types.py +75 -0
  253. sqlalchemy/util/__init__.py +165 -0
  254. sqlalchemy/util/_collections.py +688 -0
  255. sqlalchemy/util/_collections_cy.cp315-win32.pyd +0 -0
  256. sqlalchemy/util/_collections_cy.pxd +8 -0
  257. sqlalchemy/util/_collections_cy.py +516 -0
  258. sqlalchemy/util/_has_cython.py +48 -0
  259. sqlalchemy/util/_immutabledict_cy.cp315-win32.pyd +0 -0
  260. sqlalchemy/util/_immutabledict_cy.py +240 -0
  261. sqlalchemy/util/compat.py +298 -0
  262. sqlalchemy/util/concurrency.py +272 -0
  263. sqlalchemy/util/cython.py +95 -0
  264. sqlalchemy/util/deprecations.py +401 -0
  265. sqlalchemy/util/langhelpers.py +2797 -0
  266. sqlalchemy/util/preloaded.py +153 -0
  267. sqlalchemy/util/queue.py +304 -0
  268. sqlalchemy/util/tool_support.py +202 -0
  269. sqlalchemy/util/topological.py +120 -0
  270. sqlalchemy/util/typing.py +709 -0
  271. sqlalchemy-2.1.0rc1.dist-info/METADATA +270 -0
  272. sqlalchemy-2.1.0rc1.dist-info/RECORD +276 -0
  273. sqlalchemy-2.1.0rc1.dist-info/WHEEL +5 -0
  274. sqlalchemy-2.1.0rc1.dist-info/licenses/AUTHORS +30 -0
  275. sqlalchemy-2.1.0rc1.dist-info/licenses/LICENSE +19 -0
  276. sqlalchemy-2.1.0rc1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,426 @@
1
+ # testing/fixtures/base.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
+ from collections.abc import Callable
13
+ from collections.abc import Sequence
14
+ import logging
15
+ import logging.handlers
16
+
17
+ import sqlalchemy as sa
18
+ from .. import assertions
19
+ from .. import config
20
+ from ..assertions import eq_
21
+ from ..util import drop_all_tables_from_metadata
22
+ from ..util import picklers
23
+ from ... import Column
24
+ from ... import func
25
+ from ... import Integer
26
+ from ... import select
27
+ from ... import Table
28
+ from ...orm import DeclarativeBase
29
+ from ...orm import MappedAsDataclass
30
+ from ...orm import registry
31
+
32
+
33
+ @config.mark_base_test_class()
34
+ class TestBase:
35
+ # A sequence of requirement names matching testing.requires decorators
36
+ __requires__: tuple[str, ...] = ()
37
+
38
+ # A sequence of dialect names to exclude from the test class.
39
+ __unsupported_on__: tuple[str, ...] = ()
40
+
41
+ # If present, test class is only runnable for the *single* specified
42
+ # dialect. If you need multiple, use __unsupported_on__ and invert.
43
+ __only_on__: tuple[str, ...] | str | None = None
44
+
45
+ # A sequence of no-arg callables. If any are True, the entire testcase is
46
+ # skipped.
47
+ __skip_if__: Sequence[Callable[[], bool]] | None = None
48
+
49
+ # if True, the testing reaper will not attempt to touch connection
50
+ # state after a test is completed and before the outer teardown
51
+ # starts
52
+ __leave_connections_for_teardown__: bool = False
53
+
54
+ __backend__: bool
55
+
56
+ def assert_(self, val, msg=None):
57
+ assert val, msg
58
+
59
+ @config.fixture()
60
+ def nocache(self):
61
+ _cache = config.db._compiled_cache
62
+ config.db._compiled_cache = None
63
+ yield
64
+ config.db._compiled_cache = _cache
65
+
66
+ @config.fixture()
67
+ def connection_no_trans(self):
68
+ eng = getattr(self, "bind", None) or config.db
69
+
70
+ with eng.connect() as conn:
71
+ yield conn
72
+
73
+ @config.fixture()
74
+ def connection(self):
75
+ global _connection_fixture_connection
76
+
77
+ eng = getattr(self, "bind", None) or config.db
78
+
79
+ conn = eng.connect()
80
+ trans = conn.begin()
81
+
82
+ _connection_fixture_connection = conn
83
+ yield conn
84
+
85
+ _connection_fixture_connection = None
86
+
87
+ if trans.is_active:
88
+ trans.rollback()
89
+ # trans would not be active here if the test is using
90
+ # the legacy @provide_metadata decorator still, as it will
91
+ # run a close all connections.
92
+ conn.close()
93
+
94
+ @config.fixture()
95
+ def close_result_when_finished(self):
96
+ to_close = []
97
+ to_consume = []
98
+
99
+ def go(result, consume=False):
100
+ to_close.append(result)
101
+ if consume:
102
+ to_consume.append(result)
103
+
104
+ yield go
105
+ for r in to_consume:
106
+ try:
107
+ r.all()
108
+ except:
109
+ pass
110
+ for r in to_close:
111
+ try:
112
+ r.close()
113
+ except:
114
+ pass
115
+
116
+ @config.fixture()
117
+ def registry(self, metadata):
118
+ reg = registry(
119
+ metadata=metadata,
120
+ type_annotation_map={
121
+ str: sa.String().with_variant(
122
+ sa.String(50), "mysql", "mariadb", "oracle"
123
+ )
124
+ },
125
+ )
126
+ yield reg
127
+ reg.dispose()
128
+
129
+ @config.fixture
130
+ def decl_base(self, metadata):
131
+ _md = metadata
132
+
133
+ class Base(DeclarativeBase):
134
+ metadata = _md
135
+ type_annotation_map = {
136
+ str: sa.String().with_variant(
137
+ sa.String(50), "mysql", "mariadb", "oracle"
138
+ )
139
+ }
140
+
141
+ yield Base
142
+ Base.registry.dispose()
143
+
144
+ @config.fixture
145
+ def dc_decl_base(self, metadata):
146
+ _md = metadata
147
+
148
+ class Base(MappedAsDataclass, DeclarativeBase):
149
+ metadata = _md
150
+ type_annotation_map = {
151
+ str: sa.String().with_variant(
152
+ sa.String(50), "mysql", "mariadb"
153
+ )
154
+ }
155
+
156
+ yield Base
157
+ Base.registry.dispose()
158
+
159
+ @config.fixture()
160
+ def future_connection(self, future_engine, connection):
161
+ # integrate the future_engine and connection fixtures so
162
+ # that users of the "connection" fixture will get at the
163
+ # "future" connection
164
+ yield connection
165
+
166
+ @config.fixture()
167
+ def future_engine(self):
168
+ yield
169
+
170
+ @config.fixture()
171
+ def testing_engine(self):
172
+ from .. import engines
173
+
174
+ def gen_testing_engine(
175
+ url=None,
176
+ options=None,
177
+ asyncio=False,
178
+ ):
179
+ if options is None:
180
+ options = {}
181
+ options["scope"] = "fixture"
182
+ return engines.testing_engine(
183
+ url=url,
184
+ options=options,
185
+ asyncio=asyncio,
186
+ )
187
+
188
+ yield gen_testing_engine
189
+
190
+ engines.testing_reaper._drop_testing_engines("fixture")
191
+
192
+ @config.fixture()
193
+ def async_testing_engine(self, testing_engine):
194
+ def go(**kw):
195
+ kw["asyncio"] = True
196
+ return testing_engine(**kw)
197
+
198
+ return go
199
+
200
+ @config.fixture(params=picklers())
201
+ def picklers(self, request):
202
+ yield request.param
203
+
204
+ @config.fixture()
205
+ def metadata(self, request):
206
+ """Provide bound MetaData for a single test, dropping afterwards."""
207
+
208
+ from ...sql import schema
209
+
210
+ metadata = schema.MetaData()
211
+ request.instance.metadata = metadata
212
+ yield metadata
213
+ del request.instance.metadata
214
+
215
+ if (
216
+ _connection_fixture_connection
217
+ and _connection_fixture_connection.in_transaction()
218
+ ):
219
+ trans = _connection_fixture_connection.get_transaction()
220
+ trans.rollback()
221
+ with _connection_fixture_connection.begin():
222
+ drop_all_tables_from_metadata(
223
+ metadata, _connection_fixture_connection
224
+ )
225
+ else:
226
+ drop_all_tables_from_metadata(metadata, config.db)
227
+
228
+ @config.fixture()
229
+ def thirdparty_dialect(self):
230
+ from ...dialects import registry
231
+
232
+ name = None
233
+
234
+ def go(dialect_cls):
235
+ nonlocal name
236
+ name = dialect_cls.name
237
+ assert name, "name is required"
238
+ registry.impls[name] = dialect_cls
239
+ return dialect_cls
240
+
241
+ yield go
242
+
243
+ assert name is not None
244
+ del registry.impls[name]
245
+
246
+ @config.fixture(
247
+ params=[
248
+ (rollback, second_operation, begin_nested)
249
+ for rollback in (True, False)
250
+ for second_operation in ("none", "execute", "begin")
251
+ for begin_nested in (
252
+ True,
253
+ False,
254
+ )
255
+ ]
256
+ )
257
+ def trans_ctx_manager_fixture(self, request, metadata):
258
+ rollback, second_operation, begin_nested = request.param
259
+
260
+ t = Table("test", metadata, Column("data", Integer))
261
+ eng = getattr(self, "bind", None) or config.db
262
+
263
+ t.create(eng)
264
+
265
+ def run_test(subject, trans_on_subject, execute_on_subject):
266
+ with subject.begin() as trans:
267
+ if begin_nested:
268
+ if not config.requirements.savepoints.enabled:
269
+ config.skip_test("savepoints not enabled")
270
+ if execute_on_subject:
271
+ nested_trans = subject.begin_nested()
272
+ else:
273
+ nested_trans = trans.begin_nested()
274
+
275
+ with nested_trans:
276
+ if execute_on_subject:
277
+ subject.execute(t.insert(), {"data": 10})
278
+ else:
279
+ trans.execute(t.insert(), {"data": 10})
280
+
281
+ # for nested trans, we always commit/rollback on the
282
+ # "nested trans" object itself.
283
+ # only Session(future=False) will affect savepoint
284
+ # transaction for session.commit/rollback
285
+
286
+ if rollback:
287
+ nested_trans.rollback()
288
+ else:
289
+ nested_trans.commit()
290
+
291
+ if second_operation != "none":
292
+ with assertions.expect_raises_message(
293
+ sa.exc.InvalidRequestError,
294
+ "Can't operate on closed transaction "
295
+ "inside context "
296
+ "manager. Please complete the context "
297
+ "manager "
298
+ "before emitting further commands.",
299
+ ):
300
+ if second_operation == "execute":
301
+ if execute_on_subject:
302
+ subject.execute(
303
+ t.insert(), {"data": 12}
304
+ )
305
+ else:
306
+ trans.execute(t.insert(), {"data": 12})
307
+ elif second_operation == "begin":
308
+ if execute_on_subject:
309
+ subject.begin_nested()
310
+ else:
311
+ trans.begin_nested()
312
+
313
+ # outside the nested trans block, but still inside the
314
+ # transaction block, we can run SQL, and it will be
315
+ # committed
316
+ if execute_on_subject:
317
+ subject.execute(t.insert(), {"data": 14})
318
+ else:
319
+ trans.execute(t.insert(), {"data": 14})
320
+
321
+ else:
322
+ if execute_on_subject:
323
+ subject.execute(t.insert(), {"data": 10})
324
+ else:
325
+ trans.execute(t.insert(), {"data": 10})
326
+
327
+ if trans_on_subject:
328
+ if rollback:
329
+ subject.rollback()
330
+ else:
331
+ subject.commit()
332
+ else:
333
+ if rollback:
334
+ trans.rollback()
335
+ else:
336
+ trans.commit()
337
+
338
+ if second_operation != "none":
339
+ with assertions.expect_raises_message(
340
+ sa.exc.InvalidRequestError,
341
+ "Can't operate on closed transaction inside "
342
+ "context "
343
+ "manager. Please complete the context manager "
344
+ "before emitting further commands.",
345
+ ):
346
+ if second_operation == "execute":
347
+ if execute_on_subject:
348
+ subject.execute(t.insert(), {"data": 12})
349
+ else:
350
+ trans.execute(t.insert(), {"data": 12})
351
+ elif second_operation == "begin":
352
+ if hasattr(trans, "begin"):
353
+ trans.begin()
354
+ else:
355
+ subject.begin()
356
+ elif second_operation == "begin_nested":
357
+ if execute_on_subject:
358
+ subject.begin_nested()
359
+ else:
360
+ trans.begin_nested()
361
+
362
+ expected_committed = 0
363
+ if begin_nested:
364
+ # begin_nested variant, we inserted a row after the nested
365
+ # block
366
+ expected_committed += 1
367
+ if not rollback:
368
+ # not rollback variant, our row inserted in the target
369
+ # block itself would be committed
370
+ expected_committed += 1
371
+
372
+ if execute_on_subject:
373
+ eq_(
374
+ subject.scalar(select(func.count()).select_from(t)),
375
+ expected_committed,
376
+ )
377
+ else:
378
+ with subject.connect() as conn:
379
+ eq_(
380
+ conn.scalar(select(func.count()).select_from(t)),
381
+ expected_committed,
382
+ )
383
+
384
+ return run_test
385
+
386
+ @config.fixture()
387
+ def debug_logging_engine(self, testing_engine):
388
+ """a fixture that provides an engine which will capture log messages
389
+ in a buffer.
390
+
391
+ """
392
+ log = logging.getLogger("sqlalchemy.engine")
393
+ existing_level = log.level
394
+
395
+ buf = logging.handlers.BufferingHandler(100)
396
+ log.addHandler(buf)
397
+
398
+ def get_testing_engine(
399
+ echo=None, log_level=None, skip_initial_connect=True
400
+ ):
401
+ te = testing_engine(options={"sqlite_share_pool": True})
402
+
403
+ # perform initial connection first so that logging occurs
404
+ # before we begin capturing
405
+ if skip_initial_connect:
406
+ te.connect().close()
407
+
408
+ # then set up echo or logging
409
+ if echo is not None:
410
+ te.echo = echo
411
+ if log_level:
412
+ log.setLevel(logging.DEBUG)
413
+ return te
414
+
415
+ try:
416
+ yield get_testing_engine, buf
417
+ finally:
418
+ log.setLevel(existing_level)
419
+ log.removeHandler(buf)
420
+
421
+
422
+ _connection_fixture_connection = None
423
+
424
+
425
+ class FutureEngineMixin:
426
+ """alembic's suite still using this"""
@@ -0,0 +1,247 @@
1
+ # testing/fixtures/mypy.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
+ from __future__ import annotations
10
+
11
+ import inspect
12
+ import os
13
+ from pathlib import Path
14
+ import re
15
+ import shutil
16
+ import sys
17
+ import tempfile
18
+
19
+ from .base import TestBase
20
+ from .. import config
21
+ from ..assertions import eq_
22
+
23
+ try:
24
+ from mypy import version
25
+
26
+ _mypy_vers_tuple = tuple(
27
+ int(x) for x in version.__version__.split(".") if x.isdecimal()
28
+ )
29
+ except ImportError:
30
+ _mypy_vers_tuple = (0, 0, 0)
31
+
32
+
33
+ @config.add_to_marker.mypy
34
+ class MypyTest(TestBase):
35
+ __requires__ = ("no_sqlalchemy2_stubs",)
36
+
37
+ @config.fixture(scope="function")
38
+ def per_func_cachedir(self):
39
+ yield from self._cachedir()
40
+
41
+ @config.fixture(scope="class")
42
+ @classmethod
43
+ def cachedir(cls):
44
+ yield from cls._cachedir()
45
+
46
+ @classmethod
47
+ def _cachedir(cls):
48
+ # as of mypy 0.971 i think we need to keep mypy_path empty
49
+ mypy_path = ""
50
+
51
+ with tempfile.TemporaryDirectory() as cachedir:
52
+ with open(
53
+ Path(cachedir) / "plain_mypy_config.cfg", "w"
54
+ ) as config_file:
55
+ config_file.write(f"""
56
+ [mypy]\n
57
+ show_error_codes = True\n
58
+ {mypy_path}
59
+ disable_error_code = var-annotated,no-untyped-call
60
+ [mypy-sqlalchemy.*]
61
+ ignore_errors = True
62
+
63
+ """)
64
+ yield cachedir
65
+
66
+ @config.fixture()
67
+ def mypy_runner(self, cachedir):
68
+ from mypy import api
69
+
70
+ def run(path, use_cachedir=None):
71
+ if use_cachedir is None:
72
+ use_cachedir = cachedir
73
+ args = [
74
+ "--strict",
75
+ "--raise-exceptions",
76
+ "--cache-dir",
77
+ use_cachedir,
78
+ "--config-file",
79
+ os.path.join(use_cachedir, "plain_mypy_config.cfg"),
80
+ ]
81
+
82
+ # mypy as of 0.990 is more aggressively blocking messaging
83
+ # for paths that are in sys.path, and as pytest puts currdir,
84
+ # test/ etc in sys.path, just copy the source file to the
85
+ # tempdir we are working in so that we don't have to try to
86
+ # manipulate sys.path and/or guess what mypy is doing
87
+ filename = os.path.basename(path)
88
+ test_program = os.path.join(use_cachedir, filename)
89
+ if path != test_program:
90
+ shutil.copyfile(path, test_program)
91
+ args.append(test_program)
92
+
93
+ # I set this locally but for the suite here needs to be
94
+ # disabled
95
+ os.environ.pop("MYPY_FORCE_COLOR", None)
96
+
97
+ stdout, stderr, exitcode = api.run(args)
98
+ return stdout, stderr, exitcode
99
+
100
+ return run
101
+
102
+ @config.fixture
103
+ def mypy_typecheck_file(self, mypy_runner):
104
+ def run(path):
105
+ expected_messages = self._collect_messages(path)
106
+ stdout, stderr, exitcode = mypy_runner(path)
107
+ self._check_output(
108
+ path, expected_messages, stdout, stderr, exitcode
109
+ )
110
+
111
+ return run
112
+
113
+ @staticmethod
114
+ def file_combinations(dirname):
115
+ if os.path.isabs(dirname):
116
+ path = dirname
117
+ else:
118
+ caller_path = inspect.stack()[1].filename
119
+ path = os.path.join(os.path.dirname(caller_path), dirname)
120
+ files = list(Path(path).glob("**/*.py"))
121
+
122
+ for extra_dir in config.options.mypy_extra_test_paths:
123
+ if extra_dir and os.path.isdir(extra_dir):
124
+ files.extend((Path(extra_dir) / dirname).glob("**/*.py"))
125
+ return files
126
+
127
+ def _collect_messages(self, path):
128
+ expected_messages = []
129
+ expected_re = re.compile(r"\s*# EXPECTED(_MYPY)?(_RE)?(_TYPE)?: (.+)")
130
+ py_ver_re = re.compile(r"^#\s*PYTHON_VERSION\s?>=\s?(\d+\.\d+)")
131
+ with open(path) as file_:
132
+ current_assert_messages = []
133
+ for num, line in enumerate(file_, 1):
134
+ m = py_ver_re.match(line)
135
+ if m:
136
+ major, _, minor = m.group(1).partition(".")
137
+ if sys.version_info < (int(major), int(minor)):
138
+ config.skip_test(
139
+ "Requires python >= %s" % (m.group(1))
140
+ )
141
+ continue
142
+
143
+ m = expected_re.match(line)
144
+ if m:
145
+ is_mypy = bool(m.group(1))
146
+ is_re = bool(m.group(2))
147
+ is_type = bool(m.group(3))
148
+ expected_msg = re.sub(r"# noqa[:]? ?.*", "", m.group(4))
149
+
150
+ if is_type:
151
+
152
+ is_mypy = is_re = True
153
+ expected_msg = f'Revealed type is "{expected_msg}"'
154
+
155
+ # use_or_syntax
156
+ # https://github.com/python/mypy/blob/304997bfb85200fb521ac727ee0ce3e6085e5278/mypy/options.py#L368 # noqa: E501
157
+ expected_msg = re.sub(
158
+ r"Optional\[(.*?)\]",
159
+ lambda m: f"{m.group(1)} | None",
160
+ expected_msg,
161
+ )
162
+ current_assert_messages.append(
163
+ (is_mypy, is_re, expected_msg.strip())
164
+ )
165
+ elif current_assert_messages:
166
+ expected_messages.extend(
167
+ (num, is_mypy, is_re, expected_msg)
168
+ for (
169
+ is_mypy,
170
+ is_re,
171
+ expected_msg,
172
+ ) in current_assert_messages
173
+ )
174
+ current_assert_messages[:] = []
175
+
176
+ return expected_messages
177
+
178
+ def _check_output(
179
+ self, path, expected_messages, stdout: str, stderr, exitcode
180
+ ):
181
+ not_located = []
182
+ filename = os.path.basename(path)
183
+ if expected_messages:
184
+ # mypy 0.990 changed how return codes work, so don't assume a
185
+ # 1 or a 0 return code here, could be either depending on if
186
+ # errors were generated or not
187
+
188
+ output = []
189
+
190
+ raw_lines = stdout.split("\n")
191
+ while raw_lines:
192
+ e = raw_lines.pop(0)
193
+ if re.match(r".+\.py:\d+: error: .*", e):
194
+ output.append(("error", e))
195
+ elif re.match(
196
+ r".+\.py:\d+: note: +(?:Possible overload|def ).*", e
197
+ ):
198
+ while raw_lines:
199
+ ol = raw_lines.pop(0)
200
+ if not re.match(r".+\.py:\d+: note: +def .*", ol):
201
+ raw_lines.insert(0, ol)
202
+ break
203
+ elif re.match(
204
+ r".+\.py:\d+: note: .*(?:perhaps|suggestion)", e, re.I
205
+ ):
206
+ pass
207
+ elif re.match(r".+\.py:\d+: note: .*", e):
208
+ output.append(("note", e))
209
+
210
+ for num, is_mypy, is_re, msg in expected_messages:
211
+ msg = msg.replace("'", '"')
212
+ prefix = "[SQLAlchemy Mypy plugin] " if not is_mypy else ""
213
+ for idx, (typ, errmsg) in enumerate(output):
214
+ if is_re:
215
+ if re.match(
216
+ rf".*{filename}\:{num}\: {typ}\: {prefix}{msg}",
217
+ errmsg,
218
+ ):
219
+ break
220
+ elif (
221
+ f"{filename}:{num}: {typ}: {prefix}{msg}"
222
+ in errmsg.replace("'", '"')
223
+ ):
224
+ break
225
+ else:
226
+ not_located.append(msg)
227
+ continue
228
+ del output[idx]
229
+
230
+ if not_located:
231
+ missing = "\n".join(not_located)
232
+ print("Couldn't locate expected messages:", missing, sep="\n")
233
+ if output:
234
+ extra = "\n".join(msg for _, msg in output)
235
+ print("Remaining messages:", extra, sep="\n")
236
+ assert False, "expected messages not found, see stdout"
237
+
238
+ if output:
239
+ print(f"{len(output)} messages from mypy were not consumed:")
240
+ print("\n".join(msg for _, msg in output))
241
+ assert False, "errors and/or notes remain, see stdout"
242
+
243
+ else:
244
+ if exitcode != 0:
245
+ print(stdout, stderr, sep="\n")
246
+
247
+ eq_(exitcode, 0, msg=stdout)