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.

1824 lines
60KB

  1. # Copyright (C) 2005-2021 the SQLAlchemy authors and contributors
  2. # <see AUTHORS file>
  3. #
  4. # This module is part of SQLAlchemy and is released under
  5. # the MIT License: http://www.opensource.org/licenses/mit-license.php
  6. """
  7. """
  8. from . import util as orm_util
  9. from .attributes import QueryableAttribute
  10. from .base import _class_to_mapper
  11. from .base import _is_aliased_class
  12. from .base import _is_mapped_class
  13. from .base import InspectionAttr
  14. from .interfaces import LoaderOption
  15. from .interfaces import MapperProperty
  16. from .interfaces import PropComparator
  17. from .path_registry import _DEFAULT_TOKEN
  18. from .path_registry import _WILDCARD_TOKEN
  19. from .path_registry import PathRegistry
  20. from .path_registry import TokenRegistry
  21. from .util import _orm_full_deannotate
  22. from .. import exc as sa_exc
  23. from .. import inspect
  24. from .. import util
  25. from ..sql import and_
  26. from ..sql import coercions
  27. from ..sql import roles
  28. from ..sql import visitors
  29. from ..sql.base import _generative
  30. from ..sql.base import Generative
  31. class Load(Generative, LoaderOption):
  32. """Represents loader options which modify the state of a
  33. :class:`_query.Query` in order to affect how various mapped attributes are
  34. loaded.
  35. The :class:`_orm.Load` object is in most cases used implicitly behind the
  36. scenes when one makes use of a query option like :func:`_orm.joinedload`,
  37. :func:`.defer`, or similar. However, the :class:`_orm.Load` object
  38. can also be used directly, and in some cases can be useful.
  39. To use :class:`_orm.Load` directly, instantiate it with the target mapped
  40. class as the argument. This style of usage is
  41. useful when dealing with a :class:`_query.Query`
  42. that has multiple entities::
  43. myopt = Load(MyClass).joinedload("widgets")
  44. The above ``myopt`` can now be used with :meth:`_query.Query.options`,
  45. where it
  46. will only take effect for the ``MyClass`` entity::
  47. session.query(MyClass, MyOtherClass).options(myopt)
  48. One case where :class:`_orm.Load`
  49. is useful as public API is when specifying
  50. "wildcard" options that only take effect for a certain class::
  51. session.query(Order).options(Load(Order).lazyload('*'))
  52. Above, all relationships on ``Order`` will be lazy-loaded, but other
  53. attributes on those descendant objects will load using their normal
  54. loader strategy.
  55. .. seealso::
  56. :ref:`deferred_options`
  57. :ref:`deferred_loading_w_multiple`
  58. :ref:`relationship_loader_options`
  59. """
  60. _cache_key_traversal = [
  61. ("path", visitors.ExtendedInternalTraversal.dp_has_cache_key),
  62. ("strategy", visitors.ExtendedInternalTraversal.dp_plain_obj),
  63. ("_of_type", visitors.ExtendedInternalTraversal.dp_multi),
  64. ("_extra_criteria", visitors.InternalTraversal.dp_clauseelement_list),
  65. (
  66. "_context_cache_key",
  67. visitors.ExtendedInternalTraversal.dp_has_cache_key_tuples,
  68. ),
  69. (
  70. "local_opts",
  71. visitors.ExtendedInternalTraversal.dp_string_multi_dict,
  72. ),
  73. ]
  74. def __init__(self, entity):
  75. insp = inspect(entity)
  76. insp._post_inspect
  77. self.path = insp._path_registry
  78. # note that this .context is shared among all descendant
  79. # Load objects
  80. self.context = util.OrderedDict()
  81. self.local_opts = {}
  82. self.is_class_strategy = False
  83. @classmethod
  84. def for_existing_path(cls, path):
  85. load = cls.__new__(cls)
  86. load.path = path
  87. load.context = {}
  88. load.local_opts = {}
  89. load._of_type = None
  90. load._extra_criteria = ()
  91. return load
  92. def _generate_extra_criteria(self, context):
  93. """Apply the current bound parameters in a QueryContext to the
  94. "extra_criteria" stored with this Load object.
  95. Load objects are typically pulled from the cached version of
  96. the statement from a QueryContext. The statement currently being
  97. executed will have new values (and keys) for bound parameters in the
  98. extra criteria which need to be applied by loader strategies when
  99. they handle this criteria for a result set.
  100. """
  101. assert (
  102. self._extra_criteria
  103. ), "this should only be called if _extra_criteria is present"
  104. orig_query = context.compile_state.select_statement
  105. current_query = context.query
  106. # NOTE: while it seems like we should not do the "apply" operation
  107. # here if orig_query is current_query, skipping it in the "optimized"
  108. # case causes the query to be different from a cache key perspective,
  109. # because we are creating a copy of the criteria which is no longer
  110. # the same identity of the _extra_criteria in the loader option
  111. # itself. cache key logic produces a different key for
  112. # (A, copy_of_A) vs. (A, A), because in the latter case it shortens
  113. # the second part of the key to just indicate on identity.
  114. # if orig_query is current_query:
  115. # not cached yet. just do the and_()
  116. # return and_(*self._extra_criteria)
  117. k1 = orig_query._generate_cache_key()
  118. k2 = current_query._generate_cache_key()
  119. return k2._apply_params_to_element(k1, and_(*self._extra_criteria))
  120. @property
  121. def _context_cache_key(self):
  122. serialized = []
  123. if self.context is None:
  124. return []
  125. for (key, loader_path), obj in self.context.items():
  126. if key != "loader":
  127. continue
  128. serialized.append(loader_path + (obj,))
  129. return serialized
  130. def _generate(self):
  131. cloned = super(Load, self)._generate()
  132. cloned.local_opts = {}
  133. return cloned
  134. is_opts_only = False
  135. is_class_strategy = False
  136. strategy = None
  137. propagate_to_loaders = False
  138. _of_type = None
  139. _extra_criteria = ()
  140. def process_compile_state_replaced_entities(
  141. self, compile_state, mapper_entities
  142. ):
  143. if not compile_state.compile_options._enable_eagerloads:
  144. return
  145. # process is being run here so that the options given are validated
  146. # against what the lead entities were, as well as to accommodate
  147. # for the entities having been replaced with equivalents
  148. self._process(
  149. compile_state,
  150. mapper_entities,
  151. not bool(compile_state.current_path),
  152. )
  153. def process_compile_state(self, compile_state):
  154. if not compile_state.compile_options._enable_eagerloads:
  155. return
  156. self._process(
  157. compile_state,
  158. compile_state._lead_mapper_entities,
  159. not bool(compile_state.current_path),
  160. )
  161. def _process(self, compile_state, mapper_entities, raiseerr):
  162. is_refresh = compile_state.compile_options._for_refresh_state
  163. current_path = compile_state.current_path
  164. if current_path:
  165. for (token, start_path), loader in self.context.items():
  166. if is_refresh and not loader.propagate_to_loaders:
  167. continue
  168. chopped_start_path = self._chop_path(start_path, current_path)
  169. if chopped_start_path is not None:
  170. compile_state.attributes[
  171. (token, chopped_start_path)
  172. ] = loader
  173. else:
  174. compile_state.attributes.update(self.context)
  175. def _generate_path(
  176. self,
  177. path,
  178. attr,
  179. for_strategy,
  180. wildcard_key,
  181. raiseerr=True,
  182. polymorphic_entity_context=None,
  183. ):
  184. existing_of_type = self._of_type
  185. self._of_type = None
  186. if raiseerr and not path.has_entity:
  187. if isinstance(path, TokenRegistry):
  188. raise sa_exc.ArgumentError(
  189. "Wildcard token cannot be followed by another entity"
  190. )
  191. else:
  192. raise sa_exc.ArgumentError(
  193. "Mapped attribute '%s' does not "
  194. "refer to a mapped entity" % (path.prop,)
  195. )
  196. if isinstance(attr, util.string_types):
  197. default_token = attr.endswith(_DEFAULT_TOKEN)
  198. attr_str_name = attr
  199. if attr.endswith(_WILDCARD_TOKEN) or default_token:
  200. if default_token:
  201. self.propagate_to_loaders = False
  202. if wildcard_key:
  203. attr = "%s:%s" % (wildcard_key, attr)
  204. # TODO: AliasedInsp inside the path for of_type is not
  205. # working for a with_polymorphic entity because the
  206. # relationship loaders don't render the with_poly into the
  207. # path. See #4469 which will try to improve this
  208. if existing_of_type and not existing_of_type.is_aliased_class:
  209. path = path.parent[existing_of_type]
  210. path = path.token(attr)
  211. self.path = path
  212. return path
  213. if existing_of_type:
  214. ent = inspect(existing_of_type)
  215. else:
  216. ent = path.entity
  217. util.warn_deprecated_20(
  218. "Using strings to indicate column or "
  219. "relationship paths in loader options is deprecated "
  220. "and will be removed in SQLAlchemy 2.0. Please use "
  221. "the class-bound attribute directly."
  222. )
  223. try:
  224. # use getattr on the class to work around
  225. # synonyms, hybrids, etc.
  226. attr = getattr(ent.class_, attr)
  227. except AttributeError as err:
  228. if raiseerr:
  229. util.raise_(
  230. sa_exc.ArgumentError(
  231. 'Can\'t find property named "%s" on '
  232. "%s in this Query." % (attr, ent)
  233. ),
  234. replace_context=err,
  235. )
  236. else:
  237. return None
  238. else:
  239. try:
  240. attr = found_property = attr.property
  241. except AttributeError as ae:
  242. if not isinstance(attr, MapperProperty):
  243. util.raise_(
  244. sa_exc.ArgumentError(
  245. 'Expected attribute "%s" on %s to be a '
  246. "mapped attribute; "
  247. "instead got %s object."
  248. % (attr_str_name, ent, type(attr))
  249. ),
  250. replace_context=ae,
  251. )
  252. else:
  253. raise
  254. path = path[attr]
  255. else:
  256. insp = inspect(attr)
  257. if insp.is_mapper or insp.is_aliased_class:
  258. # TODO: this does not appear to be a valid codepath. "attr"
  259. # would never be a mapper. This block is present in 1.2
  260. # as well however does not seem to be accessed in any tests.
  261. if not orm_util._entity_corresponds_to_use_path_impl(
  262. attr.parent, path[-1]
  263. ):
  264. if raiseerr:
  265. raise sa_exc.ArgumentError(
  266. "Attribute '%s' does not "
  267. "link from element '%s'" % (attr, path.entity)
  268. )
  269. else:
  270. return None
  271. elif insp.is_property:
  272. prop = found_property = attr
  273. path = path[prop]
  274. elif insp.is_attribute:
  275. prop = found_property = attr.property
  276. if not orm_util._entity_corresponds_to_use_path_impl(
  277. attr.parent, path[-1]
  278. ):
  279. if raiseerr:
  280. raise sa_exc.ArgumentError(
  281. 'Attribute "%s" does not '
  282. 'link from element "%s".%s'
  283. % (
  284. attr,
  285. path.entity,
  286. (
  287. " Did you mean to use "
  288. "%s.of_type(%s)?"
  289. % (path[-2], attr.class_.__name__)
  290. if len(path) > 1
  291. and path.entity.is_mapper
  292. and attr.parent.is_aliased_class
  293. else ""
  294. ),
  295. )
  296. )
  297. else:
  298. return None
  299. if attr._extra_criteria:
  300. self._extra_criteria = attr._extra_criteria
  301. if getattr(attr, "_of_type", None):
  302. ac = attr._of_type
  303. ext_info = of_type_info = inspect(ac)
  304. if polymorphic_entity_context is None:
  305. polymorphic_entity_context = self.context
  306. existing = path.entity_path[prop].get(
  307. polymorphic_entity_context, "path_with_polymorphic"
  308. )
  309. if not ext_info.is_aliased_class:
  310. ac = orm_util.with_polymorphic(
  311. ext_info.mapper.base_mapper,
  312. ext_info.mapper,
  313. aliased=True,
  314. _use_mapper_path=True,
  315. _existing_alias=inspect(existing)
  316. if existing is not None
  317. else None,
  318. )
  319. ext_info = inspect(ac)
  320. path.entity_path[prop].set(
  321. polymorphic_entity_context, "path_with_polymorphic", ac
  322. )
  323. path = path[prop][ext_info]
  324. self._of_type = of_type_info
  325. else:
  326. path = path[prop]
  327. if for_strategy is not None:
  328. found_property._get_strategy(for_strategy)
  329. if path.has_entity:
  330. path = path.entity_path
  331. self.path = path
  332. return path
  333. def __str__(self):
  334. return "Load(strategy=%r)" % (self.strategy,)
  335. def _coerce_strat(self, strategy):
  336. if strategy is not None:
  337. strategy = tuple(sorted(strategy.items()))
  338. return strategy
  339. def _apply_to_parent(self, parent, applied, bound):
  340. raise NotImplementedError(
  341. "Only 'unbound' loader options may be used with the "
  342. "Load.options() method"
  343. )
  344. @_generative
  345. def options(self, *opts):
  346. r"""Apply a series of options as sub-options to this
  347. :class:`_orm.Load`
  348. object.
  349. E.g.::
  350. query = session.query(Author)
  351. query = query.options(
  352. joinedload(Author.book).options(
  353. load_only("summary", "excerpt"),
  354. joinedload(Book.citations).options(
  355. joinedload(Citation.author)
  356. )
  357. )
  358. )
  359. :param \*opts: A series of loader option objects (ultimately
  360. :class:`_orm.Load` objects) which should be applied to the path
  361. specified by this :class:`_orm.Load` object.
  362. .. versionadded:: 1.3.6
  363. .. seealso::
  364. :func:`.defaultload`
  365. :ref:`relationship_loader_options`
  366. :ref:`deferred_loading_w_multiple`
  367. """
  368. apply_cache = {}
  369. bound = not isinstance(self, _UnboundLoad)
  370. if bound:
  371. raise NotImplementedError(
  372. "The options() method is currently only supported "
  373. "for 'unbound' loader options"
  374. )
  375. for opt in opts:
  376. opt._apply_to_parent(self, apply_cache, bound)
  377. @_generative
  378. def set_relationship_strategy(
  379. self, attr, strategy, propagate_to_loaders=True
  380. ):
  381. strategy = self._coerce_strat(strategy)
  382. self.propagate_to_loaders = propagate_to_loaders
  383. cloned = self._clone_for_bind_strategy(attr, strategy, "relationship")
  384. self.path = cloned.path
  385. self._of_type = cloned._of_type
  386. self._extra_criteria = cloned._extra_criteria
  387. cloned.is_class_strategy = self.is_class_strategy = False
  388. self.propagate_to_loaders = cloned.propagate_to_loaders
  389. @_generative
  390. def set_column_strategy(self, attrs, strategy, opts=None, opts_only=False):
  391. strategy = self._coerce_strat(strategy)
  392. self.is_class_strategy = False
  393. for attr in attrs:
  394. cloned = self._clone_for_bind_strategy(
  395. attr, strategy, "column", opts_only=opts_only, opts=opts
  396. )
  397. cloned.propagate_to_loaders = True
  398. @_generative
  399. def set_generic_strategy(self, attrs, strategy):
  400. strategy = self._coerce_strat(strategy)
  401. for attr in attrs:
  402. cloned = self._clone_for_bind_strategy(attr, strategy, None)
  403. cloned.propagate_to_loaders = True
  404. @_generative
  405. def set_class_strategy(self, strategy, opts):
  406. strategy = self._coerce_strat(strategy)
  407. cloned = self._clone_for_bind_strategy(None, strategy, None)
  408. cloned.is_class_strategy = True
  409. cloned.propagate_to_loaders = True
  410. cloned.local_opts.update(opts)
  411. def _clone_for_bind_strategy(
  412. self, attr, strategy, wildcard_key, opts_only=False, opts=None
  413. ):
  414. """Create an anonymous clone of the Load/_UnboundLoad that is suitable
  415. to be placed in the context / _to_bind collection of this Load
  416. object. The clone will then lose references to context/_to_bind
  417. in order to not create reference cycles.
  418. """
  419. cloned = self._generate()
  420. cloned._generate_path(self.path, attr, strategy, wildcard_key)
  421. cloned.strategy = strategy
  422. cloned.local_opts = self.local_opts
  423. if opts:
  424. cloned.local_opts.update(opts)
  425. if opts_only:
  426. cloned.is_opts_only = True
  427. if strategy or cloned.is_opts_only:
  428. cloned._set_path_strategy()
  429. return cloned
  430. def _set_for_path(self, context, path, replace=True, merge_opts=False):
  431. if merge_opts or not replace:
  432. existing = path.get(context, "loader")
  433. if existing:
  434. if merge_opts:
  435. existing.local_opts.update(self.local_opts)
  436. existing._extra_criteria += self._extra_criteria
  437. else:
  438. path.set(context, "loader", self)
  439. else:
  440. existing = path.get(context, "loader")
  441. path.set(context, "loader", self)
  442. if existing and existing.is_opts_only:
  443. self.local_opts.update(existing.local_opts)
  444. existing._extra_criteria += self._extra_criteria
  445. def _set_path_strategy(self):
  446. if not self.is_class_strategy and self.path.has_entity:
  447. effective_path = self.path.parent
  448. else:
  449. effective_path = self.path
  450. if effective_path.is_token:
  451. for path in effective_path.generate_for_superclasses():
  452. self._set_for_path(
  453. self.context,
  454. path,
  455. replace=True,
  456. merge_opts=self.is_opts_only,
  457. )
  458. else:
  459. self._set_for_path(
  460. self.context,
  461. effective_path,
  462. replace=True,
  463. merge_opts=self.is_opts_only,
  464. )
  465. # remove cycles; _set_path_strategy is always invoked on an
  466. # anonymous clone of the Load / UnboundLoad object since #5056
  467. self.context = None
  468. def __getstate__(self):
  469. d = self.__dict__.copy()
  470. # can't pickle this right now; warning is raised by strategies
  471. d["_extra_criteria"] = ()
  472. if d["context"] is not None:
  473. d["context"] = PathRegistry.serialize_context_dict(
  474. d["context"], ("loader",)
  475. )
  476. d["path"] = self.path.serialize()
  477. return d
  478. def __setstate__(self, state):
  479. self.__dict__.update(state)
  480. self.path = PathRegistry.deserialize(self.path)
  481. if self.context is not None:
  482. self.context = PathRegistry.deserialize_context_dict(self.context)
  483. def _chop_path(self, to_chop, path):
  484. i = -1
  485. for i, (c_token, p_token) in enumerate(zip(to_chop, path.path)):
  486. if isinstance(c_token, util.string_types):
  487. # TODO: this is approximated from the _UnboundLoad
  488. # version and probably has issues, not fully covered.
  489. if i == 0 and c_token.endswith(":" + _DEFAULT_TOKEN):
  490. return to_chop
  491. elif (
  492. c_token != "relationship:%s" % (_WILDCARD_TOKEN,)
  493. and c_token != p_token.key
  494. ):
  495. return None
  496. if c_token is p_token:
  497. continue
  498. elif (
  499. isinstance(c_token, InspectionAttr)
  500. and c_token.is_mapper
  501. and p_token.is_mapper
  502. and c_token.isa(p_token)
  503. ):
  504. continue
  505. else:
  506. return None
  507. return to_chop[i + 1 :]
  508. class _UnboundLoad(Load):
  509. """Represent a loader option that isn't tied to a root entity.
  510. The loader option will produce an entity-linked :class:`_orm.Load`
  511. object when it is passed :meth:`_query.Query.options`.
  512. This provides compatibility with the traditional system
  513. of freestanding options, e.g. ``joinedload('x.y.z')``.
  514. """
  515. def __init__(self):
  516. self.path = ()
  517. self._to_bind = []
  518. self.local_opts = {}
  519. self._extra_criteria = ()
  520. _cache_key_traversal = [
  521. ("path", visitors.ExtendedInternalTraversal.dp_multi_list),
  522. ("strategy", visitors.ExtendedInternalTraversal.dp_plain_obj),
  523. ("_to_bind", visitors.ExtendedInternalTraversal.dp_has_cache_key_list),
  524. ("_extra_criteria", visitors.InternalTraversal.dp_clauseelement_list),
  525. (
  526. "local_opts",
  527. visitors.ExtendedInternalTraversal.dp_string_multi_dict,
  528. ),
  529. ]
  530. _is_chain_link = False
  531. def _set_path_strategy(self):
  532. self._to_bind.append(self)
  533. # remove cycles; _set_path_strategy is always invoked on an
  534. # anonymous clone of the Load / UnboundLoad object since #5056
  535. self._to_bind = None
  536. def _apply_to_parent(self, parent, applied, bound, to_bind=None):
  537. if self in applied:
  538. return applied[self]
  539. if to_bind is None:
  540. to_bind = self._to_bind
  541. cloned = self._generate()
  542. applied[self] = cloned
  543. cloned.strategy = self.strategy
  544. if self.path:
  545. attr = self.path[-1]
  546. if isinstance(attr, util.string_types) and attr.endswith(
  547. _DEFAULT_TOKEN
  548. ):
  549. attr = attr.split(":")[0] + ":" + _WILDCARD_TOKEN
  550. cloned._generate_path(
  551. parent.path + self.path[0:-1], attr, self.strategy, None
  552. )
  553. # these assertions can go away once the "sub options" API is
  554. # mature
  555. assert cloned.propagate_to_loaders == self.propagate_to_loaders
  556. assert cloned.is_class_strategy == self.is_class_strategy
  557. assert cloned.is_opts_only == self.is_opts_only
  558. new_to_bind = {
  559. elem._apply_to_parent(parent, applied, bound, to_bind)
  560. for elem in to_bind
  561. }
  562. cloned._to_bind = parent._to_bind
  563. cloned._to_bind.extend(new_to_bind)
  564. cloned.local_opts.update(self.local_opts)
  565. return cloned
  566. def _generate_path(self, path, attr, for_strategy, wildcard_key):
  567. if (
  568. wildcard_key
  569. and isinstance(attr, util.string_types)
  570. and attr in (_WILDCARD_TOKEN, _DEFAULT_TOKEN)
  571. ):
  572. if attr == _DEFAULT_TOKEN:
  573. self.propagate_to_loaders = False
  574. attr = "%s:%s" % (wildcard_key, attr)
  575. if path and _is_mapped_class(path[-1]) and not self.is_class_strategy:
  576. path = path[0:-1]
  577. if attr:
  578. path = path + (attr,)
  579. self.path = path
  580. self._extra_criteria = getattr(attr, "_extra_criteria", ())
  581. return path
  582. def __getstate__(self):
  583. d = self.__dict__.copy()
  584. # can't pickle this right now; warning is raised by strategies
  585. d["_extra_criteria"] = ()
  586. d["path"] = self._serialize_path(self.path, filter_aliased_class=True)
  587. return d
  588. def __setstate__(self, state):
  589. ret = []
  590. for key in state["path"]:
  591. if isinstance(key, tuple):
  592. if len(key) == 2:
  593. # support legacy
  594. cls, propkey = key
  595. of_type = None
  596. else:
  597. cls, propkey, of_type = key
  598. prop = getattr(cls, propkey)
  599. if of_type:
  600. prop = prop.of_type(of_type)
  601. ret.append(prop)
  602. else:
  603. ret.append(key)
  604. state["path"] = tuple(ret)
  605. self.__dict__ = state
  606. def _process(self, compile_state, mapper_entities, raiseerr):
  607. dedupes = compile_state.attributes["_unbound_load_dedupes"]
  608. is_refresh = compile_state.compile_options._for_refresh_state
  609. for val in self._to_bind:
  610. if val not in dedupes:
  611. dedupes.add(val)
  612. if is_refresh and not val.propagate_to_loaders:
  613. continue
  614. val._bind_loader(
  615. [ent.entity_zero for ent in mapper_entities],
  616. compile_state.current_path,
  617. compile_state.attributes,
  618. raiseerr,
  619. )
  620. @classmethod
  621. def _from_keys(cls, meth, keys, chained, kw):
  622. opt = _UnboundLoad()
  623. def _split_key(key):
  624. if isinstance(key, util.string_types):
  625. # coerce fooload('*') into "default loader strategy"
  626. if key == _WILDCARD_TOKEN:
  627. return (_DEFAULT_TOKEN,)
  628. # coerce fooload(".*") into "wildcard on default entity"
  629. elif key.startswith("." + _WILDCARD_TOKEN):
  630. key = key[1:]
  631. return key.split(".")
  632. else:
  633. return (key,)
  634. all_tokens = [token for key in keys for token in _split_key(key)]
  635. for token in all_tokens[0:-1]:
  636. # set _is_chain_link first so that clones of the
  637. # object also inherit this flag
  638. opt._is_chain_link = True
  639. if chained:
  640. opt = meth(opt, token, **kw)
  641. else:
  642. opt = opt.defaultload(token)
  643. opt = meth(opt, all_tokens[-1], **kw)
  644. opt._is_chain_link = False
  645. return opt
  646. def _chop_path(self, to_chop, path):
  647. i = -1
  648. for i, (c_token, (p_entity, p_prop)) in enumerate(
  649. zip(to_chop, path.pairs())
  650. ):
  651. if isinstance(c_token, util.string_types):
  652. if i == 0 and c_token.endswith(":" + _DEFAULT_TOKEN):
  653. return to_chop
  654. elif (
  655. c_token != "relationship:%s" % (_WILDCARD_TOKEN,)
  656. and c_token != p_prop.key
  657. ):
  658. return None
  659. elif isinstance(c_token, PropComparator):
  660. if c_token.property is not p_prop or (
  661. c_token._parententity is not p_entity
  662. and (
  663. not c_token._parententity.is_mapper
  664. or not c_token._parententity.isa(p_entity)
  665. )
  666. ):
  667. return None
  668. else:
  669. i += 1
  670. return to_chop[i:]
  671. def _serialize_path(self, path, filter_aliased_class=False):
  672. ret = []
  673. for token in path:
  674. if isinstance(token, QueryableAttribute):
  675. if (
  676. filter_aliased_class
  677. and token._of_type
  678. and inspect(token._of_type).is_aliased_class
  679. ):
  680. ret.append((token._parentmapper.class_, token.key, None))
  681. else:
  682. ret.append(
  683. (
  684. token._parentmapper.class_,
  685. token.key,
  686. token._of_type.entity if token._of_type else None,
  687. )
  688. )
  689. elif isinstance(token, PropComparator):
  690. ret.append((token._parentmapper.class_, token.key, None))
  691. else:
  692. ret.append(token)
  693. return ret
  694. def _bind_loader(self, entities, current_path, context, raiseerr):
  695. """Convert from an _UnboundLoad() object into a Load() object.
  696. The _UnboundLoad() uses an informal "path" and does not necessarily
  697. refer to a lead entity as it may use string tokens. The Load()
  698. OTOH refers to a complete path. This method reconciles from a
  699. given Query into a Load.
  700. Example::
  701. query = session.query(User).options(
  702. joinedload("orders").joinedload("items"))
  703. The above options will be an _UnboundLoad object along the lines
  704. of (note this is not the exact API of _UnboundLoad)::
  705. _UnboundLoad(
  706. _to_bind=[
  707. _UnboundLoad(["orders"], {"lazy": "joined"}),
  708. _UnboundLoad(["orders", "items"], {"lazy": "joined"}),
  709. ]
  710. )
  711. After this method, we get something more like this (again this is
  712. not exact API)::
  713. Load(
  714. User,
  715. (User, User.orders.property))
  716. Load(
  717. User,
  718. (User, User.orders.property, Order, Order.items.property))
  719. """
  720. start_path = self.path
  721. if self.is_class_strategy and current_path:
  722. start_path += (entities[0],)
  723. # _current_path implies we're in a
  724. # secondary load with an existing path
  725. if current_path:
  726. start_path = self._chop_path(start_path, current_path)
  727. if not start_path:
  728. return None
  729. # look at the first token and try to locate within the Query
  730. # what entity we are referring towards.
  731. token = start_path[0]
  732. if isinstance(token, util.string_types):
  733. entity = self._find_entity_basestring(entities, token, raiseerr)
  734. elif isinstance(token, PropComparator):
  735. prop = token.property
  736. entity = self._find_entity_prop_comparator(
  737. entities, prop, token._parententity, raiseerr
  738. )
  739. elif self.is_class_strategy and _is_mapped_class(token):
  740. entity = inspect(token)
  741. if entity not in entities:
  742. entity = None
  743. else:
  744. raise sa_exc.ArgumentError(
  745. "mapper option expects " "string key or list of attributes"
  746. )
  747. if not entity:
  748. return
  749. path_element = entity
  750. # transfer our entity-less state into a Load() object
  751. # with a real entity path. Start with the lead entity
  752. # we just located, then go through the rest of our path
  753. # tokens and populate into the Load().
  754. loader = Load(path_element)
  755. if context is None:
  756. context = loader.context
  757. loader.strategy = self.strategy
  758. loader.is_opts_only = self.is_opts_only
  759. loader.is_class_strategy = self.is_class_strategy
  760. path = loader.path
  761. if not loader.is_class_strategy:
  762. for idx, token in enumerate(start_path):
  763. if not loader._generate_path(
  764. loader.path,
  765. token,
  766. self.strategy if idx == len(start_path) - 1 else None,
  767. None,
  768. raiseerr,
  769. polymorphic_entity_context=context,
  770. ):
  771. return
  772. loader.local_opts.update(self.local_opts)
  773. if not loader.is_class_strategy and loader.path.has_entity:
  774. effective_path = loader.path.parent
  775. else:
  776. effective_path = loader.path
  777. # prioritize "first class" options over those
  778. # that were "links in the chain", e.g. "x" and "y" in
  779. # someload("x.y.z") versus someload("x") / someload("x.y")
  780. if effective_path.is_token:
  781. for path in effective_path.generate_for_superclasses():
  782. loader._set_for_path(
  783. context,
  784. path,
  785. replace=not self._is_chain_link,
  786. merge_opts=self.is_opts_only,
  787. )
  788. else:
  789. loader._set_for_path(
  790. context,
  791. effective_path,
  792. replace=not self._is_chain_link,
  793. merge_opts=self.is_opts_only,
  794. )
  795. return loader
  796. def _find_entity_prop_comparator(self, entities, prop, mapper, raiseerr):
  797. if _is_aliased_class(mapper):
  798. searchfor = mapper
  799. else:
  800. searchfor = _class_to_mapper(mapper)
  801. for ent in entities:
  802. if orm_util._entity_corresponds_to(ent, searchfor):
  803. return ent
  804. else:
  805. if raiseerr:
  806. if not list(entities):
  807. raise sa_exc.ArgumentError(
  808. "Query has only expression-based entities, "
  809. 'which do not apply to %s "%s"'
  810. % (util.clsname_as_plain_name(type(prop)), prop)
  811. )
  812. else:
  813. raise sa_exc.ArgumentError(
  814. 'Mapped attribute "%s" does not apply to any of the '
  815. "root entities in this query, e.g. %s. Please "
  816. "specify the full path "
  817. "from one of the root entities to the target "
  818. "attribute. "
  819. % (prop, ", ".join(str(x) for x in entities))
  820. )
  821. else:
  822. return None
  823. def _find_entity_basestring(self, entities, token, raiseerr):
  824. if token.endswith(":" + _WILDCARD_TOKEN):
  825. if len(list(entities)) != 1:
  826. if raiseerr:
  827. raise sa_exc.ArgumentError(
  828. "Can't apply wildcard ('*') or load_only() "
  829. "loader option to multiple entities %s. Specify "
  830. "loader options for each entity individually, such "
  831. "as %s."
  832. % (
  833. ", ".join(str(ent) for ent in entities),
  834. ", ".join(
  835. "Load(%s).some_option('*')" % ent
  836. for ent in entities
  837. ),
  838. )
  839. )
  840. elif token.endswith(_DEFAULT_TOKEN):
  841. raiseerr = False
  842. for ent in entities:
  843. # return only the first _MapperEntity when searching
  844. # based on string prop name. Ideally object
  845. # attributes are used to specify more exactly.
  846. return ent
  847. else:
  848. if raiseerr:
  849. raise sa_exc.ArgumentError(
  850. "Query has only expression-based entities - "
  851. 'can\'t find property named "%s".' % (token,)
  852. )
  853. else:
  854. return None
  855. class loader_option(object):
  856. def __init__(self):
  857. pass
  858. def __call__(self, fn):
  859. self.name = name = fn.__name__
  860. self.fn = fn
  861. if hasattr(Load, name):
  862. raise TypeError("Load class already has a %s method." % (name))
  863. setattr(Load, name, fn)
  864. return self
  865. def _add_unbound_fn(self, fn):
  866. self._unbound_fn = fn
  867. fn_doc = self.fn.__doc__
  868. self.fn.__doc__ = """Produce a new :class:`_orm.Load` object with the
  869. :func:`_orm.%(name)s` option applied.
  870. See :func:`_orm.%(name)s` for usage examples.
  871. """ % {
  872. "name": self.name
  873. }
  874. fn.__doc__ = fn_doc
  875. return self
  876. def _add_unbound_all_fn(self, fn):
  877. fn.__doc__ = """Produce a standalone "all" option for
  878. :func:`_orm.%(name)s`.
  879. .. deprecated:: 0.9
  880. The :func:`_orm.%(name)s_all` function is deprecated, and will be removed
  881. in a future release. Please use method chaining with
  882. :func:`_orm.%(name)s` instead, as in::
  883. session.query(MyClass).options(
  884. %(name)s("someattribute").%(name)s("anotherattribute")
  885. )
  886. """ % {
  887. "name": self.name
  888. }
  889. fn = util.deprecated(
  890. # This is used by `baked_lazyload_all` was only deprecated in
  891. # version 1.2 so this must stick around until that is removed
  892. "0.9",
  893. "The :func:`.%(name)s_all` function is deprecated, and will be "
  894. "removed in a future release. Please use method chaining with "
  895. ":func:`.%(name)s` instead" % {"name": self.name},
  896. add_deprecation_to_docstring=False,
  897. )(fn)
  898. self._unbound_all_fn = fn
  899. return self
  900. @loader_option()
  901. def contains_eager(loadopt, attr, alias=None):
  902. r"""Indicate that the given attribute should be eagerly loaded from
  903. columns stated manually in the query.
  904. This function is part of the :class:`_orm.Load` interface and supports
  905. both method-chained and standalone operation.
  906. The option is used in conjunction with an explicit join that loads
  907. the desired rows, i.e.::
  908. sess.query(Order).\
  909. join(Order.user).\
  910. options(contains_eager(Order.user))
  911. The above query would join from the ``Order`` entity to its related
  912. ``User`` entity, and the returned ``Order`` objects would have the
  913. ``Order.user`` attribute pre-populated.
  914. It may also be used for customizing the entries in an eagerly loaded
  915. collection; queries will normally want to use the
  916. :meth:`_query.Query.populate_existing` method assuming the primary
  917. collection of parent objects may already have been loaded::
  918. sess.query(User).\
  919. join(User.addresses).\
  920. filter(Address.email_address.like('%@aol.com')).\
  921. options(contains_eager(User.addresses)).\
  922. populate_existing()
  923. See the section :ref:`contains_eager` for complete usage details.
  924. .. seealso::
  925. :ref:`loading_toplevel`
  926. :ref:`contains_eager`
  927. """
  928. if alias is not None:
  929. if not isinstance(alias, str):
  930. info = inspect(alias)
  931. alias = info.selectable
  932. else:
  933. util.warn_deprecated(
  934. "Passing a string name for the 'alias' argument to "
  935. "'contains_eager()` is deprecated, and will not work in a "
  936. "future release. Please use a sqlalchemy.alias() or "
  937. "sqlalchemy.orm.aliased() construct.",
  938. version="1.4",
  939. )
  940. elif getattr(attr, "_of_type", None):
  941. ot = inspect(attr._of_type)
  942. alias = ot.selectable
  943. cloned = loadopt.set_relationship_strategy(
  944. attr, {"lazy": "joined"}, propagate_to_loaders=False
  945. )
  946. cloned.local_opts["eager_from_alias"] = alias
  947. return cloned
  948. @contains_eager._add_unbound_fn
  949. def contains_eager(*keys, **kw):
  950. return _UnboundLoad()._from_keys(
  951. _UnboundLoad.contains_eager, keys, True, kw
  952. )
  953. @loader_option()
  954. def load_only(loadopt, *attrs):
  955. """Indicate that for a particular entity, only the given list
  956. of column-based attribute names should be loaded; all others will be
  957. deferred.
  958. This function is part of the :class:`_orm.Load` interface and supports
  959. both method-chained and standalone operation.
  960. Example - given a class ``User``, load only the ``name`` and ``fullname``
  961. attributes::
  962. session.query(User).options(load_only("name", "fullname"))
  963. Example - given a relationship ``User.addresses -> Address``, specify
  964. subquery loading for the ``User.addresses`` collection, but on each
  965. ``Address`` object load only the ``email_address`` attribute::
  966. session.query(User).options(
  967. subqueryload("addresses").load_only("email_address")
  968. )
  969. For a :class:`_query.Query` that has multiple entities,
  970. the lead entity can be
  971. specifically referred to using the :class:`_orm.Load` constructor::
  972. session.query(User, Address).join(User.addresses).options(
  973. Load(User).load_only("name", "fullname"),
  974. Load(Address).load_only("email_address")
  975. )
  976. .. note:: This method will still load a :class:`_schema.Column` even
  977. if the column property is defined with ``deferred=True``
  978. for the :func:`.column_property` function.
  979. .. versionadded:: 0.9.0
  980. """
  981. cloned = loadopt.set_column_strategy(
  982. attrs, {"deferred": False, "instrument": True}
  983. )
  984. cloned.set_column_strategy(
  985. "*", {"deferred": True, "instrument": True}, {"undefer_pks": True}
  986. )
  987. return cloned
  988. @load_only._add_unbound_fn
  989. def load_only(*attrs):
  990. return _UnboundLoad().load_only(*attrs)
  991. @loader_option()
  992. def joinedload(loadopt, attr, innerjoin=None):
  993. """Indicate that the given attribute should be loaded using joined
  994. eager loading.
  995. This function is part of the :class:`_orm.Load` interface and supports
  996. both method-chained and standalone operation.
  997. examples::
  998. # joined-load the "orders" collection on "User"
  999. query(User).options(joinedload(User.orders))
  1000. # joined-load Order.items and then Item.keywords
  1001. query(Order).options(
  1002. joinedload(Order.items).joinedload(Item.keywords))
  1003. # lazily load Order.items, but when Items are loaded,
  1004. # joined-load the keywords collection
  1005. query(Order).options(
  1006. lazyload(Order.items).joinedload(Item.keywords))
  1007. :param innerjoin: if ``True``, indicates that the joined eager load should
  1008. use an inner join instead of the default of left outer join::
  1009. query(Order).options(joinedload(Order.user, innerjoin=True))
  1010. In order to chain multiple eager joins together where some may be
  1011. OUTER and others INNER, right-nested joins are used to link them::
  1012. query(A).options(
  1013. joinedload(A.bs, innerjoin=False).
  1014. joinedload(B.cs, innerjoin=True)
  1015. )
  1016. The above query, linking A.bs via "outer" join and B.cs via "inner" join
  1017. would render the joins as "a LEFT OUTER JOIN (b JOIN c)". When using
  1018. older versions of SQLite (< 3.7.16), this form of JOIN is translated to
  1019. use full subqueries as this syntax is otherwise not directly supported.
  1020. The ``innerjoin`` flag can also be stated with the term ``"unnested"``.
  1021. This indicates that an INNER JOIN should be used, *unless* the join
  1022. is linked to a LEFT OUTER JOIN to the left, in which case it
  1023. will render as LEFT OUTER JOIN. For example, supposing ``A.bs``
  1024. is an outerjoin::
  1025. query(A).options(
  1026. joinedload(A.bs).
  1027. joinedload(B.cs, innerjoin="unnested")
  1028. )
  1029. The above join will render as "a LEFT OUTER JOIN b LEFT OUTER JOIN c",
  1030. rather than as "a LEFT OUTER JOIN (b JOIN c)".
  1031. .. note:: The "unnested" flag does **not** affect the JOIN rendered
  1032. from a many-to-many association table, e.g. a table configured
  1033. as :paramref:`_orm.relationship.secondary`, to the target table; for
  1034. correctness of results, these joins are always INNER and are
  1035. therefore right-nested if linked to an OUTER join.
  1036. .. versionchanged:: 1.0.0 ``innerjoin=True`` now implies
  1037. ``innerjoin="nested"``, whereas in 0.9 it implied
  1038. ``innerjoin="unnested"``. In order to achieve the pre-1.0 "unnested"
  1039. inner join behavior, use the value ``innerjoin="unnested"``.
  1040. See :ref:`migration_3008`.
  1041. .. note::
  1042. The joins produced by :func:`_orm.joinedload` are **anonymously
  1043. aliased**. The criteria by which the join proceeds cannot be
  1044. modified, nor can the :class:`_query.Query`
  1045. refer to these joins in any way,
  1046. including ordering. See :ref:`zen_of_eager_loading` for further
  1047. detail.
  1048. To produce a specific SQL JOIN which is explicitly available, use
  1049. :meth:`_query.Query.join`.
  1050. To combine explicit JOINs with eager loading
  1051. of collections, use :func:`_orm.contains_eager`; see
  1052. :ref:`contains_eager`.
  1053. .. seealso::
  1054. :ref:`loading_toplevel`
  1055. :ref:`joined_eager_loading`
  1056. """
  1057. loader = loadopt.set_relationship_strategy(attr, {"lazy": "joined"})
  1058. if innerjoin is not None:
  1059. loader.local_opts["innerjoin"] = innerjoin
  1060. return loader
  1061. @joinedload._add_unbound_fn
  1062. def joinedload(*keys, **kw):
  1063. return _UnboundLoad._from_keys(_UnboundLoad.joinedload, keys, False, kw)
  1064. @loader_option()
  1065. def subqueryload(loadopt, attr):
  1066. """Indicate that the given attribute should be loaded using
  1067. subquery eager loading.
  1068. This function is part of the :class:`_orm.Load` interface and supports
  1069. both method-chained and standalone operation.
  1070. examples::
  1071. # subquery-load the "orders" collection on "User"
  1072. query(User).options(subqueryload(User.orders))
  1073. # subquery-load Order.items and then Item.keywords
  1074. query(Order).options(
  1075. subqueryload(Order.items).subqueryload(Item.keywords))
  1076. # lazily load Order.items, but when Items are loaded,
  1077. # subquery-load the keywords collection
  1078. query(Order).options(
  1079. lazyload(Order.items).subqueryload(Item.keywords))
  1080. .. seealso::
  1081. :ref:`loading_toplevel`
  1082. :ref:`subquery_eager_loading`
  1083. """
  1084. return loadopt.set_relationship_strategy(attr, {"lazy": "subquery"})
  1085. @subqueryload._add_unbound_fn
  1086. def subqueryload(*keys):
  1087. return _UnboundLoad._from_keys(_UnboundLoad.subqueryload, keys, False, {})
  1088. @loader_option()
  1089. def selectinload(loadopt, attr):
  1090. """Indicate that the given attribute should be loaded using
  1091. SELECT IN eager loading.
  1092. This function is part of the :class:`_orm.Load` interface and supports
  1093. both method-chained and standalone operation.
  1094. examples::
  1095. # selectin-load the "orders" collection on "User"
  1096. query(User).options(selectinload(User.orders))
  1097. # selectin-load Order.items and then Item.keywords
  1098. query(Order).options(
  1099. selectinload(Order.items).selectinload(Item.keywords))
  1100. # lazily load Order.items, but when Items are loaded,
  1101. # selectin-load the keywords collection
  1102. query(Order).options(
  1103. lazyload(Order.items).selectinload(Item.keywords))
  1104. .. versionadded:: 1.2
  1105. .. seealso::
  1106. :ref:`loading_toplevel`
  1107. :ref:`selectin_eager_loading`
  1108. """
  1109. return loadopt.set_relationship_strategy(attr, {"lazy": "selectin"})
  1110. @selectinload._add_unbound_fn
  1111. def selectinload(*keys):
  1112. return _UnboundLoad._from_keys(_UnboundLoad.selectinload, keys, False, {})
  1113. @loader_option()
  1114. def lazyload(loadopt, attr):
  1115. """Indicate that the given attribute should be loaded using "lazy"
  1116. loading.
  1117. This function is part of the :class:`_orm.Load` interface and supports
  1118. both method-chained and standalone operation.
  1119. .. seealso::
  1120. :ref:`loading_toplevel`
  1121. :ref:`lazy_loading`
  1122. """
  1123. return loadopt.set_relationship_strategy(attr, {"lazy": "select"})
  1124. @lazyload._add_unbound_fn
  1125. def lazyload(*keys):
  1126. return _UnboundLoad._from_keys(_UnboundLoad.lazyload, keys, False, {})
  1127. @loader_option()
  1128. def immediateload(loadopt, attr):
  1129. """Indicate that the given attribute should be loaded using
  1130. an immediate load with a per-attribute SELECT statement.
  1131. The load is achieved using the "lazyloader" strategy and does not
  1132. fire off any additional eager loaders.
  1133. The :func:`.immediateload` option is superseded in general
  1134. by the :func:`.selectinload` option, which performs the same task
  1135. more efficiently by emitting a SELECT for all loaded objects.
  1136. This function is part of the :class:`_orm.Load` interface and supports
  1137. both method-chained and standalone operation.
  1138. .. seealso::
  1139. :ref:`loading_toplevel`
  1140. :ref:`selectin_eager_loading`
  1141. """
  1142. loader = loadopt.set_relationship_strategy(attr, {"lazy": "immediate"})
  1143. return loader
  1144. @immediateload._add_unbound_fn
  1145. def immediateload(*keys):
  1146. return _UnboundLoad._from_keys(_UnboundLoad.immediateload, keys, False, {})
  1147. @loader_option()
  1148. def noload(loadopt, attr):
  1149. """Indicate that the given relationship attribute should remain unloaded.
  1150. The relationship attribute will return ``None`` when accessed without
  1151. producing any loading effect.
  1152. This function is part of the :class:`_orm.Load` interface and supports
  1153. both method-chained and standalone operation.
  1154. :func:`_orm.noload` applies to :func:`_orm.relationship` attributes; for
  1155. column-based attributes, see :func:`_orm.defer`.
  1156. .. note:: Setting this loading strategy as the default strategy
  1157. for a relationship using the :paramref:`.orm.relationship.lazy`
  1158. parameter may cause issues with flushes, such if a delete operation
  1159. needs to load related objects and instead ``None`` was returned.
  1160. .. seealso::
  1161. :ref:`loading_toplevel`
  1162. """
  1163. return loadopt.set_relationship_strategy(attr, {"lazy": "noload"})
  1164. @noload._add_unbound_fn
  1165. def noload(*keys):
  1166. return _UnboundLoad._from_keys(_UnboundLoad.noload, keys, False, {})
  1167. @loader_option()
  1168. def raiseload(loadopt, attr, sql_only=False):
  1169. """Indicate that the given attribute should raise an error if accessed.
  1170. A relationship attribute configured with :func:`_orm.raiseload` will
  1171. raise an :exc:`~sqlalchemy.exc.InvalidRequestError` upon access. The
  1172. typical way this is useful is when an application is attempting to ensure
  1173. that all relationship attributes that are accessed in a particular context
  1174. would have been already loaded via eager loading. Instead of having
  1175. to read through SQL logs to ensure lazy loads aren't occurring, this
  1176. strategy will cause them to raise immediately.
  1177. :func:`_orm.raiseload` applies to :func:`_orm.relationship`
  1178. attributes only.
  1179. In order to apply raise-on-SQL behavior to a column-based attribute,
  1180. use the :paramref:`.orm.defer.raiseload` parameter on the :func:`.defer`
  1181. loader option.
  1182. :param sql_only: if True, raise only if the lazy load would emit SQL, but
  1183. not if it is only checking the identity map, or determining that the
  1184. related value should just be None due to missing keys. When False, the
  1185. strategy will raise for all varieties of relationship loading.
  1186. This function is part of the :class:`_orm.Load` interface and supports
  1187. both method-chained and standalone operation.
  1188. .. versionadded:: 1.1
  1189. .. seealso::
  1190. :ref:`loading_toplevel`
  1191. :ref:`prevent_lazy_with_raiseload`
  1192. :ref:`deferred_raiseload`
  1193. """
  1194. return loadopt.set_relationship_strategy(
  1195. attr, {"lazy": "raise_on_sql" if sql_only else "raise"}
  1196. )
  1197. @raiseload._add_unbound_fn
  1198. def raiseload(*keys, **kw):
  1199. return _UnboundLoad._from_keys(_UnboundLoad.raiseload, keys, False, kw)
  1200. @loader_option()
  1201. def defaultload(loadopt, attr):
  1202. """Indicate an attribute should load using its default loader style.
  1203. This method is used to link to other loader options further into
  1204. a chain of attributes without altering the loader style of the links
  1205. along the chain. For example, to set joined eager loading for an
  1206. element of an element::
  1207. session.query(MyClass).options(
  1208. defaultload(MyClass.someattribute).
  1209. joinedload(MyOtherClass.someotherattribute)
  1210. )
  1211. :func:`.defaultload` is also useful for setting column-level options
  1212. on a related class, namely that of :func:`.defer` and :func:`.undefer`::
  1213. session.query(MyClass).options(
  1214. defaultload(MyClass.someattribute).
  1215. defer("some_column").
  1216. undefer("some_other_column")
  1217. )
  1218. .. seealso::
  1219. :meth:`_orm.Load.options` - allows for complex hierarchical
  1220. loader option structures with less verbosity than with individual
  1221. :func:`.defaultload` directives.
  1222. :ref:`relationship_loader_options`
  1223. :ref:`deferred_loading_w_multiple`
  1224. """
  1225. return loadopt.set_relationship_strategy(attr, None)
  1226. @defaultload._add_unbound_fn
  1227. def defaultload(*keys):
  1228. return _UnboundLoad._from_keys(_UnboundLoad.defaultload, keys, False, {})
  1229. @loader_option()
  1230. def defer(loadopt, key, raiseload=False):
  1231. r"""Indicate that the given column-oriented attribute should be deferred,
  1232. e.g. not loaded until accessed.
  1233. This function is part of the :class:`_orm.Load` interface and supports
  1234. both method-chained and standalone operation.
  1235. e.g.::
  1236. from sqlalchemy.orm import defer
  1237. session.query(MyClass).options(
  1238. defer("attribute_one"),
  1239. defer("attribute_two"))
  1240. session.query(MyClass).options(
  1241. defer(MyClass.attribute_one),
  1242. defer(MyClass.attribute_two))
  1243. To specify a deferred load of an attribute on a related class,
  1244. the path can be specified one token at a time, specifying the loading
  1245. style for each link along the chain. To leave the loading style
  1246. for a link unchanged, use :func:`_orm.defaultload`::
  1247. session.query(MyClass).options(defaultload("someattr").defer("some_column"))
  1248. A :class:`_orm.Load` object that is present on a certain path can have
  1249. :meth:`_orm.Load.defer` called multiple times,
  1250. each will operate on the same
  1251. parent entity::
  1252. session.query(MyClass).options(
  1253. defaultload("someattr").
  1254. defer("some_column").
  1255. defer("some_other_column").
  1256. defer("another_column")
  1257. )
  1258. :param key: Attribute to be deferred.
  1259. :param raiseload: raise :class:`.InvalidRequestError` if the column
  1260. value is to be loaded from emitting SQL. Used to prevent unwanted
  1261. SQL from being emitted.
  1262. .. versionadded:: 1.4
  1263. .. seealso::
  1264. :ref:`deferred_raiseload`
  1265. :param \*addl_attrs: This option supports the old 0.8 style
  1266. of specifying a path as a series of attributes, which is now superseded
  1267. by the method-chained style.
  1268. .. deprecated:: 0.9 The \*addl_attrs on :func:`_orm.defer` is
  1269. deprecated and will be removed in a future release. Please
  1270. use method chaining in conjunction with defaultload() to
  1271. indicate a path.
  1272. .. seealso::
  1273. :ref:`deferred`
  1274. :func:`_orm.undefer`
  1275. """
  1276. strategy = {"deferred": True, "instrument": True}
  1277. if raiseload:
  1278. strategy["raiseload"] = True
  1279. return loadopt.set_column_strategy((key,), strategy)
  1280. @defer._add_unbound_fn
  1281. def defer(key, *addl_attrs, **kw):
  1282. if addl_attrs:
  1283. util.warn_deprecated(
  1284. "The *addl_attrs on orm.defer is deprecated. Please use "
  1285. "method chaining in conjunction with defaultload() to "
  1286. "indicate a path.",
  1287. version="1.3",
  1288. )
  1289. return _UnboundLoad._from_keys(
  1290. _UnboundLoad.defer, (key,) + addl_attrs, False, kw
  1291. )
  1292. @loader_option()
  1293. def undefer(loadopt, key):
  1294. r"""Indicate that the given column-oriented attribute should be undeferred,
  1295. e.g. specified within the SELECT statement of the entity as a whole.
  1296. The column being undeferred is typically set up on the mapping as a
  1297. :func:`.deferred` attribute.
  1298. This function is part of the :class:`_orm.Load` interface and supports
  1299. both method-chained and standalone operation.
  1300. Examples::
  1301. # undefer two columns
  1302. session.query(MyClass).options(undefer("col1"), undefer("col2"))
  1303. # undefer all columns specific to a single class using Load + *
  1304. session.query(MyClass, MyOtherClass).options(
  1305. Load(MyClass).undefer("*"))
  1306. # undefer a column on a related object
  1307. session.query(MyClass).options(
  1308. defaultload(MyClass.items).undefer('text'))
  1309. :param key: Attribute to be undeferred.
  1310. :param \*addl_attrs: This option supports the old 0.8 style
  1311. of specifying a path as a series of attributes, which is now superseded
  1312. by the method-chained style.
  1313. .. deprecated:: 0.9 The \*addl_attrs on :func:`_orm.undefer` is
  1314. deprecated and will be removed in a future release. Please
  1315. use method chaining in conjunction with defaultload() to
  1316. indicate a path.
  1317. .. seealso::
  1318. :ref:`deferred`
  1319. :func:`_orm.defer`
  1320. :func:`_orm.undefer_group`
  1321. """
  1322. return loadopt.set_column_strategy(
  1323. (key,), {"deferred": False, "instrument": True}
  1324. )
  1325. @undefer._add_unbound_fn
  1326. def undefer(key, *addl_attrs):
  1327. if addl_attrs:
  1328. util.warn_deprecated(
  1329. "The *addl_attrs on orm.undefer is deprecated. Please use "
  1330. "method chaining in conjunction with defaultload() to "
  1331. "indicate a path.",
  1332. version="1.3",
  1333. )
  1334. return _UnboundLoad._from_keys(
  1335. _UnboundLoad.undefer, (key,) + addl_attrs, False, {}
  1336. )
  1337. @loader_option()
  1338. def undefer_group(loadopt, name):
  1339. """Indicate that columns within the given deferred group name should be
  1340. undeferred.
  1341. The columns being undeferred are set up on the mapping as
  1342. :func:`.deferred` attributes and include a "group" name.
  1343. E.g::
  1344. session.query(MyClass).options(undefer_group("large_attrs"))
  1345. To undefer a group of attributes on a related entity, the path can be
  1346. spelled out using relationship loader options, such as
  1347. :func:`_orm.defaultload`::
  1348. session.query(MyClass).options(
  1349. defaultload("someattr").undefer_group("large_attrs"))
  1350. .. versionchanged:: 0.9.0 :func:`_orm.undefer_group` is now specific to a
  1351. particular entity load path.
  1352. .. seealso::
  1353. :ref:`deferred`
  1354. :func:`_orm.defer`
  1355. :func:`_orm.undefer`
  1356. """
  1357. return loadopt.set_column_strategy(
  1358. "*", None, {"undefer_group_%s" % name: True}, opts_only=True
  1359. )
  1360. @undefer_group._add_unbound_fn
  1361. def undefer_group(name):
  1362. return _UnboundLoad().undefer_group(name)
  1363. @loader_option()
  1364. def with_expression(loadopt, key, expression):
  1365. r"""Apply an ad-hoc SQL expression to a "deferred expression" attribute.
  1366. This option is used in conjunction with the :func:`_orm.query_expression`
  1367. mapper-level construct that indicates an attribute which should be the
  1368. target of an ad-hoc SQL expression.
  1369. E.g.::
  1370. sess.query(SomeClass).options(
  1371. with_expression(SomeClass.x_y_expr, SomeClass.x + SomeClass.y)
  1372. )
  1373. .. versionadded:: 1.2
  1374. :param key: Attribute to be undeferred.
  1375. :param expr: SQL expression to be applied to the attribute.
  1376. .. note:: the target attribute is populated only if the target object
  1377. is **not currently loaded** in the current :class:`_orm.Session`
  1378. unless the :meth:`_query.Query.populate_existing` method is used.
  1379. Please refer to :ref:`mapper_querytime_expression` for complete
  1380. usage details.
  1381. .. seealso::
  1382. :ref:`mapper_querytime_expression`
  1383. """
  1384. expression = coercions.expect(
  1385. roles.LabeledColumnExprRole, _orm_full_deannotate(expression)
  1386. )
  1387. return loadopt.set_column_strategy(
  1388. (key,), {"query_expression": True}, opts={"expression": expression}
  1389. )
  1390. @with_expression._add_unbound_fn
  1391. def with_expression(key, expression):
  1392. return _UnboundLoad._from_keys(
  1393. _UnboundLoad.with_expression, (key,), False, {"expression": expression}
  1394. )
  1395. @loader_option()
  1396. def selectin_polymorphic(loadopt, classes):
  1397. """Indicate an eager load should take place for all attributes
  1398. specific to a subclass.
  1399. This uses an additional SELECT with IN against all matched primary
  1400. key values, and is the per-query analogue to the ``"selectin"``
  1401. setting on the :paramref:`.mapper.polymorphic_load` parameter.
  1402. .. versionadded:: 1.2
  1403. .. seealso::
  1404. :ref:`polymorphic_selectin`
  1405. """
  1406. loadopt.set_class_strategy(
  1407. {"selectinload_polymorphic": True},
  1408. opts={
  1409. "entities": tuple(
  1410. sorted((inspect(cls) for cls in classes), key=id)
  1411. )
  1412. },
  1413. )
  1414. return loadopt
  1415. @selectin_polymorphic._add_unbound_fn
  1416. def selectin_polymorphic(base_cls, classes):
  1417. ul = _UnboundLoad()
  1418. ul.is_class_strategy = True
  1419. ul.path = (inspect(base_cls),)
  1420. ul.selectin_polymorphic(classes)
  1421. return ul