strategy_options.py 68 KB

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