SQLAlchemy 2.1.0b1__cp313-cp313-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 (267) hide show
  1. sqlalchemy/__init__.py +295 -0
  2. sqlalchemy/connectors/__init__.py +18 -0
  3. sqlalchemy/connectors/aioodbc.py +161 -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 +88 -0
  9. sqlalchemy/dialects/mssql/aioodbc.py +63 -0
  10. sqlalchemy/dialects/mssql/base.py +4110 -0
  11. sqlalchemy/dialects/mssql/information_schema.py +285 -0
  12. sqlalchemy/dialects/mssql/json.py +129 -0
  13. sqlalchemy/dialects/mssql/provision.py +185 -0
  14. sqlalchemy/dialects/mssql/pymssql.py +126 -0
  15. sqlalchemy/dialects/mssql/pyodbc.py +758 -0
  16. sqlalchemy/dialects/mysql/__init__.py +106 -0
  17. sqlalchemy/dialects/mysql/_mariadb_shim.py +312 -0
  18. sqlalchemy/dialects/mysql/aiomysql.py +226 -0
  19. sqlalchemy/dialects/mysql/asyncmy.py +214 -0
  20. sqlalchemy/dialects/mysql/base.py +3870 -0
  21. sqlalchemy/dialects/mysql/cymysql.py +106 -0
  22. sqlalchemy/dialects/mysql/dml.py +279 -0
  23. sqlalchemy/dialects/mysql/enumerated.py +277 -0
  24. sqlalchemy/dialects/mysql/expression.py +146 -0
  25. sqlalchemy/dialects/mysql/json.py +91 -0
  26. sqlalchemy/dialects/mysql/mariadb.py +67 -0
  27. sqlalchemy/dialects/mysql/mariadbconnector.py +330 -0
  28. sqlalchemy/dialects/mysql/mysqlconnector.py +296 -0
  29. sqlalchemy/dialects/mysql/mysqldb.py +312 -0
  30. sqlalchemy/dialects/mysql/provision.py +147 -0
  31. sqlalchemy/dialects/mysql/pymysql.py +157 -0
  32. sqlalchemy/dialects/mysql/pyodbc.py +156 -0
  33. sqlalchemy/dialects/mysql/reflection.py +724 -0
  34. sqlalchemy/dialects/mysql/reserved_words.py +570 -0
  35. sqlalchemy/dialects/mysql/types.py +845 -0
  36. sqlalchemy/dialects/oracle/__init__.py +83 -0
  37. sqlalchemy/dialects/oracle/base.py +3871 -0
  38. sqlalchemy/dialects/oracle/cx_oracle.py +1522 -0
  39. sqlalchemy/dialects/oracle/dictionary.py +507 -0
  40. sqlalchemy/dialects/oracle/oracledb.py +894 -0
  41. sqlalchemy/dialects/oracle/provision.py +288 -0
  42. sqlalchemy/dialects/oracle/types.py +350 -0
  43. sqlalchemy/dialects/oracle/vector.py +368 -0
  44. sqlalchemy/dialects/postgresql/__init__.py +171 -0
  45. sqlalchemy/dialects/postgresql/_psycopg_common.py +193 -0
  46. sqlalchemy/dialects/postgresql/array.py +534 -0
  47. sqlalchemy/dialects/postgresql/asyncpg.py +1331 -0
  48. sqlalchemy/dialects/postgresql/base.py +5729 -0
  49. sqlalchemy/dialects/postgresql/bitstring.py +327 -0
  50. sqlalchemy/dialects/postgresql/dml.py +360 -0
  51. sqlalchemy/dialects/postgresql/ext.py +593 -0
  52. sqlalchemy/dialects/postgresql/hstore.py +413 -0
  53. sqlalchemy/dialects/postgresql/json.py +407 -0
  54. sqlalchemy/dialects/postgresql/named_types.py +521 -0
  55. sqlalchemy/dialects/postgresql/operators.py +130 -0
  56. sqlalchemy/dialects/postgresql/pg8000.py +672 -0
  57. sqlalchemy/dialects/postgresql/pg_catalog.py +344 -0
  58. sqlalchemy/dialects/postgresql/provision.py +175 -0
  59. sqlalchemy/dialects/postgresql/psycopg.py +815 -0
  60. sqlalchemy/dialects/postgresql/psycopg2.py +887 -0
  61. sqlalchemy/dialects/postgresql/psycopg2cffi.py +61 -0
  62. sqlalchemy/dialects/postgresql/ranges.py +1002 -0
  63. sqlalchemy/dialects/postgresql/types.py +388 -0
  64. sqlalchemy/dialects/sqlite/__init__.py +57 -0
  65. sqlalchemy/dialects/sqlite/aiosqlite.py +321 -0
  66. sqlalchemy/dialects/sqlite/base.py +3050 -0
  67. sqlalchemy/dialects/sqlite/dml.py +279 -0
  68. sqlalchemy/dialects/sqlite/json.py +89 -0
  69. sqlalchemy/dialects/sqlite/provision.py +223 -0
  70. sqlalchemy/dialects/sqlite/pysqlcipher.py +157 -0
  71. sqlalchemy/dialects/sqlite/pysqlite.py +754 -0
  72. sqlalchemy/dialects/type_migration_guidelines.txt +145 -0
  73. sqlalchemy/engine/__init__.py +62 -0
  74. sqlalchemy/engine/_processors_cy.cp313-win_arm64.pyd +0 -0
  75. sqlalchemy/engine/_processors_cy.py +92 -0
  76. sqlalchemy/engine/_result_cy.cp313-win_arm64.pyd +0 -0
  77. sqlalchemy/engine/_result_cy.py +633 -0
  78. sqlalchemy/engine/_row_cy.cp313-win_arm64.pyd +0 -0
  79. sqlalchemy/engine/_row_cy.py +232 -0
  80. sqlalchemy/engine/_util_cy.cp313-win_arm64.pyd +0 -0
  81. sqlalchemy/engine/_util_cy.py +136 -0
  82. sqlalchemy/engine/base.py +3334 -0
  83. sqlalchemy/engine/characteristics.py +155 -0
  84. sqlalchemy/engine/create.py +869 -0
  85. sqlalchemy/engine/cursor.py +2416 -0
  86. sqlalchemy/engine/default.py +2393 -0
  87. sqlalchemy/engine/events.py +965 -0
  88. sqlalchemy/engine/interfaces.py +3465 -0
  89. sqlalchemy/engine/mock.py +134 -0
  90. sqlalchemy/engine/processors.py +82 -0
  91. sqlalchemy/engine/reflection.py +2100 -0
  92. sqlalchemy/engine/result.py +1932 -0
  93. sqlalchemy/engine/row.py +397 -0
  94. sqlalchemy/engine/strategies.py +16 -0
  95. sqlalchemy/engine/url.py +922 -0
  96. sqlalchemy/engine/util.py +156 -0
  97. sqlalchemy/event/__init__.py +26 -0
  98. sqlalchemy/event/api.py +220 -0
  99. sqlalchemy/event/attr.py +674 -0
  100. sqlalchemy/event/base.py +472 -0
  101. sqlalchemy/event/legacy.py +258 -0
  102. sqlalchemy/event/registry.py +390 -0
  103. sqlalchemy/events.py +17 -0
  104. sqlalchemy/exc.py +922 -0
  105. sqlalchemy/ext/__init__.py +11 -0
  106. sqlalchemy/ext/associationproxy.py +2072 -0
  107. sqlalchemy/ext/asyncio/__init__.py +29 -0
  108. sqlalchemy/ext/asyncio/base.py +281 -0
  109. sqlalchemy/ext/asyncio/engine.py +1475 -0
  110. sqlalchemy/ext/asyncio/exc.py +21 -0
  111. sqlalchemy/ext/asyncio/result.py +994 -0
  112. sqlalchemy/ext/asyncio/scoping.py +1667 -0
  113. sqlalchemy/ext/asyncio/session.py +1993 -0
  114. sqlalchemy/ext/automap.py +1701 -0
  115. sqlalchemy/ext/baked.py +559 -0
  116. sqlalchemy/ext/compiler.py +600 -0
  117. sqlalchemy/ext/declarative/__init__.py +65 -0
  118. sqlalchemy/ext/declarative/extensions.py +560 -0
  119. sqlalchemy/ext/horizontal_shard.py +481 -0
  120. sqlalchemy/ext/hybrid.py +1877 -0
  121. sqlalchemy/ext/indexable.py +364 -0
  122. sqlalchemy/ext/instrumentation.py +450 -0
  123. sqlalchemy/ext/mutable.py +1081 -0
  124. sqlalchemy/ext/orderinglist.py +439 -0
  125. sqlalchemy/ext/serializer.py +185 -0
  126. sqlalchemy/future/__init__.py +16 -0
  127. sqlalchemy/future/engine.py +15 -0
  128. sqlalchemy/inspection.py +174 -0
  129. sqlalchemy/log.py +283 -0
  130. sqlalchemy/orm/__init__.py +175 -0
  131. sqlalchemy/orm/_orm_constructors.py +2694 -0
  132. sqlalchemy/orm/_typing.py +179 -0
  133. sqlalchemy/orm/attributes.py +2868 -0
  134. sqlalchemy/orm/base.py +970 -0
  135. sqlalchemy/orm/bulk_persistence.py +2152 -0
  136. sqlalchemy/orm/clsregistry.py +582 -0
  137. sqlalchemy/orm/collections.py +1568 -0
  138. sqlalchemy/orm/context.py +3471 -0
  139. sqlalchemy/orm/decl_api.py +2257 -0
  140. sqlalchemy/orm/decl_base.py +2304 -0
  141. sqlalchemy/orm/dependency.py +1306 -0
  142. sqlalchemy/orm/descriptor_props.py +1183 -0
  143. sqlalchemy/orm/dynamic.py +300 -0
  144. sqlalchemy/orm/evaluator.py +379 -0
  145. sqlalchemy/orm/events.py +3386 -0
  146. sqlalchemy/orm/exc.py +237 -0
  147. sqlalchemy/orm/identity.py +302 -0
  148. sqlalchemy/orm/instrumentation.py +746 -0
  149. sqlalchemy/orm/interfaces.py +1589 -0
  150. sqlalchemy/orm/loading.py +1684 -0
  151. sqlalchemy/orm/mapped_collection.py +557 -0
  152. sqlalchemy/orm/mapper.py +4406 -0
  153. sqlalchemy/orm/path_registry.py +814 -0
  154. sqlalchemy/orm/persistence.py +1789 -0
  155. sqlalchemy/orm/properties.py +973 -0
  156. sqlalchemy/orm/query.py +3521 -0
  157. sqlalchemy/orm/relationships.py +3570 -0
  158. sqlalchemy/orm/scoping.py +2220 -0
  159. sqlalchemy/orm/session.py +5389 -0
  160. sqlalchemy/orm/state.py +1175 -0
  161. sqlalchemy/orm/state_changes.py +196 -0
  162. sqlalchemy/orm/strategies.py +3480 -0
  163. sqlalchemy/orm/strategy_options.py +2544 -0
  164. sqlalchemy/orm/sync.py +164 -0
  165. sqlalchemy/orm/unitofwork.py +798 -0
  166. sqlalchemy/orm/util.py +2435 -0
  167. sqlalchemy/orm/writeonly.py +694 -0
  168. sqlalchemy/pool/__init__.py +41 -0
  169. sqlalchemy/pool/base.py +1514 -0
  170. sqlalchemy/pool/events.py +372 -0
  171. sqlalchemy/pool/impl.py +582 -0
  172. sqlalchemy/py.typed +0 -0
  173. sqlalchemy/schema.py +72 -0
  174. sqlalchemy/sql/__init__.py +153 -0
  175. sqlalchemy/sql/_dml_constructors.py +132 -0
  176. sqlalchemy/sql/_elements_constructors.py +2147 -0
  177. sqlalchemy/sql/_orm_types.py +20 -0
  178. sqlalchemy/sql/_selectable_constructors.py +773 -0
  179. sqlalchemy/sql/_typing.py +486 -0
  180. sqlalchemy/sql/_util_cy.cp313-win_arm64.pyd +0 -0
  181. sqlalchemy/sql/_util_cy.py +127 -0
  182. sqlalchemy/sql/annotation.py +590 -0
  183. sqlalchemy/sql/base.py +2602 -0
  184. sqlalchemy/sql/cache_key.py +1066 -0
  185. sqlalchemy/sql/coercions.py +1373 -0
  186. sqlalchemy/sql/compiler.py +8259 -0
  187. sqlalchemy/sql/crud.py +1807 -0
  188. sqlalchemy/sql/ddl.py +1928 -0
  189. sqlalchemy/sql/default_comparator.py +654 -0
  190. sqlalchemy/sql/dml.py +1974 -0
  191. sqlalchemy/sql/elements.py +6016 -0
  192. sqlalchemy/sql/events.py +458 -0
  193. sqlalchemy/sql/expression.py +170 -0
  194. sqlalchemy/sql/functions.py +2257 -0
  195. sqlalchemy/sql/lambdas.py +1443 -0
  196. sqlalchemy/sql/naming.py +209 -0
  197. sqlalchemy/sql/operators.py +2897 -0
  198. sqlalchemy/sql/roles.py +332 -0
  199. sqlalchemy/sql/schema.py +6560 -0
  200. sqlalchemy/sql/selectable.py +7497 -0
  201. sqlalchemy/sql/sqltypes.py +4050 -0
  202. sqlalchemy/sql/traversals.py +1042 -0
  203. sqlalchemy/sql/type_api.py +2425 -0
  204. sqlalchemy/sql/util.py +1495 -0
  205. sqlalchemy/sql/visitors.py +1157 -0
  206. sqlalchemy/testing/__init__.py +96 -0
  207. sqlalchemy/testing/assertions.py +1007 -0
  208. sqlalchemy/testing/assertsql.py +519 -0
  209. sqlalchemy/testing/asyncio.py +128 -0
  210. sqlalchemy/testing/config.py +440 -0
  211. sqlalchemy/testing/engines.py +478 -0
  212. sqlalchemy/testing/entities.py +117 -0
  213. sqlalchemy/testing/exclusions.py +476 -0
  214. sqlalchemy/testing/fixtures/__init__.py +30 -0
  215. sqlalchemy/testing/fixtures/base.py +366 -0
  216. sqlalchemy/testing/fixtures/mypy.py +247 -0
  217. sqlalchemy/testing/fixtures/orm.py +227 -0
  218. sqlalchemy/testing/fixtures/sql.py +538 -0
  219. sqlalchemy/testing/pickleable.py +155 -0
  220. sqlalchemy/testing/plugin/__init__.py +6 -0
  221. sqlalchemy/testing/plugin/bootstrap.py +51 -0
  222. sqlalchemy/testing/plugin/plugin_base.py +828 -0
  223. sqlalchemy/testing/plugin/pytestplugin.py +892 -0
  224. sqlalchemy/testing/profiling.py +329 -0
  225. sqlalchemy/testing/provision.py +596 -0
  226. sqlalchemy/testing/requirements.py +1973 -0
  227. sqlalchemy/testing/schema.py +198 -0
  228. sqlalchemy/testing/suite/__init__.py +19 -0
  229. sqlalchemy/testing/suite/test_cte.py +237 -0
  230. sqlalchemy/testing/suite/test_ddl.py +420 -0
  231. sqlalchemy/testing/suite/test_dialect.py +776 -0
  232. sqlalchemy/testing/suite/test_insert.py +630 -0
  233. sqlalchemy/testing/suite/test_reflection.py +3557 -0
  234. sqlalchemy/testing/suite/test_results.py +660 -0
  235. sqlalchemy/testing/suite/test_rowcount.py +258 -0
  236. sqlalchemy/testing/suite/test_select.py +2112 -0
  237. sqlalchemy/testing/suite/test_sequence.py +317 -0
  238. sqlalchemy/testing/suite/test_table_via_select.py +686 -0
  239. sqlalchemy/testing/suite/test_types.py +2253 -0
  240. sqlalchemy/testing/suite/test_unicode_ddl.py +189 -0
  241. sqlalchemy/testing/suite/test_update_delete.py +139 -0
  242. sqlalchemy/testing/util.py +535 -0
  243. sqlalchemy/testing/warnings.py +52 -0
  244. sqlalchemy/types.py +76 -0
  245. sqlalchemy/util/__init__.py +157 -0
  246. sqlalchemy/util/_collections.py +693 -0
  247. sqlalchemy/util/_collections_cy.cp313-win_arm64.pyd +0 -0
  248. sqlalchemy/util/_collections_cy.pxd +8 -0
  249. sqlalchemy/util/_collections_cy.py +516 -0
  250. sqlalchemy/util/_has_cython.py +46 -0
  251. sqlalchemy/util/_immutabledict_cy.cp313-win_arm64.pyd +0 -0
  252. sqlalchemy/util/_immutabledict_cy.py +240 -0
  253. sqlalchemy/util/compat.py +287 -0
  254. sqlalchemy/util/concurrency.py +322 -0
  255. sqlalchemy/util/cython.py +79 -0
  256. sqlalchemy/util/deprecations.py +401 -0
  257. sqlalchemy/util/langhelpers.py +2256 -0
  258. sqlalchemy/util/preloaded.py +152 -0
  259. sqlalchemy/util/queue.py +304 -0
  260. sqlalchemy/util/tool_support.py +201 -0
  261. sqlalchemy/util/topological.py +120 -0
  262. sqlalchemy/util/typing.py +711 -0
  263. sqlalchemy-2.1.0b1.dist-info/METADATA +267 -0
  264. sqlalchemy-2.1.0b1.dist-info/RECORD +267 -0
  265. sqlalchemy-2.1.0b1.dist-info/WHEEL +5 -0
  266. sqlalchemy-2.1.0b1.dist-info/licenses/LICENSE +19 -0
  267. sqlalchemy-2.1.0b1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,2425 @@
