loading.py 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663
  1. # orm/loading.py
  2. # Copyright (C) 2005-2024 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: https://www.opensource.org/licenses/mit-license.php
  7. # mypy: ignore-errors
  8. """private module containing functions used to convert database
  9. rows into object instances and associated state.
  10. the functions here are called primarily by Query, Mapper,
  11. as well as some of the attribute loading strategies.
  12. """
  13. from __future__ import annotations
  14. from typing import Any
  15. from typing import Dict
  16. from typing import Iterable
  17. from typing import List
  18. from typing import Mapping
  19. from typing import Optional
  20. from typing import Sequence
  21. from typing import Tuple
  22. from typing import TYPE_CHECKING
  23. from typing import TypeVar
  24. from typing import Union
  25. from . import attributes
  26. from . import exc as orm_exc
  27. from . import path_registry
  28. from .base import _DEFER_FOR_STATE
  29. from .base import _RAISE_FOR_STATE
  30. from .base import _SET_DEFERRED_EXPIRED
  31. from .base import PassiveFlag
  32. from .context import FromStatement
  33. from .context import ORMCompileState
  34. from .context import QueryContext
  35. from .util import _none_set
  36. from .util import state_str
  37. from .. import exc as sa_exc
  38. from .. import util
  39. from ..engine import result_tuple
  40. from ..engine.result import ChunkedIteratorResult
  41. from ..engine.result import FrozenResult
  42. from ..engine.result import SimpleResultMetaData
  43. from ..sql import select
  44. from ..sql import util as sql_util
  45. from ..sql.selectable import ForUpdateArg
  46. from ..sql.selectable import LABEL_STYLE_TABLENAME_PLUS_COL
  47. from ..sql.selectable import SelectState
  48. from ..util import EMPTY_DICT
  49. if TYPE_CHECKING:
  50. from ._typing import _IdentityKeyType
  51. from .base import LoaderCallableStatus
  52. from .interfaces import ORMOption
  53. from .mapper import Mapper
  54. from .query import Query
  55. from .session import Session
  56. from .state import InstanceState
  57. from ..engine.cursor import CursorResult
  58. from ..engine.interfaces import _ExecuteOptions
  59. from ..engine.result import Result
  60. from ..sql import Select
  61. _T = TypeVar("_T", bound=Any)
  62. _O = TypeVar("_O", bound=object)
  63. _new_runid = util.counter()
  64. _PopulatorDict = Dict[str, List[Tuple[str, Any]]]
  65. def instances(cursor: CursorResult[Any], context: QueryContext) -> Result[Any]:
  66. """Return a :class:`.Result` given an ORM query context.
  67. :param cursor: a :class:`.CursorResult`, generated by a statement
  68. which came from :class:`.ORMCompileState`
  69. :param context: a :class:`.QueryContext` object
  70. :return: a :class:`.Result` object representing ORM results
  71. .. versionchanged:: 1.4 The instances() function now uses
  72. :class:`.Result` objects and has an all new interface.
  73. """
  74. context.runid = _new_runid()
  75. if context.top_level_context:
  76. is_top_level = False
  77. context.post_load_paths = context.top_level_context.post_load_paths
  78. else:
  79. is_top_level = True
  80. context.post_load_paths = {}
  81. compile_state = context.compile_state
  82. filtered = compile_state._has_mapper_entities
  83. single_entity = (
  84. not context.load_options._only_return_tuples
  85. and len(compile_state._entities) == 1
  86. and compile_state._entities[0].supports_single_entity
  87. )
  88. try:
  89. (process, labels, extra) = list(
  90. zip(
  91. *[
  92. query_entity.row_processor(context, cursor)
  93. for query_entity in context.compile_state._entities
  94. ]
  95. )
  96. )
  97. if context.yield_per and (
  98. context.loaders_require_buffering
  99. or context.loaders_require_uniquing
  100. ):
  101. raise sa_exc.InvalidRequestError(
  102. "Can't use yield_per with eager loaders that require uniquing "
  103. "or row buffering, e.g. joinedload() against collections "
  104. "or subqueryload(). Consider the selectinload() strategy "
  105. "for better flexibility in loading objects."
  106. )
  107. except Exception:
  108. with util.safe_reraise():
  109. cursor.close()
  110. def _no_unique(entry):
  111. raise sa_exc.InvalidRequestError(
  112. "Can't use the ORM yield_per feature in conjunction with unique()"
  113. )
  114. def _not_hashable(datatype, *, legacy=False, uncertain=False):
  115. if not legacy:
  116. def go(obj):
  117. if uncertain:
  118. try:
  119. return hash(obj)
  120. except:
  121. pass
  122. raise sa_exc.InvalidRequestError(
  123. "Can't apply uniqueness to row tuple containing value of "
  124. f"""type {datatype!r}; {
  125. 'the values returned appear to be'
  126. if uncertain
  127. else 'this datatype produces'
  128. } non-hashable values"""
  129. )
  130. return go
  131. elif not uncertain:
  132. return id
  133. else:
  134. _use_id = False
  135. def go(obj):
  136. nonlocal _use_id
  137. if not _use_id:
  138. try:
  139. return hash(obj)
  140. except:
  141. pass
  142. # in #10459, we considered using a warning here, however
  143. # as legacy query uses result.unique() in all cases, this
  144. # would lead to too many warning cases.
  145. _use_id = True
  146. return id(obj)
  147. return go
  148. unique_filters = [
  149. _no_unique
  150. if context.yield_per
  151. else _not_hashable(
  152. ent.column.type, # type: ignore
  153. legacy=context.load_options._legacy_uniquing,
  154. uncertain=ent._null_column_type,
  155. )
  156. if (
  157. not ent.use_id_for_hash
  158. and (ent._non_hashable_value or ent._null_column_type)
  159. )
  160. else id
  161. if ent.use_id_for_hash
  162. else None
  163. for ent in context.compile_state._entities
  164. ]
  165. row_metadata = SimpleResultMetaData(
  166. labels, extra, _unique_filters=unique_filters
  167. )
  168. def chunks(size): # type: ignore
  169. while True:
  170. yield_per = size
  171. context.partials = {}
  172. if yield_per:
  173. fetch = cursor.fetchmany(yield_per)
  174. if not fetch:
  175. break
  176. else:
  177. fetch = cursor._raw_all_rows()
  178. if single_entity:
  179. proc = process[0]
  180. rows = [proc(row) for row in fetch]
  181. else:
  182. rows = [
  183. tuple([proc(row) for proc in process]) for row in fetch
  184. ]
  185. # if we are the originating load from a query, meaning we
  186. # aren't being called as a result of a nested "post load",
  187. # iterate through all the collected post loaders and fire them
  188. # off. Previously this used to work recursively, however that
  189. # prevented deeply nested structures from being loadable
  190. if is_top_level:
  191. if yield_per:
  192. # if using yield per, memoize the state of the
  193. # collection so that it can be restored
  194. top_level_post_loads = list(
  195. context.post_load_paths.items()
  196. )
  197. while context.post_load_paths:
  198. post_loads = list(context.post_load_paths.items())
  199. context.post_load_paths.clear()
  200. for path, post_load in post_loads:
  201. post_load.invoke(context, path)
  202. if yield_per:
  203. context.post_load_paths.clear()
  204. context.post_load_paths.update(top_level_post_loads)
  205. yield rows
  206. if not yield_per:
  207. break
  208. if context.execution_options.get("prebuffer_rows", False):
  209. # this is a bit of a hack at the moment.
  210. # I would rather have some option in the result to pre-buffer
  211. # internally.
  212. _prebuffered = list(chunks(None))
  213. def chunks(size):
  214. return iter(_prebuffered)
  215. result = ChunkedIteratorResult(
  216. row_metadata,
  217. chunks,
  218. source_supports_scalars=single_entity,
  219. raw=cursor,
  220. dynamic_yield_per=cursor.context._is_server_side,
  221. )
  222. # filtered and single_entity are used to indicate to legacy Query that the
  223. # query has ORM entities, so legacy deduping and scalars should be called
  224. # on the result.
  225. result._attributes = result._attributes.union(
  226. dict(filtered=filtered, is_single_entity=single_entity)
  227. )
  228. # multi_row_eager_loaders OTOH is specific to joinedload.
  229. if context.compile_state.multi_row_eager_loaders:
  230. def require_unique(obj):
  231. raise sa_exc.InvalidRequestError(
  232. "The unique() method must be invoked on this Result, "
  233. "as it contains results that include joined eager loads "
  234. "against collections"
  235. )
  236. result._unique_filter_state = (None, require_unique)
  237. if context.yield_per:
  238. result.yield_per(context.yield_per)
  239. return result
  240. @util.preload_module("sqlalchemy.orm.context")
  241. def merge_frozen_result(session, statement, frozen_result, load=True):
  242. """Merge a :class:`_engine.FrozenResult` back into a :class:`_orm.Session`,
  243. returning a new :class:`_engine.Result` object with :term:`persistent`
  244. objects.
  245. See the section :ref:`do_orm_execute_re_executing` for an example.
  246. .. seealso::
  247. :ref:`do_orm_execute_re_executing`
  248. :meth:`_engine.Result.freeze`
  249. :class:`_engine.FrozenResult`
  250. """
  251. querycontext = util.preloaded.orm_context
  252. if load:
  253. # flush current contents if we expect to load data
  254. session._autoflush()
  255. ctx = querycontext.ORMSelectCompileState._create_entities_collection(
  256. statement, legacy=False
  257. )
  258. autoflush = session.autoflush
  259. try:
  260. session.autoflush = False
  261. mapped_entities = [
  262. i
  263. for i, e in enumerate(ctx._entities)
  264. if isinstance(e, querycontext._MapperEntity)
  265. ]
  266. keys = [ent._label_name for ent in ctx._entities]
  267. keyed_tuple = result_tuple(
  268. keys, [ent._extra_entities for ent in ctx._entities]
  269. )
  270. result = []
  271. for newrow in frozen_result.rewrite_rows():
  272. for i in mapped_entities:
  273. if newrow[i] is not None:
  274. newrow[i] = session._merge(
  275. attributes.instance_state(newrow[i]),
  276. attributes.instance_dict(newrow[i]),
  277. load=load,
  278. _recursive={},
  279. _resolve_conflict_map={},
  280. )
  281. result.append(keyed_tuple(newrow))
  282. return frozen_result.with_new_rows(result)
  283. finally:
  284. session.autoflush = autoflush
  285. @util.became_legacy_20(
  286. ":func:`_orm.merge_result`",
  287. alternative="The function as well as the method on :class:`_orm.Query` "
  288. "is superseded by the :func:`_orm.merge_frozen_result` function.",
  289. )
  290. @util.preload_module("sqlalchemy.orm.context")
  291. def merge_result(
  292. query: Query[Any],
  293. iterator: Union[FrozenResult, Iterable[Sequence[Any]], Iterable[object]],
  294. load: bool = True,
  295. ) -> Union[FrozenResult, Iterable[Any]]:
  296. """Merge a result into the given :class:`.Query` object's Session.
  297. See :meth:`_orm.Query.merge_result` for top-level documentation on this
  298. function.
  299. """
  300. querycontext = util.preloaded.orm_context
  301. session = query.session
  302. if load:
  303. # flush current contents if we expect to load data
  304. session._autoflush()
  305. # TODO: need test coverage and documentation for the FrozenResult
  306. # use case.
  307. if isinstance(iterator, FrozenResult):
  308. frozen_result = iterator
  309. iterator = iter(frozen_result.data)
  310. else:
  311. frozen_result = None
  312. ctx = querycontext.ORMSelectCompileState._create_entities_collection(
  313. query, legacy=True
  314. )
  315. autoflush = session.autoflush
  316. try:
  317. session.autoflush = False
  318. single_entity = not frozen_result and len(ctx._entities) == 1
  319. if single_entity:
  320. if isinstance(ctx._entities[0], querycontext._MapperEntity):
  321. result = [
  322. session._merge(
  323. attributes.instance_state(instance),
  324. attributes.instance_dict(instance),
  325. load=load,
  326. _recursive={},
  327. _resolve_conflict_map={},
  328. )
  329. for instance in iterator
  330. ]
  331. else:
  332. result = list(iterator)
  333. else:
  334. mapped_entities = [
  335. i
  336. for i, e in enumerate(ctx._entities)
  337. if isinstance(e, querycontext._MapperEntity)
  338. ]
  339. result = []
  340. keys = [ent._label_name for ent in ctx._entities]
  341. keyed_tuple = result_tuple(
  342. keys, [ent._extra_entities for ent in ctx._entities]
  343. )
  344. for row in iterator:
  345. newrow = list(row)
  346. for i in mapped_entities:
  347. if newrow[i] is not None:
  348. newrow[i] = session._merge(
  349. attributes.instance_state(newrow[i]),
  350. attributes.instance_dict(newrow[i]),
  351. load=load,
  352. _recursive={},
  353. _resolve_conflict_map={},
  354. )
  355. result.append(keyed_tuple(newrow))
  356. if frozen_result:
  357. return frozen_result.with_new_rows(result)
  358. else:
  359. return iter(result)
  360. finally:
  361. session.autoflush = autoflush
  362. def get_from_identity(
  363. session: Session,
  364. mapper: Mapper[_O],
  365. key: _IdentityKeyType[_O],
  366. passive: PassiveFlag,
  367. ) -> Union[LoaderCallableStatus, Optional[_O]]:
  368. """Look up the given key in the given session's identity map,
  369. check the object for expired state if found.
  370. """
  371. instance = session.identity_map.get(key)
  372. if instance is not None:
  373. state = attributes.instance_state(instance)
  374. if mapper.inherits and not state.mapper.isa(mapper):
  375. return attributes.PASSIVE_CLASS_MISMATCH
  376. # expired - ensure it still exists
  377. if state.expired:
  378. if not passive & attributes.SQL_OK:
  379. # TODO: no coverage here
  380. return attributes.PASSIVE_NO_RESULT
  381. elif not passive & attributes.RELATED_OBJECT_OK:
  382. # this mode is used within a flush and the instance's
  383. # expired state will be checked soon enough, if necessary.
  384. # also used by immediateloader for a mutually-dependent
  385. # o2m->m2m load, :ticket:`6301`
  386. return instance
  387. try:
  388. state._load_expired(state, passive)
  389. except orm_exc.ObjectDeletedError:
  390. session._remove_newly_deleted([state])
  391. return None
  392. return instance
  393. else:
  394. return None
  395. def load_on_ident(
  396. session: Session,
  397. statement: Union[Select, FromStatement],
  398. key: Optional[_IdentityKeyType],
  399. *,
  400. load_options: Optional[Sequence[ORMOption]] = None,
  401. refresh_state: Optional[InstanceState[Any]] = None,
  402. with_for_update: Optional[ForUpdateArg] = None,
  403. only_load_props: Optional[Iterable[str]] = None,
  404. no_autoflush: bool = False,
  405. bind_arguments: Mapping[str, Any] = util.EMPTY_DICT,
  406. execution_options: _ExecuteOptions = util.EMPTY_DICT,
  407. require_pk_cols: bool = False,
  408. is_user_refresh: bool = False,
  409. ):
  410. """Load the given identity key from the database."""
  411. if key is not None:
  412. ident = key[1]
  413. identity_token = key[2]
  414. else:
  415. ident = identity_token = None
  416. return load_on_pk_identity(
  417. session,
  418. statement,
  419. ident,
  420. load_options=load_options,
  421. refresh_state=refresh_state,
  422. with_for_update=with_for_update,
  423. only_load_props=only_load_props,
  424. identity_token=identity_token,
  425. no_autoflush=no_autoflush,
  426. bind_arguments=bind_arguments,
  427. execution_options=execution_options,
  428. require_pk_cols=require_pk_cols,
  429. is_user_refresh=is_user_refresh,
  430. )
  431. def load_on_pk_identity(
  432. session: Session,
  433. statement: Union[Select, FromStatement],
  434. primary_key_identity: Optional[Tuple[Any, ...]],
  435. *,
  436. load_options: Optional[Sequence[ORMOption]] = None,
  437. refresh_state: Optional[InstanceState[Any]] = None,
  438. with_for_update: Optional[ForUpdateArg] = None,
  439. only_load_props: Optional[Iterable[str]] = None,
  440. identity_token: Optional[Any] = None,
  441. no_autoflush: bool = False,
  442. bind_arguments: Mapping[str, Any] = util.EMPTY_DICT,
  443. execution_options: _ExecuteOptions = util.EMPTY_DICT,
  444. require_pk_cols: bool = False,
  445. is_user_refresh: bool = False,
  446. ):
  447. """Load the given primary key identity from the database."""
  448. query = statement
  449. q = query._clone()
  450. assert not q._is_lambda_element
  451. if load_options is None:
  452. load_options = QueryContext.default_load_options
  453. if (
  454. statement._compile_options
  455. is SelectState.default_select_compile_options
  456. ):
  457. compile_options = ORMCompileState.default_compile_options
  458. else:
  459. compile_options = statement._compile_options
  460. if primary_key_identity is not None:
  461. mapper = query._propagate_attrs["plugin_subject"]
  462. (_get_clause, _get_params) = mapper._get_clause
  463. # None present in ident - turn those comparisons
  464. # into "IS NULL"
  465. if None in primary_key_identity:
  466. nones = {
  467. _get_params[col].key
  468. for col, value in zip(mapper.primary_key, primary_key_identity)
  469. if value is None
  470. }
  471. _get_clause = sql_util.adapt_criterion_to_null(_get_clause, nones)
  472. if len(nones) == len(primary_key_identity):
  473. util.warn(
  474. "fully NULL primary key identity cannot load any "
  475. "object. This condition may raise an error in a future "
  476. "release."
  477. )
  478. q._where_criteria = (
  479. sql_util._deep_annotate(_get_clause, {"_orm_adapt": True}),
  480. )
  481. params = {
  482. _get_params[primary_key].key: id_val
  483. for id_val, primary_key in zip(
  484. primary_key_identity, mapper.primary_key
  485. )
  486. }
  487. else:
  488. params = None
  489. if with_for_update is not None:
  490. version_check = True
  491. q._for_update_arg = with_for_update
  492. elif query._for_update_arg is not None:
  493. version_check = True
  494. q._for_update_arg = query._for_update_arg
  495. else:
  496. version_check = False
  497. if require_pk_cols and only_load_props:
  498. if not refresh_state:
  499. raise sa_exc.ArgumentError(
  500. "refresh_state is required when require_pk_cols is present"
  501. )
  502. refresh_state_prokeys = refresh_state.mapper._primary_key_propkeys
  503. has_changes = {
  504. key
  505. for key in refresh_state_prokeys.difference(only_load_props)
  506. if refresh_state.attrs[key].history.has_changes()
  507. }
  508. if has_changes:
  509. # raise if pending pk changes are present.
  510. # technically, this could be limited to the case where we have
  511. # relationships in the only_load_props collection to be refreshed
  512. # also (and only ones that have a secondary eager loader, at that).
  513. # however, the error is in place across the board so that behavior
  514. # here is easier to predict. The use case it prevents is one
  515. # of mutating PK attrs, leaving them unflushed,
  516. # calling session.refresh(), and expecting those attrs to remain
  517. # still unflushed. It seems likely someone doing all those
  518. # things would be better off having the PK attributes flushed
  519. # to the database before tinkering like that (session.refresh() is
  520. # tinkering).
  521. raise sa_exc.InvalidRequestError(
  522. f"Please flush pending primary key changes on "
  523. "attributes "
  524. f"{has_changes} for mapper {refresh_state.mapper} before "
  525. "proceeding with a refresh"
  526. )
  527. # overall, the ORM has no internal flow right now for "dont load the
  528. # primary row of an object at all, but fire off
  529. # selectinload/subqueryload/immediateload for some relationships".
  530. # It would probably be a pretty big effort to add such a flow. So
  531. # here, the case for #8703 is introduced; user asks to refresh some
  532. # relationship attributes only which are
  533. # selectinload/subqueryload/immediateload/ etc. (not joinedload).
  534. # ORM complains there's no columns in the primary row to load.
  535. # So here, we just add the PK cols if that
  536. # case is detected, so that there is a SELECT emitted for the primary
  537. # row.
  538. #
  539. # Let's just state right up front, for this one little case,
  540. # the ORM here is adding a whole extra SELECT just to satisfy
  541. # limitations in the internal flow. This is really not a thing
  542. # SQLAlchemy finds itself doing like, ever, obviously, we are
  543. # constantly working to *remove* SELECTs we don't need. We
  544. # rationalize this for now based on 1. session.refresh() is not
  545. # commonly used 2. session.refresh() with only relationship attrs is
  546. # even less commonly used 3. the SELECT in question is very low
  547. # latency.
  548. #
  549. # to add the flow to not include the SELECT, the quickest way
  550. # might be to just manufacture a single-row result set to send off to
  551. # instances(), but we'd have to weave that into context.py and all
  552. # that. For 2.0.0, we have enough big changes to navigate for now.
  553. #
  554. mp = refresh_state.mapper._props
  555. for p in only_load_props:
  556. if mp[p]._is_relationship:
  557. only_load_props = refresh_state_prokeys.union(only_load_props)
  558. break
  559. if refresh_state and refresh_state.load_options:
  560. compile_options += {"_current_path": refresh_state.load_path.parent}
  561. q = q.options(*refresh_state.load_options)
  562. new_compile_options, load_options = _set_get_options(
  563. compile_options,
  564. load_options,
  565. version_check=version_check,
  566. only_load_props=only_load_props,
  567. refresh_state=refresh_state,
  568. identity_token=identity_token,
  569. is_user_refresh=is_user_refresh,
  570. )
  571. q._compile_options = new_compile_options
  572. q._order_by = None
  573. if no_autoflush:
  574. load_options += {"_autoflush": False}
  575. execution_options = util.EMPTY_DICT.merge_with(
  576. execution_options, {"_sa_orm_load_options": load_options}
  577. )
  578. result = (
  579. session.execute(
  580. q,
  581. params=params,
  582. execution_options=execution_options,
  583. bind_arguments=bind_arguments,
  584. )
  585. .unique()
  586. .scalars()
  587. )
  588. try:
  589. return result.one()
  590. except orm_exc.NoResultFound:
  591. return None
  592. def _set_get_options(
  593. compile_opt,
  594. load_opt,
  595. populate_existing=None,
  596. version_check=None,
  597. only_load_props=None,
  598. refresh_state=None,
  599. identity_token=None,
  600. is_user_refresh=None,
  601. ):
  602. compile_options = {}
  603. load_options = {}
  604. if version_check:
  605. load_options["_version_check"] = version_check
  606. if populate_existing:
  607. load_options["_populate_existing"] = populate_existing
  608. if refresh_state:
  609. load_options["_refresh_state"] = refresh_state
  610. compile_options["_for_refresh_state"] = True
  611. if only_load_props:
  612. compile_options["_only_load_props"] = frozenset(only_load_props)
  613. if identity_token:
  614. load_options["_identity_token"] = identity_token
  615. if is_user_refresh:
  616. load_options["_is_user_refresh"] = is_user_refresh
  617. if load_options:
  618. load_opt += load_options
  619. if compile_options:
  620. compile_opt += compile_options
  621. return compile_opt, load_opt
  622. def _setup_entity_query(
  623. compile_state,
  624. mapper,
  625. query_entity,
  626. path,
  627. adapter,
  628. column_collection,
  629. with_polymorphic=None,
  630. only_load_props=None,
  631. polymorphic_discriminator=None,
  632. **kw,
  633. ):
  634. if with_polymorphic:
  635. poly_properties = mapper._iterate_polymorphic_properties(
  636. with_polymorphic
  637. )
  638. else:
  639. poly_properties = mapper._polymorphic_properties
  640. quick_populators = {}
  641. path.set(compile_state.attributes, "memoized_setups", quick_populators)
  642. # for the lead entities in the path, e.g. not eager loads, and
  643. # assuming a user-passed aliased class, e.g. not a from_self() or any
  644. # implicit aliasing, don't add columns to the SELECT that aren't
  645. # in the thing that's aliased.
  646. check_for_adapt = adapter and len(path) == 1 and path[-1].is_aliased_class
  647. for value in poly_properties:
  648. if only_load_props and value.key not in only_load_props:
  649. continue
  650. value.setup(
  651. compile_state,
  652. query_entity,
  653. path,
  654. adapter,
  655. only_load_props=only_load_props,
  656. column_collection=column_collection,
  657. memoized_populators=quick_populators,
  658. check_for_adapt=check_for_adapt,
  659. **kw,
  660. )
  661. if (
  662. polymorphic_discriminator is not None
  663. and polymorphic_discriminator is not mapper.polymorphic_on
  664. ):
  665. if adapter:
  666. pd = adapter.columns[polymorphic_discriminator]
  667. else:
  668. pd = polymorphic_discriminator
  669. column_collection.append(pd)
  670. def _warn_for_runid_changed(state):
  671. util.warn(
  672. "Loading context for %s has changed within a load/refresh "
  673. "handler, suggesting a row refresh operation took place. If this "
  674. "event handler is expected to be "
  675. "emitting row refresh operations within an existing load or refresh "
  676. "operation, set restore_load_context=True when establishing the "
  677. "listener to ensure the context remains unchanged when the event "
  678. "handler completes." % (state_str(state),)
  679. )
  680. def _instance_processor(
  681. query_entity,
  682. mapper,
  683. context,
  684. result,
  685. path,
  686. adapter,
  687. only_load_props=None,
  688. refresh_state=None,
  689. polymorphic_discriminator=None,
  690. _polymorphic_from=None,
  691. ):
  692. """Produce a mapper level row processor callable
  693. which processes rows into mapped instances."""
  694. # note that this method, most of which exists in a closure
  695. # called _instance(), resists being broken out, as
  696. # attempts to do so tend to add significant function
  697. # call overhead. _instance() is the most
  698. # performance-critical section in the whole ORM.
  699. identity_class = mapper._identity_class
  700. compile_state = context.compile_state
  701. # look for "row getter" functions that have been assigned along
  702. # with the compile state that were cached from a previous load.
  703. # these are operator.itemgetter() objects that each will extract a
  704. # particular column from each row.
  705. getter_key = ("getters", mapper)
  706. getters = path.get(compile_state.attributes, getter_key, None)
  707. if getters is None:
  708. # no getters, so go through a list of attributes we are loading for,
  709. # and the ones that are column based will have already put information
  710. # for us in another collection "memoized_setups", which represents the
  711. # output of the LoaderStrategy.setup_query() method. We can just as
  712. # easily call LoaderStrategy.create_row_processor for each, but by
  713. # getting it all at once from setup_query we save another method call
  714. # per attribute.
  715. props = mapper._prop_set
  716. if only_load_props is not None:
  717. props = props.intersection(
  718. mapper._props[k] for k in only_load_props
  719. )
  720. quick_populators = path.get(
  721. context.attributes, "memoized_setups", EMPTY_DICT
  722. )
  723. todo = []
  724. cached_populators = {
  725. "new": [],
  726. "quick": [],
  727. "deferred": [],
  728. "expire": [],
  729. "existing": [],
  730. "eager": [],
  731. }
  732. if refresh_state is None:
  733. # we can also get the "primary key" tuple getter function
  734. pk_cols = mapper.primary_key
  735. if adapter:
  736. pk_cols = [adapter.columns[c] for c in pk_cols]
  737. primary_key_getter = result._tuple_getter(pk_cols)
  738. else:
  739. primary_key_getter = None
  740. getters = {
  741. "cached_populators": cached_populators,
  742. "todo": todo,
  743. "primary_key_getter": primary_key_getter,
  744. }
  745. for prop in props:
  746. if prop in quick_populators:
  747. # this is an inlined path just for column-based attributes.
  748. col = quick_populators[prop]
  749. if col is _DEFER_FOR_STATE:
  750. cached_populators["new"].append(
  751. (prop.key, prop._deferred_column_loader)
  752. )
  753. elif col is _SET_DEFERRED_EXPIRED:
  754. # note that in this path, we are no longer
  755. # searching in the result to see if the column might
  756. # be present in some unexpected way.
  757. cached_populators["expire"].append((prop.key, False))
  758. elif col is _RAISE_FOR_STATE:
  759. cached_populators["new"].append(
  760. (prop.key, prop._raise_column_loader)
  761. )
  762. else:
  763. getter = None
  764. if adapter:
  765. # this logic had been removed for all 1.4 releases
  766. # up until 1.4.18; the adapter here is particularly
  767. # the compound eager adapter which isn't accommodated
  768. # in the quick_populators right now. The "fallback"
  769. # logic below instead took over in many more cases
  770. # until issue #6596 was identified.
  771. # note there is still an issue where this codepath
  772. # produces no "getter" for cases where a joined-inh
  773. # mapping includes a labeled column property, meaning
  774. # KeyError is caught internally and we fall back to
  775. # _getter(col), which works anyway. The adapter
  776. # here for joined inh without any aliasing might not
  777. # be useful. Tests which see this include
  778. # test.orm.inheritance.test_basic ->
  779. # EagerTargetingTest.test_adapt_stringency
  780. # OptimizedLoadTest.test_column_expression_joined
  781. # PolymorphicOnNotLocalTest.test_polymorphic_on_column_prop # noqa: E501
  782. #
  783. adapted_col = adapter.columns[col]
  784. if adapted_col is not None:
  785. getter = result._getter(adapted_col, False)
  786. if not getter:
  787. getter = result._getter(col, False)
  788. if getter:
  789. cached_populators["quick"].append((prop.key, getter))
  790. else:
  791. # fall back to the ColumnProperty itself, which
  792. # will iterate through all of its columns
  793. # to see if one fits
  794. prop.create_row_processor(
  795. context,
  796. query_entity,
  797. path,
  798. mapper,
  799. result,
  800. adapter,
  801. cached_populators,
  802. )
  803. else:
  804. # loader strategies like subqueryload, selectinload,
  805. # joinedload, basically relationships, these need to interact
  806. # with the context each time to work correctly.
  807. todo.append(prop)
  808. path.set(compile_state.attributes, getter_key, getters)
  809. cached_populators = getters["cached_populators"]
  810. populators = {key: list(value) for key, value in cached_populators.items()}
  811. for prop in getters["todo"]:
  812. prop.create_row_processor(
  813. context, query_entity, path, mapper, result, adapter, populators
  814. )
  815. propagated_loader_options = context.propagated_loader_options
  816. load_path = (
  817. context.compile_state.current_path + path
  818. if context.compile_state.current_path.path
  819. else path
  820. )
  821. session_identity_map = context.session.identity_map
  822. populate_existing = context.populate_existing or mapper.always_refresh
  823. load_evt = bool(mapper.class_manager.dispatch.load)
  824. refresh_evt = bool(mapper.class_manager.dispatch.refresh)
  825. persistent_evt = bool(context.session.dispatch.loaded_as_persistent)
  826. if persistent_evt:
  827. loaded_as_persistent = context.session.dispatch.loaded_as_persistent
  828. instance_state = attributes.instance_state
  829. instance_dict = attributes.instance_dict
  830. session_id = context.session.hash_key
  831. runid = context.runid
  832. identity_token = context.identity_token
  833. version_check = context.version_check
  834. if version_check:
  835. version_id_col = mapper.version_id_col
  836. if version_id_col is not None:
  837. if adapter:
  838. version_id_col = adapter.columns[version_id_col]
  839. version_id_getter = result._getter(version_id_col)
  840. else:
  841. version_id_getter = None
  842. if not refresh_state and _polymorphic_from is not None:
  843. key = ("loader", path.path)
  844. if key in context.attributes and context.attributes[key].strategy == (
  845. ("selectinload_polymorphic", True),
  846. ):
  847. option_entities = context.attributes[key].local_opts["entities"]
  848. else:
  849. option_entities = None
  850. selectin_load_via = mapper._should_selectin_load(
  851. option_entities,
  852. _polymorphic_from,
  853. )
  854. if selectin_load_via and selectin_load_via is not _polymorphic_from:
  855. # only_load_props goes w/ refresh_state only, and in a refresh
  856. # we are a single row query for the exact entity; polymorphic
  857. # loading does not apply
  858. assert only_load_props is None
  859. callable_ = _load_subclass_via_in(
  860. context,
  861. path,
  862. selectin_load_via,
  863. _polymorphic_from,
  864. option_entities,
  865. )
  866. PostLoad.callable_for_path(
  867. context,
  868. load_path,
  869. selectin_load_via.mapper,
  870. selectin_load_via,
  871. callable_,
  872. selectin_load_via,
  873. )
  874. post_load = PostLoad.for_context(context, load_path, only_load_props)
  875. if refresh_state:
  876. refresh_identity_key = refresh_state.key
  877. if refresh_identity_key is None:
  878. # super-rare condition; a refresh is being called
  879. # on a non-instance-key instance; this is meant to only
  880. # occur within a flush()
  881. refresh_identity_key = mapper._identity_key_from_state(
  882. refresh_state
  883. )
  884. else:
  885. refresh_identity_key = None
  886. primary_key_getter = getters["primary_key_getter"]
  887. if mapper.allow_partial_pks:
  888. is_not_primary_key = _none_set.issuperset
  889. else:
  890. is_not_primary_key = _none_set.intersection
  891. def _instance(row):
  892. # determine the state that we'll be populating
  893. if refresh_identity_key:
  894. # fixed state that we're refreshing
  895. state = refresh_state
  896. instance = state.obj()
  897. dict_ = instance_dict(instance)
  898. isnew = state.runid != runid
  899. currentload = True
  900. loaded_instance = False
  901. else:
  902. # look at the row, see if that identity is in the
  903. # session, or we have to create a new one
  904. identitykey = (
  905. identity_class,
  906. primary_key_getter(row),
  907. identity_token,
  908. )
  909. instance = session_identity_map.get(identitykey)
  910. if instance is not None:
  911. # existing instance
  912. state = instance_state(instance)
  913. dict_ = instance_dict(instance)
  914. isnew = state.runid != runid
  915. currentload = not isnew
  916. loaded_instance = False
  917. if version_check and version_id_getter and not currentload:
  918. _validate_version_id(
  919. mapper, state, dict_, row, version_id_getter
  920. )
  921. else:
  922. # create a new instance
  923. # check for non-NULL values in the primary key columns,
  924. # else no entity is returned for the row
  925. if is_not_primary_key(identitykey[1]):
  926. return None
  927. isnew = True
  928. currentload = True
  929. loaded_instance = True
  930. instance = mapper.class_manager.new_instance()
  931. dict_ = instance_dict(instance)
  932. state = instance_state(instance)
  933. state.key = identitykey
  934. state.identity_token = identity_token
  935. # attach instance to session.
  936. state.session_id = session_id
  937. session_identity_map._add_unpresent(state, identitykey)
  938. effective_populate_existing = populate_existing
  939. if refresh_state is state:
  940. effective_populate_existing = True
  941. # populate. this looks at whether this state is new
  942. # for this load or was existing, and whether or not this
  943. # row is the first row with this identity.
  944. if currentload or effective_populate_existing:
  945. # full population routines. Objects here are either
  946. # just created, or we are doing a populate_existing
  947. # be conservative about setting load_path when populate_existing
  948. # is in effect; want to maintain options from the original
  949. # load. see test_expire->test_refresh_maintains_deferred_options
  950. if isnew and (
  951. propagated_loader_options or not effective_populate_existing
  952. ):
  953. state.load_options = propagated_loader_options
  954. state.load_path = load_path
  955. _populate_full(
  956. context,
  957. row,
  958. state,
  959. dict_,
  960. isnew,
  961. load_path,
  962. loaded_instance,
  963. effective_populate_existing,
  964. populators,
  965. )
  966. if isnew:
  967. # state.runid should be equal to context.runid / runid
  968. # here, however for event checks we are being more conservative
  969. # and checking against existing run id
  970. # assert state.runid == runid
  971. existing_runid = state.runid
  972. if loaded_instance:
  973. if load_evt:
  974. state.manager.dispatch.load(state, context)
  975. if state.runid != existing_runid:
  976. _warn_for_runid_changed(state)
  977. if persistent_evt:
  978. loaded_as_persistent(context.session, state)
  979. if state.runid != existing_runid:
  980. _warn_for_runid_changed(state)
  981. elif refresh_evt:
  982. state.manager.dispatch.refresh(
  983. state, context, only_load_props
  984. )
  985. if state.runid != runid:
  986. _warn_for_runid_changed(state)
  987. if effective_populate_existing or state.modified:
  988. if refresh_state and only_load_props:
  989. state._commit(dict_, only_load_props)
  990. else:
  991. state._commit_all(dict_, session_identity_map)
  992. if post_load:
  993. post_load.add_state(state, True)
  994. else:
  995. # partial population routines, for objects that were already
  996. # in the Session, but a row matches them; apply eager loaders
  997. # on existing objects, etc.
  998. unloaded = state.unloaded
  999. isnew = state not in context.partials
  1000. if not isnew or unloaded or populators["eager"]:
  1001. # state is having a partial set of its attributes
  1002. # refreshed. Populate those attributes,
  1003. # and add to the "context.partials" collection.
  1004. to_load = _populate_partial(
  1005. context,
  1006. row,
  1007. state,
  1008. dict_,
  1009. isnew,
  1010. load_path,
  1011. unloaded,
  1012. populators,
  1013. )
  1014. if isnew:
  1015. if refresh_evt:
  1016. existing_runid = state.runid
  1017. state.manager.dispatch.refresh(state, context, to_load)
  1018. if state.runid != existing_runid:
  1019. _warn_for_runid_changed(state)
  1020. state._commit(dict_, to_load)
  1021. if post_load and context.invoke_all_eagers:
  1022. post_load.add_state(state, False)
  1023. return instance
  1024. if mapper.polymorphic_map and not _polymorphic_from and not refresh_state:
  1025. # if we are doing polymorphic, dispatch to a different _instance()
  1026. # method specific to the subclass mapper
  1027. def ensure_no_pk(row):
  1028. identitykey = (
  1029. identity_class,
  1030. primary_key_getter(row),
  1031. identity_token,
  1032. )
  1033. if not is_not_primary_key(identitykey[1]):
  1034. return identitykey
  1035. else:
  1036. return None
  1037. _instance = _decorate_polymorphic_switch(
  1038. _instance,
  1039. context,
  1040. query_entity,
  1041. mapper,
  1042. result,
  1043. path,
  1044. polymorphic_discriminator,
  1045. adapter,
  1046. ensure_no_pk,
  1047. )
  1048. return _instance
  1049. def _load_subclass_via_in(
  1050. context, path, entity, polymorphic_from, option_entities
  1051. ):
  1052. mapper = entity.mapper
  1053. # TODO: polymorphic_from seems to be a Mapper in all cases.
  1054. # this is likely not needed, but as we dont have typing in loading.py
  1055. # yet, err on the safe side
  1056. polymorphic_from_mapper = polymorphic_from.mapper
  1057. not_against_basemost = polymorphic_from_mapper.inherits is not None
  1058. zero_idx = len(mapper.base_mapper.primary_key) == 1
  1059. if entity.is_aliased_class or not_against_basemost:
  1060. q, enable_opt, disable_opt = mapper._subclass_load_via_in(
  1061. entity, polymorphic_from
  1062. )
  1063. else:
  1064. q, enable_opt, disable_opt = mapper._subclass_load_via_in_mapper
  1065. def do_load(context, path, states, load_only, effective_entity):
  1066. if not option_entities:
  1067. # filter out states for those that would have selectinloaded
  1068. # from another loader
  1069. # TODO: we are currently ignoring the case where the
  1070. # "selectin_polymorphic" option is used, as this is much more
  1071. # complex / specific / very uncommon API use
  1072. states = [
  1073. (s, v)
  1074. for s, v in states
  1075. if s.mapper._would_selectin_load_only_from_given_mapper(mapper)
  1076. ]
  1077. if not states:
  1078. return
  1079. orig_query = context.query
  1080. if path.parent:
  1081. enable_opt_lcl = enable_opt._prepend_path(path)
  1082. disable_opt_lcl = disable_opt._prepend_path(path)
  1083. else:
  1084. enable_opt_lcl = enable_opt
  1085. disable_opt_lcl = disable_opt
  1086. options = (
  1087. (enable_opt_lcl,) + orig_query._with_options + (disable_opt_lcl,)
  1088. )
  1089. q2 = q.options(*options)
  1090. q2._compile_options = context.compile_state.default_compile_options
  1091. q2._compile_options += {"_current_path": path.parent}
  1092. if context.populate_existing:
  1093. q2 = q2.execution_options(populate_existing=True)
  1094. context.session.execute(
  1095. q2,
  1096. dict(
  1097. primary_keys=[
  1098. state.key[1][0] if zero_idx else state.key[1]
  1099. for state, load_attrs in states
  1100. ]
  1101. ),
  1102. ).unique().scalars().all()
  1103. return do_load
  1104. def _populate_full(
  1105. context,
  1106. row,
  1107. state,
  1108. dict_,
  1109. isnew,
  1110. load_path,
  1111. loaded_instance,
  1112. populate_existing,
  1113. populators,
  1114. ):
  1115. if isnew:
  1116. # first time we are seeing a row with this identity.
  1117. state.runid = context.runid
  1118. for key, getter in populators["quick"]:
  1119. dict_[key] = getter(row)
  1120. if populate_existing:
  1121. for key, set_callable in populators["expire"]:
  1122. dict_.pop(key, None)
  1123. if set_callable:
  1124. state.expired_attributes.add(key)
  1125. else:
  1126. for key, set_callable in populators["expire"]:
  1127. if set_callable:
  1128. state.expired_attributes.add(key)
  1129. for key, populator in populators["new"]:
  1130. populator(state, dict_, row)
  1131. elif load_path != state.load_path:
  1132. # new load path, e.g. object is present in more than one
  1133. # column position in a series of rows
  1134. state.load_path = load_path
  1135. # if we have data, and the data isn't in the dict, OK, let's put
  1136. # it in.
  1137. for key, getter in populators["quick"]:
  1138. if key not in dict_:
  1139. dict_[key] = getter(row)
  1140. # otherwise treat like an "already seen" row
  1141. for key, populator in populators["existing"]:
  1142. populator(state, dict_, row)
  1143. # TODO: allow "existing" populator to know this is
  1144. # a new path for the state:
  1145. # populator(state, dict_, row, new_path=True)
  1146. else:
  1147. # have already seen rows with this identity in this same path.
  1148. for key, populator in populators["existing"]:
  1149. populator(state, dict_, row)
  1150. # TODO: same path
  1151. # populator(state, dict_, row, new_path=False)
  1152. def _populate_partial(
  1153. context, row, state, dict_, isnew, load_path, unloaded, populators
  1154. ):
  1155. if not isnew:
  1156. if unloaded:
  1157. # extra pass, see #8166
  1158. for key, getter in populators["quick"]:
  1159. if key in unloaded:
  1160. dict_[key] = getter(row)
  1161. to_load = context.partials[state]
  1162. for key, populator in populators["existing"]:
  1163. if key in to_load:
  1164. populator(state, dict_, row)
  1165. else:
  1166. to_load = unloaded
  1167. context.partials[state] = to_load
  1168. for key, getter in populators["quick"]:
  1169. if key in to_load:
  1170. dict_[key] = getter(row)
  1171. for key, set_callable in populators["expire"]:
  1172. if key in to_load:
  1173. dict_.pop(key, None)
  1174. if set_callable:
  1175. state.expired_attributes.add(key)
  1176. for key, populator in populators["new"]:
  1177. if key in to_load:
  1178. populator(state, dict_, row)
  1179. for key, populator in populators["eager"]:
  1180. if key not in unloaded:
  1181. populator(state, dict_, row)
  1182. return to_load
  1183. def _validate_version_id(mapper, state, dict_, row, getter):
  1184. if mapper._get_state_attr_by_column(
  1185. state, dict_, mapper.version_id_col
  1186. ) != getter(row):
  1187. raise orm_exc.StaleDataError(
  1188. "Instance '%s' has version id '%s' which "
  1189. "does not match database-loaded version id '%s'."
  1190. % (
  1191. state_str(state),
  1192. mapper._get_state_attr_by_column(
  1193. state, dict_, mapper.version_id_col
  1194. ),
  1195. getter(row),
  1196. )
  1197. )
  1198. def _decorate_polymorphic_switch(
  1199. instance_fn,
  1200. context,
  1201. query_entity,
  1202. mapper,
  1203. result,
  1204. path,
  1205. polymorphic_discriminator,
  1206. adapter,
  1207. ensure_no_pk,
  1208. ):
  1209. if polymorphic_discriminator is not None:
  1210. polymorphic_on = polymorphic_discriminator
  1211. else:
  1212. polymorphic_on = mapper.polymorphic_on
  1213. if polymorphic_on is None:
  1214. return instance_fn
  1215. if adapter:
  1216. polymorphic_on = adapter.columns[polymorphic_on]
  1217. def configure_subclass_mapper(discriminator):
  1218. try:
  1219. sub_mapper = mapper.polymorphic_map[discriminator]
  1220. except KeyError:
  1221. raise AssertionError(
  1222. "No such polymorphic_identity %r is defined" % discriminator
  1223. )
  1224. else:
  1225. if sub_mapper is mapper:
  1226. return None
  1227. elif not sub_mapper.isa(mapper):
  1228. return False
  1229. return _instance_processor(
  1230. query_entity,
  1231. sub_mapper,
  1232. context,
  1233. result,
  1234. path,
  1235. adapter,
  1236. _polymorphic_from=mapper,
  1237. )
  1238. polymorphic_instances = util.PopulateDict(configure_subclass_mapper)
  1239. getter = result._getter(polymorphic_on)
  1240. def polymorphic_instance(row):
  1241. discriminator = getter(row)
  1242. if discriminator is not None:
  1243. _instance = polymorphic_instances[discriminator]
  1244. if _instance:
  1245. return _instance(row)
  1246. elif _instance is False:
  1247. identitykey = ensure_no_pk(row)
  1248. if identitykey:
  1249. raise sa_exc.InvalidRequestError(
  1250. "Row with identity key %s can't be loaded into an "
  1251. "object; the polymorphic discriminator column '%s' "
  1252. "refers to %s, which is not a sub-mapper of "
  1253. "the requested %s"
  1254. % (
  1255. identitykey,
  1256. polymorphic_on,
  1257. mapper.polymorphic_map[discriminator],
  1258. mapper,
  1259. )
  1260. )
  1261. else:
  1262. return None
  1263. else:
  1264. return instance_fn(row)
  1265. else:
  1266. identitykey = ensure_no_pk(row)
  1267. if identitykey:
  1268. raise sa_exc.InvalidRequestError(
  1269. "Row with identity key %s can't be loaded into an "
  1270. "object; the polymorphic discriminator column '%s' is "
  1271. "NULL" % (identitykey, polymorphic_on)
  1272. )
  1273. else:
  1274. return None
  1275. return polymorphic_instance
  1276. class PostLoad:
  1277. """Track loaders and states for "post load" operations."""
  1278. __slots__ = "loaders", "states", "load_keys"
  1279. def __init__(self):
  1280. self.loaders = {}
  1281. self.states = util.OrderedDict()
  1282. self.load_keys = None
  1283. def add_state(self, state, overwrite):
  1284. # the states for a polymorphic load here are all shared
  1285. # within a single PostLoad object among multiple subtypes.
  1286. # Filtering of callables on a per-subclass basis needs to be done at
  1287. # the invocation level
  1288. self.states[state] = overwrite
  1289. def invoke(self, context, path):
  1290. if not self.states:
  1291. return
  1292. path = path_registry.PathRegistry.coerce(path)
  1293. for (
  1294. effective_context,
  1295. token,
  1296. limit_to_mapper,
  1297. loader,
  1298. arg,
  1299. kw,
  1300. ) in self.loaders.values():
  1301. states = [
  1302. (state, overwrite)
  1303. for state, overwrite in self.states.items()
  1304. if state.manager.mapper.isa(limit_to_mapper)
  1305. ]
  1306. if states:
  1307. loader(
  1308. effective_context, path, states, self.load_keys, *arg, **kw
  1309. )
  1310. self.states.clear()
  1311. @classmethod
  1312. def for_context(cls, context, path, only_load_props):
  1313. pl = context.post_load_paths.get(path.path)
  1314. if pl is not None and only_load_props:
  1315. pl.load_keys = only_load_props
  1316. return pl
  1317. @classmethod
  1318. def path_exists(self, context, path, key):
  1319. return (
  1320. path.path in context.post_load_paths
  1321. and key in context.post_load_paths[path.path].loaders
  1322. )
  1323. @classmethod
  1324. def callable_for_path(
  1325. cls, context, path, limit_to_mapper, token, loader_callable, *arg, **kw
  1326. ):
  1327. if path.path in context.post_load_paths:
  1328. pl = context.post_load_paths[path.path]
  1329. else:
  1330. pl = context.post_load_paths[path.path] = PostLoad()
  1331. pl.loaders[token] = (
  1332. context,
  1333. token,
  1334. limit_to_mapper,
  1335. loader_callable,
  1336. arg,
  1337. kw,
  1338. )
  1339. def load_scalar_attributes(mapper, state, attribute_names, passive):
  1340. """initiate a column-based attribute refresh operation."""
  1341. # assert mapper is _state_mapper(state)
  1342. session = state.session
  1343. if not session:
  1344. raise orm_exc.DetachedInstanceError(
  1345. "Instance %s is not bound to a Session; "
  1346. "attribute refresh operation cannot proceed" % (state_str(state))
  1347. )
  1348. no_autoflush = bool(passive & attributes.NO_AUTOFLUSH)
  1349. # in the case of inheritance, particularly concrete and abstract
  1350. # concrete inheritance, the class manager might have some keys
  1351. # of attributes on the superclass that we didn't actually map.
  1352. # These could be mapped as "concrete, don't load" or could be completely
  1353. # excluded from the mapping and we know nothing about them. Filter them
  1354. # here to prevent them from coming through.
  1355. if attribute_names:
  1356. attribute_names = attribute_names.intersection(mapper.attrs.keys())
  1357. if mapper.inherits and not mapper.concrete:
  1358. # load based on committed attributes in the object, formed into
  1359. # a truncated SELECT that only includes relevant tables. does not
  1360. # currently use state.key
  1361. statement = mapper._optimized_get_statement(state, attribute_names)
  1362. if statement is not None:
  1363. # undefer() isn't needed here because statement has the
  1364. # columns needed already, this implicitly undefers that column
  1365. stmt = FromStatement(mapper, statement)
  1366. return load_on_ident(
  1367. session,
  1368. stmt,
  1369. None,
  1370. only_load_props=attribute_names,
  1371. refresh_state=state,
  1372. no_autoflush=no_autoflush,
  1373. )
  1374. # normal load, use state.key as the identity to SELECT
  1375. has_key = bool(state.key)
  1376. if has_key:
  1377. identity_key = state.key
  1378. else:
  1379. # this codepath is rare - only valid when inside a flush, and the
  1380. # object is becoming persistent but hasn't yet been assigned
  1381. # an identity_key.
  1382. # check here to ensure we have the attrs we need.
  1383. pk_attrs = [
  1384. mapper._columntoproperty[col].key for col in mapper.primary_key
  1385. ]
  1386. if state.expired_attributes.intersection(pk_attrs):
  1387. raise sa_exc.InvalidRequestError(
  1388. "Instance %s cannot be refreshed - it's not "
  1389. " persistent and does not "
  1390. "contain a full primary key." % state_str(state)
  1391. )
  1392. identity_key = mapper._identity_key_from_state(state)
  1393. if (
  1394. _none_set.issubset(identity_key) and not mapper.allow_partial_pks
  1395. ) or _none_set.issuperset(identity_key):
  1396. util.warn_limited(
  1397. "Instance %s to be refreshed doesn't "
  1398. "contain a full primary key - can't be refreshed "
  1399. "(and shouldn't be expired, either).",
  1400. state_str(state),
  1401. )
  1402. return
  1403. result = load_on_ident(
  1404. session,
  1405. select(mapper).set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL),
  1406. identity_key,
  1407. refresh_state=state,
  1408. only_load_props=attribute_names,
  1409. no_autoflush=no_autoflush,
  1410. )
  1411. # if instance is pending, a refresh operation
  1412. # may not complete (even if PK attributes are assigned)
  1413. if has_key and result is None:
  1414. raise orm_exc.ObjectDeletedError(state)