unitofwork.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796
  1. # orm/unitofwork.py
  2. # Copyright (C) 2005-2025 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: https://www.opensource.org/licenses/mit-license.php
  7. # mypy: ignore-errors
  8. """The internals for the unit of work system.
  9. The session's flush() process passes objects to a contextual object
  10. here, which assembles flush tasks based on mappers and their properties,
  11. organizes them in order of dependency, and executes.
  12. """
  13. from __future__ import annotations
  14. from typing import Any
  15. from typing import Dict
  16. from typing import Optional
  17. from typing import Set
  18. from typing import TYPE_CHECKING
  19. from . import attributes
  20. from . import exc as orm_exc
  21. from . import util as orm_util
  22. from .. import event
  23. from .. import util
  24. from ..util import topological
  25. if TYPE_CHECKING:
  26. from .dependency import DependencyProcessor
  27. from .interfaces import MapperProperty
  28. from .mapper import Mapper
  29. from .session import Session
  30. from .session import SessionTransaction
  31. from .state import InstanceState
  32. def track_cascade_events(descriptor, prop):
  33. """Establish event listeners on object attributes which handle
  34. cascade-on-set/append.
  35. """
  36. key = prop.key
  37. def append(state, item, initiator, **kw):
  38. # process "save_update" cascade rules for when
  39. # an instance is appended to the list of another instance
  40. if item is None:
  41. return
  42. sess = state.session
  43. if sess:
  44. if sess._warn_on_events:
  45. sess._flush_warning("collection append")
  46. prop = state.manager.mapper._props[key]
  47. item_state = attributes.instance_state(item)
  48. if (
  49. prop._cascade.save_update
  50. and (key == initiator.key)
  51. and not sess._contains_state(item_state)
  52. ):
  53. sess._save_or_update_state(item_state)
  54. return item
  55. def remove(state, item, initiator, **kw):
  56. if item is None:
  57. return
  58. sess = state.session
  59. prop = state.manager.mapper._props[key]
  60. if sess and sess._warn_on_events:
  61. sess._flush_warning(
  62. "collection remove"
  63. if prop.uselist
  64. else "related attribute delete"
  65. )
  66. if (
  67. item is not None
  68. and item is not attributes.NEVER_SET
  69. and item is not attributes.PASSIVE_NO_RESULT
  70. and prop._cascade.delete_orphan
  71. ):
  72. # expunge pending orphans
  73. item_state = attributes.instance_state(item)
  74. if prop.mapper._is_orphan(item_state):
  75. if sess and item_state in sess._new:
  76. sess.expunge(item)
  77. else:
  78. # the related item may or may not itself be in a
  79. # Session, however the parent for which we are catching
  80. # the event is not in a session, so memoize this on the
  81. # item
  82. item_state._orphaned_outside_of_session = True
  83. def set_(state, newvalue, oldvalue, initiator, **kw):
  84. # process "save_update" cascade rules for when an instance
  85. # is attached to another instance
  86. if oldvalue is newvalue:
  87. return newvalue
  88. sess = state.session
  89. if sess:
  90. if sess._warn_on_events:
  91. sess._flush_warning("related attribute set")
  92. prop = state.manager.mapper._props[key]
  93. if newvalue is not None:
  94. newvalue_state = attributes.instance_state(newvalue)
  95. if (
  96. prop._cascade.save_update
  97. and (key == initiator.key)
  98. and not sess._contains_state(newvalue_state)
  99. ):
  100. sess._save_or_update_state(newvalue_state)
  101. if (
  102. oldvalue is not None
  103. and oldvalue is not attributes.NEVER_SET
  104. and oldvalue is not attributes.PASSIVE_NO_RESULT
  105. and prop._cascade.delete_orphan
  106. ):
  107. # possible to reach here with attributes.NEVER_SET ?
  108. oldvalue_state = attributes.instance_state(oldvalue)
  109. if oldvalue_state in sess._new and prop.mapper._is_orphan(
  110. oldvalue_state
  111. ):
  112. sess.expunge(oldvalue)
  113. return newvalue
  114. event.listen(
  115. descriptor, "append_wo_mutation", append, raw=True, include_key=True
  116. )
  117. event.listen(
  118. descriptor, "append", append, raw=True, retval=True, include_key=True
  119. )
  120. event.listen(
  121. descriptor, "remove", remove, raw=True, retval=True, include_key=True
  122. )
  123. event.listen(
  124. descriptor, "set", set_, raw=True, retval=True, include_key=True
  125. )
  126. class UOWTransaction:
  127. session: Session
  128. transaction: SessionTransaction
  129. attributes: Dict[str, Any]
  130. deps: util.defaultdict[Mapper[Any], Set[DependencyProcessor]]
  131. mappers: util.defaultdict[Mapper[Any], Set[InstanceState[Any]]]
  132. def __init__(self, session: Session):
  133. self.session = session
  134. # dictionary used by external actors to
  135. # store arbitrary state information.
  136. self.attributes = {}
  137. # dictionary of mappers to sets of
  138. # DependencyProcessors, which are also
  139. # set to be part of the sorted flush actions,
  140. # which have that mapper as a parent.
  141. self.deps = util.defaultdict(set)
  142. # dictionary of mappers to sets of InstanceState
  143. # items pending for flush which have that mapper
  144. # as a parent.
  145. self.mappers = util.defaultdict(set)
  146. # a dictionary of Preprocess objects, which gather
  147. # additional states impacted by the flush
  148. # and determine if a flush action is needed
  149. self.presort_actions = {}
  150. # dictionary of PostSortRec objects, each
  151. # one issues work during the flush within
  152. # a certain ordering.
  153. self.postsort_actions = {}
  154. # a set of 2-tuples, each containing two
  155. # PostSortRec objects where the second
  156. # is dependent on the first being executed
  157. # first
  158. self.dependencies = set()
  159. # dictionary of InstanceState-> (isdelete, listonly)
  160. # tuples, indicating if this state is to be deleted
  161. # or insert/updated, or just refreshed
  162. self.states = {}
  163. # tracks InstanceStates which will be receiving
  164. # a "post update" call. Keys are mappers,
  165. # values are a set of states and a set of the
  166. # columns which should be included in the update.
  167. self.post_update_states = util.defaultdict(lambda: (set(), set()))
  168. @property
  169. def has_work(self):
  170. return bool(self.states)
  171. def was_already_deleted(self, state):
  172. """Return ``True`` if the given state is expired and was deleted
  173. previously.
  174. """
  175. if state.expired:
  176. try:
  177. state._load_expired(state, attributes.PASSIVE_OFF)
  178. except orm_exc.ObjectDeletedError:
  179. self.session._remove_newly_deleted([state])
  180. return True
  181. return False
  182. def is_deleted(self, state):
  183. """Return ``True`` if the given state is marked as deleted
  184. within this uowtransaction."""
  185. return state in self.states and self.states[state][0]
  186. def memo(self, key, callable_):
  187. if key in self.attributes:
  188. return self.attributes[key]
  189. else:
  190. self.attributes[key] = ret = callable_()
  191. return ret
  192. def remove_state_actions(self, state):
  193. """Remove pending actions for a state from the uowtransaction."""
  194. isdelete = self.states[state][0]
  195. self.states[state] = (isdelete, True)
  196. def get_attribute_history(
  197. self, state, key, passive=attributes.PASSIVE_NO_INITIALIZE
  198. ):
  199. """Facade to attributes.get_state_history(), including
  200. caching of results."""
  201. hashkey = ("history", state, key)
  202. # cache the objects, not the states; the strong reference here
  203. # prevents newly loaded objects from being dereferenced during the
  204. # flush process
  205. if hashkey in self.attributes:
  206. history, state_history, cached_passive = self.attributes[hashkey]
  207. # if the cached lookup was "passive" and now
  208. # we want non-passive, do a non-passive lookup and re-cache
  209. if (
  210. not cached_passive & attributes.SQL_OK
  211. and passive & attributes.SQL_OK
  212. ):
  213. impl = state.manager[key].impl
  214. history = impl.get_history(
  215. state,
  216. state.dict,
  217. attributes.PASSIVE_OFF
  218. | attributes.LOAD_AGAINST_COMMITTED
  219. | attributes.NO_RAISE,
  220. )
  221. if history and impl.uses_objects:
  222. state_history = history.as_state()
  223. else:
  224. state_history = history
  225. self.attributes[hashkey] = (history, state_history, passive)
  226. else:
  227. impl = state.manager[key].impl
  228. # TODO: store the history as (state, object) tuples
  229. # so we don't have to keep converting here
  230. history = impl.get_history(
  231. state,
  232. state.dict,
  233. passive
  234. | attributes.LOAD_AGAINST_COMMITTED
  235. | attributes.NO_RAISE,
  236. )
  237. if history and impl.uses_objects:
  238. state_history = history.as_state()
  239. else:
  240. state_history = history
  241. self.attributes[hashkey] = (history, state_history, passive)
  242. return state_history
  243. def has_dep(self, processor):
  244. return (processor, True) in self.presort_actions
  245. def register_preprocessor(self, processor, fromparent):
  246. key = (processor, fromparent)
  247. if key not in self.presort_actions:
  248. self.presort_actions[key] = Preprocess(processor, fromparent)
  249. def register_object(
  250. self,
  251. state: InstanceState[Any],
  252. isdelete: bool = False,
  253. listonly: bool = False,
  254. cancel_delete: bool = False,
  255. operation: Optional[str] = None,
  256. prop: Optional[MapperProperty] = None,
  257. ) -> bool:
  258. if not self.session._contains_state(state):
  259. # this condition is normal when objects are registered
  260. # as part of a relationship cascade operation. it should
  261. # not occur for the top-level register from Session.flush().
  262. if not state.deleted and operation is not None:
  263. util.warn(
  264. "Object of type %s not in session, %s operation "
  265. "along '%s' will not proceed"
  266. % (orm_util.state_class_str(state), operation, prop)
  267. )
  268. return False
  269. if state not in self.states:
  270. mapper = state.manager.mapper
  271. if mapper not in self.mappers:
  272. self._per_mapper_flush_actions(mapper)
  273. self.mappers[mapper].add(state)
  274. self.states[state] = (isdelete, listonly)
  275. else:
  276. if not listonly and (isdelete or cancel_delete):
  277. self.states[state] = (isdelete, False)
  278. return True
  279. def register_post_update(self, state, post_update_cols):
  280. mapper = state.manager.mapper.base_mapper
  281. states, cols = self.post_update_states[mapper]
  282. states.add(state)
  283. cols.update(post_update_cols)
  284. def _per_mapper_flush_actions(self, mapper):
  285. saves = SaveUpdateAll(self, mapper.base_mapper)
  286. deletes = DeleteAll(self, mapper.base_mapper)
  287. self.dependencies.add((saves, deletes))
  288. for dep in mapper._dependency_processors:
  289. dep.per_property_preprocessors(self)
  290. for prop in mapper.relationships:
  291. if prop.viewonly:
  292. continue
  293. dep = prop._dependency_processor
  294. dep.per_property_preprocessors(self)
  295. @util.memoized_property
  296. def _mapper_for_dep(self):
  297. """return a dynamic mapping of (Mapper, DependencyProcessor) to
  298. True or False, indicating if the DependencyProcessor operates
  299. on objects of that Mapper.
  300. The result is stored in the dictionary persistently once
  301. calculated.
  302. """
  303. return util.PopulateDict(
  304. lambda tup: tup[0]._props.get(tup[1].key) is tup[1].prop
  305. )
  306. def filter_states_for_dep(self, dep, states):
  307. """Filter the given list of InstanceStates to those relevant to the
  308. given DependencyProcessor.
  309. """
  310. mapper_for_dep = self._mapper_for_dep
  311. return [s for s in states if mapper_for_dep[(s.manager.mapper, dep)]]
  312. def states_for_mapper_hierarchy(self, mapper, isdelete, listonly):
  313. checktup = (isdelete, listonly)
  314. for mapper in mapper.base_mapper.self_and_descendants:
  315. for state in self.mappers[mapper]:
  316. if self.states[state] == checktup:
  317. yield state
  318. def _generate_actions(self):
  319. """Generate the full, unsorted collection of PostSortRecs as
  320. well as dependency pairs for this UOWTransaction.
  321. """
  322. # execute presort_actions, until all states
  323. # have been processed. a presort_action might
  324. # add new states to the uow.
  325. while True:
  326. ret = False
  327. for action in list(self.presort_actions.values()):
  328. if action.execute(self):
  329. ret = True
  330. if not ret:
  331. break
  332. # see if the graph of mapper dependencies has cycles.
  333. self.cycles = cycles = topological.find_cycles(
  334. self.dependencies, list(self.postsort_actions.values())
  335. )
  336. if cycles:
  337. # if yes, break the per-mapper actions into
  338. # per-state actions
  339. convert = {
  340. rec: set(rec.per_state_flush_actions(self)) for rec in cycles
  341. }
  342. # rewrite the existing dependencies to point to
  343. # the per-state actions for those per-mapper actions
  344. # that were broken up.
  345. for edge in list(self.dependencies):
  346. if (
  347. None in edge
  348. or edge[0].disabled
  349. or edge[1].disabled
  350. or cycles.issuperset(edge)
  351. ):
  352. self.dependencies.remove(edge)
  353. elif edge[0] in cycles:
  354. self.dependencies.remove(edge)
  355. for dep in convert[edge[0]]:
  356. self.dependencies.add((dep, edge[1]))
  357. elif edge[1] in cycles:
  358. self.dependencies.remove(edge)
  359. for dep in convert[edge[1]]:
  360. self.dependencies.add((edge[0], dep))
  361. return {
  362. a for a in self.postsort_actions.values() if not a.disabled
  363. }.difference(cycles)
  364. def execute(self) -> None:
  365. postsort_actions = self._generate_actions()
  366. postsort_actions = sorted(
  367. postsort_actions,
  368. key=lambda item: item.sort_key,
  369. )
  370. # sort = topological.sort(self.dependencies, postsort_actions)
  371. # print "--------------"
  372. # print "\ndependencies:", self.dependencies
  373. # print "\ncycles:", self.cycles
  374. # print "\nsort:", list(sort)
  375. # print "\nCOUNT OF POSTSORT ACTIONS", len(postsort_actions)
  376. # execute
  377. if self.cycles:
  378. for subset in topological.sort_as_subsets(
  379. self.dependencies, postsort_actions
  380. ):
  381. set_ = set(subset)
  382. while set_:
  383. n = set_.pop()
  384. n.execute_aggregate(self, set_)
  385. else:
  386. for rec in topological.sort(self.dependencies, postsort_actions):
  387. rec.execute(self)
  388. def finalize_flush_changes(self) -> None:
  389. """Mark processed objects as clean / deleted after a successful
  390. flush().
  391. This method is called within the flush() method after the
  392. execute() method has succeeded and the transaction has been committed.
  393. """
  394. if not self.states:
  395. return
  396. states = set(self.states)
  397. isdel = {
  398. s for (s, (isdelete, listonly)) in self.states.items() if isdelete
  399. }
  400. other = states.difference(isdel)
  401. if isdel:
  402. self.session._remove_newly_deleted(isdel)
  403. if other:
  404. self.session._register_persistent(other)
  405. class IterateMappersMixin:
  406. __slots__ = ()
  407. def _mappers(self, uow):
  408. if self.fromparent:
  409. return iter(
  410. m
  411. for m in self.dependency_processor.parent.self_and_descendants
  412. if uow._mapper_for_dep[(m, self.dependency_processor)]
  413. )
  414. else:
  415. return self.dependency_processor.mapper.self_and_descendants
  416. class Preprocess(IterateMappersMixin):
  417. __slots__ = (
  418. "dependency_processor",
  419. "fromparent",
  420. "processed",
  421. "setup_flush_actions",
  422. )
  423. def __init__(self, dependency_processor, fromparent):
  424. self.dependency_processor = dependency_processor
  425. self.fromparent = fromparent
  426. self.processed = set()
  427. self.setup_flush_actions = False
  428. def execute(self, uow):
  429. delete_states = set()
  430. save_states = set()
  431. for mapper in self._mappers(uow):
  432. for state in uow.mappers[mapper].difference(self.processed):
  433. (isdelete, listonly) = uow.states[state]
  434. if not listonly:
  435. if isdelete:
  436. delete_states.add(state)
  437. else:
  438. save_states.add(state)
  439. if delete_states:
  440. self.dependency_processor.presort_deletes(uow, delete_states)
  441. self.processed.update(delete_states)
  442. if save_states:
  443. self.dependency_processor.presort_saves(uow, save_states)
  444. self.processed.update(save_states)
  445. if delete_states or save_states:
  446. if not self.setup_flush_actions and (
  447. self.dependency_processor.prop_has_changes(
  448. uow, delete_states, True
  449. )
  450. or self.dependency_processor.prop_has_changes(
  451. uow, save_states, False
  452. )
  453. ):
  454. self.dependency_processor.per_property_flush_actions(uow)
  455. self.setup_flush_actions = True
  456. return True
  457. else:
  458. return False
  459. class PostSortRec:
  460. __slots__ = ("disabled",)
  461. def __new__(cls, uow, *args):
  462. key = (cls,) + args
  463. if key in uow.postsort_actions:
  464. return uow.postsort_actions[key]
  465. else:
  466. uow.postsort_actions[key] = ret = object.__new__(cls)
  467. ret.disabled = False
  468. return ret
  469. def execute_aggregate(self, uow, recs):
  470. self.execute(uow)
  471. class ProcessAll(IterateMappersMixin, PostSortRec):
  472. __slots__ = "dependency_processor", "isdelete", "fromparent", "sort_key"
  473. def __init__(self, uow, dependency_processor, isdelete, fromparent):
  474. self.dependency_processor = dependency_processor
  475. self.sort_key = (
  476. "ProcessAll",
  477. self.dependency_processor.sort_key,
  478. isdelete,
  479. )
  480. self.isdelete = isdelete
  481. self.fromparent = fromparent
  482. uow.deps[dependency_processor.parent.base_mapper].add(
  483. dependency_processor
  484. )
  485. def execute(self, uow):
  486. states = self._elements(uow)
  487. if self.isdelete:
  488. self.dependency_processor.process_deletes(uow, states)
  489. else:
  490. self.dependency_processor.process_saves(uow, states)
  491. def per_state_flush_actions(self, uow):
  492. # this is handled by SaveUpdateAll and DeleteAll,
  493. # since a ProcessAll should unconditionally be pulled
  494. # into per-state if either the parent/child mappers
  495. # are part of a cycle
  496. return iter([])
  497. def __repr__(self):
  498. return "%s(%s, isdelete=%s)" % (
  499. self.__class__.__name__,
  500. self.dependency_processor,
  501. self.isdelete,
  502. )
  503. def _elements(self, uow):
  504. for mapper in self._mappers(uow):
  505. for state in uow.mappers[mapper]:
  506. (isdelete, listonly) = uow.states[state]
  507. if isdelete == self.isdelete and not listonly:
  508. yield state
  509. class PostUpdateAll(PostSortRec):
  510. __slots__ = "mapper", "isdelete", "sort_key"
  511. def __init__(self, uow, mapper, isdelete):
  512. self.mapper = mapper
  513. self.isdelete = isdelete
  514. self.sort_key = ("PostUpdateAll", mapper._sort_key, isdelete)
  515. @util.preload_module("sqlalchemy.orm.persistence")
  516. def execute(self, uow):
  517. persistence = util.preloaded.orm_persistence
  518. states, cols = uow.post_update_states[self.mapper]
  519. states = [s for s in states if uow.states[s][0] == self.isdelete]
  520. persistence.post_update(self.mapper, states, uow, cols)
  521. class SaveUpdateAll(PostSortRec):
  522. __slots__ = ("mapper", "sort_key")
  523. def __init__(self, uow, mapper):
  524. self.mapper = mapper
  525. self.sort_key = ("SaveUpdateAll", mapper._sort_key)
  526. assert mapper is mapper.base_mapper
  527. @util.preload_module("sqlalchemy.orm.persistence")
  528. def execute(self, uow):
  529. util.preloaded.orm_persistence.save_obj(
  530. self.mapper,
  531. uow.states_for_mapper_hierarchy(self.mapper, False, False),
  532. uow,
  533. )
  534. def per_state_flush_actions(self, uow):
  535. states = list(
  536. uow.states_for_mapper_hierarchy(self.mapper, False, False)
  537. )
  538. base_mapper = self.mapper.base_mapper
  539. delete_all = DeleteAll(uow, base_mapper)
  540. for state in states:
  541. # keep saves before deletes -
  542. # this ensures 'row switch' operations work
  543. action = SaveUpdateState(uow, state)
  544. uow.dependencies.add((action, delete_all))
  545. yield action
  546. for dep in uow.deps[self.mapper]:
  547. states_for_prop = uow.filter_states_for_dep(dep, states)
  548. dep.per_state_flush_actions(uow, states_for_prop, False)
  549. def __repr__(self):
  550. return "%s(%s)" % (self.__class__.__name__, self.mapper)
  551. class DeleteAll(PostSortRec):
  552. __slots__ = ("mapper", "sort_key")
  553. def __init__(self, uow, mapper):
  554. self.mapper = mapper
  555. self.sort_key = ("DeleteAll", mapper._sort_key)
  556. assert mapper is mapper.base_mapper
  557. @util.preload_module("sqlalchemy.orm.persistence")
  558. def execute(self, uow):
  559. util.preloaded.orm_persistence.delete_obj(
  560. self.mapper,
  561. uow.states_for_mapper_hierarchy(self.mapper, True, False),
  562. uow,
  563. )
  564. def per_state_flush_actions(self, uow):
  565. states = list(
  566. uow.states_for_mapper_hierarchy(self.mapper, True, False)
  567. )
  568. base_mapper = self.mapper.base_mapper
  569. save_all = SaveUpdateAll(uow, base_mapper)
  570. for state in states:
  571. # keep saves before deletes -
  572. # this ensures 'row switch' operations work
  573. action = DeleteState(uow, state)
  574. uow.dependencies.add((save_all, action))
  575. yield action
  576. for dep in uow.deps[self.mapper]:
  577. states_for_prop = uow.filter_states_for_dep(dep, states)
  578. dep.per_state_flush_actions(uow, states_for_prop, True)
  579. def __repr__(self):
  580. return "%s(%s)" % (self.__class__.__name__, self.mapper)
  581. class ProcessState(PostSortRec):
  582. __slots__ = "dependency_processor", "isdelete", "state", "sort_key"
  583. def __init__(self, uow, dependency_processor, isdelete, state):
  584. self.dependency_processor = dependency_processor
  585. self.sort_key = ("ProcessState", dependency_processor.sort_key)
  586. self.isdelete = isdelete
  587. self.state = state
  588. def execute_aggregate(self, uow, recs):
  589. cls_ = self.__class__
  590. dependency_processor = self.dependency_processor
  591. isdelete = self.isdelete
  592. our_recs = [
  593. r
  594. for r in recs
  595. if r.__class__ is cls_
  596. and r.dependency_processor is dependency_processor
  597. and r.isdelete is isdelete
  598. ]
  599. recs.difference_update(our_recs)
  600. states = [self.state] + [r.state for r in our_recs]
  601. if isdelete:
  602. dependency_processor.process_deletes(uow, states)
  603. else:
  604. dependency_processor.process_saves(uow, states)
  605. def __repr__(self):
  606. return "%s(%s, %s, delete=%s)" % (
  607. self.__class__.__name__,
  608. self.dependency_processor,
  609. orm_util.state_str(self.state),
  610. self.isdelete,
  611. )
  612. class SaveUpdateState(PostSortRec):
  613. __slots__ = "state", "mapper", "sort_key"
  614. def __init__(self, uow, state):
  615. self.state = state
  616. self.mapper = state.mapper.base_mapper
  617. self.sort_key = ("ProcessState", self.mapper._sort_key)
  618. @util.preload_module("sqlalchemy.orm.persistence")
  619. def execute_aggregate(self, uow, recs):
  620. persistence = util.preloaded.orm_persistence
  621. cls_ = self.__class__
  622. mapper = self.mapper
  623. our_recs = [
  624. r for r in recs if r.__class__ is cls_ and r.mapper is mapper
  625. ]
  626. recs.difference_update(our_recs)
  627. persistence.save_obj(
  628. mapper, [self.state] + [r.state for r in our_recs], uow
  629. )
  630. def __repr__(self):
  631. return "%s(%s)" % (
  632. self.__class__.__name__,
  633. orm_util.state_str(self.state),
  634. )
  635. class DeleteState(PostSortRec):
  636. __slots__ = "state", "mapper", "sort_key"
  637. def __init__(self, uow, state):
  638. self.state = state
  639. self.mapper = state.mapper.base_mapper
  640. self.sort_key = ("DeleteState", self.mapper._sort_key)
  641. @util.preload_module("sqlalchemy.orm.persistence")
  642. def execute_aggregate(self, uow, recs):
  643. persistence = util.preloaded.orm_persistence
  644. cls_ = self.__class__
  645. mapper = self.mapper
  646. our_recs = [
  647. r for r in recs if r.__class__ is cls_ and r.mapper is mapper
  648. ]
  649. recs.difference_update(our_recs)
  650. states = [self.state] + [r.state for r in our_recs]
  651. persistence.delete_obj(
  652. mapper, [s for s in states if uow.states[s][0]], uow
  653. )
  654. def __repr__(self):
  655. return "%s(%s)" % (
  656. self.__class__.__name__,
  657. orm_util.state_str(self.state),
  658. )