You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2923 lines
101KB

  1. # orm/context.py
  2. # Copyright (C) 2005-2021 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: http://www.opensource.org/licenses/mit-license.php
  7. from . import attributes
  8. from . import interfaces
  9. from . import loading
  10. from .base import _is_aliased_class
  11. from .interfaces import ORMColumnsClauseRole
  12. from .path_registry import PathRegistry
  13. from .util import _entity_corresponds_to
  14. from .util import _ORMJoin
  15. from .util import aliased
  16. from .util import Bundle
  17. from .util import ORMAdapter
  18. from .. import exc as sa_exc
  19. from .. import future
  20. from .. import inspect
  21. from .. import sql
  22. from .. import util
  23. from ..sql import coercions
  24. from ..sql import expression
  25. from ..sql import roles
  26. from ..sql import util as sql_util
  27. from ..sql import visitors
  28. from ..sql.base import _entity_namespace_key
  29. from ..sql.base import _select_iterables
  30. from ..sql.base import CacheableOptions
  31. from ..sql.base import CompileState
  32. from ..sql.base import Options
  33. from ..sql.selectable import LABEL_STYLE_DISAMBIGUATE_ONLY
  34. from ..sql.selectable import LABEL_STYLE_NONE
  35. from ..sql.selectable import LABEL_STYLE_TABLENAME_PLUS_COL
  36. from ..sql.selectable import SelectState
  37. from ..sql.visitors import ExtendedInternalTraversal
  38. from ..sql.visitors import InternalTraversal
  39. _path_registry = PathRegistry.root
  40. _EMPTY_DICT = util.immutabledict()
  41. LABEL_STYLE_LEGACY_ORM = util.symbol("LABEL_STYLE_LEGACY_ORM")
  42. class QueryContext(object):
  43. __slots__ = (
  44. "compile_state",
  45. "query",
  46. "params",
  47. "load_options",
  48. "bind_arguments",
  49. "execution_options",
  50. "session",
  51. "autoflush",
  52. "populate_existing",
  53. "invoke_all_eagers",
  54. "version_check",
  55. "refresh_state",
  56. "create_eager_joins",
  57. "propagated_loader_options",
  58. "attributes",
  59. "runid",
  60. "partials",
  61. "post_load_paths",
  62. "identity_token",
  63. "yield_per",
  64. "loaders_require_buffering",
  65. "loaders_require_uniquing",
  66. )
  67. class default_load_options(Options):
  68. _only_return_tuples = False
  69. _populate_existing = False
  70. _version_check = False
  71. _invoke_all_eagers = True
  72. _autoflush = True
  73. _refresh_identity_token = None
  74. _yield_per = None
  75. _refresh_state = None
  76. _lazy_loaded_from = None
  77. def __init__(
  78. self,
  79. compile_state,
  80. statement,
  81. params,
  82. session,
  83. load_options,
  84. execution_options=None,
  85. bind_arguments=None,
  86. ):
  87. self.load_options = load_options
  88. self.execution_options = execution_options or _EMPTY_DICT
  89. self.bind_arguments = bind_arguments or _EMPTY_DICT
  90. self.compile_state = compile_state
  91. self.query = statement
  92. self.session = session
  93. self.loaders_require_buffering = False
  94. self.loaders_require_uniquing = False
  95. self.params = params
  96. self.propagated_loader_options = {
  97. o for o in statement._with_options if o.propagate_to_loaders
  98. }
  99. self.attributes = dict(compile_state.attributes)
  100. self.autoflush = load_options._autoflush
  101. self.populate_existing = load_options._populate_existing
  102. self.invoke_all_eagers = load_options._invoke_all_eagers
  103. self.version_check = load_options._version_check
  104. self.refresh_state = load_options._refresh_state
  105. self.yield_per = load_options._yield_per
  106. self.identity_token = load_options._refresh_identity_token
  107. if self.yield_per and compile_state._no_yield_pers:
  108. raise sa_exc.InvalidRequestError(
  109. "The yield_per Query option is currently not "
  110. "compatible with %s eager loading. Please "
  111. "specify lazyload('*') or query.enable_eagerloads(False) in "
  112. "order to "
  113. "proceed with query.yield_per()."
  114. % ", ".join(compile_state._no_yield_pers)
  115. )
  116. _orm_load_exec_options = util.immutabledict(
  117. {"_result_disable_adapt_to_context": True, "future_result": True}
  118. )
  119. class ORMCompileState(CompileState):
  120. # note this is a dictionary, but the
  121. # default_compile_options._with_polymorphic_adapt_map is a tuple
  122. _with_polymorphic_adapt_map = _EMPTY_DICT
  123. class default_compile_options(CacheableOptions):
  124. _cache_key_traversal = [
  125. ("_use_legacy_query_style", InternalTraversal.dp_boolean),
  126. ("_for_statement", InternalTraversal.dp_boolean),
  127. ("_bake_ok", InternalTraversal.dp_boolean),
  128. (
  129. "_with_polymorphic_adapt_map",
  130. ExtendedInternalTraversal.dp_has_cache_key_tuples,
  131. ),
  132. ("_current_path", InternalTraversal.dp_has_cache_key),
  133. ("_enable_single_crit", InternalTraversal.dp_boolean),
  134. ("_enable_eagerloads", InternalTraversal.dp_boolean),
  135. ("_orm_only_from_obj_alias", InternalTraversal.dp_boolean),
  136. ("_only_load_props", InternalTraversal.dp_plain_obj),
  137. ("_set_base_alias", InternalTraversal.dp_boolean),
  138. ("_for_refresh_state", InternalTraversal.dp_boolean),
  139. ("_render_for_subquery", InternalTraversal.dp_boolean),
  140. ]
  141. # set to True by default from Query._statement_20(), to indicate
  142. # the rendered query should look like a legacy ORM query. right
  143. # now this basically indicates we should use tablename_columnname
  144. # style labels. Generally indicates the statement originated
  145. # from a Query object.
  146. _use_legacy_query_style = False
  147. # set *only* when we are coming from the Query.statement
  148. # accessor, or a Query-level equivalent such as
  149. # query.subquery(). this supersedes "toplevel".
  150. _for_statement = False
  151. _bake_ok = True
  152. _with_polymorphic_adapt_map = ()
  153. _current_path = _path_registry
  154. _enable_single_crit = True
  155. _enable_eagerloads = True
  156. _orm_only_from_obj_alias = True
  157. _only_load_props = None
  158. _set_base_alias = False
  159. _for_refresh_state = False
  160. _render_for_subquery = False
  161. current_path = _path_registry
  162. def __init__(self, *arg, **kw):
  163. raise NotImplementedError()
  164. @classmethod
  165. def _column_naming_convention(cls, label_style, legacy):
  166. if legacy:
  167. def name(col, col_name=None):
  168. if col_name:
  169. return col_name
  170. else:
  171. return getattr(col, "key")
  172. return name
  173. else:
  174. return SelectState._column_naming_convention(label_style)
  175. @classmethod
  176. def create_for_statement(cls, statement_container, compiler, **kw):
  177. """Create a context for a statement given a :class:`.Compiler`.
  178. This method is always invoked in the context of SQLCompiler.process().
  179. For a Select object, this would be invoked from
  180. SQLCompiler.visit_select(). For the special FromStatement object used
  181. by Query to indicate "Query.from_statement()", this is called by
  182. FromStatement._compiler_dispatch() that would be called by
  183. SQLCompiler.process().
  184. """
  185. raise NotImplementedError()
  186. @classmethod
  187. def get_column_descriptions(cls, statement):
  188. return _column_descriptions(statement)
  189. @classmethod
  190. def orm_pre_session_exec(
  191. cls,
  192. session,
  193. statement,
  194. params,
  195. execution_options,
  196. bind_arguments,
  197. is_reentrant_invoke,
  198. ):
  199. if is_reentrant_invoke:
  200. return statement, execution_options
  201. (
  202. load_options,
  203. execution_options,
  204. ) = QueryContext.default_load_options.from_execution_options(
  205. "_sa_orm_load_options",
  206. {"populate_existing", "autoflush", "yield_per"},
  207. execution_options,
  208. statement._execution_options,
  209. )
  210. # default execution options for ORM results:
  211. # 1. _result_disable_adapt_to_context=True
  212. # this will disable the ResultSetMetadata._adapt_to_context()
  213. # step which we don't need, as we have result processors cached
  214. # against the original SELECT statement before caching.
  215. # 2. future_result=True. The ORM should **never** resolve columns
  216. # in a result set based on names, only on Column objects that
  217. # are correctly adapted to the context. W the legacy result
  218. # it will still attempt name-based resolution and also emit a
  219. # warning.
  220. if not execution_options:
  221. execution_options = _orm_load_exec_options
  222. else:
  223. execution_options = execution_options.union(_orm_load_exec_options)
  224. if "yield_per" in execution_options or load_options._yield_per:
  225. execution_options = execution_options.union(
  226. {
  227. "stream_results": True,
  228. "max_row_buffer": execution_options.get(
  229. "yield_per", load_options._yield_per
  230. ),
  231. }
  232. )
  233. bind_arguments["clause"] = statement
  234. # new in 1.4 - the coercions system is leveraged to allow the
  235. # "subject" mapper of a statement be propagated to the top
  236. # as the statement is built. "subject" mapper is the generally
  237. # standard object used as an identifier for multi-database schemes.
  238. # we are here based on the fact that _propagate_attrs contains
  239. # "compile_state_plugin": "orm". The "plugin_subject"
  240. # needs to be present as well.
  241. try:
  242. plugin_subject = statement._propagate_attrs["plugin_subject"]
  243. except KeyError:
  244. assert False, "statement had 'orm' plugin but no plugin_subject"
  245. else:
  246. if plugin_subject:
  247. bind_arguments["mapper"] = plugin_subject.mapper
  248. if load_options._autoflush:
  249. session._autoflush()
  250. return statement, execution_options
  251. @classmethod
  252. def orm_setup_cursor_result(
  253. cls,
  254. session,
  255. statement,
  256. params,
  257. execution_options,
  258. bind_arguments,
  259. result,
  260. ):
  261. execution_context = result.context
  262. compile_state = execution_context.compiled.compile_state
  263. # cover edge case where ORM entities used in legacy select
  264. # were passed to session.execute:
  265. # session.execute(legacy_select([User.id, User.name]))
  266. # see test_query->test_legacy_tuple_old_select
  267. load_options = execution_options.get(
  268. "_sa_orm_load_options", QueryContext.default_load_options
  269. )
  270. querycontext = QueryContext(
  271. compile_state,
  272. statement,
  273. params,
  274. session,
  275. load_options,
  276. execution_options,
  277. bind_arguments,
  278. )
  279. return loading.instances(result, querycontext)
  280. @property
  281. def _lead_mapper_entities(self):
  282. """return all _MapperEntity objects in the lead entities collection.
  283. Does **not** include entities that have been replaced by
  284. with_entities(), with_only_columns()
  285. """
  286. return [
  287. ent for ent in self._entities if isinstance(ent, _MapperEntity)
  288. ]
  289. def _create_with_polymorphic_adapter(self, ext_info, selectable):
  290. if (
  291. not ext_info.is_aliased_class
  292. and ext_info.mapper.persist_selectable
  293. not in self._polymorphic_adapters
  294. ):
  295. for mp in ext_info.mapper.iterate_to_root():
  296. self._mapper_loads_polymorphically_with(
  297. mp,
  298. sql_util.ColumnAdapter(selectable, mp._equivalent_columns),
  299. )
  300. def _mapper_loads_polymorphically_with(self, mapper, adapter):
  301. for m2 in mapper._with_polymorphic_mappers or [mapper]:
  302. self._polymorphic_adapters[m2] = adapter
  303. for m in m2.iterate_to_root(): # TODO: redundant ?
  304. self._polymorphic_adapters[m.local_table] = adapter
  305. @sql.base.CompileState.plugin_for("orm", "orm_from_statement")
  306. class ORMFromStatementCompileState(ORMCompileState):
  307. _aliased_generations = util.immutabledict()
  308. _from_obj_alias = None
  309. _has_mapper_entities = False
  310. _has_orm_entities = False
  311. multi_row_eager_loaders = False
  312. compound_eager_adapter = None
  313. extra_criteria_entities = _EMPTY_DICT
  314. eager_joins = _EMPTY_DICT
  315. @classmethod
  316. def create_for_statement(cls, statement_container, compiler, **kw):
  317. if compiler is not None:
  318. toplevel = not compiler.stack
  319. else:
  320. toplevel = True
  321. self = cls.__new__(cls)
  322. self._primary_entity = None
  323. self.use_legacy_query_style = (
  324. statement_container._compile_options._use_legacy_query_style
  325. )
  326. self.statement_container = self.select_statement = statement_container
  327. self.requested_statement = statement = statement_container.element
  328. if statement.is_dml:
  329. self.dml_table = statement.table
  330. self._entities = []
  331. self._polymorphic_adapters = {}
  332. self._no_yield_pers = set()
  333. self.compile_options = statement_container._compile_options
  334. if (
  335. self.use_legacy_query_style
  336. and isinstance(statement, expression.SelectBase)
  337. and not statement._is_textual
  338. and not statement.is_dml
  339. and statement._label_style is LABEL_STYLE_NONE
  340. ):
  341. self.statement = statement.set_label_style(
  342. LABEL_STYLE_TABLENAME_PLUS_COL
  343. )
  344. else:
  345. self.statement = statement
  346. self._label_convention = self._column_naming_convention(
  347. statement._label_style
  348. if not statement._is_textual and not statement.is_dml
  349. else LABEL_STYLE_NONE,
  350. self.use_legacy_query_style,
  351. )
  352. _QueryEntity.to_compile_state(
  353. self, statement_container._raw_columns, self._entities
  354. )
  355. self.current_path = statement_container._compile_options._current_path
  356. if toplevel and statement_container._with_options:
  357. self.attributes = {"_unbound_load_dedupes": set()}
  358. self.global_attributes = compiler._global_attributes
  359. for opt in statement_container._with_options:
  360. if opt._is_compile_state:
  361. opt.process_compile_state(self)
  362. else:
  363. self.attributes = {}
  364. self.global_attributes = compiler._global_attributes
  365. if statement_container._with_context_options:
  366. for fn, key in statement_container._with_context_options:
  367. fn(self)
  368. self.primary_columns = []
  369. self.secondary_columns = []
  370. self.create_eager_joins = []
  371. self._fallback_from_clauses = []
  372. self.order_by = None
  373. if isinstance(
  374. self.statement, (expression.TextClause, expression.UpdateBase)
  375. ):
  376. self.extra_criteria_entities = {}
  377. # setup for all entities. Currently, this is not useful
  378. # for eager loaders, as the eager loaders that work are able
  379. # to do their work entirely in row_processor.
  380. for entity in self._entities:
  381. entity.setup_compile_state(self)
  382. # we did the setup just to get primary columns.
  383. self.statement = expression.TextualSelect(
  384. self.statement, self.primary_columns, positional=False
  385. )
  386. else:
  387. # allow TextualSelect with implicit columns as well
  388. # as select() with ad-hoc columns, see test_query::TextTest
  389. self._from_obj_alias = sql.util.ColumnAdapter(
  390. self.statement, adapt_on_names=True
  391. )
  392. # set up for eager loaders, however if we fix subqueryload
  393. # it should not need to do this here. the model of eager loaders
  394. # that can work entirely in row_processor might be interesting
  395. # here though subqueryloader has a lot of upfront work to do
  396. # see test/orm/test_query.py -> test_related_eagerload_against_text
  397. # for where this part makes a difference. would rather have
  398. # subqueryload figure out what it needs more intelligently.
  399. # for entity in self._entities:
  400. # entity.setup_compile_state(self)
  401. return self
  402. def _adapt_col_list(self, cols, current_adapter):
  403. return cols
  404. def _get_current_adapter(self):
  405. return None
  406. @sql.base.CompileState.plugin_for("orm", "select")
  407. class ORMSelectCompileState(ORMCompileState, SelectState):
  408. _joinpath = _joinpoint = _EMPTY_DICT
  409. _memoized_entities = _EMPTY_DICT
  410. _from_obj_alias = None
  411. _has_mapper_entities = False
  412. _has_orm_entities = False
  413. multi_row_eager_loaders = False
  414. compound_eager_adapter = None
  415. correlate = None
  416. correlate_except = None
  417. _where_criteria = ()
  418. _having_criteria = ()
  419. @classmethod
  420. def create_for_statement(cls, statement, compiler, **kw):
  421. """compiler hook, we arrive here from compiler.visit_select() only."""
  422. self = cls.__new__(cls)
  423. if compiler is not None:
  424. toplevel = not compiler.stack
  425. self.global_attributes = compiler._global_attributes
  426. else:
  427. toplevel = True
  428. self.global_attributes = {}
  429. select_statement = statement
  430. # if we are a select() that was never a legacy Query, we won't
  431. # have ORM level compile options.
  432. statement._compile_options = cls.default_compile_options.safe_merge(
  433. statement._compile_options
  434. )
  435. if select_statement._execution_options:
  436. # execution options should not impact the compilation of a
  437. # query, and at the moment subqueryloader is putting some things
  438. # in here that we explicitly don't want stuck in a cache.
  439. self.select_statement = select_statement._clone()
  440. self.select_statement._execution_options = util.immutabledict()
  441. else:
  442. self.select_statement = select_statement
  443. # indicates this select() came from Query.statement
  444. self.for_statement = select_statement._compile_options._for_statement
  445. # generally if we are from Query or directly from a select()
  446. self.use_legacy_query_style = (
  447. select_statement._compile_options._use_legacy_query_style
  448. )
  449. self._entities = []
  450. self._primary_entity = None
  451. self._aliased_generations = {}
  452. self._polymorphic_adapters = {}
  453. self._no_yield_pers = set()
  454. # legacy: only for query.with_polymorphic()
  455. if select_statement._compile_options._with_polymorphic_adapt_map:
  456. self._with_polymorphic_adapt_map = dict(
  457. select_statement._compile_options._with_polymorphic_adapt_map
  458. )
  459. self._setup_with_polymorphics()
  460. self.compile_options = select_statement._compile_options
  461. if not toplevel:
  462. # for subqueries, turn off eagerloads and set
  463. # "render_for_subquery".
  464. self.compile_options += {
  465. "_enable_eagerloads": False,
  466. "_render_for_subquery": True,
  467. }
  468. # determine label style. we can make different decisions here.
  469. # at the moment, trying to see if we can always use DISAMBIGUATE_ONLY
  470. # rather than LABEL_STYLE_NONE, and if we can use disambiguate style
  471. # for new style ORM selects too.
  472. if (
  473. self.use_legacy_query_style
  474. and self.select_statement._label_style is LABEL_STYLE_LEGACY_ORM
  475. ):
  476. if not self.for_statement:
  477. self.label_style = LABEL_STYLE_TABLENAME_PLUS_COL
  478. else:
  479. self.label_style = LABEL_STYLE_DISAMBIGUATE_ONLY
  480. else:
  481. self.label_style = self.select_statement._label_style
  482. self._label_convention = self._column_naming_convention(
  483. statement._label_style, self.use_legacy_query_style
  484. )
  485. if select_statement._memoized_select_entities:
  486. self._memoized_entities = {
  487. memoized_entities: _QueryEntity.to_compile_state(
  488. self,
  489. memoized_entities._raw_columns,
  490. [],
  491. )
  492. for memoized_entities in (
  493. select_statement._memoized_select_entities
  494. )
  495. }
  496. _QueryEntity.to_compile_state(
  497. self, select_statement._raw_columns, self._entities
  498. )
  499. self.current_path = select_statement._compile_options._current_path
  500. self.eager_order_by = ()
  501. if toplevel and (
  502. select_statement._with_options
  503. or select_statement._memoized_select_entities
  504. ):
  505. self.attributes = {"_unbound_load_dedupes": set()}
  506. for (
  507. memoized_entities
  508. ) in select_statement._memoized_select_entities:
  509. for opt in memoized_entities._with_options:
  510. if opt._is_compile_state:
  511. opt.process_compile_state_replaced_entities(
  512. self,
  513. [
  514. ent
  515. for ent in self._memoized_entities[
  516. memoized_entities
  517. ]
  518. if isinstance(ent, _MapperEntity)
  519. ],
  520. )
  521. for opt in self.select_statement._with_options:
  522. if opt._is_compile_state:
  523. opt.process_compile_state(self)
  524. else:
  525. self.attributes = {}
  526. if select_statement._with_context_options:
  527. for fn, key in select_statement._with_context_options:
  528. fn(self)
  529. self.primary_columns = []
  530. self.secondary_columns = []
  531. self.eager_joins = {}
  532. self.extra_criteria_entities = {}
  533. self.create_eager_joins = []
  534. self._fallback_from_clauses = []
  535. # normalize the FROM clauses early by themselves, as this makes
  536. # it an easier job when we need to assemble a JOIN onto these,
  537. # for select.join() as well as joinedload(). As of 1.4 there are now
  538. # potentially more complex sets of FROM objects here as the use
  539. # of lambda statements for lazyload, load_on_pk etc. uses more
  540. # cloning of the select() construct. See #6495
  541. self.from_clauses = self._normalize_froms(
  542. info.selectable for info in select_statement._from_obj
  543. )
  544. # this is a fairly arbitrary break into a second method,
  545. # so it might be nicer to break up create_for_statement()
  546. # and _setup_for_generate into three or four logical sections
  547. self._setup_for_generate()
  548. SelectState.__init__(self, self.statement, compiler, **kw)
  549. return self
  550. def _setup_for_generate(self):
  551. query = self.select_statement
  552. self.statement = None
  553. self._join_entities = ()
  554. if self.compile_options._set_base_alias:
  555. self._set_select_from_alias()
  556. for memoized_entities in query._memoized_select_entities:
  557. if memoized_entities._setup_joins:
  558. self._join(
  559. memoized_entities._setup_joins,
  560. self._memoized_entities[memoized_entities],
  561. )
  562. if memoized_entities._legacy_setup_joins:
  563. self._legacy_join(
  564. memoized_entities._legacy_setup_joins,
  565. self._memoized_entities[memoized_entities],
  566. )
  567. if query._setup_joins:
  568. self._join(query._setup_joins, self._entities)
  569. if query._legacy_setup_joins:
  570. self._legacy_join(query._legacy_setup_joins, self._entities)
  571. current_adapter = self._get_current_adapter()
  572. if query._where_criteria:
  573. self._where_criteria = query._where_criteria
  574. if current_adapter:
  575. self._where_criteria = tuple(
  576. current_adapter(crit, True)
  577. for crit in self._where_criteria
  578. )
  579. # TODO: some complexity with order_by here was due to mapper.order_by.
  580. # now that this is removed we can hopefully make order_by /
  581. # group_by act identically to how they are in Core select.
  582. self.order_by = (
  583. self._adapt_col_list(query._order_by_clauses, current_adapter)
  584. if current_adapter and query._order_by_clauses not in (None, False)
  585. else query._order_by_clauses
  586. )
  587. if query._having_criteria:
  588. self._having_criteria = tuple(
  589. current_adapter(crit, True) if current_adapter else crit
  590. for crit in query._having_criteria
  591. )
  592. self.group_by = (
  593. self._adapt_col_list(
  594. util.flatten_iterator(query._group_by_clauses), current_adapter
  595. )
  596. if current_adapter and query._group_by_clauses not in (None, False)
  597. else query._group_by_clauses or None
  598. )
  599. if self.eager_order_by:
  600. adapter = self.from_clauses[0]._target_adapter
  601. self.eager_order_by = adapter.copy_and_process(self.eager_order_by)
  602. if query._distinct_on:
  603. self.distinct_on = self._adapt_col_list(
  604. query._distinct_on, current_adapter
  605. )
  606. else:
  607. self.distinct_on = ()
  608. self.distinct = query._distinct
  609. if query._correlate:
  610. # ORM mapped entities that are mapped to joins can be passed
  611. # to .correlate, so here they are broken into their component
  612. # tables.
  613. self.correlate = tuple(
  614. util.flatten_iterator(
  615. sql_util.surface_selectables(s) if s is not None else None
  616. for s in query._correlate
  617. )
  618. )
  619. elif query._correlate_except:
  620. self.correlate_except = tuple(
  621. util.flatten_iterator(
  622. sql_util.surface_selectables(s) if s is not None else None
  623. for s in query._correlate_except
  624. )
  625. )
  626. elif not query._auto_correlate:
  627. self.correlate = (None,)
  628. # PART II
  629. self.dedupe_cols = True
  630. self._for_update_arg = query._for_update_arg
  631. for entity in self._entities:
  632. entity.setup_compile_state(self)
  633. for rec in self.create_eager_joins:
  634. strategy = rec[0]
  635. strategy(self, *rec[1:])
  636. # else "load from discrete FROMs" mode,
  637. # i.e. when each _MappedEntity has its own FROM
  638. if self.compile_options._enable_single_crit:
  639. self._adjust_for_extra_criteria()
  640. if not self.primary_columns:
  641. if self.compile_options._only_load_props:
  642. raise sa_exc.InvalidRequestError(
  643. "No column-based properties specified for "
  644. "refresh operation. Use session.expire() "
  645. "to reload collections and related items."
  646. )
  647. else:
  648. raise sa_exc.InvalidRequestError(
  649. "Query contains no columns with which to SELECT from."
  650. )
  651. if not self.from_clauses:
  652. self.from_clauses = list(self._fallback_from_clauses)
  653. if self.order_by is False:
  654. self.order_by = None
  655. if self.multi_row_eager_loaders and self._should_nest_selectable:
  656. self.statement = self._compound_eager_statement()
  657. else:
  658. self.statement = self._simple_statement()
  659. if self.for_statement:
  660. ezero = self._mapper_zero()
  661. if ezero is not None:
  662. # TODO: this goes away once we get rid of the deep entity
  663. # thing
  664. self.statement = self.statement._annotate(
  665. {"deepentity": ezero}
  666. )
  667. @classmethod
  668. def _create_entities_collection(cls, query, legacy):
  669. """Creates a partial ORMSelectCompileState that includes
  670. the full collection of _MapperEntity and other _QueryEntity objects.
  671. Supports a few remaining use cases that are pre-compilation
  672. but still need to gather some of the column / adaption information.
  673. """
  674. self = cls.__new__(cls)
  675. self._entities = []
  676. self._primary_entity = None
  677. self._aliased_generations = {}
  678. self._polymorphic_adapters = {}
  679. compile_options = cls.default_compile_options.safe_merge(
  680. query._compile_options
  681. )
  682. # legacy: only for query.with_polymorphic()
  683. if compile_options._with_polymorphic_adapt_map:
  684. self._with_polymorphic_adapt_map = dict(
  685. compile_options._with_polymorphic_adapt_map
  686. )
  687. self._setup_with_polymorphics()
  688. self._label_convention = self._column_naming_convention(
  689. query._label_style, legacy
  690. )
  691. # entities will also set up polymorphic adapters for mappers
  692. # that have with_polymorphic configured
  693. _QueryEntity.to_compile_state(self, query._raw_columns, self._entities)
  694. return self
  695. @classmethod
  696. def determine_last_joined_entity(cls, statement):
  697. setup_joins = statement._setup_joins
  698. if not setup_joins:
  699. return None
  700. (target, onclause, from_, flags) = setup_joins[-1]
  701. if isinstance(target, interfaces.PropComparator):
  702. return target.entity
  703. else:
  704. return target
  705. @classmethod
  706. def all_selected_columns(cls, statement):
  707. for element in statement._raw_columns:
  708. if (
  709. element.is_selectable
  710. and "entity_namespace" in element._annotations
  711. ):
  712. ens = element._annotations["entity_namespace"]
  713. if not ens.is_mapper and not ens.is_aliased_class:
  714. for elem in _select_iterables([element]):
  715. yield elem
  716. else:
  717. for elem in _select_iterables(ens._all_column_expressions):
  718. yield elem
  719. else:
  720. for elem in _select_iterables([element]):
  721. yield elem
  722. @classmethod
  723. @util.preload_module("sqlalchemy.orm.query")
  724. def from_statement(cls, statement, from_statement):
  725. query = util.preloaded.orm_query
  726. from_statement = coercions.expect(
  727. roles.ReturnsRowsRole,
  728. from_statement,
  729. apply_propagate_attrs=statement,
  730. )
  731. stmt = query.FromStatement(statement._raw_columns, from_statement)
  732. stmt.__dict__.update(
  733. _with_options=statement._with_options,
  734. _with_context_options=statement._with_context_options,
  735. _execution_options=statement._execution_options,
  736. _propagate_attrs=statement._propagate_attrs,
  737. )
  738. return stmt
  739. def _setup_with_polymorphics(self):
  740. # legacy: only for query.with_polymorphic()
  741. for ext_info, wp in self._with_polymorphic_adapt_map.items():
  742. self._mapper_loads_polymorphically_with(ext_info, wp._adapter)
  743. def _set_select_from_alias(self):
  744. query = self.select_statement # query
  745. assert self.compile_options._set_base_alias
  746. assert len(query._from_obj) == 1
  747. adapter = self._get_select_from_alias_from_obj(query._from_obj[0])
  748. if adapter:
  749. self.compile_options += {"_enable_single_crit": False}
  750. self._from_obj_alias = adapter
  751. def _get_select_from_alias_from_obj(self, from_obj):
  752. info = from_obj
  753. if "parententity" in info._annotations:
  754. info = info._annotations["parententity"]
  755. if hasattr(info, "mapper"):
  756. if not info.is_aliased_class:
  757. raise sa_exc.ArgumentError(
  758. "A selectable (FromClause) instance is "
  759. "expected when the base alias is being set."
  760. )
  761. else:
  762. return info._adapter
  763. elif isinstance(info.selectable, sql.selectable.AliasedReturnsRows):
  764. equivs = self._all_equivs()
  765. return sql_util.ColumnAdapter(info, equivs)
  766. else:
  767. return None
  768. def _mapper_zero(self):
  769. """return the Mapper associated with the first QueryEntity."""
  770. return self._entities[0].mapper
  771. def _entity_zero(self):
  772. """Return the 'entity' (mapper or AliasedClass) associated
  773. with the first QueryEntity, or alternatively the 'select from'
  774. entity if specified."""
  775. for ent in self.from_clauses:
  776. if "parententity" in ent._annotations:
  777. return ent._annotations["parententity"]
  778. for qent in self._entities:
  779. if qent.entity_zero:
  780. return qent.entity_zero
  781. return None
  782. def _only_full_mapper_zero(self, methname):
  783. if self._entities != [self._primary_entity]:
  784. raise sa_exc.InvalidRequestError(
  785. "%s() can only be used against "
  786. "a single mapped class." % methname
  787. )
  788. return self._primary_entity.entity_zero
  789. def _only_entity_zero(self, rationale=None):
  790. if len(self._entities) > 1:
  791. raise sa_exc.InvalidRequestError(
  792. rationale
  793. or "This operation requires a Query "
  794. "against a single mapper."
  795. )
  796. return self._entity_zero()
  797. def _all_equivs(self):
  798. equivs = {}
  799. for memoized_entities in self._memoized_entities.values():
  800. for ent in [
  801. ent
  802. for ent in memoized_entities
  803. if isinstance(ent, _MapperEntity)
  804. ]:
  805. equivs.update(ent.mapper._equivalent_columns)
  806. for ent in [
  807. ent for ent in self._entities if isinstance(ent, _MapperEntity)
  808. ]:
  809. equivs.update(ent.mapper._equivalent_columns)
  810. return equivs
  811. def _compound_eager_statement(self):
  812. # for eager joins present and LIMIT/OFFSET/DISTINCT,
  813. # wrap the query inside a select,
  814. # then append eager joins onto that
  815. if self.order_by:
  816. # the default coercion for ORDER BY is now the OrderByRole,
  817. # which adds an additional post coercion to ByOfRole in that
  818. # elements are converted into label references. For the
  819. # eager load / subquery wrapping case, we need to un-coerce
  820. # the original expressions outside of the label references
  821. # in order to have them render.
  822. unwrapped_order_by = [
  823. elem.element
  824. if isinstance(elem, sql.elements._label_reference)
  825. else elem
  826. for elem in self.order_by
  827. ]
  828. order_by_col_expr = sql_util.expand_column_list_from_order_by(
  829. self.primary_columns, unwrapped_order_by
  830. )
  831. else:
  832. order_by_col_expr = []
  833. unwrapped_order_by = None
  834. # put FOR UPDATE on the inner query, where MySQL will honor it,
  835. # as well as if it has an OF so PostgreSQL can use it.
  836. inner = self._select_statement(
  837. util.unique_list(self.primary_columns + order_by_col_expr)
  838. if self.dedupe_cols
  839. else (self.primary_columns + order_by_col_expr),
  840. self.from_clauses,
  841. self._where_criteria,
  842. self._having_criteria,
  843. self.label_style,
  844. self.order_by,
  845. for_update=self._for_update_arg,
  846. hints=self.select_statement._hints,
  847. statement_hints=self.select_statement._statement_hints,
  848. correlate=self.correlate,
  849. correlate_except=self.correlate_except,
  850. **self._select_args
  851. )
  852. inner = inner.alias()
  853. equivs = self._all_equivs()
  854. self.compound_eager_adapter = sql_util.ColumnAdapter(inner, equivs)
  855. statement = future.select(
  856. *([inner] + self.secondary_columns) # use_labels=self.labels
  857. )
  858. statement._label_style = self.label_style
  859. # Oracle however does not allow FOR UPDATE on the subquery,
  860. # and the Oracle dialect ignores it, plus for PostgreSQL, MySQL
  861. # we expect that all elements of the row are locked, so also put it
  862. # on the outside (except in the case of PG when OF is used)
  863. if (
  864. self._for_update_arg is not None
  865. and self._for_update_arg.of is None
  866. ):
  867. statement._for_update_arg = self._for_update_arg
  868. from_clause = inner
  869. for eager_join in self.eager_joins.values():
  870. # EagerLoader places a 'stop_on' attribute on the join,
  871. # giving us a marker as to where the "splice point" of
  872. # the join should be
  873. from_clause = sql_util.splice_joins(
  874. from_clause, eager_join, eager_join.stop_on
  875. )
  876. statement.select_from.non_generative(statement, from_clause)
  877. if unwrapped_order_by:
  878. statement.order_by.non_generative(
  879. statement,
  880. *self.compound_eager_adapter.copy_and_process(
  881. unwrapped_order_by
  882. )
  883. )
  884. statement.order_by.non_generative(statement, *self.eager_order_by)
  885. return statement
  886. def _simple_statement(self):
  887. if (
  888. self.compile_options._use_legacy_query_style
  889. and (self.distinct and not self.distinct_on)
  890. and self.order_by
  891. ):
  892. to_add = sql_util.expand_column_list_from_order_by(
  893. self.primary_columns, self.order_by
  894. )
  895. if to_add:
  896. util.warn_deprecated_20(
  897. "ORDER BY columns added implicitly due to "
  898. "DISTINCT is deprecated and will be removed in "
  899. "SQLAlchemy 2.0. SELECT statements with DISTINCT "
  900. "should be written to explicitly include the appropriate "
  901. "columns in the columns clause"
  902. )
  903. self.primary_columns += to_add
  904. statement = self._select_statement(
  905. util.unique_list(self.primary_columns + self.secondary_columns)
  906. if self.dedupe_cols
  907. else (self.primary_columns + self.secondary_columns),
  908. tuple(self.from_clauses) + tuple(self.eager_joins.values()),
  909. self._where_criteria,
  910. self._having_criteria,
  911. self.label_style,
  912. self.order_by,
  913. for_update=self._for_update_arg,
  914. hints=self.select_statement._hints,
  915. statement_hints=self.select_statement._statement_hints,
  916. correlate=self.correlate,
  917. correlate_except=self.correlate_except,
  918. **self._select_args
  919. )
  920. if self.eager_order_by:
  921. statement.order_by.non_generative(statement, *self.eager_order_by)
  922. return statement
  923. def _select_statement(
  924. self,
  925. raw_columns,
  926. from_obj,
  927. where_criteria,
  928. having_criteria,
  929. label_style,
  930. order_by,
  931. for_update,
  932. hints,
  933. statement_hints,
  934. correlate,
  935. correlate_except,
  936. limit_clause,
  937. offset_clause,
  938. distinct,
  939. distinct_on,
  940. prefixes,
  941. suffixes,
  942. group_by,
  943. ):
  944. Select = future.Select
  945. statement = Select.__new__(Select)
  946. statement._raw_columns = raw_columns
  947. statement._from_obj = from_obj
  948. statement._label_style = label_style
  949. if where_criteria:
  950. statement._where_criteria = where_criteria
  951. if having_criteria:
  952. statement._having_criteria = having_criteria
  953. if order_by:
  954. statement._order_by_clauses += tuple(order_by)
  955. if distinct_on:
  956. statement.distinct.non_generative(statement, *distinct_on)
  957. elif distinct:
  958. statement.distinct.non_generative(statement)
  959. if group_by:
  960. statement._group_by_clauses += tuple(group_by)
  961. statement._limit_clause = limit_clause
  962. statement._offset_clause = offset_clause
  963. if prefixes:
  964. statement._prefixes = prefixes
  965. if suffixes:
  966. statement._suffixes = suffixes
  967. statement._for_update_arg = for_update
  968. if hints:
  969. statement._hints = hints
  970. if statement_hints:
  971. statement._statement_hints = statement_hints
  972. if correlate:
  973. statement.correlate.non_generative(statement, *correlate)
  974. if correlate_except:
  975. statement.correlate_except.non_generative(
  976. statement, *correlate_except
  977. )
  978. return statement
  979. def _adapt_polymorphic_element(self, element):
  980. if "parententity" in element._annotations:
  981. search = element._annotations["parententity"]
  982. alias = self._polymorphic_adapters.get(search, None)
  983. if alias:
  984. return alias.adapt_clause(element)
  985. if isinstance(element, expression.FromClause):
  986. search = element
  987. elif hasattr(element, "table"):
  988. search = element.table
  989. else:
  990. return None
  991. alias = self._polymorphic_adapters.get(search, None)
  992. if alias:
  993. return alias.adapt_clause(element)
  994. def _adapt_aliased_generation(self, element):
  995. # this is crazy logic that I look forward to blowing away
  996. # when aliased=True is gone :)
  997. if "aliased_generation" in element._annotations:
  998. for adapter in self._aliased_generations.get(
  999. element._annotations["aliased_generation"], ()
  1000. ):
  1001. replaced_elem = adapter.replace(element)
  1002. if replaced_elem is not None:
  1003. return replaced_elem
  1004. return None
  1005. def _adapt_col_list(self, cols, current_adapter):
  1006. if current_adapter:
  1007. return [current_adapter(o, True) for o in cols]
  1008. else:
  1009. return cols
  1010. def _get_current_adapter(self):
  1011. adapters = []
  1012. # vvvvvvvvvvvvvvv legacy vvvvvvvvvvvvvvvvvv
  1013. if self._from_obj_alias:
  1014. # for the "from obj" alias, apply extra rule to the
  1015. # 'ORM only' check, if this query were generated from a
  1016. # subquery of itself, i.e. _from_selectable(), apply adaption
  1017. # to all SQL constructs.
  1018. adapters.append(
  1019. (
  1020. False
  1021. if self.compile_options._orm_only_from_obj_alias
  1022. else True,
  1023. self._from_obj_alias.replace,
  1024. )
  1025. )
  1026. if self._aliased_generations:
  1027. adapters.append((False, self._adapt_aliased_generation))
  1028. # ^^^^^^^^^^^^^ legacy ^^^^^^^^^^^^^^^^^^^^^
  1029. # this is the only adapter we would need going forward...
  1030. if self._polymorphic_adapters:
  1031. adapters.append((False, self._adapt_polymorphic_element))
  1032. if not adapters:
  1033. return None
  1034. def _adapt_clause(clause, as_filter):
  1035. # do we adapt all expression elements or only those
  1036. # tagged as 'ORM' constructs ?
  1037. def replace(elem):
  1038. is_orm_adapt = (
  1039. "_orm_adapt" in elem._annotations
  1040. or "parententity" in elem._annotations
  1041. )
  1042. for always_adapt, adapter in adapters:
  1043. if is_orm_adapt or always_adapt:
  1044. e = adapter(elem)
  1045. if e is not None:
  1046. return e
  1047. return visitors.replacement_traverse(clause, {}, replace)
  1048. return _adapt_clause
  1049. def _join(self, args, entities_collection):
  1050. for (right, onclause, from_, flags) in args:
  1051. isouter = flags["isouter"]
  1052. full = flags["full"]
  1053. # maybe?
  1054. self._reset_joinpoint()
  1055. right = inspect(right)
  1056. if onclause is not None:
  1057. onclause = inspect(onclause)
  1058. if onclause is None and isinstance(
  1059. right, interfaces.PropComparator
  1060. ):
  1061. # determine onclause/right_entity. still need to think
  1062. # about how to best organize this since we are getting:
  1063. #
  1064. #
  1065. # q.join(Entity, Parent.property)
  1066. # q.join(Parent.property)
  1067. # q.join(Parent.property.of_type(Entity))
  1068. # q.join(some_table)
  1069. # q.join(some_table, some_parent.c.id==some_table.c.parent_id)
  1070. #
  1071. # is this still too many choices? how do we handle this
  1072. # when sometimes "right" is implied and sometimes not?
  1073. #
  1074. onclause = right
  1075. right = None
  1076. elif "parententity" in right._annotations:
  1077. right = right._annotations["parententity"]
  1078. if onclause is None:
  1079. if not right.is_selectable and not hasattr(right, "mapper"):
  1080. raise sa_exc.ArgumentError(
  1081. "Expected mapped entity or "
  1082. "selectable/table as join target"
  1083. )
  1084. of_type = None
  1085. if isinstance(onclause, interfaces.PropComparator):
  1086. # descriptor/property given (or determined); this tells us
  1087. # explicitly what the expected "left" side of the join is.
  1088. of_type = getattr(onclause, "_of_type", None)
  1089. if right is None:
  1090. if of_type:
  1091. right = of_type
  1092. else:
  1093. right = onclause.property
  1094. try:
  1095. right = right.entity
  1096. except AttributeError as err:
  1097. util.raise_(
  1098. sa_exc.ArgumentError(
  1099. "Join target %s does not refer to a "
  1100. "mapped entity" % right
  1101. ),
  1102. replace_context=err,
  1103. )
  1104. left = onclause._parententity
  1105. alias = self._polymorphic_adapters.get(left, None)
  1106. # could be None or could be ColumnAdapter also
  1107. if isinstance(alias, ORMAdapter) and alias.mapper.isa(left):
  1108. left = alias.aliased_class
  1109. onclause = getattr(left, onclause.key)
  1110. prop = onclause.property
  1111. if not isinstance(onclause, attributes.QueryableAttribute):
  1112. onclause = prop
  1113. # TODO: this is where "check for path already present"
  1114. # would occur. see if this still applies?
  1115. if from_ is not None:
  1116. if (
  1117. from_ is not left
  1118. and from_._annotations.get("parententity", None)
  1119. is not left
  1120. ):
  1121. raise sa_exc.InvalidRequestError(
  1122. "explicit from clause %s does not match left side "
  1123. "of relationship attribute %s"
  1124. % (
  1125. from_._annotations.get("parententity", from_),
  1126. onclause,
  1127. )
  1128. )
  1129. elif from_ is not None:
  1130. prop = None
  1131. left = from_
  1132. else:
  1133. # no descriptor/property given; we will need to figure out
  1134. # what the effective "left" side is
  1135. prop = left = None
  1136. # figure out the final "left" and "right" sides and create an
  1137. # ORMJoin to add to our _from_obj tuple
  1138. self._join_left_to_right(
  1139. entities_collection,
  1140. left,
  1141. right,
  1142. onclause,
  1143. prop,
  1144. False,
  1145. False,
  1146. isouter,
  1147. full,
  1148. )
  1149. def _legacy_join(self, args, entities_collection):
  1150. """consumes arguments from join() or outerjoin(), places them into a
  1151. consistent format with which to form the actual JOIN constructs.
  1152. """
  1153. for (right, onclause, left, flags) in args:
  1154. outerjoin = flags["isouter"]
  1155. create_aliases = flags["aliased"]
  1156. from_joinpoint = flags["from_joinpoint"]
  1157. full = flags["full"]
  1158. aliased_generation = flags["aliased_generation"]
  1159. # do a quick inspect to accommodate for a lambda
  1160. if right is not None and not isinstance(right, util.string_types):
  1161. right = inspect(right)
  1162. if onclause is not None and not isinstance(
  1163. onclause, util.string_types
  1164. ):
  1165. onclause = inspect(onclause)
  1166. # legacy vvvvvvvvvvvvvvvvvvvvvvvvvv
  1167. if not from_joinpoint:
  1168. self._reset_joinpoint()
  1169. else:
  1170. prev_aliased_generation = self._joinpoint.get(
  1171. "aliased_generation", None
  1172. )
  1173. if not aliased_generation:
  1174. aliased_generation = prev_aliased_generation
  1175. elif prev_aliased_generation:
  1176. self._aliased_generations[
  1177. aliased_generation
  1178. ] = self._aliased_generations.get(
  1179. prev_aliased_generation, ()
  1180. )
  1181. # legacy ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1182. if (
  1183. isinstance(
  1184. right, (interfaces.PropComparator, util.string_types)
  1185. )
  1186. and onclause is None
  1187. ):
  1188. onclause = right
  1189. right = None
  1190. elif "parententity" in right._annotations:
  1191. right = right._annotations["parententity"]
  1192. if onclause is None:
  1193. if not right.is_selectable and not hasattr(right, "mapper"):
  1194. raise sa_exc.ArgumentError(
  1195. "Expected mapped entity or "
  1196. "selectable/table as join target"
  1197. )
  1198. if isinstance(onclause, interfaces.PropComparator):
  1199. of_type = getattr(onclause, "_of_type", None)
  1200. else:
  1201. of_type = None
  1202. if isinstance(onclause, util.string_types):
  1203. # string given, e.g. query(Foo).join("bar").
  1204. # we look to the left entity or what we last joined
  1205. # towards
  1206. onclause = _entity_namespace_key(
  1207. inspect(self._joinpoint_zero()), onclause
  1208. )
  1209. # legacy vvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
  1210. # check for q.join(Class.propname, from_joinpoint=True)
  1211. # and Class corresponds at the mapper level to the current
  1212. # joinpoint. this match intentionally looks for a non-aliased
  1213. # class-bound descriptor as the onclause and if it matches the
  1214. # current joinpoint at the mapper level, it's used. This
  1215. # is a very old use case that is intended to make it easier
  1216. # to work with the aliased=True flag, which is also something
  1217. # that probably shouldn't exist on join() due to its high
  1218. # complexity/usefulness ratio
  1219. elif from_joinpoint and isinstance(
  1220. onclause, interfaces.PropComparator
  1221. ):
  1222. jp0 = self._joinpoint_zero()
  1223. info = inspect(jp0)
  1224. if getattr(info, "mapper", None) is onclause._parententity:
  1225. onclause = _entity_namespace_key(info, onclause.key)
  1226. # legacy ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1227. if isinstance(onclause, interfaces.PropComparator):
  1228. # descriptor/property given (or determined); this tells us
  1229. # explicitly what the expected "left" side of the join is.
  1230. if right is None:
  1231. if of_type:
  1232. right = of_type
  1233. else:
  1234. right = onclause.property
  1235. try:
  1236. right = right.entity
  1237. except AttributeError as err:
  1238. util.raise_(
  1239. sa_exc.ArgumentError(
  1240. "Join target %s does not refer to a "
  1241. "mapped entity" % right
  1242. ),
  1243. replace_context=err,
  1244. )
  1245. left = onclause._parententity
  1246. alias = self._polymorphic_adapters.get(left, None)
  1247. # could be None or could be ColumnAdapter also
  1248. if isinstance(alias, ORMAdapter) and alias.mapper.isa(left):
  1249. left = alias.aliased_class
  1250. onclause = getattr(left, onclause.key)
  1251. prop = onclause.property
  1252. if not isinstance(onclause, attributes.QueryableAttribute):
  1253. onclause = prop
  1254. if not create_aliases:
  1255. # check for this path already present.
  1256. # don't render in that case.
  1257. edge = (left, right, prop.key)
  1258. if edge in self._joinpoint:
  1259. # The child's prev reference might be stale --
  1260. # it could point to a parent older than the
  1261. # current joinpoint. If this is the case,
  1262. # then we need to update it and then fix the
  1263. # tree's spine with _update_joinpoint. Copy
  1264. # and then mutate the child, which might be
  1265. # shared by a different query object.
  1266. jp = self._joinpoint[edge].copy()
  1267. jp["prev"] = (edge, self._joinpoint)
  1268. self._update_joinpoint(jp)
  1269. continue
  1270. else:
  1271. # no descriptor/property given; we will need to figure out
  1272. # what the effective "left" side is
  1273. prop = left = None
  1274. # figure out the final "left" and "right" sides and create an
  1275. # ORMJoin to add to our _from_obj tuple
  1276. self._join_left_to_right(
  1277. entities_collection,
  1278. left,
  1279. right,
  1280. onclause,
  1281. prop,
  1282. create_aliases,
  1283. aliased_generation,
  1284. outerjoin,
  1285. full,
  1286. )
  1287. def _joinpoint_zero(self):
  1288. return self._joinpoint.get("_joinpoint_entity", self._entity_zero())
  1289. def _join_left_to_right(
  1290. self,
  1291. entities_collection,
  1292. left,
  1293. right,
  1294. onclause,
  1295. prop,
  1296. create_aliases,
  1297. aliased_generation,
  1298. outerjoin,
  1299. full,
  1300. ):
  1301. """given raw "left", "right", "onclause" parameters consumed from
  1302. a particular key within _join(), add a real ORMJoin object to
  1303. our _from_obj list (or augment an existing one)
  1304. """
  1305. if left is None:
  1306. # left not given (e.g. no relationship object/name specified)
  1307. # figure out the best "left" side based on our existing froms /
  1308. # entities
  1309. assert prop is None
  1310. (
  1311. left,
  1312. replace_from_obj_index,
  1313. use_entity_index,
  1314. ) = self._join_determine_implicit_left_side(
  1315. entities_collection, left, right, onclause
  1316. )
  1317. else:
  1318. # left is given via a relationship/name, or as explicit left side.
  1319. # Determine where in our
  1320. # "froms" list it should be spliced/appended as well as what
  1321. # existing entity it corresponds to.
  1322. (
  1323. replace_from_obj_index,
  1324. use_entity_index,
  1325. ) = self._join_place_explicit_left_side(entities_collection, left)
  1326. if left is right and not create_aliases:
  1327. raise sa_exc.InvalidRequestError(
  1328. "Can't construct a join from %s to %s, they "
  1329. "are the same entity" % (left, right)
  1330. )
  1331. # the right side as given often needs to be adapted. additionally
  1332. # a lot of things can be wrong with it. handle all that and
  1333. # get back the new effective "right" side
  1334. r_info, right, onclause = self._join_check_and_adapt_right_side(
  1335. left, right, onclause, prop, create_aliases, aliased_generation
  1336. )
  1337. if not r_info.is_selectable:
  1338. extra_criteria = self._get_extra_criteria(r_info)
  1339. else:
  1340. extra_criteria = ()
  1341. if replace_from_obj_index is not None:
  1342. # splice into an existing element in the
  1343. # self._from_obj list
  1344. left_clause = self.from_clauses[replace_from_obj_index]
  1345. self.from_clauses = (
  1346. self.from_clauses[:replace_from_obj_index]
  1347. + [
  1348. _ORMJoin(
  1349. left_clause,
  1350. right,
  1351. onclause,
  1352. isouter=outerjoin,
  1353. full=full,
  1354. _extra_criteria=extra_criteria,
  1355. )
  1356. ]
  1357. + self.from_clauses[replace_from_obj_index + 1 :]
  1358. )
  1359. else:
  1360. # add a new element to the self._from_obj list
  1361. if use_entity_index is not None:
  1362. # make use of _MapperEntity selectable, which is usually
  1363. # entity_zero.selectable, but if with_polymorphic() were used
  1364. # might be distinct
  1365. assert isinstance(
  1366. entities_collection[use_entity_index], _MapperEntity
  1367. )
  1368. left_clause = entities_collection[use_entity_index].selectable
  1369. else:
  1370. left_clause = left
  1371. self.from_clauses = self.from_clauses + [
  1372. _ORMJoin(
  1373. left_clause,
  1374. r_info,
  1375. onclause,
  1376. isouter=outerjoin,
  1377. full=full,
  1378. _extra_criteria=extra_criteria,
  1379. )
  1380. ]
  1381. def _join_determine_implicit_left_side(
  1382. self, entities_collection, left, right, onclause
  1383. ):
  1384. """When join conditions don't express the left side explicitly,
  1385. determine if an existing FROM or entity in this query
  1386. can serve as the left hand side.
  1387. """
  1388. # when we are here, it means join() was called without an ORM-
  1389. # specific way of telling us what the "left" side is, e.g.:
  1390. #
  1391. # join(RightEntity)
  1392. #
  1393. # or
  1394. #
  1395. # join(RightEntity, RightEntity.foo == LeftEntity.bar)
  1396. #
  1397. r_info = inspect(right)
  1398. replace_from_obj_index = use_entity_index = None
  1399. if self.from_clauses:
  1400. # we have a list of FROMs already. So by definition this
  1401. # join has to connect to one of those FROMs.
  1402. indexes = sql_util.find_left_clause_to_join_from(
  1403. self.from_clauses, r_info.selectable, onclause
  1404. )
  1405. if len(indexes) == 1:
  1406. replace_from_obj_index = indexes[0]
  1407. left = self.from_clauses[replace_from_obj_index]
  1408. elif len(indexes) > 1:
  1409. raise sa_exc.InvalidRequestError(
  1410. "Can't determine which FROM clause to join "
  1411. "from, there are multiple FROMS which can "
  1412. "join to this entity. Please use the .select_from() "
  1413. "method to establish an explicit left side, as well as "
  1414. "providing an explicit ON clause if not present already "
  1415. "to help resolve the ambiguity."
  1416. )
  1417. else:
  1418. raise sa_exc.InvalidRequestError(
  1419. "Don't know how to join to %r. "
  1420. "Please use the .select_from() "
  1421. "method to establish an explicit left side, as well as "
  1422. "providing an explicit ON clause if not present already "
  1423. "to help resolve the ambiguity." % (right,)
  1424. )
  1425. elif entities_collection:
  1426. # we have no explicit FROMs, so the implicit left has to
  1427. # come from our list of entities.
  1428. potential = {}
  1429. for entity_index, ent in enumerate(entities_collection):
  1430. entity = ent.entity_zero_or_selectable
  1431. if entity is None:
  1432. continue
  1433. ent_info = inspect(entity)
  1434. if ent_info is r_info: # left and right are the same, skip
  1435. continue
  1436. # by using a dictionary with the selectables as keys this
  1437. # de-duplicates those selectables as occurs when the query is
  1438. # against a series of columns from the same selectable
  1439. if isinstance(ent, _MapperEntity):
  1440. potential[ent.selectable] = (entity_index, entity)
  1441. else:
  1442. potential[ent_info.selectable] = (None, entity)
  1443. all_clauses = list(potential.keys())
  1444. indexes = sql_util.find_left_clause_to_join_from(
  1445. all_clauses, r_info.selectable, onclause
  1446. )
  1447. if len(indexes) == 1:
  1448. use_entity_index, left = potential[all_clauses[indexes[0]]]
  1449. elif len(indexes) > 1:
  1450. raise sa_exc.InvalidRequestError(
  1451. "Can't determine which FROM clause to join "
  1452. "from, there are multiple FROMS which can "
  1453. "join to this entity. Please use the .select_from() "
  1454. "method to establish an explicit left side, as well as "
  1455. "providing an explicit ON clause if not present already "
  1456. "to help resolve the ambiguity."
  1457. )
  1458. else:
  1459. raise sa_exc.InvalidRequestError(
  1460. "Don't know how to join to %r. "
  1461. "Please use the .select_from() "
  1462. "method to establish an explicit left side, as well as "
  1463. "providing an explicit ON clause if not present already "
  1464. "to help resolve the ambiguity." % (right,)
  1465. )
  1466. else:
  1467. raise sa_exc.InvalidRequestError(
  1468. "No entities to join from; please use "
  1469. "select_from() to establish the left "
  1470. "entity/selectable of this join"
  1471. )
  1472. return left, replace_from_obj_index, use_entity_index
  1473. def _join_place_explicit_left_side(self, entities_collection, left):
  1474. """When join conditions express a left side explicitly, determine
  1475. where in our existing list of FROM clauses we should join towards,
  1476. or if we need to make a new join, and if so is it from one of our
  1477. existing entities.
  1478. """
  1479. # when we are here, it means join() was called with an indicator
  1480. # as to an exact left side, which means a path to a
  1481. # RelationshipProperty was given, e.g.:
  1482. #
  1483. # join(RightEntity, LeftEntity.right)
  1484. #
  1485. # or
  1486. #
  1487. # join(LeftEntity.right)
  1488. #
  1489. # as well as string forms:
  1490. #
  1491. # join(RightEntity, "right")
  1492. #
  1493. # etc.
  1494. #
  1495. replace_from_obj_index = use_entity_index = None
  1496. l_info = inspect(left)
  1497. if self.from_clauses:
  1498. indexes = sql_util.find_left_clause_that_matches_given(
  1499. self.from_clauses, l_info.selectable
  1500. )
  1501. if len(indexes) > 1:
  1502. raise sa_exc.InvalidRequestError(
  1503. "Can't identify which entity in which to assign the "
  1504. "left side of this join. Please use a more specific "
  1505. "ON clause."
  1506. )
  1507. # have an index, means the left side is already present in
  1508. # an existing FROM in the self._from_obj tuple
  1509. if indexes:
  1510. replace_from_obj_index = indexes[0]
  1511. # no index, means we need to add a new element to the
  1512. # self._from_obj tuple
  1513. # no from element present, so we will have to add to the
  1514. # self._from_obj tuple. Determine if this left side matches up
  1515. # with existing mapper entities, in which case we want to apply the
  1516. # aliasing / adaptation rules present on that entity if any
  1517. if (
  1518. replace_from_obj_index is None
  1519. and entities_collection
  1520. and hasattr(l_info, "mapper")
  1521. ):
  1522. for idx, ent in enumerate(entities_collection):
  1523. # TODO: should we be checking for multiple mapper entities
  1524. # matching?
  1525. if isinstance(ent, _MapperEntity) and ent.corresponds_to(left):
  1526. use_entity_index = idx
  1527. break
  1528. return replace_from_obj_index, use_entity_index
  1529. def _join_check_and_adapt_right_side(
  1530. self, left, right, onclause, prop, create_aliases, aliased_generation
  1531. ):
  1532. """transform the "right" side of the join as well as the onclause
  1533. according to polymorphic mapping translations, aliasing on the query
  1534. or on the join, special cases where the right and left side have
  1535. overlapping tables.
  1536. """
  1537. l_info = inspect(left)
  1538. r_info = inspect(right)
  1539. overlap = False
  1540. if not create_aliases:
  1541. right_mapper = getattr(r_info, "mapper", None)
  1542. # if the target is a joined inheritance mapping,
  1543. # be more liberal about auto-aliasing.
  1544. if right_mapper and (
  1545. right_mapper.with_polymorphic
  1546. or isinstance(right_mapper.persist_selectable, expression.Join)
  1547. ):
  1548. for from_obj in self.from_clauses or [l_info.selectable]:
  1549. if sql_util.selectables_overlap(
  1550. l_info.selectable, from_obj
  1551. ) and sql_util.selectables_overlap(
  1552. from_obj, r_info.selectable
  1553. ):
  1554. overlap = True
  1555. break
  1556. if (
  1557. overlap or not create_aliases
  1558. ) and l_info.selectable is r_info.selectable:
  1559. raise sa_exc.InvalidRequestError(
  1560. "Can't join table/selectable '%s' to itself"
  1561. % l_info.selectable
  1562. )
  1563. right_mapper, right_selectable, right_is_aliased = (
  1564. getattr(r_info, "mapper", None),
  1565. r_info.selectable,
  1566. getattr(r_info, "is_aliased_class", False),
  1567. )
  1568. if (
  1569. right_mapper
  1570. and prop
  1571. and not right_mapper.common_parent(prop.mapper)
  1572. ):
  1573. raise sa_exc.InvalidRequestError(
  1574. "Join target %s does not correspond to "
  1575. "the right side of join condition %s" % (right, onclause)
  1576. )
  1577. # _join_entities is used as a hint for single-table inheritance
  1578. # purposes at the moment
  1579. if hasattr(r_info, "mapper"):
  1580. self._join_entities += (r_info,)
  1581. need_adapter = False
  1582. # test for joining to an unmapped selectable as the target
  1583. if r_info.is_clause_element:
  1584. if prop:
  1585. right_mapper = prop.mapper
  1586. if right_selectable._is_lateral:
  1587. # orm_only is disabled to suit the case where we have to
  1588. # adapt an explicit correlate(Entity) - the select() loses
  1589. # the ORM-ness in this case right now, ideally it would not
  1590. current_adapter = self._get_current_adapter()
  1591. if current_adapter is not None:
  1592. # TODO: we had orm_only=False here before, removing
  1593. # it didn't break things. if we identify the rationale,
  1594. # may need to apply "_orm_only" annotation here.
  1595. right = current_adapter(right, True)
  1596. elif prop:
  1597. # joining to selectable with a mapper property given
  1598. # as the ON clause
  1599. if not right_selectable.is_derived_from(
  1600. right_mapper.persist_selectable
  1601. ):
  1602. raise sa_exc.InvalidRequestError(
  1603. "Selectable '%s' is not derived from '%s'"
  1604. % (
  1605. right_selectable.description,
  1606. right_mapper.persist_selectable.description,
  1607. )
  1608. )
  1609. # if the destination selectable is a plain select(),
  1610. # turn it into an alias().
  1611. if isinstance(right_selectable, expression.SelectBase):
  1612. right_selectable = coercions.expect(
  1613. roles.FromClauseRole, right_selectable
  1614. )
  1615. need_adapter = True
  1616. # make the right hand side target into an ORM entity
  1617. right = aliased(right_mapper, right_selectable)
  1618. elif create_aliases:
  1619. # it *could* work, but it doesn't right now and I'd rather
  1620. # get rid of aliased=True completely
  1621. raise sa_exc.InvalidRequestError(
  1622. "The aliased=True parameter on query.join() only works "
  1623. "with an ORM entity, not a plain selectable, as the "
  1624. "target."
  1625. )
  1626. # test for overlap:
  1627. # orm/inheritance/relationships.py
  1628. # SelfReferentialM2MTest
  1629. aliased_entity = right_mapper and not right_is_aliased and overlap
  1630. if not need_adapter and (create_aliases or aliased_entity):
  1631. # there are a few places in the ORM that automatic aliasing
  1632. # is still desirable, and can't be automatic with a Core
  1633. # only approach. For illustrations of "overlaps" see
  1634. # test/orm/inheritance/test_relationships.py. There are also
  1635. # general overlap cases with many-to-many tables where automatic
  1636. # aliasing is desirable.
  1637. right = aliased(right, flat=True)
  1638. need_adapter = True
  1639. if need_adapter:
  1640. assert right_mapper
  1641. adapter = ORMAdapter(
  1642. right, equivalents=right_mapper._equivalent_columns
  1643. )
  1644. # if an alias() on the right side was generated,
  1645. # which is intended to wrap a the right side in a subquery,
  1646. # ensure that columns retrieved from this target in the result
  1647. # set are also adapted.
  1648. if not create_aliases:
  1649. self._mapper_loads_polymorphically_with(right_mapper, adapter)
  1650. elif aliased_generation:
  1651. adapter._debug = True
  1652. self._aliased_generations[aliased_generation] = (
  1653. adapter,
  1654. ) + self._aliased_generations.get(aliased_generation, ())
  1655. elif (
  1656. not r_info.is_clause_element
  1657. and not right_is_aliased
  1658. and right_mapper.with_polymorphic
  1659. and isinstance(
  1660. right_mapper._with_polymorphic_selectable,
  1661. expression.AliasedReturnsRows,
  1662. )
  1663. ):
  1664. # for the case where the target mapper has a with_polymorphic
  1665. # set up, ensure an adapter is set up for criteria that works
  1666. # against this mapper. Previously, this logic used to
  1667. # use the "create_aliases or aliased_entity" case to generate
  1668. # an aliased() object, but this creates an alias that isn't
  1669. # strictly necessary.
  1670. # see test/orm/test_core_compilation.py
  1671. # ::RelNaturalAliasedJoinsTest::test_straight
  1672. # and similar
  1673. self._mapper_loads_polymorphically_with(
  1674. right_mapper,
  1675. sql_util.ColumnAdapter(
  1676. right_mapper.selectable,
  1677. right_mapper._equivalent_columns,
  1678. ),
  1679. )
  1680. # if the onclause is a ClauseElement, adapt it with any
  1681. # adapters that are in place right now
  1682. if isinstance(onclause, expression.ClauseElement):
  1683. current_adapter = self._get_current_adapter()
  1684. if current_adapter:
  1685. onclause = current_adapter(onclause, True)
  1686. # if joining on a MapperProperty path,
  1687. # track the path to prevent redundant joins
  1688. if not create_aliases and prop:
  1689. self._update_joinpoint(
  1690. {
  1691. "_joinpoint_entity": right,
  1692. "prev": ((left, right, prop.key), self._joinpoint),
  1693. "aliased_generation": aliased_generation,
  1694. }
  1695. )
  1696. else:
  1697. self._joinpoint = {
  1698. "_joinpoint_entity": right,
  1699. "aliased_generation": aliased_generation,
  1700. }
  1701. return inspect(right), right, onclause
  1702. def _update_joinpoint(self, jp):
  1703. self._joinpoint = jp
  1704. # copy backwards to the root of the _joinpath
  1705. # dict, so that no existing dict in the path is mutated
  1706. while "prev" in jp:
  1707. f, prev = jp["prev"]
  1708. prev = dict(prev)
  1709. prev[f] = jp.copy()
  1710. jp["prev"] = (f, prev)
  1711. jp = prev
  1712. self._joinpath = jp
  1713. def _reset_joinpoint(self):
  1714. self._joinpoint = self._joinpath
  1715. @property
  1716. def _select_args(self):
  1717. return {
  1718. "limit_clause": self.select_statement._limit_clause,
  1719. "offset_clause": self.select_statement._offset_clause,
  1720. "distinct": self.distinct,
  1721. "distinct_on": self.distinct_on,
  1722. "prefixes": self.select_statement._prefixes,
  1723. "suffixes": self.select_statement._suffixes,
  1724. "group_by": self.group_by or None,
  1725. }
  1726. @property
  1727. def _should_nest_selectable(self):
  1728. kwargs = self._select_args
  1729. return (
  1730. kwargs.get("limit_clause") is not None
  1731. or kwargs.get("offset_clause") is not None
  1732. or kwargs.get("distinct", False)
  1733. or kwargs.get("distinct_on", ())
  1734. or kwargs.get("group_by", False)
  1735. )
  1736. def _get_extra_criteria(self, ext_info):
  1737. if (
  1738. "additional_entity_criteria",
  1739. ext_info.mapper,
  1740. ) in self.global_attributes:
  1741. return tuple(
  1742. ae._resolve_where_criteria(ext_info)
  1743. for ae in self.global_attributes[
  1744. ("additional_entity_criteria", ext_info.mapper)
  1745. ]
  1746. if ae.include_aliases or ae.entity is ext_info
  1747. )
  1748. else:
  1749. return ()
  1750. def _adjust_for_extra_criteria(self):
  1751. """Apply extra criteria filtering.
  1752. For all distinct single-table-inheritance mappers represented in
  1753. the columns clause of this query, as well as the "select from entity",
  1754. add criterion to the WHERE
  1755. clause of the given QueryContext such that only the appropriate
  1756. subtypes are selected from the total results.
  1757. Additionally, add WHERE criteria originating from LoaderCriteriaOptions
  1758. associated with the global context.
  1759. """
  1760. for fromclause in self.from_clauses:
  1761. ext_info = fromclause._annotations.get("parententity", None)
  1762. if (
  1763. ext_info
  1764. and (
  1765. ext_info.mapper._single_table_criterion is not None
  1766. or ("additional_entity_criteria", ext_info.mapper)
  1767. in self.global_attributes
  1768. )
  1769. and ext_info not in self.extra_criteria_entities
  1770. ):
  1771. self.extra_criteria_entities[ext_info] = (
  1772. ext_info,
  1773. ext_info._adapter if ext_info.is_aliased_class else None,
  1774. )
  1775. search = set(self.extra_criteria_entities.values())
  1776. for (ext_info, adapter) in search:
  1777. if ext_info in self._join_entities:
  1778. continue
  1779. single_crit = ext_info.mapper._single_table_criterion
  1780. additional_entity_criteria = self._get_extra_criteria(ext_info)
  1781. if single_crit is not None:
  1782. additional_entity_criteria += (single_crit,)
  1783. current_adapter = self._get_current_adapter()
  1784. for crit in additional_entity_criteria:
  1785. if adapter:
  1786. crit = adapter.traverse(crit)
  1787. if current_adapter:
  1788. crit = sql_util._deep_annotate(crit, {"_orm_adapt": True})
  1789. crit = current_adapter(crit, False)
  1790. self._where_criteria += (crit,)
  1791. def _column_descriptions(
  1792. query_or_select_stmt, compile_state=None, legacy=False
  1793. ):
  1794. if compile_state is None:
  1795. compile_state = ORMSelectCompileState._create_entities_collection(
  1796. query_or_select_stmt, legacy=legacy
  1797. )
  1798. ctx = compile_state
  1799. return [
  1800. {
  1801. "name": ent._label_name,
  1802. "type": ent.type,
  1803. "aliased": getattr(insp_ent, "is_aliased_class", False),
  1804. "expr": ent.expr,
  1805. "entity": getattr(insp_ent, "entity", None)
  1806. if ent.entity_zero is not None and not insp_ent.is_clause_element
  1807. else None,
  1808. }
  1809. for ent, insp_ent in [
  1810. (
  1811. _ent,
  1812. (
  1813. inspect(_ent.entity_zero)
  1814. if _ent.entity_zero is not None
  1815. else None
  1816. ),
  1817. )
  1818. for _ent in ctx._entities
  1819. ]
  1820. ]
  1821. def _legacy_filter_by_entity_zero(query_or_augmented_select):
  1822. self = query_or_augmented_select
  1823. if self._legacy_setup_joins:
  1824. _last_joined_entity = self._last_joined_entity
  1825. if _last_joined_entity is not None:
  1826. return _last_joined_entity
  1827. if self._from_obj and "parententity" in self._from_obj[0]._annotations:
  1828. return self._from_obj[0]._annotations["parententity"]
  1829. return _entity_from_pre_ent_zero(self)
  1830. def _entity_from_pre_ent_zero(query_or_augmented_select):
  1831. self = query_or_augmented_select
  1832. if not self._raw_columns:
  1833. return None
  1834. ent = self._raw_columns[0]
  1835. if "parententity" in ent._annotations:
  1836. return ent._annotations["parententity"]
  1837. elif isinstance(ent, ORMColumnsClauseRole):
  1838. return ent.entity
  1839. elif "bundle" in ent._annotations:
  1840. return ent._annotations["bundle"]
  1841. else:
  1842. return ent
  1843. def _legacy_determine_last_joined_entity(setup_joins, entity_zero):
  1844. """given the legacy_setup_joins collection at a point in time,
  1845. figure out what the "filter by entity" would be in terms
  1846. of those joins.
  1847. in 2.0 this logic should hopefully be much simpler as there will
  1848. be far fewer ways to specify joins with the ORM
  1849. """
  1850. if not setup_joins:
  1851. return entity_zero
  1852. # CAN BE REMOVED IN 2.0:
  1853. # 1. from_joinpoint
  1854. # 2. aliased_generation
  1855. # 3. aliased
  1856. # 4. any treating of prop as str
  1857. # 5. tuple madness
  1858. # 6. won't need recursive call anymore without #4
  1859. # 7. therefore can pass in just the last setup_joins record,
  1860. # don't need entity_zero
  1861. (right, onclause, left_, flags) = setup_joins[-1]
  1862. from_joinpoint = flags["from_joinpoint"]
  1863. if onclause is None and isinstance(
  1864. right, (str, interfaces.PropComparator)
  1865. ):
  1866. onclause = right
  1867. right = None
  1868. if right is not None and "parententity" in right._annotations:
  1869. right = right._annotations["parententity"].entity
  1870. if right is not None:
  1871. last_entity = right
  1872. insp = inspect(last_entity)
  1873. if insp.is_clause_element or insp.is_aliased_class or insp.is_mapper:
  1874. return insp
  1875. last_entity = onclause
  1876. if isinstance(last_entity, interfaces.PropComparator):
  1877. return last_entity.entity
  1878. # legacy vvvvvvvvvvvvvvvvvvvvvvvvvvv
  1879. if isinstance(onclause, str):
  1880. if from_joinpoint:
  1881. prev = _legacy_determine_last_joined_entity(
  1882. setup_joins[0:-1], entity_zero
  1883. )
  1884. else:
  1885. prev = entity_zero
  1886. if prev is None:
  1887. return None
  1888. prev = inspect(prev)
  1889. attr = getattr(prev.entity, onclause, None)
  1890. if attr is not None:
  1891. return attr.property.entity
  1892. # legacy ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1893. return None
  1894. class _QueryEntity(object):
  1895. """represent an entity column returned within a Query result."""
  1896. __slots__ = ()
  1897. @classmethod
  1898. def to_compile_state(cls, compile_state, entities, entities_collection):
  1899. for idx, entity in enumerate(entities):
  1900. if entity._is_lambda_element:
  1901. if entity._is_sequence:
  1902. cls.to_compile_state(
  1903. compile_state, entity._resolved, entities_collection
  1904. )
  1905. continue
  1906. else:
  1907. entity = entity._resolved
  1908. if entity.is_clause_element:
  1909. if entity.is_selectable:
  1910. if "parententity" in entity._annotations:
  1911. _MapperEntity(
  1912. compile_state, entity, entities_collection
  1913. )
  1914. else:
  1915. _ColumnEntity._for_columns(
  1916. compile_state,
  1917. entity._select_iterable,
  1918. entities_collection,
  1919. idx,
  1920. )
  1921. else:
  1922. if entity._annotations.get("bundle", False):
  1923. _BundleEntity(
  1924. compile_state, entity, entities_collection
  1925. )
  1926. elif entity._is_clause_list:
  1927. # this is legacy only - test_composites.py
  1928. # test_query_cols_legacy
  1929. _ColumnEntity._for_columns(
  1930. compile_state,
  1931. entity._select_iterable,
  1932. entities_collection,
  1933. idx,
  1934. )
  1935. else:
  1936. _ColumnEntity._for_columns(
  1937. compile_state, [entity], entities_collection, idx
  1938. )
  1939. elif entity.is_bundle:
  1940. _BundleEntity(compile_state, entity, entities_collection)
  1941. return entities_collection
  1942. class _MapperEntity(_QueryEntity):
  1943. """mapper/class/AliasedClass entity"""
  1944. __slots__ = (
  1945. "expr",
  1946. "mapper",
  1947. "entity_zero",
  1948. "is_aliased_class",
  1949. "path",
  1950. "_extra_entities",
  1951. "_label_name",
  1952. "_with_polymorphic_mappers",
  1953. "selectable",
  1954. "_polymorphic_discriminator",
  1955. )
  1956. def __init__(self, compile_state, entity, entities_collection):
  1957. entities_collection.append(self)
  1958. if compile_state._primary_entity is None:
  1959. compile_state._primary_entity = self
  1960. compile_state._has_mapper_entities = True
  1961. compile_state._has_orm_entities = True
  1962. entity = entity._annotations["parententity"]
  1963. entity._post_inspect
  1964. ext_info = self.entity_zero = entity
  1965. entity = ext_info.entity
  1966. self.expr = entity
  1967. self.mapper = mapper = ext_info.mapper
  1968. self._extra_entities = (self.expr,)
  1969. if ext_info.is_aliased_class:
  1970. self._label_name = ext_info.name
  1971. else:
  1972. self._label_name = mapper.class_.__name__
  1973. self.is_aliased_class = ext_info.is_aliased_class
  1974. self.path = ext_info._path_registry
  1975. if ext_info in compile_state._with_polymorphic_adapt_map:
  1976. # this codepath occurs only if query.with_polymorphic() were
  1977. # used
  1978. wp = inspect(compile_state._with_polymorphic_adapt_map[ext_info])
  1979. if self.is_aliased_class:
  1980. # TODO: invalidrequest ?
  1981. raise NotImplementedError(
  1982. "Can't use with_polymorphic() against an Aliased object"
  1983. )
  1984. mappers, from_obj = mapper._with_polymorphic_args(
  1985. wp.with_polymorphic_mappers, wp.selectable
  1986. )
  1987. self._with_polymorphic_mappers = mappers
  1988. self.selectable = from_obj
  1989. self._polymorphic_discriminator = wp.polymorphic_on
  1990. else:
  1991. self.selectable = ext_info.selectable
  1992. self._with_polymorphic_mappers = ext_info.with_polymorphic_mappers
  1993. self._polymorphic_discriminator = ext_info.polymorphic_on
  1994. if (
  1995. mapper.with_polymorphic
  1996. # controversy - only if inheriting mapper is also
  1997. # polymorphic?
  1998. # or (mapper.inherits and mapper.inherits.with_polymorphic)
  1999. or mapper.inherits
  2000. or mapper._requires_row_aliasing
  2001. ):
  2002. compile_state._create_with_polymorphic_adapter(
  2003. ext_info, self.selectable
  2004. )
  2005. supports_single_entity = True
  2006. use_id_for_hash = True
  2007. @property
  2008. def type(self):
  2009. return self.mapper.class_
  2010. @property
  2011. def entity_zero_or_selectable(self):
  2012. return self.entity_zero
  2013. def corresponds_to(self, entity):
  2014. return _entity_corresponds_to(self.entity_zero, entity)
  2015. def _get_entity_clauses(self, compile_state):
  2016. adapter = None
  2017. if not self.is_aliased_class:
  2018. if compile_state._polymorphic_adapters:
  2019. adapter = compile_state._polymorphic_adapters.get(
  2020. self.mapper, None
  2021. )
  2022. else:
  2023. adapter = self.entity_zero._adapter
  2024. if adapter:
  2025. if compile_state._from_obj_alias:
  2026. ret = adapter.wrap(compile_state._from_obj_alias)
  2027. else:
  2028. ret = adapter
  2029. else:
  2030. ret = compile_state._from_obj_alias
  2031. return ret
  2032. def row_processor(self, context, result):
  2033. compile_state = context.compile_state
  2034. adapter = self._get_entity_clauses(compile_state)
  2035. if compile_state.compound_eager_adapter and adapter:
  2036. adapter = adapter.wrap(compile_state.compound_eager_adapter)
  2037. elif not adapter:
  2038. adapter = compile_state.compound_eager_adapter
  2039. if compile_state._primary_entity is self:
  2040. only_load_props = compile_state.compile_options._only_load_props
  2041. refresh_state = context.refresh_state
  2042. else:
  2043. only_load_props = refresh_state = None
  2044. _instance = loading._instance_processor(
  2045. self,
  2046. self.mapper,
  2047. context,
  2048. result,
  2049. self.path,
  2050. adapter,
  2051. only_load_props=only_load_props,
  2052. refresh_state=refresh_state,
  2053. polymorphic_discriminator=self._polymorphic_discriminator,
  2054. )
  2055. return _instance, self._label_name, self._extra_entities
  2056. def setup_compile_state(self, compile_state):
  2057. adapter = self._get_entity_clauses(compile_state)
  2058. single_table_crit = self.mapper._single_table_criterion
  2059. if (
  2060. single_table_crit is not None
  2061. or ("additional_entity_criteria", self.mapper)
  2062. in compile_state.global_attributes
  2063. ):
  2064. ext_info = self.entity_zero
  2065. compile_state.extra_criteria_entities[ext_info] = (
  2066. ext_info,
  2067. ext_info._adapter if ext_info.is_aliased_class else None,
  2068. )
  2069. loading._setup_entity_query(
  2070. compile_state,
  2071. self.mapper,
  2072. self,
  2073. self.path,
  2074. adapter,
  2075. compile_state.primary_columns,
  2076. with_polymorphic=self._with_polymorphic_mappers,
  2077. only_load_props=compile_state.compile_options._only_load_props,
  2078. polymorphic_discriminator=self._polymorphic_discriminator,
  2079. )
  2080. compile_state._fallback_from_clauses.append(self.selectable)
  2081. class _BundleEntity(_QueryEntity):
  2082. use_id_for_hash = False
  2083. _extra_entities = ()
  2084. __slots__ = (
  2085. "bundle",
  2086. "expr",
  2087. "type",
  2088. "_label_name",
  2089. "_entities",
  2090. "supports_single_entity",
  2091. )
  2092. def __init__(
  2093. self,
  2094. compile_state,
  2095. expr,
  2096. entities_collection,
  2097. setup_entities=True,
  2098. parent_bundle=None,
  2099. ):
  2100. compile_state._has_orm_entities = True
  2101. expr = expr._annotations["bundle"]
  2102. if parent_bundle:
  2103. parent_bundle._entities.append(self)
  2104. else:
  2105. entities_collection.append(self)
  2106. if isinstance(
  2107. expr, (attributes.QueryableAttribute, interfaces.PropComparator)
  2108. ):
  2109. bundle = expr.__clause_element__()
  2110. else:
  2111. bundle = expr
  2112. self.bundle = self.expr = bundle
  2113. self.type = type(bundle)
  2114. self._label_name = bundle.name
  2115. self._entities = []
  2116. if setup_entities:
  2117. for expr in bundle.exprs:
  2118. if "bundle" in expr._annotations:
  2119. _BundleEntity(
  2120. compile_state,
  2121. expr,
  2122. entities_collection,
  2123. parent_bundle=self,
  2124. )
  2125. elif isinstance(expr, Bundle):
  2126. _BundleEntity(
  2127. compile_state,
  2128. expr,
  2129. entities_collection,
  2130. parent_bundle=self,
  2131. )
  2132. else:
  2133. _ORMColumnEntity._for_columns(
  2134. compile_state,
  2135. [expr],
  2136. entities_collection,
  2137. None,
  2138. parent_bundle=self,
  2139. )
  2140. self.supports_single_entity = self.bundle.single_entity
  2141. if (
  2142. self.supports_single_entity
  2143. and not compile_state.compile_options._use_legacy_query_style
  2144. ):
  2145. util.warn_deprecated_20(
  2146. "The Bundle.single_entity flag has no effect when "
  2147. "using 2.0 style execution."
  2148. )
  2149. @property
  2150. def mapper(self):
  2151. ezero = self.entity_zero
  2152. if ezero is not None:
  2153. return ezero.mapper
  2154. else:
  2155. return None
  2156. @property
  2157. def entity_zero(self):
  2158. for ent in self._entities:
  2159. ezero = ent.entity_zero
  2160. if ezero is not None:
  2161. return ezero
  2162. else:
  2163. return None
  2164. def corresponds_to(self, entity):
  2165. # TODO: we might be able to implement this but for now
  2166. # we are working around it
  2167. return False
  2168. @property
  2169. def entity_zero_or_selectable(self):
  2170. for ent in self._entities:
  2171. ezero = ent.entity_zero_or_selectable
  2172. if ezero is not None:
  2173. return ezero
  2174. else:
  2175. return None
  2176. def setup_compile_state(self, compile_state):
  2177. for ent in self._entities:
  2178. ent.setup_compile_state(compile_state)
  2179. def row_processor(self, context, result):
  2180. procs, labels, extra = zip(
  2181. *[ent.row_processor(context, result) for ent in self._entities]
  2182. )
  2183. proc = self.bundle.create_row_processor(context.query, procs, labels)
  2184. return proc, self._label_name, self._extra_entities
  2185. class _ColumnEntity(_QueryEntity):
  2186. __slots__ = (
  2187. "_fetch_column",
  2188. "_row_processor",
  2189. "raw_column_index",
  2190. "translate_raw_column",
  2191. )
  2192. @classmethod
  2193. def _for_columns(
  2194. cls,
  2195. compile_state,
  2196. columns,
  2197. entities_collection,
  2198. raw_column_index,
  2199. parent_bundle=None,
  2200. ):
  2201. for column in columns:
  2202. annotations = column._annotations
  2203. if "parententity" in annotations:
  2204. _entity = annotations["parententity"]
  2205. else:
  2206. _entity = sql_util.extract_first_column_annotation(
  2207. column, "parententity"
  2208. )
  2209. if _entity:
  2210. if "identity_token" in column._annotations:
  2211. _IdentityTokenEntity(
  2212. compile_state,
  2213. column,
  2214. entities_collection,
  2215. _entity,
  2216. raw_column_index,
  2217. parent_bundle=parent_bundle,
  2218. )
  2219. else:
  2220. _ORMColumnEntity(
  2221. compile_state,
  2222. column,
  2223. entities_collection,
  2224. _entity,
  2225. raw_column_index,
  2226. parent_bundle=parent_bundle,
  2227. )
  2228. else:
  2229. _RawColumnEntity(
  2230. compile_state,
  2231. column,
  2232. entities_collection,
  2233. raw_column_index,
  2234. parent_bundle=parent_bundle,
  2235. )
  2236. @property
  2237. def type(self):
  2238. return self.column.type
  2239. @property
  2240. def use_id_for_hash(self):
  2241. return not self.column.type.hashable
  2242. def row_processor(self, context, result):
  2243. compile_state = context.compile_state
  2244. # the resulting callable is entirely cacheable so just return
  2245. # it if we already made one
  2246. if self._row_processor is not None:
  2247. getter, label_name, extra_entities = self._row_processor
  2248. if self.translate_raw_column:
  2249. extra_entities += (
  2250. result.context.invoked_statement._raw_columns[
  2251. self.raw_column_index
  2252. ],
  2253. )
  2254. return getter, label_name, extra_entities
  2255. # retrieve the column that would have been set up in
  2256. # setup_compile_state, to avoid doing redundant work
  2257. if self._fetch_column is not None:
  2258. column = self._fetch_column
  2259. else:
  2260. # fetch_column will be None when we are doing a from_statement
  2261. # and setup_compile_state may not have been called.
  2262. column = self.column
  2263. # previously, the RawColumnEntity didn't look for from_obj_alias
  2264. # however I can't think of a case where we would be here and
  2265. # we'd want to ignore it if this is the from_statement use case.
  2266. # it's not really a use case to have raw columns + from_statement
  2267. if compile_state._from_obj_alias:
  2268. column = compile_state._from_obj_alias.columns[column]
  2269. if column._annotations:
  2270. # annotated columns perform more slowly in compiler and
  2271. # result due to the __eq__() method, so use deannotated
  2272. column = column._deannotate()
  2273. if compile_state.compound_eager_adapter:
  2274. column = compile_state.compound_eager_adapter.columns[column]
  2275. getter = result._getter(column)
  2276. ret = getter, self._label_name, self._extra_entities
  2277. self._row_processor = ret
  2278. if self.translate_raw_column:
  2279. extra_entities = self._extra_entities + (
  2280. result.context.invoked_statement._raw_columns[
  2281. self.raw_column_index
  2282. ],
  2283. )
  2284. return getter, self._label_name, extra_entities
  2285. else:
  2286. return ret
  2287. class _RawColumnEntity(_ColumnEntity):
  2288. entity_zero = None
  2289. mapper = None
  2290. supports_single_entity = False
  2291. __slots__ = (
  2292. "expr",
  2293. "column",
  2294. "_label_name",
  2295. "entity_zero_or_selectable",
  2296. "_extra_entities",
  2297. )
  2298. def __init__(
  2299. self,
  2300. compile_state,
  2301. column,
  2302. entities_collection,
  2303. raw_column_index,
  2304. parent_bundle=None,
  2305. ):
  2306. self.expr = column
  2307. self.raw_column_index = raw_column_index
  2308. self.translate_raw_column = raw_column_index is not None
  2309. if column._is_text_clause:
  2310. self._label_name = None
  2311. else:
  2312. self._label_name = compile_state._label_convention(column)
  2313. if parent_bundle:
  2314. parent_bundle._entities.append(self)
  2315. else:
  2316. entities_collection.append(self)
  2317. self.column = column
  2318. self.entity_zero_or_selectable = (
  2319. self.column._from_objects[0] if self.column._from_objects else None
  2320. )
  2321. self._extra_entities = (self.expr, self.column)
  2322. self._fetch_column = self._row_processor = None
  2323. def corresponds_to(self, entity):
  2324. return False
  2325. def setup_compile_state(self, compile_state):
  2326. current_adapter = compile_state._get_current_adapter()
  2327. if current_adapter:
  2328. column = current_adapter(self.column, False)
  2329. else:
  2330. column = self.column
  2331. if column._annotations:
  2332. # annotated columns perform more slowly in compiler and
  2333. # result due to the __eq__() method, so use deannotated
  2334. column = column._deannotate()
  2335. compile_state.primary_columns.append(column)
  2336. self._fetch_column = column
  2337. class _ORMColumnEntity(_ColumnEntity):
  2338. """Column/expression based entity."""
  2339. supports_single_entity = False
  2340. __slots__ = (
  2341. "expr",
  2342. "mapper",
  2343. "column",
  2344. "_label_name",
  2345. "entity_zero_or_selectable",
  2346. "entity_zero",
  2347. "_extra_entities",
  2348. )
  2349. def __init__(
  2350. self,
  2351. compile_state,
  2352. column,
  2353. entities_collection,
  2354. parententity,
  2355. raw_column_index,
  2356. parent_bundle=None,
  2357. ):
  2358. annotations = column._annotations
  2359. _entity = parententity
  2360. # an AliasedClass won't have proxy_key in the annotations for
  2361. # a column if it was acquired using the class' adapter directly,
  2362. # such as using AliasedInsp._adapt_element(). this occurs
  2363. # within internal loaders.
  2364. orm_key = annotations.get("proxy_key", None)
  2365. proxy_owner = annotations.get("proxy_owner", _entity)
  2366. if orm_key:
  2367. self.expr = getattr(proxy_owner.entity, orm_key)
  2368. self.translate_raw_column = False
  2369. else:
  2370. # if orm_key is not present, that means this is an ad-hoc
  2371. # SQL ColumnElement, like a CASE() or other expression.
  2372. # include this column position from the invoked statement
  2373. # in the ORM-level ResultSetMetaData on each execute, so that
  2374. # it can be targeted by identity after caching
  2375. self.expr = column
  2376. self.translate_raw_column = raw_column_index is not None
  2377. self.raw_column_index = raw_column_index
  2378. self._label_name = compile_state._label_convention(
  2379. column, col_name=orm_key
  2380. )
  2381. _entity._post_inspect
  2382. self.entity_zero = self.entity_zero_or_selectable = ezero = _entity
  2383. self.mapper = mapper = _entity.mapper
  2384. if parent_bundle:
  2385. parent_bundle._entities.append(self)
  2386. else:
  2387. entities_collection.append(self)
  2388. compile_state._has_orm_entities = True
  2389. self.column = column
  2390. self._fetch_column = self._row_processor = None
  2391. self._extra_entities = (self.expr, self.column)
  2392. if (
  2393. mapper.with_polymorphic
  2394. or mapper.inherits
  2395. or mapper._requires_row_aliasing
  2396. ):
  2397. compile_state._create_with_polymorphic_adapter(
  2398. ezero, ezero.selectable
  2399. )
  2400. def corresponds_to(self, entity):
  2401. if _is_aliased_class(entity):
  2402. # TODO: polymorphic subclasses ?
  2403. return entity is self.entity_zero
  2404. else:
  2405. return not _is_aliased_class(
  2406. self.entity_zero
  2407. ) and entity.common_parent(self.entity_zero)
  2408. def setup_compile_state(self, compile_state):
  2409. current_adapter = compile_state._get_current_adapter()
  2410. if current_adapter:
  2411. column = current_adapter(self.column, False)
  2412. else:
  2413. column = self.column
  2414. ezero = self.entity_zero
  2415. single_table_crit = self.mapper._single_table_criterion
  2416. if (
  2417. single_table_crit is not None
  2418. or ("additional_entity_criteria", self.mapper)
  2419. in compile_state.global_attributes
  2420. ):
  2421. compile_state.extra_criteria_entities[ezero] = (
  2422. ezero,
  2423. ezero._adapter if ezero.is_aliased_class else None,
  2424. )
  2425. if column._annotations:
  2426. # annotated columns perform more slowly in compiler and
  2427. # result due to the __eq__() method, so use deannotated
  2428. column = column._deannotate()
  2429. # use entity_zero as the from if we have it. this is necessary
  2430. # for polymorphic scenarios where our FROM is based on ORM entity,
  2431. # not the FROM of the column. but also, don't use it if our column
  2432. # doesn't actually have any FROMs that line up, such as when its
  2433. # a scalar subquery.
  2434. if set(self.column._from_objects).intersection(
  2435. ezero.selectable._from_objects
  2436. ):
  2437. compile_state._fallback_from_clauses.append(ezero.selectable)
  2438. compile_state.primary_columns.append(column)
  2439. self._fetch_column = column
  2440. class _IdentityTokenEntity(_ORMColumnEntity):
  2441. translate_raw_column = False
  2442. def setup_compile_state(self, compile_state):
  2443. pass
  2444. def row_processor(self, context, result):
  2445. def getter(row):
  2446. return context.load_options._refresh_identity_token
  2447. return getter, self._label_name, self._extra_entities