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.

1428 lines
50KB

  1. # sql/dml.py
  2. # Copyright (C) 2009-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. """
  8. Provide :class:`_expression.Insert`, :class:`_expression.Update` and
  9. :class:`_expression.Delete`.
  10. """
  11. from sqlalchemy.types import NullType
  12. from . import coercions
  13. from . import roles
  14. from . import util as sql_util
  15. from .base import _entity_namespace_key
  16. from .base import _exclusive_against
  17. from .base import _from_objects
  18. from .base import _generative
  19. from .base import ColumnCollection
  20. from .base import CompileState
  21. from .base import DialectKWArgs
  22. from .base import Executable
  23. from .base import HasCompileState
  24. from .elements import BooleanClauseList
  25. from .elements import ClauseElement
  26. from .elements import Null
  27. from .selectable import HasCTE
  28. from .selectable import HasPrefixes
  29. from .selectable import ReturnsRows
  30. from .visitors import InternalTraversal
  31. from .. import exc
  32. from .. import util
  33. from ..util import collections_abc
  34. class DMLState(CompileState):
  35. _no_parameters = True
  36. _dict_parameters = None
  37. _multi_parameters = None
  38. _ordered_values = None
  39. _parameter_ordering = None
  40. _has_multi_parameters = False
  41. isupdate = False
  42. isdelete = False
  43. isinsert = False
  44. def __init__(self, statement, compiler, **kw):
  45. raise NotImplementedError()
  46. @property
  47. def dml_table(self):
  48. return self.statement.table
  49. def _make_extra_froms(self, statement):
  50. froms = []
  51. all_tables = list(sql_util.tables_from_leftmost(statement.table))
  52. seen = {all_tables[0]}
  53. for crit in statement._where_criteria:
  54. for item in _from_objects(crit):
  55. if not seen.intersection(item._cloned_set):
  56. froms.append(item)
  57. seen.update(item._cloned_set)
  58. froms.extend(all_tables[1:])
  59. return froms
  60. def _process_multi_values(self, statement):
  61. if not statement._supports_multi_parameters:
  62. raise exc.InvalidRequestError(
  63. "%s construct does not support "
  64. "multiple parameter sets." % statement.__visit_name__.upper()
  65. )
  66. for parameters in statement._multi_values:
  67. multi_parameters = [
  68. {
  69. c.key: value
  70. for c, value in zip(statement.table.c, parameter_set)
  71. }
  72. if isinstance(parameter_set, collections_abc.Sequence)
  73. else parameter_set
  74. for parameter_set in parameters
  75. ]
  76. if self._no_parameters:
  77. self._no_parameters = False
  78. self._has_multi_parameters = True
  79. self._multi_parameters = multi_parameters
  80. self._dict_parameters = self._multi_parameters[0]
  81. elif not self._has_multi_parameters:
  82. self._cant_mix_formats_error()
  83. else:
  84. self._multi_parameters.extend(multi_parameters)
  85. def _process_values(self, statement):
  86. if self._no_parameters:
  87. self._has_multi_parameters = False
  88. self._dict_parameters = statement._values
  89. self._no_parameters = False
  90. elif self._has_multi_parameters:
  91. self._cant_mix_formats_error()
  92. def _process_ordered_values(self, statement):
  93. parameters = statement._ordered_values
  94. if self._no_parameters:
  95. self._no_parameters = False
  96. self._dict_parameters = dict(parameters)
  97. self._ordered_values = parameters
  98. self._parameter_ordering = [key for key, value in parameters]
  99. elif self._has_multi_parameters:
  100. self._cant_mix_formats_error()
  101. else:
  102. raise exc.InvalidRequestError(
  103. "Can only invoke ordered_values() once, and not mixed "
  104. "with any other values() call"
  105. )
  106. def _process_select_values(self, statement):
  107. parameters = {
  108. coercions.expect(roles.DMLColumnRole, name, as_key=True): Null()
  109. for name in statement._select_names
  110. }
  111. if self._no_parameters:
  112. self._no_parameters = False
  113. self._dict_parameters = parameters
  114. else:
  115. # this condition normally not reachable as the Insert
  116. # does not allow this construction to occur
  117. assert False, "This statement already has parameters"
  118. def _cant_mix_formats_error(self):
  119. raise exc.InvalidRequestError(
  120. "Can't mix single and multiple VALUES "
  121. "formats in one INSERT statement; one style appends to a "
  122. "list while the other replaces values, so the intent is "
  123. "ambiguous."
  124. )
  125. @CompileState.plugin_for("default", "insert")
  126. class InsertDMLState(DMLState):
  127. isinsert = True
  128. include_table_with_column_exprs = False
  129. def __init__(self, statement, compiler, **kw):
  130. self.statement = statement
  131. self.isinsert = True
  132. if statement._select_names:
  133. self._process_select_values(statement)
  134. if statement._values is not None:
  135. self._process_values(statement)
  136. if statement._multi_values:
  137. self._process_multi_values(statement)
  138. @CompileState.plugin_for("default", "update")
  139. class UpdateDMLState(DMLState):
  140. isupdate = True
  141. include_table_with_column_exprs = False
  142. def __init__(self, statement, compiler, **kw):
  143. self.statement = statement
  144. self.isupdate = True
  145. self._preserve_parameter_order = statement._preserve_parameter_order
  146. if statement._ordered_values is not None:
  147. self._process_ordered_values(statement)
  148. elif statement._values is not None:
  149. self._process_values(statement)
  150. elif statement._multi_values:
  151. self._process_multi_values(statement)
  152. self._extra_froms = ef = self._make_extra_froms(statement)
  153. self.is_multitable = mt = ef and self._dict_parameters
  154. self.include_table_with_column_exprs = (
  155. mt and compiler.render_table_with_column_in_update_from
  156. )
  157. @CompileState.plugin_for("default", "delete")
  158. class DeleteDMLState(DMLState):
  159. isdelete = True
  160. def __init__(self, statement, compiler, **kw):
  161. self.statement = statement
  162. self.isdelete = True
  163. self._extra_froms = self._make_extra_froms(statement)
  164. class UpdateBase(
  165. roles.DMLRole,
  166. HasCTE,
  167. HasCompileState,
  168. DialectKWArgs,
  169. HasPrefixes,
  170. ReturnsRows,
  171. Executable,
  172. ClauseElement,
  173. ):
  174. """Form the base for ``INSERT``, ``UPDATE``, and ``DELETE`` statements."""
  175. __visit_name__ = "update_base"
  176. _execution_options = Executable._execution_options.union(
  177. {"autocommit": True}
  178. )
  179. _hints = util.immutabledict()
  180. named_with_column = False
  181. _return_defaults = None
  182. _returning = ()
  183. is_dml = True
  184. @classmethod
  185. def _constructor_20_deprecations(cls, fn_name, clsname, names):
  186. param_to_method_lookup = dict(
  187. whereclause=(
  188. "The :paramref:`%(func)s.whereclause` parameter "
  189. "will be removed "
  190. "in SQLAlchemy 2.0. Please refer to the "
  191. ":meth:`%(classname)s.where` method."
  192. ),
  193. values=(
  194. "The :paramref:`%(func)s.values` parameter will be removed "
  195. "in SQLAlchemy 2.0. Please refer to the "
  196. ":meth:`%(classname)s.values` method."
  197. ),
  198. bind=(
  199. "The :paramref:`%(func)s.bind` parameter will be removed in "
  200. "SQLAlchemy 2.0. Please use explicit connection execution."
  201. ),
  202. inline=(
  203. "The :paramref:`%(func)s.inline` parameter will be "
  204. "removed in "
  205. "SQLAlchemy 2.0. Please use the "
  206. ":meth:`%(classname)s.inline` method."
  207. ),
  208. prefixes=(
  209. "The :paramref:`%(func)s.prefixes parameter will be "
  210. "removed in "
  211. "SQLAlchemy 2.0. Please use the "
  212. ":meth:`%(classname)s.prefix_with` "
  213. "method."
  214. ),
  215. return_defaults=(
  216. "The :paramref:`%(func)s.return_defaults` parameter will be "
  217. "removed in SQLAlchemy 2.0. Please use the "
  218. ":meth:`%(classname)s.return_defaults` method."
  219. ),
  220. returning=(
  221. "The :paramref:`%(func)s.returning` parameter will be "
  222. "removed in SQLAlchemy 2.0. Please use the "
  223. ":meth:`%(classname)s.returning`` method."
  224. ),
  225. preserve_parameter_order=(
  226. "The :paramref:`%(func)s.preserve_parameter_order` parameter "
  227. "will be removed in SQLAlchemy 2.0. Use the "
  228. ":meth:`%(classname)s.ordered_values` method with a list "
  229. "of tuples. "
  230. ),
  231. )
  232. return util.deprecated_params(
  233. **{
  234. name: (
  235. "2.0",
  236. param_to_method_lookup[name]
  237. % {
  238. "func": "_expression.%s" % fn_name,
  239. "classname": "_expression.%s" % clsname,
  240. },
  241. )
  242. for name in names
  243. }
  244. )
  245. def _generate_fromclause_column_proxies(self, fromclause):
  246. fromclause._columns._populate_separate_keys(
  247. col._make_proxy(fromclause) for col in self._returning
  248. )
  249. def params(self, *arg, **kw):
  250. """Set the parameters for the statement.
  251. This method raises ``NotImplementedError`` on the base class,
  252. and is overridden by :class:`.ValuesBase` to provide the
  253. SET/VALUES clause of UPDATE and INSERT.
  254. """
  255. raise NotImplementedError(
  256. "params() is not supported for INSERT/UPDATE/DELETE statements."
  257. " To set the values for an INSERT or UPDATE statement, use"
  258. " stmt.values(**parameters)."
  259. )
  260. @_generative
  261. def with_dialect_options(self, **opt):
  262. """Add dialect options to this INSERT/UPDATE/DELETE object.
  263. e.g.::
  264. upd = table.update().dialect_options(mysql_limit=10)
  265. .. versionadded: 1.4 - this method supersedes the dialect options
  266. associated with the constructor.
  267. """
  268. self._validate_dialect_kwargs(opt)
  269. def _validate_dialect_kwargs_deprecated(self, dialect_kw):
  270. util.warn_deprecated_20(
  271. "Passing dialect keyword arguments directly to the "
  272. "%s constructor is deprecated and will be removed in SQLAlchemy "
  273. "2.0. Please use the ``with_dialect_options()`` method."
  274. % (self.__class__.__name__)
  275. )
  276. self._validate_dialect_kwargs(dialect_kw)
  277. def bind(self):
  278. """Return a 'bind' linked to this :class:`.UpdateBase`
  279. or a :class:`_schema.Table` associated with it.
  280. """
  281. return self._bind or self.table.bind
  282. def _set_bind(self, bind):
  283. self._bind = bind
  284. bind = property(bind, _set_bind)
  285. @_generative
  286. def returning(self, *cols):
  287. r"""Add a :term:`RETURNING` or equivalent clause to this statement.
  288. e.g.:
  289. .. sourcecode:: pycon+sql
  290. >>> stmt = (
  291. ... table.update()
  292. ... .where(table.c.data == "value")
  293. ... .values(status="X")
  294. ... .returning(table.c.server_flag, table.c.updated_timestamp)
  295. ... )
  296. >>> print(stmt)
  297. UPDATE some_table SET status=:status
  298. WHERE some_table.data = :data_1
  299. RETURNING some_table.server_flag, some_table.updated_timestamp
  300. The method may be invoked multiple times to add new entries to the
  301. list of expressions to be returned.
  302. .. versionadded:: 1.4.0b2 The method may be invoked multiple times to
  303. add new entries to the list of expressions to be returned.
  304. The given collection of column expressions should be derived from the
  305. table that is the target of the INSERT, UPDATE, or DELETE. While
  306. :class:`_schema.Column` objects are typical, the elements can also be
  307. expressions:
  308. .. sourcecode:: pycon+sql
  309. >>> stmt = table.insert().returning(
  310. ... (table.c.first_name + " " + table.c.last_name).label("fullname")
  311. ... )
  312. >>> print(stmt)
  313. INSERT INTO some_table (first_name, last_name)
  314. VALUES (:first_name, :last_name)
  315. RETURNING some_table.first_name || :first_name_1 || some_table.last_name AS fullname
  316. Upon compilation, a RETURNING clause, or database equivalent,
  317. will be rendered within the statement. For INSERT and UPDATE,
  318. the values are the newly inserted/updated values. For DELETE,
  319. the values are those of the rows which were deleted.
  320. Upon execution, the values of the columns to be returned are made
  321. available via the result set and can be iterated using
  322. :meth:`_engine.CursorResult.fetchone` and similar.
  323. For DBAPIs which do not
  324. natively support returning values (i.e. cx_oracle), SQLAlchemy will
  325. approximate this behavior at the result level so that a reasonable
  326. amount of behavioral neutrality is provided.
  327. Note that not all databases/DBAPIs
  328. support RETURNING. For those backends with no support,
  329. an exception is raised upon compilation and/or execution.
  330. For those who do support it, the functionality across backends
  331. varies greatly, including restrictions on executemany()
  332. and other statements which return multiple rows. Please
  333. read the documentation notes for the database in use in
  334. order to determine the availability of RETURNING.
  335. .. seealso::
  336. :meth:`.ValuesBase.return_defaults` - an alternative method tailored
  337. towards efficient fetching of server-side defaults and triggers
  338. for single-row INSERTs or UPDATEs.
  339. :ref:`tutorial_insert_returning` - in the :ref:`unified_tutorial`
  340. """ # noqa E501
  341. if self._return_defaults:
  342. raise exc.InvalidRequestError(
  343. "return_defaults() is already configured on this statement"
  344. )
  345. self._returning += tuple(
  346. coercions.expect(roles.ColumnsClauseRole, c) for c in cols
  347. )
  348. @property
  349. def _all_selected_columns(self):
  350. return self._returning
  351. @property
  352. def exported_columns(self):
  353. """Return the RETURNING columns as a column collection for this
  354. statement.
  355. .. versionadded:: 1.4
  356. """
  357. # TODO: no coverage here
  358. return ColumnCollection(
  359. (c.key, c) for c in self._all_selected_columns
  360. ).as_immutable()
  361. @_generative
  362. def with_hint(self, text, selectable=None, dialect_name="*"):
  363. """Add a table hint for a single table to this
  364. INSERT/UPDATE/DELETE statement.
  365. .. note::
  366. :meth:`.UpdateBase.with_hint` currently applies only to
  367. Microsoft SQL Server. For MySQL INSERT/UPDATE/DELETE hints, use
  368. :meth:`.UpdateBase.prefix_with`.
  369. The text of the hint is rendered in the appropriate
  370. location for the database backend in use, relative
  371. to the :class:`_schema.Table` that is the subject of this
  372. statement, or optionally to that of the given
  373. :class:`_schema.Table` passed as the ``selectable`` argument.
  374. The ``dialect_name`` option will limit the rendering of a particular
  375. hint to a particular backend. Such as, to add a hint
  376. that only takes effect for SQL Server::
  377. mytable.insert().with_hint("WITH (PAGLOCK)", dialect_name="mssql")
  378. :param text: Text of the hint.
  379. :param selectable: optional :class:`_schema.Table` that specifies
  380. an element of the FROM clause within an UPDATE or DELETE
  381. to be the subject of the hint - applies only to certain backends.
  382. :param dialect_name: defaults to ``*``, if specified as the name
  383. of a particular dialect, will apply these hints only when
  384. that dialect is in use.
  385. """
  386. if selectable is None:
  387. selectable = self.table
  388. self._hints = self._hints.union({(selectable, dialect_name): text})
  389. class ValuesBase(UpdateBase):
  390. """Supplies support for :meth:`.ValuesBase.values` to
  391. INSERT and UPDATE constructs."""
  392. __visit_name__ = "values_base"
  393. _supports_multi_parameters = False
  394. _preserve_parameter_order = False
  395. select = None
  396. _post_values_clause = None
  397. _values = None
  398. _multi_values = ()
  399. _ordered_values = None
  400. _select_names = None
  401. _returning = ()
  402. def __init__(self, table, values, prefixes):
  403. self.table = coercions.expect(
  404. roles.DMLTableRole, table, apply_propagate_attrs=self
  405. )
  406. if values is not None:
  407. self.values.non_generative(self, values)
  408. if prefixes:
  409. self._setup_prefixes(prefixes)
  410. @_generative
  411. @_exclusive_against(
  412. "_select_names",
  413. "_ordered_values",
  414. msgs={
  415. "_select_names": "This construct already inserts from a SELECT",
  416. "_ordered_values": "This statement already has ordered "
  417. "values present",
  418. },
  419. )
  420. def values(self, *args, **kwargs):
  421. r"""Specify a fixed VALUES clause for an INSERT statement, or the SET
  422. clause for an UPDATE.
  423. Note that the :class:`_expression.Insert` and
  424. :class:`_expression.Update`
  425. constructs support
  426. per-execution time formatting of the VALUES and/or SET clauses,
  427. based on the arguments passed to :meth:`_engine.Connection.execute`.
  428. However, the :meth:`.ValuesBase.values` method can be used to "fix" a
  429. particular set of parameters into the statement.
  430. Multiple calls to :meth:`.ValuesBase.values` will produce a new
  431. construct, each one with the parameter list modified to include
  432. the new parameters sent. In the typical case of a single
  433. dictionary of parameters, the newly passed keys will replace
  434. the same keys in the previous construct. In the case of a list-based
  435. "multiple values" construct, each new list of values is extended
  436. onto the existing list of values.
  437. :param \**kwargs: key value pairs representing the string key
  438. of a :class:`_schema.Column`
  439. mapped to the value to be rendered into the
  440. VALUES or SET clause::
  441. users.insert().values(name="some name")
  442. users.update().where(users.c.id==5).values(name="some name")
  443. :param \*args: As an alternative to passing key/value parameters,
  444. a dictionary, tuple, or list of dictionaries or tuples can be passed
  445. as a single positional argument in order to form the VALUES or
  446. SET clause of the statement. The forms that are accepted vary
  447. based on whether this is an :class:`_expression.Insert` or an
  448. :class:`_expression.Update` construct.
  449. For either an :class:`_expression.Insert` or
  450. :class:`_expression.Update`
  451. construct, a single dictionary can be passed, which works the same as
  452. that of the kwargs form::
  453. users.insert().values({"name": "some name"})
  454. users.update().values({"name": "some new name"})
  455. Also for either form but more typically for the
  456. :class:`_expression.Insert` construct, a tuple that contains an
  457. entry for every column in the table is also accepted::
  458. users.insert().values((5, "some name"))
  459. The :class:`_expression.Insert` construct also supports being
  460. passed a list of dictionaries or full-table-tuples, which on the
  461. server will render the less common SQL syntax of "multiple values" -
  462. this syntax is supported on backends such as SQLite, PostgreSQL,
  463. MySQL, but not necessarily others::
  464. users.insert().values([
  465. {"name": "some name"},
  466. {"name": "some other name"},
  467. {"name": "yet another name"},
  468. ])
  469. The above form would render a multiple VALUES statement similar to::
  470. INSERT INTO users (name) VALUES
  471. (:name_1),
  472. (:name_2),
  473. (:name_3)
  474. It is essential to note that **passing multiple values is
  475. NOT the same as using traditional executemany() form**. The above
  476. syntax is a **special** syntax not typically used. To emit an
  477. INSERT statement against multiple rows, the normal method is
  478. to pass a multiple values list to the
  479. :meth:`_engine.Connection.execute`
  480. method, which is supported by all database backends and is generally
  481. more efficient for a very large number of parameters.
  482. .. seealso::
  483. :ref:`execute_multiple` - an introduction to
  484. the traditional Core method of multiple parameter set
  485. invocation for INSERTs and other statements.
  486. .. versionchanged:: 1.0.0 an INSERT that uses a multiple-VALUES
  487. clause, even a list of length one,
  488. implies that the :paramref:`_expression.Insert.inline`
  489. flag is set to
  490. True, indicating that the statement will not attempt to fetch
  491. the "last inserted primary key" or other defaults. The
  492. statement deals with an arbitrary number of rows, so the
  493. :attr:`_engine.CursorResult.inserted_primary_key`
  494. accessor does not
  495. apply.
  496. .. versionchanged:: 1.0.0 A multiple-VALUES INSERT now supports
  497. columns with Python side default values and callables in the
  498. same way as that of an "executemany" style of invocation; the
  499. callable is invoked for each row. See :ref:`bug_3288`
  500. for other details.
  501. The UPDATE construct also supports rendering the SET parameters
  502. in a specific order. For this feature refer to the
  503. :meth:`_expression.Update.ordered_values` method.
  504. .. seealso::
  505. :meth:`_expression.Update.ordered_values`
  506. """
  507. if args:
  508. # positional case. this is currently expensive. we don't
  509. # yet have positional-only args so we have to check the length.
  510. # then we need to check multiparams vs. single dictionary.
  511. # since the parameter format is needed in order to determine
  512. # a cache key, we need to determine this up front.
  513. arg = args[0]
  514. if kwargs:
  515. raise exc.ArgumentError(
  516. "Can't pass positional and kwargs to values() "
  517. "simultaneously"
  518. )
  519. elif len(args) > 1:
  520. raise exc.ArgumentError(
  521. "Only a single dictionary/tuple or list of "
  522. "dictionaries/tuples is accepted positionally."
  523. )
  524. elif not self._preserve_parameter_order and isinstance(
  525. arg, collections_abc.Sequence
  526. ):
  527. if arg and isinstance(arg[0], (list, dict, tuple)):
  528. self._multi_values += (arg,)
  529. return
  530. # tuple values
  531. arg = {c.key: value for c, value in zip(self.table.c, arg)}
  532. elif self._preserve_parameter_order and not isinstance(
  533. arg, collections_abc.Sequence
  534. ):
  535. raise ValueError(
  536. "When preserve_parameter_order is True, "
  537. "values() only accepts a list of 2-tuples"
  538. )
  539. else:
  540. # kwarg path. this is the most common path for non-multi-params
  541. # so this is fairly quick.
  542. arg = kwargs
  543. if args:
  544. raise exc.ArgumentError(
  545. "Only a single dictionary/tuple or list of "
  546. "dictionaries/tuples is accepted positionally."
  547. )
  548. # for top level values(), convert literals to anonymous bound
  549. # parameters at statement construction time, so that these values can
  550. # participate in the cache key process like any other ClauseElement.
  551. # crud.py now intercepts bound parameters with unique=True from here
  552. # and ensures they get the "crud"-style name when rendered.
  553. if self._preserve_parameter_order:
  554. arg = [
  555. (
  556. coercions.expect(roles.DMLColumnRole, k),
  557. coercions.expect(
  558. roles.ExpressionElementRole,
  559. v,
  560. type_=NullType(),
  561. is_crud=True,
  562. ),
  563. )
  564. for k, v in arg
  565. ]
  566. self._ordered_values = arg
  567. else:
  568. arg = {
  569. coercions.expect(roles.DMLColumnRole, k): coercions.expect(
  570. roles.ExpressionElementRole,
  571. v,
  572. type_=NullType(),
  573. is_crud=True,
  574. )
  575. for k, v in arg.items()
  576. }
  577. if self._values:
  578. self._values = self._values.union(arg)
  579. else:
  580. self._values = util.immutabledict(arg)
  581. @_generative
  582. @_exclusive_against(
  583. "_returning",
  584. msgs={
  585. "_returning": "RETURNING is already configured on this statement"
  586. },
  587. defaults={"_returning": _returning},
  588. )
  589. def return_defaults(self, *cols):
  590. """Make use of a :term:`RETURNING` clause for the purpose
  591. of fetching server-side expressions and defaults.
  592. E.g.::
  593. stmt = table.insert().values(data='newdata').return_defaults()
  594. result = connection.execute(stmt)
  595. server_created_at = result.returned_defaults['created_at']
  596. When used against a backend that supports RETURNING, all column
  597. values generated by SQL expression or server-side-default will be
  598. added to any existing RETURNING clause, provided that
  599. :meth:`.UpdateBase.returning` is not used simultaneously. The column
  600. values will then be available on the result using the
  601. :attr:`_engine.CursorResult.returned_defaults` accessor as
  602. a dictionary,
  603. referring to values keyed to the :class:`_schema.Column`
  604. object as well as
  605. its ``.key``.
  606. This method differs from :meth:`.UpdateBase.returning` in these ways:
  607. 1. :meth:`.ValuesBase.return_defaults` is only intended for use with an
  608. INSERT or an UPDATE statement that matches exactly one row per
  609. parameter set. While the RETURNING construct in the general sense
  610. supports multiple rows for a multi-row UPDATE or DELETE statement,
  611. or for special cases of INSERT that return multiple rows (e.g.
  612. INSERT from SELECT, multi-valued VALUES clause),
  613. :meth:`.ValuesBase.return_defaults` is intended only for an
  614. "ORM-style" single-row INSERT/UPDATE statement. The row
  615. returned by the statement is also consumed implicitly when
  616. :meth:`.ValuesBase.return_defaults` is used. By contrast,
  617. :meth:`.UpdateBase.returning` leaves the RETURNING result-set intact
  618. with a collection of any number of rows.
  619. 2. It is compatible with the existing logic to fetch auto-generated
  620. primary key values, also known as "implicit returning". Backends
  621. that support RETURNING will automatically make use of RETURNING in
  622. order to fetch the value of newly generated primary keys; while the
  623. :meth:`.UpdateBase.returning` method circumvents this behavior,
  624. :meth:`.ValuesBase.return_defaults` leaves it intact.
  625. 3. It can be called against any backend. Backends that don't support
  626. RETURNING will skip the usage of the feature, rather than raising
  627. an exception. The return value of
  628. :attr:`_engine.CursorResult.returned_defaults` will be ``None``
  629. 4. An INSERT statement invoked with executemany() is supported if the
  630. backend database driver supports the
  631. ``insert_executemany_returning`` feature, currently this includes
  632. PostgreSQL with psycopg2. When executemany is used, the
  633. :attr:`_engine.CursorResult.returned_defaults_rows` and
  634. :attr:`_engine.CursorResult.inserted_primary_key_rows` accessors
  635. will return the inserted defaults and primary keys.
  636. .. versionadded:: 1.4
  637. :meth:`.ValuesBase.return_defaults` is used by the ORM to provide
  638. an efficient implementation for the ``eager_defaults`` feature of
  639. :func:`.mapper`.
  640. :param cols: optional list of column key names or
  641. :class:`_schema.Column`
  642. objects. If omitted, all column expressions evaluated on the server
  643. are added to the returning list.
  644. .. versionadded:: 0.9.0
  645. .. seealso::
  646. :meth:`.UpdateBase.returning`
  647. :attr:`_engine.CursorResult.returned_defaults`
  648. :attr:`_engine.CursorResult.returned_defaults_rows`
  649. :attr:`_engine.CursorResult.inserted_primary_key`
  650. :attr:`_engine.CursorResult.inserted_primary_key_rows`
  651. """
  652. self._return_defaults = cols or True
  653. class Insert(ValuesBase):
  654. """Represent an INSERT construct.
  655. The :class:`_expression.Insert` object is created using the
  656. :func:`_expression.insert()` function.
  657. """
  658. __visit_name__ = "insert"
  659. _supports_multi_parameters = True
  660. select = None
  661. include_insert_from_select_defaults = False
  662. is_insert = True
  663. _traverse_internals = (
  664. [
  665. ("table", InternalTraversal.dp_clauseelement),
  666. ("_inline", InternalTraversal.dp_boolean),
  667. ("_select_names", InternalTraversal.dp_string_list),
  668. ("_values", InternalTraversal.dp_dml_values),
  669. ("_multi_values", InternalTraversal.dp_dml_multi_values),
  670. ("select", InternalTraversal.dp_clauseelement),
  671. ("_post_values_clause", InternalTraversal.dp_clauseelement),
  672. ("_returning", InternalTraversal.dp_clauseelement_list),
  673. ("_hints", InternalTraversal.dp_table_hint_list),
  674. ]
  675. + HasPrefixes._has_prefixes_traverse_internals
  676. + DialectKWArgs._dialect_kwargs_traverse_internals
  677. + Executable._executable_traverse_internals
  678. )
  679. @ValuesBase._constructor_20_deprecations(
  680. "insert",
  681. "Insert",
  682. [
  683. "values",
  684. "inline",
  685. "bind",
  686. "prefixes",
  687. "returning",
  688. "return_defaults",
  689. ],
  690. )
  691. def __init__(
  692. self,
  693. table,
  694. values=None,
  695. inline=False,
  696. bind=None,
  697. prefixes=None,
  698. returning=None,
  699. return_defaults=False,
  700. **dialect_kw
  701. ):
  702. """Construct an :class:`_expression.Insert` object.
  703. E.g.::
  704. from sqlalchemy import insert
  705. stmt = (
  706. insert(user_table).
  707. values(name='username', fullname='Full Username')
  708. )
  709. Similar functionality is available via the
  710. :meth:`_expression.TableClause.insert` method on
  711. :class:`_schema.Table`.
  712. .. seealso::
  713. :ref:`coretutorial_insert_expressions` - in the
  714. :ref:`1.x tutorial <sqlexpression_toplevel>`
  715. :ref:`tutorial_core_insert` - in the :ref:`unified_tutorial`
  716. :param table: :class:`_expression.TableClause`
  717. which is the subject of the
  718. insert.
  719. :param values: collection of values to be inserted; see
  720. :meth:`_expression.Insert.values`
  721. for a description of allowed formats here.
  722. Can be omitted entirely; a :class:`_expression.Insert` construct
  723. will also dynamically render the VALUES clause at execution time
  724. based on the parameters passed to :meth:`_engine.Connection.execute`.
  725. :param inline: if True, no attempt will be made to retrieve the
  726. SQL-generated default values to be provided within the statement;
  727. in particular,
  728. this allows SQL expressions to be rendered 'inline' within the
  729. statement without the need to pre-execute them beforehand; for
  730. backends that support "returning", this turns off the "implicit
  731. returning" feature for the statement.
  732. If both :paramref:`_expression.Insert.values` and compile-time bind
  733. parameters are present, the compile-time bind parameters override the
  734. information specified within :paramref:`_expression.Insert.values` on a
  735. per-key basis.
  736. The keys within :paramref:`_expression.Insert.values` can be either
  737. :class:`~sqlalchemy.schema.Column` objects or their string
  738. identifiers. Each key may reference one of:
  739. * a literal data value (i.e. string, number, etc.);
  740. * a Column object;
  741. * a SELECT statement.
  742. If a ``SELECT`` statement is specified which references this
  743. ``INSERT`` statement's table, the statement will be correlated
  744. against the ``INSERT`` statement.
  745. .. seealso::
  746. :ref:`coretutorial_insert_expressions` - SQL Expression Tutorial
  747. :ref:`inserts_and_updates` - SQL Expression Tutorial
  748. """
  749. super(Insert, self).__init__(table, values, prefixes)
  750. self._bind = bind
  751. self._inline = inline
  752. if returning:
  753. self._returning = returning
  754. if dialect_kw:
  755. self._validate_dialect_kwargs_deprecated(dialect_kw)
  756. self._return_defaults = return_defaults
  757. @_generative
  758. def inline(self):
  759. """Make this :class:`_expression.Insert` construct "inline" .
  760. When set, no attempt will be made to retrieve the
  761. SQL-generated default values to be provided within the statement;
  762. in particular,
  763. this allows SQL expressions to be rendered 'inline' within the
  764. statement without the need to pre-execute them beforehand; for
  765. backends that support "returning", this turns off the "implicit
  766. returning" feature for the statement.
  767. .. versionchanged:: 1.4 the :paramref:`_expression.Insert.inline`
  768. parameter
  769. is now superseded by the :meth:`_expression.Insert.inline` method.
  770. """
  771. self._inline = True
  772. @_generative
  773. def from_select(self, names, select, include_defaults=True):
  774. """Return a new :class:`_expression.Insert` construct which represents
  775. an ``INSERT...FROM SELECT`` statement.
  776. e.g.::
  777. sel = select(table1.c.a, table1.c.b).where(table1.c.c > 5)
  778. ins = table2.insert().from_select(['a', 'b'], sel)
  779. :param names: a sequence of string column names or
  780. :class:`_schema.Column`
  781. objects representing the target columns.
  782. :param select: a :func:`_expression.select` construct,
  783. :class:`_expression.FromClause`
  784. or other construct which resolves into a
  785. :class:`_expression.FromClause`,
  786. such as an ORM :class:`_query.Query` object, etc. The order of
  787. columns returned from this FROM clause should correspond to the
  788. order of columns sent as the ``names`` parameter; while this
  789. is not checked before passing along to the database, the database
  790. would normally raise an exception if these column lists don't
  791. correspond.
  792. :param include_defaults: if True, non-server default values and
  793. SQL expressions as specified on :class:`_schema.Column` objects
  794. (as documented in :ref:`metadata_defaults_toplevel`) not
  795. otherwise specified in the list of names will be rendered
  796. into the INSERT and SELECT statements, so that these values are also
  797. included in the data to be inserted.
  798. .. note:: A Python-side default that uses a Python callable function
  799. will only be invoked **once** for the whole statement, and **not
  800. per row**.
  801. .. versionadded:: 1.0.0 - :meth:`_expression.Insert.from_select`
  802. now renders
  803. Python-side and SQL expression column defaults into the
  804. SELECT statement for columns otherwise not included in the
  805. list of column names.
  806. .. versionchanged:: 1.0.0 an INSERT that uses FROM SELECT
  807. implies that the :paramref:`_expression.insert.inline`
  808. flag is set to
  809. True, indicating that the statement will not attempt to fetch
  810. the "last inserted primary key" or other defaults. The statement
  811. deals with an arbitrary number of rows, so the
  812. :attr:`_engine.CursorResult.inserted_primary_key`
  813. accessor does not apply.
  814. """
  815. if self._values:
  816. raise exc.InvalidRequestError(
  817. "This construct already inserts value expressions"
  818. )
  819. self._select_names = names
  820. self._inline = True
  821. self.include_insert_from_select_defaults = include_defaults
  822. self.select = coercions.expect(roles.DMLSelectRole, select)
  823. class DMLWhereBase(object):
  824. _where_criteria = ()
  825. @_generative
  826. def where(self, *whereclause):
  827. """Return a new construct with the given expression(s) added to
  828. its WHERE clause, joined to the existing clause via AND, if any.
  829. Both :meth:`_dml.Update.where` and :meth:`_dml.Delete.where`
  830. support multiple-table forms, including database-specific
  831. ``UPDATE...FROM`` as well as ``DELETE..USING``. For backends that
  832. don't have multiple-table support, a backend agnostic approach
  833. to using multiple tables is to make use of correlated subqueries.
  834. See the linked tutorial sections below for examples.
  835. .. seealso::
  836. **1.x Tutorial Examples**
  837. :ref:`tutorial_1x_correlated_updates`
  838. :ref:`multi_table_updates`
  839. :ref:`multi_table_deletes`
  840. **2.0 Tutorial Examples**
  841. :ref:`tutorial_correlated_updates`
  842. :ref:`tutorial_update_from`
  843. :ref:`tutorial_multi_table_deletes`
  844. """
  845. for criterion in whereclause:
  846. where_criteria = coercions.expect(roles.WhereHavingRole, criterion)
  847. self._where_criteria += (where_criteria,)
  848. def filter(self, *criteria):
  849. """A synonym for the :meth:`_dml.DMLWhereBase.where` method.
  850. .. versionadded:: 1.4
  851. """
  852. return self.where(*criteria)
  853. def _filter_by_zero(self):
  854. return self.table
  855. def filter_by(self, **kwargs):
  856. r"""apply the given filtering criterion as a WHERE clause
  857. to this select.
  858. """
  859. from_entity = self._filter_by_zero()
  860. clauses = [
  861. _entity_namespace_key(from_entity, key) == value
  862. for key, value in kwargs.items()
  863. ]
  864. return self.filter(*clauses)
  865. @property
  866. def whereclause(self):
  867. """Return the completed WHERE clause for this :class:`.DMLWhereBase`
  868. statement.
  869. This assembles the current collection of WHERE criteria
  870. into a single :class:`_expression.BooleanClauseList` construct.
  871. .. versionadded:: 1.4
  872. """
  873. return BooleanClauseList._construct_for_whereclause(
  874. self._where_criteria
  875. )
  876. class Update(DMLWhereBase, ValuesBase):
  877. """Represent an Update construct.
  878. The :class:`_expression.Update` object is created using the
  879. :func:`_expression.update()` function.
  880. """
  881. __visit_name__ = "update"
  882. is_update = True
  883. _traverse_internals = (
  884. [
  885. ("table", InternalTraversal.dp_clauseelement),
  886. ("_where_criteria", InternalTraversal.dp_clauseelement_list),
  887. ("_inline", InternalTraversal.dp_boolean),
  888. ("_ordered_values", InternalTraversal.dp_dml_ordered_values),
  889. ("_values", InternalTraversal.dp_dml_values),
  890. ("_returning", InternalTraversal.dp_clauseelement_list),
  891. ("_hints", InternalTraversal.dp_table_hint_list),
  892. ]
  893. + HasPrefixes._has_prefixes_traverse_internals
  894. + DialectKWArgs._dialect_kwargs_traverse_internals
  895. + Executable._executable_traverse_internals
  896. )
  897. @ValuesBase._constructor_20_deprecations(
  898. "update",
  899. "Update",
  900. [
  901. "whereclause",
  902. "values",
  903. "inline",
  904. "bind",
  905. "prefixes",
  906. "returning",
  907. "return_defaults",
  908. "preserve_parameter_order",
  909. ],
  910. )
  911. def __init__(
  912. self,
  913. table,
  914. whereclause=None,
  915. values=None,
  916. inline=False,
  917. bind=None,
  918. prefixes=None,
  919. returning=None,
  920. return_defaults=False,
  921. preserve_parameter_order=False,
  922. **dialect_kw
  923. ):
  924. r"""Construct an :class:`_expression.Update` object.
  925. E.g.::
  926. from sqlalchemy import update
  927. stmt = (
  928. update(user_table).
  929. where(user_table.c.id == 5).
  930. values(name='user #5')
  931. )
  932. Similar functionality is available via the
  933. :meth:`_expression.TableClause.update` method on
  934. :class:`_schema.Table`.
  935. .. seealso::
  936. :ref:`inserts_and_updates` - in the
  937. :ref:`1.x tutorial <sqlexpression_toplevel>`
  938. :ref:`tutorial_core_update_delete` - in the :ref:`unified_tutorial`
  939. :param table: A :class:`_schema.Table`
  940. object representing the database
  941. table to be updated.
  942. :param whereclause: Optional SQL expression describing the ``WHERE``
  943. condition of the ``UPDATE`` statement; is equivalent to using the
  944. more modern :meth:`~Update.where()` method to specify the ``WHERE``
  945. clause.
  946. :param values:
  947. Optional dictionary which specifies the ``SET`` conditions of the
  948. ``UPDATE``. If left as ``None``, the ``SET``
  949. conditions are determined from those parameters passed to the
  950. statement during the execution and/or compilation of the
  951. statement. When compiled standalone without any parameters,
  952. the ``SET`` clause generates for all columns.
  953. Modern applications may prefer to use the generative
  954. :meth:`_expression.Update.values` method to set the values of the
  955. UPDATE statement.
  956. :param inline:
  957. if True, SQL defaults present on :class:`_schema.Column` objects via
  958. the ``default`` keyword will be compiled 'inline' into the statement
  959. and not pre-executed. This means that their values will not
  960. be available in the dictionary returned from
  961. :meth:`_engine.CursorResult.last_updated_params`.
  962. :param preserve_parameter_order: if True, the update statement is
  963. expected to receive parameters **only** via the
  964. :meth:`_expression.Update.values` method,
  965. and they must be passed as a Python
  966. ``list`` of 2-tuples. The rendered UPDATE statement will emit the SET
  967. clause for each referenced column maintaining this order.
  968. .. versionadded:: 1.0.10
  969. .. seealso::
  970. :ref:`updates_order_parameters` - illustrates the
  971. :meth:`_expression.Update.ordered_values` method.
  972. If both ``values`` and compile-time bind parameters are present, the
  973. compile-time bind parameters override the information specified
  974. within ``values`` on a per-key basis.
  975. The keys within ``values`` can be either :class:`_schema.Column`
  976. objects or their string identifiers (specifically the "key" of the
  977. :class:`_schema.Column`, normally but not necessarily equivalent to
  978. its "name"). Normally, the
  979. :class:`_schema.Column` objects used here are expected to be
  980. part of the target :class:`_schema.Table` that is the table
  981. to be updated. However when using MySQL, a multiple-table
  982. UPDATE statement can refer to columns from any of
  983. the tables referred to in the WHERE clause.
  984. The values referred to in ``values`` are typically:
  985. * a literal data value (i.e. string, number, etc.)
  986. * a SQL expression, such as a related :class:`_schema.Column`,
  987. a scalar-returning :func:`_expression.select` construct,
  988. etc.
  989. When combining :func:`_expression.select` constructs within the
  990. values clause of an :func:`_expression.update`
  991. construct, the subquery represented
  992. by the :func:`_expression.select` should be *correlated* to the
  993. parent table, that is, providing criterion which links the table inside
  994. the subquery to the outer table being updated::
  995. users.update().values(
  996. name=select(addresses.c.email_address).\
  997. where(addresses.c.user_id==users.c.id).\
  998. scalar_subquery()
  999. )
  1000. .. seealso::
  1001. :ref:`inserts_and_updates` - SQL Expression
  1002. Language Tutorial
  1003. """
  1004. self._preserve_parameter_order = preserve_parameter_order
  1005. super(Update, self).__init__(table, values, prefixes)
  1006. self._bind = bind
  1007. if returning:
  1008. self._returning = returning
  1009. if whereclause is not None:
  1010. self._where_criteria += (
  1011. coercions.expect(roles.WhereHavingRole, whereclause),
  1012. )
  1013. self._inline = inline
  1014. if dialect_kw:
  1015. self._validate_dialect_kwargs_deprecated(dialect_kw)
  1016. self._return_defaults = return_defaults
  1017. @_generative
  1018. def ordered_values(self, *args):
  1019. """Specify the VALUES clause of this UPDATE statement with an explicit
  1020. parameter ordering that will be maintained in the SET clause of the
  1021. resulting UPDATE statement.
  1022. E.g.::
  1023. stmt = table.update().ordered_values(
  1024. ("name", "ed"), ("ident": "foo")
  1025. )
  1026. .. seealso::
  1027. :ref:`updates_order_parameters` - full example of the
  1028. :meth:`_expression.Update.ordered_values` method.
  1029. .. versionchanged:: 1.4 The :meth:`_expression.Update.ordered_values`
  1030. method
  1031. supersedes the
  1032. :paramref:`_expression.update.preserve_parameter_order`
  1033. parameter, which will be removed in SQLAlchemy 2.0.
  1034. """
  1035. if self._values:
  1036. raise exc.ArgumentError(
  1037. "This statement already has values present"
  1038. )
  1039. elif self._ordered_values:
  1040. raise exc.ArgumentError(
  1041. "This statement already has ordered values present"
  1042. )
  1043. arg = [
  1044. (
  1045. coercions.expect(roles.DMLColumnRole, k),
  1046. coercions.expect(
  1047. roles.ExpressionElementRole,
  1048. v,
  1049. type_=NullType(),
  1050. is_crud=True,
  1051. ),
  1052. )
  1053. for k, v in args
  1054. ]
  1055. self._ordered_values = arg
  1056. @_generative
  1057. def inline(self):
  1058. """Make this :class:`_expression.Update` construct "inline" .
  1059. When set, SQL defaults present on :class:`_schema.Column`
  1060. objects via the
  1061. ``default`` keyword will be compiled 'inline' into the statement and
  1062. not pre-executed. This means that their values will not be available
  1063. in the dictionary returned from
  1064. :meth:`_engine.CursorResult.last_updated_params`.
  1065. .. versionchanged:: 1.4 the :paramref:`_expression.update.inline`
  1066. parameter
  1067. is now superseded by the :meth:`_expression.Update.inline` method.
  1068. """
  1069. self._inline = True
  1070. class Delete(DMLWhereBase, UpdateBase):
  1071. """Represent a DELETE construct.
  1072. The :class:`_expression.Delete` object is created using the
  1073. :func:`_expression.delete()` function.
  1074. """
  1075. __visit_name__ = "delete"
  1076. is_delete = True
  1077. _traverse_internals = (
  1078. [
  1079. ("table", InternalTraversal.dp_clauseelement),
  1080. ("_where_criteria", InternalTraversal.dp_clauseelement_list),
  1081. ("_returning", InternalTraversal.dp_clauseelement_list),
  1082. ("_hints", InternalTraversal.dp_table_hint_list),
  1083. ]
  1084. + HasPrefixes._has_prefixes_traverse_internals
  1085. + DialectKWArgs._dialect_kwargs_traverse_internals
  1086. + Executable._executable_traverse_internals
  1087. )
  1088. @ValuesBase._constructor_20_deprecations(
  1089. "delete",
  1090. "Delete",
  1091. ["whereclause", "values", "bind", "prefixes", "returning"],
  1092. )
  1093. def __init__(
  1094. self,
  1095. table,
  1096. whereclause=None,
  1097. bind=None,
  1098. returning=None,
  1099. prefixes=None,
  1100. **dialect_kw
  1101. ):
  1102. r"""Construct :class:`_expression.Delete` object.
  1103. E.g.::
  1104. from sqlalchemy import delete
  1105. stmt = (
  1106. delete(user_table).
  1107. where(user_table.c.id == 5)
  1108. )
  1109. Similar functionality is available via the
  1110. :meth:`_expression.TableClause.delete` method on
  1111. :class:`_schema.Table`.
  1112. .. seealso::
  1113. :ref:`inserts_and_updates` - in the
  1114. :ref:`1.x tutorial <sqlexpression_toplevel>`
  1115. :ref:`tutorial_core_update_delete` - in the :ref:`unified_tutorial`
  1116. :param table: The table to delete rows from.
  1117. :param whereclause: Optional SQL expression describing the ``WHERE``
  1118. condition of the ``DELETE`` statement; is equivalent to using the
  1119. more modern :meth:`~Delete.where()` method to specify the ``WHERE``
  1120. clause.
  1121. .. seealso::
  1122. :ref:`deletes` - SQL Expression Tutorial
  1123. """
  1124. self._bind = bind
  1125. self.table = coercions.expect(
  1126. roles.DMLTableRole, table, apply_propagate_attrs=self
  1127. )
  1128. if returning:
  1129. self._returning = returning
  1130. if prefixes:
  1131. self._setup_prefixes(prefixes)
  1132. if whereclause is not None:
  1133. self._where_criteria += (
  1134. coercions.expect(roles.WhereHavingRole, whereclause),
  1135. )
  1136. if dialect_kw:
  1137. self._validate_dialect_kwargs_deprecated(dialect_kw)