crud.py 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094
  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. """Functions used by compiler.py to determine the parameters rendered
  8. within INSERT and UPDATE statements.
  9. """
  10. import functools
  11. import operator
  12. from . import coercions
  13. from . import dml
  14. from . import elements
  15. from . import roles
  16. from .selectable import Select
  17. from .. import exc
  18. from .. import util
  19. REQUIRED = util.symbol(
  20. "REQUIRED",
  21. """
  22. Placeholder for the value within a :class:`.BindParameter`
  23. which is required to be present when the statement is passed
  24. to :meth:`_engine.Connection.execute`.
  25. This symbol is typically used when a :func:`_expression.insert`
  26. or :func:`_expression.update` statement is compiled without parameter
  27. values present.
  28. """,
  29. )
  30. def _get_crud_params(compiler, stmt, compile_state, **kw):
  31. """create a set of tuples representing column/string pairs for use
  32. in an INSERT or UPDATE statement.
  33. Also generates the Compiled object's postfetch, prefetch, and
  34. returning column collections, used for default handling and ultimately
  35. populating the CursorResult's prefetch_cols() and postfetch_cols()
  36. collections.
  37. """
  38. compiler.postfetch = []
  39. compiler.insert_prefetch = []
  40. compiler.update_prefetch = []
  41. compiler.returning = []
  42. # getters - these are normally just column.key,
  43. # but in the case of mysql multi-table update, the rules for
  44. # .key must conditionally take tablename into account
  45. (
  46. _column_as_key,
  47. _getattr_col_key,
  48. _col_bind_name,
  49. ) = getters = _key_getters_for_crud_column(compiler, stmt, compile_state)
  50. compiler._key_getters_for_crud_column = getters
  51. # no parameters in the statement, no parameters in the
  52. # compiled params - return binds for all columns
  53. if compiler.column_keys is None and compile_state._no_parameters:
  54. return [
  55. (
  56. c,
  57. compiler.preparer.format_column(c),
  58. _create_bind_param(compiler, c, None, required=True),
  59. )
  60. for c in stmt.table.columns
  61. ]
  62. if compile_state._has_multi_parameters:
  63. spd = compile_state._multi_parameters[0]
  64. stmt_parameter_tuples = list(spd.items())
  65. spd_str_key = {_column_as_key(key) for key in spd}
  66. elif compile_state._ordered_values:
  67. spd = compile_state._dict_parameters
  68. stmt_parameter_tuples = compile_state._ordered_values
  69. spd_str_key = {_column_as_key(key) for key in spd}
  70. elif compile_state._dict_parameters:
  71. spd = compile_state._dict_parameters
  72. stmt_parameter_tuples = list(spd.items())
  73. spd_str_key = {_column_as_key(key) for key in spd}
  74. else:
  75. stmt_parameter_tuples = spd = spd_str_key = None
  76. # if we have statement parameters - set defaults in the
  77. # compiled params
  78. if compiler.column_keys is None:
  79. parameters = {}
  80. elif stmt_parameter_tuples:
  81. parameters = dict(
  82. (_column_as_key(key), REQUIRED)
  83. for key in compiler.column_keys
  84. if key not in spd_str_key
  85. )
  86. else:
  87. parameters = dict(
  88. (_column_as_key(key), REQUIRED) for key in compiler.column_keys
  89. )
  90. # create a list of column assignment clauses as tuples
  91. values = []
  92. if stmt_parameter_tuples is not None:
  93. _get_stmt_parameter_tuples_params(
  94. compiler,
  95. compile_state,
  96. parameters,
  97. stmt_parameter_tuples,
  98. _column_as_key,
  99. values,
  100. kw,
  101. )
  102. check_columns = {}
  103. # special logic that only occurs for multi-table UPDATE
  104. # statements
  105. if compile_state.isupdate and compile_state.is_multitable:
  106. _get_update_multitable_params(
  107. compiler,
  108. stmt,
  109. compile_state,
  110. stmt_parameter_tuples,
  111. check_columns,
  112. _col_bind_name,
  113. _getattr_col_key,
  114. values,
  115. kw,
  116. )
  117. if compile_state.isinsert and stmt._select_names:
  118. _scan_insert_from_select_cols(
  119. compiler,
  120. stmt,
  121. compile_state,
  122. parameters,
  123. _getattr_col_key,
  124. _column_as_key,
  125. _col_bind_name,
  126. check_columns,
  127. values,
  128. kw,
  129. )
  130. else:
  131. _scan_cols(
  132. compiler,
  133. stmt,
  134. compile_state,
  135. parameters,
  136. _getattr_col_key,
  137. _column_as_key,
  138. _col_bind_name,
  139. check_columns,
  140. values,
  141. kw,
  142. )
  143. if parameters and stmt_parameter_tuples:
  144. check = (
  145. set(parameters)
  146. .intersection(_column_as_key(k) for k, v in stmt_parameter_tuples)
  147. .difference(check_columns)
  148. )
  149. if check:
  150. raise exc.CompileError(
  151. "Unconsumed column names: %s"
  152. % (", ".join("%s" % (c,) for c in check))
  153. )
  154. if compile_state._has_multi_parameters:
  155. values = _extend_values_for_multiparams(
  156. compiler,
  157. stmt,
  158. compile_state,
  159. values,
  160. _column_as_key,
  161. kw,
  162. )
  163. elif (
  164. not values
  165. and compiler.for_executemany
  166. and compiler.dialect.supports_default_metavalue
  167. ):
  168. # convert an "INSERT DEFAULT VALUES"
  169. # into INSERT (firstcol) VALUES (DEFAULT) which can be turned
  170. # into an in-place multi values. This supports
  171. # insert_executemany_returning mode :)
  172. values = [
  173. (
  174. stmt.table.columns[0],
  175. compiler.preparer.format_column(stmt.table.columns[0]),
  176. "DEFAULT",
  177. )
  178. ]
  179. return values
  180. def _create_bind_param(
  181. compiler, col, value, process=True, required=False, name=None, **kw
  182. ):
  183. if name is None:
  184. name = col.key
  185. bindparam = elements.BindParameter(
  186. name, value, type_=col.type, required=required
  187. )
  188. bindparam._is_crud = True
  189. if process:
  190. bindparam = bindparam._compiler_dispatch(compiler, **kw)
  191. return bindparam
  192. def _handle_values_anonymous_param(compiler, col, value, name, **kw):
  193. # the insert() and update() constructs as of 1.4 will now produce anonymous
  194. # bindparam() objects in the values() collections up front when given plain
  195. # literal values. This is so that cache key behaviors, which need to
  196. # produce bound parameters in deterministic order without invoking any
  197. # compilation here, can be applied to these constructs when they include
  198. # values() (but not yet multi-values, which are not included in caching
  199. # right now).
  200. #
  201. # in order to produce the desired "crud" style name for these parameters,
  202. # which will also be targetable in engine/default.py through the usual
  203. # conventions, apply our desired name to these unique parameters by
  204. # populating the compiler truncated names cache with the desired name,
  205. # rather than having
  206. # compiler.visit_bindparam()->compiler._truncated_identifier make up a
  207. # name. Saves on call counts also.
  208. # for INSERT/UPDATE that's a CTE, we don't need names to match to
  209. # external parameters and these would also conflict in the case where
  210. # multiple insert/update are combined together using CTEs
  211. is_cte = "visiting_cte" in kw
  212. if (
  213. not is_cte
  214. and value.unique
  215. and isinstance(value.key, elements._truncated_label)
  216. ):
  217. compiler.truncated_names[("bindparam", value.key)] = name
  218. if value.type._isnull:
  219. # either unique parameter, or other bound parameters that were
  220. # passed in directly
  221. # set type to that of the column unconditionally
  222. value = value._with_binary_element_type(col.type)
  223. return value._compiler_dispatch(compiler, **kw)
  224. def _key_getters_for_crud_column(compiler, stmt, compile_state):
  225. if compile_state.isupdate and compile_state._extra_froms:
  226. # when extra tables are present, refer to the columns
  227. # in those extra tables as table-qualified, including in
  228. # dictionaries and when rendering bind param names.
  229. # the "main" table of the statement remains unqualified,
  230. # allowing the most compatibility with a non-multi-table
  231. # statement.
  232. _et = set(compile_state._extra_froms)
  233. c_key_role = functools.partial(
  234. coercions.expect_as_key, roles.DMLColumnRole
  235. )
  236. def _column_as_key(key):
  237. str_key = c_key_role(key)
  238. if hasattr(key, "table") and key.table in _et:
  239. return (key.table.name, str_key)
  240. else:
  241. return str_key
  242. def _getattr_col_key(col):
  243. if col.table in _et:
  244. return (col.table.name, col.key)
  245. else:
  246. return col.key
  247. def _col_bind_name(col):
  248. if col.table in _et:
  249. return "%s_%s" % (col.table.name, col.key)
  250. else:
  251. return col.key
  252. else:
  253. _column_as_key = functools.partial(
  254. coercions.expect_as_key, roles.DMLColumnRole
  255. )
  256. _getattr_col_key = _col_bind_name = operator.attrgetter("key")
  257. return _column_as_key, _getattr_col_key, _col_bind_name
  258. def _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. kw,
  269. ):
  270. (
  271. need_pks,
  272. implicit_returning,
  273. implicit_return_defaults,
  274. postfetch_lastrowid,
  275. ) = _get_returning_modifiers(compiler, stmt, compile_state)
  276. cols = [stmt.table.c[_column_as_key(name)] for name in stmt._select_names]
  277. assert compiler.stack[-1]["selectable"] is stmt
  278. compiler.stack[-1]["insert_from_select"] = stmt.select
  279. add_select_cols = []
  280. if stmt.include_insert_from_select_defaults:
  281. col_set = set(cols)
  282. for col in stmt.table.columns:
  283. if col not in col_set and col.default:
  284. cols.append(col)
  285. for c in cols:
  286. col_key = _getattr_col_key(c)
  287. if col_key in parameters and col_key not in check_columns:
  288. parameters.pop(col_key)
  289. values.append((c, compiler.preparer.format_column(c), None))
  290. else:
  291. _append_param_insert_select_hasdefault(
  292. compiler, stmt, c, add_select_cols, kw
  293. )
  294. if add_select_cols:
  295. values.extend(add_select_cols)
  296. ins_from_select = compiler.stack[-1]["insert_from_select"]
  297. if not isinstance(ins_from_select, Select):
  298. raise exc.CompileError(
  299. "Can't extend statement for INSERT..FROM SELECT to include "
  300. "additional default-holding column(s) "
  301. "%s. Convert the selectable to a subquery() first, or pass "
  302. "include_defaults=False to Insert.from_select() to skip these "
  303. "columns."
  304. % (", ".join(repr(key) for _, key, _ in add_select_cols),)
  305. )
  306. ins_from_select = ins_from_select._generate()
  307. # copy raw_columns
  308. ins_from_select._raw_columns = list(ins_from_select._raw_columns) + [
  309. expr for col, col_expr, expr in add_select_cols
  310. ]
  311. compiler.stack[-1]["insert_from_select"] = ins_from_select
  312. def _scan_cols(
  313. compiler,
  314. stmt,
  315. compile_state,
  316. parameters,
  317. _getattr_col_key,
  318. _column_as_key,
  319. _col_bind_name,
  320. check_columns,
  321. values,
  322. kw,
  323. ):
  324. (
  325. need_pks,
  326. implicit_returning,
  327. implicit_return_defaults,
  328. postfetch_lastrowid,
  329. ) = _get_returning_modifiers(compiler, stmt, compile_state)
  330. if compile_state._parameter_ordering:
  331. parameter_ordering = [
  332. _column_as_key(key) for key in compile_state._parameter_ordering
  333. ]
  334. ordered_keys = set(parameter_ordering)
  335. cols = [
  336. stmt.table.c[key]
  337. for key in parameter_ordering
  338. if isinstance(key, util.string_types) and key in stmt.table.c
  339. ] + [c for c in stmt.table.c if c.key not in ordered_keys]
  340. else:
  341. cols = stmt.table.columns
  342. for c in cols:
  343. # scan through every column in the target table
  344. col_key = _getattr_col_key(c)
  345. if col_key in parameters and col_key not in check_columns:
  346. # parameter is present for the column. use that.
  347. _append_param_parameter(
  348. compiler,
  349. stmt,
  350. compile_state,
  351. c,
  352. col_key,
  353. parameters,
  354. _col_bind_name,
  355. implicit_returning,
  356. implicit_return_defaults,
  357. values,
  358. kw,
  359. )
  360. elif compile_state.isinsert:
  361. # no parameter is present and it's an insert.
  362. if c.primary_key and need_pks:
  363. # it's a primary key column, it will need to be generated by a
  364. # default generator of some kind, and the statement expects
  365. # inserted_primary_key to be available.
  366. if implicit_returning:
  367. # we can use RETURNING, find out how to invoke this
  368. # column and get the value where RETURNING is an option.
  369. # we can inline server-side functions in this case.
  370. _append_param_insert_pk_returning(
  371. compiler, stmt, c, values, kw
  372. )
  373. else:
  374. # otherwise, find out how to invoke this column
  375. # and get its value where RETURNING is not an option.
  376. # if we have to invoke a server-side function, we need
  377. # to pre-execute it. or if this is a straight
  378. # autoincrement column and the dialect supports it
  379. # we can use cursor.lastrowid.
  380. _append_param_insert_pk_no_returning(
  381. compiler, stmt, c, values, kw
  382. )
  383. elif c.default is not None:
  384. # column has a default, but it's not a pk column, or it is but
  385. # we don't need to get the pk back.
  386. _append_param_insert_hasdefault(
  387. compiler, stmt, c, implicit_return_defaults, values, kw
  388. )
  389. elif c.server_default is not None:
  390. # column has a DDL-level default, and is either not a pk
  391. # column or we don't need the pk.
  392. if implicit_return_defaults and c in implicit_return_defaults:
  393. compiler.returning.append(c)
  394. elif not c.primary_key:
  395. compiler.postfetch.append(c)
  396. elif implicit_return_defaults and c in implicit_return_defaults:
  397. compiler.returning.append(c)
  398. elif (
  399. c.primary_key
  400. and c is not stmt.table._autoincrement_column
  401. and not c.nullable
  402. ):
  403. _warn_pk_with_no_anticipated_value(c)
  404. elif compile_state.isupdate:
  405. # no parameter is present and it's an insert.
  406. _append_param_update(
  407. compiler,
  408. compile_state,
  409. stmt,
  410. c,
  411. implicit_return_defaults,
  412. values,
  413. kw,
  414. )
  415. def _append_param_parameter(
  416. compiler,
  417. stmt,
  418. compile_state,
  419. c,
  420. col_key,
  421. parameters,
  422. _col_bind_name,
  423. implicit_returning,
  424. implicit_return_defaults,
  425. values,
  426. kw,
  427. ):
  428. value = parameters.pop(col_key)
  429. col_value = compiler.preparer.format_column(
  430. c, use_table=compile_state.include_table_with_column_exprs
  431. )
  432. if coercions._is_literal(value):
  433. value = _create_bind_param(
  434. compiler,
  435. c,
  436. value,
  437. required=value is REQUIRED,
  438. name=_col_bind_name(c)
  439. if not compile_state._has_multi_parameters
  440. else "%s_m0" % _col_bind_name(c),
  441. **kw
  442. )
  443. elif value._is_bind_parameter:
  444. value = _handle_values_anonymous_param(
  445. compiler,
  446. c,
  447. value,
  448. name=_col_bind_name(c)
  449. if not compile_state._has_multi_parameters
  450. else "%s_m0" % _col_bind_name(c),
  451. **kw
  452. )
  453. else:
  454. # value is a SQL expression
  455. value = compiler.process(value.self_group(), **kw)
  456. if compile_state.isupdate:
  457. if implicit_return_defaults and c in implicit_return_defaults:
  458. compiler.returning.append(c)
  459. else:
  460. compiler.postfetch.append(c)
  461. else:
  462. if c.primary_key:
  463. if implicit_returning:
  464. compiler.returning.append(c)
  465. elif compiler.dialect.postfetch_lastrowid:
  466. compiler.postfetch_lastrowid = True
  467. elif implicit_return_defaults and c in implicit_return_defaults:
  468. compiler.returning.append(c)
  469. else:
  470. # postfetch specifically means, "we can SELECT the row we just
  471. # inserted by primary key to get back the server generated
  472. # defaults". so by definition this can't be used to get the
  473. # primary key value back, because we need to have it ahead of
  474. # time.
  475. compiler.postfetch.append(c)
  476. values.append((c, col_value, value))
  477. def _append_param_insert_pk_returning(compiler, stmt, c, values, kw):
  478. """Create a primary key expression in the INSERT statement where
  479. we want to populate result.inserted_primary_key and RETURNING
  480. is available.
  481. """
  482. if c.default is not None:
  483. if c.default.is_sequence:
  484. if compiler.dialect.supports_sequences and (
  485. not c.default.optional
  486. or not compiler.dialect.sequences_optional
  487. ):
  488. values.append(
  489. (
  490. c,
  491. compiler.preparer.format_column(c),
  492. compiler.process(c.default, **kw),
  493. )
  494. )
  495. compiler.returning.append(c)
  496. elif c.default.is_clause_element:
  497. values.append(
  498. (
  499. c,
  500. compiler.preparer.format_column(c),
  501. compiler.process(c.default.arg.self_group(), **kw),
  502. )
  503. )
  504. compiler.returning.append(c)
  505. else:
  506. # client side default. OK we can't use RETURNING, need to
  507. # do a "prefetch", which in fact fetches the default value
  508. # on the Python side
  509. values.append(
  510. (
  511. c,
  512. compiler.preparer.format_column(c),
  513. _create_insert_prefetch_bind_param(compiler, c, **kw),
  514. )
  515. )
  516. elif c is stmt.table._autoincrement_column or c.server_default is not None:
  517. compiler.returning.append(c)
  518. elif not c.nullable:
  519. # no .default, no .server_default, not autoincrement, we have
  520. # no indication this primary key column will have any value
  521. _warn_pk_with_no_anticipated_value(c)
  522. def _append_param_insert_pk_no_returning(compiler, stmt, c, values, kw):
  523. """Create a primary key expression in the INSERT statement where
  524. we want to populate result.inserted_primary_key and we cannot use
  525. RETURNING.
  526. Depending on the kind of default here we may create a bound parameter
  527. in the INSERT statement and pre-execute a default generation function,
  528. or we may use cursor.lastrowid if supported by the dialect.
  529. """
  530. if (
  531. # column has a Python-side default
  532. c.default is not None
  533. and (
  534. # and it either is not a sequence, or it is and we support
  535. # sequences and want to invoke it
  536. not c.default.is_sequence
  537. or (
  538. compiler.dialect.supports_sequences
  539. and (
  540. not c.default.optional
  541. or not compiler.dialect.sequences_optional
  542. )
  543. )
  544. )
  545. ) or (
  546. # column is the "autoincrement column"
  547. c is stmt.table._autoincrement_column
  548. and (
  549. # dialect can't use cursor.lastrowid
  550. not compiler.dialect.postfetch_lastrowid
  551. and (
  552. # column has a Sequence and we support those
  553. (
  554. c.default is not None
  555. and c.default.is_sequence
  556. and compiler.dialect.supports_sequences
  557. )
  558. or
  559. # column has no default on it, but dialect can run the
  560. # "autoincrement" mechanism explicitly, e.g. PostgreSQL
  561. # SERIAL we know the sequence name
  562. (
  563. c.default is None
  564. and compiler.dialect.preexecute_autoincrement_sequences
  565. )
  566. )
  567. )
  568. ):
  569. # do a pre-execute of the default
  570. values.append(
  571. (
  572. c,
  573. compiler.preparer.format_column(c),
  574. _create_insert_prefetch_bind_param(compiler, c, **kw),
  575. )
  576. )
  577. elif (
  578. c.default is None
  579. and c.server_default is None
  580. and not c.nullable
  581. and c is not stmt.table._autoincrement_column
  582. ):
  583. # no .default, no .server_default, not autoincrement, we have
  584. # no indication this primary key column will have any value
  585. _warn_pk_with_no_anticipated_value(c)
  586. elif compiler.dialect.postfetch_lastrowid:
  587. # finally, where it seems like there will be a generated primary key
  588. # value and we haven't set up any other way to fetch it, and the
  589. # dialect supports cursor.lastrowid, switch on the lastrowid flag so
  590. # that the DefaultExecutionContext calls upon cursor.lastrowid
  591. compiler.postfetch_lastrowid = True
  592. def _append_param_insert_hasdefault(
  593. compiler, stmt, c, implicit_return_defaults, values, kw
  594. ):
  595. if c.default.is_sequence:
  596. if compiler.dialect.supports_sequences and (
  597. not c.default.optional or not compiler.dialect.sequences_optional
  598. ):
  599. values.append(
  600. (
  601. c,
  602. compiler.preparer.format_column(c),
  603. compiler.process(c.default, **kw),
  604. )
  605. )
  606. if implicit_return_defaults and c in implicit_return_defaults:
  607. compiler.returning.append(c)
  608. elif not c.primary_key:
  609. compiler.postfetch.append(c)
  610. elif c.default.is_clause_element:
  611. values.append(
  612. (
  613. c,
  614. compiler.preparer.format_column(c),
  615. compiler.process(c.default.arg.self_group(), **kw),
  616. )
  617. )
  618. if implicit_return_defaults and c in implicit_return_defaults:
  619. compiler.returning.append(c)
  620. elif not c.primary_key:
  621. # don't add primary key column to postfetch
  622. compiler.postfetch.append(c)
  623. else:
  624. values.append(
  625. (
  626. c,
  627. compiler.preparer.format_column(c),
  628. _create_insert_prefetch_bind_param(compiler, c, **kw),
  629. )
  630. )
  631. def _append_param_insert_select_hasdefault(compiler, stmt, c, values, kw):
  632. if c.default.is_sequence:
  633. if compiler.dialect.supports_sequences and (
  634. not c.default.optional or not compiler.dialect.sequences_optional
  635. ):
  636. values.append(
  637. (c, compiler.preparer.format_column(c), c.default.next_value())
  638. )
  639. elif c.default.is_clause_element:
  640. values.append(
  641. (c, compiler.preparer.format_column(c), c.default.arg.self_group())
  642. )
  643. else:
  644. values.append(
  645. (
  646. c,
  647. compiler.preparer.format_column(c),
  648. _create_insert_prefetch_bind_param(
  649. compiler, c, process=False, **kw
  650. ),
  651. )
  652. )
  653. def _append_param_update(
  654. compiler, compile_state, stmt, c, implicit_return_defaults, values, kw
  655. ):
  656. include_table = compile_state.include_table_with_column_exprs
  657. if c.onupdate is not None and not c.onupdate.is_sequence:
  658. if c.onupdate.is_clause_element:
  659. values.append(
  660. (
  661. c,
  662. compiler.preparer.format_column(
  663. c,
  664. use_table=include_table,
  665. ),
  666. compiler.process(c.onupdate.arg.self_group(), **kw),
  667. )
  668. )
  669. if implicit_return_defaults and c in implicit_return_defaults:
  670. compiler.returning.append(c)
  671. else:
  672. compiler.postfetch.append(c)
  673. else:
  674. values.append(
  675. (
  676. c,
  677. compiler.preparer.format_column(
  678. c,
  679. use_table=include_table,
  680. ),
  681. _create_update_prefetch_bind_param(compiler, c, **kw),
  682. )
  683. )
  684. elif c.server_onupdate is not None:
  685. if implicit_return_defaults and c in implicit_return_defaults:
  686. compiler.returning.append(c)
  687. else:
  688. compiler.postfetch.append(c)
  689. elif (
  690. implicit_return_defaults
  691. and (stmt._return_defaults_columns or not stmt._return_defaults)
  692. and c in implicit_return_defaults
  693. ):
  694. compiler.returning.append(c)
  695. def _create_insert_prefetch_bind_param(
  696. compiler, c, process=True, name=None, **kw
  697. ):
  698. param = _create_bind_param(
  699. compiler, c, None, process=process, name=name, **kw
  700. )
  701. compiler.insert_prefetch.append(c)
  702. return param
  703. def _create_update_prefetch_bind_param(
  704. compiler, c, process=True, name=None, **kw
  705. ):
  706. param = _create_bind_param(
  707. compiler, c, None, process=process, name=name, **kw
  708. )
  709. compiler.update_prefetch.append(c)
  710. return param
  711. class _multiparam_column(elements.ColumnElement):
  712. _is_multiparam_column = True
  713. def __init__(self, original, index):
  714. self.index = index
  715. self.key = "%s_m%d" % (original.key, index + 1)
  716. self.original = original
  717. self.default = original.default
  718. self.type = original.type
  719. def compare(self, other, **kw):
  720. raise NotImplementedError()
  721. def _copy_internals(self, other, **kw):
  722. raise NotImplementedError()
  723. def __eq__(self, other):
  724. return (
  725. isinstance(other, _multiparam_column)
  726. and other.key == self.key
  727. and other.original == self.original
  728. )
  729. def _process_multiparam_default_bind(compiler, stmt, c, index, kw):
  730. if not c.default:
  731. raise exc.CompileError(
  732. "INSERT value for column %s is explicitly rendered as a bound"
  733. "parameter in the VALUES clause; "
  734. "a Python-side value or SQL expression is required" % c
  735. )
  736. elif c.default.is_clause_element:
  737. return compiler.process(c.default.arg.self_group(), **kw)
  738. elif c.default.is_sequence:
  739. # these conditions would have been established
  740. # by append_param_insert_(?:hasdefault|pk_returning|pk_no_returning)
  741. # in order for us to be here, so these don't need to be
  742. # checked
  743. # assert compiler.dialect.supports_sequences and (
  744. # not c.default.optional
  745. # or not compiler.dialect.sequences_optional
  746. # )
  747. return compiler.process(c.default, **kw)
  748. else:
  749. col = _multiparam_column(c, index)
  750. if isinstance(stmt, dml.Insert):
  751. return _create_insert_prefetch_bind_param(compiler, col, **kw)
  752. else:
  753. return _create_update_prefetch_bind_param(compiler, col, **kw)
  754. def _get_update_multitable_params(
  755. compiler,
  756. stmt,
  757. compile_state,
  758. stmt_parameter_tuples,
  759. check_columns,
  760. _col_bind_name,
  761. _getattr_col_key,
  762. values,
  763. kw,
  764. ):
  765. normalized_params = dict(
  766. (coercions.expect(roles.DMLColumnRole, c), param)
  767. for c, param in stmt_parameter_tuples
  768. )
  769. include_table = compile_state.include_table_with_column_exprs
  770. affected_tables = set()
  771. for t in compile_state._extra_froms:
  772. for c in t.c:
  773. if c in normalized_params:
  774. affected_tables.add(t)
  775. check_columns[_getattr_col_key(c)] = c
  776. value = normalized_params[c]
  777. col_value = compiler.process(c, include_table=include_table)
  778. if coercions._is_literal(value):
  779. value = _create_bind_param(
  780. compiler,
  781. c,
  782. value,
  783. required=value is REQUIRED,
  784. name=_col_bind_name(c),
  785. **kw # TODO: no test coverage for literal binds here
  786. )
  787. elif value._is_bind_parameter:
  788. value = _handle_values_anonymous_param(
  789. compiler, c, value, name=_col_bind_name(c), **kw
  790. )
  791. else:
  792. compiler.postfetch.append(c)
  793. value = compiler.process(value.self_group(), **kw)
  794. values.append((c, col_value, value))
  795. # determine tables which are actually to be updated - process onupdate
  796. # and server_onupdate for these
  797. for t in affected_tables:
  798. for c in t.c:
  799. if c in normalized_params:
  800. continue
  801. elif c.onupdate is not None and not c.onupdate.is_sequence:
  802. if c.onupdate.is_clause_element:
  803. values.append(
  804. (
  805. c,
  806. compiler.process(c, include_table=include_table),
  807. compiler.process(
  808. c.onupdate.arg.self_group(), **kw
  809. ),
  810. )
  811. )
  812. compiler.postfetch.append(c)
  813. else:
  814. values.append(
  815. (
  816. c,
  817. compiler.process(c, include_table=include_table),
  818. _create_update_prefetch_bind_param(
  819. compiler, c, name=_col_bind_name(c), **kw
  820. ),
  821. )
  822. )
  823. elif c.server_onupdate is not None:
  824. compiler.postfetch.append(c)
  825. def _extend_values_for_multiparams(
  826. compiler,
  827. stmt,
  828. compile_state,
  829. values,
  830. _column_as_key,
  831. kw,
  832. ):
  833. values_0 = values
  834. values = [values]
  835. for i, row in enumerate(compile_state._multi_parameters[1:]):
  836. extension = []
  837. row = {_column_as_key(key): v for key, v in row.items()}
  838. for (col, col_expr, param) in values_0:
  839. if col.key in row:
  840. key = col.key
  841. if coercions._is_literal(row[key]):
  842. new_param = _create_bind_param(
  843. compiler,
  844. col,
  845. row[key],
  846. name="%s_m%d" % (col.key, i + 1),
  847. **kw
  848. )
  849. else:
  850. new_param = compiler.process(row[key].self_group(), **kw)
  851. else:
  852. new_param = _process_multiparam_default_bind(
  853. compiler, stmt, col, i, kw
  854. )
  855. extension.append((col, col_expr, new_param))
  856. values.append(extension)
  857. return values
  858. def _get_stmt_parameter_tuples_params(
  859. compiler,
  860. compile_state,
  861. parameters,
  862. stmt_parameter_tuples,
  863. _column_as_key,
  864. values,
  865. kw,
  866. ):
  867. for k, v in stmt_parameter_tuples:
  868. colkey = _column_as_key(k)
  869. if colkey is not None:
  870. parameters.setdefault(colkey, v)
  871. else:
  872. # a non-Column expression on the left side;
  873. # add it to values() in an "as-is" state,
  874. # coercing right side to bound param
  875. # note one of the main use cases for this is array slice
  876. # updates on PostgreSQL, as the left side is also an expression.
  877. col_expr = compiler.process(
  878. k, include_table=compile_state.include_table_with_column_exprs
  879. )
  880. if coercions._is_literal(v):
  881. v = compiler.process(
  882. elements.BindParameter(None, v, type_=k.type), **kw
  883. )
  884. else:
  885. if v._is_bind_parameter and v.type._isnull:
  886. # either unique parameter, or other bound parameters that
  887. # were passed in directly
  888. # set type to that of the column unconditionally
  889. v = v._with_binary_element_type(k.type)
  890. v = compiler.process(v.self_group(), **kw)
  891. values.append((k, col_expr, v))
  892. def _get_returning_modifiers(compiler, stmt, compile_state):
  893. need_pks = (
  894. compile_state.isinsert
  895. and not stmt._inline
  896. and (
  897. not compiler.for_executemany
  898. or (
  899. compiler.dialect.insert_executemany_returning
  900. and stmt._return_defaults
  901. )
  902. )
  903. and not stmt._returning
  904. and not compile_state._has_multi_parameters
  905. )
  906. implicit_returning = (
  907. need_pks
  908. and compiler.dialect.implicit_returning
  909. and stmt.table.implicit_returning
  910. )
  911. if compile_state.isinsert:
  912. implicit_return_defaults = implicit_returning and stmt._return_defaults
  913. elif compile_state.isupdate:
  914. implicit_return_defaults = (
  915. compiler.dialect.implicit_returning
  916. and stmt.table.implicit_returning
  917. and stmt._return_defaults
  918. )
  919. else:
  920. # this line is unused, currently we are always
  921. # isinsert or isupdate
  922. implicit_return_defaults = False # pragma: no cover
  923. if implicit_return_defaults:
  924. if not stmt._return_defaults_columns:
  925. implicit_return_defaults = set(stmt.table.c)
  926. else:
  927. implicit_return_defaults = set(stmt._return_defaults_columns)
  928. postfetch_lastrowid = need_pks and compiler.dialect.postfetch_lastrowid
  929. return (
  930. need_pks,
  931. implicit_returning,
  932. implicit_return_defaults,
  933. postfetch_lastrowid,
  934. )
  935. def _warn_pk_with_no_anticipated_value(c):
  936. msg = (
  937. "Column '%s.%s' is marked as a member of the "
  938. "primary key for table '%s', "
  939. "but has no Python-side or server-side default generator indicated, "
  940. "nor does it indicate 'autoincrement=True' or 'nullable=True', "
  941. "and no explicit value is passed. "
  942. "Primary key columns typically may not store NULL."
  943. % (c.table.fullname, c.name, c.table.fullname)
  944. )
  945. if len(c.table.primary_key) > 1:
  946. msg += (
  947. " Note that as of SQLAlchemy 1.1, 'autoincrement=True' must be "
  948. "indicated explicitly for composite (e.g. multicolumn) primary "
  949. "keys if AUTO_INCREMENT/SERIAL/IDENTITY "
  950. "behavior is expected for one of the columns in the primary key. "
  951. "CREATE TABLE statements are impacted by this change as well on "
  952. "most backends."
  953. )
  954. util.warn(msg)