You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1053 lines
34KB

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