unitofwork.py 24 KB

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