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