MCPcopy Create free account
hub / github.com/sqlalchemy/sqlalchemy / merge_result

Function merge_result

lib/sqlalchemy/orm/loading.py:366–447  ·  view source on GitHub ↗

Merge a result into the given :class:`.Query` object's Session. See :meth:`_orm.Query.merge_result` for top-level documentation on this function.

(
    query: Query[Any],
    iterator: Union[FrozenResult, Iterable[Sequence[Any]], Iterable[object]],
    load: bool = True,
)

Source from the content-addressed store, hash-verified

364)
365@util.preload_module("sqlalchemy.orm.context")
366def merge_result(
367 query: Query[Any],
368 iterator: Union[FrozenResult, Iterable[Sequence[Any]], Iterable[object]],
369 load: bool = True,
370) -> Union[FrozenResult, Iterable[Any]]:
371 """Merge a result into the given :class:`.Query` object's Session.
372
373 See :meth:`_orm.Query.merge_result` for top-level documentation on this
374 function.
375
376 """
377
378 querycontext = util.preloaded.orm_context
379
380 session = query.session
381 if load:
382 # flush current contents if we expect to load data
383 session._autoflush()
384
385 # TODO: need test coverage and documentation for the FrozenResult
386 # use case.
387 if isinstance(iterator, FrozenResult):
388 frozen_result = iterator
389 iterator = iter(frozen_result.data)
390 else:
391 frozen_result = None
392
393 ctx = querycontext.ORMSelectCompileState._create_entities_collection(
394 query, legacy=True
395 )
396
397 autoflush = session.autoflush
398 try:
399 session.autoflush = False
400 single_entity = not frozen_result and len(ctx._entities) == 1
401
402 if single_entity:
403 if isinstance(ctx._entities[0], querycontext._MapperEntity):
404 result = [
405 session._merge(
406 attributes.instance_state(instance),
407 attributes.instance_dict(instance),
408 load=load,
409 _recursive={},
410 _resolve_conflict_map={},
411 )
412 for instance in iterator
413 ]
414 else:
415 result = list(iterator)
416 else:
417 mapped_entities = [
418 i
419 for i, e in enumerate(ctx._entities)
420 if isinstance(e, querycontext._MapperEntity)
421 ]
422 result = []
423 keys = [ent._label_name for ent in ctx._entities]

Callers

nothing calls this directly

Calls 6

result_tupleFunction · 0.85
_autoflushMethod · 0.80
with_new_rowsMethod · 0.80
_mergeMethod · 0.45
appendMethod · 0.45

Tested by

no test coverage detected