persistence.py 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765
  1. # orm/persistence.py
  2. # Copyright (C) 2005-2024 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. """private module containing functions used to emit INSERT, UPDATE
  9. and DELETE statements on behalf of a :class:`_orm.Mapper` and its descending
  10. mappers.
  11. The functions here are called only by the unit of work functions
  12. in unitofwork.py.
  13. """
  14. from __future__ import annotations
  15. from itertools import chain
  16. from itertools import groupby
  17. from itertools import zip_longest
  18. import operator
  19. from . import attributes
  20. from . import exc as orm_exc
  21. from . import loading
  22. from . import sync
  23. from .base import state_str
  24. from .. import exc as sa_exc
  25. from .. import future
  26. from .. import sql
  27. from .. import util
  28. from ..engine import cursor as _cursor
  29. from ..sql import operators
  30. from ..sql.elements import BooleanClauseList
  31. from ..sql.selectable import LABEL_STYLE_TABLENAME_PLUS_COL
  32. def save_obj(base_mapper, states, uowtransaction, single=False):
  33. """Issue ``INSERT`` and/or ``UPDATE`` statements for a list
  34. of objects.
  35. This is called within the context of a UOWTransaction during a
  36. flush operation, given a list of states to be flushed. The
  37. base mapper in an inheritance hierarchy handles the inserts/
  38. updates for all descendant mappers.
  39. """
  40. # if batch=false, call _save_obj separately for each object
  41. if not single and not base_mapper.batch:
  42. for state in _sort_states(base_mapper, states):
  43. save_obj(base_mapper, [state], uowtransaction, single=True)
  44. return
  45. states_to_update = []
  46. states_to_insert = []
  47. for (
  48. state,
  49. dict_,
  50. mapper,
  51. connection,
  52. has_identity,
  53. row_switch,
  54. update_version_id,
  55. ) in _organize_states_for_save(base_mapper, states, uowtransaction):
  56. if has_identity or row_switch:
  57. states_to_update.append(
  58. (state, dict_, mapper, connection, update_version_id)
  59. )
  60. else:
  61. states_to_insert.append((state, dict_, mapper, connection))
  62. for table, mapper in base_mapper._sorted_tables.items():
  63. if table not in mapper._pks_by_table:
  64. continue
  65. insert = _collect_insert_commands(table, states_to_insert)
  66. update = _collect_update_commands(
  67. uowtransaction, table, states_to_update
  68. )
  69. _emit_update_statements(
  70. base_mapper,
  71. uowtransaction,
  72. mapper,
  73. table,
  74. update,
  75. )
  76. _emit_insert_statements(
  77. base_mapper,
  78. uowtransaction,
  79. mapper,
  80. table,
  81. insert,
  82. )
  83. _finalize_insert_update_commands(
  84. base_mapper,
  85. uowtransaction,
  86. chain(
  87. (
  88. (state, state_dict, mapper, connection, False)
  89. for (state, state_dict, mapper, connection) in states_to_insert
  90. ),
  91. (
  92. (state, state_dict, mapper, connection, True)
  93. for (
  94. state,
  95. state_dict,
  96. mapper,
  97. connection,
  98. update_version_id,
  99. ) in states_to_update
  100. ),
  101. ),
  102. )
  103. def post_update(base_mapper, states, uowtransaction, post_update_cols):
  104. """Issue UPDATE statements on behalf of a relationship() which
  105. specifies post_update.
  106. """
  107. states_to_update = list(
  108. _organize_states_for_post_update(base_mapper, states, uowtransaction)
  109. )
  110. for table, mapper in base_mapper._sorted_tables.items():
  111. if table not in mapper._pks_by_table:
  112. continue
  113. update = (
  114. (
  115. state,
  116. state_dict,
  117. sub_mapper,
  118. connection,
  119. mapper._get_committed_state_attr_by_column(
  120. state, state_dict, mapper.version_id_col
  121. )
  122. if mapper.version_id_col is not None
  123. else None,
  124. )
  125. for state, state_dict, sub_mapper, connection in states_to_update
  126. if table in sub_mapper._pks_by_table
  127. )
  128. update = _collect_post_update_commands(
  129. base_mapper, uowtransaction, table, update, post_update_cols
  130. )
  131. _emit_post_update_statements(
  132. base_mapper,
  133. uowtransaction,
  134. mapper,
  135. table,
  136. update,
  137. )
  138. def delete_obj(base_mapper, states, uowtransaction):
  139. """Issue ``DELETE`` statements for a list of objects.
  140. This is called within the context of a UOWTransaction during a
  141. flush operation.
  142. """
  143. states_to_delete = list(
  144. _organize_states_for_delete(base_mapper, states, uowtransaction)
  145. )
  146. table_to_mapper = base_mapper._sorted_tables
  147. for table in reversed(list(table_to_mapper.keys())):
  148. mapper = table_to_mapper[table]
  149. if table not in mapper._pks_by_table:
  150. continue
  151. elif mapper.inherits and mapper.passive_deletes:
  152. continue
  153. delete = _collect_delete_commands(
  154. base_mapper, uowtransaction, table, states_to_delete
  155. )
  156. _emit_delete_statements(
  157. base_mapper,
  158. uowtransaction,
  159. mapper,
  160. table,
  161. delete,
  162. )
  163. for (
  164. state,
  165. state_dict,
  166. mapper,
  167. connection,
  168. update_version_id,
  169. ) in states_to_delete:
  170. mapper.dispatch.after_delete(mapper, connection, state)
  171. def _organize_states_for_save(base_mapper, states, uowtransaction):
  172. """Make an initial pass across a set of states for INSERT or
  173. UPDATE.
  174. This includes splitting out into distinct lists for
  175. each, calling before_insert/before_update, obtaining
  176. key information for each state including its dictionary,
  177. mapper, the connection to use for the execution per state,
  178. and the identity flag.
  179. """
  180. for state, dict_, mapper, connection in _connections_for_states(
  181. base_mapper, uowtransaction, states
  182. ):
  183. has_identity = bool(state.key)
  184. instance_key = state.key or mapper._identity_key_from_state(state)
  185. row_switch = update_version_id = None
  186. # call before_XXX extensions
  187. if not has_identity:
  188. mapper.dispatch.before_insert(mapper, connection, state)
  189. else:
  190. mapper.dispatch.before_update(mapper, connection, state)
  191. if mapper._validate_polymorphic_identity:
  192. mapper._validate_polymorphic_identity(mapper, state, dict_)
  193. # detect if we have a "pending" instance (i.e. has
  194. # no instance_key attached to it), and another instance
  195. # with the same identity key already exists as persistent.
  196. # convert to an UPDATE if so.
  197. if (
  198. not has_identity
  199. and instance_key in uowtransaction.session.identity_map
  200. ):
  201. instance = uowtransaction.session.identity_map[instance_key]
  202. existing = attributes.instance_state(instance)
  203. if not uowtransaction.was_already_deleted(existing):
  204. if not uowtransaction.is_deleted(existing):
  205. util.warn(
  206. "New instance %s with identity key %s conflicts "
  207. "with persistent instance %s"
  208. % (state_str(state), instance_key, state_str(existing))
  209. )
  210. else:
  211. base_mapper._log_debug(
  212. "detected row switch for identity %s. "
  213. "will update %s, remove %s from "
  214. "transaction",
  215. instance_key,
  216. state_str(state),
  217. state_str(existing),
  218. )
  219. # remove the "delete" flag from the existing element
  220. uowtransaction.remove_state_actions(existing)
  221. row_switch = existing
  222. if (has_identity or row_switch) and mapper.version_id_col is not None:
  223. update_version_id = mapper._get_committed_state_attr_by_column(
  224. row_switch if row_switch else state,
  225. row_switch.dict if row_switch else dict_,
  226. mapper.version_id_col,
  227. )
  228. yield (
  229. state,
  230. dict_,
  231. mapper,
  232. connection,
  233. has_identity,
  234. row_switch,
  235. update_version_id,
  236. )
  237. def _organize_states_for_post_update(base_mapper, states, uowtransaction):
  238. """Make an initial pass across a set of states for UPDATE
  239. corresponding to post_update.
  240. This includes obtaining key information for each state
  241. including its dictionary, mapper, the connection to use for
  242. the execution per state.
  243. """
  244. return _connections_for_states(base_mapper, uowtransaction, states)
  245. def _organize_states_for_delete(base_mapper, states, uowtransaction):
  246. """Make an initial pass across a set of states for DELETE.
  247. This includes calling out before_delete and obtaining
  248. key information for each state including its dictionary,
  249. mapper, the connection to use for the execution per state.
  250. """
  251. for state, dict_, mapper, connection in _connections_for_states(
  252. base_mapper, uowtransaction, states
  253. ):
  254. mapper.dispatch.before_delete(mapper, connection, state)
  255. if mapper.version_id_col is not None:
  256. update_version_id = mapper._get_committed_state_attr_by_column(
  257. state, dict_, mapper.version_id_col
  258. )
  259. else:
  260. update_version_id = None
  261. yield (state, dict_, mapper, connection, update_version_id)
  262. def _collect_insert_commands(
  263. table,
  264. states_to_insert,
  265. *,
  266. bulk=False,
  267. return_defaults=False,
  268. render_nulls=False,
  269. include_bulk_keys=(),
  270. ):
  271. """Identify sets of values to use in INSERT statements for a
  272. list of states.
  273. """
  274. for state, state_dict, mapper, connection in states_to_insert:
  275. if table not in mapper._pks_by_table:
  276. continue
  277. params = {}
  278. value_params = {}
  279. propkey_to_col = mapper._propkey_to_col[table]
  280. eval_none = mapper._insert_cols_evaluating_none[table]
  281. for propkey in set(propkey_to_col).intersection(state_dict):
  282. value = state_dict[propkey]
  283. col = propkey_to_col[propkey]
  284. if value is None and col not in eval_none and not render_nulls:
  285. continue
  286. elif not bulk and (
  287. hasattr(value, "__clause_element__")
  288. or isinstance(value, sql.ClauseElement)
  289. ):
  290. value_params[col] = (
  291. value.__clause_element__()
  292. if hasattr(value, "__clause_element__")
  293. else value
  294. )
  295. else:
  296. params[col.key] = value
  297. if not bulk:
  298. # for all the columns that have no default and we don't have
  299. # a value and where "None" is not a special value, add
  300. # explicit None to the INSERT. This is a legacy behavior
  301. # which might be worth removing, as it should not be necessary
  302. # and also produces confusion, given that "missing" and None
  303. # now have distinct meanings
  304. for colkey in (
  305. mapper._insert_cols_as_none[table]
  306. .difference(params)
  307. .difference([c.key for c in value_params])
  308. ):
  309. params[colkey] = None
  310. if not bulk or return_defaults:
  311. # params are in terms of Column key objects, so
  312. # compare to pk_keys_by_table
  313. has_all_pks = mapper._pk_keys_by_table[table].issubset(params)
  314. if mapper.base_mapper._prefer_eager_defaults(
  315. connection.dialect, table
  316. ):
  317. has_all_defaults = mapper._server_default_col_keys[
  318. table
  319. ].issubset(params)
  320. else:
  321. has_all_defaults = True
  322. else:
  323. has_all_defaults = has_all_pks = True
  324. if (
  325. mapper.version_id_generator is not False
  326. and mapper.version_id_col is not None
  327. and mapper.version_id_col in mapper._cols_by_table[table]
  328. ):
  329. params[mapper.version_id_col.key] = mapper.version_id_generator(
  330. None
  331. )
  332. if bulk:
  333. if mapper._set_polymorphic_identity:
  334. params.setdefault(
  335. mapper._polymorphic_attr_key, mapper.polymorphic_identity
  336. )
  337. if include_bulk_keys:
  338. params.update((k, state_dict[k]) for k in include_bulk_keys)
  339. yield (
  340. state,
  341. state_dict,
  342. params,
  343. mapper,
  344. connection,
  345. value_params,
  346. has_all_pks,
  347. has_all_defaults,
  348. )
  349. def _collect_update_commands(
  350. uowtransaction,
  351. table,
  352. states_to_update,
  353. *,
  354. bulk=False,
  355. use_orm_update_stmt=None,
  356. include_bulk_keys=(),
  357. ):
  358. """Identify sets of values to use in UPDATE statements for a
  359. list of states.
  360. This function works intricately with the history system
  361. to determine exactly what values should be updated
  362. as well as how the row should be matched within an UPDATE
  363. statement. Includes some tricky scenarios where the primary
  364. key of an object might have been changed.
  365. """
  366. for (
  367. state,
  368. state_dict,
  369. mapper,
  370. connection,
  371. update_version_id,
  372. ) in states_to_update:
  373. if table not in mapper._pks_by_table:
  374. continue
  375. pks = mapper._pks_by_table[table]
  376. if use_orm_update_stmt is not None:
  377. # TODO: ordered values, etc
  378. value_params = use_orm_update_stmt._values
  379. else:
  380. value_params = {}
  381. propkey_to_col = mapper._propkey_to_col[table]
  382. if bulk:
  383. # keys here are mapped attribute keys, so
  384. # look at mapper attribute keys for pk
  385. params = {
  386. propkey_to_col[propkey].key: state_dict[propkey]
  387. for propkey in set(propkey_to_col)
  388. .intersection(state_dict)
  389. .difference(mapper._pk_attr_keys_by_table[table])
  390. }
  391. has_all_defaults = True
  392. else:
  393. params = {}
  394. for propkey in set(propkey_to_col).intersection(
  395. state.committed_state
  396. ):
  397. value = state_dict[propkey]
  398. col = propkey_to_col[propkey]
  399. if hasattr(value, "__clause_element__") or isinstance(
  400. value, sql.ClauseElement
  401. ):
  402. value_params[col] = (
  403. value.__clause_element__()
  404. if hasattr(value, "__clause_element__")
  405. else value
  406. )
  407. # guard against values that generate non-__nonzero__
  408. # objects for __eq__()
  409. elif (
  410. state.manager[propkey].impl.is_equal(
  411. value, state.committed_state[propkey]
  412. )
  413. is not True
  414. ):
  415. params[col.key] = value
  416. if mapper.base_mapper.eager_defaults is True:
  417. has_all_defaults = (
  418. mapper._server_onupdate_default_col_keys[table]
  419. ).issubset(params)
  420. else:
  421. has_all_defaults = True
  422. if (
  423. update_version_id is not None
  424. and mapper.version_id_col in mapper._cols_by_table[table]
  425. ):
  426. if not bulk and not (params or value_params):
  427. # HACK: check for history in other tables, in case the
  428. # history is only in a different table than the one
  429. # where the version_id_col is. This logic was lost
  430. # from 0.9 -> 1.0.0 and restored in 1.0.6.
  431. for prop in mapper._columntoproperty.values():
  432. history = state.manager[prop.key].impl.get_history(
  433. state, state_dict, attributes.PASSIVE_NO_INITIALIZE
  434. )
  435. if history.added:
  436. break
  437. else:
  438. # no net change, break
  439. continue
  440. col = mapper.version_id_col
  441. no_params = not params and not value_params
  442. params[col._label] = update_version_id
  443. if (
  444. bulk or col.key not in params
  445. ) and mapper.version_id_generator is not False:
  446. val = mapper.version_id_generator(update_version_id)
  447. params[col.key] = val
  448. elif mapper.version_id_generator is False and no_params:
  449. # no version id generator, no values set on the table,
  450. # and version id wasn't manually incremented.
  451. # set version id to itself so we get an UPDATE
  452. # statement
  453. params[col.key] = update_version_id
  454. elif not (params or value_params):
  455. continue
  456. has_all_pks = True
  457. expect_pk_cascaded = False
  458. if bulk:
  459. # keys here are mapped attribute keys, so
  460. # look at mapper attribute keys for pk
  461. pk_params = {
  462. propkey_to_col[propkey]._label: state_dict.get(propkey)
  463. for propkey in set(propkey_to_col).intersection(
  464. mapper._pk_attr_keys_by_table[table]
  465. )
  466. }
  467. if util.NONE_SET.intersection(pk_params.values()):
  468. raise sa_exc.InvalidRequestError(
  469. f"No primary key value supplied for column(s) "
  470. f"""{
  471. ', '.join(
  472. str(c) for c in pks if pk_params[c._label] is None
  473. )
  474. }; """
  475. "per-row ORM Bulk UPDATE by Primary Key requires that "
  476. "records contain primary key values",
  477. code="bupq",
  478. )
  479. else:
  480. pk_params = {}
  481. for col in pks:
  482. propkey = mapper._columntoproperty[col].key
  483. history = state.manager[propkey].impl.get_history(
  484. state, state_dict, attributes.PASSIVE_OFF
  485. )
  486. if history.added:
  487. if (
  488. not history.deleted
  489. or ("pk_cascaded", state, col)
  490. in uowtransaction.attributes
  491. ):
  492. expect_pk_cascaded = True
  493. pk_params[col._label] = history.added[0]
  494. params.pop(col.key, None)
  495. else:
  496. # else, use the old value to locate the row
  497. pk_params[col._label] = history.deleted[0]
  498. if col in value_params:
  499. has_all_pks = False
  500. else:
  501. pk_params[col._label] = history.unchanged[0]
  502. if pk_params[col._label] is None:
  503. raise orm_exc.FlushError(
  504. "Can't update table %s using NULL for primary "
  505. "key value on column %s" % (table, col)
  506. )
  507. if include_bulk_keys:
  508. params.update((k, state_dict[k]) for k in include_bulk_keys)
  509. if params or value_params:
  510. params.update(pk_params)
  511. yield (
  512. state,
  513. state_dict,
  514. params,
  515. mapper,
  516. connection,
  517. value_params,
  518. has_all_defaults,
  519. has_all_pks,
  520. )
  521. elif expect_pk_cascaded:
  522. # no UPDATE occurs on this table, but we expect that CASCADE rules
  523. # have changed the primary key of the row; propagate this event to
  524. # other columns that expect to have been modified. this normally
  525. # occurs after the UPDATE is emitted however we invoke it here
  526. # explicitly in the absence of our invoking an UPDATE
  527. for m, equated_pairs in mapper._table_to_equated[table]:
  528. sync.populate(
  529. state,
  530. m,
  531. state,
  532. m,
  533. equated_pairs,
  534. uowtransaction,
  535. mapper.passive_updates,
  536. )
  537. def _collect_post_update_commands(
  538. base_mapper, uowtransaction, table, states_to_update, post_update_cols
  539. ):
  540. """Identify sets of values to use in UPDATE statements for a
  541. list of states within a post_update operation.
  542. """
  543. for (
  544. state,
  545. state_dict,
  546. mapper,
  547. connection,
  548. update_version_id,
  549. ) in states_to_update:
  550. # assert table in mapper._pks_by_table
  551. pks = mapper._pks_by_table[table]
  552. params = {}
  553. hasdata = False
  554. for col in mapper._cols_by_table[table]:
  555. if col in pks:
  556. params[col._label] = mapper._get_state_attr_by_column(
  557. state, state_dict, col, passive=attributes.PASSIVE_OFF
  558. )
  559. elif col in post_update_cols or col.onupdate is not None:
  560. prop = mapper._columntoproperty[col]
  561. history = state.manager[prop.key].impl.get_history(
  562. state, state_dict, attributes.PASSIVE_NO_INITIALIZE
  563. )
  564. if history.added:
  565. value = history.added[0]
  566. params[col.key] = value
  567. hasdata = True
  568. if hasdata:
  569. if (
  570. update_version_id is not None
  571. and mapper.version_id_col in mapper._cols_by_table[table]
  572. ):
  573. col = mapper.version_id_col
  574. params[col._label] = update_version_id
  575. if (
  576. bool(state.key)
  577. and col.key not in params
  578. and mapper.version_id_generator is not False
  579. ):
  580. val = mapper.version_id_generator(update_version_id)
  581. params[col.key] = val
  582. yield state, state_dict, mapper, connection, params
  583. def _collect_delete_commands(
  584. base_mapper, uowtransaction, table, states_to_delete
  585. ):
  586. """Identify values to use in DELETE statements for a list of
  587. states to be deleted."""
  588. for (
  589. state,
  590. state_dict,
  591. mapper,
  592. connection,
  593. update_version_id,
  594. ) in states_to_delete:
  595. if table not in mapper._pks_by_table:
  596. continue
  597. params = {}
  598. for col in mapper._pks_by_table[table]:
  599. params[
  600. col.key
  601. ] = value = mapper._get_committed_state_attr_by_column(
  602. state, state_dict, col
  603. )
  604. if value is None:
  605. raise orm_exc.FlushError(
  606. "Can't delete from table %s "
  607. "using NULL for primary "
  608. "key value on column %s" % (table, col)
  609. )
  610. if (
  611. update_version_id is not None
  612. and mapper.version_id_col in mapper._cols_by_table[table]
  613. ):
  614. params[mapper.version_id_col.key] = update_version_id
  615. yield params, connection
  616. def _emit_update_statements(
  617. base_mapper,
  618. uowtransaction,
  619. mapper,
  620. table,
  621. update,
  622. *,
  623. bookkeeping=True,
  624. use_orm_update_stmt=None,
  625. enable_check_rowcount=True,
  626. ):
  627. """Emit UPDATE statements corresponding to value lists collected
  628. by _collect_update_commands()."""
  629. needs_version_id = (
  630. mapper.version_id_col is not None
  631. and mapper.version_id_col in mapper._cols_by_table[table]
  632. )
  633. execution_options = {"compiled_cache": base_mapper._compiled_cache}
  634. def update_stmt(existing_stmt=None):
  635. clauses = BooleanClauseList._construct_raw(operators.and_)
  636. for col in mapper._pks_by_table[table]:
  637. clauses._append_inplace(
  638. col == sql.bindparam(col._label, type_=col.type)
  639. )
  640. if needs_version_id:
  641. clauses._append_inplace(
  642. mapper.version_id_col
  643. == sql.bindparam(
  644. mapper.version_id_col._label,
  645. type_=mapper.version_id_col.type,
  646. )
  647. )
  648. if existing_stmt is not None:
  649. stmt = existing_stmt.where(clauses)
  650. else:
  651. stmt = table.update().where(clauses)
  652. return stmt
  653. if use_orm_update_stmt is not None:
  654. cached_stmt = update_stmt(use_orm_update_stmt)
  655. else:
  656. cached_stmt = base_mapper._memo(("update", table), update_stmt)
  657. for (
  658. (connection, paramkeys, hasvalue, has_all_defaults, has_all_pks),
  659. records,
  660. ) in groupby(
  661. update,
  662. lambda rec: (
  663. rec[4], # connection
  664. set(rec[2]), # set of parameter keys
  665. bool(rec[5]), # whether or not we have "value" parameters
  666. rec[6], # has_all_defaults
  667. rec[7], # has all pks
  668. ),
  669. ):
  670. rows = 0
  671. records = list(records)
  672. statement = cached_stmt
  673. if use_orm_update_stmt is not None:
  674. statement = statement._annotate(
  675. {
  676. "_emit_update_table": table,
  677. "_emit_update_mapper": mapper,
  678. }
  679. )
  680. return_defaults = False
  681. if not has_all_pks:
  682. statement = statement.return_defaults(*mapper._pks_by_table[table])
  683. return_defaults = True
  684. if (
  685. bookkeeping
  686. and not has_all_defaults
  687. and mapper.base_mapper.eager_defaults is True
  688. # change as of #8889 - if RETURNING is not going to be used anyway,
  689. # (applies to MySQL, MariaDB which lack UPDATE RETURNING) ensure
  690. # we can do an executemany UPDATE which is more efficient
  691. and table.implicit_returning
  692. and connection.dialect.update_returning
  693. ):
  694. statement = statement.return_defaults(
  695. *mapper._server_onupdate_default_cols[table]
  696. )
  697. return_defaults = True
  698. if mapper._version_id_has_server_side_value:
  699. statement = statement.return_defaults(mapper.version_id_col)
  700. return_defaults = True
  701. assert_singlerow = connection.dialect.supports_sane_rowcount
  702. assert_multirow = (
  703. assert_singlerow
  704. and connection.dialect.supports_sane_multi_rowcount
  705. )
  706. # change as of #8889 - if RETURNING is not going to be used anyway,
  707. # (applies to MySQL, MariaDB which lack UPDATE RETURNING) ensure
  708. # we can do an executemany UPDATE which is more efficient
  709. allow_executemany = not return_defaults and not needs_version_id
  710. if hasvalue:
  711. for (
  712. state,
  713. state_dict,
  714. params,
  715. mapper,
  716. connection,
  717. value_params,
  718. has_all_defaults,
  719. has_all_pks,
  720. ) in records:
  721. c = connection.execute(
  722. statement.values(value_params),
  723. params,
  724. execution_options=execution_options,
  725. )
  726. if bookkeeping:
  727. _postfetch(
  728. mapper,
  729. uowtransaction,
  730. table,
  731. state,
  732. state_dict,
  733. c,
  734. c.context.compiled_parameters[0],
  735. value_params,
  736. True,
  737. c.returned_defaults,
  738. )
  739. rows += c.rowcount
  740. check_rowcount = enable_check_rowcount and assert_singlerow
  741. else:
  742. if not allow_executemany:
  743. check_rowcount = enable_check_rowcount and assert_singlerow
  744. for (
  745. state,
  746. state_dict,
  747. params,
  748. mapper,
  749. connection,
  750. value_params,
  751. has_all_defaults,
  752. has_all_pks,
  753. ) in records:
  754. c = connection.execute(
  755. statement, params, execution_options=execution_options
  756. )
  757. # TODO: why with bookkeeping=False?
  758. if bookkeeping:
  759. _postfetch(
  760. mapper,
  761. uowtransaction,
  762. table,
  763. state,
  764. state_dict,
  765. c,
  766. c.context.compiled_parameters[0],
  767. value_params,
  768. True,
  769. c.returned_defaults,
  770. )
  771. rows += c.rowcount
  772. else:
  773. multiparams = [rec[2] for rec in records]
  774. check_rowcount = enable_check_rowcount and (
  775. assert_multirow
  776. or (assert_singlerow and len(multiparams) == 1)
  777. )
  778. c = connection.execute(
  779. statement, multiparams, execution_options=execution_options
  780. )
  781. rows += c.rowcount
  782. for (
  783. state,
  784. state_dict,
  785. params,
  786. mapper,
  787. connection,
  788. value_params,
  789. has_all_defaults,
  790. has_all_pks,
  791. ) in records:
  792. if bookkeeping:
  793. _postfetch(
  794. mapper,
  795. uowtransaction,
  796. table,
  797. state,
  798. state_dict,
  799. c,
  800. c.context.compiled_parameters[0],
  801. value_params,
  802. True,
  803. c.returned_defaults
  804. if not c.context.executemany
  805. else None,
  806. )
  807. if check_rowcount:
  808. if rows != len(records):
  809. raise orm_exc.StaleDataError(
  810. "UPDATE statement on table '%s' expected to "
  811. "update %d row(s); %d were matched."
  812. % (table.description, len(records), rows)
  813. )
  814. elif needs_version_id:
  815. util.warn(
  816. "Dialect %s does not support updated rowcount "
  817. "- versioning cannot be verified."
  818. % c.dialect.dialect_description
  819. )
  820. def _emit_insert_statements(
  821. base_mapper,
  822. uowtransaction,
  823. mapper,
  824. table,
  825. insert,
  826. *,
  827. bookkeeping=True,
  828. use_orm_insert_stmt=None,
  829. execution_options=None,
  830. ):
  831. """Emit INSERT statements corresponding to value lists collected
  832. by _collect_insert_commands()."""
  833. if use_orm_insert_stmt is not None:
  834. cached_stmt = use_orm_insert_stmt
  835. exec_opt = util.EMPTY_DICT
  836. # if a user query with RETURNING was passed, we definitely need
  837. # to use RETURNING.
  838. returning_is_required_anyway = bool(use_orm_insert_stmt._returning)
  839. deterministic_results_reqd = (
  840. returning_is_required_anyway
  841. and use_orm_insert_stmt._sort_by_parameter_order
  842. ) or bookkeeping
  843. else:
  844. returning_is_required_anyway = False
  845. deterministic_results_reqd = bookkeeping
  846. cached_stmt = base_mapper._memo(("insert", table), table.insert)
  847. exec_opt = {"compiled_cache": base_mapper._compiled_cache}
  848. if execution_options:
  849. execution_options = util.EMPTY_DICT.merge_with(
  850. exec_opt, execution_options
  851. )
  852. else:
  853. execution_options = exec_opt
  854. return_result = None
  855. for (
  856. (connection, _, hasvalue, has_all_pks, has_all_defaults),
  857. records,
  858. ) in groupby(
  859. insert,
  860. lambda rec: (
  861. rec[4], # connection
  862. set(rec[2]), # parameter keys
  863. bool(rec[5]), # whether we have "value" parameters
  864. rec[6],
  865. rec[7],
  866. ),
  867. ):
  868. statement = cached_stmt
  869. if use_orm_insert_stmt is not None:
  870. statement = statement._annotate(
  871. {
  872. "_emit_insert_table": table,
  873. "_emit_insert_mapper": mapper,
  874. }
  875. )
  876. if (
  877. (
  878. not bookkeeping
  879. or (
  880. has_all_defaults
  881. or not base_mapper._prefer_eager_defaults(
  882. connection.dialect, table
  883. )
  884. or not table.implicit_returning
  885. or not connection.dialect.insert_returning
  886. )
  887. )
  888. and not returning_is_required_anyway
  889. and has_all_pks
  890. and not hasvalue
  891. ):
  892. # the "we don't need newly generated values back" section.
  893. # here we have all the PKs, all the defaults or we don't want
  894. # to fetch them, or the dialect doesn't support RETURNING at all
  895. # so we have to post-fetch / use lastrowid anyway.
  896. records = list(records)
  897. multiparams = [rec[2] for rec in records]
  898. result = connection.execute(
  899. statement, multiparams, execution_options=execution_options
  900. )
  901. if bookkeeping:
  902. for (
  903. (
  904. state,
  905. state_dict,
  906. params,
  907. mapper_rec,
  908. conn,
  909. value_params,
  910. has_all_pks,
  911. has_all_defaults,
  912. ),
  913. last_inserted_params,
  914. ) in zip(records, result.context.compiled_parameters):
  915. if state:
  916. _postfetch(
  917. mapper_rec,
  918. uowtransaction,
  919. table,
  920. state,
  921. state_dict,
  922. result,
  923. last_inserted_params,
  924. value_params,
  925. False,
  926. result.returned_defaults
  927. if not result.context.executemany
  928. else None,
  929. )
  930. else:
  931. _postfetch_bulk_save(mapper_rec, state_dict, table)
  932. else:
  933. # here, we need defaults and/or pk values back or we otherwise
  934. # know that we are using RETURNING in any case
  935. records = list(records)
  936. if returning_is_required_anyway or (
  937. table.implicit_returning and not hasvalue and len(records) > 1
  938. ):
  939. if (
  940. deterministic_results_reqd
  941. and connection.dialect.insert_executemany_returning_sort_by_parameter_order # noqa: E501
  942. ) or (
  943. not deterministic_results_reqd
  944. and connection.dialect.insert_executemany_returning
  945. ):
  946. do_executemany = True
  947. elif returning_is_required_anyway:
  948. if deterministic_results_reqd:
  949. dt = " with RETURNING and sort by parameter order"
  950. else:
  951. dt = " with RETURNING"
  952. raise sa_exc.InvalidRequestError(
  953. f"Can't use explicit RETURNING for bulk INSERT "
  954. f"operation with "
  955. f"{connection.dialect.dialect_description} backend; "
  956. f"executemany{dt} is not enabled for this dialect."
  957. )
  958. else:
  959. do_executemany = False
  960. else:
  961. do_executemany = False
  962. if use_orm_insert_stmt is None:
  963. if (
  964. not has_all_defaults
  965. and base_mapper._prefer_eager_defaults(
  966. connection.dialect, table
  967. )
  968. ):
  969. statement = statement.return_defaults(
  970. *mapper._server_default_cols[table],
  971. sort_by_parameter_order=bookkeeping,
  972. )
  973. if mapper.version_id_col is not None:
  974. statement = statement.return_defaults(
  975. mapper.version_id_col,
  976. sort_by_parameter_order=bookkeeping,
  977. )
  978. elif do_executemany:
  979. statement = statement.return_defaults(
  980. *table.primary_key, sort_by_parameter_order=bookkeeping
  981. )
  982. if do_executemany:
  983. multiparams = [rec[2] for rec in records]
  984. result = connection.execute(
  985. statement, multiparams, execution_options=execution_options
  986. )
  987. if use_orm_insert_stmt is not None:
  988. if return_result is None:
  989. return_result = result
  990. else:
  991. return_result = return_result.splice_vertically(result)
  992. if bookkeeping:
  993. for (
  994. (
  995. state,
  996. state_dict,
  997. params,
  998. mapper_rec,
  999. conn,
  1000. value_params,
  1001. has_all_pks,
  1002. has_all_defaults,
  1003. ),
  1004. last_inserted_params,
  1005. inserted_primary_key,
  1006. returned_defaults,
  1007. ) in zip_longest(
  1008. records,
  1009. result.context.compiled_parameters,
  1010. result.inserted_primary_key_rows,
  1011. result.returned_defaults_rows or (),
  1012. ):
  1013. if inserted_primary_key is None:
  1014. # this is a real problem and means that we didn't
  1015. # get back as many PK rows. we can't continue
  1016. # since this indicates PK rows were missing, which
  1017. # means we likely mis-populated records starting
  1018. # at that point with incorrectly matched PK
  1019. # values.
  1020. raise orm_exc.FlushError(
  1021. "Multi-row INSERT statement for %s did not "
  1022. "produce "
  1023. "the correct number of INSERTed rows for "
  1024. "RETURNING. Ensure there are no triggers or "
  1025. "special driver issues preventing INSERT from "
  1026. "functioning properly." % mapper_rec
  1027. )
  1028. for pk, col in zip(
  1029. inserted_primary_key,
  1030. mapper._pks_by_table[table],
  1031. ):
  1032. prop = mapper_rec._columntoproperty[col]
  1033. if state_dict.get(prop.key) is None:
  1034. state_dict[prop.key] = pk
  1035. if state:
  1036. _postfetch(
  1037. mapper_rec,
  1038. uowtransaction,
  1039. table,
  1040. state,
  1041. state_dict,
  1042. result,
  1043. last_inserted_params,
  1044. value_params,
  1045. False,
  1046. returned_defaults,
  1047. )
  1048. else:
  1049. _postfetch_bulk_save(mapper_rec, state_dict, table)
  1050. else:
  1051. assert not returning_is_required_anyway
  1052. for (
  1053. state,
  1054. state_dict,
  1055. params,
  1056. mapper_rec,
  1057. connection,
  1058. value_params,
  1059. has_all_pks,
  1060. has_all_defaults,
  1061. ) in records:
  1062. if value_params:
  1063. result = connection.execute(
  1064. statement.values(value_params),
  1065. params,
  1066. execution_options=execution_options,
  1067. )
  1068. else:
  1069. result = connection.execute(
  1070. statement,
  1071. params,
  1072. execution_options=execution_options,
  1073. )
  1074. primary_key = result.inserted_primary_key
  1075. if primary_key is None:
  1076. raise orm_exc.FlushError(
  1077. "Single-row INSERT statement for %s "
  1078. "did not produce a "
  1079. "new primary key result "
  1080. "being invoked. Ensure there are no triggers or "
  1081. "special driver issues preventing INSERT from "
  1082. "functioning properly." % (mapper_rec,)
  1083. )
  1084. for pk, col in zip(
  1085. primary_key, mapper._pks_by_table[table]
  1086. ):
  1087. prop = mapper_rec._columntoproperty[col]
  1088. if (
  1089. col in value_params
  1090. or state_dict.get(prop.key) is None
  1091. ):
  1092. state_dict[prop.key] = pk
  1093. if bookkeeping:
  1094. if state:
  1095. _postfetch(
  1096. mapper_rec,
  1097. uowtransaction,
  1098. table,
  1099. state,
  1100. state_dict,
  1101. result,
  1102. result.context.compiled_parameters[0],
  1103. value_params,
  1104. False,
  1105. result.returned_defaults
  1106. if not result.context.executemany
  1107. else None,
  1108. )
  1109. else:
  1110. _postfetch_bulk_save(mapper_rec, state_dict, table)
  1111. if use_orm_insert_stmt is not None:
  1112. if return_result is None:
  1113. return _cursor.null_dml_result()
  1114. else:
  1115. return return_result
  1116. def _emit_post_update_statements(
  1117. base_mapper, uowtransaction, mapper, table, update
  1118. ):
  1119. """Emit UPDATE statements corresponding to value lists collected
  1120. by _collect_post_update_commands()."""
  1121. execution_options = {"compiled_cache": base_mapper._compiled_cache}
  1122. needs_version_id = (
  1123. mapper.version_id_col is not None
  1124. and mapper.version_id_col in mapper._cols_by_table[table]
  1125. )
  1126. def update_stmt():
  1127. clauses = BooleanClauseList._construct_raw(operators.and_)
  1128. for col in mapper._pks_by_table[table]:
  1129. clauses._append_inplace(
  1130. col == sql.bindparam(col._label, type_=col.type)
  1131. )
  1132. if needs_version_id:
  1133. clauses._append_inplace(
  1134. mapper.version_id_col
  1135. == sql.bindparam(
  1136. mapper.version_id_col._label,
  1137. type_=mapper.version_id_col.type,
  1138. )
  1139. )
  1140. stmt = table.update().where(clauses)
  1141. return stmt
  1142. statement = base_mapper._memo(("post_update", table), update_stmt)
  1143. if mapper._version_id_has_server_side_value:
  1144. statement = statement.return_defaults(mapper.version_id_col)
  1145. # execute each UPDATE in the order according to the original
  1146. # list of states to guarantee row access order, but
  1147. # also group them into common (connection, cols) sets
  1148. # to support executemany().
  1149. for key, records in groupby(
  1150. update,
  1151. lambda rec: (rec[3], set(rec[4])), # connection # parameter keys
  1152. ):
  1153. rows = 0
  1154. records = list(records)
  1155. connection = key[0]
  1156. assert_singlerow = connection.dialect.supports_sane_rowcount
  1157. assert_multirow = (
  1158. assert_singlerow
  1159. and connection.dialect.supports_sane_multi_rowcount
  1160. )
  1161. allow_executemany = not needs_version_id or assert_multirow
  1162. if not allow_executemany:
  1163. check_rowcount = assert_singlerow
  1164. for state, state_dict, mapper_rec, connection, params in records:
  1165. c = connection.execute(
  1166. statement, params, execution_options=execution_options
  1167. )
  1168. _postfetch_post_update(
  1169. mapper_rec,
  1170. uowtransaction,
  1171. table,
  1172. state,
  1173. state_dict,
  1174. c,
  1175. c.context.compiled_parameters[0],
  1176. )
  1177. rows += c.rowcount
  1178. else:
  1179. multiparams = [
  1180. params
  1181. for state, state_dict, mapper_rec, conn, params in records
  1182. ]
  1183. check_rowcount = assert_multirow or (
  1184. assert_singlerow and len(multiparams) == 1
  1185. )
  1186. c = connection.execute(
  1187. statement, multiparams, execution_options=execution_options
  1188. )
  1189. rows += c.rowcount
  1190. for state, state_dict, mapper_rec, connection, params in records:
  1191. _postfetch_post_update(
  1192. mapper_rec,
  1193. uowtransaction,
  1194. table,
  1195. state,
  1196. state_dict,
  1197. c,
  1198. c.context.compiled_parameters[0],
  1199. )
  1200. if check_rowcount:
  1201. if rows != len(records):
  1202. raise orm_exc.StaleDataError(
  1203. "UPDATE statement on table '%s' expected to "
  1204. "update %d row(s); %d were matched."
  1205. % (table.description, len(records), rows)
  1206. )
  1207. elif needs_version_id:
  1208. util.warn(
  1209. "Dialect %s does not support updated rowcount "
  1210. "- versioning cannot be verified."
  1211. % c.dialect.dialect_description
  1212. )
  1213. def _emit_delete_statements(
  1214. base_mapper, uowtransaction, mapper, table, delete
  1215. ):
  1216. """Emit DELETE statements corresponding to value lists collected
  1217. by _collect_delete_commands()."""
  1218. need_version_id = (
  1219. mapper.version_id_col is not None
  1220. and mapper.version_id_col in mapper._cols_by_table[table]
  1221. )
  1222. def delete_stmt():
  1223. clauses = BooleanClauseList._construct_raw(operators.and_)
  1224. for col in mapper._pks_by_table[table]:
  1225. clauses._append_inplace(
  1226. col == sql.bindparam(col.key, type_=col.type)
  1227. )
  1228. if need_version_id:
  1229. clauses._append_inplace(
  1230. mapper.version_id_col
  1231. == sql.bindparam(
  1232. mapper.version_id_col.key, type_=mapper.version_id_col.type
  1233. )
  1234. )
  1235. return table.delete().where(clauses)
  1236. statement = base_mapper._memo(("delete", table), delete_stmt)
  1237. for connection, recs in groupby(delete, lambda rec: rec[1]): # connection
  1238. del_objects = [params for params, connection in recs]
  1239. execution_options = {"compiled_cache": base_mapper._compiled_cache}
  1240. expected = len(del_objects)
  1241. rows_matched = -1
  1242. only_warn = False
  1243. if (
  1244. need_version_id
  1245. and not connection.dialect.supports_sane_multi_rowcount
  1246. ):
  1247. if connection.dialect.supports_sane_rowcount:
  1248. rows_matched = 0
  1249. # execute deletes individually so that versioned
  1250. # rows can be verified
  1251. for params in del_objects:
  1252. c = connection.execute(
  1253. statement, params, execution_options=execution_options
  1254. )
  1255. rows_matched += c.rowcount
  1256. else:
  1257. util.warn(
  1258. "Dialect %s does not support deleted rowcount "
  1259. "- versioning cannot be verified."
  1260. % connection.dialect.dialect_description
  1261. )
  1262. connection.execute(
  1263. statement, del_objects, execution_options=execution_options
  1264. )
  1265. else:
  1266. c = connection.execute(
  1267. statement, del_objects, execution_options=execution_options
  1268. )
  1269. if not need_version_id:
  1270. only_warn = True
  1271. rows_matched = c.rowcount
  1272. if (
  1273. base_mapper.confirm_deleted_rows
  1274. and rows_matched > -1
  1275. and expected != rows_matched
  1276. and (
  1277. connection.dialect.supports_sane_multi_rowcount
  1278. or len(del_objects) == 1
  1279. )
  1280. ):
  1281. # TODO: why does this "only warn" if versioning is turned off,
  1282. # whereas the UPDATE raises?
  1283. if only_warn:
  1284. util.warn(
  1285. "DELETE statement on table '%s' expected to "
  1286. "delete %d row(s); %d were matched. Please set "
  1287. "confirm_deleted_rows=False within the mapper "
  1288. "configuration to prevent this warning."
  1289. % (table.description, expected, rows_matched)
  1290. )
  1291. else:
  1292. raise orm_exc.StaleDataError(
  1293. "DELETE statement on table '%s' expected to "
  1294. "delete %d row(s); %d were matched. Please set "
  1295. "confirm_deleted_rows=False within the mapper "
  1296. "configuration to prevent this warning."
  1297. % (table.description, expected, rows_matched)
  1298. )
  1299. def _finalize_insert_update_commands(base_mapper, uowtransaction, states):
  1300. """finalize state on states that have been inserted or updated,
  1301. including calling after_insert/after_update events.
  1302. """
  1303. for state, state_dict, mapper, connection, has_identity in states:
  1304. if mapper._readonly_props:
  1305. readonly = state.unmodified_intersection(
  1306. [
  1307. p.key
  1308. for p in mapper._readonly_props
  1309. if (
  1310. p.expire_on_flush
  1311. and (not p.deferred or p.key in state.dict)
  1312. )
  1313. or (
  1314. not p.expire_on_flush
  1315. and not p.deferred
  1316. and p.key not in state.dict
  1317. )
  1318. ]
  1319. )
  1320. if readonly:
  1321. state._expire_attributes(state.dict, readonly)
  1322. # if eager_defaults option is enabled, load
  1323. # all expired cols. Else if we have a version_id_col, make sure
  1324. # it isn't expired.
  1325. toload_now = []
  1326. # this is specifically to emit a second SELECT for eager_defaults,
  1327. # so only if it's set to True, not "auto"
  1328. if base_mapper.eager_defaults is True:
  1329. toload_now.extend(
  1330. state._unloaded_non_object.intersection(
  1331. mapper._server_default_plus_onupdate_propkeys
  1332. )
  1333. )
  1334. if (
  1335. mapper.version_id_col is not None
  1336. and mapper.version_id_generator is False
  1337. ):
  1338. if mapper._version_id_prop.key in state.unloaded:
  1339. toload_now.extend([mapper._version_id_prop.key])
  1340. if toload_now:
  1341. state.key = base_mapper._identity_key_from_state(state)
  1342. stmt = future.select(mapper).set_label_style(
  1343. LABEL_STYLE_TABLENAME_PLUS_COL
  1344. )
  1345. loading.load_on_ident(
  1346. uowtransaction.session,
  1347. stmt,
  1348. state.key,
  1349. refresh_state=state,
  1350. only_load_props=toload_now,
  1351. )
  1352. # call after_XXX extensions
  1353. if not has_identity:
  1354. mapper.dispatch.after_insert(mapper, connection, state)
  1355. else:
  1356. mapper.dispatch.after_update(mapper, connection, state)
  1357. if (
  1358. mapper.version_id_generator is False
  1359. and mapper.version_id_col is not None
  1360. ):
  1361. if state_dict[mapper._version_id_prop.key] is None:
  1362. raise orm_exc.FlushError(
  1363. "Instance does not contain a non-NULL version value"
  1364. )
  1365. def _postfetch_post_update(
  1366. mapper, uowtransaction, table, state, dict_, result, params
  1367. ):
  1368. if uowtransaction.is_deleted(state):
  1369. return
  1370. prefetch_cols = result.context.compiled.prefetch
  1371. postfetch_cols = result.context.compiled.postfetch
  1372. if (
  1373. mapper.version_id_col is not None
  1374. and mapper.version_id_col in mapper._cols_by_table[table]
  1375. ):
  1376. prefetch_cols = list(prefetch_cols) + [mapper.version_id_col]
  1377. refresh_flush = bool(mapper.class_manager.dispatch.refresh_flush)
  1378. if refresh_flush:
  1379. load_evt_attrs = []
  1380. for c in prefetch_cols:
  1381. if c.key in params and c in mapper._columntoproperty:
  1382. dict_[mapper._columntoproperty[c].key] = params[c.key]
  1383. if refresh_flush:
  1384. load_evt_attrs.append(mapper._columntoproperty[c].key)
  1385. if refresh_flush and load_evt_attrs:
  1386. mapper.class_manager.dispatch.refresh_flush(
  1387. state, uowtransaction, load_evt_attrs
  1388. )
  1389. if postfetch_cols:
  1390. state._expire_attributes(
  1391. state.dict,
  1392. [
  1393. mapper._columntoproperty[c].key
  1394. for c in postfetch_cols
  1395. if c in mapper._columntoproperty
  1396. ],
  1397. )
  1398. def _postfetch(
  1399. mapper,
  1400. uowtransaction,
  1401. table,
  1402. state,
  1403. dict_,
  1404. result,
  1405. params,
  1406. value_params,
  1407. isupdate,
  1408. returned_defaults,
  1409. ):
  1410. """Expire attributes in need of newly persisted database state,
  1411. after an INSERT or UPDATE statement has proceeded for that
  1412. state."""
  1413. prefetch_cols = result.context.compiled.prefetch
  1414. postfetch_cols = result.context.compiled.postfetch
  1415. returning_cols = result.context.compiled.effective_returning
  1416. if (
  1417. mapper.version_id_col is not None
  1418. and mapper.version_id_col in mapper._cols_by_table[table]
  1419. ):
  1420. prefetch_cols = list(prefetch_cols) + [mapper.version_id_col]
  1421. refresh_flush = bool(mapper.class_manager.dispatch.refresh_flush)
  1422. if refresh_flush:
  1423. load_evt_attrs = []
  1424. if returning_cols:
  1425. row = returned_defaults
  1426. if row is not None:
  1427. for row_value, col in zip(row, returning_cols):
  1428. # pk cols returned from insert are handled
  1429. # distinctly, don't step on the values here
  1430. if col.primary_key and result.context.isinsert:
  1431. continue
  1432. # note that columns can be in the "return defaults" that are
  1433. # not mapped to this mapper, typically because they are
  1434. # "excluded", which can be specified directly or also occurs
  1435. # when using declarative w/ single table inheritance
  1436. prop = mapper._columntoproperty.get(col)
  1437. if prop:
  1438. dict_[prop.key] = row_value
  1439. if refresh_flush:
  1440. load_evt_attrs.append(prop.key)
  1441. for c in prefetch_cols:
  1442. if c.key in params and c in mapper._columntoproperty:
  1443. pkey = mapper._columntoproperty[c].key
  1444. # set prefetched value in dict and also pop from committed_state,
  1445. # since this is new database state that replaces whatever might
  1446. # have previously been fetched (see #10800). this is essentially a
  1447. # shorthand version of set_committed_value(), which could also be
  1448. # used here directly (with more overhead)
  1449. dict_[pkey] = params[c.key]
  1450. state.committed_state.pop(pkey, None)
  1451. if refresh_flush:
  1452. load_evt_attrs.append(pkey)
  1453. if refresh_flush and load_evt_attrs:
  1454. mapper.class_manager.dispatch.refresh_flush(
  1455. state, uowtransaction, load_evt_attrs
  1456. )
  1457. if isupdate and value_params:
  1458. # explicitly suit the use case specified by
  1459. # [ticket:3801], PK SQL expressions for UPDATE on non-RETURNING
  1460. # database which are set to themselves in order to do a version bump.
  1461. postfetch_cols.extend(
  1462. [
  1463. col
  1464. for col in value_params
  1465. if col.primary_key and col not in returning_cols
  1466. ]
  1467. )
  1468. if postfetch_cols:
  1469. state._expire_attributes(
  1470. state.dict,
  1471. [
  1472. mapper._columntoproperty[c].key
  1473. for c in postfetch_cols
  1474. if c in mapper._columntoproperty
  1475. ],
  1476. )
  1477. # synchronize newly inserted ids from one table to the next
  1478. # TODO: this still goes a little too often. would be nice to
  1479. # have definitive list of "columns that changed" here
  1480. for m, equated_pairs in mapper._table_to_equated[table]:
  1481. sync.populate(
  1482. state,
  1483. m,
  1484. state,
  1485. m,
  1486. equated_pairs,
  1487. uowtransaction,
  1488. mapper.passive_updates,
  1489. )
  1490. def _postfetch_bulk_save(mapper, dict_, table):
  1491. for m, equated_pairs in mapper._table_to_equated[table]:
  1492. sync.bulk_populate_inherit_keys(dict_, m, equated_pairs)
  1493. def _connections_for_states(base_mapper, uowtransaction, states):
  1494. """Return an iterator of (state, state.dict, mapper, connection).
  1495. The states are sorted according to _sort_states, then paired
  1496. with the connection they should be using for the given
  1497. unit of work transaction.
  1498. """
  1499. # if session has a connection callable,
  1500. # organize individual states with the connection
  1501. # to use for update
  1502. if uowtransaction.session.connection_callable:
  1503. connection_callable = uowtransaction.session.connection_callable
  1504. else:
  1505. connection = uowtransaction.transaction.connection(base_mapper)
  1506. connection_callable = None
  1507. for state in _sort_states(base_mapper, states):
  1508. if connection_callable:
  1509. connection = connection_callable(base_mapper, state.obj())
  1510. mapper = state.manager.mapper
  1511. yield state, state.dict, mapper, connection
  1512. def _sort_states(mapper, states):
  1513. pending = set(states)
  1514. persistent = {s for s in pending if s.key is not None}
  1515. pending.difference_update(persistent)
  1516. try:
  1517. persistent_sorted = sorted(
  1518. persistent, key=mapper._persistent_sortkey_fn
  1519. )
  1520. except TypeError as err:
  1521. raise sa_exc.InvalidRequestError(
  1522. "Could not sort objects by primary key; primary key "
  1523. "values must be sortable in Python (was: %s)" % err
  1524. ) from err
  1525. return (
  1526. sorted(pending, key=operator.attrgetter("insert_order"))
  1527. + persistent_sorted
  1528. )