loading.py 50 KB

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