-
-
Notifications
You must be signed in to change notification settings - Fork 889
/
test_types.py
4566 lines (3768 loc) · 142 KB
/
test_types.py
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
import datetime
import decimal
import importlib
import operator
import os
import pickle
import subprocess
import sys
from tempfile import mkstemp
import sqlalchemy as sa
from sqlalchemy import and_
from sqlalchemy import ARRAY
from sqlalchemy import BigInteger
from sqlalchemy import bindparam
from sqlalchemy import BLOB
from sqlalchemy import BOOLEAN
from sqlalchemy import Boolean
from sqlalchemy import cast
from sqlalchemy import CHAR
from sqlalchemy import CLOB
from sqlalchemy import collate
from sqlalchemy import DATE
from sqlalchemy import Date
from sqlalchemy import DATETIME
from sqlalchemy import DateTime
from sqlalchemy import DECIMAL
from sqlalchemy import dialects
from sqlalchemy import distinct
from sqlalchemy import Double
from sqlalchemy import Enum
from sqlalchemy import exc
from sqlalchemy import FLOAT
from sqlalchemy import Float
from sqlalchemy import func
from sqlalchemy import inspection
from sqlalchemy import INTEGER
from sqlalchemy import Integer
from sqlalchemy import Interval
from sqlalchemy import JSON
from sqlalchemy import LargeBinary
from sqlalchemy import literal
from sqlalchemy import MetaData
from sqlalchemy import NCHAR
from sqlalchemy import NUMERIC
from sqlalchemy import Numeric
from sqlalchemy import NVARCHAR
from sqlalchemy import PickleType
from sqlalchemy import REAL
from sqlalchemy import select
from sqlalchemy import SMALLINT
from sqlalchemy import SmallInteger
from sqlalchemy import String
from sqlalchemy import testing
from sqlalchemy import Text
from sqlalchemy import text
from sqlalchemy import TIME
from sqlalchemy import Time
from sqlalchemy import TIMESTAMP
from sqlalchemy import type_coerce
from sqlalchemy import TypeDecorator
from sqlalchemy import types
from sqlalchemy import Unicode
from sqlalchemy import util
from sqlalchemy import VARCHAR
import sqlalchemy.dialects.mysql as mysql
import sqlalchemy.dialects.oracle as oracle
import sqlalchemy.dialects.postgresql as pg
from sqlalchemy.engine import default
from sqlalchemy.engine import interfaces
from sqlalchemy.schema import AddConstraint
from sqlalchemy.schema import CheckConstraint
from sqlalchemy.sql import column
from sqlalchemy.sql import compiler
from sqlalchemy.sql import ddl
from sqlalchemy.sql import elements
from sqlalchemy.sql import null
from sqlalchemy.sql import operators
from sqlalchemy.sql import sqltypes
from sqlalchemy.sql import table
from sqlalchemy.sql import type_api
from sqlalchemy.sql import visitors
from sqlalchemy.sql.compiler import TypeCompiler
from sqlalchemy.sql.sqltypes import TypeEngine
from sqlalchemy.testing import assert_raises
from sqlalchemy.testing import assert_raises_message
from sqlalchemy.testing import AssertsCompiledSQL
from sqlalchemy.testing import AssertsExecutionResults
from sqlalchemy.testing import engines
from sqlalchemy.testing import eq_
from sqlalchemy.testing import expect_raises
from sqlalchemy.testing import fixtures
from sqlalchemy.testing import is_
from sqlalchemy.testing import is_not
from sqlalchemy.testing import is_true
from sqlalchemy.testing import mock
from sqlalchemy.testing import pickleable
from sqlalchemy.testing.assertions import expect_raises_message
from sqlalchemy.testing.schema import Column
from sqlalchemy.testing.schema import pep435_enum
from sqlalchemy.testing.schema import Table
from sqlalchemy.testing.util import picklers
from sqlalchemy.types import UserDefinedType
def _all_dialect_modules():
return [
importlib.import_module("sqlalchemy.dialects.%s" % d)
for d in dialects.__all__
if not d.startswith("_")
]
def _all_dialects():
return [d.base.dialect() for d in _all_dialect_modules()]
def _types_for_mod(mod):
for key in dir(mod):
typ = getattr(mod, key)
if (
not isinstance(typ, type)
or not issubclass(typ, types.TypeEngine)
or typ.__dict__.get("__abstract__")
):
continue
yield typ
def _all_types(omit_special_types=False):
yield from (
typ
for typ, _ in _all_types_w_their_dialect(
omit_special_types=omit_special_types
)
)
def _all_types_w_their_dialect(omit_special_types=False):
seen = set()
for typ in _types_for_mod(types):
if omit_special_types and (
typ
in (
TypeEngine,
type_api.TypeEngineMixin,
types.Variant,
types.TypeDecorator,
types.PickleType,
)
or type_api.TypeEngineMixin in typ.__bases__
):
continue
if typ in seen:
continue
seen.add(typ)
yield typ, default.DefaultDialect
for dialect in _all_dialect_modules():
for typ in _types_for_mod(dialect):
if typ in seen:
continue
seen.add(typ)
yield typ, dialect.dialect
def _get_instance(type_):
if issubclass(type_, ARRAY):
return type_(String)
elif hasattr(type_, "__test_init__"):
t1 = type_.__test_init__()
is_(isinstance(t1, type_), True)
return t1
else:
return type_()
class AdaptTest(fixtures.TestBase):
@testing.combinations(((t,) for t in _types_for_mod(types)), id_="n")
def test_uppercase_importable(self, typ):
if typ.__name__ == typ.__name__.upper():
assert getattr(sa, typ.__name__) is typ
assert typ.__name__ in dir(types)
@testing.combinations(
((d.name, d) for d in _all_dialects()), argnames="dialect", id_="ia"
)
@testing.combinations(
(REAL(), "REAL"),
(FLOAT(), "FLOAT"),
(NUMERIC(), "NUMERIC"),
(DECIMAL(), "DECIMAL"),
(INTEGER(), "INTEGER"),
(SMALLINT(), "SMALLINT"),
(TIMESTAMP(), ("TIMESTAMP", "TIMESTAMP WITHOUT TIME ZONE")),
(DATETIME(), "DATETIME"),
(DATE(), "DATE"),
(TIME(), ("TIME", "TIME WITHOUT TIME ZONE")),
(CLOB(), "CLOB"),
(VARCHAR(10), ("VARCHAR(10)", "VARCHAR(10 CHAR)")),
(
NVARCHAR(10),
("NVARCHAR(10)", "NATIONAL VARCHAR(10)", "NVARCHAR2(10)"),
),
(CHAR(), "CHAR"),
(NCHAR(), ("NCHAR", "NATIONAL CHAR")),
(BLOB(), ("BLOB", "BLOB SUB_TYPE 0")),
(BOOLEAN(), ("BOOLEAN", "BOOL", "INTEGER")),
argnames="type_, expected",
id_="ra",
)
def test_uppercase_rendering(self, dialect, type_, expected):
"""Test that uppercase types from types.py always render as their
type.
As of SQLA 0.6, using an uppercase type means you want specifically
that type. If the database in use doesn't support that DDL, it (the DB
backend) should raise an error - it means you should be using a
lowercased (genericized) type.
"""
if isinstance(expected, str):
expected = (expected,)
try:
compiled = type_.compile(dialect=dialect)
except NotImplementedError:
return
assert compiled in expected, "%r matches none of %r for dialect %s" % (
compiled,
expected,
dialect.name,
)
assert (
str(types.to_instance(type_)) in expected
), "default str() of type %r not expected, %r" % (type_, expected)
def _adaptions():
for typ in _all_types(omit_special_types=True):
# up adapt from LowerCase to UPPERCASE,
# as well as to all non-sqltypes
up_adaptions = [typ] + typ.__subclasses__()
yield "%s.%s" % (
typ.__module__,
typ.__name__,
), False, typ, up_adaptions
for subcl in typ.__subclasses__():
if (
subcl is not typ
and typ is not TypeDecorator
and "sqlalchemy" in subcl.__module__
):
yield "%s.%s" % (
subcl.__module__,
subcl.__name__,
), True, subcl, [typ]
@testing.combinations(_adaptions(), id_="iaaa")
def test_adapt_method(self, is_down_adaption, typ, target_adaptions):
"""ensure all types have a working adapt() method,
which creates a distinct copy.
The distinct copy ensures that when we cache
the adapted() form of a type against the original
in a weak key dictionary, a cycle is not formed.
This test doesn't test type-specific arguments of
adapt() beyond their defaults.
"""
t1 = _get_instance(typ)
for cls in target_adaptions:
if (is_down_adaption and issubclass(typ, sqltypes.Emulated)) or (
not is_down_adaption and issubclass(cls, sqltypes.Emulated)
):
continue
# print("ADAPT %s -> %s" % (t1.__class__, cls))
t2 = t1.adapt(cls)
assert t1 is not t2
if is_down_adaption:
t2, t1 = t1, t2
for k in t1.__dict__:
if k in (
"impl",
"_is_oracle_number",
"_create_events",
"create_constraint",
"inherit_schema",
"schema",
"metadata",
"name",
):
continue
# assert each value was copied, or that
# the adapted type has a more specific
# value than the original (i.e. SQL Server
# applies precision=24 for REAL)
assert (
getattr(t2, k) == t1.__dict__[k] or t1.__dict__[k] is None
)
eq_(t1.evaluates_none().should_evaluate_none, True)
def test_python_type(self):
eq_(types.Integer().python_type, int)
eq_(types.Numeric().python_type, decimal.Decimal)
eq_(types.Numeric(asdecimal=False).python_type, float)
eq_(types.LargeBinary().python_type, bytes)
eq_(types.Float().python_type, float)
eq_(types.Double().python_type, float)
eq_(types.Interval().python_type, datetime.timedelta)
eq_(types.Date().python_type, datetime.date)
eq_(types.DateTime().python_type, datetime.datetime)
eq_(types.String().python_type, str)
eq_(types.Unicode().python_type, str)
eq_(types.Enum("one", "two", "three").python_type, str)
assert_raises(
NotImplementedError, lambda: types.TypeEngine().python_type
)
@testing.uses_deprecated()
@testing.combinations(*[(t,) for t in _all_types(omit_special_types=True)])
def test_repr(self, typ):
t1 = _get_instance(typ)
repr(t1)
@testing.uses_deprecated()
@testing.combinations(*[(t,) for t in _all_types(omit_special_types=True)])
def test_str(self, typ):
t1 = _get_instance(typ)
str(t1)
def test_str_third_party(self):
class TINYINT(types.TypeEngine):
__visit_name__ = "TINYINT"
eq_(str(TINYINT()), "TINYINT")
def test_str_third_party_uppercase_no_visit_name(self):
class TINYINT(types.TypeEngine):
pass
eq_(str(TINYINT()), "TINYINT")
def test_str_third_party_camelcase_no_visit_name(self):
class TinyInt(types.TypeEngine):
pass
eq_(str(TinyInt()), "TinyInt()")
def test_adapt_constructor_copy_override_kw(self):
"""test that adapt() can accept kw args that override
the state of the original object.
This essentially is testing the behavior of util.constructor_copy().
"""
t1 = String(length=50)
t2 = t1.adapt(Text)
eq_(t2.length, 50)
@testing.combinations(
*[
(t, d)
for t, d in _all_types_w_their_dialect(omit_special_types=True)
]
)
def test_every_possible_type_can_be_decorated(self, typ, dialect_cls):
"""test for #9020
Apparently the adapt() method is called with the same class as given
in the case of :class:`.TypeDecorator`, at least with the
PostgreSQL RANGE types, which is not usually expected.
"""
my_type = type("MyType", (TypeDecorator,), {"impl": typ})
if issubclass(typ, ARRAY):
inst = my_type(Integer)
elif issubclass(typ, pg.ENUM):
inst = my_type(name="my_enum")
elif issubclass(typ, pg.DOMAIN):
inst = my_type(name="my_domain", data_type=Integer)
else:
inst = my_type()
impl = inst._unwrapped_dialect_impl(dialect_cls())
if dialect_cls is default.DefaultDialect:
is_true(isinstance(impl, typ))
if impl._type_affinity is Interval:
is_true(issubclass(typ, sqltypes._AbstractInterval))
else:
is_true(issubclass(typ, impl._type_affinity))
class TypeAffinityTest(fixtures.TestBase):
@testing.combinations(
(String(), String),
(VARCHAR(), String),
(Date(), Date),
(LargeBinary(), types._Binary),
id_="rn",
)
def test_type_affinity(self, type_, affin):
eq_(type_._type_affinity, affin)
@testing.combinations(
(Integer(), SmallInteger(), True),
(Integer(), String(), False),
(Integer(), Integer(), True),
(Text(), String(), True),
(Text(), Unicode(), True),
(LargeBinary(), Integer(), False),
(LargeBinary(), PickleType(), True),
(PickleType(), LargeBinary(), True),
(PickleType(), PickleType(), True),
id_="rra",
)
def test_compare_type_affinity(self, t1, t2, comp):
eq_(t1._compare_type_affinity(t2), comp, "%s %s" % (t1, t2))
def test_decorator_doesnt_cache(self):
from sqlalchemy.dialects import postgresql
class MyType(TypeDecorator):
impl = CHAR
cache_ok = True
def load_dialect_impl(self, dialect):
if dialect.name == "postgresql":
return dialect.type_descriptor(postgresql.INET())
else:
return dialect.type_descriptor(CHAR(32))
t1 = MyType()
d = postgresql.dialect()
assert t1._type_affinity is String
assert t1.dialect_impl(d)._type_affinity is postgresql.INET
class AsGenericTest(fixtures.TestBase):
@testing.combinations(
(String(), String()),
(VARCHAR(length=100), String(length=100)),
(NVARCHAR(length=100), Unicode(length=100)),
(DATE(), Date()),
(pg.JSON(), sa.JSON()),
(pg.ARRAY(sa.String), sa.ARRAY(sa.String)),
(Enum("a", "b", "c"), Enum("a", "b", "c")),
(pg.ENUM("a", "b", "c", name="pgenum"), Enum("a", "b", "c")),
(mysql.ENUM("a", "b", "c"), Enum("a", "b", "c")),
(pg.INTERVAL(precision=5), Interval(native=True, second_precision=5)),
(
oracle.INTERVAL(second_precision=5, day_precision=5),
Interval(native=True, day_precision=5, second_precision=5),
),
)
def test_as_generic(self, t1, t2):
assert repr(t1.as_generic(allow_nulltype=False)) == repr(t2)
@testing.combinations(
*[
(t,)
for t in _all_types(omit_special_types=True)
if not util.method_is_overridden(t, TypeEngine.as_generic)
]
)
def test_as_generic_all_types_heuristic(self, type_):
t1 = _get_instance(type_)
try:
gentype = t1.as_generic()
except NotImplementedError:
pass
else:
assert isinstance(t1, gentype.__class__)
assert isinstance(gentype, TypeEngine)
gentype = t1.as_generic(allow_nulltype=True)
if not isinstance(gentype, types.NULLTYPE.__class__):
assert isinstance(t1, gentype.__class__)
assert isinstance(gentype, TypeEngine)
@testing.combinations(
*[
(t,)
for t in _all_types(omit_special_types=True)
if util.method_is_overridden(t, TypeEngine.as_generic)
]
)
def test_as_generic_all_types_custom(self, type_):
t1 = _get_instance(type_)
gentype = t1.as_generic(allow_nulltype=False)
assert isinstance(gentype, TypeEngine)
class PickleTypesTest(fixtures.TestBase):
@testing.combinations(
("Boo", Boolean()),
("Str", String()),
("Tex", Text()),
("Uni", Unicode()),
("Int", Integer()),
("Sma", SmallInteger()),
("Big", BigInteger()),
("Num", Numeric()),
("Flo", Float()),
("Enu", Enum("one", "two", "three")),
("Dat", DateTime()),
("Dat", Date()),
("Tim", Time()),
("Lar", LargeBinary()),
("Pic", PickleType()),
("Int", Interval()),
argnames="name,type_",
id_="ar",
)
@testing.variation("use_adapt", [True, False])
def test_pickle_types(self, name, type_, use_adapt):
if use_adapt:
type_ = type_.copy()
column_type = Column(name, type_)
meta = MetaData()
Table("foo", meta, column_type)
for loads, dumps in picklers():
loads(dumps(column_type))
loads(dumps(meta))
@testing.combinations(
("Str", String()),
("Tex", Text()),
("Uni", Unicode()),
("Boo", Boolean()),
("Dat", DateTime()),
("Dat", Date()),
("Tim", Time()),
("Lar", LargeBinary()),
("Pic", PickleType()),
("Int", Interval()),
("Enu", Enum("one", "two", "three")),
argnames="name,type_",
id_="ar",
)
@testing.variation("use_adapt", [True, False])
def test_pickle_types_other_process(self, name, type_, use_adapt):
"""test for #11530
this does a full exec of python interpreter so the number of variations
here is reduced to just a single pickler, else each case takes
a full second.
"""
if use_adapt:
type_ = type_.copy()
column_type = Column(name, type_)
meta = MetaData()
Table("foo", meta, column_type)
for target in column_type, meta:
f, name = mkstemp("pkl")
with os.fdopen(f, "wb") as f:
pickle.dump(target, f)
name = name.replace(os.sep, "/")
code = (
"import sqlalchemy; import pickle; "
f"pickle.load(open('''{name}''', 'rb'))"
)
parts = list(sys.path)
if os.environ.get("PYTHONPATH"):
parts.append(os.environ["PYTHONPATH"])
pythonpath = os.pathsep.join(parts)
proc = subprocess.run(
[sys.executable, "-c", code],
env={**os.environ, "PYTHONPATH": pythonpath},
)
eq_(proc.returncode, 0)
os.unlink(name)
class _UserDefinedTypeFixture:
@classmethod
def define_tables(cls, metadata):
class MyType(types.UserDefinedType):
def get_col_spec(self):
return "VARCHAR(100)"
def bind_processor(self, dialect):
def process(value):
if value is None:
value = "<null value>"
return "BIND_IN" + value
return process
def result_processor(self, dialect, coltype):
def process(value):
return value + "BIND_OUT"
return process
def adapt(self, typeobj):
return typeobj()
class MyDecoratedType(types.TypeDecorator):
impl = String
cache_ok = True
def bind_processor(self, dialect):
impl_processor = super().bind_processor(dialect) or (
lambda value: value
)
def process(value):
if value is None:
value = "<null value>"
return "BIND_IN" + impl_processor(value)
return process
def result_processor(self, dialect, coltype):
impl_processor = super().result_processor(
dialect, coltype
) or (lambda value: value)
def process(value):
return impl_processor(value) + "BIND_OUT"
return process
def copy(self):
return MyDecoratedType()
class MyNewUnicodeType(types.TypeDecorator):
impl = Unicode
cache_ok = True
def process_bind_param(self, value, dialect):
if value is None:
value = "<null value>"
return "BIND_IN" + value
def process_result_value(self, value, dialect):
return value + "BIND_OUT"
def copy(self):
return MyNewUnicodeType(self.impl.length)
class MyNewIntType(types.TypeDecorator):
impl = Integer
cache_ok = True
def process_bind_param(self, value, dialect):
if value is None:
value = 29
return value * 10
def process_result_value(self, value, dialect):
return value * 10
def copy(self):
return MyNewIntType()
class MyNewIntSubClass(MyNewIntType):
def process_result_value(self, value, dialect):
return value * 15
def copy(self):
return MyNewIntSubClass()
class MyUnicodeType(types.TypeDecorator):
impl = Unicode
cache_ok = True
def bind_processor(self, dialect):
impl_processor = super().bind_processor(dialect) or (
lambda value: value
)
def process(value):
if value is None:
value = "<null value>"
return "BIND_IN" + impl_processor(value)
return process
def result_processor(self, dialect, coltype):
impl_processor = super().result_processor(
dialect, coltype
) or (lambda value: value)
def process(value):
return impl_processor(value) + "BIND_OUT"
return process
def copy(self):
return MyUnicodeType(self.impl.length)
class MyDecOfDec(types.TypeDecorator):
impl = MyNewIntType
cache_ok = True
Table(
"users",
metadata,
Column("user_id", Integer, primary_key=True),
# totall custom type
Column("goofy", MyType, nullable=False),
# decorated type with an argument, so its a String
Column("goofy2", MyDecoratedType(50), nullable=False),
Column("goofy4", MyUnicodeType(50), nullable=False),
Column("goofy7", MyNewUnicodeType(50), nullable=False),
Column("goofy8", MyNewIntType, nullable=False),
Column("goofy9", MyNewIntSubClass, nullable=False),
Column("goofy10", MyDecOfDec, nullable=False),
)
class UserDefinedRoundTripTest(_UserDefinedTypeFixture, fixtures.TablesTest):
__backend__ = True
def _data_fixture(self, connection):
users = self.tables.users
connection.execute(
users.insert(),
dict(
user_id=2,
goofy="jack",
goofy2="jack",
goofy4="jack",
goofy7="jack",
goofy8=12,
goofy9=12,
goofy10=12,
),
)
connection.execute(
users.insert(),
dict(
user_id=3,
goofy="lala",
goofy2="lala",
goofy4="lala",
goofy7="lala",
goofy8=15,
goofy9=15,
goofy10=15,
),
)
connection.execute(
users.insert(),
dict(
user_id=4,
goofy="fred",
goofy2="fred",
goofy4="fred",
goofy7="fred",
goofy8=9,
goofy9=9,
goofy10=9,
),
)
connection.execute(
users.insert(),
dict(
user_id=5,
goofy=None,
goofy2=None,
goofy4=None,
goofy7=None,
goofy8=None,
goofy9=None,
goofy10=None,
),
)
@testing.variation("use_driver_cols", [True, False])
def test_processing(self, connection, use_driver_cols):
users = self.tables.users
self._data_fixture(connection)
if use_driver_cols:
result = connection.execute(
users.select().order_by(users.c.user_id),
execution_options={"driver_column_names": True},
).fetchall()
else:
result = connection.execute(
users.select().order_by(users.c.user_id)
).fetchall()
eq_(
result,
[
(
2,
"BIND_INjackBIND_OUT",
"BIND_INjackBIND_OUT",
"BIND_INjackBIND_OUT",
"BIND_INjackBIND_OUT",
1200,
1800,
1200,
),
(
3,
"BIND_INlalaBIND_OUT",
"BIND_INlalaBIND_OUT",
"BIND_INlalaBIND_OUT",
"BIND_INlalaBIND_OUT",
1500,
2250,
1500,
),
(
4,
"BIND_INfredBIND_OUT",
"BIND_INfredBIND_OUT",
"BIND_INfredBIND_OUT",
"BIND_INfredBIND_OUT",
900,
1350,
900,
),
(
5,
"BIND_IN<null value>BIND_OUT",
"BIND_IN<null value>BIND_OUT",
"BIND_IN<null value>BIND_OUT",
"BIND_IN<null value>BIND_OUT",
2900,
4350,
2900,
),
],
)
def test_plain_in_typedec(self, connection):
users = self.tables.users
self._data_fixture(connection)
stmt = (
select(users.c.user_id, users.c.goofy8)
.where(users.c.goofy8.in_([15, 9]))
.order_by(users.c.user_id)
)
result = connection.execute(stmt, {"goofy": [15, 9]})
eq_(result.fetchall(), [(3, 1500), (4, 900)])
def test_plain_in_typedec_of_typedec(self, connection):
users = self.tables.users
self._data_fixture(connection)
stmt = (
select(users.c.user_id, users.c.goofy10)
.where(users.c.goofy10.in_([15, 9]))
.order_by(users.c.user_id)
)
result = connection.execute(stmt, {"goofy": [15, 9]})
eq_(result.fetchall(), [(3, 1500), (4, 900)])
def test_expanding_in_typedec(self, connection):
users = self.tables.users
self._data_fixture(connection)
stmt = (
select(users.c.user_id, users.c.goofy8)
.where(users.c.goofy8.in_(bindparam("goofy", expanding=True)))
.order_by(users.c.user_id)
)
result = connection.execute(stmt, {"goofy": [15, 9]})
eq_(result.fetchall(), [(3, 1500), (4, 900)])
def test_expanding_in_typedec_of_typedec(self, connection):
users = self.tables.users
self._data_fixture(connection)
stmt = (
select(users.c.user_id, users.c.goofy10)
.where(users.c.goofy10.in_(bindparam("goofy", expanding=True)))
.order_by(users.c.user_id)
)
result = connection.execute(stmt, {"goofy": [15, 9]})
eq_(result.fetchall(), [(3, 1500), (4, 900)])
class TypeDecoratorSpecialCasesTest(AssertsCompiledSQL, fixtures.TestBase):
__backend__ = True
@testing.requires.array_type
def test_typedec_of_array_modified(self, metadata, connection):
"""test #7249"""
class SkipsFirst(TypeDecorator): # , Indexable):
impl = ARRAY(Integer, zero_indexes=True)
cache_ok = True
def process_bind_param(self, value, dialect):
return value[1:]
def copy(self, **kw):
return SkipsFirst(**kw)
def coerce_compared_value(self, op, value):
return self.impl.coerce_compared_value(op, value)
t = Table(
"t",
metadata,
Column("id", Integer, primary_key=True),
Column("data", SkipsFirst),
)
t.create(connection)
connection.execute(t.insert(), {"data": [1, 2, 3]})
val = connection.scalar(select(t.c.data))
eq_(val, [2, 3])
val = connection.scalar(select(t.c.data[0]))
eq_(val, 2)
def test_typedec_of_array_ops(self):
class ArrayDec(TypeDecorator):
impl = ARRAY(Integer, zero_indexes=True)
cache_ok = True
def coerce_compared_value(self, op, value):
return self.impl.coerce_compared_value(op, value)
expr1 = column("q", ArrayDec)[0]
expr2 = column("q", ARRAY(Integer, zero_indexes=True))[0]
eq_(expr1.right.type._type_affinity, Integer)
eq_(expr2.right.type._type_affinity, Integer)
self.assert_compile(
column("q", ArrayDec).any(7, operator=operators.lt),
"%(q_1)s < ANY (q)",
dialect="postgresql",
)
self.assert_compile(
column("q", ArrayDec)[5], "q[%(q_1)s]", dialect="postgresql"
)
def test_typedec_of_json_ops(self):
class JsonDec(TypeDecorator):
impl = JSON()
cache_ok = True
self.assert_compile(
column("q", JsonDec)["q"], "q -> %(q_1)s", dialect="postgresql"
)
self.assert_compile(
column("q", JsonDec)["q"].as_integer(),
"CAST(q ->> %(q_1)s AS INTEGER)",
dialect="postgresql",
)
@testing.requires.array_type
def test_typedec_of_array(self, metadata, connection):
"""test #7249"""
class ArrayDec(TypeDecorator):
impl = ARRAY(Integer, zero_indexes=True)
cache_ok = True
def coerce_compared_value(self, op, value):
return self.impl.coerce_compared_value(op, value)
t = Table(
"t",
metadata,
Column("id", Integer, primary_key=True),
Column("data", ArrayDec),
)
t.create(connection)
connection.execute(t.insert(), {"data": [1, 2, 3]})