-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathtype_api.py
More file actions
2446 lines (1847 loc) · 86.3 KB
/
type_api.py
File metadata and controls
2446 lines (1847 loc) · 86.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# sql/type_api.py
# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: https://www.opensource.org/licenses/mit-license.php
"""Base types API."""
from __future__ import annotations
from enum import Enum
import typing
from typing import Any
from typing import Callable
from typing import cast
from typing import ClassVar
from typing import Dict
from typing import Generic
from typing import Mapping
from typing import Optional
from typing import overload
from typing import Protocol
from typing import Sequence
from typing import Tuple
from typing import Type
from typing import TYPE_CHECKING
from typing import TypedDict
from typing import TypeGuard
from typing import TypeVar
from typing import Union
from sqlalchemy.util.typing import _MatchedOnType
from .base import SchemaEventTarget
from .cache_key import CacheConst
from .cache_key import NO_CACHE
from .operators import _OPERATOR_CLASSES
from .operators import ColumnOperators
from .operators import custom_op
from .operators import OperatorClass
from .visitors import Visitable
from .. import exc
from .. import util
from ..util.typing import Self
# these are back-assigned by sqltypes.
if typing.TYPE_CHECKING:
from ._typing import _TypeEngineArgument
from .elements import BindParameter
from .elements import ColumnElement
from .operators import OperatorType
from .sqltypes import _resolve_value_to_type as _resolve_value_to_type
from .sqltypes import BOOLEANTYPE as BOOLEANTYPE # noqa: F401
from .sqltypes import INDEXABLE as INDEXABLE # noqa: F401
from .sqltypes import INTEGERTYPE as INTEGERTYPE # noqa: F401
from .sqltypes import MATCHTYPE as MATCHTYPE # noqa: F401
from .sqltypes import NULLTYPE as NULLTYPE
from .sqltypes import NUMERICTYPE as NUMERICTYPE # noqa: F401
from .sqltypes import STRINGTYPE as STRINGTYPE # noqa: F401
from .sqltypes import TABLEVALUE as TABLEVALUE # noqa: F401
from ..engine.interfaces import DBAPIModule
from ..engine.interfaces import Dialect
_T = TypeVar("_T", bound=Any)
_T_co = TypeVar("_T_co", bound=Any, covariant=True)
_T_con = TypeVar("_T_con", bound=Any, contravariant=True)
_O = TypeVar("_O", bound=object)
_TE = TypeVar("_TE", bound="TypeEngine[Any]")
_CT = TypeVar("_CT", bound=Any)
_RT = TypeVar("_RT", bound=Any)
class _NoValueInList(Enum):
NO_VALUE_IN_LIST = 0
"""indicates we are trying to determine the type of an expression
against an empty list."""
_NO_VALUE_IN_LIST = _NoValueInList.NO_VALUE_IN_LIST
class _LiteralProcessorType(Protocol[_T_co]):
def __call__(self, value: Any) -> str: ...
class _BindProcessorType(Protocol[_T_con]):
def __call__(self, value: Optional[_T_con]) -> Any: ...
class _ResultProcessorType(Protocol[_T_co]):
def __call__(self, value: Any) -> Optional[_T_co]: ...
class _SentinelProcessorType(Protocol[_T_co]):
def __call__(self, value: Any) -> Optional[_T_co]: ...
class _BaseTypeMemoDict(TypedDict):
impl: TypeEngine[Any]
result: Dict[Any, Optional[_ResultProcessorType[Any]]]
class _TypeMemoDict(_BaseTypeMemoDict, total=False):
literal: Optional[_LiteralProcessorType[Any]]
bind: Optional[_BindProcessorType[Any]]
sentinel: Optional[_SentinelProcessorType[Any]]
custom: Dict[Any, object]
class _ComparatorFactory(Protocol[_T]):
def __call__(
self, expr: ColumnElement[_T]
) -> TypeEngine.Comparator[_T]: ...
class TypeEngine(Visitable, Generic[_T]):
"""The ultimate base class for all SQL datatypes.
Common subclasses of :class:`.TypeEngine` include
:class:`.String`, :class:`.Integer`, and :class:`.Boolean`.
For an overview of the SQLAlchemy typing system, see
:ref:`types_toplevel`.
.. seealso::
:ref:`types_toplevel`
"""
_sqla_type = True
_isnull = False
_is_tuple_type = False
_is_table_value = False
_is_array = False
_is_type_decorator = False
render_bind_cast = False
"""Render bind casts for :attr:`.BindTyping.RENDER_CASTS` mode.
If True, this type (usually a dialect level impl type) signals
to the compiler that a cast should be rendered around a bound parameter
for this type.
.. versionadded:: 2.0
.. seealso::
:class:`.BindTyping`
"""
render_literal_cast = False
"""render casts when rendering a value as an inline literal,
e.g. with :meth:`.TypeEngine.literal_processor`.
.. versionadded:: 2.0
"""
operator_classes: ClassVar[OperatorClass] = OperatorClass.UNSPECIFIED
"""Indicate categories of operators that should be available on this type.
.. versionadded:: 2.1
.. seealso::
:class:`.OperatorClass`
"""
class Comparator(
ColumnOperators,
Generic[_CT],
):
"""Base class for custom comparison operations defined at the
type level. See :attr:`.TypeEngine.comparator_factory`.
"""
__slots__ = "expr", "type"
expr: ColumnElement[_CT]
type: TypeEngine[_CT]
def __clause_element__(self) -> ColumnElement[_CT]:
return self.expr
def __init__(self, expr: ColumnElement[_CT]):
self.expr = expr
self.type = expr.type
def __reduce__(self) -> Any:
return self.__class__, (self.expr,)
@util.preload_module("sqlalchemy.sql.default_comparator")
def _resolve_operator_lookup(self, op: OperatorType) -> Tuple[
Callable[..., "ColumnElement[Any]"],
util.immutabledict[
str, Union["OperatorType", Callable[..., "ColumnElement[Any]"]]
],
]:
default_comparator = util.preloaded.sql_default_comparator
op_fn, addtl_kw = default_comparator.operator_lookup[op.__name__]
if op_fn is default_comparator._custom_op_operate:
if TYPE_CHECKING:
assert isinstance(op, custom_op)
operator_class = op.operator_class
else:
try:
operator_class = _OPERATOR_CLASSES[op]
except KeyError:
operator_class = OperatorClass.UNSPECIFIED
if not operator_class & self.type.operator_classes:
if self.type.operator_classes is OperatorClass.UNSPECIFIED:
util.warn_deprecated(
f"Type object {self.type.__class__} does not refer "
"to an OperatorClass in its operator_classes "
"attribute. This attribute will be required in a "
"future release.",
"2.1",
)
else:
if isinstance(op, custom_op):
op_description = f"custom operator {op.opstring!r}"
else:
op_description = f"operator {op.__name__!r}"
util.warn_deprecated(
f"Type object {self.type.__class__!r} does not "
"include "
f"{op_description} in its operator classes. "
"Using built-in operators (not including custom or "
"overridden operators) outside of "
"a type's stated operator classes is deprecated and "
"will raise InvalidRequestError in a future release",
"2.1",
)
return op_fn, addtl_kw
@overload
def operate(
self,
op: OperatorType,
*other: Any,
result_type: Type[TypeEngine[_RT]],
**kwargs: Any,
) -> ColumnElement[_RT]: ...
@overload
def operate(
self, op: OperatorType, *other: Any, **kwargs: Any
) -> ColumnElement[_CT]: ...
def operate(
self, op: OperatorType, *other: Any, **kwargs: Any
) -> ColumnElement[Any]:
op_fn, addtl_kw = self._resolve_operator_lookup(op)
if kwargs:
addtl_kw = addtl_kw.union(kwargs)
return op_fn(self.expr, op, *other, **addtl_kw)
def reverse_operate(
self, op: OperatorType, other: Any, **kwargs: Any
) -> ColumnElement[_CT]:
op_fn, addtl_kw = self._resolve_operator_lookup(op)
if kwargs:
addtl_kw = addtl_kw.union(kwargs)
return op_fn(self.expr, op, other, reverse=True, **addtl_kw)
def _adapt_expression(
self,
op: OperatorType,
other_comparator: TypeEngine.Comparator[Any],
) -> Tuple[OperatorType, TypeEngine[Any]]:
"""evaluate the return type of <self> <op> <othertype>,
and apply any adaptations to the given operator.
This method determines the type of a resulting binary expression
given two source types and an operator. For example, two
:class:`_schema.Column` objects, both of the type
:class:`.Integer`, will
produce a :class:`.BinaryExpression` that also has the type
:class:`.Integer` when compared via the addition (``+``) operator.
However, using the addition operator with an :class:`.Integer`
and a :class:`.Date` object will produce a :class:`.Date`, assuming
"days delta" behavior by the database (in reality, most databases
other than PostgreSQL don't accept this particular operation).
The method returns a tuple of the form <operator>, <type>.
The resulting operator and type will be those applied to the
resulting :class:`.BinaryExpression` as the final operator and the
right-hand side of the expression.
Note that only a subset of operators make usage of
:meth:`._adapt_expression`,
including math operators and user-defined operators, but not
boolean comparison or special SQL keywords like MATCH or BETWEEN.
"""
return op, self.type
hashable = True
"""Flag, if False, means values from this type aren't hashable.
Used by the ORM when uniquing result lists.
"""
comparator_factory: _ComparatorFactory[Any] = Comparator
"""A :class:`.TypeEngine.Comparator` class which will apply
to operations performed by owning :class:`_expression.ColumnElement`
objects.
The :attr:`.comparator_factory` attribute is a hook consulted by
the core expression system when column and SQL expression operations
are performed. When a :class:`.TypeEngine.Comparator` class is
associated with this attribute, it allows custom re-definition of
all existing operators, as well as definition of new operators.
Existing operators include those provided by Python operator overloading
such as :meth:`.operators.ColumnOperators.__add__` and
:meth:`.operators.ColumnOperators.__eq__`,
those provided as standard
attributes of :class:`.operators.ColumnOperators` such as
:meth:`.operators.ColumnOperators.like`
and :meth:`.operators.ColumnOperators.in_`.
Rudimentary usage of this hook is allowed through simple subclassing
of existing types, or alternatively by using :class:`.TypeDecorator`.
See the documentation section :ref:`types_operators` for examples.
"""
sort_key_function: Optional[Callable[[Any], Any]] = None
"""A sorting function that can be passed as the key to sorted.
The default value of ``None`` indicates that the values stored by
this type are self-sorting.
"""
should_evaluate_none: bool = False
"""If True, the Python constant ``None`` is considered to be handled
explicitly by this type.
The ORM uses this flag to indicate that a positive value of ``None``
is passed to the column in an INSERT statement, rather than omitting
the column from the INSERT statement which has the effect of firing
off column-level defaults. It also allows types which have special
behavior for Python None, such as a JSON type, to indicate that
they'd like to handle the None value explicitly.
To set this flag on an existing type, use the
:meth:`.TypeEngine.evaluates_none` method.
.. seealso::
:meth:`.TypeEngine.evaluates_none`
"""
_variant_mapping: util.immutabledict[str, TypeEngine[Any]] = (
util.EMPTY_DICT
)
def evaluates_none(self) -> Self:
"""Return a copy of this type which has the
:attr:`.should_evaluate_none` flag set to True.
E.g.::
Table(
"some_table",
metadata,
Column(
String(50).evaluates_none(),
nullable=True,
server_default="no value",
),
)
The ORM uses this flag to indicate that a positive value of ``None``
is passed to the column in an INSERT statement, rather than omitting
the column from the INSERT statement which has the effect of firing
off column-level defaults. It also allows for types which have
special behavior associated with the Python None value to indicate
that the value doesn't necessarily translate into SQL NULL; a
prime example of this is a JSON type which may wish to persist the
JSON value ``'null'``.
In all cases, the actual NULL SQL value can be always be
persisted in any column by using
the :obj:`_expression.null` SQL construct in an INSERT statement
or associated with an ORM-mapped attribute.
.. note::
The "evaluates none" flag does **not** apply to a value
of ``None`` passed to :paramref:`_schema.Column.default` or
:paramref:`_schema.Column.server_default`; in these cases,
``None``
still means "no default".
.. seealso::
:ref:`session_forcing_null` - in the ORM documentation
:paramref:`.postgresql.JSON.none_as_null` - PostgreSQL JSON
interaction with this flag.
:attr:`.TypeEngine.should_evaluate_none` - class-level flag
"""
typ = self.copy()
typ.should_evaluate_none = True
return typ
def copy(self, **kw: Any) -> Self:
return self.adapt(self.__class__)
def copy_value(self, value: Any) -> Any:
return value
def literal_processor(
self, dialect: Dialect
) -> Optional[_LiteralProcessorType[_T]]:
"""Return a conversion function for processing literal values that are
to be rendered directly without using binds.
This function is used when the compiler makes use of the
"literal_binds" flag, typically used in DDL generation as well
as in certain scenarios where backends don't accept bound parameters.
Returns a callable which will receive a literal Python value
as the sole positional argument and will return a string representation
to be rendered in a SQL statement.
.. tip::
This method is only called relative to a **dialect specific type
object**, which is often **private to a dialect in use** and is not
the same type object as the public facing one, which means it's not
feasible to subclass a :class:`.types.TypeEngine` class in order to
provide an alternate :meth:`_types.TypeEngine.literal_processor`
method, unless subclassing the :class:`_types.UserDefinedType`
class explicitly.
To provide alternate behavior for
:meth:`_types.TypeEngine.literal_processor`, implement a
:class:`_types.TypeDecorator` class and provide an implementation
of :meth:`_types.TypeDecorator.process_literal_param`.
.. seealso::
:ref:`types_typedecorator`
"""
return None
def bind_processor(
self, dialect: Dialect
) -> Optional[_BindProcessorType[_T]]:
"""Return a conversion function for processing bind values.
Returns a callable which will receive a bind parameter value
as the sole positional argument and will return a value to
send to the DB-API.
If processing is not necessary, the method should return ``None``.
.. tip::
This method is only called relative to a **dialect specific type
object**, which is often **private to a dialect in use** and is not
the same type object as the public facing one, which means it's not
feasible to subclass a :class:`.types.TypeEngine` class in order to
provide an alternate :meth:`_types.TypeEngine.bind_processor`
method, unless subclassing the :class:`_types.UserDefinedType`
class explicitly.
To provide alternate behavior for
:meth:`_types.TypeEngine.bind_processor`, implement a
:class:`_types.TypeDecorator` class and provide an implementation
of :meth:`_types.TypeDecorator.process_bind_param`.
.. seealso::
:ref:`types_typedecorator`
:param dialect: Dialect instance in use.
"""
return None
def result_processor(
self, dialect: Dialect, coltype: object
) -> Optional[_ResultProcessorType[_T]]:
"""Return a conversion function for processing result row values.
Returns a callable which will receive a result row column
value as the sole positional argument and will return a value
to return to the user.
If processing is not necessary, the method should return ``None``.
.. tip::
This method is only called relative to a **dialect specific type
object**, which is often **private to a dialect in use** and is not
the same type object as the public facing one, which means it's not
feasible to subclass a :class:`.types.TypeEngine` class in order to
provide an alternate :meth:`_types.TypeEngine.result_processor`
method, unless subclassing the :class:`_types.UserDefinedType`
class explicitly.
To provide alternate behavior for
:meth:`_types.TypeEngine.result_processor`, implement a
:class:`_types.TypeDecorator` class and provide an implementation
of :meth:`_types.TypeDecorator.process_result_value`.
.. seealso::
:ref:`types_typedecorator`
:param dialect: Dialect instance in use.
:param coltype: DBAPI coltype argument received in cursor.description.
"""
return None
def column_expression(
self, colexpr: ColumnElement[_T]
) -> Optional[ColumnElement[_T]]:
"""Given a SELECT column expression, return a wrapping SQL expression.
This is typically a SQL function that wraps a column expression
as rendered in the columns clause of a SELECT statement.
It is used for special data types that require
columns to be wrapped in some special database function in order
to coerce the value before being sent back to the application.
It is the SQL analogue of the :meth:`.TypeEngine.result_processor`
method.
.. note:: The :func:`.TypeEngine.column_expression` method is applied
only to the **outermost columns clause** of a SELECT statement, that
is, the columns that are to be delivered directly into the returned
result rows. It does **not** apply to the columns clause inside
of subqueries. This necessarily avoids double conversions against
the column and only runs the conversion when ready to be returned
to the client.
This method is called during the **SQL compilation** phase of a
statement, when rendering a SQL string. It is **not** called
against specific values.
.. tip::
This method is only called relative to a **dialect specific type
object**, which is often **private to a dialect in use** and is not
the same type object as the public facing one, which means it's not
feasible to subclass a :class:`.types.TypeEngine` class in order to
provide an alternate :meth:`_types.TypeEngine.column_expression`
method, unless subclassing the :class:`_types.UserDefinedType`
class explicitly.
To provide alternate behavior for
:meth:`_types.TypeEngine.column_expression`, implement a
:class:`_types.TypeDecorator` class and provide an implementation
of :meth:`_types.TypeDecorator.column_expression`.
.. seealso::
:ref:`types_typedecorator`
.. seealso::
:ref:`types_sql_value_processing`
"""
return None
@util.memoized_property
def _has_column_expression(self) -> bool:
"""memoized boolean, check if column_expression is implemented.
Allows the method to be skipped for the vast majority of expression
types that don't use this feature.
"""
return (
self.__class__.column_expression.__code__
is not TypeEngine.column_expression.__code__
)
def bind_expression(
self, bindvalue: BindParameter[_T]
) -> Optional[ColumnElement[_T]]:
"""Given a bind value (i.e. a :class:`.BindParameter` instance),
return a SQL expression in its place.
This is typically a SQL function that wraps the existing bound
parameter within the statement. It is used for special data types
that require literals being wrapped in some special database function
in order to coerce an application-level value into a database-specific
format. It is the SQL analogue of the
:meth:`.TypeEngine.bind_processor` method.
This method is called during the **SQL compilation** phase of a
statement, when rendering a SQL string. It is **not** called
against specific values.
Note that this method, when implemented, should always return
the exact same structure, without any conditional logic, as it
may be used in an executemany() call against an arbitrary number
of bound parameter sets.
.. note::
This method is only called relative to a **dialect specific type
object**, which is often **private to a dialect in use** and is not
the same type object as the public facing one, which means it's not
feasible to subclass a :class:`.types.TypeEngine` class in order to
provide an alternate :meth:`_types.TypeEngine.bind_expression`
method, unless subclassing the :class:`_types.UserDefinedType`
class explicitly.
To provide alternate behavior for
:meth:`_types.TypeEngine.bind_expression`, implement a
:class:`_types.TypeDecorator` class and provide an implementation
of :meth:`_types.TypeDecorator.bind_expression`.
.. seealso::
:ref:`types_typedecorator`
.. seealso::
:ref:`types_sql_value_processing`
"""
return None
@util.memoized_property
def _has_bind_expression(self) -> bool:
"""memoized boolean, check if bind_expression is implemented.
Allows the method to be skipped for the vast majority of expression
types that don't use this feature.
"""
return util.method_is_overridden(self, TypeEngine.bind_expression)
@staticmethod
def _to_instance(cls_or_self: Union[Type[_TE], _TE]) -> _TE:
return to_instance(cls_or_self)
def compare_values(self, x: Any, y: Any) -> bool:
"""Compare two values for equality."""
return x == y # type: ignore[no-any-return]
def get_dbapi_type(self, dbapi: DBAPIModule) -> Optional[Any]:
"""Return the corresponding type object from the underlying DB-API, if
any.
This can be useful for calling ``setinputsizes()``, for example.
"""
return None
@property
def python_type(self) -> Type[Any]:
"""Return the Python type object expected to be returned
by instances of this type.
Basically, for those types which enforce a return type,
or are known across the board to do such for all common
DBAPIs (like ``int`` for example), will return that type.
By default the generic ``object`` type is returned.
Note that any type also accommodates NULL in SQL which
means you can also get back ``None`` from any type
in practice.
.. versionchanged:: 2.1 - The default implementation now returns
``object`` instead of raising ``NotImplementedError``.
"""
return object
def with_variant(
self,
type_: _TypeEngineArgument[Any],
*dialect_names: str,
) -> Self:
r"""Produce a copy of this type object that will utilize the given
type when applied to the dialect of the given name.
e.g.::
from sqlalchemy.types import String
from sqlalchemy.dialects import mysql
string_type = String()
string_type = string_type.with_variant(
mysql.VARCHAR(collation="foo"), "mysql", "mariadb"
)
The variant mapping indicates that when this type is
interpreted by a specific dialect, it will instead be
transmuted into the given type, rather than using the
primary type.
.. versionchanged:: 2.0 the :meth:`_types.TypeEngine.with_variant`
method now works with a :class:`_types.TypeEngine` object "in
place", returning a copy of the original type rather than returning
a wrapping object; the ``Variant`` class is no longer used.
:param type\_: a :class:`.TypeEngine` that will be selected
as a variant from the originating type, when a dialect
of the given name is in use.
:param \*dialect_names: one or more base names of the dialect which
uses this type. (i.e. ``'postgresql'``, ``'mysql'``, etc.)
.. versionchanged:: 2.0 multiple dialect names can be specified
for one variant.
.. seealso::
:ref:`types_with_variant` - illustrates the use of
:meth:`_types.TypeEngine.with_variant`.
"""
if not dialect_names:
raise exc.ArgumentError("At least one dialect name is required")
for dialect_name in dialect_names:
if dialect_name in self._variant_mapping:
raise exc.ArgumentError(
f"Dialect {dialect_name!r} is already present in "
f"the mapping for this {self!r}"
)
new_type = self.copy()
type_ = to_instance(type_)
if type_._variant_mapping:
raise exc.ArgumentError(
"can't pass a type that already has variants as a "
"dialect-level type to with_variant()"
)
new_type._variant_mapping = self._variant_mapping.union(
{dialect_name: type_ for dialect_name in dialect_names}
)
return new_type
def _resolve_for_literal(self, value: Any) -> Self:
"""adjust this type given a literal Python value that will be
stored in a bound parameter.
Used exclusively by _resolve_value_to_type().
.. versionadded:: 1.4.30 or 2.0
TODO: this should be part of public API
.. seealso::
:meth:`.TypeEngine._resolve_for_python_type`
"""
return self
def _resolve_for_python_type(
self,
python_type: Type[Any],
matched_on: _MatchedOnType,
matched_on_flattened: Type[Any],
) -> Optional[Self]:
"""given a Python type (e.g. ``int``, ``str``, etc. ) return an
instance of this :class:`.TypeEngine` that's appropriate for this type.
An additional argument ``matched_on`` is passed, which indicates an
entry from the ``__mro__`` of the given ``python_type`` that more
specifically matches how the caller located this :class:`.TypeEngine`
object. Such as, if a lookup of some kind links the ``int`` Python
type to the :class:`.Integer` SQL type, and the original object
was some custom subclass of ``int`` such as ``MyInt(int)``, the
arguments passed would be ``(MyInt, int)``.
If the given Python type does not correspond to this
:class:`.TypeEngine`, or the Python type is otherwise ambiguous, the
method should return None.
For simple cases, the method checks that the ``python_type``
and ``matched_on`` types are the same (i.e. not a subclass), and
returns self; for all other cases, it returns ``None``.
The initial use case here is for the ORM to link user-defined
Python standard library ``enum.Enum`` classes to the SQLAlchemy
:class:`.Enum` SQL type when constructing ORM Declarative mappings.
:param python_type: the Python type we want to use
:param matched_on: the Python type that led us to choose this
particular :class:`.TypeEngine` class, which would be a supertype
of ``python_type``. By default, the request is rejected if
``python_type`` doesn't match ``matched_on`` (None is returned).
.. versionadded:: 2.0.0b4
TODO: this should be part of public API
.. seealso::
:meth:`.TypeEngine._resolve_for_literal`
"""
if python_type is not matched_on_flattened:
return None
return self
def _with_collation(self, collation: str) -> Self:
"""set up error handling for the collate expression"""
raise NotImplementedError("this datatype does not support collation")
@util.ro_memoized_property
def _type_affinity(self) -> Optional[Type[TypeEngine[_T]]]:
"""Return a rudimental 'affinity' value expressing the general class
of type."""
typ = None
for t in self.__class__.__mro__:
if t is TypeEngine or TypeEngineMixin in t.__bases__:
return typ
elif issubclass(t, TypeEngine):
typ = t
else:
return self.__class__
@util.ro_memoized_property
def _generic_type_affinity(
self,
) -> Type[TypeEngine[_T]]:
best_camelcase = None
best_uppercase = None
if not isinstance(self, TypeEngine):
return self.__class__
for t in self.__class__.__mro__:
if (
t.__module__
in (
"sqlalchemy.sql.sqltypes",
"sqlalchemy.sql.type_api",
)
and issubclass(t, TypeEngine)
and TypeEngineMixin not in t.__bases__
and t not in (TypeEngine, TypeEngineMixin)
and t.__name__[0] != "_"
):
if t.__name__.isupper() and not best_uppercase:
best_uppercase = t
elif not t.__name__.isupper() and not best_camelcase:
best_camelcase = t
return (
best_camelcase
or best_uppercase
or cast("Type[TypeEngine[_T]]", NULLTYPE.__class__)
)
def as_generic(self, allow_nulltype: bool = False) -> TypeEngine[_T]:
"""
Return an instance of the generic type corresponding to this type
using heuristic rule. The method may be overridden if this
heuristic rule is not sufficient.
>>> from sqlalchemy.dialects.mysql import INTEGER
>>> INTEGER(display_width=4).as_generic()
Integer()
>>> from sqlalchemy.dialects.mysql import NVARCHAR
>>> NVARCHAR(length=100).as_generic()
Unicode(length=100)
.. versionadded:: 1.4.0b2
.. seealso::
:ref:`metadata_reflection_dbagnostic_types` - describes the
use of :meth:`_types.TypeEngine.as_generic` in conjunction with
the :meth:`_sql.DDLEvents.column_reflect` event, which is its
intended use.
"""
if (
not allow_nulltype
and self._generic_type_affinity == NULLTYPE.__class__
):
raise NotImplementedError(
"Default TypeEngine.as_generic() "
"heuristic method was unsuccessful for {}. A custom "
"as_generic() method must be implemented for this "
"type class.".format(
self.__class__.__module__ + "." + self.__class__.__name__
)
)
return util.constructor_copy(self, self._generic_type_affinity)
def dialect_impl(self, dialect: Dialect) -> TypeEngine[_T]:
"""Return a dialect-specific implementation for this
:class:`.TypeEngine`.
"""
try:
tm = dialect._type_memos[self]
except KeyError:
pass
else:
return tm["impl"]
return self._dialect_info(dialect)["impl"]
def _unwrapped_dialect_impl(self, dialect: Dialect) -> TypeEngine[_T]:
"""Return the 'unwrapped' dialect impl for this type.
For a type that applies wrapping logic (e.g. TypeDecorator), give
us the real, actual dialect-level type that is used.
This is used by TypeDecorator itself as well at least one case where
dialects need to check that a particular specific dialect-level
type is in use, within the :meth:`.DefaultDialect.set_input_sizes`
method.
"""
return self.dialect_impl(dialect)
def _cached_literal_processor(
self, dialect: Dialect
) -> Optional[_LiteralProcessorType[_T]]:
"""Return a dialect-specific literal processor for this type."""
try:
return dialect._type_memos[self]["literal"]
except KeyError:
pass
# avoid KeyError context coming into literal_processor() function
# raises
d = self._dialect_info(dialect)
d["literal"] = lp = d["impl"].literal_processor(dialect)
return lp
def _cached_bind_processor(
self, dialect: Dialect
) -> Optional[_BindProcessorType[_T]]:
"""Return a dialect-specific bind processor for this type."""
try:
return dialect._type_memos[self]["bind"]
except KeyError:
pass
# avoid KeyError context coming into bind_processor() function
# raises
d = self._dialect_info(dialect)
d["bind"] = bp = d["impl"].bind_processor(dialect)
return bp
def _cached_result_processor(
self, dialect: Dialect, coltype: Any
) -> Optional[_ResultProcessorType[_T]]:
"""Return a dialect-specific result processor for this type."""
try:
return dialect._type_memos[self]["result"][coltype]
except KeyError:
pass
# avoid KeyError context coming into result_processor() function
# raises