SQLAlchemy 2.0.36__cp313-cp313-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (273) hide show
  1. SQLAlchemy-2.0.36.dist-info/LICENSE +19 -0
  2. SQLAlchemy-2.0.36.dist-info/METADATA +243 -0
  3. SQLAlchemy-2.0.36.dist-info/RECORD +273 -0
  4. SQLAlchemy-2.0.36.dist-info/WHEEL +5 -0
  5. SQLAlchemy-2.0.36.dist-info/top_level.txt +1 -0
  6. sqlalchemy/__init__.py +294 -0
  7. sqlalchemy/connectors/__init__.py +18 -0
  8. sqlalchemy/connectors/aioodbc.py +174 -0
  9. sqlalchemy/connectors/asyncio.py +213 -0
  10. sqlalchemy/connectors/pyodbc.py +249 -0
  11. sqlalchemy/cyextension/__init__.py +6 -0
  12. sqlalchemy/cyextension/collections.cp313-win_amd64.pyd +0 -0
  13. sqlalchemy/cyextension/collections.pyx +409 -0
  14. sqlalchemy/cyextension/immutabledict.cp313-win_amd64.pyd +0 -0
  15. sqlalchemy/cyextension/immutabledict.pxd +8 -0
  16. sqlalchemy/cyextension/immutabledict.pyx +133 -0
  17. sqlalchemy/cyextension/processors.cp313-win_amd64.pyd +0 -0
  18. sqlalchemy/cyextension/processors.pyx +68 -0
  19. sqlalchemy/cyextension/resultproxy.cp313-win_amd64.pyd +0 -0
  20. sqlalchemy/cyextension/resultproxy.pyx +102 -0
  21. sqlalchemy/cyextension/util.cp313-win_amd64.pyd +0 -0
  22. sqlalchemy/cyextension/util.pyx +91 -0
  23. sqlalchemy/dialects/__init__.py +61 -0
  24. sqlalchemy/dialects/_typing.py +25 -0
  25. sqlalchemy/dialects/mssql/__init__.py +88 -0
  26. sqlalchemy/dialects/mssql/aioodbc.py +64 -0
  27. sqlalchemy/dialects/mssql/base.py +4010 -0
  28. sqlalchemy/dialects/mssql/information_schema.py +254 -0
  29. sqlalchemy/dialects/mssql/json.py +133 -0
  30. sqlalchemy/dialects/mssql/provision.py +162 -0
  31. sqlalchemy/dialects/mssql/pymssql.py +126 -0
  32. sqlalchemy/dialects/mssql/pyodbc.py +745 -0
  33. sqlalchemy/dialects/mysql/__init__.py +101 -0
  34. sqlalchemy/dialects/mysql/aiomysql.py +333 -0
  35. sqlalchemy/dialects/mysql/asyncmy.py +337 -0
  36. sqlalchemy/dialects/mysql/base.py +3494 -0
  37. sqlalchemy/dialects/mysql/cymysql.py +84 -0
  38. sqlalchemy/dialects/mysql/dml.py +219 -0
  39. sqlalchemy/dialects/mysql/enumerated.py +244 -0
  40. sqlalchemy/dialects/mysql/expression.py +141 -0
  41. sqlalchemy/dialects/mysql/json.py +81 -0
  42. sqlalchemy/dialects/mysql/mariadb.py +32 -0
  43. sqlalchemy/dialects/mysql/mariadbconnector.py +277 -0
  44. sqlalchemy/dialects/mysql/mysqlconnector.py +180 -0
  45. sqlalchemy/dialects/mysql/mysqldb.py +303 -0
  46. sqlalchemy/dialects/mysql/provision.py +110 -0
  47. sqlalchemy/dialects/mysql/pymysql.py +137 -0
  48. sqlalchemy/dialects/mysql/pyodbc.py +138 -0
  49. sqlalchemy/dialects/mysql/reflection.py +677 -0
  50. sqlalchemy/dialects/mysql/reserved_words.py +571 -0
  51. sqlalchemy/dialects/mysql/types.py +774 -0
  52. sqlalchemy/dialects/oracle/__init__.py +67 -0
  53. sqlalchemy/dialects/oracle/base.py +3271 -0
  54. sqlalchemy/dialects/oracle/cx_oracle.py +1483 -0
  55. sqlalchemy/dialects/oracle/dictionary.py +507 -0
  56. sqlalchemy/dialects/oracle/oracledb.py +431 -0
  57. sqlalchemy/dialects/oracle/provision.py +220 -0
  58. sqlalchemy/dialects/oracle/types.py +287 -0
  59. sqlalchemy/dialects/postgresql/__init__.py +167 -0
  60. sqlalchemy/dialects/postgresql/_psycopg_common.py +187 -0
  61. sqlalchemy/dialects/postgresql/array.py +425 -0
  62. sqlalchemy/dialects/postgresql/asyncpg.py +1274 -0
  63. sqlalchemy/dialects/postgresql/base.py +5008 -0
  64. sqlalchemy/dialects/postgresql/dml.py +310 -0
  65. sqlalchemy/dialects/postgresql/ext.py +496 -0
  66. sqlalchemy/dialects/postgresql/hstore.py +397 -0
  67. sqlalchemy/dialects/postgresql/json.py +333 -0
  68. sqlalchemy/dialects/postgresql/named_types.py +509 -0
  69. sqlalchemy/dialects/postgresql/operators.py +129 -0
  70. sqlalchemy/dialects/postgresql/pg8000.py +662 -0
  71. sqlalchemy/dialects/postgresql/pg_catalog.py +300 -0
  72. sqlalchemy/dialects/postgresql/provision.py +175 -0
  73. sqlalchemy/dialects/postgresql/psycopg.py +772 -0
  74. sqlalchemy/dialects/postgresql/psycopg2.py +886 -0
  75. sqlalchemy/dialects/postgresql/psycopg2cffi.py +61 -0
  76. sqlalchemy/dialects/postgresql/ranges.py +1029 -0
  77. sqlalchemy/dialects/postgresql/types.py +303 -0
  78. sqlalchemy/dialects/sqlite/__init__.py +57 -0
  79. sqlalchemy/dialects/sqlite/aiosqlite.py +396 -0
  80. sqlalchemy/dialects/sqlite/base.py +2805 -0
  81. sqlalchemy/dialects/sqlite/dml.py +240 -0
  82. sqlalchemy/dialects/sqlite/json.py +92 -0
  83. sqlalchemy/dialects/sqlite/provision.py +198 -0
  84. sqlalchemy/dialects/sqlite/pysqlcipher.py +155 -0
  85. sqlalchemy/dialects/sqlite/pysqlite.py +756 -0
  86. sqlalchemy/dialects/type_migration_guidelines.txt +145 -0
  87. sqlalchemy/engine/__init__.py +62 -0
  88. sqlalchemy/engine/_py_processors.py +136 -0
  89. sqlalchemy/engine/_py_row.py +128 -0
  90. sqlalchemy/engine/_py_util.py +74 -0
  91. sqlalchemy/engine/base.py +3375 -0
  92. sqlalchemy/engine/characteristics.py +155 -0
  93. sqlalchemy/engine/create.py +875 -0
  94. sqlalchemy/engine/cursor.py +2181 -0
  95. sqlalchemy/engine/default.py +2365 -0
  96. sqlalchemy/engine/events.py +951 -0
  97. sqlalchemy/engine/interfaces.py +3403 -0
  98. sqlalchemy/engine/mock.py +131 -0
  99. sqlalchemy/engine/processors.py +61 -0
  100. sqlalchemy/engine/reflection.py +2098 -0
  101. sqlalchemy/engine/result.py +2382 -0
  102. sqlalchemy/engine/row.py +401 -0
  103. sqlalchemy/engine/strategies.py +19 -0
  104. sqlalchemy/engine/url.py +910 -0
  105. sqlalchemy/engine/util.py +167 -0
  106. sqlalchemy/event/__init__.py +25 -0
  107. sqlalchemy/event/api.py +225 -0
  108. sqlalchemy/event/attr.py +655 -0
  109. sqlalchemy/event/base.py +470 -0
  110. sqlalchemy/event/legacy.py +246 -0
  111. sqlalchemy/event/registry.py +386 -0
  112. sqlalchemy/events.py +17 -0
  113. sqlalchemy/exc.py +830 -0
  114. sqlalchemy/ext/__init__.py +11 -0
  115. sqlalchemy/ext/associationproxy.py +2013 -0
  116. sqlalchemy/ext/asyncio/__init__.py +25 -0
  117. sqlalchemy/ext/asyncio/base.py +279 -0
  118. sqlalchemy/ext/asyncio/engine.py +1466 -0
  119. sqlalchemy/ext/asyncio/exc.py +21 -0
  120. sqlalchemy/ext/asyncio/result.py +961 -0
  121. sqlalchemy/ext/asyncio/scoping.py +1614 -0
  122. sqlalchemy/ext/asyncio/session.py +1936 -0
  123. sqlalchemy/ext/automap.py +1691 -0
  124. sqlalchemy/ext/baked.py +574 -0
  125. sqlalchemy/ext/compiler.py +570 -0
  126. sqlalchemy/ext/declarative/__init__.py +65 -0
  127. sqlalchemy/ext/declarative/extensions.py +548 -0
  128. sqlalchemy/ext/horizontal_shard.py +481 -0
  129. sqlalchemy/ext/hybrid.py +1514 -0
  130. sqlalchemy/ext/indexable.py +341 -0
  131. sqlalchemy/ext/instrumentation.py +450 -0
  132. sqlalchemy/ext/mutable.py +1073 -0
  133. sqlalchemy/ext/mypy/__init__.py +6 -0
  134. sqlalchemy/ext/mypy/apply.py +320 -0
  135. sqlalchemy/ext/mypy/decl_class.py +515 -0
  136. sqlalchemy/ext/mypy/infer.py +590 -0
  137. sqlalchemy/ext/mypy/names.py +335 -0
  138. sqlalchemy/ext/mypy/plugin.py +303 -0
  139. sqlalchemy/ext/mypy/util.py +357 -0
  140. sqlalchemy/ext/orderinglist.py +416 -0
  141. sqlalchemy/ext/serializer.py +181 -0
  142. sqlalchemy/future/__init__.py +16 -0
  143. sqlalchemy/future/engine.py +15 -0
  144. sqlalchemy/inspection.py +174 -0
  145. sqlalchemy/log.py +288 -0
  146. sqlalchemy/orm/__init__.py +170 -0
  147. sqlalchemy/orm/_orm_constructors.py +2571 -0
  148. sqlalchemy/orm/_typing.py +179 -0
  149. sqlalchemy/orm/attributes.py +2835 -0
  150. sqlalchemy/orm/base.py +973 -0
  151. sqlalchemy/orm/bulk_persistence.py +2123 -0
  152. sqlalchemy/orm/clsregistry.py +571 -0
  153. sqlalchemy/orm/collections.py +1620 -0
  154. sqlalchemy/orm/context.py +3268 -0
  155. sqlalchemy/orm/decl_api.py +1883 -0
  156. sqlalchemy/orm/decl_base.py +2190 -0
  157. sqlalchemy/orm/dependency.py +1304 -0
  158. sqlalchemy/orm/descriptor_props.py +1076 -0
  159. sqlalchemy/orm/dynamic.py +300 -0
  160. sqlalchemy/orm/evaluator.py +379 -0
  161. sqlalchemy/orm/events.py +3261 -0
  162. sqlalchemy/orm/exc.py +228 -0
  163. sqlalchemy/orm/identity.py +302 -0
  164. sqlalchemy/orm/instrumentation.py +754 -0
  165. sqlalchemy/orm/interfaces.py +1474 -0
  166. sqlalchemy/orm/loading.py +1682 -0
  167. sqlalchemy/orm/mapped_collection.py +557 -0
  168. sqlalchemy/orm/mapper.py +4432 -0
  169. sqlalchemy/orm/path_registry.py +811 -0
  170. sqlalchemy/orm/persistence.py +1782 -0
  171. sqlalchemy/orm/properties.py +886 -0
  172. sqlalchemy/orm/query.py +3396 -0
  173. sqlalchemy/orm/relationships.py +3500 -0
  174. sqlalchemy/orm/scoping.py +2165 -0
  175. sqlalchemy/orm/session.py +5301 -0
  176. sqlalchemy/orm/state.py +1143 -0
  177. sqlalchemy/orm/state_changes.py +198 -0
  178. sqlalchemy/orm/strategies.py +3473 -0
  179. sqlalchemy/orm/strategy_options.py +2569 -0
  180. sqlalchemy/orm/sync.py +164 -0
  181. sqlalchemy/orm/unitofwork.py +796 -0
  182. sqlalchemy/orm/util.py +2424 -0
  183. sqlalchemy/orm/writeonly.py +678 -0
  184. sqlalchemy/pool/__init__.py +44 -0
  185. sqlalchemy/pool/base.py +1515 -0
  186. sqlalchemy/pool/events.py +370 -0
  187. sqlalchemy/pool/impl.py +581 -0
  188. sqlalchemy/py.typed +0 -0
  189. sqlalchemy/schema.py +70 -0
  190. sqlalchemy/sql/__init__.py +145 -0
  191. sqlalchemy/sql/_dml_constructors.py +140 -0
  192. sqlalchemy/sql/_elements_constructors.py +1850 -0
  193. sqlalchemy/sql/_orm_types.py +20 -0
  194. sqlalchemy/sql/_py_util.py +75 -0
  195. sqlalchemy/sql/_selectable_constructors.py +635 -0
  196. sqlalchemy/sql/_typing.py +460 -0
  197. sqlalchemy/sql/annotation.py +585 -0
  198. sqlalchemy/sql/base.py +2185 -0
  199. sqlalchemy/sql/cache_key.py +1057 -0
  200. sqlalchemy/sql/coercions.py +1405 -0
  201. sqlalchemy/sql/compiler.py +7818 -0
  202. sqlalchemy/sql/crud.py +1669 -0
  203. sqlalchemy/sql/ddl.py +1378 -0
  204. sqlalchemy/sql/default_comparator.py +552 -0
  205. sqlalchemy/sql/dml.py +1817 -0
  206. sqlalchemy/sql/elements.py +5499 -0
  207. sqlalchemy/sql/events.py +455 -0
  208. sqlalchemy/sql/expression.py +162 -0
  209. sqlalchemy/sql/functions.py +2055 -0
  210. sqlalchemy/sql/lambdas.py +1449 -0
  211. sqlalchemy/sql/naming.py +212 -0
  212. sqlalchemy/sql/operators.py +2579 -0
  213. sqlalchemy/sql/roles.py +323 -0
  214. sqlalchemy/sql/schema.py +6158 -0
  215. sqlalchemy/sql/selectable.py +7004 -0
  216. sqlalchemy/sql/sqltypes.py +3827 -0
  217. sqlalchemy/sql/traversals.py +1024 -0
  218. sqlalchemy/sql/type_api.py +2339 -0
  219. sqlalchemy/sql/util.py +1486 -0
  220. sqlalchemy/sql/visitors.py +1165 -0
  221. sqlalchemy/testing/__init__.py +96 -0
  222. sqlalchemy/testing/assertions.py +989 -0
  223. sqlalchemy/testing/assertsql.py +516 -0
  224. sqlalchemy/testing/asyncio.py +135 -0
  225. sqlalchemy/testing/config.py +427 -0
  226. sqlalchemy/testing/engines.py +472 -0
  227. sqlalchemy/testing/entities.py +117 -0
  228. sqlalchemy/testing/exclusions.py +435 -0
  229. sqlalchemy/testing/fixtures/__init__.py +28 -0
  230. sqlalchemy/testing/fixtures/base.py +366 -0
  231. sqlalchemy/testing/fixtures/mypy.py +312 -0
  232. sqlalchemy/testing/fixtures/orm.py +227 -0
  233. sqlalchemy/testing/fixtures/sql.py +503 -0
  234. sqlalchemy/testing/pickleable.py +155 -0
  235. sqlalchemy/testing/plugin/__init__.py +6 -0
  236. sqlalchemy/testing/plugin/bootstrap.py +51 -0
  237. sqlalchemy/testing/plugin/plugin_base.py +779 -0
  238. sqlalchemy/testing/plugin/pytestplugin.py +868 -0
  239. sqlalchemy/testing/profiling.py +324 -0
  240. sqlalchemy/testing/provision.py +496 -0
  241. sqlalchemy/testing/requirements.py +1818 -0
  242. sqlalchemy/testing/schema.py +224 -0
  243. sqlalchemy/testing/suite/__init__.py +19 -0
  244. sqlalchemy/testing/suite/test_cte.py +211 -0
  245. sqlalchemy/testing/suite/test_ddl.py +389 -0
  246. sqlalchemy/testing/suite/test_deprecations.py +153 -0
  247. sqlalchemy/testing/suite/test_dialect.py +740 -0
  248. sqlalchemy/testing/suite/test_insert.py +630 -0
  249. sqlalchemy/testing/suite/test_reflection.py +3225 -0
  250. sqlalchemy/testing/suite/test_results.py +502 -0
  251. sqlalchemy/testing/suite/test_rowcount.py +258 -0
  252. sqlalchemy/testing/suite/test_select.py +1999 -0
  253. sqlalchemy/testing/suite/test_sequence.py +317 -0
  254. sqlalchemy/testing/suite/test_types.py +2141 -0
  255. sqlalchemy/testing/suite/test_unicode_ddl.py +189 -0
  256. sqlalchemy/testing/suite/test_update_delete.py +139 -0
  257. sqlalchemy/testing/util.py +537 -0
  258. sqlalchemy/testing/warnings.py +52 -0
  259. sqlalchemy/types.py +76 -0
  260. sqlalchemy/util/__init__.py +160 -0
  261. sqlalchemy/util/_collections.py +715 -0
  262. sqlalchemy/util/_concurrency_py3k.py +288 -0
  263. sqlalchemy/util/_has_cy.py +40 -0
  264. sqlalchemy/util/_py_collections.py +541 -0
  265. sqlalchemy/util/compat.py +301 -0
  266. sqlalchemy/util/concurrency.py +108 -0
  267. sqlalchemy/util/deprecations.py +401 -0
  268. sqlalchemy/util/langhelpers.py +2218 -0
  269. sqlalchemy/util/preloaded.py +150 -0
  270. sqlalchemy/util/queue.py +322 -0
  271. sqlalchemy/util/tool_support.py +201 -0
  272. sqlalchemy/util/topological.py +120 -0
  273. sqlalchemy/util/typing.py +629 -0
