SQLAlchemy 2.0.47__cp313-cp313t-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 (274) hide show
  1. sqlalchemy/__init__.py +283 -0
  2. sqlalchemy/connectors/__init__.py +18 -0
  3. sqlalchemy/connectors/aioodbc.py +184 -0
  4. sqlalchemy/connectors/asyncio.py +429 -0
  5. sqlalchemy/connectors/pyodbc.py +250 -0
  6. sqlalchemy/cyextension/__init__.py +6 -0
  7. sqlalchemy/cyextension/collections.cp313t-win_amd64.pyd +0 -0
  8. sqlalchemy/cyextension/collections.pyx +409 -0
  9. sqlalchemy/cyextension/immutabledict.cp313t-win_amd64.pyd +0 -0
  10. sqlalchemy/cyextension/immutabledict.pxd +8 -0
  11. sqlalchemy/cyextension/immutabledict.pyx +133 -0
  12. sqlalchemy/cyextension/processors.cp313t-win_amd64.pyd +0 -0
  13. sqlalchemy/cyextension/processors.pyx +68 -0
  14. sqlalchemy/cyextension/resultproxy.cp313t-win_amd64.pyd +0 -0
  15. sqlalchemy/cyextension/resultproxy.pyx +102 -0
  16. sqlalchemy/cyextension/util.cp313t-win_amd64.pyd +0 -0
  17. sqlalchemy/cyextension/util.pyx +90 -0
  18. sqlalchemy/dialects/__init__.py +62 -0
  19. sqlalchemy/dialects/_typing.py +30 -0
  20. sqlalchemy/dialects/mssql/__init__.py +88 -0
  21. sqlalchemy/dialects/mssql/aioodbc.py +63 -0
  22. sqlalchemy/dialects/mssql/base.py +4093 -0
  23. sqlalchemy/dialects/mssql/information_schema.py +285 -0
  24. sqlalchemy/dialects/mssql/json.py +129 -0
  25. sqlalchemy/dialects/mssql/provision.py +185 -0
  26. sqlalchemy/dialects/mssql/pymssql.py +126 -0
  27. sqlalchemy/dialects/mssql/pyodbc.py +760 -0
  28. sqlalchemy/dialects/mysql/__init__.py +104 -0
  29. sqlalchemy/dialects/mysql/aiomysql.py +250 -0
  30. sqlalchemy/dialects/mysql/asyncmy.py +231 -0
  31. sqlalchemy/dialects/mysql/base.py +3949 -0
  32. sqlalchemy/dialects/mysql/cymysql.py +106 -0
  33. sqlalchemy/dialects/mysql/dml.py +225 -0
  34. sqlalchemy/dialects/mysql/enumerated.py +282 -0
  35. sqlalchemy/dialects/mysql/expression.py +146 -0
  36. sqlalchemy/dialects/mysql/json.py +91 -0
  37. sqlalchemy/dialects/mysql/mariadb.py +72 -0
  38. sqlalchemy/dialects/mysql/mariadbconnector.py +322 -0
  39. sqlalchemy/dialects/mysql/mysqlconnector.py +302 -0
  40. sqlalchemy/dialects/mysql/mysqldb.py +314 -0
  41. sqlalchemy/dialects/mysql/provision.py +153 -0
  42. sqlalchemy/dialects/mysql/pymysql.py +158 -0
  43. sqlalchemy/dialects/mysql/pyodbc.py +157 -0
  44. sqlalchemy/dialects/mysql/reflection.py +727 -0
  45. sqlalchemy/dialects/mysql/reserved_words.py +570 -0
  46. sqlalchemy/dialects/mysql/types.py +835 -0
  47. sqlalchemy/dialects/oracle/__init__.py +81 -0
  48. sqlalchemy/dialects/oracle/base.py +3802 -0
  49. sqlalchemy/dialects/oracle/cx_oracle.py +1555 -0
  50. sqlalchemy/dialects/oracle/dictionary.py +507 -0
  51. sqlalchemy/dialects/oracle/oracledb.py +941 -0
  52. sqlalchemy/dialects/oracle/provision.py +297 -0
  53. sqlalchemy/dialects/oracle/types.py +316 -0
  54. sqlalchemy/dialects/oracle/vector.py +365 -0
  55. sqlalchemy/dialects/postgresql/__init__.py +167 -0
  56. sqlalchemy/dialects/postgresql/_psycopg_common.py +189 -0
  57. sqlalchemy/dialects/postgresql/array.py +519 -0
  58. sqlalchemy/dialects/postgresql/asyncpg.py +1284 -0
  59. sqlalchemy/dialects/postgresql/base.py +5378 -0
  60. sqlalchemy/dialects/postgresql/dml.py +339 -0
  61. sqlalchemy/dialects/postgresql/ext.py +540 -0
  62. sqlalchemy/dialects/postgresql/hstore.py +406 -0
  63. sqlalchemy/dialects/postgresql/json.py +404 -0
  64. sqlalchemy/dialects/postgresql/named_types.py +524 -0
  65. sqlalchemy/dialects/postgresql/operators.py +129 -0
  66. sqlalchemy/dialects/postgresql/pg8000.py +669 -0
  67. sqlalchemy/dialects/postgresql/pg_catalog.py +326 -0
  68. sqlalchemy/dialects/postgresql/provision.py +183 -0
  69. sqlalchemy/dialects/postgresql/psycopg.py +862 -0
  70. sqlalchemy/dialects/postgresql/psycopg2.py +892 -0
  71. sqlalchemy/dialects/postgresql/psycopg2cffi.py +61 -0
  72. sqlalchemy/dialects/postgresql/ranges.py +1031 -0
  73. sqlalchemy/dialects/postgresql/types.py +313 -0
  74. sqlalchemy/dialects/sqlite/__init__.py +57 -0
  75. sqlalchemy/dialects/sqlite/aiosqlite.py +482 -0
  76. sqlalchemy/dialects/sqlite/base.py +3056 -0
  77. sqlalchemy/dialects/sqlite/dml.py +263 -0
  78. sqlalchemy/dialects/sqlite/json.py +92 -0
  79. sqlalchemy/dialects/sqlite/provision.py +229 -0
  80. sqlalchemy/dialects/sqlite/pysqlcipher.py +157 -0
  81. sqlalchemy/dialects/sqlite/pysqlite.py +756 -0
  82. sqlalchemy/dialects/type_migration_guidelines.txt +145 -0
  83. sqlalchemy/engine/__init__.py +62 -0
  84. sqlalchemy/engine/_py_processors.py +136 -0
  85. sqlalchemy/engine/_py_row.py +128 -0
  86. sqlalchemy/engine/_py_util.py +74 -0
  87. sqlalchemy/engine/base.py +3390 -0
  88. sqlalchemy/engine/characteristics.py +155 -0
  89. sqlalchemy/engine/create.py +893 -0
  90. sqlalchemy/engine/cursor.py +2298 -0
  91. sqlalchemy/engine/default.py +2394 -0
  92. sqlalchemy/engine/events.py +965 -0
  93. sqlalchemy/engine/interfaces.py +3471 -0
  94. sqlalchemy/engine/mock.py +134 -0
  95. sqlalchemy/engine/processors.py +61 -0
  96. sqlalchemy/engine/reflection.py +2102 -0
  97. sqlalchemy/engine/result.py +2399 -0
  98. sqlalchemy/engine/row.py +400 -0
  99. sqlalchemy/engine/strategies.py +16 -0
  100. sqlalchemy/engine/url.py +924 -0
  101. sqlalchemy/engine/util.py +167 -0
  102. sqlalchemy/event/__init__.py +26 -0
  103. sqlalchemy/event/api.py +220 -0
  104. sqlalchemy/event/attr.py +676 -0
  105. sqlalchemy/event/base.py +472 -0
  106. sqlalchemy/event/legacy.py +258 -0
  107. sqlalchemy/event/registry.py +390 -0
  108. sqlalchemy/events.py +17 -0
  109. sqlalchemy/exc.py +832 -0
  110. sqlalchemy/ext/__init__.py +11 -0
  111. sqlalchemy/ext/associationproxy.py +2027 -0
  112. sqlalchemy/ext/asyncio/__init__.py +25 -0
  113. sqlalchemy/ext/asyncio/base.py +281 -0
  114. sqlalchemy/ext/asyncio/engine.py +1471 -0
  115. sqlalchemy/ext/asyncio/exc.py +21 -0
  116. sqlalchemy/ext/asyncio/result.py +965 -0
  117. sqlalchemy/ext/asyncio/scoping.py +1599 -0
  118. sqlalchemy/ext/asyncio/session.py +1947 -0
  119. sqlalchemy/ext/automap.py +1701 -0
  120. sqlalchemy/ext/baked.py +570 -0
  121. sqlalchemy/ext/compiler.py +600 -0
  122. sqlalchemy/ext/declarative/__init__.py +65 -0
  123. sqlalchemy/ext/declarative/extensions.py +564 -0
  124. sqlalchemy/ext/horizontal_shard.py +478 -0
  125. sqlalchemy/ext/hybrid.py +1535 -0
  126. sqlalchemy/ext/indexable.py +364 -0
  127. sqlalchemy/ext/instrumentation.py +450 -0
  128. sqlalchemy/ext/mutable.py +1085 -0
  129. sqlalchemy/ext/mypy/__init__.py +6 -0
  130. sqlalchemy/ext/mypy/apply.py +324 -0
  131. sqlalchemy/ext/mypy/decl_class.py +515 -0
  132. sqlalchemy/ext/mypy/infer.py +590 -0
  133. sqlalchemy/ext/mypy/names.py +335 -0
  134. sqlalchemy/ext/mypy/plugin.py +303 -0
  135. sqlalchemy/ext/mypy/util.py +357 -0
  136. sqlalchemy/ext/orderinglist.py +439 -0
  137. sqlalchemy/ext/serializer.py +185 -0
  138. sqlalchemy/future/__init__.py +16 -0
  139. sqlalchemy/future/engine.py +15 -0
  140. sqlalchemy/inspection.py +174 -0
  141. sqlalchemy/log.py +288 -0
  142. sqlalchemy/orm/__init__.py +171 -0
  143. sqlalchemy/orm/_orm_constructors.py +2661 -0
  144. sqlalchemy/orm/_typing.py +179 -0
  145. sqlalchemy/orm/attributes.py +2845 -0
  146. sqlalchemy/orm/base.py +971 -0
  147. sqlalchemy/orm/bulk_persistence.py +2135 -0
  148. sqlalchemy/orm/clsregistry.py +571 -0
  149. sqlalchemy/orm/collections.py +1627 -0
  150. sqlalchemy/orm/context.py +3334 -0
  151. sqlalchemy/orm/decl_api.py +2004 -0
  152. sqlalchemy/orm/decl_base.py +2192 -0
  153. sqlalchemy/orm/dependency.py +1302 -0
  154. sqlalchemy/orm/descriptor_props.py +1092 -0
  155. sqlalchemy/orm/dynamic.py +300 -0
  156. sqlalchemy/orm/evaluator.py +379 -0
  157. sqlalchemy/orm/events.py +3252 -0
  158. sqlalchemy/orm/exc.py +237 -0
  159. sqlalchemy/orm/identity.py +302 -0
  160. sqlalchemy/orm/instrumentation.py +754 -0
  161. sqlalchemy/orm/interfaces.py +1496 -0
  162. sqlalchemy/orm/loading.py +1686 -0
  163. sqlalchemy/orm/mapped_collection.py +557 -0
  164. sqlalchemy/orm/mapper.py +4444 -0
  165. sqlalchemy/orm/path_registry.py +809 -0
  166. sqlalchemy/orm/persistence.py +1788 -0
  167. sqlalchemy/orm/properties.py +935 -0
  168. sqlalchemy/orm/query.py +3459 -0
  169. sqlalchemy/orm/relationships.py +3508 -0
  170. sqlalchemy/orm/scoping.py +2148 -0
  171. sqlalchemy/orm/session.py +5280 -0
  172. sqlalchemy/orm/state.py +1168 -0
  173. sqlalchemy/orm/state_changes.py +196 -0
  174. sqlalchemy/orm/strategies.py +3470 -0
  175. sqlalchemy/orm/strategy_options.py +2568 -0
  176. sqlalchemy/orm/sync.py +164 -0
  177. sqlalchemy/orm/unitofwork.py +796 -0
  178. sqlalchemy/orm/util.py +2403 -0
  179. sqlalchemy/orm/writeonly.py +674 -0
  180. sqlalchemy/pool/__init__.py +44 -0
  181. sqlalchemy/pool/base.py +1524 -0
  182. sqlalchemy/pool/events.py +375 -0
  183. sqlalchemy/pool/impl.py +588 -0
  184. sqlalchemy/py.typed +0 -0
  185. sqlalchemy/schema.py +69 -0
  186. sqlalchemy/sql/__init__.py +145 -0
  187. sqlalchemy/sql/_dml_constructors.py +132 -0
  188. sqlalchemy/sql/_elements_constructors.py +1872 -0
  189. sqlalchemy/sql/_orm_types.py +20 -0
  190. sqlalchemy/sql/_py_util.py +75 -0
  191. sqlalchemy/sql/_selectable_constructors.py +763 -0
  192. sqlalchemy/sql/_typing.py +482 -0
  193. sqlalchemy/sql/annotation.py +587 -0
  194. sqlalchemy/sql/base.py +2293 -0
  195. sqlalchemy/sql/cache_key.py +1057 -0
  196. sqlalchemy/sql/coercions.py +1404 -0
  197. sqlalchemy/sql/compiler.py +8081 -0
  198. sqlalchemy/sql/crud.py +1752 -0
  199. sqlalchemy/sql/ddl.py +1444 -0
  200. sqlalchemy/sql/default_comparator.py +551 -0
  201. sqlalchemy/sql/dml.py +1850 -0
  202. sqlalchemy/sql/elements.py +5589 -0
  203. sqlalchemy/sql/events.py +458 -0
  204. sqlalchemy/sql/expression.py +159 -0
  205. sqlalchemy/sql/functions.py +2158 -0
  206. sqlalchemy/sql/lambdas.py +1442 -0
  207. sqlalchemy/sql/naming.py +209 -0
  208. sqlalchemy/sql/operators.py +2623 -0
  209. sqlalchemy/sql/roles.py +323 -0
  210. sqlalchemy/sql/schema.py +6222 -0
  211. sqlalchemy/sql/selectable.py +7265 -0
  212. sqlalchemy/sql/sqltypes.py +3930 -0
  213. sqlalchemy/sql/traversals.py +1024 -0
  214. sqlalchemy/sql/type_api.py +2368 -0
  215. sqlalchemy/sql/util.py +1485 -0
  216. sqlalchemy/sql/visitors.py +1164 -0
  217. sqlalchemy/testing/__init__.py +96 -0
  218. sqlalchemy/testing/assertions.py +994 -0
  219. sqlalchemy/testing/assertsql.py +520 -0
  220. sqlalchemy/testing/asyncio.py +135 -0
  221. sqlalchemy/testing/config.py +434 -0
  222. sqlalchemy/testing/engines.py +483 -0
  223. sqlalchemy/testing/entities.py +117 -0
  224. sqlalchemy/testing/exclusions.py +476 -0
  225. sqlalchemy/testing/fixtures/__init__.py +28 -0
  226. sqlalchemy/testing/fixtures/base.py +384 -0
  227. sqlalchemy/testing/fixtures/mypy.py +332 -0
  228. sqlalchemy/testing/fixtures/orm.py +227 -0
  229. sqlalchemy/testing/fixtures/sql.py +482 -0
  230. sqlalchemy/testing/pickleable.py +155 -0
  231. sqlalchemy/testing/plugin/__init__.py +6 -0
  232. sqlalchemy/testing/plugin/bootstrap.py +51 -0
  233. sqlalchemy/testing/plugin/plugin_base.py +828 -0
  234. sqlalchemy/testing/plugin/pytestplugin.py +892 -0
  235. sqlalchemy/testing/profiling.py +329 -0
  236. sqlalchemy/testing/provision.py +603 -0
  237. sqlalchemy/testing/requirements.py +1945 -0
  238. sqlalchemy/testing/schema.py +198 -0
  239. sqlalchemy/testing/suite/__init__.py +19 -0
  240. sqlalchemy/testing/suite/test_cte.py +237 -0
  241. sqlalchemy/testing/suite/test_ddl.py +389 -0
  242. sqlalchemy/testing/suite/test_deprecations.py +153 -0
  243. sqlalchemy/testing/suite/test_dialect.py +776 -0
  244. sqlalchemy/testing/suite/test_insert.py +630 -0
  245. sqlalchemy/testing/suite/test_reflection.py +3557 -0
  246. sqlalchemy/testing/suite/test_results.py +504 -0
  247. sqlalchemy/testing/suite/test_rowcount.py +258 -0
  248. sqlalchemy/testing/suite/test_select.py +2010 -0
  249. sqlalchemy/testing/suite/test_sequence.py +317 -0
  250. sqlalchemy/testing/suite/test_types.py +2147 -0
  251. sqlalchemy/testing/suite/test_unicode_ddl.py +189 -0
  252. sqlalchemy/testing/suite/test_update_delete.py +139 -0
  253. sqlalchemy/testing/util.py +535 -0
  254. sqlalchemy/testing/warnings.py +52 -0
  255. sqlalchemy/types.py +74 -0
  256. sqlalchemy/util/__init__.py +162 -0
  257. sqlalchemy/util/_collections.py +712 -0
  258. sqlalchemy/util/_concurrency_py3k.py +288 -0
  259. sqlalchemy/util/_has_cy.py +40 -0
  260. sqlalchemy/util/_py_collections.py +541 -0
  261. sqlalchemy/util/compat.py +421 -0
  262. sqlalchemy/util/concurrency.py +110 -0
  263. sqlalchemy/util/deprecations.py +401 -0
  264. sqlalchemy/util/langhelpers.py +2203 -0
  265. sqlalchemy/util/preloaded.py +150 -0
  266. sqlalchemy/util/queue.py +322 -0
  267. sqlalchemy/util/tool_support.py +201 -0
  268. sqlalchemy/util/topological.py +120 -0
  269. sqlalchemy/util/typing.py +734 -0
  270. sqlalchemy-2.0.47.dist-info/METADATA +243 -0
  271. sqlalchemy-2.0.47.dist-info/RECORD +274 -0
  272. sqlalchemy-2.0.47.dist-info/WHEEL +5 -0
  273. sqlalchemy-2.0.47.dist-info/licenses/LICENSE +19 -0
  274. sqlalchemy-2.0.47.dist-info/top_level.txt +1 -0
