-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathtest_types.py
More file actions
2271 lines (1877 loc) · 70.9 KB
/
test_types.py
File metadata and controls
2271 lines (1877 loc) · 70.9 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
# testing/suite/test_types.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: ignore-errors
import datetime
import decimal
import json
import re
import uuid
from .. import config
from .. import engines
from .. import fixtures
from .. import mock
from ..assertions import eq_
from ..assertions import is_
from ..assertions import ne_
from ..config import requirements
from ..schema import Column
from ..schema import Table
from ... import and_
from ... import ARRAY
from ... import BigInteger
from ... import bindparam
from ... import Boolean
from ... import case
from ... import cast
from ... import Date
from ... import DateTime
from ... import Enum
from ... import Float
from ... import Integer
from ... import Interval
from ... import JSON
from ... import literal
from ... import literal_column
from ... import MetaData
from ... import null
from ... import Numeric
from ... import select
from ... import String
from ... import testing
from ... import Text
from ... import Time
from ... import TIMESTAMP
from ... import type_coerce
from ... import TypeDecorator
from ... import Unicode
from ... import UnicodeText
from ... import UUID
from ... import Uuid
from ...orm import declarative_base
from ...orm import Session
from ...sql import sqltypes
from ...sql.sqltypes import LargeBinary
from ...sql.sqltypes import PickleType
from ...testing import Variation
class _LiteralRoundTripFixture:
supports_whereclause = True
@testing.fixture
def literal_round_trip(self, metadata, connection):
"""test literal rendering"""
# for literal, we test the literal render in an INSERT
# into a typed column. we can then SELECT it back as its
# official type; ideally we'd be able to use CAST here
# but MySQL in particular can't CAST fully
def run(
type_,
input_,
output,
filter_=None,
compare=None,
support_whereclause=True,
):
t = Table("t", metadata, Column("x", type_))
t.create(connection)
for value in input_:
ins = t.insert().values(
x=literal(value, type_, literal_execute=True)
)
connection.execute(ins)
ins = t.insert().values(
x=literal(None, type_, literal_execute=True)
)
connection.execute(ins)
if support_whereclause and self.supports_whereclause:
if compare:
stmt = t.select().where(
t.c.x
== literal(
compare,
type_,
literal_execute=True,
),
t.c.x
== literal(
input_[0],
type_,
literal_execute=True,
),
)
else:
stmt = t.select().where(
t.c.x
== literal(
compare if compare is not None else input_[0],
type_,
literal_execute=True,
)
)
else:
stmt = t.select().where(t.c.x.is_not(None))
rows = connection.execute(stmt).all()
assert rows, "No rows returned"
for row in rows:
value = row[0]
if filter_ is not None:
value = filter_(value)
assert value in output
stmt = t.select().where(t.c.x.is_(None))
rows = connection.execute(stmt).all()
eq_(rows, [(None,)])
return run
class _UnicodeFixture(_LiteralRoundTripFixture, fixtures.TestBase):
__requires__ = ("unicode_data",)
data = (
"Alors vous imaginez ma 🐍 surprise, au lever du jour, "
"quand une drôle de petite 🐍 voix m’a réveillé. Elle "
"disait: « S’il vous plaît… dessine-moi 🐍 un mouton! »"
)
@property
def supports_whereclause(self):
return config.requirements.expressions_against_unbounded_text.enabled
@classmethod
def define_tables(cls, metadata):
Table(
"unicode_table",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("unicode_data", cls.datatype),
)
def test_round_trip(self, connection):
unicode_table = self.tables.unicode_table
connection.execute(
unicode_table.insert(), {"id": 1, "unicode_data": self.data}
)
row = connection.execute(select(unicode_table.c.unicode_data)).first()
eq_(row, (self.data,))
assert isinstance(row[0], str)
def test_round_trip_executemany(self, connection):
unicode_table = self.tables.unicode_table
connection.execute(
unicode_table.insert(),
[{"id": i, "unicode_data": self.data} for i in range(1, 4)],
)
rows = connection.execute(
select(unicode_table.c.unicode_data)
).fetchall()
eq_(rows, [(self.data,) for i in range(1, 4)])
for row in rows:
assert isinstance(row[0], str)
def _test_null_strings(self, connection):
unicode_table = self.tables.unicode_table
connection.execute(
unicode_table.insert(), {"id": 1, "unicode_data": None}
)
row = connection.execute(select(unicode_table.c.unicode_data)).first()
eq_(row, (None,))
def _test_empty_strings(self, connection):
unicode_table = self.tables.unicode_table
connection.execute(
unicode_table.insert(), {"id": 1, "unicode_data": ""}
)
row = connection.execute(select(unicode_table.c.unicode_data)).first()
eq_(row, ("",))
def test_literal(self, literal_round_trip):
literal_round_trip(self.datatype, [self.data], [self.data])
def test_literal_non_ascii(self, literal_round_trip):
literal_round_trip(self.datatype, ["réve🐍 illé"], ["réve🐍 illé"])
class UnicodeVarcharTest(_UnicodeFixture, fixtures.TablesTest):
__requires__ = ("unicode_data",)
__backend__ = True
datatype = Unicode(255)
@requirements.empty_strings_varchar
def test_empty_strings_varchar(self, connection):
self._test_empty_strings(connection)
def test_null_strings_varchar(self, connection):
self._test_null_strings(connection)
class UnicodeTextTest(_UnicodeFixture, fixtures.TablesTest):
__requires__ = "unicode_data", "text_type"
__backend__ = True
datatype = UnicodeText()
@requirements.empty_strings_text
def test_empty_strings_text(self, connection):
self._test_empty_strings(connection)
def test_null_strings_text(self, connection):
self._test_null_strings(connection)
class ArrayTest(_LiteralRoundTripFixture, fixtures.TablesTest):
"""Add ARRAY test suite, #8138.
This only works on PostgreSQL right now.
"""
__requires__ = ("array_type",)
__backend__ = True
@classmethod
def define_tables(cls, metadata):
Table(
"array_table",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("single_dim", ARRAY(Integer)),
Column("multi_dim", ARRAY(String, dimensions=2)),
)
def test_array_roundtrip(self, connection):
array_table = self.tables.array_table
connection.execute(
array_table.insert(),
{
"id": 1,
"single_dim": [1, 2, 3],
"multi_dim": [["one", "two"], ["thr'ee", "réve🐍 illé"]],
},
)
row = connection.execute(
select(array_table.c.single_dim, array_table.c.multi_dim)
).first()
eq_(row, ([1, 2, 3], [["one", "two"], ["thr'ee", "réve🐍 illé"]]))
def test_literal_simple(self, literal_round_trip):
literal_round_trip(
ARRAY(Integer),
([1, 2, 3],),
([1, 2, 3],),
support_whereclause=False,
)
def test_literal_complex(self, literal_round_trip):
literal_round_trip(
ARRAY(String, dimensions=2),
([["one", "two"], ["thr'ee", "réve🐍 illé"]],),
([["one", "two"], ["thr'ee", "réve🐍 illé"]],),
support_whereclause=False,
)
class BinaryTest(_LiteralRoundTripFixture, fixtures.TablesTest):
__backend__ = True
__requires__ = ("binary_literals",)
@classmethod
def define_tables(cls, metadata):
Table(
"binary_table",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("binary_data", LargeBinary),
Column("pickle_data", PickleType),
)
@testing.combinations(b"this is binary", b"7\xe7\x9f", argnames="data")
def test_binary_roundtrip(self, connection, data):
binary_table = self.tables.binary_table
connection.execute(
binary_table.insert(), {"id": 1, "binary_data": data}
)
row = connection.execute(select(binary_table.c.binary_data)).first()
eq_(row, (data,))
def test_pickle_roundtrip(self, connection):
binary_table = self.tables.binary_table
connection.execute(
binary_table.insert(),
{"id": 1, "pickle_data": {"foo": [1, 2, 3], "bar": "bat"}},
)
row = connection.execute(select(binary_table.c.pickle_data)).first()
eq_(row, ({"foo": [1, 2, 3], "bar": "bat"},))
class TextTest(_LiteralRoundTripFixture, fixtures.TablesTest):
__requires__ = ("text_type",)
__backend__ = True
@property
def supports_whereclause(self):
return config.requirements.expressions_against_unbounded_text.enabled
@classmethod
def define_tables(cls, metadata):
Table(
"text_table",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("text_data", Text),
)
def test_text_roundtrip(self, connection):
text_table = self.tables.text_table
connection.execute(
text_table.insert(), {"id": 1, "text_data": "some text"}
)
row = connection.execute(select(text_table.c.text_data)).first()
eq_(row, ("some text",))
@testing.requires.empty_strings_text
def test_text_empty_strings(self, connection):
text_table = self.tables.text_table
connection.execute(text_table.insert(), {"id": 1, "text_data": ""})
row = connection.execute(select(text_table.c.text_data)).first()
eq_(row, ("",))
def test_text_null_strings(self, connection):
text_table = self.tables.text_table
connection.execute(text_table.insert(), {"id": 1, "text_data": None})
row = connection.execute(select(text_table.c.text_data)).first()
eq_(row, (None,))
def test_literal(self, literal_round_trip):
literal_round_trip(Text, ["some text"], ["some text"])
@requirements.unicode_data_no_special_types
def test_literal_non_ascii(self, literal_round_trip):
literal_round_trip(Text, ["réve🐍 illé"], ["réve🐍 illé"])
def test_literal_quoting(self, literal_round_trip):
data = """some 'text' hey "hi there" that's text"""
literal_round_trip(Text, [data], [data])
def test_literal_backslashes(self, literal_round_trip):
data = r"backslash one \ backslash two \\ end"
literal_round_trip(Text, [data], [data])
def test_literal_percentsigns(self, literal_round_trip):
data = r"percent % signs %% percent"
literal_round_trip(Text, [data], [data])
class StringTest(_LiteralRoundTripFixture, fixtures.TestBase):
__backend__ = True
@requirements.unbounded_varchar
def test_nolength_string(self):
metadata = MetaData()
foo = Table("foo", metadata, Column("one", String))
foo.create(config.db)
foo.drop(config.db)
def test_literal(self, literal_round_trip):
# note that in Python 3, this invokes the Unicode
# datatype for the literal part because all strings are unicode
literal_round_trip(String(40), ["some text"], ["some text"])
@requirements.unicode_data_no_special_types
def test_literal_non_ascii(self, literal_round_trip):
literal_round_trip(String(40), ["réve🐍 illé"], ["réve🐍 illé"])
@testing.combinations(
("%B%", ["AB", "BC"]),
("A%C", ["AC"]),
("A%C%Z", []),
argnames="expr, expected",
)
def test_dont_truncate_rightside(
self, metadata, connection, expr, expected
):
t = Table("t", metadata, Column("x", String(2)))
t.create(connection)
connection.execute(t.insert(), [{"x": "AB"}, {"x": "BC"}, {"x": "AC"}])
eq_(
connection.scalars(
select(t.c.x).where(t.c.x.like(expr)).order_by(t.c.x)
).all(),
expected,
)
def test_literal_quoting(self, literal_round_trip):
data = """some 'text' hey "hi there" that's text"""
literal_round_trip(String(40), [data], [data])
def test_literal_backslashes(self, literal_round_trip):
data = r"backslash one \ backslash two \\ end"
literal_round_trip(String(40), [data], [data])
def test_concatenate_binary(self, connection):
"""dialects with special string concatenation operators should
implement visit_concat_op_binary() and visit_concat_op_clauselist()
in their compiler.
.. versionchanged:: 2.0 visit_concat_op_clauselist() is also needed
for dialects to override the string concatenation operator.
"""
eq_(connection.scalar(select(literal("a") + "b")), "ab")
def test_concatenate_clauselist(self, connection):
"""dialects with special string concatenation operators should
implement visit_concat_op_binary() and visit_concat_op_clauselist()
in their compiler.
.. versionchanged:: 2.0 visit_concat_op_clauselist() is also needed
for dialects to override the string concatenation operator.
"""
eq_(
connection.scalar(select(literal("a") + "b" + "c" + "d" + "e")),
"abcde",
)
class IntervalTest(_LiteralRoundTripFixture, fixtures.TestBase):
__requires__ = ("datetime_interval",)
__backend__ = True
datatype = Interval
data = datetime.timedelta(days=1, seconds=4)
def test_literal(self, literal_round_trip):
literal_round_trip(self.datatype, [self.data], [self.data])
def test_select_direct_literal_interval(self, connection):
row = connection.execute(select(literal(self.data))).first()
eq_(row, (self.data,))
def test_arithmetic_operation_literal_interval(self, connection):
now = datetime.datetime.now().replace(microsecond=0)
# Able to subtract
row = connection.execute(
select(literal(now) - literal(self.data))
).scalar()
eq_(row, now - self.data)
# Able to Add
row = connection.execute(
select(literal(now) + literal(self.data))
).scalar()
eq_(row, now + self.data)
@testing.fixture
def arithmetic_table_fixture(cls, metadata, connection):
class Decorated(TypeDecorator):
impl = cls.datatype
cache_ok = True
it = Table(
"interval_table",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("interval_data", cls.datatype),
Column("date_data", DateTime),
Column("decorated_interval_data", Decorated),
)
it.create(connection)
return it
def test_arithmetic_operation_table_interval_and_literal_interval(
self, connection, arithmetic_table_fixture
):
interval_table = arithmetic_table_fixture
data = datetime.timedelta(days=2, seconds=5)
connection.execute(
interval_table.insert(), {"id": 1, "interval_data": data}
)
# Subtraction Operation
value = connection.execute(
select(interval_table.c.interval_data - literal(self.data))
).scalar()
eq_(value, data - self.data)
# Addition Operation
value = connection.execute(
select(interval_table.c.interval_data + literal(self.data))
).scalar()
eq_(value, data + self.data)
def test_arithmetic_operation_table_date_and_literal_interval(
self, connection, arithmetic_table_fixture
):
interval_table = arithmetic_table_fixture
now = datetime.datetime.now().replace(microsecond=0)
connection.execute(
interval_table.insert(), {"id": 1, "date_data": now}
)
# Subtraction Operation
value = connection.execute(
select(interval_table.c.date_data - literal(self.data))
).scalar()
eq_(value, (now - self.data))
# Addition Operation
value = connection.execute(
select(interval_table.c.date_data + literal(self.data))
).scalar()
eq_(value, (now + self.data))
class PrecisionIntervalTest(IntervalTest):
__requires__ = ("datetime_interval",)
__backend__ = True
datatype = Interval(day_precision=9, second_precision=9)
data = datetime.timedelta(days=103, seconds=4)
class _DateFixture(_LiteralRoundTripFixture, fixtures.TestBase):
compare = None
@classmethod
def define_tables(cls, metadata):
class Decorated(TypeDecorator):
impl = cls.datatype
cache_ok = True
Table(
"date_table",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("date_data", cls.datatype),
Column("decorated_date_data", Decorated),
)
def test_round_trip(self, connection):
date_table = self.tables.date_table
connection.execute(
date_table.insert(), {"id": 1, "date_data": self.data}
)
row = connection.execute(select(date_table.c.date_data)).first()
compare = self.compare or self.data
eq_(row, (compare,))
assert isinstance(row[0], type(compare))
def test_round_trip_decorated(self, connection):
date_table = self.tables.date_table
connection.execute(
date_table.insert(), {"id": 1, "decorated_date_data": self.data}
)
row = connection.execute(
select(date_table.c.decorated_date_data)
).first()
compare = self.compare or self.data
eq_(row, (compare,))
assert isinstance(row[0], type(compare))
def test_null(self, connection):
date_table = self.tables.date_table
connection.execute(date_table.insert(), {"id": 1, "date_data": None})
row = connection.execute(select(date_table.c.date_data)).first()
eq_(row, (None,))
@testing.requires.datetime_literals
def test_literal(self, literal_round_trip):
compare = self.compare or self.data
literal_round_trip(
self.datatype, [self.data], [compare], compare=compare
)
@testing.requires.standalone_null_binds_whereclause
def test_null_bound_comparison(self):
# this test is based on an Oracle issue observed in #4886.
# passing NULL for an expression that needs to be interpreted as
# a certain type, does the DBAPI have the info it needs to do this.
date_table = self.tables.date_table
with config.db.begin() as conn:
result = conn.execute(
date_table.insert(), {"id": 1, "date_data": self.data}
)
id_ = result.inserted_primary_key[0]
stmt = select(date_table.c.id).where(
case(
(
bindparam("foo", type_=self.datatype) != None,
bindparam("foo", type_=self.datatype),
),
else_=date_table.c.date_data,
)
== date_table.c.date_data
)
row = conn.execute(stmt, {"foo": None}).first()
eq_(row[0], id_)
class DateTimeTest(_DateFixture, fixtures.TablesTest):
__requires__ = ("datetime",)
__backend__ = True
datatype = DateTime
data = datetime.datetime(2012, 10, 15, 12, 57, 18)
@testing.requires.datetime_implicit_bound
def test_select_direct(self, connection):
result = connection.scalar(select(literal(self.data)))
eq_(result, self.data)
class DateTimeTZTest(_DateFixture, fixtures.TablesTest):
__requires__ = ("datetime_timezone",)
__backend__ = True
datatype = DateTime(timezone=True)
data = datetime.datetime(
2012, 10, 15, 12, 57, 18, tzinfo=datetime.timezone.utc
)
@testing.requires.datetime_implicit_bound
def test_select_direct(self, connection):
result = connection.scalar(select(literal(self.data)))
eq_(result, self.data)
class DateTimeMicrosecondsTest(_DateFixture, fixtures.TablesTest):
__requires__ = ("datetime_microseconds",)
__backend__ = True
datatype = DateTime
data = datetime.datetime(2012, 10, 15, 12, 57, 18, 39642)
class TimestampMicrosecondsTest(_DateFixture, fixtures.TablesTest):
__requires__ = ("timestamp_microseconds",)
__backend__ = True
datatype = TIMESTAMP
data = datetime.datetime(2012, 10, 15, 12, 57, 18, 396)
@testing.requires.timestamp_microseconds_implicit_bound
def test_select_direct(self, connection):
result = connection.scalar(select(literal(self.data)))
eq_(result, self.data)
class TimeTest(_DateFixture, fixtures.TablesTest):
__requires__ = ("time",)
__backend__ = True
datatype = Time
data = datetime.time(12, 57, 18)
@testing.requires.time_implicit_bound
def test_select_direct(self, connection):
result = connection.scalar(select(literal(self.data)))
eq_(result, self.data)
class TimeTZTest(_DateFixture, fixtures.TablesTest):
__requires__ = ("time_timezone",)
__backend__ = True
datatype = Time(timezone=True)
data = datetime.time(12, 57, 18, tzinfo=datetime.timezone.utc)
@testing.requires.time_implicit_bound
def test_select_direct(self, connection):
result = connection.scalar(select(literal(self.data)))
eq_(result, self.data)
class TimeMicrosecondsTest(_DateFixture, fixtures.TablesTest):
__requires__ = ("time_microseconds",)
__backend__ = True
datatype = Time
data = datetime.time(12, 57, 18, 396)
@testing.requires.time_implicit_bound
def test_select_direct(self, connection):
result = connection.scalar(select(literal(self.data)))
eq_(result, self.data)
class DateTest(_DateFixture, fixtures.TablesTest):
__requires__ = ("date",)
__backend__ = True
datatype = Date
data = datetime.date(2012, 10, 15)
@testing.requires.date_implicit_bound
def test_select_direct(self, connection):
result = connection.scalar(select(literal(self.data)))
eq_(result, self.data)
class DateTimeCoercedToDateTimeTest(_DateFixture, fixtures.TablesTest):
"""this particular suite is testing that datetime parameters get
coerced to dates, which tends to be something DBAPIs do.
"""
__requires__ = "date", "date_coerces_from_datetime"
__backend__ = True
datatype = Date
data = datetime.datetime(2012, 10, 15, 12, 57, 18)
compare = datetime.date(2012, 10, 15)
@testing.requires.datetime_implicit_bound
def test_select_direct(self, connection):
result = connection.scalar(select(literal(self.data)))
eq_(result, self.data)
class DateTimeHistoricTest(_DateFixture, fixtures.TablesTest):
__requires__ = ("datetime_historic",)
__backend__ = True
datatype = DateTime
data = datetime.datetime(1850, 11, 10, 11, 52, 35)
@testing.requires.date_implicit_bound
def test_select_direct(self, connection):
result = connection.scalar(select(literal(self.data)))
eq_(result, self.data)
class DateHistoricTest(_DateFixture, fixtures.TablesTest):
__requires__ = ("date_historic",)
__backend__ = True
datatype = Date
data = datetime.date(1727, 4, 1)
@testing.requires.date_implicit_bound
def test_select_direct(self, connection):
result = connection.scalar(select(literal(self.data)))
eq_(result, self.data)
class IntegerTest(_LiteralRoundTripFixture, fixtures.TestBase):
__backend__ = True
def test_literal(self, literal_round_trip):
literal_round_trip(Integer, [5], [5])
def _huge_ints():
return testing.combinations(
2147483649, # 32 bits
2147483648, # 32 bits
2147483647, # 31 bits
2147483646, # 31 bits
-2147483649, # 32 bits
-2147483648, # 32 interestingly, asyncpg accepts this one as int32
-2147483647, # 31
-2147483646, # 31
0,
1376537018368127,
-1376537018368127,
argnames="intvalue",
)
@_huge_ints()
def test_huge_int_auto_accommodation(self, connection, intvalue):
"""test #7909"""
eq_(
connection.scalar(
select(intvalue).where(literal(intvalue) == intvalue)
),
intvalue,
)
@_huge_ints()
def test_huge_int(self, integer_round_trip, intvalue):
integer_round_trip(BigInteger, intvalue)
@testing.fixture
def integer_round_trip(self, metadata, connection):
def run(datatype, data):
int_table = Table(
"integer_table",
metadata,
Column(
"id",
Integer,
primary_key=True,
test_needs_autoincrement=True,
),
Column("integer_data", datatype),
)
metadata.create_all(config.db)
connection.execute(
int_table.insert(), {"id": 1, "integer_data": data}
)
row = connection.execute(select(int_table.c.integer_data)).first()
eq_(row, (data,))
assert isinstance(row[0], int)
return run
class CastTypeDecoratorTest(_LiteralRoundTripFixture, fixtures.TestBase):
__backend__ = True
@testing.fixture
def string_as_int(self):
class StringAsInt(TypeDecorator):
impl = String(50)
cache_ok = True
def column_expression(self, col):
return cast(col, Integer)
def bind_expression(self, col):
return cast(type_coerce(col, Integer), String(50))
return StringAsInt()
def test_special_type(self, metadata, connection, string_as_int):
type_ = string_as_int
t = Table("t", metadata, Column("x", type_))
t.create(connection)
connection.execute(t.insert(), [{"x": x} for x in [1, 2, 3]])
result = {row[0] for row in connection.execute(t.select())}
eq_(result, {1, 2, 3})
result = {
row[0] for row in connection.execute(t.select().where(t.c.x == 2))
}
eq_(result, {2})
class TrueDivTest(fixtures.TestBase):
__backend__ = True
@testing.combinations(
("15", "10", 1.5),
("-15", "10", -1.5),
argnames="left, right, expected",
)
def test_truediv_integer(self, connection, left, right, expected):
"""test #4926"""
eq_(
connection.scalar(
select(
literal_column(left, type_=Integer())
/ literal_column(right, type_=Integer())
)
),
expected,
)
@testing.combinations(
("15", "10", 1), ("-15", "5", -3), argnames="left, right, expected"
)
def test_floordiv_integer(self, connection, left, right, expected):
"""test #4926"""
eq_(
connection.scalar(
select(
literal_column(left, type_=Integer())
// literal_column(right, type_=Integer())
)
),
expected,
)
@testing.combinations(
("5.52", "2.4", "2.3"), argnames="left, right, expected"
)
def test_truediv_numeric(self, connection, left, right, expected):
"""test #4926"""
eq_(
connection.scalar(
select(
literal_column(left, type_=Numeric(10, 2))
/ literal_column(right, type_=Numeric(10, 2))
)
),
decimal.Decimal(expected),
)
@testing.combinations(
("5.52", "2.4", 2.3), argnames="left, right, expected"
)
def test_truediv_float(self, connection, left, right, expected):
"""test #4926"""
eq_(
connection.scalar(
select(
literal_column(left, type_=Float())
/ literal_column(right, type_=Float())
)
),
expected,
)
@testing.combinations(
("5.52", "2.4", "2.0"), argnames="left, right, expected"
)
def test_floordiv_numeric(self, connection, left, right, expected):
"""test #4926"""
eq_(
connection.scalar(
select(
literal_column(left, type_=Numeric())
// literal_column(right, type_=Numeric())
)
),
decimal.Decimal(expected),
)
def test_truediv_integer_bound(self, connection):
"""test #4926"""
eq_(
connection.scalar(select(literal(15) / literal(10))),
1.5,
)
def test_floordiv_integer_bound(self, connection):
"""test #4926"""
eq_(
connection.scalar(select(literal(15) // literal(10))),
1,
)
class NumericTest(_LiteralRoundTripFixture, fixtures.TestBase):
__backend__ = True