sqlalchemy/sql/dml.py ADDED
@@ -0,0 +1,1817 @@
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
+ """
12
+ from __future__ import annotations
13
+
14
+ import collections.abc as collections_abc
15
+ import operator
16
+ from typing import Any
17
+ from typing import cast
18
+ from typing import Dict
19
+ from typing import Iterable
20
+ from typing import List
21
+ from typing import MutableMapping
22
+ from typing import NoReturn
23
+ from typing import Optional
24
+ from typing import overload
25
+ from typing import Sequence
26
+ from typing import Tuple
27
+ from typing import Type
28
+ from typing import TYPE_CHECKING
29
+ from typing import TypeVar
30
+ from typing import Union
31
+
32
+ from . import coercions
33
+ from . import roles
34
+ from . import util as sql_util
35
+ from ._typing import _TP
36
+ from ._typing import _unexpected_kw
37
+ from ._typing import is_column_element
38
+ from ._typing import is_named_from_clause
39
+ from .base import _entity_namespace_key
40
+ from .base import _exclusive_against
41
+ from .base import _from_objects
42
+ from .base import _generative
43
+ from .base import _select_iterables
44
+ from .base import ColumnCollection
45
+ from .base import CompileState
46
+ from .base import DialectKWArgs
47
+ from .base import Executable
48
+ from .base import Generative
49
+ from .base import HasCompileState
50
+ from .elements import BooleanClauseList
51
+ from .elements import ClauseElement
52
+ from .elements import ColumnClause
53
+ from .elements import ColumnElement
54
+ from .elements import Null
55
+ from .selectable import Alias
56
+ from .selectable import ExecutableReturnsRows
57
+ from .selectable import FromClause
58
+ from .selectable import HasCTE
59
+ from .selectable import HasPrefixes
60
+ from .selectable import Join
61
+ from .selectable import SelectLabelStyle
62
+ from .selectable import TableClause
63
+ from .selectable import TypedReturnsRows
64
+ from .sqltypes import NullType
65
+ from .visitors import InternalTraversal
66
+ from .. import exc
67
+ from .. import util
68
+ from ..util.typing import Self
69
+ from ..util.typing import TypeGuard
70
+
71
+ if TYPE_CHECKING:
72
+ from ._typing import _ColumnExpressionArgument
73
+ from ._typing import _ColumnsClauseArgument
74
+ from ._typing import _DMLColumnArgument
75
+ from ._typing import _DMLColumnKeyMapping
76
+ from ._typing import _DMLTableArgument
77
+ from ._typing import _T0 # noqa
78
+ from ._typing import _T1 # noqa
79
+ from ._typing import _T2 # noqa
80
+ from ._typing import _T3 # noqa
81
+ from ._typing import _T4 # noqa
82
+ from ._typing import _T5 # noqa
83
+ from ._typing import _T6 # noqa
84
+ from ._typing import _T7 # noqa
85
+ from ._typing import _TypedColumnClauseArgument as _TCCA # noqa
86
+ from .base import ReadOnlyColumnCollection
87
+ from .compiler import SQLCompiler
88
+ from .elements import KeyedColumnElement
89
+ from .selectable import _ColumnsClauseElement
90
+ from .selectable import _SelectIterable
91
+ from .selectable import Select
92
+ from .selectable import Selectable
93
+
94
+ def isupdate(dml: DMLState) -> TypeGuard[UpdateDMLState]: ...
95
+
96
+ def isdelete(dml: DMLState) -> TypeGuard[DeleteDMLState]: ...
97
+
98
+ def isinsert(dml: DMLState) -> TypeGuard[InsertDMLState]: ...
99
+
100
+ else:
101
+ isupdate = operator.attrgetter("isupdate")
102
+ isdelete = operator.attrgetter("isdelete")
103
+ isinsert = operator.attrgetter("isinsert")
104
+
105
+
106
+ _T = TypeVar("_T", bound=Any)
107
+
108
+ _DMLColumnElement = Union[str, ColumnClause[Any]]
109
+ _DMLTableElement = Union[TableClause, Alias, Join]
110
+
111
+
112
+ class DMLState(CompileState):
113
+ _no_parameters = True
114
+ _dict_parameters: Optional[MutableMapping[_DMLColumnElement, Any]] = None
115
+ _multi_parameters: Optional[
116
+ List[MutableMapping[_DMLColumnElement, Any]]
117
+ ] = None
118
+ _ordered_values: Optional[List[Tuple[_DMLColumnElement, Any]]] = None
119
+ _parameter_ordering: Optional[List[_DMLColumnElement]] = None
120
+ _primary_table: FromClause
121
+ _supports_implicit_returning = True
122
+
123
+ isupdate = False
124
+ isdelete = False
125
+ isinsert = False
126
+
127
+ statement: UpdateBase
128
+
129
+ def __init__(
130
+ self, statement: UpdateBase, compiler: SQLCompiler, **kw: Any
131
+ ):
132
+ raise NotImplementedError()
133
+
134
+ @classmethod
135
+ def get_entity_description(cls, statement: UpdateBase) -> Dict[str, Any]:
136
+ return {
137
+ "name": (
138
+ statement.table.name
139
+ if is_named_from_clause(statement.table)
140
+ else None
141
+ ),
142
+ "table": statement.table,
143
+ }
144
+
145
+ @classmethod
146
+ def get_returning_column_descriptions(
147
+ cls, statement: UpdateBase
148
+ ) -> List[Dict[str, Any]]:
149
+ return [
150
+ {
151
+ "name": c.key,
152
+ "type": c.type,
153
+ "expr": c,
154
+ }
155
+ for c in statement._all_selected_columns
156
+ ]
157
+
158
+ @property
159
+ def dml_table(self) -> _DMLTableElement:
160
+ return self.statement.table
161
+
162
+ if TYPE_CHECKING:
163
+
164
+ @classmethod
165
+ def get_plugin_class(cls, statement: Executable) -> Type[DMLState]: ...
166
+
167
+ @classmethod
168
+ def _get_multi_crud_kv_pairs(
169
+ cls,
170
+ statement: UpdateBase,
171
+ multi_kv_iterator: Iterable[Dict[_DMLColumnArgument, Any]],
172
+ ) -> List[Dict[_DMLColumnElement, Any]]:
173
+ return [
174
+ {
175
+ coercions.expect(roles.DMLColumnRole, k): v
176
+ for k, v in mapping.items()
177
+ }
178
+ for mapping in multi_kv_iterator
179
+ ]
180
+
181
+ @classmethod
182
+ def _get_crud_kv_pairs(
183
+ cls,
184
+ statement: UpdateBase,
185
+ kv_iterator: Iterable[Tuple[_DMLColumnArgument, Any]],
186
+ needs_to_be_cacheable: bool,
187
+ ) -> List[Tuple[_DMLColumnElement, Any]]:
188
+ return [
189
+ (
190
+ coercions.expect(roles.DMLColumnRole, k),
191
+ (
192
+ v
193
+ if not needs_to_be_cacheable
194
+ else coercions.expect(
195
+ roles.ExpressionElementRole,
196
+ v,
197
+ type_=NullType(),
198
+ is_crud=True,
199
+ )
200
+ ),
201
+ )
202
+ for k, v in kv_iterator
203
+ ]
204
+
205
+ def _make_extra_froms(
206
+ self, statement: DMLWhereBase
207
+ ) -> Tuple[FromClause, List[FromClause]]:
208
+ froms: List[FromClause] = []
209
+
210
+ all_tables = list(sql_util.tables_from_leftmost(statement.table))
211
+ primary_table = all_tables[0]
212
+ seen = {primary_table}
213
+
214
+ consider = statement._where_criteria
215
+ if self._dict_parameters:
216
+ consider += tuple(self._dict_parameters.values())
217
+
218
+ for crit in consider:
219
+ for item in _from_objects(crit):
220
+ if not seen.intersection(item._cloned_set):
221
+ froms.append(item)
222
+ seen.update(item._cloned_set)
223
+
224
+ froms.extend(all_tables[1:])
225
+ return primary_table, froms
226
+
227
+ def _process_values(self, statement: ValuesBase) -> None:
228
+ if self._no_parameters:
229
+ self._dict_parameters = statement._values
230
+ self._no_parameters = False
231
+
232
+ def _process_select_values(self, statement: ValuesBase) -> None:
233
+ assert statement._select_names is not None
234
+ parameters: MutableMapping[_DMLColumnElement, Any] = {
235
+ name: Null() for name in statement._select_names
236
+ }
237
+
238
+ if self._no_parameters:
239
+ self._no_parameters = False
240
+ self._dict_parameters = parameters
241
+ else:
242
+ # this condition normally not reachable as the Insert
243
+ # does not allow this construction to occur
244
+ assert False, "This statement already has parameters"
245
+
246
+ def _no_multi_values_supported(self, statement: ValuesBase) -> NoReturn:
247
+ raise exc.InvalidRequestError(
248
+ "%s construct does not support "
249
+ "multiple parameter sets." % statement.__visit_name__.upper()
250
+ )
251
+
252
+ def _cant_mix_formats_error(self) -> NoReturn:
253
+ raise exc.InvalidRequestError(
254
+ "Can't mix single and multiple VALUES "
255
+ "formats in one INSERT statement; one style appends to a "
256
+ "list while the other replaces values, so the intent is "
257
+ "ambiguous."
258
+ )
259
+
260
+
261
+ @CompileState.plugin_for("default", "insert")
262
+ class InsertDMLState(DMLState):
263
+ isinsert = True
264
+
265
+ include_table_with_column_exprs = False
266
+
267
+ _has_multi_parameters = False
268
+
269
+ def __init__(
270
+ self,
271
+ statement: Insert,
272
+ compiler: SQLCompiler,
273
+ disable_implicit_returning: bool = False,
274
+ **kw: Any,
275
+ ):
276
+ self.statement = statement
277
+ self._primary_table = statement.table
278
+
279
+ if disable_implicit_returning:
280
+ self._supports_implicit_returning = False
281
+
282
+ self.isinsert = True
283
+ if statement._select_names:
284
+ self._process_select_values(statement)
285
+ if statement._values is not None:
286
+ self._process_values(statement)
287
+ if statement._multi_values:
288
+ self._process_multi_values(statement)
289
+
290
+ @util.memoized_property
291
+ def _insert_col_keys(self) -> List[str]:
292
+ # this is also done in crud.py -> _key_getters_for_crud_column
293
+ return [
294
+ coercions.expect(roles.DMLColumnRole, col, as_key=True)
295
+ for col in self._dict_parameters or ()
296
+ ]
297
+
298
+ def _process_values(self, statement: ValuesBase) -> None:
299
+ if self._no_parameters:
300
+ self._has_multi_parameters = False
301
+ self._dict_parameters = statement._values
302
+ self._no_parameters = False
303
+ elif self._has_multi_parameters:
304
+ self._cant_mix_formats_error()
305
+
306
+ def _process_multi_values(self, statement: ValuesBase) -> None:
307
+ for parameters in statement._multi_values:
308
+ multi_parameters: List[MutableMapping[_DMLColumnElement, Any]] = [
309
+ (
310
+ {
311
+ c.key: value
312
+ for c, value in zip(statement.table.c, parameter_set)
313
+ }
314
+ if isinstance(parameter_set, collections_abc.Sequence)
315
+ else parameter_set
316
+ )
317
+ for parameter_set in parameters
318
+ ]
319
+
320
+ if self._no_parameters:
321
+ self._no_parameters = False
322
+ self._has_multi_parameters = True
323
+ self._multi_parameters = multi_parameters
324
+ self._dict_parameters = self._multi_parameters[0]
325
+ elif not self._has_multi_parameters:
326
+ self._cant_mix_formats_error()
327
+ else:
328
+ assert self._multi_parameters
329
+ self._multi_parameters.extend(multi_parameters)
330
+
331
+
332
+ @CompileState.plugin_for("default", "update")
333
+ class UpdateDMLState(DMLState):
334
+ isupdate = True
335
+
336
+ include_table_with_column_exprs = False
337
+
338
+ def __init__(self, statement: Update, compiler: SQLCompiler, **kw: Any):
339
+ self.statement = statement
340
+
341
+ self.isupdate = True
342
+ if statement._ordered_values is not None:
343
+ self._process_ordered_values(statement)
344
+ elif statement._values is not None:
345
+ self._process_values(statement)
346
+ elif statement._multi_values:
347
+ self._no_multi_values_supported(statement)
348
+ t, ef = self._make_extra_froms(statement)
349
+ self._primary_table = t
350
+ self._extra_froms = ef
351
+
352
+ self.is_multitable = mt = ef
353
+ self.include_table_with_column_exprs = bool(
354
+ mt and compiler.render_table_with_column_in_update_from
355
+ )
356
+
357
+ def _process_ordered_values(self, statement: ValuesBase) -> None:
358
+ parameters = statement._ordered_values
359
+
360
+ if self._no_parameters:
361
+ self._no_parameters = False
362
+ assert parameters is not None
363
+ self._dict_parameters = dict(parameters)
364
+ self._ordered_values = parameters
365
+ self._parameter_ordering = [key for key, value in parameters]
366
+ else:
367
+ raise exc.InvalidRequestError(
368
+ "Can only invoke ordered_values() once, and not mixed "
369
+ "with any other values() call"
370
+ )
371
+
372
+
373
+ @CompileState.plugin_for("default", "delete")
374
+ class DeleteDMLState(DMLState):
375
+ isdelete = True
376
+
377
+ def __init__(self, statement: Delete, compiler: SQLCompiler, **kw: Any):
378
+ self.statement = statement
379
+
380
+ self.isdelete = True
381
+ t, ef = self._make_extra_froms(statement)
382
+ self._primary_table = t
383
+ self._extra_froms = ef
384
+ self.is_multitable = ef
385
+
386
+
387
+ class UpdateBase(
388
+ roles.DMLRole,
389
+ HasCTE,
390
+ HasCompileState,
391
+ DialectKWArgs,
392
+ HasPrefixes,
393
+ Generative,
394
+ ExecutableReturnsRows,
395
+ ClauseElement,
396
+ ):
397
+ """Form the base for ``INSERT``, ``UPDATE``, and ``DELETE`` statements."""
398
+
399
+ __visit_name__ = "update_base"
400
+
401
+ _hints: util.immutabledict[Tuple[_DMLTableElement, str], str] = (
402
+ util.EMPTY_DICT
403
+ )
404
+ named_with_column = False
405
+
406
+ _label_style: SelectLabelStyle = (
407
+ SelectLabelStyle.LABEL_STYLE_DISAMBIGUATE_ONLY
408
+ )
409
+ table: _DMLTableElement
410
+
411
+ _return_defaults = False
412
+ _return_defaults_columns: Optional[Tuple[_ColumnsClauseElement, ...]] = (
413
+ None
414
+ )
415
+ _supplemental_returning: Optional[Tuple[_ColumnsClauseElement, ...]] = None
416
+ _returning: Tuple[_ColumnsClauseElement, ...] = ()
417
+
418
+ is_dml = True
419
+
420
+ def _generate_fromclause_column_proxies(
421
+ self, fromclause: FromClause
422
+ ) -> None:
423
+ fromclause._columns._populate_separate_keys(
424
+ col._make_proxy(fromclause)
425
+ for col in self._all_selected_columns
426
+ if is_column_element(col)
427
+ )
428
+
429
+ def params(self, *arg: Any, **kw: Any) -> NoReturn:
430
+ """Set the parameters for the statement.
431
+
432
+ This method raises ``NotImplementedError`` on the base class,
433
+ and is overridden by :class:`.ValuesBase` to provide the
434
+ SET/VALUES clause of UPDATE and INSERT.
435
+
436
+ """
437
+ raise NotImplementedError(
438
+ "params() is not supported for INSERT/UPDATE/DELETE statements."
439
+ " To set the values for an INSERT or UPDATE statement, use"
440
+ " stmt.values(**parameters)."
441
+ )
442
+
443
+ @_generative
444
+ def with_dialect_options(self, **opt: Any) -> Self:
445
+ """Add dialect options to this INSERT/UPDATE/DELETE object.
446
+
447
+ e.g.::
448
+
449
+ upd = table.update().dialect_options(mysql_limit=10)
450
+
451
+ .. versionadded: 1.4 - this method supersedes the dialect options
452
+ associated with the constructor.
453
+
454
+
455
+ """
456
+ self._validate_dialect_kwargs(opt)
457
+ return self
458
+
459
+ @_generative
460
+ def return_defaults(
461
+ self,
462
+ *cols: _DMLColumnArgument,
463
+ supplemental_cols: Optional[Iterable[_DMLColumnArgument]] = None,
464
+ sort_by_parameter_order: bool = False,
465
+ ) -> Self:
466
+ """Make use of a :term:`RETURNING` clause for the purpose
467
+ of fetching server-side expressions and defaults, for supporting
468
+ backends only.
469
+
470
+ .. deepalchemy::
471
+
472
+ The :meth:`.UpdateBase.return_defaults` method is used by the ORM
473
+ for its internal work in fetching newly generated primary key
474
+ and server default values, in particular to provide the underyling
475
+ implementation of the :paramref:`_orm.Mapper.eager_defaults`
476
+ ORM feature as well as to allow RETURNING support with bulk
477
+ ORM inserts. Its behavior is fairly idiosyncratic
478
+ and is not really intended for general use. End users should
479
+ stick with using :meth:`.UpdateBase.returning` in order to
480
+ add RETURNING clauses to their INSERT, UPDATE and DELETE
481
+ statements.
482
+
483
+ Normally, a single row INSERT statement will automatically populate the
484
+ :attr:`.CursorResult.inserted_primary_key` attribute when executed,
485
+ which stores the primary key of the row that was just inserted in the
486
+ form of a :class:`.Row` object with column names as named tuple keys
487
+ (and the :attr:`.Row._mapping` view fully populated as well). The
488
+ dialect in use chooses the strategy to use in order to populate this
489
+ data; if it was generated using server-side defaults and / or SQL
490
+ expressions, dialect-specific approaches such as ``cursor.lastrowid``
491
+ or ``RETURNING`` are typically used to acquire the new primary key
492
+ value.
493
+
494
+ However, when the statement is modified by calling
495
+ :meth:`.UpdateBase.return_defaults` before executing the statement,
496
+ additional behaviors take place **only** for backends that support
497
+ RETURNING and for :class:`.Table` objects that maintain the
498
+ :paramref:`.Table.implicit_returning` parameter at its default value of
499
+ ``True``. In these cases, when the :class:`.CursorResult` is returned
500
+ from the statement's execution, not only will
501
+ :attr:`.CursorResult.inserted_primary_key` be populated as always, the
502
+ :attr:`.CursorResult.returned_defaults` attribute will also be
503
+ populated with a :class:`.Row` named-tuple representing the full range
504
+ of server generated
505
+ values from that single row, including values for any columns that
506
+ specify :paramref:`_schema.Column.server_default` or which make use of
507
+ :paramref:`_schema.Column.default` using a SQL expression.
508
+
509
+ When invoking INSERT statements with multiple rows using
510
+ :ref:`insertmanyvalues <engine_insertmanyvalues>`, the
511
+ :meth:`.UpdateBase.return_defaults` modifier will have the effect of
512
+ the :attr:`_engine.CursorResult.inserted_primary_key_rows` and
513
+ :attr:`_engine.CursorResult.returned_defaults_rows` attributes being
514
+ fully populated with lists of :class:`.Row` objects representing newly
515
+ inserted primary key values as well as newly inserted server generated
516
+ values for each row inserted. The
517
+ :attr:`.CursorResult.inserted_primary_key` and
518
+ :attr:`.CursorResult.returned_defaults` attributes will also continue
519
+ to be populated with the first row of these two collections.
520
+
521
+ If the backend does not support RETURNING or the :class:`.Table` in use
522
+ has disabled :paramref:`.Table.implicit_returning`, then no RETURNING
523
+ clause is added and no additional data is fetched, however the
524
+ INSERT, UPDATE or DELETE statement proceeds normally.
525
+
526
+ E.g.::
527
+
528
+ stmt = table.insert().values(data='newdata').return_defaults()
529
+
530
+ result = connection.execute(stmt)
531
+
532
+ server_created_at = result.returned_defaults['created_at']
533
+
534
+ When used against an UPDATE statement
535
+ :meth:`.UpdateBase.return_defaults` instead looks for columns that
536
+ include :paramref:`_schema.Column.onupdate` or
537
+ :paramref:`_schema.Column.server_onupdate` parameters assigned, when
538
+ constructing the columns that will be included in the RETURNING clause
539
+ by default if explicit columns were not specified. When used against a
540
+ DELETE statement, no columns are included in RETURNING by default, they
541
+ instead must be specified explicitly as there are no columns that
542
+ normally change values when a DELETE statement proceeds.
543
+
544
+ .. versionadded:: 2.0 :meth:`.UpdateBase.return_defaults` is supported
545
+ for DELETE statements also and has been moved from
546
+ :class:`.ValuesBase` to :class:`.UpdateBase`.
547
+
548
+ The :meth:`.UpdateBase.return_defaults` method is mutually exclusive
549
+ against the :meth:`.UpdateBase.returning` method and errors will be
550
+ raised during the SQL compilation process if both are used at the same
551
+ time on one statement. The RETURNING clause of the INSERT, UPDATE or
552
+ DELETE statement is therefore controlled by only one of these methods
553
+ at a time.
554
+
555
+ The :meth:`.UpdateBase.return_defaults` method differs from
556
+ :meth:`.UpdateBase.returning` in these ways:
557
+
558
+ 1. :meth:`.UpdateBase.return_defaults` method causes the
559
+ :attr:`.CursorResult.returned_defaults` collection to be populated
560
+ with the first row from the RETURNING result. This attribute is not
561
+ populated when using :meth:`.UpdateBase.returning`.
562
+
563
+ 2. :meth:`.UpdateBase.return_defaults` is compatible with existing
564
+ logic used to fetch auto-generated primary key values that are then
565
+ populated into the :attr:`.CursorResult.inserted_primary_key`
566
+ attribute. By contrast, using :meth:`.UpdateBase.returning` will
567
+ have the effect of the :attr:`.CursorResult.inserted_primary_key`
568
+ attribute being left unpopulated.
569
+
570
+ 3. :meth:`.UpdateBase.return_defaults` can be called against any
571
+ backend. Backends that don't support RETURNING will skip the usage
572
+ of the feature, rather than raising an exception, *unless*
573
+ ``supplemental_cols`` is passed. The return value
574
+ of :attr:`_engine.CursorResult.returned_defaults` will be ``None``
575
+ for backends that don't support RETURNING or for which the target
576
+ :class:`.Table` sets :paramref:`.Table.implicit_returning` to
577
+ ``False``.
578
+
579
+ 4. An INSERT statement invoked with executemany() is supported if the
580
+ backend database driver supports the
581
+ :ref:`insertmanyvalues <engine_insertmanyvalues>`
582
+ feature which is now supported by most SQLAlchemy-included backends.
583
+ When executemany is used, the
584
+ :attr:`_engine.CursorResult.returned_defaults_rows` and
585
+ :attr:`_engine.CursorResult.inserted_primary_key_rows` accessors
586
+ will return the inserted defaults and primary keys.
587
+
588
+ .. versionadded:: 1.4 Added
589
+ :attr:`_engine.CursorResult.returned_defaults_rows` and
590
+ :attr:`_engine.CursorResult.inserted_primary_key_rows` accessors.
591
+ In version 2.0, the underlying implementation which fetches and
592
+ populates the data for these attributes was generalized to be
593
+ supported by most backends, whereas in 1.4 they were only
594
+ supported by the ``psycopg2`` driver.
595
+
596
+
597
+ :param cols: optional list of column key names or
598
+ :class:`_schema.Column` that acts as a filter for those columns that
599
+ will be fetched.
600
+ :param supplemental_cols: optional list of RETURNING expressions,
601
+ in the same form as one would pass to the
602
+ :meth:`.UpdateBase.returning` method. When present, the additional
603
+ columns will be included in the RETURNING clause, and the
604
+ :class:`.CursorResult` object will be "rewound" when returned, so
605
+ that methods like :meth:`.CursorResult.all` will return new rows
606
+ mostly as though the statement used :meth:`.UpdateBase.returning`
607
+ directly. However, unlike when using :meth:`.UpdateBase.returning`
608
+ directly, the **order of the columns is undefined**, so can only be
609
+ targeted using names or :attr:`.Row._mapping` keys; they cannot
610
+ reliably be targeted positionally.
611
+
612
+ .. versionadded:: 2.0
613
+
614
+ :param sort_by_parameter_order: for a batch INSERT that is being
615
+ executed against multiple parameter sets, organize the results of
616
+ RETURNING so that the returned rows correspond to the order of
617
+ parameter sets passed in. This applies only to an :term:`executemany`
618
+ execution for supporting dialects and typically makes use of the
619
+ :term:`insertmanyvalues` feature.
620
+
621
+ .. versionadded:: 2.0.10
622
+
623
+ .. seealso::
624
+
625
+ :ref:`engine_insertmanyvalues_returning_order` - background on
626
+ sorting of RETURNING rows for bulk INSERT
627
+
628
+ .. seealso::
629
+
630
+ :meth:`.UpdateBase.returning`
631
+
632
+ :attr:`_engine.CursorResult.returned_defaults`
633
+
634
+ :attr:`_engine.CursorResult.returned_defaults_rows`
635
+
636
+ :attr:`_engine.CursorResult.inserted_primary_key`
637
+
638
+ :attr:`_engine.CursorResult.inserted_primary_key_rows`
639
+
640
+ """
641
+
642
+ if self._return_defaults:
643
+ # note _return_defaults_columns = () means return all columns,
644
+ # so if we have been here before, only update collection if there
645
+ # are columns in the collection
646
+ if self._return_defaults_columns and cols:
647
+ self._return_defaults_columns = tuple(
648
+ util.OrderedSet(self._return_defaults_columns).union(
649
+ coercions.expect(roles.ColumnsClauseRole, c)
650
+ for c in cols
651
+ )
652
+ )
653
+ else:
654
+ # set for all columns
655
+ self._return_defaults_columns = ()
656
+ else:
657
+ self._return_defaults_columns = tuple(
658
+ coercions.expect(roles.ColumnsClauseRole, c) for c in cols
659
+ )
660
+ self._return_defaults = True
661
+ if sort_by_parameter_order:
662
+ if not self.is_insert:
663
+ raise exc.ArgumentError(
664
+ "The 'sort_by_parameter_order' argument to "
665
+ "return_defaults() only applies to INSERT statements"
666
+ )
667
+ self._sort_by_parameter_order = True
668
+ if supplemental_cols:
669
+ # uniquifying while also maintaining order (the maintain of order
670
+ # is for test suites but also for vertical splicing
671
+ supplemental_col_tup = (
672
+ coercions.expect(roles.ColumnsClauseRole, c)
673
+ for c in supplemental_cols
674
+ )
675
+
676
+ if self._supplemental_returning is None:
677
+ self._supplemental_returning = tuple(
678
+ util.unique_list(supplemental_col_tup)
679
+ )
680
+ else:
681
+ self._supplemental_returning = tuple(
682
+ util.unique_list(
683
+ self._supplemental_returning
684
+ + tuple(supplemental_col_tup)
685
+ )
686
+ )
687
+
688
+ return self
689
+
690
+ @_generative
691
+ def returning(
692
+ self,
693
+ *cols: _ColumnsClauseArgument[Any],
694
+ sort_by_parameter_order: bool = False,
695
+ **__kw: Any,
696
+ ) -> UpdateBase:
697
+ r"""Add a :term:`RETURNING` or equivalent clause to this statement.
698
+
699
+ e.g.:
700
+
701
+ .. sourcecode:: pycon+sql
702
+
703
+ >>> stmt = (
704
+ ... table.update()
705
+ ... .where(table.c.data == "value")
706
+ ... .values(status="X")
707
+ ... .returning(table.c.server_flag, table.c.updated_timestamp)
708
+ ... )
709
+ >>> print(stmt)
710
+ {printsql}UPDATE some_table SET status=:status
711
+ WHERE some_table.data = :data_1
712
+ RETURNING some_table.server_flag, some_table.updated_timestamp
713
+
714
+ The method may be invoked multiple times to add new entries to the
715
+ list of expressions to be returned.
716
+
717
+ .. versionadded:: 1.4.0b2 The method may be invoked multiple times to
718
+ add new entries to the list of expressions to be returned.
719
+
720
+ The given collection of column expressions should be derived from the
721
+ table that is the target of the INSERT, UPDATE, or DELETE. While
722
+ :class:`_schema.Column` objects are typical, the elements can also be
723
+ expressions:
724
+
725
+ .. sourcecode:: pycon+sql
726
+
727
+ >>> stmt = table.insert().returning(
728
+ ... (table.c.first_name + " " + table.c.last_name).label("fullname")
729
+ ... )
730
+ >>> print(stmt)
731
+ {printsql}INSERT INTO some_table (first_name, last_name)
732
+ VALUES (:first_name, :last_name)
733
+ RETURNING some_table.first_name || :first_name_1 || some_table.last_name AS fullname
734
+
735
+ Upon compilation, a RETURNING clause, or database equivalent,
736
+ will be rendered within the statement. For INSERT and UPDATE,
737
+ the values are the newly inserted/updated values. For DELETE,
738
+ the values are those of the rows which were deleted.
739
+
740
+ Upon execution, the values of the columns to be returned are made
741
+ available via the result set and can be iterated using
742
+ :meth:`_engine.CursorResult.fetchone` and similar.
743
+ For DBAPIs which do not
744
+ natively support returning values (i.e. cx_oracle), SQLAlchemy will
745
+ approximate this behavior at the result level so that a reasonable
746
+ amount of behavioral neutrality is provided.
747
+
748
+ Note that not all databases/DBAPIs
749
+ support RETURNING. For those backends with no support,
750
+ an exception is raised upon compilation and/or execution.
751
+ For those who do support it, the functionality across backends
752
+ varies greatly, including restrictions on executemany()
753
+ and other statements which return multiple rows. Please
754
+ read the documentation notes for the database in use in
755
+ order to determine the availability of RETURNING.
756
+
757
+ :param \*cols: series of columns, SQL expressions, or whole tables
758
+ entities to be returned.
759
+ :param sort_by_parameter_order: for a batch INSERT that is being
760
+ executed against multiple parameter sets, organize the results of
761
+ RETURNING so that the returned rows correspond to the order of
762
+ parameter sets passed in. This applies only to an :term:`executemany`
763
+ execution for supporting dialects and typically makes use of the
764
+ :term:`insertmanyvalues` feature.
765
+
766
+ .. versionadded:: 2.0.10
767
+
768
+ .. seealso::
769
+
770
+ :ref:`engine_insertmanyvalues_returning_order` - background on
771
+ sorting of RETURNING rows for bulk INSERT (Core level discussion)
772
+
773
+ :ref:`orm_queryguide_bulk_insert_returning_ordered` - example of
774
+ use with :ref:`orm_queryguide_bulk_insert` (ORM level discussion)
775
+
776
+ .. seealso::
777
+
778
+ :meth:`.UpdateBase.return_defaults` - an alternative method tailored
779
+ towards efficient fetching of server-side defaults and triggers
780
+ for single-row INSERTs or UPDATEs.
781
+
782
+ :ref:`tutorial_insert_returning` - in the :ref:`unified_tutorial`
783
+
784
+ """ # noqa: E501
785
+ if __kw:
786
+ raise _unexpected_kw("UpdateBase.returning()", __kw)
787
+ if self._return_defaults:
788
+ raise exc.InvalidRequestError(
789
+ "return_defaults() is already configured on this statement"
790
+ )
791
+ self._returning += tuple(
792
+ coercions.expect(roles.ColumnsClauseRole, c) for c in cols
793
+ )
794
+ if sort_by_parameter_order:
795
+ if not self.is_insert:
796
+ raise exc.ArgumentError(
797
+ "The 'sort_by_parameter_order' argument to returning() "
798
+ "only applies to INSERT statements"
799
+ )
800
+ self._sort_by_parameter_order = True
801
+ return self
802
+
803
+ def corresponding_column(
804
+ self, column: KeyedColumnElement[Any], require_embedded: bool = False
805
+ ) -> Optional[ColumnElement[Any]]:
806
+ return self.exported_columns.corresponding_column(
807
+ column, require_embedded=require_embedded
808
+ )
809
+
810
+ @util.ro_memoized_property
811
+ def _all_selected_columns(self) -> _SelectIterable:
812
+ return [c for c in _select_iterables(self._returning)]
813
+
814
+ @util.ro_memoized_property
815
+ def exported_columns(
816
+ self,
817
+ ) -> ReadOnlyColumnCollection[Optional[str], ColumnElement[Any]]:
818
+ """Return the RETURNING columns as a column collection for this
819
+ statement.
820
+
821
+ .. versionadded:: 1.4
822
+
823
+ """
824
+ return ColumnCollection(
825
+ (c.key, c)
826
+ for c in self._all_selected_columns
827
+ if is_column_element(c)
828
+ ).as_readonly()
829
+
830
+ @_generative
831
+ def with_hint(
832
+ self,
833
+ text: str,
834
+ selectable: Optional[_DMLTableArgument] = None,
835
+ dialect_name: str = "*",
836
+ ) -> Self:
837
+ """Add a table hint for a single table to this
838
+ INSERT/UPDATE/DELETE statement.
839
+
840
+ .. note::
841
+
842
+ :meth:`.UpdateBase.with_hint` currently applies only to
843
+ Microsoft SQL Server. For MySQL INSERT/UPDATE/DELETE hints, use
844
+ :meth:`.UpdateBase.prefix_with`.
845
+
846
+ The text of the hint is rendered in the appropriate
847
+ location for the database backend in use, relative
848
+ to the :class:`_schema.Table` that is the subject of this
849
+ statement, or optionally to that of the given
850
+ :class:`_schema.Table` passed as the ``selectable`` argument.
851
+
852
+ The ``dialect_name`` option will limit the rendering of a particular
853
+ hint to a particular backend. Such as, to add a hint
854
+ that only takes effect for SQL Server::
855
+
856
+ mytable.insert().with_hint("WITH (PAGLOCK)", dialect_name="mssql")
857
+
858
+ :param text: Text of the hint.
859
+ :param selectable: optional :class:`_schema.Table` that specifies
860
+ an element of the FROM clause within an UPDATE or DELETE
861
+ to be the subject of the hint - applies only to certain backends.
862
+ :param dialect_name: defaults to ``*``, if specified as the name
863
+ of a particular dialect, will apply these hints only when
864
+ that dialect is in use.
865
+ """
866
+ if selectable is None:
867
+ selectable = self.table
868
+ else:
869
+ selectable = coercions.expect(roles.DMLTableRole, selectable)
870
+ self._hints = self._hints.union({(selectable, dialect_name): text})
871
+ return self
872
+
873
+ @property
874
+ def entity_description(self) -> Dict[str, Any]:
875
+ """Return a :term:`plugin-enabled` description of the table and/or
876
+ entity which this DML construct is operating against.
877
+
878
+ This attribute is generally useful when using the ORM, as an
879
+ extended structure which includes information about mapped
880
+ entities is returned. The section :ref:`queryguide_inspection`
881
+ contains more background.
882
+
883
+ For a Core statement, the structure returned by this accessor
884
+ is derived from the :attr:`.UpdateBase.table` attribute, and
885
+ refers to the :class:`.Table` being inserted, updated, or deleted::
886
+
887
+ >>> stmt = insert(user_table)
888
+ >>> stmt.entity_description
889
+ {
890
+ "name": "user_table",
891
+ "table": Table("user_table", ...)
892
+ }
893
+
894
+ .. versionadded:: 1.4.33
895
+
896
+ .. seealso::
897
+
898
+ :attr:`.UpdateBase.returning_column_descriptions`
899
+
900
+ :attr:`.Select.column_descriptions` - entity information for
901
+ a :func:`.select` construct
902
+
903
+ :ref:`queryguide_inspection` - ORM background
904
+
905
+ """
906
+ meth = DMLState.get_plugin_class(self).get_entity_description
907
+ return meth(self)
908
+
909
+ @property
910
+ def returning_column_descriptions(self) -> List[Dict[str, Any]]:
911
+ """Return a :term:`plugin-enabled` description of the columns
912
+ which this DML construct is RETURNING against, in other words
913
+ the expressions established as part of :meth:`.UpdateBase.returning`.
914
+
915
+ This attribute is generally useful when using the ORM, as an
916
+ extended structure which includes information about mapped
917
+ entities is returned. The section :ref:`queryguide_inspection`
918
+ contains more background.
919
+
920
+ For a Core statement, the structure returned by this accessor is
921
+ derived from the same objects that are returned by the
922
+ :attr:`.UpdateBase.exported_columns` accessor::
923
+
924
+ >>> stmt = insert(user_table).returning(user_table.c.id, user_table.c.name)
925
+ >>> stmt.entity_description
926
+ [
927
+ {
928
+ "name": "id",
929
+ "type": Integer,
930
+ "expr": Column("id", Integer(), table=<user>, ...)
931
+ },
932
+ {
933
+ "name": "name",
934
+ "type": String(),
935
+ "expr": Column("name", String(), table=<user>, ...)
936
+ },
937
+ ]
938
+
939
+ .. versionadded:: 1.4.33
940
+
941
+ .. seealso::
942
+
943
+ :attr:`.UpdateBase.entity_description`
944
+
945
+ :attr:`.Select.column_descriptions` - entity information for
946
+ a :func:`.select` construct
947
+
948
+ :ref:`queryguide_inspection` - ORM background
949
+
950
+ """ # noqa: E501
951
+ meth = DMLState.get_plugin_class(
952
+ self
953
+ ).get_returning_column_descriptions
954
+ return meth(self)
955
+
956
+
957
+ class ValuesBase(UpdateBase):
958
+ """Supplies support for :meth:`.ValuesBase.values` to
959
+ INSERT and UPDATE constructs."""
960
+
961
+ __visit_name__ = "values_base"
962
+
963
+ _supports_multi_parameters = False
964
+
965
+ select: Optional[Select[Any]] = None
966
+ """SELECT statement for INSERT .. FROM SELECT"""
967
+
968
+ _post_values_clause: Optional[ClauseElement] = None
969
+ """used by extensions to Insert etc. to add additional syntacitcal
970
+ constructs, e.g. ON CONFLICT etc."""
971
+
972
+ _values: Optional[util.immutabledict[_DMLColumnElement, Any]] = None
973
+ _multi_values: Tuple[
974
+ Union[
975
+ Sequence[Dict[_DMLColumnElement, Any]],
976
+ Sequence[Sequence[Any]],
977
+ ],
978
+ ...,
979
+ ] = ()
980
+
981
+ _ordered_values: Optional[List[Tuple[_DMLColumnElement, Any]]] = None
982
+
983
+ _select_names: Optional[List[str]] = None
984
+ _inline: bool = False
985
+
986
+ def __init__(self, table: _DMLTableArgument):
987
+ self.table = coercions.expect(
988
+ roles.DMLTableRole, table, apply_propagate_attrs=self
989
+ )
990
+
991
+ @_generative
992
+ @_exclusive_against(
993
+ "_select_names",
994
+ "_ordered_values",
995
+ msgs={
996
+ "_select_names": "This construct already inserts from a SELECT",
997
+ "_ordered_values": "This statement already has ordered "
998
+ "values present",
999
+ },
1000
+ )
1001
+ def values(
1002
+ self,
1003
+ *args: Union[
1004
+ _DMLColumnKeyMapping[Any],
1005
+ Sequence[Any],
1006
+ ],
1007
+ **kwargs: Any,
1008
+ ) -> Self:
1009
+ r"""Specify a fixed VALUES clause for an INSERT statement, or the SET
1010
+ clause for an UPDATE.
1011
+
1012
+ Note that the :class:`_expression.Insert` and
1013
+ :class:`_expression.Update`
1014
+ constructs support
1015
+ per-execution time formatting of the VALUES and/or SET clauses,
1016
+ based on the arguments passed to :meth:`_engine.Connection.execute`.
1017
+ However, the :meth:`.ValuesBase.values` method can be used to "fix" a
1018
+ particular set of parameters into the statement.
1019
+
1020
+ Multiple calls to :meth:`.ValuesBase.values` will produce a new
1021
+ construct, each one with the parameter list modified to include
1022
+ the new parameters sent. In the typical case of a single
1023
+ dictionary of parameters, the newly passed keys will replace
1024
+ the same keys in the previous construct. In the case of a list-based
1025
+ "multiple values" construct, each new list of values is extended
1026
+ onto the existing list of values.
1027
+
1028
+ :param \**kwargs: key value pairs representing the string key
1029
+ of a :class:`_schema.Column`
1030
+ mapped to the value to be rendered into the
1031
+ VALUES or SET clause::
1032
+
1033
+ users.insert().values(name="some name")
1034
+
1035
+ users.update().where(users.c.id==5).values(name="some name")
1036
+
1037
+ :param \*args: As an alternative to passing key/value parameters,
1038
+ a dictionary, tuple, or list of dictionaries or tuples can be passed
1039
+ as a single positional argument in order to form the VALUES or
1040
+ SET clause of the statement. The forms that are accepted vary
1041
+ based on whether this is an :class:`_expression.Insert` or an
1042
+ :class:`_expression.Update` construct.
1043
+
1044
+ For either an :class:`_expression.Insert` or
1045
+ :class:`_expression.Update`
1046
+ construct, a single dictionary can be passed, which works the same as
1047
+ that of the kwargs form::
1048
+
1049
+ users.insert().values({"name": "some name"})
1050
+
1051
+ users.update().values({"name": "some new name"})
1052
+
1053
+ Also for either form but more typically for the
1054
+ :class:`_expression.Insert` construct, a tuple that contains an
1055
+ entry for every column in the table is also accepted::
1056
+
1057
+ users.insert().values((5, "some name"))
1058
+
1059
+ The :class:`_expression.Insert` construct also supports being
1060
+ passed a list of dictionaries or full-table-tuples, which on the
1061
+ server will render the less common SQL syntax of "multiple values" -
1062
+ this syntax is supported on backends such as SQLite, PostgreSQL,
1063
+ MySQL, but not necessarily others::
1064
+
1065
+ users.insert().values([
1066
+ {"name": "some name"},
1067
+ {"name": "some other name"},
1068
+ {"name": "yet another name"},
1069
+ ])
1070
+
1071
+ The above form would render a multiple VALUES statement similar to::
1072
+
1073
+ INSERT INTO users (name) VALUES
1074
+ (:name_1),
1075
+ (:name_2),
1076
+ (:name_3)
1077
+
1078
+ It is essential to note that **passing multiple values is
1079
+ NOT the same as using traditional executemany() form**. The above
1080
+ syntax is a **special** syntax not typically used. To emit an
1081
+ INSERT statement against multiple rows, the normal method is
1082
+ to pass a multiple values list to the
1083
+ :meth:`_engine.Connection.execute`
1084
+ method, which is supported by all database backends and is generally
1085
+ more efficient for a very large number of parameters.
1086
+
1087
+ .. seealso::
1088
+
1089
+ :ref:`tutorial_multiple_parameters` - an introduction to
1090
+ the traditional Core method of multiple parameter set
1091
+ invocation for INSERTs and other statements.
1092
+
1093
+ The UPDATE construct also supports rendering the SET parameters
1094
+ in a specific order. For this feature refer to the
1095
+ :meth:`_expression.Update.ordered_values` method.
1096
+
1097
+ .. seealso::
1098
+
1099
+ :meth:`_expression.Update.ordered_values`
1100
+
1101
+
1102
+ """
1103
+ if args:
1104
+ # positional case. this is currently expensive. we don't
1105
+ # yet have positional-only args so we have to check the length.
1106
+ # then we need to check multiparams vs. single dictionary.
1107
+ # since the parameter format is needed in order to determine
1108
+ # a cache key, we need to determine this up front.
1109
+ arg = args[0]
1110
+
1111
+ if kwargs:
1112
+ raise exc.ArgumentError(
1113
+ "Can't pass positional and kwargs to values() "
1114
+ "simultaneously"
1115
+ )
1116
+ elif len(args) > 1:
1117
+ raise exc.ArgumentError(
1118
+ "Only a single dictionary/tuple or list of "
1119
+ "dictionaries/tuples is accepted positionally."
1120
+ )
1121
+
1122
+ elif isinstance(arg, collections_abc.Sequence):
1123
+ if arg and isinstance(arg[0], dict):
1124
+ multi_kv_generator = DMLState.get_plugin_class(
1125
+ self
1126
+ )._get_multi_crud_kv_pairs
1127
+ self._multi_values += (multi_kv_generator(self, arg),)
1128
+ return self
1129
+
1130
+ if arg and isinstance(arg[0], (list, tuple)):
1131
+ self._multi_values += (arg,)
1132
+ return self
1133
+
1134
+ if TYPE_CHECKING:
1135
+ # crud.py raises during compilation if this is not the
1136
+ # case
1137
+ assert isinstance(self, Insert)
1138
+
1139
+ # tuple values
1140
+ arg = {c.key: value for c, value in zip(self.table.c, arg)}
1141
+
1142
+ else:
1143
+ # kwarg path. this is the most common path for non-multi-params
1144
+ # so this is fairly quick.
1145
+ arg = cast("Dict[_DMLColumnArgument, Any]", kwargs)
1146
+ if args:
1147
+ raise exc.ArgumentError(
1148
+ "Only a single dictionary/tuple or list of "
1149
+ "dictionaries/tuples is accepted positionally."
1150
+ )
1151
+
1152
+ # for top level values(), convert literals to anonymous bound
1153
+ # parameters at statement construction time, so that these values can
1154
+ # participate in the cache key process like any other ClauseElement.
1155
+ # crud.py now intercepts bound parameters with unique=True from here
1156
+ # and ensures they get the "crud"-style name when rendered.
1157
+
1158
+ kv_generator = DMLState.get_plugin_class(self)._get_crud_kv_pairs
1159
+ coerced_arg = dict(kv_generator(self, arg.items(), True))
1160
+ if self._values:
1161
+ self._values = self._values.union(coerced_arg)
1162
+ else:
1163
+ self._values = util.immutabledict(coerced_arg)
1164
+ return self
1165
+
1166
+
1167
+ class Insert(ValuesBase):
1168
+ """Represent an INSERT construct.
1169
+
1170
+ The :class:`_expression.Insert` object is created using the
1171
+ :func:`_expression.insert()` function.
1172
+
1173
+ """
1174
+
1175
+ __visit_name__ = "insert"
1176
+
1177
+ _supports_multi_parameters = True
1178
+
1179
+ select = None
1180
+ include_insert_from_select_defaults = False
1181
+
1182
+ _sort_by_parameter_order: bool = False
1183
+
1184
+ is_insert = True
1185
+
1186
+ table: TableClause
1187
+
1188
+ _traverse_internals = (
1189
+ [
1190
+ ("table", InternalTraversal.dp_clauseelement),
1191
+ ("_inline", InternalTraversal.dp_boolean),
1192
+ ("_select_names", InternalTraversal.dp_string_list),
1193
+ ("_values", InternalTraversal.dp_dml_values),
1194
+ ("_multi_values", InternalTraversal.dp_dml_multi_values),
1195
+ ("select", InternalTraversal.dp_clauseelement),
1196
+ ("_post_values_clause", InternalTraversal.dp_clauseelement),
1197
+ ("_returning", InternalTraversal.dp_clauseelement_tuple),
1198
+ ("_hints", InternalTraversal.dp_table_hint_list),
1199
+ ("_return_defaults", InternalTraversal.dp_boolean),
1200
+ (
1201
+ "_return_defaults_columns",
1202
+ InternalTraversal.dp_clauseelement_tuple,
1203
+ ),
1204
+ ("_sort_by_parameter_order", InternalTraversal.dp_boolean),
1205
+ ]
1206
+ + HasPrefixes._has_prefixes_traverse_internals
1207
+ + DialectKWArgs._dialect_kwargs_traverse_internals
1208
+ + Executable._executable_traverse_internals
1209
+ + HasCTE._has_ctes_traverse_internals
1210
+ )
1211
+
1212
+ def __init__(self, table: _DMLTableArgument):
1213
+ super().__init__(table)
1214
+
1215
+ @_generative
1216
+ def inline(self) -> Self:
1217
+ """Make this :class:`_expression.Insert` construct "inline" .
1218
+
1219
+ When set, no attempt will be made to retrieve the
1220
+ SQL-generated default values to be provided within the statement;
1221
+ in particular,
1222
+ this allows SQL expressions to be rendered 'inline' within the
1223
+ statement without the need to pre-execute them beforehand; for
1224
+ backends that support "returning", this turns off the "implicit
1225
+ returning" feature for the statement.
1226
+
1227
+
1228
+ .. versionchanged:: 1.4 the :paramref:`_expression.Insert.inline`
1229
+ parameter
1230
+ is now superseded by the :meth:`_expression.Insert.inline` method.
1231
+
1232
+ """
1233
+ self._inline = True
1234
+ return self
1235
+
1236
+ @_generative
1237
+ def from_select(
1238
+ self,
1239
+ names: Sequence[_DMLColumnArgument],
1240
+ select: Selectable,
1241
+ include_defaults: bool = True,
1242
+ ) -> Self:
1243
+ """Return a new :class:`_expression.Insert` construct which represents
1244
+ an ``INSERT...FROM SELECT`` statement.
1245
+
1246
+ e.g.::
1247
+
1248
+ sel = select(table1.c.a, table1.c.b).where(table1.c.c > 5)
1249
+ ins = table2.insert().from_select(['a', 'b'], sel)
1250
+
1251
+ :param names: a sequence of string column names or
1252
+ :class:`_schema.Column`
1253
+ objects representing the target columns.
1254
+ :param select: a :func:`_expression.select` construct,
1255
+ :class:`_expression.FromClause`
1256
+ or other construct which resolves into a
1257
+ :class:`_expression.FromClause`,
1258
+ such as an ORM :class:`_query.Query` object, etc. The order of
1259
+ columns returned from this FROM clause should correspond to the
1260
+ order of columns sent as the ``names`` parameter; while this
1261
+ is not checked before passing along to the database, the database
1262
+ would normally raise an exception if these column lists don't
1263
+ correspond.
1264
+ :param include_defaults: if True, non-server default values and
1265
+ SQL expressions as specified on :class:`_schema.Column` objects
1266
+ (as documented in :ref:`metadata_defaults_toplevel`) not
1267
+ otherwise specified in the list of names will be rendered
1268
+ into the INSERT and SELECT statements, so that these values are also
1269
+ included in the data to be inserted.
1270
+
1271
+ .. note:: A Python-side default that uses a Python callable function
1272
+ will only be invoked **once** for the whole statement, and **not
1273
+ per row**.
1274
+
1275
+ """
1276
+
1277
+ if self._values:
1278
+ raise exc.InvalidRequestError(
1279
+ "This construct already inserts value expressions"
1280
+ )
1281
+
1282
+ self._select_names = [
1283
+ coercions.expect(roles.DMLColumnRole, name, as_key=True)
1284
+ for name in names
1285
+ ]
1286
+ self._inline = True
1287
+ self.include_insert_from_select_defaults = include_defaults
1288
+ self.select = coercions.expect(roles.DMLSelectRole, select)
1289
+ return self
1290
+
1291
+ if TYPE_CHECKING:
1292
+ # START OVERLOADED FUNCTIONS self.returning ReturningInsert 1-8 ", *, sort_by_parameter_order: bool = False" # noqa: E501
1293
+
1294
+ # code within this block is **programmatically,
1295
+ # statically generated** by tools/generate_tuple_map_overloads.py
1296
+
1297
+ @overload
1298
+ def returning(
1299
+ self, __ent0: _TCCA[_T0], *, sort_by_parameter_order: bool = False
1300
+ ) -> ReturningInsert[Tuple[_T0]]: ...
1301
+
1302
+ @overload
1303
+ def returning(
1304
+ self,
1305
+ __ent0: _TCCA[_T0],
1306
+ __ent1: _TCCA[_T1],
1307
+ *,
1308
+ sort_by_parameter_order: bool = False,
1309
+ ) -> ReturningInsert[Tuple[_T0, _T1]]: ...
1310
+
1311
+ @overload
1312
+ def returning(
1313
+ self,
1314
+ __ent0: _TCCA[_T0],
1315
+ __ent1: _TCCA[_T1],
1316
+ __ent2: _TCCA[_T2],
1317
+ *,
1318
+ sort_by_parameter_order: bool = False,
1319
+ ) -> ReturningInsert[Tuple[_T0, _T1, _T2]]: ...
1320
+
1321
+ @overload
1322
+ def returning(
1323
+ self,
1324
+ __ent0: _TCCA[_T0],
1325
+ __ent1: _TCCA[_T1],
1326
+ __ent2: _TCCA[_T2],
1327
+ __ent3: _TCCA[_T3],
1328
+ *,
1329
+ sort_by_parameter_order: bool = False,
1330
+ ) -> ReturningInsert[Tuple[_T0, _T1, _T2, _T3]]: ...
1331
+
1332
+ @overload
1333
+ def returning(
1334
+ self,
1335
+ __ent0: _TCCA[_T0],
1336
+ __ent1: _TCCA[_T1],
1337
+ __ent2: _TCCA[_T2],
1338
+ __ent3: _TCCA[_T3],
1339
+ __ent4: _TCCA[_T4],
1340
+ *,
1341
+ sort_by_parameter_order: bool = False,
1342
+ ) -> ReturningInsert[Tuple[_T0, _T1, _T2, _T3, _T4]]: ...
1343
+
1344
+ @overload
1345
+ def returning(
1346
+ self,
1347
+ __ent0: _TCCA[_T0],
1348
+ __ent1: _TCCA[_T1],
1349
+ __ent2: _TCCA[_T2],
1350
+ __ent3: _TCCA[_T3],
1351
+ __ent4: _TCCA[_T4],
1352
+ __ent5: _TCCA[_T5],
1353
+ *,
1354
+ sort_by_parameter_order: bool = False,
1355
+ ) -> ReturningInsert[Tuple[_T0, _T1, _T2, _T3, _T4, _T5]]: ...
1356
+
1357
+ @overload
1358
+ def returning(
1359
+ self,
1360
+ __ent0: _TCCA[_T0],
1361
+ __ent1: _TCCA[_T1],
1362
+ __ent2: _TCCA[_T2],
1363
+ __ent3: _TCCA[_T3],
1364
+ __ent4: _TCCA[_T4],
1365
+ __ent5: _TCCA[_T5],
1366
+ __ent6: _TCCA[_T6],
1367
+ *,
1368
+ sort_by_parameter_order: bool = False,
1369
+ ) -> ReturningInsert[Tuple[_T0, _T1, _T2, _T3, _T4, _T5, _T6]]: ...
1370
+
1371
+ @overload
1372
+ def returning(
1373
+ self,
1374
+ __ent0: _TCCA[_T0],
1375
+ __ent1: _TCCA[_T1],
1376
+ __ent2: _TCCA[_T2],
1377
+ __ent3: _TCCA[_T3],
1378
+ __ent4: _TCCA[_T4],
1379
+ __ent5: _TCCA[_T5],
1380
+ __ent6: _TCCA[_T6],
1381
+ __ent7: _TCCA[_T7],
1382
+ *,
1383
+ sort_by_parameter_order: bool = False,
1384
+ ) -> ReturningInsert[
1385
+ Tuple[_T0, _T1, _T2, _T3, _T4, _T5, _T6, _T7]
1386
+ ]: ...
1387
+
1388
+ # END OVERLOADED FUNCTIONS self.returning
1389
+
1390
+ @overload
1391
+ def returning(
1392
+ self,
1393
+ *cols: _ColumnsClauseArgument[Any],
1394
+ sort_by_parameter_order: bool = False,
1395
+ **__kw: Any,
1396
+ ) -> ReturningInsert[Any]: ...
1397
+
1398
+ def returning(
1399
+ self,
1400
+ *cols: _ColumnsClauseArgument[Any],
1401
+ sort_by_parameter_order: bool = False,
1402
+ **__kw: Any,
1403
+ ) -> ReturningInsert[Any]: ...
1404
+
1405
+
1406
+ class ReturningInsert(Insert, TypedReturnsRows[_TP]):
1407
+ """Typing-only class that establishes a generic type form of
1408
+ :class:`.Insert` which tracks returned column types.
1409
+
1410
+ This datatype is delivered when calling the
1411
+ :meth:`.Insert.returning` method.
1412
+
1413
+ .. versionadded:: 2.0
1414
+
1415
+ """
1416
+
1417
+
1418
+ class DMLWhereBase:
1419
+ table: _DMLTableElement
1420
+ _where_criteria: Tuple[ColumnElement[Any], ...] = ()
1421
+
1422
+ @_generative
1423
+ def where(self, *whereclause: _ColumnExpressionArgument[bool]) -> Self:
1424
+ """Return a new construct with the given expression(s) added to
1425
+ its WHERE clause, joined to the existing clause via AND, if any.
1426
+
1427
+ Both :meth:`_dml.Update.where` and :meth:`_dml.Delete.where`
1428
+ support multiple-table forms, including database-specific
1429
+ ``UPDATE...FROM`` as well as ``DELETE..USING``. For backends that
1430
+ don't have multiple-table support, a backend agnostic approach
1431
+ to using multiple tables is to make use of correlated subqueries.
1432
+ See the linked tutorial sections below for examples.
1433
+
1434
+ .. seealso::
1435
+
1436
+ :ref:`tutorial_correlated_updates`
1437
+
1438
+ :ref:`tutorial_update_from`
1439
+
1440
+ :ref:`tutorial_multi_table_deletes`
1441
+
1442
+ """
1443
+
1444
+ for criterion in whereclause:
1445
+ where_criteria: ColumnElement[Any] = coercions.expect(
1446
+ roles.WhereHavingRole, criterion, apply_propagate_attrs=self
1447
+ )
1448
+ self._where_criteria += (where_criteria,)
1449
+ return self
1450
+
1451
+ def filter(self, *criteria: roles.ExpressionElementRole[Any]) -> Self:
1452
+ """A synonym for the :meth:`_dml.DMLWhereBase.where` method.
1453
+
1454
+ .. versionadded:: 1.4
1455
+
1456
+ """
1457
+
1458
+ return self.where(*criteria)
1459
+
1460
+ def _filter_by_zero(self) -> _DMLTableElement:
1461
+ return self.table
1462
+
1463
+ def filter_by(self, **kwargs: Any) -> Self:
1464
+ r"""apply the given filtering criterion as a WHERE clause
1465
+ to this select.
1466
+
1467
+ """
1468
+ from_entity = self._filter_by_zero()
1469
+
1470
+ clauses = [
1471
+ _entity_namespace_key(from_entity, key) == value
1472
+ for key, value in kwargs.items()
1473
+ ]
1474
+ return self.filter(*clauses)
1475
+
1476
+ @property
1477
+ def whereclause(self) -> Optional[ColumnElement[Any]]:
1478
+ """Return the completed WHERE clause for this :class:`.DMLWhereBase`
1479
+ statement.
1480
+
1481
+ This assembles the current collection of WHERE criteria
1482
+ into a single :class:`_expression.BooleanClauseList` construct.
1483
+
1484
+
1485
+ .. versionadded:: 1.4
1486
+
1487
+ """
1488
+
1489
+ return BooleanClauseList._construct_for_whereclause(
1490
+ self._where_criteria
1491
+ )
1492
+
1493
+
1494
+ class Update(DMLWhereBase, ValuesBase):
1495
+ """Represent an Update construct.
1496
+
1497
+ The :class:`_expression.Update` object is created using the
1498
+ :func:`_expression.update()` function.
1499
+
1500
+ """
1501
+
1502
+ __visit_name__ = "update"
1503
+
1504
+ is_update = True
1505
+
1506
+ _traverse_internals = (
1507
+ [
1508
+ ("table", InternalTraversal.dp_clauseelement),
1509
+ ("_where_criteria", InternalTraversal.dp_clauseelement_tuple),
1510
+ ("_inline", InternalTraversal.dp_boolean),
1511
+ ("_ordered_values", InternalTraversal.dp_dml_ordered_values),
1512
+ ("_values", InternalTraversal.dp_dml_values),
1513
+ ("_returning", InternalTraversal.dp_clauseelement_tuple),
1514
+ ("_hints", InternalTraversal.dp_table_hint_list),
1515
+ ("_return_defaults", InternalTraversal.dp_boolean),
1516
+ (
1517
+ "_return_defaults_columns",
1518
+ InternalTraversal.dp_clauseelement_tuple,
1519
+ ),
1520
+ ]
1521
+ + HasPrefixes._has_prefixes_traverse_internals
1522
+ + DialectKWArgs._dialect_kwargs_traverse_internals
1523
+ + Executable._executable_traverse_internals
1524
+ + HasCTE._has_ctes_traverse_internals
1525
+ )
1526
+
1527
+ def __init__(self, table: _DMLTableArgument):
1528
+ super().__init__(table)
1529
+
1530
+ @_generative
1531
+ def ordered_values(self, *args: Tuple[_DMLColumnArgument, Any]) -> Self:
1532
+ """Specify the VALUES clause of this UPDATE statement with an explicit
1533
+ parameter ordering that will be maintained in the SET clause of the
1534
+ resulting UPDATE statement.
1535
+
1536
+ E.g.::
1537
+
1538
+ stmt = table.update().ordered_values(
1539
+ ("name", "ed"), ("ident", "foo")
1540
+ )
1541
+
1542
+ .. seealso::
1543
+
1544
+ :ref:`tutorial_parameter_ordered_updates` - full example of the
1545
+ :meth:`_expression.Update.ordered_values` method.
1546
+
1547
+ .. versionchanged:: 1.4 The :meth:`_expression.Update.ordered_values`
1548
+ method
1549
+ supersedes the
1550
+ :paramref:`_expression.update.preserve_parameter_order`
1551
+ parameter, which will be removed in SQLAlchemy 2.0.
1552
+
1553
+ """
1554
+ if self._values:
1555
+ raise exc.ArgumentError(
1556
+ "This statement already has values present"
1557
+ )
1558
+ elif self._ordered_values:
1559
+ raise exc.ArgumentError(
1560
+ "This statement already has ordered values present"
1561
+ )
1562
+
1563
+ kv_generator = DMLState.get_plugin_class(self)._get_crud_kv_pairs
1564
+ self._ordered_values = kv_generator(self, args, True)
1565
+ return self
1566
+
1567
+ @_generative
1568
+ def inline(self) -> Self:
1569
+ """Make this :class:`_expression.Update` construct "inline" .
1570
+
1571
+ When set, SQL defaults present on :class:`_schema.Column`
1572
+ objects via the
1573
+ ``default`` keyword will be compiled 'inline' into the statement and
1574
+ not pre-executed. This means that their values will not be available
1575
+ in the dictionary returned from
1576
+ :meth:`_engine.CursorResult.last_updated_params`.
1577
+
1578
+ .. versionchanged:: 1.4 the :paramref:`_expression.update.inline`
1579
+ parameter
1580
+ is now superseded by the :meth:`_expression.Update.inline` method.
1581
+
1582
+ """
1583
+ self._inline = True
1584
+ return self
1585
+
1586
+ if TYPE_CHECKING:
1587
+ # START OVERLOADED FUNCTIONS self.returning ReturningUpdate 1-8
1588
+
1589
+ # code within this block is **programmatically,
1590
+ # statically generated** by tools/generate_tuple_map_overloads.py
1591
+
1592
+ @overload
1593
+ def returning(
1594
+ self, __ent0: _TCCA[_T0]
1595
+ ) -> ReturningUpdate[Tuple[_T0]]: ...
1596
+
1597
+ @overload
1598
+ def returning(
1599
+ self, __ent0: _TCCA[_T0], __ent1: _TCCA[_T1]
1600
+ ) -> ReturningUpdate[Tuple[_T0, _T1]]: ...
1601
+
1602
+ @overload
1603
+ def returning(
1604
+ self, __ent0: _TCCA[_T0], __ent1: _TCCA[_T1], __ent2: _TCCA[_T2]
1605
+ ) -> ReturningUpdate[Tuple[_T0, _T1, _T2]]: ...
1606
+
1607
+ @overload
1608
+ def returning(
1609
+ self,
1610
+ __ent0: _TCCA[_T0],
1611
+ __ent1: _TCCA[_T1],
1612
+ __ent2: _TCCA[_T2],
1613
+ __ent3: _TCCA[_T3],
1614
+ ) -> ReturningUpdate[Tuple[_T0, _T1, _T2, _T3]]: ...
1615
+
1616
+ @overload
1617
+ def returning(
1618
+ self,
1619
+ __ent0: _TCCA[_T0],
1620
+ __ent1: _TCCA[_T1],
1621
+ __ent2: _TCCA[_T2],
1622
+ __ent3: _TCCA[_T3],
1623
+ __ent4: _TCCA[_T4],
1624
+ ) -> ReturningUpdate[Tuple[_T0, _T1, _T2, _T3, _T4]]: ...
1625
+
1626
+ @overload
1627
+ def returning(
1628
+ self,
1629
+ __ent0: _TCCA[_T0],
1630
+ __ent1: _TCCA[_T1],
1631
+ __ent2: _TCCA[_T2],
1632
+ __ent3: _TCCA[_T3],
1633
+ __ent4: _TCCA[_T4],
1634
+ __ent5: _TCCA[_T5],
1635
+ ) -> ReturningUpdate[Tuple[_T0, _T1, _T2, _T3, _T4, _T5]]: ...
1636
+
1637
+ @overload
1638
+ def returning(
1639
+ self,
1640
+ __ent0: _TCCA[_T0],
1641
+ __ent1: _TCCA[_T1],
1642
+ __ent2: _TCCA[_T2],
1643
+ __ent3: _TCCA[_T3],
1644
+ __ent4: _TCCA[_T4],
1645
+ __ent5: _TCCA[_T5],
1646
+ __ent6: _TCCA[_T6],
1647
+ ) -> ReturningUpdate[Tuple[_T0, _T1, _T2, _T3, _T4, _T5, _T6]]: ...
1648
+
1649
+ @overload
1650
+ def returning(
1651
+ self,
1652
+ __ent0: _TCCA[_T0],
1653
+ __ent1: _TCCA[_T1],
1654
+ __ent2: _TCCA[_T2],
1655
+ __ent3: _TCCA[_T3],
1656
+ __ent4: _TCCA[_T4],
1657
+ __ent5: _TCCA[_T5],
1658
+ __ent6: _TCCA[_T6],
1659
+ __ent7: _TCCA[_T7],
1660
+ ) -> ReturningUpdate[
1661
+ Tuple[_T0, _T1, _T2, _T3, _T4, _T5, _T6, _T7]
1662
+ ]: ...
1663
+
1664
+ # END OVERLOADED FUNCTIONS self.returning
1665
+
1666
+ @overload
1667
+ def returning(
1668
+ self, *cols: _ColumnsClauseArgument[Any], **__kw: Any
1669
+ ) -> ReturningUpdate[Any]: ...
1670
+
1671
+ def returning(
1672
+ self, *cols: _ColumnsClauseArgument[Any], **__kw: Any
1673
+ ) -> ReturningUpdate[Any]: ...
1674
+
1675
+
1676
+ class ReturningUpdate(Update, TypedReturnsRows[_TP]):
1677
+ """Typing-only class that establishes a generic type form of
1678
+ :class:`.Update` which tracks returned column types.
1679
+
1680
+ This datatype is delivered when calling the
1681
+ :meth:`.Update.returning` method.
1682
+
1683
+ .. versionadded:: 2.0
1684
+
1685
+ """
1686
+
1687
+
1688
+ class Delete(DMLWhereBase, UpdateBase):
1689
+ """Represent a DELETE construct.
1690
+
1691
+ The :class:`_expression.Delete` object is created using the
1692
+ :func:`_expression.delete()` function.
1693
+
1694
+ """
1695
+
1696
+ __visit_name__ = "delete"
1697
+
1698
+ is_delete = True
1699
+
1700
+ _traverse_internals = (
1701
+ [
1702
+ ("table", InternalTraversal.dp_clauseelement),
1703
+ ("_where_criteria", InternalTraversal.dp_clauseelement_tuple),
1704
+ ("_returning", InternalTraversal.dp_clauseelement_tuple),
1705
+ ("_hints", InternalTraversal.dp_table_hint_list),
1706
+ ]
1707
+ + HasPrefixes._has_prefixes_traverse_internals
1708
+ + DialectKWArgs._dialect_kwargs_traverse_internals
1709
+ + Executable._executable_traverse_internals
1710
+ + HasCTE._has_ctes_traverse_internals
1711
+ )
1712
+
1713
+ def __init__(self, table: _DMLTableArgument):
1714
+ self.table = coercions.expect(
1715
+ roles.DMLTableRole, table, apply_propagate_attrs=self
1716
+ )
1717
+
1718
+ if TYPE_CHECKING:
1719
+ # START OVERLOADED FUNCTIONS self.returning ReturningDelete 1-8
1720
+
1721
+ # code within this block is **programmatically,
1722
+ # statically generated** by tools/generate_tuple_map_overloads.py
1723
+
1724
+ @overload
1725
+ def returning(
1726
+ self, __ent0: _TCCA[_T0]
1727
+ ) -> ReturningDelete[Tuple[_T0]]: ...
1728
+
1729
+ @overload
1730
+ def returning(
1731
+ self, __ent0: _TCCA[_T0], __ent1: _TCCA[_T1]
1732
+ ) -> ReturningDelete[Tuple[_T0, _T1]]: ...
1733
+
1734
+ @overload
1735
+ def returning(
1736
+ self, __ent0: _TCCA[_T0], __ent1: _TCCA[_T1], __ent2: _TCCA[_T2]
1737
+ ) -> ReturningDelete[Tuple[_T0, _T1, _T2]]: ...
1738
+
1739
+ @overload
1740
+ def returning(
1741
+ self,
1742
+ __ent0: _TCCA[_T0],
1743
+ __ent1: _TCCA[_T1],
1744
+ __ent2: _TCCA[_T2],
1745
+ __ent3: _TCCA[_T3],
1746
+ ) -> ReturningDelete[Tuple[_T0, _T1, _T2, _T3]]: ...
1747
+
1748
+ @overload
1749
+ def returning(
1750
+ self,
1751
+ __ent0: _TCCA[_T0],
1752
+ __ent1: _TCCA[_T1],
1753
+ __ent2: _TCCA[_T2],
1754
+ __ent3: _TCCA[_T3],
1755
+ __ent4: _TCCA[_T4],
1756
+ ) -> ReturningDelete[Tuple[_T0, _T1, _T2, _T3, _T4]]: ...
1757
+
1758
+ @overload
1759
+ def returning(
1760
+ self,
1761
+ __ent0: _TCCA[_T0],
1762
+ __ent1: _TCCA[_T1],
1763
+ __ent2: _TCCA[_T2],
1764
+ __ent3: _TCCA[_T3],
1765
+ __ent4: _TCCA[_T4],
1766
+ __ent5: _TCCA[_T5],
1767
+ ) -> ReturningDelete[Tuple[_T0, _T1, _T2, _T3, _T4, _T5]]: ...
1768
+
1769
+ @overload
1770
+ def returning(
1771
+ self,
1772
+ __ent0: _TCCA[_T0],
1773
+ __ent1: _TCCA[_T1],
1774
+ __ent2: _TCCA[_T2],
1775
+ __ent3: _TCCA[_T3],
1776
+ __ent4: _TCCA[_T4],
1777
+ __ent5: _TCCA[_T5],
1778
+ __ent6: _TCCA[_T6],
1779
+ ) -> ReturningDelete[Tuple[_T0, _T1, _T2, _T3, _T4, _T5, _T6]]: ...
1780
+
1781
+ @overload
1782
+ def returning(
1783
+ self,
1784
+ __ent0: _TCCA[_T0],
1785
+ __ent1: _TCCA[_T1],
1786
+ __ent2: _TCCA[_T2],
1787
+ __ent3: _TCCA[_T3],
1788
+ __ent4: _TCCA[_T4],
1789
+ __ent5: _TCCA[_T5],
1790
+ __ent6: _TCCA[_T6],
1791
+ __ent7: _TCCA[_T7],
1792
+ ) -> ReturningDelete[
1793
+ Tuple[_T0, _T1, _T2, _T3, _T4, _T5, _T6, _T7]
1794
+ ]: ...
1795
+
1796
+ # END OVERLOADED FUNCTIONS self.returning
1797
+
1798
+ @overload
1799
+ def returning(
1800
+ self, *cols: _ColumnsClauseArgument[Any], **__kw: Any
1801
+ ) -> ReturningDelete[Any]: ...
1802
+
1803
+ def returning(
1804
+ self, *cols: _ColumnsClauseArgument[Any], **__kw: Any
1805
+ ) -> ReturningDelete[Any]: ...
1806
+
1807
+
1808
+ class ReturningDelete(Update, TypedReturnsRows[_TP]):
1809
+ """Typing-only class that establishes a generic type form of
1810
+ :class:`.Delete` which tracks returned column types.
1811
+
1812
+ This datatype is delivered when calling the
1813
+ :meth:`.Delete.returning` method.
1814
+
1815
+ .. versionadded:: 2.0
1816
+
1817
+ """