-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathsqltypes.py
More file actions
4093 lines (3115 loc) · 133 KB
/
sqltypes.py
File metadata and controls
4093 lines (3115 loc) · 133 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/sqltypes.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
# mypy: allow-untyped-defs, allow-untyped-calls
"""SQL specific types."""
from __future__ import annotations
import collections.abc as collections_abc
import datetime as dt
import decimal
import enum
import functools
import json
import pickle
from typing import Any
from typing import Callable
from typing import cast
from typing import Dict
from typing import Generic
from typing import get_args
from typing import Iterable
from typing import List
from typing import Literal
from typing import Mapping
from typing import Optional
from typing import overload
from typing import Sequence
from typing import Tuple
from typing import Type
from typing import TYPE_CHECKING
from typing import TypeAlias
from typing import Union
from uuid import UUID as _python_UUID
from . import coercions
from . import elements
from . import operators
from . import roles
from . import type_api
from .base import _NoArg
from .base import _NONE_NAME
from .base import NO_ARG
from .base import SchemaEventTarget
from .cache_key import HasCacheKey
from .elements import quoted_name
from .elements import Slice
from .elements import TypeCoerce as type_coerce # noqa
from .operators import OperatorClass
from .type_api import Emulated
from .type_api import NativeForEmulated # noqa
from .type_api import to_instance as to_instance
from .type_api import TypeDecorator as TypeDecorator
from .type_api import TypeEngine as TypeEngine
from .type_api import TypeEngineMixin
from .type_api import Variant # noqa
from .visitors import InternalTraversal
from .. import event
from .. import exc
from .. import inspection
from .. import util
from ..engine import processors
from ..util import deprecated_params
from ..util import langhelpers
from ..util import OrderedDict
from ..util import warn_deprecated
from ..util.typing import is_literal
from ..util.typing import is_pep695
from ..util.typing import TupleAny
from ..util.typing import TypeVar
if TYPE_CHECKING:
from ._typing import _ColumnExpressionArgument
from ._typing import _CreateDropBind
from ._typing import _TypeEngineArgument
from .elements import ColumnElement
from .operators import OperatorType
from .schema import MetaData
from .type_api import _BindProcessorType
from .type_api import _ComparatorFactory
from .type_api import _LiteralProcessorType
from .type_api import _ResultProcessorType
from ..engine.interfaces import Dialect
from ..util.typing import _MatchedOnType
_T = TypeVar("_T", bound=Any)
_JSON_VALUE: TypeAlias = (
str | int | bool | None | dict[str, "_JSON_VALUE"] | list["_JSON_VALUE"]
)
_T_JSON = TypeVar(
"_T_JSON",
bound=Any,
default=_JSON_VALUE,
)
_CT_JSON = TypeVar(
"_CT_JSON",
bound=Any,
default=_JSON_VALUE,
)
_CT = TypeVar("_CT", bound=Any)
_TE = TypeVar("_TE", bound=TypeEngine[Any])
_P = TypeVar("_P")
class HasExpressionLookup(TypeEngineMixin):
"""Mixin expression adaptations based on lookup tables.
These rules are currently used by the numeric, integer and date types
which have detailed cross-expression coercion rules.
"""
@property
def _expression_adaptations(self):
raise NotImplementedError()
class Comparator(TypeEngine.Comparator[_CT]):
__slots__ = ()
_blank_dict = util.EMPTY_DICT
def _adapt_expression(
self,
op: OperatorType,
other_comparator: TypeEngine.Comparator[Any],
) -> Tuple[OperatorType, TypeEngine[Any]]:
othertype = other_comparator.type._type_affinity
if TYPE_CHECKING:
assert isinstance(self.type, HasExpressionLookup)
lookup = self.type._expression_adaptations.get(
op, self._blank_dict
).get(othertype, self.type)
if lookup is othertype:
return (op, other_comparator.type)
elif lookup is self.type._type_affinity:
return (op, self.type)
else:
return (op, to_instance(lookup))
comparator_factory: _ComparatorFactory[Any] = Comparator
class Concatenable(TypeEngineMixin):
"""A mixin that marks a type as supporting 'concatenation',
typically strings."""
class Comparator(TypeEngine.Comparator[_T]):
__slots__ = ()
def _adapt_expression(
self,
op: OperatorType,
other_comparator: TypeEngine.Comparator[Any],
) -> Tuple[OperatorType, TypeEngine[Any]]:
if op is operators.add and isinstance(
other_comparator,
(Concatenable.Comparator, NullType.Comparator),
):
return operators.concat_op, self.expr.type
else:
return super()._adapt_expression(op, other_comparator)
comparator_factory: _ComparatorFactory[Any] = Comparator
class Indexable(TypeEngineMixin):
"""A mixin that marks a type as supporting indexing operations,
such as array or JSON structures.
"""
class Comparator(TypeEngine.Comparator[_T]):
__slots__ = ()
def _setup_getitem(self, index):
raise NotImplementedError()
def __getitem__(self, index):
(
adjusted_op,
adjusted_right_expr,
result_type,
) = self._setup_getitem(index)
return self.operate(
adjusted_op, adjusted_right_expr, result_type=result_type
)
comparator_factory: _ComparatorFactory[Any] = Comparator
class String(Concatenable, TypeEngine[str]):
"""The base for all string and character types.
In SQL, corresponds to VARCHAR.
The `length` field is usually required when the `String` type is
used within a CREATE TABLE statement, as VARCHAR requires a length
on most databases.
"""
__visit_name__ = "string"
operator_classes = OperatorClass.STRING
def __init__(
self,
length: Optional[int] = None,
collation: Optional[str] = None,
):
"""
Create a string-holding type.
:param length: optional, a length for the column for use in
DDL and CAST expressions. May be safely omitted if no ``CREATE
TABLE`` will be issued. Certain databases may require a
``length`` for use in DDL, and will raise an exception when
the ``CREATE TABLE`` DDL is issued if a ``VARCHAR``
with no length is included. Whether the value is
interpreted as bytes or characters is database specific.
:param collation: Optional, a column-level collation for
use in DDL and CAST expressions. Renders using the
COLLATE keyword supported by SQLite, MySQL, and PostgreSQL.
E.g.:
.. sourcecode:: pycon+sql
>>> from sqlalchemy import cast, select, String
>>> print(select(cast("some string", String(collation="utf8"))))
{printsql}SELECT CAST(:param_1 AS VARCHAR COLLATE utf8) AS anon_1
.. note::
In most cases, the :class:`.Unicode` or :class:`.UnicodeText`
datatypes should be used for a :class:`_schema.Column` that expects
to store non-ascii data. These datatypes will ensure that the
correct types are used on the database.
"""
self.length = length
self.collation = collation
def _with_collation(self, collation):
new_type = self.copy()
new_type.collation = collation
return new_type
def _resolve_for_literal(self, value):
# I was SO PROUD of my regex trick, but we dont need it.
# re.search(r"[^\u0000-\u007F]", value)
if value.isascii():
return _STRING
else:
return _UNICODE
def literal_processor(self, dialect):
def process(value):
value = value.replace("'", "''")
if dialect.identifier_preparer._double_percents:
value = value.replace("%", "%%")
return "'%s'" % value
return process
def bind_processor(
self, dialect: Dialect
) -> Optional[_BindProcessorType[str]]:
return None
def result_processor(
self, dialect: Dialect, coltype: object
) -> Optional[_ResultProcessorType[str]]:
return None
@property
def python_type(self):
return str
def get_dbapi_type(self, dbapi):
return dbapi.STRING
class Text(String):
"""A variably sized string type.
In SQL, usually corresponds to CLOB or TEXT. In general, TEXT objects
do not have a length; while some databases will accept a length
argument here, it will be rejected by others.
"""
__visit_name__ = "text"
class Unicode(String):
"""A variable length Unicode string type.
The :class:`.Unicode` type is a :class:`.String` subclass that assumes
input and output strings that may contain non-ASCII characters, and for
some backends implies an underlying column type that is explicitly
supporting of non-ASCII data, such as ``NVARCHAR`` on Oracle Database and
SQL Server. This will impact the output of ``CREATE TABLE`` statements and
``CAST`` functions at the dialect level.
The character encoding used by the :class:`.Unicode` type that is used to
transmit and receive data to the database is usually determined by the
DBAPI itself. All modern DBAPIs accommodate non-ASCII strings but may have
different methods of managing database encodings; if necessary, this
encoding should be configured as detailed in the notes for the target DBAPI
in the :ref:`dialect_toplevel` section.
In modern SQLAlchemy, use of the :class:`.Unicode` datatype does not
imply any encoding/decoding behavior within SQLAlchemy itself. In Python
3, all string objects are inherently Unicode capable, and SQLAlchemy
does not produce bytestring objects nor does it accommodate a DBAPI that
does not return Python Unicode objects in result sets for string values.
.. warning:: Some database backends, particularly SQL Server with pyodbc,
are known to have undesirable behaviors regarding data that is noted
as being of ``NVARCHAR`` type as opposed to ``VARCHAR``, including
datatype mismatch errors and non-use of indexes. See the section
on :meth:`.DialectEvents.do_setinputsizes` for background on working
around unicode character issues for backends like SQL Server with
pyodbc as well as cx_Oracle.
.. seealso::
:class:`.UnicodeText` - unlengthed textual counterpart
to :class:`.Unicode`.
:meth:`.DialectEvents.do_setinputsizes`
"""
__visit_name__ = "unicode"
class UnicodeText(Text):
"""An unbounded-length Unicode string type.
See :class:`.Unicode` for details on the unicode
behavior of this object.
Like :class:`.Unicode`, usage the :class:`.UnicodeText` type implies a
unicode-capable type being used on the backend, such as
``NCLOB``, ``NTEXT``.
"""
__visit_name__ = "unicode_text"
class Integer(HasExpressionLookup, TypeEngine[int]):
"""A type for ``int`` integers."""
__visit_name__ = "integer"
operator_classes = OperatorClass.INTEGER
if TYPE_CHECKING:
@util.ro_memoized_property
def _type_affinity(self) -> Type[Integer]: ...
def get_dbapi_type(self, dbapi):
return dbapi.NUMBER
@property
def python_type(self):
return int
def _resolve_for_literal(self, value):
if value.bit_length() >= 32:
return _BIGINTEGER
else:
return self
def literal_processor(self, dialect):
def process(value):
return str(int(value))
return process
@util.memoized_property
def _expression_adaptations(self):
return {
operators.add: {
Date: Date,
Integer: self.__class__,
Numeric: Numeric,
Float: Float,
},
operators.mul: {
Interval: Interval,
Integer: self.__class__,
Numeric: Numeric,
Float: Float,
},
operators.truediv: {
Integer: Numeric,
Numeric: Numeric,
Float: Float,
},
operators.floordiv: {Integer: self.__class__, Numeric: Numeric},
operators.sub: {
Integer: self.__class__,
Numeric: Numeric,
Float: Float,
},
}
class SmallInteger(Integer):
"""A type for smaller ``int`` integers.
Typically generates a ``SMALLINT`` in DDL, and otherwise acts like
a normal :class:`.Integer` on the Python side.
"""
__visit_name__ = "small_integer"
class BigInteger(Integer):
"""A type for bigger ``int`` integers.
Typically generates a ``BIGINT`` in DDL, and otherwise acts like
a normal :class:`.Integer` on the Python side.
"""
__visit_name__ = "big_integer"
_N = TypeVar("_N", bound=Union[decimal.Decimal, float])
class NumericCommon(HasExpressionLookup, TypeEngineMixin, Generic[_N]):
"""common mixin for the :class:`.Numeric` and :class:`.Float` types.
.. versionadded:: 2.1
"""
_default_decimal_return_scale = 10
operator_classes = OperatorClass.NUMERIC
if TYPE_CHECKING:
@util.ro_memoized_property
def _type_affinity(self) -> Type[Union[Numeric[_N], Float[_N]]]: ...
def __init__(
self,
*,
precision: Optional[int],
scale: Optional[int],
decimal_return_scale: Optional[int],
asdecimal: bool,
):
self.precision = precision
self.scale = scale
self.decimal_return_scale = decimal_return_scale
self.asdecimal = asdecimal
@property
def _effective_decimal_return_scale(self):
if self.decimal_return_scale is not None:
return self.decimal_return_scale
elif getattr(self, "scale", None) is not None:
return self.scale
else:
return self._default_decimal_return_scale
def get_dbapi_type(self, dbapi):
return dbapi.NUMBER
def literal_processor(self, dialect):
def process(value):
return str(value)
return process
@property
def python_type(self):
if self.asdecimal:
return decimal.Decimal
else:
return float
def bind_processor(self, dialect):
if dialect.supports_native_decimal:
return None
else:
return processors.to_float
@util.memoized_property
def _expression_adaptations(self):
return {
operators.mul: {
Interval: Interval,
Numeric: self.__class__,
Float: self.__class__,
Integer: self.__class__,
},
operators.truediv: {
Numeric: self.__class__,
Float: self.__class__,
Integer: self.__class__,
},
operators.add: {
Numeric: self.__class__,
Float: self.__class__,
Integer: self.__class__,
},
operators.sub: {
Numeric: self.__class__,
Float: self.__class__,
Integer: self.__class__,
},
}
class Numeric(NumericCommon[_N], TypeEngine[_N]):
"""Base for non-integer numeric types, such as
``NUMERIC``, ``FLOAT``, ``DECIMAL``, and other variants.
The :class:`.Numeric` datatype when used directly will render DDL
corresponding to precision numerics if available, such as
``NUMERIC(precision, scale)``. The :class:`.Float` subclass will
attempt to render a floating-point datatype such as ``FLOAT(precision)``.
:class:`.Numeric` returns Python ``decimal.Decimal`` objects by default,
based on the default value of ``True`` for the
:paramref:`.Numeric.asdecimal` parameter. If this parameter is set to
False, returned values are coerced to Python ``float`` objects.
The :class:`.Float` subtype, being more specific to floating point,
defaults the :paramref:`.Float.asdecimal` flag to False so that the
default Python datatype is ``float``.
.. note::
When using a :class:`.Numeric` datatype against a database type that
returns Python floating point values to the driver, the accuracy of the
decimal conversion indicated by :paramref:`.Numeric.asdecimal` may be
limited. The behavior of specific numeric/floating point datatypes
is a product of the SQL datatype in use, the Python :term:`DBAPI`
in use, as well as strategies that may be present within
the SQLAlchemy dialect in use. Users requiring specific precision/
scale are encouraged to experiment with the available datatypes
in order to determine the best results.
"""
__visit_name__ = "numeric"
@overload
def __init__(
self: Numeric[decimal.Decimal],
precision: Optional[int] = ...,
scale: Optional[int] = ...,
decimal_return_scale: Optional[int] = ...,
asdecimal: Literal[True] = ...,
): ...
@overload
def __init__(
self: Numeric[float],
precision: Optional[int] = ...,
scale: Optional[int] = ...,
decimal_return_scale: Optional[int] = ...,
asdecimal: Literal[False] = ...,
): ...
def __init__(
self,
precision: Optional[int] = None,
scale: Optional[int] = None,
decimal_return_scale: Optional[int] = None,
asdecimal: bool = True,
):
"""
Construct a Numeric.
:param precision: the numeric precision for use in DDL ``CREATE
TABLE``.
:param scale: the numeric scale for use in DDL ``CREATE TABLE``.
:param asdecimal: default True. Return whether or not
values should be sent as Python Decimal objects, or
as floats. Different DBAPIs send one or the other based on
datatypes - the Numeric type will ensure that return values
are one or the other across DBAPIs consistently.
:param decimal_return_scale: Default scale to use when converting
from floats to Python decimals. Floating point values will typically
be much longer due to decimal inaccuracy, and most floating point
database types don't have a notion of "scale", so by default the
float type looks for the first ten decimal places when converting.
Specifying this value will override that length. Types which
do include an explicit ".scale" value, such as the base
:class:`.Numeric` as well as the MySQL float types, will use the
value of ".scale" as the default for decimal_return_scale, if not
otherwise specified.
When using the ``Numeric`` type, care should be taken to ensure
that the asdecimal setting is appropriate for the DBAPI in use -
when Numeric applies a conversion from Decimal->float or float->
Decimal, this conversion incurs an additional performance overhead
for all result columns received.
DBAPIs that return Decimal natively (e.g. psycopg2) will have
better accuracy and higher performance with a setting of ``True``,
as the native translation to Decimal reduces the amount of floating-
point issues at play, and the Numeric type itself doesn't need
to apply any further conversions. However, another DBAPI which
returns floats natively *will* incur an additional conversion
overhead, and is still subject to floating point data loss - in
which case ``asdecimal=False`` will at least remove the extra
conversion overhead.
"""
super().__init__(
precision=precision,
scale=scale,
decimal_return_scale=decimal_return_scale,
asdecimal=asdecimal,
)
@property
def _type_affinity(self):
return Numeric
def result_processor(self, dialect, coltype):
if self.asdecimal:
if dialect.supports_native_decimal:
# we're a "numeric", DBAPI will give us Decimal directly
return None
else:
# we're a "numeric", DBAPI returns floats, convert.
return processors.to_decimal_processor_factory(
decimal.Decimal,
(
self.scale
if self.scale is not None
else self._default_decimal_return_scale
),
)
else:
if dialect.supports_native_decimal:
return processors.to_float
else:
return None
class Float(NumericCommon[_N], TypeEngine[_N]):
"""Type representing floating point types, such as ``FLOAT`` or ``REAL``.
This type returns Python ``float`` objects by default, unless the
:paramref:`.Float.asdecimal` flag is set to ``True``, in which case they
are coerced to ``decimal.Decimal`` objects.
When a :paramref:`.Float.precision` is not provided in a
:class:`_types.Float` type some backend may compile this type as
an 8 bytes / 64 bit float datatype. To use a 4 bytes / 32 bit float
datatype a precision <= 24 can usually be provided or the
:class:`_types.REAL` type can be used.
This is known to be the case in the PostgreSQL and MSSQL dialects
that render the type as ``FLOAT`` that's in both an alias of
``DOUBLE PRECISION``. Other third party dialects may have similar
behavior.
"""
__visit_name__ = "float"
@overload
def __init__(
self: Float[float],
precision: Optional[int] = ...,
asdecimal: Literal[False] = ...,
decimal_return_scale: Optional[int] = ...,
): ...
@overload
def __init__(
self: Float[decimal.Decimal],
precision: Optional[int] = ...,
asdecimal: Literal[True] = ...,
decimal_return_scale: Optional[int] = ...,
): ...
def __init__(
self: Float[_N],
precision: Optional[int] = None,
asdecimal: bool = False,
decimal_return_scale: Optional[int] = None,
):
r"""
Construct a Float.
:param precision: the numeric precision for use in DDL ``CREATE
TABLE``. Backends **should** attempt to ensure this precision
indicates a number of digits for the generic
:class:`_sqltypes.Float` datatype.
.. note:: For the Oracle Database backend, the
:paramref:`_sqltypes.Float.precision` parameter is not accepted
when rendering DDL, as Oracle Database does not support float precision
specified as a number of decimal places. Instead, use the
Oracle Database-specific :class:`_oracle.FLOAT` datatype and specify the
:paramref:`_oracle.FLOAT.binary_precision` parameter. This is new
in version 2.0 of SQLAlchemy.
To create a database agnostic :class:`_types.Float` that
separately specifies binary precision for Oracle Database, use
:meth:`_types.TypeEngine.with_variant` as follows::
from sqlalchemy import Column
from sqlalchemy import Float
from sqlalchemy.dialects import oracle
Column(
"float_data",
Float(5).with_variant(oracle.FLOAT(binary_precision=16), "oracle"),
)
:param asdecimal: the same flag as that of :class:`.Numeric`, but
defaults to ``False``. Note that setting this flag to ``True``
results in floating point conversion.
:param decimal_return_scale: Default scale to use when converting
from floats to Python decimals. Floating point values will typically
be much longer due to decimal inaccuracy, and most floating point
database types don't have a notion of "scale", so by default the
float type looks for the first ten decimal places when converting.
Specifying this value will override that length. Note that the
MySQL float types, which do include "scale", will use "scale"
as the default for decimal_return_scale, if not otherwise specified.
""" # noqa: E501
super().__init__(
precision=precision,
scale=None,
asdecimal=asdecimal,
decimal_return_scale=decimal_return_scale,
)
@property
def _type_affinity(self):
return Float
def result_processor(self, dialect, coltype):
if self.asdecimal:
return processors.to_decimal_processor_factory(
decimal.Decimal, self._effective_decimal_return_scale
)
elif dialect.supports_native_decimal:
return processors.to_float
else:
return None
class Double(Float[_N]):
"""A type for double ``FLOAT`` floating point types.
Typically generates a ``DOUBLE`` or ``DOUBLE_PRECISION`` in DDL,
and otherwise acts like a normal :class:`.Float` on the Python
side.
.. versionadded:: 2.0
"""
__visit_name__ = "double"
class _RenderISO8601NoT:
def _literal_processor_datetime(self, dialect):
return self._literal_processor_portion(dialect, None)
def _literal_processor_date(self, dialect):
return self._literal_processor_portion(dialect, 0)
def _literal_processor_time(self, dialect):
return self._literal_processor_portion(dialect, -1)
def _literal_processor_portion(self, dialect, _portion=None):
assert _portion in (None, 0, -1)
if _portion is not None:
def process(value):
return f"""'{value.isoformat().split("T")[_portion]}'"""
else:
def process(value):
return f"""'{value.isoformat().replace("T", " ")}'"""
return process
class DateTime(
_RenderISO8601NoT, HasExpressionLookup, TypeEngine[dt.datetime]
):
"""A type for ``datetime.datetime()`` objects.
Date and time types return objects from the Python ``datetime``
module. Most DBAPIs have built in support for the datetime
module, with the noted exception of SQLite. In the case of
SQLite, date and time types are stored as strings which are then
converted back to datetime objects when rows are returned.
For the time representation within the datetime type, some
backends include additional options, such as timezone support and
fractional seconds support. For fractional seconds, use the
dialect-specific datatype, such as :class:`.mysql.TIME`. For
timezone support, use at least the :class:`_types.TIMESTAMP` datatype,
if not the dialect-specific datatype object.
"""
__visit_name__ = "datetime"
operator_classes = OperatorClass.DATETIME
def __init__(self, timezone: bool = False):
"""Construct a new :class:`.DateTime`.
:param timezone: boolean. Indicates that the datetime type should
enable timezone support, if available on the
**base date/time-holding type only**. It is recommended
to make use of the :class:`_types.TIMESTAMP` datatype directly when
using this flag, as some databases include separate generic
date/time-holding types distinct from the timezone-capable
TIMESTAMP datatype, such as Oracle Database.
"""
self.timezone = timezone
def get_dbapi_type(self, dbapi):
return dbapi.DATETIME
def _resolve_for_literal(self, value):
with_timezone = value.tzinfo is not None
if with_timezone and not self.timezone:
return DATETIME_TIMEZONE
else:
return self
def literal_processor(self, dialect):
return self._literal_processor_datetime(dialect)
@property
def python_type(self):
return dt.datetime
@util.memoized_property
def _expression_adaptations(self):
# Based on
# https://www.postgresql.org/docs/current/static/functions-datetime.html.
return {
operators.add: {Interval: self.__class__},
operators.sub: {Interval: self.__class__, DateTime: Interval},
}
class Date(_RenderISO8601NoT, HasExpressionLookup, TypeEngine[dt.date]):
"""A type for ``datetime.date()`` objects."""
__visit_name__ = "date"
operator_classes = OperatorClass.DATETIME
def get_dbapi_type(self, dbapi):
return dbapi.DATETIME
@property
def python_type(self):
return dt.date
def literal_processor(self, dialect):
return self._literal_processor_date(dialect)
@util.memoized_property
def _expression_adaptations(self):
# Based on
# https://www.postgresql.org/docs/current/static/functions-datetime.html.
return {
operators.add: {
Integer: self.__class__,
Interval: DateTime,
Time: DateTime,
},
operators.sub: {
# date - integer = date
Integer: self.__class__,
# date - date = integer.
Date: Integer,
Interval: DateTime,
# date - datetime = interval,
# this one is not in the PG docs
# but works
DateTime: Interval,
},
}
class Time(_RenderISO8601NoT, HasExpressionLookup, TypeEngine[dt.time]):
"""A type for ``datetime.time()`` objects."""
__visit_name__ = "time"
operator_classes = OperatorClass.DATETIME
def __init__(self, timezone: bool = False):
self.timezone = timezone
def get_dbapi_type(self, dbapi):
return dbapi.DATETIME
@property
def python_type(self):
return dt.time
def _resolve_for_literal(self, value):
with_timezone = value.tzinfo is not None
if with_timezone and not self.timezone:
return TIME_TIMEZONE
else:
return self
@util.memoized_property
def _expression_adaptations(self):
# Based on
# https://www.postgresql.org/docs/current/static/functions-datetime.html.
return {
operators.add: {Date: DateTime, Interval: self.__class__},
operators.sub: {Time: Interval, Interval: self.__class__},
}
def literal_processor(self, dialect):
return self._literal_processor_time(dialect)
class _Binary(TypeEngine[bytes]):
"""Define base behavior for binary types."""
operator_classes = OperatorClass.BINARY
length: Optional[int]
def __init__(self, length: Optional[int] = None):
self.length = length
@util.ro_memoized_property
def _generic_type_affinity(
self,
) -> Type[TypeEngine[bytes]]:
return LargeBinary
def literal_processor(self, dialect):
def process(value):
# TODO: this is useless for real world scenarios; implement
# real binary literals
value = value.decode(
dialect._legacy_binary_type_literal_encoding
).replace("'", "''")
return "'%s'" % value
return process
@property
def python_type(self):
return bytes
# Python 3 - sqlite3 doesn't need the `Binary` conversion
# here, though pg8000 does to indicate "bytea"
def bind_processor(self, dialect):
if dialect.dbapi is None:
return None