SQLAlchemy 2.0.36__cp313-cp313-win_amd64.whl

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