crud.py 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678
  1. # sql/crud.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: allow-untyped-defs, allow-untyped-calls
  8. """Functions used by compiler.py to determine the parameters rendered
  9. within INSERT and UPDATE statements.
  10. """
  11. from __future__ import annotations
  12. import functools
  13. import operator
  14. from typing import Any
  15. from typing import Callable
  16. from typing import cast
  17. from typing import Dict
  18. from typing import Iterable
  19. from typing import List
  20. from typing import MutableMapping
  21. from typing import NamedTuple
  22. from typing import Optional
  23. from typing import overload
  24. from typing import Sequence
  25. from typing import Set
  26. from typing import Tuple
  27. from typing import TYPE_CHECKING
  28. from typing import Union
  29. from . import coercions
  30. from . import dml
  31. from . import elements
  32. from . import roles
  33. from .base import _DefaultDescriptionTuple
  34. from .dml import isinsert as _compile_state_isinsert
  35. from .elements import ColumnClause
  36. from .schema import default_is_clause_element
  37. from .schema import default_is_sequence
  38. from .selectable import Select
  39. from .selectable import TableClause
  40. from .. import exc
  41. from .. import util
  42. from ..util.typing import Literal
  43. if TYPE_CHECKING:
  44. from .compiler import _BindNameForColProtocol
  45. from .compiler import SQLCompiler
  46. from .dml import _DMLColumnElement
  47. from .dml import DMLState
  48. from .dml import ValuesBase
  49. from .elements import ColumnElement
  50. from .elements import KeyedColumnElement
  51. from .schema import _SQLExprDefault
  52. from .schema import Column
  53. REQUIRED = util.symbol(
  54. "REQUIRED",
  55. """
  56. Placeholder for the value within a :class:`.BindParameter`
  57. which is required to be present when the statement is passed
  58. to :meth:`_engine.Connection.execute`.
  59. This symbol is typically used when a :func:`_expression.insert`
  60. or :func:`_expression.update` statement is compiled without parameter
  61. values present.
  62. """,
  63. )
  64. def _as_dml_column(c: ColumnElement[Any]) -> ColumnClause[Any]:
  65. if not isinstance(c, ColumnClause):
  66. raise exc.CompileError(
  67. f"Can't create DML statement against column expression {c!r}"
  68. )
  69. return c
  70. _CrudParamElement = Tuple[
  71. "ColumnElement[Any]",
  72. str, # column name
  73. Optional[
  74. Union[str, "_SQLExprDefault"]
  75. ], # bound parameter string or SQL expression to apply
  76. Iterable[str],
  77. ]
  78. _CrudParamElementStr = Tuple[
  79. "KeyedColumnElement[Any]",
  80. str, # column name
  81. str, # bound parameter string
  82. Iterable[str],
  83. ]
  84. _CrudParamElementSQLExpr = Tuple[
  85. "ColumnClause[Any]",
  86. str,
  87. "_SQLExprDefault", # SQL expression to apply
  88. Iterable[str],
  89. ]
  90. _CrudParamSequence = List[_CrudParamElement]
  91. class _CrudParams(NamedTuple):
  92. single_params: _CrudParamSequence
  93. all_multi_params: List[Sequence[_CrudParamElementStr]]
  94. is_default_metavalue_only: bool = False
  95. use_insertmanyvalues: bool = False
  96. use_sentinel_columns: Optional[Sequence[Column[Any]]] = None
  97. def _get_crud_params(
  98. compiler: SQLCompiler,
  99. stmt: ValuesBase,
  100. compile_state: DMLState,
  101. toplevel: bool,
  102. **kw: Any,
  103. ) -> _CrudParams:
  104. """create a set of tuples representing column/string pairs for use
  105. in an INSERT or UPDATE statement.
  106. Also generates the Compiled object's postfetch, prefetch, and
  107. returning column collections, used for default handling and ultimately
  108. populating the CursorResult's prefetch_cols() and postfetch_cols()
  109. collections.
  110. """
  111. # note: the _get_crud_params() system was written with the notion in mind
  112. # that INSERT, UPDATE, DELETE are always the top level statement and
  113. # that there is only one of them. With the addition of CTEs that can
  114. # make use of DML, this assumption is no longer accurate; the DML
  115. # statement is not necessarily the top-level "row returning" thing
  116. # and it is also theoretically possible (fortunately nobody has asked yet)
  117. # to have a single statement with multiple DMLs inside of it via CTEs.
  118. # the current _get_crud_params() design doesn't accommodate these cases
  119. # right now. It "just works" for a CTE that has a single DML inside of
  120. # it, and for a CTE with multiple DML, it's not clear what would happen.
  121. # overall, the "compiler.XYZ" collections here would need to be in a
  122. # per-DML structure of some kind, and DefaultDialect would need to
  123. # navigate these collections on a per-statement basis, with additional
  124. # emphasis on the "toplevel returning data" statement. However we
  125. # still need to run through _get_crud_params() for all DML as we have
  126. # Python / SQL generated column defaults that need to be rendered.
  127. # if there is user need for this kind of thing, it's likely a post 2.0
  128. # kind of change as it would require deep changes to DefaultDialect
  129. # as well as here.
  130. compiler.postfetch = []
  131. compiler.insert_prefetch = []
  132. compiler.update_prefetch = []
  133. compiler.implicit_returning = []
  134. visiting_cte = kw.get("visiting_cte", None)
  135. if visiting_cte is not None:
  136. # for insert -> CTE -> insert, don't populate an incoming
  137. # _crud_accumulate_bind_names collection; the INSERT we process here
  138. # will not be inline within the VALUES of the enclosing INSERT as the
  139. # CTE is placed on the outside. See issue #9173
  140. kw.pop("accumulate_bind_names", None)
  141. assert (
  142. "accumulate_bind_names" not in kw
  143. ), "Don't know how to handle insert within insert without a CTE"
  144. # getters - these are normally just column.key,
  145. # but in the case of mysql multi-table update, the rules for
  146. # .key must conditionally take tablename into account
  147. (
  148. _column_as_key,
  149. _getattr_col_key,
  150. _col_bind_name,
  151. ) = _key_getters_for_crud_column(compiler, stmt, compile_state)
  152. compiler._get_bind_name_for_col = _col_bind_name
  153. if stmt._returning and stmt._return_defaults:
  154. raise exc.CompileError(
  155. "Can't compile statement that includes returning() and "
  156. "return_defaults() simultaneously"
  157. )
  158. if compile_state.isdelete:
  159. _setup_delete_return_defaults(
  160. compiler,
  161. stmt,
  162. compile_state,
  163. (),
  164. _getattr_col_key,
  165. _column_as_key,
  166. _col_bind_name,
  167. (),
  168. (),
  169. toplevel,
  170. kw,
  171. )
  172. return _CrudParams([], [])
  173. # no parameters in the statement, no parameters in the
  174. # compiled params - return binds for all columns
  175. if compiler.column_keys is None and compile_state._no_parameters:
  176. return _CrudParams(
  177. [
  178. (
  179. c,
  180. compiler.preparer.format_column(c),
  181. _create_bind_param(compiler, c, None, required=True),
  182. (c.key,),
  183. )
  184. for c in stmt.table.columns
  185. if not c._omit_from_statements
  186. ],
  187. [],
  188. )
  189. stmt_parameter_tuples: Optional[
  190. List[Tuple[Union[str, ColumnClause[Any]], Any]]
  191. ]
  192. spd: Optional[MutableMapping[_DMLColumnElement, Any]]
  193. if (
  194. _compile_state_isinsert(compile_state)
  195. and compile_state._has_multi_parameters
  196. ):
  197. mp = compile_state._multi_parameters
  198. assert mp is not None
  199. spd = mp[0]
  200. stmt_parameter_tuples = list(spd.items())
  201. spd_str_key = {_column_as_key(key) for key in spd}
  202. elif compile_state._ordered_values:
  203. spd = compile_state._dict_parameters
  204. stmt_parameter_tuples = compile_state._ordered_values
  205. assert spd is not None
  206. spd_str_key = {_column_as_key(key) for key in spd}
  207. elif compile_state._dict_parameters:
  208. spd = compile_state._dict_parameters
  209. stmt_parameter_tuples = list(spd.items())
  210. spd_str_key = {_column_as_key(key) for key in spd}
  211. else:
  212. stmt_parameter_tuples = spd_str_key = None
  213. # if we have statement parameters - set defaults in the
  214. # compiled params
  215. if compiler.column_keys is None:
  216. parameters = {}
  217. elif stmt_parameter_tuples:
  218. assert spd_str_key is not None
  219. parameters = {
  220. _column_as_key(key): REQUIRED
  221. for key in compiler.column_keys
  222. if key not in spd_str_key
  223. }
  224. else:
  225. parameters = {
  226. _column_as_key(key): REQUIRED for key in compiler.column_keys
  227. }
  228. # create a list of column assignment clauses as tuples
  229. values: List[_CrudParamElement] = []
  230. if stmt_parameter_tuples is not None:
  231. _get_stmt_parameter_tuples_params(
  232. compiler,
  233. compile_state,
  234. parameters,
  235. stmt_parameter_tuples,
  236. _column_as_key,
  237. values,
  238. kw,
  239. )
  240. check_columns: Dict[str, ColumnClause[Any]] = {}
  241. # special logic that only occurs for multi-table UPDATE
  242. # statements
  243. if dml.isupdate(compile_state) and compile_state.is_multitable:
  244. _get_update_multitable_params(
  245. compiler,
  246. stmt,
  247. compile_state,
  248. stmt_parameter_tuples,
  249. check_columns,
  250. _col_bind_name,
  251. _getattr_col_key,
  252. values,
  253. kw,
  254. )
  255. if _compile_state_isinsert(compile_state) and stmt._select_names:
  256. # is an insert from select, is not a multiparams
  257. assert not compile_state._has_multi_parameters
  258. _scan_insert_from_select_cols(
  259. compiler,
  260. stmt,
  261. compile_state,
  262. parameters,
  263. _getattr_col_key,
  264. _column_as_key,
  265. _col_bind_name,
  266. check_columns,
  267. values,
  268. toplevel,
  269. kw,
  270. )
  271. use_insertmanyvalues = False
  272. use_sentinel_columns = None
  273. else:
  274. use_insertmanyvalues, use_sentinel_columns = _scan_cols(
  275. compiler,
  276. stmt,
  277. compile_state,
  278. parameters,
  279. _getattr_col_key,
  280. _column_as_key,
  281. _col_bind_name,
  282. check_columns,
  283. values,
  284. toplevel,
  285. kw,
  286. )
  287. if parameters and stmt_parameter_tuples:
  288. check = (
  289. set(parameters)
  290. .intersection(_column_as_key(k) for k, v in stmt_parameter_tuples)
  291. .difference(check_columns)
  292. )
  293. if check:
  294. raise exc.CompileError(
  295. "Unconsumed column names: %s"
  296. % (", ".join("%s" % (c,) for c in check))
  297. )
  298. is_default_metavalue_only = False
  299. if (
  300. _compile_state_isinsert(compile_state)
  301. and compile_state._has_multi_parameters
  302. ):
  303. # is a multiparams, is not an insert from a select
  304. assert not stmt._select_names
  305. multi_extended_values = _extend_values_for_multiparams(
  306. compiler,
  307. stmt,
  308. compile_state,
  309. cast(
  310. "Sequence[_CrudParamElementStr]",
  311. values,
  312. ),
  313. cast("Callable[..., str]", _column_as_key),
  314. kw,
  315. )
  316. return _CrudParams(values, multi_extended_values)
  317. elif (
  318. not values
  319. and compiler.for_executemany
  320. and compiler.dialect.supports_default_metavalue
  321. ):
  322. # convert an "INSERT DEFAULT VALUES"
  323. # into INSERT (firstcol) VALUES (DEFAULT) which can be turned
  324. # into an in-place multi values. This supports
  325. # insert_executemany_returning mode :)
  326. values = [
  327. (
  328. _as_dml_column(stmt.table.columns[0]),
  329. compiler.preparer.format_column(stmt.table.columns[0]),
  330. compiler.dialect.default_metavalue_token,
  331. (),
  332. )
  333. ]
  334. is_default_metavalue_only = True
  335. return _CrudParams(
  336. values,
  337. [],
  338. is_default_metavalue_only=is_default_metavalue_only,
  339. use_insertmanyvalues=use_insertmanyvalues,
  340. use_sentinel_columns=use_sentinel_columns,
  341. )
  342. @overload
  343. def _create_bind_param(
  344. compiler: SQLCompiler,
  345. col: ColumnElement[Any],
  346. value: Any,
  347. process: Literal[True] = ...,
  348. required: bool = False,
  349. name: Optional[str] = None,
  350. force_anonymous: bool = False,
  351. **kw: Any,
  352. ) -> str: ...
  353. @overload
  354. def _create_bind_param(
  355. compiler: SQLCompiler,
  356. col: ColumnElement[Any],
  357. value: Any,
  358. **kw: Any,
  359. ) -> str: ...
  360. def _create_bind_param(
  361. compiler: SQLCompiler,
  362. col: ColumnElement[Any],
  363. value: Any,
  364. process: bool = True,
  365. required: bool = False,
  366. name: Optional[str] = None,
  367. force_anonymous: bool = False,
  368. **kw: Any,
  369. ) -> Union[str, elements.BindParameter[Any]]:
  370. if force_anonymous:
  371. name = None
  372. elif name is None:
  373. name = col.key
  374. bindparam = elements.BindParameter(
  375. name, value, type_=col.type, required=required
  376. )
  377. bindparam._is_crud = True
  378. if process:
  379. return bindparam._compiler_dispatch(compiler, **kw)
  380. else:
  381. return bindparam
  382. def _handle_values_anonymous_param(compiler, col, value, name, **kw):
  383. # the insert() and update() constructs as of 1.4 will now produce anonymous
  384. # bindparam() objects in the values() collections up front when given plain
  385. # literal values. This is so that cache key behaviors, which need to
  386. # produce bound parameters in deterministic order without invoking any
  387. # compilation here, can be applied to these constructs when they include
  388. # values() (but not yet multi-values, which are not included in caching
  389. # right now).
  390. #
  391. # in order to produce the desired "crud" style name for these parameters,
  392. # which will also be targetable in engine/default.py through the usual
  393. # conventions, apply our desired name to these unique parameters by
  394. # populating the compiler truncated names cache with the desired name,
  395. # rather than having
  396. # compiler.visit_bindparam()->compiler._truncated_identifier make up a
  397. # name. Saves on call counts also.
  398. # for INSERT/UPDATE that's a CTE, we don't need names to match to
  399. # external parameters and these would also conflict in the case where
  400. # multiple insert/update are combined together using CTEs
  401. is_cte = "visiting_cte" in kw
  402. if (
  403. not is_cte
  404. and value.unique
  405. and isinstance(value.key, elements._truncated_label)
  406. ):
  407. compiler.truncated_names[("bindparam", value.key)] = name
  408. if value.type._isnull:
  409. # either unique parameter, or other bound parameters that were
  410. # passed in directly
  411. # set type to that of the column unconditionally
  412. value = value._with_binary_element_type(col.type)
  413. return value._compiler_dispatch(compiler, **kw)
  414. def _key_getters_for_crud_column(
  415. compiler: SQLCompiler, stmt: ValuesBase, compile_state: DMLState
  416. ) -> Tuple[
  417. Callable[[Union[str, ColumnClause[Any]]], Union[str, Tuple[str, str]]],
  418. Callable[[ColumnClause[Any]], Union[str, Tuple[str, str]]],
  419. _BindNameForColProtocol,
  420. ]:
  421. if dml.isupdate(compile_state) and compile_state._extra_froms:
  422. # when extra tables are present, refer to the columns
  423. # in those extra tables as table-qualified, including in
  424. # dictionaries and when rendering bind param names.
  425. # the "main" table of the statement remains unqualified,
  426. # allowing the most compatibility with a non-multi-table
  427. # statement.
  428. _et = set(compile_state._extra_froms)
  429. c_key_role = functools.partial(
  430. coercions.expect_as_key, roles.DMLColumnRole
  431. )
  432. def _column_as_key(
  433. key: Union[ColumnClause[Any], str],
  434. ) -> Union[str, Tuple[str, str]]:
  435. str_key = c_key_role(key)
  436. if hasattr(key, "table") and key.table in _et:
  437. return (key.table.name, str_key) # type: ignore
  438. else:
  439. return str_key
  440. def _getattr_col_key(
  441. col: ColumnClause[Any],
  442. ) -> Union[str, Tuple[str, str]]:
  443. if col.table in _et:
  444. return (col.table.name, col.key) # type: ignore
  445. else:
  446. return col.key
  447. def _col_bind_name(col: ColumnClause[Any]) -> str:
  448. if col.table in _et:
  449. if TYPE_CHECKING:
  450. assert isinstance(col.table, TableClause)
  451. return "%s_%s" % (col.table.name, col.key)
  452. else:
  453. return col.key
  454. else:
  455. _column_as_key = functools.partial(
  456. coercions.expect_as_key, roles.DMLColumnRole
  457. )
  458. _getattr_col_key = _col_bind_name = operator.attrgetter("key") # type: ignore # noqa: E501
  459. return _column_as_key, _getattr_col_key, _col_bind_name
  460. def _scan_insert_from_select_cols(
  461. compiler,
  462. stmt,
  463. compile_state,
  464. parameters,
  465. _getattr_col_key,
  466. _column_as_key,
  467. _col_bind_name,
  468. check_columns,
  469. values,
  470. toplevel,
  471. kw,
  472. ):
  473. cols = [stmt.table.c[_column_as_key(name)] for name in stmt._select_names]
  474. assert compiler.stack[-1]["selectable"] is stmt
  475. compiler.stack[-1]["insert_from_select"] = stmt.select
  476. add_select_cols: List[_CrudParamElementSQLExpr] = []
  477. if stmt.include_insert_from_select_defaults:
  478. col_set = set(cols)
  479. for col in stmt.table.columns:
  480. # omit columns that were not in the SELECT statement.
  481. # this will omit columns marked as omit_from_statements naturally,
  482. # as long as that col was not explicit in the SELECT.
  483. # if an omit_from_statements col has a "default" on it, then
  484. # we need to include it, as these defaults should still fire off.
  485. # but, if it has that default and it's the "sentinel" default,
  486. # we don't do sentinel default operations for insert_from_select
  487. # here so we again omit it.
  488. if (
  489. col not in col_set
  490. and col.default
  491. and not col.default.is_sentinel
  492. ):
  493. cols.append(col)
  494. for c in cols:
  495. col_key = _getattr_col_key(c)
  496. if col_key in parameters and col_key not in check_columns:
  497. parameters.pop(col_key)
  498. values.append((c, compiler.preparer.format_column(c), None, ()))
  499. else:
  500. _append_param_insert_select_hasdefault(
  501. compiler, stmt, c, add_select_cols, kw
  502. )
  503. if add_select_cols:
  504. values.extend(add_select_cols)
  505. ins_from_select = compiler.stack[-1]["insert_from_select"]
  506. if not isinstance(ins_from_select, Select):
  507. raise exc.CompileError(
  508. f"Can't extend statement for INSERT..FROM SELECT to include "
  509. f"additional default-holding column(s) "
  510. f"""{
  511. ', '.join(repr(key) for _, key, _, _ in add_select_cols)
  512. }. Convert the selectable to a subquery() first, or pass """
  513. "include_defaults=False to Insert.from_select() to skip these "
  514. "columns."
  515. )
  516. ins_from_select = ins_from_select._generate()
  517. # copy raw_columns
  518. ins_from_select._raw_columns = list(ins_from_select._raw_columns) + [
  519. expr for _, _, expr, _ in add_select_cols
  520. ]
  521. compiler.stack[-1]["insert_from_select"] = ins_from_select
  522. def _scan_cols(
  523. compiler,
  524. stmt,
  525. compile_state,
  526. parameters,
  527. _getattr_col_key,
  528. _column_as_key,
  529. _col_bind_name,
  530. check_columns,
  531. values,
  532. toplevel,
  533. kw,
  534. ):
  535. (
  536. need_pks,
  537. implicit_returning,
  538. implicit_return_defaults,
  539. postfetch_lastrowid,
  540. use_insertmanyvalues,
  541. use_sentinel_columns,
  542. ) = _get_returning_modifiers(compiler, stmt, compile_state, toplevel)
  543. assert compile_state.isupdate or compile_state.isinsert
  544. if compile_state._parameter_ordering:
  545. parameter_ordering = [
  546. _column_as_key(key) for key in compile_state._parameter_ordering
  547. ]
  548. ordered_keys = set(parameter_ordering)
  549. cols = [
  550. stmt.table.c[key]
  551. for key in parameter_ordering
  552. if isinstance(key, str) and key in stmt.table.c
  553. ] + [c for c in stmt.table.c if c.key not in ordered_keys]
  554. else:
  555. cols = stmt.table.columns
  556. isinsert = _compile_state_isinsert(compile_state)
  557. if isinsert and not compile_state._has_multi_parameters:
  558. # new rules for #7998. fetch lastrowid or implicit returning
  559. # for autoincrement column even if parameter is NULL, for DBs that
  560. # override NULL param for primary key (sqlite, mysql/mariadb)
  561. autoincrement_col = stmt.table._autoincrement_column
  562. insert_null_pk_still_autoincrements = (
  563. compiler.dialect.insert_null_pk_still_autoincrements
  564. )
  565. else:
  566. autoincrement_col = insert_null_pk_still_autoincrements = None
  567. if stmt._supplemental_returning:
  568. supplemental_returning = set(stmt._supplemental_returning)
  569. else:
  570. supplemental_returning = set()
  571. compiler_implicit_returning = compiler.implicit_returning
  572. # TODO - see TODO(return_defaults_columns) below
  573. # cols_in_params = set()
  574. for c in cols:
  575. # scan through every column in the target table
  576. col_key = _getattr_col_key(c)
  577. if col_key in parameters and col_key not in check_columns:
  578. # parameter is present for the column. use that.
  579. _append_param_parameter(
  580. compiler,
  581. stmt,
  582. compile_state,
  583. c,
  584. col_key,
  585. parameters,
  586. _col_bind_name,
  587. implicit_returning,
  588. implicit_return_defaults,
  589. postfetch_lastrowid,
  590. values,
  591. autoincrement_col,
  592. insert_null_pk_still_autoincrements,
  593. kw,
  594. )
  595. # TODO - see TODO(return_defaults_columns) below
  596. # cols_in_params.add(c)
  597. elif isinsert:
  598. # no parameter is present and it's an insert.
  599. if c.primary_key and need_pks:
  600. # it's a primary key column, it will need to be generated by a
  601. # default generator of some kind, and the statement expects
  602. # inserted_primary_key to be available.
  603. if implicit_returning:
  604. # we can use RETURNING, find out how to invoke this
  605. # column and get the value where RETURNING is an option.
  606. # we can inline server-side functions in this case.
  607. _append_param_insert_pk_returning(
  608. compiler, stmt, c, values, kw
  609. )
  610. else:
  611. # otherwise, find out how to invoke this column
  612. # and get its value where RETURNING is not an option.
  613. # if we have to invoke a server-side function, we need
  614. # to pre-execute it. or if this is a straight
  615. # autoincrement column and the dialect supports it
  616. # we can use cursor.lastrowid.
  617. _append_param_insert_pk_no_returning(
  618. compiler, stmt, c, values, kw
  619. )
  620. elif c.default is not None:
  621. # column has a default, but it's not a pk column, or it is but
  622. # we don't need to get the pk back.
  623. if not c.default.is_sentinel or (
  624. use_sentinel_columns is not None
  625. ):
  626. _append_param_insert_hasdefault(
  627. compiler, stmt, c, implicit_return_defaults, values, kw
  628. )
  629. elif c.server_default is not None:
  630. # column has a DDL-level default, and is either not a pk
  631. # column or we don't need the pk.
  632. if implicit_return_defaults and c in implicit_return_defaults:
  633. compiler_implicit_returning.append(c)
  634. elif not c.primary_key:
  635. compiler.postfetch.append(c)
  636. elif implicit_return_defaults and c in implicit_return_defaults:
  637. compiler_implicit_returning.append(c)
  638. elif (
  639. c.primary_key
  640. and c is not stmt.table._autoincrement_column
  641. and not c.nullable
  642. ):
  643. _warn_pk_with_no_anticipated_value(c)
  644. elif compile_state.isupdate:
  645. # no parameter is present and it's an insert.
  646. _append_param_update(
  647. compiler,
  648. compile_state,
  649. stmt,
  650. c,
  651. implicit_return_defaults,
  652. values,
  653. kw,
  654. )
  655. # adding supplemental cols to implicit_returning in table
  656. # order so that order is maintained between multiple INSERT
  657. # statements which may have different parameters included, but all
  658. # have the same RETURNING clause
  659. if (
  660. c in supplemental_returning
  661. and c not in compiler_implicit_returning
  662. ):
  663. compiler_implicit_returning.append(c)
  664. if supplemental_returning:
  665. # we should have gotten every col into implicit_returning,
  666. # however supplemental returning can also have SQL functions etc.
  667. # in it
  668. remaining_supplemental = supplemental_returning.difference(
  669. compiler_implicit_returning
  670. )
  671. compiler_implicit_returning.extend(
  672. c
  673. for c in stmt._supplemental_returning
  674. if c in remaining_supplemental
  675. )
  676. # TODO(return_defaults_columns): there can still be more columns in
  677. # _return_defaults_columns in the case that they are from something like an
  678. # aliased of the table. we can add them here, however this breaks other ORM
  679. # things. so this is for another day. see
  680. # test/orm/dml/test_update_delete_where.py -> test_update_from_alias
  681. # if stmt._return_defaults_columns:
  682. # compiler_implicit_returning.extend(
  683. # set(stmt._return_defaults_columns)
  684. # .difference(compiler_implicit_returning)
  685. # .difference(cols_in_params)
  686. # )
  687. return (use_insertmanyvalues, use_sentinel_columns)
  688. def _setup_delete_return_defaults(
  689. compiler,
  690. stmt,
  691. compile_state,
  692. parameters,
  693. _getattr_col_key,
  694. _column_as_key,
  695. _col_bind_name,
  696. check_columns,
  697. values,
  698. toplevel,
  699. kw,
  700. ):
  701. (_, _, implicit_return_defaults, *_) = _get_returning_modifiers(
  702. compiler, stmt, compile_state, toplevel
  703. )
  704. if not implicit_return_defaults:
  705. return
  706. if stmt._return_defaults_columns:
  707. compiler.implicit_returning.extend(implicit_return_defaults)
  708. if stmt._supplemental_returning:
  709. ir_set = set(compiler.implicit_returning)
  710. compiler.implicit_returning.extend(
  711. c for c in stmt._supplemental_returning if c not in ir_set
  712. )
  713. def _append_param_parameter(
  714. compiler,
  715. stmt,
  716. compile_state,
  717. c,
  718. col_key,
  719. parameters,
  720. _col_bind_name,
  721. implicit_returning,
  722. implicit_return_defaults,
  723. postfetch_lastrowid,
  724. values,
  725. autoincrement_col,
  726. insert_null_pk_still_autoincrements,
  727. kw,
  728. ):
  729. value = parameters.pop(col_key)
  730. has_visiting_cte = kw.get("visiting_cte") is not None
  731. col_value = compiler.preparer.format_column(
  732. c, use_table=compile_state.include_table_with_column_exprs
  733. )
  734. accumulated_bind_names: Set[str] = set()
  735. if coercions._is_literal(value):
  736. if (
  737. insert_null_pk_still_autoincrements
  738. and c.primary_key
  739. and c is autoincrement_col
  740. ):
  741. # support use case for #7998, fetch autoincrement cols
  742. # even if value was given.
  743. if postfetch_lastrowid:
  744. compiler.postfetch_lastrowid = True
  745. elif implicit_returning:
  746. compiler.implicit_returning.append(c)
  747. value = _create_bind_param(
  748. compiler,
  749. c,
  750. value,
  751. required=value is REQUIRED,
  752. name=(
  753. _col_bind_name(c)
  754. if not _compile_state_isinsert(compile_state)
  755. or not compile_state._has_multi_parameters
  756. else "%s_m0" % _col_bind_name(c)
  757. ),
  758. accumulate_bind_names=accumulated_bind_names,
  759. force_anonymous=has_visiting_cte,
  760. **kw,
  761. )
  762. elif value._is_bind_parameter:
  763. if (
  764. insert_null_pk_still_autoincrements
  765. and value.value is None
  766. and c.primary_key
  767. and c is autoincrement_col
  768. ):
  769. # support use case for #7998, fetch autoincrement cols
  770. # even if value was given
  771. if implicit_returning:
  772. compiler.implicit_returning.append(c)
  773. elif compiler.dialect.postfetch_lastrowid:
  774. compiler.postfetch_lastrowid = True
  775. value = _handle_values_anonymous_param(
  776. compiler,
  777. c,
  778. value,
  779. name=(
  780. _col_bind_name(c)
  781. if not _compile_state_isinsert(compile_state)
  782. or not compile_state._has_multi_parameters
  783. else "%s_m0" % _col_bind_name(c)
  784. ),
  785. accumulate_bind_names=accumulated_bind_names,
  786. **kw,
  787. )
  788. else:
  789. # value is a SQL expression
  790. value = compiler.process(
  791. value.self_group(),
  792. accumulate_bind_names=accumulated_bind_names,
  793. **kw,
  794. )
  795. if compile_state.isupdate:
  796. if implicit_return_defaults and c in implicit_return_defaults:
  797. compiler.implicit_returning.append(c)
  798. else:
  799. compiler.postfetch.append(c)
  800. else:
  801. if c.primary_key:
  802. if implicit_returning:
  803. compiler.implicit_returning.append(c)
  804. elif compiler.dialect.postfetch_lastrowid:
  805. compiler.postfetch_lastrowid = True
  806. elif implicit_return_defaults and (c in implicit_return_defaults):
  807. compiler.implicit_returning.append(c)
  808. else:
  809. # postfetch specifically means, "we can SELECT the row we just
  810. # inserted by primary key to get back the server generated
  811. # defaults". so by definition this can't be used to get the
  812. # primary key value back, because we need to have it ahead of
  813. # time.
  814. compiler.postfetch.append(c)
  815. values.append((c, col_value, value, accumulated_bind_names))
  816. def _append_param_insert_pk_returning(compiler, stmt, c, values, kw):
  817. """Create a primary key expression in the INSERT statement where
  818. we want to populate result.inserted_primary_key and RETURNING
  819. is available.
  820. """
  821. if c.default is not None:
  822. if c.default.is_sequence:
  823. if compiler.dialect.supports_sequences and (
  824. not c.default.optional
  825. or not compiler.dialect.sequences_optional
  826. ):
  827. accumulated_bind_names: Set[str] = set()
  828. values.append(
  829. (
  830. c,
  831. compiler.preparer.format_column(c),
  832. compiler.process(
  833. c.default,
  834. accumulate_bind_names=accumulated_bind_names,
  835. **kw,
  836. ),
  837. accumulated_bind_names,
  838. )
  839. )
  840. compiler.implicit_returning.append(c)
  841. elif c.default.is_clause_element:
  842. accumulated_bind_names = set()
  843. values.append(
  844. (
  845. c,
  846. compiler.preparer.format_column(c),
  847. compiler.process(
  848. c.default.arg.self_group(),
  849. accumulate_bind_names=accumulated_bind_names,
  850. **kw,
  851. ),
  852. accumulated_bind_names,
  853. )
  854. )
  855. compiler.implicit_returning.append(c)
  856. else:
  857. # client side default. OK we can't use RETURNING, need to
  858. # do a "prefetch", which in fact fetches the default value
  859. # on the Python side
  860. values.append(
  861. (
  862. c,
  863. compiler.preparer.format_column(c),
  864. _create_insert_prefetch_bind_param(compiler, c, **kw),
  865. (c.key,),
  866. )
  867. )
  868. elif c is stmt.table._autoincrement_column or c.server_default is not None:
  869. compiler.implicit_returning.append(c)
  870. elif not c.nullable:
  871. # no .default, no .server_default, not autoincrement, we have
  872. # no indication this primary key column will have any value
  873. _warn_pk_with_no_anticipated_value(c)
  874. def _append_param_insert_pk_no_returning(compiler, stmt, c, values, kw):
  875. """Create a primary key expression in the INSERT statement where
  876. we want to populate result.inserted_primary_key and we cannot use
  877. RETURNING.
  878. Depending on the kind of default here we may create a bound parameter
  879. in the INSERT statement and pre-execute a default generation function,
  880. or we may use cursor.lastrowid if supported by the dialect.
  881. """
  882. if (
  883. # column has a Python-side default
  884. c.default is not None
  885. and (
  886. # and it either is not a sequence, or it is and we support
  887. # sequences and want to invoke it
  888. not c.default.is_sequence
  889. or (
  890. compiler.dialect.supports_sequences
  891. and (
  892. not c.default.optional
  893. or not compiler.dialect.sequences_optional
  894. )
  895. )
  896. )
  897. ) or (
  898. # column is the "autoincrement column"
  899. c is stmt.table._autoincrement_column
  900. and (
  901. # dialect can't use cursor.lastrowid
  902. not compiler.dialect.postfetch_lastrowid
  903. and (
  904. # column has a Sequence and we support those
  905. (
  906. c.default is not None
  907. and c.default.is_sequence
  908. and compiler.dialect.supports_sequences
  909. )
  910. or
  911. # column has no default on it, but dialect can run the
  912. # "autoincrement" mechanism explicitly, e.g. PostgreSQL
  913. # SERIAL we know the sequence name
  914. (
  915. c.default is None
  916. and compiler.dialect.preexecute_autoincrement_sequences
  917. )
  918. )
  919. )
  920. ):
  921. # do a pre-execute of the default
  922. values.append(
  923. (
  924. c,
  925. compiler.preparer.format_column(c),
  926. _create_insert_prefetch_bind_param(compiler, c, **kw),
  927. (c.key,),
  928. )
  929. )
  930. elif (
  931. c.default is None
  932. and c.server_default is None
  933. and not c.nullable
  934. and c is not stmt.table._autoincrement_column
  935. ):
  936. # no .default, no .server_default, not autoincrement, we have
  937. # no indication this primary key column will have any value
  938. _warn_pk_with_no_anticipated_value(c)
  939. elif compiler.dialect.postfetch_lastrowid:
  940. # finally, where it seems like there will be a generated primary key
  941. # value and we haven't set up any other way to fetch it, and the
  942. # dialect supports cursor.lastrowid, switch on the lastrowid flag so
  943. # that the DefaultExecutionContext calls upon cursor.lastrowid
  944. compiler.postfetch_lastrowid = True
  945. def _append_param_insert_hasdefault(
  946. compiler, stmt, c, implicit_return_defaults, values, kw
  947. ):
  948. if c.default.is_sequence:
  949. if compiler.dialect.supports_sequences and (
  950. not c.default.optional or not compiler.dialect.sequences_optional
  951. ):
  952. accumulated_bind_names: Set[str] = set()
  953. values.append(
  954. (
  955. c,
  956. compiler.preparer.format_column(c),
  957. compiler.process(
  958. c.default,
  959. accumulate_bind_names=accumulated_bind_names,
  960. **kw,
  961. ),
  962. accumulated_bind_names,
  963. )
  964. )
  965. if implicit_return_defaults and c in implicit_return_defaults:
  966. compiler.implicit_returning.append(c)
  967. elif not c.primary_key:
  968. compiler.postfetch.append(c)
  969. elif c.default.is_clause_element:
  970. accumulated_bind_names = set()
  971. values.append(
  972. (
  973. c,
  974. compiler.preparer.format_column(c),
  975. compiler.process(
  976. c.default.arg.self_group(),
  977. accumulate_bind_names=accumulated_bind_names,
  978. **kw,
  979. ),
  980. accumulated_bind_names,
  981. )
  982. )
  983. if implicit_return_defaults and c in implicit_return_defaults:
  984. compiler.implicit_returning.append(c)
  985. elif not c.primary_key:
  986. # don't add primary key column to postfetch
  987. compiler.postfetch.append(c)
  988. else:
  989. values.append(
  990. (
  991. c,
  992. compiler.preparer.format_column(c),
  993. _create_insert_prefetch_bind_param(compiler, c, **kw),
  994. (c.key,),
  995. )
  996. )
  997. def _append_param_insert_select_hasdefault(
  998. compiler: SQLCompiler,
  999. stmt: ValuesBase,
  1000. c: ColumnClause[Any],
  1001. values: List[_CrudParamElementSQLExpr],
  1002. kw: Dict[str, Any],
  1003. ) -> None:
  1004. if default_is_sequence(c.default):
  1005. if compiler.dialect.supports_sequences and (
  1006. not c.default.optional or not compiler.dialect.sequences_optional
  1007. ):
  1008. values.append(
  1009. (
  1010. c,
  1011. compiler.preparer.format_column(c),
  1012. c.default.next_value(),
  1013. (),
  1014. )
  1015. )
  1016. elif default_is_clause_element(c.default):
  1017. values.append(
  1018. (
  1019. c,
  1020. compiler.preparer.format_column(c),
  1021. c.default.arg.self_group(),
  1022. (),
  1023. )
  1024. )
  1025. else:
  1026. values.append(
  1027. (
  1028. c,
  1029. compiler.preparer.format_column(c),
  1030. _create_insert_prefetch_bind_param(
  1031. compiler, c, process=False, **kw
  1032. ),
  1033. (c.key,),
  1034. )
  1035. )
  1036. def _append_param_update(
  1037. compiler, compile_state, stmt, c, implicit_return_defaults, values, kw
  1038. ):
  1039. include_table = compile_state.include_table_with_column_exprs
  1040. if c.onupdate is not None and not c.onupdate.is_sequence:
  1041. if c.onupdate.is_clause_element:
  1042. values.append(
  1043. (
  1044. c,
  1045. compiler.preparer.format_column(
  1046. c,
  1047. use_table=include_table,
  1048. ),
  1049. compiler.process(c.onupdate.arg.self_group(), **kw),
  1050. (),
  1051. )
  1052. )
  1053. if implicit_return_defaults and c in implicit_return_defaults:
  1054. compiler.implicit_returning.append(c)
  1055. else:
  1056. compiler.postfetch.append(c)
  1057. else:
  1058. values.append(
  1059. (
  1060. c,
  1061. compiler.preparer.format_column(
  1062. c,
  1063. use_table=include_table,
  1064. ),
  1065. _create_update_prefetch_bind_param(compiler, c, **kw),
  1066. (c.key,),
  1067. )
  1068. )
  1069. elif c.server_onupdate is not None:
  1070. if implicit_return_defaults and c in implicit_return_defaults:
  1071. compiler.implicit_returning.append(c)
  1072. else:
  1073. compiler.postfetch.append(c)
  1074. elif (
  1075. implicit_return_defaults
  1076. and (stmt._return_defaults_columns or not stmt._return_defaults)
  1077. and c in implicit_return_defaults
  1078. ):
  1079. compiler.implicit_returning.append(c)
  1080. @overload
  1081. def _create_insert_prefetch_bind_param(
  1082. compiler: SQLCompiler,
  1083. c: ColumnElement[Any],
  1084. process: Literal[True] = ...,
  1085. **kw: Any,
  1086. ) -> str: ...
  1087. @overload
  1088. def _create_insert_prefetch_bind_param(
  1089. compiler: SQLCompiler,
  1090. c: ColumnElement[Any],
  1091. process: Literal[False],
  1092. **kw: Any,
  1093. ) -> elements.BindParameter[Any]: ...
  1094. def _create_insert_prefetch_bind_param(
  1095. compiler: SQLCompiler,
  1096. c: ColumnElement[Any],
  1097. process: bool = True,
  1098. name: Optional[str] = None,
  1099. **kw: Any,
  1100. ) -> Union[elements.BindParameter[Any], str]:
  1101. param = _create_bind_param(
  1102. compiler, c, None, process=process, name=name, **kw
  1103. )
  1104. compiler.insert_prefetch.append(c) # type: ignore
  1105. return param
  1106. @overload
  1107. def _create_update_prefetch_bind_param(
  1108. compiler: SQLCompiler,
  1109. c: ColumnElement[Any],
  1110. process: Literal[True] = ...,
  1111. **kw: Any,
  1112. ) -> str: ...
  1113. @overload
  1114. def _create_update_prefetch_bind_param(
  1115. compiler: SQLCompiler,
  1116. c: ColumnElement[Any],
  1117. process: Literal[False],
  1118. **kw: Any,
  1119. ) -> elements.BindParameter[Any]: ...
  1120. def _create_update_prefetch_bind_param(
  1121. compiler: SQLCompiler,
  1122. c: ColumnElement[Any],
  1123. process: bool = True,
  1124. name: Optional[str] = None,
  1125. **kw: Any,
  1126. ) -> Union[elements.BindParameter[Any], str]:
  1127. param = _create_bind_param(
  1128. compiler, c, None, process=process, name=name, **kw
  1129. )
  1130. compiler.update_prefetch.append(c) # type: ignore
  1131. return param
  1132. class _multiparam_column(elements.ColumnElement[Any]):
  1133. _is_multiparam_column = True
  1134. def __init__(self, original, index):
  1135. self.index = index
  1136. self.key = "%s_m%d" % (original.key, index + 1)
  1137. self.original = original
  1138. self.default = original.default
  1139. self.type = original.type
  1140. def compare(self, other, **kw):
  1141. raise NotImplementedError()
  1142. def _copy_internals(self, **kw):
  1143. raise NotImplementedError()
  1144. def __eq__(self, other):
  1145. return (
  1146. isinstance(other, _multiparam_column)
  1147. and other.key == self.key
  1148. and other.original == self.original
  1149. )
  1150. @util.memoized_property
  1151. def _default_description_tuple(self) -> _DefaultDescriptionTuple:
  1152. """used by default.py -> _process_execute_defaults()"""
  1153. return _DefaultDescriptionTuple._from_column_default(self.default)
  1154. @util.memoized_property
  1155. def _onupdate_description_tuple(self) -> _DefaultDescriptionTuple:
  1156. """used by default.py -> _process_execute_defaults()"""
  1157. return _DefaultDescriptionTuple._from_column_default(self.onupdate)
  1158. def _process_multiparam_default_bind(
  1159. compiler: SQLCompiler,
  1160. stmt: ValuesBase,
  1161. c: KeyedColumnElement[Any],
  1162. index: int,
  1163. kw: Dict[str, Any],
  1164. ) -> str:
  1165. if not c.default:
  1166. raise exc.CompileError(
  1167. "INSERT value for column %s is explicitly rendered as a bound"
  1168. "parameter in the VALUES clause; "
  1169. "a Python-side value or SQL expression is required" % c
  1170. )
  1171. elif default_is_clause_element(c.default):
  1172. return compiler.process(c.default.arg.self_group(), **kw)
  1173. elif c.default.is_sequence:
  1174. # these conditions would have been established
  1175. # by append_param_insert_(?:hasdefault|pk_returning|pk_no_returning)
  1176. # in order for us to be here, so these don't need to be
  1177. # checked
  1178. # assert compiler.dialect.supports_sequences and (
  1179. # not c.default.optional
  1180. # or not compiler.dialect.sequences_optional
  1181. # )
  1182. return compiler.process(c.default, **kw)
  1183. else:
  1184. col = _multiparam_column(c, index)
  1185. assert isinstance(stmt, dml.Insert)
  1186. return _create_insert_prefetch_bind_param(
  1187. compiler, col, process=True, **kw
  1188. )
  1189. def _get_update_multitable_params(
  1190. compiler,
  1191. stmt,
  1192. compile_state,
  1193. stmt_parameter_tuples,
  1194. check_columns,
  1195. _col_bind_name,
  1196. _getattr_col_key,
  1197. values,
  1198. kw,
  1199. ):
  1200. normalized_params = {
  1201. coercions.expect(roles.DMLColumnRole, c): param
  1202. for c, param in stmt_parameter_tuples or ()
  1203. }
  1204. include_table = compile_state.include_table_with_column_exprs
  1205. affected_tables = set()
  1206. for t in compile_state._extra_froms:
  1207. for c in t.c:
  1208. if c in normalized_params:
  1209. affected_tables.add(t)
  1210. check_columns[_getattr_col_key(c)] = c
  1211. value = normalized_params[c]
  1212. col_value = compiler.process(c, include_table=include_table)
  1213. if coercions._is_literal(value):
  1214. value = _create_bind_param(
  1215. compiler,
  1216. c,
  1217. value,
  1218. required=value is REQUIRED,
  1219. name=_col_bind_name(c),
  1220. **kw, # TODO: no test coverage for literal binds here
  1221. )
  1222. accumulated_bind_names: Iterable[str] = (c.key,)
  1223. elif value._is_bind_parameter:
  1224. cbn = _col_bind_name(c)
  1225. value = _handle_values_anonymous_param(
  1226. compiler, c, value, name=cbn, **kw
  1227. )
  1228. accumulated_bind_names = (cbn,)
  1229. else:
  1230. compiler.postfetch.append(c)
  1231. value = compiler.process(value.self_group(), **kw)
  1232. accumulated_bind_names = ()
  1233. values.append((c, col_value, value, accumulated_bind_names))
  1234. # determine tables which are actually to be updated - process onupdate
  1235. # and server_onupdate for these
  1236. for t in affected_tables:
  1237. for c in t.c:
  1238. if c in normalized_params:
  1239. continue
  1240. elif c.onupdate is not None and not c.onupdate.is_sequence:
  1241. if c.onupdate.is_clause_element:
  1242. values.append(
  1243. (
  1244. c,
  1245. compiler.process(c, include_table=include_table),
  1246. compiler.process(
  1247. c.onupdate.arg.self_group(), **kw
  1248. ),
  1249. (),
  1250. )
  1251. )
  1252. compiler.postfetch.append(c)
  1253. else:
  1254. values.append(
  1255. (
  1256. c,
  1257. compiler.process(c, include_table=include_table),
  1258. _create_update_prefetch_bind_param(
  1259. compiler, c, name=_col_bind_name(c), **kw
  1260. ),
  1261. (c.key,),
  1262. )
  1263. )
  1264. elif c.server_onupdate is not None:
  1265. compiler.postfetch.append(c)
  1266. def _extend_values_for_multiparams(
  1267. compiler: SQLCompiler,
  1268. stmt: ValuesBase,
  1269. compile_state: DMLState,
  1270. initial_values: Sequence[_CrudParamElementStr],
  1271. _column_as_key: Callable[..., str],
  1272. kw: Dict[str, Any],
  1273. ) -> List[Sequence[_CrudParamElementStr]]:
  1274. values_0 = initial_values
  1275. values = [initial_values]
  1276. has_visiting_cte = kw.get("visiting_cte") is not None
  1277. mp = compile_state._multi_parameters
  1278. assert mp is not None
  1279. for i, row in enumerate(mp[1:]):
  1280. extension: List[_CrudParamElementStr] = []
  1281. row = {_column_as_key(key): v for key, v in row.items()}
  1282. for col, col_expr, param, accumulated_names in values_0:
  1283. if col.key in row:
  1284. key = col.key
  1285. if coercions._is_literal(row[key]):
  1286. new_param = _create_bind_param(
  1287. compiler,
  1288. col,
  1289. row[key],
  1290. name=("%s_m%d" % (col.key, i + 1)),
  1291. force_anonymous=has_visiting_cte,
  1292. **kw,
  1293. )
  1294. else:
  1295. new_param = compiler.process(row[key].self_group(), **kw)
  1296. else:
  1297. new_param = _process_multiparam_default_bind(
  1298. compiler, stmt, col, i, kw
  1299. )
  1300. extension.append((col, col_expr, new_param, accumulated_names))
  1301. values.append(extension)
  1302. return values
  1303. def _get_stmt_parameter_tuples_params(
  1304. compiler,
  1305. compile_state,
  1306. parameters,
  1307. stmt_parameter_tuples,
  1308. _column_as_key,
  1309. values,
  1310. kw,
  1311. ):
  1312. for k, v in stmt_parameter_tuples:
  1313. colkey = _column_as_key(k)
  1314. if colkey is not None:
  1315. parameters.setdefault(colkey, v)
  1316. else:
  1317. # a non-Column expression on the left side;
  1318. # add it to values() in an "as-is" state,
  1319. # coercing right side to bound param
  1320. # note one of the main use cases for this is array slice
  1321. # updates on PostgreSQL, as the left side is also an expression.
  1322. col_expr = compiler.process(
  1323. k, include_table=compile_state.include_table_with_column_exprs
  1324. )
  1325. if coercions._is_literal(v):
  1326. v = compiler.process(
  1327. elements.BindParameter(None, v, type_=k.type), **kw
  1328. )
  1329. else:
  1330. if v._is_bind_parameter and v.type._isnull:
  1331. # either unique parameter, or other bound parameters that
  1332. # were passed in directly
  1333. # set type to that of the column unconditionally
  1334. v = v._with_binary_element_type(k.type)
  1335. v = compiler.process(v.self_group(), **kw)
  1336. # TODO: not sure if accumulated_bind_names applies here
  1337. values.append((k, col_expr, v, ()))
  1338. def _get_returning_modifiers(compiler, stmt, compile_state, toplevel):
  1339. """determines RETURNING strategy, if any, for the statement.
  1340. This is where it's determined what we need to fetch from the
  1341. INSERT or UPDATE statement after it's invoked.
  1342. """
  1343. dialect = compiler.dialect
  1344. need_pks = (
  1345. toplevel
  1346. and _compile_state_isinsert(compile_state)
  1347. and not stmt._inline
  1348. and (
  1349. not compiler.for_executemany
  1350. or (dialect.insert_executemany_returning and stmt._return_defaults)
  1351. )
  1352. and not stmt._returning
  1353. # and (not stmt._returning or stmt._return_defaults)
  1354. and not compile_state._has_multi_parameters
  1355. )
  1356. # check if we have access to simple cursor.lastrowid. we can use that
  1357. # after the INSERT if that's all we need.
  1358. postfetch_lastrowid = (
  1359. need_pks
  1360. and dialect.postfetch_lastrowid
  1361. and stmt.table._autoincrement_column is not None
  1362. )
  1363. # see if we want to add RETURNING to an INSERT in order to get
  1364. # primary key columns back. This would be instead of postfetch_lastrowid
  1365. # if that's set.
  1366. implicit_returning = (
  1367. # statement itself can veto it
  1368. need_pks
  1369. # the dialect can veto it if it just doesnt support RETURNING
  1370. # with INSERT
  1371. and dialect.insert_returning
  1372. # user-defined implicit_returning on Table can veto it
  1373. and compile_state._primary_table.implicit_returning
  1374. # the compile_state can veto it (SQlite uses this to disable
  1375. # RETURNING for an ON CONFLICT insert, as SQLite does not return
  1376. # for rows that were updated, which is wrong)
  1377. and compile_state._supports_implicit_returning
  1378. and (
  1379. # since we support MariaDB and SQLite which also support lastrowid,
  1380. # decide if we should use lastrowid or RETURNING. for insert
  1381. # that didnt call return_defaults() and has just one set of
  1382. # parameters, we can use lastrowid. this is more "traditional"
  1383. # and a lot of weird use cases are supported by it.
  1384. # SQLite lastrowid times 3x faster than returning,
  1385. # Mariadb lastrowid 2x faster than returning
  1386. (not postfetch_lastrowid or dialect.favor_returning_over_lastrowid)
  1387. or compile_state._has_multi_parameters
  1388. or stmt._return_defaults
  1389. )
  1390. )
  1391. if implicit_returning:
  1392. postfetch_lastrowid = False
  1393. if _compile_state_isinsert(compile_state):
  1394. should_implicit_return_defaults = (
  1395. implicit_returning and stmt._return_defaults
  1396. )
  1397. explicit_returning = (
  1398. should_implicit_return_defaults
  1399. or stmt._returning
  1400. or stmt._supplemental_returning
  1401. )
  1402. use_insertmanyvalues = (
  1403. toplevel
  1404. and compiler.for_executemany
  1405. and dialect.use_insertmanyvalues
  1406. and (
  1407. explicit_returning or dialect.use_insertmanyvalues_wo_returning
  1408. )
  1409. )
  1410. use_sentinel_columns = None
  1411. if (
  1412. use_insertmanyvalues
  1413. and explicit_returning
  1414. and stmt._sort_by_parameter_order
  1415. ):
  1416. use_sentinel_columns = compiler._get_sentinel_column_for_table(
  1417. stmt.table
  1418. )
  1419. elif compile_state.isupdate:
  1420. should_implicit_return_defaults = (
  1421. stmt._return_defaults
  1422. and compile_state._primary_table.implicit_returning
  1423. and compile_state._supports_implicit_returning
  1424. and dialect.update_returning
  1425. )
  1426. use_insertmanyvalues = False
  1427. use_sentinel_columns = None
  1428. elif compile_state.isdelete:
  1429. should_implicit_return_defaults = (
  1430. stmt._return_defaults
  1431. and compile_state._primary_table.implicit_returning
  1432. and compile_state._supports_implicit_returning
  1433. and dialect.delete_returning
  1434. )
  1435. use_insertmanyvalues = False
  1436. use_sentinel_columns = None
  1437. else:
  1438. should_implicit_return_defaults = False # pragma: no cover
  1439. use_insertmanyvalues = False
  1440. use_sentinel_columns = None
  1441. if should_implicit_return_defaults:
  1442. if not stmt._return_defaults_columns:
  1443. # TODO: this is weird. See #9685 where we have to
  1444. # take an extra step to prevent this from happening. why
  1445. # would this ever be *all* columns? but if we set to blank, then
  1446. # that seems to break things also in the ORM. So we should
  1447. # try to clean this up and figure out what return_defaults
  1448. # needs to do w/ the ORM etc. here
  1449. implicit_return_defaults = set(stmt.table.c)
  1450. else:
  1451. implicit_return_defaults = set(stmt._return_defaults_columns)
  1452. else:
  1453. implicit_return_defaults = None
  1454. return (
  1455. need_pks,
  1456. implicit_returning or should_implicit_return_defaults,
  1457. implicit_return_defaults,
  1458. postfetch_lastrowid,
  1459. use_insertmanyvalues,
  1460. use_sentinel_columns,
  1461. )
  1462. def _warn_pk_with_no_anticipated_value(c):
  1463. msg = (
  1464. "Column '%s.%s' is marked as a member of the "
  1465. "primary key for table '%s', "
  1466. "but has no Python-side or server-side default generator indicated, "
  1467. "nor does it indicate 'autoincrement=True' or 'nullable=True', "
  1468. "and no explicit value is passed. "
  1469. "Primary key columns typically may not store NULL."
  1470. % (c.table.fullname, c.name, c.table.fullname)
  1471. )
  1472. if len(c.table.primary_key) > 1:
  1473. msg += (
  1474. " Note that as of SQLAlchemy 1.1, 'autoincrement=True' must be "
  1475. "indicated explicitly for composite (e.g. multicolumn) primary "
  1476. "keys if AUTO_INCREMENT/SERIAL/IDENTITY "
  1477. "behavior is expected for one of the columns in the primary key. "
  1478. "CREATE TABLE statements are impacted by this change as well on "
  1479. "most backends."
  1480. )
  1481. util.warn(msg)