SQLAlchemy 2.0.36__cp313-cp313-win32.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (273) hide show
  1. SQLAlchemy-2.0.36.dist-info/LICENSE +19 -0
  2. SQLAlchemy-2.0.36.dist-info/METADATA +243 -0
  3. SQLAlchemy-2.0.36.dist-info/RECORD +273 -0
  4. SQLAlchemy-2.0.36.dist-info/WHEEL +5 -0
  5. SQLAlchemy-2.0.36.dist-info/top_level.txt +1 -0
  6. sqlalchemy/__init__.py +294 -0
  7. sqlalchemy/connectors/__init__.py +18 -0
  8. sqlalchemy/connectors/aioodbc.py +174 -0
  9. sqlalchemy/connectors/asyncio.py +213 -0
  10. sqlalchemy/connectors/pyodbc.py +249 -0
  11. sqlalchemy/cyextension/__init__.py +6 -0
  12. sqlalchemy/cyextension/collections.cp313-win32.pyd +0 -0
  13. sqlalchemy/cyextension/collections.pyx +409 -0
  14. sqlalchemy/cyextension/immutabledict.cp313-win32.pyd +0 -0
  15. sqlalchemy/cyextension/immutabledict.pxd +8 -0
  16. sqlalchemy/cyextension/immutabledict.pyx +133 -0
  17. sqlalchemy/cyextension/processors.cp313-win32.pyd +0 -0
  18. sqlalchemy/cyextension/processors.pyx +68 -0
  19. sqlalchemy/cyextension/resultproxy.cp313-win32.pyd +0 -0
  20. sqlalchemy/cyextension/resultproxy.pyx +102 -0
  21. sqlalchemy/cyextension/util.cp313-win32.pyd +0 -0
  22. sqlalchemy/cyextension/util.pyx +91 -0
  23. sqlalchemy/dialects/__init__.py +61 -0
  24. sqlalchemy/dialects/_typing.py +25 -0
  25. sqlalchemy/dialects/mssql/__init__.py +88 -0
  26. sqlalchemy/dialects/mssql/aioodbc.py +64 -0
  27. sqlalchemy/dialects/mssql/base.py +4010 -0
  28. sqlalchemy/dialects/mssql/information_schema.py +254 -0
  29. sqlalchemy/dialects/mssql/json.py +133 -0
  30. sqlalchemy/dialects/mssql/provision.py +162 -0
  31. sqlalchemy/dialects/mssql/pymssql.py +126 -0
  32. sqlalchemy/dialects/mssql/pyodbc.py +745 -0
  33. sqlalchemy/dialects/mysql/__init__.py +101 -0
  34. sqlalchemy/dialects/mysql/aiomysql.py +333 -0
  35. sqlalchemy/dialects/mysql/asyncmy.py +337 -0
  36. sqlalchemy/dialects/mysql/base.py +3494 -0
  37. sqlalchemy/dialects/mysql/cymysql.py +84 -0
  38. sqlalchemy/dialects/mysql/dml.py +219 -0
  39. sqlalchemy/dialects/mysql/enumerated.py +244 -0
  40. sqlalchemy/dialects/mysql/expression.py +141 -0
  41. sqlalchemy/dialects/mysql/json.py +81 -0
  42. sqlalchemy/dialects/mysql/mariadb.py +32 -0
  43. sqlalchemy/dialects/mysql/mariadbconnector.py +277 -0
  44. sqlalchemy/dialects/mysql/mysqlconnector.py +180 -0
  45. sqlalchemy/dialects/mysql/mysqldb.py +303 -0
  46. sqlalchemy/dialects/mysql/provision.py +110 -0
  47. sqlalchemy/dialects/mysql/pymysql.py +137 -0
  48. sqlalchemy/dialects/mysql/pyodbc.py +138 -0
  49. sqlalchemy/dialects/mysql/reflection.py +677 -0
  50. sqlalchemy/dialects/mysql/reserved_words.py +571 -0
  51. sqlalchemy/dialects/mysql/types.py +774 -0
  52. sqlalchemy/dialects/oracle/__init__.py +67 -0
  53. sqlalchemy/dialects/oracle/base.py +3271 -0
  54. sqlalchemy/dialects/oracle/cx_oracle.py +1483 -0
  55. sqlalchemy/dialects/oracle/dictionary.py +507 -0
  56. sqlalchemy/dialects/oracle/oracledb.py +431 -0
  57. sqlalchemy/dialects/oracle/provision.py +220 -0
  58. sqlalchemy/dialects/oracle/types.py +287 -0
  59. sqlalchemy/dialects/postgresql/__init__.py +167 -0
  60. sqlalchemy/dialects/postgresql/_psycopg_common.py +187 -0
  61. sqlalchemy/dialects/postgresql/array.py +425 -0
  62. sqlalchemy/dialects/postgresql/asyncpg.py +1274 -0
  63. sqlalchemy/dialects/postgresql/base.py +5008 -0
  64. sqlalchemy/dialects/postgresql/dml.py +310 -0
  65. sqlalchemy/dialects/postgresql/ext.py +496 -0
  66. sqlalchemy/dialects/postgresql/hstore.py +397 -0
  67. sqlalchemy/dialects/postgresql/json.py +333 -0
  68. sqlalchemy/dialects/postgresql/named_types.py +509 -0
  69. sqlalchemy/dialects/postgresql/operators.py +129 -0
  70. sqlalchemy/dialects/postgresql/pg8000.py +662 -0
  71. sqlalchemy/dialects/postgresql/pg_catalog.py +300 -0
  72. sqlalchemy/dialects/postgresql/provision.py +175 -0
  73. sqlalchemy/dialects/postgresql/psycopg.py +772 -0
  74. sqlalchemy/dialects/postgresql/psycopg2.py +886 -0
  75. sqlalchemy/dialects/postgresql/psycopg2cffi.py +61 -0
  76. sqlalchemy/dialects/postgresql/ranges.py +1029 -0
  77. sqlalchemy/dialects/postgresql/types.py +303 -0
  78. sqlalchemy/dialects/sqlite/__init__.py +57 -0
  79. sqlalchemy/dialects/sqlite/aiosqlite.py +396 -0
  80. sqlalchemy/dialects/sqlite/base.py +2805 -0
  81. sqlalchemy/dialects/sqlite/dml.py +240 -0
  82. sqlalchemy/dialects/sqlite/json.py +92 -0
  83. sqlalchemy/dialects/sqlite/provision.py +198 -0
  84. sqlalchemy/dialects/sqlite/pysqlcipher.py +155 -0
  85. sqlalchemy/dialects/sqlite/pysqlite.py +756 -0
  86. sqlalchemy/dialects/type_migration_guidelines.txt +145 -0
  87. sqlalchemy/engine/__init__.py +62 -0
  88. sqlalchemy/engine/_py_processors.py +136 -0
  89. sqlalchemy/engine/_py_row.py +128 -0
  90. sqlalchemy/engine/_py_util.py +74 -0
  91. sqlalchemy/engine/base.py +3375 -0
  92. sqlalchemy/engine/characteristics.py +155 -0
  93. sqlalchemy/engine/create.py +875 -0
  94. sqlalchemy/engine/cursor.py +2181 -0
  95. sqlalchemy/engine/default.py +2365 -0
  96. sqlalchemy/engine/events.py +951 -0
  97. sqlalchemy/engine/interfaces.py +3403 -0
  98. sqlalchemy/engine/mock.py +131 -0
  99. sqlalchemy/engine/processors.py +61 -0
  100. sqlalchemy/engine/reflection.py +2098 -0
  101. sqlalchemy/engine/result.py +2382 -0
  102. sqlalchemy/engine/row.py +401 -0
  103. sqlalchemy/engine/strategies.py +19 -0
  104. sqlalchemy/engine/url.py +910 -0
  105. sqlalchemy/engine/util.py +167 -0
  106. sqlalchemy/event/__init__.py +25 -0
  107. sqlalchemy/event/api.py +225 -0
  108. sqlalchemy/event/attr.py +655 -0
  109. sqlalchemy/event/base.py +470 -0
  110. sqlalchemy/event/legacy.py +246 -0
  111. sqlalchemy/event/registry.py +386 -0
  112. sqlalchemy/events.py +17 -0
  113. sqlalchemy/exc.py +830 -0
  114. sqlalchemy/ext/__init__.py +11 -0
  115. sqlalchemy/ext/associationproxy.py +2013 -0
  116. sqlalchemy/ext/asyncio/__init__.py +25 -0
  117. sqlalchemy/ext/asyncio/base.py +279 -0
  118. sqlalchemy/ext/asyncio/engine.py +1466 -0
  119. sqlalchemy/ext/asyncio/exc.py +21 -0
  120. sqlalchemy/ext/asyncio/result.py +961 -0
  121. sqlalchemy/ext/asyncio/scoping.py +1614 -0
  122. sqlalchemy/ext/asyncio/session.py +1936 -0
  123. sqlalchemy/ext/automap.py +1691 -0
  124. sqlalchemy/ext/baked.py +574 -0
  125. sqlalchemy/ext/compiler.py +570 -0
  126. sqlalchemy/ext/declarative/__init__.py +65 -0
  127. sqlalchemy/ext/declarative/extensions.py +548 -0
  128. sqlalchemy/ext/horizontal_shard.py +481 -0
  129. sqlalchemy/ext/hybrid.py +1514 -0
  130. sqlalchemy/ext/indexable.py +341 -0
  131. sqlalchemy/ext/instrumentation.py +450 -0
  132. sqlalchemy/ext/mutable.py +1073 -0
  133. sqlalchemy/ext/mypy/__init__.py +6 -0
  134. sqlalchemy/ext/mypy/apply.py +320 -0
  135. sqlalchemy/ext/mypy/decl_class.py +515 -0
  136. sqlalchemy/ext/mypy/infer.py +590 -0
  137. sqlalchemy/ext/mypy/names.py +335 -0
  138. sqlalchemy/ext/mypy/plugin.py +303 -0
  139. sqlalchemy/ext/mypy/util.py +357 -0
  140. sqlalchemy/ext/orderinglist.py +416 -0
  141. sqlalchemy/ext/serializer.py +181 -0
  142. sqlalchemy/future/__init__.py +16 -0
  143. sqlalchemy/future/engine.py +15 -0
  144. sqlalchemy/inspection.py +174 -0
  145. sqlalchemy/log.py +288 -0
  146. sqlalchemy/orm/__init__.py +170 -0
  147. sqlalchemy/orm/_orm_constructors.py +2571 -0
  148. sqlalchemy/orm/_typing.py +179 -0
  149. sqlalchemy/orm/attributes.py +2835 -0
  150. sqlalchemy/orm/base.py +973 -0
  151. sqlalchemy/orm/bulk_persistence.py +2123 -0
  152. sqlalchemy/orm/clsregistry.py +571 -0
  153. sqlalchemy/orm/collections.py +1620 -0
  154. sqlalchemy/orm/context.py +3268 -0
  155. sqlalchemy/orm/decl_api.py +1883 -0
  156. sqlalchemy/orm/decl_base.py +2190 -0
  157. sqlalchemy/orm/dependency.py +1304 -0
  158. sqlalchemy/orm/descriptor_props.py +1076 -0
  159. sqlalchemy/orm/dynamic.py +300 -0
  160. sqlalchemy/orm/evaluator.py +379 -0
  161. sqlalchemy/orm/events.py +3261 -0
  162. sqlalchemy/orm/exc.py +228 -0
  163. sqlalchemy/orm/identity.py +302 -0
  164. sqlalchemy/orm/instrumentation.py +754 -0
  165. sqlalchemy/orm/interfaces.py +1474 -0
  166. sqlalchemy/orm/loading.py +1682 -0
  167. sqlalchemy/orm/mapped_collection.py +557 -0
  168. sqlalchemy/orm/mapper.py +4432 -0
  169. sqlalchemy/orm/path_registry.py +811 -0
  170. sqlalchemy/orm/persistence.py +1782 -0
  171. sqlalchemy/orm/properties.py +886 -0
  172. sqlalchemy/orm/query.py +3396 -0
  173. sqlalchemy/orm/relationships.py +3500 -0
  174. sqlalchemy/orm/scoping.py +2165 -0
  175. sqlalchemy/orm/session.py +5301 -0
  176. sqlalchemy/orm/state.py +1143 -0
  177. sqlalchemy/orm/state_changes.py +198 -0
  178. sqlalchemy/orm/strategies.py +3473 -0
  179. sqlalchemy/orm/strategy_options.py +2569 -0
  180. sqlalchemy/orm/sync.py +164 -0
  181. sqlalchemy/orm/unitofwork.py +796 -0
  182. sqlalchemy/orm/util.py +2424 -0
  183. sqlalchemy/orm/writeonly.py +678 -0
  184. sqlalchemy/pool/__init__.py +44 -0
  185. sqlalchemy/pool/base.py +1515 -0
  186. sqlalchemy/pool/events.py +370 -0
  187. sqlalchemy/pool/impl.py +581 -0
  188. sqlalchemy/py.typed +0 -0
  189. sqlalchemy/schema.py +70 -0
  190. sqlalchemy/sql/__init__.py +145 -0
  191. sqlalchemy/sql/_dml_constructors.py +140 -0
  192. sqlalchemy/sql/_elements_constructors.py +1850 -0
  193. sqlalchemy/sql/_orm_types.py +20 -0
  194. sqlalchemy/sql/_py_util.py +75 -0
  195. sqlalchemy/sql/_selectable_constructors.py +635 -0
  196. sqlalchemy/sql/_typing.py +460 -0
  197. sqlalchemy/sql/annotation.py +585 -0
  198. sqlalchemy/sql/base.py +2185 -0
  199. sqlalchemy/sql/cache_key.py +1057 -0
  200. sqlalchemy/sql/coercions.py +1405 -0
  201. sqlalchemy/sql/compiler.py +7818 -0
  202. sqlalchemy/sql/crud.py +1669 -0
  203. sqlalchemy/sql/ddl.py +1378 -0
  204. sqlalchemy/sql/default_comparator.py +552 -0
  205. sqlalchemy/sql/dml.py +1817 -0
  206. sqlalchemy/sql/elements.py +5499 -0
  207. sqlalchemy/sql/events.py +455 -0
  208. sqlalchemy/sql/expression.py +162 -0
  209. sqlalchemy/sql/functions.py +2055 -0
  210. sqlalchemy/sql/lambdas.py +1449 -0
  211. sqlalchemy/sql/naming.py +212 -0
  212. sqlalchemy/sql/operators.py +2579 -0
  213. sqlalchemy/sql/roles.py +323 -0
  214. sqlalchemy/sql/schema.py +6158 -0
  215. sqlalchemy/sql/selectable.py +7004 -0
  216. sqlalchemy/sql/sqltypes.py +3827 -0
  217. sqlalchemy/sql/traversals.py +1024 -0
  218. sqlalchemy/sql/type_api.py +2339 -0
  219. sqlalchemy/sql/util.py +1486 -0
  220. sqlalchemy/sql/visitors.py +1165 -0
  221. sqlalchemy/testing/__init__.py +96 -0
  222. sqlalchemy/testing/assertions.py +989 -0
  223. sqlalchemy/testing/assertsql.py +516 -0
  224. sqlalchemy/testing/asyncio.py +135 -0
  225. sqlalchemy/testing/config.py +427 -0
  226. sqlalchemy/testing/engines.py +472 -0
  227. sqlalchemy/testing/entities.py +117 -0
  228. sqlalchemy/testing/exclusions.py +435 -0
  229. sqlalchemy/testing/fixtures/__init__.py +28 -0
  230. sqlalchemy/testing/fixtures/base.py +366 -0
  231. sqlalchemy/testing/fixtures/mypy.py +312 -0
  232. sqlalchemy/testing/fixtures/orm.py +227 -0
  233. sqlalchemy/testing/fixtures/sql.py +503 -0
  234. sqlalchemy/testing/pickleable.py +155 -0
  235. sqlalchemy/testing/plugin/__init__.py +6 -0
  236. sqlalchemy/testing/plugin/bootstrap.py +51 -0
  237. sqlalchemy/testing/plugin/plugin_base.py +779 -0
  238. sqlalchemy/testing/plugin/pytestplugin.py +868 -0
  239. sqlalchemy/testing/profiling.py +324 -0
  240. sqlalchemy/testing/provision.py +496 -0
  241. sqlalchemy/testing/requirements.py +1818 -0
  242. sqlalchemy/testing/schema.py +224 -0
  243. sqlalchemy/testing/suite/__init__.py +19 -0
  244. sqlalchemy/testing/suite/test_cte.py +211 -0
  245. sqlalchemy/testing/suite/test_ddl.py +389 -0
  246. sqlalchemy/testing/suite/test_deprecations.py +153 -0
  247. sqlalchemy/testing/suite/test_dialect.py +740 -0
  248. sqlalchemy/testing/suite/test_insert.py +630 -0
  249. sqlalchemy/testing/suite/test_reflection.py +3225 -0
  250. sqlalchemy/testing/suite/test_results.py +502 -0
  251. sqlalchemy/testing/suite/test_rowcount.py +258 -0
  252. sqlalchemy/testing/suite/test_select.py +1999 -0
  253. sqlalchemy/testing/suite/test_sequence.py +317 -0
  254. sqlalchemy/testing/suite/test_types.py +2141 -0
  255. sqlalchemy/testing/suite/test_unicode_ddl.py +189 -0
  256. sqlalchemy/testing/suite/test_update_delete.py +139 -0
  257. sqlalchemy/testing/util.py +537 -0
  258. sqlalchemy/testing/warnings.py +52 -0
  259. sqlalchemy/types.py +76 -0
  260. sqlalchemy/util/__init__.py +160 -0
  261. sqlalchemy/util/_collections.py +715 -0
  262. sqlalchemy/util/_concurrency_py3k.py +288 -0
  263. sqlalchemy/util/_has_cy.py +40 -0
  264. sqlalchemy/util/_py_collections.py +541 -0
  265. sqlalchemy/util/compat.py +301 -0
  266. sqlalchemy/util/concurrency.py +108 -0
  267. sqlalchemy/util/deprecations.py +401 -0
  268. sqlalchemy/util/langhelpers.py +2218 -0
  269. sqlalchemy/util/preloaded.py +150 -0
  270. sqlalchemy/util/queue.py +322 -0
  271. sqlalchemy/util/tool_support.py +201 -0
  272. sqlalchemy/util/topological.py +120 -0
  273. sqlalchemy/util/typing.py +629 -0