@@ -0,0 +1,3930 @@
1
+ # sql/sqltypes.py
2
+ # Copyright (C) 2005-2026 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
+ # mypy: allow-untyped-defs, allow-untyped-calls
8
+
9
+ """SQL specific types."""
10
+ from __future__ import annotations
11
+
12
+ import collections.abc as collections_abc
13
+ import datetime as dt
14
+ import decimal
15
+ import enum
16
+ import json
17
+ import pickle
18
+ from typing import Any
19
+ from typing import Callable
20
+ from typing import cast
21
+ from typing import Dict
22
+ from typing import Iterable
23
+ from typing import List
24
+ from typing import Mapping
25
+ from typing import Optional
26
+ from typing import overload
27
+ from typing import Sequence
28
+ from typing import Tuple
29
+ from typing import Type
30
+ from typing import TYPE_CHECKING
31
+ from typing import TypeVar
32
+ from typing import Union
33
+ from uuid import UUID as _python_UUID
34
+
35
+ from . import coercions
36
+ from . import elements
37
+ from . import operators
38
+ from . import roles
39
+ from . import type_api
40
+ from .base import _NONE_NAME
41
+ from .base import NO_ARG
42
+ from .base import SchemaEventTarget
43
+ from .cache_key import HasCacheKey
44
+ from .elements import quoted_name
45
+ from .elements import Slice
46
+ from .elements import TypeCoerce as type_coerce # noqa
47
+ from .type_api import Emulated
48
+ from .type_api import NativeForEmulated # noqa
49
+ from .type_api import to_instance as to_instance
50
+ from .type_api import TypeDecorator as TypeDecorator
51
+ from .type_api import TypeEngine as TypeEngine
52
+ from .type_api import TypeEngineMixin
53
+ from .type_api import Variant # noqa
54
+ from .visitors import InternalTraversal
55
+ from .. import event
56
+ from .. import exc
57
+ from .. import inspection
58
+ from .. import util
59
+ from ..engine import processors
60
+ from ..util import langhelpers
61
+ from ..util import OrderedDict
62
+ from ..util import warn_deprecated
63
+ from ..util.typing import get_args
64
+ from ..util.typing import is_literal
65
+ from ..util.typing import is_pep695
66
+ from ..util.typing import Literal
67
+
68
+ if TYPE_CHECKING:
69
+ from ._typing import _ColumnExpressionArgument
70
+ from ._typing import _CreateDropBind
71
+ from ._typing import _TypeEngineArgument
72
+ from .elements import ColumnElement
73
+ from .operators import OperatorType
74
+ from .schema import MetaData
75
+ from .type_api import _BindProcessorType
76
+ from .type_api import _ComparatorFactory
77
+ from .type_api import _LiteralProcessorType
78
+ from .type_api import _MatchedOnType
79
+ from .type_api import _ResultProcessorType
80
+ from ..engine.interfaces import Dialect
81
+
82
+ _T = TypeVar("_T", bound="Any")
83
+ _CT = TypeVar("_CT", bound=Any)
84
+ _TE = TypeVar("_TE", bound="TypeEngine[Any]")
85
+ _P = TypeVar("_P")
86
+
87
+
88
+ class HasExpressionLookup(TypeEngineMixin):
89
+ """Mixin expression adaptations based on lookup tables.
90
+
91
+ These rules are currently used by the numeric, integer and date types
92
+ which have detailed cross-expression coercion rules.
93
+
94
+ """
95
+
96
+ @property
97
+ def _expression_adaptations(self):
98
+ raise NotImplementedError()
99
+
100
+ class Comparator(TypeEngine.Comparator[_CT]):
101
+ __slots__ = ()
102
+
103
+ _blank_dict = util.EMPTY_DICT
104
+
105
+ def _adapt_expression(
106
+ self,
107
+ op: OperatorType,
108
+ other_comparator: TypeEngine.Comparator[Any],
109
+ ) -> Tuple[OperatorType, TypeEngine[Any]]:
110
+ othertype = other_comparator.type._type_affinity
111
+ if TYPE_CHECKING:
112
+ assert isinstance(self.type, HasExpressionLookup)
113
+ lookup = self.type._expression_adaptations.get(
114
+ op, self._blank_dict
115
+ ).get(othertype, self.type)
116
+ if lookup is othertype:
117
+ return (op, other_comparator.type)
118
+ elif lookup is self.type._type_affinity:
119
+ return (op, self.type)
120
+ else:
121
+ return (op, to_instance(lookup))
122
+
123
+ comparator_factory: _ComparatorFactory[Any] = Comparator
124
+
125
+
126
+ class Concatenable(TypeEngineMixin):
127
+ """A mixin that marks a type as supporting 'concatenation',
128
+ typically strings."""
129
+
130
+ class Comparator(TypeEngine.Comparator[_T]):
131
+ __slots__ = ()
132
+
133
+ def _adapt_expression(
134
+ self,
135
+ op: OperatorType,
136
+ other_comparator: TypeEngine.Comparator[Any],
137
+ ) -> Tuple[OperatorType, TypeEngine[Any]]:
138
+ if op is operators.add and isinstance(
139
+ other_comparator,
140
+ (Concatenable.Comparator, NullType.Comparator),
141
+ ):
142
+ return operators.concat_op, self.expr.type
143
+ else:
144
+ return super()._adapt_expression(op, other_comparator)
145
+
146
+ comparator_factory: _ComparatorFactory[Any] = Comparator
147
+
148
+
149
+ class Indexable(TypeEngineMixin):
150
+ """A mixin that marks a type as supporting indexing operations,
151
+ such as array or JSON structures.
152
+
153
+ """
154
+
155
+ class Comparator(TypeEngine.Comparator[_T]):
156
+ __slots__ = ()
157
+
158
+ def _setup_getitem(self, index):
159
+ raise NotImplementedError()
160
+
161
+ def __getitem__(self, index):
162
+ (
163
+ adjusted_op,
164
+ adjusted_right_expr,
165
+ result_type,
166
+ ) = self._setup_getitem(index)
167
+ return self.operate(
168
+ adjusted_op, adjusted_right_expr, result_type=result_type
169
+ )
170
+
171
+ comparator_factory: _ComparatorFactory[Any] = Comparator
172
+
173
+
174
+ class String(Concatenable, TypeEngine[str]):
175
+ """The base for all string and character types.
176
+
177
+ In SQL, corresponds to VARCHAR.
178
+
179
+ The `length` field is usually required when the `String` type is
180
+ used within a CREATE TABLE statement, as VARCHAR requires a length
181
+ on most databases.
182
+
183
+ """
184
+
185
+ __visit_name__ = "string"
186
+
187
+ def __init__(
188
+ self,
189
+ length: Optional[int] = None,
190
+ collation: Optional[str] = None,
191
+ ):
192
+ """
193
+ Create a string-holding type.
194
+
195
+ :param length: optional, a length for the column for use in
196
+ DDL and CAST expressions. May be safely omitted if no ``CREATE
197
+ TABLE`` will be issued. Certain databases may require a
198
+ ``length`` for use in DDL, and will raise an exception when
199
+ the ``CREATE TABLE`` DDL is issued if a ``VARCHAR``
200
+ with no length is included. Whether the value is
201
+ interpreted as bytes or characters is database specific.
202
+
203
+ :param collation: Optional, a column-level collation for
204
+ use in DDL and CAST expressions. Renders using the
205
+ COLLATE keyword supported by SQLite, MySQL, and PostgreSQL.
206
+ E.g.:
207
+
208
+ .. sourcecode:: pycon+sql
209
+
210
+ >>> from sqlalchemy import cast, select, String
211
+ >>> print(select(cast("some string", String(collation="utf8"))))
212
+ {printsql}SELECT CAST(:param_1 AS VARCHAR COLLATE utf8) AS anon_1
213
+
214
+ .. note::
215
+
216
+ In most cases, the :class:`.Unicode` or :class:`.UnicodeText`
217
+ datatypes should be used for a :class:`_schema.Column` that expects
218
+ to store non-ascii data. These datatypes will ensure that the
219
+ correct types are used on the database.
220
+
221
+ """
222
+
223
+ self.length = length
224
+ self.collation = collation
225
+
226
+ def _with_collation(self, collation):
227
+ new_type = self.copy()
228
+ new_type.collation = collation
229
+ return new_type
230
+
231
+ def _resolve_for_literal(self, value):
232
+ # I was SO PROUD of my regex trick, but we dont need it.
233
+ # re.search(r"[^\u0000-\u007F]", value)
234
+
235
+ if value.isascii():
236
+ return _STRING
237
+ else:
238
+ return _UNICODE
239
+
240
+ def literal_processor(self, dialect):
241
+ def process(value):
242
+ value = value.replace("'", "''")
243
+
244
+ if dialect.identifier_preparer._double_percents:
245
+ value = value.replace("%", "%%")
246
+
247
+ return "'%s'" % value
248
+
249
+ return process
250
+
251
+ def bind_processor(
252
+ self, dialect: Dialect
253
+ ) -> Optional[_BindProcessorType[str]]:
254
+ return None
255
+
256
+ def result_processor(
257
+ self, dialect: Dialect, coltype: object
258
+ ) -> Optional[_ResultProcessorType[str]]:
259
+ return None
260
+
261
+ @property
262
+ def python_type(self):
263
+ return str
264
+
265
+ def get_dbapi_type(self, dbapi):
266
+ return dbapi.STRING
267
+
268
+
269
+ class Text(String):
270
+ """A variably sized string type.
271
+
272
+ In SQL, usually corresponds to CLOB or TEXT. In general, TEXT objects
273
+ do not have a length; while some databases will accept a length
274
+ argument here, it will be rejected by others.
275
+
276
+ """
277
+
278
+ __visit_name__ = "text"
279
+
280
+
281
+ class Unicode(String):
282
+ """A variable length Unicode string type.
283
+
284
+ The :class:`.Unicode` type is a :class:`.String` subclass that assumes
285
+ input and output strings that may contain non-ASCII characters, and for
286
+ some backends implies an underlying column type that is explicitly
287
+ supporting of non-ASCII data, such as ``NVARCHAR`` on Oracle Database and
288
+ SQL Server. This will impact the output of ``CREATE TABLE`` statements and
289
+ ``CAST`` functions at the dialect level.
290
+
291
+ The character encoding used by the :class:`.Unicode` type that is used to
292
+ transmit and receive data to the database is usually determined by the
293
+ DBAPI itself. All modern DBAPIs accommodate non-ASCII strings but may have
294
+ different methods of managing database encodings; if necessary, this
295
+ encoding should be configured as detailed in the notes for the target DBAPI
296
+ in the :ref:`dialect_toplevel` section.
297
+
298
+ In modern SQLAlchemy, use of the :class:`.Unicode` datatype does not
299
+ imply any encoding/decoding behavior within SQLAlchemy itself. In Python
300
+ 3, all string objects are inherently Unicode capable, and SQLAlchemy
301
+ does not produce bytestring objects nor does it accommodate a DBAPI that
302
+ does not return Python Unicode objects in result sets for string values.
303
+
304
+ .. warning:: Some database backends, particularly SQL Server with pyodbc,
305
+ are known to have undesirable behaviors regarding data that is noted
306
+ as being of ``NVARCHAR`` type as opposed to ``VARCHAR``, including
307
+ datatype mismatch errors and non-use of indexes. See the section
308
+ on :meth:`.DialectEvents.do_setinputsizes` for background on working
309
+ around unicode character issues for backends like SQL Server with
310
+ pyodbc as well as cx_Oracle.
311
+
312
+ .. seealso::
313
+
314
+ :class:`.UnicodeText` - unlengthed textual counterpart
315
+ to :class:`.Unicode`.
316
+
317
+ :meth:`.DialectEvents.do_setinputsizes`
318
+
319
+ """
320
+
321
+ __visit_name__ = "unicode"
322
+
323
+
324
+ class UnicodeText(Text):
325
+ """An unbounded-length Unicode string type.
326
+
327
+ See :class:`.Unicode` for details on the unicode
328
+ behavior of this object.
329
+
330
+ Like :class:`.Unicode`, usage the :class:`.UnicodeText` type implies a
331
+ unicode-capable type being used on the backend, such as
332
+ ``NCLOB``, ``NTEXT``.
333
+
334
+ """
335
+
336
+ __visit_name__ = "unicode_text"
337
+
338
+
339
+ class Integer(HasExpressionLookup, TypeEngine[int]):
340
+ """A type for ``int`` integers."""
341
+
342
+ __visit_name__ = "integer"
343
+
344
+ if TYPE_CHECKING:
345
+
346
+ @util.ro_memoized_property
347
+ def _type_affinity(self) -> Type[Integer]: ...
348
+
349
+ def get_dbapi_type(self, dbapi):
350
+ return dbapi.NUMBER
351
+
352
+ @property
353
+ def python_type(self):
354
+ return int
355
+
356
+ def _resolve_for_literal(self, value):
357
+ if value.bit_length() >= 32:
358
+ return _BIGINTEGER
359
+ else:
360
+ return self
361
+
362
+ def literal_processor(self, dialect):
363
+ def process(value):
364
+ return str(int(value))
365
+
366
+ return process
367
+
368
+ @util.memoized_property
369
+ def _expression_adaptations(self):
370
+ return {
371
+ operators.add: {
372
+ Date: Date,
373
+ Integer: self.__class__,
374
+ Numeric: Numeric,
375
+ },
376
+ operators.mul: {
377
+ Interval: Interval,
378
+ Integer: self.__class__,
379
+ Numeric: Numeric,
380
+ },
381
+ operators.truediv: {Integer: Numeric, Numeric: Numeric},
382
+ operators.floordiv: {Integer: self.__class__, Numeric: Numeric},
383
+ operators.sub: {Integer: self.__class__, Numeric: Numeric},
384
+ }
385
+
386
+
387
+ class SmallInteger(Integer):
388
+ """A type for smaller ``int`` integers.
389
+
390
+ Typically generates a ``SMALLINT`` in DDL, and otherwise acts like
391
+ a normal :class:`.Integer` on the Python side.
392
+
393
+ """
394
+
395
+ __visit_name__ = "small_integer"
396
+
397
+
398
+ class BigInteger(Integer):
399
+ """A type for bigger ``int`` integers.
400
+
401
+ Typically generates a ``BIGINT`` in DDL, and otherwise acts like
402
+ a normal :class:`.Integer` on the Python side.
403
+
404
+ """
405
+
406
+ __visit_name__ = "big_integer"
407
+
408
+
409
+ _N = TypeVar("_N", bound=Union[decimal.Decimal, float])
410
+
411
+
412
+ class Numeric(HasExpressionLookup, TypeEngine[_N]):
413
+ """Base for non-integer numeric types, such as
414
+ ``NUMERIC``, ``FLOAT``, ``DECIMAL``, and other variants.
415
+
416
+ The :class:`.Numeric` datatype when used directly will render DDL
417
+ corresponding to precision numerics if available, such as
418
+ ``NUMERIC(precision, scale)``. The :class:`.Float` subclass will
419
+ attempt to render a floating-point datatype such as ``FLOAT(precision)``.
420
+
421
+ :class:`.Numeric` returns Python ``decimal.Decimal`` objects by default,
422
+ based on the default value of ``True`` for the
423
+ :paramref:`.Numeric.asdecimal` parameter. If this parameter is set to
424
+ False, returned values are coerced to Python ``float`` objects.
425
+
426
+ The :class:`.Float` subtype, being more specific to floating point,
427
+ defaults the :paramref:`.Float.asdecimal` flag to False so that the
428
+ default Python datatype is ``float``.
429
+
430
+ .. note::
431
+
432
+ When using a :class:`.Numeric` datatype against a database type that
433
+ returns Python floating point values to the driver, the accuracy of the
434
+ decimal conversion indicated by :paramref:`.Numeric.asdecimal` may be
435
+ limited. The behavior of specific numeric/floating point datatypes
436
+ is a product of the SQL datatype in use, the Python :term:`DBAPI`
437
+ in use, as well as strategies that may be present within
438
+ the SQLAlchemy dialect in use. Users requiring specific precision/
439
+ scale are encouraged to experiment with the available datatypes
440
+ in order to determine the best results.
441
+
442
+ """
443
+
444
+ __visit_name__ = "numeric"
445
+
446
+ if TYPE_CHECKING:
447
+
448
+ @util.ro_memoized_property
449
+ def _type_affinity(self) -> Type[Numeric[_N]]: ...
450
+
451
+ _default_decimal_return_scale = 10
452
+
453
+ @overload
454
+ def __init__(
455
+ self: Numeric[decimal.Decimal],
456
+ precision: Optional[int] = ...,
457
+ scale: Optional[int] = ...,
458
+ decimal_return_scale: Optional[int] = ...,
459
+ asdecimal: Literal[True] = ...,
460
+ ): ...
461
+
462
+ @overload
463
+ def __init__(
464
+ self: Numeric[float],
465
+ precision: Optional[int] = ...,
466
+ scale: Optional[int] = ...,
467
+ decimal_return_scale: Optional[int] = ...,
468
+ asdecimal: Literal[False] = ...,
469
+ ): ...
470
+
471
+ def __init__(
472
+ self,
473
+ precision: Optional[int] = None,
474
+ scale: Optional[int] = None,
475
+ decimal_return_scale: Optional[int] = None,
476
+ asdecimal: bool = True,
477
+ ):
478
+ """
479
+ Construct a Numeric.
480
+
481
+ :param precision: the numeric precision for use in DDL ``CREATE
482
+ TABLE``.
483
+
484
+ :param scale: the numeric scale for use in DDL ``CREATE TABLE``.
485
+
486
+ :param asdecimal: default True. Return whether or not
487
+ values should be sent as Python Decimal objects, or
488
+ as floats. Different DBAPIs send one or the other based on
489
+ datatypes - the Numeric type will ensure that return values
490
+ are one or the other across DBAPIs consistently.
491
+
492
+ :param decimal_return_scale: Default scale to use when converting
493
+ from floats to Python decimals. Floating point values will typically
494
+ be much longer due to decimal inaccuracy, and most floating point
495
+ database types don't have a notion of "scale", so by default the
496
+ float type looks for the first ten decimal places when converting.
497
+ Specifying this value will override that length. Types which
498
+ do include an explicit ".scale" value, such as the base
499
+ :class:`.Numeric` as well as the MySQL float types, will use the
500
+ value of ".scale" as the default for decimal_return_scale, if not
501
+ otherwise specified.
502
+
503
+ When using the ``Numeric`` type, care should be taken to ensure
504
+ that the asdecimal setting is appropriate for the DBAPI in use -
505
+ when Numeric applies a conversion from Decimal->float or float->
506
+ Decimal, this conversion incurs an additional performance overhead
507
+ for all result columns received.
508
+
509
+ DBAPIs that return Decimal natively (e.g. psycopg2) will have
510
+ better accuracy and higher performance with a setting of ``True``,
511
+ as the native translation to Decimal reduces the amount of floating-
512
+ point issues at play, and the Numeric type itself doesn't need
513
+ to apply any further conversions. However, another DBAPI which
514
+ returns floats natively *will* incur an additional conversion
515
+ overhead, and is still subject to floating point data loss - in
516
+ which case ``asdecimal=False`` will at least remove the extra
517
+ conversion overhead.
518
+
519
+ """
520
+ self.precision = precision
521
+ self.scale = scale
522
+ self.decimal_return_scale = decimal_return_scale
523
+ self.asdecimal = asdecimal
524
+
525
+ @property
526
+ def _effective_decimal_return_scale(self):
527
+ if self.decimal_return_scale is not None:
528
+ return self.decimal_return_scale
529
+ elif getattr(self, "scale", None) is not None:
530
+ return self.scale
531
+ else:
532
+ return self._default_decimal_return_scale
533
+
534
+ def get_dbapi_type(self, dbapi):
535
+ return dbapi.NUMBER
536
+
537
+ def literal_processor(self, dialect):
538
+ def process(value):
539
+ return str(value)
540
+
541
+ return process
542
+
543
+ @property
544
+ def python_type(self):
545
+ if self.asdecimal:
546
+ return decimal.Decimal
547
+ else:
548
+ return float
549
+
550
+ def bind_processor(self, dialect):
551
+ if dialect.supports_native_decimal:
552
+ return None
553
+ else:
554
+ return processors.to_float
555
+
556
+ def result_processor(self, dialect, coltype):
557
+ if self.asdecimal:
558
+ if dialect.supports_native_decimal:
559
+ # we're a "numeric", DBAPI will give us Decimal directly
560
+ return None
561
+ else:
562
+ # we're a "numeric", DBAPI returns floats, convert.
563
+ return processors.to_decimal_processor_factory(
564
+ decimal.Decimal,
565
+ (
566
+ self.scale
567
+ if self.scale is not None
568
+ else self._default_decimal_return_scale
569
+ ),
570
+ )
571
+ else:
572
+ if dialect.supports_native_decimal:
573
+ return processors.to_float
574
+ else:
575
+ return None
576
+
577
+ @util.memoized_property
578
+ def _expression_adaptations(self):
579
+ return {
580
+ operators.mul: {
581
+ Interval: Interval,
582
+ Numeric: self.__class__,
583
+ Integer: self.__class__,
584
+ },
585
+ operators.truediv: {
586
+ Numeric: self.__class__,
587
+ Integer: self.__class__,
588
+ },
589
+ operators.add: {Numeric: self.__class__, Integer: self.__class__},
590
+ operators.sub: {Numeric: self.__class__, Integer: self.__class__},
591
+ }
592
+
593
+
594
+ class Float(Numeric[_N]):
595
+ """Type representing floating point types, such as ``FLOAT`` or ``REAL``.
596
+
597
+ This type returns Python ``float`` objects by default, unless the
598
+ :paramref:`.Float.asdecimal` flag is set to ``True``, in which case they
599
+ are coerced to ``decimal.Decimal`` objects.
600
+
601
+ When a :paramref:`.Float.precision` is not provided in a
602
+ :class:`_types.Float` type some backend may compile this type as
603
+ an 8 bytes / 64 bit float datatype. To use a 4 bytes / 32 bit float
604
+ datatype a precision <= 24 can usually be provided or the
605
+ :class:`_types.REAL` type can be used.
606
+ This is known to be the case in the PostgreSQL and MSSQL dialects
607
+ that render the type as ``FLOAT`` that's in both an alias of
608
+ ``DOUBLE PRECISION``. Other third party dialects may have similar
609
+ behavior.
610
+ """
611
+
612
+ __visit_name__ = "float"
613
+
614
+ if not TYPE_CHECKING:
615
+ # this is not in 2.1 branch, not clear if needed for 2.0
616
+ # implementation
617
+ scale = None
618
+
619
+ @overload
620
+ def __init__(
621
+ self: Float[float],
622
+ precision: Optional[int] = ...,
623
+ asdecimal: Literal[False] = ...,
624
+ decimal_return_scale: Optional[int] = ...,
625
+ ): ...
626
+
627
+ @overload
628
+ def __init__(
629
+ self: Float[decimal.Decimal],
630
+ precision: Optional[int] = ...,
631
+ asdecimal: Literal[True] = ...,
632
+ decimal_return_scale: Optional[int] = ...,
633
+ ): ...
634
+
635
+ def __init__(
636
+ self: Float[_N],
637
+ precision: Optional[int] = None,
638
+ asdecimal: bool = False,
639
+ decimal_return_scale: Optional[int] = None,
640
+ ):
641
+ r"""
642
+ Construct a Float.
643
+
644
+ :param precision: the numeric precision for use in DDL ``CREATE
645
+ TABLE``. Backends **should** attempt to ensure this precision
646
+ indicates a number of digits for the generic
647
+ :class:`_sqltypes.Float` datatype.
648
+
649
+ .. note:: For the Oracle Database backend, the
650
+ :paramref:`_sqltypes.Float.precision` parameter is not accepted
651
+ when rendering DDL, as Oracle Database does not support float precision
652
+ specified as a number of decimal places. Instead, use the
653
+ Oracle Database-specific :class:`_oracle.FLOAT` datatype and specify the
654
+ :paramref:`_oracle.FLOAT.binary_precision` parameter. This is new
655
+ in version 2.0 of SQLAlchemy.
656
+
657
+ To create a database agnostic :class:`_types.Float` that
658
+ separately specifies binary precision for Oracle Database, use
659
+ :meth:`_types.TypeEngine.with_variant` as follows::
660
+
661
+ from sqlalchemy import Column
662
+ from sqlalchemy import Float
663
+ from sqlalchemy.dialects import oracle
664
+
665
+ Column(
666
+ "float_data",
667
+ Float(5).with_variant(oracle.FLOAT(binary_precision=16), "oracle"),
668
+ )
669
+
670
+ :param asdecimal: the same flag as that of :class:`.Numeric`, but
671
+ defaults to ``False``. Note that setting this flag to ``True``
672
+ results in floating point conversion.
673
+
674
+ :param decimal_return_scale: Default scale to use when converting
675
+ from floats to Python decimals. Floating point values will typically
676
+ be much longer due to decimal inaccuracy, and most floating point
677
+ database types don't have a notion of "scale", so by default the
678
+ float type looks for the first ten decimal places when converting.
679
+ Specifying this value will override that length. Note that the
680
+ MySQL float types, which do include "scale", will use "scale"
681
+ as the default for decimal_return_scale, if not otherwise specified.
682
+
683
+ """ # noqa: E501
684
+ self.precision = precision
685
+ self.asdecimal = asdecimal
686
+ self.decimal_return_scale = decimal_return_scale
687
+
688
+ def result_processor(self, dialect, coltype):
689
+ if self.asdecimal:
690
+ return processors.to_decimal_processor_factory(
691
+ decimal.Decimal, self._effective_decimal_return_scale
692
+ )
693
+ elif dialect.supports_native_decimal:
694
+ return processors.to_float
695
+ else:
696
+ return None
697
+
698
+
699
+ class Double(Float[_N]):
700
+ """A type for double ``FLOAT`` floating point types.
701
+
702
+ Typically generates a ``DOUBLE`` or ``DOUBLE_PRECISION`` in DDL,
703
+ and otherwise acts like a normal :class:`.Float` on the Python
704
+ side.
705
+
706
+ .. versionadded:: 2.0
707
+
708
+ """
709
+
710
+ __visit_name__ = "double"
711
+
712
+
713
+ class _RenderISO8601NoT:
714
+ def _literal_processor_datetime(self, dialect):
715
+ return self._literal_processor_portion(dialect, None)
716
+
717
+ def _literal_processor_date(self, dialect):
718
+ return self._literal_processor_portion(dialect, 0)
719
+
720
+ def _literal_processor_time(self, dialect):
721
+ return self._literal_processor_portion(dialect, -1)
722
+
723
+ def _literal_processor_portion(self, dialect, _portion=None):
724
+ assert _portion in (None, 0, -1)
725
+ if _portion is not None:
726
+
727
+ def process(value):
728
+ return f"""'{value.isoformat().split("T")[_portion]}'"""
729
+
730
+ else:
731
+
732
+ def process(value):
733
+ return f"""'{value.isoformat().replace("T", " ")}'"""
734
+
735
+ return process
736
+
737
+
738
+ class DateTime(
739
+ _RenderISO8601NoT, HasExpressionLookup, TypeEngine[dt.datetime]
740
+ ):
741
+ """A type for ``datetime.datetime()`` objects.
742
+
743
+ Date and time types return objects from the Python ``datetime``
744
+ module. Most DBAPIs have built in support for the datetime
745
+ module, with the noted exception of SQLite. In the case of
746
+ SQLite, date and time types are stored as strings which are then
747
+ converted back to datetime objects when rows are returned.
748
+
749
+ For the time representation within the datetime type, some
750
+ backends include additional options, such as timezone support and
751
+ fractional seconds support. For fractional seconds, use the
752
+ dialect-specific datatype, such as :class:`.mysql.TIME`. For
753
+ timezone support, use at least the :class:`_types.TIMESTAMP` datatype,
754
+ if not the dialect-specific datatype object.
755
+
756
+ """
757
+
758
+ __visit_name__ = "datetime"
759
+
760
+ def __init__(self, timezone: bool = False):
761
+ """Construct a new :class:`.DateTime`.
762
+
763
+ :param timezone: boolean. Indicates that the datetime type should
764
+ enable timezone support, if available on the
765
+ **base date/time-holding type only**. It is recommended
766
+ to make use of the :class:`_types.TIMESTAMP` datatype directly when
767
+ using this flag, as some databases include separate generic
768
+ date/time-holding types distinct from the timezone-capable
769
+ TIMESTAMP datatype, such as Oracle Database.
770
+
771
+
772
+ """
773
+ self.timezone = timezone
774
+
775
+ def get_dbapi_type(self, dbapi):
776
+ return dbapi.DATETIME
777
+
778
+ def _resolve_for_literal(self, value):
779
+ with_timezone = value.tzinfo is not None
780
+ if with_timezone and not self.timezone:
781
+ return DATETIME_TIMEZONE
782
+ else:
783
+ return self
784
+
785
+ def literal_processor(self, dialect):
786
+ return self._literal_processor_datetime(dialect)
787
+
788
+ @property
789
+ def python_type(self):
790
+ return dt.datetime
791
+
792
+ @util.memoized_property
793
+ def _expression_adaptations(self):
794
+ # Based on
795
+ # https://www.postgresql.org/docs/current/static/functions-datetime.html.
796
+
797
+ return {
798
+ operators.add: {Interval: self.__class__},
799
+ operators.sub: {Interval: self.__class__, DateTime: Interval},
800
+ }
801
+
802
+
803
+ class Date(_RenderISO8601NoT, HasExpressionLookup, TypeEngine[dt.date]):
804
+ """A type for ``datetime.date()`` objects."""
805
+
806
+ __visit_name__ = "date"
807
+
808
+ def get_dbapi_type(self, dbapi):
809
+ return dbapi.DATETIME
810
+
811
+ @property
812
+ def python_type(self):
813
+ return dt.date
814
+
815
+ def literal_processor(self, dialect):
816
+ return self._literal_processor_date(dialect)
817
+
818
+ @util.memoized_property
819
+ def _expression_adaptations(self):
820
+ # Based on
821
+ # https://www.postgresql.org/docs/current/static/functions-datetime.html.
822
+
823
+ return {
824
+ operators.add: {
825
+ Integer: self.__class__,
826
+ Interval: DateTime,
827
+ Time: DateTime,
828
+ },
829
+ operators.sub: {
830
+ # date - integer = date
831
+ Integer: self.__class__,
832
+ # date - date = integer.
833
+ Date: Integer,
834
+ Interval: DateTime,
835
+ # date - datetime = interval,
836
+ # this one is not in the PG docs
837
+ # but works
838
+ DateTime: Interval,
839
+ },
840
+ }
841
+
842
+
843
+ class Time(_RenderISO8601NoT, HasExpressionLookup, TypeEngine[dt.time]):
844
+ """A type for ``datetime.time()`` objects."""
845
+
846
+ __visit_name__ = "time"
847
+
848
+ def __init__(self, timezone: bool = False):
849
+ self.timezone = timezone
850
+
851
+ def get_dbapi_type(self, dbapi):
852
+ return dbapi.DATETIME
853
+
854
+ @property
855
+ def python_type(self):
856
+ return dt.time
857
+
858
+ def _resolve_for_literal(self, value):
859
+ with_timezone = value.tzinfo is not None
860
+ if with_timezone and not self.timezone:
861
+ return TIME_TIMEZONE
862
+ else:
863
+ return self
864
+
865
+ @util.memoized_property
866
+ def _expression_adaptations(self):
867
+ # Based on
868
+ # https://www.postgresql.org/docs/current/static/functions-datetime.html.
869
+
870
+ return {
871
+ operators.add: {Date: DateTime, Interval: self.__class__},
872
+ operators.sub: {Time: Interval, Interval: self.__class__},
873
+ }
874
+
875
+ def literal_processor(self, dialect):
876
+ return self._literal_processor_time(dialect)
877
+
878
+
879
+ class _Binary(TypeEngine[bytes]):
880
+ """Define base behavior for binary types."""
881
+
882
+ length: Optional[int]
883
+
884
+ def __init__(self, length: Optional[int] = None):
885
+ self.length = length
886
+
887
+ @util.ro_memoized_property
888
+ def _generic_type_affinity(
889
+ self,
890
+ ) -> Type[TypeEngine[bytes]]:
891
+ return LargeBinary
892
+
893
+ def literal_processor(self, dialect):
894
+ def process(value):
895
+ # TODO: this is useless for real world scenarios; implement
896
+ # real binary literals
897
+ value = value.decode(
898
+ dialect._legacy_binary_type_literal_encoding
899
+ ).replace("'", "''")
900
+ return "'%s'" % value
901
+
902
+ return process
903
+
904
+ @property
905
+ def python_type(self):
906
+ return bytes
907
+
908
+ # Python 3 - sqlite3 doesn't need the `Binary` conversion
909
+ # here, though pg8000 does to indicate "bytea"
910
+ def bind_processor(self, dialect):
911
+ if dialect.dbapi is None:
912
+ return None
913
+
914
+ DBAPIBinary = dialect.dbapi.Binary
915
+
916
+ def process(value):
917
+ if value is not None:
918
+ return DBAPIBinary(value)
919
+ else:
920
+ return None
921
+
922
+ return process
923
+
924
+ # Python 3 has native bytes() type
925
+ # both sqlite3 and pg8000 seem to return it,
926
+ # psycopg2 as of 2.5 returns 'memoryview'
927
+ def result_processor(self, dialect, coltype):
928
+ if dialect.returns_native_bytes:
929
+ return None
930
+
931
+ def process(value):
932
+ if value is not None:
933
+ value = bytes(value)
934
+ return value
935
+
936
+ return process
937
+
938
+ def coerce_compared_value(self, op, value):
939
+ """See :meth:`.TypeEngine.coerce_compared_value` for a description."""
940
+
941
+ if isinstance(value, str):
942
+ return self
943
+ else:
944
+ return super().coerce_compared_value(op, value)
945
+
946
+ def get_dbapi_type(self, dbapi):
947
+ return dbapi.BINARY
948
+
949
+
950
+ class LargeBinary(_Binary):
951
+ """A type for large binary byte data.
952
+
953
+ The :class:`.LargeBinary` type corresponds to a large and/or unlengthed
954
+ binary type for the target platform, such as BLOB on MySQL and BYTEA for
955
+ PostgreSQL. It also handles the necessary conversions for the DBAPI.
956
+
957
+ """
958
+
959
+ __visit_name__ = "large_binary"
960
+
961
+ def __init__(self, length: Optional[int] = None):
962
+ """
963
+ Construct a LargeBinary type.
964
+
965
+ :param length: optional, a length for the column for use in
966
+ DDL statements, for those binary types that accept a length,
967
+ such as the MySQL BLOB type.
968
+
969
+ """
970
+ _Binary.__init__(self, length=length)
971
+
972
+
973
+ class SchemaType(SchemaEventTarget, TypeEngineMixin):
974
+ """Add capabilities to a type which allow for schema-level DDL to be
975
+ associated with a type.
976
+
977
+ Supports types that must be explicitly created/dropped (i.e. PG ENUM type)
978
+ as well as types that are complimented by table or schema level
979
+ constraints, triggers, and other rules.
980
+
981
+ :class:`.SchemaType` classes can also be targets for the
982
+ :meth:`.DDLEvents.before_parent_attach` and
983
+ :meth:`.DDLEvents.after_parent_attach` events, where the events fire off
984
+ surrounding the association of the type object with a parent
985
+ :class:`_schema.Column`.
986
+
987
+ .. seealso::
988
+
989
+ :class:`.Enum`
990
+
991
+ :class:`.Boolean`
992
+
993
+
994
+ """
995
+
996
+ _use_schema_map = True
997
+
998
+ name: Optional[str]
999
+
1000
+ def __init__(
1001
+ self,
1002
+ name: Optional[str] = None,
1003
+ schema: Optional[str] = None,
1004
+ metadata: Optional[MetaData] = None,
1005
+ inherit_schema: bool = False,
1006
+ quote: Optional[bool] = None,
1007
+ _create_events: bool = True,
1008
+ _adapted_from: Optional[SchemaType] = None,
1009
+ ):
1010
+ if name is not None:
1011
+ self.name = quoted_name(name, quote)
1012
+ else:
1013
+ self.name = None
1014
+ self.schema = schema
1015
+ self.metadata = metadata
1016
+ self.inherit_schema = inherit_schema
1017
+ self._create_events = _create_events
1018
+
1019
+ if _create_events and self.metadata:
1020
+ event.listen(
1021
+ self.metadata,
1022
+ "before_create",
1023
+ util.portable_instancemethod(self._on_metadata_create),
1024
+ )
1025
+ event.listen(
1026
+ self.metadata,
1027
+ "after_drop",
1028
+ util.portable_instancemethod(self._on_metadata_drop),
1029
+ )
1030
+
1031
+ if _adapted_from:
1032
+ self.dispatch = self.dispatch._join(_adapted_from.dispatch)
1033
+
1034
+ def _set_parent(self, parent, **kw):
1035
+ # set parent hook is when this type is associated with a column.
1036
+ # Column calls it for all SchemaEventTarget instances, either the
1037
+ # base type and/or variants in _variant_mapping.
1038
+
1039
+ # we want to register a second hook to trigger when that column is
1040
+ # associated with a table. in that event, we and all of our variants
1041
+ # may want to set up some state on the table such as a CheckConstraint
1042
+ # that will conditionally render at DDL render time.
1043
+
1044
+ # the base SchemaType also sets up events for
1045
+ # on_table/metadata_create/drop in this method, which is used by
1046
+ # "native" types with a separate CREATE/DROP e.g. Postgresql.ENUM
1047
+
1048
+ parent._on_table_attach(util.portable_instancemethod(self._set_table))
1049
+
1050
+ def _variant_mapping_for_set_table(self, column):
1051
+ if column.type._variant_mapping:
1052
+ variant_mapping = dict(column.type._variant_mapping)
1053
+ variant_mapping["_default"] = column.type
1054
+ else:
1055
+ variant_mapping = None
1056
+ return variant_mapping
1057
+
1058
+ def _set_table(self, column, table):
1059
+ if self.inherit_schema:
1060
+ self.schema = table.schema
1061
+ elif self.metadata and self.schema is None and self.metadata.schema:
1062
+ self.schema = self.metadata.schema
1063
+
1064
+ if not self._create_events:
1065
+ return
1066
+
1067
+ variant_mapping = self._variant_mapping_for_set_table(column)
1068
+
1069
+ event.listen(
1070
+ table,
1071
+ "before_create",
1072
+ util.portable_instancemethod(
1073
+ self._on_table_create, {"variant_mapping": variant_mapping}
1074
+ ),
1075
+ )
1076
+ event.listen(
1077
+ table,
1078
+ "after_drop",
1079
+ util.portable_instancemethod(
1080
+ self._on_table_drop, {"variant_mapping": variant_mapping}
1081
+ ),
1082
+ )
1083
+ if self.metadata is None:
1084
+ # if SchemaType were created w/ a metadata argument, these
1085
+ # events would already have been associated with that metadata
1086
+ # and would preclude an association with table.metadata
1087
+ event.listen(
1088
+ table.metadata,
1089
+ "before_create",
1090
+ util.portable_instancemethod(
1091
+ self._on_metadata_create,
1092
+ {"variant_mapping": variant_mapping},
1093
+ ),
1094
+ )
1095
+ event.listen(
1096
+ table.metadata,
1097
+ "after_drop",
1098
+ util.portable_instancemethod(
1099
+ self._on_metadata_drop,
1100
+ {"variant_mapping": variant_mapping},
1101
+ ),
1102
+ )
1103
+
1104
+ def copy(self, **kw):
1105
+ return self.adapt(
1106
+ cast("Type[TypeEngine[Any]]", self.__class__),
1107
+ _create_events=True,
1108
+ metadata=(
1109
+ kw.get("_to_metadata", self.metadata)
1110
+ if self.metadata is not None
1111
+ else None
1112
+ ),
1113
+ )
1114
+
1115
+ @overload
1116
+ def adapt(self, cls: Type[_TE], **kw: Any) -> _TE: ...
1117
+
1118
+ @overload
1119
+ def adapt(
1120
+ self, cls: Type[TypeEngineMixin], **kw: Any
1121
+ ) -> TypeEngine[Any]: ...
1122
+
1123
+ def adapt(
1124
+ self, cls: Type[Union[TypeEngine[Any], TypeEngineMixin]], **kw: Any
1125
+ ) -> TypeEngine[Any]:
1126
+ kw.setdefault("_create_events", False)
1127
+ kw.setdefault("_adapted_from", self)
1128
+ return super().adapt(cls, **kw)
1129
+
1130
+ def create(self, bind: _CreateDropBind, checkfirst: bool = False) -> None:
1131
+ """Issue CREATE DDL for this type, if applicable."""
1132
+
1133
+ t = self.dialect_impl(bind.dialect)
1134
+ if isinstance(t, SchemaType) and t.__class__ is not self.__class__:
1135
+ t.create(bind, checkfirst=checkfirst)
1136
+
1137
+ def drop(self, bind: _CreateDropBind, checkfirst: bool = False) -> None:
1138
+ """Issue DROP DDL for this type, if applicable."""
1139
+
1140
+ t = self.dialect_impl(bind.dialect)
1141
+ if isinstance(t, SchemaType) and t.__class__ is not self.__class__:
1142
+ t.drop(bind, checkfirst=checkfirst)
1143
+
1144
+ def _on_table_create(
1145
+ self, target: Any, bind: _CreateDropBind, **kw: Any
1146
+ ) -> None:
1147
+ if not self._is_impl_for_variant(bind.dialect, kw):
1148
+ return
1149
+
1150
+ t = self.dialect_impl(bind.dialect)
1151
+ if isinstance(t, SchemaType) and t.__class__ is not self.__class__:
1152
+ t._on_table_create(target, bind, **kw)
1153
+
1154
+ def _on_table_drop(
1155
+ self, target: Any, bind: _CreateDropBind, **kw: Any
1156
+ ) -> None:
1157
+ if not self._is_impl_for_variant(bind.dialect, kw):
1158
+ return
1159
+
1160
+ t = self.dialect_impl(bind.dialect)
1161
+ if isinstance(t, SchemaType) and t.__class__ is not self.__class__:
1162
+ t._on_table_drop(target, bind, **kw)
1163
+
1164
+ def _on_metadata_create(
1165
+ self, target: Any, bind: _CreateDropBind, **kw: Any
1166
+ ) -> None:
1167
+ if not self._is_impl_for_variant(bind.dialect, kw):
1168
+ return
1169
+
1170
+ t = self.dialect_impl(bind.dialect)
1171
+ if isinstance(t, SchemaType) and t.__class__ is not self.__class__:
1172
+ t._on_metadata_create(target, bind, **kw)
1173
+
1174
+ def _on_metadata_drop(
1175
+ self, target: Any, bind: _CreateDropBind, **kw: Any
1176
+ ) -> None:
1177
+ if not self._is_impl_for_variant(bind.dialect, kw):
1178
+ return
1179
+
1180
+ t = self.dialect_impl(bind.dialect)
1181
+ if isinstance(t, SchemaType) and t.__class__ is not self.__class__:
1182
+ t._on_metadata_drop(target, bind, **kw)
1183
+
1184
+ def _is_impl_for_variant(
1185
+ self, dialect: Dialect, kw: Dict[str, Any]
1186
+ ) -> Optional[bool]:
1187
+ variant_mapping = kw.pop("variant_mapping", None)
1188
+
1189
+ if not variant_mapping:
1190
+ return True
1191
+
1192
+ # for types that have _variant_mapping, all the impls in the map
1193
+ # that are SchemaEventTarget subclasses get set up as event holders.
1194
+ # this is so that constructs that need
1195
+ # to be associated with the Table at dialect-agnostic time etc. like
1196
+ # CheckConstraints can be set up with that table. they then add
1197
+ # to these constraints a DDL check_rule that among other things
1198
+ # will check this _is_impl_for_variant() method to determine when
1199
+ # the dialect is known that we are part of the table's DDL sequence.
1200
+
1201
+ # since PostgreSQL is the only DB that has ARRAY this can only
1202
+ # be integration tested by PG-specific tests
1203
+ def _we_are_the_impl(typ: SchemaType) -> bool:
1204
+ return (
1205
+ typ is self
1206
+ or isinstance(typ, ARRAY)
1207
+ and typ.item_type is self # type: ignore[comparison-overlap]
1208
+ )
1209
+
1210
+ if dialect.name in variant_mapping and _we_are_the_impl(
1211
+ variant_mapping[dialect.name]
1212
+ ):
1213
+ return True
1214
+ elif dialect.name not in variant_mapping:
1215
+ return _we_are_the_impl(variant_mapping["_default"])
1216
+ else:
1217
+ return None
1218
+
1219
+
1220
+ _EnumTupleArg = Union[Sequence[enum.Enum], Sequence[str]]
1221
+
1222
+
1223
+ class Enum(String, SchemaType, Emulated, TypeEngine[Union[str, enum.Enum]]):
1224
+ """Generic Enum Type.
1225
+
1226
+ The :class:`.Enum` type provides a set of possible string values
1227
+ which the column is constrained towards.
1228
+
1229
+ The :class:`.Enum` type will make use of the backend's native "ENUM"
1230
+ type if one is available; otherwise, it uses a VARCHAR datatype.
1231
+ An option also exists to automatically produce a CHECK constraint
1232
+ when the VARCHAR (so called "non-native") variant is produced;
1233
+ see the :paramref:`.Enum.create_constraint` flag.
1234
+
1235
+ The :class:`.Enum` type also provides in-Python validation of string
1236
+ values during both read and write operations. When reading a value
1237
+ from the database in a result set, the string value is always checked
1238
+ against the list of possible values and a ``LookupError`` is raised
1239
+ if no match is found. When passing a value to the database as a
1240
+ plain string within a SQL statement, if the
1241
+ :paramref:`.Enum.validate_strings` parameter is
1242
+ set to True, a ``LookupError`` is raised for any string value that's
1243
+ not located in the given list of possible values; note that this
1244
+ impacts usage of LIKE expressions with enumerated values (an unusual
1245
+ use case).
1246
+
1247
+ The source of enumerated values may be a list of string values, or
1248
+ alternatively a PEP-435-compliant enumerated class. For the purposes
1249
+ of the :class:`.Enum` datatype, this class need only provide a
1250
+ ``__members__`` method.
1251
+
1252
+ When using an enumerated class, the enumerated objects are used
1253
+ both for input and output, rather than strings as is the case with
1254
+ a plain-string enumerated type::
1255
+
1256
+ import enum
1257
+ from sqlalchemy import Enum
1258
+
1259
+
1260
+ class MyEnum(enum.Enum):
1261
+ one = 1
1262
+ two = 2
1263
+ three = 3
1264
+
1265
+
1266
+ t = Table("data", MetaData(), Column("value", Enum(MyEnum)))
1267
+
1268
+ connection.execute(t.insert(), {"value": MyEnum.two})
1269
+ assert connection.scalar(t.select()) is MyEnum.two
1270
+
1271
+ Above, the string names of each element, e.g. "one", "two", "three",
1272
+ are persisted to the database; the values of the Python Enum, here
1273
+ indicated as integers, are **not** used; the value of each enum can
1274
+ therefore be any kind of Python object whether or not it is persistable.
1275
+
1276
+ In order to persist the values and not the names, the
1277
+ :paramref:`.Enum.values_callable` parameter may be used. The value of
1278
+ this parameter is a user-supplied callable, which is intended to be used
1279
+ with a PEP-435-compliant enumerated class and returns a list of string
1280
+ values to be persisted. For a simple enumeration that uses string values,
1281
+ a callable such as ``lambda x: [e.value for e in x]`` is sufficient.
1282
+
1283
+ .. seealso::
1284
+
1285
+ :ref:`orm_declarative_mapped_column_enums` - background on using
1286
+ the :class:`_sqltypes.Enum` datatype with the ORM's
1287
+ :ref:`ORM Annotated Declarative <orm_declarative_mapped_column>`
1288
+ feature.
1289
+
1290
+ :class:`_postgresql.ENUM` - PostgreSQL-specific type,
1291
+ which has additional functionality.
1292
+
1293
+ :class:`.mysql.ENUM` - MySQL-specific type
1294
+
1295
+ """
1296
+
1297
+ __visit_name__ = "enum"
1298
+
1299
+ values_callable: Optional[Callable[[Type[enum.Enum]], Sequence[str]]]
1300
+ enum_class: Optional[Type[enum.Enum]]
1301
+ _valid_lookup: Dict[Union[enum.Enum, str, None], Optional[str]]
1302
+ _object_lookup: Dict[Optional[str], Union[enum.Enum, str, None]]
1303
+
1304
+ @overload
1305
+ def __init__(self, enums: Type[enum.Enum], **kw: Any) -> None: ...
1306
+
1307
+ @overload
1308
+ def __init__(self, *enums: str, **kw: Any) -> None: ...
1309
+
1310
+ def __init__(self, *enums: Union[str, Type[enum.Enum]], **kw: Any) -> None:
1311
+ r"""Construct an enum.
1312
+
1313
+ Keyword arguments which don't apply to a specific backend are ignored
1314
+ by that backend.
1315
+
1316
+ :param \*enums: either exactly one PEP-435 compliant enumerated type
1317
+ or one or more string labels.
1318
+
1319
+ :param create_constraint: defaults to False. When creating a
1320
+ non-native enumerated type, also build a CHECK constraint on the
1321
+ database against the valid values.
1322
+
1323
+ .. note:: it is strongly recommended that the CHECK constraint
1324
+ have an explicit name in order to support schema-management
1325
+ concerns. This can be established either by setting the
1326
+ :paramref:`.Enum.name` parameter or by setting up an
1327
+ appropriate naming convention; see
1328
+ :ref:`constraint_naming_conventions` for background.
1329
+
1330
+ .. versionchanged:: 1.4 - this flag now defaults to False, meaning
1331
+ no CHECK constraint is generated for a non-native enumerated
1332
+ type.
1333
+
1334
+ :param metadata: Associate this type directly with a ``MetaData``
1335
+ object. For types that exist on the target database as an
1336
+ independent schema construct (PostgreSQL), this type will be
1337
+ created and dropped within ``create_all()`` and ``drop_all()``
1338
+ operations. If the type is not associated with any ``MetaData``
1339
+ object, it will associate itself with each ``Table`` in which it is
1340
+ used, and will be created when any of those individual tables are
1341
+ created, after a check is performed for its existence. The type is
1342
+ only dropped when ``drop_all()`` is called for that ``Table``
1343
+ object's metadata, however.
1344
+
1345
+ The value of the :paramref:`_schema.MetaData.schema` parameter of
1346
+ the :class:`_schema.MetaData` object, if set, will be used as the
1347
+ default value of the :paramref:`_types.Enum.schema` on this object
1348
+ if an explicit value is not otherwise supplied.
1349
+
1350
+ .. versionchanged:: 1.4.12 :class:`_types.Enum` inherits the
1351
+ :paramref:`_schema.MetaData.schema` parameter of the
1352
+ :class:`_schema.MetaData` object if present, when passed using
1353
+ the :paramref:`_types.Enum.metadata` parameter.
1354
+
1355
+ :param name: The name of this type. This is required for PostgreSQL
1356
+ and any future supported database which requires an explicitly
1357
+ named type, or an explicitly named constraint in order to generate
1358
+ the type and/or a table that uses it. If a PEP-435 enumerated
1359
+ class was used, its name (converted to lower case) is used by
1360
+ default.
1361
+
1362
+ :param native_enum: Use the database's native ENUM type when
1363
+ available. Defaults to True. When False, uses VARCHAR + check
1364
+ constraint for all backends. When False, the VARCHAR length can be
1365
+ controlled with :paramref:`.Enum.length`; currently "length" is
1366
+ ignored if native_enum=True.
1367
+
1368
+ :param length: Allows specifying a custom length for the VARCHAR
1369
+ when a non-native enumeration datatype is used. By default it uses
1370
+ the length of the longest value.
1371
+
1372
+ .. versionchanged:: 2.0.0 The :paramref:`.Enum.length` parameter
1373
+ is used unconditionally for ``VARCHAR`` rendering regardless of
1374
+ the :paramref:`.Enum.native_enum` parameter, for those backends
1375
+ where ``VARCHAR`` is used for enumerated datatypes.
1376
+
1377
+
1378
+ :param schema: Schema name of this type. For types that exist on the
1379
+ target database as an independent schema construct (PostgreSQL),
1380
+ this parameter specifies the named schema in which the type is
1381
+ present.
1382
+
1383
+ If not present, the schema name will be taken from the
1384
+ :class:`_schema.MetaData` collection if passed as
1385
+ :paramref:`_types.Enum.metadata`, for a :class:`_schema.MetaData`
1386
+ that includes the :paramref:`_schema.MetaData.schema` parameter.
1387
+
1388
+ .. versionchanged:: 1.4.12 :class:`_types.Enum` inherits the
1389
+ :paramref:`_schema.MetaData.schema` parameter of the
1390
+ :class:`_schema.MetaData` object if present, when passed using
1391
+ the :paramref:`_types.Enum.metadata` parameter.
1392
+
1393
+ Otherwise, if the :paramref:`_types.Enum.inherit_schema` flag is set
1394
+ to ``True``, the schema will be inherited from the associated
1395
+ :class:`_schema.Table` object if any; when
1396
+ :paramref:`_types.Enum.inherit_schema` is at its default of
1397
+ ``False``, the owning table's schema is **not** used.
1398
+
1399
+
1400
+ :param quote: Set explicit quoting preferences for the type's name.
1401
+
1402
+ :param inherit_schema: When ``True``, the "schema" from the owning
1403
+ :class:`_schema.Table`
1404
+ will be copied to the "schema" attribute of this
1405
+ :class:`.Enum`, replacing whatever value was passed for the
1406
+ ``schema`` attribute. This also takes effect when using the
1407
+ :meth:`_schema.Table.to_metadata` operation.
1408
+
1409
+ :param validate_strings: when True, string values that are being
1410
+ passed to the database in a SQL statement will be checked
1411
+ for validity against the list of enumerated values. Unrecognized
1412
+ values will result in a ``LookupError`` being raised.
1413
+
1414
+ :param values_callable: A callable which will be passed the PEP-435
1415
+ compliant enumerated type, which should then return a list of string
1416
+ values to be persisted. This allows for alternate usages such as
1417
+ using the string value of an enum to be persisted to the database
1418
+ instead of its name. The callable must return the values to be
1419
+ persisted in the same order as iterating through the Enum's
1420
+ ``__member__`` attribute. For example
1421
+ ``lambda x: [i.value for i in x]``.
1422
+
1423
+ .. versionadded:: 1.2.3
1424
+
1425
+ :param sort_key_function: a Python callable which may be used as the
1426
+ "key" argument in the Python ``sorted()`` built-in. The SQLAlchemy
1427
+ ORM requires that primary key columns which are mapped must
1428
+ be sortable in some way. When using an unsortable enumeration
1429
+ object such as a Python 3 ``Enum`` object, this parameter may be
1430
+ used to set a default sort key function for the objects. By
1431
+ default, the database value of the enumeration is used as the
1432
+ sorting function.
1433
+
1434
+ .. versionadded:: 1.3.8
1435
+
1436
+ :param omit_aliases: A boolean that when true will remove aliases from
1437
+ pep 435 enums. defaults to ``True``.
1438
+
1439
+ .. versionchanged:: 2.0 This parameter now defaults to True.
1440
+
1441
+ """
1442
+ self._enum_init(enums, kw) # type: ignore[arg-type]
1443
+
1444
+ @property
1445
+ def _enums_argument(self):
1446
+ if self.enum_class is not None:
1447
+ return [self.enum_class]
1448
+ else:
1449
+ return self.enums
1450
+
1451
+ def _enum_init(self, enums: _EnumTupleArg, kw: Dict[str, Any]) -> None:
1452
+ """internal init for :class:`.Enum` and subclasses.
1453
+
1454
+ friendly init helper used by subclasses to remove
1455
+ all the Enum-specific keyword arguments from kw. Allows all
1456
+ other arguments in kw to pass through.
1457
+
1458
+ """
1459
+ self.native_enum = kw.pop("native_enum", True)
1460
+ self.create_constraint = kw.pop("create_constraint", False)
1461
+ self.values_callable = kw.pop("values_callable", None)
1462
+ self._sort_key_function = kw.pop("sort_key_function", NO_ARG)
1463
+ length_arg = kw.pop("length", NO_ARG)
1464
+ self._omit_aliases = kw.pop("omit_aliases", True)
1465
+ _disable_warnings = kw.pop("_disable_warnings", False)
1466
+ values, objects = self._parse_into_values(enums, kw)
1467
+ self._setup_for_values(values, objects, kw)
1468
+
1469
+ self.validate_strings = kw.pop("validate_strings", False)
1470
+
1471
+ if self.enums:
1472
+ self._default_length = length = max(len(x) for x in self.enums)
1473
+ else:
1474
+ self._default_length = length = 0
1475
+
1476
+ if length_arg is not NO_ARG:
1477
+ if (
1478
+ not _disable_warnings
1479
+ and length_arg is not None
1480
+ and length_arg < length
1481
+ ):
1482
+ raise ValueError(
1483
+ "When provided, length must be larger or equal"
1484
+ " than the length of the longest enum value. %s < %s"
1485
+ % (length_arg, length)
1486
+ )
1487
+ length = length_arg
1488
+
1489
+ self._valid_lookup[None] = self._object_lookup[None] = None
1490
+
1491
+ super().__init__(length=length)
1492
+
1493
+ # assign name to the given enum class if no other name, and this
1494
+ # enum is not an "empty" enum. if the enum is "empty" we assume
1495
+ # this is a template enum that will be used to generate
1496
+ # new Enum classes.
1497
+ if self.enum_class and values:
1498
+ kw.setdefault("name", self.enum_class.__name__.lower())
1499
+ SchemaType.__init__(
1500
+ self,
1501
+ name=kw.pop("name", None),
1502
+ schema=kw.pop("schema", None),
1503
+ metadata=kw.pop("metadata", None),
1504
+ inherit_schema=kw.pop("inherit_schema", False),
1505
+ quote=kw.pop("quote", None),
1506
+ _create_events=kw.pop("_create_events", True),
1507
+ _adapted_from=kw.pop("_adapted_from", None),
1508
+ )
1509
+
1510
+ def _parse_into_values(
1511
+ self, enums: _EnumTupleArg, kw: Any
1512
+ ) -> Tuple[Sequence[str], _EnumTupleArg]:
1513
+ if not enums and "_enums" in kw:
1514
+ enums = kw.pop("_enums")
1515
+
1516
+ if len(enums) == 1 and hasattr(enums[0], "__members__"):
1517
+ self.enum_class = enums[0] # type: ignore[assignment]
1518
+ assert self.enum_class is not None
1519
+
1520
+ _members = self.enum_class.__members__
1521
+
1522
+ members: Mapping[str, enum.Enum]
1523
+ if self._omit_aliases is True:
1524
+ # remove aliases
1525
+ members = OrderedDict(
1526
+ (n, v) for n, v in _members.items() if v.name == n
1527
+ )
1528
+ else:
1529
+ members = _members
1530
+ if self.values_callable:
1531
+ values = self.values_callable(self.enum_class)
1532
+ else:
1533
+ values = list(members)
1534
+ objects = [members[k] for k in members]
1535
+ return values, objects
1536
+ else:
1537
+ self.enum_class = None
1538
+ return enums, enums # type: ignore[return-value]
1539
+
1540
+ def _compare_type_affinity(self, other: TypeEngine[Any]) -> bool:
1541
+ return (
1542
+ super()._compare_type_affinity(other)
1543
+ or other._type_affinity is String
1544
+ )
1545
+
1546
+ def _resolve_for_literal(self, value: Any) -> Enum:
1547
+ tv = type(value)
1548
+ typ = self._resolve_for_python_type(tv, tv, tv)
1549
+ assert typ is not None
1550
+ return typ
1551
+
1552
+ def _resolve_for_python_type(
1553
+ self,
1554
+ python_type: Type[Any],
1555
+ matched_on: _MatchedOnType,
1556
+ matched_on_flattened: Type[Any],
1557
+ ) -> Optional[Enum]:
1558
+ # "generic form" indicates we were placed in a type map
1559
+ # as ``sqlalchemy.Enum(enum.Enum)`` which indicates we need to
1560
+ # get enumerated values from the datatype
1561
+ we_are_generic_form = self._enums_argument == [enum.Enum]
1562
+
1563
+ native_enum = None
1564
+
1565
+ def process_literal(pt):
1566
+ # for a literal, where we need to get its contents, parse it out.
1567
+ enum_args = get_args(pt)
1568
+ bad_args = [arg for arg in enum_args if not isinstance(arg, str)]
1569
+ if bad_args:
1570
+ raise exc.ArgumentError(
1571
+ f"Can't create string-based Enum datatype from non-string "
1572
+ f"values: {', '.join(repr(x) for x in bad_args)}. Please "
1573
+ f"provide an explicit Enum datatype for this Python type"
1574
+ )
1575
+ native_enum = False
1576
+ return enum_args, native_enum
1577
+
1578
+ if not we_are_generic_form and python_type is matched_on:
1579
+ # if we have enumerated values, and the incoming python
1580
+ # type is exactly the one that matched in the type map,
1581
+ # then we use these enumerated values and dont try to parse
1582
+ # what's incoming
1583
+ enum_args = self._enums_argument
1584
+
1585
+ elif is_literal(python_type):
1586
+ enum_args, native_enum = process_literal(python_type)
1587
+ elif is_pep695(python_type):
1588
+ value = python_type.__value__
1589
+ if is_pep695(value):
1590
+ new_value = value
1591
+ while is_pep695(new_value):
1592
+ new_value = new_value.__value__
1593
+ if is_literal(new_value):
1594
+ value = new_value
1595
+ warn_deprecated(
1596
+ f"Mapping recursive TypeAliasType '{python_type}' "
1597
+ "that resolve to literal to generate an Enum is "
1598
+ "deprecated. SQLAlchemy 2.1 will not support this "
1599
+ "use case. Please avoid using recursing "
1600
+ "TypeAliasType.",
1601
+ "2.0",
1602
+ )
1603
+ if not is_literal(value):
1604
+ raise exc.ArgumentError(
1605
+ f"Can't associate TypeAliasType '{python_type}' to an "
1606
+ "Enum since it's not a direct alias of a Literal. Only "
1607
+ "aliases in this form `type my_alias = Literal['a', "
1608
+ "'b']` are supported when generating Enums."
1609
+ )
1610
+ enum_args, native_enum = process_literal(value)
1611
+
1612
+ elif isinstance(python_type, type) and issubclass(
1613
+ python_type, enum.Enum
1614
+ ):
1615
+ # same for an enum.Enum
1616
+ enum_args = [python_type]
1617
+
1618
+ else:
1619
+ enum_args = self._enums_argument
1620
+
1621
+ # make a new Enum that looks like this one.
1622
+ # arguments or other rules
1623
+ kw = self._make_enum_kw({})
1624
+
1625
+ if native_enum is False:
1626
+ kw["native_enum"] = False
1627
+
1628
+ kw["length"] = NO_ARG if self.length == 0 else self.length
1629
+ return cast(
1630
+ Enum,
1631
+ self._generic_type_affinity(_enums=enum_args, **kw), # type: ignore # noqa: E501
1632
+ )
1633
+
1634
+ def _setup_for_values(
1635
+ self,
1636
+ values: Sequence[str],
1637
+ objects: _EnumTupleArg,
1638
+ kw: Any,
1639
+ ) -> None:
1640
+ self.enums = list(values)
1641
+
1642
+ self._valid_lookup = dict(zip(reversed(objects), reversed(values)))
1643
+
1644
+ self._object_lookup = dict(zip(values, objects))
1645
+
1646
+ self._valid_lookup.update(
1647
+ [
1648
+ (value, self._valid_lookup[self._object_lookup[value]])
1649
+ for value in values
1650
+ ]
1651
+ )
1652
+
1653
+ @property
1654
+ def sort_key_function(self): # type: ignore[override]
1655
+ if self._sort_key_function is NO_ARG:
1656
+ return self._db_value_for_elem
1657
+ else:
1658
+ return self._sort_key_function
1659
+
1660
+ @property
1661
+ def native(self): # type: ignore[override]
1662
+ return self.native_enum
1663
+
1664
+ def _db_value_for_elem(self, elem):
1665
+ try:
1666
+ return self._valid_lookup[elem]
1667
+ except KeyError as err:
1668
+ # for unknown string values, we return as is. While we can
1669
+ # validate these if we wanted, that does not allow for lesser-used
1670
+ # end-user use cases, such as using a LIKE comparison with an enum,
1671
+ # or for an application that wishes to apply string tests to an
1672
+ # ENUM (see [ticket:3725]). While we can decide to differentiate
1673
+ # here between an INSERT statement and a criteria used in a SELECT,
1674
+ # for now we're staying conservative w/ behavioral changes (perhaps
1675
+ # someone has a trigger that handles strings on INSERT)
1676
+ if not self.validate_strings and isinstance(elem, str):
1677
+ return elem
1678
+ else:
1679
+ raise LookupError(
1680
+ "'%s' is not among the defined enum values. "
1681
+ "Enum name: %s. Possible values: %s"
1682
+ % (
1683
+ elem,
1684
+ self.name,
1685
+ langhelpers.repr_tuple_names(self.enums),
1686
+ )
1687
+ ) from err
1688
+
1689
+ class Comparator(String.Comparator[str]):
1690
+ __slots__ = ()
1691
+
1692
+ type: String
1693
+
1694
+ def _adapt_expression(
1695
+ self,
1696
+ op: OperatorType,
1697
+ other_comparator: TypeEngine.Comparator[Any],
1698
+ ) -> Tuple[OperatorType, TypeEngine[Any]]:
1699
+ op, typ = super()._adapt_expression(op, other_comparator)
1700
+ if op is operators.concat_op:
1701
+ typ = String(self.type.length)
1702
+ return op, typ
1703
+
1704
+ comparator_factory = Comparator
1705
+
1706
+ def _object_value_for_elem(self, elem: str) -> Union[str, enum.Enum]:
1707
+ try:
1708
+ # Value will not be None because key is not None
1709
+ return self._object_lookup[elem] # type: ignore[return-value]
1710
+ except KeyError as err:
1711
+ raise LookupError(
1712
+ "'%s' is not among the defined enum values. "
1713
+ "Enum name: %s. Possible values: %s"
1714
+ % (
1715
+ elem,
1716
+ self.name,
1717
+ langhelpers.repr_tuple_names(self.enums),
1718
+ )
1719
+ ) from err
1720
+
1721
+ def __repr__(self):
1722
+ return util.generic_repr(
1723
+ self,
1724
+ additional_kw=[
1725
+ ("native_enum", True),
1726
+ ("create_constraint", False),
1727
+ ("length", self._default_length),
1728
+ ],
1729
+ to_inspect=[Enum, SchemaType],
1730
+ )
1731
+
1732
+ def as_generic(self, allow_nulltype=False):
1733
+ try:
1734
+ args = self.enums
1735
+ except AttributeError:
1736
+ raise NotImplementedError(
1737
+ "TypeEngine.as_generic() heuristic "
1738
+ "is undefined for types that inherit Enum but do not have "
1739
+ "an `enums` attribute."
1740
+ ) from None
1741
+
1742
+ return util.constructor_copy(
1743
+ self, self._generic_type_affinity, *args, _disable_warnings=True
1744
+ )
1745
+
1746
+ def _make_enum_kw(self, kw):
1747
+ kw.setdefault("validate_strings", self.validate_strings)
1748
+ if self.name:
1749
+ kw.setdefault("name", self.name)
1750
+ kw.setdefault("schema", self.schema)
1751
+ kw.setdefault("inherit_schema", self.inherit_schema)
1752
+ kw.setdefault("metadata", self.metadata)
1753
+ kw.setdefault("native_enum", self.native_enum)
1754
+ kw.setdefault("values_callable", self.values_callable)
1755
+ kw.setdefault("create_constraint", self.create_constraint)
1756
+ kw.setdefault("length", self.length)
1757
+ kw.setdefault("omit_aliases", self._omit_aliases)
1758
+ return kw
1759
+
1760
+ def adapt_to_emulated(self, impltype, **kw):
1761
+ self._make_enum_kw(kw)
1762
+ kw["_disable_warnings"] = True
1763
+ kw.setdefault("_create_events", False)
1764
+ assert "_enums" in kw
1765
+ return impltype(**kw)
1766
+
1767
+ def adapt(self, cls, **kw):
1768
+ kw["_enums"] = self._enums_argument
1769
+ kw["_disable_warnings"] = True
1770
+ return super().adapt(cls, **kw)
1771
+
1772
+ def _should_create_constraint(self, compiler, **kw):
1773
+ if not self._is_impl_for_variant(compiler.dialect, kw):
1774
+ return False
1775
+ return (
1776
+ not self.native_enum or not compiler.dialect.supports_native_enum
1777
+ )
1778
+
1779
+ @util.preload_module("sqlalchemy.sql.schema")
1780
+ def _set_table(self, column, table):
1781
+ schema = util.preloaded.sql_schema
1782
+ SchemaType._set_table(self, column, table)
1783
+
1784
+ if not self.create_constraint:
1785
+ return
1786
+
1787
+ variant_mapping = self._variant_mapping_for_set_table(column)
1788
+
1789
+ e = schema.CheckConstraint(
1790
+ type_coerce(column, String()).in_(self.enums),
1791
+ name=_NONE_NAME if self.name is None else self.name,
1792
+ _create_rule=util.portable_instancemethod(
1793
+ self._should_create_constraint,
1794
+ {"variant_mapping": variant_mapping},
1795
+ ),
1796
+ _type_bound=True,
1797
+ )
1798
+ assert e.table is table
1799
+
1800
+ def literal_processor(self, dialect):
1801
+ parent_processor = super().literal_processor(dialect)
1802
+
1803
+ def process(value):
1804
+ value = self._db_value_for_elem(value)
1805
+ if parent_processor:
1806
+ value = parent_processor(value)
1807
+ return value
1808
+
1809
+ return process
1810
+
1811
+ def bind_processor(self, dialect):
1812
+ parent_processor = super().bind_processor(dialect)
1813
+
1814
+ def process(value):
1815
+ value = self._db_value_for_elem(value)
1816
+ if parent_processor:
1817
+ value = parent_processor(value)
1818
+ return value
1819
+
1820
+ return process
1821
+
1822
+ def result_processor(self, dialect, coltype):
1823
+ parent_processor = super().result_processor(dialect, coltype)
1824
+
1825
+ def process(value):
1826
+ if parent_processor:
1827
+ value = parent_processor(value)
1828
+
1829
+ value = self._object_value_for_elem(value)
1830
+ return value
1831
+
1832
+ return process
1833
+
1834
+ def copy(self, **kw):
1835
+ return SchemaType.copy(self, **kw)
1836
+
1837
+ @property
1838
+ def python_type(self):
1839
+ if self.enum_class:
1840
+ return self.enum_class
1841
+ else:
1842
+ return super().python_type
1843
+
1844
+
1845
+ class PickleType(TypeDecorator[object]):
1846
+ """Holds Python objects, which are serialized using pickle.
1847
+
1848
+ PickleType builds upon the Binary type to apply Python's
1849
+ ``pickle.dumps()`` to incoming objects, and ``pickle.loads()`` on
1850
+ the way out, allowing any pickleable Python object to be stored as
1851
+ a serialized binary field.
1852
+
1853
+ To allow ORM change events to propagate for elements associated
1854
+ with :class:`.PickleType`, see :ref:`mutable_toplevel`.
1855
+
1856
+ """
1857
+
1858
+ impl = LargeBinary
1859
+ cache_ok = True
1860
+
1861
+ def __init__(
1862
+ self,
1863
+ protocol: int = pickle.HIGHEST_PROTOCOL,
1864
+ pickler: Any = None,
1865
+ comparator: Optional[Callable[[Any, Any], bool]] = None,
1866
+ impl: Optional[_TypeEngineArgument[Any]] = None,
1867
+ ):
1868
+ """
1869
+ Construct a PickleType.
1870
+
1871
+ :param protocol: defaults to ``pickle.HIGHEST_PROTOCOL``.
1872
+
1873
+ :param pickler: defaults to pickle. May be any object with
1874
+ pickle-compatible ``dumps`` and ``loads`` methods.
1875
+
1876
+ :param comparator: a 2-arg callable predicate used
1877
+ to compare values of this type. If left as ``None``,
1878
+ the Python "equals" operator is used to compare values.
1879
+
1880
+ :param impl: A binary-storing :class:`_types.TypeEngine` class or
1881
+ instance to use in place of the default :class:`_types.LargeBinary`.
1882
+ For example the :class: `_mysql.LONGBLOB` class may be more effective
1883
+ when using MySQL.
1884
+
1885
+ .. versionadded:: 1.4.20
1886
+
1887
+ """
1888
+ self.protocol = protocol
1889
+ self.pickler = pickler or pickle
1890
+ self.comparator = comparator
1891
+ super().__init__()
1892
+
1893
+ if impl:
1894
+ # custom impl is not necessarily a LargeBinary subclass.
1895
+ # make an exception to typing for this
1896
+ self.impl = to_instance(impl) # type: ignore
1897
+
1898
+ def __reduce__(self):
1899
+ return PickleType, (self.protocol, None, self.comparator)
1900
+
1901
+ def bind_processor(self, dialect):
1902
+ impl_processor = self.impl_instance.bind_processor(dialect)
1903
+ dumps = self.pickler.dumps
1904
+ protocol = self.protocol
1905
+ if impl_processor:
1906
+ fixed_impl_processor = impl_processor
1907
+
1908
+ def process(value):
1909
+ if value is not None:
1910
+ value = dumps(value, protocol)
1911
+ return fixed_impl_processor(value)
1912
+
1913
+ else:
1914
+
1915
+ def process(value):
1916
+ if value is not None:
1917
+ value = dumps(value, protocol)
1918
+ return value
1919
+
1920
+ return process
1921
+
1922
+ def result_processor(self, dialect, coltype):
1923
+ impl_processor = self.impl_instance.result_processor(dialect, coltype)
1924
+ loads = self.pickler.loads
1925
+ if impl_processor:
1926
+ fixed_impl_processor = impl_processor
1927
+
1928
+ def process(value):
1929
+ value = fixed_impl_processor(value)
1930
+ if value is None:
1931
+ return None
1932
+ return loads(value)
1933
+
1934
+ else:
1935
+
1936
+ def process(value):
1937
+ if value is None:
1938
+ return None
1939
+ return loads(value)
1940
+
1941
+ return process
1942
+
1943
+ def compare_values(self, x, y):
1944
+ if self.comparator:
1945
+ return self.comparator(x, y)
1946
+ else:
1947
+ return x == y
1948
+
1949
+
1950
+ class Boolean(SchemaType, Emulated, TypeEngine[bool]):
1951
+ """A bool datatype.
1952
+
1953
+ :class:`.Boolean` typically uses BOOLEAN or SMALLINT on the DDL side,
1954
+ and on the Python side deals in ``True`` or ``False``.
1955
+
1956
+ The :class:`.Boolean` datatype currently has two levels of assertion
1957
+ that the values persisted are simple true/false values. For all
1958
+ backends, only the Python values ``None``, ``True``, ``False``, ``1``
1959
+ or ``0`` are accepted as parameter values. For those backends that
1960
+ don't support a "native boolean" datatype, an option exists to
1961
+ also create a CHECK constraint on the target column
1962
+
1963
+ .. versionchanged:: 1.2 the :class:`.Boolean` datatype now asserts that
1964
+ incoming Python values are already in pure boolean form.
1965
+
1966
+
1967
+ """
1968
+
1969
+ __visit_name__ = "boolean"
1970
+ native = True
1971
+
1972
+ def __init__(
1973
+ self,
1974
+ create_constraint: bool = False,
1975
+ name: Optional[str] = None,
1976
+ _create_events: bool = True,
1977
+ _adapted_from: Optional[SchemaType] = None,
1978
+ ):
1979
+ """Construct a Boolean.
1980
+
1981
+ :param create_constraint: defaults to False. If the boolean
1982
+ is generated as an int/smallint, also create a CHECK constraint
1983
+ on the table that ensures 1 or 0 as a value.
1984
+
1985
+ .. note:: it is strongly recommended that the CHECK constraint
1986
+ have an explicit name in order to support schema-management
1987
+ concerns. This can be established either by setting the
1988
+ :paramref:`.Boolean.name` parameter or by setting up an
1989
+ appropriate naming convention; see
1990
+ :ref:`constraint_naming_conventions` for background.
1991
+
1992
+ .. versionchanged:: 1.4 - this flag now defaults to False, meaning
1993
+ no CHECK constraint is generated for a non-native enumerated
1994
+ type.
1995
+
1996
+ :param name: if a CHECK constraint is generated, specify
1997
+ the name of the constraint.
1998
+
1999
+ """
2000
+ self.create_constraint = create_constraint
2001
+ self.name = name
2002
+ self._create_events = _create_events
2003
+ if _adapted_from:
2004
+ self.dispatch = self.dispatch._join(_adapted_from.dispatch)
2005
+
2006
+ def copy(self, **kw):
2007
+ # override SchemaType.copy() to not include to_metadata logic
2008
+ return self.adapt(
2009
+ cast("Type[TypeEngine[Any]]", self.__class__),
2010
+ _create_events=True,
2011
+ )
2012
+
2013
+ def _should_create_constraint(self, compiler, **kw):
2014
+ if not self._is_impl_for_variant(compiler.dialect, kw):
2015
+ return False
2016
+ return (
2017
+ not compiler.dialect.supports_native_boolean
2018
+ and compiler.dialect.non_native_boolean_check_constraint
2019
+ )
2020
+
2021
+ @util.preload_module("sqlalchemy.sql.schema")
2022
+ def _set_table(self, column, table):
2023
+ schema = util.preloaded.sql_schema
2024
+ if not self.create_constraint:
2025
+ return
2026
+
2027
+ variant_mapping = self._variant_mapping_for_set_table(column)
2028
+
2029
+ e = schema.CheckConstraint(
2030
+ type_coerce(column, self).in_([0, 1]),
2031
+ name=_NONE_NAME if self.name is None else self.name,
2032
+ _create_rule=util.portable_instancemethod(
2033
+ self._should_create_constraint,
2034
+ {"variant_mapping": variant_mapping},
2035
+ ),
2036
+ _type_bound=True,
2037
+ )
2038
+ assert e.table is table
2039
+
2040
+ @property
2041
+ def python_type(self):
2042
+ return bool
2043
+
2044
+ _strict_bools = frozenset([None, True, False])
2045
+
2046
+ def _strict_as_bool(self, value):
2047
+ if value not in self._strict_bools:
2048
+ if not isinstance(value, int):
2049
+ raise TypeError("Not a boolean value: %r" % (value,))
2050
+ else:
2051
+ raise ValueError(
2052
+ "Value %r is not None, True, or False" % (value,)
2053
+ )
2054
+ return value
2055
+
2056
+ def literal_processor(self, dialect):
2057
+ compiler = dialect.statement_compiler(dialect, None)
2058
+ true = compiler.visit_true(None)
2059
+ false = compiler.visit_false(None)
2060
+
2061
+ def process(value):
2062
+ return true if self._strict_as_bool(value) else false
2063
+
2064
+ return process
2065
+
2066
+ def bind_processor(self, dialect):
2067
+ _strict_as_bool = self._strict_as_bool
2068
+
2069
+ _coerce: Union[Type[bool], Type[int]]
2070
+
2071
+ if dialect.supports_native_boolean:
2072
+ _coerce = bool
2073
+ else:
2074
+ _coerce = int
2075
+
2076
+ def process(value):
2077
+ value = _strict_as_bool(value)
2078
+ if value is not None:
2079
+ value = _coerce(value)
2080
+ return value
2081
+
2082
+ return process
2083
+
2084
+ def result_processor(self, dialect, coltype):
2085
+ if dialect.supports_native_boolean:
2086
+ return None
2087
+ else:
2088
+ return processors.int_to_boolean
2089
+
2090
+
2091
+ class _AbstractInterval(HasExpressionLookup, TypeEngine[dt.timedelta]):
2092
+ @util.memoized_property
2093
+ def _expression_adaptations(self):
2094
+ # Based on
2095
+ # https://www.postgresql.org/docs/current/static/functions-datetime.html.
2096
+
2097
+ return {
2098
+ operators.add: {
2099
+ Date: DateTime,
2100
+ Interval: self.__class__,
2101
+ DateTime: DateTime,
2102
+ Time: Time,
2103
+ },
2104
+ operators.sub: {Interval: self.__class__},
2105
+ operators.mul: {Numeric: self.__class__},
2106
+ operators.truediv: {Numeric: self.__class__},
2107
+ }
2108
+
2109
+ @util.ro_non_memoized_property
2110
+ def _type_affinity(self) -> Type[Interval]:
2111
+ return Interval
2112
+
2113
+
2114
+ class Interval(Emulated, _AbstractInterval, TypeDecorator[dt.timedelta]):
2115
+ """A type for ``datetime.timedelta()`` objects.
2116
+
2117
+ The Interval type deals with ``datetime.timedelta`` objects. In PostgreSQL
2118
+ and Oracle Database, the native ``INTERVAL`` type is used; for others, the
2119
+ value is stored as a date which is relative to the "epoch" (Jan. 1, 1970).
2120
+
2121
+ Note that the ``Interval`` type does not currently provide date arithmetic
2122
+ operations on platforms which do not support interval types natively. Such
2123
+ operations usually require transformation of both sides of the expression
2124
+ (such as, conversion of both sides into integer epoch values first) which
2125
+ currently is a manual procedure (such as via
2126
+ :attr:`~sqlalchemy.sql.expression.func`).
2127
+
2128
+ """
2129
+
2130
+ impl = DateTime
2131
+ epoch = dt.datetime.fromtimestamp(0, dt.timezone.utc).replace(tzinfo=None)
2132
+ cache_ok = True
2133
+
2134
+ def __init__(
2135
+ self,
2136
+ native: bool = True,
2137
+ second_precision: Optional[int] = None,
2138
+ day_precision: Optional[int] = None,
2139
+ ):
2140
+ """Construct an Interval object.
2141
+
2142
+ :param native: when True, use the actual
2143
+ INTERVAL type provided by the database, if
2144
+ supported (currently PostgreSQL, Oracle Database).
2145
+ Otherwise, represent the interval data as
2146
+ an epoch value regardless.
2147
+
2148
+ :param second_precision: For native interval types
2149
+ which support a "fractional seconds precision" parameter,
2150
+ i.e. Oracle Database and PostgreSQL
2151
+
2152
+ :param day_precision: for native interval types which
2153
+ support a "day precision" parameter, i.e. Oracle Database.
2154
+
2155
+ """
2156
+ super().__init__()
2157
+ self.native = native
2158
+ self.second_precision = second_precision
2159
+ self.day_precision = day_precision
2160
+
2161
+ class Comparator(
2162
+ TypeDecorator.Comparator[_CT],
2163
+ _AbstractInterval.Comparator[_CT],
2164
+ ):
2165
+ __slots__ = ()
2166
+
2167
+ comparator_factory = Comparator
2168
+
2169
+ @property
2170
+ def python_type(self):
2171
+ return dt.timedelta
2172
+
2173
+ def adapt_to_emulated(self, impltype, **kw):
2174
+ return _AbstractInterval.adapt(self, impltype, **kw)
2175
+
2176
+ def coerce_compared_value(self, op, value):
2177
+ return self.impl_instance.coerce_compared_value(op, value)
2178
+
2179
+ def bind_processor(
2180
+ self, dialect: Dialect
2181
+ ) -> _BindProcessorType[dt.timedelta]:
2182
+ if TYPE_CHECKING:
2183
+ assert isinstance(self.impl_instance, DateTime)
2184
+ impl_processor = self.impl_instance.bind_processor(dialect)
2185
+ epoch = self.epoch
2186
+ if impl_processor:
2187
+ fixed_impl_processor = impl_processor
2188
+
2189
+ def process(
2190
+ value: Optional[dt.timedelta],
2191
+ ) -> Any:
2192
+ if value is not None:
2193
+ dt_value = epoch + value
2194
+ else:
2195
+ dt_value = None
2196
+ return fixed_impl_processor(dt_value)
2197
+
2198
+ else:
2199
+
2200
+ def process(
2201
+ value: Optional[dt.timedelta],
2202
+ ) -> Any:
2203
+ if value is not None:
2204
+ dt_value = epoch + value
2205
+ else:
2206
+ dt_value = None
2207
+ return dt_value
2208
+
2209
+ return process
2210
+
2211
+ def result_processor(
2212
+ self, dialect: Dialect, coltype: Any
2213
+ ) -> _ResultProcessorType[dt.timedelta]:
2214
+ if TYPE_CHECKING:
2215
+ assert isinstance(self.impl_instance, DateTime)
2216
+ impl_processor = self.impl_instance.result_processor(dialect, coltype)
2217
+ epoch = self.epoch
2218
+ if impl_processor:
2219
+ fixed_impl_processor = impl_processor
2220
+
2221
+ def process(value: Any) -> Optional[dt.timedelta]:
2222
+ dt_value = fixed_impl_processor(value)
2223
+ if dt_value is None:
2224
+ return None
2225
+ return dt_value - epoch
2226
+
2227
+ else:
2228
+
2229
+ def process(value: Any) -> Optional[dt.timedelta]:
2230
+ if value is None:
2231
+ return None
2232
+ return value - epoch # type: ignore
2233
+
2234
+ return process
2235
+
2236
+
2237
+ class JSON(Indexable, TypeEngine[Any]):
2238
+ """Represent a SQL JSON type.
2239
+
2240
+ .. note:: :class:`_types.JSON`
2241
+ is provided as a facade for vendor-specific
2242
+ JSON types. Since it supports JSON SQL operations, it only
2243
+ works on backends that have an actual JSON type, currently:
2244
+
2245
+ * PostgreSQL - see :class:`sqlalchemy.dialects.postgresql.JSON` and
2246
+ :class:`sqlalchemy.dialects.postgresql.JSONB` for backend-specific
2247
+ notes
2248
+
2249
+ * MySQL - see
2250
+ :class:`sqlalchemy.dialects.mysql.JSON` for backend-specific notes
2251
+
2252
+ * SQLite as of version 3.9 - see
2253
+ :class:`sqlalchemy.dialects.sqlite.JSON` for backend-specific notes
2254
+
2255
+ * Microsoft SQL Server 2016 and later - see
2256
+ :class:`sqlalchemy.dialects.mssql.JSON` for backend-specific notes
2257
+
2258
+ :class:`_types.JSON` is part of the Core in support of the growing
2259
+ popularity of native JSON datatypes.
2260
+
2261
+ The :class:`_types.JSON` type stores arbitrary JSON format data, e.g.::
2262
+
2263
+ data_table = Table(
2264
+ "data_table",
2265
+ metadata,
2266
+ Column("id", Integer, primary_key=True),
2267
+ Column("data", JSON),
2268
+ )
2269
+
2270
+ with engine.connect() as conn:
2271
+ conn.execute(
2272
+ data_table.insert(), {"data": {"key1": "value1", "key2": "value2"}}
2273
+ )
2274
+
2275
+ **JSON-Specific Expression Operators**
2276
+
2277
+ The :class:`_types.JSON`
2278
+ datatype provides these additional SQL operations:
2279
+
2280
+ * Keyed index operations::
2281
+
2282
+ data_table.c.data["some key"]
2283
+
2284
+ * Integer index operations::
2285
+
2286
+ data_table.c.data[3]
2287
+
2288
+ * Path index operations::
2289
+
2290
+ data_table.c.data[("key_1", "key_2", 5, ..., "key_n")]
2291
+
2292
+ * Data casters for specific JSON element types, subsequent to an index
2293
+ or path operation being invoked::
2294
+
2295
+ data_table.c.data["some key"].as_integer()
2296
+
2297
+ .. versionadded:: 1.3.11
2298
+
2299
+ Additional operations may be available from the dialect-specific versions
2300
+ of :class:`_types.JSON`, such as
2301
+ :class:`sqlalchemy.dialects.postgresql.JSON` and
2302
+ :class:`sqlalchemy.dialects.postgresql.JSONB` which both offer additional
2303
+ PostgreSQL-specific operations.
2304
+
2305
+ **Casting JSON Elements to Other Types**
2306
+
2307
+ Index operations, i.e. those invoked by calling upon the expression using
2308
+ the Python bracket operator as in ``some_column['some key']``, return an
2309
+ expression object whose type defaults to :class:`_types.JSON` by default,
2310
+ so that
2311
+ further JSON-oriented instructions may be called upon the result type.
2312
+ However, it is likely more common that an index operation is expected
2313
+ to return a specific scalar element, such as a string or integer. In
2314
+ order to provide access to these elements in a backend-agnostic way,
2315
+ a series of data casters are provided:
2316
+
2317
+ * :meth:`.JSON.Comparator.as_string` - return the element as a string
2318
+
2319
+ * :meth:`.JSON.Comparator.as_boolean` - return the element as a boolean
2320
+
2321
+ * :meth:`.JSON.Comparator.as_float` - return the element as a float
2322
+
2323
+ * :meth:`.JSON.Comparator.as_integer` - return the element as an integer
2324
+
2325
+ These data casters are implemented by supporting dialects in order to
2326
+ assure that comparisons to the above types will work as expected, such as::
2327
+
2328
+ # integer comparison
2329
+ data_table.c.data["some_integer_key"].as_integer() == 5
2330
+
2331
+ # boolean comparison
2332
+ data_table.c.data["some_boolean"].as_boolean() == True
2333
+
2334
+ .. versionadded:: 1.3.11 Added type-specific casters for the basic JSON
2335
+ data element types.
2336
+
2337
+ .. note::
2338
+
2339
+ The data caster functions are new in version 1.3.11, and supersede
2340
+ the previous documented approaches of using CAST; for reference,
2341
+ this looked like::
2342
+
2343
+ from sqlalchemy import cast, type_coerce
2344
+ from sqlalchemy import String, JSON
2345
+
2346
+ cast(data_table.c.data["some_key"], String) == type_coerce(55, JSON)
2347
+
2348
+ The above case now works directly as::
2349
+
2350
+ data_table.c.data["some_key"].as_integer() == 5
2351
+
2352
+ For details on the previous comparison approach within the 1.3.x
2353
+ series, see the documentation for SQLAlchemy 1.2 or the included HTML
2354
+ files in the doc/ directory of the version's distribution.
2355
+
2356
+ **Detecting Changes in JSON columns when using the ORM**
2357
+
2358
+ The :class:`_types.JSON` type, when used with the SQLAlchemy ORM, does not
2359
+ detect in-place mutations to the structure. In order to detect these, the
2360
+ :mod:`sqlalchemy.ext.mutable` extension must be used, most typically
2361
+ using the :class:`.MutableDict` class. This extension will
2362
+ allow "in-place" changes to the datastructure to produce events which
2363
+ will be detected by the unit of work. See the example at :class:`.HSTORE`
2364
+ for a simple example involving a dictionary.
2365
+
2366
+ Alternatively, assigning a JSON structure to an ORM element that
2367
+ replaces the old one will always trigger a change event.
2368
+
2369
+ **Support for JSON null vs. SQL NULL**
2370
+
2371
+ When working with NULL values, the :class:`_types.JSON` type recommends the
2372
+ use of two specific constants in order to differentiate between a column
2373
+ that evaluates to SQL NULL, e.g. no value, vs. the JSON-encoded string of
2374
+ ``"null"``. To insert or select against a value that is SQL NULL, use the
2375
+ constant :func:`.null`. This symbol may be passed as a parameter value
2376
+ specifically when using the :class:`_types.JSON` datatype, which contains
2377
+ special logic that interprets this symbol to mean that the column value
2378
+ should be SQL NULL as opposed to JSON ``"null"``::
2379
+
2380
+ from sqlalchemy import null
2381
+
2382
+ conn.execute(table.insert(), {"json_value": null()})
2383
+
2384
+ To insert or select against a value that is JSON ``"null"``, use the
2385
+ constant :attr:`_types.JSON.NULL`::
2386
+
2387
+ conn.execute(table.insert(), {"json_value": JSON.NULL})
2388
+
2389
+ The :class:`_types.JSON` type supports a flag
2390
+ :paramref:`_types.JSON.none_as_null` which when set to True will result
2391
+ in the Python constant ``None`` evaluating to the value of SQL
2392
+ NULL, and when set to False results in the Python constant
2393
+ ``None`` evaluating to the value of JSON ``"null"``. The Python
2394
+ value ``None`` may be used in conjunction with either
2395
+ :attr:`_types.JSON.NULL` and :func:`.null` in order to indicate NULL
2396
+ values, but care must be taken as to the value of the
2397
+ :paramref:`_types.JSON.none_as_null` in these cases.
2398
+
2399
+ **Customizing the JSON Serializer**
2400
+
2401
+ The JSON serializer and deserializer used by :class:`_types.JSON`
2402
+ defaults to
2403
+ Python's ``json.dumps`` and ``json.loads`` functions; in the case of the
2404
+ psycopg2 dialect, psycopg2 may be using its own custom loader function.
2405
+
2406
+ In order to affect the serializer / deserializer, they are currently
2407
+ configurable at the :func:`_sa.create_engine` level via the
2408
+ :paramref:`_sa.create_engine.json_serializer` and
2409
+ :paramref:`_sa.create_engine.json_deserializer` parameters. For example,
2410
+ to turn off ``ensure_ascii``::
2411
+
2412
+ engine = create_engine(
2413
+ "sqlite://",
2414
+ json_serializer=lambda obj: json.dumps(obj, ensure_ascii=False),
2415
+ )
2416
+
2417
+ .. versionchanged:: 1.3.7
2418
+
2419
+ SQLite dialect's ``json_serializer`` and ``json_deserializer``
2420
+ parameters renamed from ``_json_serializer`` and
2421
+ ``_json_deserializer``.
2422
+
2423
+ .. seealso::
2424
+
2425
+ :class:`sqlalchemy.dialects.postgresql.JSON`
2426
+
2427
+ :class:`sqlalchemy.dialects.postgresql.JSONB`
2428
+
2429
+ :class:`sqlalchemy.dialects.mysql.JSON`
2430
+
2431
+ :class:`sqlalchemy.dialects.sqlite.JSON`
2432
+
2433
+ """ # noqa: E501
2434
+
2435
+ __visit_name__ = "JSON"
2436
+
2437
+ hashable = False
2438
+ NULL = util.symbol("JSON_NULL")
2439
+ """Describe the json value of NULL.
2440
+
2441
+ This value is used to force the JSON value of ``"null"`` to be
2442
+ used as the value. A value of Python ``None`` will be recognized
2443
+ either as SQL NULL or JSON ``"null"``, based on the setting
2444
+ of the :paramref:`_types.JSON.none_as_null` flag; the
2445
+ :attr:`_types.JSON.NULL`
2446
+ constant can be used to always resolve to JSON ``"null"`` regardless
2447
+ of this setting. This is in contrast to the :func:`_expression.null`
2448
+ construct,
2449
+ which always resolves to SQL NULL. E.g.::
2450
+
2451
+ from sqlalchemy import null
2452
+ from sqlalchemy.dialects.postgresql import JSON
2453
+
2454
+ # will *always* insert SQL NULL
2455
+ obj1 = MyObject(json_value=null())
2456
+
2457
+ # will *always* insert JSON string "null"
2458
+ obj2 = MyObject(json_value=JSON.NULL)
2459
+
2460
+ session.add_all([obj1, obj2])
2461
+ session.commit()
2462
+
2463
+ In order to set JSON NULL as a default value for a column, the most
2464
+ transparent method is to use :func:`_expression.text`::
2465
+
2466
+ Table(
2467
+ "my_table", metadata, Column("json_data", JSON, default=text("'null'"))
2468
+ )
2469
+
2470
+ While it is possible to use :attr:`_types.JSON.NULL` in this context, the
2471
+ :attr:`_types.JSON.NULL` value will be returned as the value of the
2472
+ column,
2473
+ which in the context of the ORM or other repurposing of the default
2474
+ value, may not be desirable. Using a SQL expression means the value
2475
+ will be re-fetched from the database within the context of retrieving
2476
+ generated defaults.
2477
+
2478
+
2479
+ """ # noqa: E501
2480
+
2481
+ def __init__(self, none_as_null: bool = False):
2482
+ """Construct a :class:`_types.JSON` type.
2483
+
2484
+ :param none_as_null=False: if True, persist the value ``None`` as a
2485
+ SQL NULL value, not the JSON encoding of ``null``. Note that when this
2486
+ flag is False, the :func:`.null` construct can still be used to
2487
+ persist a NULL value, which may be passed directly as a parameter
2488
+ value that is specially interpreted by the :class:`_types.JSON` type
2489
+ as SQL NULL::
2490
+
2491
+ from sqlalchemy import null
2492
+
2493
+ conn.execute(table.insert(), {"data": null()})
2494
+
2495
+ .. note::
2496
+
2497
+ :paramref:`_types.JSON.none_as_null` does **not** apply to the
2498
+ values passed to :paramref:`_schema.Column.default` and
2499
+ :paramref:`_schema.Column.server_default`; a value of ``None``
2500
+ passed for these parameters means "no default present".
2501
+
2502
+ Additionally, when used in SQL comparison expressions, the
2503
+ Python value ``None`` continues to refer to SQL null, and not
2504
+ JSON NULL. The :paramref:`_types.JSON.none_as_null` flag refers
2505
+ explicitly to the **persistence** of the value within an
2506
+ INSERT or UPDATE statement. The :attr:`_types.JSON.NULL`
2507
+ value should be used for SQL expressions that wish to compare to
2508
+ JSON null.
2509
+
2510
+ .. seealso::
2511
+
2512
+ :attr:`.types.JSON.NULL`
2513
+
2514
+ """
2515
+ self.none_as_null = none_as_null
2516
+
2517
+ class JSONElementType(TypeEngine[Any]):
2518
+ """Common function for index / path elements in a JSON expression."""
2519
+
2520
+ _integer = Integer()
2521
+ _string = String()
2522
+
2523
+ def string_bind_processor(
2524
+ self, dialect: Dialect
2525
+ ) -> Optional[_BindProcessorType[str]]:
2526
+ return self._string._cached_bind_processor(dialect)
2527
+
2528
+ def string_literal_processor(
2529
+ self, dialect: Dialect
2530
+ ) -> Optional[_LiteralProcessorType[str]]:
2531
+ return self._string._cached_literal_processor(dialect)
2532
+
2533
+ def bind_processor(self, dialect: Dialect) -> _BindProcessorType[Any]:
2534
+ int_processor = self._integer._cached_bind_processor(dialect)
2535
+ string_processor = self.string_bind_processor(dialect)
2536
+
2537
+ def process(value: Optional[Any]) -> Any:
2538
+ if int_processor and isinstance(value, int):
2539
+ value = int_processor(value)
2540
+ elif string_processor and isinstance(value, str):
2541
+ value = string_processor(value)
2542
+ return value
2543
+
2544
+ return process
2545
+
2546
+ def literal_processor(
2547
+ self, dialect: Dialect
2548
+ ) -> _LiteralProcessorType[Any]:
2549
+ int_processor = self._integer._cached_literal_processor(dialect)
2550
+ string_processor = self.string_literal_processor(dialect)
2551
+
2552
+ def process(value: Optional[Any]) -> Any:
2553
+ if int_processor and isinstance(value, int):
2554
+ value = int_processor(value)
2555
+ elif string_processor and isinstance(value, str):
2556
+ value = string_processor(value)
2557
+ else:
2558
+ raise NotImplementedError()
2559
+
2560
+ return value
2561
+
2562
+ return process
2563
+
2564
+ class JSONIndexType(JSONElementType):
2565
+ """Placeholder for the datatype of a JSON index value.
2566
+
2567
+ This allows execution-time processing of JSON index values
2568
+ for special syntaxes.
2569
+
2570
+ """
2571
+
2572
+ class JSONIntIndexType(JSONIndexType):
2573
+ """Placeholder for the datatype of a JSON index value.
2574
+
2575
+ This allows execution-time processing of JSON index values
2576
+ for special syntaxes.
2577
+
2578
+ """
2579
+
2580
+ class JSONStrIndexType(JSONIndexType):
2581
+ """Placeholder for the datatype of a JSON index value.
2582
+
2583
+ This allows execution-time processing of JSON index values
2584
+ for special syntaxes.
2585
+
2586
+ """
2587
+
2588
+ class JSONPathType(JSONElementType):
2589
+ """Placeholder type for JSON path operations.
2590
+
2591
+ This allows execution-time processing of a path-based
2592
+ index value into a specific SQL syntax.
2593
+
2594
+ """
2595
+
2596
+ __visit_name__ = "json_path"
2597
+
2598
+ class Comparator(Indexable.Comparator[_T], Concatenable.Comparator[_T]):
2599
+ """Define comparison operations for :class:`_types.JSON`."""
2600
+
2601
+ __slots__ = ()
2602
+
2603
+ type: JSON
2604
+
2605
+ def _setup_getitem(self, index):
2606
+ if not isinstance(index, str) and isinstance(
2607
+ index, collections_abc.Sequence
2608
+ ):
2609
+ index = coercions.expect(
2610
+ roles.BinaryElementRole,
2611
+ index,
2612
+ expr=self.expr,
2613
+ operator=operators.json_path_getitem_op,
2614
+ bindparam_type=JSON.JSONPathType,
2615
+ )
2616
+
2617
+ operator = operators.json_path_getitem_op
2618
+ else:
2619
+ index = coercions.expect(
2620
+ roles.BinaryElementRole,
2621
+ index,
2622
+ expr=self.expr,
2623
+ operator=operators.json_getitem_op,
2624
+ bindparam_type=(
2625
+ JSON.JSONIntIndexType
2626
+ if isinstance(index, int)
2627
+ else JSON.JSONStrIndexType
2628
+ ),
2629
+ )
2630
+ operator = operators.json_getitem_op
2631
+
2632
+ return operator, index, self.type
2633
+
2634
+ def as_boolean(self):
2635
+ """Consider an indexed value as boolean.
2636
+
2637
+ This is similar to using :class:`_sql.type_coerce`, and will
2638
+ usually not apply a ``CAST()``.
2639
+
2640
+ e.g.::
2641
+
2642
+ stmt = select(mytable.c.json_column["some_data"].as_boolean()).where(
2643
+ mytable.c.json_column["some_data"].as_boolean() == True
2644
+ )
2645
+
2646
+ .. versionadded:: 1.3.11
2647
+
2648
+ """ # noqa: E501
2649
+ return self._binary_w_type(Boolean(), "as_boolean")
2650
+
2651
+ def as_string(self):
2652
+ """Consider an indexed value as string.
2653
+
2654
+ This is similar to using :class:`_sql.type_coerce`, and will
2655
+ usually not apply a ``CAST()``.
2656
+
2657
+ e.g.::
2658
+
2659
+ stmt = select(mytable.c.json_column["some_data"].as_string()).where(
2660
+ mytable.c.json_column["some_data"].as_string() == "some string"
2661
+ )
2662
+
2663
+ .. versionadded:: 1.3.11
2664
+
2665
+ """ # noqa: E501
2666
+ return self._binary_w_type(Unicode(), "as_string")
2667
+
2668
+ def as_integer(self):
2669
+ """Consider an indexed value as integer.
2670
+
2671
+ This is similar to using :class:`_sql.type_coerce`, and will
2672
+ usually not apply a ``CAST()``.
2673
+
2674
+ e.g.::
2675
+
2676
+ stmt = select(mytable.c.json_column["some_data"].as_integer()).where(
2677
+ mytable.c.json_column["some_data"].as_integer() == 5
2678
+ )
2679
+
2680
+ .. versionadded:: 1.3.11
2681
+
2682
+ """ # noqa: E501
2683
+ return self._binary_w_type(Integer(), "as_integer")
2684
+
2685
+ def as_float(self):
2686
+ """Consider an indexed value as float.
2687
+
2688
+ This is similar to using :class:`_sql.type_coerce`, and will
2689
+ usually not apply a ``CAST()``.
2690
+
2691
+ e.g.::
2692
+
2693
+ stmt = select(mytable.c.json_column["some_data"].as_float()).where(
2694
+ mytable.c.json_column["some_data"].as_float() == 29.75
2695
+ )
2696
+
2697
+ .. versionadded:: 1.3.11
2698
+
2699
+ """ # noqa: E501
2700
+ return self._binary_w_type(Float(), "as_float")
2701
+
2702
+ def as_numeric(self, precision, scale, asdecimal=True):
2703
+ """Consider an indexed value as numeric/decimal.
2704
+
2705
+ This is similar to using :class:`_sql.type_coerce`, and will
2706
+ usually not apply a ``CAST()``.
2707
+
2708
+ e.g.::
2709
+
2710
+ stmt = select(mytable.c.json_column["some_data"].as_numeric(10, 6)).where(
2711
+ mytable.c.json_column["some_data"].as_numeric(10, 6) == 29.75
2712
+ )
2713
+
2714
+ .. versionadded:: 1.4.0b2
2715
+
2716
+ """ # noqa: E501
2717
+ return self._binary_w_type(
2718
+ Numeric(precision, scale, asdecimal=asdecimal), "as_numeric"
2719
+ )
2720
+
2721
+ def as_json(self):
2722
+ """Consider an indexed value as JSON.
2723
+
2724
+ This is similar to using :class:`_sql.type_coerce`, and will
2725
+ usually not apply a ``CAST()``.
2726
+
2727
+ e.g.::
2728
+
2729
+ stmt = select(mytable.c.json_column["some_data"].as_json())
2730
+
2731
+ This is typically the default behavior of indexed elements in any
2732
+ case.
2733
+
2734
+ Note that comparison of full JSON structures may not be
2735
+ supported by all backends.
2736
+
2737
+ .. versionadded:: 1.3.11
2738
+
2739
+ """
2740
+ return self.expr
2741
+
2742
+ def _binary_w_type(self, typ, method_name):
2743
+ if not isinstance(
2744
+ self.expr, elements.BinaryExpression
2745
+ ) or self.expr.operator not in (
2746
+ operators.json_getitem_op,
2747
+ operators.json_path_getitem_op,
2748
+ ):
2749
+ raise exc.InvalidRequestError(
2750
+ "The JSON cast operator JSON.%s() only works with a JSON "
2751
+ "index expression e.g. col['q'].%s()"
2752
+ % (method_name, method_name)
2753
+ )
2754
+ expr = self.expr._clone()
2755
+ expr.type = typ
2756
+ return expr
2757
+
2758
+ comparator_factory = Comparator
2759
+
2760
+ @property
2761
+ def python_type(self):
2762
+ return dict
2763
+
2764
+ @property
2765
+ def should_evaluate_none(self):
2766
+ """Alias of :attr:`_types.JSON.none_as_null`"""
2767
+ return not self.none_as_null
2768
+
2769
+ @should_evaluate_none.setter
2770
+ def should_evaluate_none(self, value):
2771
+ self.none_as_null = not value
2772
+
2773
+ @util.memoized_property
2774
+ def _str_impl(self):
2775
+ return String()
2776
+
2777
+ def _make_bind_processor(self, string_process, json_serializer):
2778
+ if string_process:
2779
+
2780
+ def process(value):
2781
+ if value is self.NULL:
2782
+ value = None
2783
+ elif isinstance(value, elements.Null) or (
2784
+ value is None and self.none_as_null
2785
+ ):
2786
+ return None
2787
+
2788
+ serialized = json_serializer(value)
2789
+ return string_process(serialized)
2790
+
2791
+ else:
2792
+
2793
+ def process(value):
2794
+ if value is self.NULL:
2795
+ value = None
2796
+ elif isinstance(value, elements.Null) or (
2797
+ value is None and self.none_as_null
2798
+ ):
2799
+ return None
2800
+
2801
+ return json_serializer(value)
2802
+
2803
+ return process
2804
+
2805
+ def bind_processor(self, dialect):
2806
+ string_process = self._str_impl.bind_processor(dialect)
2807
+ json_serializer = dialect._json_serializer or json.dumps
2808
+
2809
+ return self._make_bind_processor(string_process, json_serializer)
2810
+
2811
+ def result_processor(self, dialect, coltype):
2812
+ string_process = self._str_impl.result_processor(dialect, coltype)
2813
+ json_deserializer = dialect._json_deserializer or json.loads
2814
+
2815
+ def process(value):
2816
+ if value is None:
2817
+ return None
2818
+ if string_process:
2819
+ value = string_process(value)
2820
+ return json_deserializer(value)
2821
+
2822
+ return process
2823
+
2824
+
2825
+ class ARRAY(
2826
+ SchemaEventTarget, Indexable, Concatenable, TypeEngine[Sequence[_T]]
2827
+ ):
2828
+ """Represent a SQL Array type.
2829
+
2830
+ .. note:: This type serves as the basis for all ARRAY operations.
2831
+ However, currently **only the PostgreSQL backend has support for SQL
2832
+ arrays in SQLAlchemy**. It is recommended to use the PostgreSQL-specific
2833
+ :class:`sqlalchemy.dialects.postgresql.ARRAY` type directly when using
2834
+ ARRAY types with PostgreSQL, as it provides additional operators
2835
+ specific to that backend.
2836
+
2837
+ :class:`_types.ARRAY` is part of the Core in support of various SQL
2838
+ standard functions such as :class:`_functions.array_agg`
2839
+ which explicitly involve
2840
+ arrays; however, with the exception of the PostgreSQL backend and possibly
2841
+ some third-party dialects, no other SQLAlchemy built-in dialect has support
2842
+ for this type.
2843
+
2844
+ An :class:`_types.ARRAY` type is constructed given the "type"
2845
+ of element::
2846
+
2847
+ mytable = Table("mytable", metadata, Column("data", ARRAY(Integer)))
2848
+
2849
+ The above type represents an N-dimensional array,
2850
+ meaning a supporting backend such as PostgreSQL will interpret values
2851
+ with any number of dimensions automatically. To produce an INSERT
2852
+ construct that passes in a 1-dimensional array of integers::
2853
+
2854
+ connection.execute(mytable.insert(), {"data": [1, 2, 3]})
2855
+
2856
+ The :class:`_types.ARRAY` type can be constructed given a fixed number
2857
+ of dimensions::
2858
+
2859
+ mytable = Table(
2860
+ "mytable", metadata, Column("data", ARRAY(Integer, dimensions=2))
2861
+ )
2862
+
2863
+ Sending a number of dimensions is optional, but recommended if the
2864
+ datatype is to represent arrays of more than one dimension. This number
2865
+ is used:
2866
+
2867
+ * When emitting the type declaration itself to the database, e.g.
2868
+ ``INTEGER[][]``
2869
+
2870
+ * When translating Python values to database values, and vice versa, e.g.
2871
+ an ARRAY of :class:`.Unicode` objects uses this number to efficiently
2872
+ access the string values inside of array structures without resorting
2873
+ to per-row type inspection
2874
+
2875
+ * When used with the Python ``getitem`` accessor, the number of dimensions
2876
+ serves to define the kind of type that the ``[]`` operator should
2877
+ return, e.g. for an ARRAY of INTEGER with two dimensions::
2878
+
2879
+ >>> expr = table.c.column[5] # returns ARRAY(Integer, dimensions=1)
2880
+ >>> expr = expr[6] # returns Integer
2881
+
2882
+ For 1-dimensional arrays, an :class:`_types.ARRAY` instance with no
2883
+ dimension parameter will generally assume single-dimensional behaviors.
2884
+
2885
+ SQL expressions of type :class:`_types.ARRAY` have support for "index" and
2886
+ "slice" behavior. The ``[]`` operator produces expression
2887
+ constructs which will produce the appropriate SQL, both for
2888
+ SELECT statements::
2889
+
2890
+ select(mytable.c.data[5], mytable.c.data[2:7])
2891
+
2892
+ as well as UPDATE statements when the :meth:`_expression.Update.values`
2893
+ method is used::
2894
+
2895
+ mytable.update().values(
2896
+ {mytable.c.data[5]: 7, mytable.c.data[2:7]: [1, 2, 3]}
2897
+ )
2898
+
2899
+ Indexed access is one-based by default;
2900
+ for zero-based index conversion, set :paramref:`_types.ARRAY.zero_indexes`.
2901
+
2902
+ The :class:`_types.ARRAY` type also provides for the operators
2903
+ :meth:`.types.ARRAY.Comparator.any` and
2904
+ :meth:`.types.ARRAY.Comparator.all`. The PostgreSQL-specific version of
2905
+ :class:`_types.ARRAY` also provides additional operators.
2906
+
2907
+ .. container:: topic
2908
+
2909
+ **Detecting Changes in ARRAY columns when using the ORM**
2910
+
2911
+ The :class:`_sqltypes.ARRAY` type, when used with the SQLAlchemy ORM,
2912
+ does not detect in-place mutations to the array. In order to detect
2913
+ these, the :mod:`sqlalchemy.ext.mutable` extension must be used, using
2914
+ the :class:`.MutableList` class::
2915
+
2916
+ from sqlalchemy import ARRAY
2917
+ from sqlalchemy.ext.mutable import MutableList
2918
+
2919
+
2920
+ class SomeOrmClass(Base):
2921
+ # ...
2922
+
2923
+ data = Column(MutableList.as_mutable(ARRAY(Integer)))
2924
+
2925
+ This extension will allow "in-place" changes such to the array
2926
+ such as ``.append()`` to produce events which will be detected by the
2927
+ unit of work. Note that changes to elements **inside** the array,
2928
+ including subarrays that are mutated in place, are **not** detected.
2929
+
2930
+ Alternatively, assigning a new array value to an ORM element that
2931
+ replaces the old one will always trigger a change event.
2932
+
2933
+ .. seealso::
2934
+
2935
+ :class:`sqlalchemy.dialects.postgresql.ARRAY`
2936
+
2937
+ """
2938
+
2939
+ __visit_name__ = "ARRAY"
2940
+
2941
+ _is_array = True
2942
+
2943
+ zero_indexes = False
2944
+ """If True, Python zero-based indexes should be interpreted as one-based
2945
+ on the SQL expression side."""
2946
+
2947
+ def __init__(
2948
+ self,
2949
+ item_type: _TypeEngineArgument[_T],
2950
+ as_tuple: bool = False,
2951
+ dimensions: Optional[int] = None,
2952
+ zero_indexes: bool = False,
2953
+ ):
2954
+ """Construct an :class:`_types.ARRAY`.
2955
+
2956
+ E.g.::
2957
+
2958
+ Column("myarray", ARRAY(Integer))
2959
+
2960
+ Arguments are:
2961
+
2962
+ :param item_type: The data type of items of this array. Note that
2963
+ dimensionality is irrelevant here, so multi-dimensional arrays like
2964
+ ``INTEGER[][]``, are constructed as ``ARRAY(Integer)``, not as
2965
+ ``ARRAY(ARRAY(Integer))`` or such.
2966
+
2967
+ :param as_tuple=False: Specify whether return results
2968
+ should be converted to tuples from lists. This parameter is
2969
+ not generally needed as a Python list corresponds well
2970
+ to a SQL array.
2971
+
2972
+ :param dimensions: if non-None, the ARRAY will assume a fixed
2973
+ number of dimensions. This impacts how the array is declared
2974
+ on the database, how it goes about interpreting Python and
2975
+ result values, as well as how expression behavior in conjunction
2976
+ with the "getitem" operator works. See the description at
2977
+ :class:`_types.ARRAY` for additional detail.
2978
+
2979
+ :param zero_indexes=False: when True, index values will be converted
2980
+ between Python zero-based and SQL one-based indexes, e.g.
2981
+ a value of one will be added to all index values before passing
2982
+ to the database.
2983
+
2984
+ """
2985
+ if isinstance(item_type, ARRAY):
2986
+ raise ValueError(
2987
+ "Do not nest ARRAY types; ARRAY(basetype) "
2988
+ "handles multi-dimensional arrays of basetype"
2989
+ )
2990
+ if isinstance(item_type, type):
2991
+ item_type = item_type()
2992
+ self.item_type = item_type
2993
+ self.as_tuple = as_tuple
2994
+ self.dimensions = dimensions
2995
+ self.zero_indexes = zero_indexes
2996
+
2997
+ class Comparator(
2998
+ Indexable.Comparator[Sequence[_CT]],
2999
+ Concatenable.Comparator[Sequence[_CT]],
3000
+ ):
3001
+ """Define comparison operations for :class:`_types.ARRAY`.
3002
+
3003
+ More operators are available on the dialect-specific form
3004
+ of this type. See :class:`.postgresql.ARRAY.Comparator`.
3005
+
3006
+ """
3007
+
3008
+ __slots__ = ()
3009
+
3010
+ type: ARRAY[_CT]
3011
+
3012
+ @overload
3013
+ def _setup_getitem(
3014
+ self, index: int
3015
+ ) -> Tuple[OperatorType, int, TypeEngine[Any]]: ...
3016
+
3017
+ @overload
3018
+ def _setup_getitem(
3019
+ self, index: slice
3020
+ ) -> Tuple[OperatorType, Slice, TypeEngine[Any]]: ...
3021
+
3022
+ def _setup_getitem(self, index: Union[int, slice]) -> Union[
3023
+ Tuple[OperatorType, int, TypeEngine[Any]],
3024
+ Tuple[OperatorType, Slice, TypeEngine[Any]],
3025
+ ]:
3026
+ arr_type = self.type
3027
+
3028
+ return_type: TypeEngine[Any]
3029
+
3030
+ if isinstance(index, slice):
3031
+ return_type = arr_type
3032
+ if arr_type.zero_indexes:
3033
+ index = slice(index.start + 1, index.stop + 1, index.step)
3034
+ slice_ = Slice(
3035
+ index.start, index.stop, index.step, _name=self.expr.key
3036
+ )
3037
+ return operators.getitem, slice_, return_type
3038
+ else:
3039
+ if arr_type.zero_indexes:
3040
+ index += 1
3041
+ if arr_type.dimensions is None or arr_type.dimensions == 1:
3042
+ return_type = arr_type.item_type
3043
+ else:
3044
+ adapt_kw = {"dimensions": arr_type.dimensions - 1}
3045
+ return_type = arr_type.adapt(
3046
+ arr_type.__class__, **adapt_kw
3047
+ )
3048
+
3049
+ return operators.getitem, index, return_type
3050
+
3051
+ def contains(self, *arg: Any, **kw: Any) -> ColumnElement[bool]:
3052
+ """``ARRAY.contains()`` not implemented for the base ARRAY type.
3053
+ Use the dialect-specific ARRAY type.
3054
+
3055
+ .. seealso::
3056
+
3057
+ :class:`_postgresql.ARRAY` - PostgreSQL specific version.
3058
+ """
3059
+ raise NotImplementedError(
3060
+ "ARRAY.contains() not implemented for the base "
3061
+ "ARRAY type; please use the dialect-specific ARRAY type"
3062
+ )
3063
+
3064
+ @util.preload_module("sqlalchemy.sql.elements")
3065
+ def any(
3066
+ self, other: Any, operator: Optional[OperatorType] = None
3067
+ ) -> ColumnElement[bool]:
3068
+ """Return ``other operator ANY (array)`` clause.
3069
+
3070
+ .. legacy:: This method is an :class:`_types.ARRAY` - specific
3071
+ construct that is now superseded by the :func:`_sql.any_`
3072
+ function, which features a different calling style. The
3073
+ :func:`_sql.any_` function is also mirrored at the method level
3074
+ via the :meth:`_sql.ColumnOperators.any_` method.
3075
+
3076
+ Usage of array-specific :meth:`_types.ARRAY.Comparator.any`
3077
+ is as follows::
3078
+
3079
+ from sqlalchemy.sql import operators
3080
+
3081
+ conn.execute(
3082
+ select(table.c.data).where(table.c.data.any(7, operator=operators.lt))
3083
+ )
3084
+
3085
+ :param other: expression to be compared
3086
+ :param operator: an operator object from the
3087
+ :mod:`sqlalchemy.sql.operators`
3088
+ package, defaults to :func:`.operators.eq`.
3089
+
3090
+ .. seealso::
3091
+
3092
+ :func:`_expression.any_`
3093
+
3094
+ :meth:`.types.ARRAY.Comparator.all`
3095
+
3096
+ """ # noqa: E501
3097
+ elements = util.preloaded.sql_elements
3098
+ operator = operator if operator else operators.eq
3099
+
3100
+ arr_type = self.type
3101
+
3102
+ return elements.CollectionAggregate._create_any(self.expr).operate(
3103
+ operators.mirror(operator),
3104
+ coercions.expect(
3105
+ roles.BinaryElementRole,
3106
+ element=other,
3107
+ operator=operator,
3108
+ expr=self.expr,
3109
+ bindparam_type=arr_type.item_type,
3110
+ ),
3111
+ )
3112
+
3113
+ @util.preload_module("sqlalchemy.sql.elements")
3114
+ def all(
3115
+ self, other: Any, operator: Optional[OperatorType] = None
3116
+ ) -> ColumnElement[bool]:
3117
+ """Return ``other operator ALL (array)`` clause.
3118
+
3119
+ .. legacy:: This method is an :class:`_types.ARRAY` - specific
3120
+ construct that is now superseded by the :func:`_sql.all_`
3121
+ function, which features a different calling style. The
3122
+ :func:`_sql.all_` function is also mirrored at the method level
3123
+ via the :meth:`_sql.ColumnOperators.all_` method.
3124
+
3125
+ Usage of array-specific :meth:`_types.ARRAY.Comparator.all`
3126
+ is as follows::
3127
+
3128
+ from sqlalchemy.sql import operators
3129
+
3130
+ conn.execute(
3131
+ select(table.c.data).where(table.c.data.all(7, operator=operators.lt))
3132
+ )
3133
+
3134
+ :param other: expression to be compared
3135
+ :param operator: an operator object from the
3136
+ :mod:`sqlalchemy.sql.operators`
3137
+ package, defaults to :func:`.operators.eq`.
3138
+
3139
+ .. seealso::
3140
+
3141
+ :func:`_expression.all_`
3142
+
3143
+ :meth:`.types.ARRAY.Comparator.any`
3144
+
3145
+ """ # noqa: E501
3146
+ elements = util.preloaded.sql_elements
3147
+ operator = operator if operator else operators.eq
3148
+
3149
+ arr_type = self.type
3150
+
3151
+ return elements.CollectionAggregate._create_all(self.expr).operate(
3152
+ operators.mirror(operator),
3153
+ coercions.expect(
3154
+ roles.BinaryElementRole,
3155
+ element=other,
3156
+ operator=operator,
3157
+ expr=self.expr,
3158
+ bindparam_type=arr_type.item_type,
3159
+ ),
3160
+ )
3161
+
3162
+ comparator_factory = Comparator
3163
+
3164
+ @property
3165
+ def hashable(self) -> bool: # type: ignore[override]
3166
+ return self.as_tuple
3167
+
3168
+ @property
3169
+ def python_type(self) -> Type[Any]:
3170
+ return list
3171
+
3172
+ def compare_values(self, x: Any, y: Any) -> bool:
3173
+ return x == y # type: ignore[no-any-return]
3174
+
3175
+ def _set_parent(
3176
+ self, parent: SchemaEventTarget, outer: bool = False, **kw: Any
3177
+ ) -> None:
3178
+ """Support SchemaEventTarget"""
3179
+
3180
+ if not outer and isinstance(self.item_type, SchemaEventTarget):
3181
+ self.item_type._set_parent(parent, **kw)
3182
+
3183
+ def _set_parent_with_dispatch(
3184
+ self, parent: SchemaEventTarget, **kw: Any
3185
+ ) -> None:
3186
+ """Support SchemaEventTarget"""
3187
+
3188
+ super()._set_parent_with_dispatch(parent, outer=True)
3189
+
3190
+ if isinstance(self.item_type, SchemaEventTarget):
3191
+ self.item_type._set_parent_with_dispatch(parent)
3192
+
3193
+ def literal_processor(
3194
+ self, dialect: Dialect
3195
+ ) -> Optional[_LiteralProcessorType[_T]]:
3196
+ item_proc = self.item_type.dialect_impl(dialect).literal_processor(
3197
+ dialect
3198
+ )
3199
+ if item_proc is None:
3200
+ return None
3201
+
3202
+ def to_str(elements: Iterable[Any]) -> str:
3203
+ return f"[{', '.join(elements)}]"
3204
+
3205
+ def process(value: Sequence[Any]) -> str:
3206
+ inner = self._apply_item_processor(
3207
+ value, item_proc, self.dimensions, to_str
3208
+ )
3209
+ return inner
3210
+
3211
+ return process
3212
+
3213
+ def _apply_item_processor(
3214
+ self,
3215
+ arr: Sequence[Any],
3216
+ itemproc: Optional[Callable[[Any], Any]],
3217
+ dim: Optional[int],
3218
+ collection_callable: Callable[[Iterable[Any]], _P],
3219
+ ) -> _P:
3220
+ """Helper method that can be used by bind_processor(),
3221
+ literal_processor(), etc. to apply an item processor to elements of
3222
+ an array value, taking into account the 'dimensions' for this
3223
+ array type.
3224
+
3225
+ See the Postgresql ARRAY datatype for usage examples.
3226
+
3227
+ .. versionadded:: 2.0
3228
+
3229
+ """
3230
+
3231
+ if dim is None:
3232
+ arr = list(arr)
3233
+ if (
3234
+ dim == 1
3235
+ or dim is None
3236
+ and (
3237
+ # this has to be (list, tuple), or at least
3238
+ # not hasattr('__iter__'), since Py3K strings
3239
+ # etc. have __iter__
3240
+ not arr
3241
+ or not isinstance(arr[0], (list, tuple))
3242
+ )
3243
+ ):
3244
+ if itemproc:
3245
+ return collection_callable(itemproc(x) for x in arr)
3246
+ else:
3247
+ return collection_callable(arr)
3248
+ else:
3249
+ return collection_callable(
3250
+ (
3251
+ self._apply_item_processor(
3252
+ x,
3253
+ itemproc,
3254
+ dim - 1 if dim is not None else None,
3255
+ collection_callable,
3256
+ )
3257
+ if x is not None
3258
+ else None
3259
+ )
3260
+ for x in arr
3261
+ )
3262
+
3263
+
3264
+ class TupleType(TypeEngine[Tuple[Any, ...]]):
3265
+ """represent the composite type of a Tuple."""
3266
+
3267
+ _is_tuple_type = True
3268
+
3269
+ types: List[TypeEngine[Any]]
3270
+
3271
+ def __init__(self, *types: _TypeEngineArgument[Any]):
3272
+ self._fully_typed = NULLTYPE not in types
3273
+ self.types = [
3274
+ item_type() if isinstance(item_type, type) else item_type
3275
+ for item_type in types
3276
+ ]
3277
+
3278
+ def coerce_compared_value(
3279
+ self, op: Optional[OperatorType], value: Any
3280
+ ) -> TypeEngine[Any]:
3281
+ if value is type_api._NO_VALUE_IN_LIST:
3282
+ return super().coerce_compared_value(op, value)
3283
+ else:
3284
+ return TupleType(
3285
+ *[
3286
+ typ.coerce_compared_value(op, elem)
3287
+ for typ, elem in zip(self.types, value)
3288
+ ]
3289
+ )
3290
+
3291
+ def _resolve_values_to_types(self, value: Any) -> TupleType:
3292
+ if self._fully_typed:
3293
+ return self
3294
+ else:
3295
+ return TupleType(
3296
+ *[
3297
+ _resolve_value_to_type(elem) if typ is NULLTYPE else typ
3298
+ for typ, elem in zip(self.types, value)
3299
+ ]
3300
+ )
3301
+
3302
+ def result_processor(self, dialect, coltype):
3303
+ raise NotImplementedError(
3304
+ "The tuple type does not support being fetched "
3305
+ "as a column in a result row."
3306
+ )
3307
+
3308
+
3309
+ class REAL(Float[_N]):
3310
+ """The SQL REAL type.
3311
+
3312
+ .. seealso::
3313
+
3314
+ :class:`_types.Float` - documentation for the base type.
3315
+
3316
+ """
3317
+
3318
+ __visit_name__ = "REAL"
3319
+
3320
+
3321
+ class FLOAT(Float[_N]):
3322
+ """The SQL FLOAT type.
3323
+
3324
+ .. seealso::
3325
+
3326
+ :class:`_types.Float` - documentation for the base type.
3327
+
3328
+ """
3329
+
3330
+ __visit_name__ = "FLOAT"
3331
+
3332
+
3333
+ class DOUBLE(Double[_N]):
3334
+ """The SQL DOUBLE type.
3335
+
3336
+ .. versionadded:: 2.0
3337
+
3338
+ .. seealso::
3339
+
3340
+ :class:`_types.Double` - documentation for the base type.
3341
+
3342
+ """
3343
+
3344
+ __visit_name__ = "DOUBLE"
3345
+
3346
+
3347
+ class DOUBLE_PRECISION(Double[_N]):
3348
+ """The SQL DOUBLE PRECISION type.
3349
+
3350
+ .. versionadded:: 2.0
3351
+
3352
+ .. seealso::
3353
+
3354
+ :class:`_types.Double` - documentation for the base type.
3355
+
3356
+ """
3357
+
3358
+ __visit_name__ = "DOUBLE_PRECISION"
3359
+
3360
+
3361
+ class NUMERIC(Numeric[_N]):
3362
+ """The SQL NUMERIC type.
3363
+
3364
+ .. seealso::
3365
+
3366
+ :class:`_types.Numeric` - documentation for the base type.
3367
+
3368
+ """
3369
+
3370
+ __visit_name__ = "NUMERIC"
3371
+
3372
+
3373
+ class DECIMAL(Numeric[_N]):
3374
+ """The SQL DECIMAL type.
3375
+
3376
+ .. seealso::
3377
+
3378
+ :class:`_types.Numeric` - documentation for the base type.
3379
+
3380
+ """
3381
+
3382
+ __visit_name__ = "DECIMAL"
3383
+
3384
+
3385
+ class INTEGER(Integer):
3386
+ """The SQL INT or INTEGER type.
3387
+
3388
+ .. seealso::
3389
+
3390
+ :class:`_types.Integer` - documentation for the base type.
3391
+
3392
+ """
3393
+
3394
+ __visit_name__ = "INTEGER"
3395
+
3396
+
3397
+ INT = INTEGER
3398
+
3399
+
3400
+ class SMALLINT(SmallInteger):
3401
+ """The SQL SMALLINT type.
3402
+
3403
+ .. seealso::
3404
+
3405
+ :class:`_types.SmallInteger` - documentation for the base type.
3406
+
3407
+ """
3408
+
3409
+ __visit_name__ = "SMALLINT"
3410
+
3411
+
3412
+ class BIGINT(BigInteger):
3413
+ """The SQL BIGINT type.
3414
+
3415
+ .. seealso::
3416
+
3417
+ :class:`_types.BigInteger` - documentation for the base type.
3418
+
3419
+ """
3420
+
3421
+ __visit_name__ = "BIGINT"
3422
+
3423
+
3424
+ class TIMESTAMP(DateTime):
3425
+ """The SQL TIMESTAMP type.
3426
+
3427
+ :class:`_types.TIMESTAMP` datatypes have support for timezone storage on
3428
+ some backends, such as PostgreSQL and Oracle Database. Use the
3429
+ :paramref:`~types.TIMESTAMP.timezone` argument in order to enable
3430
+ "TIMESTAMP WITH TIMEZONE" for these backends.
3431
+
3432
+ """
3433
+
3434
+ __visit_name__ = "TIMESTAMP"
3435
+
3436
+ def __init__(self, timezone: bool = False):
3437
+ """Construct a new :class:`_types.TIMESTAMP`.
3438
+
3439
+ :param timezone: boolean. Indicates that the TIMESTAMP type should
3440
+ enable timezone support, if available on the target database.
3441
+ On a per-dialect basis is similar to "TIMESTAMP WITH TIMEZONE".
3442
+ If the target database does not support timezones, this flag is
3443
+ ignored.
3444
+
3445
+
3446
+ """
3447
+ super().__init__(timezone=timezone)
3448
+
3449
+ def get_dbapi_type(self, dbapi):
3450
+ return dbapi.TIMESTAMP
3451
+
3452
+
3453
+ class DATETIME(DateTime):
3454
+ """The SQL DATETIME type."""
3455
+
3456
+ __visit_name__ = "DATETIME"
3457
+
3458
+
3459
+ class DATE(Date):
3460
+ """The SQL DATE type."""
3461
+
3462
+ __visit_name__ = "DATE"
3463
+
3464
+
3465
+ class TIME(Time):
3466
+ """The SQL TIME type."""
3467
+
3468
+ __visit_name__ = "TIME"
3469
+
3470
+
3471
+ class TEXT(Text):
3472
+ """The SQL TEXT type."""
3473
+
3474
+ __visit_name__ = "TEXT"
3475
+
3476
+
3477
+ class CLOB(Text):
3478
+ """The CLOB type.
3479
+
3480
+ This type is found in Oracle Database and Informix.
3481
+ """
3482
+
3483
+ __visit_name__ = "CLOB"
3484
+
3485
+
3486
+ class VARCHAR(String):
3487
+ """The SQL VARCHAR type."""
3488
+
3489
+ __visit_name__ = "VARCHAR"
3490
+
3491
+
3492
+ class NVARCHAR(Unicode):
3493
+ """The SQL NVARCHAR type."""
3494
+
3495
+ __visit_name__ = "NVARCHAR"
3496
+
3497
+
3498
+ class CHAR(String):
3499
+ """The SQL CHAR type."""
3500
+
3501
+ __visit_name__ = "CHAR"
3502
+
3503
+
3504
+ class NCHAR(Unicode):
3505
+ """The SQL NCHAR type."""
3506
+
3507
+ __visit_name__ = "NCHAR"
3508
+
3509
+
3510
+ class BLOB(LargeBinary):
3511
+ """The SQL BLOB type."""
3512
+
3513
+ __visit_name__ = "BLOB"
3514
+
3515
+
3516
+ class BINARY(_Binary):
3517
+ """The SQL BINARY type."""
3518
+
3519
+ __visit_name__ = "BINARY"
3520
+
3521
+
3522
+ class VARBINARY(_Binary):
3523
+ """The SQL VARBINARY type."""
3524
+
3525
+ __visit_name__ = "VARBINARY"
3526
+
3527
+
3528
+ class BOOLEAN(Boolean):
3529
+ """The SQL BOOLEAN type."""
3530
+
3531
+ __visit_name__ = "BOOLEAN"
3532
+
3533
+
3534
+ class NullType(TypeEngine[None]):
3535
+ """An unknown type.
3536
+
3537
+ :class:`.NullType` is used as a default type for those cases where
3538
+ a type cannot be determined, including:
3539
+
3540
+ * During table reflection, when the type of a column is not recognized
3541
+ by the :class:`.Dialect`
3542
+ * When constructing SQL expressions using plain Python objects of
3543
+ unknown types (e.g. ``somecolumn == my_special_object``)
3544
+ * When a new :class:`_schema.Column` is created,
3545
+ and the given type is passed
3546
+ as ``None`` or is not passed at all.
3547
+
3548
+ The :class:`.NullType` can be used within SQL expression invocation
3549
+ without issue, it just has no behavior either at the expression
3550
+ construction level or at the bind-parameter/result processing level.
3551
+ :class:`.NullType` will result in a :exc:`.CompileError` if the compiler
3552
+ is asked to render the type itself, such as if it is used in a
3553
+ :func:`.cast` operation or within a schema creation operation such as that
3554
+ invoked by :meth:`_schema.MetaData.create_all` or the
3555
+ :class:`.CreateTable`
3556
+ construct.
3557
+
3558
+ """
3559
+
3560
+ __visit_name__ = "null"
3561
+
3562
+ _isnull = True
3563
+
3564
+ def literal_processor(self, dialect):
3565
+ return None
3566
+
3567
+ class Comparator(TypeEngine.Comparator[_T]):
3568
+ __slots__ = ()
3569
+
3570
+ def _adapt_expression(
3571
+ self,
3572
+ op: OperatorType,
3573
+ other_comparator: TypeEngine.Comparator[Any],
3574
+ ) -> Tuple[OperatorType, TypeEngine[Any]]:
3575
+ if isinstance(
3576
+ other_comparator, NullType.Comparator
3577
+ ) or not operators.is_commutative(op):
3578
+ return op, self.expr.type
3579
+ else:
3580
+ return other_comparator._adapt_expression(op, self)
3581
+
3582
+ comparator_factory = Comparator
3583
+
3584
+
3585
+ class TableValueType(HasCacheKey, TypeEngine[Any]):
3586
+ """Refers to a table value type."""
3587
+
3588
+ _is_table_value = True
3589
+
3590
+ _traverse_internals = [
3591
+ ("_elements", InternalTraversal.dp_clauseelement_list),
3592
+ ]
3593
+
3594
+ def __init__(self, *elements: Union[str, _ColumnExpressionArgument[Any]]):
3595
+ self._elements = [
3596
+ coercions.expect(roles.StrAsPlainColumnRole, elem)
3597
+ for elem in elements
3598
+ ]
3599
+
3600
+
3601
+ class MatchType(Boolean):
3602
+ """Refers to the return type of the MATCH operator.
3603
+
3604
+ As the :meth:`.ColumnOperators.match` is probably the most open-ended
3605
+ operator in generic SQLAlchemy Core, we can't assume the return type
3606
+ at SQL evaluation time, as MySQL returns a floating point, not a boolean,
3607
+ and other backends might do something different. So this type
3608
+ acts as a placeholder, currently subclassing :class:`.Boolean`.
3609
+ The type allows dialects to inject result-processing functionality
3610
+ if needed, and on MySQL will return floating-point values.
3611
+
3612
+ """
3613
+
3614
+
3615
+ _UUID_RETURN = TypeVar("_UUID_RETURN", str, _python_UUID)
3616
+
3617
+
3618
+ class Uuid(Emulated, TypeEngine[_UUID_RETURN]):
3619
+ """Represent a database agnostic UUID datatype.
3620
+
3621
+ For backends that have no "native" UUID datatype, the value will
3622
+ make use of ``CHAR(32)`` and store the UUID as a 32-character alphanumeric
3623
+ hex string.
3624
+
3625
+ For backends which are known to support ``UUID`` directly or a similar
3626
+ uuid-storing datatype such as SQL Server's ``UNIQUEIDENTIFIER``, a
3627
+ "native" mode enabled by default allows these types will be used on those
3628
+ backends.
3629
+
3630
+ In its default mode of use, the :class:`_sqltypes.Uuid` datatype expects
3631
+ **Python uuid objects**, from the Python
3632
+ `uuid <https://docs.python.org/3/library/uuid.html>`_
3633
+ module::
3634
+
3635
+ import uuid
3636
+
3637
+ from sqlalchemy import Uuid
3638
+ from sqlalchemy import Table, Column, MetaData, String
3639
+
3640
+
3641
+ metadata_obj = MetaData()
3642
+
3643
+ t = Table(
3644
+ "t",
3645
+ metadata_obj,
3646
+ Column("uuid_data", Uuid, primary_key=True),
3647
+ Column("other_data", String),
3648
+ )
3649
+
3650
+ with engine.begin() as conn:
3651
+ conn.execute(
3652
+ t.insert(), {"uuid_data": uuid.uuid4(), "other_data": "some data"}
3653
+ )
3654
+
3655
+ To have the :class:`_sqltypes.Uuid` datatype work with string-based
3656
+ Uuids (e.g. 32 character hexadecimal strings), pass the
3657
+ :paramref:`_sqltypes.Uuid.as_uuid` parameter with the value ``False``.
3658
+
3659
+ .. versionadded:: 2.0
3660
+
3661
+ .. seealso::
3662
+
3663
+ :class:`_sqltypes.UUID` - represents exactly the ``UUID`` datatype
3664
+ without any backend-agnostic behaviors.
3665
+
3666
+ """ # noqa: E501
3667
+
3668
+ __visit_name__ = "uuid"
3669
+
3670
+ length: Optional[int] = None
3671
+ collation: Optional[str] = None
3672
+
3673
+ @overload
3674
+ def __init__(
3675
+ self: Uuid[_python_UUID],
3676
+ as_uuid: Literal[True] = ...,
3677
+ native_uuid: bool = ...,
3678
+ ): ...
3679
+
3680
+ @overload
3681
+ def __init__(
3682
+ self: Uuid[str],
3683
+ as_uuid: Literal[False] = ...,
3684
+ native_uuid: bool = ...,
3685
+ ): ...
3686
+
3687
+ def __init__(self, as_uuid: bool = True, native_uuid: bool = True):
3688
+ """Construct a :class:`_sqltypes.Uuid` type.
3689
+
3690
+ :param as_uuid=True: if True, values will be interpreted
3691
+ as Python uuid objects, converting to/from string via the
3692
+ DBAPI.
3693
+
3694
+ .. versionchanged: 2.0 ``as_uuid`` now defaults to ``True``.
3695
+
3696
+ :param native_uuid=True: if True, backends that support either the
3697
+ ``UUID`` datatype directly, or a UUID-storing value
3698
+ (such as SQL Server's ``UNIQUEIDENTIFIER`` will be used by those
3699
+ backends. If False, a ``CHAR(32)`` datatype will be used for
3700
+ all backends regardless of native support.
3701
+
3702
+ """
3703
+ self.as_uuid = as_uuid
3704
+ self.native_uuid = native_uuid
3705
+
3706
+ @property
3707
+ def python_type(self):
3708
+ return _python_UUID if self.as_uuid else str
3709
+
3710
+ @property
3711
+ def native(self): # type: ignore[override]
3712
+ return self.native_uuid
3713
+
3714
+ def coerce_compared_value(self, op, value):
3715
+ """See :meth:`.TypeEngine.coerce_compared_value` for a description."""
3716
+
3717
+ if isinstance(value, str):
3718
+ return self
3719
+ else:
3720
+ return super().coerce_compared_value(op, value)
3721
+
3722
+ def bind_processor(
3723
+ self, dialect: Dialect
3724
+ ) -> Optional[_BindProcessorType[_UUID_RETURN]]:
3725
+ character_based_uuid = (
3726
+ not dialect.supports_native_uuid or not self.native_uuid
3727
+ )
3728
+
3729
+ if character_based_uuid:
3730
+ if self.as_uuid:
3731
+
3732
+ def process(value):
3733
+ if value is not None:
3734
+ value = value.hex
3735
+ return value
3736
+
3737
+ return process
3738
+ else:
3739
+
3740
+ def process(value):
3741
+ if value is not None:
3742
+ value = value.replace("-", "")
3743
+ return value
3744
+
3745
+ return process
3746
+ else:
3747
+ return None
3748
+
3749
+ def result_processor(self, dialect, coltype):
3750
+ character_based_uuid = (
3751
+ not dialect.supports_native_uuid or not self.native_uuid
3752
+ )
3753
+
3754
+ if character_based_uuid:
3755
+ if self.as_uuid:
3756
+
3757
+ def process(value):
3758
+ if value is not None:
3759
+ value = _python_UUID(value)
3760
+ return value
3761
+
3762
+ return process
3763
+ else:
3764
+
3765
+ def process(value):
3766
+ if value is not None:
3767
+ value = str(_python_UUID(value))
3768
+ return value
3769
+
3770
+ return process
3771
+ else:
3772
+ if not self.as_uuid:
3773
+
3774
+ def process(value):
3775
+ if value is not None:
3776
+ value = str(value)
3777
+ return value
3778
+
3779
+ return process
3780
+ else:
3781
+ return None
3782
+
3783
+ def literal_processor(self, dialect):
3784
+ character_based_uuid = (
3785
+ not dialect.supports_native_uuid or not self.native_uuid
3786
+ )
3787
+
3788
+ if not self.as_uuid:
3789
+
3790
+ def process(value):
3791
+ return f"""'{value.replace("-", "").replace("'", "''")}'"""
3792
+
3793
+ return process
3794
+ else:
3795
+ if character_based_uuid:
3796
+
3797
+ def process(value):
3798
+ return f"""'{value.hex}'"""
3799
+
3800
+ return process
3801
+ else:
3802
+
3803
+ def process(value):
3804
+ return f"""'{str(value).replace("'", "''")}'"""
3805
+
3806
+ return process
3807
+
3808
+
3809
+ class UUID(Uuid[_UUID_RETURN], type_api.NativeForEmulated):
3810
+ """Represent the SQL UUID type.
3811
+
3812
+ This is the SQL-native form of the :class:`_types.Uuid` database agnostic
3813
+ datatype, and is backwards compatible with the previous PostgreSQL-only
3814
+ version of ``UUID``.
3815
+
3816
+ The :class:`_sqltypes.UUID` datatype only works on databases that have a
3817
+ SQL datatype named ``UUID``. It will not function for backends which don't
3818
+ have this exact-named type, including SQL Server. For backend-agnostic UUID
3819
+ values with native support, including for SQL Server's ``UNIQUEIDENTIFIER``
3820
+ datatype, use the :class:`_sqltypes.Uuid` datatype.
3821
+
3822
+ .. versionadded:: 2.0
3823
+
3824
+ .. seealso::
3825
+
3826
+ :class:`_sqltypes.Uuid`
3827
+
3828
+ """
3829
+
3830
+ __visit_name__ = "UUID"
3831
+
3832
+ @overload
3833
+ def __init__(self: UUID[_python_UUID], as_uuid: Literal[True] = ...): ...
3834
+
3835
+ @overload
3836
+ def __init__(self: UUID[str], as_uuid: Literal[False] = ...): ...
3837
+
3838
+ def __init__(self, as_uuid: bool = True):
3839
+ """Construct a :class:`_sqltypes.UUID` type.
3840
+
3841
+
3842
+ :param as_uuid=True: if True, values will be interpreted
3843
+ as Python uuid objects, converting to/from string via the
3844
+ DBAPI.
3845
+
3846
+ .. versionchanged: 2.0 ``as_uuid`` now defaults to ``True``.
3847
+
3848
+ """
3849
+ self.as_uuid = as_uuid
3850
+ self.native_uuid = True
3851
+
3852
+ @classmethod
3853
+ def adapt_emulated_to_native(cls, impl, **kw):
3854
+ kw.setdefault("as_uuid", impl.as_uuid)
3855
+ return cls(**kw)
3856
+
3857
+
3858
+ NULLTYPE = NullType()
3859
+ BOOLEANTYPE = Boolean()
3860
+ STRINGTYPE = String()
3861
+ INTEGERTYPE = Integer()
3862
+ NUMERICTYPE: Numeric[decimal.Decimal] = Numeric()
3863
+ MATCHTYPE = MatchType()
3864
+ TABLEVALUE = TableValueType()
3865
+ DATETIME_TIMEZONE = DateTime(timezone=True)
3866
+ TIME_TIMEZONE = Time(timezone=True)
3867
+ _BIGINTEGER = BigInteger()
3868
+ _DATETIME = DateTime()
3869
+ _TIME = Time()
3870
+ _STRING = String()
3871
+ _UNICODE = Unicode()
3872
+
3873
+ _type_map: Dict[Type[Any], TypeEngine[Any]] = {
3874
+ int: Integer(),
3875
+ float: Float(),
3876
+ bool: BOOLEANTYPE,
3877
+ _python_UUID: Uuid(),
3878
+ decimal.Decimal: Numeric(),
3879
+ dt.date: Date(),
3880
+ dt.datetime: _DATETIME,
3881
+ dt.time: _TIME,
3882
+ dt.timedelta: Interval(),
3883
+ type(None): NULLTYPE,
3884
+ bytes: LargeBinary(),
3885
+ str: _STRING,
3886
+ enum.Enum: Enum(enum.Enum),
3887
+ Literal: Enum(enum.Enum), # type: ignore[dict-item]
3888
+ }
3889
+
3890
+
3891
+ _type_map_get = _type_map.get
3892
+
3893
+
3894
+ def _resolve_value_to_type(value: Any) -> TypeEngine[Any]:
3895
+ _result_type = _type_map_get(type(value), False)
3896
+
3897
+ if _result_type is False:
3898
+ _result_type = getattr(value, "__sa_type_engine__", False)
3899
+
3900
+ if _result_type is False:
3901
+ # use inspect() to detect SQLAlchemy built-in
3902
+ # objects.
3903
+ insp = inspection.inspect(value, False)
3904
+ if (
3905
+ insp is not None
3906
+ and
3907
+ # foil mock.Mock() and other impostors by ensuring
3908
+ # the inspection target itself self-inspects
3909
+ insp.__class__ in inspection._registrars
3910
+ ):
3911
+ raise exc.ArgumentError(
3912
+ "Object %r is not legal as a SQL literal value" % (value,)
3913
+ )
3914
+ return NULLTYPE
3915
+ else:
3916
+ return _result_type._resolve_for_literal( # type: ignore [union-attr]
3917
+ value
3918
+ )
3919
+
3920
+
3921
+ # back-assign to type_api
3922
+ type_api.BOOLEANTYPE = BOOLEANTYPE
3923
+ type_api.STRINGTYPE = STRINGTYPE
3924
+ type_api.INTEGERTYPE = INTEGERTYPE
3925
+ type_api.NULLTYPE = NULLTYPE
3926
+ type_api.NUMERICTYPE = NUMERICTYPE
3927
+ type_api.MATCHTYPE = MATCHTYPE
3928
+ type_api.INDEXABLE = INDEXABLE = Indexable
3929
+ type_api.TABLEVALUE = TABLEVALUE
3930
+ type_api._resolve_value_to_type = _resolve_value_to_type