You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

785 lines
26KB

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