crud.py 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671
  1. # sql/crud.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: 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 = 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. **kw: Any,
  351. ) -> str:
  352. ...
  353. @overload
  354. def _create_bind_param(
  355. compiler: SQLCompiler,
  356. col: ColumnElement[Any],
  357. value: Any,
  358. **kw: Any,
  359. ) -> str:
  360. ...
  361. def _create_bind_param(
  362. compiler: SQLCompiler,
  363. col: ColumnElement[Any],
  364. value: Any,
  365. process: bool = True,
  366. required: bool = False,
  367. name: Optional[str] = None,
  368. **kw: Any,
  369. ) -> Union[str, elements.BindParameter[Any]]:
  370. if name is None:
  371. name = col.key
  372. bindparam = elements.BindParameter(
  373. name, value, type_=col.type, required=required
  374. )
  375. bindparam._is_crud = True
  376. if process:
  377. return bindparam._compiler_dispatch(compiler, **kw)
  378. else:
  379. return bindparam
  380. def _handle_values_anonymous_param(compiler, col, value, name, **kw):
  381. # the insert() and update() constructs as of 1.4 will now produce anonymous
  382. # bindparam() objects in the values() collections up front when given plain
  383. # literal values. This is so that cache key behaviors, which need to
  384. # produce bound parameters in deterministic order without invoking any
  385. # compilation here, can be applied to these constructs when they include
  386. # values() (but not yet multi-values, which are not included in caching
  387. # right now).
  388. #
  389. # in order to produce the desired "crud" style name for these parameters,
  390. # which will also be targetable in engine/default.py through the usual
  391. # conventions, apply our desired name to these unique parameters by
  392. # populating the compiler truncated names cache with the desired name,
  393. # rather than having
  394. # compiler.visit_bindparam()->compiler._truncated_identifier make up a
  395. # name. Saves on call counts also.
  396. # for INSERT/UPDATE that's a CTE, we don't need names to match to
  397. # external parameters and these would also conflict in the case where
  398. # multiple insert/update are combined together using CTEs
  399. is_cte = "visiting_cte" in kw
  400. if (
  401. not is_cte
  402. and value.unique
  403. and isinstance(value.key, elements._truncated_label)
  404. ):
  405. compiler.truncated_names[("bindparam", value.key)] = name
  406. if value.type._isnull:
  407. # either unique parameter, or other bound parameters that were
  408. # passed in directly
  409. # set type to that of the column unconditionally
  410. value = value._with_binary_element_type(col.type)
  411. return value._compiler_dispatch(compiler, **kw)
  412. def _key_getters_for_crud_column(
  413. compiler: SQLCompiler, stmt: ValuesBase, compile_state: DMLState
  414. ) -> Tuple[
  415. Callable[[Union[str, ColumnClause[Any]]], Union[str, Tuple[str, str]]],
  416. Callable[[ColumnClause[Any]], Union[str, Tuple[str, str]]],
  417. _BindNameForColProtocol,
  418. ]:
  419. if dml.isupdate(compile_state) and compile_state._extra_froms:
  420. # when extra tables are present, refer to the columns
  421. # in those extra tables as table-qualified, including in
  422. # dictionaries and when rendering bind param names.
  423. # the "main" table of the statement remains unqualified,
  424. # allowing the most compatibility with a non-multi-table
  425. # statement.
  426. _et = set(compile_state._extra_froms)
  427. c_key_role = functools.partial(
  428. coercions.expect_as_key, roles.DMLColumnRole
  429. )
  430. def _column_as_key(
  431. key: Union[ColumnClause[Any], str]
  432. ) -> Union[str, Tuple[str, str]]:
  433. str_key = c_key_role(key)
  434. if hasattr(key, "table") and key.table in _et:
  435. return (key.table.name, str_key) # type: ignore
  436. else:
  437. return str_key
  438. def _getattr_col_key(
  439. col: ColumnClause[Any],
  440. ) -> Union[str, Tuple[str, str]]:
  441. if col.table in _et:
  442. return (col.table.name, col.key) # type: ignore
  443. else:
  444. return col.key
  445. def _col_bind_name(col: ColumnClause[Any]) -> str:
  446. if col.table in _et:
  447. if TYPE_CHECKING:
  448. assert isinstance(col.table, TableClause)
  449. return "%s_%s" % (col.table.name, col.key)
  450. else:
  451. return col.key
  452. else:
  453. _column_as_key = functools.partial(
  454. coercions.expect_as_key, roles.DMLColumnRole
  455. )
  456. _getattr_col_key = _col_bind_name = operator.attrgetter("key") # type: ignore # noqa: E501
  457. return _column_as_key, _getattr_col_key, _col_bind_name
  458. def _scan_insert_from_select_cols(
  459. compiler,
  460. stmt,
  461. compile_state,
  462. parameters,
  463. _getattr_col_key,
  464. _column_as_key,
  465. _col_bind_name,
  466. check_columns,
  467. values,
  468. toplevel,
  469. kw,
  470. ):
  471. cols = [stmt.table.c[_column_as_key(name)] for name in stmt._select_names]
  472. assert compiler.stack[-1]["selectable"] is stmt
  473. compiler.stack[-1]["insert_from_select"] = stmt.select
  474. add_select_cols: List[_CrudParamElementSQLExpr] = []
  475. if stmt.include_insert_from_select_defaults:
  476. col_set = set(cols)
  477. for col in stmt.table.columns:
  478. # omit columns that were not in the SELECT statement.
  479. # this will omit columns marked as omit_from_statements naturally,
  480. # as long as that col was not explicit in the SELECT.
  481. # if an omit_from_statements col has a "default" on it, then
  482. # we need to include it, as these defaults should still fire off.
  483. # but, if it has that default and it's the "sentinel" default,
  484. # we don't do sentinel default operations for insert_from_select
  485. # here so we again omit it.
  486. if (
  487. col not in col_set
  488. and col.default
  489. and not col.default.is_sentinel
  490. ):
  491. cols.append(col)
  492. for c in cols:
  493. col_key = _getattr_col_key(c)
  494. if col_key in parameters and col_key not in check_columns:
  495. parameters.pop(col_key)
  496. values.append((c, compiler.preparer.format_column(c), None, ()))
  497. else:
  498. _append_param_insert_select_hasdefault(
  499. compiler, stmt, c, add_select_cols, kw
  500. )
  501. if add_select_cols:
  502. values.extend(add_select_cols)
  503. ins_from_select = compiler.stack[-1]["insert_from_select"]
  504. if not isinstance(ins_from_select, Select):
  505. raise exc.CompileError(
  506. f"Can't extend statement for INSERT..FROM SELECT to include "
  507. f"additional default-holding column(s) "
  508. f"""{
  509. ', '.join(repr(key) for _, key, _, _ in add_select_cols)
  510. }. Convert the selectable to a subquery() first, or pass """
  511. "include_defaults=False to Insert.from_select() to skip these "
  512. "columns."
  513. )
  514. ins_from_select = ins_from_select._generate()
  515. # copy raw_columns
  516. ins_from_select._raw_columns = list(ins_from_select._raw_columns) + [
  517. expr for _, _, expr, _ in add_select_cols
  518. ]
  519. compiler.stack[-1]["insert_from_select"] = ins_from_select
  520. def _scan_cols(
  521. compiler,
  522. stmt,
  523. compile_state,
  524. parameters,
  525. _getattr_col_key,
  526. _column_as_key,
  527. _col_bind_name,
  528. check_columns,
  529. values,
  530. toplevel,
  531. kw,
  532. ):
  533. (
  534. need_pks,
  535. implicit_returning,
  536. implicit_return_defaults,
  537. postfetch_lastrowid,
  538. use_insertmanyvalues,
  539. use_sentinel_columns,
  540. ) = _get_returning_modifiers(compiler, stmt, compile_state, toplevel)
  541. assert compile_state.isupdate or compile_state.isinsert
  542. if compile_state._parameter_ordering:
  543. parameter_ordering = [
  544. _column_as_key(key) for key in compile_state._parameter_ordering
  545. ]
  546. ordered_keys = set(parameter_ordering)
  547. cols = [
  548. stmt.table.c[key]
  549. for key in parameter_ordering
  550. if isinstance(key, str) and key in stmt.table.c
  551. ] + [c for c in stmt.table.c if c.key not in ordered_keys]
  552. else:
  553. cols = stmt.table.columns
  554. isinsert = _compile_state_isinsert(compile_state)
  555. if isinsert and not compile_state._has_multi_parameters:
  556. # new rules for #7998. fetch lastrowid or implicit returning
  557. # for autoincrement column even if parameter is NULL, for DBs that
  558. # override NULL param for primary key (sqlite, mysql/mariadb)
  559. autoincrement_col = stmt.table._autoincrement_column
  560. insert_null_pk_still_autoincrements = (
  561. compiler.dialect.insert_null_pk_still_autoincrements
  562. )
  563. else:
  564. autoincrement_col = insert_null_pk_still_autoincrements = None
  565. if stmt._supplemental_returning:
  566. supplemental_returning = set(stmt._supplemental_returning)
  567. else:
  568. supplemental_returning = set()
  569. compiler_implicit_returning = compiler.implicit_returning
  570. # TODO - see TODO(return_defaults_columns) below
  571. # cols_in_params = set()
  572. for c in cols:
  573. # scan through every column in the target table
  574. col_key = _getattr_col_key(c)
  575. if col_key in parameters and col_key not in check_columns:
  576. # parameter is present for the column. use that.
  577. _append_param_parameter(
  578. compiler,
  579. stmt,
  580. compile_state,
  581. c,
  582. col_key,
  583. parameters,
  584. _col_bind_name,
  585. implicit_returning,
  586. implicit_return_defaults,
  587. postfetch_lastrowid,
  588. values,
  589. autoincrement_col,
  590. insert_null_pk_still_autoincrements,
  591. kw,
  592. )
  593. # TODO - see TODO(return_defaults_columns) below
  594. # cols_in_params.add(c)
  595. elif isinsert:
  596. # no parameter is present and it's an insert.
  597. if c.primary_key and need_pks:
  598. # it's a primary key column, it will need to be generated by a
  599. # default generator of some kind, and the statement expects
  600. # inserted_primary_key to be available.
  601. if implicit_returning:
  602. # we can use RETURNING, find out how to invoke this
  603. # column and get the value where RETURNING is an option.
  604. # we can inline server-side functions in this case.
  605. _append_param_insert_pk_returning(
  606. compiler, stmt, c, values, kw
  607. )
  608. else:
  609. # otherwise, find out how to invoke this column
  610. # and get its value where RETURNING is not an option.
  611. # if we have to invoke a server-side function, we need
  612. # to pre-execute it. or if this is a straight
  613. # autoincrement column and the dialect supports it
  614. # we can use cursor.lastrowid.
  615. _append_param_insert_pk_no_returning(
  616. compiler, stmt, c, values, kw
  617. )
  618. elif c.default is not None:
  619. # column has a default, but it's not a pk column, or it is but
  620. # we don't need to get the pk back.
  621. if not c.default.is_sentinel or (
  622. use_sentinel_columns is not None
  623. ):
  624. _append_param_insert_hasdefault(
  625. compiler, stmt, c, implicit_return_defaults, values, kw
  626. )
  627. elif c.server_default is not None:
  628. # column has a DDL-level default, and is either not a pk
  629. # column or we don't need the pk.
  630. if implicit_return_defaults and c in implicit_return_defaults:
  631. compiler_implicit_returning.append(c)
  632. elif not c.primary_key:
  633. compiler.postfetch.append(c)
  634. elif implicit_return_defaults and c in implicit_return_defaults:
  635. compiler_implicit_returning.append(c)
  636. elif (
  637. c.primary_key
  638. and c is not stmt.table._autoincrement_column
  639. and not c.nullable
  640. ):
  641. _warn_pk_with_no_anticipated_value(c)
  642. elif compile_state.isupdate:
  643. # no parameter is present and it's an insert.
  644. _append_param_update(
  645. compiler,
  646. compile_state,
  647. stmt,
  648. c,
  649. implicit_return_defaults,
  650. values,
  651. kw,
  652. )
  653. # adding supplemental cols to implicit_returning in table
  654. # order so that order is maintained between multiple INSERT
  655. # statements which may have different parameters included, but all
  656. # have the same RETURNING clause
  657. if (
  658. c in supplemental_returning
  659. and c not in compiler_implicit_returning
  660. ):
  661. compiler_implicit_returning.append(c)
  662. if supplemental_returning:
  663. # we should have gotten every col into implicit_returning,
  664. # however supplemental returning can also have SQL functions etc.
  665. # in it
  666. remaining_supplemental = supplemental_returning.difference(
  667. compiler_implicit_returning
  668. )
  669. compiler_implicit_returning.extend(
  670. c
  671. for c in stmt._supplemental_returning
  672. if c in remaining_supplemental
  673. )
  674. # TODO(return_defaults_columns): there can still be more columns in
  675. # _return_defaults_columns in the case that they are from something like an
  676. # aliased of the table. we can add them here, however this breaks other ORM
  677. # things. so this is for another day. see
  678. # test/orm/dml/test_update_delete_where.py -> test_update_from_alias
  679. # if stmt._return_defaults_columns:
  680. # compiler_implicit_returning.extend(
  681. # set(stmt._return_defaults_columns)
  682. # .difference(compiler_implicit_returning)
  683. # .difference(cols_in_params)
  684. # )
  685. return (use_insertmanyvalues, use_sentinel_columns)
  686. def _setup_delete_return_defaults(
  687. compiler,
  688. stmt,
  689. compile_state,
  690. parameters,
  691. _getattr_col_key,
  692. _column_as_key,
  693. _col_bind_name,
  694. check_columns,
  695. values,
  696. toplevel,
  697. kw,
  698. ):
  699. (_, _, implicit_return_defaults, *_) = _get_returning_modifiers(
  700. compiler, stmt, compile_state, toplevel
  701. )
  702. if not implicit_return_defaults:
  703. return
  704. if stmt._return_defaults_columns:
  705. compiler.implicit_returning.extend(implicit_return_defaults)
  706. if stmt._supplemental_returning:
  707. ir_set = set(compiler.implicit_returning)
  708. compiler.implicit_returning.extend(
  709. c for c in stmt._supplemental_returning if c not in ir_set
  710. )
  711. def _append_param_parameter(
  712. compiler,
  713. stmt,
  714. compile_state,
  715. c,
  716. col_key,
  717. parameters,
  718. _col_bind_name,
  719. implicit_returning,
  720. implicit_return_defaults,
  721. postfetch_lastrowid,
  722. values,
  723. autoincrement_col,
  724. insert_null_pk_still_autoincrements,
  725. kw,
  726. ):
  727. value = parameters.pop(col_key)
  728. col_value = compiler.preparer.format_column(
  729. c, use_table=compile_state.include_table_with_column_exprs
  730. )
  731. accumulated_bind_names: Set[str] = set()
  732. if coercions._is_literal(value):
  733. if (
  734. insert_null_pk_still_autoincrements
  735. and c.primary_key
  736. and c is autoincrement_col
  737. ):
  738. # support use case for #7998, fetch autoincrement cols
  739. # even if value was given.
  740. if postfetch_lastrowid:
  741. compiler.postfetch_lastrowid = True
  742. elif implicit_returning:
  743. compiler.implicit_returning.append(c)
  744. value = _create_bind_param(
  745. compiler,
  746. c,
  747. value,
  748. required=value is REQUIRED,
  749. name=_col_bind_name(c)
  750. if not _compile_state_isinsert(compile_state)
  751. or not compile_state._has_multi_parameters
  752. else "%s_m0" % _col_bind_name(c),
  753. accumulate_bind_names=accumulated_bind_names,
  754. **kw,
  755. )
  756. elif value._is_bind_parameter:
  757. if (
  758. insert_null_pk_still_autoincrements
  759. and value.value is None
  760. and c.primary_key
  761. and c is autoincrement_col
  762. ):
  763. # support use case for #7998, fetch autoincrement cols
  764. # even if value was given
  765. if implicit_returning:
  766. compiler.implicit_returning.append(c)
  767. elif compiler.dialect.postfetch_lastrowid:
  768. compiler.postfetch_lastrowid = True
  769. value = _handle_values_anonymous_param(
  770. compiler,
  771. c,
  772. value,
  773. name=_col_bind_name(c)
  774. if not _compile_state_isinsert(compile_state)
  775. or not compile_state._has_multi_parameters
  776. else "%s_m0" % _col_bind_name(c),
  777. accumulate_bind_names=accumulated_bind_names,
  778. **kw,
  779. )
  780. else:
  781. # value is a SQL expression
  782. value = compiler.process(
  783. value.self_group(),
  784. accumulate_bind_names=accumulated_bind_names,
  785. **kw,
  786. )
  787. if compile_state.isupdate:
  788. if implicit_return_defaults and c in implicit_return_defaults:
  789. compiler.implicit_returning.append(c)
  790. else:
  791. compiler.postfetch.append(c)
  792. else:
  793. if c.primary_key:
  794. if implicit_returning:
  795. compiler.implicit_returning.append(c)
  796. elif compiler.dialect.postfetch_lastrowid:
  797. compiler.postfetch_lastrowid = True
  798. elif implicit_return_defaults and (c in implicit_return_defaults):
  799. compiler.implicit_returning.append(c)
  800. else:
  801. # postfetch specifically means, "we can SELECT the row we just
  802. # inserted by primary key to get back the server generated
  803. # defaults". so by definition this can't be used to get the
  804. # primary key value back, because we need to have it ahead of
  805. # time.
  806. compiler.postfetch.append(c)
  807. values.append((c, col_value, value, accumulated_bind_names))
  808. def _append_param_insert_pk_returning(compiler, stmt, c, values, kw):
  809. """Create a primary key expression in the INSERT statement where
  810. we want to populate result.inserted_primary_key and RETURNING
  811. is available.
  812. """
  813. if c.default is not None:
  814. if c.default.is_sequence:
  815. if compiler.dialect.supports_sequences and (
  816. not c.default.optional
  817. or not compiler.dialect.sequences_optional
  818. ):
  819. accumulated_bind_names: Set[str] = set()
  820. values.append(
  821. (
  822. c,
  823. compiler.preparer.format_column(c),
  824. compiler.process(
  825. c.default,
  826. accumulate_bind_names=accumulated_bind_names,
  827. **kw,
  828. ),
  829. accumulated_bind_names,
  830. )
  831. )
  832. compiler.implicit_returning.append(c)
  833. elif c.default.is_clause_element:
  834. accumulated_bind_names = set()
  835. values.append(
  836. (
  837. c,
  838. compiler.preparer.format_column(c),
  839. compiler.process(
  840. c.default.arg.self_group(),
  841. accumulate_bind_names=accumulated_bind_names,
  842. **kw,
  843. ),
  844. accumulated_bind_names,
  845. )
  846. )
  847. compiler.implicit_returning.append(c)
  848. else:
  849. # client side default. OK we can't use RETURNING, need to
  850. # do a "prefetch", which in fact fetches the default value
  851. # on the Python side
  852. values.append(
  853. (
  854. c,
  855. compiler.preparer.format_column(c),
  856. _create_insert_prefetch_bind_param(compiler, c, **kw),
  857. (c.key,),
  858. )
  859. )
  860. elif c is stmt.table._autoincrement_column or c.server_default is not None:
  861. compiler.implicit_returning.append(c)
  862. elif not c.nullable:
  863. # no .default, no .server_default, not autoincrement, we have
  864. # no indication this primary key column will have any value
  865. _warn_pk_with_no_anticipated_value(c)
  866. def _append_param_insert_pk_no_returning(compiler, stmt, c, values, kw):
  867. """Create a primary key expression in the INSERT statement where
  868. we want to populate result.inserted_primary_key and we cannot use
  869. RETURNING.
  870. Depending on the kind of default here we may create a bound parameter
  871. in the INSERT statement and pre-execute a default generation function,
  872. or we may use cursor.lastrowid if supported by the dialect.
  873. """
  874. if (
  875. # column has a Python-side default
  876. c.default is not None
  877. and (
  878. # and it either is not a sequence, or it is and we support
  879. # sequences and want to invoke it
  880. not c.default.is_sequence
  881. or (
  882. compiler.dialect.supports_sequences
  883. and (
  884. not c.default.optional
  885. or not compiler.dialect.sequences_optional
  886. )
  887. )
  888. )
  889. ) or (
  890. # column is the "autoincrement column"
  891. c is stmt.table._autoincrement_column
  892. and (
  893. # dialect can't use cursor.lastrowid
  894. not compiler.dialect.postfetch_lastrowid
  895. and (
  896. # column has a Sequence and we support those
  897. (
  898. c.default is not None
  899. and c.default.is_sequence
  900. and compiler.dialect.supports_sequences
  901. )
  902. or
  903. # column has no default on it, but dialect can run the
  904. # "autoincrement" mechanism explicitly, e.g. PostgreSQL
  905. # SERIAL we know the sequence name
  906. (
  907. c.default is None
  908. and compiler.dialect.preexecute_autoincrement_sequences
  909. )
  910. )
  911. )
  912. ):
  913. # do a pre-execute of the default
  914. values.append(
  915. (
  916. c,
  917. compiler.preparer.format_column(c),
  918. _create_insert_prefetch_bind_param(compiler, c, **kw),
  919. (c.key,),
  920. )
  921. )
  922. elif (
  923. c.default is None
  924. and c.server_default is None
  925. and not c.nullable
  926. and c is not stmt.table._autoincrement_column
  927. ):
  928. # no .default, no .server_default, not autoincrement, we have
  929. # no indication this primary key column will have any value
  930. _warn_pk_with_no_anticipated_value(c)
  931. elif compiler.dialect.postfetch_lastrowid:
  932. # finally, where it seems like there will be a generated primary key
  933. # value and we haven't set up any other way to fetch it, and the
  934. # dialect supports cursor.lastrowid, switch on the lastrowid flag so
  935. # that the DefaultExecutionContext calls upon cursor.lastrowid
  936. compiler.postfetch_lastrowid = True
  937. def _append_param_insert_hasdefault(
  938. compiler, stmt, c, implicit_return_defaults, values, kw
  939. ):
  940. if c.default.is_sequence:
  941. if compiler.dialect.supports_sequences and (
  942. not c.default.optional or not compiler.dialect.sequences_optional
  943. ):
  944. accumulated_bind_names: Set[str] = set()
  945. values.append(
  946. (
  947. c,
  948. compiler.preparer.format_column(c),
  949. compiler.process(
  950. c.default,
  951. accumulate_bind_names=accumulated_bind_names,
  952. **kw,
  953. ),
  954. accumulated_bind_names,
  955. )
  956. )
  957. if implicit_return_defaults and c in implicit_return_defaults:
  958. compiler.implicit_returning.append(c)
  959. elif not c.primary_key:
  960. compiler.postfetch.append(c)
  961. elif c.default.is_clause_element:
  962. accumulated_bind_names = set()
  963. values.append(
  964. (
  965. c,
  966. compiler.preparer.format_column(c),
  967. compiler.process(
  968. c.default.arg.self_group(),
  969. accumulate_bind_names=accumulated_bind_names,
  970. **kw,
  971. ),
  972. accumulated_bind_names,
  973. )
  974. )
  975. if implicit_return_defaults and c in implicit_return_defaults:
  976. compiler.implicit_returning.append(c)
  977. elif not c.primary_key:
  978. # don't add primary key column to postfetch
  979. compiler.postfetch.append(c)
  980. else:
  981. values.append(
  982. (
  983. c,
  984. compiler.preparer.format_column(c),
  985. _create_insert_prefetch_bind_param(compiler, c, **kw),
  986. (c.key,),
  987. )
  988. )
  989. def _append_param_insert_select_hasdefault(
  990. compiler: SQLCompiler,
  991. stmt: ValuesBase,
  992. c: ColumnClause[Any],
  993. values: List[_CrudParamElementSQLExpr],
  994. kw: Dict[str, Any],
  995. ) -> None:
  996. if default_is_sequence(c.default):
  997. if compiler.dialect.supports_sequences and (
  998. not c.default.optional or not compiler.dialect.sequences_optional
  999. ):
  1000. values.append(
  1001. (
  1002. c,
  1003. compiler.preparer.format_column(c),
  1004. c.default.next_value(),
  1005. (),
  1006. )
  1007. )
  1008. elif default_is_clause_element(c.default):
  1009. values.append(
  1010. (
  1011. c,
  1012. compiler.preparer.format_column(c),
  1013. c.default.arg.self_group(),
  1014. (),
  1015. )
  1016. )
  1017. else:
  1018. values.append(
  1019. (
  1020. c,
  1021. compiler.preparer.format_column(c),
  1022. _create_insert_prefetch_bind_param(
  1023. compiler, c, process=False, **kw
  1024. ),
  1025. (c.key,),
  1026. )
  1027. )
  1028. def _append_param_update(
  1029. compiler, compile_state, stmt, c, implicit_return_defaults, values, kw
  1030. ):
  1031. include_table = compile_state.include_table_with_column_exprs
  1032. if c.onupdate is not None and not c.onupdate.is_sequence:
  1033. if c.onupdate.is_clause_element:
  1034. values.append(
  1035. (
  1036. c,
  1037. compiler.preparer.format_column(
  1038. c,
  1039. use_table=include_table,
  1040. ),
  1041. compiler.process(c.onupdate.arg.self_group(), **kw),
  1042. (),
  1043. )
  1044. )
  1045. if implicit_return_defaults and c in implicit_return_defaults:
  1046. compiler.implicit_returning.append(c)
  1047. else:
  1048. compiler.postfetch.append(c)
  1049. else:
  1050. values.append(
  1051. (
  1052. c,
  1053. compiler.preparer.format_column(
  1054. c,
  1055. use_table=include_table,
  1056. ),
  1057. _create_update_prefetch_bind_param(compiler, c, **kw),
  1058. (c.key,),
  1059. )
  1060. )
  1061. elif c.server_onupdate is not None:
  1062. if implicit_return_defaults and c in implicit_return_defaults:
  1063. compiler.implicit_returning.append(c)
  1064. else:
  1065. compiler.postfetch.append(c)
  1066. elif (
  1067. implicit_return_defaults
  1068. and (stmt._return_defaults_columns or not stmt._return_defaults)
  1069. and c in implicit_return_defaults
  1070. ):
  1071. compiler.implicit_returning.append(c)
  1072. @overload
  1073. def _create_insert_prefetch_bind_param(
  1074. compiler: SQLCompiler,
  1075. c: ColumnElement[Any],
  1076. process: Literal[True] = ...,
  1077. **kw: Any,
  1078. ) -> str:
  1079. ...
  1080. @overload
  1081. def _create_insert_prefetch_bind_param(
  1082. compiler: SQLCompiler,
  1083. c: ColumnElement[Any],
  1084. process: Literal[False],
  1085. **kw: Any,
  1086. ) -> elements.BindParameter[Any]:
  1087. ...
  1088. def _create_insert_prefetch_bind_param(
  1089. compiler: SQLCompiler,
  1090. c: ColumnElement[Any],
  1091. process: bool = True,
  1092. name: Optional[str] = None,
  1093. **kw: Any,
  1094. ) -> Union[elements.BindParameter[Any], str]:
  1095. param = _create_bind_param(
  1096. compiler, c, None, process=process, name=name, **kw
  1097. )
  1098. compiler.insert_prefetch.append(c) # type: ignore
  1099. return param
  1100. @overload
  1101. def _create_update_prefetch_bind_param(
  1102. compiler: SQLCompiler,
  1103. c: ColumnElement[Any],
  1104. process: Literal[True] = ...,
  1105. **kw: Any,
  1106. ) -> str:
  1107. ...
  1108. @overload
  1109. def _create_update_prefetch_bind_param(
  1110. compiler: SQLCompiler,
  1111. c: ColumnElement[Any],
  1112. process: Literal[False],
  1113. **kw: Any,
  1114. ) -> elements.BindParameter[Any]:
  1115. ...
  1116. def _create_update_prefetch_bind_param(
  1117. compiler: SQLCompiler,
  1118. c: ColumnElement[Any],
  1119. process: bool = True,
  1120. name: Optional[str] = None,
  1121. **kw: Any,
  1122. ) -> Union[elements.BindParameter[Any], str]:
  1123. param = _create_bind_param(
  1124. compiler, c, None, process=process, name=name, **kw
  1125. )
  1126. compiler.update_prefetch.append(c) # type: ignore
  1127. return param
  1128. class _multiparam_column(elements.ColumnElement[Any]):
  1129. _is_multiparam_column = True
  1130. def __init__(self, original, index):
  1131. self.index = index
  1132. self.key = "%s_m%d" % (original.key, index + 1)
  1133. self.original = original
  1134. self.default = original.default
  1135. self.type = original.type
  1136. def compare(self, other, **kw):
  1137. raise NotImplementedError()
  1138. def _copy_internals(self, other, **kw):
  1139. raise NotImplementedError()
  1140. def __eq__(self, other):
  1141. return (
  1142. isinstance(other, _multiparam_column)
  1143. and other.key == self.key
  1144. and other.original == self.original
  1145. )
  1146. @util.memoized_property
  1147. def _default_description_tuple(self) -> _DefaultDescriptionTuple:
  1148. """used by default.py -> _process_execute_defaults()"""
  1149. return _DefaultDescriptionTuple._from_column_default(self.default)
  1150. @util.memoized_property
  1151. def _onupdate_description_tuple(self) -> _DefaultDescriptionTuple:
  1152. """used by default.py -> _process_execute_defaults()"""
  1153. return _DefaultDescriptionTuple._from_column_default(self.onupdate)
  1154. def _process_multiparam_default_bind(
  1155. compiler: SQLCompiler,
  1156. stmt: ValuesBase,
  1157. c: KeyedColumnElement[Any],
  1158. index: int,
  1159. kw: Dict[str, Any],
  1160. ) -> str:
  1161. if not c.default:
  1162. raise exc.CompileError(
  1163. "INSERT value for column %s is explicitly rendered as a bound"
  1164. "parameter in the VALUES clause; "
  1165. "a Python-side value or SQL expression is required" % c
  1166. )
  1167. elif default_is_clause_element(c.default):
  1168. return compiler.process(c.default.arg.self_group(), **kw)
  1169. elif c.default.is_sequence:
  1170. # these conditions would have been established
  1171. # by append_param_insert_(?:hasdefault|pk_returning|pk_no_returning)
  1172. # in order for us to be here, so these don't need to be
  1173. # checked
  1174. # assert compiler.dialect.supports_sequences and (
  1175. # not c.default.optional
  1176. # or not compiler.dialect.sequences_optional
  1177. # )
  1178. return compiler.process(c.default, **kw)
  1179. else:
  1180. col = _multiparam_column(c, index)
  1181. assert isinstance(stmt, dml.Insert)
  1182. return _create_insert_prefetch_bind_param(
  1183. compiler, col, process=True, **kw
  1184. )
  1185. def _get_update_multitable_params(
  1186. compiler,
  1187. stmt,
  1188. compile_state,
  1189. stmt_parameter_tuples,
  1190. check_columns,
  1191. _col_bind_name,
  1192. _getattr_col_key,
  1193. values,
  1194. kw,
  1195. ):
  1196. normalized_params = {
  1197. coercions.expect(roles.DMLColumnRole, c): param
  1198. for c, param in stmt_parameter_tuples or ()
  1199. }
  1200. include_table = compile_state.include_table_with_column_exprs
  1201. affected_tables = set()
  1202. for t in compile_state._extra_froms:
  1203. for c in t.c:
  1204. if c in normalized_params:
  1205. affected_tables.add(t)
  1206. check_columns[_getattr_col_key(c)] = c
  1207. value = normalized_params[c]
  1208. col_value = compiler.process(c, include_table=include_table)
  1209. if coercions._is_literal(value):
  1210. value = _create_bind_param(
  1211. compiler,
  1212. c,
  1213. value,
  1214. required=value is REQUIRED,
  1215. name=_col_bind_name(c),
  1216. **kw, # TODO: no test coverage for literal binds here
  1217. )
  1218. accumulated_bind_names: Iterable[str] = (c.key,)
  1219. elif value._is_bind_parameter:
  1220. cbn = _col_bind_name(c)
  1221. value = _handle_values_anonymous_param(
  1222. compiler, c, value, name=cbn, **kw
  1223. )
  1224. accumulated_bind_names = (cbn,)
  1225. else:
  1226. compiler.postfetch.append(c)
  1227. value = compiler.process(value.self_group(), **kw)
  1228. accumulated_bind_names = ()
  1229. values.append((c, col_value, value, accumulated_bind_names))
  1230. # determine tables which are actually to be updated - process onupdate
  1231. # and server_onupdate for these
  1232. for t in affected_tables:
  1233. for c in t.c:
  1234. if c in normalized_params:
  1235. continue
  1236. elif c.onupdate is not None and not c.onupdate.is_sequence:
  1237. if c.onupdate.is_clause_element:
  1238. values.append(
  1239. (
  1240. c,
  1241. compiler.process(c, include_table=include_table),
  1242. compiler.process(
  1243. c.onupdate.arg.self_group(), **kw
  1244. ),
  1245. (),
  1246. )
  1247. )
  1248. compiler.postfetch.append(c)
  1249. else:
  1250. values.append(
  1251. (
  1252. c,
  1253. compiler.process(c, include_table=include_table),
  1254. _create_update_prefetch_bind_param(
  1255. compiler, c, name=_col_bind_name(c), **kw
  1256. ),
  1257. (c.key,),
  1258. )
  1259. )
  1260. elif c.server_onupdate is not None:
  1261. compiler.postfetch.append(c)
  1262. def _extend_values_for_multiparams(
  1263. compiler: SQLCompiler,
  1264. stmt: ValuesBase,
  1265. compile_state: DMLState,
  1266. initial_values: Sequence[_CrudParamElementStr],
  1267. _column_as_key: Callable[..., str],
  1268. kw: Dict[str, Any],
  1269. ) -> List[Sequence[_CrudParamElementStr]]:
  1270. values_0 = initial_values
  1271. values = [initial_values]
  1272. mp = compile_state._multi_parameters
  1273. assert mp is not None
  1274. for i, row in enumerate(mp[1:]):
  1275. extension: List[_CrudParamElementStr] = []
  1276. row = {_column_as_key(key): v for key, v in row.items()}
  1277. for col, col_expr, param, accumulated_names in values_0:
  1278. if col.key in row:
  1279. key = col.key
  1280. if coercions._is_literal(row[key]):
  1281. new_param = _create_bind_param(
  1282. compiler,
  1283. col,
  1284. row[key],
  1285. name="%s_m%d" % (col.key, i + 1),
  1286. **kw,
  1287. )
  1288. else:
  1289. new_param = compiler.process(row[key].self_group(), **kw)
  1290. else:
  1291. new_param = _process_multiparam_default_bind(
  1292. compiler, stmt, col, i, kw
  1293. )
  1294. extension.append((col, col_expr, new_param, accumulated_names))
  1295. values.append(extension)
  1296. return values
  1297. def _get_stmt_parameter_tuples_params(
  1298. compiler,
  1299. compile_state,
  1300. parameters,
  1301. stmt_parameter_tuples,
  1302. _column_as_key,
  1303. values,
  1304. kw,
  1305. ):
  1306. for k, v in stmt_parameter_tuples:
  1307. colkey = _column_as_key(k)
  1308. if colkey is not None:
  1309. parameters.setdefault(colkey, v)
  1310. else:
  1311. # a non-Column expression on the left side;
  1312. # add it to values() in an "as-is" state,
  1313. # coercing right side to bound param
  1314. # note one of the main use cases for this is array slice
  1315. # updates on PostgreSQL, as the left side is also an expression.
  1316. col_expr = compiler.process(
  1317. k, include_table=compile_state.include_table_with_column_exprs
  1318. )
  1319. if coercions._is_literal(v):
  1320. v = compiler.process(
  1321. elements.BindParameter(None, v, type_=k.type), **kw
  1322. )
  1323. else:
  1324. if v._is_bind_parameter and v.type._isnull:
  1325. # either unique parameter, or other bound parameters that
  1326. # were passed in directly
  1327. # set type to that of the column unconditionally
  1328. v = v._with_binary_element_type(k.type)
  1329. v = compiler.process(v.self_group(), **kw)
  1330. # TODO: not sure if accumulated_bind_names applies here
  1331. values.append((k, col_expr, v, ()))
  1332. def _get_returning_modifiers(compiler, stmt, compile_state, toplevel):
  1333. """determines RETURNING strategy, if any, for the statement.
  1334. This is where it's determined what we need to fetch from the
  1335. INSERT or UPDATE statement after it's invoked.
  1336. """
  1337. dialect = compiler.dialect
  1338. need_pks = (
  1339. toplevel
  1340. and _compile_state_isinsert(compile_state)
  1341. and not stmt._inline
  1342. and (
  1343. not compiler.for_executemany
  1344. or (dialect.insert_executemany_returning and stmt._return_defaults)
  1345. )
  1346. and not stmt._returning
  1347. # and (not stmt._returning or stmt._return_defaults)
  1348. and not compile_state._has_multi_parameters
  1349. )
  1350. # check if we have access to simple cursor.lastrowid. we can use that
  1351. # after the INSERT if that's all we need.
  1352. postfetch_lastrowid = (
  1353. need_pks
  1354. and dialect.postfetch_lastrowid
  1355. and stmt.table._autoincrement_column is not None
  1356. )
  1357. # see if we want to add RETURNING to an INSERT in order to get
  1358. # primary key columns back. This would be instead of postfetch_lastrowid
  1359. # if that's set.
  1360. implicit_returning = (
  1361. # statement itself can veto it
  1362. need_pks
  1363. # the dialect can veto it if it just doesnt support RETURNING
  1364. # with INSERT
  1365. and dialect.insert_returning
  1366. # user-defined implicit_returning on Table can veto it
  1367. and compile_state._primary_table.implicit_returning
  1368. # the compile_state can veto it (SQlite uses this to disable
  1369. # RETURNING for an ON CONFLICT insert, as SQLite does not return
  1370. # for rows that were updated, which is wrong)
  1371. and compile_state._supports_implicit_returning
  1372. and (
  1373. # since we support MariaDB and SQLite which also support lastrowid,
  1374. # decide if we should use lastrowid or RETURNING. for insert
  1375. # that didnt call return_defaults() and has just one set of
  1376. # parameters, we can use lastrowid. this is more "traditional"
  1377. # and a lot of weird use cases are supported by it.
  1378. # SQLite lastrowid times 3x faster than returning,
  1379. # Mariadb lastrowid 2x faster than returning
  1380. (not postfetch_lastrowid or dialect.favor_returning_over_lastrowid)
  1381. or compile_state._has_multi_parameters
  1382. or stmt._return_defaults
  1383. )
  1384. )
  1385. if implicit_returning:
  1386. postfetch_lastrowid = False
  1387. if _compile_state_isinsert(compile_state):
  1388. should_implicit_return_defaults = (
  1389. implicit_returning and stmt._return_defaults
  1390. )
  1391. explicit_returning = (
  1392. should_implicit_return_defaults
  1393. or stmt._returning
  1394. or stmt._supplemental_returning
  1395. )
  1396. use_insertmanyvalues = (
  1397. toplevel
  1398. and compiler.for_executemany
  1399. and dialect.use_insertmanyvalues
  1400. and (
  1401. explicit_returning or dialect.use_insertmanyvalues_wo_returning
  1402. )
  1403. )
  1404. use_sentinel_columns = None
  1405. if (
  1406. use_insertmanyvalues
  1407. and explicit_returning
  1408. and stmt._sort_by_parameter_order
  1409. ):
  1410. use_sentinel_columns = compiler._get_sentinel_column_for_table(
  1411. stmt.table
  1412. )
  1413. elif compile_state.isupdate:
  1414. should_implicit_return_defaults = (
  1415. stmt._return_defaults
  1416. and compile_state._primary_table.implicit_returning
  1417. and compile_state._supports_implicit_returning
  1418. and dialect.update_returning
  1419. )
  1420. use_insertmanyvalues = False
  1421. use_sentinel_columns = None
  1422. elif compile_state.isdelete:
  1423. should_implicit_return_defaults = (
  1424. stmt._return_defaults
  1425. and compile_state._primary_table.implicit_returning
  1426. and compile_state._supports_implicit_returning
  1427. and dialect.delete_returning
  1428. )
  1429. use_insertmanyvalues = False
  1430. use_sentinel_columns = None
  1431. else:
  1432. should_implicit_return_defaults = False # pragma: no cover
  1433. use_insertmanyvalues = False
  1434. use_sentinel_columns = None
  1435. if should_implicit_return_defaults:
  1436. if not stmt._return_defaults_columns:
  1437. # TODO: this is weird. See #9685 where we have to
  1438. # take an extra step to prevent this from happening. why
  1439. # would this ever be *all* columns? but if we set to blank, then
  1440. # that seems to break things also in the ORM. So we should
  1441. # try to clean this up and figure out what return_defaults
  1442. # needs to do w/ the ORM etc. here
  1443. implicit_return_defaults = set(stmt.table.c)
  1444. else:
  1445. implicit_return_defaults = set(stmt._return_defaults_columns)
  1446. else:
  1447. implicit_return_defaults = None
  1448. return (
  1449. need_pks,
  1450. implicit_returning or should_implicit_return_defaults,
  1451. implicit_return_defaults,
  1452. postfetch_lastrowid,
  1453. use_insertmanyvalues,
  1454. use_sentinel_columns,
  1455. )
  1456. def _warn_pk_with_no_anticipated_value(c):
  1457. msg = (
  1458. "Column '%s.%s' is marked as a member of the "
  1459. "primary key for table '%s', "
  1460. "but has no Python-side or server-side default generator indicated, "
  1461. "nor does it indicate 'autoincrement=True' or 'nullable=True', "
  1462. "and no explicit value is passed. "
  1463. "Primary key columns typically may not store NULL."
  1464. % (c.table.fullname, c.name, c.table.fullname)
  1465. )
  1466. if len(c.table.primary_key) > 1:
  1467. msg += (
  1468. " Note that as of SQLAlchemy 1.1, 'autoincrement=True' must be "
  1469. "indicated explicitly for composite (e.g. multicolumn) primary "
  1470. "keys if AUTO_INCREMENT/SERIAL/IDENTITY "
  1471. "behavior is expected for one of the columns in the primary key. "
  1472. "CREATE TABLE statements are impacted by this change as well on "
  1473. "most backends."
  1474. )
  1475. util.warn(msg)