SQLAlchemy 2.0.47__cp313-cp313t-win32.whl

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