dml.py 53 KB

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