dml.py 52 KB

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