dependency.py 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302
  1. # orm/dependency.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. """Relationship dependencies."""
  9. from __future__ import annotations
  10. from . import attributes
  11. from . import exc
  12. from . import sync
  13. from . import unitofwork
  14. from . import util as mapperutil
  15. from .interfaces import MANYTOMANY
  16. from .interfaces import MANYTOONE
  17. from .interfaces import ONETOMANY
  18. from .. import exc as sa_exc
  19. from .. import sql
  20. from .. import util
  21. class DependencyProcessor:
  22. def __init__(self, prop):
  23. self.prop = prop
  24. self.cascade = prop.cascade
  25. self.mapper = prop.mapper
  26. self.parent = prop.parent
  27. self.secondary = prop.secondary
  28. self.direction = prop.direction
  29. self.post_update = prop.post_update
  30. self.passive_deletes = prop.passive_deletes
  31. self.passive_updates = prop.passive_updates
  32. self.enable_typechecks = prop.enable_typechecks
  33. if self.passive_deletes:
  34. self._passive_delete_flag = attributes.PASSIVE_NO_INITIALIZE
  35. else:
  36. self._passive_delete_flag = attributes.PASSIVE_OFF
  37. if self.passive_updates:
  38. self._passive_update_flag = attributes.PASSIVE_NO_INITIALIZE
  39. else:
  40. self._passive_update_flag = attributes.PASSIVE_OFF
  41. self.sort_key = "%s_%s" % (self.parent._sort_key, prop.key)
  42. self.key = prop.key
  43. if not self.prop.synchronize_pairs:
  44. raise sa_exc.ArgumentError(
  45. "Can't build a DependencyProcessor for relationship %s. "
  46. "No target attributes to populate between parent and "
  47. "child are present" % self.prop
  48. )
  49. @classmethod
  50. def from_relationship(cls, prop):
  51. return _direction_to_processor[prop.direction](prop)
  52. def hasparent(self, state):
  53. """return True if the given object instance has a parent,
  54. according to the ``InstrumentedAttribute`` handled by this
  55. ``DependencyProcessor``.
  56. """
  57. return self.parent.class_manager.get_impl(self.key).hasparent(state)
  58. def per_property_preprocessors(self, uow):
  59. """establish actions and dependencies related to a flush.
  60. These actions will operate on all relevant states in
  61. the aggregate.
  62. """
  63. uow.register_preprocessor(self, True)
  64. def per_property_flush_actions(self, uow):
  65. after_save = unitofwork.ProcessAll(uow, self, False, True)
  66. before_delete = unitofwork.ProcessAll(uow, self, True, True)
  67. parent_saves = unitofwork.SaveUpdateAll(
  68. uow, self.parent.primary_base_mapper
  69. )
  70. child_saves = unitofwork.SaveUpdateAll(
  71. uow, self.mapper.primary_base_mapper
  72. )
  73. parent_deletes = unitofwork.DeleteAll(
  74. uow, self.parent.primary_base_mapper
  75. )
  76. child_deletes = unitofwork.DeleteAll(
  77. uow, self.mapper.primary_base_mapper
  78. )
  79. self.per_property_dependencies(
  80. uow,
  81. parent_saves,
  82. child_saves,
  83. parent_deletes,
  84. child_deletes,
  85. after_save,
  86. before_delete,
  87. )
  88. def per_state_flush_actions(self, uow, states, isdelete):
  89. """establish actions and dependencies related to a flush.
  90. These actions will operate on all relevant states
  91. individually. This occurs only if there are cycles
  92. in the 'aggregated' version of events.
  93. """
  94. child_base_mapper = self.mapper.primary_base_mapper
  95. child_saves = unitofwork.SaveUpdateAll(uow, child_base_mapper)
  96. child_deletes = unitofwork.DeleteAll(uow, child_base_mapper)
  97. # locate and disable the aggregate processors
  98. # for this dependency
  99. if isdelete:
  100. before_delete = unitofwork.ProcessAll(uow, self, True, True)
  101. before_delete.disabled = True
  102. else:
  103. after_save = unitofwork.ProcessAll(uow, self, False, True)
  104. after_save.disabled = True
  105. # check if the "child" side is part of the cycle
  106. if child_saves not in uow.cycles:
  107. # based on the current dependencies we use, the saves/
  108. # deletes should always be in the 'cycles' collection
  109. # together. if this changes, we will have to break up
  110. # this method a bit more.
  111. assert child_deletes not in uow.cycles
  112. # child side is not part of the cycle, so we will link per-state
  113. # actions to the aggregate "saves", "deletes" actions
  114. child_actions = [(child_saves, False), (child_deletes, True)]
  115. child_in_cycles = False
  116. else:
  117. child_in_cycles = True
  118. # check if the "parent" side is part of the cycle
  119. if not isdelete:
  120. parent_saves = unitofwork.SaveUpdateAll(
  121. uow, self.parent.base_mapper
  122. )
  123. parent_deletes = before_delete = None
  124. if parent_saves in uow.cycles:
  125. parent_in_cycles = True
  126. else:
  127. parent_deletes = unitofwork.DeleteAll(uow, self.parent.base_mapper)
  128. parent_saves = after_save = None
  129. if parent_deletes in uow.cycles:
  130. parent_in_cycles = True
  131. # now create actions /dependencies for each state.
  132. for state in states:
  133. # detect if there's anything changed or loaded
  134. # by a preprocessor on this state/attribute. In the
  135. # case of deletes we may try to load missing items here as well.
  136. sum_ = state.manager[self.key].impl.get_all_pending(
  137. state,
  138. state.dict,
  139. (
  140. self._passive_delete_flag
  141. if isdelete
  142. else attributes.PASSIVE_NO_INITIALIZE
  143. ),
  144. )
  145. if not sum_:
  146. continue
  147. if isdelete:
  148. before_delete = unitofwork.ProcessState(uow, self, True, state)
  149. if parent_in_cycles:
  150. parent_deletes = unitofwork.DeleteState(uow, state)
  151. else:
  152. after_save = unitofwork.ProcessState(uow, self, False, state)
  153. if parent_in_cycles:
  154. parent_saves = unitofwork.SaveUpdateState(uow, state)
  155. if child_in_cycles:
  156. child_actions = []
  157. for child_state, child in sum_:
  158. if child_state not in uow.states:
  159. child_action = (None, None)
  160. else:
  161. (deleted, listonly) = uow.states[child_state]
  162. if deleted:
  163. child_action = (
  164. unitofwork.DeleteState(uow, child_state),
  165. True,
  166. )
  167. else:
  168. child_action = (
  169. unitofwork.SaveUpdateState(uow, child_state),
  170. False,
  171. )
  172. child_actions.append(child_action)
  173. # establish dependencies between our possibly per-state
  174. # parent action and our possibly per-state child action.
  175. for child_action, childisdelete in child_actions:
  176. self.per_state_dependencies(
  177. uow,
  178. parent_saves,
  179. parent_deletes,
  180. child_action,
  181. after_save,
  182. before_delete,
  183. isdelete,
  184. childisdelete,
  185. )
  186. def presort_deletes(self, uowcommit, states):
  187. return False
  188. def presort_saves(self, uowcommit, states):
  189. return False
  190. def process_deletes(self, uowcommit, states):
  191. pass
  192. def process_saves(self, uowcommit, states):
  193. pass
  194. def prop_has_changes(self, uowcommit, states, isdelete):
  195. if not isdelete or self.passive_deletes:
  196. passive = (
  197. attributes.PASSIVE_NO_INITIALIZE
  198. | attributes.INCLUDE_PENDING_MUTATIONS
  199. )
  200. elif self.direction is MANYTOONE:
  201. # here, we were hoping to optimize having to fetch many-to-one
  202. # for history and ignore it, if there's no further cascades
  203. # to take place. however there are too many less common conditions
  204. # that still take place and tests in test_relationships /
  205. # test_cascade etc. will still fail.
  206. passive = attributes.PASSIVE_NO_FETCH_RELATED
  207. else:
  208. passive = (
  209. attributes.PASSIVE_OFF | attributes.INCLUDE_PENDING_MUTATIONS
  210. )
  211. for s in states:
  212. # TODO: add a high speed method
  213. # to InstanceState which returns: attribute
  214. # has a non-None value, or had one
  215. history = uowcommit.get_attribute_history(s, self.key, passive)
  216. if history and not history.empty():
  217. return True
  218. else:
  219. return (
  220. states
  221. and not self.prop._is_self_referential
  222. and self.mapper in uowcommit.mappers
  223. )
  224. def _verify_canload(self, state):
  225. if self.prop.uselist and state is None:
  226. raise exc.FlushError(
  227. "Can't flush None value found in "
  228. "collection %s" % (self.prop,)
  229. )
  230. elif state is not None and not self.mapper._canload(
  231. state, allow_subtypes=not self.enable_typechecks
  232. ):
  233. if self.mapper._canload(state, allow_subtypes=True):
  234. raise exc.FlushError(
  235. "Attempting to flush an item of type "
  236. "%(x)s as a member of collection "
  237. '"%(y)s". Expected an object of type '
  238. "%(z)s or a polymorphic subclass of "
  239. "this type. If %(x)s is a subclass of "
  240. '%(z)s, configure mapper "%(zm)s" to '
  241. "load this subtype polymorphically, or "
  242. "set enable_typechecks=False to allow "
  243. "any subtype to be accepted for flush. "
  244. % {
  245. "x": state.class_,
  246. "y": self.prop,
  247. "z": self.mapper.class_,
  248. "zm": self.mapper,
  249. }
  250. )
  251. else:
  252. raise exc.FlushError(
  253. "Attempting to flush an item of type "
  254. "%(x)s as a member of collection "
  255. '"%(y)s". Expected an object of type '
  256. "%(z)s or a polymorphic subclass of "
  257. "this type."
  258. % {
  259. "x": state.class_,
  260. "y": self.prop,
  261. "z": self.mapper.class_,
  262. }
  263. )
  264. def _synchronize(self, state, child, associationrow, clearkeys, uowcommit):
  265. raise NotImplementedError()
  266. def _get_reversed_processed_set(self, uow):
  267. if not self.prop._reverse_property:
  268. return None
  269. process_key = tuple(
  270. sorted([self.key] + [p.key for p in self.prop._reverse_property])
  271. )
  272. return uow.memo(("reverse_key", process_key), set)
  273. def _post_update(self, state, uowcommit, related, is_m2o_delete=False):
  274. for x in related:
  275. if not is_m2o_delete or x is not None:
  276. uowcommit.register_post_update(
  277. state, [r for l, r in self.prop.synchronize_pairs]
  278. )
  279. break
  280. def _pks_changed(self, uowcommit, state):
  281. raise NotImplementedError()
  282. def __repr__(self):
  283. return "%s(%s)" % (self.__class__.__name__, self.prop)
  284. class OneToManyDP(DependencyProcessor):
  285. def per_property_dependencies(
  286. self,
  287. uow,
  288. parent_saves,
  289. child_saves,
  290. parent_deletes,
  291. child_deletes,
  292. after_save,
  293. before_delete,
  294. ):
  295. if self.post_update:
  296. child_post_updates = unitofwork.PostUpdateAll(
  297. uow, self.mapper.primary_base_mapper, False
  298. )
  299. child_pre_updates = unitofwork.PostUpdateAll(
  300. uow, self.mapper.primary_base_mapper, True
  301. )
  302. uow.dependencies.update(
  303. [
  304. (child_saves, after_save),
  305. (parent_saves, after_save),
  306. (after_save, child_post_updates),
  307. (before_delete, child_pre_updates),
  308. (child_pre_updates, parent_deletes),
  309. (child_pre_updates, child_deletes),
  310. ]
  311. )
  312. else:
  313. uow.dependencies.update(
  314. [
  315. (parent_saves, after_save),
  316. (after_save, child_saves),
  317. (after_save, child_deletes),
  318. (child_saves, parent_deletes),
  319. (child_deletes, parent_deletes),
  320. (before_delete, child_saves),
  321. (before_delete, child_deletes),
  322. ]
  323. )
  324. def per_state_dependencies(
  325. self,
  326. uow,
  327. save_parent,
  328. delete_parent,
  329. child_action,
  330. after_save,
  331. before_delete,
  332. isdelete,
  333. childisdelete,
  334. ):
  335. if self.post_update:
  336. child_post_updates = unitofwork.PostUpdateAll(
  337. uow, self.mapper.primary_base_mapper, False
  338. )
  339. child_pre_updates = unitofwork.PostUpdateAll(
  340. uow, self.mapper.primary_base_mapper, True
  341. )
  342. # TODO: this whole block is not covered
  343. # by any tests
  344. if not isdelete:
  345. if childisdelete:
  346. uow.dependencies.update(
  347. [
  348. (child_action, after_save),
  349. (after_save, child_post_updates),
  350. ]
  351. )
  352. else:
  353. uow.dependencies.update(
  354. [
  355. (save_parent, after_save),
  356. (child_action, after_save),
  357. (after_save, child_post_updates),
  358. ]
  359. )
  360. else:
  361. if childisdelete:
  362. uow.dependencies.update(
  363. [
  364. (before_delete, child_pre_updates),
  365. (child_pre_updates, delete_parent),
  366. ]
  367. )
  368. else:
  369. uow.dependencies.update(
  370. [
  371. (before_delete, child_pre_updates),
  372. (child_pre_updates, delete_parent),
  373. ]
  374. )
  375. elif not isdelete:
  376. uow.dependencies.update(
  377. [
  378. (save_parent, after_save),
  379. (after_save, child_action),
  380. (save_parent, child_action),
  381. ]
  382. )
  383. else:
  384. uow.dependencies.update(
  385. [(before_delete, child_action), (child_action, delete_parent)]
  386. )
  387. def presort_deletes(self, uowcommit, states):
  388. # head object is being deleted, and we manage its list of
  389. # child objects the child objects have to have their
  390. # foreign key to the parent set to NULL
  391. should_null_fks = (
  392. not self.cascade.delete and not self.passive_deletes == "all"
  393. )
  394. for state in states:
  395. history = uowcommit.get_attribute_history(
  396. state, self.key, self._passive_delete_flag
  397. )
  398. if history:
  399. for child in history.deleted:
  400. if child is not None and self.hasparent(child) is False:
  401. if self.cascade.delete_orphan:
  402. uowcommit.register_object(child, isdelete=True)
  403. else:
  404. uowcommit.register_object(child)
  405. if should_null_fks:
  406. for child in history.unchanged:
  407. if child is not None:
  408. uowcommit.register_object(
  409. child, operation="delete", prop=self.prop
  410. )
  411. def presort_saves(self, uowcommit, states):
  412. children_added = uowcommit.memo(("children_added", self), set)
  413. should_null_fks = (
  414. not self.cascade.delete_orphan
  415. and not self.passive_deletes == "all"
  416. )
  417. for state in states:
  418. pks_changed = self._pks_changed(uowcommit, state)
  419. if not pks_changed or self.passive_updates:
  420. passive = (
  421. attributes.PASSIVE_NO_INITIALIZE
  422. | attributes.INCLUDE_PENDING_MUTATIONS
  423. )
  424. else:
  425. passive = (
  426. attributes.PASSIVE_OFF
  427. | attributes.INCLUDE_PENDING_MUTATIONS
  428. )
  429. history = uowcommit.get_attribute_history(state, self.key, passive)
  430. if history:
  431. for child in history.added:
  432. if child is not None:
  433. uowcommit.register_object(
  434. child,
  435. cancel_delete=True,
  436. operation="add",
  437. prop=self.prop,
  438. )
  439. children_added.update(history.added)
  440. for child in history.deleted:
  441. if not self.cascade.delete_orphan:
  442. if should_null_fks:
  443. uowcommit.register_object(
  444. child,
  445. isdelete=False,
  446. operation="delete",
  447. prop=self.prop,
  448. )
  449. elif self.hasparent(child) is False:
  450. uowcommit.register_object(
  451. child,
  452. isdelete=True,
  453. operation="delete",
  454. prop=self.prop,
  455. )
  456. for c, m, st_, dct_ in self.mapper.cascade_iterator(
  457. "delete", child
  458. ):
  459. uowcommit.register_object(st_, isdelete=True)
  460. if pks_changed:
  461. if history:
  462. for child in history.unchanged:
  463. if child is not None:
  464. uowcommit.register_object(
  465. child,
  466. False,
  467. self.passive_updates,
  468. operation="pk change",
  469. prop=self.prop,
  470. )
  471. def process_deletes(self, uowcommit, states):
  472. # head object is being deleted, and we manage its list of
  473. # child objects the child objects have to have their foreign
  474. # key to the parent set to NULL this phase can be called
  475. # safely for any cascade but is unnecessary if delete cascade
  476. # is on.
  477. if self.post_update or not self.passive_deletes == "all":
  478. children_added = uowcommit.memo(("children_added", self), set)
  479. for state in states:
  480. history = uowcommit.get_attribute_history(
  481. state, self.key, self._passive_delete_flag
  482. )
  483. if history:
  484. for child in history.deleted:
  485. if (
  486. child is not None
  487. and self.hasparent(child) is False
  488. ):
  489. self._synchronize(
  490. state, child, None, True, uowcommit, False
  491. )
  492. if self.post_update and child:
  493. self._post_update(child, uowcommit, [state])
  494. if self.post_update or not self.cascade.delete:
  495. for child in set(history.unchanged).difference(
  496. children_added
  497. ):
  498. if child is not None:
  499. self._synchronize(
  500. state, child, None, True, uowcommit, False
  501. )
  502. if self.post_update and child:
  503. self._post_update(
  504. child, uowcommit, [state]
  505. )
  506. # technically, we can even remove each child from the
  507. # collection here too. but this would be a somewhat
  508. # inconsistent behavior since it wouldn't happen
  509. # if the old parent wasn't deleted but child was moved.
  510. def process_saves(self, uowcommit, states):
  511. should_null_fks = (
  512. not self.cascade.delete_orphan
  513. and not self.passive_deletes == "all"
  514. )
  515. for state in states:
  516. history = uowcommit.get_attribute_history(
  517. state, self.key, attributes.PASSIVE_NO_INITIALIZE
  518. )
  519. if history:
  520. for child in history.added:
  521. self._synchronize(
  522. state, child, None, False, uowcommit, False
  523. )
  524. if child is not None and self.post_update:
  525. self._post_update(child, uowcommit, [state])
  526. for child in history.deleted:
  527. if (
  528. should_null_fks
  529. and not self.cascade.delete_orphan
  530. and not self.hasparent(child)
  531. ):
  532. self._synchronize(
  533. state, child, None, True, uowcommit, False
  534. )
  535. if self._pks_changed(uowcommit, state):
  536. for child in history.unchanged:
  537. self._synchronize(
  538. state, child, None, False, uowcommit, True
  539. )
  540. def _synchronize(
  541. self, state, child, associationrow, clearkeys, uowcommit, pks_changed
  542. ):
  543. source = state
  544. dest = child
  545. self._verify_canload(child)
  546. if dest is None or (
  547. not self.post_update and uowcommit.is_deleted(dest)
  548. ):
  549. return
  550. if clearkeys:
  551. sync.clear(dest, self.mapper, self.prop.synchronize_pairs)
  552. else:
  553. sync.populate(
  554. source,
  555. self.parent,
  556. dest,
  557. self.mapper,
  558. self.prop.synchronize_pairs,
  559. uowcommit,
  560. self.passive_updates and pks_changed,
  561. )
  562. def _pks_changed(self, uowcommit, state):
  563. return sync.source_modified(
  564. uowcommit, state, self.parent, self.prop.synchronize_pairs
  565. )
  566. class ManyToOneDP(DependencyProcessor):
  567. def __init__(self, prop):
  568. DependencyProcessor.__init__(self, prop)
  569. for mapper in self.mapper.self_and_descendants:
  570. mapper._dependency_processors.append(DetectKeySwitch(prop))
  571. def per_property_dependencies(
  572. self,
  573. uow,
  574. parent_saves,
  575. child_saves,
  576. parent_deletes,
  577. child_deletes,
  578. after_save,
  579. before_delete,
  580. ):
  581. if self.post_update:
  582. parent_post_updates = unitofwork.PostUpdateAll(
  583. uow, self.parent.primary_base_mapper, False
  584. )
  585. parent_pre_updates = unitofwork.PostUpdateAll(
  586. uow, self.parent.primary_base_mapper, True
  587. )
  588. uow.dependencies.update(
  589. [
  590. (child_saves, after_save),
  591. (parent_saves, after_save),
  592. (after_save, parent_post_updates),
  593. (after_save, parent_pre_updates),
  594. (before_delete, parent_pre_updates),
  595. (parent_pre_updates, child_deletes),
  596. (parent_pre_updates, parent_deletes),
  597. ]
  598. )
  599. else:
  600. uow.dependencies.update(
  601. [
  602. (child_saves, after_save),
  603. (after_save, parent_saves),
  604. (parent_saves, child_deletes),
  605. (parent_deletes, child_deletes),
  606. ]
  607. )
  608. def per_state_dependencies(
  609. self,
  610. uow,
  611. save_parent,
  612. delete_parent,
  613. child_action,
  614. after_save,
  615. before_delete,
  616. isdelete,
  617. childisdelete,
  618. ):
  619. if self.post_update:
  620. if not isdelete:
  621. parent_post_updates = unitofwork.PostUpdateAll(
  622. uow, self.parent.primary_base_mapper, False
  623. )
  624. if childisdelete:
  625. uow.dependencies.update(
  626. [
  627. (after_save, parent_post_updates),
  628. (parent_post_updates, child_action),
  629. ]
  630. )
  631. else:
  632. uow.dependencies.update(
  633. [
  634. (save_parent, after_save),
  635. (child_action, after_save),
  636. (after_save, parent_post_updates),
  637. ]
  638. )
  639. else:
  640. parent_pre_updates = unitofwork.PostUpdateAll(
  641. uow, self.parent.primary_base_mapper, True
  642. )
  643. uow.dependencies.update(
  644. [
  645. (before_delete, parent_pre_updates),
  646. (parent_pre_updates, delete_parent),
  647. (parent_pre_updates, child_action),
  648. ]
  649. )
  650. elif not isdelete:
  651. if not childisdelete:
  652. uow.dependencies.update(
  653. [(child_action, after_save), (after_save, save_parent)]
  654. )
  655. else:
  656. uow.dependencies.update([(after_save, save_parent)])
  657. else:
  658. if childisdelete:
  659. uow.dependencies.update([(delete_parent, child_action)])
  660. def presort_deletes(self, uowcommit, states):
  661. if self.cascade.delete or self.cascade.delete_orphan:
  662. for state in states:
  663. history = uowcommit.get_attribute_history(
  664. state, self.key, self._passive_delete_flag
  665. )
  666. if history:
  667. if self.cascade.delete_orphan:
  668. todelete = history.sum()
  669. else:
  670. todelete = history.non_deleted()
  671. for child in todelete:
  672. if child is None:
  673. continue
  674. uowcommit.register_object(
  675. child,
  676. isdelete=True,
  677. operation="delete",
  678. prop=self.prop,
  679. )
  680. t = self.mapper.cascade_iterator("delete", child)
  681. for c, m, st_, dct_ in t:
  682. uowcommit.register_object(st_, isdelete=True)
  683. def presort_saves(self, uowcommit, states):
  684. for state in states:
  685. uowcommit.register_object(state, operation="add", prop=self.prop)
  686. if self.cascade.delete_orphan:
  687. history = uowcommit.get_attribute_history(
  688. state, self.key, self._passive_delete_flag
  689. )
  690. if history:
  691. for child in history.deleted:
  692. if self.hasparent(child) is False:
  693. uowcommit.register_object(
  694. child,
  695. isdelete=True,
  696. operation="delete",
  697. prop=self.prop,
  698. )
  699. t = self.mapper.cascade_iterator("delete", child)
  700. for c, m, st_, dct_ in t:
  701. uowcommit.register_object(st_, isdelete=True)
  702. def process_deletes(self, uowcommit, states):
  703. if (
  704. self.post_update
  705. and not self.cascade.delete_orphan
  706. and not self.passive_deletes == "all"
  707. ):
  708. # post_update means we have to update our
  709. # row to not reference the child object
  710. # before we can DELETE the row
  711. for state in states:
  712. self._synchronize(state, None, None, True, uowcommit)
  713. if state and self.post_update:
  714. history = uowcommit.get_attribute_history(
  715. state, self.key, self._passive_delete_flag
  716. )
  717. if history:
  718. self._post_update(
  719. state, uowcommit, history.sum(), is_m2o_delete=True
  720. )
  721. def process_saves(self, uowcommit, states):
  722. for state in states:
  723. history = uowcommit.get_attribute_history(
  724. state, self.key, attributes.PASSIVE_NO_INITIALIZE
  725. )
  726. if history:
  727. if history.added:
  728. for child in history.added:
  729. self._synchronize(
  730. state, child, None, False, uowcommit, "add"
  731. )
  732. elif history.deleted:
  733. self._synchronize(
  734. state, None, None, True, uowcommit, "delete"
  735. )
  736. if self.post_update:
  737. self._post_update(state, uowcommit, history.sum())
  738. def _synchronize(
  739. self,
  740. state,
  741. child,
  742. associationrow,
  743. clearkeys,
  744. uowcommit,
  745. operation=None,
  746. ):
  747. if state is None or (
  748. not self.post_update and uowcommit.is_deleted(state)
  749. ):
  750. return
  751. if (
  752. operation is not None
  753. and child is not None
  754. and not uowcommit.session._contains_state(child)
  755. ):
  756. util.warn(
  757. "Object of type %s not in session, %s "
  758. "operation along '%s' won't proceed"
  759. % (mapperutil.state_class_str(child), operation, self.prop)
  760. )
  761. return
  762. if clearkeys or child is None:
  763. sync.clear(state, self.parent, self.prop.synchronize_pairs)
  764. else:
  765. self._verify_canload(child)
  766. sync.populate(
  767. child,
  768. self.mapper,
  769. state,
  770. self.parent,
  771. self.prop.synchronize_pairs,
  772. uowcommit,
  773. False,
  774. )
  775. class DetectKeySwitch(DependencyProcessor):
  776. """For many-to-one relationships with no one-to-many backref,
  777. searches for parents through the unit of work when a primary
  778. key has changed and updates them.
  779. Theoretically, this approach could be expanded to support transparent
  780. deletion of objects referenced via many-to-one as well, although
  781. the current attribute system doesn't do enough bookkeeping for this
  782. to be efficient.
  783. """
  784. def per_property_preprocessors(self, uow):
  785. if self.prop._reverse_property:
  786. if self.passive_updates:
  787. return
  788. else:
  789. if False in (
  790. prop.passive_updates
  791. for prop in self.prop._reverse_property
  792. ):
  793. return
  794. uow.register_preprocessor(self, False)
  795. def per_property_flush_actions(self, uow):
  796. parent_saves = unitofwork.SaveUpdateAll(uow, self.parent.base_mapper)
  797. after_save = unitofwork.ProcessAll(uow, self, False, False)
  798. uow.dependencies.update([(parent_saves, after_save)])
  799. def per_state_flush_actions(self, uow, states, isdelete):
  800. pass
  801. def presort_deletes(self, uowcommit, states):
  802. pass
  803. def presort_saves(self, uow, states):
  804. if not self.passive_updates:
  805. # for non-passive updates, register in the preprocess stage
  806. # so that mapper save_obj() gets a hold of changes
  807. self._process_key_switches(states, uow)
  808. def prop_has_changes(self, uow, states, isdelete):
  809. if not isdelete and self.passive_updates:
  810. d = self._key_switchers(uow, states)
  811. return bool(d)
  812. return False
  813. def process_deletes(self, uowcommit, states):
  814. assert False
  815. def process_saves(self, uowcommit, states):
  816. # for passive updates, register objects in the process stage
  817. # so that we avoid ManyToOneDP's registering the object without
  818. # the listonly flag in its own preprocess stage (results in UPDATE)
  819. # statements being emitted
  820. assert self.passive_updates
  821. self._process_key_switches(states, uowcommit)
  822. def _key_switchers(self, uow, states):
  823. switched, notswitched = uow.memo(
  824. ("pk_switchers", self), lambda: (set(), set())
  825. )
  826. allstates = switched.union(notswitched)
  827. for s in states:
  828. if s not in allstates:
  829. if self._pks_changed(uow, s):
  830. switched.add(s)
  831. else:
  832. notswitched.add(s)
  833. return switched
  834. def _process_key_switches(self, deplist, uowcommit):
  835. switchers = self._key_switchers(uowcommit, deplist)
  836. if switchers:
  837. # if primary key values have actually changed somewhere, perform
  838. # a linear search through the UOW in search of a parent.
  839. for state in uowcommit.session.identity_map.all_states():
  840. if not issubclass(state.class_, self.parent.class_):
  841. continue
  842. dict_ = state.dict
  843. related = state.get_impl(self.key).get(
  844. state, dict_, passive=self._passive_update_flag
  845. )
  846. if (
  847. related is not attributes.PASSIVE_NO_RESULT
  848. and related is not None
  849. ):
  850. if self.prop.uselist:
  851. if not related:
  852. continue
  853. related_obj = related[0]
  854. else:
  855. related_obj = related
  856. related_state = attributes.instance_state(related_obj)
  857. if related_state in switchers:
  858. uowcommit.register_object(
  859. state, False, self.passive_updates
  860. )
  861. sync.populate(
  862. related_state,
  863. self.mapper,
  864. state,
  865. self.parent,
  866. self.prop.synchronize_pairs,
  867. uowcommit,
  868. self.passive_updates,
  869. )
  870. def _pks_changed(self, uowcommit, state):
  871. return bool(state.key) and sync.source_modified(
  872. uowcommit, state, self.mapper, self.prop.synchronize_pairs
  873. )
  874. class ManyToManyDP(DependencyProcessor):
  875. def per_property_dependencies(
  876. self,
  877. uow,
  878. parent_saves,
  879. child_saves,
  880. parent_deletes,
  881. child_deletes,
  882. after_save,
  883. before_delete,
  884. ):
  885. uow.dependencies.update(
  886. [
  887. (parent_saves, after_save),
  888. (child_saves, after_save),
  889. (after_save, child_deletes),
  890. # a rowswitch on the parent from deleted to saved
  891. # can make this one occur, as the "save" may remove
  892. # an element from the
  893. # "deleted" list before we have a chance to
  894. # process its child rows
  895. (before_delete, parent_saves),
  896. (before_delete, parent_deletes),
  897. (before_delete, child_deletes),
  898. (before_delete, child_saves),
  899. ]
  900. )
  901. def per_state_dependencies(
  902. self,
  903. uow,
  904. save_parent,
  905. delete_parent,
  906. child_action,
  907. after_save,
  908. before_delete,
  909. isdelete,
  910. childisdelete,
  911. ):
  912. if not isdelete:
  913. if childisdelete:
  914. uow.dependencies.update(
  915. [(save_parent, after_save), (after_save, child_action)]
  916. )
  917. else:
  918. uow.dependencies.update(
  919. [(save_parent, after_save), (child_action, after_save)]
  920. )
  921. else:
  922. uow.dependencies.update(
  923. [(before_delete, child_action), (before_delete, delete_parent)]
  924. )
  925. def presort_deletes(self, uowcommit, states):
  926. # TODO: no tests fail if this whole
  927. # thing is removed !!!!
  928. if not self.passive_deletes:
  929. # if no passive deletes, load history on
  930. # the collection, so that prop_has_changes()
  931. # returns True
  932. for state in states:
  933. uowcommit.get_attribute_history(
  934. state, self.key, self._passive_delete_flag
  935. )
  936. def presort_saves(self, uowcommit, states):
  937. if not self.passive_updates:
  938. # if no passive updates, load history on
  939. # each collection where parent has changed PK,
  940. # so that prop_has_changes() returns True
  941. for state in states:
  942. if self._pks_changed(uowcommit, state):
  943. uowcommit.get_attribute_history(
  944. state, self.key, attributes.PASSIVE_OFF
  945. )
  946. if not self.cascade.delete_orphan:
  947. return
  948. # check for child items removed from the collection
  949. # if delete_orphan check is turned on.
  950. for state in states:
  951. history = uowcommit.get_attribute_history(
  952. state, self.key, attributes.PASSIVE_NO_INITIALIZE
  953. )
  954. if history:
  955. for child in history.deleted:
  956. if self.hasparent(child) is False:
  957. uowcommit.register_object(
  958. child,
  959. isdelete=True,
  960. operation="delete",
  961. prop=self.prop,
  962. )
  963. for c, m, st_, dct_ in self.mapper.cascade_iterator(
  964. "delete", child
  965. ):
  966. uowcommit.register_object(st_, isdelete=True)
  967. def process_deletes(self, uowcommit, states):
  968. secondary_delete = []
  969. secondary_insert = []
  970. secondary_update = []
  971. processed = self._get_reversed_processed_set(uowcommit)
  972. tmp = set()
  973. for state in states:
  974. # this history should be cached already, as
  975. # we loaded it in preprocess_deletes
  976. history = uowcommit.get_attribute_history(
  977. state, self.key, self._passive_delete_flag
  978. )
  979. if history:
  980. for child in history.non_added():
  981. if child is None or (
  982. processed is not None and (state, child) in processed
  983. ):
  984. continue
  985. associationrow = {}
  986. if not self._synchronize(
  987. state,
  988. child,
  989. associationrow,
  990. False,
  991. uowcommit,
  992. "delete",
  993. ):
  994. continue
  995. secondary_delete.append(associationrow)
  996. tmp.update((c, state) for c in history.non_added())
  997. if processed is not None:
  998. processed.update(tmp)
  999. self._run_crud(
  1000. uowcommit, secondary_insert, secondary_update, secondary_delete
  1001. )
  1002. def process_saves(self, uowcommit, states):
  1003. secondary_delete = []
  1004. secondary_insert = []
  1005. secondary_update = []
  1006. processed = self._get_reversed_processed_set(uowcommit)
  1007. tmp = set()
  1008. for state in states:
  1009. need_cascade_pks = not self.passive_updates and self._pks_changed(
  1010. uowcommit, state
  1011. )
  1012. if need_cascade_pks:
  1013. passive = (
  1014. attributes.PASSIVE_OFF
  1015. | attributes.INCLUDE_PENDING_MUTATIONS
  1016. )
  1017. else:
  1018. passive = (
  1019. attributes.PASSIVE_NO_INITIALIZE
  1020. | attributes.INCLUDE_PENDING_MUTATIONS
  1021. )
  1022. history = uowcommit.get_attribute_history(state, self.key, passive)
  1023. if history:
  1024. for child in history.added:
  1025. if processed is not None and (state, child) in processed:
  1026. continue
  1027. associationrow = {}
  1028. if not self._synchronize(
  1029. state, child, associationrow, False, uowcommit, "add"
  1030. ):
  1031. continue
  1032. secondary_insert.append(associationrow)
  1033. for child in history.deleted:
  1034. if processed is not None and (state, child) in processed:
  1035. continue
  1036. associationrow = {}
  1037. if not self._synchronize(
  1038. state,
  1039. child,
  1040. associationrow,
  1041. False,
  1042. uowcommit,
  1043. "delete",
  1044. ):
  1045. continue
  1046. secondary_delete.append(associationrow)
  1047. tmp.update((c, state) for c in history.added + history.deleted)
  1048. if need_cascade_pks:
  1049. for child in history.unchanged:
  1050. associationrow = {}
  1051. sync.update(
  1052. state,
  1053. self.parent,
  1054. associationrow,
  1055. "old_",
  1056. self.prop.synchronize_pairs,
  1057. )
  1058. sync.update(
  1059. child,
  1060. self.mapper,
  1061. associationrow,
  1062. "old_",
  1063. self.prop.secondary_synchronize_pairs,
  1064. )
  1065. secondary_update.append(associationrow)
  1066. if processed is not None:
  1067. processed.update(tmp)
  1068. self._run_crud(
  1069. uowcommit, secondary_insert, secondary_update, secondary_delete
  1070. )
  1071. def _run_crud(
  1072. self, uowcommit, secondary_insert, secondary_update, secondary_delete
  1073. ):
  1074. connection = uowcommit.transaction.connection(self.mapper)
  1075. if secondary_delete:
  1076. associationrow = secondary_delete[0]
  1077. statement = self.secondary.delete().where(
  1078. sql.and_(
  1079. *[
  1080. c == sql.bindparam(c.key, type_=c.type)
  1081. for c in self.secondary.c
  1082. if c.key in associationrow
  1083. ]
  1084. )
  1085. )
  1086. result = connection.execute(statement, secondary_delete)
  1087. if (
  1088. result.supports_sane_multi_rowcount()
  1089. ) and result.rowcount != len(secondary_delete):
  1090. raise exc.StaleDataError(
  1091. "DELETE statement on table '%s' expected to delete "
  1092. "%d row(s); Only %d were matched."
  1093. % (
  1094. self.secondary.description,
  1095. len(secondary_delete),
  1096. result.rowcount,
  1097. )
  1098. )
  1099. if secondary_update:
  1100. associationrow = secondary_update[0]
  1101. statement = self.secondary.update().where(
  1102. sql.and_(
  1103. *[
  1104. c == sql.bindparam("old_" + c.key, type_=c.type)
  1105. for c in self.secondary.c
  1106. if c.key in associationrow
  1107. ]
  1108. )
  1109. )
  1110. result = connection.execute(statement, secondary_update)
  1111. if (
  1112. result.supports_sane_multi_rowcount()
  1113. ) and result.rowcount != len(secondary_update):
  1114. raise exc.StaleDataError(
  1115. "UPDATE statement on table '%s' expected to update "
  1116. "%d row(s); Only %d were matched."
  1117. % (
  1118. self.secondary.description,
  1119. len(secondary_update),
  1120. result.rowcount,
  1121. )
  1122. )
  1123. if secondary_insert:
  1124. statement = self.secondary.insert()
  1125. connection.execute(statement, secondary_insert)
  1126. def _synchronize(
  1127. self, state, child, associationrow, clearkeys, uowcommit, operation
  1128. ):
  1129. # this checks for None if uselist=True
  1130. self._verify_canload(child)
  1131. # but if uselist=False we get here. If child is None,
  1132. # no association row can be generated, so return.
  1133. if child is None:
  1134. return False
  1135. if child is not None and not uowcommit.session._contains_state(child):
  1136. if not child.deleted:
  1137. util.warn(
  1138. "Object of type %s not in session, %s "
  1139. "operation along '%s' won't proceed"
  1140. % (mapperutil.state_class_str(child), operation, self.prop)
  1141. )
  1142. return False
  1143. sync.populate_dict(
  1144. state, self.parent, associationrow, self.prop.synchronize_pairs
  1145. )
  1146. sync.populate_dict(
  1147. child,
  1148. self.mapper,
  1149. associationrow,
  1150. self.prop.secondary_synchronize_pairs,
  1151. )
  1152. return True
  1153. def _pks_changed(self, uowcommit, state):
  1154. return sync.source_modified(
  1155. uowcommit, state, self.parent, self.prop.synchronize_pairs
  1156. )
  1157. _direction_to_processor = {
  1158. ONETOMANY: OneToManyDP,
  1159. MANYTOONE: ManyToOneDP,
  1160. MANYTOMANY: ManyToManyDP,
  1161. }