summaryrefslogtreecommitdiff
path: root/lib/sqlalchemy/testing/suite/test_types.py
blob: ba2dda9efe96caf14715502710c82e2a37d7a654 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
# 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 ..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 Float
from ... import Identity
from ... import Integer
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 ...dialects.postgresql import BYTEA
from ...orm import declarative_base
from ...orm import Session
from ...sql.sqltypes import LargeBinary
from ...sql.sqltypes import PickleType


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)

            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()

            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

        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

    @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"},))

    @testing.combinations(
        (
            LargeBinary(),
            b"this is binary",
        ),
        (LargeBinary(), b"7\xe7\x9f"),
        (BYTEA(), b"7\xe7\x9f", testing.only_on("postgresql")),
        argnames="type_,value",
    )
    @testing.variation("sort_by_parameter_order", [True, False])
    @testing.variation("multiple_rows", [True, False])
    @testing.requires.insert_returning
    def test_imv_returning(
        self,
        connection,
        metadata,
        sort_by_parameter_order,
        type_,
        value,
        multiple_rows,
    ):
        """test #9739 (similar to #9701).

        this tests insertmanyvalues as well as binary
        RETURNING types

        """
        t = Table(
            "t",
            metadata,
            Column("id", Integer, Identity(), primary_key=True),
            Column("value", type_),
        )

        t.create(connection)

        result = connection.execute(
            t.insert().returning(
                t.c.id,
                t.c.value,
                sort_by_parameter_order=bool(sort_by_parameter_order),
            ),
            [{"value": value} for i in range(10)]
            if multiple_rows
            else {"value": value},
        )

        if multiple_rows:
            i_range = range(1, 11)
        else:
            i_range = range(1, 2)

        eq_(
            set(result),
            {(id_, value) for id_ in i_range},
        )

        eq_(
            set(connection.scalars(select(t.c.value))),
            {value},
        )


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))).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 _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

    @testing.fixture
    def do_numeric_test(self, metadata, connection):
        def run(type_, input_, output, filter_=None, check_scale=False):
            t = Table("t", metadata, Column("x", type_))
            t.create(connection)
            connection.execute(t.insert(), [{"x": x} for x in input_])

            result = {row[0] for row in connection.execute(t.select())}
            output = set(output)
            if filter_:
                result = {filter_(x) for x in result}
                output = {filter_(x) for x in output}
            eq_(result, output)
            if check_scale:
                eq_([str(x) for x in result], [str(x) for x in output])

            connection.execute(t.delete())

            # test that this is actually a number!
            # note we have tiny scale here as we have tests with very
            # small scale Numeric types.  PostgreSQL will raise an error
            # if you use values outside the available scale.
            if type_.asdecimal:
                test_value = decimal.Decimal("2.9")
                add_value = decimal.Decimal("37.12")
            else:
                test_value = 2.9
                add_value = 37.12

            connection.execute(t.insert(), {"x": test_value})
            assert_we_are_a_number = connection.scalar(
                select(type_coerce(t.c.x + add_value, type_))
            )
            eq_(
                round(assert_we_are_a_number, 3),
                round(test_value + add_value, 3),
            )

        return run

    def test_render_literal_numeric(self, literal_round_trip):
        literal_round_trip(
            Numeric(precision=8, scale=4),
            [15.7563, decimal.Decimal("15.7563")],
            [decimal.Decimal("15.7563")],
        )

    def test_render_literal_numeric_asfloat(self, literal_round_trip):
        literal_round_trip(
            Numeric(precision=8, scale=4, asdecimal=False),
            [15.7563, decimal.Decimal("15.7563")],
            [15.7563],
        )

    def test_render_literal_float(self, literal_round_trip):
        literal_round_trip(
            Float(),
            [15.7563, decimal.Decimal("15.7563")],
            [15.7563],
            filter_=lambda n: n is not None and round(n, 5) or None,
            support_whereclause=False,
        )

    @testing.requires.precision_generic_float_type
    def test_float_custom_scale(self, do_numeric_test):
        do_numeric_test(
            Float(None, decimal_return_scale=7, asdecimal=True),
            [15.7563827, decimal.Decimal("15.7563827")],
            [decimal.Decimal("15.7563827")],
            check_scale=True,
        )

    def test_numeric_as_decimal(self, do_numeric_test):
        do_numeric_test(
            Numeric(precision=8, scale=4),
            [15.7563, decimal.Decimal("15.7563")],
            [decimal.Decimal("15.7563")],
        )

    def test_numeric_as_float(self, do_numeric_test):
        do_numeric_test(
            Numeric(precision=8, scale=4, asdecimal=False),
            [15.7563, decimal.Decimal("15.7563")],
            [15.7563],
        )

    @testing.requires.infinity_floats
    def test_infinity_floats(self, do_numeric_test):
        """test for #977, #7283"""

        do_numeric_test(
            Float(None),
            [float("inf")],
            [float("inf")],
        )

    @testing.requires.fetch_null_from_numeric
    def test_numeric_null_as_decimal(self, do_numeric_test):
        do_numeric_test(Numeric(precision=8, scale=4), [None], [None])

    @testing.requires.fetch_null_from_numeric
    def test_numeric_null_as_float(self, do_numeric_test):
        do_numeric_test(
            Numeric(precision=8, scale=4, asdecimal=False), [None], [None]
        )

    @testing.requires.floats_to_four_decimals
    def test_float_as_decimal(self, do_numeric_test):
        do_numeric_test(
            Float(asdecimal=True),
            [15.756, decimal.Decimal("15.756"), None],
            [decimal.Decimal("15.756"), None],
            filter_=lambda n: n is not None and round(n, 4) or None,
        )

    def test_float_as_float(self, do_numeric_test):
        do_numeric_test(
            Float(),
            [15.756, decimal.Decimal("15.756")],
            [15.756],
            filter_=lambda n: n is not None and round(n, 5) or None,
        )

    @testing.requires.literal_float_coercion
    def test_float_coerce_round_trip(self, connection):
        expr = 15.7563

        val = connection.scalar(select(literal(expr)))
        eq_(val, expr)

    # this does not work in MySQL, see #4036, however we choose not
    # to render CAST unconditionally since this is kind of an edge case.

    @testing.requires.implicit_decimal_binds
    def test_decimal_coerce_round_trip(self, connection):
        expr = decimal.Decimal("15.7563")

        val = connection.scalar(select(literal(expr)))
        eq_(val, expr)

    def test_decimal_coerce_round_trip_w_cast(self, connection):
        expr = decimal.Decimal("15.7563")

        val = connection.scalar(select(cast(expr, Numeric(10, 4))))
        eq_(val, expr)

    @testing.requires.precision_numerics_general
    def test_precision_decimal(self, do_numeric_test):
        numbers = {
            decimal.Decimal("54.234246451650"),
            decimal.Decimal("0.004354"),
            decimal.Decimal("900.0"),
        }

        do_numeric_test(Numeric(precision=18, scale=12), numbers, numbers)

    @testing.requires.precision_numerics_enotation_large
    def test_enotation_decimal(self, do_numeric_test):
        """test exceedingly small decimals.

        Decimal reports values with E notation when the exponent
        is greater than 6.

        """

        numbers = {
            decimal.Decimal("1E-2"),
            decimal.Decimal("1E-3"),
            decimal.Decimal("1E-4"),
            decimal.Decimal("1E-5"),
            decimal.Decimal("1E-6"),
            decimal.Decimal("1E-7"),
            decimal.Decimal("1E-8"),
            decimal.Decimal("0.01000005940696"),
            decimal.Decimal("0.00000005940696"),
            decimal.Decimal("0.00000000000696"),
            decimal.Decimal("0.70000000000696"),
            decimal.Decimal("696E-12"),
        }
        do_numeric_test(Numeric(precision=18, scale=14), numbers, numbers)

    @testing.requires.precision_numerics_enotation_large
    def test_enotation_decimal_large(self, do_numeric_test):
        """test exceedingly large decimals."""

        numbers = {
            decimal.Decimal("4E+8"),
            decimal.Decimal("5748E+15"),
            decimal.Decimal("1.521E+15"),
            decimal.Decimal("00000000000000.1E+12"),
        }
        do_numeric_test(Numeric(precision=25, scale=2), numbers, numbers)

    @testing.requires.precision_numerics_many_significant_digits
    def test_many_significant_digits(self, do_numeric_test):
        numbers = {
            decimal.Decimal("31943874831932418390.01"),
            decimal.Decimal("319438950232418390.273596"),
            decimal.Decimal("87673.594069654243"),
        }
        do_numeric_test(Numeric(precision=38, scale=12), numbers, numbers)

    @testing.requires.precision_numerics_retains_significant_digits
    def test_numeric_no_decimal(self, do_numeric_test):
        numbers = {decimal.Decimal("1.000")}
        do_numeric_test(
            Numeric(precision=5, scale=3), numbers, numbers, check_scale=True
        )


