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