SQLAlchemy 2.1.0rc1__cp315-cp315-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (276) hide show
  1. sqlalchemy/__init__.py +299 -0
  2. sqlalchemy/connectors/__init__.py +18 -0
  3. sqlalchemy/connectors/aioodbc.py +171 -0
  4. sqlalchemy/connectors/asyncio.py +476 -0
  5. sqlalchemy/connectors/pyodbc.py +248 -0
  6. sqlalchemy/dialects/__init__.py +62 -0
  7. sqlalchemy/dialects/_typing.py +29 -0
  8. sqlalchemy/dialects/mssql/__init__.py +88 -0
  9. sqlalchemy/dialects/mssql/aioodbc.py +63 -0
  10. sqlalchemy/dialects/mssql/base.py +4833 -0
  11. sqlalchemy/dialects/mssql/information_schema.py +345 -0
  12. sqlalchemy/dialects/mssql/json.py +140 -0
  13. sqlalchemy/dialects/mssql/mssqlpython.py +242 -0
  14. sqlalchemy/dialects/mssql/provision.py +196 -0
  15. sqlalchemy/dialects/mssql/pymssql.py +130 -0
  16. sqlalchemy/dialects/mssql/pyodbc.py +697 -0
  17. sqlalchemy/dialects/mysql/__init__.py +106 -0
  18. sqlalchemy/dialects/mysql/_mariadb_shim.py +312 -0
  19. sqlalchemy/dialects/mysql/aiomysql.py +260 -0
  20. sqlalchemy/dialects/mysql/asyncmy.py +241 -0
  21. sqlalchemy/dialects/mysql/base.py +3896 -0
  22. sqlalchemy/dialects/mysql/cymysql.py +107 -0
  23. sqlalchemy/dialects/mysql/dml.py +279 -0
  24. sqlalchemy/dialects/mysql/enumerated.py +277 -0
  25. sqlalchemy/dialects/mysql/expression.py +146 -0
  26. sqlalchemy/dialects/mysql/json.py +92 -0
  27. sqlalchemy/dialects/mysql/mariadb.py +67 -0
  28. sqlalchemy/dialects/mysql/mariadbconnector.py +314 -0
  29. sqlalchemy/dialects/mysql/mysqlconnector.py +291 -0
  30. sqlalchemy/dialects/mysql/mysqldb.py +318 -0
  31. sqlalchemy/dialects/mysql/provision.py +153 -0
  32. sqlalchemy/dialects/mysql/pymysql.py +188 -0
  33. sqlalchemy/dialects/mysql/pyodbc.py +157 -0
  34. sqlalchemy/dialects/mysql/reflection.py +724 -0
  35. sqlalchemy/dialects/mysql/reserved_words.py +570 -0
  36. sqlalchemy/dialects/mysql/types.py +845 -0
  37. sqlalchemy/dialects/oracle/__init__.py +85 -0
  38. sqlalchemy/dialects/oracle/base.py +3847 -0
  39. sqlalchemy/dialects/oracle/cx_oracle.py +1736 -0
  40. sqlalchemy/dialects/oracle/dictionary.py +507 -0
  41. sqlalchemy/dialects/oracle/json.py +157 -0
  42. sqlalchemy/dialects/oracle/oracledb.py +898 -0
  43. sqlalchemy/dialects/oracle/provision.py +288 -0
  44. sqlalchemy/dialects/oracle/types.py +367 -0
  45. sqlalchemy/dialects/oracle/vector.py +366 -0
  46. sqlalchemy/dialects/postgresql/__init__.py +170 -0
  47. sqlalchemy/dialects/postgresql/_psycopg_common.py +232 -0
  48. sqlalchemy/dialects/postgresql/array.py +534 -0
  49. sqlalchemy/dialects/postgresql/asyncpg.py +1318 -0
  50. sqlalchemy/dialects/postgresql/base.py +5935 -0
  51. sqlalchemy/dialects/postgresql/bitstring.py +327 -0
  52. sqlalchemy/dialects/postgresql/dml.py +360 -0
  53. sqlalchemy/dialects/postgresql/ext.py +599 -0
  54. sqlalchemy/dialects/postgresql/hstore.py +422 -0
  55. sqlalchemy/dialects/postgresql/json.py +411 -0
  56. sqlalchemy/dialects/postgresql/named_types.py +535 -0
  57. sqlalchemy/dialects/postgresql/operators.py +129 -0
  58. sqlalchemy/dialects/postgresql/pg8000.py +655 -0
  59. sqlalchemy/dialects/postgresql/pg_catalog.py +345 -0
  60. sqlalchemy/dialects/postgresql/provision.py +202 -0
  61. sqlalchemy/dialects/postgresql/psycopg.py +800 -0
  62. sqlalchemy/dialects/postgresql/psycopg2.py +860 -0
  63. sqlalchemy/dialects/postgresql/psycopg2cffi.py +62 -0
  64. sqlalchemy/dialects/postgresql/ranges.py +1002 -0
  65. sqlalchemy/dialects/postgresql/types.py +388 -0
  66. sqlalchemy/dialects/sqlite/__init__.py +59 -0
  67. sqlalchemy/dialects/sqlite/aiosqlite.py +375 -0
  68. sqlalchemy/dialects/sqlite/base.py +3103 -0
  69. sqlalchemy/dialects/sqlite/dml.py +314 -0
  70. sqlalchemy/dialects/sqlite/json.py +134 -0
  71. sqlalchemy/dialects/sqlite/provision.py +237 -0
  72. sqlalchemy/dialects/sqlite/pysqlcipher.py +166 -0
  73. sqlalchemy/dialects/sqlite/pysqlite.py +959 -0
  74. sqlalchemy/dialects/type_migration_guidelines.txt +145 -0
  75. sqlalchemy/engine/__init__.py +62 -0
  76. sqlalchemy/engine/_processors_cy.cp315-win_amd64.pyd +0 -0
  77. sqlalchemy/engine/_processors_cy.py +92 -0
  78. sqlalchemy/engine/_result_cy.cp315-win_amd64.pyd +0 -0
  79. sqlalchemy/engine/_result_cy.py +711 -0
  80. sqlalchemy/engine/_row_cy.cp315-win_amd64.pyd +0 -0
  81. sqlalchemy/engine/_row_cy.py +232 -0
  82. sqlalchemy/engine/_util_cy.cp315-win_amd64.pyd +0 -0
  83. sqlalchemy/engine/_util_cy.py +136 -0
  84. sqlalchemy/engine/base.py +3357 -0
  85. sqlalchemy/engine/characteristics.py +155 -0
  86. sqlalchemy/engine/create.py +877 -0
  87. sqlalchemy/engine/cursor.py +2425 -0
  88. sqlalchemy/engine/default.py +2627 -0
  89. sqlalchemy/engine/events.py +965 -0
  90. sqlalchemy/engine/interfaces.py +3636 -0
  91. sqlalchemy/engine/mock.py +133 -0
  92. sqlalchemy/engine/processors.py +83 -0
  93. sqlalchemy/engine/reflection.py +2141 -0
  94. sqlalchemy/engine/result.py +2012 -0
  95. sqlalchemy/engine/row.py +397 -0
  96. sqlalchemy/engine/strategies.py +16 -0
  97. sqlalchemy/engine/url.py +922 -0
  98. sqlalchemy/engine/util.py +164 -0
  99. sqlalchemy/event/__init__.py +26 -0
  100. sqlalchemy/event/api.py +220 -0
  101. sqlalchemy/event/attr.py +675 -0
  102. sqlalchemy/event/base.py +473 -0
  103. sqlalchemy/event/legacy.py +259 -0
  104. sqlalchemy/event/registry.py +391 -0
  105. sqlalchemy/events.py +17 -0
  106. sqlalchemy/exc.py +939 -0
  107. sqlalchemy/ext/__init__.py +10 -0
  108. sqlalchemy/ext/associationproxy.py +2073 -0
  109. sqlalchemy/ext/asyncio/__init__.py +29 -0
  110. sqlalchemy/ext/asyncio/base.py +281 -0
  111. sqlalchemy/ext/asyncio/engine.py +1487 -0
  112. sqlalchemy/ext/asyncio/exc.py +21 -0
  113. sqlalchemy/ext/asyncio/result.py +994 -0
  114. sqlalchemy/ext/asyncio/scoping.py +1679 -0
  115. sqlalchemy/ext/asyncio/session.py +2006 -0
  116. sqlalchemy/ext/automap.py +1702 -0
  117. sqlalchemy/ext/baked.py +558 -0
  118. sqlalchemy/ext/compiler.py +601 -0
  119. sqlalchemy/ext/declarative/__init__.py +65 -0
  120. sqlalchemy/ext/declarative/extensions.py +561 -0
  121. sqlalchemy/ext/horizontal_shard.py +481 -0
  122. sqlalchemy/ext/hybrid.py +1877 -0
  123. sqlalchemy/ext/indexable.py +364 -0
  124. sqlalchemy/ext/instrumentation.py +450 -0
  125. sqlalchemy/ext/mutable.py +1081 -0
  126. sqlalchemy/ext/orderinglist.py +440 -0
  127. sqlalchemy/ext/serializer.py +184 -0
  128. sqlalchemy/future/__init__.py +17 -0
  129. sqlalchemy/future/engine.py +15 -0
  130. sqlalchemy/inspection.py +188 -0
  131. sqlalchemy/log.py +279 -0
  132. sqlalchemy/orm/__init__.py +176 -0
  133. sqlalchemy/orm/_orm_constructors.py +2694 -0
  134. sqlalchemy/orm/_typing.py +180 -0
  135. sqlalchemy/orm/attributes.py +2868 -0
  136. sqlalchemy/orm/base.py +991 -0
  137. sqlalchemy/orm/bulk_persistence.py +2168 -0
  138. sqlalchemy/orm/clsregistry.py +630 -0
  139. sqlalchemy/orm/collections.py +1569 -0
  140. sqlalchemy/orm/context.py +3475 -0
  141. sqlalchemy/orm/decl_api.py +2283 -0
  142. sqlalchemy/orm/decl_base.py +2320 -0
  143. sqlalchemy/orm/dependency.py +1306 -0
  144. sqlalchemy/orm/descriptor_props.py +1183 -0
  145. sqlalchemy/orm/dynamic.py +306 -0
  146. sqlalchemy/orm/evaluator.py +378 -0
  147. sqlalchemy/orm/events.py +3387 -0
  148. sqlalchemy/orm/exc.py +237 -0
  149. sqlalchemy/orm/identity.py +302 -0
  150. sqlalchemy/orm/instrumentation.py +749 -0
  151. sqlalchemy/orm/interfaces.py +1595 -0
  152. sqlalchemy/orm/loading.py +1712 -0
  153. sqlalchemy/orm/mapped_collection.py +557 -0
  154. sqlalchemy/orm/mapper.py +4465 -0
  155. sqlalchemy/orm/path_registry.py +907 -0
  156. sqlalchemy/orm/persistence.py +1790 -0
  157. sqlalchemy/orm/properties.py +972 -0
  158. sqlalchemy/orm/query.py +3528 -0
  159. sqlalchemy/orm/relationships.py +3608 -0
  160. sqlalchemy/orm/scoping.py +2233 -0
  161. sqlalchemy/orm/session.py +5468 -0
  162. sqlalchemy/orm/state.py +1175 -0
  163. sqlalchemy/orm/state_changes.py +196 -0
  164. sqlalchemy/orm/strategies.py +3552 -0
  165. sqlalchemy/orm/strategy_options.py +2648 -0
  166. sqlalchemy/orm/sync.py +164 -0
  167. sqlalchemy/orm/unitofwork.py +797 -0
  168. sqlalchemy/orm/util.py +2461 -0
  169. sqlalchemy/orm/writeonly.py +701 -0
  170. sqlalchemy/pool/__init__.py +41 -0
  171. sqlalchemy/pool/base.py +1540 -0
  172. sqlalchemy/pool/events.py +375 -0
  173. sqlalchemy/pool/impl.py +583 -0
  174. sqlalchemy/py.typed +0 -0
  175. sqlalchemy/schema.py +75 -0
  176. sqlalchemy/sql/__init__.py +156 -0
  177. sqlalchemy/sql/_annotated_cols.py +402 -0
  178. sqlalchemy/sql/_cache_key_cy.cp315-win_amd64.pyd +0 -0
  179. sqlalchemy/sql/_cache_key_cy.py +363 -0
  180. sqlalchemy/sql/_dml_constructors.py +132 -0
  181. sqlalchemy/sql/_elements_constructors.py +2190 -0
  182. sqlalchemy/sql/_orm_types.py +19 -0
  183. sqlalchemy/sql/_selectable_constructors.py +840 -0
  184. sqlalchemy/sql/_typing.py +500 -0
  185. sqlalchemy/sql/_util_cy.cp315-win_amd64.pyd +0 -0
  186. sqlalchemy/sql/_util_cy.pxd +11 -0
  187. sqlalchemy/sql/_util_cy.py +127 -0
  188. sqlalchemy/sql/annotation.py +590 -0
  189. sqlalchemy/sql/base.py +2702 -0
  190. sqlalchemy/sql/cache_key.py +915 -0
  191. sqlalchemy/sql/coercions.py +1373 -0
  192. sqlalchemy/sql/compiler.py +8453 -0
  193. sqlalchemy/sql/crud.py +1816 -0
  194. sqlalchemy/sql/ddl.py +1962 -0
  195. sqlalchemy/sql/default_comparator.py +660 -0
  196. sqlalchemy/sql/dml.py +2018 -0
  197. sqlalchemy/sql/elements.py +6057 -0
  198. sqlalchemy/sql/events.py +458 -0
  199. sqlalchemy/sql/expression.py +171 -0
  200. sqlalchemy/sql/functions.py +2380 -0
  201. sqlalchemy/sql/lambdas.py +1442 -0
  202. sqlalchemy/sql/naming.py +204 -0
  203. sqlalchemy/sql/operators.py +2909 -0
  204. sqlalchemy/sql/roles.py +332 -0
  205. sqlalchemy/sql/schema.py +7075 -0
  206. sqlalchemy/sql/selectable.py +7634 -0
  207. sqlalchemy/sql/sqltypes.py +4130 -0
  208. sqlalchemy/sql/traversals.py +1041 -0
  209. sqlalchemy/sql/type_api.py +2450 -0
  210. sqlalchemy/sql/util.py +1496 -0
  211. sqlalchemy/sql/visitors.py +1153 -0
  212. sqlalchemy/testing/__init__.py +97 -0
  213. sqlalchemy/testing/assertions.py +1007 -0
  214. sqlalchemy/testing/assertsql.py +519 -0
  215. sqlalchemy/testing/asyncio.py +128 -0
  216. sqlalchemy/testing/cancellation.py +237 -0
  217. sqlalchemy/testing/config.py +440 -0
  218. sqlalchemy/testing/engines.py +482 -0
  219. sqlalchemy/testing/entities.py +117 -0
  220. sqlalchemy/testing/exclusions.py +501 -0
  221. sqlalchemy/testing/fixtures/__init__.py +30 -0
  222. sqlalchemy/testing/fixtures/base.py +426 -0
  223. sqlalchemy/testing/fixtures/mypy.py +247 -0
  224. sqlalchemy/testing/fixtures/orm.py +227 -0
  225. sqlalchemy/testing/fixtures/sql.py +538 -0
  226. sqlalchemy/testing/pickleable.py +155 -0
  227. sqlalchemy/testing/plugin/__init__.py +6 -0
  228. sqlalchemy/testing/plugin/bootstrap.py +50 -0
  229. sqlalchemy/testing/plugin/plugin_base.py +828 -0
  230. sqlalchemy/testing/plugin/pytestplugin.py +896 -0
  231. sqlalchemy/testing/profiles_file.py +350 -0
  232. sqlalchemy/testing/profiling.py +294 -0
  233. sqlalchemy/testing/provision.py +633 -0
  234. sqlalchemy/testing/requirements.py +1971 -0
  235. sqlalchemy/testing/schema.py +198 -0
  236. sqlalchemy/testing/suite/__init__.py +19 -0
  237. sqlalchemy/testing/suite/test_cte.py +237 -0
  238. sqlalchemy/testing/suite/test_ddl.py +420 -0
  239. sqlalchemy/testing/suite/test_dialect.py +776 -0
  240. sqlalchemy/testing/suite/test_insert.py +630 -0
  241. sqlalchemy/testing/suite/test_reflection.py +3815 -0
  242. sqlalchemy/testing/suite/test_results.py +660 -0
  243. sqlalchemy/testing/suite/test_rowcount.py +258 -0
  244. sqlalchemy/testing/suite/test_select.py +2112 -0
  245. sqlalchemy/testing/suite/test_sequence.py +317 -0
  246. sqlalchemy/testing/suite/test_table_via_select.py +686 -0
  247. sqlalchemy/testing/suite/test_types.py +2271 -0
  248. sqlalchemy/testing/suite/test_unicode_ddl.py +189 -0
  249. sqlalchemy/testing/suite/test_update_delete.py +139 -0
  250. sqlalchemy/testing/util.py +575 -0
  251. sqlalchemy/testing/warnings.py +52 -0
  252. sqlalchemy/types.py +75 -0
  253. sqlalchemy/util/__init__.py +165 -0
  254. sqlalchemy/util/_collections.py +688 -0
  255. sqlalchemy/util/_collections_cy.cp315-win_amd64.pyd +0 -0
  256. sqlalchemy/util/_collections_cy.pxd +8 -0
  257. sqlalchemy/util/_collections_cy.py +516 -0
  258. sqlalchemy/util/_has_cython.py +48 -0
  259. sqlalchemy/util/_immutabledict_cy.cp315-win_amd64.pyd +0 -0
  260. sqlalchemy/util/_immutabledict_cy.py +240 -0
  261. sqlalchemy/util/compat.py +298 -0
  262. sqlalchemy/util/concurrency.py +272 -0
  263. sqlalchemy/util/cython.py +95 -0
  264. sqlalchemy/util/deprecations.py +401 -0
  265. sqlalchemy/util/langhelpers.py +2797 -0
  266. sqlalchemy/util/preloaded.py +153 -0
  267. sqlalchemy/util/queue.py +304 -0
  268. sqlalchemy/util/tool_support.py +202 -0
  269. sqlalchemy/util/topological.py +120 -0
  270. sqlalchemy/util/typing.py +709 -0
  271. sqlalchemy-2.1.0rc1.dist-info/METADATA +270 -0
  272. sqlalchemy-2.1.0rc1.dist-info/RECORD +276 -0
  273. sqlalchemy-2.1.0rc1.dist-info/WHEEL +5 -0
  274. sqlalchemy-2.1.0rc1.dist-info/licenses/AUTHORS +30 -0
  275. sqlalchemy-2.1.0rc1.dist-info/licenses/LICENSE +19 -0
  276. sqlalchemy-2.1.0rc1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,2450 @@
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(
840
+ self, collation: str, collation_schema: Optional[str] = None
841
+ ) -> Self:
842
+ """set up error handling for the collate expression"""
843
+ raise NotImplementedError("this datatype does not support collation")
844
+
845
+ @util.ro_memoized_property
846
+ def _type_affinity(self) -> Optional[Type[TypeEngine[_T]]]:
847
+ """Return a rudimental 'affinity' value expressing the general class
848
+ of type."""
849
+
850
+ typ = None
851
+ for t in self.__class__.__mro__:
852
+ if t is TypeEngine or TypeEngineMixin in t.__bases__:
853
+ return typ
854
+ elif issubclass(t, TypeEngine):
855
+ typ = t
856
+ else:
857
+ return self.__class__
858
+
859
+ @util.ro_memoized_property
860
+ def _generic_type_affinity(
861
+ self,
862
+ ) -> Type[TypeEngine[_T]]:
863
+ best_camelcase = None
864
+ best_uppercase = None
865
+
866
+ if not isinstance(self, TypeEngine):
867
+ return self.__class__
868
+
869
+ for t in self.__class__.__mro__:
870
+ if (
871
+ t.__module__
872
+ in (
873
+ "sqlalchemy.sql.sqltypes",
874
+ "sqlalchemy.sql.type_api",
875
+ )
876
+ and issubclass(t, TypeEngine)
877
+ and TypeEngineMixin not in t.__bases__
878
+ and t not in (TypeEngine, TypeEngineMixin)
879
+ and t.__name__[0] != "_"
880
+ ):
881
+ if t.__name__.isupper() and not best_uppercase:
882
+ best_uppercase = t
883
+ elif not t.__name__.isupper() and not best_camelcase:
884
+ best_camelcase = t
885
+
886
+ return (
887
+ best_camelcase
888
+ or best_uppercase
889
+ or cast("Type[TypeEngine[_T]]", NULLTYPE.__class__)
890
+ )
891
+
892
+ def as_generic(self, allow_nulltype: bool = False) -> TypeEngine[_T]:
893
+ """
894
+ Return an instance of the generic type corresponding to this type
895
+ using heuristic rule. The method may be overridden if this
896
+ heuristic rule is not sufficient.
897
+
898
+ >>> from sqlalchemy.dialects.mysql import INTEGER
899
+ >>> INTEGER(display_width=4).as_generic()
900
+ Integer()
901
+
902
+ >>> from sqlalchemy.dialects.mysql import NVARCHAR
903
+ >>> NVARCHAR(length=100).as_generic()
904
+ Unicode(length=100)
905
+
906
+ .. versionadded:: 1.4.0b2
907
+
908
+
909
+ .. seealso::
910
+
911
+ :ref:`metadata_reflection_dbagnostic_types` - describes the
912
+ use of :meth:`_types.TypeEngine.as_generic` in conjunction with
913
+ the :meth:`_sql.DDLEvents.column_reflect` event, which is its
914
+ intended use.
915
+
916
+ """
917
+ if (
918
+ not allow_nulltype
919
+ and self._generic_type_affinity == NULLTYPE.__class__
920
+ ):
921
+ raise NotImplementedError(
922
+ "Default TypeEngine.as_generic() "
923
+ "heuristic method was unsuccessful for {}. A custom "
924
+ "as_generic() method must be implemented for this "
925
+ "type class.".format(
926
+ self.__class__.__module__ + "." + self.__class__.__name__
927
+ )
928
+ )
929
+
930
+ return util.constructor_copy(self, self._generic_type_affinity)
931
+
932
+ def dialect_impl(self, dialect: Dialect) -> TypeEngine[_T]:
933
+ """Return a dialect-specific implementation for this
934
+ :class:`.TypeEngine`.
935
+
936
+ """
937
+ try:
938
+ tm = dialect._type_memos[self]
939
+ except KeyError:
940
+ pass
941
+ else:
942
+ return tm["impl"]
943
+ return self._dialect_info(dialect)["impl"]
944
+
945
+ def _unwrapped_dialect_impl(self, dialect: Dialect) -> TypeEngine[_T]:
946
+ """Return the 'unwrapped' dialect impl for this type.
947
+
948
+ For a type that applies wrapping logic (e.g. TypeDecorator), give
949
+ us the real, actual dialect-level type that is used.
950
+
951
+ This is used by TypeDecorator itself as well at least one case where
952
+ dialects need to check that a particular specific dialect-level
953
+ type is in use, within the :meth:`.DefaultDialect.set_input_sizes`
954
+ method.
955
+
956
+ """
957
+ return self.dialect_impl(dialect)
958
+
959
+ def _cached_literal_processor(
960
+ self, dialect: Dialect
961
+ ) -> Optional[_LiteralProcessorType[_T]]:
962
+ """Return a dialect-specific literal processor for this type."""
963
+
964
+ try:
965
+ return dialect._type_memos[self]["literal"]
966
+ except KeyError:
967
+ pass
968
+
969
+ # avoid KeyError context coming into literal_processor() function
970
+ # raises
971
+ d = self._dialect_info(dialect)
972
+ d["literal"] = lp = d["impl"].literal_processor(dialect)
973
+ return lp
974
+
975
+ def _cached_bind_processor(
976
+ self, dialect: Dialect
977
+ ) -> Optional[_BindProcessorType[_T]]:
978
+ """Return a dialect-specific bind processor for this type."""
979
+
980
+ try:
981
+ return dialect._type_memos[self]["bind"]
982
+ except KeyError:
983
+ pass
984
+
985
+ # avoid KeyError context coming into bind_processor() function
986
+ # raises
987
+ d = self._dialect_info(dialect)
988
+ d["bind"] = bp = d["impl"].bind_processor(dialect)
989
+ return bp
990
+
991
+ def _cached_result_processor(
992
+ self, dialect: Dialect, coltype: Any
993
+ ) -> Optional[_ResultProcessorType[_T]]:
994
+ """Return a dialect-specific result processor for this type."""
995
+
996
+ try:
997
+ return dialect._type_memos[self]["result"][coltype]
998
+ except KeyError:
999
+ pass
1000
+
1001
+ # avoid KeyError context coming into result_processor() function
1002
+ # raises
1003
+ d = self._dialect_info(dialect)
1004
+ # key assumption: DBAPI type codes are
1005
+ # constants. Else this dictionary would
1006
+ # grow unbounded.
1007
+ rp = d["impl"].result_processor(dialect, coltype)
1008
+ d["result"][coltype] = rp
1009
+ return rp
1010
+
1011
+ def _cached_custom_processor(
1012
+ self, dialect: Dialect, key: str, fn: Callable[[TypeEngine[_T]], _O]
1013
+ ) -> _O:
1014
+ """return a dialect-specific processing object for
1015
+ custom purposes.
1016
+
1017
+ The cx_Oracle dialect uses this at the moment.
1018
+
1019
+ """
1020
+ try:
1021
+ return cast(_O, dialect._type_memos[self]["custom"][key])
1022
+ except KeyError:
1023
+ pass
1024
+ # avoid KeyError context coming into fn() function
1025
+ # raises
1026
+ d = self._dialect_info(dialect)
1027
+ impl = d["impl"]
1028
+ custom_dict = d.setdefault("custom", {})
1029
+ custom_dict[key] = result = fn(impl)
1030
+ return result
1031
+
1032
+ def _dialect_info(self, dialect: Dialect) -> _TypeMemoDict:
1033
+ """Return a dialect-specific registry which
1034
+ caches a dialect-specific implementation, bind processing
1035
+ function, and one or more result processing functions."""
1036
+
1037
+ if self in dialect._type_memos:
1038
+ return dialect._type_memos[self]
1039
+ else:
1040
+ impl = self._gen_dialect_impl(dialect)
1041
+ if impl is self:
1042
+ impl = self.adapt(type(self))
1043
+ # this can't be self, else we create a cycle
1044
+ assert impl is not self
1045
+ d: _TypeMemoDict = {"impl": impl, "result": {}}
1046
+ dialect._type_memos[self] = d
1047
+ return d
1048
+
1049
+ def _gen_dialect_impl(self, dialect: Dialect) -> TypeEngine[Any]:
1050
+ if dialect.name in self._variant_mapping:
1051
+ return self._variant_mapping[dialect.name]._gen_dialect_impl(
1052
+ dialect
1053
+ )
1054
+ else:
1055
+ return dialect.type_descriptor(self)
1056
+
1057
+ @util.memoized_property
1058
+ def _static_cache_key(
1059
+ self,
1060
+ ) -> Union[CacheConst, Tuple[Any, ...]]:
1061
+ names = util.get_cls_kwargs(self.__class__)
1062
+ return (self.__class__,) + tuple(
1063
+ (
1064
+ k,
1065
+ (
1066
+ self.__dict__[k]._static_cache_key
1067
+ if isinstance(self.__dict__[k], TypeEngine)
1068
+ else self.__dict__[k]
1069
+ ),
1070
+ )
1071
+ for k in names
1072
+ if k in self.__dict__
1073
+ and not k.startswith("_")
1074
+ and self.__dict__[k] is not None
1075
+ )
1076
+
1077
+ @overload
1078
+ def adapt(self, cls: Type[_TE], **kw: Any) -> _TE: ...
1079
+
1080
+ @overload
1081
+ def adapt(
1082
+ self, cls: Type[TypeEngineMixin], **kw: Any
1083
+ ) -> TypeEngine[Any]: ...
1084
+
1085
+ def adapt(
1086
+ self, cls: Type[Union[TypeEngine[Any], TypeEngineMixin]], **kw: Any
1087
+ ) -> TypeEngine[Any]:
1088
+ """Produce an "adapted" form of this type, given an "impl" class
1089
+ to work with.
1090
+
1091
+ This method is used internally to associate generic
1092
+ types with "implementation" types that are specific to a particular
1093
+ dialect.
1094
+ """
1095
+ typ = util.constructor_copy(
1096
+ self, cast(Type[TypeEngine[Any]], cls), **kw
1097
+ )
1098
+ typ._variant_mapping = self._variant_mapping
1099
+ return typ
1100
+
1101
+ def coerce_compared_value(
1102
+ self, op: Optional[OperatorType], value: Any
1103
+ ) -> TypeEngine[Any]:
1104
+ """Suggest a type for a 'coerced' Python value in an expression.
1105
+
1106
+ Given an operator and value, gives the type a chance
1107
+ to return a type which the value should be coerced into.
1108
+
1109
+ The default behavior here is conservative; if the right-hand
1110
+ side is already coerced into a SQL type based on its
1111
+ Python type, it is usually left alone.
1112
+
1113
+ End-user functionality extension here should generally be via
1114
+ :class:`.TypeDecorator`, which provides more liberal behavior in that
1115
+ it defaults to coercing the other side of the expression into this
1116
+ type, thus applying special Python conversions above and beyond those
1117
+ needed by the DBAPI to both ides. It also provides the public method
1118
+ :meth:`.TypeDecorator.coerce_compared_value` which is intended for
1119
+ end-user customization of this behavior.
1120
+
1121
+ """
1122
+ _coerced_type = _resolve_value_to_type(value)
1123
+ if (
1124
+ _coerced_type is NULLTYPE
1125
+ or _coerced_type._type_affinity is self._type_affinity
1126
+ ):
1127
+ return self
1128
+ else:
1129
+ return _coerced_type
1130
+
1131
+ def _compare_type_affinity(self, other: TypeEngine[Any]) -> bool:
1132
+ return self._type_affinity is other._type_affinity
1133
+
1134
+ def compile(self, dialect: Optional[Dialect] = None) -> str:
1135
+ """Produce a string-compiled form of this :class:`.TypeEngine`.
1136
+
1137
+ When called with no arguments, uses a "default" dialect
1138
+ to produce a string result.
1139
+
1140
+ :param dialect: a :class:`.Dialect` instance.
1141
+
1142
+ """
1143
+ # arg, return value is inconsistent with
1144
+ # ClauseElement.compile()....this is a mistake.
1145
+
1146
+ if dialect is None:
1147
+ dialect = self._default_dialect()
1148
+
1149
+ return dialect.type_compiler_instance.process(self)
1150
+
1151
+ @util.preload_module("sqlalchemy.engine.default")
1152
+ def _default_dialect(self) -> Dialect:
1153
+ default = util.preloaded.engine_default
1154
+
1155
+ # dmypy / mypy seems to sporadically keep thinking this line is
1156
+ # returning Any, which seems to be caused by the @deprecated_params
1157
+ # decorator on the DefaultDialect constructor
1158
+ return default.StrCompileDialect() # type: ignore[no-any-return]
1159
+
1160
+ def __str__(self) -> str:
1161
+ return str(self.compile())
1162
+
1163
+ def repr_struct(self) -> util.GenericRepr:
1164
+ """Return a :class:`.GenericRepr` object representing this type.
1165
+
1166
+ This method is used to generate the repr string for the type.
1167
+ Subclasses can override this to customize the repr structure.
1168
+
1169
+ .. versionadded:: 2.1
1170
+
1171
+ """
1172
+ return util.GenericRepr(self)
1173
+
1174
+ def __repr__(self) -> str:
1175
+ return str(self.repr_struct())
1176
+
1177
+
1178
+ class TypeEngineMixin:
1179
+ """classes which subclass this can act as "mixin" classes for
1180
+ TypeEngine."""
1181
+
1182
+ __slots__ = ()
1183
+
1184
+ if TYPE_CHECKING:
1185
+
1186
+ @util.memoized_property
1187
+ def _static_cache_key(
1188
+ self,
1189
+ ) -> Union[CacheConst, Tuple[Any, ...]]: ...
1190
+
1191
+ @overload
1192
+ def adapt(self, cls: Type[_TE], **kw: Any) -> _TE: ...
1193
+
1194
+ @overload
1195
+ def adapt(
1196
+ self, cls: Type[TypeEngineMixin], **kw: Any
1197
+ ) -> TypeEngine[Any]: ...
1198
+
1199
+ def adapt(
1200
+ self, cls: Type[Union[TypeEngine[Any], TypeEngineMixin]], **kw: Any
1201
+ ) -> TypeEngine[Any]: ...
1202
+
1203
+ def dialect_impl(self, dialect: Dialect) -> TypeEngine[Any]: ...
1204
+
1205
+
1206
+ class ExternalType(TypeEngineMixin):
1207
+ """mixin that defines attributes and behaviors specific to third-party
1208
+ datatypes.
1209
+
1210
+ "Third party" refers to datatypes that are defined outside the scope
1211
+ of SQLAlchemy within either end-user application code or within
1212
+ external extensions to SQLAlchemy.
1213
+
1214
+ Subclasses currently include :class:`.TypeDecorator` and
1215
+ :class:`.UserDefinedType`.
1216
+
1217
+ .. versionadded:: 1.4.28
1218
+
1219
+ """
1220
+
1221
+ cache_ok: Optional[bool] = None
1222
+ '''Indicate if statements using this :class:`.ExternalType` are "safe to
1223
+ cache".
1224
+
1225
+ The default value ``None`` will emit a warning and then not allow caching
1226
+ of a statement which includes this type. Set to ``False`` to disable
1227
+ statements using this type from being cached at all without a warning.
1228
+ When set to ``True``, the object's class and selected elements from its
1229
+ state will be used as part of the cache key. For example, using a
1230
+ :class:`.TypeDecorator`::
1231
+
1232
+ class MyType(TypeDecorator):
1233
+ impl = String
1234
+
1235
+ cache_ok = True
1236
+
1237
+ def __init__(self, choices):
1238
+ self.choices = tuple(choices)
1239
+ self.internal_only = True
1240
+
1241
+ The cache key for the above type would be equivalent to::
1242
+
1243
+ >>> MyType(["a", "b", "c"])._static_cache_key
1244
+ (<class '__main__.MyType'>, ('choices', ('a', 'b', 'c')))
1245
+
1246
+ The caching scheme will extract attributes from the type that correspond
1247
+ to the names of parameters in the ``__init__()`` method. Above, the
1248
+ "choices" attribute becomes part of the cache key but "internal_only"
1249
+ does not, because there is no parameter named "internal_only".
1250
+
1251
+ The requirements for cacheable elements is that they are hashable
1252
+ and also that they indicate the same SQL rendered for expressions using
1253
+ this type every time for a given cache value.
1254
+
1255
+ To accommodate for datatypes that refer to unhashable structures such
1256
+ as dictionaries, sets and lists, these objects can be made "cacheable"
1257
+ by assigning hashable structures to the attributes whose names
1258
+ correspond with the names of the arguments. For example, a datatype
1259
+ which accepts a dictionary of lookup values may publish this as a sorted
1260
+ series of tuples. Given a previously un-cacheable type as::
1261
+
1262
+ class LookupType(UserDefinedType):
1263
+ """a custom type that accepts a dictionary as a parameter.
1264
+
1265
+ this is the non-cacheable version, as "self.lookup" is not
1266
+ hashable.
1267
+
1268
+ """
1269
+
1270
+ def __init__(self, lookup):
1271
+ self.lookup = lookup
1272
+
1273
+ def get_col_spec(self, **kw):
1274
+ return "VARCHAR(255)"
1275
+
1276
+ def bind_processor(self, dialect): ... # works with "self.lookup" ...
1277
+
1278
+ Where "lookup" is a dictionary. The type will not be able to generate
1279
+ a cache key::
1280
+
1281
+ >>> type_ = LookupType({"a": 10, "b": 20})
1282
+ >>> type_._static_cache_key
1283
+ <stdin>:1: SAWarning: UserDefinedType LookupType({'a': 10, 'b': 20}) will not
1284
+ produce a cache key because the ``cache_ok`` flag is not set to True.
1285
+ Set this flag to True if this type object's state is safe to use
1286
+ in a cache key, or False to disable this warning.
1287
+ symbol('no_cache')
1288
+
1289
+ If we **did** set up such a cache key, it wouldn't be usable. We would
1290
+ get a tuple structure that contains a dictionary inside of it, which
1291
+ cannot itself be used as a key in a "cache dictionary" such as SQLAlchemy's
1292
+ statement cache, since Python dictionaries aren't hashable::
1293
+
1294
+ >>> # set cache_ok = True
1295
+ >>> type_.cache_ok = True
1296
+
1297
+ >>> # this is the cache key it would generate
1298
+ >>> key = type_._static_cache_key
1299
+ >>> key
1300
+ (<class '__main__.LookupType'>, ('lookup', {'a': 10, 'b': 20}))
1301
+
1302
+ >>> # however this key is not hashable, will fail when used with
1303
+ >>> # SQLAlchemy statement cache
1304
+ >>> some_cache = {key: "some sql value"}
1305
+ Traceback (most recent call last): File "<stdin>", line 1,
1306
+ in <module> TypeError: unhashable type: 'dict'
1307
+
1308
+ The type may be made cacheable by assigning a sorted tuple of tuples
1309
+ to the ".lookup" attribute::
1310
+
1311
+ class LookupType(UserDefinedType):
1312
+ """a custom type that accepts a dictionary as a parameter.
1313
+
1314
+ The dictionary is stored both as itself in a private variable,
1315
+ and published in a public variable as a sorted tuple of tuples,
1316
+ which is hashable and will also return the same value for any
1317
+ two equivalent dictionaries. Note it assumes the keys and
1318
+ values of the dictionary are themselves hashable.
1319
+
1320
+ """
1321
+
1322
+ cache_ok = True
1323
+
1324
+ def __init__(self, lookup):
1325
+ self._lookup = lookup
1326
+
1327
+ # assume keys/values of "lookup" are hashable; otherwise
1328
+ # they would also need to be converted in some way here
1329
+ self.lookup = tuple((key, lookup[key]) for key in sorted(lookup))
1330
+
1331
+ def get_col_spec(self, **kw):
1332
+ return "VARCHAR(255)"
1333
+
1334
+ def bind_processor(self, dialect): ... # works with "self._lookup" ...
1335
+
1336
+ Where above, the cache key for ``LookupType({"a": 10, "b": 20})`` will be::
1337
+
1338
+ >>> LookupType({"a": 10, "b": 20})._static_cache_key
1339
+ (<class '__main__.LookupType'>, ('lookup', (('a', 10), ('b', 20))))
1340
+
1341
+ .. versionadded:: 1.4.14 - added the ``cache_ok`` flag to allow
1342
+ some configurability of caching for :class:`.TypeDecorator` classes.
1343
+
1344
+ .. versionadded:: 1.4.28 - added the :class:`.ExternalType` mixin which
1345
+ generalizes the ``cache_ok`` flag to both the :class:`.TypeDecorator`
1346
+ and :class:`.UserDefinedType` classes.
1347
+
1348
+ .. seealso::
1349
+
1350
+ :ref:`sql_caching`
1351
+
1352
+ ''' # noqa: E501
1353
+
1354
+ @util.non_memoized_property
1355
+ def _static_cache_key(
1356
+ self,
1357
+ ) -> Union[CacheConst, Tuple[Any, ...]]:
1358
+ cache_ok = self.__class__.__dict__.get("cache_ok", None)
1359
+
1360
+ if cache_ok is None:
1361
+ for subtype in self.__class__.__mro__:
1362
+ if ExternalType in subtype.__bases__:
1363
+ break
1364
+ else:
1365
+ subtype = self.__class__.__mro__[1]
1366
+
1367
+ util.warn(
1368
+ "%s %r will not produce a cache key because "
1369
+ "the ``cache_ok`` attribute is not set to True. This can "
1370
+ "have significant performance implications including some "
1371
+ "performance degradations in comparison to prior SQLAlchemy "
1372
+ "versions. Set this attribute to True if this type object's "
1373
+ "state is safe to use in a cache key, or False to "
1374
+ "disable this warning." % (subtype.__name__, self),
1375
+ code="cprf",
1376
+ )
1377
+ elif cache_ok is True:
1378
+ return super()._static_cache_key
1379
+
1380
+ return NO_CACHE
1381
+
1382
+
1383
+ class UserDefinedType(
1384
+ ExternalType, TypeEngineMixin, TypeEngine[_T], util.EnsureKWArg
1385
+ ):
1386
+ """Base for user defined types.
1387
+
1388
+ This should be the base of new types. Note that
1389
+ for most cases, :class:`.TypeDecorator` is probably
1390
+ more appropriate::
1391
+
1392
+ import sqlalchemy.types as types
1393
+
1394
+
1395
+ class MyType(types.UserDefinedType):
1396
+ cache_ok = True
1397
+
1398
+ def __init__(self, precision=8):
1399
+ self.precision = precision
1400
+
1401
+ def get_col_spec(self, **kw):
1402
+ return "MYTYPE(%s)" % self.precision
1403
+
1404
+ def bind_processor(self, dialect):
1405
+ def process(value):
1406
+ return value
1407
+
1408
+ return process
1409
+
1410
+ def result_processor(self, dialect, coltype):
1411
+ def process(value):
1412
+ return value
1413
+
1414
+ return process
1415
+
1416
+ Once the type is made, it's immediately usable::
1417
+
1418
+ table = Table(
1419
+ "foo",
1420
+ metadata_obj,
1421
+ Column("id", Integer, primary_key=True),
1422
+ Column("data", MyType(16)),
1423
+ )
1424
+
1425
+ The ``get_col_spec()`` method will in most cases receive a keyword
1426
+ argument ``type_expression`` which refers to the owning expression
1427
+ of the type as being compiled, such as a :class:`_schema.Column` or
1428
+ :func:`.cast` construct. This keyword is only sent if the method
1429
+ accepts keyword arguments (e.g. ``**kw``) in its argument signature;
1430
+ introspection is used to check for this in order to support legacy
1431
+ forms of this function.
1432
+
1433
+ The :attr:`.UserDefinedType.cache_ok` class-level flag indicates if this
1434
+ custom :class:`.UserDefinedType` is safe to be used as part of a cache key.
1435
+ This flag defaults to ``None`` which will initially generate a warning
1436
+ when the SQL compiler attempts to generate a cache key for a statement
1437
+ that uses this type. If the :class:`.UserDefinedType` is not guaranteed
1438
+ to produce the same bind/result behavior and SQL generation
1439
+ every time, this flag should be set to ``False``; otherwise if the
1440
+ class produces the same behavior each time, it may be set to ``True``.
1441
+ See :attr:`.UserDefinedType.cache_ok` for further notes on how this works.
1442
+
1443
+ .. versionadded:: 1.4.28 Generalized the :attr:`.ExternalType.cache_ok`
1444
+ flag so that it is available for both :class:`.TypeDecorator` as well
1445
+ as :class:`.UserDefinedType`.
1446
+
1447
+ """
1448
+
1449
+ __visit_name__ = "user_defined"
1450
+
1451
+ ensure_kwarg = "get_col_spec"
1452
+
1453
+ operator_classes = OperatorClass.ANY
1454
+
1455
+ def coerce_compared_value(
1456
+ self, op: Optional[OperatorType], value: Any
1457
+ ) -> TypeEngine[Any]:
1458
+ """Suggest a type for a 'coerced' Python value in an expression.
1459
+
1460
+ Default behavior for :class:`.UserDefinedType` is the
1461
+ same as that of :class:`.TypeDecorator`; by default it returns
1462
+ ``self``, assuming the compared value should be coerced into
1463
+ the same type as this one. See
1464
+ :meth:`.TypeDecorator.coerce_compared_value` for more detail.
1465
+
1466
+ """
1467
+
1468
+ return self
1469
+
1470
+ if TYPE_CHECKING:
1471
+
1472
+ def get_col_spec(self, **kw: Any) -> str: ...
1473
+
1474
+
1475
+ class Emulated(TypeEngineMixin):
1476
+ """Mixin for base types that emulate the behavior of a DB-native type.
1477
+
1478
+ An :class:`.Emulated` type will use an available database type
1479
+ in conjunction with Python-side routines and/or database constraints
1480
+ in order to approximate the behavior of a database type that is provided
1481
+ natively by some backends. When a native-providing backend is in
1482
+ use, the native version of the type is used. This native version
1483
+ should include the :class:`.NativeForEmulated` mixin to allow it to be
1484
+ distinguished from :class:`.Emulated`.
1485
+
1486
+ Current examples of :class:`.Emulated` are: :class:`.Interval`,
1487
+ :class:`.Enum`, :class:`.Boolean`.
1488
+
1489
+ """
1490
+
1491
+ native: bool
1492
+
1493
+ def adapt_to_emulated(
1494
+ self,
1495
+ impltype: Type[Union[TypeEngine[Any], TypeEngineMixin]],
1496
+ **kw: Any,
1497
+ ) -> TypeEngine[Any]:
1498
+ """Given an impl class, adapt this type to the impl assuming
1499
+ "emulated".
1500
+
1501
+ The impl should also be an "emulated" version of this type,
1502
+ most likely the same class as this type itself.
1503
+
1504
+ e.g.: sqltypes.Enum adapts to the Enum class.
1505
+
1506
+ """
1507
+ return super().adapt(impltype, **kw)
1508
+
1509
+ @overload
1510
+ def adapt(self, cls: Type[_TE], **kw: Any) -> _TE: ...
1511
+
1512
+ @overload
1513
+ def adapt(
1514
+ self, cls: Type[TypeEngineMixin], **kw: Any
1515
+ ) -> TypeEngine[Any]: ...
1516
+
1517
+ def adapt(
1518
+ self, cls: Type[Union[TypeEngine[Any], TypeEngineMixin]], **kw: Any
1519
+ ) -> TypeEngine[Any]:
1520
+ if _is_native_for_emulated(cls):
1521
+ if self.native:
1522
+ # native support requested, dialect gave us a native
1523
+ # implementor, pass control over to it
1524
+ return cls.adapt_emulated_to_native(self, **kw)
1525
+ else:
1526
+ # non-native support, let the native implementor
1527
+ # decide also, at the moment this is just to help debugging
1528
+ # as only the default logic is implemented.
1529
+ return cls.adapt_native_to_emulated(self, **kw)
1530
+ else:
1531
+ # this would be, both classes are Enum, or both classes
1532
+ # are postgresql.ENUM
1533
+ if issubclass(cls, self.__class__):
1534
+ return self.adapt_to_emulated(cls, **kw)
1535
+ else:
1536
+ return super().adapt(cls, **kw)
1537
+
1538
+
1539
+ def _is_native_for_emulated(
1540
+ typ: Type[Union[TypeEngine[Any], TypeEngineMixin]],
1541
+ ) -> TypeGuard[Type[NativeForEmulated]]:
1542
+ return hasattr(typ, "adapt_emulated_to_native")
1543
+
1544
+
1545
+ class NativeForEmulated(TypeEngineMixin):
1546
+ """Indicates DB-native types supported by an :class:`.Emulated` type."""
1547
+
1548
+ @classmethod
1549
+ def adapt_native_to_emulated(
1550
+ cls,
1551
+ impl: Union[TypeEngine[Any], TypeEngineMixin],
1552
+ **kw: Any,
1553
+ ) -> TypeEngine[Any]:
1554
+ """Given an impl, adapt this type's class to the impl assuming
1555
+ "emulated".
1556
+
1557
+
1558
+ """
1559
+ impltype = impl.__class__
1560
+ return impl.adapt(impltype, **kw)
1561
+
1562
+ @classmethod
1563
+ def adapt_emulated_to_native(
1564
+ cls,
1565
+ impl: Union[TypeEngine[Any], TypeEngineMixin],
1566
+ **kw: Any,
1567
+ ) -> TypeEngine[Any]:
1568
+ """Given an impl, adapt this type's class to the impl assuming
1569
+ "native".
1570
+
1571
+ The impl will be an :class:`.Emulated` class but not a
1572
+ :class:`.NativeForEmulated`.
1573
+
1574
+ e.g.: postgresql.ENUM produces a type given an Enum instance.
1575
+
1576
+ """
1577
+
1578
+ # dmypy seems to crash on this
1579
+ return cls(**kw) # type: ignore[return-value]
1580
+
1581
+ # dmypy seems to crash with this, on repeated runs with changes
1582
+ # if TYPE_CHECKING:
1583
+ # def __init__(self, **kw: Any):
1584
+ # ...
1585
+
1586
+
1587
+ class TypeDecorator(SchemaEventTarget, ExternalType, TypeEngine[_T]):
1588
+ '''Allows the creation of types which add additional functionality
1589
+ to an existing type.
1590
+
1591
+ This method is preferred to direct subclassing of SQLAlchemy's
1592
+ built-in types as it ensures that all required functionality of
1593
+ the underlying type is kept in place.
1594
+
1595
+ Typical usage::
1596
+
1597
+ import sqlalchemy.types as types
1598
+
1599
+
1600
+ class MyType(types.TypeDecorator):
1601
+ """Prefixes Unicode values with "PREFIX:" on the way in and
1602
+ strips it off on the way out.
1603
+ """
1604
+
1605
+ impl = types.Unicode
1606
+
1607
+ cache_ok = True
1608
+
1609
+ def process_bind_param(self, value, dialect):
1610
+ return "PREFIX:" + value
1611
+
1612
+ def process_result_value(self, value, dialect):
1613
+ return value[7:]
1614
+
1615
+ def copy(self, **kw):
1616
+ return MyType(self.impl.length)
1617
+
1618
+ The class-level ``impl`` attribute is required, and can reference any
1619
+ :class:`.TypeEngine` class. Alternatively, the :meth:`load_dialect_impl`
1620
+ method can be used to provide different type classes based on the dialect
1621
+ given; in this case, the ``impl`` variable can reference
1622
+ ``TypeEngine`` as a placeholder.
1623
+
1624
+ The :attr:`.TypeDecorator.cache_ok` class-level flag indicates if this
1625
+ custom :class:`.TypeDecorator` is safe to be used as part of a cache key.
1626
+ This flag defaults to ``None`` which will initially generate a warning
1627
+ when the SQL compiler attempts to generate a cache key for a statement
1628
+ that uses this type. If the :class:`.TypeDecorator` is not guaranteed
1629
+ to produce the same bind/result behavior and SQL generation
1630
+ every time, this flag should be set to ``False``; otherwise if the
1631
+ class produces the same behavior each time, it may be set to ``True``.
1632
+ See :attr:`.TypeDecorator.cache_ok` for further notes on how this works.
1633
+
1634
+ Types that receive a Python type that isn't similar to the ultimate type
1635
+ used may want to define the :meth:`TypeDecorator.coerce_compared_value`
1636
+ method. This is used to give the expression system a hint when coercing
1637
+ Python objects into bind parameters within expressions. Consider this
1638
+ expression::
1639
+
1640
+ mytable.c.somecol + datetime.date(2009, 5, 15)
1641
+
1642
+ Above, if "somecol" is an ``Integer`` variant, it makes sense that
1643
+ we're doing date arithmetic, where above is usually interpreted
1644
+ by databases as adding a number of days to the given date.
1645
+ The expression system does the right thing by not attempting to
1646
+ coerce the "date()" value into an integer-oriented bind parameter.
1647
+
1648
+ However, in the case of ``TypeDecorator``, we are usually changing an
1649
+ incoming Python type to something new - ``TypeDecorator`` by default will
1650
+ "coerce" the non-typed side to be the same type as itself. Such as below,
1651
+ we define an "epoch" type that stores a date value as an integer::
1652
+
1653
+ class MyEpochType(types.TypeDecorator):
1654
+ impl = types.Integer
1655
+
1656
+ cache_ok = True
1657
+
1658
+ epoch = datetime.date(1970, 1, 1)
1659
+
1660
+ def process_bind_param(self, value, dialect):
1661
+ return (value - self.epoch).days
1662
+
1663
+ def process_result_value(self, value, dialect):
1664
+ return self.epoch + timedelta(days=value)
1665
+
1666
+ Our expression of ``somecol + date`` with the above type will coerce the
1667
+ "date" on the right side to also be treated as ``MyEpochType``.
1668
+
1669
+ This behavior can be overridden via the
1670
+ :meth:`~TypeDecorator.coerce_compared_value` method, which returns a type
1671
+ that should be used for the value of the expression. Below we set it such
1672
+ that an integer value will be treated as an ``Integer``, and any other
1673
+ value is assumed to be a date and will be treated as a ``MyEpochType``::
1674
+
1675
+ def coerce_compared_value(self, op, value):
1676
+ if isinstance(value, int):
1677
+ return Integer()
1678
+ else:
1679
+ return self
1680
+
1681
+ .. warning::
1682
+
1683
+ Note that the **behavior of coerce_compared_value is not inherited
1684
+ by default from that of the base type**.
1685
+ If the :class:`.TypeDecorator` is augmenting a
1686
+ type that requires special logic for certain types of operators,
1687
+ this method **must** be overridden. A key example is when decorating
1688
+ the :class:`_postgresql.JSON` and :class:`_postgresql.JSONB` types;
1689
+ the default rules of :meth:`.TypeEngine.coerce_compared_value` should
1690
+ be used in order to deal with operators like index operations::
1691
+
1692
+ from sqlalchemy import JSON
1693
+ from sqlalchemy import TypeDecorator
1694
+
1695
+
1696
+ class MyJsonType(TypeDecorator):
1697
+ impl = JSON
1698
+
1699
+ cache_ok = True
1700
+
1701
+ def coerce_compared_value(self, op, value):
1702
+ return self.impl.coerce_compared_value(op, value)
1703
+
1704
+ Without the above step, index operations such as ``mycol['foo']``
1705
+ will cause the index value ``'foo'`` to be JSON encoded.
1706
+
1707
+ Similarly, when working with the :class:`.ARRAY` datatype, the
1708
+ type coercion for index operations (e.g. ``mycol[5]``) is also
1709
+ handled by :meth:`.TypeDecorator.coerce_compared_value`, where
1710
+ again a simple override is sufficient unless special rules are needed
1711
+ for particular operators::
1712
+
1713
+ from sqlalchemy import ARRAY
1714
+ from sqlalchemy import TypeDecorator
1715
+
1716
+
1717
+ class MyArrayType(TypeDecorator):
1718
+ impl = ARRAY
1719
+
1720
+ cache_ok = True
1721
+
1722
+ def coerce_compared_value(self, op, value):
1723
+ return self.impl.coerce_compared_value(op, value)
1724
+
1725
+ '''
1726
+
1727
+ __visit_name__ = "type_decorator"
1728
+
1729
+ _is_type_decorator = True
1730
+
1731
+ # this is that pattern I've used in a few places (Dialect.dbapi,
1732
+ # Dialect.type_compiler) where the "cls.attr" is a class to make something,
1733
+ # and "instance.attr" is an instance of that thing. It's such a nifty,
1734
+ # great pattern, and there is zero chance Python typing tools will ever be
1735
+ # OK with it. For TypeDecorator.impl, this is a highly public attribute so
1736
+ # we really can't change its behavior without a major deprecation routine.
1737
+ impl: Union[TypeEngine[Any], Type[TypeEngine[Any]]]
1738
+
1739
+ # we are changing its behavior *slightly*, which is that we now consume
1740
+ # the instance level version from this memoized property instead, so you
1741
+ # can't reassign "impl" on an existing TypeDecorator that's already been
1742
+ # used (something one shouldn't do anyway) without also updating
1743
+ # impl_instance.
1744
+ @util.memoized_property
1745
+ def impl_instance(self) -> TypeEngine[Any]:
1746
+ return self.impl # type: ignore[return-value]
1747
+
1748
+ def __init__(self, *args: Any, **kwargs: Any):
1749
+ """Construct a :class:`.TypeDecorator`.
1750
+
1751
+ Arguments sent here are passed to the constructor
1752
+ of the class assigned to the ``impl`` class level attribute,
1753
+ assuming the ``impl`` is a callable, and the resulting
1754
+ object is assigned to the ``self.impl`` instance attribute
1755
+ (thus overriding the class attribute of the same name).
1756
+
1757
+ If the class level ``impl`` is not a callable (the unusual case),
1758
+ it will be assigned to the same instance attribute 'as-is',
1759
+ ignoring those arguments passed to the constructor.
1760
+
1761
+ Subclasses can override this to customize the generation
1762
+ of ``self.impl`` entirely.
1763
+
1764
+ """
1765
+
1766
+ if not hasattr(self.__class__, "impl"):
1767
+ raise AssertionError(
1768
+ "TypeDecorator implementations "
1769
+ "require a class-level variable "
1770
+ "'impl' which refers to the class of "
1771
+ "type being decorated"
1772
+ )
1773
+
1774
+ self.impl = to_instance(self.__class__.impl, *args, **kwargs)
1775
+
1776
+ coerce_to_is_types: Sequence[Type[Any]] = (type(None),)
1777
+ """Specify those Python types which should be coerced at the expression
1778
+ level to "IS <constant>" when compared using ``==`` (and same for
1779
+ ``IS NOT`` in conjunction with ``!=``).
1780
+
1781
+ For most SQLAlchemy types, this includes ``NoneType``, as well as
1782
+ ``bool``.
1783
+
1784
+ :class:`.TypeDecorator` modifies this list to only include ``NoneType``,
1785
+ as typedecorator implementations that deal with boolean types are common.
1786
+
1787
+ Custom :class:`.TypeDecorator` classes can override this attribute to
1788
+ return an empty tuple, in which case no values will be coerced to
1789
+ constants.
1790
+
1791
+ """
1792
+
1793
+ if not TYPE_CHECKING:
1794
+
1795
+ @property
1796
+ def operator_classes(self) -> OperatorClass:
1797
+ return self.impl_instance.operator_classes
1798
+
1799
+ class Comparator(TypeEngine.Comparator[_CT]):
1800
+ """A :class:`.TypeEngine.Comparator` that is specific to
1801
+ :class:`.TypeDecorator`.
1802
+
1803
+ User-defined :class:`.TypeDecorator` classes should not typically
1804
+ need to modify this.
1805
+
1806
+
1807
+ """
1808
+
1809
+ __slots__ = ()
1810
+
1811
+ def operate(
1812
+ self, op: OperatorType, *other: Any, **kwargs: Any
1813
+ ) -> ColumnElement[_CT]:
1814
+ if TYPE_CHECKING:
1815
+ assert isinstance(self.expr.type, TypeDecorator)
1816
+ kwargs["_python_is_types"] = self.expr.type.coerce_to_is_types
1817
+ return super().operate(op, *other, **kwargs)
1818
+
1819
+ def reverse_operate(
1820
+ self, op: OperatorType, other: Any, **kwargs: Any
1821
+ ) -> ColumnElement[_CT]:
1822
+ if TYPE_CHECKING:
1823
+ assert isinstance(self.expr.type, TypeDecorator)
1824
+ kwargs["_python_is_types"] = self.expr.type.coerce_to_is_types
1825
+ return super().reverse_operate(op, other, **kwargs)
1826
+
1827
+ @staticmethod
1828
+ def _reduce_td_comparator(
1829
+ impl: TypeEngine[Any], expr: ColumnElement[_T]
1830
+ ) -> Any:
1831
+ return TypeDecorator._create_td_comparator_type(impl)(expr)
1832
+
1833
+ @staticmethod
1834
+ def _create_td_comparator_type(
1835
+ impl: TypeEngine[Any],
1836
+ ) -> _ComparatorFactory[Any]:
1837
+
1838
+ def __reduce__(self: TypeDecorator.Comparator[Any]) -> Any:
1839
+ return (TypeDecorator._reduce_td_comparator, (impl, self.expr))
1840
+
1841
+ return type(
1842
+ "TDComparator",
1843
+ (TypeDecorator.Comparator, impl.comparator_factory), # type: ignore[arg-type, return-value] # noqa: E501
1844
+ {"__reduce__": __reduce__},
1845
+ )
1846
+
1847
+ @property
1848
+ def comparator_factory( # type: ignore[override] # mypy properties bug
1849
+ self,
1850
+ ) -> _ComparatorFactory[Any]:
1851
+ if TypeDecorator.Comparator in self.impl.comparator_factory.__mro__: # type: ignore[attr-defined] # noqa: E501
1852
+ return self.impl_instance.comparator_factory
1853
+ else:
1854
+ # reconcile the Comparator class on the impl with that
1855
+ # of TypeDecorator.
1856
+ # the use of multiple staticmethods is to support repeated
1857
+ # pickling of the Comparator itself
1858
+ return TypeDecorator._create_td_comparator_type(self.impl_instance)
1859
+
1860
+ def _copy_with_check(self) -> Self:
1861
+ tt = self.copy()
1862
+ if not isinstance(tt, self.__class__):
1863
+ raise AssertionError(
1864
+ "Type object %s does not properly "
1865
+ "implement the copy() method, it must "
1866
+ "return an object of type %s" % (self, self.__class__)
1867
+ )
1868
+ return tt
1869
+
1870
+ def _gen_dialect_impl(self, dialect: Dialect) -> TypeEngine[_T]:
1871
+ if dialect.name in self._variant_mapping:
1872
+ adapted = dialect.type_descriptor(
1873
+ self._variant_mapping[dialect.name]
1874
+ )
1875
+ else:
1876
+ adapted = dialect.type_descriptor(self)
1877
+ if adapted is not self:
1878
+ return adapted
1879
+
1880
+ # otherwise adapt the impl type, link
1881
+ # to a copy of this TypeDecorator and return
1882
+ # that.
1883
+ typedesc = self.load_dialect_impl(dialect).dialect_impl(dialect)
1884
+ tt = self._copy_with_check()
1885
+ tt.impl = tt.impl_instance = typedesc
1886
+ return tt
1887
+
1888
+ def _with_collation(
1889
+ self, collation: str, collation_schema: Optional[str] = None
1890
+ ) -> Self:
1891
+ tt = self._copy_with_check()
1892
+ tt.impl = tt.impl_instance = self.impl_instance._with_collation(
1893
+ collation, collation_schema
1894
+ )
1895
+ return tt
1896
+
1897
+ @util.ro_non_memoized_property
1898
+ def _type_affinity(self) -> Optional[Type[TypeEngine[Any]]]:
1899
+ return self.impl_instance._type_affinity
1900
+
1901
+ def _set_parent(
1902
+ self, parent: SchemaEventTarget, outer: bool = False, **kw: Any
1903
+ ) -> None:
1904
+ """Support SchemaEventTarget"""
1905
+
1906
+ super()._set_parent(parent)
1907
+
1908
+ if not outer and isinstance(self.impl_instance, SchemaEventTarget):
1909
+ self.impl_instance._set_parent(parent, outer=False, **kw)
1910
+
1911
+ def _set_parent_with_dispatch(
1912
+ self, parent: SchemaEventTarget, **kw: Any
1913
+ ) -> None:
1914
+ """Support SchemaEventTarget"""
1915
+
1916
+ super()._set_parent_with_dispatch(parent, outer=True, **kw)
1917
+
1918
+ if isinstance(self.impl_instance, SchemaEventTarget):
1919
+ self.impl_instance._set_parent_with_dispatch(parent)
1920
+
1921
+ def type_engine(self, dialect: Dialect) -> TypeEngine[Any]:
1922
+ """Return a dialect-specific :class:`.TypeEngine` instance
1923
+ for this :class:`.TypeDecorator`.
1924
+
1925
+ In most cases this returns a dialect-adapted form of
1926
+ the :class:`.TypeEngine` type represented by ``self.impl``.
1927
+ Makes usage of :meth:`dialect_impl`.
1928
+ Behavior can be customized here by overriding
1929
+ :meth:`load_dialect_impl`.
1930
+
1931
+ """
1932
+ adapted = dialect.type_descriptor(self)
1933
+ if not isinstance(adapted, type(self)):
1934
+ return adapted
1935
+ else:
1936
+ return self.load_dialect_impl(dialect)
1937
+
1938
+ def load_dialect_impl(self, dialect: Dialect) -> TypeEngine[Any]:
1939
+ """Return a :class:`.TypeEngine` object corresponding to a dialect.
1940
+
1941
+ This is an end-user override hook that can be used to provide
1942
+ differing types depending on the given dialect. It is used
1943
+ by the :class:`.TypeDecorator` implementation of :meth:`type_engine`
1944
+ to help determine what type should ultimately be returned
1945
+ for a given :class:`.TypeDecorator`.
1946
+
1947
+ By default returns ``self.impl``.
1948
+
1949
+ """
1950
+ return self.impl_instance
1951
+
1952
+ def _unwrapped_dialect_impl(self, dialect: Dialect) -> TypeEngine[Any]:
1953
+ """Return the 'unwrapped' dialect impl for this type.
1954
+
1955
+ This is used by the :meth:`.DefaultDialect.set_input_sizes`
1956
+ method.
1957
+
1958
+ """
1959
+ # some dialects have a lookup for a TypeDecorator subclass directly.
1960
+ # postgresql.INTERVAL being the main example
1961
+ typ = self.dialect_impl(dialect)
1962
+
1963
+ # if we are still a type decorator, load the per-dialect switch
1964
+ # (such as what Variant uses), then get the dialect impl for that.
1965
+ if isinstance(typ, self.__class__):
1966
+ return typ.load_dialect_impl(dialect).dialect_impl(dialect)
1967
+ else:
1968
+ return typ
1969
+
1970
+ def __getattr__(self, key: str) -> Any:
1971
+ """Proxy all other undefined accessors to the underlying
1972
+ implementation."""
1973
+ return getattr(self.impl_instance, key)
1974
+
1975
+ def process_literal_param(
1976
+ self, value: Optional[_T], dialect: Dialect
1977
+ ) -> str:
1978
+ """Receive a literal parameter value to be rendered inline within
1979
+ a statement.
1980
+
1981
+ .. note::
1982
+
1983
+ This method is called during the **SQL compilation** phase of a
1984
+ statement, when rendering a SQL string. Unlike other SQL
1985
+ compilation methods, it is passed a specific Python value to be
1986
+ rendered as a string. However it should not be confused with the
1987
+ :meth:`_types.TypeDecorator.process_bind_param` method, which is
1988
+ the more typical method that processes the actual value passed to a
1989
+ particular parameter at statement execution time.
1990
+
1991
+ Custom subclasses of :class:`_types.TypeDecorator` should override
1992
+ this method to provide custom behaviors for incoming data values
1993
+ that are in the special case of being rendered as literals.
1994
+
1995
+ The returned string will be rendered into the output string.
1996
+
1997
+ """
1998
+ raise NotImplementedError()
1999
+
2000
+ def process_bind_param(self, value: Optional[_T], dialect: Dialect) -> Any:
2001
+ """Receive a bound parameter value to be converted.
2002
+
2003
+ Custom subclasses of :class:`_types.TypeDecorator` should override
2004
+ this method to provide custom behaviors for incoming data values.
2005
+ This method is called at **statement execution time** and is passed
2006
+ the literal Python data value which is to be associated with a bound
2007
+ parameter in the statement.
2008
+
2009
+ The operation could be anything desired to perform custom
2010
+ behavior, such as transforming or serializing data.
2011
+ This could also be used as a hook for validating logic.
2012
+
2013
+ :param value: Data to operate upon, of any type expected by
2014
+ this method in the subclass. Can be ``None``.
2015
+ :param dialect: the :class:`.Dialect` in use.
2016
+
2017
+ .. seealso::
2018
+
2019
+ :ref:`types_typedecorator`
2020
+
2021
+ :meth:`_types.TypeDecorator.process_result_value`
2022
+
2023
+ """
2024
+
2025
+ raise NotImplementedError()
2026
+
2027
+ def process_result_value(
2028
+ self, value: Optional[Any], dialect: Dialect
2029
+ ) -> Optional[_T]:
2030
+ """Receive a result-row column value to be converted.
2031
+
2032
+ Custom subclasses of :class:`_types.TypeDecorator` should override
2033
+ this method to provide custom behaviors for data values
2034
+ being received in result rows coming from the database.
2035
+ This method is called at **result fetching time** and is passed
2036
+ the literal Python data value that's extracted from a database result
2037
+ row.
2038
+
2039
+ The operation could be anything desired to perform custom
2040
+ behavior, such as transforming or deserializing data.
2041
+
2042
+ :param value: Data to operate upon, of any type expected by
2043
+ this method in the subclass. Can be ``None``.
2044
+ :param dialect: the :class:`.Dialect` in use.
2045
+
2046
+ .. seealso::
2047
+
2048
+ :ref:`types_typedecorator`
2049
+
2050
+ :meth:`_types.TypeDecorator.process_bind_param`
2051
+
2052
+
2053
+ """
2054
+
2055
+ raise NotImplementedError()
2056
+
2057
+ @util.memoized_property
2058
+ def _has_bind_processor(self) -> bool:
2059
+ """memoized boolean, check if process_bind_param is implemented.
2060
+
2061
+ Allows the base process_bind_param to raise
2062
+ NotImplementedError without needing to test an expensive
2063
+ exception throw.
2064
+
2065
+ """
2066
+
2067
+ return util.method_is_overridden(
2068
+ self, TypeDecorator.process_bind_param
2069
+ )
2070
+
2071
+ @util.memoized_property
2072
+ def _has_literal_processor(self) -> bool:
2073
+ """memoized boolean, check if process_literal_param is implemented."""
2074
+
2075
+ return util.method_is_overridden(
2076
+ self, TypeDecorator.process_literal_param
2077
+ )
2078
+
2079
+ def literal_processor(
2080
+ self, dialect: Dialect
2081
+ ) -> Optional[_LiteralProcessorType[_T]]:
2082
+ """Provide a literal processing function for the given
2083
+ :class:`.Dialect`.
2084
+
2085
+ This is the method that fulfills the :class:`.TypeEngine`
2086
+ contract for literal value conversion which normally occurs via
2087
+ the :meth:`_types.TypeEngine.literal_processor` method.
2088
+
2089
+ .. note::
2090
+
2091
+ User-defined subclasses of :class:`_types.TypeDecorator` should
2092
+ **not** implement this method, and should instead implement
2093
+ :meth:`_types.TypeDecorator.process_literal_param` so that the
2094
+ "inner" processing provided by the implementing type is maintained.
2095
+
2096
+ """
2097
+
2098
+ if self._has_literal_processor:
2099
+ process_literal_param = self.process_literal_param
2100
+ process_bind_param = None
2101
+ elif self._has_bind_processor:
2102
+ # use the bind processor if dont have a literal processor,
2103
+ # but we have an impl literal processor
2104
+ process_literal_param = None
2105
+ process_bind_param = self.process_bind_param
2106
+ else:
2107
+ process_literal_param = None
2108
+ process_bind_param = None
2109
+
2110
+ if process_literal_param is not None:
2111
+ impl_processor = self.impl_instance.literal_processor(dialect)
2112
+ if impl_processor:
2113
+ fixed_impl_processor = impl_processor
2114
+ fixed_process_literal_param = process_literal_param
2115
+
2116
+ def process(value: Any) -> str:
2117
+ return fixed_impl_processor(
2118
+ fixed_process_literal_param(value, dialect)
2119
+ )
2120
+
2121
+ else:
2122
+ fixed_process_literal_param = process_literal_param
2123
+
2124
+ def process(value: Any) -> str:
2125
+ return fixed_process_literal_param(value, dialect)
2126
+
2127
+ return process
2128
+
2129
+ elif process_bind_param is not None:
2130
+ impl_processor = self.impl_instance.literal_processor(dialect)
2131
+ if not impl_processor:
2132
+ return None
2133
+ else:
2134
+ fixed_impl_processor = impl_processor
2135
+ fixed_process_bind_param = process_bind_param
2136
+
2137
+ def process(value: Any) -> str:
2138
+ return fixed_impl_processor(
2139
+ fixed_process_bind_param(value, dialect)
2140
+ )
2141
+
2142
+ return process
2143
+ else:
2144
+ return self.impl_instance.literal_processor(dialect)
2145
+
2146
+ def bind_processor(
2147
+ self, dialect: Dialect
2148
+ ) -> Optional[_BindProcessorType[_T]]:
2149
+ """Provide a bound value processing function for the
2150
+ given :class:`.Dialect`.
2151
+
2152
+ This is the method that fulfills the :class:`.TypeEngine`
2153
+ contract for bound value conversion which normally occurs via
2154
+ the :meth:`_types.TypeEngine.bind_processor` method.
2155
+
2156
+ .. note::
2157
+
2158
+ User-defined subclasses of :class:`_types.TypeDecorator` should
2159
+ **not** implement this method, and should instead implement
2160
+ :meth:`_types.TypeDecorator.process_bind_param` so that the "inner"
2161
+ processing provided by the implementing type is maintained.
2162
+
2163
+ :param dialect: Dialect instance in use.
2164
+
2165
+ """
2166
+ if self._has_bind_processor:
2167
+ process_param = self.process_bind_param
2168
+ impl_processor = self.impl_instance.bind_processor(dialect)
2169
+ if impl_processor:
2170
+ fixed_impl_processor = impl_processor
2171
+ fixed_process_param = process_param
2172
+
2173
+ def process(value: Optional[_T]) -> Any:
2174
+ return fixed_impl_processor(
2175
+ fixed_process_param(value, dialect)
2176
+ )
2177
+
2178
+ else:
2179
+ fixed_process_param = process_param
2180
+
2181
+ def process(value: Optional[_T]) -> Any:
2182
+ return fixed_process_param(value, dialect)
2183
+
2184
+ return process
2185
+ else:
2186
+ return self.impl_instance.bind_processor(dialect)
2187
+
2188
+ @util.memoized_property
2189
+ def _has_result_processor(self) -> bool:
2190
+ """memoized boolean, check if process_result_value is implemented.
2191
+
2192
+ Allows the base process_result_value to raise
2193
+ NotImplementedError without needing to test an expensive
2194
+ exception throw.
2195
+
2196
+ """
2197
+
2198
+ return util.method_is_overridden(
2199
+ self, TypeDecorator.process_result_value
2200
+ )
2201
+
2202
+ def result_processor(
2203
+ self, dialect: Dialect, coltype: Any
2204
+ ) -> Optional[_ResultProcessorType[_T]]:
2205
+ """Provide a result value processing function for the given
2206
+ :class:`.Dialect`.
2207
+
2208
+ This is the method that fulfills the :class:`.TypeEngine`
2209
+ contract for bound value conversion which normally occurs via
2210
+ the :meth:`_types.TypeEngine.result_processor` method.
2211
+
2212
+ .. note::
2213
+
2214
+ User-defined subclasses of :class:`_types.TypeDecorator` should
2215
+ **not** implement this method, and should instead implement
2216
+ :meth:`_types.TypeDecorator.process_result_value` so that the
2217
+ "inner" processing provided by the implementing type is maintained.
2218
+
2219
+ :param dialect: Dialect instance in use.
2220
+ :param coltype: A SQLAlchemy data type
2221
+
2222
+ """
2223
+ if self._has_result_processor:
2224
+ process_value = self.process_result_value
2225
+ impl_processor = self.impl_instance.result_processor(
2226
+ dialect, coltype
2227
+ )
2228
+ if impl_processor:
2229
+ fixed_process_value = process_value
2230
+ fixed_impl_processor = impl_processor
2231
+
2232
+ def process(value: Any) -> Optional[_T]:
2233
+ return fixed_process_value(
2234
+ fixed_impl_processor(value), dialect
2235
+ )
2236
+
2237
+ else:
2238
+ fixed_process_value = process_value
2239
+
2240
+ def process(value: Any) -> Optional[_T]:
2241
+ return fixed_process_value(value, dialect)
2242
+
2243
+ return process
2244
+ else:
2245
+ return self.impl_instance.result_processor(dialect, coltype)
2246
+
2247
+ @util.memoized_property
2248
+ def _has_bind_expression(self) -> bool:
2249
+ return (
2250
+ util.method_is_overridden(self, TypeDecorator.bind_expression)
2251
+ or self.impl_instance._has_bind_expression
2252
+ )
2253
+
2254
+ def bind_expression(
2255
+ self, bindparam: BindParameter[_T]
2256
+ ) -> Optional[ColumnElement[_T]]:
2257
+ """Given a bind value (i.e. a :class:`.BindParameter` instance),
2258
+ return a SQL expression which will typically wrap the given parameter.
2259
+
2260
+ .. note::
2261
+
2262
+ This method is called during the **SQL compilation** phase of a
2263
+ statement, when rendering a SQL string. It is **not** necessarily
2264
+ called against specific values, and should not be confused with the
2265
+ :meth:`_types.TypeDecorator.process_bind_param` method, which is
2266
+ the more typical method that processes the actual value passed to a
2267
+ particular parameter at statement execution time.
2268
+
2269
+ Subclasses of :class:`_types.TypeDecorator` can override this method
2270
+ to provide custom bind expression behavior for the type. This
2271
+ implementation will **replace** that of the underlying implementation
2272
+ type.
2273
+
2274
+ """
2275
+ return self.impl_instance.bind_expression(bindparam)
2276
+
2277
+ @util.memoized_property
2278
+ def _has_column_expression(self) -> bool:
2279
+ """memoized boolean, check if column_expression is implemented.
2280
+
2281
+ Allows the method to be skipped for the vast majority of expression
2282
+ types that don't use this feature.
2283
+
2284
+ """
2285
+
2286
+ return (
2287
+ util.method_is_overridden(self, TypeDecorator.column_expression)
2288
+ or self.impl_instance._has_column_expression
2289
+ )
2290
+
2291
+ def column_expression(
2292
+ self, column: ColumnElement[_T]
2293
+ ) -> Optional[ColumnElement[_T]]:
2294
+ """Given a SELECT column expression, return a wrapping SQL expression.
2295
+
2296
+ .. note::
2297
+
2298
+ This method is called during the **SQL compilation** phase of a
2299
+ statement, when rendering a SQL string. It is **not** called
2300
+ against specific values, and should not be confused with the
2301
+ :meth:`_types.TypeDecorator.process_result_value` method, which is
2302
+ the more typical method that processes the actual value returned
2303
+ in a result row subsequent to statement execution time.
2304
+
2305
+ Subclasses of :class:`_types.TypeDecorator` can override this method
2306
+ to provide custom column expression behavior for the type. This
2307
+ implementation will **replace** that of the underlying implementation
2308
+ type.
2309
+
2310
+ See the description of :meth:`_types.TypeEngine.column_expression`
2311
+ for a complete description of the method's use.
2312
+
2313
+ """
2314
+
2315
+ return self.impl_instance.column_expression(column)
2316
+
2317
+ def coerce_compared_value(
2318
+ self, op: Optional[OperatorType], value: Any
2319
+ ) -> Any:
2320
+ """Suggest a type for a 'coerced' Python value in an expression.
2321
+
2322
+ By default, returns self. This method is called by
2323
+ the expression system when an object using this type is
2324
+ on the left or right side of an expression against a plain Python
2325
+ object which does not yet have a SQLAlchemy type assigned::
2326
+
2327
+ expr = table.c.somecolumn + 35
2328
+
2329
+ Where above, if ``somecolumn`` uses this type, this method will
2330
+ be called with the value ``operator.add``
2331
+ and ``35``. The return value is whatever SQLAlchemy type should
2332
+ be used for ``35`` for this particular operation.
2333
+
2334
+ """
2335
+ return self
2336
+
2337
+ def copy(self, **kw: Any) -> Self:
2338
+ """Produce a copy of this :class:`.TypeDecorator` instance.
2339
+
2340
+ This is a shallow copy and is provided to fulfill part of
2341
+ the :class:`.TypeEngine` contract. It usually does not
2342
+ need to be overridden unless the user-defined :class:`.TypeDecorator`
2343
+ has local state that should be deep-copied.
2344
+
2345
+ """
2346
+
2347
+ instance = self.__class__.__new__(self.__class__)
2348
+ instance.__dict__.update(self.__dict__)
2349
+ return instance
2350
+
2351
+ def get_dbapi_type(self, dbapi: DBAPIModule) -> Optional[Any]:
2352
+ """Return the DBAPI type object represented by this
2353
+ :class:`.TypeDecorator`.
2354
+
2355
+ By default this calls upon :meth:`.TypeEngine.get_dbapi_type` of the
2356
+ underlying "impl".
2357
+ """
2358
+ return self.impl_instance.get_dbapi_type(dbapi)
2359
+
2360
+ def compare_values(self, x: Any, y: Any) -> bool:
2361
+ """Given two values, compare them for equality.
2362
+
2363
+ By default this calls upon :meth:`.TypeEngine.compare_values`
2364
+ of the underlying "impl", which in turn usually
2365
+ uses the Python equals operator ``==``.
2366
+
2367
+ This function is used by the ORM to compare
2368
+ an original-loaded value with an intercepted
2369
+ "changed" value, to determine if a net change
2370
+ has occurred.
2371
+
2372
+ """
2373
+ return self.impl_instance.compare_values(x, y)
2374
+
2375
+ # mypy property bug
2376
+ @property
2377
+ def sort_key_function(self) -> Optional[Callable[[Any], Any]]: # type: ignore[override] # noqa: E501
2378
+ return self.impl_instance.sort_key_function
2379
+
2380
+ def repr_struct(self) -> util.GenericRepr:
2381
+ """Return a :class:`.GenericRepr` object representing this type.
2382
+
2383
+ For TypeDecorator, this returns a repr structure based on the
2384
+ impl instance but with the TypeDecorator's class name.
2385
+
2386
+ .. versionadded:: 2.1
2387
+
2388
+ """
2389
+ return self.impl_instance.repr_struct().set_class_name(
2390
+ self.__class__.__name__
2391
+ )
2392
+
2393
+
2394
+ class Variant(TypeDecorator[_T]):
2395
+ """deprecated. symbol is present for backwards-compatibility with
2396
+ workaround recipes, however this actual type should not be used.
2397
+
2398
+ """
2399
+
2400
+ def __init__(self, *arg: Any, **kw: Any):
2401
+ raise NotImplementedError(
2402
+ "Variant is no longer used in SQLAlchemy; this is a "
2403
+ "placeholder symbol for backwards compatibility."
2404
+ )
2405
+
2406
+
2407
+ @overload
2408
+ def to_instance(
2409
+ typeobj: Union[Type[_TE], _TE], *arg: Any, **kw: Any
2410
+ ) -> _TE: ...
2411
+
2412
+
2413
+ @overload
2414
+ def to_instance(typeobj: None, *arg: Any, **kw: Any) -> TypeEngine[None]: ...
2415
+
2416
+
2417
+ def to_instance(
2418
+ typeobj: Union[Type[_TE], _TE, None], *arg: Any, **kw: Any
2419
+ ) -> Union[_TE, TypeEngine[None]]:
2420
+ if typeobj is None:
2421
+ return NULLTYPE
2422
+
2423
+ if callable(typeobj):
2424
+ return typeobj(*arg, **kw)
2425
+ else:
2426
+ return typeobj
2427
+
2428
+
2429
+ def adapt_type(
2430
+ typeobj: _TypeEngineArgument[Any],
2431
+ colspecs: Mapping[Type[Any], Type[TypeEngine[Any]]],
2432
+ ) -> TypeEngine[Any]:
2433
+ typeobj = to_instance(typeobj)
2434
+ for t in typeobj.__class__.__mro__[0:-1]:
2435
+ try:
2436
+ impltype = colspecs[t]
2437
+ break
2438
+ except KeyError:
2439
+ pass
2440
+ else:
2441
+ # couldn't adapt - so just return the type itself
2442
+ # (it may be a user-defined type)
2443
+ return typeobj
2444
+ # if we adapted the given generic type to a database-specific type,
2445
+ # but it turns out the originally given "generic" type
2446
+ # is actually a subclass of our resulting type, then we were already
2447
+ # given a more specific type than that required; so use that.
2448
+ if issubclass(typeobj.__class__, impltype):
2449
+ return typeobj
2450
+ return typeobj.adapt(impltype)