Coverage for /home/martinb/.local/share/virtualenvs/camcops/lib/python3.6/site-packages/sqlalchemy/sql/dml.py : 52%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# sql/dml.py
2# Copyright (C) 2009-2020 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"""
8Provide :class:`_expression.Insert`, :class:`_expression.Update` and
9:class:`_expression.Delete`.
11"""
13from .base import _from_objects
14from .base import _generative
15from .base import DialectKWArgs
16from .base import Executable
17from .elements import _clone
18from .elements import _column_as_key
19from .elements import _literal_as_text
20from .elements import and_
21from .elements import ClauseElement
22from .elements import Null
23from .selectable import _interpret_as_from
24from .selectable import _interpret_as_select
25from .selectable import HasCTE
26from .selectable import HasPrefixes
27from .. import exc
28from .. import util
31class UpdateBase(
32 HasCTE, DialectKWArgs, HasPrefixes, Executable, ClauseElement
33):
34 """Form the base for ``INSERT``, ``UPDATE``, and ``DELETE`` statements.
36 """
38 __visit_name__ = "update_base"
40 _execution_options = Executable._execution_options.union(
41 {"autocommit": True}
42 )
43 _hints = util.immutabledict()
44 _parameter_ordering = None
45 _prefixes = ()
46 named_with_column = False
48 def _process_colparams(self, parameters):
49 def process_single(p):
50 if isinstance(p, (list, tuple)):
51 return dict((c.key, pval) for c, pval in zip(self.table.c, p))
52 else:
53 return p
55 if self._preserve_parameter_order and parameters is not None:
56 if not isinstance(parameters, list) or (
57 parameters and not isinstance(parameters[0], tuple)
58 ):
59 raise ValueError(
60 "When preserve_parameter_order is True, "
61 "values() only accepts a list of 2-tuples"
62 )
63 self._parameter_ordering = [key for key, value in parameters]
65 return dict(parameters), False
67 if (
68 isinstance(parameters, (list, tuple))
69 and parameters
70 and isinstance(parameters[0], (list, tuple, dict))
71 ):
73 if not self._supports_multi_parameters:
74 raise exc.InvalidRequestError(
75 "This construct does not support "
76 "multiple parameter sets."
77 )
79 return [process_single(p) for p in parameters], True
80 else:
81 return process_single(parameters), False
83 def params(self, *arg, **kw):
84 """Set the parameters for the statement.
86 This method raises ``NotImplementedError`` on the base class,
87 and is overridden by :class:`.ValuesBase` to provide the
88 SET/VALUES clause of UPDATE and INSERT.
90 """
91 raise NotImplementedError(
92 "params() is not supported for INSERT/UPDATE/DELETE statements."
93 " To set the values for an INSERT or UPDATE statement, use"
94 " stmt.values(**parameters)."
95 )
97 def bind(self):
98 """Return a 'bind' linked to this :class:`.UpdateBase`
99 or a :class:`_schema.Table` associated with it.
101 """
102 return self._bind or self.table.bind
104 def _set_bind(self, bind):
105 self._bind = bind
107 bind = property(bind, _set_bind)
109 @_generative
110 def returning(self, *cols):
111 r"""Add a :term:`RETURNING` or equivalent clause to this statement.
113 e.g.::
115 stmt = table.update().\
116 where(table.c.data == 'value').\
117 values(status='X').\
118 returning(table.c.server_flag,
119 table.c.updated_timestamp)
121 for server_flag, updated_timestamp in connection.execute(stmt):
122 print(server_flag, updated_timestamp)
124 The given collection of column expressions should be derived from
125 the table that is
126 the target of the INSERT, UPDATE, or DELETE. While
127 :class:`_schema.Column`
128 objects are typical, the elements can also be expressions::
130 stmt = table.insert().returning(
131 (table.c.first_name + " " + table.c.last_name).
132 label('fullname'))
134 Upon compilation, a RETURNING clause, or database equivalent,
135 will be rendered within the statement. For INSERT and UPDATE,
136 the values are the newly inserted/updated values. For DELETE,
137 the values are those of the rows which were deleted.
139 Upon execution, the values of the columns to be returned are made
140 available via the result set and can be iterated using
141 :meth:`_engine.ResultProxy.fetchone` and similar.
142 For DBAPIs which do not
143 natively support returning values (i.e. cx_oracle), SQLAlchemy will
144 approximate this behavior at the result level so that a reasonable
145 amount of behavioral neutrality is provided.
147 Note that not all databases/DBAPIs
148 support RETURNING. For those backends with no support,
149 an exception is raised upon compilation and/or execution.
150 For those who do support it, the functionality across backends
151 varies greatly, including restrictions on executemany()
152 and other statements which return multiple rows. Please
153 read the documentation notes for the database in use in
154 order to determine the availability of RETURNING.
156 .. seealso::
158 :meth:`.ValuesBase.return_defaults` - an alternative method tailored
159 towards efficient fetching of server-side defaults and triggers
160 for single-row INSERTs or UPDATEs.
163 """
164 self._returning = cols
166 @_generative
167 def with_hint(self, text, selectable=None, dialect_name="*"):
168 """Add a table hint for a single table to this
169 INSERT/UPDATE/DELETE statement.
171 .. note::
173 :meth:`.UpdateBase.with_hint` currently applies only to
174 Microsoft SQL Server. For MySQL INSERT/UPDATE/DELETE hints, use
175 :meth:`.UpdateBase.prefix_with`.
177 The text of the hint is rendered in the appropriate
178 location for the database backend in use, relative
179 to the :class:`_schema.Table` that is the subject of this
180 statement, or optionally to that of the given
181 :class:`_schema.Table` passed as the ``selectable`` argument.
183 The ``dialect_name`` option will limit the rendering of a particular
184 hint to a particular backend. Such as, to add a hint
185 that only takes effect for SQL Server::
187 mytable.insert().with_hint("WITH (PAGLOCK)", dialect_name="mssql")
189 :param text: Text of the hint.
190 :param selectable: optional :class:`_schema.Table` that specifies
191 an element of the FROM clause within an UPDATE or DELETE
192 to be the subject of the hint - applies only to certain backends.
193 :param dialect_name: defaults to ``*``, if specified as the name
194 of a particular dialect, will apply these hints only when
195 that dialect is in use.
196 """
197 if selectable is None:
198 selectable = self.table
200 self._hints = self._hints.union({(selectable, dialect_name): text})
203class ValuesBase(UpdateBase):
204 """Supplies support for :meth:`.ValuesBase.values` to
205 INSERT and UPDATE constructs."""
207 __visit_name__ = "values_base"
209 _supports_multi_parameters = False
210 _has_multi_parameters = False
211 _preserve_parameter_order = False
212 select = None
213 _post_values_clause = None
215 def __init__(self, table, values, prefixes):
216 self.table = _interpret_as_from(table)
217 self.parameters, self._has_multi_parameters = self._process_colparams(
218 values
219 )
220 if prefixes:
221 self._setup_prefixes(prefixes)
223 @_generative
224 def values(self, *args, **kwargs):
225 r"""specify a fixed VALUES clause for an INSERT statement, or the SET
226 clause for an UPDATE.
228 Note that the :class:`_expression.Insert` and
229 :class:`_expression.Update` constructs support
230 per-execution time formatting of the VALUES and/or SET clauses,
231 based on the arguments passed to :meth:`_engine.Connection.execute`.
232 However, the :meth:`.ValuesBase.values` method can be used to "fix" a
233 particular set of parameters into the statement.
235 Multiple calls to :meth:`.ValuesBase.values` will produce a new
236 construct, each one with the parameter list modified to include
237 the new parameters sent. In the typical case of a single
238 dictionary of parameters, the newly passed keys will replace
239 the same keys in the previous construct. In the case of a list-based
240 "multiple values" construct, each new list of values is extended
241 onto the existing list of values.
243 :param \**kwargs: key value pairs representing the string key
244 of a :class:`_schema.Column`
245 mapped to the value to be rendered into the
246 VALUES or SET clause::
248 users.insert().values(name="some name")
250 users.update().where(users.c.id==5).values(name="some name")
252 :param \*args: As an alternative to passing key/value parameters,
253 a dictionary, tuple, or list of dictionaries or tuples can be passed
254 as a single positional argument in order to form the VALUES or
255 SET clause of the statement. The forms that are accepted vary
256 based on whether this is an :class:`_expression.Insert` or an
257 :class:`_expression.Update`
258 construct.
260 For either an :class:`_expression.Insert` or
261 :class:`_expression.Update` construct, a
262 single dictionary can be passed, which works the same as that of
263 the kwargs form::
265 users.insert().values({"name": "some name"})
267 users.update().values({"name": "some new name"})
269 Also for either form but more typically for the
270 :class:`_expression.Insert`
271 construct, a tuple that contains an entry for every column in the
272 table is also accepted::
274 users.insert().values((5, "some name"))
276 The :class:`_expression.Insert`
277 construct also supports being passed a list
278 of dictionaries or full-table-tuples, which on the server will
279 render the less common SQL syntax of "multiple values" - this
280 syntax is supported on backends such as SQLite, PostgreSQL, MySQL,
281 but not necessarily others::
283 users.insert().values([
284 {"name": "some name"},
285 {"name": "some other name"},
286 {"name": "yet another name"},
287 ])
289 The above form would render a multiple VALUES statement similar to::
291 INSERT INTO users (name) VALUES
292 (:name_1),
293 (:name_2),
294 (:name_3)
296 It is essential to note that **passing multiple values is
297 NOT the same as using traditional executemany() form**. The above
298 syntax is a **special** syntax not typically used. To emit an
299 INSERT statement against multiple rows, the normal method is
300 to pass a multiple values list to the
301 :meth:`_engine.Connection.execute`
302 method, which is supported by all database backends and is generally
303 more efficient for a very large number of parameters.
305 .. seealso::
307 :ref:`execute_multiple` - an introduction to
308 the traditional Core method of multiple parameter set
309 invocation for INSERTs and other statements.
311 .. versionchanged:: 1.0.0 an INSERT that uses a multiple-VALUES
312 clause, even a list of length one,
313 implies that the :paramref:`_expression.Insert.inline`
314 flag is set to
315 True, indicating that the statement will not attempt to fetch
316 the "last inserted primary key" or other defaults. The
317 statement deals with an arbitrary number of rows, so the
318 :attr:`_engine.ResultProxy.inserted_primary_key`
319 accessor does not
320 apply.
322 .. versionchanged:: 1.0.0 A multiple-VALUES INSERT now supports
323 columns with Python side default values and callables in the
324 same way as that of an "executemany" style of invocation; the
325 callable is invoked for each row. See :ref:`bug_3288`
326 for other details.
328 The :class:`_expression.Update`
329 construct supports a special form which is a
330 list of 2-tuples, which when provided must be passed in conjunction
331 with the
332 :paramref:`~sqlalchemy.sql.expression.update.preserve_parameter_order`
333 parameter.
334 This form causes the UPDATE statement to render the SET clauses
335 using the order of parameters given to
336 :meth:`_expression.Update.values`, rather
337 than the ordering of columns given in the :class:`_schema.Table`.
339 .. versionadded:: 1.0.10 - added support for parameter-ordered
340 UPDATE statements via the
341 :paramref:`~sqlalchemy.sql.expression.update.preserve_parameter_order`
342 flag.
344 .. seealso::
346 :ref:`updates_order_parameters` - full example of the
347 :paramref:`~sqlalchemy.sql.expression.update.preserve_parameter_order`
348 flag
350 .. seealso::
352 :ref:`inserts_and_updates` - SQL Expression
353 Language Tutorial
355 :func:`_expression.insert` - produce an ``INSERT`` statement
357 :func:`_expression.update` - produce an ``UPDATE`` statement
359 """
360 if self.select is not None:
361 raise exc.InvalidRequestError(
362 "This construct already inserts from a SELECT"
363 )
364 if self._has_multi_parameters and kwargs:
365 raise exc.InvalidRequestError(
366 "This construct already has multiple parameter sets."
367 )
369 if args:
370 if len(args) > 1:
371 raise exc.ArgumentError(
372 "Only a single dictionary/tuple or list of "
373 "dictionaries/tuples is accepted positionally."
374 )
375 v = args[0]
376 else:
377 v = {}
379 if self.parameters is None:
380 (
381 self.parameters,
382 self._has_multi_parameters,
383 ) = self._process_colparams(v)
384 else:
385 if self._has_multi_parameters:
386 self.parameters = list(self.parameters)
387 p, self._has_multi_parameters = self._process_colparams(v)
388 if not self._has_multi_parameters:
389 raise exc.ArgumentError(
390 "Can't mix single-values and multiple values "
391 "formats in one statement"
392 )
394 self.parameters.extend(p)
395 else:
396 self.parameters = self.parameters.copy()
397 p, self._has_multi_parameters = self._process_colparams(v)
398 if self._has_multi_parameters:
399 raise exc.ArgumentError(
400 "Can't mix single-values and multiple values "
401 "formats in one statement"
402 )
403 self.parameters.update(p)
405 if kwargs:
406 if self._has_multi_parameters:
407 raise exc.ArgumentError(
408 "Can't pass kwargs and multiple parameter sets "
409 "simultaneously"
410 )
411 else:
412 self.parameters.update(kwargs)
414 @_generative
415 def return_defaults(self, *cols):
416 """Make use of a :term:`RETURNING` clause for the purpose
417 of fetching server-side expressions and defaults.
419 E.g.::
421 stmt = table.insert().values(data='newdata').return_defaults()
423 result = connection.execute(stmt)
425 server_created_at = result.returned_defaults['created_at']
427 When used against a backend that supports RETURNING, all column
428 values generated by SQL expression or server-side-default will be
429 added to any existing RETURNING clause, provided that
430 :meth:`.UpdateBase.returning` is not used simultaneously. The column
431 values will then be available on the result using the
432 :attr:`_engine.ResultProxy.returned_defaults` accessor as a dictionary
433 ,
434 referring to values keyed to the :class:`_schema.Column`
435 object as well as
436 its ``.key``.
438 This method differs from :meth:`.UpdateBase.returning` in these ways:
440 1. :meth:`.ValuesBase.return_defaults` is only intended for use with
441 an INSERT or an UPDATE statement that matches exactly one row.
442 While the RETURNING construct in the general sense supports
443 multiple rows for a multi-row UPDATE or DELETE statement, or for
444 special cases of INSERT that return multiple rows (e.g. INSERT from
445 SELECT, multi-valued VALUES clause),
446 :meth:`.ValuesBase.return_defaults` is intended only for an
447 "ORM-style" single-row INSERT/UPDATE statement. The row returned
448 by the statement is also consumed implicitly when
449 :meth:`.ValuesBase.return_defaults` is used. By contrast,
450 :meth:`.UpdateBase.returning` leaves the RETURNING result-set
451 intact with a collection of any number of rows.
453 2. It is compatible with the existing logic to fetch auto-generated
454 primary key values, also known as "implicit returning". Backends
455 that support RETURNING will automatically make use of RETURNING in
456 order to fetch the value of newly generated primary keys; while the
457 :meth:`.UpdateBase.returning` method circumvents this behavior,
458 :meth:`.ValuesBase.return_defaults` leaves it intact.
460 3. It can be called against any backend. Backends that don't support
461 RETURNING will skip the usage of the feature, rather than raising
462 an exception. The return value of
463 :attr:`_engine.ResultProxy.returned_defaults` will be ``None``
465 :meth:`.ValuesBase.return_defaults` is used by the ORM to provide
466 an efficient implementation for the ``eager_defaults`` feature of
467 :func:`.mapper`.
469 :param cols: optional list of column key names or
470 :class:`_schema.Column`
471 objects. If omitted, all column expressions evaluated on the server
472 are added to the returning list.
474 .. versionadded:: 0.9.0
476 .. seealso::
478 :meth:`.UpdateBase.returning`
480 :attr:`_engine.ResultProxy.returned_defaults`
482 """
483 self._return_defaults = cols or True
486class Insert(ValuesBase):
487 """Represent an INSERT construct.
489 The :class:`_expression.Insert` object is created using the
490 :func:`_expression.insert()` function.
492 .. seealso::
494 :ref:`coretutorial_insert_expressions`
496 """
498 __visit_name__ = "insert"
500 _supports_multi_parameters = True
502 def __init__(
503 self,
504 table,
505 values=None,
506 inline=False,
507 bind=None,
508 prefixes=None,
509 returning=None,
510 return_defaults=False,
511 **dialect_kw
512 ):
513 """Construct an :class:`_expression.Insert` object.
515 Similar functionality is available via the
516 :meth:`_expression.TableClause.insert` method on
517 :class:`_schema.Table`.
519 :param table: :class:`_expression.TableClause`
520 which is the subject of the
521 insert.
523 :param values: collection of values to be inserted; see
524 :meth:`_expression.Insert.values`
525 for a description of allowed formats here.
526 Can be omitted entirely; a :class:`_expression.Insert`
527 construct will also
528 dynamically render the VALUES clause at execution time based on
529 the parameters passed to :meth:`_engine.Connection.execute`.
531 :param inline: if True, no attempt will be made to retrieve the
532 SQL-generated default values to be provided within the statement;
533 in particular,
534 this allows SQL expressions to be rendered 'inline' within the
535 statement without the need to pre-execute them beforehand; for
536 backends that support "returning", this turns off the "implicit
537 returning" feature for the statement.
539 If both `values` and compile-time bind parameters are present, the
540 compile-time bind parameters override the information specified
541 within `values` on a per-key basis.
543 The keys within `values` can be either
544 :class:`~sqlalchemy.schema.Column` objects or their string
545 identifiers. Each key may reference one of:
547 * a literal data value (i.e. string, number, etc.);
548 * a Column object;
549 * a SELECT statement.
551 If a ``SELECT`` statement is specified which references this
552 ``INSERT`` statement's table, the statement will be correlated
553 against the ``INSERT`` statement.
555 .. seealso::
557 :ref:`coretutorial_insert_expressions` - SQL Expression Tutorial
559 :ref:`inserts_and_updates` - SQL Expression Tutorial
561 """
562 ValuesBase.__init__(self, table, values, prefixes)
563 self._bind = bind
564 self.select = self.select_names = None
565 self.include_insert_from_select_defaults = False
566 self.inline = inline
567 self._returning = returning
568 self._validate_dialect_kwargs(dialect_kw)
569 self._return_defaults = return_defaults
571 def get_children(self, **kwargs):
572 if self.select is not None:
573 return (self.select,)
574 else:
575 return ()
577 @_generative
578 def from_select(self, names, select, include_defaults=True):
579 """Return a new :class:`_expression.Insert` construct which represents
580 an ``INSERT...FROM SELECT`` statement.
582 e.g.::
584 sel = select([table1.c.a, table1.c.b]).where(table1.c.c > 5)
585 ins = table2.insert().from_select(['a', 'b'], sel)
587 :param names: a sequence of string column names or
588 :class:`_schema.Column`
589 objects representing the target columns.
590 :param select: a :func:`_expression.select` construct,
591 :class:`_expression.FromClause`
592 or other construct which resolves into a
593 :class:`_expression.FromClause`,
594 such as an ORM :class:`_query.Query` object, etc. The order of
595 columns returned from this FROM clause should correspond to the
596 order of columns sent as the ``names`` parameter; while this
597 is not checked before passing along to the database, the database
598 would normally raise an exception if these column lists don't
599 correspond.
600 :param include_defaults: if True, non-server default values and
601 SQL expressions as specified on :class:`_schema.Column` objects
602 (as documented in :ref:`metadata_defaults_toplevel`) not
603 otherwise specified in the list of names will be rendered
604 into the INSERT and SELECT statements, so that these values are also
605 included in the data to be inserted.
607 .. note:: A Python-side default that uses a Python callable function
608 will only be invoked **once** for the whole statement, and **not
609 per row**.
611 .. versionadded:: 1.0.0 - :meth:`_expression.Insert.from_select`
612 now renders
613 Python-side and SQL expression column defaults into the
614 SELECT statement for columns otherwise not included in the
615 list of column names.
617 .. versionchanged:: 1.0.0 an INSERT that uses FROM SELECT
618 implies that the :paramref:`_expression.insert.inline`
619 flag is set to
620 True, indicating that the statement will not attempt to fetch
621 the "last inserted primary key" or other defaults. The statement
622 deals with an arbitrary number of rows, so the
623 :attr:`_engine.ResultProxy.inserted_primary_key`
624 accessor does not apply.
626 """
627 if self.parameters:
628 raise exc.InvalidRequestError(
629 "This construct already inserts value expressions"
630 )
632 self.parameters, self._has_multi_parameters = self._process_colparams(
633 {_column_as_key(n): Null() for n in names}
634 )
636 self.select_names = names
637 self.inline = True
638 self.include_insert_from_select_defaults = include_defaults
639 self.select = _interpret_as_select(select)
641 def _copy_internals(self, clone=_clone, **kw):
642 # TODO: coverage
643 self.parameters = self.parameters.copy()
644 if self.select is not None:
645 self.select = _clone(self.select)
648class Update(ValuesBase):
649 """Represent an Update construct.
651 The :class:`_expression.Update`
652 object is created using the :func:`update()`
653 function.
655 """
657 __visit_name__ = "update"
659 def __init__(
660 self,
661 table,
662 whereclause=None,
663 values=None,
664 inline=False,
665 bind=None,
666 prefixes=None,
667 returning=None,
668 return_defaults=False,
669 preserve_parameter_order=False,
670 **dialect_kw
671 ):
672 r"""Construct an :class:`_expression.Update` object.
674 E.g.::
676 from sqlalchemy import update
678 stmt = update(users).where(users.c.id==5).\
679 values(name='user #5')
681 Similar functionality is available via the
682 :meth:`_expression.TableClause.update` method on
683 :class:`_schema.Table`::
685 stmt = users.update().\
686 where(users.c.id==5).\
687 values(name='user #5')
689 :param table: A :class:`_schema.Table`
690 object representing the database
691 table to be updated.
693 :param whereclause: Optional SQL expression describing the ``WHERE``
694 condition of the ``UPDATE`` statement. Modern applications
695 may prefer to use the generative :meth:`~Update.where()`
696 method to specify the ``WHERE`` clause.
698 The WHERE clause can refer to multiple tables.
699 For databases which support this, an ``UPDATE FROM`` clause will
700 be generated, or on MySQL, a multi-table update. The statement
701 will fail on databases that don't have support for multi-table
702 update statements. A SQL-standard method of referring to
703 additional tables in the WHERE clause is to use a correlated
704 subquery::
706 users.update().values(name='ed').where(
707 users.c.name==select([addresses.c.email_address]).\
708 where(addresses.c.user_id==users.c.id).\
709 as_scalar()
710 )
712 :param values:
713 Optional dictionary which specifies the ``SET`` conditions of the
714 ``UPDATE``. If left as ``None``, the ``SET``
715 conditions are determined from those parameters passed to the
716 statement during the execution and/or compilation of the
717 statement. When compiled standalone without any parameters,
718 the ``SET`` clause generates for all columns.
720 Modern applications may prefer to use the generative
721 :meth:`_expression.Update.values` method to set the values of the
722 UPDATE statement.
724 :param inline:
725 if True, SQL defaults present on :class:`_schema.Column` objects via
726 the ``default`` keyword will be compiled 'inline' into the statement
727 and not pre-executed. This means that their values will not
728 be available in the dictionary returned from
729 :meth:`_engine.ResultProxy.last_updated_params`.
731 :param preserve_parameter_order: if True, the update statement is
732 expected to receive parameters **only** via the
733 :meth:`_expression.Update.values` method,
734 and they must be passed as a Python
735 ``list`` of 2-tuples. The rendered UPDATE statement will emit the SET
736 clause for each referenced column maintaining this order.
738 .. versionadded:: 1.0.10
740 .. seealso::
742 :ref:`updates_order_parameters` - full example of the
743 :paramref:`_expression.update.preserve_parameter_order` flag
745 If both ``values`` and compile-time bind parameters are present, the
746 compile-time bind parameters override the information specified
747 within ``values`` on a per-key basis.
749 The keys within ``values`` can be either :class:`_schema.Column`
750 objects or their string identifiers (specifically the "key" of the
751 :class:`_schema.Column`, normally but not necessarily equivalent to
752 its "name"). Normally, the
753 :class:`_schema.Column` objects used here are expected to be
754 part of the target :class:`_schema.Table` that is the table
755 to be updated. However when using MySQL, a multiple-table
756 UPDATE statement can refer to columns from any of
757 the tables referred to in the WHERE clause.
759 The values referred to in ``values`` are typically:
761 * a literal data value (i.e. string, number, etc.)
762 * a SQL expression, such as a related :class:`_schema.Column`,
763 a scalar-returning :func:`_expression.select` construct,
764 etc.
766 When combining :func:`_expression.select` constructs within the values
767 clause of an :func:`_expression.update` construct,
768 the subquery represented by the :func:`_expression.select` should be
769 *correlated* to the parent table, that is, providing criterion
770 which links the table inside the subquery to the outer table
771 being updated::
773 users.update().values(
774 name=select([addresses.c.email_address]).\
775 where(addresses.c.user_id==users.c.id).\
776 as_scalar()
777 )
779 .. seealso::
781 :ref:`inserts_and_updates` - SQL Expression
782 Language Tutorial
785 """
786 self._preserve_parameter_order = preserve_parameter_order
787 ValuesBase.__init__(self, table, values, prefixes)
788 self._bind = bind
789 self._returning = returning
790 if whereclause is not None:
791 self._whereclause = _literal_as_text(whereclause)
792 else:
793 self._whereclause = None
794 self.inline = inline
795 self._validate_dialect_kwargs(dialect_kw)
796 self._return_defaults = return_defaults
798 def get_children(self, **kwargs):
799 if self._whereclause is not None:
800 return (self._whereclause,)
801 else:
802 return ()
804 def _copy_internals(self, clone=_clone, **kw):
805 # TODO: coverage
806 self._whereclause = clone(self._whereclause, **kw)
807 self.parameters = self.parameters.copy()
809 @_generative
810 def where(self, whereclause):
811 """return a new update() construct with the given expression added to
812 its WHERE clause, joined to the existing clause via AND, if any.
814 """
815 if self._whereclause is not None:
816 self._whereclause = and_(
817 self._whereclause, _literal_as_text(whereclause)
818 )
819 else:
820 self._whereclause = _literal_as_text(whereclause)
822 @property
823 def _extra_froms(self):
824 froms = []
825 seen = {self.table}
827 if self._whereclause is not None:
828 for item in _from_objects(self._whereclause):
829 if not seen.intersection(item._cloned_set):
830 froms.append(item)
831 seen.update(item._cloned_set)
833 return froms
836class Delete(UpdateBase):
837 """Represent a DELETE construct.
839 The :class:`_expression.Delete`
840 object is created using the :func:`delete()`
841 function.
843 """
845 __visit_name__ = "delete"
847 def __init__(
848 self,
849 table,
850 whereclause=None,
851 bind=None,
852 returning=None,
853 prefixes=None,
854 **dialect_kw
855 ):
856 r"""Construct :class:`_expression.Delete` object.
858 Similar functionality is available via the
859 :meth:`_expression.TableClause.delete` method on
860 :class:`_schema.Table`.
862 :param table: The table to delete rows from.
864 :param whereclause: A :class:`_expression.ClauseElement`
865 describing the ``WHERE``
866 condition of the ``DELETE`` statement. Note that the
867 :meth:`~Delete.where()` generative method may be used instead.
869 The WHERE clause can refer to multiple tables.
870 For databases which support this, a ``DELETE..USING`` or similar
871 clause will be generated. The statement
872 will fail on databases that don't have support for multi-table
873 delete statements. A SQL-standard method of referring to
874 additional tables in the WHERE clause is to use a correlated
875 subquery::
877 users.delete().where(
878 users.c.name==select([addresses.c.email_address]).\
879 where(addresses.c.user_id==users.c.id).\
880 as_scalar()
881 )
883 .. versionchanged:: 1.2.0
884 The WHERE clause of DELETE can refer to multiple tables.
886 .. seealso::
888 :ref:`deletes` - SQL Expression Tutorial
890 """
891 self._bind = bind
892 self.table = _interpret_as_from(table)
893 self._returning = returning
895 if prefixes:
896 self._setup_prefixes(prefixes)
898 if whereclause is not None:
899 self._whereclause = _literal_as_text(whereclause)
900 else:
901 self._whereclause = None
903 self._validate_dialect_kwargs(dialect_kw)
905 def get_children(self, **kwargs):
906 if self._whereclause is not None:
907 return (self._whereclause,)
908 else:
909 return ()
911 @_generative
912 def where(self, whereclause):
913 """Add the given WHERE clause to a newly returned delete construct."""
915 if self._whereclause is not None:
916 self._whereclause = and_(
917 self._whereclause, _literal_as_text(whereclause)
918 )
919 else:
920 self._whereclause = _literal_as_text(whereclause)
922 @property
923 def _extra_froms(self):
924 froms = []
925 seen = {self.table}
927 if self._whereclause is not None:
928 for item in _from_objects(self._whereclause):
929 if not seen.intersection(item._cloned_set):
930 froms.append(item)
931 seen.update(item._cloned_set)
933 return froms
935 def _copy_internals(self, clone=_clone, **kw):
936 # TODO: coverage
937 self._whereclause = clone(self._whereclause, **kw)