dml.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851
  1. # sql/dml.py
  2. # Copyright (C) 2009-2017 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:`.Insert`, :class:`.Update` and :class:`.Delete`.
  9. """
  10. from .base import Executable, _generative, _from_objects, DialectKWArgs, \
  11. ColumnCollection
  12. from .elements import ClauseElement, _literal_as_text, Null, and_, _clone, \
  13. _column_as_key
  14. from .selectable import _interpret_as_from, _interpret_as_select, \
  15. HasPrefixes, HasCTE
  16. from .. import util
  17. from .. import exc
  18. class UpdateBase(
  19. HasCTE, DialectKWArgs, HasPrefixes, Executable, ClauseElement):
  20. """Form the base for ``INSERT``, ``UPDATE``, and ``DELETE`` statements.
  21. """
  22. __visit_name__ = 'update_base'
  23. _execution_options = \
  24. Executable._execution_options.union({'autocommit': True})
  25. _hints = util.immutabledict()
  26. _parameter_ordering = None
  27. _prefixes = ()
  28. named_with_column = False
  29. def _process_colparams(self, parameters):
  30. def process_single(p):
  31. if isinstance(p, (list, tuple)):
  32. return dict(
  33. (c.key, pval)
  34. for c, pval in zip(self.table.c, p)
  35. )
  36. else:
  37. return p
  38. if self._preserve_parameter_order and parameters is not None:
  39. if not isinstance(parameters, list) or \
  40. (parameters and not isinstance(parameters[0], tuple)):
  41. raise ValueError(
  42. "When preserve_parameter_order is True, "
  43. "values() only accepts a list of 2-tuples")
  44. self._parameter_ordering = [key for key, value in parameters]
  45. return dict(parameters), False
  46. if (isinstance(parameters, (list, tuple)) and parameters and
  47. isinstance(parameters[0], (list, tuple, dict))):
  48. if not self._supports_multi_parameters:
  49. raise exc.InvalidRequestError(
  50. "This construct does not support "
  51. "multiple parameter sets.")
  52. return [process_single(p) for p in parameters], True
  53. else:
  54. return process_single(parameters), False
  55. def params(self, *arg, **kw):
  56. """Set the parameters for the statement.
  57. This method raises ``NotImplementedError`` on the base class,
  58. and is overridden by :class:`.ValuesBase` to provide the
  59. SET/VALUES clause of UPDATE and INSERT.
  60. """
  61. raise NotImplementedError(
  62. "params() is not supported for INSERT/UPDATE/DELETE statements."
  63. " To set the values for an INSERT or UPDATE statement, use"
  64. " stmt.values(**parameters).")
  65. def bind(self):
  66. """Return a 'bind' linked to this :class:`.UpdateBase`
  67. or a :class:`.Table` associated with it.
  68. """
  69. return self._bind or self.table.bind
  70. def _set_bind(self, bind):
  71. self._bind = bind
  72. bind = property(bind, _set_bind)
  73. @_generative
  74. def returning(self, *cols):
  75. r"""Add a :term:`RETURNING` or equivalent clause to this statement.
  76. e.g.::
  77. stmt = table.update().\
  78. where(table.c.data == 'value').\
  79. values(status='X').\
  80. returning(table.c.server_flag,
  81. table.c.updated_timestamp)
  82. for server_flag, updated_timestamp in connection.execute(stmt):
  83. print(server_flag, updated_timestamp)
  84. The given collection of column expressions should be derived from
  85. the table that is
  86. the target of the INSERT, UPDATE, or DELETE. While :class:`.Column`
  87. objects are typical, the elements can also be expressions::
  88. stmt = table.insert().returning(
  89. (table.c.first_name + " " + table.c.last_name).
  90. label('fullname'))
  91. Upon compilation, a RETURNING clause, or database equivalent,
  92. will be rendered within the statement. For INSERT and UPDATE,
  93. the values are the newly inserted/updated values. For DELETE,
  94. the values are those of the rows which were deleted.
  95. Upon execution, the values of the columns to be returned are made
  96. available via the result set and can be iterated using
  97. :meth:`.ResultProxy.fetchone` and similar. For DBAPIs which do not
  98. natively support returning values (i.e. cx_oracle), SQLAlchemy will
  99. approximate this behavior at the result level so that a reasonable
  100. amount of behavioral neutrality is provided.
  101. Note that not all databases/DBAPIs
  102. support RETURNING. For those backends with no support,
  103. an exception is raised upon compilation and/or execution.
  104. For those who do support it, the functionality across backends
  105. varies greatly, including restrictions on executemany()
  106. and other statements which return multiple rows. Please
  107. read the documentation notes for the database in use in
  108. order to determine the availability of RETURNING.
  109. .. seealso::
  110. :meth:`.ValuesBase.return_defaults` - an alternative method tailored
  111. towards efficient fetching of server-side defaults and triggers
  112. for single-row INSERTs or UPDATEs.
  113. """
  114. self._returning = cols
  115. @_generative
  116. def with_hint(self, text, selectable=None, dialect_name="*"):
  117. """Add a table hint for a single table to this
  118. INSERT/UPDATE/DELETE statement.
  119. .. note::
  120. :meth:`.UpdateBase.with_hint` currently applies only to
  121. Microsoft SQL Server. For MySQL INSERT/UPDATE/DELETE hints, use
  122. :meth:`.UpdateBase.prefix_with`.
  123. The text of the hint is rendered in the appropriate
  124. location for the database backend in use, relative
  125. to the :class:`.Table` that is the subject of this
  126. statement, or optionally to that of the given
  127. :class:`.Table` passed as the ``selectable`` argument.
  128. The ``dialect_name`` option will limit the rendering of a particular
  129. hint to a particular backend. Such as, to add a hint
  130. that only takes effect for SQL Server::
  131. mytable.insert().with_hint("WITH (PAGLOCK)", dialect_name="mssql")
  132. .. versionadded:: 0.7.6
  133. :param text: Text of the hint.
  134. :param selectable: optional :class:`.Table` that specifies
  135. an element of the FROM clause within an UPDATE or DELETE
  136. to be the subject of the hint - applies only to certain backends.
  137. :param dialect_name: defaults to ``*``, if specified as the name
  138. of a particular dialect, will apply these hints only when
  139. that dialect is in use.
  140. """
  141. if selectable is None:
  142. selectable = self.table
  143. self._hints = self._hints.union(
  144. {(selectable, dialect_name): text})
  145. class ValuesBase(UpdateBase):
  146. """Supplies support for :meth:`.ValuesBase.values` to
  147. INSERT and UPDATE constructs."""
  148. __visit_name__ = 'values_base'
  149. _supports_multi_parameters = False
  150. _has_multi_parameters = False
  151. _preserve_parameter_order = False
  152. select = None
  153. _post_values_clause = None
  154. def __init__(self, table, values, prefixes):
  155. self.table = _interpret_as_from(table)
  156. self.parameters, self._has_multi_parameters = \
  157. self._process_colparams(values)
  158. if prefixes:
  159. self._setup_prefixes(prefixes)
  160. @_generative
  161. def values(self, *args, **kwargs):
  162. r"""specify a fixed VALUES clause for an INSERT statement, or the SET
  163. clause for an UPDATE.
  164. Note that the :class:`.Insert` and :class:`.Update` constructs support
  165. per-execution time formatting of the VALUES and/or SET clauses,
  166. based on the arguments passed to :meth:`.Connection.execute`.
  167. However, the :meth:`.ValuesBase.values` method can be used to "fix" a
  168. particular set of parameters into the statement.
  169. Multiple calls to :meth:`.ValuesBase.values` will produce a new
  170. construct, each one with the parameter list modified to include
  171. the new parameters sent. In the typical case of a single
  172. dictionary of parameters, the newly passed keys will replace
  173. the same keys in the previous construct. In the case of a list-based
  174. "multiple values" construct, each new list of values is extended
  175. onto the existing list of values.
  176. :param \**kwargs: key value pairs representing the string key
  177. of a :class:`.Column` mapped to the value to be rendered into the
  178. VALUES or SET clause::
  179. users.insert().values(name="some name")
  180. users.update().where(users.c.id==5).values(name="some name")
  181. :param \*args: As an alternative to passing key/value parameters,
  182. a dictionary, tuple, or list of dictionaries or tuples can be passed
  183. as a single positional argument in order to form the VALUES or
  184. SET clause of the statement. The forms that are accepted vary
  185. based on whether this is an :class:`.Insert` or an :class:`.Update`
  186. construct.
  187. For either an :class:`.Insert` or :class:`.Update` construct, a
  188. single dictionary can be passed, which works the same as that of
  189. the kwargs form::
  190. users.insert().values({"name": "some name"})
  191. users.update().values({"name": "some new name"})
  192. Also for either form but more typically for the :class:`.Insert`
  193. construct, a tuple that contains an entry for every column in the
  194. table is also accepted::
  195. users.insert().values((5, "some name"))
  196. The :class:`.Insert` construct also supports being passed a list
  197. of dictionaries or full-table-tuples, which on the server will
  198. render the less common SQL syntax of "multiple values" - this
  199. syntax is supported on backends such as SQLite, PostgreSQL, MySQL,
  200. but not necessarily others::
  201. users.insert().values([
  202. {"name": "some name"},
  203. {"name": "some other name"},
  204. {"name": "yet another name"},
  205. ])
  206. The above form would render a multiple VALUES statement similar to::
  207. INSERT INTO users (name) VALUES
  208. (:name_1),
  209. (:name_2),
  210. (:name_3)
  211. It is essential to note that **passing multiple values is
  212. NOT the same as using traditional executemany() form**. The above
  213. syntax is a **special** syntax not typically used. To emit an
  214. INSERT statement against multiple rows, the normal method is
  215. to pass a multiple values list to the :meth:`.Connection.execute`
  216. method, which is supported by all database backends and is generally
  217. more efficient for a very large number of parameters.
  218. .. seealso::
  219. :ref:`execute_multiple` - an introduction to
  220. the traditional Core method of multiple parameter set
  221. invocation for INSERTs and other statements.
  222. .. versionchanged:: 1.0.0 an INSERT that uses a multiple-VALUES
  223. clause, even a list of length one,
  224. implies that the :paramref:`.Insert.inline` flag is set to
  225. True, indicating that the statement will not attempt to fetch
  226. the "last inserted primary key" or other defaults. The
  227. statement deals with an arbitrary number of rows, so the
  228. :attr:`.ResultProxy.inserted_primary_key` accessor does not
  229. apply.
  230. .. versionchanged:: 1.0.0 A multiple-VALUES INSERT now supports
  231. columns with Python side default values and callables in the
  232. same way as that of an "executemany" style of invocation; the
  233. callable is invoked for each row. See :ref:`bug_3288`
  234. for other details.
  235. The :class:`.Update` construct supports a special form which is a
  236. list of 2-tuples, which when provided must be passed in conjunction
  237. with the
  238. :paramref:`~sqlalchemy.sql.expression.update.preserve_parameter_order`
  239. parameter.
  240. This form causes the UPDATE statement to render the SET clauses
  241. using the order of parameters given to :meth:`.Update.values`, rather
  242. than the ordering of columns given in the :class:`.Table`.
  243. .. versionadded:: 1.0.10 - added support for parameter-ordered
  244. UPDATE statements via the
  245. :paramref:`~sqlalchemy.sql.expression.update.preserve_parameter_order`
  246. flag.
  247. .. seealso::
  248. :ref:`updates_order_parameters` - full example of the
  249. :paramref:`~sqlalchemy.sql.expression.update.preserve_parameter_order`
  250. flag
  251. .. seealso::
  252. :ref:`inserts_and_updates` - SQL Expression
  253. Language Tutorial
  254. :func:`~.expression.insert` - produce an ``INSERT`` statement
  255. :func:`~.expression.update` - produce an ``UPDATE`` statement
  256. """
  257. if self.select is not None:
  258. raise exc.InvalidRequestError(
  259. "This construct already inserts from a SELECT")
  260. if self._has_multi_parameters and kwargs:
  261. raise exc.InvalidRequestError(
  262. "This construct already has multiple parameter sets.")
  263. if args:
  264. if len(args) > 1:
  265. raise exc.ArgumentError(
  266. "Only a single dictionary/tuple or list of "
  267. "dictionaries/tuples is accepted positionally.")
  268. v = args[0]
  269. else:
  270. v = {}
  271. if self.parameters is None:
  272. self.parameters, self._has_multi_parameters = \
  273. self._process_colparams(v)
  274. else:
  275. if self._has_multi_parameters:
  276. self.parameters = list(self.parameters)
  277. p, self._has_multi_parameters = self._process_colparams(v)
  278. if not self._has_multi_parameters:
  279. raise exc.ArgumentError(
  280. "Can't mix single-values and multiple values "
  281. "formats in one statement")
  282. self.parameters.extend(p)
  283. else:
  284. self.parameters = self.parameters.copy()
  285. p, self._has_multi_parameters = self._process_colparams(v)
  286. if self._has_multi_parameters:
  287. raise exc.ArgumentError(
  288. "Can't mix single-values and multiple values "
  289. "formats in one statement")
  290. self.parameters.update(p)
  291. if kwargs:
  292. if self._has_multi_parameters:
  293. raise exc.ArgumentError(
  294. "Can't pass kwargs and multiple parameter sets "
  295. "simultaneously")
  296. else:
  297. self.parameters.update(kwargs)
  298. @_generative
  299. def return_defaults(self, *cols):
  300. """Make use of a :term:`RETURNING` clause for the purpose
  301. of fetching server-side expressions and defaults.
  302. E.g.::
  303. stmt = table.insert().values(data='newdata').return_defaults()
  304. result = connection.execute(stmt)
  305. server_created_at = result.returned_defaults['created_at']
  306. When used against a backend that supports RETURNING, all column
  307. values generated by SQL expression or server-side-default will be
  308. added to any existing RETURNING clause, provided that
  309. :meth:`.UpdateBase.returning` is not used simultaneously. The column
  310. values will then be available on the result using the
  311. :attr:`.ResultProxy.returned_defaults` accessor as a dictionary,
  312. referring to values keyed to the :class:`.Column` object as well as
  313. its ``.key``.
  314. This method differs from :meth:`.UpdateBase.returning` in these ways:
  315. 1. :meth:`.ValuesBase.return_defaults` is only intended for use with
  316. an INSERT or an UPDATE statement that matches exactly one row.
  317. While the RETURNING construct in the general sense supports
  318. multiple rows for a multi-row UPDATE or DELETE statement, or for
  319. special cases of INSERT that return multiple rows (e.g. INSERT from
  320. SELECT, multi-valued VALUES clause),
  321. :meth:`.ValuesBase.return_defaults` is intended only for an
  322. "ORM-style" single-row INSERT/UPDATE statement. The row returned
  323. by the statement is also consumed implicitly when
  324. :meth:`.ValuesBase.return_defaults` is used. By contrast,
  325. :meth:`.UpdateBase.returning` leaves the RETURNING result-set
  326. intact with a collection of any number of rows.
  327. 2. It is compatible with the existing logic to fetch auto-generated
  328. primary key values, also known as "implicit returning". Backends
  329. that support RETURNING will automatically make use of RETURNING in
  330. order to fetch the value of newly generated primary keys; while the
  331. :meth:`.UpdateBase.returning` method circumvents this behavior,
  332. :meth:`.ValuesBase.return_defaults` leaves it intact.
  333. 3. It can be called against any backend. Backends that don't support
  334. RETURNING will skip the usage of the feature, rather than raising
  335. an exception. The return value of
  336. :attr:`.ResultProxy.returned_defaults` will be ``None``
  337. :meth:`.ValuesBase.return_defaults` is used by the ORM to provide
  338. an efficient implementation for the ``eager_defaults`` feature of
  339. :func:`.mapper`.
  340. :param cols: optional list of column key names or :class:`.Column`
  341. objects. If omitted, all column expressions evaluated on the server
  342. are added to the returning list.
  343. .. versionadded:: 0.9.0
  344. .. seealso::
  345. :meth:`.UpdateBase.returning`
  346. :attr:`.ResultProxy.returned_defaults`
  347. """
  348. self._return_defaults = cols or True
  349. class Insert(ValuesBase):
  350. """Represent an INSERT construct.
  351. The :class:`.Insert` object is created using the
  352. :func:`~.expression.insert()` function.
  353. .. seealso::
  354. :ref:`coretutorial_insert_expressions`
  355. """
  356. __visit_name__ = 'insert'
  357. _supports_multi_parameters = True
  358. def __init__(self,
  359. table,
  360. values=None,
  361. inline=False,
  362. bind=None,
  363. prefixes=None,
  364. returning=None,
  365. return_defaults=False,
  366. **dialect_kw):
  367. """Construct an :class:`.Insert` object.
  368. Similar functionality is available via the
  369. :meth:`~.TableClause.insert` method on
  370. :class:`~.schema.Table`.
  371. :param table: :class:`.TableClause` which is the subject of the
  372. insert.
  373. :param values: collection of values to be inserted; see
  374. :meth:`.Insert.values` for a description of allowed formats here.
  375. Can be omitted entirely; a :class:`.Insert` construct will also
  376. dynamically render the VALUES clause at execution time based on
  377. the parameters passed to :meth:`.Connection.execute`.
  378. :param inline: if True, no attempt will be made to retrieve the
  379. SQL-generated default values to be provided within the statement;
  380. in particular,
  381. this allows SQL expressions to be rendered 'inline' within the
  382. statement without the need to pre-execute them beforehand; for
  383. backends that support "returning", this turns off the "implicit
  384. returning" feature for the statement.
  385. If both `values` and compile-time bind parameters are present, the
  386. compile-time bind parameters override the information specified
  387. within `values` on a per-key basis.
  388. The keys within `values` can be either
  389. :class:`~sqlalchemy.schema.Column` objects or their string
  390. identifiers. Each key may reference one of:
  391. * a literal data value (i.e. string, number, etc.);
  392. * a Column object;
  393. * a SELECT statement.
  394. If a ``SELECT`` statement is specified which references this
  395. ``INSERT`` statement's table, the statement will be correlated
  396. against the ``INSERT`` statement.
  397. .. seealso::
  398. :ref:`coretutorial_insert_expressions` - SQL Expression Tutorial
  399. :ref:`inserts_and_updates` - SQL Expression Tutorial
  400. """
  401. ValuesBase.__init__(self, table, values, prefixes)
  402. self._bind = bind
  403. self.select = self.select_names = None
  404. self.include_insert_from_select_defaults = False
  405. self.inline = inline
  406. self._returning = returning
  407. self._validate_dialect_kwargs(dialect_kw)
  408. self._return_defaults = return_defaults
  409. def get_children(self, **kwargs):
  410. if self.select is not None:
  411. return self.select,
  412. else:
  413. return ()
  414. @_generative
  415. def from_select(self, names, select, include_defaults=True):
  416. """Return a new :class:`.Insert` construct which represents
  417. an ``INSERT...FROM SELECT`` statement.
  418. e.g.::
  419. sel = select([table1.c.a, table1.c.b]).where(table1.c.c > 5)
  420. ins = table2.insert().from_select(['a', 'b'], sel)
  421. :param names: a sequence of string column names or :class:`.Column`
  422. objects representing the target columns.
  423. :param select: a :func:`.select` construct, :class:`.FromClause`
  424. or other construct which resolves into a :class:`.FromClause`,
  425. such as an ORM :class:`.Query` object, etc. The order of
  426. columns returned from this FROM clause should correspond to the
  427. order of columns sent as the ``names`` parameter; while this
  428. is not checked before passing along to the database, the database
  429. would normally raise an exception if these column lists don't
  430. correspond.
  431. :param include_defaults: if True, non-server default values and
  432. SQL expressions as specified on :class:`.Column` objects
  433. (as documented in :ref:`metadata_defaults_toplevel`) not
  434. otherwise specified in the list of names will be rendered
  435. into the INSERT and SELECT statements, so that these values are also
  436. included in the data to be inserted.
  437. .. note:: A Python-side default that uses a Python callable function
  438. will only be invoked **once** for the whole statement, and **not
  439. per row**.
  440. .. versionadded:: 1.0.0 - :meth:`.Insert.from_select` now renders
  441. Python-side and SQL expression column defaults into the
  442. SELECT statement for columns otherwise not included in the
  443. list of column names.
  444. .. versionchanged:: 1.0.0 an INSERT that uses FROM SELECT
  445. implies that the :paramref:`.insert.inline` flag is set to
  446. True, indicating that the statement will not attempt to fetch
  447. the "last inserted primary key" or other defaults. The statement
  448. deals with an arbitrary number of rows, so the
  449. :attr:`.ResultProxy.inserted_primary_key` accessor does not apply.
  450. .. versionadded:: 0.8.3
  451. """
  452. if self.parameters:
  453. raise exc.InvalidRequestError(
  454. "This construct already inserts value expressions")
  455. self.parameters, self._has_multi_parameters = \
  456. self._process_colparams(
  457. dict((_column_as_key(n), Null()) for n in names))
  458. self.select_names = names
  459. self.inline = True
  460. self.include_insert_from_select_defaults = include_defaults
  461. self.select = _interpret_as_select(select)
  462. def _copy_internals(self, clone=_clone, **kw):
  463. # TODO: coverage
  464. self.parameters = self.parameters.copy()
  465. if self.select is not None:
  466. self.select = _clone(self.select)
  467. class Update(ValuesBase):
  468. """Represent an Update construct.
  469. The :class:`.Update` object is created using the :func:`update()`
  470. function.
  471. """
  472. __visit_name__ = 'update'
  473. def __init__(self,
  474. table,
  475. whereclause=None,
  476. values=None,
  477. inline=False,
  478. bind=None,
  479. prefixes=None,
  480. returning=None,
  481. return_defaults=False,
  482. preserve_parameter_order=False,
  483. **dialect_kw):
  484. r"""Construct an :class:`.Update` object.
  485. E.g.::
  486. from sqlalchemy import update
  487. stmt = update(users).where(users.c.id==5).\
  488. values(name='user #5')
  489. Similar functionality is available via the
  490. :meth:`~.TableClause.update` method on
  491. :class:`.Table`::
  492. stmt = users.update().\
  493. where(users.c.id==5).\
  494. values(name='user #5')
  495. :param table: A :class:`.Table` object representing the database
  496. table to be updated.
  497. :param whereclause: Optional SQL expression describing the ``WHERE``
  498. condition of the ``UPDATE`` statement. Modern applications
  499. may prefer to use the generative :meth:`~Update.where()`
  500. method to specify the ``WHERE`` clause.
  501. The WHERE clause can refer to multiple tables.
  502. For databases which support this, an ``UPDATE FROM`` clause will
  503. be generated, or on MySQL, a multi-table update. The statement
  504. will fail on databases that don't have support for multi-table
  505. update statements. A SQL-standard method of referring to
  506. additional tables in the WHERE clause is to use a correlated
  507. subquery::
  508. users.update().values(name='ed').where(
  509. users.c.name==select([addresses.c.email_address]).\
  510. where(addresses.c.user_id==users.c.id).\
  511. as_scalar()
  512. )
  513. .. versionchanged:: 0.7.4
  514. The WHERE clause can refer to multiple tables.
  515. :param values:
  516. Optional dictionary which specifies the ``SET`` conditions of the
  517. ``UPDATE``. If left as ``None``, the ``SET``
  518. conditions are determined from those parameters passed to the
  519. statement during the execution and/or compilation of the
  520. statement. When compiled standalone without any parameters,
  521. the ``SET`` clause generates for all columns.
  522. Modern applications may prefer to use the generative
  523. :meth:`.Update.values` method to set the values of the
  524. UPDATE statement.
  525. :param inline:
  526. if True, SQL defaults present on :class:`.Column` objects via
  527. the ``default`` keyword will be compiled 'inline' into the statement
  528. and not pre-executed. This means that their values will not
  529. be available in the dictionary returned from
  530. :meth:`.ResultProxy.last_updated_params`.
  531. :param preserve_parameter_order: if True, the update statement is
  532. expected to receive parameters **only** via the :meth:`.Update.values`
  533. method, and they must be passed as a Python ``list`` of 2-tuples.
  534. The rendered UPDATE statement will emit the SET clause for each
  535. referenced column maintaining this order.
  536. .. versionadded:: 1.0.10
  537. .. seealso::
  538. :ref:`updates_order_parameters` - full example of the
  539. :paramref:`~sqlalchemy.sql.expression.update.preserve_parameter_order` flag
  540. If both ``values`` and compile-time bind parameters are present, the
  541. compile-time bind parameters override the information specified
  542. within ``values`` on a per-key basis.
  543. The keys within ``values`` can be either :class:`.Column`
  544. objects or their string identifiers (specifically the "key" of the
  545. :class:`.Column`, normally but not necessarily equivalent to
  546. its "name"). Normally, the
  547. :class:`.Column` objects used here are expected to be
  548. part of the target :class:`.Table` that is the table
  549. to be updated. However when using MySQL, a multiple-table
  550. UPDATE statement can refer to columns from any of
  551. the tables referred to in the WHERE clause.
  552. The values referred to in ``values`` are typically:
  553. * a literal data value (i.e. string, number, etc.)
  554. * a SQL expression, such as a related :class:`.Column`,
  555. a scalar-returning :func:`.select` construct,
  556. etc.
  557. When combining :func:`.select` constructs within the values
  558. clause of an :func:`.update` construct,
  559. the subquery represented by the :func:`.select` should be
  560. *correlated* to the parent table, that is, providing criterion
  561. which links the table inside the subquery to the outer table
  562. being updated::
  563. users.update().values(
  564. name=select([addresses.c.email_address]).\
  565. where(addresses.c.user_id==users.c.id).\
  566. as_scalar()
  567. )
  568. .. seealso::
  569. :ref:`inserts_and_updates` - SQL Expression
  570. Language Tutorial
  571. """
  572. self._preserve_parameter_order = preserve_parameter_order
  573. ValuesBase.__init__(self, table, values, prefixes)
  574. self._bind = bind
  575. self._returning = returning
  576. if whereclause is not None:
  577. self._whereclause = _literal_as_text(whereclause)
  578. else:
  579. self._whereclause = None
  580. self.inline = inline
  581. self._validate_dialect_kwargs(dialect_kw)
  582. self._return_defaults = return_defaults
  583. def get_children(self, **kwargs):
  584. if self._whereclause is not None:
  585. return self._whereclause,
  586. else:
  587. return ()
  588. def _copy_internals(self, clone=_clone, **kw):
  589. # TODO: coverage
  590. self._whereclause = clone(self._whereclause, **kw)
  591. self.parameters = self.parameters.copy()
  592. @_generative
  593. def where(self, whereclause):
  594. """return a new update() construct with the given expression added to
  595. its WHERE clause, joined to the existing clause via AND, if any.
  596. """
  597. if self._whereclause is not None:
  598. self._whereclause = and_(self._whereclause,
  599. _literal_as_text(whereclause))
  600. else:
  601. self._whereclause = _literal_as_text(whereclause)
  602. @property
  603. def _extra_froms(self):
  604. # TODO: this could be made memoized
  605. # if the memoization is reset on each generative call.
  606. froms = []
  607. seen = set([self.table])
  608. if self._whereclause is not None:
  609. for item in _from_objects(self._whereclause):
  610. if not seen.intersection(item._cloned_set):
  611. froms.append(item)
  612. seen.update(item._cloned_set)
  613. return froms
  614. class Delete(UpdateBase):
  615. """Represent a DELETE construct.
  616. The :class:`.Delete` object is created using the :func:`delete()`
  617. function.
  618. """
  619. __visit_name__ = 'delete'
  620. def __init__(self,
  621. table,
  622. whereclause=None,
  623. bind=None,
  624. returning=None,
  625. prefixes=None,
  626. **dialect_kw):
  627. """Construct :class:`.Delete` object.
  628. Similar functionality is available via the
  629. :meth:`~.TableClause.delete` method on
  630. :class:`~.schema.Table`.
  631. :param table: The table to delete rows from.
  632. :param whereclause: A :class:`.ClauseElement` describing the ``WHERE``
  633. condition of the ``DELETE`` statement. Note that the
  634. :meth:`~Delete.where()` generative method may be used instead.
  635. .. seealso::
  636. :ref:`deletes` - SQL Expression Tutorial
  637. """
  638. self._bind = bind
  639. self.table = _interpret_as_from(table)
  640. self._returning = returning
  641. if prefixes:
  642. self._setup_prefixes(prefixes)
  643. if whereclause is not None:
  644. self._whereclause = _literal_as_text(whereclause)
  645. else:
  646. self._whereclause = None
  647. self._validate_dialect_kwargs(dialect_kw)
  648. def get_children(self, **kwargs):
  649. if self._whereclause is not None:
  650. return self._whereclause,
  651. else:
  652. return ()
  653. @_generative
  654. def where(self, whereclause):
  655. """Add the given WHERE clause to a newly returned delete construct."""
  656. if self._whereclause is not None:
  657. self._whereclause = and_(self._whereclause,
  658. _literal_as_text(whereclause))
  659. else:
  660. self._whereclause = _literal_as_text(whereclause)
  661. def _copy_internals(self, clone=_clone, **kw):
  662. # TODO: coverage
  663. self._whereclause = clone(self._whereclause, **kw)