@@ -0,0 +1,3268 @@
1
+ # orm/context.py
2
+ # Copyright (C) 2005-2024 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+ # mypy: ignore-errors
8
+
9
+ from __future__ import annotations
10
+
11
+ import itertools
12
+ from typing import Any
13
+ from typing import cast
14
+ from typing import Dict
15
+ from typing import Iterable
16
+ from typing import List
17
+ from typing import Optional
18
+ from typing import Set
19
+ from typing import Tuple
20
+ from typing import Type
21
+ from typing import TYPE_CHECKING
22
+ from typing import TypeVar
23
+ from typing import Union
24
+
25
+ from . import attributes
26
+ from . import interfaces
27
+ from . import loading
28
+ from .base import _is_aliased_class
29
+ from .interfaces import ORMColumnDescription
30
+ from .interfaces import ORMColumnsClauseRole
31
+ from .path_registry import PathRegistry
32
+ from .util import _entity_corresponds_to
33
+ from .util import _ORMJoin
34
+ from .util import _TraceAdaptRole
35
+ from .util import AliasedClass
36
+ from .util import Bundle
37
+ from .util import ORMAdapter
38
+ from .util import ORMStatementAdapter
39
+ from .. import exc as sa_exc
40
+ from .. import future
41
+ from .. import inspect
42
+ from .. import sql
43
+ from .. import util
44
+ from ..sql import coercions
45
+ from ..sql import expression
46
+ from ..sql import roles
47
+ from ..sql import util as sql_util
48
+ from ..sql import visitors
49
+ from ..sql._typing import _TP
50
+ from ..sql._typing import is_dml
51
+ from ..sql._typing import is_insert_update
52
+ from ..sql._typing import is_select_base
53
+ from ..sql.base import _select_iterables
54
+ from ..sql.base import CacheableOptions
55
+ from ..sql.base import CompileState
56
+ from ..sql.base import Executable
57
+ from ..sql.base import Generative
58
+ from ..sql.base import Options
59
+ from ..sql.dml import UpdateBase
60
+ from ..sql.elements import GroupedElement
61
+ from ..sql.elements import TextClause
62
+ from ..sql.selectable import CompoundSelectState
63
+ from ..sql.selectable import LABEL_STYLE_DISAMBIGUATE_ONLY
64
+ from ..sql.selectable import LABEL_STYLE_NONE
65
+ from ..sql.selectable import LABEL_STYLE_TABLENAME_PLUS_COL
66
+ from ..sql.selectable import Select
67
+ from ..sql.selectable import SelectLabelStyle
68
+ from ..sql.selectable import SelectState
69
+ from ..sql.selectable import TypedReturnsRows
70
+ from ..sql.visitors import InternalTraversal
71
+
72
+ if TYPE_CHECKING:
73
+ from ._typing import _InternalEntityType
74
+ from ._typing import OrmExecuteOptionsParameter
75
+ from .loading import PostLoad
76
+ from .mapper import Mapper
77
+ from .query import Query
78
+ from .session import _BindArguments
79
+ from .session import Session
80
+ from ..engine import Result
81
+ from ..engine.interfaces import _CoreSingleExecuteParams
82
+ from ..sql._typing import _ColumnsClauseArgument
83
+ from ..sql.compiler import SQLCompiler
84
+ from ..sql.dml import _DMLTableElement
85
+ from ..sql.elements import ColumnElement
86
+ from ..sql.selectable import _JoinTargetElement
87
+ from ..sql.selectable import _LabelConventionCallable
88
+ from ..sql.selectable import _SetupJoinsElement
89
+ from ..sql.selectable import ExecutableReturnsRows
90
+ from ..sql.selectable import SelectBase
91
+ from ..sql.type_api import TypeEngine
92
+
93
+ _T = TypeVar("_T", bound=Any)
94
+ _path_registry = PathRegistry.root
95
+
96
+ _EMPTY_DICT = util.immutabledict()
97
+
98
+
99
+ LABEL_STYLE_LEGACY_ORM = SelectLabelStyle.LABEL_STYLE_LEGACY_ORM
100
+
101
+
102
+ class QueryContext:
103
+ __slots__ = (
104
+ "top_level_context",
105
+ "compile_state",
106
+ "query",
107
+ "user_passed_query",
108
+ "params",
109
+ "load_options",
110
+ "bind_arguments",
111
+ "execution_options",
112
+ "session",
113
+ "autoflush",
114
+ "populate_existing",
115
+ "invoke_all_eagers",
116
+ "version_check",
117
+ "refresh_state",
118
+ "create_eager_joins",
119
+ "propagated_loader_options",
120
+ "attributes",
121
+ "runid",
122
+ "partials",
123
+ "post_load_paths",
124
+ "identity_token",
125
+ "yield_per",
126
+ "loaders_require_buffering",
127
+ "loaders_require_uniquing",
128
+ )
129
+
130
+ runid: int
131
+ post_load_paths: Dict[PathRegistry, PostLoad]
132
+ compile_state: ORMCompileState
133
+
134
+ class default_load_options(Options):
135
+ _only_return_tuples = False
136
+ _populate_existing = False
137
+ _version_check = False
138
+ _invoke_all_eagers = True
139
+ _autoflush = True
140
+ _identity_token = None
141
+ _yield_per = None
142
+ _refresh_state = None
143
+ _lazy_loaded_from = None
144
+ _legacy_uniquing = False
145
+ _sa_top_level_orm_context = None
146
+ _is_user_refresh = False
147
+
148
+ def __init__(
149
+ self,
150
+ compile_state: CompileState,
151
+ statement: Union[Select[Any], FromStatement[Any]],
152
+ user_passed_query: Union[
153
+ Select[Any],
154
+ FromStatement[Any],
155
+ ],
156
+ params: _CoreSingleExecuteParams,
157
+ session: Session,
158
+ load_options: Union[
159
+ Type[QueryContext.default_load_options],
160
+ QueryContext.default_load_options,
161
+ ],
162
+ execution_options: Optional[OrmExecuteOptionsParameter] = None,
163
+ bind_arguments: Optional[_BindArguments] = None,
164
+ ):
165
+ self.load_options = load_options
166
+ self.execution_options = execution_options or _EMPTY_DICT
167
+ self.bind_arguments = bind_arguments or _EMPTY_DICT
168
+ self.compile_state = compile_state
169
+ self.query = statement
170
+
171
+ # the query that the end user passed to Session.execute() or similar.
172
+ # this is usually the same as .query, except in the bulk_persistence
173
+ # routines where a separate FromStatement is manufactured in the
174
+ # compile stage; this allows differentiation in that case.
175
+ self.user_passed_query = user_passed_query
176
+
177
+ self.session = session
178
+ self.loaders_require_buffering = False
179
+ self.loaders_require_uniquing = False
180
+ self.params = params
181
+ self.top_level_context = load_options._sa_top_level_orm_context
182
+
183
+ cached_options = compile_state.select_statement._with_options
184
+ uncached_options = user_passed_query._with_options
185
+
186
+ # see issue #7447 , #8399 for some background
187
+ # propagated loader options will be present on loaded InstanceState
188
+ # objects under state.load_options and are typically used by
189
+ # LazyLoader to apply options to the SELECT statement it emits.
190
+ # For compile state options (i.e. loader strategy options), these
191
+ # need to line up with the ".load_path" attribute which in
192
+ # loader.py is pulled from context.compile_state.current_path.
193
+ # so, this means these options have to be the ones from the
194
+ # *cached* statement that's travelling with compile_state, not the
195
+ # *current* statement which won't match up for an ad-hoc
196
+ # AliasedClass
197
+ self.propagated_loader_options = tuple(
198
+ opt._adapt_cached_option_to_uncached_option(self, uncached_opt)
199
+ for opt, uncached_opt in zip(cached_options, uncached_options)
200
+ if opt.propagate_to_loaders
201
+ )
202
+
203
+ self.attributes = dict(compile_state.attributes)
204
+
205
+ self.autoflush = load_options._autoflush
206
+ self.populate_existing = load_options._populate_existing
207
+ self.invoke_all_eagers = load_options._invoke_all_eagers
208
+ self.version_check = load_options._version_check
209
+ self.refresh_state = load_options._refresh_state
210
+ self.yield_per = load_options._yield_per
211
+ self.identity_token = load_options._identity_token
212
+
213
+ def _get_top_level_context(self) -> QueryContext:
214
+ return self.top_level_context or self
215
+
216
+
217
+ _orm_load_exec_options = util.immutabledict(
218
+ {"_result_disable_adapt_to_context": True}
219
+ )
220
+
221
+
222
+ class AbstractORMCompileState(CompileState):
223
+ is_dml_returning = False
224
+
225
+ def _init_global_attributes(
226
+ self, statement, compiler, *, toplevel, process_criteria_for_toplevel
227
+ ):
228
+ self.attributes = {}
229
+
230
+ if compiler is None:
231
+ # this is the legacy / testing only ORM _compile_state() use case.
232
+ # there is no need to apply criteria options for this.
233
+ self.global_attributes = ga = {}
234
+ assert toplevel
235
+ return
236
+ else:
237
+ self.global_attributes = ga = compiler._global_attributes
238
+
239
+ if toplevel:
240
+ ga["toplevel_orm"] = True
241
+
242
+ if process_criteria_for_toplevel:
243
+ for opt in statement._with_options:
244
+ if opt._is_criteria_option:
245
+ opt.process_compile_state(self)
246
+
247
+ return
248
+ elif ga.get("toplevel_orm", False):
249
+ return
250
+
251
+ stack_0 = compiler.stack[0]
252
+
253
+ try:
254
+ toplevel_stmt = stack_0["selectable"]
255
+ except KeyError:
256
+ pass
257
+ else:
258
+ for opt in toplevel_stmt._with_options:
259
+ if opt._is_compile_state and opt._is_criteria_option:
260
+ opt.process_compile_state(self)
261
+
262
+ ga["toplevel_orm"] = True
263
+
264
+ @classmethod
265
+ def create_for_statement(
266
+ cls,
267
+ statement: Union[Select, FromStatement],
268
+ compiler: Optional[SQLCompiler],
269
+ **kw: Any,
270
+ ) -> AbstractORMCompileState:
271
+ """Create a context for a statement given a :class:`.Compiler`.
272
+
273
+ This method is always invoked in the context of SQLCompiler.process().
274
+
275
+ For a Select object, this would be invoked from
276
+ SQLCompiler.visit_select(). For the special FromStatement object used
277
+ by Query to indicate "Query.from_statement()", this is called by
278
+ FromStatement._compiler_dispatch() that would be called by
279
+ SQLCompiler.process().
280
+ """
281
+ return super().create_for_statement(statement, compiler, **kw)
282
+
283
+ @classmethod
284
+ def orm_pre_session_exec(
285
+ cls,
286
+ session,
287
+ statement,
288
+ params,
289
+ execution_options,
290
+ bind_arguments,
291
+ is_pre_event,
292
+ ):
293
+ raise NotImplementedError()
294
+
295
+ @classmethod
296
+ def orm_execute_statement(
297
+ cls,
298
+ session,
299
+ statement,
300
+ params,
301
+ execution_options,
302
+ bind_arguments,
303
+ conn,
304
+ ) -> Result:
305
+ result = conn.execute(
306
+ statement, params or {}, execution_options=execution_options
307
+ )
308
+ return cls.orm_setup_cursor_result(
309
+ session,
310
+ statement,
311
+ params,
312
+ execution_options,
313
+ bind_arguments,
314
+ result,
315
+ )
316
+
317
+ @classmethod
318
+ def orm_setup_cursor_result(
319
+ cls,
320
+ session,
321
+ statement,
322
+ params,
323
+ execution_options,
324
+ bind_arguments,
325
+ result,
326
+ ):
327
+ raise NotImplementedError()
328
+
329
+
330
+ class AutoflushOnlyORMCompileState(AbstractORMCompileState):
331
+ """ORM compile state that is a passthrough, except for autoflush."""
332
+
333
+ @classmethod
334
+ def orm_pre_session_exec(
335
+ cls,
336
+ session,
337
+ statement,
338
+ params,
339
+ execution_options,
340
+ bind_arguments,
341
+ is_pre_event,
342
+ ):
343
+ # consume result-level load_options. These may have been set up
344
+ # in an ORMExecuteState hook
345
+ (
346
+ load_options,
347
+ execution_options,
348
+ ) = QueryContext.default_load_options.from_execution_options(
349
+ "_sa_orm_load_options",
350
+ {
351
+ "autoflush",
352
+ },
353
+ execution_options,
354
+ statement._execution_options,
355
+ )
356
+
357
+ if not is_pre_event and load_options._autoflush:
358
+ session._autoflush()
359
+
360
+ return statement, execution_options
361
+
362
+ @classmethod
363
+ def orm_setup_cursor_result(
364
+ cls,
365
+ session,
366
+ statement,
367
+ params,
368
+ execution_options,
369
+ bind_arguments,
370
+ result,
371
+ ):
372
+ return result
373
+
374
+
375
+ class ORMCompileState(AbstractORMCompileState):
376
+ class default_compile_options(CacheableOptions):
377
+ _cache_key_traversal = [
378
+ ("_use_legacy_query_style", InternalTraversal.dp_boolean),
379
+ ("_for_statement", InternalTraversal.dp_boolean),
380
+ ("_bake_ok", InternalTraversal.dp_boolean),
381
+ ("_current_path", InternalTraversal.dp_has_cache_key),
382
+ ("_enable_single_crit", InternalTraversal.dp_boolean),
383
+ ("_enable_eagerloads", InternalTraversal.dp_boolean),
384
+ ("_only_load_props", InternalTraversal.dp_plain_obj),
385
+ ("_set_base_alias", InternalTraversal.dp_boolean),
386
+ ("_for_refresh_state", InternalTraversal.dp_boolean),
387
+ ("_render_for_subquery", InternalTraversal.dp_boolean),
388
+ ("_is_star", InternalTraversal.dp_boolean),
389
+ ]
390
+
391
+ # set to True by default from Query._statement_20(), to indicate
392
+ # the rendered query should look like a legacy ORM query. right
393
+ # now this basically indicates we should use tablename_columnname
394
+ # style labels. Generally indicates the statement originated
395
+ # from a Query object.
396
+ _use_legacy_query_style = False
397
+
398
+ # set *only* when we are coming from the Query.statement
399
+ # accessor, or a Query-level equivalent such as
400
+ # query.subquery(). this supersedes "toplevel".
401
+ _for_statement = False
402
+
403
+ _bake_ok = True
404
+ _current_path = _path_registry
405
+ _enable_single_crit = True
406
+ _enable_eagerloads = True
407
+ _only_load_props = None
408
+ _set_base_alias = False
409
+ _for_refresh_state = False
410
+ _render_for_subquery = False
411
+ _is_star = False
412
+
413
+ attributes: Dict[Any, Any]
414
+ global_attributes: Dict[Any, Any]
415
+
416
+ statement: Union[Select[Any], FromStatement[Any]]
417
+ select_statement: Union[Select[Any], FromStatement[Any]]
418
+ _entities: List[_QueryEntity]
419
+ _polymorphic_adapters: Dict[_InternalEntityType, ORMAdapter]
420
+ compile_options: Union[
421
+ Type[default_compile_options], default_compile_options
422
+ ]
423
+ _primary_entity: Optional[_QueryEntity]
424
+ use_legacy_query_style: bool
425
+ _label_convention: _LabelConventionCallable
426
+ primary_columns: List[ColumnElement[Any]]
427
+ secondary_columns: List[ColumnElement[Any]]
428
+ dedupe_columns: Set[ColumnElement[Any]]
429
+ create_eager_joins: List[
430
+ # TODO: this structure is set up by JoinedLoader
431
+ Tuple[Any, ...]
432
+ ]
433
+ current_path: PathRegistry = _path_registry
434
+ _has_mapper_entities = False
435
+
436
+ def __init__(self, *arg, **kw):
437
+ raise NotImplementedError()
438
+
439
+ if TYPE_CHECKING:
440
+
441
+ @classmethod
442
+ def create_for_statement(
443
+ cls,
444
+ statement: Union[Select, FromStatement],
445
+ compiler: Optional[SQLCompiler],
446
+ **kw: Any,
447
+ ) -> ORMCompileState: ...
448
+
449
+ def _append_dedupe_col_collection(self, obj, col_collection):
450
+ dedupe = self.dedupe_columns
451
+ if obj not in dedupe:
452
+ dedupe.add(obj)
453
+ col_collection.append(obj)
454
+
455
+ @classmethod
456
+ def _column_naming_convention(
457
+ cls, label_style: SelectLabelStyle, legacy: bool
458
+ ) -> _LabelConventionCallable:
459
+ if legacy:
460
+
461
+ def name(col, col_name=None):
462
+ if col_name:
463
+ return col_name
464
+ else:
465
+ return getattr(col, "key")
466
+
467
+ return name
468
+ else:
469
+ return SelectState._column_naming_convention(label_style)
470
+
471
+ @classmethod
472
+ def get_column_descriptions(cls, statement):
473
+ return _column_descriptions(statement)
474
+
475
+ @classmethod
476
+ def orm_pre_session_exec(
477
+ cls,
478
+ session,
479
+ statement,
480
+ params,
481
+ execution_options,
482
+ bind_arguments,
483
+ is_pre_event,
484
+ ):
485
+ # consume result-level load_options. These may have been set up
486
+ # in an ORMExecuteState hook
487
+ (
488
+ load_options,
489
+ execution_options,
490
+ ) = QueryContext.default_load_options.from_execution_options(
491
+ "_sa_orm_load_options",
492
+ {
493
+ "populate_existing",
494
+ "autoflush",
495
+ "yield_per",
496
+ "identity_token",
497
+ "sa_top_level_orm_context",
498
+ },
499
+ execution_options,
500
+ statement._execution_options,
501
+ )
502
+
503
+ # default execution options for ORM results:
504
+ # 1. _result_disable_adapt_to_context=True
505
+ # this will disable the ResultSetMetadata._adapt_to_context()
506
+ # step which we don't need, as we have result processors cached
507
+ # against the original SELECT statement before caching.
508
+
509
+ if "sa_top_level_orm_context" in execution_options:
510
+ ctx = execution_options["sa_top_level_orm_context"]
511
+ execution_options = ctx.query._execution_options.merge_with(
512
+ ctx.execution_options, execution_options
513
+ )
514
+
515
+ if not execution_options:
516
+ execution_options = _orm_load_exec_options
517
+ else:
518
+ execution_options = execution_options.union(_orm_load_exec_options)
519
+
520
+ # would have been placed here by legacy Query only
521
+ if load_options._yield_per:
522
+ execution_options = execution_options.union(
523
+ {"yield_per": load_options._yield_per}
524
+ )
525
+
526
+ if (
527
+ getattr(statement._compile_options, "_current_path", None)
528
+ and len(statement._compile_options._current_path) > 10
529
+ and execution_options.get("compiled_cache", True) is not None
530
+ ):
531
+ execution_options: util.immutabledict[str, Any] = (
532
+ execution_options.union(
533
+ {
534
+ "compiled_cache": None,
535
+ "_cache_disable_reason": "excess depth for "
536
+ "ORM loader options",
537
+ }
538
+ )
539
+ )
540
+
541
+ bind_arguments["clause"] = statement
542
+
543
+ # new in 1.4 - the coercions system is leveraged to allow the
544
+ # "subject" mapper of a statement be propagated to the top
545
+ # as the statement is built. "subject" mapper is the generally
546
+ # standard object used as an identifier for multi-database schemes.
547
+
548
+ # we are here based on the fact that _propagate_attrs contains
549
+ # "compile_state_plugin": "orm". The "plugin_subject"
550
+ # needs to be present as well.
551
+
552
+ try:
553
+ plugin_subject = statement._propagate_attrs["plugin_subject"]
554
+ except KeyError:
555
+ assert False, "statement had 'orm' plugin but no plugin_subject"
556
+ else:
557
+ if plugin_subject:
558
+ bind_arguments["mapper"] = plugin_subject.mapper
559
+
560
+ if not is_pre_event and load_options._autoflush:
561
+ session._autoflush()
562
+
563
+ return statement, execution_options
564
+
565
+ @classmethod
566
+ def orm_setup_cursor_result(
567
+ cls,
568
+ session,
569
+ statement,
570
+ params,
571
+ execution_options,
572
+ bind_arguments,
573
+ result,
574
+ ):
575
+ execution_context = result.context
576
+ compile_state = execution_context.compiled.compile_state
577
+
578
+ # cover edge case where ORM entities used in legacy select
579
+ # were passed to session.execute:
580
+ # session.execute(legacy_select([User.id, User.name]))
581
+ # see test_query->test_legacy_tuple_old_select
582
+
583
+ load_options = execution_options.get(
584
+ "_sa_orm_load_options", QueryContext.default_load_options
585
+ )
586
+
587
+ if compile_state.compile_options._is_star:
588
+ return result
589
+
590
+ querycontext = QueryContext(
591
+ compile_state,
592
+ statement,
593
+ statement,
594
+ params,
595
+ session,
596
+ load_options,
597
+ execution_options,
598
+ bind_arguments,
599
+ )
600
+ return loading.instances(result, querycontext)
601
+
602
+ @property
603
+ def _lead_mapper_entities(self):
604
+ """return all _MapperEntity objects in the lead entities collection.
605
+
606
+ Does **not** include entities that have been replaced by
607
+ with_entities(), with_only_columns()
608
+
609
+ """
610
+ return [
611
+ ent for ent in self._entities if isinstance(ent, _MapperEntity)
612
+ ]
613
+
614
+ def _create_with_polymorphic_adapter(self, ext_info, selectable):
615
+ """given MapperEntity or ORMColumnEntity, setup polymorphic loading
616
+ if called for by the Mapper.
617
+
618
+ As of #8168 in 2.0.0rc1, polymorphic adapters, which greatly increase
619
+ the complexity of the query creation process, are not used at all
620
+ except in the quasi-legacy cases of with_polymorphic referring to an
621
+ alias and/or subquery. This would apply to concrete polymorphic
622
+ loading, and joined inheritance where a subquery is
623
+ passed to with_polymorphic (which is completely unnecessary in modern
624
+ use).
625
+
626
+ """
627
+ if (
628
+ not ext_info.is_aliased_class
629
+ and ext_info.mapper.persist_selectable
630
+ not in self._polymorphic_adapters
631
+ ):
632
+ for mp in ext_info.mapper.iterate_to_root():
633
+ self._mapper_loads_polymorphically_with(
634
+ mp,
635
+ ORMAdapter(
636
+ _TraceAdaptRole.WITH_POLYMORPHIC_ADAPTER,
637
+ mp,
638
+ equivalents=mp._equivalent_columns,
639
+ selectable=selectable,
640
+ ),
641
+ )
642
+
643
+ def _mapper_loads_polymorphically_with(self, mapper, adapter):
644
+ for m2 in mapper._with_polymorphic_mappers or [mapper]:
645
+ self._polymorphic_adapters[m2] = adapter
646
+
647
+ for m in m2.iterate_to_root():
648
+ self._polymorphic_adapters[m.local_table] = adapter
649
+
650
+ @classmethod
651
+ def _create_entities_collection(cls, query, legacy):
652
+ raise NotImplementedError(
653
+ "this method only works for ORMSelectCompileState"
654
+ )
655
+
656
+
657
+ class DMLReturningColFilter:
658
+ """an adapter used for the DML RETURNING case.
659
+
660
+ Has a subset of the interface used by
661
+ :class:`.ORMAdapter` and is used for :class:`._QueryEntity`
662
+ instances to set up their columns as used in RETURNING for a
663
+ DML statement.
664
+
665
+ """
666
+
667
+ __slots__ = ("mapper", "columns", "__weakref__")
668
+
669
+ def __init__(self, target_mapper, immediate_dml_mapper):
670
+ if (
671
+ immediate_dml_mapper is not None
672
+ and target_mapper.local_table
673
+ is not immediate_dml_mapper.local_table
674
+ ):
675
+ # joined inh, or in theory other kinds of multi-table mappings
676
+ self.mapper = immediate_dml_mapper
677
+ else:
678
+ # single inh, normal mappings, etc.
679
+ self.mapper = target_mapper
680
+ self.columns = self.columns = util.WeakPopulateDict(
681
+ self.adapt_check_present # type: ignore
682
+ )
683
+
684
+ def __call__(self, col, as_filter):
685
+ for cc in sql_util._find_columns(col):
686
+ c2 = self.adapt_check_present(cc)
687
+ if c2 is not None:
688
+ return col
689
+ else:
690
+ return None
691
+
692
+ def adapt_check_present(self, col):
693
+ mapper = self.mapper
694
+ prop = mapper._columntoproperty.get(col, None)
695
+ if prop is None:
696
+ return None
697
+ return mapper.local_table.c.corresponding_column(col)
698
+
699
+
700
+ @sql.base.CompileState.plugin_for("orm", "orm_from_statement")
701
+ class ORMFromStatementCompileState(ORMCompileState):
702
+ _from_obj_alias = None
703
+ _has_mapper_entities = False
704
+
705
+ statement_container: FromStatement
706
+ requested_statement: Union[SelectBase, TextClause, UpdateBase]
707
+ dml_table: Optional[_DMLTableElement] = None
708
+
709
+ _has_orm_entities = False
710
+ multi_row_eager_loaders = False
711
+ eager_adding_joins = False
712
+ compound_eager_adapter = None
713
+
714
+ extra_criteria_entities = _EMPTY_DICT
715
+ eager_joins = _EMPTY_DICT
716
+
717
+ @classmethod
718
+ def create_for_statement(
719
+ cls,
720
+ statement_container: Union[Select, FromStatement],
721
+ compiler: Optional[SQLCompiler],
722
+ **kw: Any,
723
+ ) -> ORMFromStatementCompileState:
724
+ assert isinstance(statement_container, FromStatement)
725
+
726
+ if compiler is not None and compiler.stack:
727
+ raise sa_exc.CompileError(
728
+ "The ORM FromStatement construct only supports being "
729
+ "invoked as the topmost statement, as it is only intended to "
730
+ "define how result rows should be returned."
731
+ )
732
+
733
+ self = cls.__new__(cls)
734
+ self._primary_entity = None
735
+
736
+ self.use_legacy_query_style = (
737
+ statement_container._compile_options._use_legacy_query_style
738
+ )
739
+ self.statement_container = self.select_statement = statement_container
740
+ self.requested_statement = statement = statement_container.element
741
+
742
+ if statement.is_dml:
743
+ self.dml_table = statement.table
744
+ self.is_dml_returning = True
745
+
746
+ self._entities = []
747
+ self._polymorphic_adapters = {}
748
+
749
+ self.compile_options = statement_container._compile_options
750
+
751
+ if (
752
+ self.use_legacy_query_style
753
+ and isinstance(statement, expression.SelectBase)
754
+ and not statement._is_textual
755
+ and not statement.is_dml
756
+ and statement._label_style is LABEL_STYLE_NONE
757
+ ):
758
+ self.statement = statement.set_label_style(
759
+ LABEL_STYLE_TABLENAME_PLUS_COL
760
+ )
761
+ else:
762
+ self.statement = statement
763
+
764
+ self._label_convention = self._column_naming_convention(
765
+ (
766
+ statement._label_style
767
+ if not statement._is_textual and not statement.is_dml
768
+ else LABEL_STYLE_NONE
769
+ ),
770
+ self.use_legacy_query_style,
771
+ )
772
+
773
+ _QueryEntity.to_compile_state(
774
+ self,
775
+ statement_container._raw_columns,
776
+ self._entities,
777
+ is_current_entities=True,
778
+ )
779
+
780
+ self.current_path = statement_container._compile_options._current_path
781
+
782
+ self._init_global_attributes(
783
+ statement_container,
784
+ compiler,
785
+ process_criteria_for_toplevel=False,
786
+ toplevel=True,
787
+ )
788
+
789
+ if statement_container._with_options:
790
+ for opt in statement_container._with_options:
791
+ if opt._is_compile_state:
792
+ opt.process_compile_state(self)
793
+
794
+ if statement_container._with_context_options:
795
+ for fn, key in statement_container._with_context_options:
796
+ fn(self)
797
+
798
+ self.primary_columns = []
799
+ self.secondary_columns = []
800
+ self.dedupe_columns = set()
801
+ self.create_eager_joins = []
802
+ self._fallback_from_clauses = []
803
+
804
+ self.order_by = None
805
+
806
+ if isinstance(self.statement, expression.TextClause):
807
+ # TextClause has no "column" objects at all. for this case,
808
+ # we generate columns from our _QueryEntity objects, then
809
+ # flip on all the "please match no matter what" parameters.
810
+ self.extra_criteria_entities = {}
811
+
812
+ for entity in self._entities:
813
+ entity.setup_compile_state(self)
814
+
815
+ compiler._ordered_columns = compiler._textual_ordered_columns = (
816
+ False
817
+ )
818
+
819
+ # enable looser result column matching. this is shown to be
820
+ # needed by test_query.py::TextTest
821
+ compiler._loose_column_name_matching = True
822
+
823
+ for c in self.primary_columns:
824
+ compiler.process(
825
+ c,
826
+ within_columns_clause=True,
827
+ add_to_result_map=compiler._add_to_result_map,
828
+ )
829
+ else:
830
+ # for everyone else, Select, Insert, Update, TextualSelect, they
831
+ # have column objects already. After much
832
+ # experimentation here, the best approach seems to be, use
833
+ # those columns completely, don't interfere with the compiler
834
+ # at all; just in ORM land, use an adapter to convert from
835
+ # our ORM columns to whatever columns are in the statement,
836
+ # before we look in the result row. Adapt on names
837
+ # to accept cases such as issue #9217, however also allow
838
+ # this to be overridden for cases such as #9273.
839
+ self._from_obj_alias = ORMStatementAdapter(
840
+ _TraceAdaptRole.ADAPT_FROM_STATEMENT,
841
+ self.statement,
842
+ adapt_on_names=statement_container._adapt_on_names,
843
+ )
844
+
845
+ return self
846
+
847
+ def _adapt_col_list(self, cols, current_adapter):
848
+ return cols
849
+
850
+ def _get_current_adapter(self):
851
+ return None
852
+
853
+ def setup_dml_returning_compile_state(self, dml_mapper):
854
+ """used by BulkORMInsert (and Update / Delete?) to set up a handler
855
+ for RETURNING to return ORM objects and expressions
856
+
857
+ """
858
+ target_mapper = self.statement._propagate_attrs.get(
859
+ "plugin_subject", None
860
+ )
861
+ adapter = DMLReturningColFilter(target_mapper, dml_mapper)
862
+
863
+ if self.compile_options._is_star and (len(self._entities) != 1):
864
+ raise sa_exc.CompileError(
865
+ "Can't generate ORM query that includes multiple expressions "
866
+ "at the same time as '*'; query for '*' alone if present"
867
+ )
868
+
869
+ for entity in self._entities:
870
+ entity.setup_dml_returning_compile_state(self, adapter)
871
+
872
+
873
+ class FromStatement(GroupedElement, Generative, TypedReturnsRows[_TP]):
874
+ """Core construct that represents a load of ORM objects from various
875
+ :class:`.ReturnsRows` and other classes including:
876
+
877
+ :class:`.Select`, :class:`.TextClause`, :class:`.TextualSelect`,
878
+ :class:`.CompoundSelect`, :class`.Insert`, :class:`.Update`,
879
+ and in theory, :class:`.Delete`.
880
+
881
+ """
882
+
883
+ __visit_name__ = "orm_from_statement"
884
+
885
+ _compile_options = ORMFromStatementCompileState.default_compile_options
886
+
887
+ _compile_state_factory = ORMFromStatementCompileState.create_for_statement
888
+
889
+ _for_update_arg = None
890
+
891
+ element: Union[ExecutableReturnsRows, TextClause]
892
+
893
+ _adapt_on_names: bool
894
+
895
+ _traverse_internals = [
896
+ ("_raw_columns", InternalTraversal.dp_clauseelement_list),
897
+ ("element", InternalTraversal.dp_clauseelement),
898
+ ] + Executable._executable_traverse_internals
899
+
900
+ _cache_key_traversal = _traverse_internals + [
901
+ ("_compile_options", InternalTraversal.dp_has_cache_key)
902
+ ]
903
+
904
+ is_from_statement = True
905
+
906
+ def __init__(
907
+ self,
908
+ entities: Iterable[_ColumnsClauseArgument[Any]],
909
+ element: Union[ExecutableReturnsRows, TextClause],
910
+ _adapt_on_names: bool = True,
911
+ ):
912
+ self._raw_columns = [
913
+ coercions.expect(
914
+ roles.ColumnsClauseRole,
915
+ ent,
916
+ apply_propagate_attrs=self,
917
+ post_inspect=True,
918
+ )
919
+ for ent in util.to_list(entities)
920
+ ]
921
+ self.element = element
922
+ self.is_dml = element.is_dml
923
+ self.is_select = element.is_select
924
+ self.is_delete = element.is_delete
925
+ self.is_insert = element.is_insert
926
+ self.is_update = element.is_update
927
+ self._label_style = (
928
+ element._label_style if is_select_base(element) else None
929
+ )
930
+ self._adapt_on_names = _adapt_on_names
931
+
932
+ def _compiler_dispatch(self, compiler, **kw):
933
+ """provide a fixed _compiler_dispatch method.
934
+
935
+ This is roughly similar to using the sqlalchemy.ext.compiler
936
+ ``@compiles`` extension.
937
+
938
+ """
939
+
940
+ compile_state = self._compile_state_factory(self, compiler, **kw)
941
+
942
+ toplevel = not compiler.stack
943
+
944
+ if toplevel:
945
+ compiler.compile_state = compile_state
946
+
947
+ return compiler.process(compile_state.statement, **kw)
948
+
949
+ @property
950
+ def column_descriptions(self):
951
+ """Return a :term:`plugin-enabled` 'column descriptions' structure
952
+ referring to the columns which are SELECTed by this statement.
953
+
954
+ See the section :ref:`queryguide_inspection` for an overview
955
+ of this feature.
956
+
957
+ .. seealso::
958
+
959
+ :ref:`queryguide_inspection` - ORM background
960
+
961
+ """
962
+ meth = cast(
963
+ ORMSelectCompileState, SelectState.get_plugin_class(self)
964
+ ).get_column_descriptions
965
+ return meth(self)
966
+
967
+ def _ensure_disambiguated_names(self):
968
+ return self
969
+
970
+ def get_children(self, **kw):
971
+ yield from itertools.chain.from_iterable(
972
+ element._from_objects for element in self._raw_columns
973
+ )
974
+ yield from super().get_children(**kw)
975
+
976
+ @property
977
+ def _all_selected_columns(self):
978
+ return self.element._all_selected_columns
979
+
980
+ @property
981
+ def _return_defaults(self):
982
+ return self.element._return_defaults if is_dml(self.element) else None
983
+
984
+ @property
985
+ def _returning(self):
986
+ return self.element._returning if is_dml(self.element) else None
987
+
988
+ @property
989
+ def _inline(self):
990
+ return self.element._inline if is_insert_update(self.element) else None
991
+
992
+
993
+ @sql.base.CompileState.plugin_for("orm", "compound_select")
994
+ class CompoundSelectCompileState(
995
+ AutoflushOnlyORMCompileState, CompoundSelectState
996
+ ):
997
+ pass
998
+
999
+
1000
+ @sql.base.CompileState.plugin_for("orm", "select")
1001
+ class ORMSelectCompileState(ORMCompileState, SelectState):
1002
+ _already_joined_edges = ()
1003
+
1004
+ _memoized_entities = _EMPTY_DICT
1005
+
1006
+ _from_obj_alias = None
1007
+ _has_mapper_entities = False
1008
+
1009
+ _has_orm_entities = False
1010
+ multi_row_eager_loaders = False
1011
+ eager_adding_joins = False
1012
+ compound_eager_adapter = None
1013
+
1014
+ correlate = None
1015
+ correlate_except = None
1016
+ _where_criteria = ()
1017
+ _having_criteria = ()
1018
+
1019
+ @classmethod
1020
+ def create_for_statement(
1021
+ cls,
1022
+ statement: Union[Select, FromStatement],
1023
+ compiler: Optional[SQLCompiler],
1024
+ **kw: Any,
1025
+ ) -> ORMSelectCompileState:
1026
+ """compiler hook, we arrive here from compiler.visit_select() only."""
1027
+
1028
+ self = cls.__new__(cls)
1029
+
1030
+ if compiler is not None:
1031
+ toplevel = not compiler.stack
1032
+ else:
1033
+ toplevel = True
1034
+
1035
+ select_statement = statement
1036
+
1037
+ # if we are a select() that was never a legacy Query, we won't
1038
+ # have ORM level compile options.
1039
+ statement._compile_options = cls.default_compile_options.safe_merge(
1040
+ statement._compile_options
1041
+ )
1042
+
1043
+ if select_statement._execution_options:
1044
+ # execution options should not impact the compilation of a
1045
+ # query, and at the moment subqueryloader is putting some things
1046
+ # in here that we explicitly don't want stuck in a cache.
1047
+ self.select_statement = select_statement._clone()
1048
+ self.select_statement._execution_options = util.immutabledict()
1049
+ else:
1050
+ self.select_statement = select_statement
1051
+
1052
+ # indicates this select() came from Query.statement
1053
+ self.for_statement = select_statement._compile_options._for_statement
1054
+
1055
+ # generally if we are from Query or directly from a select()
1056
+ self.use_legacy_query_style = (
1057
+ select_statement._compile_options._use_legacy_query_style
1058
+ )
1059
+
1060
+ self._entities = []
1061
+ self._primary_entity = None
1062
+ self._polymorphic_adapters = {}
1063
+
1064
+ self.compile_options = select_statement._compile_options
1065
+
1066
+ if not toplevel:
1067
+ # for subqueries, turn off eagerloads and set
1068
+ # "render_for_subquery".
1069
+ self.compile_options += {
1070
+ "_enable_eagerloads": False,
1071
+ "_render_for_subquery": True,
1072
+ }
1073
+
1074
+ # determine label style. we can make different decisions here.
1075
+ # at the moment, trying to see if we can always use DISAMBIGUATE_ONLY
1076
+ # rather than LABEL_STYLE_NONE, and if we can use disambiguate style
1077
+ # for new style ORM selects too.
1078
+ if (
1079
+ self.use_legacy_query_style
1080
+ and self.select_statement._label_style is LABEL_STYLE_LEGACY_ORM
1081
+ ):
1082
+ if not self.for_statement:
1083
+ self.label_style = LABEL_STYLE_TABLENAME_PLUS_COL
1084
+ else:
1085
+ self.label_style = LABEL_STYLE_DISAMBIGUATE_ONLY
1086
+ else:
1087
+ self.label_style = self.select_statement._label_style
1088
+
1089
+ if select_statement._memoized_select_entities:
1090
+ self._memoized_entities = {
1091
+ memoized_entities: _QueryEntity.to_compile_state(
1092
+ self,
1093
+ memoized_entities._raw_columns,
1094
+ [],
1095
+ is_current_entities=False,
1096
+ )
1097
+ for memoized_entities in (
1098
+ select_statement._memoized_select_entities
1099
+ )
1100
+ }
1101
+
1102
+ # label_convention is stateful and will yield deduping keys if it
1103
+ # sees the same key twice. therefore it's important that it is not
1104
+ # invoked for the above "memoized" entities that aren't actually
1105
+ # in the columns clause
1106
+ self._label_convention = self._column_naming_convention(
1107
+ statement._label_style, self.use_legacy_query_style
1108
+ )
1109
+
1110
+ _QueryEntity.to_compile_state(
1111
+ self,
1112
+ select_statement._raw_columns,
1113
+ self._entities,
1114
+ is_current_entities=True,
1115
+ )
1116
+
1117
+ self.current_path = select_statement._compile_options._current_path
1118
+
1119
+ self.eager_order_by = ()
1120
+
1121
+ self._init_global_attributes(
1122
+ select_statement,
1123
+ compiler,
1124
+ toplevel=toplevel,
1125
+ process_criteria_for_toplevel=False,
1126
+ )
1127
+
1128
+ if toplevel and (
1129
+ select_statement._with_options
1130
+ or select_statement._memoized_select_entities
1131
+ ):
1132
+ for (
1133
+ memoized_entities
1134
+ ) in select_statement._memoized_select_entities:
1135
+ for opt in memoized_entities._with_options:
1136
+ if opt._is_compile_state:
1137
+ opt.process_compile_state_replaced_entities(
1138
+ self,
1139
+ [
1140
+ ent
1141
+ for ent in self._memoized_entities[
1142
+ memoized_entities
1143
+ ]
1144
+ if isinstance(ent, _MapperEntity)
1145
+ ],
1146
+ )
1147
+
1148
+ for opt in self.select_statement._with_options:
1149
+ if opt._is_compile_state:
1150
+ opt.process_compile_state(self)
1151
+
1152
+ # uncomment to print out the context.attributes structure
1153
+ # after it's been set up above
1154
+ # self._dump_option_struct()
1155
+
1156
+ if select_statement._with_context_options:
1157
+ for fn, key in select_statement._with_context_options:
1158
+ fn(self)
1159
+
1160
+ self.primary_columns = []
1161
+ self.secondary_columns = []
1162
+ self.dedupe_columns = set()
1163
+ self.eager_joins = {}
1164
+ self.extra_criteria_entities = {}
1165
+ self.create_eager_joins = []
1166
+ self._fallback_from_clauses = []
1167
+
1168
+ # normalize the FROM clauses early by themselves, as this makes
1169
+ # it an easier job when we need to assemble a JOIN onto these,
1170
+ # for select.join() as well as joinedload(). As of 1.4 there are now
1171
+ # potentially more complex sets of FROM objects here as the use
1172
+ # of lambda statements for lazyload, load_on_pk etc. uses more
1173
+ # cloning of the select() construct. See #6495
1174
+ self.from_clauses = self._normalize_froms(
1175
+ info.selectable for info in select_statement._from_obj
1176
+ )
1177
+
1178
+ # this is a fairly arbitrary break into a second method,
1179
+ # so it might be nicer to break up create_for_statement()
1180
+ # and _setup_for_generate into three or four logical sections
1181
+ self._setup_for_generate()
1182
+
1183
+ SelectState.__init__(self, self.statement, compiler, **kw)
1184
+ return self
1185
+
1186
+ def _dump_option_struct(self):
1187
+ print("\n---------------------------------------------------\n")
1188
+ print(f"current path: {self.current_path}")
1189
+ for key in self.attributes:
1190
+ if isinstance(key, tuple) and key[0] == "loader":
1191
+ print(f"\nLoader: {PathRegistry.coerce(key[1])}")
1192
+ print(f" {self.attributes[key]}")
1193
+ print(f" {self.attributes[key].__dict__}")
1194
+ elif isinstance(key, tuple) and key[0] == "path_with_polymorphic":
1195
+ print(f"\nWith Polymorphic: {PathRegistry.coerce(key[1])}")
1196
+ print(f" {self.attributes[key]}")
1197
+
1198
+ def _setup_for_generate(self):
1199
+ query = self.select_statement
1200
+
1201
+ self.statement = None
1202
+ self._join_entities = ()
1203
+
1204
+ if self.compile_options._set_base_alias:
1205
+ # legacy Query only
1206
+ self._set_select_from_alias()
1207
+
1208
+ for memoized_entities in query._memoized_select_entities:
1209
+ if memoized_entities._setup_joins:
1210
+ self._join(
1211
+ memoized_entities._setup_joins,
1212
+ self._memoized_entities[memoized_entities],
1213
+ )
1214
+
1215
+ if query._setup_joins:
1216
+ self._join(query._setup_joins, self._entities)
1217
+
1218
+ current_adapter = self._get_current_adapter()
1219
+
1220
+ if query._where_criteria:
1221
+ self._where_criteria = query._where_criteria
1222
+
1223
+ if current_adapter:
1224
+ self._where_criteria = tuple(
1225
+ current_adapter(crit, True)
1226
+ for crit in self._where_criteria
1227
+ )
1228
+
1229
+ # TODO: some complexity with order_by here was due to mapper.order_by.
1230
+ # now that this is removed we can hopefully make order_by /
1231
+ # group_by act identically to how they are in Core select.
1232
+ self.order_by = (
1233
+ self._adapt_col_list(query._order_by_clauses, current_adapter)
1234
+ if current_adapter and query._order_by_clauses not in (None, False)
1235
+ else query._order_by_clauses
1236
+ )
1237
+
1238
+ if query._having_criteria:
1239
+ self._having_criteria = tuple(
1240
+ current_adapter(crit, True) if current_adapter else crit
1241
+ for crit in query._having_criteria
1242
+ )
1243
+
1244
+ self.group_by = (
1245
+ self._adapt_col_list(
1246
+ util.flatten_iterator(query._group_by_clauses), current_adapter
1247
+ )
1248
+ if current_adapter and query._group_by_clauses not in (None, False)
1249
+ else query._group_by_clauses or None
1250
+ )
1251
+
1252
+ if self.eager_order_by:
1253
+ adapter = self.from_clauses[0]._target_adapter
1254
+ self.eager_order_by = adapter.copy_and_process(self.eager_order_by)
1255
+
1256
+ if query._distinct_on:
1257
+ self.distinct_on = self._adapt_col_list(
1258
+ query._distinct_on, current_adapter
1259
+ )
1260
+ else:
1261
+ self.distinct_on = ()
1262
+
1263
+ self.distinct = query._distinct
1264
+
1265
+ if query._correlate:
1266
+ # ORM mapped entities that are mapped to joins can be passed
1267
+ # to .correlate, so here they are broken into their component
1268
+ # tables.
1269
+ self.correlate = tuple(
1270
+ util.flatten_iterator(
1271
+ sql_util.surface_selectables(s) if s is not None else None
1272
+ for s in query._correlate
1273
+ )
1274
+ )
1275
+ elif query._correlate_except is not None:
1276
+ self.correlate_except = tuple(
1277
+ util.flatten_iterator(
1278
+ sql_util.surface_selectables(s) if s is not None else None
1279
+ for s in query._correlate_except
1280
+ )
1281
+ )
1282
+ elif not query._auto_correlate:
1283
+ self.correlate = (None,)
1284
+
1285
+ # PART II
1286
+
1287
+ self._for_update_arg = query._for_update_arg
1288
+
1289
+ if self.compile_options._is_star and (len(self._entities) != 1):
1290
+ raise sa_exc.CompileError(
1291
+ "Can't generate ORM query that includes multiple expressions "
1292
+ "at the same time as '*'; query for '*' alone if present"
1293
+ )
1294
+ for entity in self._entities:
1295
+ entity.setup_compile_state(self)
1296
+
1297
+ for rec in self.create_eager_joins:
1298
+ strategy = rec[0]
1299
+ strategy(self, *rec[1:])
1300
+
1301
+ # else "load from discrete FROMs" mode,
1302
+ # i.e. when each _MappedEntity has its own FROM
1303
+
1304
+ if self.compile_options._enable_single_crit:
1305
+ self._adjust_for_extra_criteria()
1306
+
1307
+ if not self.primary_columns:
1308
+ if self.compile_options._only_load_props:
1309
+ assert False, "no columns were included in _only_load_props"
1310
+
1311
+ raise sa_exc.InvalidRequestError(
1312
+ "Query contains no columns with which to SELECT from."
1313
+ )
1314
+
1315
+ if not self.from_clauses:
1316
+ self.from_clauses = list(self._fallback_from_clauses)
1317
+
1318
+ if self.order_by is False:
1319
+ self.order_by = None
1320
+
1321
+ if (
1322
+ self.multi_row_eager_loaders
1323
+ and self.eager_adding_joins
1324
+ and self._should_nest_selectable
1325
+ ):
1326
+ self.statement = self._compound_eager_statement()
1327
+ else:
1328
+ self.statement = self._simple_statement()
1329
+
1330
+ if self.for_statement:
1331
+ ezero = self._mapper_zero()
1332
+ if ezero is not None:
1333
+ # TODO: this goes away once we get rid of the deep entity
1334
+ # thing
1335
+ self.statement = self.statement._annotate(
1336
+ {"deepentity": ezero}
1337
+ )
1338
+
1339
+ @classmethod
1340
+ def _create_entities_collection(cls, query, legacy):
1341
+ """Creates a partial ORMSelectCompileState that includes
1342
+ the full collection of _MapperEntity and other _QueryEntity objects.
1343
+
1344
+ Supports a few remaining use cases that are pre-compilation
1345
+ but still need to gather some of the column / adaption information.
1346
+
1347
+ """
1348
+ self = cls.__new__(cls)
1349
+
1350
+ self._entities = []
1351
+ self._primary_entity = None
1352
+ self._polymorphic_adapters = {}
1353
+
1354
+ self._label_convention = self._column_naming_convention(
1355
+ query._label_style, legacy
1356
+ )
1357
+
1358
+ # entities will also set up polymorphic adapters for mappers
1359
+ # that have with_polymorphic configured
1360
+ _QueryEntity.to_compile_state(
1361
+ self, query._raw_columns, self._entities, is_current_entities=True
1362
+ )
1363
+ return self
1364
+
1365
+ @classmethod
1366
+ def determine_last_joined_entity(cls, statement):
1367
+ setup_joins = statement._setup_joins
1368
+
1369
+ return _determine_last_joined_entity(setup_joins, None)
1370
+
1371
+ @classmethod
1372
+ def all_selected_columns(cls, statement):
1373
+ for element in statement._raw_columns:
1374
+ if (
1375
+ element.is_selectable
1376
+ and "entity_namespace" in element._annotations
1377
+ ):
1378
+ ens = element._annotations["entity_namespace"]
1379
+ if not ens.is_mapper and not ens.is_aliased_class:
1380
+ yield from _select_iterables([element])
1381
+ else:
1382
+ yield from _select_iterables(ens._all_column_expressions)
1383
+ else:
1384
+ yield from _select_iterables([element])
1385
+
1386
+ @classmethod
1387
+ def get_columns_clause_froms(cls, statement):
1388
+ return cls._normalize_froms(
1389
+ itertools.chain.from_iterable(
1390
+ (
1391
+ element._from_objects
1392
+ if "parententity" not in element._annotations
1393
+ else [
1394
+ element._annotations[
1395
+ "parententity"
1396
+ ].__clause_element__()
1397
+ ]
1398
+ )
1399
+ for element in statement._raw_columns
1400
+ )
1401
+ )
1402
+
1403
+ @classmethod
1404
+ def from_statement(cls, statement, from_statement):
1405
+ from_statement = coercions.expect(
1406
+ roles.ReturnsRowsRole,
1407
+ from_statement,
1408
+ apply_propagate_attrs=statement,
1409
+ )
1410
+
1411
+ stmt = FromStatement(statement._raw_columns, from_statement)
1412
+
1413
+ stmt.__dict__.update(
1414
+ _with_options=statement._with_options,
1415
+ _with_context_options=statement._with_context_options,
1416
+ _execution_options=statement._execution_options,
1417
+ _propagate_attrs=statement._propagate_attrs,
1418
+ )
1419
+ return stmt
1420
+
1421
+ def _set_select_from_alias(self):
1422
+ """used only for legacy Query cases"""
1423
+
1424
+ query = self.select_statement # query
1425
+
1426
+ assert self.compile_options._set_base_alias
1427
+ assert len(query._from_obj) == 1
1428
+
1429
+ adapter = self._get_select_from_alias_from_obj(query._from_obj[0])
1430
+ if adapter:
1431
+ self.compile_options += {"_enable_single_crit": False}
1432
+ self._from_obj_alias = adapter
1433
+
1434
+ def _get_select_from_alias_from_obj(self, from_obj):
1435
+ """used only for legacy Query cases"""
1436
+
1437
+ info = from_obj
1438
+
1439
+ if "parententity" in info._annotations:
1440
+ info = info._annotations["parententity"]
1441
+
1442
+ if hasattr(info, "mapper"):
1443
+ if not info.is_aliased_class:
1444
+ raise sa_exc.ArgumentError(
1445
+ "A selectable (FromClause) instance is "
1446
+ "expected when the base alias is being set."
1447
+ )
1448
+ else:
1449
+ return info._adapter
1450
+
1451
+ elif isinstance(info.selectable, sql.selectable.AliasedReturnsRows):
1452
+ equivs = self._all_equivs()
1453
+ assert info is info.selectable
1454
+ return ORMStatementAdapter(
1455
+ _TraceAdaptRole.LEGACY_SELECT_FROM_ALIAS,
1456
+ info.selectable,
1457
+ equivalents=equivs,
1458
+ )
1459
+ else:
1460
+ return None
1461
+
1462
+ def _mapper_zero(self):
1463
+ """return the Mapper associated with the first QueryEntity."""
1464
+ return self._entities[0].mapper
1465
+
1466
+ def _entity_zero(self):
1467
+ """Return the 'entity' (mapper or AliasedClass) associated
1468
+ with the first QueryEntity, or alternatively the 'select from'
1469
+ entity if specified."""
1470
+
1471
+ for ent in self.from_clauses:
1472
+ if "parententity" in ent._annotations:
1473
+ return ent._annotations["parententity"]
1474
+ for qent in self._entities:
1475
+ if qent.entity_zero:
1476
+ return qent.entity_zero
1477
+
1478
+ return None
1479
+
1480
+ def _only_full_mapper_zero(self, methname):
1481
+ if self._entities != [self._primary_entity]:
1482
+ raise sa_exc.InvalidRequestError(
1483
+ "%s() can only be used against "
1484
+ "a single mapped class." % methname
1485
+ )
1486
+ return self._primary_entity.entity_zero
1487
+
1488
+ def _only_entity_zero(self, rationale=None):
1489
+ if len(self._entities) > 1:
1490
+ raise sa_exc.InvalidRequestError(
1491
+ rationale
1492
+ or "This operation requires a Query "
1493
+ "against a single mapper."
1494
+ )
1495
+ return self._entity_zero()
1496
+
1497
+ def _all_equivs(self):
1498
+ equivs = {}
1499
+
1500
+ for memoized_entities in self._memoized_entities.values():
1501
+ for ent in [
1502
+ ent
1503
+ for ent in memoized_entities
1504
+ if isinstance(ent, _MapperEntity)
1505
+ ]:
1506
+ equivs.update(ent.mapper._equivalent_columns)
1507
+
1508
+ for ent in [
1509
+ ent for ent in self._entities if isinstance(ent, _MapperEntity)
1510
+ ]:
1511
+ equivs.update(ent.mapper._equivalent_columns)
1512
+ return equivs
1513
+
1514
+ def _compound_eager_statement(self):
1515
+ # for eager joins present and LIMIT/OFFSET/DISTINCT,
1516
+ # wrap the query inside a select,
1517
+ # then append eager joins onto that
1518
+
1519
+ if self.order_by:
1520
+ # the default coercion for ORDER BY is now the OrderByRole,
1521
+ # which adds an additional post coercion to ByOfRole in that
1522
+ # elements are converted into label references. For the
1523
+ # eager load / subquery wrapping case, we need to un-coerce
1524
+ # the original expressions outside of the label references
1525
+ # in order to have them render.
1526
+ unwrapped_order_by = [
1527
+ (
1528
+ elem.element
1529
+ if isinstance(elem, sql.elements._label_reference)
1530
+ else elem
1531
+ )
1532
+ for elem in self.order_by
1533
+ ]
1534
+
1535
+ order_by_col_expr = sql_util.expand_column_list_from_order_by(
1536
+ self.primary_columns, unwrapped_order_by
1537
+ )
1538
+ else:
1539
+ order_by_col_expr = []
1540
+ unwrapped_order_by = None
1541
+
1542
+ # put FOR UPDATE on the inner query, where MySQL will honor it,
1543
+ # as well as if it has an OF so PostgreSQL can use it.
1544
+ inner = self._select_statement(
1545
+ self.primary_columns
1546
+ + [c for c in order_by_col_expr if c not in self.dedupe_columns],
1547
+ self.from_clauses,
1548
+ self._where_criteria,
1549
+ self._having_criteria,
1550
+ self.label_style,
1551
+ self.order_by,
1552
+ for_update=self._for_update_arg,
1553
+ hints=self.select_statement._hints,
1554
+ statement_hints=self.select_statement._statement_hints,
1555
+ correlate=self.correlate,
1556
+ correlate_except=self.correlate_except,
1557
+ **self._select_args,
1558
+ )
1559
+
1560
+ inner = inner.alias()
1561
+
1562
+ equivs = self._all_equivs()
1563
+
1564
+ self.compound_eager_adapter = ORMStatementAdapter(
1565
+ _TraceAdaptRole.COMPOUND_EAGER_STATEMENT, inner, equivalents=equivs
1566
+ )
1567
+
1568
+ statement = future.select(
1569
+ *([inner] + self.secondary_columns) # use_labels=self.labels
1570
+ )
1571
+ statement._label_style = self.label_style
1572
+
1573
+ # Oracle however does not allow FOR UPDATE on the subquery,
1574
+ # and the Oracle dialect ignores it, plus for PostgreSQL, MySQL
1575
+ # we expect that all elements of the row are locked, so also put it
1576
+ # on the outside (except in the case of PG when OF is used)
1577
+ if (
1578
+ self._for_update_arg is not None
1579
+ and self._for_update_arg.of is None
1580
+ ):
1581
+ statement._for_update_arg = self._for_update_arg
1582
+
1583
+ from_clause = inner
1584
+ for eager_join in self.eager_joins.values():
1585
+ # EagerLoader places a 'stop_on' attribute on the join,
1586
+ # giving us a marker as to where the "splice point" of
1587
+ # the join should be
1588
+ from_clause = sql_util.splice_joins(
1589
+ from_clause, eager_join, eager_join.stop_on
1590
+ )
1591
+
1592
+ statement.select_from.non_generative(statement, from_clause)
1593
+
1594
+ if unwrapped_order_by:
1595
+ statement.order_by.non_generative(
1596
+ statement,
1597
+ *self.compound_eager_adapter.copy_and_process(
1598
+ unwrapped_order_by
1599
+ ),
1600
+ )
1601
+
1602
+ statement.order_by.non_generative(statement, *self.eager_order_by)
1603
+ return statement
1604
+
1605
+ def _simple_statement(self):
1606
+ statement = self._select_statement(
1607
+ self.primary_columns + self.secondary_columns,
1608
+ tuple(self.from_clauses) + tuple(self.eager_joins.values()),
1609
+ self._where_criteria,
1610
+ self._having_criteria,
1611
+ self.label_style,
1612
+ self.order_by,
1613
+ for_update=self._for_update_arg,
1614
+ hints=self.select_statement._hints,
1615
+ statement_hints=self.select_statement._statement_hints,
1616
+ correlate=self.correlate,
1617
+ correlate_except=self.correlate_except,
1618
+ **self._select_args,
1619
+ )
1620
+
1621
+ if self.eager_order_by:
1622
+ statement.order_by.non_generative(statement, *self.eager_order_by)
1623
+ return statement
1624
+
1625
+ def _select_statement(
1626
+ self,
1627
+ raw_columns,
1628
+ from_obj,
1629
+ where_criteria,
1630
+ having_criteria,
1631
+ label_style,
1632
+ order_by,
1633
+ for_update,
1634
+ hints,
1635
+ statement_hints,
1636
+ correlate,
1637
+ correlate_except,
1638
+ limit_clause,
1639
+ offset_clause,
1640
+ fetch_clause,
1641
+ fetch_clause_options,
1642
+ distinct,
1643
+ distinct_on,
1644
+ prefixes,
1645
+ suffixes,
1646
+ group_by,
1647
+ independent_ctes,
1648
+ independent_ctes_opts,
1649
+ ):
1650
+ statement = Select._create_raw_select(
1651
+ _raw_columns=raw_columns,
1652
+ _from_obj=from_obj,
1653
+ _label_style=label_style,
1654
+ )
1655
+
1656
+ if where_criteria:
1657
+ statement._where_criteria = where_criteria
1658
+ if having_criteria:
1659
+ statement._having_criteria = having_criteria
1660
+
1661
+ if order_by:
1662
+ statement._order_by_clauses += tuple(order_by)
1663
+
1664
+ if distinct_on:
1665
+ statement.distinct.non_generative(statement, *distinct_on)
1666
+ elif distinct:
1667
+ statement.distinct.non_generative(statement)
1668
+
1669
+ if group_by:
1670
+ statement._group_by_clauses += tuple(group_by)
1671
+
1672
+ statement._limit_clause = limit_clause
1673
+ statement._offset_clause = offset_clause
1674
+ statement._fetch_clause = fetch_clause
1675
+ statement._fetch_clause_options = fetch_clause_options
1676
+ statement._independent_ctes = independent_ctes
1677
+ statement._independent_ctes_opts = independent_ctes_opts
1678
+
1679
+ if prefixes:
1680
+ statement._prefixes = prefixes
1681
+
1682
+ if suffixes:
1683
+ statement._suffixes = suffixes
1684
+
1685
+ statement._for_update_arg = for_update
1686
+
1687
+ if hints:
1688
+ statement._hints = hints
1689
+ if statement_hints:
1690
+ statement._statement_hints = statement_hints
1691
+
1692
+ if correlate:
1693
+ statement.correlate.non_generative(statement, *correlate)
1694
+
1695
+ if correlate_except is not None:
1696
+ statement.correlate_except.non_generative(
1697
+ statement, *correlate_except
1698
+ )
1699
+
1700
+ return statement
1701
+
1702
+ def _adapt_polymorphic_element(self, element):
1703
+ if "parententity" in element._annotations:
1704
+ search = element._annotations["parententity"]
1705
+ alias = self._polymorphic_adapters.get(search, None)
1706
+ if alias:
1707
+ return alias.adapt_clause(element)
1708
+
1709
+ if isinstance(element, expression.FromClause):
1710
+ search = element
1711
+ elif hasattr(element, "table"):
1712
+ search = element.table
1713
+ else:
1714
+ return None
1715
+
1716
+ alias = self._polymorphic_adapters.get(search, None)
1717
+ if alias:
1718
+ return alias.adapt_clause(element)
1719
+
1720
+ def _adapt_col_list(self, cols, current_adapter):
1721
+ if current_adapter:
1722
+ return [current_adapter(o, True) for o in cols]
1723
+ else:
1724
+ return cols
1725
+
1726
+ def _get_current_adapter(self):
1727
+ adapters = []
1728
+
1729
+ if self._from_obj_alias:
1730
+ # used for legacy going forward for query set_ops, e.g.
1731
+ # union(), union_all(), etc.
1732
+ # 1.4 and previously, also used for from_self(),
1733
+ # select_entity_from()
1734
+ #
1735
+ # for the "from obj" alias, apply extra rule to the
1736
+ # 'ORM only' check, if this query were generated from a
1737
+ # subquery of itself, i.e. _from_selectable(), apply adaption
1738
+ # to all SQL constructs.
1739
+ adapters.append(
1740
+ (
1741
+ True,
1742
+ self._from_obj_alias.replace,
1743
+ )
1744
+ )
1745
+
1746
+ # this was *hopefully* the only adapter we were going to need
1747
+ # going forward...however, we unfortunately need _from_obj_alias
1748
+ # for query.union(), which we can't drop
1749
+ if self._polymorphic_adapters:
1750
+ adapters.append((False, self._adapt_polymorphic_element))
1751
+
1752
+ if not adapters:
1753
+ return None
1754
+
1755
+ def _adapt_clause(clause, as_filter):
1756
+ # do we adapt all expression elements or only those
1757
+ # tagged as 'ORM' constructs ?
1758
+
1759
+ def replace(elem):
1760
+ is_orm_adapt = (
1761
+ "_orm_adapt" in elem._annotations
1762
+ or "parententity" in elem._annotations
1763
+ )
1764
+ for always_adapt, adapter in adapters:
1765
+ if is_orm_adapt or always_adapt:
1766
+ e = adapter(elem)
1767
+ if e is not None:
1768
+ return e
1769
+
1770
+ return visitors.replacement_traverse(clause, {}, replace)
1771
+
1772
+ return _adapt_clause
1773
+
1774
+ def _join(self, args, entities_collection):
1775
+ for right, onclause, from_, flags in args:
1776
+ isouter = flags["isouter"]
1777
+ full = flags["full"]
1778
+
1779
+ right = inspect(right)
1780
+ if onclause is not None:
1781
+ onclause = inspect(onclause)
1782
+
1783
+ if isinstance(right, interfaces.PropComparator):
1784
+ if onclause is not None:
1785
+ raise sa_exc.InvalidRequestError(
1786
+ "No 'on clause' argument may be passed when joining "
1787
+ "to a relationship path as a target"
1788
+ )
1789
+
1790
+ onclause = right
1791
+ right = None
1792
+ elif "parententity" in right._annotations:
1793
+ right = right._annotations["parententity"]
1794
+
1795
+ if onclause is None:
1796
+ if not right.is_selectable and not hasattr(right, "mapper"):
1797
+ raise sa_exc.ArgumentError(
1798
+ "Expected mapped entity or "
1799
+ "selectable/table as join target"
1800
+ )
1801
+
1802
+ of_type = None
1803
+
1804
+ if isinstance(onclause, interfaces.PropComparator):
1805
+ # descriptor/property given (or determined); this tells us
1806
+ # explicitly what the expected "left" side of the join is.
1807
+
1808
+ of_type = getattr(onclause, "_of_type", None)
1809
+
1810
+ if right is None:
1811
+ if of_type:
1812
+ right = of_type
1813
+ else:
1814
+ right = onclause.property
1815
+
1816
+ try:
1817
+ right = right.entity
1818
+ except AttributeError as err:
1819
+ raise sa_exc.ArgumentError(
1820
+ "Join target %s does not refer to a "
1821
+ "mapped entity" % right
1822
+ ) from err
1823
+
1824
+ left = onclause._parententity
1825
+
1826
+ prop = onclause.property
1827
+ if not isinstance(onclause, attributes.QueryableAttribute):
1828
+ onclause = prop
1829
+
1830
+ # check for this path already present. don't render in that
1831
+ # case.
1832
+ if (left, right, prop.key) in self._already_joined_edges:
1833
+ continue
1834
+
1835
+ if from_ is not None:
1836
+ if (
1837
+ from_ is not left
1838
+ and from_._annotations.get("parententity", None)
1839
+ is not left
1840
+ ):
1841
+ raise sa_exc.InvalidRequestError(
1842
+ "explicit from clause %s does not match left side "
1843
+ "of relationship attribute %s"
1844
+ % (
1845
+ from_._annotations.get("parententity", from_),
1846
+ onclause,
1847
+ )
1848
+ )
1849
+ elif from_ is not None:
1850
+ prop = None
1851
+ left = from_
1852
+ else:
1853
+ # no descriptor/property given; we will need to figure out
1854
+ # what the effective "left" side is
1855
+ prop = left = None
1856
+
1857
+ # figure out the final "left" and "right" sides and create an
1858
+ # ORMJoin to add to our _from_obj tuple
1859
+ self._join_left_to_right(
1860
+ entities_collection,
1861
+ left,
1862
+ right,
1863
+ onclause,
1864
+ prop,
1865
+ isouter,
1866
+ full,
1867
+ )
1868
+
1869
+ def _join_left_to_right(
1870
+ self,
1871
+ entities_collection,
1872
+ left,
1873
+ right,
1874
+ onclause,
1875
+ prop,
1876
+ outerjoin,
1877
+ full,
1878
+ ):
1879
+ """given raw "left", "right", "onclause" parameters consumed from
1880
+ a particular key within _join(), add a real ORMJoin object to
1881
+ our _from_obj list (or augment an existing one)
1882
+
1883
+ """
1884
+
1885
+ if left is None:
1886
+ # left not given (e.g. no relationship object/name specified)
1887
+ # figure out the best "left" side based on our existing froms /
1888
+ # entities
1889
+ assert prop is None
1890
+ (
1891
+ left,
1892
+ replace_from_obj_index,
1893
+ use_entity_index,
1894
+ ) = self._join_determine_implicit_left_side(
1895
+ entities_collection, left, right, onclause
1896
+ )
1897
+ else:
1898
+ # left is given via a relationship/name, or as explicit left side.
1899
+ # Determine where in our
1900
+ # "froms" list it should be spliced/appended as well as what
1901
+ # existing entity it corresponds to.
1902
+ (
1903
+ replace_from_obj_index,
1904
+ use_entity_index,
1905
+ ) = self._join_place_explicit_left_side(entities_collection, left)
1906
+
1907
+ if left is right:
1908
+ raise sa_exc.InvalidRequestError(
1909
+ "Can't construct a join from %s to %s, they "
1910
+ "are the same entity" % (left, right)
1911
+ )
1912
+
1913
+ # the right side as given often needs to be adapted. additionally
1914
+ # a lot of things can be wrong with it. handle all that and
1915
+ # get back the new effective "right" side
1916
+ r_info, right, onclause = self._join_check_and_adapt_right_side(
1917
+ left, right, onclause, prop
1918
+ )
1919
+
1920
+ if not r_info.is_selectable:
1921
+ extra_criteria = self._get_extra_criteria(r_info)
1922
+ else:
1923
+ extra_criteria = ()
1924
+
1925
+ if replace_from_obj_index is not None:
1926
+ # splice into an existing element in the
1927
+ # self._from_obj list
1928
+ left_clause = self.from_clauses[replace_from_obj_index]
1929
+
1930
+ self.from_clauses = (
1931
+ self.from_clauses[:replace_from_obj_index]
1932
+ + [
1933
+ _ORMJoin(
1934
+ left_clause,
1935
+ right,
1936
+ onclause,
1937
+ isouter=outerjoin,
1938
+ full=full,
1939
+ _extra_criteria=extra_criteria,
1940
+ )
1941
+ ]
1942
+ + self.from_clauses[replace_from_obj_index + 1 :]
1943
+ )
1944
+ else:
1945
+ # add a new element to the self._from_obj list
1946
+ if use_entity_index is not None:
1947
+ # make use of _MapperEntity selectable, which is usually
1948
+ # entity_zero.selectable, but if with_polymorphic() were used
1949
+ # might be distinct
1950
+ assert isinstance(
1951
+ entities_collection[use_entity_index], _MapperEntity
1952
+ )
1953
+ left_clause = entities_collection[use_entity_index].selectable
1954
+ else:
1955
+ left_clause = left
1956
+
1957
+ self.from_clauses = self.from_clauses + [
1958
+ _ORMJoin(
1959
+ left_clause,
1960
+ r_info,
1961
+ onclause,
1962
+ isouter=outerjoin,
1963
+ full=full,
1964
+ _extra_criteria=extra_criteria,
1965
+ )
1966
+ ]
1967
+
1968
+ def _join_determine_implicit_left_side(
1969
+ self, entities_collection, left, right, onclause
1970
+ ):
1971
+ """When join conditions don't express the left side explicitly,
1972
+ determine if an existing FROM or entity in this query
1973
+ can serve as the left hand side.
1974
+
1975
+ """
1976
+
1977
+ # when we are here, it means join() was called without an ORM-
1978
+ # specific way of telling us what the "left" side is, e.g.:
1979
+ #
1980
+ # join(RightEntity)
1981
+ #
1982
+ # or
1983
+ #
1984
+ # join(RightEntity, RightEntity.foo == LeftEntity.bar)
1985
+ #
1986
+
1987
+ r_info = inspect(right)
1988
+
1989
+ replace_from_obj_index = use_entity_index = None
1990
+
1991
+ if self.from_clauses:
1992
+ # we have a list of FROMs already. So by definition this
1993
+ # join has to connect to one of those FROMs.
1994
+
1995
+ indexes = sql_util.find_left_clause_to_join_from(
1996
+ self.from_clauses, r_info.selectable, onclause
1997
+ )
1998
+
1999
+ if len(indexes) == 1:
2000
+ replace_from_obj_index = indexes[0]
2001
+ left = self.from_clauses[replace_from_obj_index]
2002
+ elif len(indexes) > 1:
2003
+ raise sa_exc.InvalidRequestError(
2004
+ "Can't determine which FROM clause to join "
2005
+ "from, there are multiple FROMS which can "
2006
+ "join to this entity. Please use the .select_from() "
2007
+ "method to establish an explicit left side, as well as "
2008
+ "providing an explicit ON clause if not present already "
2009
+ "to help resolve the ambiguity."
2010
+ )
2011
+ else:
2012
+ raise sa_exc.InvalidRequestError(
2013
+ "Don't know how to join to %r. "
2014
+ "Please use the .select_from() "
2015
+ "method to establish an explicit left side, as well as "
2016
+ "providing an explicit ON clause if not present already "
2017
+ "to help resolve the ambiguity." % (right,)
2018
+ )
2019
+
2020
+ elif entities_collection:
2021
+ # we have no explicit FROMs, so the implicit left has to
2022
+ # come from our list of entities.
2023
+
2024
+ potential = {}
2025
+ for entity_index, ent in enumerate(entities_collection):
2026
+ entity = ent.entity_zero_or_selectable
2027
+ if entity is None:
2028
+ continue
2029
+ ent_info = inspect(entity)
2030
+ if ent_info is r_info: # left and right are the same, skip
2031
+ continue
2032
+
2033
+ # by using a dictionary with the selectables as keys this
2034
+ # de-duplicates those selectables as occurs when the query is
2035
+ # against a series of columns from the same selectable
2036
+ if isinstance(ent, _MapperEntity):
2037
+ potential[ent.selectable] = (entity_index, entity)
2038
+ else:
2039
+ potential[ent_info.selectable] = (None, entity)
2040
+
2041
+ all_clauses = list(potential.keys())
2042
+ indexes = sql_util.find_left_clause_to_join_from(
2043
+ all_clauses, r_info.selectable, onclause
2044
+ )
2045
+
2046
+ if len(indexes) == 1:
2047
+ use_entity_index, left = potential[all_clauses[indexes[0]]]
2048
+ elif len(indexes) > 1:
2049
+ raise sa_exc.InvalidRequestError(
2050
+ "Can't determine which FROM clause to join "
2051
+ "from, there are multiple FROMS which can "
2052
+ "join to this entity. Please use the .select_from() "
2053
+ "method to establish an explicit left side, as well as "
2054
+ "providing an explicit ON clause if not present already "
2055
+ "to help resolve the ambiguity."
2056
+ )
2057
+ else:
2058
+ raise sa_exc.InvalidRequestError(
2059
+ "Don't know how to join to %r. "
2060
+ "Please use the .select_from() "
2061
+ "method to establish an explicit left side, as well as "
2062
+ "providing an explicit ON clause if not present already "
2063
+ "to help resolve the ambiguity." % (right,)
2064
+ )
2065
+ else:
2066
+ raise sa_exc.InvalidRequestError(
2067
+ "No entities to join from; please use "
2068
+ "select_from() to establish the left "
2069
+ "entity/selectable of this join"
2070
+ )
2071
+
2072
+ return left, replace_from_obj_index, use_entity_index
2073
+
2074
+ def _join_place_explicit_left_side(self, entities_collection, left):
2075
+ """When join conditions express a left side explicitly, determine
2076
+ where in our existing list of FROM clauses we should join towards,
2077
+ or if we need to make a new join, and if so is it from one of our
2078
+ existing entities.
2079
+
2080
+ """
2081
+
2082
+ # when we are here, it means join() was called with an indicator
2083
+ # as to an exact left side, which means a path to a
2084
+ # Relationship was given, e.g.:
2085
+ #
2086
+ # join(RightEntity, LeftEntity.right)
2087
+ #
2088
+ # or
2089
+ #
2090
+ # join(LeftEntity.right)
2091
+ #
2092
+ # as well as string forms:
2093
+ #
2094
+ # join(RightEntity, "right")
2095
+ #
2096
+ # etc.
2097
+ #
2098
+
2099
+ replace_from_obj_index = use_entity_index = None
2100
+
2101
+ l_info = inspect(left)
2102
+ if self.from_clauses:
2103
+ indexes = sql_util.find_left_clause_that_matches_given(
2104
+ self.from_clauses, l_info.selectable
2105
+ )
2106
+
2107
+ if len(indexes) > 1:
2108
+ raise sa_exc.InvalidRequestError(
2109
+ "Can't identify which entity in which to assign the "
2110
+ "left side of this join. Please use a more specific "
2111
+ "ON clause."
2112
+ )
2113
+
2114
+ # have an index, means the left side is already present in
2115
+ # an existing FROM in the self._from_obj tuple
2116
+ if indexes:
2117
+ replace_from_obj_index = indexes[0]
2118
+
2119
+ # no index, means we need to add a new element to the
2120
+ # self._from_obj tuple
2121
+
2122
+ # no from element present, so we will have to add to the
2123
+ # self._from_obj tuple. Determine if this left side matches up
2124
+ # with existing mapper entities, in which case we want to apply the
2125
+ # aliasing / adaptation rules present on that entity if any
2126
+ if (
2127
+ replace_from_obj_index is None
2128
+ and entities_collection
2129
+ and hasattr(l_info, "mapper")
2130
+ ):
2131
+ for idx, ent in enumerate(entities_collection):
2132
+ # TODO: should we be checking for multiple mapper entities
2133
+ # matching?
2134
+ if isinstance(ent, _MapperEntity) and ent.corresponds_to(left):
2135
+ use_entity_index = idx
2136
+ break
2137
+
2138
+ return replace_from_obj_index, use_entity_index
2139
+
2140
+ def _join_check_and_adapt_right_side(self, left, right, onclause, prop):
2141
+ """transform the "right" side of the join as well as the onclause
2142
+ according to polymorphic mapping translations, aliasing on the query
2143
+ or on the join, special cases where the right and left side have
2144
+ overlapping tables.
2145
+
2146
+ """
2147
+
2148
+ l_info = inspect(left)
2149
+ r_info = inspect(right)
2150
+
2151
+ overlap = False
2152
+
2153
+ right_mapper = getattr(r_info, "mapper", None)
2154
+ # if the target is a joined inheritance mapping,
2155
+ # be more liberal about auto-aliasing.
2156
+ if right_mapper and (
2157
+ right_mapper.with_polymorphic
2158
+ or isinstance(right_mapper.persist_selectable, expression.Join)
2159
+ ):
2160
+ for from_obj in self.from_clauses or [l_info.selectable]:
2161
+ if sql_util.selectables_overlap(
2162
+ l_info.selectable, from_obj
2163
+ ) and sql_util.selectables_overlap(
2164
+ from_obj, r_info.selectable
2165
+ ):
2166
+ overlap = True
2167
+ break
2168
+
2169
+ if overlap and l_info.selectable is r_info.selectable:
2170
+ raise sa_exc.InvalidRequestError(
2171
+ "Can't join table/selectable '%s' to itself"
2172
+ % l_info.selectable
2173
+ )
2174
+
2175
+ right_mapper, right_selectable, right_is_aliased = (
2176
+ getattr(r_info, "mapper", None),
2177
+ r_info.selectable,
2178
+ getattr(r_info, "is_aliased_class", False),
2179
+ )
2180
+
2181
+ if (
2182
+ right_mapper
2183
+ and prop
2184
+ and not right_mapper.common_parent(prop.mapper)
2185
+ ):
2186
+ raise sa_exc.InvalidRequestError(
2187
+ "Join target %s does not correspond to "
2188
+ "the right side of join condition %s" % (right, onclause)
2189
+ )
2190
+
2191
+ # _join_entities is used as a hint for single-table inheritance
2192
+ # purposes at the moment
2193
+ if hasattr(r_info, "mapper"):
2194
+ self._join_entities += (r_info,)
2195
+
2196
+ need_adapter = False
2197
+
2198
+ # test for joining to an unmapped selectable as the target
2199
+ if r_info.is_clause_element:
2200
+ if prop:
2201
+ right_mapper = prop.mapper
2202
+
2203
+ if right_selectable._is_lateral:
2204
+ # orm_only is disabled to suit the case where we have to
2205
+ # adapt an explicit correlate(Entity) - the select() loses
2206
+ # the ORM-ness in this case right now, ideally it would not
2207
+ current_adapter = self._get_current_adapter()
2208
+ if current_adapter is not None:
2209
+ # TODO: we had orm_only=False here before, removing
2210
+ # it didn't break things. if we identify the rationale,
2211
+ # may need to apply "_orm_only" annotation here.
2212
+ right = current_adapter(right, True)
2213
+
2214
+ elif prop:
2215
+ # joining to selectable with a mapper property given
2216
+ # as the ON clause
2217
+
2218
+ if not right_selectable.is_derived_from(
2219
+ right_mapper.persist_selectable
2220
+ ):
2221
+ raise sa_exc.InvalidRequestError(
2222
+ "Selectable '%s' is not derived from '%s'"
2223
+ % (
2224
+ right_selectable.description,
2225
+ right_mapper.persist_selectable.description,
2226
+ )
2227
+ )
2228
+
2229
+ # if the destination selectable is a plain select(),
2230
+ # turn it into an alias().
2231
+ if isinstance(right_selectable, expression.SelectBase):
2232
+ right_selectable = coercions.expect(
2233
+ roles.FromClauseRole, right_selectable
2234
+ )
2235
+ need_adapter = True
2236
+
2237
+ # make the right hand side target into an ORM entity
2238
+ right = AliasedClass(right_mapper, right_selectable)
2239
+
2240
+ util.warn_deprecated(
2241
+ "An alias is being generated automatically against "
2242
+ "joined entity %s for raw clauseelement, which is "
2243
+ "deprecated and will be removed in a later release. "
2244
+ "Use the aliased() "
2245
+ "construct explicitly, see the linked example."
2246
+ % right_mapper,
2247
+ "1.4",
2248
+ code="xaj1",
2249
+ )
2250
+
2251
+ # test for overlap:
2252
+ # orm/inheritance/relationships.py
2253
+ # SelfReferentialM2MTest
2254
+ aliased_entity = right_mapper and not right_is_aliased and overlap
2255
+
2256
+ if not need_adapter and aliased_entity:
2257
+ # there are a few places in the ORM that automatic aliasing
2258
+ # is still desirable, and can't be automatic with a Core
2259
+ # only approach. For illustrations of "overlaps" see
2260
+ # test/orm/inheritance/test_relationships.py. There are also
2261
+ # general overlap cases with many-to-many tables where automatic
2262
+ # aliasing is desirable.
2263
+ right = AliasedClass(right, flat=True)
2264
+ need_adapter = True
2265
+
2266
+ util.warn(
2267
+ "An alias is being generated automatically against "
2268
+ "joined entity %s due to overlapping tables. This is a "
2269
+ "legacy pattern which may be "
2270
+ "deprecated in a later release. Use the "
2271
+ "aliased(<entity>, flat=True) "
2272
+ "construct explicitly, see the linked example." % right_mapper,
2273
+ code="xaj2",
2274
+ )
2275
+
2276
+ if need_adapter:
2277
+ # if need_adapter is True, we are in a deprecated case and
2278
+ # a warning has been emitted.
2279
+ assert right_mapper
2280
+
2281
+ adapter = ORMAdapter(
2282
+ _TraceAdaptRole.DEPRECATED_JOIN_ADAPT_RIGHT_SIDE,
2283
+ inspect(right),
2284
+ equivalents=right_mapper._equivalent_columns,
2285
+ )
2286
+
2287
+ # if an alias() on the right side was generated,
2288
+ # which is intended to wrap a the right side in a subquery,
2289
+ # ensure that columns retrieved from this target in the result
2290
+ # set are also adapted.
2291
+ self._mapper_loads_polymorphically_with(right_mapper, adapter)
2292
+ elif (
2293
+ not r_info.is_clause_element
2294
+ and not right_is_aliased
2295
+ and right_mapper._has_aliased_polymorphic_fromclause
2296
+ ):
2297
+ # for the case where the target mapper has a with_polymorphic
2298
+ # set up, ensure an adapter is set up for criteria that works
2299
+ # against this mapper. Previously, this logic used to
2300
+ # use the "create_aliases or aliased_entity" case to generate
2301
+ # an aliased() object, but this creates an alias that isn't
2302
+ # strictly necessary.
2303
+ # see test/orm/test_core_compilation.py
2304
+ # ::RelNaturalAliasedJoinsTest::test_straight
2305
+ # and similar
2306
+ self._mapper_loads_polymorphically_with(
2307
+ right_mapper,
2308
+ ORMAdapter(
2309
+ _TraceAdaptRole.WITH_POLYMORPHIC_ADAPTER_RIGHT_JOIN,
2310
+ right_mapper,
2311
+ selectable=right_mapper.selectable,
2312
+ equivalents=right_mapper._equivalent_columns,
2313
+ ),
2314
+ )
2315
+ # if the onclause is a ClauseElement, adapt it with any
2316
+ # adapters that are in place right now
2317
+ if isinstance(onclause, expression.ClauseElement):
2318
+ current_adapter = self._get_current_adapter()
2319
+ if current_adapter:
2320
+ onclause = current_adapter(onclause, True)
2321
+
2322
+ # if joining on a MapperProperty path,
2323
+ # track the path to prevent redundant joins
2324
+ if prop:
2325
+ self._already_joined_edges += ((left, right, prop.key),)
2326
+
2327
+ return inspect(right), right, onclause
2328
+
2329
+ @property
2330
+ def _select_args(self):
2331
+ return {
2332
+ "limit_clause": self.select_statement._limit_clause,
2333
+ "offset_clause": self.select_statement._offset_clause,
2334
+ "distinct": self.distinct,
2335
+ "distinct_on": self.distinct_on,
2336
+ "prefixes": self.select_statement._prefixes,
2337
+ "suffixes": self.select_statement._suffixes,
2338
+ "group_by": self.group_by or None,
2339
+ "fetch_clause": self.select_statement._fetch_clause,
2340
+ "fetch_clause_options": (
2341
+ self.select_statement._fetch_clause_options
2342
+ ),
2343
+ "independent_ctes": self.select_statement._independent_ctes,
2344
+ "independent_ctes_opts": (
2345
+ self.select_statement._independent_ctes_opts
2346
+ ),
2347
+ }
2348
+
2349
+ @property
2350
+ def _should_nest_selectable(self):
2351
+ kwargs = self._select_args
2352
+ return (
2353
+ kwargs.get("limit_clause") is not None
2354
+ or kwargs.get("offset_clause") is not None
2355
+ or kwargs.get("distinct", False)
2356
+ or kwargs.get("distinct_on", ())
2357
+ or kwargs.get("group_by", False)
2358
+ )
2359
+
2360
+ def _get_extra_criteria(self, ext_info):
2361
+ if (
2362
+ "additional_entity_criteria",
2363
+ ext_info.mapper,
2364
+ ) in self.global_attributes:
2365
+ return tuple(
2366
+ ae._resolve_where_criteria(ext_info)
2367
+ for ae in self.global_attributes[
2368
+ ("additional_entity_criteria", ext_info.mapper)
2369
+ ]
2370
+ if (ae.include_aliases or ae.entity is ext_info)
2371
+ and ae._should_include(self)
2372
+ )
2373
+ else:
2374
+ return ()
2375
+
2376
+ def _adjust_for_extra_criteria(self):
2377
+ """Apply extra criteria filtering.
2378
+
2379
+ For all distinct single-table-inheritance mappers represented in
2380
+ the columns clause of this query, as well as the "select from entity",
2381
+ add criterion to the WHERE
2382
+ clause of the given QueryContext such that only the appropriate
2383
+ subtypes are selected from the total results.
2384
+
2385
+ Additionally, add WHERE criteria originating from LoaderCriteriaOptions
2386
+ associated with the global context.
2387
+
2388
+ """
2389
+
2390
+ for fromclause in self.from_clauses:
2391
+ ext_info = fromclause._annotations.get("parententity", None)
2392
+
2393
+ if (
2394
+ ext_info
2395
+ and (
2396
+ ext_info.mapper._single_table_criterion is not None
2397
+ or ("additional_entity_criteria", ext_info.mapper)
2398
+ in self.global_attributes
2399
+ )
2400
+ and ext_info not in self.extra_criteria_entities
2401
+ ):
2402
+ self.extra_criteria_entities[ext_info] = (
2403
+ ext_info,
2404
+ ext_info._adapter if ext_info.is_aliased_class else None,
2405
+ )
2406
+
2407
+ search = set(self.extra_criteria_entities.values())
2408
+
2409
+ for ext_info, adapter in search:
2410
+ if ext_info in self._join_entities:
2411
+ continue
2412
+
2413
+ single_crit = ext_info.mapper._single_table_criterion
2414
+
2415
+ if self.compile_options._for_refresh_state:
2416
+ additional_entity_criteria = []
2417
+ else:
2418
+ additional_entity_criteria = self._get_extra_criteria(ext_info)
2419
+
2420
+ if single_crit is not None:
2421
+ additional_entity_criteria += (single_crit,)
2422
+
2423
+ current_adapter = self._get_current_adapter()
2424
+ for crit in additional_entity_criteria:
2425
+ if adapter:
2426
+ crit = adapter.traverse(crit)
2427
+
2428
+ if current_adapter:
2429
+ crit = sql_util._deep_annotate(crit, {"_orm_adapt": True})
2430
+ crit = current_adapter(crit, False)
2431
+ self._where_criteria += (crit,)
2432
+
2433
+
2434
+ def _column_descriptions(
2435
+ query_or_select_stmt: Union[Query, Select, FromStatement],
2436
+ compile_state: Optional[ORMSelectCompileState] = None,
2437
+ legacy: bool = False,
2438
+ ) -> List[ORMColumnDescription]:
2439
+ if compile_state is None:
2440
+ compile_state = ORMSelectCompileState._create_entities_collection(
2441
+ query_or_select_stmt, legacy=legacy
2442
+ )
2443
+ ctx = compile_state
2444
+ d = [
2445
+ {
2446
+ "name": ent._label_name,
2447
+ "type": ent.type,
2448
+ "aliased": getattr(insp_ent, "is_aliased_class", False),
2449
+ "expr": ent.expr,
2450
+ "entity": (
2451
+ getattr(insp_ent, "entity", None)
2452
+ if ent.entity_zero is not None
2453
+ and not insp_ent.is_clause_element
2454
+ else None
2455
+ ),
2456
+ }
2457
+ for ent, insp_ent in [
2458
+ (_ent, _ent.entity_zero) for _ent in ctx._entities
2459
+ ]
2460
+ ]
2461
+ return d
2462
+
2463
+
2464
+ def _legacy_filter_by_entity_zero(
2465
+ query_or_augmented_select: Union[Query[Any], Select[Any]]
2466
+ ) -> Optional[_InternalEntityType[Any]]:
2467
+ self = query_or_augmented_select
2468
+ if self._setup_joins:
2469
+ _last_joined_entity = self._last_joined_entity
2470
+ if _last_joined_entity is not None:
2471
+ return _last_joined_entity
2472
+
2473
+ if self._from_obj and "parententity" in self._from_obj[0]._annotations:
2474
+ return self._from_obj[0]._annotations["parententity"]
2475
+
2476
+ return _entity_from_pre_ent_zero(self)
2477
+
2478
+
2479
+ def _entity_from_pre_ent_zero(
2480
+ query_or_augmented_select: Union[Query[Any], Select[Any]]
2481
+ ) -> Optional[_InternalEntityType[Any]]:
2482
+ self = query_or_augmented_select
2483
+ if not self._raw_columns:
2484
+ return None
2485
+
2486
+ ent = self._raw_columns[0]
2487
+
2488
+ if "parententity" in ent._annotations:
2489
+ return ent._annotations["parententity"]
2490
+ elif isinstance(ent, ORMColumnsClauseRole):
2491
+ return ent.entity
2492
+ elif "bundle" in ent._annotations:
2493
+ return ent._annotations["bundle"]
2494
+ else:
2495
+ return ent
2496
+
2497
+
2498
+ def _determine_last_joined_entity(
2499
+ setup_joins: Tuple[_SetupJoinsElement, ...],
2500
+ entity_zero: Optional[_InternalEntityType[Any]] = None,
2501
+ ) -> Optional[Union[_InternalEntityType[Any], _JoinTargetElement]]:
2502
+ if not setup_joins:
2503
+ return None
2504
+
2505
+ (target, onclause, from_, flags) = setup_joins[-1]
2506
+
2507
+ if isinstance(
2508
+ target,
2509
+ attributes.QueryableAttribute,
2510
+ ):
2511
+ return target.entity
2512
+ else:
2513
+ return target
2514
+
2515
+
2516
+ class _QueryEntity:
2517
+ """represent an entity column returned within a Query result."""
2518
+
2519
+ __slots__ = ()
2520
+
2521
+ supports_single_entity: bool
2522
+
2523
+ _non_hashable_value = False
2524
+ _null_column_type = False
2525
+ use_id_for_hash = False
2526
+
2527
+ _label_name: Optional[str]
2528
+ type: Union[Type[Any], TypeEngine[Any]]
2529
+ expr: Union[_InternalEntityType, ColumnElement[Any]]
2530
+ entity_zero: Optional[_InternalEntityType]
2531
+
2532
+ def setup_compile_state(self, compile_state: ORMCompileState) -> None:
2533
+ raise NotImplementedError()
2534
+
2535
+ def setup_dml_returning_compile_state(
2536
+ self,
2537
+ compile_state: ORMCompileState,
2538
+ adapter: DMLReturningColFilter,
2539
+ ) -> None:
2540
+ raise NotImplementedError()
2541
+
2542
+ def row_processor(self, context, result):
2543
+ raise NotImplementedError()
2544
+
2545
+ @classmethod
2546
+ def to_compile_state(
2547
+ cls, compile_state, entities, entities_collection, is_current_entities
2548
+ ):
2549
+ for idx, entity in enumerate(entities):
2550
+ if entity._is_lambda_element:
2551
+ if entity._is_sequence:
2552
+ cls.to_compile_state(
2553
+ compile_state,
2554
+ entity._resolved,
2555
+ entities_collection,
2556
+ is_current_entities,
2557
+ )
2558
+ continue
2559
+ else:
2560
+ entity = entity._resolved
2561
+
2562
+ if entity.is_clause_element:
2563
+ if entity.is_selectable:
2564
+ if "parententity" in entity._annotations:
2565
+ _MapperEntity(
2566
+ compile_state,
2567
+ entity,
2568
+ entities_collection,
2569
+ is_current_entities,
2570
+ )
2571
+ else:
2572
+ _ColumnEntity._for_columns(
2573
+ compile_state,
2574
+ entity._select_iterable,
2575
+ entities_collection,
2576
+ idx,
2577
+ is_current_entities,
2578
+ )
2579
+ else:
2580
+ if entity._annotations.get("bundle", False):
2581
+ _BundleEntity(
2582
+ compile_state,
2583
+ entity,
2584
+ entities_collection,
2585
+ is_current_entities,
2586
+ )
2587
+ elif entity._is_clause_list:
2588
+ # this is legacy only - test_composites.py
2589
+ # test_query_cols_legacy
2590
+ _ColumnEntity._for_columns(
2591
+ compile_state,
2592
+ entity._select_iterable,
2593
+ entities_collection,
2594
+ idx,
2595
+ is_current_entities,
2596
+ )
2597
+ else:
2598
+ _ColumnEntity._for_columns(
2599
+ compile_state,
2600
+ [entity],
2601
+ entities_collection,
2602
+ idx,
2603
+ is_current_entities,
2604
+ )
2605
+ elif entity.is_bundle:
2606
+ _BundleEntity(compile_state, entity, entities_collection)
2607
+
2608
+ return entities_collection
2609
+
2610
+
2611
+ class _MapperEntity(_QueryEntity):
2612
+ """mapper/class/AliasedClass entity"""
2613
+
2614
+ __slots__ = (
2615
+ "expr",
2616
+ "mapper",
2617
+ "entity_zero",
2618
+ "is_aliased_class",
2619
+ "path",
2620
+ "_extra_entities",
2621
+ "_label_name",
2622
+ "_with_polymorphic_mappers",
2623
+ "selectable",
2624
+ "_polymorphic_discriminator",
2625
+ )
2626
+
2627
+ expr: _InternalEntityType
2628
+ mapper: Mapper[Any]
2629
+ entity_zero: _InternalEntityType
2630
+ is_aliased_class: bool
2631
+ path: PathRegistry
2632
+ _label_name: str
2633
+
2634
+ def __init__(
2635
+ self, compile_state, entity, entities_collection, is_current_entities
2636
+ ):
2637
+ entities_collection.append(self)
2638
+ if is_current_entities:
2639
+ if compile_state._primary_entity is None:
2640
+ compile_state._primary_entity = self
2641
+ compile_state._has_mapper_entities = True
2642
+ compile_state._has_orm_entities = True
2643
+
2644
+ entity = entity._annotations["parententity"]
2645
+ entity._post_inspect
2646
+ ext_info = self.entity_zero = entity
2647
+ entity = ext_info.entity
2648
+
2649
+ self.expr = entity
2650
+ self.mapper = mapper = ext_info.mapper
2651
+
2652
+ self._extra_entities = (self.expr,)
2653
+
2654
+ if ext_info.is_aliased_class:
2655
+ self._label_name = ext_info.name
2656
+ else:
2657
+ self._label_name = mapper.class_.__name__
2658
+
2659
+ self.is_aliased_class = ext_info.is_aliased_class
2660
+ self.path = ext_info._path_registry
2661
+
2662
+ self.selectable = ext_info.selectable
2663
+ self._with_polymorphic_mappers = ext_info.with_polymorphic_mappers
2664
+ self._polymorphic_discriminator = ext_info.polymorphic_on
2665
+
2666
+ if mapper._should_select_with_poly_adapter:
2667
+ compile_state._create_with_polymorphic_adapter(
2668
+ ext_info, self.selectable
2669
+ )
2670
+
2671
+ supports_single_entity = True
2672
+
2673
+ _non_hashable_value = True
2674
+ use_id_for_hash = True
2675
+
2676
+ @property
2677
+ def type(self):
2678
+ return self.mapper.class_
2679
+
2680
+ @property
2681
+ def entity_zero_or_selectable(self):
2682
+ return self.entity_zero
2683
+
2684
+ def corresponds_to(self, entity):
2685
+ return _entity_corresponds_to(self.entity_zero, entity)
2686
+
2687
+ def _get_entity_clauses(self, compile_state):
2688
+ adapter = None
2689
+
2690
+ if not self.is_aliased_class:
2691
+ if compile_state._polymorphic_adapters:
2692
+ adapter = compile_state._polymorphic_adapters.get(
2693
+ self.mapper, None
2694
+ )
2695
+ else:
2696
+ adapter = self.entity_zero._adapter
2697
+
2698
+ if adapter:
2699
+ if compile_state._from_obj_alias:
2700
+ ret = adapter.wrap(compile_state._from_obj_alias)
2701
+ else:
2702
+ ret = adapter
2703
+ else:
2704
+ ret = compile_state._from_obj_alias
2705
+
2706
+ return ret
2707
+
2708
+ def row_processor(self, context, result):
2709
+ compile_state = context.compile_state
2710
+ adapter = self._get_entity_clauses(compile_state)
2711
+
2712
+ if compile_state.compound_eager_adapter and adapter:
2713
+ adapter = adapter.wrap(compile_state.compound_eager_adapter)
2714
+ elif not adapter:
2715
+ adapter = compile_state.compound_eager_adapter
2716
+
2717
+ if compile_state._primary_entity is self:
2718
+ only_load_props = compile_state.compile_options._only_load_props
2719
+ refresh_state = context.refresh_state
2720
+ else:
2721
+ only_load_props = refresh_state = None
2722
+
2723
+ _instance = loading._instance_processor(
2724
+ self,
2725
+ self.mapper,
2726
+ context,
2727
+ result,
2728
+ self.path,
2729
+ adapter,
2730
+ only_load_props=only_load_props,
2731
+ refresh_state=refresh_state,
2732
+ polymorphic_discriminator=self._polymorphic_discriminator,
2733
+ )
2734
+
2735
+ return _instance, self._label_name, self._extra_entities
2736
+
2737
+ def setup_dml_returning_compile_state(
2738
+ self,
2739
+ compile_state: ORMCompileState,
2740
+ adapter: DMLReturningColFilter,
2741
+ ) -> None:
2742
+ loading._setup_entity_query(
2743
+ compile_state,
2744
+ self.mapper,
2745
+ self,
2746
+ self.path,
2747
+ adapter,
2748
+ compile_state.primary_columns,
2749
+ with_polymorphic=self._with_polymorphic_mappers,
2750
+ only_load_props=compile_state.compile_options._only_load_props,
2751
+ polymorphic_discriminator=self._polymorphic_discriminator,
2752
+ )
2753
+
2754
+ def setup_compile_state(self, compile_state):
2755
+ adapter = self._get_entity_clauses(compile_state)
2756
+
2757
+ single_table_crit = self.mapper._single_table_criterion
2758
+ if (
2759
+ single_table_crit is not None
2760
+ or ("additional_entity_criteria", self.mapper)
2761
+ in compile_state.global_attributes
2762
+ ):
2763
+ ext_info = self.entity_zero
2764
+ compile_state.extra_criteria_entities[ext_info] = (
2765
+ ext_info,
2766
+ ext_info._adapter if ext_info.is_aliased_class else None,
2767
+ )
2768
+
2769
+ loading._setup_entity_query(
2770
+ compile_state,
2771
+ self.mapper,
2772
+ self,
2773
+ self.path,
2774
+ adapter,
2775
+ compile_state.primary_columns,
2776
+ with_polymorphic=self._with_polymorphic_mappers,
2777
+ only_load_props=compile_state.compile_options._only_load_props,
2778
+ polymorphic_discriminator=self._polymorphic_discriminator,
2779
+ )
2780
+ compile_state._fallback_from_clauses.append(self.selectable)
2781
+
2782
+
2783
+ class _BundleEntity(_QueryEntity):
2784
+ _extra_entities = ()
2785
+
2786
+ __slots__ = (
2787
+ "bundle",
2788
+ "expr",
2789
+ "type",
2790
+ "_label_name",
2791
+ "_entities",
2792
+ "supports_single_entity",
2793
+ )
2794
+
2795
+ _entities: List[_QueryEntity]
2796
+ bundle: Bundle
2797
+ type: Type[Any]
2798
+ _label_name: str
2799
+ supports_single_entity: bool
2800
+ expr: Bundle
2801
+
2802
+ def __init__(
2803
+ self,
2804
+ compile_state,
2805
+ expr,
2806
+ entities_collection,
2807
+ is_current_entities,
2808
+ setup_entities=True,
2809
+ parent_bundle=None,
2810
+ ):
2811
+ compile_state._has_orm_entities = True
2812
+
2813
+ expr = expr._annotations["bundle"]
2814
+ if parent_bundle:
2815
+ parent_bundle._entities.append(self)
2816
+ else:
2817
+ entities_collection.append(self)
2818
+
2819
+ if isinstance(
2820
+ expr, (attributes.QueryableAttribute, interfaces.PropComparator)
2821
+ ):
2822
+ bundle = expr.__clause_element__()
2823
+ else:
2824
+ bundle = expr
2825
+
2826
+ self.bundle = self.expr = bundle
2827
+ self.type = type(bundle)
2828
+ self._label_name = bundle.name
2829
+ self._entities = []
2830
+
2831
+ if setup_entities:
2832
+ for expr in bundle.exprs:
2833
+ if "bundle" in expr._annotations:
2834
+ _BundleEntity(
2835
+ compile_state,
2836
+ expr,
2837
+ entities_collection,
2838
+ is_current_entities,
2839
+ parent_bundle=self,
2840
+ )
2841
+ elif isinstance(expr, Bundle):
2842
+ _BundleEntity(
2843
+ compile_state,
2844
+ expr,
2845
+ entities_collection,
2846
+ is_current_entities,
2847
+ parent_bundle=self,
2848
+ )
2849
+ else:
2850
+ _ORMColumnEntity._for_columns(
2851
+ compile_state,
2852
+ [expr],
2853
+ entities_collection,
2854
+ None,
2855
+ is_current_entities,
2856
+ parent_bundle=self,
2857
+ )
2858
+
2859
+ self.supports_single_entity = self.bundle.single_entity
2860
+
2861
+ @property
2862
+ def mapper(self):
2863
+ ezero = self.entity_zero
2864
+ if ezero is not None:
2865
+ return ezero.mapper
2866
+ else:
2867
+ return None
2868
+
2869
+ @property
2870
+ def entity_zero(self):
2871
+ for ent in self._entities:
2872
+ ezero = ent.entity_zero
2873
+ if ezero is not None:
2874
+ return ezero
2875
+ else:
2876
+ return None
2877
+
2878
+ def corresponds_to(self, entity):
2879
+ # TODO: we might be able to implement this but for now
2880
+ # we are working around it
2881
+ return False
2882
+
2883
+ @property
2884
+ def entity_zero_or_selectable(self):
2885
+ for ent in self._entities:
2886
+ ezero = ent.entity_zero_or_selectable
2887
+ if ezero is not None:
2888
+ return ezero
2889
+ else:
2890
+ return None
2891
+
2892
+ def setup_compile_state(self, compile_state):
2893
+ for ent in self._entities:
2894
+ ent.setup_compile_state(compile_state)
2895
+
2896
+ def setup_dml_returning_compile_state(
2897
+ self,
2898
+ compile_state: ORMCompileState,
2899
+ adapter: DMLReturningColFilter,
2900
+ ) -> None:
2901
+ return self.setup_compile_state(compile_state)
2902
+
2903
+ def row_processor(self, context, result):
2904
+ procs, labels, extra = zip(
2905
+ *[ent.row_processor(context, result) for ent in self._entities]
2906
+ )
2907
+
2908
+ proc = self.bundle.create_row_processor(context.query, procs, labels)
2909
+
2910
+ return proc, self._label_name, self._extra_entities
2911
+
2912
+
2913
+ class _ColumnEntity(_QueryEntity):
2914
+ __slots__ = (
2915
+ "_fetch_column",
2916
+ "_row_processor",
2917
+ "raw_column_index",
2918
+ "translate_raw_column",
2919
+ )
2920
+
2921
+ @classmethod
2922
+ def _for_columns(
2923
+ cls,
2924
+ compile_state,
2925
+ columns,
2926
+ entities_collection,
2927
+ raw_column_index,
2928
+ is_current_entities,
2929
+ parent_bundle=None,
2930
+ ):
2931
+ for column in columns:
2932
+ annotations = column._annotations
2933
+ if "parententity" in annotations:
2934
+ _entity = annotations["parententity"]
2935
+ else:
2936
+ _entity = sql_util.extract_first_column_annotation(
2937
+ column, "parententity"
2938
+ )
2939
+
2940
+ if _entity:
2941
+ if "identity_token" in column._annotations:
2942
+ _IdentityTokenEntity(
2943
+ compile_state,
2944
+ column,
2945
+ entities_collection,
2946
+ _entity,
2947
+ raw_column_index,
2948
+ is_current_entities,
2949
+ parent_bundle=parent_bundle,
2950
+ )
2951
+ else:
2952
+ _ORMColumnEntity(
2953
+ compile_state,
2954
+ column,
2955
+ entities_collection,
2956
+ _entity,
2957
+ raw_column_index,
2958
+ is_current_entities,
2959
+ parent_bundle=parent_bundle,
2960
+ )
2961
+ else:
2962
+ _RawColumnEntity(
2963
+ compile_state,
2964
+ column,
2965
+ entities_collection,
2966
+ raw_column_index,
2967
+ is_current_entities,
2968
+ parent_bundle=parent_bundle,
2969
+ )
2970
+
2971
+ @property
2972
+ def type(self):
2973
+ return self.column.type
2974
+
2975
+ @property
2976
+ def _non_hashable_value(self):
2977
+ return not self.column.type.hashable
2978
+
2979
+ @property
2980
+ def _null_column_type(self):
2981
+ return self.column.type._isnull
2982
+
2983
+ def row_processor(self, context, result):
2984
+ compile_state = context.compile_state
2985
+
2986
+ # the resulting callable is entirely cacheable so just return
2987
+ # it if we already made one
2988
+ if self._row_processor is not None:
2989
+ getter, label_name, extra_entities = self._row_processor
2990
+ if self.translate_raw_column:
2991
+ extra_entities += (
2992
+ context.query._raw_columns[self.raw_column_index],
2993
+ )
2994
+
2995
+ return getter, label_name, extra_entities
2996
+
2997
+ # retrieve the column that would have been set up in
2998
+ # setup_compile_state, to avoid doing redundant work
2999
+ if self._fetch_column is not None:
3000
+ column = self._fetch_column
3001
+ else:
3002
+ # fetch_column will be None when we are doing a from_statement
3003
+ # and setup_compile_state may not have been called.
3004
+ column = self.column
3005
+
3006
+ # previously, the RawColumnEntity didn't look for from_obj_alias
3007
+ # however I can't think of a case where we would be here and
3008
+ # we'd want to ignore it if this is the from_statement use case.
3009
+ # it's not really a use case to have raw columns + from_statement
3010
+ if compile_state._from_obj_alias:
3011
+ column = compile_state._from_obj_alias.columns[column]
3012
+
3013
+ if column._annotations:
3014
+ # annotated columns perform more slowly in compiler and
3015
+ # result due to the __eq__() method, so use deannotated
3016
+ column = column._deannotate()
3017
+
3018
+ if compile_state.compound_eager_adapter:
3019
+ column = compile_state.compound_eager_adapter.columns[column]
3020
+
3021
+ getter = result._getter(column)
3022
+ ret = getter, self._label_name, self._extra_entities
3023
+ self._row_processor = ret
3024
+
3025
+ if self.translate_raw_column:
3026
+ extra_entities = self._extra_entities + (
3027
+ context.query._raw_columns[self.raw_column_index],
3028
+ )
3029
+ return getter, self._label_name, extra_entities
3030
+ else:
3031
+ return ret
3032
+
3033
+
3034
+ class _RawColumnEntity(_ColumnEntity):
3035
+ entity_zero = None
3036
+ mapper = None
3037
+ supports_single_entity = False
3038
+
3039
+ __slots__ = (
3040
+ "expr",
3041
+ "column",
3042
+ "_label_name",
3043
+ "entity_zero_or_selectable",
3044
+ "_extra_entities",
3045
+ )
3046
+
3047
+ def __init__(
3048
+ self,
3049
+ compile_state,
3050
+ column,
3051
+ entities_collection,
3052
+ raw_column_index,
3053
+ is_current_entities,
3054
+ parent_bundle=None,
3055
+ ):
3056
+ self.expr = column
3057
+ self.raw_column_index = raw_column_index
3058
+ self.translate_raw_column = raw_column_index is not None
3059
+
3060
+ if column._is_star:
3061
+ compile_state.compile_options += {"_is_star": True}
3062
+
3063
+ if not is_current_entities or column._is_text_clause:
3064
+ self._label_name = None
3065
+ else:
3066
+ if parent_bundle:
3067
+ self._label_name = column._proxy_key
3068
+ else:
3069
+ self._label_name = compile_state._label_convention(column)
3070
+
3071
+ if parent_bundle:
3072
+ parent_bundle._entities.append(self)
3073
+ else:
3074
+ entities_collection.append(self)
3075
+
3076
+ self.column = column
3077
+ self.entity_zero_or_selectable = (
3078
+ self.column._from_objects[0] if self.column._from_objects else None
3079
+ )
3080
+ self._extra_entities = (self.expr, self.column)
3081
+ self._fetch_column = self._row_processor = None
3082
+
3083
+ def corresponds_to(self, entity):
3084
+ return False
3085
+
3086
+ def setup_dml_returning_compile_state(
3087
+ self,
3088
+ compile_state: ORMCompileState,
3089
+ adapter: DMLReturningColFilter,
3090
+ ) -> None:
3091
+ return self.setup_compile_state(compile_state)
3092
+
3093
+ def setup_compile_state(self, compile_state):
3094
+ current_adapter = compile_state._get_current_adapter()
3095
+ if current_adapter:
3096
+ column = current_adapter(self.column, False)
3097
+ if column is None:
3098
+ return
3099
+ else:
3100
+ column = self.column
3101
+
3102
+ if column._annotations:
3103
+ # annotated columns perform more slowly in compiler and
3104
+ # result due to the __eq__() method, so use deannotated
3105
+ column = column._deannotate()
3106
+
3107
+ compile_state.dedupe_columns.add(column)
3108
+ compile_state.primary_columns.append(column)
3109
+ self._fetch_column = column
3110
+
3111
+
3112
+ class _ORMColumnEntity(_ColumnEntity):
3113
+ """Column/expression based entity."""
3114
+
3115
+ supports_single_entity = False
3116
+
3117
+ __slots__ = (
3118
+ "expr",
3119
+ "mapper",
3120
+ "column",
3121
+ "_label_name",
3122
+ "entity_zero_or_selectable",
3123
+ "entity_zero",
3124
+ "_extra_entities",
3125
+ )
3126
+
3127
+ def __init__(
3128
+ self,
3129
+ compile_state,
3130
+ column,
3131
+ entities_collection,
3132
+ parententity,
3133
+ raw_column_index,
3134
+ is_current_entities,
3135
+ parent_bundle=None,
3136
+ ):
3137
+ annotations = column._annotations
3138
+
3139
+ _entity = parententity
3140
+
3141
+ # an AliasedClass won't have proxy_key in the annotations for
3142
+ # a column if it was acquired using the class' adapter directly,
3143
+ # such as using AliasedInsp._adapt_element(). this occurs
3144
+ # within internal loaders.
3145
+
3146
+ orm_key = annotations.get("proxy_key", None)
3147
+ proxy_owner = annotations.get("proxy_owner", _entity)
3148
+ if orm_key:
3149
+ self.expr = getattr(proxy_owner.entity, orm_key)
3150
+ self.translate_raw_column = False
3151
+ else:
3152
+ # if orm_key is not present, that means this is an ad-hoc
3153
+ # SQL ColumnElement, like a CASE() or other expression.
3154
+ # include this column position from the invoked statement
3155
+ # in the ORM-level ResultSetMetaData on each execute, so that
3156
+ # it can be targeted by identity after caching
3157
+ self.expr = column
3158
+ self.translate_raw_column = raw_column_index is not None
3159
+
3160
+ self.raw_column_index = raw_column_index
3161
+
3162
+ if is_current_entities:
3163
+ if parent_bundle:
3164
+ self._label_name = orm_key if orm_key else column._proxy_key
3165
+ else:
3166
+ self._label_name = compile_state._label_convention(
3167
+ column, col_name=orm_key
3168
+ )
3169
+ else:
3170
+ self._label_name = None
3171
+
3172
+ _entity._post_inspect
3173
+ self.entity_zero = self.entity_zero_or_selectable = ezero = _entity
3174
+ self.mapper = mapper = _entity.mapper
3175
+
3176
+ if parent_bundle:
3177
+ parent_bundle._entities.append(self)
3178
+ else:
3179
+ entities_collection.append(self)
3180
+
3181
+ compile_state._has_orm_entities = True
3182
+
3183
+ self.column = column
3184
+
3185
+ self._fetch_column = self._row_processor = None
3186
+
3187
+ self._extra_entities = (self.expr, self.column)
3188
+
3189
+ if mapper._should_select_with_poly_adapter:
3190
+ compile_state._create_with_polymorphic_adapter(
3191
+ ezero, ezero.selectable
3192
+ )
3193
+
3194
+ def corresponds_to(self, entity):
3195
+ if _is_aliased_class(entity):
3196
+ # TODO: polymorphic subclasses ?
3197
+ return entity is self.entity_zero
3198
+ else:
3199
+ return not _is_aliased_class(
3200
+ self.entity_zero
3201
+ ) and entity.common_parent(self.entity_zero)
3202
+
3203
+ def setup_dml_returning_compile_state(
3204
+ self,
3205
+ compile_state: ORMCompileState,
3206
+ adapter: DMLReturningColFilter,
3207
+ ) -> None:
3208
+ self._fetch_column = self.column
3209
+ column = adapter(self.column, False)
3210
+ if column is not None:
3211
+ compile_state.dedupe_columns.add(column)
3212
+ compile_state.primary_columns.append(column)
3213
+
3214
+ def setup_compile_state(self, compile_state):
3215
+ current_adapter = compile_state._get_current_adapter()
3216
+ if current_adapter:
3217
+ column = current_adapter(self.column, False)
3218
+ if column is None:
3219
+ assert compile_state.is_dml_returning
3220
+ self._fetch_column = self.column
3221
+ return
3222
+ else:
3223
+ column = self.column
3224
+
3225
+ ezero = self.entity_zero
3226
+
3227
+ single_table_crit = self.mapper._single_table_criterion
3228
+ if (
3229
+ single_table_crit is not None
3230
+ or ("additional_entity_criteria", self.mapper)
3231
+ in compile_state.global_attributes
3232
+ ):
3233
+ compile_state.extra_criteria_entities[ezero] = (
3234
+ ezero,
3235
+ ezero._adapter if ezero.is_aliased_class else None,
3236
+ )
3237
+
3238
+ if column._annotations and not column._expression_label:
3239
+ # annotated columns perform more slowly in compiler and
3240
+ # result due to the __eq__() method, so use deannotated
3241
+ column = column._deannotate()
3242
+
3243
+ # use entity_zero as the from if we have it. this is necessary
3244
+ # for polymorphic scenarios where our FROM is based on ORM entity,
3245
+ # not the FROM of the column. but also, don't use it if our column
3246
+ # doesn't actually have any FROMs that line up, such as when its
3247
+ # a scalar subquery.
3248
+ if set(self.column._from_objects).intersection(
3249
+ ezero.selectable._from_objects
3250
+ ):
3251
+ compile_state._fallback_from_clauses.append(ezero.selectable)
3252
+
3253
+ compile_state.dedupe_columns.add(column)
3254
+ compile_state.primary_columns.append(column)
3255
+ self._fetch_column = column
3256
+
3257
+
3258
+ class _IdentityTokenEntity(_ORMColumnEntity):
3259
+ translate_raw_column = False
3260
+
3261
+ def setup_compile_state(self, compile_state):
3262
+ pass
3263
+
3264
+ def row_processor(self, context, result):
3265
+ def getter(row):
3266
+ return context.load_options._identity_token
3267
+
3268
+ return getter, self._label_name, self._extra_entities