SQLAlchemy 2.0.47__cp313-cp313t-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 (274) hide show
  1. sqlalchemy/__init__.py +283 -0
  2. sqlalchemy/connectors/__init__.py +18 -0
  3. sqlalchemy/connectors/aioodbc.py +184 -0
  4. sqlalchemy/connectors/asyncio.py +429 -0
  5. sqlalchemy/connectors/pyodbc.py +250 -0
  6. sqlalchemy/cyextension/__init__.py +6 -0
  7. sqlalchemy/cyextension/collections.cp313t-win32.pyd +0 -0
  8. sqlalchemy/cyextension/collections.pyx +409 -0
  9. sqlalchemy/cyextension/immutabledict.cp313t-win32.pyd +0 -0
  10. sqlalchemy/cyextension/immutabledict.pxd +8 -0
  11. sqlalchemy/cyextension/immutabledict.pyx +133 -0
  12. sqlalchemy/cyextension/processors.cp313t-win32.pyd +0 -0
  13. sqlalchemy/cyextension/processors.pyx +68 -0
  14. sqlalchemy/cyextension/resultproxy.cp313t-win32.pyd +0 -0
  15. sqlalchemy/cyextension/resultproxy.pyx +102 -0
  16. sqlalchemy/cyextension/util.cp313t-win32.pyd +0 -0
  17. sqlalchemy/cyextension/util.pyx +90 -0
  18. sqlalchemy/dialects/__init__.py +62 -0
  19. sqlalchemy/dialects/_typing.py +30 -0
  20. sqlalchemy/dialects/mssql/__init__.py +88 -0
  21. sqlalchemy/dialects/mssql/aioodbc.py +63 -0
  22. sqlalchemy/dialects/mssql/base.py +4093 -0
  23. sqlalchemy/dialects/mssql/information_schema.py +285 -0
  24. sqlalchemy/dialects/mssql/json.py +129 -0
  25. sqlalchemy/dialects/mssql/provision.py +185 -0
  26. sqlalchemy/dialects/mssql/pymssql.py +126 -0
  27. sqlalchemy/dialects/mssql/pyodbc.py +760 -0
  28. sqlalchemy/dialects/mysql/__init__.py +104 -0
  29. sqlalchemy/dialects/mysql/aiomysql.py +250 -0
  30. sqlalchemy/dialects/mysql/asyncmy.py +231 -0
  31. sqlalchemy/dialects/mysql/base.py +3949 -0
  32. sqlalchemy/dialects/mysql/cymysql.py +106 -0
  33. sqlalchemy/dialects/mysql/dml.py +225 -0
  34. sqlalchemy/dialects/mysql/enumerated.py +282 -0
  35. sqlalchemy/dialects/mysql/expression.py +146 -0
  36. sqlalchemy/dialects/mysql/json.py +91 -0
  37. sqlalchemy/dialects/mysql/mariadb.py +72 -0
  38. sqlalchemy/dialects/mysql/mariadbconnector.py +322 -0
  39. sqlalchemy/dialects/mysql/mysqlconnector.py +302 -0
  40. sqlalchemy/dialects/mysql/mysqldb.py +314 -0
  41. sqlalchemy/dialects/mysql/provision.py +153 -0
  42. sqlalchemy/dialects/mysql/pymysql.py +158 -0
  43. sqlalchemy/dialects/mysql/pyodbc.py +157 -0
  44. sqlalchemy/dialects/mysql/reflection.py +727 -0
  45. sqlalchemy/dialects/mysql/reserved_words.py +570 -0
  46. sqlalchemy/dialects/mysql/types.py +835 -0
  47. sqlalchemy/dialects/oracle/__init__.py +81 -0
  48. sqlalchemy/dialects/oracle/base.py +3802 -0
  49. sqlalchemy/dialects/oracle/cx_oracle.py +1555 -0
  50. sqlalchemy/dialects/oracle/dictionary.py +507 -0
  51. sqlalchemy/dialects/oracle/oracledb.py +941 -0
  52. sqlalchemy/dialects/oracle/provision.py +297 -0
  53. sqlalchemy/dialects/oracle/types.py +316 -0
  54. sqlalchemy/dialects/oracle/vector.py +365 -0
  55. sqlalchemy/dialects/postgresql/__init__.py +167 -0
  56. sqlalchemy/dialects/postgresql/_psycopg_common.py +189 -0
  57. sqlalchemy/dialects/postgresql/array.py +519 -0
  58. sqlalchemy/dialects/postgresql/asyncpg.py +1284 -0
  59. sqlalchemy/dialects/postgresql/base.py +5378 -0
  60. sqlalchemy/dialects/postgresql/dml.py +339 -0
  61. sqlalchemy/dialects/postgresql/ext.py +540 -0
  62. sqlalchemy/dialects/postgresql/hstore.py +406 -0
  63. sqlalchemy/dialects/postgresql/json.py +404 -0
  64. sqlalchemy/dialects/postgresql/named_types.py +524 -0
  65. sqlalchemy/dialects/postgresql/operators.py +129 -0
  66. sqlalchemy/dialects/postgresql/pg8000.py +669 -0
  67. sqlalchemy/dialects/postgresql/pg_catalog.py +326 -0
  68. sqlalchemy/dialects/postgresql/provision.py +183 -0
  69. sqlalchemy/dialects/postgresql/psycopg.py +862 -0
  70. sqlalchemy/dialects/postgresql/psycopg2.py +892 -0
  71. sqlalchemy/dialects/postgresql/psycopg2cffi.py +61 -0
  72. sqlalchemy/dialects/postgresql/ranges.py +1031 -0
  73. sqlalchemy/dialects/postgresql/types.py +313 -0
  74. sqlalchemy/dialects/sqlite/__init__.py +57 -0
  75. sqlalchemy/dialects/sqlite/aiosqlite.py +482 -0
  76. sqlalchemy/dialects/sqlite/base.py +3056 -0
  77. sqlalchemy/dialects/sqlite/dml.py +263 -0
  78. sqlalchemy/dialects/sqlite/json.py +92 -0
  79. sqlalchemy/dialects/sqlite/provision.py +229 -0
  80. sqlalchemy/dialects/sqlite/pysqlcipher.py +157 -0
  81. sqlalchemy/dialects/sqlite/pysqlite.py +756 -0
  82. sqlalchemy/dialects/type_migration_guidelines.txt +145 -0
  83. sqlalchemy/engine/__init__.py +62 -0
  84. sqlalchemy/engine/_py_processors.py +136 -0
  85. sqlalchemy/engine/_py_row.py +128 -0
  86. sqlalchemy/engine/_py_util.py +74 -0
  87. sqlalchemy/engine/base.py +3390 -0
  88. sqlalchemy/engine/characteristics.py +155 -0
  89. sqlalchemy/engine/create.py +893 -0
  90. sqlalchemy/engine/cursor.py +2298 -0
  91. sqlalchemy/engine/default.py +2394 -0
  92. sqlalchemy/engine/events.py +965 -0
  93. sqlalchemy/engine/interfaces.py +3471 -0
  94. sqlalchemy/engine/mock.py +134 -0
  95. sqlalchemy/engine/processors.py +61 -0
  96. sqlalchemy/engine/reflection.py +2102 -0
  97. sqlalchemy/engine/result.py +2399 -0
  98. sqlalchemy/engine/row.py +400 -0
  99. sqlalchemy/engine/strategies.py +16 -0
  100. sqlalchemy/engine/url.py +924 -0
  101. sqlalchemy/engine/util.py +167 -0
  102. sqlalchemy/event/__init__.py +26 -0
  103. sqlalchemy/event/api.py +220 -0
  104. sqlalchemy/event/attr.py +676 -0
  105. sqlalchemy/event/base.py +472 -0
  106. sqlalchemy/event/legacy.py +258 -0
  107. sqlalchemy/event/registry.py +390 -0
  108. sqlalchemy/events.py +17 -0
  109. sqlalchemy/exc.py +832 -0
  110. sqlalchemy/ext/__init__.py +11 -0
  111. sqlalchemy/ext/associationproxy.py +2027 -0
  112. sqlalchemy/ext/asyncio/__init__.py +25 -0
  113. sqlalchemy/ext/asyncio/base.py +281 -0
  114. sqlalchemy/ext/asyncio/engine.py +1471 -0
  115. sqlalchemy/ext/asyncio/exc.py +21 -0
  116. sqlalchemy/ext/asyncio/result.py +965 -0
  117. sqlalchemy/ext/asyncio/scoping.py +1599 -0
  118. sqlalchemy/ext/asyncio/session.py +1947 -0
  119. sqlalchemy/ext/automap.py +1701 -0
  120. sqlalchemy/ext/baked.py +570 -0
  121. sqlalchemy/ext/compiler.py +600 -0
  122. sqlalchemy/ext/declarative/__init__.py +65 -0
  123. sqlalchemy/ext/declarative/extensions.py +564 -0
  124. sqlalchemy/ext/horizontal_shard.py +478 -0
  125. sqlalchemy/ext/hybrid.py +1535 -0
  126. sqlalchemy/ext/indexable.py +364 -0
  127. sqlalchemy/ext/instrumentation.py +450 -0
  128. sqlalchemy/ext/mutable.py +1085 -0
  129. sqlalchemy/ext/mypy/__init__.py +6 -0
  130. sqlalchemy/ext/mypy/apply.py +324 -0
  131. sqlalchemy/ext/mypy/decl_class.py +515 -0
  132. sqlalchemy/ext/mypy/infer.py +590 -0
  133. sqlalchemy/ext/mypy/names.py +335 -0
  134. sqlalchemy/ext/mypy/plugin.py +303 -0
  135. sqlalchemy/ext/mypy/util.py +357 -0
  136. sqlalchemy/ext/orderinglist.py +439 -0
  137. sqlalchemy/ext/serializer.py +185 -0
  138. sqlalchemy/future/__init__.py +16 -0
  139. sqlalchemy/future/engine.py +15 -0
  140. sqlalchemy/inspection.py +174 -0
  141. sqlalchemy/log.py +288 -0
  142. sqlalchemy/orm/__init__.py +171 -0
  143. sqlalchemy/orm/_orm_constructors.py +2661 -0
  144. sqlalchemy/orm/_typing.py +179 -0
  145. sqlalchemy/orm/attributes.py +2845 -0
  146. sqlalchemy/orm/base.py +971 -0
  147. sqlalchemy/orm/bulk_persistence.py +2135 -0
  148. sqlalchemy/orm/clsregistry.py +571 -0
  149. sqlalchemy/orm/collections.py +1627 -0
  150. sqlalchemy/orm/context.py +3334 -0
  151. sqlalchemy/orm/decl_api.py +2004 -0
  152. sqlalchemy/orm/decl_base.py +2192 -0
  153. sqlalchemy/orm/dependency.py +1302 -0
  154. sqlalchemy/orm/descriptor_props.py +1092 -0
  155. sqlalchemy/orm/dynamic.py +300 -0
  156. sqlalchemy/orm/evaluator.py +379 -0
  157. sqlalchemy/orm/events.py +3252 -0
  158. sqlalchemy/orm/exc.py +237 -0
  159. sqlalchemy/orm/identity.py +302 -0
  160. sqlalchemy/orm/instrumentation.py +754 -0
  161. sqlalchemy/orm/interfaces.py +1496 -0
  162. sqlalchemy/orm/loading.py +1686 -0
  163. sqlalchemy/orm/mapped_collection.py +557 -0
  164. sqlalchemy/orm/mapper.py +4444 -0
  165. sqlalchemy/orm/path_registry.py +809 -0
  166. sqlalchemy/orm/persistence.py +1788 -0
  167. sqlalchemy/orm/properties.py +935 -0
  168. sqlalchemy/orm/query.py +3459 -0
  169. sqlalchemy/orm/relationships.py +3508 -0
  170. sqlalchemy/orm/scoping.py +2148 -0
  171. sqlalchemy/orm/session.py +5280 -0
  172. sqlalchemy/orm/state.py +1168 -0
  173. sqlalchemy/orm/state_changes.py +196 -0
  174. sqlalchemy/orm/strategies.py +3470 -0
  175. sqlalchemy/orm/strategy_options.py +2568 -0
  176. sqlalchemy/orm/sync.py +164 -0
  177. sqlalchemy/orm/unitofwork.py +796 -0
  178. sqlalchemy/orm/util.py +2403 -0
  179. sqlalchemy/orm/writeonly.py +674 -0
  180. sqlalchemy/pool/__init__.py +44 -0
  181. sqlalchemy/pool/base.py +1524 -0
  182. sqlalchemy/pool/events.py +375 -0
  183. sqlalchemy/pool/impl.py +588 -0
  184. sqlalchemy/py.typed +0 -0
  185. sqlalchemy/schema.py +69 -0
  186. sqlalchemy/sql/__init__.py +145 -0
  187. sqlalchemy/sql/_dml_constructors.py +132 -0
  188. sqlalchemy/sql/_elements_constructors.py +1872 -0
  189. sqlalchemy/sql/_orm_types.py +20 -0
  190. sqlalchemy/sql/_py_util.py +75 -0
  191. sqlalchemy/sql/_selectable_constructors.py +763 -0
  192. sqlalchemy/sql/_typing.py +482 -0
  193. sqlalchemy/sql/annotation.py +587 -0
  194. sqlalchemy/sql/base.py +2293 -0
  195. sqlalchemy/sql/cache_key.py +1057 -0
  196. sqlalchemy/sql/coercions.py +1404 -0
  197. sqlalchemy/sql/compiler.py +8081 -0
  198. sqlalchemy/sql/crud.py +1752 -0
  199. sqlalchemy/sql/ddl.py +1444 -0
  200. sqlalchemy/sql/default_comparator.py +551 -0
  201. sqlalchemy/sql/dml.py +1850 -0
  202. sqlalchemy/sql/elements.py +5589 -0
  203. sqlalchemy/sql/events.py +458 -0
  204. sqlalchemy/sql/expression.py +159 -0
  205. sqlalchemy/sql/functions.py +2158 -0
  206. sqlalchemy/sql/lambdas.py +1442 -0
  207. sqlalchemy/sql/naming.py +209 -0
  208. sqlalchemy/sql/operators.py +2623 -0
  209. sqlalchemy/sql/roles.py +323 -0
  210. sqlalchemy/sql/schema.py +6222 -0
  211. sqlalchemy/sql/selectable.py +7265 -0
  212. sqlalchemy/sql/sqltypes.py +3930 -0
  213. sqlalchemy/sql/traversals.py +1024 -0
  214. sqlalchemy/sql/type_api.py +2368 -0
  215. sqlalchemy/sql/util.py +1485 -0
  216. sqlalchemy/sql/visitors.py +1164 -0
  217. sqlalchemy/testing/__init__.py +96 -0
  218. sqlalchemy/testing/assertions.py +994 -0
  219. sqlalchemy/testing/assertsql.py +520 -0
  220. sqlalchemy/testing/asyncio.py +135 -0
  221. sqlalchemy/testing/config.py +434 -0
  222. sqlalchemy/testing/engines.py +483 -0
  223. sqlalchemy/testing/entities.py +117 -0
  224. sqlalchemy/testing/exclusions.py +476 -0
  225. sqlalchemy/testing/fixtures/__init__.py +28 -0
  226. sqlalchemy/testing/fixtures/base.py +384 -0
  227. sqlalchemy/testing/fixtures/mypy.py +332 -0
  228. sqlalchemy/testing/fixtures/orm.py +227 -0
  229. sqlalchemy/testing/fixtures/sql.py +482 -0
  230. sqlalchemy/testing/pickleable.py +155 -0
  231. sqlalchemy/testing/plugin/__init__.py +6 -0
  232. sqlalchemy/testing/plugin/bootstrap.py +51 -0
  233. sqlalchemy/testing/plugin/plugin_base.py +828 -0
  234. sqlalchemy/testing/plugin/pytestplugin.py +892 -0
  235. sqlalchemy/testing/profiling.py +329 -0
  236. sqlalchemy/testing/provision.py +603 -0
  237. sqlalchemy/testing/requirements.py +1945 -0
  238. sqlalchemy/testing/schema.py +198 -0
  239. sqlalchemy/testing/suite/__init__.py +19 -0
  240. sqlalchemy/testing/suite/test_cte.py +237 -0
  241. sqlalchemy/testing/suite/test_ddl.py +389 -0
  242. sqlalchemy/testing/suite/test_deprecations.py +153 -0
  243. sqlalchemy/testing/suite/test_dialect.py +776 -0
  244. sqlalchemy/testing/suite/test_insert.py +630 -0
  245. sqlalchemy/testing/suite/test_reflection.py +3557 -0
  246. sqlalchemy/testing/suite/test_results.py +504 -0
  247. sqlalchemy/testing/suite/test_rowcount.py +258 -0
  248. sqlalchemy/testing/suite/test_select.py +2010 -0
  249. sqlalchemy/testing/suite/test_sequence.py +317 -0
  250. sqlalchemy/testing/suite/test_types.py +2147 -0
  251. sqlalchemy/testing/suite/test_unicode_ddl.py +189 -0
  252. sqlalchemy/testing/suite/test_update_delete.py +139 -0
  253. sqlalchemy/testing/util.py +535 -0
  254. sqlalchemy/testing/warnings.py +52 -0
  255. sqlalchemy/types.py +74 -0
  256. sqlalchemy/util/__init__.py +162 -0
  257. sqlalchemy/util/_collections.py +712 -0
  258. sqlalchemy/util/_concurrency_py3k.py +288 -0
  259. sqlalchemy/util/_has_cy.py +40 -0
  260. sqlalchemy/util/_py_collections.py +541 -0
  261. sqlalchemy/util/compat.py +421 -0
  262. sqlalchemy/util/concurrency.py +110 -0
  263. sqlalchemy/util/deprecations.py +401 -0
  264. sqlalchemy/util/langhelpers.py +2203 -0
  265. sqlalchemy/util/preloaded.py +150 -0
  266. sqlalchemy/util/queue.py +322 -0
  267. sqlalchemy/util/tool_support.py +201 -0
  268. sqlalchemy/util/topological.py +120 -0
  269. sqlalchemy/util/typing.py +734 -0
  270. sqlalchemy-2.0.47.dist-info/METADATA +243 -0
  271. sqlalchemy-2.0.47.dist-info/RECORD +274 -0
  272. sqlalchemy-2.0.47.dist-info/WHEEL +5 -0
  273. sqlalchemy-2.0.47.dist-info/licenses/LICENSE +19 -0
  274. sqlalchemy-2.0.47.dist-info/top_level.txt +1 -0