class BooleanTest(_LiteralRoundTripFixture, fixtures.TablesTest):
    __backend__ = True

    @classmethod
    def define_tables(cls, metadata):
        Table(
            "boolean_table",
            metadata,
            Column("id", Integer, primary_key=True, autoincrement=False),
            Column("value", Boolean),
            Column("unconstrained_value", Boolean(create_constraint=False)),
        )

    def test_render_literal_bool(self, literal_round_trip):
        literal_round_trip(Boolean(), [True, False], [True, False])

    def test_round_trip(self, connection):
        boolean_table = self.tables.boolean_table

        connection.execute(
            boolean_table.insert(),
            {"id": 1, "value": True, "unconstrained_value": False},
        )

        row = connection.execute(
            select(boolean_table.c.value, boolean_table.c.unconstrained_value)
        ).first()

        eq_(row, (True, False))
        assert isinstance(row[0], bool)

    @testing.requires.nullable_booleans
    def test_null(self, connection):
        boolean_table = self.tables.boolean_table

        connection.execute(
            boolean_table.insert(),
            {"id": 1, "value": None, "unconstrained_value": None},
        )

        row = connection.execute(
            select(boolean_table.c.value, boolean_table.c.unconstrained_value)
        ).first()

        eq_(row, (None, None))

    def test_whereclause(self):
        # testing "WHERE <column>" renders a compatible expression
        boolean_table = self.tables.boolean_table

        with config.db.begin() as conn:
            conn.execute(
                boolean_table.insert(),
                [
                    {"id": 1, "value": True, "unconstrained_value": True},
                    {"id": 2, "value": False, "unconstrained_value": False},
                ],
            )

            eq_(
                conn.scalar(
                    select(boolean_table.c.id).where(boolean_table.c.value)
                ),
                1,
            )
            eq_(
                conn.scalar(
                    select(boolean_table.c.id).where(
                        boolean_table.c.unconstrained_value
                    )
                ),
                1,
            )
            eq_(
                conn.scalar(
                    select(boolean_table.c.id).where(~boolean_table.c.value)
                ),
                2,
            )
            eq_(
                conn.scalar(
                    select(boolean_table.c.id).where(
                        ~boolean_table.c.unconstrained_value
                    )
                ),
                2,
            )


