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
@@ -0,0 +1,1850 @@
1
+ # sql/_elements_constructors.py
2
+ # Copyright (C) 2005-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
+ from __future__ import annotations
9
+
10
+ import typing
11
+ from typing import Any
12
+ from typing import Callable
13
+ from typing import Mapping
14
+ from typing import Optional
15
+ from typing import overload
16
+ from typing import Sequence
17
+ from typing import Tuple as typing_Tuple
18
+ from typing import TYPE_CHECKING
19
+ from typing import TypeVar
20
+ from typing import Union
21
+
22
+ from . import coercions
23
+ from . import roles
24
+ from .base import _NoArg
25
+ from .coercions import _document_text_coercion
26
+ from .elements import BindParameter
27
+ from .elements import BooleanClauseList
28
+ from .elements import Case
29
+ from .elements import Cast
30
+ from .elements import CollationClause
31
+ from .elements import CollectionAggregate
32
+ from .elements import ColumnClause
33
+ from .elements import ColumnElement
34
+ from .elements import Extract
35
+ from .elements import False_
36
+ from .elements import FunctionFilter
37
+ from .elements import Label
38
+ from .elements import Null
39
+ from .elements import Over
40
+ from .elements import TextClause
41
+ from .elements import True_
42
+ from .elements import TryCast
43
+ from .elements import Tuple
44
+ from .elements import TypeCoerce
45
+ from .elements import UnaryExpression
46
+ from .elements import WithinGroup
47
+ from .functions import FunctionElement
48
+ from ..util.typing import Literal
49
+
50
+ if typing.TYPE_CHECKING:
51
+ from ._typing import _ByArgument
52
+ from ._typing import _ColumnExpressionArgument
53
+ from ._typing import _ColumnExpressionOrLiteralArgument
54
+ from ._typing import _ColumnExpressionOrStrLabelArgument
55
+ from ._typing import _TypeEngineArgument
56
+ from .elements import BinaryExpression
57
+ from .selectable import FromClause
58
+ from .type_api import TypeEngine
59
+
60
+ _T = TypeVar("_T")
61
+
62
+
63
+ def all_(expr: _ColumnExpressionArgument[_T]) -> CollectionAggregate[bool]:
64
+ """Produce an ALL expression.
65
+
66
+ For dialects such as that of PostgreSQL, this operator applies
67
+ to usage of the :class:`_types.ARRAY` datatype, for that of
68
+ MySQL, it may apply to a subquery. e.g.::
69
+
70
+ # renders on PostgreSQL:
71
+ # '5 = ALL (somearray)'
72
+ expr = 5 == all_(mytable.c.somearray)
73
+
74
+ # renders on MySQL:
75
+ # '5 = ALL (SELECT value FROM table)'
76
+ expr = 5 == all_(select(table.c.value))
77
+
78
+ Comparison to NULL may work using ``None``::
79
+
80
+ None == all_(mytable.c.somearray)
81
+
82
+ The any_() / all_() operators also feature a special "operand flipping"
83
+ behavior such that if any_() / all_() are used on the left side of a
84
+ comparison using a standalone operator such as ``==``, ``!=``, etc.
85
+ (not including operator methods such as
86
+ :meth:`_sql.ColumnOperators.is_`) the rendered expression is flipped::
87
+
88
+ # would render '5 = ALL (column)`
89
+ all_(mytable.c.column) == 5
90
+
91
+ Or with ``None``, which note will not perform
92
+ the usual step of rendering "IS" as is normally the case for NULL::
93
+
94
+ # would render 'NULL = ALL(somearray)'
95
+ all_(mytable.c.somearray) == None
96
+
97
+ .. versionchanged:: 1.4.26 repaired the use of any_() / all_()
98
+ comparing to NULL on the right side to be flipped to the left.
99
+
100
+ The column-level :meth:`_sql.ColumnElement.all_` method (not to be
101
+ confused with :class:`_types.ARRAY` level
102
+ :meth:`_types.ARRAY.Comparator.all`) is shorthand for
103
+ ``all_(col)``::
104
+
105
+ 5 == mytable.c.somearray.all_()
106
+
107
+ .. seealso::
108
+
109
+ :meth:`_sql.ColumnOperators.all_`
110
+
111
+ :func:`_expression.any_`
112
+
113
+ """
114
+ return CollectionAggregate._create_all(expr)
115
+
116
+
117
+ def and_( # type: ignore[empty-body]
118
+ initial_clause: Union[Literal[True], _ColumnExpressionArgument[bool]],
119
+ *clauses: _ColumnExpressionArgument[bool],
120
+ ) -> ColumnElement[bool]:
121
+ r"""Produce a conjunction of expressions joined by ``AND``.
122
+
123
+ E.g.::
124
+
125
+ from sqlalchemy import and_
126
+
127
+ stmt = select(users_table).where(
128
+ and_(
129
+ users_table.c.name == 'wendy',
130
+ users_table.c.enrolled == True
131
+ )
132
+ )
133
+
134
+ The :func:`.and_` conjunction is also available using the
135
+ Python ``&`` operator (though note that compound expressions
136
+ need to be parenthesized in order to function with Python
137
+ operator precedence behavior)::
138
+
139
+ stmt = select(users_table).where(
140
+ (users_table.c.name == 'wendy') &
141
+ (users_table.c.enrolled == True)
142
+ )
143
+
144
+ The :func:`.and_` operation is also implicit in some cases;
145
+ the :meth:`_expression.Select.where`
146
+ method for example can be invoked multiple
147
+ times against a statement, which will have the effect of each
148
+ clause being combined using :func:`.and_`::
149
+
150
+ stmt = select(users_table).\
151
+ where(users_table.c.name == 'wendy').\
152
+ where(users_table.c.enrolled == True)
153
+
154
+ The :func:`.and_` construct must be given at least one positional
155
+ argument in order to be valid; a :func:`.and_` construct with no
156
+ arguments is ambiguous. To produce an "empty" or dynamically
157
+ generated :func:`.and_` expression, from a given list of expressions,
158
+ a "default" element of :func:`_sql.true` (or just ``True``) should be
159
+ specified::
160
+
161
+ from sqlalchemy import true
162
+ criteria = and_(true(), *expressions)
163
+
164
+ The above expression will compile to SQL as the expression ``true``
165
+ or ``1 = 1``, depending on backend, if no other expressions are
166
+ present. If expressions are present, then the :func:`_sql.true` value is
167
+ ignored as it does not affect the outcome of an AND expression that
168
+ has other elements.
169
+
170
+ .. deprecated:: 1.4 The :func:`.and_` element now requires that at
171
+ least one argument is passed; creating the :func:`.and_` construct
172
+ with no arguments is deprecated, and will emit a deprecation warning
173
+ while continuing to produce a blank SQL string.
174
+
175
+ .. seealso::
176
+
177
+ :func:`.or_`
178
+
179
+ """
180
+ ...
181
+
182
+
183
+ if not TYPE_CHECKING:
184
+ # handle deprecated case which allows zero-arguments
185
+ def and_(*clauses): # noqa: F811
186
+ r"""Produce a conjunction of expressions joined by ``AND``.
187
+
188
+ E.g.::
189
+
190
+ from sqlalchemy import and_
191
+
192
+ stmt = select(users_table).where(
193
+ and_(
194
+ users_table.c.name == 'wendy',
195
+ users_table.c.enrolled == True
196
+ )
197
+ )
198
+
199
+ The :func:`.and_` conjunction is also available using the
200
+ Python ``&`` operator (though note that compound expressions
201
+ need to be parenthesized in order to function with Python
202
+ operator precedence behavior)::
203
+
204
+ stmt = select(users_table).where(
205
+ (users_table.c.name == 'wendy') &
206
+ (users_table.c.enrolled == True)
207
+ )
208
+
209
+ The :func:`.and_` operation is also implicit in some cases;
210
+ the :meth:`_expression.Select.where`
211
+ method for example can be invoked multiple
212
+ times against a statement, which will have the effect of each
213
+ clause being combined using :func:`.and_`::
214
+
215
+ stmt = select(users_table).\
216
+ where(users_table.c.name == 'wendy').\
217
+ where(users_table.c.enrolled == True)
218
+
219
+ The :func:`.and_` construct must be given at least one positional
220
+ argument in order to be valid; a :func:`.and_` construct with no
221
+ arguments is ambiguous. To produce an "empty" or dynamically
222
+ generated :func:`.and_` expression, from a given list of expressions,
223
+ a "default" element of :func:`_sql.true` (or just ``True``) should be
224
+ specified::
225
+
226
+ from sqlalchemy import true
227
+ criteria = and_(true(), *expressions)
228
+
229
+ The above expression will compile to SQL as the expression ``true``
230
+ or ``1 = 1``, depending on backend, if no other expressions are
231
+ present. If expressions are present, then the :func:`_sql.true` value
232
+ is ignored as it does not affect the outcome of an AND expression that
233
+ has other elements.
234
+
235
+ .. deprecated:: 1.4 The :func:`.and_` element now requires that at
236
+ least one argument is passed; creating the :func:`.and_` construct
237
+ with no arguments is deprecated, and will emit a deprecation warning
238
+ while continuing to produce a blank SQL string.
239
+
240
+ .. seealso::
241
+
242
+ :func:`.or_`
243
+
244
+ """
245
+ return BooleanClauseList.and_(*clauses)
246
+
247
+
248
+ def any_(expr: _ColumnExpressionArgument[_T]) -> CollectionAggregate[bool]:
249
+ """Produce an ANY expression.
250
+
251
+ For dialects such as that of PostgreSQL, this operator applies
252
+ to usage of the :class:`_types.ARRAY` datatype, for that of
253
+ MySQL, it may apply to a subquery. e.g.::
254
+
255
+ # renders on PostgreSQL:
256
+ # '5 = ANY (somearray)'
257
+ expr = 5 == any_(mytable.c.somearray)
258
+
259
+ # renders on MySQL:
260
+ # '5 = ANY (SELECT value FROM table)'
261
+ expr = 5 == any_(select(table.c.value))
262
+
263
+ Comparison to NULL may work using ``None`` or :func:`_sql.null`::
264
+
265
+ None == any_(mytable.c.somearray)
266
+
267
+ The any_() / all_() operators also feature a special "operand flipping"
268
+ behavior such that if any_() / all_() are used on the left side of a
269
+ comparison using a standalone operator such as ``==``, ``!=``, etc.
270
+ (not including operator methods such as
271
+ :meth:`_sql.ColumnOperators.is_`) the rendered expression is flipped::
272
+
273
+ # would render '5 = ANY (column)`
274
+ any_(mytable.c.column) == 5
275
+
276
+ Or with ``None``, which note will not perform
277
+ the usual step of rendering "IS" as is normally the case for NULL::
278
+
279
+ # would render 'NULL = ANY(somearray)'
280
+ any_(mytable.c.somearray) == None
281
+
282
+ .. versionchanged:: 1.4.26 repaired the use of any_() / all_()
283
+ comparing to NULL on the right side to be flipped to the left.
284
+
285
+ The column-level :meth:`_sql.ColumnElement.any_` method (not to be
286
+ confused with :class:`_types.ARRAY` level
287
+ :meth:`_types.ARRAY.Comparator.any`) is shorthand for
288
+ ``any_(col)``::
289
+
290
+ 5 = mytable.c.somearray.any_()
291
+
292
+ .. seealso::
293
+
294
+ :meth:`_sql.ColumnOperators.any_`
295
+
296
+ :func:`_expression.all_`
297
+
298
+ """
299
+ return CollectionAggregate._create_any(expr)
300
+
301
+
302
+ def asc(
303
+ column: _ColumnExpressionOrStrLabelArgument[_T],
304
+ ) -> UnaryExpression[_T]:
305
+ """Produce an ascending ``ORDER BY`` clause element.
306
+
307
+ e.g.::
308
+
309
+ from sqlalchemy import asc
310
+ stmt = select(users_table).order_by(asc(users_table.c.name))
311
+
312
+ will produce SQL as::
313
+
314
+ SELECT id, name FROM user ORDER BY name ASC
315
+
316
+ The :func:`.asc` function is a standalone version of the
317
+ :meth:`_expression.ColumnElement.asc`
318
+ method available on all SQL expressions,
319
+ e.g.::
320
+
321
+
322
+ stmt = select(users_table).order_by(users_table.c.name.asc())
323
+
324
+ :param column: A :class:`_expression.ColumnElement` (e.g.
325
+ scalar SQL expression)
326
+ with which to apply the :func:`.asc` operation.
327
+
328
+ .. seealso::
329
+
330
+ :func:`.desc`
331
+
332
+ :func:`.nulls_first`
333
+
334
+ :func:`.nulls_last`
335
+
336
+ :meth:`_expression.Select.order_by`
337
+
338
+ """
339
+ return UnaryExpression._create_asc(column)
340
+
341
+
342
+ def collate(
343
+ expression: _ColumnExpressionArgument[str], collation: str
344
+ ) -> BinaryExpression[str]:
345
+ """Return the clause ``expression COLLATE collation``.
346
+
347
+ e.g.::
348
+
349
+ collate(mycolumn, 'utf8_bin')
350
+
351
+ produces::
352
+
353
+ mycolumn COLLATE utf8_bin
354
+
355
+ The collation expression is also quoted if it is a case sensitive
356
+ identifier, e.g. contains uppercase characters.
357
+
358
+ .. versionchanged:: 1.2 quoting is automatically applied to COLLATE
359
+ expressions if they are case sensitive.
360
+
361
+ """
362
+ return CollationClause._create_collation_expression(expression, collation)
363
+
364
+
365
+ def between(
366
+ expr: _ColumnExpressionOrLiteralArgument[_T],
367
+ lower_bound: Any,
368
+ upper_bound: Any,
369
+ symmetric: bool = False,
370
+ ) -> BinaryExpression[bool]:
371
+ """Produce a ``BETWEEN`` predicate clause.
372
+
373
+ E.g.::
374
+
375
+ from sqlalchemy import between
376
+ stmt = select(users_table).where(between(users_table.c.id, 5, 7))
377
+
378
+ Would produce SQL resembling::
379
+
380
+ SELECT id, name FROM user WHERE id BETWEEN :id_1 AND :id_2
381
+
382
+ The :func:`.between` function is a standalone version of the
383
+ :meth:`_expression.ColumnElement.between` method available on all
384
+ SQL expressions, as in::
385
+
386
+ stmt = select(users_table).where(users_table.c.id.between(5, 7))
387
+
388
+ All arguments passed to :func:`.between`, including the left side
389
+ column expression, are coerced from Python scalar values if a
390
+ the value is not a :class:`_expression.ColumnElement` subclass.
391
+ For example,
392
+ three fixed values can be compared as in::
393
+
394
+ print(between(5, 3, 7))
395
+
396
+ Which would produce::
397
+
398
+ :param_1 BETWEEN :param_2 AND :param_3
399
+
400
+ :param expr: a column expression, typically a
401
+ :class:`_expression.ColumnElement`
402
+ instance or alternatively a Python scalar expression to be coerced
403
+ into a column expression, serving as the left side of the ``BETWEEN``
404
+ expression.
405
+
406
+ :param lower_bound: a column or Python scalar expression serving as the
407
+ lower bound of the right side of the ``BETWEEN`` expression.
408
+
409
+ :param upper_bound: a column or Python scalar expression serving as the
410
+ upper bound of the right side of the ``BETWEEN`` expression.
411
+
412
+ :param symmetric: if True, will render " BETWEEN SYMMETRIC ". Note
413
+ that not all databases support this syntax.
414
+
415
+ .. seealso::
416
+
417
+ :meth:`_expression.ColumnElement.between`
418
+
419
+ """
420
+ col_expr = coercions.expect(roles.ExpressionElementRole, expr)
421
+ return col_expr.between(lower_bound, upper_bound, symmetric=symmetric)
422
+
423
+
424
+ def outparam(
425
+ key: str, type_: Optional[TypeEngine[_T]] = None
426
+ ) -> BindParameter[_T]:
427
+ """Create an 'OUT' parameter for usage in functions (stored procedures),
428
+ for databases which support them.
429
+
430
+ The ``outparam`` can be used like a regular function parameter.
431
+ The "output" value will be available from the
432
+ :class:`~sqlalchemy.engine.CursorResult` object via its ``out_parameters``
433
+ attribute, which returns a dictionary containing the values.
434
+
435
+ """
436
+ return BindParameter(key, None, type_=type_, unique=False, isoutparam=True)
437
+
438
+
439
+ @overload
440
+ def not_(clause: BinaryExpression[_T]) -> BinaryExpression[_T]: ...
441
+
442
+
443
+ @overload
444
+ def not_(clause: _ColumnExpressionArgument[_T]) -> ColumnElement[_T]: ...
445
+
446
+
447
+ def not_(clause: _ColumnExpressionArgument[_T]) -> ColumnElement[_T]:
448
+ """Return a negation of the given clause, i.e. ``NOT(clause)``.
449
+
450
+ The ``~`` operator is also overloaded on all
451
+ :class:`_expression.ColumnElement` subclasses to produce the
452
+ same result.
453
+
454
+ """
455
+
456
+ return coercions.expect(roles.ExpressionElementRole, clause).__invert__()
457
+
458
+
459
+ def bindparam(
460
+ key: Optional[str],
461
+ value: Any = _NoArg.NO_ARG,
462
+ type_: Optional[_TypeEngineArgument[_T]] = None,
463
+ unique: bool = False,
464
+ required: Union[bool, Literal[_NoArg.NO_ARG]] = _NoArg.NO_ARG,
465
+ quote: Optional[bool] = None,
466
+ callable_: Optional[Callable[[], Any]] = None,
467
+ expanding: bool = False,
468
+ isoutparam: bool = False,
469
+ literal_execute: bool = False,
470
+ ) -> BindParameter[_T]:
471
+ r"""Produce a "bound expression".
472
+
473
+ The return value is an instance of :class:`.BindParameter`; this
474
+ is a :class:`_expression.ColumnElement`
475
+ subclass which represents a so-called
476
+ "placeholder" value in a SQL expression, the value of which is
477
+ supplied at the point at which the statement in executed against a
478
+ database connection.
479
+
480
+ In SQLAlchemy, the :func:`.bindparam` construct has
481
+ the ability to carry along the actual value that will be ultimately
482
+ used at expression time. In this way, it serves not just as
483
+ a "placeholder" for eventual population, but also as a means of
484
+ representing so-called "unsafe" values which should not be rendered
485
+ directly in a SQL statement, but rather should be passed along
486
+ to the :term:`DBAPI` as values which need to be correctly escaped
487
+ and potentially handled for type-safety.
488
+
489
+ When using :func:`.bindparam` explicitly, the use case is typically
490
+ one of traditional deferment of parameters; the :func:`.bindparam`
491
+ construct accepts a name which can then be referred to at execution
492
+ time::
493
+
494
+ from sqlalchemy import bindparam
495
+
496
+ stmt = select(users_table).where(
497
+ users_table.c.name == bindparam("username")
498
+ )
499
+
500
+ The above statement, when rendered, will produce SQL similar to::
501
+
502
+ SELECT id, name FROM user WHERE name = :username
503
+
504
+ In order to populate the value of ``:username`` above, the value
505
+ would typically be applied at execution time to a method
506
+ like :meth:`_engine.Connection.execute`::
507
+
508
+ result = connection.execute(stmt, {"username": "wendy"})
509
+
510
+ Explicit use of :func:`.bindparam` is also common when producing
511
+ UPDATE or DELETE statements that are to be invoked multiple times,
512
+ where the WHERE criterion of the statement is to change on each
513
+ invocation, such as::
514
+
515
+ stmt = (
516
+ users_table.update()
517
+ .where(user_table.c.name == bindparam("username"))
518
+ .values(fullname=bindparam("fullname"))
519
+ )
520
+
521
+ connection.execute(
522
+ stmt,
523
+ [
524
+ {"username": "wendy", "fullname": "Wendy Smith"},
525
+ {"username": "jack", "fullname": "Jack Jones"},
526
+ ],
527
+ )
528
+
529
+ SQLAlchemy's Core expression system makes wide use of
530
+ :func:`.bindparam` in an implicit sense. It is typical that Python
531
+ literal values passed to virtually all SQL expression functions are
532
+ coerced into fixed :func:`.bindparam` constructs. For example, given
533
+ a comparison operation such as::
534
+
535
+ expr = users_table.c.name == 'Wendy'
536
+
537
+ The above expression will produce a :class:`.BinaryExpression`
538
+ construct, where the left side is the :class:`_schema.Column` object
539
+ representing the ``name`` column, and the right side is a
540
+ :class:`.BindParameter` representing the literal value::
541
+
542
+ print(repr(expr.right))
543
+ BindParameter('%(4327771088 name)s', 'Wendy', type_=String())
544
+
545
+ The expression above will render SQL such as::
546
+
547
+ user.name = :name_1
548
+
549
+ Where the ``:name_1`` parameter name is an anonymous name. The
550
+ actual string ``Wendy`` is not in the rendered string, but is carried
551
+ along where it is later used within statement execution. If we
552
+ invoke a statement like the following::
553
+
554
+ stmt = select(users_table).where(users_table.c.name == 'Wendy')
555
+ result = connection.execute(stmt)
556
+
557
+ We would see SQL logging output as::
558
+
559
+ SELECT "user".id, "user".name
560
+ FROM "user"
561
+ WHERE "user".name = %(name_1)s
562
+ {'name_1': 'Wendy'}
563
+
564
+ Above, we see that ``Wendy`` is passed as a parameter to the database,
565
+ while the placeholder ``:name_1`` is rendered in the appropriate form
566
+ for the target database, in this case the PostgreSQL database.
567
+
568
+ Similarly, :func:`.bindparam` is invoked automatically when working
569
+ with :term:`CRUD` statements as far as the "VALUES" portion is
570
+ concerned. The :func:`_expression.insert` construct produces an
571
+ ``INSERT`` expression which will, at statement execution time, generate
572
+ bound placeholders based on the arguments passed, as in::
573
+
574
+ stmt = users_table.insert()
575
+ result = connection.execute(stmt, {"name": "Wendy"})
576
+
577
+ The above will produce SQL output as::
578
+
579
+ INSERT INTO "user" (name) VALUES (%(name)s)
580
+ {'name': 'Wendy'}
581
+
582
+ The :class:`_expression.Insert` construct, at
583
+ compilation/execution time, rendered a single :func:`.bindparam`
584
+ mirroring the column name ``name`` as a result of the single ``name``
585
+ parameter we passed to the :meth:`_engine.Connection.execute` method.
586
+
587
+ :param key:
588
+ the key (e.g. the name) for this bind param.
589
+ Will be used in the generated
590
+ SQL statement for dialects that use named parameters. This
591
+ value may be modified when part of a compilation operation,
592
+ if other :class:`BindParameter` objects exist with the same
593
+ key, or if its length is too long and truncation is
594
+ required.
595
+
596
+ If omitted, an "anonymous" name is generated for the bound parameter;
597
+ when given a value to bind, the end result is equivalent to calling upon
598
+ the :func:`.literal` function with a value to bind, particularly
599
+ if the :paramref:`.bindparam.unique` parameter is also provided.
600
+
601
+ :param value:
602
+ Initial value for this bind param. Will be used at statement
603
+ execution time as the value for this parameter passed to the
604
+ DBAPI, if no other value is indicated to the statement execution
605
+ method for this particular parameter name. Defaults to ``None``.
606
+
607
+ :param callable\_:
608
+ A callable function that takes the place of "value". The function
609
+ will be called at statement execution time to determine the
610
+ ultimate value. Used for scenarios where the actual bind
611
+ value cannot be determined at the point at which the clause
612
+ construct is created, but embedded bind values are still desirable.
613
+
614
+ :param type\_:
615
+ A :class:`.TypeEngine` class or instance representing an optional
616
+ datatype for this :func:`.bindparam`. If not passed, a type
617
+ may be determined automatically for the bind, based on the given
618
+ value; for example, trivial Python types such as ``str``,
619
+ ``int``, ``bool``
620
+ may result in the :class:`.String`, :class:`.Integer` or
621
+ :class:`.Boolean` types being automatically selected.
622
+
623
+ The type of a :func:`.bindparam` is significant especially in that
624
+ the type will apply pre-processing to the value before it is
625
+ passed to the database. For example, a :func:`.bindparam` which
626
+ refers to a datetime value, and is specified as holding the
627
+ :class:`.DateTime` type, may apply conversion needed to the
628
+ value (such as stringification on SQLite) before passing the value
629
+ to the database.
630
+
631
+ :param unique:
632
+ if True, the key name of this :class:`.BindParameter` will be
633
+ modified if another :class:`.BindParameter` of the same name
634
+ already has been located within the containing
635
+ expression. This flag is used generally by the internals
636
+ when producing so-called "anonymous" bound expressions, it
637
+ isn't generally applicable to explicitly-named :func:`.bindparam`
638
+ constructs.
639
+
640
+ :param required:
641
+ If ``True``, a value is required at execution time. If not passed,
642
+ it defaults to ``True`` if neither :paramref:`.bindparam.value`
643
+ or :paramref:`.bindparam.callable` were passed. If either of these
644
+ parameters are present, then :paramref:`.bindparam.required`
645
+ defaults to ``False``.
646
+
647
+ :param quote:
648
+ True if this parameter name requires quoting and is not
649
+ currently known as a SQLAlchemy reserved word; this currently
650
+ only applies to the Oracle backend, where bound names must
651
+ sometimes be quoted.
652
+
653
+ :param isoutparam:
654
+ if True, the parameter should be treated like a stored procedure
655
+ "OUT" parameter. This applies to backends such as Oracle which
656
+ support OUT parameters.
657
+
658
+ :param expanding:
659
+ if True, this parameter will be treated as an "expanding" parameter
660
+ at execution time; the parameter value is expected to be a sequence,
661
+ rather than a scalar value, and the string SQL statement will
662
+ be transformed on a per-execution basis to accommodate the sequence
663
+ with a variable number of parameter slots passed to the DBAPI.
664
+ This is to allow statement caching to be used in conjunction with
665
+ an IN clause.
666
+
667
+ .. seealso::
668
+
669
+ :meth:`.ColumnOperators.in_`
670
+
671
+ :ref:`baked_in` - with baked queries
672
+
673
+ .. note:: The "expanding" feature does not support "executemany"-
674
+ style parameter sets.
675
+
676
+ .. versionadded:: 1.2
677
+
678
+ .. versionchanged:: 1.3 the "expanding" bound parameter feature now
679
+ supports empty lists.
680
+
681
+ :param literal_execute:
682
+ if True, the bound parameter will be rendered in the compile phase
683
+ with a special "POSTCOMPILE" token, and the SQLAlchemy compiler will
684
+ render the final value of the parameter into the SQL statement at
685
+ statement execution time, omitting the value from the parameter
686
+ dictionary / list passed to DBAPI ``cursor.execute()``. This
687
+ produces a similar effect as that of using the ``literal_binds``,
688
+ compilation flag, however takes place as the statement is sent to
689
+ the DBAPI ``cursor.execute()`` method, rather than when the statement
690
+ is compiled. The primary use of this
691
+ capability is for rendering LIMIT / OFFSET clauses for database
692
+ drivers that can't accommodate for bound parameters in these
693
+ contexts, while allowing SQL constructs to be cacheable at the
694
+ compilation level.
695
+
696
+ .. versionadded:: 1.4 Added "post compile" bound parameters
697
+
698
+ .. seealso::
699
+
700
+ :ref:`change_4808`.
701
+
702
+ .. seealso::
703
+
704
+ :ref:`tutorial_sending_parameters` - in the
705
+ :ref:`unified_tutorial`
706
+
707
+
708
+ """
709
+ return BindParameter(
710
+ key,
711
+ value,
712
+ type_,
713
+ unique,
714
+ required,
715
+ quote,
716
+ callable_,
717
+ expanding,
718
+ isoutparam,
719
+ literal_execute,
720
+ )
721
+
722
+
723
+ def case(
724
+ *whens: Union[
725
+ typing_Tuple[_ColumnExpressionArgument[bool], Any], Mapping[Any, Any]
726
+ ],
727
+ value: Optional[Any] = None,
728
+ else_: Optional[Any] = None,
729
+ ) -> Case[Any]:
730
+ r"""Produce a ``CASE`` expression.
731
+
732
+ The ``CASE`` construct in SQL is a conditional object that
733
+ acts somewhat analogously to an "if/then" construct in other
734
+ languages. It returns an instance of :class:`.Case`.
735
+
736
+ :func:`.case` in its usual form is passed a series of "when"
737
+ constructs, that is, a list of conditions and results as tuples::
738
+
739
+ from sqlalchemy import case
740
+
741
+ stmt = select(users_table).\
742
+ where(
743
+ case(
744
+ (users_table.c.name == 'wendy', 'W'),
745
+ (users_table.c.name == 'jack', 'J'),
746
+ else_='E'
747
+ )
748
+ )
749
+
750
+ The above statement will produce SQL resembling::
751
+
752
+ SELECT id, name FROM user
753
+ WHERE CASE
754
+ WHEN (name = :name_1) THEN :param_1
755
+ WHEN (name = :name_2) THEN :param_2
756
+ ELSE :param_3
757
+ END
758
+
759
+ When simple equality expressions of several values against a single
760
+ parent column are needed, :func:`.case` also has a "shorthand" format
761
+ used via the
762
+ :paramref:`.case.value` parameter, which is passed a column
763
+ expression to be compared. In this form, the :paramref:`.case.whens`
764
+ parameter is passed as a dictionary containing expressions to be
765
+ compared against keyed to result expressions. The statement below is
766
+ equivalent to the preceding statement::
767
+
768
+ stmt = select(users_table).\
769
+ where(
770
+ case(
771
+ {"wendy": "W", "jack": "J"},
772
+ value=users_table.c.name,
773
+ else_='E'
774
+ )
775
+ )
776
+
777
+ The values which are accepted as result values in
778
+ :paramref:`.case.whens` as well as with :paramref:`.case.else_` are
779
+ coerced from Python literals into :func:`.bindparam` constructs.
780
+ SQL expressions, e.g. :class:`_expression.ColumnElement` constructs,
781
+ are accepted
782
+ as well. To coerce a literal string expression into a constant
783
+ expression rendered inline, use the :func:`_expression.literal_column`
784
+ construct,
785
+ as in::
786
+
787
+ from sqlalchemy import case, literal_column
788
+
789
+ case(
790
+ (
791
+ orderline.c.qty > 100,
792
+ literal_column("'greaterthan100'")
793
+ ),
794
+ (
795
+ orderline.c.qty > 10,
796
+ literal_column("'greaterthan10'")
797
+ ),
798
+ else_=literal_column("'lessthan10'")
799
+ )
800
+
801
+ The above will render the given constants without using bound
802
+ parameters for the result values (but still for the comparison
803
+ values), as in::
804
+
805
+ CASE
806
+ WHEN (orderline.qty > :qty_1) THEN 'greaterthan100'
807
+ WHEN (orderline.qty > :qty_2) THEN 'greaterthan10'
808
+ ELSE 'lessthan10'
809
+ END
810
+
811
+ :param \*whens: The criteria to be compared against,
812
+ :paramref:`.case.whens` accepts two different forms, based on
813
+ whether or not :paramref:`.case.value` is used.
814
+
815
+ .. versionchanged:: 1.4 the :func:`_sql.case`
816
+ function now accepts the series of WHEN conditions positionally
817
+
818
+ In the first form, it accepts multiple 2-tuples passed as positional
819
+ arguments; each 2-tuple consists of ``(<sql expression>, <value>)``,
820
+ where the SQL expression is a boolean expression and "value" is a
821
+ resulting value, e.g.::
822
+
823
+ case(
824
+ (users_table.c.name == 'wendy', 'W'),
825
+ (users_table.c.name == 'jack', 'J')
826
+ )
827
+
828
+ In the second form, it accepts a Python dictionary of comparison
829
+ values mapped to a resulting value; this form requires
830
+ :paramref:`.case.value` to be present, and values will be compared
831
+ using the ``==`` operator, e.g.::
832
+
833
+ case(
834
+ {"wendy": "W", "jack": "J"},
835
+ value=users_table.c.name
836
+ )
837
+
838
+ :param value: An optional SQL expression which will be used as a
839
+ fixed "comparison point" for candidate values within a dictionary
840
+ passed to :paramref:`.case.whens`.
841
+
842
+ :param else\_: An optional SQL expression which will be the evaluated
843
+ result of the ``CASE`` construct if all expressions within
844
+ :paramref:`.case.whens` evaluate to false. When omitted, most
845
+ databases will produce a result of NULL if none of the "when"
846
+ expressions evaluate to true.
847
+
848
+
849
+ """
850
+ return Case(*whens, value=value, else_=else_)
851
+
852
+
853
+ def cast(
854
+ expression: _ColumnExpressionOrLiteralArgument[Any],
855
+ type_: _TypeEngineArgument[_T],
856
+ ) -> Cast[_T]:
857
+ r"""Produce a ``CAST`` expression.
858
+
859
+ :func:`.cast` returns an instance of :class:`.Cast`.
860
+
861
+ E.g.::
862
+
863
+ from sqlalchemy import cast, Numeric
864
+
865
+ stmt = select(cast(product_table.c.unit_price, Numeric(10, 4)))
866
+
867
+ The above statement will produce SQL resembling::
868
+
869
+ SELECT CAST(unit_price AS NUMERIC(10, 4)) FROM product
870
+
871
+ The :func:`.cast` function performs two distinct functions when
872
+ used. The first is that it renders the ``CAST`` expression within
873
+ the resulting SQL string. The second is that it associates the given
874
+ type (e.g. :class:`.TypeEngine` class or instance) with the column
875
+ expression on the Python side, which means the expression will take
876
+ on the expression operator behavior associated with that type,
877
+ as well as the bound-value handling and result-row-handling behavior
878
+ of the type.
879
+
880
+ An alternative to :func:`.cast` is the :func:`.type_coerce` function.
881
+ This function performs the second task of associating an expression
882
+ with a specific type, but does not render the ``CAST`` expression
883
+ in SQL.
884
+
885
+ :param expression: A SQL expression, such as a
886
+ :class:`_expression.ColumnElement`
887
+ expression or a Python string which will be coerced into a bound
888
+ literal value.
889
+
890
+ :param type\_: A :class:`.TypeEngine` class or instance indicating
891
+ the type to which the ``CAST`` should apply.
892
+
893
+ .. seealso::
894
+
895
+ :ref:`tutorial_casts`
896
+
897
+ :func:`.try_cast` - an alternative to CAST that results in
898
+ NULLs when the cast fails, instead of raising an error.
899
+ Only supported by some dialects.
900
+
901
+ :func:`.type_coerce` - an alternative to CAST that coerces the type
902
+ on the Python side only, which is often sufficient to generate the
903
+ correct SQL and data coercion.
904
+
905
+
906
+ """
907
+ return Cast(expression, type_)
908
+
909
+
910
+ def try_cast(
911
+ expression: _ColumnExpressionOrLiteralArgument[Any],
912
+ type_: _TypeEngineArgument[_T],
913
+ ) -> TryCast[_T]:
914
+ """Produce a ``TRY_CAST`` expression for backends which support it;
915
+ this is a ``CAST`` which returns NULL for un-castable conversions.
916
+
917
+ In SQLAlchemy, this construct is supported **only** by the SQL Server
918
+ dialect, and will raise a :class:`.CompileError` if used on other
919
+ included backends. However, third party backends may also support
920
+ this construct.
921
+
922
+ .. tip:: As :func:`_sql.try_cast` originates from the SQL Server dialect,
923
+ it's importable both from ``sqlalchemy.`` as well as from
924
+ ``sqlalchemy.dialects.mssql``.
925
+
926
+ :func:`_sql.try_cast` returns an instance of :class:`.TryCast` and
927
+ generally behaves similarly to the :class:`.Cast` construct;
928
+ at the SQL level, the difference between ``CAST`` and ``TRY_CAST``
929
+ is that ``TRY_CAST`` returns NULL for an un-castable expression,
930
+ such as attempting to cast a string ``"hi"`` to an integer value.
931
+
932
+ E.g.::
933
+
934
+ from sqlalchemy import select, try_cast, Numeric
935
+
936
+ stmt = select(
937
+ try_cast(product_table.c.unit_price, Numeric(10, 4))
938
+ )
939
+
940
+ The above would render on Microsoft SQL Server as::
941
+
942
+ SELECT TRY_CAST (product_table.unit_price AS NUMERIC(10, 4))
943
+ FROM product_table
944
+
945
+ .. versionadded:: 2.0.14 :func:`.try_cast` has been
946
+ generalized from the SQL Server dialect into a general use
947
+ construct that may be supported by additional dialects.
948
+
949
+ """
950
+ return TryCast(expression, type_)
951
+
952
+
953
+ def column(
954
+ text: str,
955
+ type_: Optional[_TypeEngineArgument[_T]] = None,
956
+ is_literal: bool = False,
957
+ _selectable: Optional[FromClause] = None,
958
+ ) -> ColumnClause[_T]:
959
+ """Produce a :class:`.ColumnClause` object.
960
+
961
+ The :class:`.ColumnClause` is a lightweight analogue to the
962
+ :class:`_schema.Column` class. The :func:`_expression.column`
963
+ function can
964
+ be invoked with just a name alone, as in::
965
+
966
+ from sqlalchemy import column
967
+
968
+ id, name = column("id"), column("name")
969
+ stmt = select(id, name).select_from("user")
970
+
971
+ The above statement would produce SQL like::
972
+
973
+ SELECT id, name FROM user
974
+
975
+ Once constructed, :func:`_expression.column`
976
+ may be used like any other SQL
977
+ expression element such as within :func:`_expression.select`
978
+ constructs::
979
+
980
+ from sqlalchemy.sql import column
981
+
982
+ id, name = column("id"), column("name")
983
+ stmt = select(id, name).select_from("user")
984
+
985
+ The text handled by :func:`_expression.column`
986
+ is assumed to be handled
987
+ like the name of a database column; if the string contains mixed case,
988
+ special characters, or matches a known reserved word on the target
989
+ backend, the column expression will render using the quoting
990
+ behavior determined by the backend. To produce a textual SQL
991
+ expression that is rendered exactly without any quoting,
992
+ use :func:`_expression.literal_column` instead,
993
+ or pass ``True`` as the
994
+ value of :paramref:`_expression.column.is_literal`. Additionally,
995
+ full SQL
996
+ statements are best handled using the :func:`_expression.text`
997
+ construct.
998
+
999
+ :func:`_expression.column` can be used in a table-like
1000
+ fashion by combining it with the :func:`.table` function
1001
+ (which is the lightweight analogue to :class:`_schema.Table`
1002
+ ) to produce
1003
+ a working table construct with minimal boilerplate::
1004
+
1005
+ from sqlalchemy import table, column, select
1006
+
1007
+ user = table("user",
1008
+ column("id"),
1009
+ column("name"),
1010
+ column("description"),
1011
+ )
1012
+
1013
+ stmt = select(user.c.description).where(user.c.name == 'wendy')
1014
+
1015
+ A :func:`_expression.column` / :func:`.table`
1016
+ construct like that illustrated
1017
+ above can be created in an
1018
+ ad-hoc fashion and is not associated with any
1019
+ :class:`_schema.MetaData`, DDL, or events, unlike its
1020
+ :class:`_schema.Table` counterpart.
1021
+
1022
+ :param text: the text of the element.
1023
+
1024
+ :param type: :class:`_types.TypeEngine` object which can associate
1025
+ this :class:`.ColumnClause` with a type.
1026
+
1027
+ :param is_literal: if True, the :class:`.ColumnClause` is assumed to
1028
+ be an exact expression that will be delivered to the output with no
1029
+ quoting rules applied regardless of case sensitive settings. the
1030
+ :func:`_expression.literal_column()` function essentially invokes
1031
+ :func:`_expression.column` while passing ``is_literal=True``.
1032
+
1033
+ .. seealso::
1034
+
1035
+ :class:`_schema.Column`
1036
+
1037
+ :func:`_expression.literal_column`
1038
+
1039
+ :func:`.table`
1040
+
1041
+ :func:`_expression.text`
1042
+
1043
+ :ref:`tutorial_select_arbitrary_text`
1044
+
1045
+ """
1046
+ return ColumnClause(text, type_, is_literal, _selectable)
1047
+
1048
+
1049
+ def desc(
1050
+ column: _ColumnExpressionOrStrLabelArgument[_T],
1051
+ ) -> UnaryExpression[_T]:
1052
+ """Produce a descending ``ORDER BY`` clause element.
1053
+
1054
+ e.g.::
1055
+
1056
+ from sqlalchemy import desc
1057
+
1058
+ stmt = select(users_table).order_by(desc(users_table.c.name))
1059
+
1060
+ will produce SQL as::
1061
+
1062
+ SELECT id, name FROM user ORDER BY name DESC
1063
+
1064
+ The :func:`.desc` function is a standalone version of the
1065
+ :meth:`_expression.ColumnElement.desc`
1066
+ method available on all SQL expressions,
1067
+ e.g.::
1068
+
1069
+
1070
+ stmt = select(users_table).order_by(users_table.c.name.desc())
1071
+
1072
+ :param column: A :class:`_expression.ColumnElement` (e.g.
1073
+ scalar SQL expression)
1074
+ with which to apply the :func:`.desc` operation.
1075
+
1076
+ .. seealso::
1077
+
1078
+ :func:`.asc`
1079
+
1080
+ :func:`.nulls_first`
1081
+
1082
+ :func:`.nulls_last`
1083
+
1084
+ :meth:`_expression.Select.order_by`
1085
+
1086
+ """
1087
+ return UnaryExpression._create_desc(column)
1088
+
1089
+
1090
+ def distinct(expr: _ColumnExpressionArgument[_T]) -> UnaryExpression[_T]:
1091
+ """Produce an column-expression-level unary ``DISTINCT`` clause.
1092
+
1093
+ This applies the ``DISTINCT`` keyword to an **individual column
1094
+ expression** (e.g. not the whole statement), and renders **specifically
1095
+ in that column position**; this is used for containment within
1096
+ an aggregate function, as in::
1097
+
1098
+ from sqlalchemy import distinct, func
1099
+ stmt = select(users_table.c.id, func.count(distinct(users_table.c.name)))
1100
+
1101
+ The above would produce an statement resembling::
1102
+
1103
+ SELECT user.id, count(DISTINCT user.name) FROM user
1104
+
1105
+ .. tip:: The :func:`_sql.distinct` function does **not** apply DISTINCT
1106
+ to the full SELECT statement, instead applying a DISTINCT modifier
1107
+ to **individual column expressions**. For general ``SELECT DISTINCT``
1108
+ support, use the
1109
+ :meth:`_sql.Select.distinct` method on :class:`_sql.Select`.
1110
+
1111
+ The :func:`.distinct` function is also available as a column-level
1112
+ method, e.g. :meth:`_expression.ColumnElement.distinct`, as in::
1113
+
1114
+ stmt = select(func.count(users_table.c.name.distinct()))
1115
+
1116
+ The :func:`.distinct` operator is different from the
1117
+ :meth:`_expression.Select.distinct` method of
1118
+ :class:`_expression.Select`,
1119
+ which produces a ``SELECT`` statement
1120
+ with ``DISTINCT`` applied to the result set as a whole,
1121
+ e.g. a ``SELECT DISTINCT`` expression. See that method for further
1122
+ information.
1123
+
1124
+ .. seealso::
1125
+
1126
+ :meth:`_expression.ColumnElement.distinct`
1127
+
1128
+ :meth:`_expression.Select.distinct`
1129
+
1130
+ :data:`.func`
1131
+
1132
+ """ # noqa: E501
1133
+ return UnaryExpression._create_distinct(expr)
1134
+
1135
+
1136
+ def bitwise_not(expr: _ColumnExpressionArgument[_T]) -> UnaryExpression[_T]:
1137
+ """Produce a unary bitwise NOT clause, typically via the ``~`` operator.
1138
+
1139
+ Not to be confused with boolean negation :func:`_sql.not_`.
1140
+
1141
+ .. versionadded:: 2.0.2
1142
+
1143
+ .. seealso::
1144
+
1145
+ :ref:`operators_bitwise`
1146
+
1147
+
1148
+ """
1149
+
1150
+ return UnaryExpression._create_bitwise_not(expr)
1151
+
1152
+
1153
+ def extract(field: str, expr: _ColumnExpressionArgument[Any]) -> Extract:
1154
+ """Return a :class:`.Extract` construct.
1155
+
1156
+ This is typically available as :func:`.extract`
1157
+ as well as ``func.extract`` from the
1158
+ :data:`.func` namespace.
1159
+
1160
+ :param field: The field to extract.
1161
+
1162
+ .. warning:: This field is used as a literal SQL string.
1163
+ **DO NOT PASS UNTRUSTED INPUT TO THIS STRING**.
1164
+
1165
+ :param expr: A column or Python scalar expression serving as the
1166
+ right side of the ``EXTRACT`` expression.
1167
+
1168
+ E.g.::
1169
+
1170
+ from sqlalchemy import extract
1171
+ from sqlalchemy import table, column
1172
+
1173
+ logged_table = table("user",
1174
+ column("id"),
1175
+ column("date_created"),
1176
+ )
1177
+
1178
+ stmt = select(logged_table.c.id).where(
1179
+ extract("YEAR", logged_table.c.date_created) == 2021
1180
+ )
1181
+
1182
+ In the above example, the statement is used to select ids from the
1183
+ database where the ``YEAR`` component matches a specific value.
1184
+
1185
+ Similarly, one can also select an extracted component::
1186
+
1187
+ stmt = select(
1188
+ extract("YEAR", logged_table.c.date_created)
1189
+ ).where(logged_table.c.id == 1)
1190
+
1191
+ The implementation of ``EXTRACT`` may vary across database backends.
1192
+ Users are reminded to consult their database documentation.
1193
+ """
1194
+ return Extract(field, expr)
1195
+
1196
+
1197
+ def false() -> False_:
1198
+ """Return a :class:`.False_` construct.
1199
+
1200
+ E.g.:
1201
+
1202
+ .. sourcecode:: pycon+sql
1203
+
1204
+ >>> from sqlalchemy import false
1205
+ >>> print(select(t.c.x).where(false()))
1206
+ {printsql}SELECT x FROM t WHERE false
1207
+
1208
+ A backend which does not support true/false constants will render as
1209
+ an expression against 1 or 0:
1210
+
1211
+ .. sourcecode:: pycon+sql
1212
+
1213
+ >>> print(select(t.c.x).where(false()))
1214
+ {printsql}SELECT x FROM t WHERE 0 = 1
1215
+
1216
+ The :func:`.true` and :func:`.false` constants also feature
1217
+ "short circuit" operation within an :func:`.and_` or :func:`.or_`
1218
+ conjunction:
1219
+
1220
+ .. sourcecode:: pycon+sql
1221
+
1222
+ >>> print(select(t.c.x).where(or_(t.c.x > 5, true())))
1223
+ {printsql}SELECT x FROM t WHERE true{stop}
1224
+
1225
+ >>> print(select(t.c.x).where(and_(t.c.x > 5, false())))
1226
+ {printsql}SELECT x FROM t WHERE false{stop}
1227
+
1228
+ .. seealso::
1229
+
1230
+ :func:`.true`
1231
+
1232
+ """
1233
+
1234
+ return False_._instance()
1235
+
1236
+
1237
+ def funcfilter(
1238
+ func: FunctionElement[_T], *criterion: _ColumnExpressionArgument[bool]
1239
+ ) -> FunctionFilter[_T]:
1240
+ """Produce a :class:`.FunctionFilter` object against a function.
1241
+
1242
+ Used against aggregate and window functions,
1243
+ for database backends that support the "FILTER" clause.
1244
+
1245
+ E.g.::
1246
+
1247
+ from sqlalchemy import funcfilter
1248
+ funcfilter(func.count(1), MyClass.name == 'some name')
1249
+
1250
+ Would produce "COUNT(1) FILTER (WHERE myclass.name = 'some name')".
1251
+
1252
+ This function is also available from the :data:`~.expression.func`
1253
+ construct itself via the :meth:`.FunctionElement.filter` method.
1254
+
1255
+ .. seealso::
1256
+
1257
+ :ref:`tutorial_functions_within_group` - in the
1258
+ :ref:`unified_tutorial`
1259
+
1260
+ :meth:`.FunctionElement.filter`
1261
+
1262
+ """
1263
+ return FunctionFilter(func, *criterion)
1264
+
1265
+
1266
+ def label(
1267
+ name: str,
1268
+ element: _ColumnExpressionArgument[_T],
1269
+ type_: Optional[_TypeEngineArgument[_T]] = None,
1270
+ ) -> Label[_T]:
1271
+ """Return a :class:`Label` object for the
1272
+ given :class:`_expression.ColumnElement`.
1273
+
1274
+ A label changes the name of an element in the columns clause of a
1275
+ ``SELECT`` statement, typically via the ``AS`` SQL keyword.
1276
+
1277
+ This functionality is more conveniently available via the
1278
+ :meth:`_expression.ColumnElement.label` method on
1279
+ :class:`_expression.ColumnElement`.
1280
+
1281
+ :param name: label name
1282
+
1283
+ :param obj: a :class:`_expression.ColumnElement`.
1284
+
1285
+ """
1286
+ return Label(name, element, type_)
1287
+
1288
+
1289
+ def null() -> Null:
1290
+ """Return a constant :class:`.Null` construct."""
1291
+
1292
+ return Null._instance()
1293
+
1294
+
1295
+ def nulls_first(column: _ColumnExpressionArgument[_T]) -> UnaryExpression[_T]:
1296
+ """Produce the ``NULLS FIRST`` modifier for an ``ORDER BY`` expression.
1297
+
1298
+ :func:`.nulls_first` is intended to modify the expression produced
1299
+ by :func:`.asc` or :func:`.desc`, and indicates how NULL values
1300
+ should be handled when they are encountered during ordering::
1301
+
1302
+
1303
+ from sqlalchemy import desc, nulls_first
1304
+
1305
+ stmt = select(users_table).order_by(
1306
+ nulls_first(desc(users_table.c.name)))
1307
+
1308
+ The SQL expression from the above would resemble::
1309
+
1310
+ SELECT id, name FROM user ORDER BY name DESC NULLS FIRST
1311
+
1312
+ Like :func:`.asc` and :func:`.desc`, :func:`.nulls_first` is typically
1313
+ invoked from the column expression itself using
1314
+ :meth:`_expression.ColumnElement.nulls_first`,
1315
+ rather than as its standalone
1316
+ function version, as in::
1317
+
1318
+ stmt = select(users_table).order_by(
1319
+ users_table.c.name.desc().nulls_first())
1320
+
1321
+ .. versionchanged:: 1.4 :func:`.nulls_first` is renamed from
1322
+ :func:`.nullsfirst` in previous releases.
1323
+ The previous name remains available for backwards compatibility.
1324
+
1325
+ .. seealso::
1326
+
1327
+ :func:`.asc`
1328
+
1329
+ :func:`.desc`
1330
+
1331
+ :func:`.nulls_last`
1332
+
1333
+ :meth:`_expression.Select.order_by`
1334
+
1335
+ """
1336
+ return UnaryExpression._create_nulls_first(column)
1337
+
1338
+
1339
+ def nulls_last(column: _ColumnExpressionArgument[_T]) -> UnaryExpression[_T]:
1340
+ """Produce the ``NULLS LAST`` modifier for an ``ORDER BY`` expression.
1341
+
1342
+ :func:`.nulls_last` is intended to modify the expression produced
1343
+ by :func:`.asc` or :func:`.desc`, and indicates how NULL values
1344
+ should be handled when they are encountered during ordering::
1345
+
1346
+
1347
+ from sqlalchemy import desc, nulls_last
1348
+
1349
+ stmt = select(users_table).order_by(
1350
+ nulls_last(desc(users_table.c.name)))
1351
+
1352
+ The SQL expression from the above would resemble::
1353
+
1354
+ SELECT id, name FROM user ORDER BY name DESC NULLS LAST
1355
+
1356
+ Like :func:`.asc` and :func:`.desc`, :func:`.nulls_last` is typically
1357
+ invoked from the column expression itself using
1358
+ :meth:`_expression.ColumnElement.nulls_last`,
1359
+ rather than as its standalone
1360
+ function version, as in::
1361
+
1362
+ stmt = select(users_table).order_by(
1363
+ users_table.c.name.desc().nulls_last())
1364
+
1365
+ .. versionchanged:: 1.4 :func:`.nulls_last` is renamed from
1366
+ :func:`.nullslast` in previous releases.
1367
+ The previous name remains available for backwards compatibility.
1368
+
1369
+ .. seealso::
1370
+
1371
+ :func:`.asc`
1372
+
1373
+ :func:`.desc`
1374
+
1375
+ :func:`.nulls_first`
1376
+
1377
+ :meth:`_expression.Select.order_by`
1378
+
1379
+ """
1380
+ return UnaryExpression._create_nulls_last(column)
1381
+
1382
+
1383
+ def or_( # type: ignore[empty-body]
1384
+ initial_clause: Union[Literal[False], _ColumnExpressionArgument[bool]],
1385
+ *clauses: _ColumnExpressionArgument[bool],
1386
+ ) -> ColumnElement[bool]:
1387
+ """Produce a conjunction of expressions joined by ``OR``.
1388
+
1389
+ E.g.::
1390
+
1391
+ from sqlalchemy import or_
1392
+
1393
+ stmt = select(users_table).where(
1394
+ or_(
1395
+ users_table.c.name == 'wendy',
1396
+ users_table.c.name == 'jack'
1397
+ )
1398
+ )
1399
+
1400
+ The :func:`.or_` conjunction is also available using the
1401
+ Python ``|`` operator (though note that compound expressions
1402
+ need to be parenthesized in order to function with Python
1403
+ operator precedence behavior)::
1404
+
1405
+ stmt = select(users_table).where(
1406
+ (users_table.c.name == 'wendy') |
1407
+ (users_table.c.name == 'jack')
1408
+ )
1409
+
1410
+ The :func:`.or_` construct must be given at least one positional
1411
+ argument in order to be valid; a :func:`.or_` construct with no
1412
+ arguments is ambiguous. To produce an "empty" or dynamically
1413
+ generated :func:`.or_` expression, from a given list of expressions,
1414
+ a "default" element of :func:`_sql.false` (or just ``False``) should be
1415
+ specified::
1416
+
1417
+ from sqlalchemy import false
1418
+ or_criteria = or_(false(), *expressions)
1419
+
1420
+ The above expression will compile to SQL as the expression ``false``
1421
+ or ``0 = 1``, depending on backend, if no other expressions are
1422
+ present. If expressions are present, then the :func:`_sql.false` value is
1423
+ ignored as it does not affect the outcome of an OR expression which
1424
+ has other elements.
1425
+
1426
+ .. deprecated:: 1.4 The :func:`.or_` element now requires that at
1427
+ least one argument is passed; creating the :func:`.or_` construct
1428
+ with no arguments is deprecated, and will emit a deprecation warning
1429
+ while continuing to produce a blank SQL string.
1430
+
1431
+ .. seealso::
1432
+
1433
+ :func:`.and_`
1434
+
1435
+ """
1436
+ ...
1437
+
1438
+
1439
+ if not TYPE_CHECKING:
1440
+ # handle deprecated case which allows zero-arguments
1441
+ def or_(*clauses): # noqa: F811
1442
+ """Produce a conjunction of expressions joined by ``OR``.
1443
+
1444
+ E.g.::
1445
+
1446
+ from sqlalchemy import or_
1447
+
1448
+ stmt = select(users_table).where(
1449
+ or_(
1450
+ users_table.c.name == 'wendy',
1451
+ users_table.c.name == 'jack'
1452
+ )
1453
+ )
1454
+
1455
+ The :func:`.or_` conjunction is also available using the
1456
+ Python ``|`` operator (though note that compound expressions
1457
+ need to be parenthesized in order to function with Python
1458
+ operator precedence behavior)::
1459
+
1460
+ stmt = select(users_table).where(
1461
+ (users_table.c.name == 'wendy') |
1462
+ (users_table.c.name == 'jack')
1463
+ )
1464
+
1465
+ The :func:`.or_` construct must be given at least one positional
1466
+ argument in order to be valid; a :func:`.or_` construct with no
1467
+ arguments is ambiguous. To produce an "empty" or dynamically
1468
+ generated :func:`.or_` expression, from a given list of expressions,
1469
+ a "default" element of :func:`_sql.false` (or just ``False``) should be
1470
+ specified::
1471
+
1472
+ from sqlalchemy import false
1473
+ or_criteria = or_(false(), *expressions)
1474
+
1475
+ The above expression will compile to SQL as the expression ``false``
1476
+ or ``0 = 1``, depending on backend, if no other expressions are
1477
+ present. If expressions are present, then the :func:`_sql.false` value
1478
+ is ignored as it does not affect the outcome of an OR expression which
1479
+ has other elements.
1480
+
1481
+ .. deprecated:: 1.4 The :func:`.or_` element now requires that at
1482
+ least one argument is passed; creating the :func:`.or_` construct
1483
+ with no arguments is deprecated, and will emit a deprecation warning
1484
+ while continuing to produce a blank SQL string.
1485
+
1486
+ .. seealso::
1487
+
1488
+ :func:`.and_`
1489
+
1490
+ """
1491
+ return BooleanClauseList.or_(*clauses)
1492
+
1493
+
1494
+ def over(
1495
+ element: FunctionElement[_T],
1496
+ partition_by: Optional[_ByArgument] = None,
1497
+ order_by: Optional[_ByArgument] = None,
1498
+ range_: Optional[typing_Tuple[Optional[int], Optional[int]]] = None,
1499
+ rows: Optional[typing_Tuple[Optional[int], Optional[int]]] = None,
1500
+ ) -> Over[_T]:
1501
+ r"""Produce an :class:`.Over` object against a function.
1502
+
1503
+ Used against aggregate or so-called "window" functions,
1504
+ for database backends that support window functions.
1505
+
1506
+ :func:`_expression.over` is usually called using
1507
+ the :meth:`.FunctionElement.over` method, e.g.::
1508
+
1509
+ func.row_number().over(order_by=mytable.c.some_column)
1510
+
1511
+ Would produce::
1512
+
1513
+ ROW_NUMBER() OVER(ORDER BY some_column)
1514
+
1515
+ Ranges are also possible using the :paramref:`.expression.over.range_`
1516
+ and :paramref:`.expression.over.rows` parameters. These
1517
+ mutually-exclusive parameters each accept a 2-tuple, which contains
1518
+ a combination of integers and None::
1519
+
1520
+ func.row_number().over(
1521
+ order_by=my_table.c.some_column, range_=(None, 0))
1522
+
1523
+ The above would produce::
1524
+
1525
+ ROW_NUMBER() OVER(ORDER BY some_column
1526
+ RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
1527
+
1528
+ A value of ``None`` indicates "unbounded", a
1529
+ value of zero indicates "current row", and negative / positive
1530
+ integers indicate "preceding" and "following":
1531
+
1532
+ * RANGE BETWEEN 5 PRECEDING AND 10 FOLLOWING::
1533
+
1534
+ func.row_number().over(order_by='x', range_=(-5, 10))
1535
+
1536
+ * ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW::
1537
+
1538
+ func.row_number().over(order_by='x', rows=(None, 0))
1539
+
1540
+ * RANGE BETWEEN 2 PRECEDING AND UNBOUNDED FOLLOWING::
1541
+
1542
+ func.row_number().over(order_by='x', range_=(-2, None))
1543
+
1544
+ * RANGE BETWEEN 1 FOLLOWING AND 3 FOLLOWING::
1545
+
1546
+ func.row_number().over(order_by='x', range_=(1, 3))
1547
+
1548
+ :param element: a :class:`.FunctionElement`, :class:`.WithinGroup`,
1549
+ or other compatible construct.
1550
+ :param partition_by: a column element or string, or a list
1551
+ of such, that will be used as the PARTITION BY clause
1552
+ of the OVER construct.
1553
+ :param order_by: a column element or string, or a list
1554
+ of such, that will be used as the ORDER BY clause
1555
+ of the OVER construct.
1556
+ :param range\_: optional range clause for the window. This is a
1557
+ tuple value which can contain integer values or ``None``,
1558
+ and will render a RANGE BETWEEN PRECEDING / FOLLOWING clause.
1559
+
1560
+ :param rows: optional rows clause for the window. This is a tuple
1561
+ value which can contain integer values or None, and will render
1562
+ a ROWS BETWEEN PRECEDING / FOLLOWING clause.
1563
+
1564
+ This function is also available from the :data:`~.expression.func`
1565
+ construct itself via the :meth:`.FunctionElement.over` method.
1566
+
1567
+ .. seealso::
1568
+
1569
+ :ref:`tutorial_window_functions` - in the :ref:`unified_tutorial`
1570
+
1571
+ :data:`.expression.func`
1572
+
1573
+ :func:`_expression.within_group`
1574
+
1575
+ """
1576
+ return Over(element, partition_by, order_by, range_, rows)
1577
+
1578
+
1579
+ @_document_text_coercion("text", ":func:`.text`", ":paramref:`.text.text`")
1580
+ def text(text: str) -> TextClause:
1581
+ r"""Construct a new :class:`_expression.TextClause` clause,
1582
+ representing
1583
+ a textual SQL string directly.
1584
+
1585
+ E.g.::
1586
+
1587
+ from sqlalchemy import text
1588
+
1589
+ t = text("SELECT * FROM users")
1590
+ result = connection.execute(t)
1591
+
1592
+ The advantages :func:`_expression.text`
1593
+ provides over a plain string are
1594
+ backend-neutral support for bind parameters, per-statement
1595
+ execution options, as well as
1596
+ bind parameter and result-column typing behavior, allowing
1597
+ SQLAlchemy type constructs to play a role when executing
1598
+ a statement that is specified literally. The construct can also
1599
+ be provided with a ``.c`` collection of column elements, allowing
1600
+ it to be embedded in other SQL expression constructs as a subquery.
1601
+
1602
+ Bind parameters are specified by name, using the format ``:name``.
1603
+ E.g.::
1604
+
1605
+ t = text("SELECT * FROM users WHERE id=:user_id")
1606
+ result = connection.execute(t, {"user_id": 12})
1607
+
1608
+ For SQL statements where a colon is required verbatim, as within
1609
+ an inline string, use a backslash to escape::
1610
+
1611
+ t = text(r"SELECT * FROM users WHERE name='\:username'")
1612
+
1613
+ The :class:`_expression.TextClause`
1614
+ construct includes methods which can
1615
+ provide information about the bound parameters as well as the column
1616
+ values which would be returned from the textual statement, assuming
1617
+ it's an executable SELECT type of statement. The
1618
+ :meth:`_expression.TextClause.bindparams`
1619
+ method is used to provide bound
1620
+ parameter detail, and :meth:`_expression.TextClause.columns`
1621
+ method allows
1622
+ specification of return columns including names and types::
1623
+
1624
+ t = text("SELECT * FROM users WHERE id=:user_id").\
1625
+ bindparams(user_id=7).\
1626
+ columns(id=Integer, name=String)
1627
+
1628
+ for id, name in connection.execute(t):
1629
+ print(id, name)
1630
+
1631
+ The :func:`_expression.text` construct is used in cases when
1632
+ a literal string SQL fragment is specified as part of a larger query,
1633
+ such as for the WHERE clause of a SELECT statement::
1634
+
1635
+ s = select(users.c.id, users.c.name).where(text("id=:user_id"))
1636
+ result = connection.execute(s, {"user_id": 12})
1637
+
1638
+ :func:`_expression.text` is also used for the construction
1639
+ of a full, standalone statement using plain text.
1640
+ As such, SQLAlchemy refers
1641
+ to it as an :class:`.Executable` object and may be used
1642
+ like any other statement passed to an ``.execute()`` method.
1643
+
1644
+ :param text:
1645
+ the text of the SQL statement to be created. Use ``:<param>``
1646
+ to specify bind parameters; they will be compiled to their
1647
+ engine-specific format.
1648
+
1649
+ .. seealso::
1650
+
1651
+ :ref:`tutorial_select_arbitrary_text`
1652
+
1653
+ """
1654
+ return TextClause(text)
1655
+
1656
+
1657
+ def true() -> True_:
1658
+ """Return a constant :class:`.True_` construct.
1659
+
1660
+ E.g.:
1661
+
1662
+ .. sourcecode:: pycon+sql
1663
+
1664
+ >>> from sqlalchemy import true
1665
+ >>> print(select(t.c.x).where(true()))
1666
+ {printsql}SELECT x FROM t WHERE true
1667
+
1668
+ A backend which does not support true/false constants will render as
1669
+ an expression against 1 or 0:
1670
+
1671
+ .. sourcecode:: pycon+sql
1672
+
1673
+ >>> print(select(t.c.x).where(true()))
1674
+ {printsql}SELECT x FROM t WHERE 1 = 1
1675
+
1676
+ The :func:`.true` and :func:`.false` constants also feature
1677
+ "short circuit" operation within an :func:`.and_` or :func:`.or_`
1678
+ conjunction:
1679
+
1680
+ .. sourcecode:: pycon+sql
1681
+
1682
+ >>> print(select(t.c.x).where(or_(t.c.x > 5, true())))
1683
+ {printsql}SELECT x FROM t WHERE true{stop}
1684
+
1685
+ >>> print(select(t.c.x).where(and_(t.c.x > 5, false())))
1686
+ {printsql}SELECT x FROM t WHERE false{stop}
1687
+
1688
+ .. seealso::
1689
+
1690
+ :func:`.false`
1691
+
1692
+ """
1693
+
1694
+ return True_._instance()
1695
+
1696
+
1697
+ def tuple_(
1698
+ *clauses: _ColumnExpressionArgument[Any],
1699
+ types: Optional[Sequence[_TypeEngineArgument[Any]]] = None,
1700
+ ) -> Tuple:
1701
+ """Return a :class:`.Tuple`.
1702
+
1703
+ Main usage is to produce a composite IN construct using
1704
+ :meth:`.ColumnOperators.in_` ::
1705
+
1706
+ from sqlalchemy import tuple_
1707
+
1708
+ tuple_(table.c.col1, table.c.col2).in_(
1709
+ [(1, 2), (5, 12), (10, 19)]
1710
+ )
1711
+
1712
+ .. versionchanged:: 1.3.6 Added support for SQLite IN tuples.
1713
+
1714
+ .. warning::
1715
+
1716
+ The composite IN construct is not supported by all backends, and is
1717
+ currently known to work on PostgreSQL, MySQL, and SQLite.
1718
+ Unsupported backends will raise a subclass of
1719
+ :class:`~sqlalchemy.exc.DBAPIError` when such an expression is
1720
+ invoked.
1721
+
1722
+ """
1723
+ return Tuple(*clauses, types=types)
1724
+
1725
+
1726
+ def type_coerce(
1727
+ expression: _ColumnExpressionOrLiteralArgument[Any],
1728
+ type_: _TypeEngineArgument[_T],
1729
+ ) -> TypeCoerce[_T]:
1730
+ r"""Associate a SQL expression with a particular type, without rendering
1731
+ ``CAST``.
1732
+
1733
+ E.g.::
1734
+
1735
+ from sqlalchemy import type_coerce
1736
+
1737
+ stmt = select(type_coerce(log_table.date_string, StringDateTime()))
1738
+
1739
+ The above construct will produce a :class:`.TypeCoerce` object, which
1740
+ does not modify the rendering in any way on the SQL side, with the
1741
+ possible exception of a generated label if used in a columns clause
1742
+ context:
1743
+
1744
+ .. sourcecode:: sql
1745
+
1746
+ SELECT date_string AS date_string FROM log
1747
+
1748
+ When result rows are fetched, the ``StringDateTime`` type processor
1749
+ will be applied to result rows on behalf of the ``date_string`` column.
1750
+
1751
+ .. note:: the :func:`.type_coerce` construct does not render any
1752
+ SQL syntax of its own, including that it does not imply
1753
+ parenthesization. Please use :meth:`.TypeCoerce.self_group`
1754
+ if explicit parenthesization is required.
1755
+
1756
+ In order to provide a named label for the expression, use
1757
+ :meth:`_expression.ColumnElement.label`::
1758
+
1759
+ stmt = select(
1760
+ type_coerce(log_table.date_string, StringDateTime()).label('date')
1761
+ )
1762
+
1763
+
1764
+ A type that features bound-value handling will also have that behavior
1765
+ take effect when literal values or :func:`.bindparam` constructs are
1766
+ passed to :func:`.type_coerce` as targets.
1767
+ For example, if a type implements the
1768
+ :meth:`.TypeEngine.bind_expression`
1769
+ method or :meth:`.TypeEngine.bind_processor` method or equivalent,
1770
+ these functions will take effect at statement compilation/execution
1771
+ time when a literal value is passed, as in::
1772
+
1773
+ # bound-value handling of MyStringType will be applied to the
1774
+ # literal value "some string"
1775
+ stmt = select(type_coerce("some string", MyStringType))
1776
+
1777
+ When using :func:`.type_coerce` with composed expressions, note that
1778
+ **parenthesis are not applied**. If :func:`.type_coerce` is being
1779
+ used in an operator context where the parenthesis normally present from
1780
+ CAST are necessary, use the :meth:`.TypeCoerce.self_group` method:
1781
+
1782
+ .. sourcecode:: pycon+sql
1783
+
1784
+ >>> some_integer = column("someint", Integer)
1785
+ >>> some_string = column("somestr", String)
1786
+ >>> expr = type_coerce(some_integer + 5, String) + some_string
1787
+ >>> print(expr)
1788
+ {printsql}someint + :someint_1 || somestr{stop}
1789
+ >>> expr = type_coerce(some_integer + 5, String).self_group() + some_string
1790
+ >>> print(expr)
1791
+ {printsql}(someint + :someint_1) || somestr{stop}
1792
+
1793
+ :param expression: A SQL expression, such as a
1794
+ :class:`_expression.ColumnElement`
1795
+ expression or a Python string which will be coerced into a bound
1796
+ literal value.
1797
+
1798
+ :param type\_: A :class:`.TypeEngine` class or instance indicating
1799
+ the type to which the expression is coerced.
1800
+
1801
+ .. seealso::
1802
+
1803
+ :ref:`tutorial_casts`
1804
+
1805
+ :func:`.cast`
1806
+
1807
+ """ # noqa
1808
+ return TypeCoerce(expression, type_)
1809
+
1810
+
1811
+ def within_group(
1812
+ element: FunctionElement[_T], *order_by: _ColumnExpressionArgument[Any]
1813
+ ) -> WithinGroup[_T]:
1814
+ r"""Produce a :class:`.WithinGroup` object against a function.
1815
+
1816
+ Used against so-called "ordered set aggregate" and "hypothetical
1817
+ set aggregate" functions, including :class:`.percentile_cont`,
1818
+ :class:`.rank`, :class:`.dense_rank`, etc.
1819
+
1820
+ :func:`_expression.within_group` is usually called using
1821
+ the :meth:`.FunctionElement.within_group` method, e.g.::
1822
+
1823
+ from sqlalchemy import within_group
1824
+ stmt = select(
1825
+ department.c.id,
1826
+ func.percentile_cont(0.5).within_group(
1827
+ department.c.salary.desc()
1828
+ )
1829
+ )
1830
+
1831
+ The above statement would produce SQL similar to
1832
+ ``SELECT department.id, percentile_cont(0.5)
1833
+ WITHIN GROUP (ORDER BY department.salary DESC)``.
1834
+
1835
+ :param element: a :class:`.FunctionElement` construct, typically
1836
+ generated by :data:`~.expression.func`.
1837
+ :param \*order_by: one or more column elements that will be used
1838
+ as the ORDER BY clause of the WITHIN GROUP construct.
1839
+
1840
+ .. seealso::
1841
+
1842
+ :ref:`tutorial_functions_within_group` - in the
1843
+ :ref:`unified_tutorial`
1844
+
1845
+ :data:`.expression.func`
1846
+
1847
+ :func:`_expression.over`
1848
+
1849
+ """
1850
+ return WithinGroup(element, *order_by)