1
+ # sql/type_api.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
+
8
+ """Base types API."""
9
+
10
+ from __future__ import annotations
11
+
12
+ from enum import Enum
13
+ import typing
14
+ from typing import Any
15
+ from typing import Callable
16
+ from typing import cast
17
+ from typing import ClassVar
18
+ from typing import Dict
19
+ from typing import Generic
20
+ from typing import Mapping
21
+ from typing import Optional
22
+ from typing import overload
23
+ from typing import Protocol
24
+ from typing import Sequence
25
+ from typing import Tuple
26
+ from typing import Type
27
+ from typing import TYPE_CHECKING
28
+ from typing import TypedDict
29
+ from typing import TypeGuard
30
+ from typing import TypeVar
31
+ from typing import Union
32
+
33
+ from sqlalchemy.util.typing import _MatchedOnType
34
+ from .base import SchemaEventTarget
35
+ from .cache_key import CacheConst
36
+ from .cache_key import NO_CACHE
37
+ from .operators import _OPERATOR_CLASSES
38
+ from .operators import ColumnOperators
39
+ from .operators import custom_op
40
+ from .operators import OperatorClass
41
+ from .visitors import Visitable
42
+ from .. import exc
43
+ from .. import util
44
+ from ..util.typing import Self
45
+
46
+ # these are back-assigned by sqltypes.
47
+ if typing.TYPE_CHECKING:
48
+ from ._typing import _TypeEngineArgument
49
+ from .elements import BindParameter
50
+ from .elements import ColumnElement
51
+ from .operators import OperatorType
52
+ from .sqltypes import _resolve_value_to_type as _resolve_value_to_type
53
+ from .sqltypes import BOOLEANTYPE as BOOLEANTYPE # noqa: F401
54
+ from .sqltypes import INDEXABLE as INDEXABLE # noqa: F401
55
+ from .sqltypes import INTEGERTYPE as INTEGERTYPE # noqa: F401
56
+ from .sqltypes import MATCHTYPE as MATCHTYPE # noqa: F401
57
+ from .sqltypes import NULLTYPE as NULLTYPE
58
+ from .sqltypes import NUMERICTYPE as NUMERICTYPE # noqa: F401
59
+ from .sqltypes import STRINGTYPE as STRINGTYPE # noqa: F401
60
+ from .sqltypes import TABLEVALUE as TABLEVALUE # noqa: F401
61
+ from ..engine.interfaces import DBAPIModule
62
+ from ..engine.interfaces import Dialect
63
+
64
+ _T = TypeVar("_T", bound=Any)
65
+ _T_co = TypeVar("_T_co", bound=Any, covariant=True)
66
+ _T_con = TypeVar("_T_con", bound=Any, contravariant=True)
67
+ _O = TypeVar("_O", bound=object)
68
+ _TE = TypeVar("_TE", bound="TypeEngine[Any]")
69
+ _CT = TypeVar("_CT", bound=Any)
70
+ _RT = TypeVar("_RT", bound=Any)
71
+
72
+
73
+ class _NoValueInList(Enum):
74
+ NO_VALUE_IN_LIST = 0
75
+ """indicates we are trying to determine the type of an expression
76
+ against an empty list."""
77
+
78
+
79
+ _NO_VALUE_IN_LIST = _NoValueInList.NO_VALUE_IN_LIST
80
+
81
+
82
+ class _LiteralProcessorType(Protocol[_T_co]):
83
+ def __call__(self, value: Any) -> str: ...
84
+
85
+
86
+ class _BindProcessorType(Protocol[_T_con]):
87
+ def __call__(self, value: Optional[_T_con]) -> Any: ...
88
+
89
+
90
+ class _ResultProcessorType(Protocol[_T_co]):
91
+ def __call__(self, value: Any) -> Optional[_T_co]: ...
92
+
93
+
94
+ class _SentinelProcessorType(Protocol[_T_co]):
95
+ def __call__(self, value: Any) -> Optional[_T_co]: ...
96
+
97
+
98
+ class _BaseTypeMemoDict(TypedDict):
99
+ impl: TypeEngine[Any]
100
+ result: Dict[Any, Optional[_ResultProcessorType[Any]]]
101
+
102
+
103
+ class _TypeMemoDict(_BaseTypeMemoDict, total=False):
104
+ literal: Optional[_LiteralProcessorType[Any]]
105
+ bind: Optional[_BindProcessorType[Any]]
106
+ sentinel: Optional[_SentinelProcessorType[Any]]
107
+ custom: Dict[Any, object]
108
+
109
+
110
+ class _ComparatorFactory(Protocol[_T]):
111
+ def __call__(
112
+ self, expr: ColumnElement[_T]
113
+ ) -> TypeEngine.Comparator[_T]: ...
114
+
115
+
116
+ class TypeEngine(Visitable, Generic[_T]):
117
+ """The ultimate base class for all SQL datatypes.
118
+
119
+ Common subclasses of :class:`.TypeEngine` include
120
+ :class:`.String`, :class:`.Integer`, and :class:`.Boolean`.
121
+
122
+ For an overview of the SQLAlchemy typing system, see
123
+ :ref:`types_toplevel`.
124
+
125
+ .. seealso::
126
+
127
+ :ref:`types_toplevel`
128
+
129
+ """
130
+
131
+ _sqla_type = True
132
+ _isnull = False
133
+ _is_tuple_type = False
134
+ _is_table_value = False
135
+ _is_array = False
136
+ _is_type_decorator = False
137
+
138
+ render_bind_cast = False
139
+ """Render bind casts for :attr:`.BindTyping.RENDER_CASTS` mode.
140
+
141
+ If True, this type (usually a dialect level impl type) signals
142
+ to the compiler that a cast should be rendered around a bound parameter
143
+ for this type.
144
+
145
+ .. versionadded:: 2.0
146
+
147
+ .. seealso::
148
+
149
+ :class:`.BindTyping`
150
+
151
+ """
152
+
153
+ render_literal_cast = False
154
+ """render casts when rendering a value as an inline literal,
155
+ e.g. with :meth:`.TypeEngine.literal_processor`.
156
+
157
+ .. versionadded:: 2.0
158
+
159
+ """
160
+
161
+ operator_classes: ClassVar[OperatorClass] = OperatorClass.UNSPECIFIED
162
+ """Indicate categories of operators that should be available on this type.
163
+
164
+ .. versionadded:: 2.1
165
+
166
+ .. seealso::
167
+
168
+ :class:`.OperatorClass`
169
+
170
+ """
171
+
172
+ class Comparator(
173
+ ColumnOperators,
174
+ Generic[_CT],
175
+ ):
176
+ """Base class for custom comparison operations defined at the
177
+ type level. See :attr:`.TypeEngine.comparator_factory`.
178
+
179
+
180
+ """
181
+
182
+ __slots__ = "expr", "type"
183
+
184
+ expr: ColumnElement[_CT]
185
+ type: TypeEngine[_CT]
186
+
187
+ def __clause_element__(self) -> ColumnElement[_CT]:
188
+ return self.expr
189
+
190
+ def __init__(self, expr: ColumnElement[_CT]):
191
+ self.expr = expr
192
+ self.type = expr.type
193
+
194
+ def __reduce__(self) -> Any:
195
+ return self.__class__, (self.expr,)
196
+
197
+ @util.preload_module("sqlalchemy.sql.default_comparator")
198
+ def _resolve_operator_lookup(self, op: OperatorType) -> Tuple[
199
+ Callable[..., "ColumnElement[Any]"],
200
+ util.immutabledict[
201
+ str, Union["OperatorType", Callable[..., "ColumnElement[Any]"]]
202
+ ],
203
+ ]:
204
+ default_comparator = util.preloaded.sql_default_comparator
205
+
206
+ op_fn, addtl_kw = default_comparator.operator_lookup[op.__name__]
207
+
208
+ if op_fn is default_comparator._custom_op_operate:
209
+ if TYPE_CHECKING:
210
+ assert isinstance(op, custom_op)
211
+ operator_class = op.operator_class
212
+ else:
213
+ try:
214
+ operator_class = _OPERATOR_CLASSES[op]
215
+ except KeyError:
216
+ operator_class = OperatorClass.UNSPECIFIED
217
+
218
+ if not operator_class & self.type.operator_classes:
219
+
220
+ if self.type.operator_classes is OperatorClass.UNSPECIFIED:
221
+ util.warn_deprecated(
222
+ f"Type object {self.type.__class__} does not refer "
223
+ "to an OperatorClass in its operator_classes "
224
+ "attribute. This attribute will be required in a "
225
+ "future release.",
226
+ "2.1",
227
+ )
228
+ else:
229
+ if isinstance(op, custom_op):
230
+ op_description = f"custom operator {op.opstring!r}"
231
+ else:
232
+ op_description = f"operator {op.__name__!r}"
233
+
234
+ util.warn_deprecated(
235
+ f"Type object {self.type.__class__!r} does not "
236
+ "include "
237
+ f"{op_description} in its operator classes. "
238
+ "Using built-in operators (not including custom or "
239
+ "overridden operators) outside of "
240
+ "a type's stated operator classes is deprecated and "
241
+ "will raise InvalidRequestError in a future release",
242
+ "2.1",
243
+ )
244
+
245
+ return op_fn, addtl_kw
246
+
247
+ @overload
248
+ def operate(
249
+ self,
250
+ op: OperatorType,
251
+ *other: Any,
252
+ result_type: Type[TypeEngine[_RT]],
253
+ **kwargs: Any,
254
+ ) -> ColumnElement[_RT]: ...
255
+
256
+ @overload
257
+ def operate(
258
+ self, op: OperatorType, *other: Any, **kwargs: Any
259
+ ) -> ColumnElement[_CT]: ...
260
+
261
+ def operate(
262
+ self, op: OperatorType, *other: Any, **kwargs: Any
263
+ ) -> ColumnElement[Any]:
264
+ op_fn, addtl_kw = self._resolve_operator_lookup(op)
265
+ if kwargs:
266
+ addtl_kw = addtl_kw.union(kwargs)
267
+ return op_fn(self.expr, op, *other, **addtl_kw)
268
+
269
+ def reverse_operate(
270
+ self, op: OperatorType, other: Any, **kwargs: Any
271
+ ) -> ColumnElement[_CT]:
272
+ op_fn, addtl_kw = self._resolve_operator_lookup(op)
273
+
274
+ if kwargs:
275
+ addtl_kw = addtl_kw.union(kwargs)
276
+ return op_fn(self.expr, op, other, reverse=True, **addtl_kw)
277
+
278
+ def _adapt_expression(
279
+ self,
280
+ op: OperatorType,
281
+ other_comparator: TypeEngine.Comparator[Any],
282
+ ) -> Tuple[OperatorType, TypeEngine[Any]]:
283
+ """evaluate the return type of <self> <op> <othertype>,
284
+ and apply any adaptations to the given operator.
285
+
286
+ This method determines the type of a resulting binary expression
287
+ given two source types and an operator. For example, two
288
+ :class:`_schema.Column` objects, both of the type
289
+ :class:`.Integer`, will
290
+ produce a :class:`.BinaryExpression` that also has the type
291
+ :class:`.Integer` when compared via the addition (``+``) operator.
292
+ However, using the addition operator with an :class:`.Integer`
293
+ and a :class:`.Date` object will produce a :class:`.Date`, assuming
294
+ "days delta" behavior by the database (in reality, most databases
295
+ other than PostgreSQL don't accept this particular operation).
296
+
297
+ The method returns a tuple of the form <operator>, <type>.
298
+ The resulting operator and type will be those applied to the
299
+ resulting :class:`.BinaryExpression` as the final operator and the
300
+ right-hand side of the expression.
301
+
302
+ Note that only a subset of operators make usage of
303
+ :meth:`._adapt_expression`,
304
+ including math operators and user-defined operators, but not
305
+ boolean comparison or special SQL keywords like MATCH or BETWEEN.
306
+
307
+ """
308
+
309
+ return op, self.type
310
+
311
+ hashable = True
312
+ """Flag, if False, means values from this type aren't hashable.
313
+
314
+ Used by the ORM when uniquing result lists.
315
+
316
+ """
317
+
318
+ comparator_factory: _ComparatorFactory[Any] = Comparator
319
+ """A :class:`.TypeEngine.Comparator` class which will apply
320
+ to operations performed by owning :class:`_expression.ColumnElement`
321
+ objects.
322
+
323
+ The :attr:`.comparator_factory` attribute is a hook consulted by
324
+ the core expression system when column and SQL expression operations
325
+ are performed. When a :class:`.TypeEngine.Comparator` class is
326
+ associated with this attribute, it allows custom re-definition of
327
+ all existing operators, as well as definition of new operators.
328
+ Existing operators include those provided by Python operator overloading
329
+ such as :meth:`.operators.ColumnOperators.__add__` and
330
+ :meth:`.operators.ColumnOperators.__eq__`,
331
+ those provided as standard
332
+ attributes of :class:`.operators.ColumnOperators` such as
333
+ :meth:`.operators.ColumnOperators.like`
334
+ and :meth:`.operators.ColumnOperators.in_`.
335
+
336
+ Rudimentary usage of this hook is allowed through simple subclassing
337
+ of existing types, or alternatively by using :class:`.TypeDecorator`.
338
+ See the documentation section :ref:`types_operators` for examples.
339
+
340
+ """
341
+
342
+ sort_key_function: Optional[Callable[[Any], Any]] = None
343
+ """A sorting function that can be passed as the key to sorted.
344
+
345
+ The default value of ``None`` indicates that the values stored by
346
+ this type are self-sorting.
347
+
348
+ """
349
+
350
+ should_evaluate_none: bool = False
351
+ """If True, the Python constant ``None`` is considered to be handled
352
+ explicitly by this type.
353
+
354
+ The ORM uses this flag to indicate that a positive value of ``None``
355
+ is passed to the column in an INSERT statement, rather than omitting
356
+ the column from the INSERT statement which has the effect of firing
357
+ off column-level defaults. It also allows types which have special
358
+ behavior for Python None, such as a JSON type, to indicate that
359
+ they'd like to handle the None value explicitly.
360
+
361
+ To set this flag on an existing type, use the
362
+ :meth:`.TypeEngine.evaluates_none` method.
363
+
364
+ .. seealso::
365
+
366
+ :meth:`.TypeEngine.evaluates_none`
367
+
368
+ """
369
+
370
+ _variant_mapping: util.immutabledict[str, TypeEngine[Any]] = (
371
+ util.EMPTY_DICT
372
+ )
373
+
374
+ def evaluates_none(self) -> Self:
375
+ """Return a copy of this type which has the
376
+ :attr:`.should_evaluate_none` flag set to True.
377
+
378
+ E.g.::
379
+
380
+ Table(
381
+ "some_table",
382
+ metadata,
383
+ Column(
384
+ String(50).evaluates_none(),
385
+ nullable=True,
386
+ server_default="no value",
387
+ ),
388
+ )
389
+
390
+ The ORM uses this flag to indicate that a positive value of ``None``
391
+ is passed to the column in an INSERT statement, rather than omitting
392
+ the column from the INSERT statement which has the effect of firing
393
+ off column-level defaults. It also allows for types which have
394
+ special behavior associated with the Python None value to indicate
395
+ that the value doesn't necessarily translate into SQL NULL; a
396
+ prime example of this is a JSON type which may wish to persist the
397
+ JSON value ``'null'``.
398
+
399
+ In all cases, the actual NULL SQL value can be always be
400
+ persisted in any column by using
401
+ the :obj:`_expression.null` SQL construct in an INSERT statement
402
+ or associated with an ORM-mapped attribute.
403
+
404
+ .. note::
405
+
406
+ The "evaluates none" flag does **not** apply to a value
407
+ of ``None`` passed to :paramref:`_schema.Column.default` or
408
+ :paramref:`_schema.Column.server_default`; in these cases,
409
+ ``None``
410
+ still means "no default".
411
+
412
+ .. seealso::
413
+
414
+ :ref:`session_forcing_null` - in the ORM documentation
415
+
416
+ :paramref:`.postgresql.JSON.none_as_null` - PostgreSQL JSON
417
+ interaction with this flag.
418
+
419
+ :attr:`.TypeEngine.should_evaluate_none` - class-level flag
420
+
421
+ """
422
+ typ = self.copy()
423
+ typ.should_evaluate_none = True
424
+ return typ
425
+
426
+ def copy(self, **kw: Any) -> Self:
427
+ return self.adapt(self.__class__)
428
+
429
+ def copy_value(self, value: Any) -> Any:
430
+ return value
431
+
432
+ def literal_processor(
433
+ self, dialect: Dialect
434
+ ) -> Optional[_LiteralProcessorType[_T]]:
435
+ """Return a conversion function for processing literal values that are
436
+ to be rendered directly without using binds.
437
+
438
+ This function is used when the compiler makes use of the
439
+ "literal_binds" flag, typically used in DDL generation as well
440
+ as in certain scenarios where backends don't accept bound parameters.
441
+
442
+ Returns a callable which will receive a literal Python value
443
+ as the sole positional argument and will return a string representation
444
+ to be rendered in a SQL statement.
445
+
446
+ .. tip::
447
+
448
+ This method is only called relative to a **dialect specific type
449
+ object**, which is often **private to a dialect in use** and is not
450
+ the same type object as the public facing one, which means it's not
451
+ feasible to subclass a :class:`.types.TypeEngine` class in order to
452
+ provide an alternate :meth:`_types.TypeEngine.literal_processor`
453
+ method, unless subclassing the :class:`_types.UserDefinedType`
454
+ class explicitly.
455
+
456
+ To provide alternate behavior for
457
+ :meth:`_types.TypeEngine.literal_processor`, implement a
458
+ :class:`_types.TypeDecorator` class and provide an implementation
459
+ of :meth:`_types.TypeDecorator.process_literal_param`.
460
+
461
+ .. seealso::
462
+
463
+ :ref:`types_typedecorator`
464
+
465
+
466
+ """
467
+ return None
468
+
469
+ def bind_processor(
470
+ self, dialect: Dialect
471
+ ) -> Optional[_BindProcessorType[_T]]:
472
+ """Return a conversion function for processing bind values.
473
+
474
+ Returns a callable which will receive a bind parameter value
475
+ as the sole positional argument and will return a value to
476
+ send to the DB-API.
477
+
478
+ If processing is not necessary, the method should return ``None``.
479
+
480
+ .. tip::
481
+
482
+ This method is only called relative to a **dialect specific type
483
+ object**, which is often **private to a dialect in use** and is not
484
+ the same type object as the public facing one, which means it's not
485
+ feasible to subclass a :class:`.types.TypeEngine` class in order to
486
+ provide an alternate :meth:`_types.TypeEngine.bind_processor`
487
+ method, unless subclassing the :class:`_types.UserDefinedType`
488
+ class explicitly.
489
+
490
+ To provide alternate behavior for
491
+ :meth:`_types.TypeEngine.bind_processor`, implement a
492
+ :class:`_types.TypeDecorator` class and provide an implementation
493
+ of :meth:`_types.TypeDecorator.process_bind_param`.
494
+
495
+ .. seealso::
496
+
497
+ :ref:`types_typedecorator`
498
+
499
+
500
+ :param dialect: Dialect instance in use.
501
+
502
+ """
503
+ return None
504
+
505
+ def result_processor(
506
+ self, dialect: Dialect, coltype: object
507
+ ) -> Optional[_ResultProcessorType[_T]]:
508
+ """Return a conversion function for processing result row values.
509
+
510
+ Returns a callable which will receive a result row column
511
+ value as the sole positional argument and will return a value
512
+ to return to the user.
513
+
514
+ If processing is not necessary, the method should return ``None``.
515
+
516
+ .. tip::
517
+
518
+ This method is only called relative to a **dialect specific type
519
+ object**, which is often **private to a dialect in use** and is not
520
+ the same type object as the public facing one, which means it's not
521
+ feasible to subclass a :class:`.types.TypeEngine` class in order to
522
+ provide an alternate :meth:`_types.TypeEngine.result_processor`
523
+ method, unless subclassing the :class:`_types.UserDefinedType`
524
+ class explicitly.
525
+
526
+ To provide alternate behavior for
527
+ :meth:`_types.TypeEngine.result_processor`, implement a
528
+ :class:`_types.TypeDecorator` class and provide an implementation
529
+ of :meth:`_types.TypeDecorator.process_result_value`.
530
+
531
+ .. seealso::
532
+
533
+ :ref:`types_typedecorator`
534
+
535
+ :param dialect: Dialect instance in use.
536
+
537
+ :param coltype: DBAPI coltype argument received in cursor.description.
538
+
539
+ """
540
+ return None
541
+
542
+ def column_expression(
543
+ self, colexpr: ColumnElement[_T]
544
+ ) -> Optional[ColumnElement[_T]]:
545
+ """Given a SELECT column expression, return a wrapping SQL expression.
546
+
547
+ This is typically a SQL function that wraps a column expression
548
+ as rendered in the columns clause of a SELECT statement.
549
+ It is used for special data types that require
550
+ columns to be wrapped in some special database function in order
551
+ to coerce the value before being sent back to the application.
552
+ It is the SQL analogue of the :meth:`.TypeEngine.result_processor`
553
+ method.
554
+
555
+ .. note:: The :func:`.TypeEngine.column_expression` method is applied
556
+ only to the **outermost columns clause** of a SELECT statement, that
557
+ is, the columns that are to be delivered directly into the returned
558
+ result rows. It does **not** apply to the columns clause inside
559
+ of subqueries. This necessarily avoids double conversions against
560
+ the column and only runs the conversion when ready to be returned
561
+ to the client.
562
+
563
+ This method is called during the **SQL compilation** phase of a
564
+ statement, when rendering a SQL string. It is **not** called
565
+ against specific values.
566
+
567
+ .. tip::
568
+
569
+ This method is only called relative to a **dialect specific type
570
+ object**, which is often **private to a dialect in use** and is not
571
+ the same type object as the public facing one, which means it's not
572
+ feasible to subclass a :class:`.types.TypeEngine` class in order to
573
+ provide an alternate :meth:`_types.TypeEngine.column_expression`
574
+ method, unless subclassing the :class:`_types.UserDefinedType`
575
+ class explicitly.
576
+
577
+ To provide alternate behavior for
578
+ :meth:`_types.TypeEngine.column_expression`, implement a
579
+ :class:`_types.TypeDecorator` class and provide an implementation
580
+ of :meth:`_types.TypeDecorator.column_expression`.
581
+
582
+ .. seealso::
583
+
584
+ :ref:`types_typedecorator`
585
+
586
+
587
+ .. seealso::
588
+
589
+ :ref:`types_sql_value_processing`
590
+
591
+ """
592
+
593
+ return None
594
+
595
+ @util.memoized_property
596
+ def _has_column_expression(self) -> bool:
597
+ """memoized boolean, check if column_expression is implemented.
598
+
599
+ Allows the method to be skipped for the vast majority of expression
600
+ types that don't use this feature.
601
+
602
+ """
603
+
604
+ return (
605
+ self.__class__.column_expression.__code__
606
+ is not TypeEngine.column_expression.__code__
607
+ )
608
+
609
+ def bind_expression(
610
+ self, bindvalue: BindParameter[_T]
611
+ ) -> Optional[ColumnElement[_T]]:
612
+ """Given a bind value (i.e. a :class:`.BindParameter` instance),
613
+ return a SQL expression in its place.
614
+
615
+ This is typically a SQL function that wraps the existing bound
616
+ parameter within the statement. It is used for special data types
617
+ that require literals being wrapped in some special database function
618
+ in order to coerce an application-level value into a database-specific
619
+ format. It is the SQL analogue of the
620
+ :meth:`.TypeEngine.bind_processor` method.
621
+
622
+ This method is called during the **SQL compilation** phase of a
623
+ statement, when rendering a SQL string. It is **not** called
624
+ against specific values.
625
+
626
+ Note that this method, when implemented, should always return
627
+ the exact same structure, without any conditional logic, as it
628
+ may be used in an executemany() call against an arbitrary number
629
+ of bound parameter sets.
630
+
631
+ .. note::
632
+
633
+ This method is only called relative to a **dialect specific type
634
+ object**, which is often **private to a dialect in use** and is not
635
+ the same type object as the public facing one, which means it's not
636
+ feasible to subclass a :class:`.types.TypeEngine` class in order to
637
+ provide an alternate :meth:`_types.TypeEngine.bind_expression`
638
+ method, unless subclassing the :class:`_types.UserDefinedType`
639
+ class explicitly.
640
+
641
+ To provide alternate behavior for
642
+ :meth:`_types.TypeEngine.bind_expression`, implement a
643
+ :class:`_types.TypeDecorator` class and provide an implementation
644
+ of :meth:`_types.TypeDecorator.bind_expression`.
645
+
646
+ .. seealso::
647
+
648
+ :ref:`types_typedecorator`
649
+
650
+ .. seealso::
651
+
652
+ :ref:`types_sql_value_processing`
653
+
654
+ """
655
+ return None
656
+
657
+ @util.memoized_property
658
+ def _has_bind_expression(self) -> bool:
659
+ """memoized boolean, check if bind_expression is implemented.
660
+
661
+ Allows the method to be skipped for the vast majority of expression
662
+ types that don't use this feature.
663
+
664
+ """
665
+
666
+ return util.method_is_overridden(self, TypeEngine.bind_expression)
667
+
668
+ @staticmethod
669
+ def _to_instance(cls_or_self: Union[Type[_TE], _TE]) -> _TE:
670
+ return to_instance(cls_or_self)
671
+
672
+ def compare_values(self, x: Any, y: Any) -> bool:
673
+ """Compare two values for equality."""
674
+
675
+ return x == y # type: ignore[no-any-return]
676
+
677
+ def get_dbapi_type(self, dbapi: DBAPIModule) -> Optional[Any]:
678
+ """Return the corresponding type object from the underlying DB-API, if
679
+ any.
680
+
681
+ This can be useful for calling ``setinputsizes()``, for example.
682
+
683
+ """
684
+ return None
685
+
686
+ @property
687
+ def python_type(self) -> Type[Any]:
688
+ """Return the Python type object expected to be returned
689
+ by instances of this type.
690
+
691
+ Basically, for those types which enforce a return type,
692
+ or are known across the board to do such for all common
693
+ DBAPIs (like ``int`` for example), will return that type.
694
+
695
+ By default the generic ``object`` type is returned.
696
+
697
+ Note that any type also accommodates NULL in SQL which
698
+ means you can also get back ``None`` from any type
699
+ in practice.
700
+
701
+ .. versionchanged:: 2.1 - The default implementation now returns
702
+ ``object`` instead of raising ``NotImplementedError``.
703
+ """
704
+ return object
705
+
706
+ def with_variant(
707
+ self,
708
+ type_: _TypeEngineArgument[Any],
709
+ *dialect_names: str,
710
+ ) -> Self:
711
+ r"""Produce a copy of this type object that will utilize the given
712
+ type when applied to the dialect of the given name.
713
+
714
+ e.g.::
715
+
716
+ from sqlalchemy.types import String
717
+ from sqlalchemy.dialects import mysql
718
+
719
+ string_type = String()
720
+
721
+ string_type = string_type.with_variant(
722
+ mysql.VARCHAR(collation="foo"), "mysql", "mariadb"
723
+ )
724
+
725
+ The variant mapping indicates that when this type is
726
+ interpreted by a specific dialect, it will instead be
727
+ transmuted into the given type, rather than using the
728
+ primary type.
729
+
730
+ .. versionchanged:: 2.0 the :meth:`_types.TypeEngine.with_variant`
731
+ method now works with a :class:`_types.TypeEngine` object "in
732
+ place", returning a copy of the original type rather than returning
733
+ a wrapping object; the ``Variant`` class is no longer used.
734
+
735
+ :param type\_: a :class:`.TypeEngine` that will be selected
736
+ as a variant from the originating type, when a dialect
737
+ of the given name is in use.
738
+ :param \*dialect_names: one or more base names of the dialect which
739
+ uses this type. (i.e. ``'postgresql'``, ``'mysql'``, etc.)
740
+
741
+ .. versionchanged:: 2.0 multiple dialect names can be specified
742
+ for one variant.
743
+
744
+ .. seealso::
745
+
746
+ :ref:`types_with_variant` - illustrates the use of
747
+ :meth:`_types.TypeEngine.with_variant`.
748
+
749
+ """
750
+
751
+ if not dialect_names:
752
+ raise exc.ArgumentError("At least one dialect name is required")
753
+ for dialect_name in dialect_names:
754
+ if dialect_name in self._variant_mapping:
755
+ raise exc.ArgumentError(
756
+ f"Dialect {dialect_name!r} is already present in "
757
+ f"the mapping for this {self!r}"
758
+ )
759
+ new_type = self.copy()
760
+ type_ = to_instance(type_)
761
+ if type_._variant_mapping:
762
+ raise exc.ArgumentError(
763
+ "can't pass a type that already has variants as a "
764
+ "dialect-level type to with_variant()"
765
+ )
766
+
767
+ new_type._variant_mapping = self._variant_mapping.union(
768
+ {dialect_name: type_ for dialect_name in dialect_names}
769
+ )
770
+ return new_type
771
+
772
+ def _resolve_for_literal(self, value: Any) -> Self:
773
+ """adjust this type given a literal Python value that will be
774
+ stored in a bound parameter.
775
+
776
+ Used exclusively by _resolve_value_to_type().
777
+
778
+ .. versionadded:: 1.4.30 or 2.0
779
+
780
+ TODO: this should be part of public API
781
+
782
+ .. seealso::
783
+
784
+ :meth:`.TypeEngine._resolve_for_python_type`
785
+
786
+ """
787
+ return self
788
+
789
+ def _resolve_for_python_type(
790
+ self,
791
+ python_type: Type[Any],
792
+ matched_on: _MatchedOnType,
793
+ matched_on_flattened: Type[Any],
794
+ ) -> Optional[Self]:
795
+ """given a Python type (e.g. ``int``, ``str``, etc. ) return an
796
+ instance of this :class:`.TypeEngine` that's appropriate for this type.
797
+
798
+ An additional argument ``matched_on`` is passed, which indicates an
799
+ entry from the ``__mro__`` of the given ``python_type`` that more
800
+ specifically matches how the caller located this :class:`.TypeEngine`
801
+ object. Such as, if a lookup of some kind links the ``int`` Python
802
+ type to the :class:`.Integer` SQL type, and the original object
803
+ was some custom subclass of ``int`` such as ``MyInt(int)``, the
804
+ arguments passed would be ``(MyInt, int)``.
805
+
806
+ If the given Python type does not correspond to this
807
+ :class:`.TypeEngine`, or the Python type is otherwise ambiguous, the
808
+ method should return None.
809
+
810
+ For simple cases, the method checks that the ``python_type``
811
+ and ``matched_on`` types are the same (i.e. not a subclass), and
812
+ returns self; for all other cases, it returns ``None``.
813
+
814
+ The initial use case here is for the ORM to link user-defined
815
+ Python standard library ``enum.Enum`` classes to the SQLAlchemy
816
+ :class:`.Enum` SQL type when constructing ORM Declarative mappings.
817
+
818
+ :param python_type: the Python type we want to use
819
+ :param matched_on: the Python type that led us to choose this
820
+ particular :class:`.TypeEngine` class, which would be a supertype
821
+ of ``python_type``. By default, the request is rejected if
822
+ ``python_type`` doesn't match ``matched_on`` (None is returned).
823
+
824
+ .. versionadded:: 2.0.0b4
825
+
826
+ TODO: this should be part of public API
827
+
828
+ .. seealso::
829
+
830
+ :meth:`.TypeEngine._resolve_for_literal`
831
+
832
+ """
833
+
834
+ if python_type is not matched_on_flattened:
835
+ return None
836
+
837
+ return self
838
+
839
+ def _with_collation(self, collation: str) -> Self:
840
+ """set up error handling for the collate expression"""
841
+ raise NotImplementedError("this datatype does not support collation")
842
+
843
+ @util.ro_memoized_property
844
+ def _type_affinity(self) -> Optional[Type[TypeEngine[_T]]]:
845
+ """Return a rudimental 'affinity' value expressing the general class
846
+ of type."""
847
+
848
+ typ = None
849
+ for t in self.__class__.__mro__:
850
+ if t is TypeEngine or TypeEngineMixin in t.__bases__:
851
+ return typ
852
+ elif issubclass(t, TypeEngine):
853
+ typ = t
854
+ else:
855
+ return self.__class__
856
+
857
+ @util.ro_memoized_property
858
+ def _generic_type_affinity(
859
+ self,
860
+ ) -> Type[TypeEngine[_T]]:
861
+ best_camelcase = None
862
+ best_uppercase = None
863
+
864
+ if not isinstance(self, TypeEngine):
865
+ return self.__class__
866
+
867
+ for t in self.__class__.__mro__:
868
+ if (
869
+ t.__module__
870
+ in (
871
+ "sqlalchemy.sql.sqltypes",
872
+ "sqlalchemy.sql.type_api",
873
+ )
874
+ and issubclass(t, TypeEngine)
875
+ and TypeEngineMixin not in t.__bases__
876
+ and t not in (TypeEngine, TypeEngineMixin)
877
+ and t.__name__[0] != "_"
878
+ ):
879
+ if t.__name__.isupper() and not best_uppercase:
880
+ best_uppercase = t
881
+ elif not t.__name__.isupper() and not best_camelcase:
882
+ best_camelcase = t
883
+
884
+ return (
885
+ best_camelcase
886
+ or best_uppercase
887
+ or cast("Type[TypeEngine[_T]]", NULLTYPE.__class__)
888
+ )
889
+
890
+ def as_generic(self, allow_nulltype: bool = False) -> TypeEngine[_T]:
891
+ """
892
+ Return an instance of the generic type corresponding to this type
893
+ using heuristic rule. The method may be overridden if this
894
+ heuristic rule is not sufficient.
895
+
896
+ >>> from sqlalchemy.dialects.mysql import INTEGER
897
+ >>> INTEGER(display_width=4).as_generic()
898
+ Integer()
899
+
900
+ >>> from sqlalchemy.dialects.mysql import NVARCHAR
901
+ >>> NVARCHAR(length=100).as_generic()
902
+ Unicode(length=100)
903
+
904
+ .. versionadded:: 1.4.0b2
905
+
906
+
907
+ .. seealso::
908
+
909
+ :ref:`metadata_reflection_dbagnostic_types` - describes the
910
+ use of :meth:`_types.TypeEngine.as_generic` in conjunction with
911
+ the :meth:`_sql.DDLEvents.column_reflect` event, which is its
912
+ intended use.
913
+
914
+ """
915
+ if (
916
+ not allow_nulltype
917
+ and self._generic_type_affinity == NULLTYPE.__class__
918
+ ):
919
+ raise NotImplementedError(
920
+ "Default TypeEngine.as_generic() "
921
+ "heuristic method was unsuccessful for {}. A custom "
922
+ "as_generic() method must be implemented for this "
923
+ "type class.".format(
924
+ self.__class__.__module__ + "." + self.__class__.__name__
925
+ )
926
+ )
927
+
928
+ return util.constructor_copy(self, self._generic_type_affinity)
929
+
930
+ def dialect_impl(self, dialect: Dialect) -> TypeEngine[_T]:
931
+ """Return a dialect-specific implementation for this
932
+ :class:`.TypeEngine`.
933
+
934
+ """
935
+ try:
936
+ tm = dialect._type_memos[self]
937
+ except KeyError:
938
+ pass
939
+ else:
940
+ return tm["impl"]
941
+ return self._dialect_info(dialect)["impl"]
942
+
943
+ def _unwrapped_dialect_impl(self, dialect: Dialect) -> TypeEngine[_T]:
944
+ """Return the 'unwrapped' dialect impl for this type.
945
+
946
+ For a type that applies wrapping logic (e.g. TypeDecorator), give
947
+ us the real, actual dialect-level type that is used.
948
+
949
+ This is used by TypeDecorator itself as well at least one case where
950
+ dialects need to check that a particular specific dialect-level
951
+ type is in use, within the :meth:`.DefaultDialect.set_input_sizes`
952
+ method.
953
+
954
+ """
955
+ return self.dialect_impl(dialect)
956
+
957
+ def _cached_literal_processor(
958
+ self, dialect: Dialect
959
+ ) -> Optional[_LiteralProcessorType[_T]]:
960
+ """Return a dialect-specific literal processor for this type."""
961
+
962
+ try:
963
+ return dialect._type_memos[self]["literal"]
964
+ except KeyError:
965
+ pass
966
+
967
+ # avoid KeyError context coming into literal_processor() function
968
+ # raises
969
+ d = self._dialect_info(dialect)
970
+ d["literal"] = lp = d["impl"].literal_processor(dialect)
971
+ return lp
972
+
973
+ def _cached_bind_processor(
974
+ self, dialect: Dialect
975
+ ) -> Optional[_BindProcessorType[_T]]:
976
+ """Return a dialect-specific bind processor for this type."""
977
+
978
+ try:
979
+ return dialect._type_memos[self]["bind"]
980
+ except KeyError:
981
+ pass
982
+
983
+ # avoid KeyError context coming into bind_processor() function
984
+ # raises
985
+ d = self._dialect_info(dialect)
986
+ d["bind"] = bp = d["impl"].bind_processor(dialect)
987
+ return bp
988
+
989
+ def _cached_result_processor(
990
+ self, dialect: Dialect, coltype: Any
991
+ ) -> Optional[_ResultProcessorType[_T]]:
992
+ """Return a dialect-specific result processor for this type."""
993
+
994
+ try:
995
+ return dialect._type_memos[self]["result"][coltype]
996
+ except KeyError:
997
+ pass
998
+
999
+ # avoid KeyError context coming into result_processor() function
1000
+ # raises
1001
+ d = self._dialect_info(dialect)
1002
+ # key assumption: DBAPI type codes are
1003
+ # constants. Else this dictionary would
1004
+ # grow unbounded.
1005
+ rp = d["impl"].result_processor(dialect, coltype)
1006
+ d["result"][coltype] = rp
1007
+ return rp
1008
+
1009
+ def _cached_custom_processor(
1010
+ self, dialect: Dialect, key: str, fn: Callable[[TypeEngine[_T]], _O]
1011
+ ) -> _O:
1012
+ """return a dialect-specific processing object for
1013
+ custom purposes.
1014
+
1015
+ The cx_Oracle dialect uses this at the moment.
1016
+
1017
+ """
1018
+ try:
1019
+ return cast(_O, dialect._type_memos[self]["custom"][key])
1020
+ except KeyError:
1021
+ pass
1022
+ # avoid KeyError context coming into fn() function
1023
+ # raises
1024
+ d = self._dialect_info(dialect)
1025
+ impl = d["impl"]
1026
+ custom_dict = d.setdefault("custom", {})
1027
+ custom_dict[key] = result = fn(impl)
1028
+ return result
1029
+
1030
+ def _dialect_info(self, dialect: Dialect) -> _TypeMemoDict:
1031
+ """Return a dialect-specific registry which
1032
+ caches a dialect-specific implementation, bind processing
1033
+ function, and one or more result processing functions."""
1034
+
1035
+ if self in dialect._type_memos:
1036
+ return dialect._type_memos[self]
1037
+ else:
1038
+ impl = self._gen_dialect_impl(dialect)
1039
+ if impl is self:
1040
+ impl = self.adapt(type(self))
1041
+ # this can't be self, else we create a cycle
1042
+ assert impl is not self
1043
+ d: _TypeMemoDict = {"impl": impl, "result": {}}
1044
+ dialect._type_memos[self] = d
1045
+ return d
1046
+
1047
+ def _gen_dialect_impl(self, dialect: Dialect) -> TypeEngine[Any]:
1048
+ if dialect.name in self._variant_mapping:
1049
+ return self._variant_mapping[dialect.name]._gen_dialect_impl(
1050
+ dialect
1051
+ )
1052
+ else:
1053
+ return dialect.type_descriptor(self)
1054
+
1055
+ @util.memoized_property
1056
+ def _static_cache_key(
1057
+ self,
1058
+ ) -> Union[CacheConst, Tuple[Any, ...]]:
1059
+ names = util.get_cls_kwargs(self.__class__)
1060
+ return (self.__class__,) + tuple(
1061
+ (
1062
+ k,
1063
+ (
1064
+ self.__dict__[k]._static_cache_key
1065
+ if isinstance(self.__dict__[k], TypeEngine)
1066
+ else self.__dict__[k]
1067
+ ),
1068
+ )
1069
+ for k in names
1070
+ if k in self.__dict__
1071
+ and not k.startswith("_")
1072
+ and self.__dict__[k] is not None
1073
+ )
1074
+
1075
+ @overload
1076
+ def adapt(self, cls: Type[_TE], **kw: Any) -> _TE: ...
1077
+
1078
+ @overload
1079
+ def adapt(
1080
+ self, cls: Type[TypeEngineMixin], **kw: Any
1081
+ ) -> TypeEngine[Any]: ...
1082
+
1083
+ def adapt(
1084
+ self, cls: Type[Union[TypeEngine[Any], TypeEngineMixin]], **kw: Any
1085
+ ) -> TypeEngine[Any]:
1086
+ """Produce an "adapted" form of this type, given an "impl" class
1087
+ to work with.
1088
+
1089
+ This method is used internally to associate generic
1090
+ types with "implementation" types that are specific to a particular
1091
+ dialect.
1092
+ """
1093
+ typ = util.constructor_copy(
1094
+ self, cast(Type[TypeEngine[Any]], cls), **kw
1095
+ )
1096
+ typ._variant_mapping = self._variant_mapping
1097
+ return typ
1098
+
1099
+ def coerce_compared_value(
1100
+ self, op: Optional[OperatorType], value: Any
1101
+ ) -> TypeEngine[Any]:
1102
+ """Suggest a type for a 'coerced' Python value in an expression.
1103
+
1104
+ Given an operator and value, gives the type a chance
1105
+ to return a type which the value should be coerced into.
1106
+
1107
+ The default behavior here is conservative; if the right-hand
1108
+ side is already coerced into a SQL type based on its
1109
+ Python type, it is usually left alone.
1110
+
1111
+ End-user functionality extension here should generally be via
1112
+ :class:`.TypeDecorator`, which provides more liberal behavior in that
1113
+ it defaults to coercing the other side of the expression into this
1114
+ type, thus applying special Python conversions above and beyond those
1115
+ needed by the DBAPI to both ides. It also provides the public method
1116
+ :meth:`.TypeDecorator.coerce_compared_value` which is intended for
1117
+ end-user customization of this behavior.
1118
+
1119
+ """
1120
+ _coerced_type = _resolve_value_to_type(value)
1121
+ if (
1122
+ _coerced_type is NULLTYPE
1123
+ or _coerced_type._type_affinity is self._type_affinity
1124
+ ):
1125
+ return self
1126
+ else:
1127
+ return _coerced_type
1128
+
1129
+ def _compare_type_affinity(self, other: TypeEngine[Any]) -> bool:
1130
+ return self._type_affinity is other._type_affinity
1131
+
1132
+ def compile(self, dialect: Optional[Dialect] = None) -> str:
1133
+ """Produce a string-compiled form of this :class:`.TypeEngine`.
1134
+
1135
+ When called with no arguments, uses a "default" dialect
1136
+ to produce a string result.
1137
+
1138
+ :param dialect: a :class:`.Dialect` instance.
1139
+
1140
+ """
1141
+ # arg, return value is inconsistent with
1142
+ # ClauseElement.compile()....this is a mistake.
1143
+
1144
+ if dialect is None:
1145
+ dialect = self._default_dialect()
1146
+
1147
+ return dialect.type_compiler_instance.process(self)
1148
+
1149
+ @util.preload_module("sqlalchemy.engine.default")
1150
+ def _default_dialect(self) -> Dialect:
1151
+ default = util.preloaded.engine_default
1152
+
1153
+ # dmypy / mypy seems to sporadically keep thinking this line is
1154
+ # returning Any, which seems to be caused by the @deprecated_params
1155
+ # decorator on the DefaultDialect constructor
1156
+ return default.StrCompileDialect() # type: ignore
1157
+
1158
+ def __str__(self) -> str:
1159
+ return str(self.compile())
1160
+
1161
+ def __repr__(self) -> str:
1162
+ return util.generic_repr(self)
1163
+
1164
+
1165
+ class TypeEngineMixin:
1166
+ """classes which subclass this can act as "mixin" classes for
1167
+ TypeEngine."""
1168
+
1169
+ __slots__ = ()
1170
+
1171
+ if TYPE_CHECKING:
1172
+
1173
+ @util.memoized_property
1174
+ def _static_cache_key(
1175
+ self,
1176
+ ) -> Union[CacheConst, Tuple[Any, ...]]: ...
1177
+
1178
+ @overload
1179
+ def adapt(self, cls: Type[_TE], **kw: Any) -> _TE: ...
1180
+
1181
+ @overload
1182
+ def adapt(
1183
+ self, cls: Type[TypeEngineMixin], **kw: Any
1184
+ ) -> TypeEngine[Any]: ...
1185
+
1186
+ def adapt(
1187
+ self, cls: Type[Union[TypeEngine[Any], TypeEngineMixin]], **kw: Any
1188
+ ) -> TypeEngine[Any]: ...
1189
+
1190
+ def dialect_impl(self, dialect: Dialect) -> TypeEngine[Any]: ...
1191
+
1192
+
1193
+ class ExternalType(TypeEngineMixin):
1194
+ """mixin that defines attributes and behaviors specific to third-party
1195
+ datatypes.
1196
+
1197
+ "Third party" refers to datatypes that are defined outside the scope
1198
+ of SQLAlchemy within either end-user application code or within
1199
+ external extensions to SQLAlchemy.
1200
+
1201
+ Subclasses currently include :class:`.TypeDecorator` and
1202
+ :class:`.UserDefinedType`.
1203
+
1204
+ .. versionadded:: 1.4.28
1205
+
1206
+ """
1207
+
1208
+ cache_ok: Optional[bool] = None
1209
+ '''Indicate if statements using this :class:`.ExternalType` are "safe to
1210
+ cache".
1211
+
1212
+ The default value ``None`` will emit a warning and then not allow caching
1213
+ of a statement which includes this type. Set to ``False`` to disable
1214
+ statements using this type from being cached at all without a warning.
1215
+ When set to ``True``, the object's class and selected elements from its
1216
+ state will be used as part of the cache key. For example, using a
1217
+ :class:`.TypeDecorator`::
1218
+
1219
+ class MyType(TypeDecorator):
1220
+ impl = String
1221
+
1222
+ cache_ok = True
1223
+
1224
+ def __init__(self, choices):
1225
+ self.choices = tuple(choices)
1226
+ self.internal_only = True
1227
+
1228
+ The cache key for the above type would be equivalent to::
1229
+
1230
+ >>> MyType(["a", "b", "c"])._static_cache_key
1231
+ (<class '__main__.MyType'>, ('choices', ('a', 'b', 'c')))
1232
+
1233
+ The caching scheme will extract attributes from the type that correspond
1234
+ to the names of parameters in the ``__init__()`` method. Above, the
1235
+ "choices" attribute becomes part of the cache key but "internal_only"
1236
+ does not, because there is no parameter named "internal_only".
1237
+
1238
+ The requirements for cacheable elements is that they are hashable
1239
+ and also that they indicate the same SQL rendered for expressions using
1240
+ this type every time for a given cache value.
1241
+
1242
+ To accommodate for datatypes that refer to unhashable structures such
1243
+ as dictionaries, sets and lists, these objects can be made "cacheable"
1244
+ by assigning hashable structures to the attributes whose names
1245
+ correspond with the names of the arguments. For example, a datatype
1246
+ which accepts a dictionary of lookup values may publish this as a sorted
1247
+ series of tuples. Given a previously un-cacheable type as::
1248
+
1249
+ class LookupType(UserDefinedType):
1250
+ """a custom type that accepts a dictionary as a parameter.
1251
+
1252
+ this is the non-cacheable version, as "self.lookup" is not
1253
+ hashable.
1254
+
1255
+ """
1256
+
1257
+ def __init__(self, lookup):
1258
+ self.lookup = lookup
1259
+
1260
+ def get_col_spec(self, **kw):
1261
+ return "VARCHAR(255)"
1262
+
1263
+ def bind_processor(self, dialect): ... # works with "self.lookup" ...
1264
+
1265
+ Where "lookup" is a dictionary. The type will not be able to generate
1266
+ a cache key::
1267
+
1268
+ >>> type_ = LookupType({"a": 10, "b": 20})
1269
+ >>> type_._static_cache_key
1270
+ <stdin>:1: SAWarning: UserDefinedType LookupType({'a': 10, 'b': 20}) will not
1271
+ produce a cache key because the ``cache_ok`` flag is not set to True.
1272
+ Set this flag to True if this type object's state is safe to use
1273
+ in a cache key, or False to disable this warning.
1274
+ symbol('no_cache')
1275
+
1276
+ If we **did** set up such a cache key, it wouldn't be usable. We would
1277
+ get a tuple structure that contains a dictionary inside of it, which
1278
+ cannot itself be used as a key in a "cache dictionary" such as SQLAlchemy's
1279
+ statement cache, since Python dictionaries aren't hashable::
1280
+
1281
+ >>> # set cache_ok = True
1282
+ >>> type_.cache_ok = True
1283
+
1284
+ >>> # this is the cache key it would generate
1285
+ >>> key = type_._static_cache_key
1286
+ >>> key
1287
+ (<class '__main__.LookupType'>, ('lookup', {'a': 10, 'b': 20}))
1288
+
1289
+ >>> # however this key is not hashable, will fail when used with
1290
+ >>> # SQLAlchemy statement cache
1291
+ >>> some_cache = {key: "some sql value"}
1292
+ Traceback (most recent call last): File "<stdin>", line 1,
1293
+ in <module> TypeError: unhashable type: 'dict'
1294
+
1295
+ The type may be made cacheable by assigning a sorted tuple of tuples
1296
+ to the ".lookup" attribute::
1297
+
1298
+ class LookupType(UserDefinedType):
1299
+ """a custom type that accepts a dictionary as a parameter.
1300
+
1301
+ The dictionary is stored both as itself in a private variable,
1302
+ and published in a public variable as a sorted tuple of tuples,
1303
+ which is hashable and will also return the same value for any
1304
+ two equivalent dictionaries. Note it assumes the keys and
1305
+ values of the dictionary are themselves hashable.
1306
+
1307
+ """
1308
+
1309
+ cache_ok = True
1310
+
1311
+ def __init__(self, lookup):
1312
+ self._lookup = lookup
1313
+
1314
+ # assume keys/values of "lookup" are hashable; otherwise
1315
+ # they would also need to be converted in some way here
1316
+ self.lookup = tuple((key, lookup[key]) for key in sorted(lookup))
1317
+
1318
+ def get_col_spec(self, **kw):
1319
+ return "VARCHAR(255)"
1320
+
1321
+ def bind_processor(self, dialect): ... # works with "self._lookup" ...
1322
+
1323
+ Where above, the cache key for ``LookupType({"a": 10, "b": 20})`` will be::
1324
+
1325
+ >>> LookupType({"a": 10, "b": 20})._static_cache_key
1326
+ (<class '__main__.LookupType'>, ('lookup', (('a', 10), ('b', 20))))
1327
+
1328
+ .. versionadded:: 1.4.14 - added the ``cache_ok`` flag to allow
1329
+ some configurability of caching for :class:`.TypeDecorator` classes.
1330
+
1331
+ .. versionadded:: 1.4.28 - added the :class:`.ExternalType` mixin which
1332
+ generalizes the ``cache_ok`` flag to both the :class:`.TypeDecorator`
1333
+ and :class:`.UserDefinedType` classes.
1334
+
1335
+ .. seealso::
1336
+
1337
+ :ref:`sql_caching`
1338
+
1339
+ ''' # noqa: E501
1340
+
1341
+ @util.non_memoized_property
1342
+ def _static_cache_key(
1343
+ self,
1344
+ ) -> Union[CacheConst, Tuple[Any, ...]]:
1345
+ cache_ok = self.__class__.__dict__.get("cache_ok", None)
1346
+
1347
+ if cache_ok is None:
1348
+ for subtype in self.__class__.__mro__:
1349
+ if ExternalType in subtype.__bases__:
1350
+ break
1351
+ else:
1352
+ subtype = self.__class__.__mro__[1]
1353
+
1354
+ util.warn(
1355
+ "%s %r will not produce a cache key because "
1356
+ "the ``cache_ok`` attribute is not set to True. This can "
1357
+ "have significant performance implications including some "
1358
+ "performance degradations in comparison to prior SQLAlchemy "
1359
+ "versions. Set this attribute to True if this type object's "
1360
+ "state is safe to use in a cache key, or False to "
1361
+ "disable this warning." % (subtype.__name__, self),
1362
+ code="cprf",
1363
+ )
1364
+ elif cache_ok is True:
1365
+ return super()._static_cache_key
1366
+
1367
+ return NO_CACHE
1368
+
1369
+
1370
+ class UserDefinedType(
1371
+ ExternalType, TypeEngineMixin, TypeEngine[_T], util.EnsureKWArg
1372
+ ):
1373
+ """Base for user defined types.
1374
+
1375
+ This should be the base of new types. Note that
1376
+ for most cases, :class:`.TypeDecorator` is probably
1377
+ more appropriate::
1378
+
1379
+ import sqlalchemy.types as types
1380
+
1381
+
1382
+ class MyType(types.UserDefinedType):
1383
+ cache_ok = True
1384
+
1385
+ def __init__(self, precision=8):
1386
+ self.precision = precision
1387
+
1388
+ def get_col_spec(self, **kw):
1389
+ return "MYTYPE(%s)" % self.precision
1390
+
1391
+ def bind_processor(self, dialect):
1392
+ def process(value):
1393
+ return value
1394
+
1395
+ return process
1396
+
1397
+ def result_processor(self, dialect, coltype):
1398
+ def process(value):
1399
+ return value
1400
+
1401
+ return process
1402
+
1403
+ Once the type is made, it's immediately usable::
1404
+
1405
+ table = Table(
1406
+ "foo",
1407
+ metadata_obj,
1408
+ Column("id", Integer, primary_key=True),
1409
+ Column("data", MyType(16)),
1410
+ )
1411
+
1412
+ The ``get_col_spec()`` method will in most cases receive a keyword
1413
+ argument ``type_expression`` which refers to the owning expression
1414
+ of the type as being compiled, such as a :class:`_schema.Column` or
1415
+ :func:`.cast` construct. This keyword is only sent if the method
1416
+ accepts keyword arguments (e.g. ``**kw``) in its argument signature;
1417
+ introspection is used to check for this in order to support legacy
1418
+ forms of this function.
1419
+
1420
+ The :attr:`.UserDefinedType.cache_ok` class-level flag indicates if this
1421
+ custom :class:`.UserDefinedType` is safe to be used as part of a cache key.
1422
+ This flag defaults to ``None`` which will initially generate a warning
1423
+ when the SQL compiler attempts to generate a cache key for a statement
1424
+ that uses this type. If the :class:`.UserDefinedType` is not guaranteed
1425
+ to produce the same bind/result behavior and SQL generation
1426
+ every time, this flag should be set to ``False``; otherwise if the
1427
+ class produces the same behavior each time, it may be set to ``True``.
1428
+ See :attr:`.UserDefinedType.cache_ok` for further notes on how this works.
1429
+
1430
+ .. versionadded:: 1.4.28 Generalized the :attr:`.ExternalType.cache_ok`
1431
+ flag so that it is available for both :class:`.TypeDecorator` as well
1432
+ as :class:`.UserDefinedType`.
1433
+
1434
+ """
1435
+
1436
+ __visit_name__ = "user_defined"
1437
+
1438
+ ensure_kwarg = "get_col_spec"
1439
+
1440
+ operator_classes = OperatorClass.ANY
1441
+
1442
+ def coerce_compared_value(
1443
+ self, op: Optional[OperatorType], value: Any
1444
+ ) -> TypeEngine[Any]:
1445
+ """Suggest a type for a 'coerced' Python value in an expression.
1446
+
1447
+ Default behavior for :class:`.UserDefinedType` is the
1448
+ same as that of :class:`.TypeDecorator`; by default it returns
1449
+ ``self``, assuming the compared value should be coerced into
1450
+ the same type as this one. See
1451
+ :meth:`.TypeDecorator.coerce_compared_value` for more detail.
1452
+
1453
+ """
1454
+
1455
+ return self
1456
+
1457
+ if TYPE_CHECKING:
1458
+
1459
+ def get_col_spec(self, **kw: Any) -> str: ...
1460
+
1461
+
1462
+ class Emulated(TypeEngineMixin):
1463
+ """Mixin for base types that emulate the behavior of a DB-native type.
1464
+
1465
+ An :class:`.Emulated` type will use an available database type
1466
+ in conjunction with Python-side routines and/or database constraints
1467
+ in order to approximate the behavior of a database type that is provided
1468
+ natively by some backends. When a native-providing backend is in
1469
+ use, the native version of the type is used. This native version
1470
+ should include the :class:`.NativeForEmulated` mixin to allow it to be
1471
+ distinguished from :class:`.Emulated`.
1472
+
1473
+ Current examples of :class:`.Emulated` are: :class:`.Interval`,
1474
+ :class:`.Enum`, :class:`.Boolean`.
1475
+
1476
+ """
1477
+
1478
+ native: bool
1479
+
1480
+ def adapt_to_emulated(
1481
+ self,
1482
+ impltype: Type[Union[TypeEngine[Any], TypeEngineMixin]],
1483
+ **kw: Any,
1484
+ ) -> TypeEngine[Any]:
1485
+ """Given an impl class, adapt this type to the impl assuming
1486
+ "emulated".
1487
+
1488
+ The impl should also be an "emulated" version of this type,
1489
+ most likely the same class as this type itself.
1490
+
1491
+ e.g.: sqltypes.Enum adapts to the Enum class.
1492
+
1493
+ """
1494
+ return super().adapt(impltype, **kw)
1495
+
1496
+ @overload
1497
+ def adapt(self, cls: Type[_TE], **kw: Any) -> _TE: ...
1498
+
1499
+ @overload
1500
+ def adapt(
1501
+ self, cls: Type[TypeEngineMixin], **kw: Any
1502
+ ) -> TypeEngine[Any]: ...
1503
+
1504
+ def adapt(
1505
+ self, cls: Type[Union[TypeEngine[Any], TypeEngineMixin]], **kw: Any
1506
+ ) -> TypeEngine[Any]:
1507
+ if _is_native_for_emulated(cls):
1508
+ if self.native:
1509
+ # native support requested, dialect gave us a native
1510
+ # implementor, pass control over to it
1511
+ return cls.adapt_emulated_to_native(self, **kw)
1512
+ else:
1513
+ # non-native support, let the native implementor
1514
+ # decide also, at the moment this is just to help debugging
1515
+ # as only the default logic is implemented.
1516
+ return cls.adapt_native_to_emulated(self, **kw)
1517
+ else:
1518
+ # this would be, both classes are Enum, or both classes
1519
+ # are postgresql.ENUM
1520
+ if issubclass(cls, self.__class__):
1521
+ return self.adapt_to_emulated(cls, **kw)
1522
+ else:
1523
+ return super().adapt(cls, **kw)
1524
+
1525
+
1526
+ def _is_native_for_emulated(
1527
+ typ: Type[Union[TypeEngine[Any], TypeEngineMixin]],
1528
+ ) -> TypeGuard[Type[NativeForEmulated]]:
1529
+ return hasattr(typ, "adapt_emulated_to_native")
1530
+
1531
+
1532
+ class NativeForEmulated(TypeEngineMixin):
1533
+ """Indicates DB-native types supported by an :class:`.Emulated` type."""
1534
+
1535
+ @classmethod
1536
+ def adapt_native_to_emulated(
1537
+ cls,
1538
+ impl: Union[TypeEngine[Any], TypeEngineMixin],
1539
+ **kw: Any,
1540
+ ) -> TypeEngine[Any]:
1541
+ """Given an impl, adapt this type's class to the impl assuming
1542
+ "emulated".
1543
+
1544
+
1545
+ """
1546
+ impltype = impl.__class__
1547
+ return impl.adapt(impltype, **kw)
1548
+
1549
+ @classmethod
1550
+ def adapt_emulated_to_native(
1551
+ cls,
1552
+ impl: Union[TypeEngine[Any], TypeEngineMixin],
1553
+ **kw: Any,
1554
+ ) -> TypeEngine[Any]:
1555
+ """Given an impl, adapt this type's class to the impl assuming
1556
+ "native".
1557
+
1558
+ The impl will be an :class:`.Emulated` class but not a
1559
+ :class:`.NativeForEmulated`.
1560
+
1561
+ e.g.: postgresql.ENUM produces a type given an Enum instance.
1562
+
1563
+ """
1564
+
1565
+ # dmypy seems to crash on this
1566
+ return cls(**kw) # type: ignore
1567
+
1568
+ # dmypy seems to crash with this, on repeated runs with changes
1569
+ # if TYPE_CHECKING:
1570
+ # def __init__(self, **kw: Any):
1571
+ # ...
1572
+
1573
+
1574
+ class TypeDecorator(SchemaEventTarget, ExternalType, TypeEngine[_T]):
1575
+ '''Allows the creation of types which add additional functionality
1576
+ to an existing type.
1577
+
1578
+ This method is preferred to direct subclassing of SQLAlchemy's
1579
+ built-in types as it ensures that all required functionality of
1580
+ the underlying type is kept in place.
1581
+
1582
+ Typical usage::
1583
+
1584
+ import sqlalchemy.types as types
1585
+
1586
+
1587
+ class MyType(types.TypeDecorator):
1588
+ """Prefixes Unicode values with "PREFIX:" on the way in and
1589
+ strips it off on the way out.
1590
+ """
1591
+
1592
+ impl = types.Unicode
1593
+
1594
+ cache_ok = True
1595
+
1596
+ def process_bind_param(self, value, dialect):
1597
+ return "PREFIX:" + value
1598
+
1599
+ def process_result_value(self, value, dialect):
1600
+ return value[7:]
1601
+
1602
+ def copy(self, **kw):
1603
+ return MyType(self.impl.length)
1604
+
1605
+ The class-level ``impl`` attribute is required, and can reference any
1606
+ :class:`.TypeEngine` class. Alternatively, the :meth:`load_dialect_impl`
1607
+ method can be used to provide different type classes based on the dialect
1608
+ given; in this case, the ``impl`` variable can reference
1609
+ ``TypeEngine`` as a placeholder.
1610
+
1611
+ The :attr:`.TypeDecorator.cache_ok` class-level flag indicates if this
1612
+ custom :class:`.TypeDecorator` is safe to be used as part of a cache key.
1613
+ This flag defaults to ``None`` which will initially generate a warning
1614
+ when the SQL compiler attempts to generate a cache key for a statement
1615
+ that uses this type. If the :class:`.TypeDecorator` is not guaranteed
1616
+ to produce the same bind/result behavior and SQL generation
1617
+ every time, this flag should be set to ``False``; otherwise if the
1618
+ class produces the same behavior each time, it may be set to ``True``.
1619
+ See :attr:`.TypeDecorator.cache_ok` for further notes on how this works.
1620
+
1621
+ Types that receive a Python type that isn't similar to the ultimate type
1622
+ used may want to define the :meth:`TypeDecorator.coerce_compared_value`
1623
+ method. This is used to give the expression system a hint when coercing
1624
+ Python objects into bind parameters within expressions. Consider this
1625
+ expression::
1626
+
1627
+ mytable.c.somecol + datetime.date(2009, 5, 15)
1628
+
1629
+ Above, if "somecol" is an ``Integer`` variant, it makes sense that
1630
+ we're doing date arithmetic, where above is usually interpreted
1631
+ by databases as adding a number of days to the given date.
1632
+ The expression system does the right thing by not attempting to
1633
+ coerce the "date()" value into an integer-oriented bind parameter.
1634
+
1635
+ However, in the case of ``TypeDecorator``, we are usually changing an
1636
+ incoming Python type to something new - ``TypeDecorator`` by default will
1637
+ "coerce" the non-typed side to be the same type as itself. Such as below,
1638
+ we define an "epoch" type that stores a date value as an integer::
1639
+
1640
+ class MyEpochType(types.TypeDecorator):
1641
+ impl = types.Integer
1642
+
1643
+ cache_ok = True
1644
+
1645
+ epoch = datetime.date(1970, 1, 1)
1646
+
1647
+ def process_bind_param(self, value, dialect):
1648
+ return (value - self.epoch).days
1649
+
1650
+ def process_result_value(self, value, dialect):
1651
+ return self.epoch + timedelta(days=value)
1652
+
1653
+ Our expression of ``somecol + date`` with the above type will coerce the
1654
+ "date" on the right side to also be treated as ``MyEpochType``.
1655
+
1656
+ This behavior can be overridden via the
1657
+ :meth:`~TypeDecorator.coerce_compared_value` method, which returns a type
1658
+ that should be used for the value of the expression. Below we set it such
1659
+ that an integer value will be treated as an ``Integer``, and any other
1660
+ value is assumed to be a date and will be treated as a ``MyEpochType``::
1661
+
1662
+ def coerce_compared_value(self, op, value):
1663
+ if isinstance(value, int):
1664
+ return Integer()
1665
+ else:
1666
+ return self
1667
+
1668
+ .. warning::
1669
+
1670
+ Note that the **behavior of coerce_compared_value is not inherited
1671
+ by default from that of the base type**.
1672
+ If the :class:`.TypeDecorator` is augmenting a
1673
+ type that requires special logic for certain types of operators,
1674
+ this method **must** be overridden. A key example is when decorating
1675
+ the :class:`_postgresql.JSON` and :class:`_postgresql.JSONB` types;
1676
+ the default rules of :meth:`.TypeEngine.coerce_compared_value` should
1677
+ be used in order to deal with operators like index operations::
1678
+
1679
+ from sqlalchemy import JSON
1680
+ from sqlalchemy import TypeDecorator
1681
+
1682
+
1683
+ class MyJsonType(TypeDecorator):
1684
+ impl = JSON
1685
+
1686
+ cache_ok = True
1687
+
1688
+ def coerce_compared_value(self, op, value):
1689
+ return self.impl.coerce_compared_value(op, value)
1690
+
1691
+ Without the above step, index operations such as ``mycol['foo']``
1692
+ will cause the index value ``'foo'`` to be JSON encoded.
1693
+
1694
+ Similarly, when working with the :class:`.ARRAY` datatype, the
1695
+ type coercion for index operations (e.g. ``mycol[5]``) is also
1696
+ handled by :meth:`.TypeDecorator.coerce_compared_value`, where
1697
+ again a simple override is sufficient unless special rules are needed
1698
+ for particular operators::
1699
+
1700
+ from sqlalchemy import ARRAY
1701
+ from sqlalchemy import TypeDecorator
1702
+
1703
+
1704
+ class MyArrayType(TypeDecorator):
1705
+ impl = ARRAY
1706
+
1707
+ cache_ok = True
1708
+
1709
+ def coerce_compared_value(self, op, value):
1710
+ return self.impl.coerce_compared_value(op, value)
1711
+
1712
+ '''
1713
+
1714
+ __visit_name__ = "type_decorator"
1715
+
1716
+ _is_type_decorator = True
1717
+
1718
+ # this is that pattern I've used in a few places (Dialect.dbapi,
1719
+ # Dialect.type_compiler) where the "cls.attr" is a class to make something,
1720
+ # and "instance.attr" is an instance of that thing. It's such a nifty,
1721
+ # great pattern, and there is zero chance Python typing tools will ever be
1722
+ # OK with it. For TypeDecorator.impl, this is a highly public attribute so
1723
+ # we really can't change its behavior without a major deprecation routine.
1724
+ impl: Union[TypeEngine[Any], Type[TypeEngine[Any]]]
1725
+
1726
+ # we are changing its behavior *slightly*, which is that we now consume
1727
+ # the instance level version from this memoized property instead, so you
1728
+ # can't reassign "impl" on an existing TypeDecorator that's already been
1729
+ # used (something one shouldn't do anyway) without also updating
1730
+ # impl_instance.
1731
+ @util.memoized_property
1732
+ def impl_instance(self) -> TypeEngine[Any]:
1733
+ return self.impl # type: ignore
1734
+
1735
+ def __init__(self, *args: Any, **kwargs: Any):
1736
+ """Construct a :class:`.TypeDecorator`.
1737
+
1738
+ Arguments sent here are passed to the constructor
1739
+ of the class assigned to the ``impl`` class level attribute,
1740
+ assuming the ``impl`` is a callable, and the resulting
1741
+ object is assigned to the ``self.impl`` instance attribute
1742
+ (thus overriding the class attribute of the same name).
1743
+
1744
+ If the class level ``impl`` is not a callable (the unusual case),
1745
+ it will be assigned to the same instance attribute 'as-is',
1746
+ ignoring those arguments passed to the constructor.
1747
+
1748
+ Subclasses can override this to customize the generation
1749
+ of ``self.impl`` entirely.
1750
+
1751
+ """
1752
+
1753
+ if not hasattr(self.__class__, "impl"):
1754
+ raise AssertionError(
1755
+ "TypeDecorator implementations "
1756
+ "require a class-level variable "
1757
+ "'impl' which refers to the class of "
1758
+ "type being decorated"
1759
+ )
1760
+
1761
+ self.impl = to_instance(self.__class__.impl, *args, **kwargs)
1762
+
1763
+ coerce_to_is_types: Sequence[Type[Any]] = (type(None),)
1764
+ """Specify those Python types which should be coerced at the expression
1765
+ level to "IS <constant>" when compared using ``==`` (and same for
1766
+ ``IS NOT`` in conjunction with ``!=``).
1767
+
1768
+ For most SQLAlchemy types, this includes ``NoneType``, as well as
1769
+ ``bool``.
1770
+
1771
+ :class:`.TypeDecorator` modifies this list to only include ``NoneType``,
1772
+ as typedecorator implementations that deal with boolean types are common.
1773
+
1774
+ Custom :class:`.TypeDecorator` classes can override this attribute to
1775
+ return an empty tuple, in which case no values will be coerced to
1776
+ constants.
1777
+
1778
+ """
1779
+
1780
+ if not TYPE_CHECKING:
1781
+
1782
+ @property
1783
+ def operator_classes(self) -> OperatorClass:
1784
+ return self.impl_instance.operator_classes
1785
+
1786
+ class Comparator(TypeEngine.Comparator[_CT]):
1787
+ """A :class:`.TypeEngine.Comparator` that is specific to
1788
+ :class:`.TypeDecorator`.
1789
+
1790
+ User-defined :class:`.TypeDecorator` classes should not typically
1791
+ need to modify this.
1792
+
1793
+
1794
+ """
1795
+
1796
+ __slots__ = ()
1797
+
1798
+ def operate(
1799
+ self, op: OperatorType, *other: Any, **kwargs: Any
1800
+ ) -> ColumnElement[_CT]:
1801
+ if TYPE_CHECKING:
1802
+ assert isinstance(self.expr.type, TypeDecorator)
1803
+ kwargs["_python_is_types"] = self.expr.type.coerce_to_is_types
1804
+ return super().operate(op, *other, **kwargs)
1805
+
1806
+ def reverse_operate(
1807
+ self, op: OperatorType, other: Any, **kwargs: Any
1808
+ ) -> ColumnElement[_CT]:
1809
+ if TYPE_CHECKING:
1810
+ assert isinstance(self.expr.type, TypeDecorator)
1811
+ kwargs["_python_is_types"] = self.expr.type.coerce_to_is_types
1812
+ return super().reverse_operate(op, other, **kwargs)
1813
+
1814
+ @staticmethod
1815
+ def _reduce_td_comparator(
1816
+ impl: TypeEngine[Any], expr: ColumnElement[_T]
1817
+ ) -> Any:
1818
+ return TypeDecorator._create_td_comparator_type(impl)(expr)
1819
+
1820
+ @staticmethod
1821
+ def _create_td_comparator_type(
1822
+ impl: TypeEngine[Any],
1823
+ ) -> _ComparatorFactory[Any]:
1824
+
1825
+ def __reduce__(self: TypeDecorator.Comparator[Any]) -> Any:
1826
+ return (TypeDecorator._reduce_td_comparator, (impl, self.expr))
1827
+
1828
+ return type(
1829
+ "TDComparator",
1830
+ (TypeDecorator.Comparator, impl.comparator_factory), # type: ignore # noqa: E501
1831
+ {"__reduce__": __reduce__},
1832
+ )
1833
+
1834
+ @property
1835
+ def comparator_factory( # type: ignore # mypy properties bug
1836
+ self,
1837
+ ) -> _ComparatorFactory[Any]:
1838
+ if TypeDecorator.Comparator in self.impl.comparator_factory.__mro__: # type: ignore # noqa: E501
1839
+ return self.impl_instance.comparator_factory
1840
+ else:
1841
+ # reconcile the Comparator class on the impl with that
1842
+ # of TypeDecorator.
1843
+ # the use of multiple staticmethods is to support repeated
1844
+ # pickling of the Comparator itself
1845
+ return TypeDecorator._create_td_comparator_type(self.impl_instance)
1846
+
1847
+ def _copy_with_check(self) -> Self:
1848
+ tt = self.copy()
1849
+ if not isinstance(tt, self.__class__):
1850
+ raise AssertionError(
1851
+ "Type object %s does not properly "
1852
+ "implement the copy() method, it must "
1853
+ "return an object of type %s" % (self, self.__class__)
1854
+ )
1855
+ return tt
1856
+
1857
+ def _gen_dialect_impl(self, dialect: Dialect) -> TypeEngine[_T]:
1858
+ if dialect.name in self._variant_mapping:
1859
+ adapted = dialect.type_descriptor(
1860
+ self._variant_mapping[dialect.name]
1861
+ )
1862
+ else:
1863
+ adapted = dialect.type_descriptor(self)
1864
+ if adapted is not self:
1865
+ return adapted
1866
+
1867
+ # otherwise adapt the impl type, link
1868
+ # to a copy of this TypeDecorator and return
1869
+ # that.
1870
+ typedesc = self.load_dialect_impl(dialect).dialect_impl(dialect)
1871
+ tt = self._copy_with_check()
1872
+ tt.impl = tt.impl_instance = typedesc
1873
+ return tt
1874
+
1875
+ def _with_collation(self, collation: str) -> Self:
1876
+ tt = self._copy_with_check()
1877
+ tt.impl = tt.impl_instance = self.impl_instance._with_collation(
1878
+ collation
1879
+ )
1880
+ return tt
1881
+
1882
+ @util.ro_non_memoized_property
1883
+ def _type_affinity(self) -> Optional[Type[TypeEngine[Any]]]:
1884
+ return self.impl_instance._type_affinity
1885
+
1886
+ def _set_parent(
1887
+ self, parent: SchemaEventTarget, outer: bool = False, **kw: Any
1888
+ ) -> None:
1889
+ """Support SchemaEventTarget"""
1890
+
1891
+ super()._set_parent(parent)
1892
+
1893
+ if not outer and isinstance(self.impl_instance, SchemaEventTarget):
1894
+ self.impl_instance._set_parent(parent, outer=False, **kw)
1895
+
1896
+ def _set_parent_with_dispatch(
1897
+ self, parent: SchemaEventTarget, **kw: Any
1898
+ ) -> None:
1899
+ """Support SchemaEventTarget"""
1900
+
1901
+ super()._set_parent_with_dispatch(parent, outer=True, **kw)
1902
+
1903
+ if isinstance(self.impl_instance, SchemaEventTarget):
1904
+ self.impl_instance._set_parent_with_dispatch(parent)
1905
+
1906
+ def type_engine(self, dialect: Dialect) -> TypeEngine[Any]:
1907
+ """Return a dialect-specific :class:`.TypeEngine` instance
1908
+ for this :class:`.TypeDecorator`.
1909
+
1910
+ In most cases this returns a dialect-adapted form of
1911
+ the :class:`.TypeEngine` type represented by ``self.impl``.
1912
+ Makes usage of :meth:`dialect_impl`.
1913
+ Behavior can be customized here by overriding
1914
+ :meth:`load_dialect_impl`.
1915
+
1916
+ """
1917
+ adapted = dialect.type_descriptor(self)
1918
+ if not isinstance(adapted, type(self)):
1919
+ return adapted
1920
+ else:
1921
+ return self.load_dialect_impl(dialect)
1922
+
1923
+ def load_dialect_impl(self, dialect: Dialect) -> TypeEngine[Any]:
1924
+ """Return a :class:`.TypeEngine` object corresponding to a dialect.
1925
+
1926
+ This is an end-user override hook that can be used to provide
1927
+ differing types depending on the given dialect. It is used
1928
+ by the :class:`.TypeDecorator` implementation of :meth:`type_engine`
1929
+ to help determine what type should ultimately be returned
1930
+ for a given :class:`.TypeDecorator`.
1931
+
1932
+ By default returns ``self.impl``.
1933
+
1934
+ """
1935
+ return self.impl_instance
1936
+
1937
+ def _unwrapped_dialect_impl(self, dialect: Dialect) -> TypeEngine[Any]:
1938
+ """Return the 'unwrapped' dialect impl for this type.
1939
+
1940
+ This is used by the :meth:`.DefaultDialect.set_input_sizes`
1941
+ method.
1942
+
1943
+ """
1944
+ # some dialects have a lookup for a TypeDecorator subclass directly.
1945
+ # postgresql.INTERVAL being the main example
1946
+ typ = self.dialect_impl(dialect)
1947
+
1948
+ # if we are still a type decorator, load the per-dialect switch
1949
+ # (such as what Variant uses), then get the dialect impl for that.
1950
+ if isinstance(typ, self.__class__):
1951
+ return typ.load_dialect_impl(dialect).dialect_impl(dialect)
1952
+ else:
1953
+ return typ
1954
+
1955
+ def __getattr__(self, key: str) -> Any:
1956
+ """Proxy all other undefined accessors to the underlying
1957
+ implementation."""
1958
+ return getattr(self.impl_instance, key)
1959
+
1960
+ def process_literal_param(
1961
+ self, value: Optional[_T], dialect: Dialect
1962
+ ) -> str:
1963
+ """Receive a literal parameter value to be rendered inline within
1964
+ a statement.
1965
+
1966
+ .. note::
1967
+
1968
+ This method is called during the **SQL compilation** phase of a
1969
+ statement, when rendering a SQL string. Unlike other SQL
1970
+ compilation methods, it is passed a specific Python value to be
1971
+ rendered as a string. However it should not be confused with the
1972
+ :meth:`_types.TypeDecorator.process_bind_param` method, which is
1973
+ the more typical method that processes the actual value passed to a
1974
+ particular parameter at statement execution time.
1975
+
1976
+ Custom subclasses of :class:`_types.TypeDecorator` should override
1977
+ this method to provide custom behaviors for incoming data values
1978
+ that are in the special case of being rendered as literals.
1979
+
1980
+ The returned string will be rendered into the output string.
1981
+
1982
+ """
1983
+ raise NotImplementedError()
1984
+
1985
+ def process_bind_param(self, value: Optional[_T], dialect: Dialect) -> Any:
1986
+ """Receive a bound parameter value to be converted.
1987
+
1988
+ Custom subclasses of :class:`_types.TypeDecorator` should override
1989
+ this method to provide custom behaviors for incoming data values.
1990
+ This method is called at **statement execution time** and is passed
1991
+ the literal Python data value which is to be associated with a bound
1992
+ parameter in the statement.
1993
+
1994
+ The operation could be anything desired to perform custom
1995
+ behavior, such as transforming or serializing data.
1996
+ This could also be used as a hook for validating logic.
1997
+
1998
+ :param value: Data to operate upon, of any type expected by
1999
+ this method in the subclass. Can be ``None``.
2000
+ :param dialect: the :class:`.Dialect` in use.
2001
+
2002
+ .. seealso::
2003
+
2004
+ :ref:`types_typedecorator`
2005
+
2006
+ :meth:`_types.TypeDecorator.process_result_value`
2007
+
2008
+ """
2009
+
2010
+ raise NotImplementedError()
2011
+
2012
+ def process_result_value(
2013
+ self, value: Optional[Any], dialect: Dialect
2014
+ ) -> Optional[_T]:
2015
+ """Receive a result-row column value to be converted.
2016
+
2017
+ Custom subclasses of :class:`_types.TypeDecorator` should override
2018
+ this method to provide custom behaviors for data values
2019
+ being received in result rows coming from the database.
2020
+ This method is called at **result fetching time** and is passed
2021
+ the literal Python data value that's extracted from a database result
2022
+ row.
2023
+
2024
+ The operation could be anything desired to perform custom
2025
+ behavior, such as transforming or deserializing data.
2026
+
2027
+ :param value: Data to operate upon, of any type expected by
2028
+ this method in the subclass. Can be ``None``.
2029
+ :param dialect: the :class:`.Dialect` in use.
2030
+
2031
+ .. seealso::
2032
+
2033
+ :ref:`types_typedecorator`
2034
+
2035
+ :meth:`_types.TypeDecorator.process_bind_param`
2036
+
2037
+
2038
+ """
2039
+
2040
+ raise NotImplementedError()
2041
+
2042
+ @util.memoized_property
2043
+ def _has_bind_processor(self) -> bool:
2044
+ """memoized boolean, check if process_bind_param is implemented.
2045
+
2046
+ Allows the base process_bind_param to raise
2047
+ NotImplementedError without needing to test an expensive
2048
+ exception throw.
2049
+
2050
+ """
2051
+
2052
+ return util.method_is_overridden(
2053
+ self, TypeDecorator.process_bind_param
2054
+ )
2055
+
2056
+ @util.memoized_property
2057
+ def _has_literal_processor(self) -> bool:
2058
+ """memoized boolean, check if process_literal_param is implemented."""
2059
+
2060
+ return util.method_is_overridden(
2061
+ self, TypeDecorator.process_literal_param
2062
+ )
2063
+
2064
+ def literal_processor(
2065
+ self, dialect: Dialect
2066
+ ) -> Optional[_LiteralProcessorType[_T]]:
2067
+ """Provide a literal processing function for the given
2068
+ :class:`.Dialect`.
2069
+
2070
+ This is the method that fulfills the :class:`.TypeEngine`
2071
+ contract for literal value conversion which normally occurs via
2072
+ the :meth:`_types.TypeEngine.literal_processor` method.
2073
+
2074
+ .. note::
2075
+
2076
+ User-defined subclasses of :class:`_types.TypeDecorator` should
2077
+ **not** implement this method, and should instead implement
2078
+ :meth:`_types.TypeDecorator.process_literal_param` so that the
2079
+ "inner" processing provided by the implementing type is maintained.
2080
+
2081
+ """
2082
+
2083
+ if self._has_literal_processor:
2084
+ process_literal_param = self.process_literal_param
2085
+ process_bind_param = None
2086
+ elif self._has_bind_processor:
2087
+ # use the bind processor if dont have a literal processor,
2088
+ # but we have an impl literal processor
2089
+ process_literal_param = None
2090
+ process_bind_param = self.process_bind_param
2091
+ else:
2092
+ process_literal_param = None
2093
+ process_bind_param = None
2094
+
2095
+ if process_literal_param is not None:
2096
+ impl_processor = self.impl_instance.literal_processor(dialect)
2097
+ if impl_processor:
2098
+ fixed_impl_processor = impl_processor
2099
+ fixed_process_literal_param = process_literal_param
2100
+
2101
+ def process(value: Any) -> str:
2102
+ return fixed_impl_processor(
2103
+ fixed_process_literal_param(value, dialect)
2104
+ )
2105
+
2106
+ else:
2107
+ fixed_process_literal_param = process_literal_param
2108
+
2109
+ def process(value: Any) -> str:
2110
+ return fixed_process_literal_param(value, dialect)
2111
+
2112
+ return process
2113
+
2114
+ elif process_bind_param is not None:
2115
+ impl_processor = self.impl_instance.literal_processor(dialect)
2116
+ if not impl_processor:
2117
+ return None
2118
+ else:
2119
+ fixed_impl_processor = impl_processor
2120
+ fixed_process_bind_param = process_bind_param
2121
+
2122
+ def process(value: Any) -> str:
2123
+ return fixed_impl_processor(
2124
+ fixed_process_bind_param(value, dialect)
2125
+ )
2126
+
2127
+ return process
2128
+ else:
2129
+ return self.impl_instance.literal_processor(dialect)
2130
+
2131
+ def bind_processor(
2132
+ self, dialect: Dialect
2133
+ ) -> Optional[_BindProcessorType[_T]]:
2134
+ """Provide a bound value processing function for the
2135
+ given :class:`.Dialect`.
2136
+
2137
+ This is the method that fulfills the :class:`.TypeEngine`
2138
+ contract for bound value conversion which normally occurs via
2139
+ the :meth:`_types.TypeEngine.bind_processor` method.
2140
+
2141
+ .. note::
2142
+
2143
+ User-defined subclasses of :class:`_types.TypeDecorator` should
2144
+ **not** implement this method, and should instead implement
2145
+ :meth:`_types.TypeDecorator.process_bind_param` so that the "inner"
2146
+ processing provided by the implementing type is maintained.
2147
+
2148
+ :param dialect: Dialect instance in use.
2149
+
2150
+ """
2151
+ if self._has_bind_processor:
2152
+ process_param = self.process_bind_param
2153
+ impl_processor = self.impl_instance.bind_processor(dialect)
2154
+ if impl_processor:
2155
+ fixed_impl_processor = impl_processor
2156
+ fixed_process_param = process_param
2157
+
2158
+ def process(value: Optional[_T]) -> Any:
2159
+ return fixed_impl_processor(
2160
+ fixed_process_param(value, dialect)
2161
+ )
2162
+
2163
+ else:
2164
+ fixed_process_param = process_param
2165
+
2166
+ def process(value: Optional[_T]) -> Any:
2167
+ return fixed_process_param(value, dialect)
2168
+
2169
+ return process
2170
+ else:
2171
+ return self.impl_instance.bind_processor(dialect)
2172
+
2173
+ @util.memoized_property
2174
+ def _has_result_processor(self) -> bool:
2175
+ """memoized boolean, check if process_result_value is implemented.
2176
+
2177
+ Allows the base process_result_value to raise
2178
+ NotImplementedError without needing to test an expensive
2179
+ exception throw.
2180
+
2181
+ """
2182
+
2183
+ return util.method_is_overridden(
2184
+ self, TypeDecorator.process_result_value
2185
+ )
2186
+
2187
+ def result_processor(
2188
+ self, dialect: Dialect, coltype: Any
2189
+ ) -> Optional[_ResultProcessorType[_T]]:
2190
+ """Provide a result value processing function for the given
2191
+ :class:`.Dialect`.
2192
+
2193
+ This is the method that fulfills the :class:`.TypeEngine`
2194
+ contract for bound value conversion which normally occurs via
2195
+ the :meth:`_types.TypeEngine.result_processor` method.
2196
+
2197
+ .. note::
2198
+
2199
+ User-defined subclasses of :class:`_types.TypeDecorator` should
2200
+ **not** implement this method, and should instead implement
2201
+ :meth:`_types.TypeDecorator.process_result_value` so that the
2202
+ "inner" processing provided by the implementing type is maintained.
2203
+
2204
+ :param dialect: Dialect instance in use.
2205
+ :param coltype: A SQLAlchemy data type
2206
+
2207
+ """
2208
+ if self._has_result_processor:
2209
+ process_value = self.process_result_value
2210
+ impl_processor = self.impl_instance.result_processor(
2211
+ dialect, coltype
2212
+ )
2213
+ if impl_processor:
2214
+ fixed_process_value = process_value
2215
+ fixed_impl_processor = impl_processor
2216
+
2217
+ def process(value: Any) -> Optional[_T]:
2218
+ return fixed_process_value(
2219
+ fixed_impl_processor(value), dialect
2220
+ )
2221
+
2222
+ else:
2223
+ fixed_process_value = process_value
2224
+
2225
+ def process(value: Any) -> Optional[_T]:
2226
+ return fixed_process_value(value, dialect)
2227
+
2228
+ return process
2229
+ else:
2230
+ return self.impl_instance.result_processor(dialect, coltype)
2231
+
2232
+ @util.memoized_property
2233
+ def _has_bind_expression(self) -> bool:
2234
+ return (
2235
+ util.method_is_overridden(self, TypeDecorator.bind_expression)
2236
+ or self.impl_instance._has_bind_expression
2237
+ )
2238
+
2239
+ def bind_expression(
2240
+ self, bindparam: BindParameter[_T]
2241
+ ) -> Optional[ColumnElement[_T]]:
2242
+ """Given a bind value (i.e. a :class:`.BindParameter` instance),
2243
+ return a SQL expression which will typically wrap the given parameter.
2244
+
2245
+ .. note::
2246
+
2247
+ This method is called during the **SQL compilation** phase of a
2248
+ statement, when rendering a SQL string. It is **not** necessarily
2249
+ called against specific values, and should not be confused with the
2250
+ :meth:`_types.TypeDecorator.process_bind_param` method, which is
2251
+ the more typical method that processes the actual value passed to a
2252
+ particular parameter at statement execution time.
2253
+
2254
+ Subclasses of :class:`_types.TypeDecorator` can override this method
2255
+ to provide custom bind expression behavior for the type. This
2256
+ implementation will **replace** that of the underlying implementation
2257
+ type.
2258
+
2259
+ """
2260
+ return self.impl_instance.bind_expression(bindparam)
2261
+
2262
+ @util.memoized_property
2263
+ def _has_column_expression(self) -> bool:
2264
+ """memoized boolean, check if column_expression is implemented.
2265
+
2266
+ Allows the method to be skipped for the vast majority of expression
2267
+ types that don't use this feature.
2268
+
2269
+ """
2270
+
2271
+ return (
2272
+ util.method_is_overridden(self, TypeDecorator.column_expression)
2273
+ or self.impl_instance._has_column_expression
2274
+ )
2275
+
2276
+ def column_expression(
2277
+ self, column: ColumnElement[_T]
2278
+ ) -> Optional[ColumnElement[_T]]:
2279
+ """Given a SELECT column expression, return a wrapping SQL expression.
2280
+
2281
+ .. note::
2282
+
2283
+ This method is called during the **SQL compilation** phase of a
2284
+ statement, when rendering a SQL string. It is **not** called
2285
+ against specific values, and should not be confused with the
2286
+ :meth:`_types.TypeDecorator.process_result_value` method, which is
2287
+ the more typical method that processes the actual value returned
2288
+ in a result row subsequent to statement execution time.
2289
+
2290
+ Subclasses of :class:`_types.TypeDecorator` can override this method
2291
+ to provide custom column expression behavior for the type. This
2292
+ implementation will **replace** that of the underlying implementation
2293
+ type.
2294
+
2295
+ See the description of :meth:`_types.TypeEngine.column_expression`
2296
+ for a complete description of the method's use.
2297
+
2298
+ """
2299
+
2300
+ return self.impl_instance.column_expression(column)
2301
+
2302
+ def coerce_compared_value(
2303
+ self, op: Optional[OperatorType], value: Any
2304
+ ) -> Any:
2305
+ """Suggest a type for a 'coerced' Python value in an expression.
2306
+
2307
+ By default, returns self. This method is called by
2308
+ the expression system when an object using this type is
2309
+ on the left or right side of an expression against a plain Python
2310
+ object which does not yet have a SQLAlchemy type assigned::
2311
+
2312
+ expr = table.c.somecolumn + 35
2313
+
2314
+ Where above, if ``somecolumn`` uses this type, this method will
2315
+ be called with the value ``operator.add``
2316
+ and ``35``. The return value is whatever SQLAlchemy type should
2317
+ be used for ``35`` for this particular operation.
2318
+
2319
+ """
2320
+ return self
2321
+
2322
+ def copy(self, **kw: Any) -> Self:
2323
+ """Produce a copy of this :class:`.TypeDecorator` instance.
2324
+
2325
+ This is a shallow copy and is provided to fulfill part of
2326
+ the :class:`.TypeEngine` contract. It usually does not
2327
+ need to be overridden unless the user-defined :class:`.TypeDecorator`
2328
+ has local state that should be deep-copied.
2329
+
2330
+ """
2331
+
2332
+ instance = self.__class__.__new__(self.__class__)
2333
+ instance.__dict__.update(self.__dict__)
2334
+ return instance
2335
+
2336
+ def get_dbapi_type(self, dbapi: DBAPIModule) -> Optional[Any]:
2337
+ """Return the DBAPI type object represented by this
2338
+ :class:`.TypeDecorator`.
2339
+
2340
+ By default this calls upon :meth:`.TypeEngine.get_dbapi_type` of the
2341
+ underlying "impl".
2342
+ """
2343
+ return self.impl_instance.get_dbapi_type(dbapi)
2344
+
2345
+ def compare_values(self, x: Any, y: Any) -> bool:
2346
+ """Given two values, compare them for equality.
2347
+
2348
+ By default this calls upon :meth:`.TypeEngine.compare_values`
2349
+ of the underlying "impl", which in turn usually
2350
+ uses the Python equals operator ``==``.
2351
+
2352
+ This function is used by the ORM to compare
2353
+ an original-loaded value with an intercepted
2354
+ "changed" value, to determine if a net change
2355
+ has occurred.
2356
+
2357
+ """
2358
+ return self.impl_instance.compare_values(x, y)
2359
+
2360
+ # mypy property bug
2361
+ @property
2362
+ def sort_key_function(self) -> Optional[Callable[[Any], Any]]: # type: ignore # noqa: E501
2363
+ return self.impl_instance.sort_key_function
2364
+
2365
+ def __repr__(self) -> str:
2366
+ return util.generic_repr(self, to_inspect=self.impl_instance)
2367
+
2368
+
2369
+ class Variant(TypeDecorator[_T]):
2370
+ """deprecated. symbol is present for backwards-compatibility with
2371
+ workaround recipes, however this actual type should not be used.
2372
+
2373
+ """
2374
+
2375
+ def __init__(self, *arg: Any, **kw: Any):
2376
+ raise NotImplementedError(
2377
+ "Variant is no longer used in SQLAlchemy; this is a "
2378
+ "placeholder symbol for backwards compatibility."
2379
+ )
2380
+
2381
+
2382
+ @overload
2383
+ def to_instance(
2384
+ typeobj: Union[Type[_TE], _TE], *arg: Any, **kw: Any
2385
+ ) -> _TE: ...
2386
+
2387
+
2388
+ @overload
2389
+ def to_instance(typeobj: None, *arg: Any, **kw: Any) -> TypeEngine[None]: ...
2390
+
2391
+
2392
+ def to_instance(
2393
+ typeobj: Union[Type[_TE], _TE, None], *arg: Any, **kw: Any
2394
+ ) -> Union[_TE, TypeEngine[None]]:
2395
+ if typeobj is None:
2396
+ return NULLTYPE
2397
+
2398
+ if callable(typeobj):
2399
+ return typeobj(*arg, **kw)
2400
+ else:
2401
+ return typeobj
2402
+
2403
+
2404
+ def adapt_type(
2405
+ typeobj: _TypeEngineArgument[Any],
2406
+ colspecs: Mapping[Type[Any], Type[TypeEngine[Any]]],
2407
+ ) -> TypeEngine[Any]:
2408
+ typeobj = to_instance(typeobj)
2409
+ for t in typeobj.__class__.__mro__[0:-1]:
2410
+ try:
2411
+ impltype = colspecs[t]
2412
+ break
2413
+ except KeyError:
2414
+ pass
2415
+ else:
2416
+ # couldn't adapt - so just return the type itself
2417
+ # (it may be a user-defined type)
2418
+ return typeobj
2419
+ # if we adapted the given generic type to a database-specific type,
2420
+ # but it turns out the originally given "generic" type
2421
+ # is actually a subclass of our resulting type, then we were already
2422
+ # given a more specific type than that required; so use that.
2423
+ if issubclass(typeobj.__class__, impltype):
2424
+ return typeobj
2425
+ return typeobj.adapt(impltype)