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,350 @@
1
+ # testing/profiles_file.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
+
8
+ """Format of the call count file used by ``test/aaa_profiling/``.
9
+
10
+ ``test/profiles.txt`` stores the expected function call counts asserted by
11
+ the profiling suite. Each line is keyed to a "platform key" that encodes
12
+ the machine architecture, operating system, Python implementation and
13
+ version, the database / DBAPI in use, and whether or not the C extensions
14
+ were built:
15
+
16
+ .. sourcecode:: text
17
+
18
+ test.aaa_profiling.test_orm.MergeTest.test_merge_load \
19
+ x86_64_linux_cpython_3.14_sqlite_pysqlite_dbapiunicode_cextensions 1234
20
+
21
+ The key covers anything that moves the counts, which includes compiled
22
+ code that isn't SQLAlchemy's own: a DBAPI that ships both a pure Python
23
+ and a C accelerated build carries a ``pydbapi`` / ``cdbapi`` token naming
24
+ which one was loaded, since the difference between them can be tens of
25
+ thousands of calls.
26
+
27
+ A call count is only asserted when the running environment matches a key
28
+ that's present in the file; otherwise the test is skipped.
29
+
30
+ Two different things read and write this file: :mod:`.testing.profiling`,
31
+ which records counts as the suite runs, and ``tools/profiles.py``, which
32
+ maintains the file from the outside. Both use this module so that the
33
+ format is spelled out in exactly one place.
34
+
35
+ .. note::
36
+
37
+ ``tools/profiles.py`` loads this module directly from the source tree,
38
+ without importing the ``sqlalchemy`` package, so that the maintenance
39
+ tooling and the noxfile that drives it work in an environment where
40
+ SQLAlchemy itself isn't installed. Keep the imports here to the
41
+ standard library only.
42
+
43
+ """
44
+
45
+ from __future__ import annotations
46
+
47
+ import os
48
+ import re
49
+ from typing import Dict
50
+ from typing import KeysView
51
+ from typing import List
52
+ from typing import NamedTuple
53
+ from typing import Optional
54
+ from typing import Set
55
+ from typing import Tuple
56
+ from typing import TypeAlias
57
+ from typing import Union
58
+
59
+ HEADER = """\
60
+ # SQLAlchemy call count profiles.
61
+ # This file is written out on a per-environment basis.
62
+ # For each test in aaa_profiling, the corresponding function and
63
+ # environment is located within this file. If it doesn't exist,
64
+ # the test is skipped.
65
+ # If a callcount does exist, it is compared to what we received.
66
+ # assertions are raised if the counts do not match.
67
+ #
68
+ # To add a new callcount test, apply the function_call_count
69
+ # decorator and re-run the tests using the --write-profiles
70
+ # option - this file will be rewritten including the new count.
71
+ #
72
+ """
73
+
74
+ DB_TOKEN_TO_DATABASE = {
75
+ "sqlite": "sqlite",
76
+ "postgresql": "postgresql",
77
+ "mysql": "mysql",
78
+ "mariadb": "mysql",
79
+ "oracle": "oracle",
80
+ "mssql": "mssql",
81
+ }
82
+ """Map the dialect name found in a platform key to a ``--db`` name.
83
+
84
+ The dialect name is what the *server* turned out to be, so e.g. running
85
+ ``--db mysql`` against a MariaDB server records ``mariadb`` in the key.
86
+
87
+ """
88
+
89
+ TestKey: TypeAlias = str
90
+ """A test's id as reported by the plugin, e.g.
91
+ ``test.aaa_profiling.test_orm.MergeTest.test_merge_load``.
92
+
93
+ An opaque string; the profiling suite never takes one apart.
94
+
95
+ """
96
+
97
+ _EMPTY_COUNTS: Dict[PlatformKey, List[int]] = {}
98
+
99
+ _PY_VERSION = re.compile(r"^\d+\.\d+t?$")
100
+
101
+ _UNICODE_TOKEN = "dbapiunicode"
102
+
103
+
104
+ class PlatformKey(NamedTuple):
105
+ """The environment half of a line in ``test/profiles.txt``."""
106
+
107
+ machine: str
108
+ """``platform.machine()``, e.g. ``x86_64``; may contain underscores."""
109
+
110
+ system: str
111
+ """lower case ``platform.system()``, e.g. ``linux``."""
112
+
113
+ implementation: str
114
+ """lower case ``platform.python_implementation()``, e.g. ``cpython``."""
115
+
116
+ python: str
117
+ """major.minor Python version, with a ``t`` suffix for freethreading."""
118
+
119
+ dialect: str
120
+ """the dialect name reported by the backend, e.g. ``mariadb``."""
121
+
122
+ driver: str
123
+ """the DBAPI name, e.g. ``psycopg``."""
124
+
125
+ dbapi_flags: Tuple[str, ...]
126
+ """extra DBAPI tokens, in the order they're rendered.
127
+
128
+ ``async`` for an asyncio driver, followed by whatever the dialect
129
+ contributes through the ``profile_platform_tokens`` provisioning hook,
130
+ such as ``file`` for a file based SQLite database or ``cdbapi`` /
131
+ ``pydbapi`` for a DBAPI that ships in both a compiled and a pure
132
+ Python build.
133
+
134
+ """
135
+
136
+ cextensions: bool
137
+ """whether the C / Cython extensions were built."""
138
+
139
+ def __str__(self) -> str:
140
+ return "_".join(
141
+ [
142
+ self.machine,
143
+ self.system,
144
+ self.implementation,
145
+ self.python,
146
+ self.dialect,
147
+ self.driver,
148
+ *self.dbapi_flags,
149
+ _UNICODE_TOKEN,
150
+ self.cext_token,
151
+ ]
152
+ )
153
+
154
+ @classmethod
155
+ def parse(cls, key: str) -> PlatformKey:
156
+ """Parse a platform key string.
157
+
158
+ Raises ``ValueError`` if the key isn't in the format written by
159
+ :meth:`.PlatformKey.__str__`.
160
+
161
+ """
162
+
163
+ tokens = key.split("_")
164
+
165
+ if tokens[-1] not in ("cextensions", "nocextensions"):
166
+ raise ValueError(f"unrecognized cextensions token in {key!r}")
167
+ cextensions = tokens.pop() == "cextensions"
168
+
169
+ if tokens[-1] != _UNICODE_TOKEN:
170
+ raise ValueError(f"unrecognized {_UNICODE_TOKEN} token in {key!r}")
171
+ tokens.pop()
172
+
173
+ for idx, token in enumerate(tokens):
174
+ if _PY_VERSION.match(token):
175
+ break
176
+ else:
177
+ raise ValueError(f"no python version found in {key!r}")
178
+
179
+ if idx < 3 or len(tokens) < idx + 3:
180
+ raise ValueError(f"can't parse platform key {key!r}")
181
+
182
+ return cls(
183
+ machine="_".join(tokens[: idx - 2]),
184
+ system=tokens[idx - 2],
185
+ implementation=tokens[idx - 1],
186
+ python=tokens[idx],
187
+ dialect=tokens[idx + 1],
188
+ driver=tokens[idx + 2],
189
+ dbapi_flags=tuple(tokens[idx + 3 :]),
190
+ cextensions=cextensions,
191
+ )
192
+
193
+ @property
194
+ def database(self) -> str:
195
+ """the ``--db`` name that would regenerate this key."""
196
+
197
+ return DB_TOKEN_TO_DATABASE.get(self.dialect, self.dialect)
198
+
199
+ @property
200
+ def cext_token(self) -> str:
201
+ return "cextensions" if self.cextensions else "nocextensions"
202
+
203
+
204
+ class ProfilesFile:
205
+ """The parsed contents of ``test/profiles.txt``.
206
+
207
+ The entries are reached through the accessors below rather than through
208
+ the underlying dictionary; :meth:`.ProfilesFile.setdefault_counts` and
209
+ :meth:`.ProfilesFile.counts_for` hand back the live list of call counts
210
+ for a test on a platform, which the caller is free to mutate in place,
211
+ and :meth:`.ProfilesFile.write` then serializes whatever is present.
212
+
213
+ """
214
+
215
+ path: str
216
+
217
+ _data: Dict[TestKey, Dict[PlatformKey, List[int]]]
218
+ """test key -> platform key -> call counts."""
219
+
220
+ linenos: Dict[Tuple[TestKey, PlatformKey], int]
221
+ """(test key, platform key) -> one based line number as read."""
222
+
223
+ def __init__(self, path: Union[str, os.PathLike[str]]):
224
+ self.path = os.path.abspath(path)
225
+ self._data = {}
226
+ self.linenos = {}
227
+ self.read()
228
+
229
+ def read(self) -> None:
230
+ """Populate from the file, if it exists.
231
+
232
+ Raises ``ValueError`` for a line that isn't in the format written
233
+ by :meth:`.ProfilesFile.write`, including a platform key that
234
+ :meth:`.PlatformKey.parse` doesn't recognize.
235
+
236
+ """
237
+
238
+ self._data.clear()
239
+ self.linenos.clear()
240
+
241
+ try:
242
+ profile_f = open(self.path)
243
+ except OSError:
244
+ return
245
+
246
+ with profile_f:
247
+ for lineno, line in enumerate(profile_f, 1):
248
+ line = line.strip()
249
+ if not line or line.startswith("#"):
250
+ continue
251
+
252
+ try:
253
+ test_key, raw_key, counts = line.split()
254
+ platform_key = PlatformKey.parse(raw_key)
255
+ call_counts = [int(count) for count in counts.split(",")]
256
+ except ValueError as ve:
257
+ raise ValueError(
258
+ f"{self.path}:{lineno}: can't parse {line!r}: {ve}"
259
+ ) from ve
260
+
261
+ self._data.setdefault(test_key, {})[platform_key] = call_counts
262
+ self.linenos[test_key, platform_key] = lineno
263
+
264
+ def write(self) -> None:
265
+ """Rewrite the file from what's currently recorded."""
266
+
267
+ with open(self.path, "w") as profile_f:
268
+ profile_f.write(HEADER)
269
+ for test_key in sorted(self._data):
270
+ per_fn = self._data[test_key]
271
+ profile_f.write("\n# TEST: %s\n\n" % test_key)
272
+ for platform_key in sorted(per_fn, key=str):
273
+ counts = ",".join(
274
+ str(count) for count in per_fn[platform_key]
275
+ )
276
+ profile_f.write(
277
+ "%s %s %s\n" % (test_key, platform_key, counts)
278
+ )
279
+
280
+ def test_keys(self) -> KeysView[TestKey]:
281
+ """All test keys present in the file."""
282
+
283
+ return self._data.keys()
284
+
285
+ def platforms_for(self, test_key: TestKey) -> KeysView[PlatformKey]:
286
+ """The platform keys recorded for one test."""
287
+
288
+ return self._data.get(test_key, _EMPTY_COUNTS).keys()
289
+
290
+ def counts_for(
291
+ self, test_key: TestKey, platform_key: PlatformKey
292
+ ) -> Optional[List[int]]:
293
+ """The call counts recorded for a test on a platform, or ``None``.
294
+
295
+ The list returned is the one stored here; mutating it in place
296
+ updates what :meth:`.ProfilesFile.write` will emit.
297
+
298
+ """
299
+
300
+ return self._data.get(test_key, _EMPTY_COUNTS).get(platform_key)
301
+
302
+ def setdefault_counts(
303
+ self, test_key: TestKey, platform_key: PlatformKey
304
+ ) -> List[int]:
305
+ """Like :meth:`.ProfilesFile.counts_for`, adding an empty entry for
306
+ the test and platform if there isn't one yet.
307
+
308
+ """
309
+
310
+ return self._data.setdefault(test_key, {}).setdefault(platform_key, [])
311
+
312
+ def remove_entry(
313
+ self, test_key: TestKey, platform_key: PlatformKey
314
+ ) -> None:
315
+ """Drop one test / platform entry.
316
+
317
+ The test itself is dropped once its last platform is gone.
318
+
319
+ """
320
+
321
+ per_fn = self._data.get(test_key)
322
+ if per_fn is None:
323
+ return
324
+ per_fn.pop(platform_key, None)
325
+ if not per_fn:
326
+ del self._data[test_key]
327
+
328
+ def remove_test(self, test_key: TestKey) -> int:
329
+ """Drop every entry for one test, returning how many there were."""
330
+
331
+ return len(self._data.pop(test_key, {}))
332
+
333
+ def platform_keys(self) -> Set[PlatformKey]:
334
+ """All platform keys present anywhere in the file."""
335
+
336
+ return {
337
+ platform_key
338
+ for per_fn in self._data.values()
339
+ for platform_key in per_fn
340
+ }
341
+
342
+ def entry_count(self) -> int:
343
+ """Total number of recorded lines."""
344
+
345
+ return sum(len(per_fn) for per_fn in self._data.values())
346
+
347
+ def lineno_for(
348
+ self, test_key: TestKey, platform_key: PlatformKey
349
+ ) -> Optional[int]:
350
+ return self.linenos.get((test_key, platform_key))
@@ -0,0 +1,294 @@
1
+ # testing/profiling.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: allow-untyped-calls
8
+ #
9
+ # allow-untyped-calls is for sqlalchemy.testing.config, which is itself
10
+ # not typed.
11
+
12
+
13
+ """Profiling support for unit and performance tests.
14
+
15
+ These are special purpose profiling methods which operate
16
+ in a more fine-grained way than nose's profiling plugin.
17
+
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import collections
23
+ import contextlib
24
+ import os
25
+ import platform
26
+ import pstats
27
+ import re
28
+ import sys
29
+ from typing import Any
30
+ from typing import Callable
31
+ from typing import DefaultDict
32
+ from typing import Generator
33
+ from typing import Optional
34
+ from typing import Tuple
35
+
36
+ from . import config
37
+ from . import provision
38
+ from .profiles_file import PlatformKey
39
+ from .profiles_file import ProfilesFile
40
+ from .profiles_file import TestKey
41
+ from .util import gc_collect
42
+ from ..util import freethreading
43
+ from ..util import has_compiled_ext
44
+
45
+ try:
46
+ import cProfile
47
+ except ImportError:
48
+ cProfile = None # type: ignore[assignment]
49
+
50
+ _profile_stats: ProfileStatsFile = None # type: ignore[assignment]
51
+ """global ProfileStatsFileInstance.
52
+
53
+ plugin_base assigns this at the start of all tests.
54
+
55
+ """
56
+
57
+
58
+ _current_test: TestKey = None # type: ignore[assignment]
59
+ """String id of current test.
60
+
61
+ plugin_base assigns this at the start of each test using
62
+ _start_current_test.
63
+
64
+ """
65
+
66
+
67
+ def _start_current_test(id_: TestKey) -> None:
68
+ global _current_test
69
+ _current_test = id_
70
+
71
+ if _profile_stats.force_write:
72
+ _profile_stats.reset_count()
73
+
74
+
75
+ class ProfileStatsFile:
76
+ """Store per-platform/fn profiling results in a file.
77
+
78
+ There was no json module available when this was written, but now
79
+ the file format which is very deterministically line oriented is kind of
80
+ handy in any case for diffs and merges.
81
+
82
+ The parsing and rendering of the file itself, as well as of the platform
83
+ keys used within it, is in :mod:`.testing.profiles_file`, which is shared
84
+ with ``tools/profiles.py``. This class adds the bookkeeping needed while
85
+ the test suite runs.
86
+
87
+ """
88
+
89
+ def __init__(
90
+ self,
91
+ filename: str,
92
+ sort: str = "cumulative",
93
+ dump: Optional[str] = None,
94
+ ) -> None:
95
+ self.force_write = (
96
+ config.options is not None and config.options.force_write_profiles
97
+ )
98
+ self.write = self.force_write or (
99
+ config.options is not None and config.options.write_profiles
100
+ )
101
+ self.profiles = ProfilesFile(filename)
102
+ self.fname = self.profiles.path
103
+ self.short_fname = os.path.split(self.fname)[-1]
104
+ self.dump = dump
105
+ self.sort = sort
106
+
107
+ # (test key, platform key) -> number of counts consumed so far
108
+ # within the current test
109
+ self._current_counts: DefaultDict[Tuple[TestKey, PlatformKey], int] = (
110
+ collections.defaultdict(int)
111
+ )
112
+
113
+ if self.write:
114
+ # rewrite for the case where features changed,
115
+ # etc.
116
+ self._write()
117
+
118
+ @property
119
+ def platform_key(self) -> PlatformKey:
120
+ db = config.db
121
+ assert db is not None, "no database configured"
122
+
123
+ dbapi_flags = []
124
+ if db.dialect.is_async:
125
+ dbapi_flags.append("async")
126
+
127
+ # anything else that moves the counts and that only the dialect
128
+ # knows about, e.g. whether the DBAPI loaded its C accelerator
129
+ dbapi_flags.extend(provision.profile_platform_tokens(db))
130
+
131
+ # major.minor only; the micro version isn't part of the key
132
+ py_version = f"{sys.version_info.major}.{sys.version_info.minor}"
133
+ if freethreading:
134
+ py_version += "t"
135
+
136
+ return PlatformKey(
137
+ machine=platform.machine(),
138
+ system=platform.system().lower(),
139
+ implementation=platform.python_implementation().lower(),
140
+ python=py_version,
141
+ dialect=db.name,
142
+ driver=db.driver,
143
+ dbapi_flags=tuple(dbapi_flags),
144
+ cextensions=has_compiled_ext(),
145
+ )
146
+
147
+ def has_stats(self) -> bool:
148
+ return (
149
+ self.profiles.counts_for(_current_test, self.platform_key)
150
+ is not None
151
+ )
152
+
153
+ def result(self, callcount: int) -> Optional[Tuple[Optional[int], int]]:
154
+ test_key = _current_test
155
+ platform_key = self.platform_key
156
+
157
+ counts = self.profiles.setdefault_counts(test_key, platform_key)
158
+ current_count = self._current_counts[test_key, platform_key]
159
+
160
+ result: Optional[Tuple[Optional[int], int]]
161
+ if len(counts) <= current_count:
162
+ counts.append(callcount)
163
+ if self.write:
164
+ self._write()
165
+ result = None
166
+ else:
167
+ result = (
168
+ self.profiles.lineno_for(test_key, platform_key),
169
+ counts[current_count],
170
+ )
171
+ self._current_counts[test_key, platform_key] = current_count + 1
172
+ return result
173
+
174
+ def reset_count(self) -> None:
175
+ counts = self.profiles.counts_for(_current_test, self.platform_key)
176
+ if counts is not None:
177
+ counts[:] = []
178
+
179
+ def replace(self, callcount: int) -> None:
180
+ test_key = _current_test
181
+ platform_key = self.platform_key
182
+
183
+ counts = self.profiles.counts_for(test_key, platform_key)
184
+ assert counts, "replace() called before result() recorded a count"
185
+
186
+ current_count = self._current_counts[test_key, platform_key]
187
+ if current_count < len(counts):
188
+ counts[current_count - 1] = callcount
189
+ else:
190
+ counts[-1] = callcount
191
+ if self.write:
192
+ self._write()
193
+
194
+ def _write(self) -> None:
195
+ print("Writing profile file %s" % self.fname)
196
+ self.profiles.write()
197
+
198
+
199
+ def function_call_count(
200
+ variance: float = 0.05, times: int = 1, warmup: int = 0
201
+ ) -> Callable[..., Any]:
202
+ """Assert a target for a test case's function call count.
203
+
204
+ The main purpose of this assertion is to detect changes in
205
+ callcounts for various functions - the actual number is not as important.
206
+ Callcounts are stored in a file keyed to Python version and OS platform
207
+ information. This file is generated automatically for new tests,
208
+ and versioned so that unexpected changes in callcounts will be detected.
209
+
210
+ """
211
+
212
+ from sqlalchemy.util import decorator
213
+
214
+ @decorator
215
+ def wrap(fn: Callable[..., Any], *args: Any, **kw: Any) -> Any:
216
+ for warm in range(warmup):
217
+ fn(*args, **kw)
218
+
219
+ timerange = range(times)
220
+ with count_functions(variance=variance):
221
+ for time in timerange:
222
+ rv = fn(*args, **kw)
223
+ return rv
224
+
225
+ return wrap
226
+
227
+
228
+ @contextlib.contextmanager
229
+ def count_functions(variance: float = 0.05) -> Generator[None, None, None]:
230
+ if cProfile is None:
231
+ raise config._skip_test_exception("cProfile is not installed")
232
+
233
+ if not _profile_stats.has_stats() and not _profile_stats.write:
234
+ config.skip_test(
235
+ "No profiling stats available on this "
236
+ "platform for this function. Run tests with "
237
+ "--write-profiles to add statistics to %s for "
238
+ "this platform." % _profile_stats.short_fname
239
+ )
240
+
241
+ gc_collect()
242
+
243
+ pr = cProfile.Profile()
244
+ pr.enable()
245
+ # began = time.time()
246
+ yield
247
+ # ended = time.time()
248
+ pr.disable()
249
+
250
+ # s = StringIO()
251
+ stats = pstats.Stats(pr, stream=sys.stdout)
252
+
253
+ # timespent = ended - began
254
+ callcount = stats.total_calls # type: ignore[attr-defined]
255
+
256
+ expected = _profile_stats.result(callcount)
257
+
258
+ if expected is None:
259
+ expected_count = None
260
+ else:
261
+ line_no, expected_count = expected
262
+
263
+ print("Pstats calls: %d Expected %s" % (callcount, expected_count))
264
+ stats.sort_stats(*re.split(r"[, ]", _profile_stats.sort))
265
+ stats.print_stats()
266
+ if _profile_stats.dump:
267
+ base, ext = os.path.splitext(_profile_stats.dump)
268
+ test_name = _current_test.split(".")[-1]
269
+ dumpfile = "%s_%s%s" % (base, test_name, ext or ".profile")
270
+ stats.dump_stats(dumpfile)
271
+ print("Dumped stats to file %s" % dumpfile)
272
+ # stats.print_callers()
273
+ if _profile_stats.force_write:
274
+ _profile_stats.replace(callcount)
275
+ elif expected_count:
276
+ deviance = int(callcount * variance)
277
+ failed = abs(callcount - expected_count) > deviance
278
+
279
+ if failed:
280
+ if _profile_stats.write:
281
+ _profile_stats.replace(callcount)
282
+ else:
283
+ raise AssertionError(
284
+ "Adjusted function call count %s not within %s%% "
285
+ "of expected %s, platform %s. Rerun with "
286
+ "--write-profiles to "
287
+ "regenerate this callcount."
288
+ % (
289
+ callcount,
290
+ (variance * 100),
291
+ expected_count,
292
+ _profile_stats.platform_key,
293
+ )
294
+ )