SQLAlchemy 2.1.0rc1__cp315-cp315-win_arm64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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-win_arm64.pyd +0 -0
  77. sqlalchemy/engine/_processors_cy.py +92 -0
  78. sqlalchemy/engine/_result_cy.cp315-win_arm64.pyd +0 -0
  79. sqlalchemy/engine/_result_cy.py +711 -0
  80. sqlalchemy/engine/_row_cy.cp315-win_arm64.pyd +0 -0
  81. sqlalchemy/engine/_row_cy.py +232 -0
  82. sqlalchemy/engine/_util_cy.cp315-win_arm64.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-win_arm64.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-win_arm64.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-win_arm64.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-win_arm64.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,558 @@
1
+ # ext/baked.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
+ """Baked query extension.
11
+
12
+ Provides a creational pattern for the :class:`.query.Query` object which
13
+ allows the fully constructed object, Core select statement, and string
14
+ compiled result to be fully cached.
15
+
16
+
17
+ """
18
+
19
+ import collections.abc as collections_abc
20
+ import logging
21
+
22
+ from .. import exc as sa_exc
23
+ from .. import util
24
+ from ..orm import exc as orm_exc
25
+ from ..orm.query import Query
26
+ from ..orm.session import Session
27
+ from ..sql import func
28
+ from ..sql import literal_column
29
+ from ..sql import util as sql_util
30
+
31
+ log = logging.getLogger(__name__)
32
+
33
+
34
+ class Bakery:
35
+ """Callable which returns a :class:`.BakedQuery`.
36
+
37
+ This object is returned by the class method
38
+ :meth:`.BakedQuery.bakery`. It exists as an object
39
+ so that the "cache" can be easily inspected.
40
+
41
+ """
42
+
43
+ __slots__ = "cls", "cache"
44
+
45
+ def __init__(self, cls_, cache):
46
+ self.cls = cls_
47
+ self.cache = cache
48
+
49
+ def __call__(self, initial_fn, *args):
50
+ return self.cls(self.cache, initial_fn, args)
51
+
52
+
53
+ class BakedQuery:
54
+ """A builder object for :class:`.query.Query` objects."""
55
+
56
+ __slots__ = "steps", "_bakery", "_cache_key", "_spoiled"
57
+
58
+ def __init__(self, bakery, initial_fn, args=()):
59
+ self._cache_key = ()
60
+ self._update_cache_key(initial_fn, args)
61
+ self.steps = [initial_fn]
62
+ self._spoiled = False
63
+ self._bakery = bakery
64
+
65
+ @classmethod
66
+ def bakery(cls, size=200, _size_alert=None):
67
+ """Construct a new bakery.
68
+
69
+ :return: an instance of :class:`.Bakery`
70
+
71
+ """
72
+
73
+ return Bakery(cls, util.LRUCache(size, size_alert=_size_alert))
74
+
75
+ def _clone(self):
76
+ b1 = BakedQuery.__new__(BakedQuery)
77
+ b1._cache_key = self._cache_key
78
+ b1.steps = list(self.steps)
79
+ b1._bakery = self._bakery
80
+ b1._spoiled = self._spoiled
81
+ return b1
82
+
83
+ def _update_cache_key(self, fn, args=()):
84
+ self._cache_key += (fn.__code__,) + args
85
+
86
+ def __iadd__(self, other):
87
+ if isinstance(other, tuple):
88
+ self.add_criteria(*other)
89
+ else:
90
+ self.add_criteria(other)
91
+ return self
92
+
93
+ def __add__(self, other):
94
+ if isinstance(other, tuple):
95
+ return self.with_criteria(*other)
96
+ else:
97
+ return self.with_criteria(other)
98
+
99
+ def add_criteria(self, fn, *args):
100
+ """Add a criteria function to this :class:`.BakedQuery`.
101
+
102
+ This is equivalent to using the ``+=`` operator to
103
+ modify a :class:`.BakedQuery` in-place.
104
+
105
+ """
106
+ self._update_cache_key(fn, args)
107
+ self.steps.append(fn)
108
+ return self
109
+
110
+ def with_criteria(self, fn, *args):
111
+ """Add a criteria function to a :class:`.BakedQuery` cloned from this
112
+ one.
113
+
114
+ This is equivalent to using the ``+`` operator to
115
+ produce a new :class:`.BakedQuery` with modifications.
116
+
117
+ """
118
+ return self._clone().add_criteria(fn, *args)
119
+
120
+ def for_session(self, session):
121
+ """Return a :class:`_baked.Result` object for this
122
+ :class:`.BakedQuery`.
123
+
124
+ This is equivalent to calling the :class:`.BakedQuery` as a
125
+ Python callable, e.g. ``result = my_baked_query(session)``.
126
+
127
+ """
128
+ return Result(self, session)
129
+
130
+ def __call__(self, session):
131
+ return self.for_session(session)
132
+
133
+ def spoil(self, full=False):
134
+ """Cancel any query caching that will occur on this BakedQuery object.
135
+
136
+ The BakedQuery can continue to be used normally, however additional
137
+ creational functions will not be cached; they will be called
138
+ on every invocation.
139
+
140
+ This is to support the case where a particular step in constructing
141
+ a baked query disqualifies the query from being cacheable, such
142
+ as a variant that relies upon some uncacheable value.
143
+
144
+ :param full: if False, only functions added to this
145
+ :class:`.BakedQuery` object subsequent to the spoil step will be
146
+ non-cached; the state of the :class:`.BakedQuery` up until
147
+ this point will be pulled from the cache. If True, then the
148
+ entire :class:`_query.Query` object is built from scratch each
149
+ time, with all creational functions being called on each
150
+ invocation.
151
+
152
+ """
153
+ if not full and not self._spoiled:
154
+ _spoil_point = self._clone()
155
+ _spoil_point._cache_key += ("_query_only",)
156
+ self.steps = [_spoil_point._retrieve_baked_query]
157
+ self._spoiled = True
158
+ return self
159
+
160
+ def _effective_key(self, session):
161
+ """Return the key that actually goes into the cache dictionary for
162
+ this :class:`.BakedQuery`, taking into account the given
163
+ :class:`.Session`.
164
+
165
+ This basically means we also will include the session's query_class,
166
+ as the actual :class:`_query.Query` object is part of what's cached
167
+ and needs to match the type of :class:`_query.Query` that a later
168
+ session will want to use.
169
+
170
+ """
171
+ return self._cache_key + (session._query_cls,)
172
+
173
+ def _with_lazyload_options(self, options, effective_path, cache_path=None):
174
+ """Cloning version of _add_lazyload_options."""
175
+ q = self._clone()
176
+ q._add_lazyload_options(options, effective_path, cache_path=cache_path)
177
+ return q
178
+
179
+ def _add_lazyload_options(self, options, effective_path, cache_path=None):
180
+ """Used by per-state lazy loaders to add options to the
181
+ "lazy load" query from a parent query.
182
+
183
+ Creates a cache key based on given load path and query options;
184
+ if a repeatable cache key cannot be generated, the query is
185
+ "spoiled" so that it won't use caching.
186
+
187
+ """
188
+
189
+ key = ()
190
+
191
+ if not cache_path:
192
+ cache_path = effective_path
193
+
194
+ for opt in options:
195
+ if opt._is_legacy_option or opt._is_compile_state:
196
+ ck = opt._generate_cache_key()
197
+ if ck is None:
198
+ self.spoil(full=True)
199
+ else:
200
+ assert not ck[1], (
201
+ "loader options with variable bound parameters "
202
+ "not supported with baked queries. Please "
203
+ "use new-style select() statements for cached "
204
+ "ORM queries."
205
+ )
206
+ key += ck[0]
207
+
208
+ self.add_criteria(
209
+ lambda q: q._with_current_path(effective_path).options(*options),
210
+ cache_path.path,
211
+ key,
212
+ )
213
+
214
+ def _retrieve_baked_query(self, session):
215
+ query = self._bakery.get(self._effective_key(session), None)
216
+ if query is None:
217
+ query = self._as_query(session)
218
+ self._bakery[self._effective_key(session)] = query.with_session(
219
+ None
220
+ )
221
+ return query.with_session(session)
222
+
223
+ def _bake(self, session):
224
+ query = self._as_query(session)
225
+ query.session = None
226
+
227
+ # in 1.4, this is where before_compile() event is
228
+ # invoked
229
+ statement = query._statement_20()
230
+
231
+ # if the query is not safe to cache, we still do everything as though
232
+ # we did cache it, since the receiver of _bake() assumes subqueryload
233
+ # context was set up, etc.
234
+ #
235
+ # note also we want to cache the statement itself because this
236
+ # allows the statement itself to hold onto its cache key that is
237
+ # used by the Connection, which in itself is more expensive to
238
+ # generate than what BakedQuery was able to provide in 1.3 and prior
239
+
240
+ if statement._compile_options._bake_ok:
241
+ self._bakery[self._effective_key(session)] = (
242
+ query,
243
+ statement,
244
+ )
245
+
246
+ return query, statement
247
+
248
+ def to_query(self, query_or_session):
249
+ """Return the :class:`_query.Query` object for use as a subquery.
250
+
251
+ This method should be used within the lambda callable being used
252
+ to generate a step of an enclosing :class:`.BakedQuery`. The
253
+ parameter should normally be the :class:`_query.Query` object that
254
+ is passed to the lambda::
255
+
256
+ sub_bq = self.bakery(lambda s: s.query(User.name))
257
+ sub_bq += lambda q: q.filter(User.id == Address.user_id).correlate(Address)
258
+
259
+ main_bq = self.bakery(lambda s: s.query(Address))
260
+ main_bq += lambda q: q.filter(sub_bq.to_query(q).exists())
261
+
262
+ In the case where the subquery is used in the first callable against
263
+ a :class:`.Session`, the :class:`.Session` is also accepted::
264
+
265
+ sub_bq = self.bakery(lambda s: s.query(User.name))
266
+ sub_bq += lambda q: q.filter(User.id == Address.user_id).correlate(Address)
267
+
268
+ main_bq = self.bakery(
269
+ lambda s: s.query(Address.id, sub_bq.to_query(q).scalar_subquery())
270
+ )
271
+
272
+ :param query_or_session: a :class:`_query.Query` object or a class
273
+ :class:`.Session` object, that is assumed to be within the context
274
+ of an enclosing :class:`.BakedQuery` callable.
275
+
276
+ """ # noqa: E501
277
+
278
+ if isinstance(query_or_session, Session):
279
+ session = query_or_session
280
+ elif isinstance(query_or_session, Query):
281
+ session = query_or_session.session
282
+ if session is None:
283
+ raise sa_exc.ArgumentError(
284
+ "Given Query needs to be associated with a Session"
285
+ )
286
+ else:
287
+ raise TypeError(
288
+ "Query or Session object expected, got %r."
289
+ % type(query_or_session)
290
+ )
291
+ return self._as_query(session)
292
+
293
+ def _as_query(self, session):
294
+ query = self.steps[0](session)
295
+
296
+ for step in self.steps[1:]:
297
+ query = step(query)
298
+
299
+ return query
300
+
301
+
302
+ class Result:
303
+ """Invokes a :class:`.BakedQuery` against a :class:`.Session`.
304
+
305
+ The :class:`_baked.Result` object is where the actual :class:`.query.Query`
306
+ object gets created, or retrieved from the cache,
307
+ against a target :class:`.Session`, and is then invoked for results.
308
+
309
+ """
310
+
311
+ __slots__ = "bq", "session", "_params", "_post_criteria"
312
+
313
+ def __init__(self, bq, session):
314
+ self.bq = bq
315
+ self.session = session
316
+ self._params = {}
317
+ self._post_criteria = []
318
+
319
+ def params(self, *args, **kw):
320
+ """Specify parameters to be replaced into the string SQL statement."""
321
+
322
+ if len(args) == 1:
323
+ kw.update(args[0])
324
+ elif len(args) > 0:
325
+ raise sa_exc.ArgumentError(
326
+ "params() takes zero or one positional argument, "
327
+ "which is a dictionary."
328
+ )
329
+ self._params.update(kw)
330
+ return self
331
+
332
+ def _using_post_criteria(self, fns):
333
+ if fns:
334
+ self._post_criteria.extend(fns)
335
+ return self
336
+
337
+ def with_post_criteria(self, fn):
338
+ """Add a criteria function that will be applied post-cache.
339
+
340
+ This adds a function that will be run against the
341
+ :class:`_query.Query` object after it is retrieved from the
342
+ cache. This currently includes **only** the
343
+ :meth:`_query.Query.params` and :meth:`_query.Query.execution_options`
344
+ methods.
345
+
346
+ .. warning:: :meth:`_baked.Result.with_post_criteria`
347
+ functions are applied
348
+ to the :class:`_query.Query`
349
+ object **after** the query's SQL statement
350
+ object has been retrieved from the cache. Only
351
+ :meth:`_query.Query.params` and
352
+ :meth:`_query.Query.execution_options`
353
+ methods should be used.
354
+
355
+ """
356
+ return self._using_post_criteria([fn])
357
+
358
+ def _as_query(self):
359
+ q = self.bq._as_query(self.session).params(self._params)
360
+ for fn in self._post_criteria:
361
+ q = fn(q)
362
+ return q
363
+
364
+ def __str__(self):
365
+ return str(self._as_query())
366
+
367
+ def __iter__(self):
368
+ return self._iter().__iter__()
369
+
370
+ def _iter(self):
371
+ bq = self.bq
372
+
373
+ if not self.session.enable_baked_queries or bq._spoiled:
374
+ return self._as_query()._iter()
375
+
376
+ query, statement = bq._bakery.get(
377
+ bq._effective_key(self.session), (None, None)
378
+ )
379
+ if query is None:
380
+ query, statement = bq._bake(self.session)
381
+
382
+ if self._params:
383
+ q = query.params(self._params)
384
+ else:
385
+ q = query
386
+ for fn in self._post_criteria:
387
+ q = fn(q)
388
+
389
+ params = q._params
390
+ execution_options = dict(q._execution_options)
391
+ execution_options.update(
392
+ {
393
+ "_sa_orm_load_options": q.load_options,
394
+ "compiled_cache": bq._bakery,
395
+ }
396
+ )
397
+
398
+ result = self.session.execute(
399
+ statement, params, execution_options=execution_options
400
+ )
401
+ if result._attributes.get("is_single_entity", False):
402
+ result = result.scalars()
403
+
404
+ if result._attributes.get("filtered", False):
405
+ result = result.unique()
406
+
407
+ return result
408
+
409
+ def count(self):
410
+ """return the 'count'.
411
+
412
+ Equivalent to :meth:`_query.Query.count`.
413
+
414
+ Note this uses a subquery to ensure an accurate count regardless
415
+ of the structure of the original statement.
416
+
417
+ """
418
+
419
+ col = func.count(literal_column("*"))
420
+ bq = self.bq.with_criteria(lambda q: q._legacy_from_self(col))
421
+ return bq.for_session(self.session).params(self._params).scalar()
422
+
423
+ def scalar(self):
424
+ """Return the first element of the first result or None
425
+ if no rows present. If multiple rows are returned,
426
+ raises MultipleResultsFound.
427
+
428
+ Equivalent to :meth:`_query.Query.scalar`.
429
+
430
+ """
431
+ try:
432
+ ret = self.one()
433
+ if not isinstance(ret, collections_abc.Sequence):
434
+ return ret
435
+ return ret[0]
436
+ except orm_exc.NoResultFound:
437
+ return None
438
+
439
+ def first(self):
440
+ """Return the first row.
441
+
442
+ Equivalent to :meth:`_query.Query.first`.
443
+
444
+ """
445
+
446
+ bq = self.bq.with_criteria(lambda q: q.slice(0, 1))
447
+ return (
448
+ bq.for_session(self.session)
449
+ .params(self._params)
450
+ ._using_post_criteria(self._post_criteria)
451
+ ._iter()
452
+ .first()
453
+ )
454
+
455
+ def one(self):
456
+ """Return exactly one result or raise an exception.
457
+
458
+ Equivalent to :meth:`_query.Query.one`.
459
+
460
+ """
461
+ return self._iter().one()
462
+
463
+ def one_or_none(self):
464
+ """Return one or zero results, or raise an exception for multiple
465
+ rows.
466
+
467
+ Equivalent to :meth:`_query.Query.one_or_none`.
468
+
469
+ """
470
+ return self._iter().one_or_none()
471
+
472
+ def all(self):
473
+ """Return all rows.
474
+
475
+ Equivalent to :meth:`_query.Query.all`.
476
+
477
+ """
478
+ return self._iter().all()
479
+
480
+ def get(self, ident):
481
+ """Retrieve an object based on identity.
482
+
483
+ Equivalent to :meth:`_query.Query.get`.
484
+
485
+ """
486
+
487
+ query = self.bq.steps[0](self.session)
488
+ return query._get_impl(ident, self._load_on_pk_identity)
489
+
490
+ def _load_on_pk_identity(self, session, query, primary_key_identity, **kw):
491
+ """Load the given primary key identity from the database."""
492
+
493
+ mapper = query._raw_columns[0]._annotations["parententity"]
494
+
495
+ _get_clause, _get_params = mapper._get_clause
496
+
497
+ def setup(query):
498
+ _lcl_get_clause = _get_clause
499
+ q = query._clone()
500
+ q._get_condition()
501
+ q._order_by = None
502
+
503
+ # None present in ident - turn those comparisons
504
+ # into "IS NULL"
505
+ if None in primary_key_identity:
506
+ nones = {
507
+ _get_params[col].key
508
+ for col, value in zip(
509
+ mapper.primary_key, primary_key_identity
510
+ )
511
+ if value is None
512
+ }
513
+ _lcl_get_clause = sql_util.adapt_criterion_to_null(
514
+ _lcl_get_clause, nones
515
+ )
516
+
517
+ # TODO: can mapper._get_clause be pre-adapted?
518
+ q._where_criteria = (
519
+ sql_util._deep_annotate(_lcl_get_clause, {"_orm_adapt": True}),
520
+ )
521
+
522
+ for fn in self._post_criteria:
523
+ q = fn(q)
524
+ return q
525
+
526
+ # cache the query against a key that includes
527
+ # which positions in the primary key are NULL
528
+ # (remember, we can map to an OUTER JOIN)
529
+ bq = self.bq
530
+
531
+ # add the clause we got from mapper._get_clause to the cache
532
+ # key so that if a race causes multiple calls to _get_clause,
533
+ # we've cached on ours
534
+ bq = bq._clone()
535
+ bq._cache_key += (_get_clause,)
536
+
537
+ bq = bq.with_criteria(
538
+ setup, tuple(elem is None for elem in primary_key_identity)
539
+ )
540
+
541
+ params = {
542
+ _get_params[primary_key].key: id_val
543
+ for id_val, primary_key in zip(
544
+ primary_key_identity, mapper.primary_key
545
+ )
546
+ }
547
+
548
+ result = list(bq.for_session(self.session).params(**params))
549
+ l = len(result)
550
+ if l > 1:
551
+ raise orm_exc.MultipleResultsFound()
552
+ elif l:
553
+ return result[0]
554
+ else:
555
+ return None
556
+
557
+
558
+ bakery = BakedQuery.bakery