Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

1464 lignes
48KB

  1. # orm/loading.py
  2. # Copyright (C) 2005-2021 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: http://www.opensource.org/licenses/mit-license.php
  7. """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. _new_runid = util.counter()
  32. def instances(cursor, context):
  33. """Return a :class:`.Result` given an ORM query context.
  34. :param cursor: a :class:`.CursorResult`, generated by a statement
  35. which came from :class:`.ORMCompileState`
  36. :param context: a :class:`.QueryContext` object
  37. :return: a :class:`.Result` object representing ORM results
  38. .. versionchanged:: 1.4 The instances() function now uses
  39. :class:`.Result` objects and has an all new interface.
  40. """
  41. context.runid = _new_runid()
  42. context.post_load_paths = {}
  43. compile_state = context.compile_state
  44. filtered = compile_state._has_mapper_entities
  45. single_entity = (
  46. not context.load_options._only_return_tuples
  47. and len(compile_state._entities) == 1
  48. and compile_state._entities[0].supports_single_entity
  49. )
  50. try:
  51. (process, labels, extra) = list(
  52. zip(
  53. *[
  54. query_entity.row_processor(context, cursor)
  55. for query_entity in context.compile_state._entities
  56. ]
  57. )
  58. )
  59. if context.yield_per and (
  60. context.loaders_require_buffering
  61. or context.loaders_require_uniquing
  62. ):
  63. raise sa_exc.InvalidRequestError(
  64. "Can't use yield_per with eager loaders that require uniquing "
  65. "or row buffering, e.g. joinedload() against collections "
  66. "or subqueryload(). Consider the selectinload() strategy "
  67. "for better flexibility in loading objects."
  68. )
  69. except Exception:
  70. with util.safe_reraise():
  71. cursor.close()
  72. def _no_unique(entry):
  73. raise sa_exc.InvalidRequestError(
  74. "Can't use the ORM yield_per feature in conjunction with unique()"
  75. )
  76. row_metadata = SimpleResultMetaData(
  77. labels,
  78. extra,
  79. _unique_filters=[
  80. _no_unique
  81. if context.yield_per
  82. else id
  83. if ent.use_id_for_hash
  84. else None
  85. for ent in context.compile_state._entities
  86. ],
  87. )
  88. def chunks(size):
  89. while True:
  90. yield_per = size
  91. context.partials = {}
  92. if yield_per:
  93. fetch = cursor.fetchmany(yield_per)
  94. if not fetch:
  95. break
  96. else:
  97. fetch = cursor._raw_all_rows()
  98. if single_entity:
  99. proc = process[0]
  100. rows = [proc(row) for row in fetch]
  101. else:
  102. rows = [
  103. tuple([proc(row) for proc in process]) for row in fetch
  104. ]
  105. for path, post_load in context.post_load_paths.items():
  106. post_load.invoke(context, path)
  107. yield rows
  108. if not yield_per:
  109. break
  110. if context.execution_options.get("prebuffer_rows", False):
  111. # this is a bit of a hack at the moment.
  112. # I would rather have some option in the result to pre-buffer
  113. # internally.
  114. _prebuffered = list(chunks(None))
  115. def chunks(size):
  116. return iter(_prebuffered)
  117. result = ChunkedIteratorResult(
  118. row_metadata,
  119. chunks,
  120. source_supports_scalars=single_entity,
  121. raw=cursor,
  122. dynamic_yield_per=cursor.context._is_server_side,
  123. )
  124. # filtered and single_entity are used to indicate to legacy Query that the
  125. # query has ORM entities, so legacy deduping and scalars should be called
  126. # on the result.
  127. result._attributes = result._attributes.union(
  128. dict(filtered=filtered, is_single_entity=single_entity)
  129. )
  130. # multi_row_eager_loaders OTOH is specific to joinedload.
  131. if context.compile_state.multi_row_eager_loaders:
  132. def require_unique(obj):
  133. raise sa_exc.InvalidRequestError(
  134. "The unique() method must be invoked on this Result, "
  135. "as it contains results that include joined eager loads "
  136. "against collections"
  137. )
  138. result._unique_filter_state = (None, require_unique)
  139. if context.yield_per:
  140. result.yield_per(context.yield_per)
  141. return result
  142. @util.preload_module("sqlalchemy.orm.context")
  143. def merge_frozen_result(session, statement, frozen_result, load=True):
  144. """Merge a :class:`_engine.FrozenResult` back into a :class:`_orm.Session`,
  145. returning a new :class:`_engine.Result` object with :term:`persistent`
  146. objects.
  147. See the section :ref:`do_orm_execute_re_executing` for an example.
  148. .. seealso::
  149. :ref:`do_orm_execute_re_executing`
  150. :meth:`_engine.Result.freeze`
  151. :class:`_engine.FrozenResult`
  152. """
  153. querycontext = util.preloaded.orm_context
  154. if load:
  155. # flush current contents if we expect to load data
  156. session._autoflush()
  157. ctx = querycontext.ORMSelectCompileState._create_entities_collection(
  158. statement, legacy=False
  159. )
  160. autoflush = session.autoflush
  161. try:
  162. session.autoflush = False
  163. mapped_entities = [
  164. i
  165. for i, e in enumerate(ctx._entities)
  166. if isinstance(e, querycontext._MapperEntity)
  167. ]
  168. keys = [ent._label_name for ent in ctx._entities]
  169. keyed_tuple = result_tuple(
  170. keys, [ent._extra_entities for ent in ctx._entities]
  171. )
  172. result = []
  173. for newrow in frozen_result.rewrite_rows():
  174. for i in mapped_entities:
  175. if newrow[i] is not None:
  176. newrow[i] = session._merge(
  177. attributes.instance_state(newrow[i]),
  178. attributes.instance_dict(newrow[i]),
  179. load=load,
  180. _recursive={},
  181. _resolve_conflict_map={},
  182. )
  183. result.append(keyed_tuple(newrow))
  184. return frozen_result.with_new_rows(result)
  185. finally:
  186. session.autoflush = autoflush
  187. @util.deprecated(
  188. "2.0",
  189. "The :func:`_orm.merge_result` method is superseded by the "
  190. ":func:`_orm.merge_frozen_result` function.",
  191. )
  192. @util.preload_module("sqlalchemy.orm.context")
  193. def merge_result(query, iterator, load=True):
  194. """Merge a result into this :class:`.Query` object's Session."""
  195. querycontext = util.preloaded.orm_context
  196. session = query.session
  197. if load:
  198. # flush current contents if we expect to load data
  199. session._autoflush()
  200. # TODO: need test coverage and documentation for the FrozenResult
  201. # use case.
  202. if isinstance(iterator, FrozenResult):
  203. frozen_result = iterator
  204. iterator = iter(frozen_result.data)
  205. else:
  206. frozen_result = None
  207. ctx = querycontext.ORMSelectCompileState._create_entities_collection(
  208. query, legacy=True
  209. )
  210. autoflush = session.autoflush
  211. try:
  212. session.autoflush = False
  213. single_entity = not frozen_result and len(ctx._entities) == 1
  214. if single_entity:
  215. if isinstance(ctx._entities[0], querycontext._MapperEntity):
  216. result = [
  217. session._merge(
  218. attributes.instance_state(instance),
  219. attributes.instance_dict(instance),
  220. load=load,
  221. _recursive={},
  222. _resolve_conflict_map={},
  223. )
  224. for instance in iterator
  225. ]
  226. else:
  227. result = list(iterator)
  228. else:
  229. mapped_entities = [
  230. i
  231. for i, e in enumerate(ctx._entities)
  232. if isinstance(e, querycontext._MapperEntity)
  233. ]
  234. result = []
  235. keys = [ent._label_name for ent in ctx._entities]
  236. keyed_tuple = result_tuple(
  237. keys, [ent._extra_entities for ent in ctx._entities]
  238. )
  239. for row in iterator:
  240. newrow = list(row)
  241. for i in mapped_entities:
  242. if newrow[i] is not None:
  243. newrow[i] = session._merge(
  244. attributes.instance_state(newrow[i]),
  245. attributes.instance_dict(newrow[i]),
  246. load=load,
  247. _recursive={},
  248. _resolve_conflict_map={},
  249. )
  250. result.append(keyed_tuple(newrow))
  251. if frozen_result:
  252. return frozen_result.with_data(result)
  253. else:
  254. return iter(result)
  255. finally:
  256. session.autoflush = autoflush
  257. def get_from_identity(session, mapper, key, passive):
  258. """Look up the given key in the given session's identity map,
  259. check the object for expired state if found.
  260. """
  261. instance = session.identity_map.get(key)
  262. if instance is not None:
  263. state = attributes.instance_state(instance)
  264. if mapper.inherits and not state.mapper.isa(mapper):
  265. return attributes.PASSIVE_CLASS_MISMATCH
  266. # expired - ensure it still exists
  267. if state.expired:
  268. if not passive & attributes.SQL_OK:
  269. # TODO: no coverage here
  270. return attributes.PASSIVE_NO_RESULT
  271. elif not passive & attributes.RELATED_OBJECT_OK:
  272. # this mode is used within a flush and the instance's
  273. # expired state will be checked soon enough, if necessary.
  274. # also used by immediateloader for a mutually-dependent
  275. # o2m->m2m load, :ticket:`6301`
  276. return instance
  277. try:
  278. state._load_expired(state, passive)
  279. except orm_exc.ObjectDeletedError:
  280. session._remove_newly_deleted([state])
  281. return None
  282. return instance
  283. else:
  284. return None
  285. def load_on_ident(
  286. session,
  287. statement,
  288. key,
  289. load_options=None,
  290. refresh_state=None,
  291. with_for_update=None,
  292. only_load_props=None,
  293. no_autoflush=False,
  294. bind_arguments=util.EMPTY_DICT,
  295. execution_options=util.EMPTY_DICT,
  296. ):
  297. """Load the given identity key from the database."""
  298. if key is not None:
  299. ident = key[1]
  300. identity_token = key[2]
  301. else:
  302. ident = identity_token = None
  303. return load_on_pk_identity(
  304. session,
  305. statement,
  306. ident,
  307. load_options=load_options,
  308. refresh_state=refresh_state,
  309. with_for_update=with_for_update,
  310. only_load_props=only_load_props,
  311. identity_token=identity_token,
  312. no_autoflush=no_autoflush,
  313. bind_arguments=bind_arguments,
  314. execution_options=execution_options,
  315. )
  316. def load_on_pk_identity(
  317. session,
  318. statement,
  319. primary_key_identity,
  320. load_options=None,
  321. refresh_state=None,
  322. with_for_update=None,
  323. only_load_props=None,
  324. identity_token=None,
  325. no_autoflush=False,
  326. bind_arguments=util.EMPTY_DICT,
  327. execution_options=util.EMPTY_DICT,
  328. ):
  329. """Load the given primary key identity from the database."""
  330. query = statement
  331. q = query._clone()
  332. is_lambda = q._is_lambda_element
  333. # TODO: fix these imports ....
  334. from .context import QueryContext, ORMCompileState
  335. if load_options is None:
  336. load_options = QueryContext.default_load_options
  337. compile_options = ORMCompileState.default_compile_options
  338. if primary_key_identity is not None:
  339. mapper = query._propagate_attrs["plugin_subject"]
  340. (_get_clause, _get_params) = mapper._get_clause
  341. # None present in ident - turn those comparisons
  342. # into "IS NULL"
  343. if None in primary_key_identity:
  344. nones = set(
  345. [
  346. _get_params[col].key
  347. for col, value in zip(
  348. mapper.primary_key, primary_key_identity
  349. )
  350. if value is None
  351. ]
  352. )
  353. _get_clause = sql_util.adapt_criterion_to_null(_get_clause, nones)
  354. if len(nones) == len(primary_key_identity):
  355. util.warn(
  356. "fully NULL primary key identity cannot load any "
  357. "object. This condition may raise an error in a future "
  358. "release."
  359. )
  360. if is_lambda:
  361. q = q.add_criteria(
  362. lambda q: q.where(
  363. sql_util._deep_annotate(_get_clause, {"_orm_adapt": True})
  364. ),
  365. # this track_on will allow the lambda to refresh if
  366. # _get_clause goes stale due to reconfigured mapper.
  367. # however, it's not needed as the lambda otherwise tracks
  368. # on the SQL cache key of the expression. the main thing
  369. # is that the bindparam.key stays the same if the cache key
  370. # stays the same, as we are referring to the .key explicitly
  371. # in the params.
  372. # track_on=[id(_get_clause)]
  373. )
  374. else:
  375. q._where_criteria = (
  376. sql_util._deep_annotate(_get_clause, {"_orm_adapt": True}),
  377. )
  378. params = dict(
  379. [
  380. (_get_params[primary_key].key, id_val)
  381. for id_val, primary_key in zip(
  382. primary_key_identity, mapper.primary_key
  383. )
  384. ]
  385. )
  386. else:
  387. params = None
  388. if is_lambda:
  389. if with_for_update is not None or refresh_state or only_load_props:
  390. raise NotImplementedError(
  391. "refresh operation not supported with lambda statement"
  392. )
  393. version_check = False
  394. _, load_options = _set_get_options(
  395. compile_options,
  396. load_options,
  397. version_check=version_check,
  398. only_load_props=only_load_props,
  399. refresh_state=refresh_state,
  400. identity_token=identity_token,
  401. )
  402. if no_autoflush:
  403. load_options += {"_autoflush": False}
  404. else:
  405. if with_for_update is not None:
  406. version_check = True
  407. q._for_update_arg = with_for_update
  408. elif query._for_update_arg is not None:
  409. version_check = True
  410. q._for_update_arg = query._for_update_arg
  411. else:
  412. version_check = False
  413. if refresh_state and refresh_state.load_options:
  414. compile_options += {
  415. "_current_path": refresh_state.load_path.parent
  416. }
  417. q = q.options(*refresh_state.load_options)
  418. # TODO: most of the compile_options that are not legacy only involve
  419. # this function, so try to see if handling of them can mostly be local
  420. # to here
  421. q._compile_options, load_options = _set_get_options(
  422. compile_options,
  423. load_options,
  424. version_check=version_check,
  425. only_load_props=only_load_props,
  426. refresh_state=refresh_state,
  427. identity_token=identity_token,
  428. )
  429. q._order_by = None
  430. if no_autoflush:
  431. load_options += {"_autoflush": False}
  432. execution_options = util.EMPTY_DICT.merge_with(
  433. execution_options, {"_sa_orm_load_options": load_options}
  434. )
  435. result = (
  436. session.execute(
  437. q,
  438. params=params,
  439. execution_options=execution_options,
  440. bind_arguments=bind_arguments,
  441. )
  442. .unique()
  443. .scalars()
  444. )
  445. try:
  446. return result.one()
  447. except orm_exc.NoResultFound:
  448. return None
  449. def _set_get_options(
  450. compile_opt,
  451. load_opt,
  452. populate_existing=None,
  453. version_check=None,
  454. only_load_props=None,
  455. refresh_state=None,
  456. identity_token=None,
  457. ):
  458. compile_options = {}
  459. load_options = {}
  460. if version_check:
  461. load_options["_version_check"] = version_check
  462. if populate_existing:
  463. load_options["_populate_existing"] = populate_existing
  464. if refresh_state:
  465. load_options["_refresh_state"] = refresh_state
  466. compile_options["_for_refresh_state"] = True
  467. if only_load_props:
  468. compile_options["_only_load_props"] = frozenset(only_load_props)
  469. if identity_token:
  470. load_options["_refresh_identity_token"] = identity_token
  471. if load_options:
  472. load_opt += load_options
  473. if compile_options:
  474. compile_opt += compile_options
  475. return compile_opt, load_opt
  476. def _setup_entity_query(
  477. compile_state,
  478. mapper,
  479. query_entity,
  480. path,
  481. adapter,
  482. column_collection,
  483. with_polymorphic=None,
  484. only_load_props=None,
  485. polymorphic_discriminator=None,
  486. **kw
  487. ):
  488. if with_polymorphic:
  489. poly_properties = mapper._iterate_polymorphic_properties(
  490. with_polymorphic
  491. )
  492. else:
  493. poly_properties = mapper._polymorphic_properties
  494. quick_populators = {}
  495. path.set(compile_state.attributes, "memoized_setups", quick_populators)
  496. # for the lead entities in the path, e.g. not eager loads, and
  497. # assuming a user-passed aliased class, e.g. not a from_self() or any
  498. # implicit aliasing, don't add columns to the SELECT that aren't
  499. # in the thing that's aliased.
  500. check_for_adapt = adapter and len(path) == 1 and path[-1].is_aliased_class
  501. for value in poly_properties:
  502. if only_load_props and value.key not in only_load_props:
  503. continue
  504. value.setup(
  505. compile_state,
  506. query_entity,
  507. path,
  508. adapter,
  509. only_load_props=only_load_props,
  510. column_collection=column_collection,
  511. memoized_populators=quick_populators,
  512. check_for_adapt=check_for_adapt,
  513. **kw
  514. )
  515. if (
  516. polymorphic_discriminator is not None
  517. and polymorphic_discriminator is not mapper.polymorphic_on
  518. ):
  519. if adapter:
  520. pd = adapter.columns[polymorphic_discriminator]
  521. else:
  522. pd = polymorphic_discriminator
  523. column_collection.append(pd)
  524. def _warn_for_runid_changed(state):
  525. util.warn(
  526. "Loading context for %s has changed within a load/refresh "
  527. "handler, suggesting a row refresh operation took place. If this "
  528. "event handler is expected to be "
  529. "emitting row refresh operations within an existing load or refresh "
  530. "operation, set restore_load_context=True when establishing the "
  531. "listener to ensure the context remains unchanged when the event "
  532. "handler completes." % (state_str(state),)
  533. )
  534. def _instance_processor(
  535. query_entity,
  536. mapper,
  537. context,
  538. result,
  539. path,
  540. adapter,
  541. only_load_props=None,
  542. refresh_state=None,
  543. polymorphic_discriminator=None,
  544. _polymorphic_from=None,
  545. ):
  546. """Produce a mapper level row processor callable
  547. which processes rows into mapped instances."""
  548. # note that this method, most of which exists in a closure
  549. # called _instance(), resists being broken out, as
  550. # attempts to do so tend to add significant function
  551. # call overhead. _instance() is the most
  552. # performance-critical section in the whole ORM.
  553. identity_class = mapper._identity_class
  554. compile_state = context.compile_state
  555. # look for "row getter" functions that have been assigned along
  556. # with the compile state that were cached from a previous load.
  557. # these are operator.itemgetter() objects that each will extract a
  558. # particular column from each row.
  559. getter_key = ("getters", mapper)
  560. getters = path.get(compile_state.attributes, getter_key, None)
  561. if getters is None:
  562. # no getters, so go through a list of attributes we are loading for,
  563. # and the ones that are column based will have already put information
  564. # for us in another collection "memoized_setups", which represents the
  565. # output of the LoaderStrategy.setup_query() method. We can just as
  566. # easily call LoaderStrategy.create_row_processor for each, but by
  567. # getting it all at once from setup_query we save another method call
  568. # per attribute.
  569. props = mapper._prop_set
  570. if only_load_props is not None:
  571. props = props.intersection(
  572. mapper._props[k] for k in only_load_props
  573. )
  574. quick_populators = path.get(
  575. context.attributes, "memoized_setups", _none_set
  576. )
  577. todo = []
  578. cached_populators = {
  579. "new": [],
  580. "quick": [],
  581. "deferred": [],
  582. "expire": [],
  583. "delayed": [],
  584. "existing": [],
  585. "eager": [],
  586. }
  587. if refresh_state is None:
  588. # we can also get the "primary key" tuple getter function
  589. pk_cols = mapper.primary_key
  590. if adapter:
  591. pk_cols = [adapter.columns[c] for c in pk_cols]
  592. primary_key_getter = result._tuple_getter(pk_cols)
  593. else:
  594. primary_key_getter = None
  595. getters = {
  596. "cached_populators": cached_populators,
  597. "todo": todo,
  598. "primary_key_getter": primary_key_getter,
  599. }
  600. for prop in props:
  601. if prop in quick_populators:
  602. # this is an inlined path just for column-based attributes.
  603. col = quick_populators[prop]
  604. if col is _DEFER_FOR_STATE:
  605. cached_populators["new"].append(
  606. (prop.key, prop._deferred_column_loader)
  607. )
  608. elif col is _SET_DEFERRED_EXPIRED:
  609. # note that in this path, we are no longer
  610. # searching in the result to see if the column might
  611. # be present in some unexpected way.
  612. cached_populators["expire"].append((prop.key, False))
  613. elif col is _RAISE_FOR_STATE:
  614. cached_populators["new"].append(
  615. (prop.key, prop._raise_column_loader)
  616. )
  617. else:
  618. getter = None
  619. if adapter:
  620. # this logic had been removed for all 1.4 releases
  621. # up until 1.4.18; the adapter here is particularly
  622. # the compound eager adapter which isn't accommodated
  623. # in the quick_populators right now. The "fallback"
  624. # logic below instead took over in many more cases
  625. # until issue #6596 was identified.
  626. # note there is still an issue where this codepath
  627. # produces no "getter" for cases where a joined-inh
  628. # mapping includes a labeled column property, meaning
  629. # KeyError is caught internally and we fall back to
  630. # _getter(col), which works anyway. The adapter
  631. # here for joined inh without any aliasing might not
  632. # be useful. Tests which see this include
  633. # test.orm.inheritance.test_basic ->
  634. # EagerTargetingTest.test_adapt_stringency
  635. # OptimizedLoadTest.test_column_expression_joined
  636. # PolymorphicOnNotLocalTest.test_polymorphic_on_column_prop # noqa E501
  637. #
  638. adapted_col = adapter.columns[col]
  639. if adapted_col is not None:
  640. getter = result._getter(adapted_col, False)
  641. if not getter:
  642. getter = result._getter(col, False)
  643. if getter:
  644. cached_populators["quick"].append((prop.key, getter))
  645. else:
  646. # fall back to the ColumnProperty itself, which
  647. # will iterate through all of its columns
  648. # to see if one fits
  649. prop.create_row_processor(
  650. context,
  651. query_entity,
  652. path,
  653. mapper,
  654. result,
  655. adapter,
  656. cached_populators,
  657. )
  658. else:
  659. # loader strategies like subqueryload, selectinload,
  660. # joinedload, basically relationships, these need to interact
  661. # with the context each time to work correctly.
  662. todo.append(prop)
  663. path.set(compile_state.attributes, getter_key, getters)
  664. cached_populators = getters["cached_populators"]
  665. populators = {key: list(value) for key, value in cached_populators.items()}
  666. for prop in getters["todo"]:
  667. prop.create_row_processor(
  668. context, query_entity, path, mapper, result, adapter, populators
  669. )
  670. propagated_loader_options = context.propagated_loader_options
  671. load_path = (
  672. context.compile_state.current_path + path
  673. if context.compile_state.current_path.path
  674. else path
  675. )
  676. session_identity_map = context.session.identity_map
  677. populate_existing = context.populate_existing or mapper.always_refresh
  678. load_evt = bool(mapper.class_manager.dispatch.load)
  679. refresh_evt = bool(mapper.class_manager.dispatch.refresh)
  680. persistent_evt = bool(context.session.dispatch.loaded_as_persistent)
  681. if persistent_evt:
  682. loaded_as_persistent = context.session.dispatch.loaded_as_persistent
  683. instance_state = attributes.instance_state
  684. instance_dict = attributes.instance_dict
  685. session_id = context.session.hash_key
  686. runid = context.runid
  687. identity_token = context.identity_token
  688. version_check = context.version_check
  689. if version_check:
  690. version_id_col = mapper.version_id_col
  691. if version_id_col is not None:
  692. if adapter:
  693. version_id_col = adapter.columns[version_id_col]
  694. version_id_getter = result._getter(version_id_col)
  695. else:
  696. version_id_getter = None
  697. if not refresh_state and _polymorphic_from is not None:
  698. key = ("loader", path.path)
  699. if key in context.attributes and context.attributes[key].strategy == (
  700. ("selectinload_polymorphic", True),
  701. ):
  702. selectin_load_via = mapper._should_selectin_load(
  703. context.attributes[key].local_opts["entities"],
  704. _polymorphic_from,
  705. )
  706. else:
  707. selectin_load_via = mapper._should_selectin_load(
  708. None, _polymorphic_from
  709. )
  710. if selectin_load_via and selectin_load_via is not _polymorphic_from:
  711. # only_load_props goes w/ refresh_state only, and in a refresh
  712. # we are a single row query for the exact entity; polymorphic
  713. # loading does not apply
  714. assert only_load_props is None
  715. callable_ = _load_subclass_via_in(context, path, selectin_load_via)
  716. PostLoad.callable_for_path(
  717. context,
  718. load_path,
  719. selectin_load_via.mapper,
  720. selectin_load_via,
  721. callable_,
  722. selectin_load_via,
  723. )
  724. post_load = PostLoad.for_context(context, load_path, only_load_props)
  725. if refresh_state:
  726. refresh_identity_key = refresh_state.key
  727. if refresh_identity_key is None:
  728. # super-rare condition; a refresh is being called
  729. # on a non-instance-key instance; this is meant to only
  730. # occur within a flush()
  731. refresh_identity_key = mapper._identity_key_from_state(
  732. refresh_state
  733. )
  734. else:
  735. refresh_identity_key = None
  736. primary_key_getter = getters["primary_key_getter"]
  737. if mapper.allow_partial_pks:
  738. is_not_primary_key = _none_set.issuperset
  739. else:
  740. is_not_primary_key = _none_set.intersection
  741. def _instance(row):
  742. # determine the state that we'll be populating
  743. if refresh_identity_key:
  744. # fixed state that we're refreshing
  745. state = refresh_state
  746. instance = state.obj()
  747. dict_ = instance_dict(instance)
  748. isnew = state.runid != runid
  749. currentload = True
  750. loaded_instance = False
  751. else:
  752. # look at the row, see if that identity is in the
  753. # session, or we have to create a new one
  754. identitykey = (
  755. identity_class,
  756. primary_key_getter(row),
  757. identity_token,
  758. )
  759. instance = session_identity_map.get(identitykey)
  760. if instance is not None:
  761. # existing instance
  762. state = instance_state(instance)
  763. dict_ = instance_dict(instance)
  764. isnew = state.runid != runid
  765. currentload = not isnew
  766. loaded_instance = False
  767. if version_check and version_id_getter and not currentload:
  768. _validate_version_id(
  769. mapper, state, dict_, row, version_id_getter
  770. )
  771. else:
  772. # create a new instance
  773. # check for non-NULL values in the primary key columns,
  774. # else no entity is returned for the row
  775. if is_not_primary_key(identitykey[1]):
  776. return None
  777. isnew = True
  778. currentload = True
  779. loaded_instance = True
  780. instance = mapper.class_manager.new_instance()
  781. dict_ = instance_dict(instance)
  782. state = instance_state(instance)
  783. state.key = identitykey
  784. state.identity_token = identity_token
  785. # attach instance to session.
  786. state.session_id = session_id
  787. session_identity_map._add_unpresent(state, identitykey)
  788. effective_populate_existing = populate_existing
  789. if refresh_state is state:
  790. effective_populate_existing = True
  791. # populate. this looks at whether this state is new
  792. # for this load or was existing, and whether or not this
  793. # row is the first row with this identity.
  794. if currentload or effective_populate_existing:
  795. # full population routines. Objects here are either
  796. # just created, or we are doing a populate_existing
  797. # be conservative about setting load_path when populate_existing
  798. # is in effect; want to maintain options from the original
  799. # load. see test_expire->test_refresh_maintains_deferred_options
  800. if isnew and (
  801. propagated_loader_options or not effective_populate_existing
  802. ):
  803. state.load_options = propagated_loader_options
  804. state.load_path = load_path
  805. _populate_full(
  806. context,
  807. row,
  808. state,
  809. dict_,
  810. isnew,
  811. load_path,
  812. loaded_instance,
  813. effective_populate_existing,
  814. populators,
  815. )
  816. if isnew:
  817. # state.runid should be equal to context.runid / runid
  818. # here, however for event checks we are being more conservative
  819. # and checking against existing run id
  820. # assert state.runid == runid
  821. existing_runid = state.runid
  822. if loaded_instance:
  823. if load_evt:
  824. state.manager.dispatch.load(state, context)
  825. if state.runid != existing_runid:
  826. _warn_for_runid_changed(state)
  827. if persistent_evt:
  828. loaded_as_persistent(context.session, state)
  829. if state.runid != existing_runid:
  830. _warn_for_runid_changed(state)
  831. elif refresh_evt:
  832. state.manager.dispatch.refresh(
  833. state, context, only_load_props
  834. )
  835. if state.runid != runid:
  836. _warn_for_runid_changed(state)
  837. if effective_populate_existing or state.modified:
  838. if refresh_state and only_load_props:
  839. state._commit(dict_, only_load_props)
  840. else:
  841. state._commit_all(dict_, session_identity_map)
  842. if post_load:
  843. post_load.add_state(state, True)
  844. else:
  845. # partial population routines, for objects that were already
  846. # in the Session, but a row matches them; apply eager loaders
  847. # on existing objects, etc.
  848. unloaded = state.unloaded
  849. isnew = state not in context.partials
  850. if not isnew or unloaded or populators["eager"]:
  851. # state is having a partial set of its attributes
  852. # refreshed. Populate those attributes,
  853. # and add to the "context.partials" collection.
  854. to_load = _populate_partial(
  855. context,
  856. row,
  857. state,
  858. dict_,
  859. isnew,
  860. load_path,
  861. unloaded,
  862. populators,
  863. )
  864. if isnew:
  865. if refresh_evt:
  866. existing_runid = state.runid
  867. state.manager.dispatch.refresh(state, context, to_load)
  868. if state.runid != existing_runid:
  869. _warn_for_runid_changed(state)
  870. state._commit(dict_, to_load)
  871. if post_load and context.invoke_all_eagers:
  872. post_load.add_state(state, False)
  873. return instance
  874. if mapper.polymorphic_map and not _polymorphic_from and not refresh_state:
  875. # if we are doing polymorphic, dispatch to a different _instance()
  876. # method specific to the subclass mapper
  877. def ensure_no_pk(row):
  878. identitykey = (
  879. identity_class,
  880. primary_key_getter(row),
  881. identity_token,
  882. )
  883. if not is_not_primary_key(identitykey[1]):
  884. return identitykey
  885. else:
  886. return None
  887. _instance = _decorate_polymorphic_switch(
  888. _instance,
  889. context,
  890. query_entity,
  891. mapper,
  892. result,
  893. path,
  894. polymorphic_discriminator,
  895. adapter,
  896. ensure_no_pk,
  897. )
  898. return _instance
  899. def _load_subclass_via_in(context, path, entity):
  900. mapper = entity.mapper
  901. zero_idx = len(mapper.base_mapper.primary_key) == 1
  902. if entity.is_aliased_class:
  903. q, enable_opt, disable_opt = mapper._subclass_load_via_in(entity)
  904. else:
  905. q, enable_opt, disable_opt = mapper._subclass_load_via_in_mapper
  906. def do_load(context, path, states, load_only, effective_entity):
  907. orig_query = context.query
  908. q2 = q._with_lazyload_options(
  909. (enable_opt,) + orig_query._with_options + (disable_opt,),
  910. path.parent,
  911. cache_path=path,
  912. )
  913. if context.populate_existing:
  914. q2.add_criteria(lambda q: q.populate_existing())
  915. q2(context.session).params(
  916. primary_keys=[
  917. state.key[1][0] if zero_idx else state.key[1]
  918. for state, load_attrs in states
  919. ]
  920. ).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)