@@ -0,0 +1,570 @@
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
+
32
+ log = logging.getLogger(__name__)
33
+
34
+
35
+ class Bakery:
36
+ """Callable which returns a :class:`.BakedQuery`.
37
+
38
+ This object is returned by the class method
39
+ :meth:`.BakedQuery.bakery`. It exists as an object
40
+ so that the "cache" can be easily inspected.
41
+
42
+ .. versionadded:: 1.2
43
+
44
+
45
+ """
46
+
47
+ __slots__ = "cls", "cache"
48
+
49
+ def __init__(self, cls_, cache):
50
+ self.cls = cls_
51
+ self.cache = cache
52
+
53
+ def __call__(self, initial_fn, *args):
54
+ return self.cls(self.cache, initial_fn, args)
55
+
56
+
57
+ class BakedQuery:
58
+ """A builder object for :class:`.query.Query` objects."""
59
+
60
+ __slots__ = "steps", "_bakery", "_cache_key", "_spoiled"
61
+
62
+ def __init__(self, bakery, initial_fn, args=()):
63
+ self._cache_key = ()
64
+ self._update_cache_key(initial_fn, args)
65
+ self.steps = [initial_fn]
66
+ self._spoiled = False
67
+ self._bakery = bakery
68
+
69
+ @classmethod
70
+ def bakery(cls, size=200, _size_alert=None):
71
+ """Construct a new bakery.
72
+
73
+ :return: an instance of :class:`.Bakery`
74
+
75
+ """
76
+
77
+ return Bakery(cls, util.LRUCache(size, size_alert=_size_alert))
78
+
79
+ def _clone(self):
80
+ b1 = BakedQuery.__new__(BakedQuery)
81
+ b1._cache_key = self._cache_key
82
+ b1.steps = list(self.steps)
83
+ b1._bakery = self._bakery
84
+ b1._spoiled = self._spoiled
85
+ return b1
86
+
87
+ def _update_cache_key(self, fn, args=()):
88
+ self._cache_key += (fn.__code__,) + args
89
+
90
+ def __iadd__(self, other):
91
+ if isinstance(other, tuple):
92
+ self.add_criteria(*other)
93
+ else:
94
+ self.add_criteria(other)
95
+ return self
96
+
97
+ def __add__(self, other):
98
+ if isinstance(other, tuple):
99
+ return self.with_criteria(*other)
100
+ else:
101
+ return self.with_criteria(other)
102
+
103
+ def add_criteria(self, fn, *args):
104
+ """Add a criteria function to this :class:`.BakedQuery`.
105
+
106
+ This is equivalent to using the ``+=`` operator to
107
+ modify a :class:`.BakedQuery` in-place.
108
+
109
+ """
110
+ self._update_cache_key(fn, args)
111
+ self.steps.append(fn)
112
+ return self
113
+
114
+ def with_criteria(self, fn, *args):
115
+ """Add a criteria function to a :class:`.BakedQuery` cloned from this
116
+ one.
117
+
118
+ This is equivalent to using the ``+`` operator to
119
+ produce a new :class:`.BakedQuery` with modifications.
120
+
121
+ """
122
+ return self._clone().add_criteria(fn, *args)
123
+
124
+ def for_session(self, session):
125
+ """Return a :class:`_baked.Result` object for this
126
+ :class:`.BakedQuery`.
127
+
128
+ This is equivalent to calling the :class:`.BakedQuery` as a
129
+ Python callable, e.g. ``result = my_baked_query(session)``.
130
+
131
+ """
132
+ return Result(self, session)
133
+
134
+ def __call__(self, session):
135
+ return self.for_session(session)
136
+
137
+ def spoil(self, full=False):
138
+ """Cancel any query caching that will occur on this BakedQuery object.
139
+
140
+ The BakedQuery can continue to be used normally, however additional
141
+ creational functions will not be cached; they will be called
142
+ on every invocation.
143
+
144
+ This is to support the case where a particular step in constructing
145
+ a baked query disqualifies the query from being cacheable, such
146
+ as a variant that relies upon some uncacheable value.
147
+
148
+ :param full: if False, only functions added to this
149
+ :class:`.BakedQuery` object subsequent to the spoil step will be
150
+ non-cached; the state of the :class:`.BakedQuery` up until
151
+ this point will be pulled from the cache. If True, then the
152
+ entire :class:`_query.Query` object is built from scratch each
153
+ time, with all creational functions being called on each
154
+ invocation.
155
+
156
+ """
157
+ if not full and not self._spoiled:
158
+ _spoil_point = self._clone()
159
+ _spoil_point._cache_key += ("_query_only",)
160
+ self.steps = [_spoil_point._retrieve_baked_query]
161
+ self._spoiled = True
162
+ return self
163
+
164
+ def _effective_key(self, session):
165
+ """Return the key that actually goes into the cache dictionary for
166
+ this :class:`.BakedQuery`, taking into account the given
167
+ :class:`.Session`.
168
+
169
+ This basically means we also will include the session's query_class,
170
+ as the actual :class:`_query.Query` object is part of what's cached
171
+ and needs to match the type of :class:`_query.Query` that a later
172
+ session will want to use.
173
+
174
+ """
175
+ return self._cache_key + (session._query_cls,)
176
+
177
+ def _with_lazyload_options(self, options, effective_path, cache_path=None):
178
+ """Cloning version of _add_lazyload_options."""
179
+ q = self._clone()
180
+ q._add_lazyload_options(options, effective_path, cache_path=cache_path)
181
+ return q
182
+
183
+ def _add_lazyload_options(self, options, effective_path, cache_path=None):
184
+ """Used by per-state lazy loaders to add options to the
185
+ "lazy load" query from a parent query.
186
+
187
+ Creates a cache key based on given load path and query options;
188
+ if a repeatable cache key cannot be generated, the query is
189
+ "spoiled" so that it won't use caching.
190
+
191
+ """
192
+
193
+ key = ()
194
+
195
+ if not cache_path:
196
+ cache_path = effective_path
197
+
198
+ for opt in options:
199
+ if opt._is_legacy_option or opt._is_compile_state:
200
+ ck = opt._generate_cache_key()
201
+ if ck is None:
202
+ self.spoil(full=True)
203
+ else:
204
+ assert not ck[1], (
205
+ "loader options with variable bound parameters "
206
+ "not supported with baked queries. Please "
207
+ "use new-style select() statements for cached "
208
+ "ORM queries."
209
+ )
210
+ key += ck[0]
211
+
212
+ self.add_criteria(
213
+ lambda q: q._with_current_path(effective_path).options(*options),
214
+ cache_path.path,
215
+ key,
216
+ )
217
+
218
+ def _retrieve_baked_query(self, session):
219
+ query = self._bakery.get(self._effective_key(session), None)
220
+ if query is None:
221
+ query = self._as_query(session)
222
+ self._bakery[self._effective_key(session)] = query.with_session(
223
+ None
224
+ )
225
+ return query.with_session(session)
226
+
227
+ def _bake(self, session):
228
+ query = self._as_query(session)
229
+ query.session = None
230
+
231
+ # in 1.4, this is where before_compile() event is
232
+ # invoked
233
+ statement = query._statement_20()
234
+
235
+ # if the query is not safe to cache, we still do everything as though
236
+ # we did cache it, since the receiver of _bake() assumes subqueryload
237
+ # context was set up, etc.
238
+ #
239
+ # note also we want to cache the statement itself because this
240
+ # allows the statement itself to hold onto its cache key that is
241
+ # used by the Connection, which in itself is more expensive to
242
+ # generate than what BakedQuery was able to provide in 1.3 and prior
243
+
244
+ if statement._compile_options._bake_ok:
245
+ self._bakery[self._effective_key(session)] = (
246
+ query,
247
+ statement,
248
+ )
249
+
250
+ return query, statement
251
+
252
+ def to_query(self, query_or_session):
253
+ """Return the :class:`_query.Query` object for use as a subquery.
254
+
255
+ This method should be used within the lambda callable being used
256
+ to generate a step of an enclosing :class:`.BakedQuery`. The
257
+ parameter should normally be the :class:`_query.Query` object that
258
+ is passed to the lambda::
259
+
260
+ sub_bq = self.bakery(lambda s: s.query(User.name))
261
+ sub_bq += lambda q: q.filter(User.id == Address.user_id).correlate(Address)
262
+
263
+ main_bq = self.bakery(lambda s: s.query(Address))
264
+ main_bq += lambda q: q.filter(sub_bq.to_query(q).exists())
265
+
266
+ In the case where the subquery is used in the first callable against
267
+ a :class:`.Session`, the :class:`.Session` is also accepted::
268
+
269
+ sub_bq = self.bakery(lambda s: s.query(User.name))
270
+ sub_bq += lambda q: q.filter(User.id == Address.user_id).correlate(Address)
271
+
272
+ main_bq = self.bakery(
273
+ lambda s: s.query(Address.id, sub_bq.to_query(q).scalar_subquery())
274
+ )
275
+
276
+ :param query_or_session: a :class:`_query.Query` object or a class
277
+ :class:`.Session` object, that is assumed to be within the context
278
+ of an enclosing :class:`.BakedQuery` callable.
279
+
280
+
281
+ .. versionadded:: 1.3
282
+
283
+
284
+ """ # noqa: E501
285
+
286
+ if isinstance(query_or_session, Session):
287
+ session = query_or_session
288
+ elif isinstance(query_or_session, Query):
289
+ session = query_or_session.session
290
+ if session is None:
291
+ raise sa_exc.ArgumentError(
292
+ "Given Query needs to be associated with a Session"
293
+ )
294
+ else:
295
+ raise TypeError(
296
+ "Query or Session object expected, got %r."
297
+ % type(query_or_session)
298
+ )
299
+ return self._as_query(session)
300
+
301
+ def _as_query(self, session):
302
+ query = self.steps[0](session)
303
+
304
+ for step in self.steps[1:]:
305
+ query = step(query)
306
+
307
+ return query
308
+
309
+
310
+ class Result:
311
+ """Invokes a :class:`.BakedQuery` against a :class:`.Session`.
312
+
313
+ The :class:`_baked.Result` object is where the actual :class:`.query.Query`
314
+ object gets created, or retrieved from the cache,
315
+ against a target :class:`.Session`, and is then invoked for results.
316
+
317
+ """
318
+
319
+ __slots__ = "bq", "session", "_params", "_post_criteria"
320
+
321
+ def __init__(self, bq, session):
322
+ self.bq = bq
323
+ self.session = session
324
+ self._params = {}
325
+ self._post_criteria = []
326
+
327
+ def params(self, *args, **kw):
328
+ """Specify parameters to be replaced into the string SQL statement."""
329
+
330
+ if len(args) == 1:
331
+ kw.update(args[0])
332
+ elif len(args) > 0:
333
+ raise sa_exc.ArgumentError(
334
+ "params() takes zero or one positional argument, "
335
+ "which is a dictionary."
336
+ )
337
+ self._params.update(kw)
338
+ return self
339
+
340
+ def _using_post_criteria(self, fns):
341
+ if fns:
342
+ self._post_criteria.extend(fns)
343
+ return self
344
+
345
+ def with_post_criteria(self, fn):
346
+ """Add a criteria function that will be applied post-cache.
347
+
348
+ This adds a function that will be run against the
349
+ :class:`_query.Query` object after it is retrieved from the
350
+ cache. This currently includes **only** the
351
+ :meth:`_query.Query.params` and :meth:`_query.Query.execution_options`
352
+ methods.
353
+
354
+ .. warning:: :meth:`_baked.Result.with_post_criteria`
355
+ functions are applied
356
+ to the :class:`_query.Query`
357
+ object **after** the query's SQL statement
358
+ object has been retrieved from the cache. Only
359
+ :meth:`_query.Query.params` and
360
+ :meth:`_query.Query.execution_options`
361
+ methods should be used.
362
+
363
+
364
+ .. versionadded:: 1.2
365
+
366
+
367
+ """
368
+ return self._using_post_criteria([fn])
369
+
370
+ def _as_query(self):
371
+ q = self.bq._as_query(self.session).params(self._params)
372
+ for fn in self._post_criteria:
373
+ q = fn(q)
374
+ return q
375
+
376
+ def __str__(self):
377
+ return str(self._as_query())
378
+
379
+ def __iter__(self):
380
+ return self._iter().__iter__()
381
+
382
+ def _iter(self):
383
+ bq = self.bq
384
+
385
+ if not self.session.enable_baked_queries or bq._spoiled:
386
+ return self._as_query()._iter()
387
+
388
+ query, statement = bq._bakery.get(
389
+ bq._effective_key(self.session), (None, None)
390
+ )
391
+ if query is None:
392
+ query, statement = bq._bake(self.session)
393
+
394
+ if self._params:
395
+ q = query.params(self._params)
396
+ else:
397
+ q = query
398
+ for fn in self._post_criteria:
399
+ q = fn(q)
400
+
401
+ params = q._params
402
+ execution_options = dict(q._execution_options)
403
+ execution_options.update(
404
+ {
405
+ "_sa_orm_load_options": q.load_options,
406
+ "compiled_cache": bq._bakery,
407
+ }
408
+ )
409
+
410
+ result = self.session.execute(
411
+ statement, params, execution_options=execution_options
412
+ )
413
+ if result._attributes.get("is_single_entity", False):
414
+ result = result.scalars()
415
+
416
+ if result._attributes.get("filtered", False):
417
+ result = result.unique()
418
+
419
+ return result
420
+
421
+ def count(self):
422
+ """return the 'count'.
423
+
424
+ Equivalent to :meth:`_query.Query.count`.
425
+
426
+ Note this uses a subquery to ensure an accurate count regardless
427
+ of the structure of the original statement.
428
+
429
+ """
430
+
431
+ col = func.count(literal_column("*"))
432
+ bq = self.bq.with_criteria(lambda q: q._legacy_from_self(col))
433
+ return bq.for_session(self.session).params(self._params).scalar()
434
+
435
+ def scalar(self):
436
+ """Return the first element of the first result or None
437
+ if no rows present. If multiple rows are returned,
438
+ raises MultipleResultsFound.
439
+
440
+ Equivalent to :meth:`_query.Query.scalar`.
441
+
442
+ """
443
+ try:
444
+ ret = self.one()
445
+ if not isinstance(ret, collections_abc.Sequence):
446
+ return ret
447
+ return ret[0]
448
+ except orm_exc.NoResultFound:
449
+ return None
450
+
451
+ def first(self):
452
+ """Return the first row.
453
+
454
+ Equivalent to :meth:`_query.Query.first`.
455
+
456
+ """
457
+
458
+ bq = self.bq.with_criteria(lambda q: q.slice(0, 1))
459
+ return (
460
+ bq.for_session(self.session)
461
+ .params(self._params)
462
+ ._using_post_criteria(self._post_criteria)
463
+ ._iter()
464
+ .first()
465
+ )
466
+
467
+ def one(self):
468
+ """Return exactly one result or raise an exception.
469
+
470
+ Equivalent to :meth:`_query.Query.one`.
471
+
472
+ """
473
+ return self._iter().one()
474
+
475
+ def one_or_none(self):
476
+ """Return one or zero results, or raise an exception for multiple
477
+ rows.
478
+
479
+ Equivalent to :meth:`_query.Query.one_or_none`.
480
+
481
+ """
482
+ return self._iter().one_or_none()
483
+
484
+ def all(self):
485
+ """Return all rows.
486
+
487
+ Equivalent to :meth:`_query.Query.all`.
488
+
489
+ """
490
+ return self._iter().all()
491
+
492
+ def get(self, ident):
493
+ """Retrieve an object based on identity.
494
+
495
+ Equivalent to :meth:`_query.Query.get`.
496
+
497
+ """
498
+
499
+ query = self.bq.steps[0](self.session)
500
+ return query._get_impl(ident, self._load_on_pk_identity)
501
+
502
+ def _load_on_pk_identity(self, session, query, primary_key_identity, **kw):
503
+ """Load the given primary key identity from the database."""
504
+
505
+ mapper = query._raw_columns[0]._annotations["parententity"]
506
+
507
+ _get_clause, _get_params = mapper._get_clause
508
+
509
+ def setup(query):
510
+ _lcl_get_clause = _get_clause
511
+ q = query._clone()
512
+ q._get_condition()
513
+ q._order_by = None
514
+
515
+ # None present in ident - turn those comparisons
516
+ # into "IS NULL"
517
+ if None in primary_key_identity:
518
+ nones = {
519
+ _get_params[col].key
520
+ for col, value in zip(
521
+ mapper.primary_key, primary_key_identity
522
+ )
523
+ if value is None
524
+ }
525
+ _lcl_get_clause = sql_util.adapt_criterion_to_null(
526
+ _lcl_get_clause, nones
527
+ )
528
+
529
+ # TODO: can mapper._get_clause be pre-adapted?
530
+ q._where_criteria = (
531
+ sql_util._deep_annotate(_lcl_get_clause, {"_orm_adapt": True}),
532
+ )
533
+
534
+ for fn in self._post_criteria:
535
+ q = fn(q)
536
+ return q
537
+
538
+ # cache the query against a key that includes
539
+ # which positions in the primary key are NULL
540
+ # (remember, we can map to an OUTER JOIN)
541
+ bq = self.bq
542
+
543
+ # add the clause we got from mapper._get_clause to the cache
544
+ # key so that if a race causes multiple calls to _get_clause,
545
+ # we've cached on ours
546
+ bq = bq._clone()
547
+ bq._cache_key += (_get_clause,)
548
+
549
+ bq = bq.with_criteria(
550
+ setup, tuple(elem is None for elem in primary_key_identity)
551
+ )
552
+
553
+ params = {
554
+ _get_params[primary_key].key: id_val
555
+ for id_val, primary_key in zip(
556
+ primary_key_identity, mapper.primary_key
557
+ )
558
+ }
559
+
560
+ result = list(bq.for_session(self.session).params(**params))
561
+ l = len(result)
562
+ if l > 1:
563
+ raise orm_exc.MultipleResultsFound()
564
+ elif l:
565
+ return result[0]
566
+ else:
567
+ return None
568
+
569
+
570
+ bakery = BakedQuery.bakery