class JSONTest(_LiteralRoundTripFixture, fixtures.TablesTest):
    __requires__ = ("json_type",)
    __backend__ = True

    datatype = JSON

    @classmethod
    def define_tables(cls, metadata):
        Table(
            "data_table",
            metadata,
            Column("id", Integer, primary_key=True),
            Column("name", String(30), nullable=False),
            Column("data", cls.datatype, nullable=False),
            Column("nulldata", cls.datatype(none_as_null=True)),
        )

    def test_round_trip_data1(self, connection):
        self._test_round_trip({"key1": "value1", "key2": "value2"}, connection)

    @testing.combinations(
        ("unicode", True), ("ascii", False), argnames="unicode_", id_="ia"
    )
    @testing.combinations(100, 1999, 3000, 4000, 5000, 9000, argnames="length")
    def test_round_trip_pretty_large_data(self, connection, unicode_, length):

        if unicode_:
            data = "rĂ©ve🐍illĂ©" * ((length // 9) + 1)
            data = data[0 : (length // 2)]
        else:
            data = "abcdefg" * ((length // 7) + 1)
            data = data[0:length]

        self._test_round_trip({"key1": data, "key2": data}, connection)

    def _test_round_trip(self, data_element, connection):
        data_table = self.tables.data_table

        connection.execute(
            data_table.insert(),
            {"id": 1, "name": "row1", "data": data_element},
        )

        row = connection.execute(select(data_table.c.data)).first()

        eq_(row, (data_element,))

    def _index_fixtures(include_comparison):

        if include_comparison:
            # basically SQL Server and MariaDB can kind of do json
            # comparison, MySQL, PG and SQLite can't.  not worth it.
            json_elements = []
        else:
            json_elements = [
                ("json", {"foo": "bar"}),
                ("json", ["one", "two", "three"]),
                (None, {"foo": "bar"}),
                (None, ["one", "two", "three"]),
            ]

        elements = [
            ("boolean", True),
            ("boolean", False),
            ("boolean", None),
            ("string", "some string"),
            ("string", None),
            ("string", "réve illé"),
            (
                "string",
                "rĂ©ve🐍 illĂ©",
                testing.requires.json_index_supplementary_unicode_element,
            ),
            ("integer", 15),
            ("integer", 1),
            ("integer", 0),
            ("integer", None),
            ("float", 28.5),
            ("float", None),
            ("float", 1234567.89, testing.requires.literal_float_coercion),
            ("numeric", 1234567.89),
            # this one "works" because the float value you see here is
            # lost immediately to floating point stuff
            (
                "numeric",
                99998969694839.983485848,
            ),
            ("numeric", 99939.983485848),
            ("_decimal", decimal.Decimal("1234567.89")),
            (
                "_decimal",
                decimal.Decimal("99998969694839.983485848"),
                # fails on SQLite and MySQL (non-mariadb)
                requirements.cast_precision_numerics_many_significant_digits,
            ),
            (
                "_decimal",
                decimal.Decimal("99939.983485848"),
            ),
        ] + json_elements

        def decorate(fn):
            fn = testing.combinations(id_="sa", *elements)(fn)

            return fn

        return decorate

    def _json_value_insert(self, connection, datatype, value, data_element):
        data_table = self.tables.data_table
        if datatype == "_decimal":

            # Python's builtin json serializer basically doesn't support
            # Decimal objects without implicit float conversion period.
            # users can otherwise use simplejson which supports
            # precision decimals

            # https://bugs.python.org/issue16535

            # inserting as strings to avoid a new fixture around the
            # dialect which would have idiosyncrasies for different
            # backends.

            class DecimalEncoder(json.JSONEncoder):
                def default(self, o):
                    if isinstance(o, decimal.Decimal):
                        return str(o)
                    return super().default(o)

            json_data = json.dumps(data_element, cls=DecimalEncoder)

            # take the quotes out.  yup, there is *literally* no other
            # way to get Python's json.dumps() to put all the digits in
            # the string
            json_data = re.sub(r'"(%s)"' % str(value), str(value), json_data)

            datatype = "numeric"

            connection.execute(
                data_table.insert().values(
                    name="row1",
                    # to pass the string directly to every backend, including
                    # PostgreSQL which needs the value to be CAST as JSON
                    # both in the SQL as well as at the prepared statement
                    # level for asyncpg, while at the same time MySQL
                    # doesn't even support CAST for JSON, here we are
                    # sending the string embedded in the SQL without using
                    # a parameter.
                    data=bindparam(None, json_data, literal_execute=True),
                    nulldata=bindparam(None, json_data, literal_execute=True),
                ),
            )
        else:
            connection.execute(
                data_table.insert(),
                {
                    "name": "row1",
                    "data": data_element,
                    "nulldata": data_element,
                },
            )

        p_s = None

        if datatype:
            if datatype == "numeric":
                a, b = str(value).split(".")
                s = len(b)
                p = len(a) + s

                if isinstance(value, decimal.Decimal):
                    compare_value = value
                else:
                    compare_value = decimal.Decimal(str(value))

                p_s = (p, s)
            else:
                compare_value = value
        else:
            compare_value = value

        return datatype, compare_value, p_s

    @_index_fixtures(False)
    def test_index_typed_access(self, datatype, value):
        data_table = self.tables.data_table
        data_element = {"key1": value}

        with config.db.begin() as conn:

            datatype, compare_value, p_s = self._json_value_insert(
                conn, datatype, value, data_element
            )

            expr = data_table.c.data["key1"]
            if datatype:
                if datatype == "numeric" and p_s:
                    expr = expr.as_numeric(*p_s)
                else:
                    expr = getattr(expr, "as_%s" % datatype)()

            roundtrip = conn.scalar(select(expr))
            eq_(roundtrip, compare_value)
            is_(type(roundtrip), type(compare_value))

    @_index_fixtures(True)
    def test_index_typed_comparison(self, datatype, value):
        data_table = self.tables.data_table
        data_element = {"key1": value}

        with config.db.begin() as conn:
            datatype, compare_value, p_s = self._json_value_insert(
                conn, datatype, value, data_element
            )

            expr = data_table.c.data["key1"]
            if datatype:
                if datatype == "numeric" and p_s:
                    expr = expr.as_numeric(*p_s)
                else:
                    expr = getattr(expr, "as_%s" % datatype)()

            row = conn.execute(
                select(expr).where(expr == compare_value)
            ).first()

            # make sure we get a row even if value is None
            eq_(row, (compare_value,))

    @_index_fixtures(True)
    def test_path_typed_comparison(self, datatype, value):
        data_table = self.tables.data_table
        data_element = {"key1": {"subkey1": value}}
        with config.db.begin() as conn:

            datatype, compare_value, p_s = self._json_value_insert(
                conn, datatype, value, data_element
            )

            expr = data_table.c.data[("key1", "subkey1")]

            if datatype:
                if datatype == "numeric" and p_s:
                    expr = expr.as_numeric(*p_s)
                else:
                    expr = getattr(expr, "as_%s" % datatype)()

            row = conn.execute(
                select(expr).where(expr == compare_value)
            ).first()

            # make sure we get a row even if value is None
            eq_(row, (compare_value,))

    @testing.combinations(
        (True,),
        (False,),
        (None,),
        (15,),
        (0,),
        (-1,),
        (-1.0,),
        (15.052,),
        ("a string",),
        ("réve illé",),
        ("rĂ©ve🐍 illĂ©",),
    )
    def test_single_element_round_trip(self, element):
        data_table = self.tables.data_table
        data_element = element
        with config.db.begin() as conn:
            conn.execute(
                data_table.insert(),
                {
                    "name": "row1",
                    "data": data_element,
                    "nulldata": data_element,
                },
            )

            row = conn.execute(
                select(data_table.c.data, data_table.c.nulldata)
            ).first()

            eq_(row, (data_element, data_element))

    def test_round_trip_custom_json(self):
        data_table = self.tables.data_table
        data_element = {"key1": "data1"}

        js = mock.Mock(side_effect=json.dumps)
        jd = mock.Mock(side_effect=json.loads)
        engine = engines.testing_engine(
            options=dict(json_serializer=js, json_deserializer=jd)
        )

        # support sqlite :memory: database...
        data_table.create(engine, checkfirst=True)
        with engine.begin() as conn:
            conn.execute(
                data_table.insert(), {"name": "row1", "data": data_element}
            )
            row = conn.execute(select(data_table.c.data)).first()

            eq_(row, (data_element,))
            eq_(js.mock_calls, [mock.call(data_element)])
            if testing.requires.json_deserializer_binary.enabled:
                eq_(
                    jd.mock_calls,
                    [mock.call(json.dumps(data_element).encode())],
                )
            else:
                eq_(jd.mock_calls, [mock.call(json.dumps(data_element))])

    @testing.combinations(
        ("parameters",),
        ("multiparameters",),
        ("values",),
        ("omit",),
        argnames="insert_type",
    )
    def test_round_trip_none_as_sql_null(self, connection, insert_type):
        col = self.tables.data_table.c["nulldata"]

        conn = connection

        if insert_type == "parameters":
            stmt, params = self.tables.data_table.insert(), {
                "name": "r1",
                "nulldata": None,
                "data": None,
            }
        elif insert_type == "multiparameters":
            stmt, params = self.tables.data_table.insert(), [
                {"name": "r1", "nulldata": None, "data": None}
            ]
        elif insert_type == "values":
            stmt, params = (
                self.tables.data_table.insert().values(
                    name="r1",
                    nulldata=None,
                    data=None,
                ),
                {},
            )
        elif insert_type == "omit":
            stmt, params = (
                self.tables.data_table.insert(),
                {"name": "r1", "data": None},
            )

        else:
            assert False

        conn.execute(stmt, params)

        eq_(
            conn.scalar(
                select(self.tables.data_table.c.name).where(col.is_(null()))
            ),
            "r1",
        )

        eq_(conn.scalar(select(col)), None)

    def test_round_trip_json_null_as_json_null(self, connection):
        col = self.tables.data_table.c["data"]

        conn = connection
        conn.execute(
            self.tables.data_table.insert(),
            {"name": "r1", "data": JSON.NULL},
        )

        eq_(
            conn.scalar(
                select(self.tables.data_table.c.name).where(
                    cast(col, String) == "null"
                )
            ),
            "r1",
        )

        eq_(conn.scalar(select(col)), None)

    @testing.combinations(
        ("parameters",),
        ("multiparameters",),
        ("values",),
        argnames="insert_type",
    )
    def test_round_trip_none_as_json_null(self, connection, insert_type):
        col = self.tables.data_table.c["data"]

        if insert_type == "parameters":
            stmt, params = self.tables.data_table.insert(), {
                "name": "r1",
                "data": None,
            }
        elif insert_type == "multiparameters":
            stmt, params = self.tables.data_table.insert(), [
                {"name": "r1", "data": None}
            ]
        elif insert_type == "values":
            stmt, params = (
                self.tables.data_table.insert().values(name="r1", data=None),
                {},
            )
        else:
            assert False

        conn = connection
        conn.execute(stmt, params)

        eq_(
            conn.scalar(
                select(self.tables.data_table.c.name).where(
                    cast(col, String) == "null"
                )
            ),
            "r1",
        )

        eq_(conn.scalar(select(col)), None)

    def test_unicode_round_trip(self):
        # note we include Unicode supplementary characters as well
        with config.db.begin() as conn:
            conn.execute(
                self.tables.data_table.insert(),
                {
                    "name": "r1",
                    "data": {
                        "rĂ©ve🐍 illĂ©": "rĂ©ve🐍 illĂ©",
                        "data": {"k1": "drîl🐍e"},
                    },
                },
            )

            eq_(
                conn.scalar(select(self.tables.data_table.c.data)),
                {
                    "rĂ©ve🐍 illĂ©": "rĂ©ve🐍 illĂ©",
                    "data": {"k1": "drîl🐍e"},
                },
            )

    def test_eval_none_flag_orm(self, connection):

        Base = declarative_base()

        class Data(Base):
            __table__ = self.tables.data_table

        with Session(connection) as s:
            d1 = Data(name="d1", data=None, nulldata=None)
            s.add(d1)
            s.commit()

            s.bulk_insert_mappings(
                Data, [{"name": "d2", "data": None, "nulldata": None}]
            )
            eq_(
                s.query(
                    cast(self.tables.data_table.c.data, String()),
                    cast(self.tables.data_table.c.nulldata, String),
                )
                .filter(self.tables.data_table.c.name == "d1")
                .first(),
                ("null", None),
            )
            eq_(
                s.query(
                    cast(self.tables.data_table.c.data, String()),
                    cast(self.tables.data_table.c.nulldata, String),
                )
                .filter(self.tables.data_table.c.name == "d2")
                .first(),
                ("null", None),
            )


class JSONLegacyStringCastIndexTest(
    _LiteralRoundTripFixture, fixtures.TablesTest
):
    """test JSON index access with "cast to string", which we have documented
    for a long time as how to compare JSON values, but is ultimately not
    reliable in all cases.   The "as_XYZ()" comparators should be used
    instead.

    """

    __requires__ = ("json_type", "legacy_unconditional_json_extract")
    __backend__ = True

    datatype = JSON

    data1 = {"key1": "value1", "key2": "value2"}

    data2 = {
        "Key 'One'": "value1",
        "key two": "value2",
        "key three": "value ' three '",
    }

    data3 = {
        "key1": [1, 2, 3],
        "key2": ["one", "two", "three"],
        "key3": [{"four": "five"}, {"six": "seven"}],
    }

    data4 = ["one", "two", "three"]

    data5 = {
        "nested": {
            "elem1": [{"a": "b", "c": "d"}, {"e": "f", "g": "h"}],
            "elem2": {"elem3": {"elem4": "elem5"}},
        }
    }

    data6 = {"a": 5, "b": "some value", "c": {"foo": "bar"}}

    @classmethod
    def define_tables(cls, metadata):
        Table(
            "data_table",
            metadata,
            Column("id", Integer, primary_key=True),
            Column("name", String(30), nullable=False),
            Column("data", cls.datatype),
            Column("nulldata", cls.datatype(none_as_null=True)),
        )

    def _criteria_fixture(self):
        with config.db.begin() as conn:
            conn.execute(
                self.tables.data_table.insert(),
                [
                    {"name": "r1", "data": self.data1},
                    {"name": "r2", "data": self.data2},
                    {"name": "r3", "data": self.data3},
                    {"name": "r4", "data": self.data4},
                    {"name": "r5", "data": self.data5},
                    {"name": "r6", "data": self.data6},
                ],
            )

    def _test_index_criteria(self, crit, expected, test_literal=True):
        self._criteria_fixture()
        with config.db.connect() as conn:
            stmt = select(self.tables.data_table.c.name).where(crit)

            eq_(conn.scalar(stmt), expected)

            if test_literal:
                literal_sql = str(
                    stmt.compile(
                        config.db, compile_kwargs={"literal_binds": True}
                    )
                )

                eq_(conn.exec_driver_sql(literal_sql).scalar(), expected)

    def test_string_cast_crit_spaces_in_key(self):
        name = self.tables.data_table.c.name
        col = self.tables.data_table.c["data"]

        # limit the rows here to avoid PG error
        # "cannot extract field from a non-object", which is
        # fixed in 9.4 but may exist in 9.3
        self._test_index_criteria(
            and_(
                name.in_(["r1", "r2", "r3"]),
                cast(col["key two"], String) == '"value2"',
            ),
            "r2",
        )

    @config.requirements.json_array_indexes
    def test_string_cast_crit_simple_int(self):
        name = self.tables.data_table.c.name
        col = self.tables.data_table.c["data"]

        # limit the rows here to avoid PG error
        # "cannot extract array element from a non-array", which is
        # fixed in 9.4 but may exist in 9.3
        self._test_index_criteria(
            and_(
                name == "r4",
                cast(col[1], String) == '"two"',
            ),
            "r4",
        )

    def test_string_cast_crit_mixed_path(self):
        col = self.tables.data_table.c["data"]
        self._test_index_criteria(
            cast(col[("key3", 1, "six")], String) == '"seven"',
            "r3",
        )

    def test_string_cast_crit_string_path(self):
        col = self.tables.data_table.c["data"]
        self._test_index_criteria(
            cast(col[("nested", "elem2", "elem3", "elem4")], String)
            == '"elem5"',
            "r5",
        )

    def test_string_cast_crit_against_string_basic(self):
        name = self.tables.data_table.c.name
        col = self.tables.data_table.c["data"]

        self._test_index_criteria(
            and_(
                name == "r6",
                cast(col["b"], String) == '"some value"',
            ),
            "r6",
        )


class UuidTest(_LiteralRoundTripFixture, fixtures.TablesTest):
    __backend__ = True

    datatype = Uuid

    @classmethod
    def define_tables(cls, metadata):
        Table(
            "uuid_table",
            metadata,
            Column(
                "id", Integer, primary_key=True, test_needs_autoincrement=True
            ),
            Column("uuid_data", cls.datatype),
            Column("uuid_text_data", cls.datatype(as_uuid=False)),
            Column("uuid_data_nonnative", Uuid(native_uuid=False)),
            Column(
                "uuid_text_data_nonnative",
                Uuid(as_uuid=False, native_uuid=False),
            ),
        )

    def test_uuid_round_trip(self, connection):
        data = uuid.uuid4()
        uuid_table = self.tables.uuid_table

        connection.execute(
            uuid_table.insert(),
            {"id": 1, "uuid_data": data, "uuid_data_nonnative": data},
        )
        row = connection.execute(
            select(
                uuid_table.c.uuid_data, uuid_table.c.uuid_data_nonnative
            ).where(
                uuid_table.c.uuid_data == data,
                uuid_table.c.uuid_data_nonnative == data,
            )
        ).first()
        eq_(row, (data, data))

    def test_uuid_text_round_trip(self, connection):
        data = str(uuid.uuid4())
        uuid_table = self.tables.uuid_table

        connection.execute(
            uuid_table.insert(),
            {
                "id": 1,
                "uuid_text_data": data,
                "uuid_text_data_nonnative": data,
            },
        )
        row = connection.execute(
            select(
                uuid_table.c.uuid_text_data,
                uuid_table.c.uuid_text_data_nonnative,
            ).where(
                uuid_table.c.uuid_text_data == data,
                uuid_table.c.uuid_text_data_nonnative == data,
            )
        ).first()
        eq_((row[0].lower(), row[1].lower()), (data, data))

    def test_literal_uuid(self, literal_round_trip):
        data = uuid.uuid4()
        literal_round_trip(self.datatype, [data], [data])

    def test_literal_text(self, literal_round_trip):
        data = str(uuid.uuid4())
        literal_round_trip(
            self.datatype(as_uuid=False),
            [data],
            [data],
            filter_=lambda x: x.lower(),
        )

    def test_literal_nonnative_uuid(self, literal_round_trip):
        data = uuid.uuid4()
        literal_round_trip(Uuid(native_uuid=False), [data], [data])

    def test_literal_nonnative_text(self, literal_round_trip):
        data = str(uuid.uuid4())
        literal_round_trip(
            Uuid(as_uuid=False, native_uuid=False),
            [data],
            [data],
            filter_=lambda x: x.lower(),
        )

    @testing.requires.insert_returning
    def test_uuid_returning(self, connection):
        data = uuid.uuid4()
        str_data = str(data)
        uuid_table = self.tables.uuid_table

        result = connection.execute(
            uuid_table.insert().returning(
                uuid_table.c.uuid_data,
                uuid_table.c.uuid_text_data,
                uuid_table.c.uuid_data_nonnative,
                uuid_table.c.uuid_text_data_nonnative,
            ),
            {
                "id": 1,
                "uuid_data": data,
                "uuid_text_data": str_data,
                "uuid_data_nonnative": data,
                "uuid_text_data_nonnative": str_data,
            },
        )
        row = result.first()

        eq_(row, (data, str_data, data, str_data))


class NativeUUIDTest(UuidTest):
    __requires__ = ("uuid_data_type",)

    datatype = UUID


__all__ = (
    "ArrayTest",
    "BinaryTest",
    "UnicodeVarcharTest",
    "UnicodeTextTest",
    "JSONTest",
    "JSONLegacyStringCastIndexTest",
    "DateTest",
    "DateTimeTest",
    "DateTimeTZTest",
    "TextTest",
    "NumericTest",
    "IntegerTest",
    "CastTypeDecoratorTest",
    "DateTimeHistoricTest",
    "DateTimeCoercedToDateTimeTest",
    "TimeMicrosecondsTest",
    "TimestampMicrosecondsTest",
    "TimeTest",
    "TimeTZTest",
    "TrueDivTest",
    "DateTimeMicrosecondsTest",
    "DateHistoricTest",
    "StringTest",
    "BooleanTest",
    "UuidTest",
    "NativeUUIDTest",
)