File: test_reflection.py

package info (click to toggle)
sqlalchemy 2.0.44%2Bds1-1
  • links: PTS
  • area: main
  • in suites: forky, sid
  • size: 26,740 kB
  • sloc: python: 414,900; makefile: 231; sh: 7
file content (1336 lines) | stat: -rw-r--r-- 46,569 bytes parent folder | download
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
"""SQLite-specific tests."""

from sqlalchemy import CheckConstraint
from sqlalchemy import Column
from sqlalchemy import DDL
from sqlalchemy import event
from sqlalchemy import exc
from sqlalchemy import Index
from sqlalchemy import inspect
from sqlalchemy import MetaData
from sqlalchemy import PrimaryKeyConstraint
from sqlalchemy import Table
from sqlalchemy import testing
from sqlalchemy import types as sqltypes
from sqlalchemy import UniqueConstraint
from sqlalchemy.dialects.sqlite import base as sqlite
from sqlalchemy.sql.elements import quoted_name
from sqlalchemy.testing import assert_raises_message
from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
from sqlalchemy.testing import is_
from sqlalchemy.testing import is_true
from sqlalchemy.testing import mock
from sqlalchemy.types import Integer
from sqlalchemy.types import String


def exec_sql(engine, sql, *args, **kwargs):
    # TODO: convert all tests to not use this
    with engine.begin() as conn:
        conn.exec_driver_sql(sql, *args, **kwargs)


class ReflectHeadlessFKsTest(fixtures.TestBase):
    __only_on__ = "sqlite"
    __backend__ = True

    def setup_test(self):
        exec_sql(testing.db, "CREATE TABLE a (id INTEGER PRIMARY KEY)")
        # this syntax actually works on other DBs perhaps we'd want to add
        # tests to test_reflection
        exec_sql(
            testing.db, "CREATE TABLE b (id INTEGER PRIMARY KEY REFERENCES a)"
        )

    def teardown_test(self):
        exec_sql(testing.db, "drop table b")
        exec_sql(testing.db, "drop table a")

    def test_reflect_tables_fk_no_colref(self):
        meta = MetaData()
        a = Table("a", meta, autoload_with=testing.db)
        b = Table("b", meta, autoload_with=testing.db)

        assert b.c.id.references(a.c.id)


class KeywordInDatabaseNameTest(fixtures.TestBase):
    __only_on__ = "sqlite"
    __backend__ = True

    @testing.fixture
    def db_fixture(self, connection):
        connection.exec_driver_sql(
            'ATTACH %r AS "default"' % connection.engine.url.database
        )
        connection.exec_driver_sql(
            'CREATE TABLE "default".a (id INTEGER PRIMARY KEY)'
        )
        try:
            yield
        finally:
            connection.exec_driver_sql('drop table "default".a')
            connection.exec_driver_sql('DETACH DATABASE "default"')

    def test_reflect(self, connection, db_fixture):
        meta = MetaData(schema="default")
        meta.reflect(connection)
        assert "default.a" in meta.tables


class ConstraintReflectionTest(fixtures.TestBase):
    __only_on__ = "sqlite"
    __backend__ = True

    @classmethod
    def setup_test_class(cls):
        with testing.db.begin() as conn:
            conn.exec_driver_sql("CREATE TABLE a1 (id INTEGER PRIMARY KEY)")
            conn.exec_driver_sql("CREATE TABLE a2 (id INTEGER PRIMARY KEY)")
            conn.exec_driver_sql(
                "CREATE TABLE b (id INTEGER PRIMARY KEY, "
                "FOREIGN KEY(id) REFERENCES a1(id),"
                "FOREIGN KEY(id) REFERENCES a2(id)"
                ")"
            )
            conn.exec_driver_sql(
                "CREATE TABLE c (id INTEGER, "
                "CONSTRAINT bar PRIMARY KEY(id),"
                "CONSTRAINT foo1 FOREIGN KEY(id) REFERENCES a1(id),"
                "CONSTRAINT foo2 FOREIGN KEY(id) REFERENCES a2(id)"
                ")"
            )
            conn.exec_driver_sql(
                # the lower casing + inline is intentional here
                "CREATE TABLE d (id INTEGER, x INTEGER unique)"
            )
            conn.exec_driver_sql(
                # the lower casing + inline is intentional here
                "CREATE TABLE d1 "
                '(id INTEGER, "some ( STUPID n,ame" INTEGER unique)'
            )
            conn.exec_driver_sql(
                # the lower casing + inline is intentional here
                'CREATE TABLE d2 ( "some STUPID n,ame" INTEGER unique)'
            )
            conn.exec_driver_sql(
                # the lower casing + inline is intentional here
                'CREATE TABLE d3 ( "some STUPID n,ame" INTEGER NULL unique)'
            )

            conn.exec_driver_sql(
                # lower casing + inline is intentional
                "CREATE TABLE e (id INTEGER, x INTEGER references a2(id))"
            )
            conn.exec_driver_sql(
                'CREATE TABLE e1 (id INTEGER, "some ( STUPID n,ame" INTEGER '
                'references a2   ("some ( STUPID n,ame"))'
            )
            conn.exec_driver_sql(
                "CREATE TABLE e2 (id INTEGER, "
                '"some ( STUPID n,ame" INTEGER NOT NULL  '
                'references a2   ("some ( STUPID n,ame"))'
            )

            conn.exec_driver_sql(
                "CREATE TABLE f (x INTEGER, CONSTRAINT foo_fx UNIQUE(x))"
            )
            conn.exec_driver_sql(
                # intentional broken casing
                "CREATE TABLE h (x INTEGER, COnstraINT foo_hx unIQUE(x))"
            )
            conn.exec_driver_sql(
                "CREATE TABLE i (x INTEGER, y INTEGER, PRIMARY KEY(x, y))"
            )
            conn.exec_driver_sql(
                "CREATE TABLE j (id INTEGER, q INTEGER, p INTEGER, "
                "PRIMARY KEY(id), FOreiGN KEY(q,p) REFERENCes  i(x,y))"
            )
            conn.exec_driver_sql(
                "CREATE TABLE k (id INTEGER, q INTEGER, p INTEGER, "
                "PRIMARY KEY(id), "
                "conSTRAINT my_fk FOreiGN KEY (  q  , p  )   "
                "REFERENCes   i    (  x ,   y ))"
            )

            meta = MetaData()
            Table("l", meta, Column("bar", String, index=True), schema="main")

            Table(
                "m",
                meta,
                Column("id", Integer, primary_key=True),
                Column("x", String(30)),
                UniqueConstraint("x"),
            )

            Table(
                "p",
                meta,
                Column("id", Integer),
                PrimaryKeyConstraint("id", name="pk_name"),
            )

            Table("q", meta, Column("id", Integer), PrimaryKeyConstraint("id"))

            # intentional new line
            Table(
                "r",
                meta,
                Column("id", Integer),
                Column("value", Integer),
                Column("prefix", String),
                CheckConstraint("id > 0"),
                UniqueConstraint("prefix", name="prefix_named"),
                # Constraint definition with newline and tab characters
                CheckConstraint(
                    """((value > 0) AND \n\t(value < 100) AND \n\t
                      (value != 50))""",
                    name="ck_r_value_multiline",
                ),
                UniqueConstraint("value"),
                # Constraint name with special chars and 'check' in the name
                CheckConstraint("value IS NOT NULL", name="^check-r* #\n\t"),
                PrimaryKeyConstraint("id", name="pk_name"),
                # Constraint definition with special characters.
                CheckConstraint("prefix NOT GLOB '*[^-. /#,]*'"),
            )

            meta.create_all(conn)

            # will contain an "autoindex"
            conn.exec_driver_sql(
                "create table o (foo varchar(20) primary key)"
            )
            conn.exec_driver_sql(
                "CREATE TABLE onud_test (id INTEGER PRIMARY KEY, "
                "c1 INTEGER, c2 INTEGER, c3 INTEGER, c4 INTEGER, "
                "CONSTRAINT fk1 FOREIGN KEY (c1) REFERENCES a1(id) "
                "ON DELETE SET NULL, "
                "CONSTRAINT fk2 FOREIGN KEY (c2) REFERENCES a1(id) "
                "ON UPDATE CASCADE, "
                "CONSTRAINT fk3 FOREIGN KEY (c3) REFERENCES a2(id) "
                "ON DELETE CASCADE ON UPDATE SET NULL,"
                "CONSTRAINT fk4 FOREIGN KEY (c4) REFERENCES a2(id) "
                "ON UPDATE NO ACTION)"
            )

            conn.exec_driver_sql(
                "CREATE TABLE deferrable_test (id INTEGER PRIMARY KEY, "
                "c1 INTEGER, c2 INTEGER, c3 INTEGER, c4 INTEGER, "
                "CONSTRAINT fk1 FOREIGN KEY (c1) REFERENCES a1(id) "
                "DEFERRABLE,"
                "CONSTRAINT fk2 FOREIGN KEY (c2) REFERENCES a1(id) "
                "NOT DEFERRABLE,"
                "CONSTRAINT fk3 FOREIGN KEY (c3) REFERENCES a2(id) "
                "ON UPDATE CASCADE "
                "DEFERRABLE INITIALLY DEFERRED,"
                "CONSTRAINT fk4 FOREIGN KEY (c4) REFERENCES a2(id) "
                "NOT DEFERRABLE INITIALLY IMMEDIATE)"
            )

            conn.exec_driver_sql(
                "CREATE TABLE cp ("
                "id INTEGER NOT NULL,\n"
                "q INTEGER, \n"
                "p INTEGER, \n"
                "CONSTRAINT cq CHECK (p = 1 OR (p > 2 AND p < 5)),\n"
                "PRIMARY KEY (id)\n"
                ")"
            )

            conn.exec_driver_sql(
                "CREATE TABLE cp_inline (\n"
                "id INTEGER NOT NULL,\n"
                "q INTEGER CHECK (q > 1 AND q < 6), \n"
                "p INTEGER CONSTRAINT cq CHECK (p = 1 OR (p > 2 AND p < 5)),\n"
                "PRIMARY KEY (id)\n"
                ")"
            )

            conn.exec_driver_sql(
                "CREATE TABLE implicit_referred (pk integer primary key)"
            )
            # single col foreign key with no referred column given,
            # must assume primary key of referred table
            conn.exec_driver_sql(
                "CREATE TABLE implicit_referrer "
                "(id integer REFERENCES implicit_referred)"
            )

            conn.exec_driver_sql(
                "CREATE TABLE implicit_referred_comp "
                "(pk1 integer, pk2 integer, primary key (pk1, pk2))"
            )
            # composite foreign key with no referred columns given,
            # must assume primary key of referred table
            conn.exec_driver_sql(
                "CREATE TABLE implicit_referrer_comp "
                "(id1 integer, id2 integer, foreign key(id1, id2) "
                "REFERENCES implicit_referred_comp)"
            )

            # worst case - FK that refers to nonexistent table so we can't
            # get pks.  requires FK pragma is turned off
            conn.exec_driver_sql(
                "CREATE TABLE implicit_referrer_comp_fake "
                "(id1 integer, id2 integer, foreign key(id1, id2) "
                "REFERENCES fake_table)"
            )

    @classmethod
    def teardown_test_class(cls):
        with testing.db.begin() as conn:
            for name in [
                "implicit_referrer_comp_fake",
                "implicit_referrer",
                "implicit_referred",
                "implicit_referrer_comp",
                "implicit_referred_comp",
                "m",
                "main.l",
                "k",
                "j",
                "i",
                "h",
                "f",
                "e",
                "e1",
                "d",
                "d1",
                "d2",
                "c",
                "b",
                "a1",
                "a2",
                "r",
            ]:
                conn.exec_driver_sql("drop table %s" % name)

    @testing.fixture
    def temp_table_fixture(self, connection):
        connection.exec_driver_sql(
            "CREATE TEMPORARY TABLE g "
            "(x INTEGER, CONSTRAINT foo_gx UNIQUE(x))"
        )

        n = Table(
            "n",
            MetaData(),
            Column("id", Integer, primary_key=True),
            Column("x", String(30)),
            UniqueConstraint("x"),
            prefixes=["TEMPORARY"],
        )

        n.create(connection)
        try:
            yield
        finally:
            connection.exec_driver_sql("DROP TABLE g")
            n.drop(connection)

    def test_legacy_quoted_identifiers_unit(self):
        dialect = sqlite.dialect()
        dialect._broken_fk_pragma_quotes = True

        for row in [
            (0, None, "target", "tid", "id", None),
            (0, None, '"target"', "tid", "id", None),
            (0, None, "[target]", "tid", "id", None),
            (0, None, "'target'", "tid", "id", None),
            (0, None, "`target`", "tid", "id", None),
        ]:

            def _get_table_pragma(*arg, **kw):
                return [row]

            def _get_table_sql(*arg, **kw):
                return (
                    "CREATE TABLE foo "
                    "(tid INTEGER, "
                    "FOREIGN KEY(tid) REFERENCES %s (id))" % row[2]
                )

            with mock.patch.object(
                dialect, "_get_table_pragma", _get_table_pragma
            ):
                with mock.patch.object(
                    dialect, "_get_table_sql", _get_table_sql
                ):
                    fkeys = dialect.get_foreign_keys(None, "foo")
                    eq_(
                        fkeys,
                        [
                            {
                                "referred_table": "target",
                                "referred_columns": ["id"],
                                "referred_schema": None,
                                "name": None,
                                "constrained_columns": ["tid"],
                                "options": {},
                            }
                        ],
                    )

    def test_foreign_key_name_is_none(self):
        # and not "0"
        inspector = inspect(testing.db)
        fks = inspector.get_foreign_keys("b")
        eq_(
            fks,
            [
                {
                    "referred_table": "a1",
                    "referred_columns": ["id"],
                    "referred_schema": None,
                    "name": None,
                    "constrained_columns": ["id"],
                    "options": {},
                },
                {
                    "referred_table": "a2",
                    "referred_columns": ["id"],
                    "referred_schema": None,
                    "name": None,
                    "constrained_columns": ["id"],
                    "options": {},
                },
            ],
        )

    def test_foreign_key_name_is_not_none(self):
        inspector = inspect(testing.db)
        fks = inspector.get_foreign_keys("c")
        eq_(
            fks,
            [
                {
                    "referred_table": "a1",
                    "referred_columns": ["id"],
                    "referred_schema": None,
                    "name": "foo1",
                    "constrained_columns": ["id"],
                    "options": {},
                },
                {
                    "referred_table": "a2",
                    "referred_columns": ["id"],
                    "referred_schema": None,
                    "name": "foo2",
                    "constrained_columns": ["id"],
                    "options": {},
                },
            ],
        )

    def test_foreign_key_implicit_parent(self):
        inspector = inspect(testing.db)
        fks = inspector.get_foreign_keys("implicit_referrer")
        eq_(
            fks,
            [
                {
                    "name": None,
                    "constrained_columns": ["id"],
                    "referred_schema": None,
                    "referred_table": "implicit_referred",
                    "referred_columns": ["pk"],
                    "options": {},
                }
            ],
        )

    def test_foreign_key_composite_implicit_parent(self):
        inspector = inspect(testing.db)
        fks = inspector.get_foreign_keys("implicit_referrer_comp")
        eq_(
            fks,
            [
                {
                    "name": None,
                    "constrained_columns": ["id1", "id2"],
                    "referred_schema": None,
                    "referred_table": "implicit_referred_comp",
                    "referred_columns": ["pk1", "pk2"],
                    "options": {},
                }
            ],
        )

    def test_foreign_key_implicit_missing_parent(self):
        # test when the FK refers to a non-existent table and column names
        # aren't given.   only sqlite allows this case to exist
        inspector = inspect(testing.db)
        fks = inspector.get_foreign_keys("implicit_referrer_comp_fake")
        # the referred table doesn't exist but the operation does not fail
        eq_(
            fks,
            [
                {
                    "name": None,
                    "constrained_columns": ["id1", "id2"],
                    "referred_schema": None,
                    "referred_table": "fake_table",
                    "referred_columns": [],
                    "options": {},
                }
            ],
        )

    def test_foreign_key_implicit_missing_parent_reflection(self):
        # full Table reflection fails however, which is not a new behavior
        m = MetaData()
        assert_raises_message(
            exc.NoSuchTableError,
            "fake_table",
            Table,
            "implicit_referrer_comp_fake",
            m,
            autoload_with=testing.db,
        )

    def test_unnamed_inline_foreign_key(self):
        inspector = inspect(testing.db)
        fks = inspector.get_foreign_keys("e")
        eq_(
            fks,
            [
                {
                    "referred_table": "a2",
                    "referred_columns": ["id"],
                    "referred_schema": None,
                    "name": None,
                    "constrained_columns": ["x"],
                    "options": {},
                }
            ],
        )

    def test_unnamed_inline_foreign_key_quoted(self):
        inspector = inspect(testing.db)
        fks = inspector.get_foreign_keys("e1")
        eq_(
            fks,
            [
                {
                    "referred_table": "a2",
                    "referred_columns": ["some ( STUPID n,ame"],
                    "referred_schema": None,
                    "options": {},
                    "name": None,
                    "constrained_columns": ["some ( STUPID n,ame"],
                }
            ],
        )
        fks = inspector.get_foreign_keys("e2")
        eq_(
            fks,
            [
                {
                    "referred_table": "a2",
                    "referred_columns": ["some ( STUPID n,ame"],
                    "referred_schema": None,
                    "options": {},
                    "name": None,
                    "constrained_columns": ["some ( STUPID n,ame"],
                }
            ],
        )

    def test_foreign_key_composite_broken_casing(self):
        inspector = inspect(testing.db)
        fks = inspector.get_foreign_keys("j")
        eq_(
            fks,
            [
                {
                    "referred_table": "i",
                    "referred_columns": ["x", "y"],
                    "referred_schema": None,
                    "name": None,
                    "constrained_columns": ["q", "p"],
                    "options": {},
                }
            ],
        )
        fks = inspector.get_foreign_keys("k")
        eq_(
            fks,
            [
                {
                    "referred_table": "i",
                    "referred_columns": ["x", "y"],
                    "referred_schema": None,
                    "name": "my_fk",
                    "constrained_columns": ["q", "p"],
                    "options": {},
                }
            ],
        )

    def test_foreign_key_ondelete_onupdate(self):
        inspector = inspect(testing.db)
        fks = inspector.get_foreign_keys("onud_test")
        eq_(
            fks,
            [
                {
                    "referred_table": "a1",
                    "referred_columns": ["id"],
                    "referred_schema": None,
                    "name": "fk1",
                    "constrained_columns": ["c1"],
                    "options": {"ondelete": "SET NULL"},
                },
                {
                    "referred_table": "a1",
                    "referred_columns": ["id"],
                    "referred_schema": None,
                    "name": "fk2",
                    "constrained_columns": ["c2"],
                    "options": {"onupdate": "CASCADE"},
                },
                {
                    "referred_table": "a2",
                    "referred_columns": ["id"],
                    "referred_schema": None,
                    "name": "fk3",
                    "constrained_columns": ["c3"],
                    "options": {"ondelete": "CASCADE", "onupdate": "SET NULL"},
                },
                {
                    "referred_table": "a2",
                    "referred_columns": ["id"],
                    "referred_schema": None,
                    "name": "fk4",
                    "constrained_columns": ["c4"],
                    "options": {},
                },
            ],
        )

    def test_foreign_key_deferrable_initially(self):
        inspector = inspect(testing.db)
        fks = inspector.get_foreign_keys("deferrable_test")
        eq_(
            fks,
            [
                {
                    "referred_table": "a1",
                    "referred_columns": ["id"],
                    "referred_schema": None,
                    "name": "fk1",
                    "constrained_columns": ["c1"],
                    "options": {"deferrable": True},
                },
                {
                    "referred_table": "a1",
                    "referred_columns": ["id"],
                    "referred_schema": None,
                    "name": "fk2",
                    "constrained_columns": ["c2"],
                    "options": {"deferrable": False},
                },
                {
                    "referred_table": "a2",
                    "referred_columns": ["id"],
                    "referred_schema": None,
                    "name": "fk3",
                    "constrained_columns": ["c3"],
                    "options": {
                        "deferrable": True,
                        "initially": "DEFERRED",
                        "onupdate": "CASCADE",
                    },
                },
                {
                    "referred_table": "a2",
                    "referred_columns": ["id"],
                    "referred_schema": None,
                    "name": "fk4",
                    "constrained_columns": ["c4"],
                    "options": {"deferrable": False, "initially": "IMMEDIATE"},
                },
            ],
        )

    def test_foreign_key_options_unnamed_inline(self):
        with testing.db.begin() as conn:
            conn.exec_driver_sql(
                "create table foo (id integer, "
                "foreign key (id) references bar (id) on update cascade)"
            )

            insp = inspect(conn)
            eq_(
                insp.get_foreign_keys("foo"),
                [
                    {
                        "name": None,
                        "referred_columns": ["id"],
                        "referred_table": "bar",
                        "constrained_columns": ["id"],
                        "referred_schema": None,
                        "options": {"onupdate": "CASCADE"},
                    }
                ],
            )

    def test_dont_reflect_autoindex(self):
        inspector = inspect(testing.db)
        eq_(inspector.get_indexes("o"), [])
        eq_(
            inspector.get_indexes("o", include_auto_indexes=True),
            [
                {
                    "unique": 1,
                    "name": "sqlite_autoindex_o_1",
                    "column_names": ["foo"],
                    "dialect_options": {},
                }
            ],
        )

    def test_create_index_with_schema(self):
        """Test creation of index with explicit schema"""

        inspector = inspect(testing.db)
        eq_(
            inspector.get_indexes("l", schema="main"),
            [
                {
                    "unique": 0,
                    "name": "ix_main_l_bar",
                    "column_names": ["bar"],
                    "dialect_options": {},
                }
            ],
        )

    @testing.requires.sqlite_partial_indexes
    def test_reflect_partial_indexes(self, connection):
        connection.exec_driver_sql(
            "create table foo_with_partial_index (x integer, y integer)"
        )
        connection.exec_driver_sql(
            "create unique index ix_partial on "
            "foo_with_partial_index (x) where y > 10"
        )
        connection.exec_driver_sql(
            "create unique index ix_no_partial on "
            "foo_with_partial_index (x)"
        )
        connection.exec_driver_sql(
            "create unique index ix_partial2 on "
            "foo_with_partial_index (x, y) where "
            "y = 10 or abs(x) < 5"
        )

        inspector = inspect(connection)
        indexes = inspector.get_indexes("foo_with_partial_index")
        eq_(
            indexes,
            [
                {
                    "unique": 1,
                    "name": "ix_no_partial",
                    "column_names": ["x"],
                    "dialect_options": {},
                },
                {
                    "unique": 1,
                    "name": "ix_partial",
                    "column_names": ["x"],
                    "dialect_options": {"sqlite_where": mock.ANY},
                },
                {
                    "unique": 1,
                    "name": "ix_partial2",
                    "column_names": ["x", "y"],
                    "dialect_options": {"sqlite_where": mock.ANY},
                },
            ],
        )
        eq_(indexes[1]["dialect_options"]["sqlite_where"].text, "y > 10")
        eq_(
            indexes[2]["dialect_options"]["sqlite_where"].text,
            "y = 10 or abs(x) < 5",
        )

    def test_unique_constraint_named(self):
        inspector = inspect(testing.db)
        eq_(
            inspector.get_unique_constraints("f"),
            [{"column_names": ["x"], "name": "foo_fx"}],
        )

    def test_unique_constraint_named_broken_casing(self):
        inspector = inspect(testing.db)
        eq_(
            inspector.get_unique_constraints("h"),
            [{"column_names": ["x"], "name": "foo_hx"}],
        )

    def test_unique_constraint_named_broken_temp(
        self, connection, temp_table_fixture
    ):
        inspector = inspect(connection)
        eq_(
            inspector.get_unique_constraints("g"),
            [{"column_names": ["x"], "name": "foo_gx"}],
        )

    def test_unique_constraint_unnamed_inline(self):
        inspector = inspect(testing.db)
        eq_(
            inspector.get_unique_constraints("d"),
            [{"column_names": ["x"], "name": None}],
        )

    def test_unique_constraint_unnamed_inline_quoted(self):
        inspector = inspect(testing.db)
        eq_(
            inspector.get_unique_constraints("d1"),
            [{"column_names": ["some ( STUPID n,ame"], "name": None}],
        )
        eq_(
            inspector.get_unique_constraints("d2"),
            [{"column_names": ["some STUPID n,ame"], "name": None}],
        )
        eq_(
            inspector.get_unique_constraints("d3"),
            [{"column_names": ["some STUPID n,ame"], "name": None}],
        )

    def test_unique_constraint_unnamed_normal(self):
        inspector = inspect(testing.db)
        eq_(
            inspector.get_unique_constraints("m"),
            [{"column_names": ["x"], "name": None}],
        )

    def test_unique_constraint_unnamed_normal_temporary(
        self, connection, temp_table_fixture
    ):
        inspector = inspect(connection)
        eq_(
            inspector.get_unique_constraints("n"),
            [{"column_names": ["x"], "name": None}],
        )

    def test_unique_constraint_mixed_into_ck(self, connection):
        """test #11832"""

        inspector = inspect(connection)
        eq_(
            inspector.get_unique_constraints("r"),
            [
                {"name": "prefix_named", "column_names": ["prefix"]},
                {"name": None, "column_names": ["value"]},
            ],
        )

    def test_primary_key_constraint_mixed_into_ck(self, connection):
        """test #11832"""

        inspector = inspect(connection)
        eq_(
            inspector.get_pk_constraint("r"),
            {"constrained_columns": ["id"], "name": "pk_name"},
        )

    def test_primary_key_constraint_named(self):
        inspector = inspect(testing.db)
        eq_(
            inspector.get_pk_constraint("p"),
            {"constrained_columns": ["id"], "name": "pk_name"},
        )

    def test_primary_key_constraint_unnamed(self):
        inspector = inspect(testing.db)
        eq_(
            inspector.get_pk_constraint("q"),
            {"constrained_columns": ["id"], "name": None},
        )

    def test_primary_key_constraint_no_pk(self):
        inspector = inspect(testing.db)
        eq_(
            inspector.get_pk_constraint("d"),
            {"constrained_columns": [], "name": None},
        )

    def test_check_constraint_plain(self):
        inspector = inspect(testing.db)
        eq_(
            inspector.get_check_constraints("cp"),
            [
                {"sqltext": "p = 1 OR (p > 2 AND p < 5)", "name": "cq"},
            ],
        )

    def test_check_constraint_inline_plain(self):
        inspector = inspect(testing.db)
        eq_(
            inspector.get_check_constraints("cp_inline"),
            [
                {"sqltext": "p = 1 OR (p > 2 AND p < 5)", "name": "cq"},
                {"sqltext": "q > 1 AND q < 6", "name": None},
            ],
        )

    @testing.fails("need to come up with new regex and/or DDL parsing")
    def test_check_constraint_multiline(self):
        """test for #11677"""

        inspector = inspect(testing.db)
        eq_(
            inspector.get_check_constraints("r"),
            [
                {"sqltext": "value IS NOT NULL", "name": "^check-r* #\n\t"},
                # Triple-quote multi-line definition should have added a
                # newline and whitespace:
                {
                    "sqltext": "((value > 0) AND \n\t(value < 100) AND \n\t\n"
                    "                      (value != 50))",
                    "name": "ck_r_value_multiline",
                },
                {"sqltext": "id > 0", "name": None},
                {"sqltext": "prefix NOT GLOB '*[^-. /#,]*'", "name": None},
            ],
        )

    @testing.combinations(
        ("plain_name", "plain_name"),
        ("name with spaces", "name with spaces"),
        ("plainname", "plainname"),
        ("[Code]", "[Code]"),
        (quoted_name("[Code]", quote=False), "Code"),
        argnames="colname,expected",
    )
    @testing.combinations(
        "uq",
        "uq_inline",
        "uq_inline_tab_before",  # tab before column params
        "uq_inline_tab_within",  # tab within column params
        "pk",
        "ix",
        argnames="constraint_type",
    )
    def test_constraint_cols(
        self, colname, expected, constraint_type, connection, metadata
    ):
        if constraint_type.startswith("uq_inline"):
            inline_create_sql = {
                "uq_inline": "CREATE TABLE t (%s INTEGER UNIQUE)",
                "uq_inline_tab_before": "CREATE TABLE t (%s\tINTEGER UNIQUE)",
                "uq_inline_tab_within": "CREATE TABLE t (%s INTEGER\tUNIQUE)",
            }

            t = Table("t", metadata, Column(colname, Integer))
            connection.exec_driver_sql(
                inline_create_sql[constraint_type]
                % connection.dialect.identifier_preparer.quote(colname)
            )
        else:
            t = Table("t", metadata, Column(colname, Integer))
            if constraint_type == "uq":
                constraint = UniqueConstraint(t.c[colname])
            elif constraint_type == "pk":
                constraint = PrimaryKeyConstraint(t.c[colname])
            elif constraint_type == "ix":
                constraint = Index("some_index", t.c[colname])
            else:
                assert False

            t.append_constraint(constraint)

            t.create(connection)

        if constraint_type in (
            "uq",
            "uq_inline",
            "uq_inline_tab_before",
            "uq_inline_tab_within",
        ):
            const = inspect(connection).get_unique_constraints("t")[0]
            eq_(const["column_names"], [expected])
        elif constraint_type == "pk":
            const = inspect(connection).get_pk_constraint("t")
            eq_(const["constrained_columns"], [expected])
        elif constraint_type == "ix":
            const = inspect(connection).get_indexes("t")[0]
            eq_(const["column_names"], [expected])
        else:
            assert False


class TypeReflectionTest(fixtures.TestBase):
    __only_on__ = "sqlite"
    __backend__ = True

    def _fixed_lookup_fixture(self):
        return [
            (sqltypes.String(), sqltypes.VARCHAR()),
            (sqltypes.String(1), sqltypes.VARCHAR(1)),
            (sqltypes.String(3), sqltypes.VARCHAR(3)),
            (sqltypes.Text(), sqltypes.TEXT()),
            (sqltypes.Unicode(), sqltypes.VARCHAR()),
            (sqltypes.Unicode(1), sqltypes.VARCHAR(1)),
            (sqltypes.UnicodeText(), sqltypes.TEXT()),
            (sqltypes.CHAR(3), sqltypes.CHAR(3)),
            (sqltypes.NUMERIC, sqltypes.NUMERIC()),
            (sqltypes.NUMERIC(10, 2), sqltypes.NUMERIC(10, 2)),
            (sqltypes.Numeric, sqltypes.NUMERIC()),
            (sqltypes.Numeric(10, 2), sqltypes.NUMERIC(10, 2)),
            (sqltypes.DECIMAL, sqltypes.DECIMAL()),
            (sqltypes.DECIMAL(10, 2), sqltypes.DECIMAL(10, 2)),
            (sqltypes.INTEGER, sqltypes.INTEGER()),
            (sqltypes.BIGINT, sqltypes.BIGINT()),
            (sqltypes.Float, sqltypes.FLOAT()),
            (sqltypes.TIMESTAMP, sqltypes.TIMESTAMP()),
            (sqltypes.DATETIME, sqltypes.DATETIME()),
            (sqltypes.DateTime, sqltypes.DATETIME()),
            (sqltypes.DateTime(), sqltypes.DATETIME()),
            (sqltypes.DATE, sqltypes.DATE()),
            (sqltypes.Date, sqltypes.DATE()),
            (sqltypes.TIME, sqltypes.TIME()),
            (sqltypes.Time, sqltypes.TIME()),
            (sqltypes.BOOLEAN, sqltypes.BOOLEAN()),
            (sqltypes.Boolean, sqltypes.BOOLEAN()),
            (
                sqlite.DATE(storage_format="%(year)04d%(month)02d%(day)02d"),
                sqltypes.DATE(),
            ),
            (
                sqlite.TIME(
                    storage_format="%(hour)02d%(minute)02d%(second)02d"
                ),
                sqltypes.TIME(),
            ),
            (
                sqlite.DATETIME(
                    storage_format="%(year)04d%(month)02d%(day)02d"
                    "%(hour)02d%(minute)02d%(second)02d"
                ),
                sqltypes.DATETIME(),
            ),
        ]

    def _unsupported_args_fixture(self):
        return [
            ("INTEGER(5)", sqltypes.INTEGER()),
            ("DATETIME(6, 12)", sqltypes.DATETIME()),
        ]

    def _type_affinity_fixture(self):
        return [
            ("LONGTEXT", sqltypes.TEXT()),
            ("TINYINT", sqltypes.INTEGER()),
            ("MEDIUMINT", sqltypes.INTEGER()),
            ("INT2", sqltypes.INTEGER()),
            ("UNSIGNED BIG INT", sqltypes.INTEGER()),
            ("INT8", sqltypes.INTEGER()),
            ("CHARACTER(20)", sqltypes.TEXT()),
            ("CLOB", sqltypes.TEXT()),
            ("CLOBBER", sqltypes.TEXT()),
            ("VARYING CHARACTER(70)", sqltypes.TEXT()),
            ("NATIVE CHARACTER(70)", sqltypes.TEXT()),
            ("BLOB", sqltypes.BLOB()),
            ("BLOBBER", sqltypes.NullType()),
            ("DOUBLE PRECISION", sqltypes.REAL()),
            ("FLOATY", sqltypes.REAL()),
            ("SOMETHING UNKNOWN", sqltypes.NUMERIC()),
        ]

    def _fixture_as_string(self, fixture):
        for from_, to_ in fixture:
            if isinstance(from_, sqltypes.TypeEngine):
                from_ = str(from_.compile())
            elif isinstance(from_, type):
                from_ = str(from_().compile())
            yield from_, to_

    def _test_lookup_direct(self, fixture, warnings=False):
        dialect = sqlite.dialect()
        for from_, to_ in self._fixture_as_string(fixture):
            if warnings:

                def go():
                    return dialect._resolve_type_affinity(from_)

                final_type = testing.assert_warnings(
                    go, ["Could not instantiate"], regex=True
                )
            else:
                final_type = dialect._resolve_type_affinity(from_)
            expected_type = type(to_)
            is_(type(final_type), expected_type)

    def _test_round_trip(self, fixture, warnings=False):
        from sqlalchemy import inspect

        for from_, to_ in self._fixture_as_string(fixture):
            with testing.db.begin() as conn:
                inspector = inspect(conn)
                conn.exec_driver_sql("CREATE TABLE foo (data %s)" % from_)
                try:
                    if warnings:

                        def go():
                            return inspector.get_columns("foo")[0]

                        col_info = testing.assert_warnings(
                            go, ["Could not instantiate"], regex=True
                        )
                    else:
                        col_info = inspector.get_columns("foo")[0]
                    expected_type = type(to_)
                    is_(type(col_info["type"]), expected_type)

                    # test args
                    for attr in ("scale", "precision", "length"):
                        if getattr(to_, attr, None) is not None:
                            eq_(
                                getattr(col_info["type"], attr),
                                getattr(to_, attr, None),
                            )
                finally:
                    conn.exec_driver_sql("DROP TABLE foo")

    def test_lookup_direct_lookup(self):
        self._test_lookup_direct(self._fixed_lookup_fixture())

    def test_lookup_direct_unsupported_args(self):
        self._test_lookup_direct(
            self._unsupported_args_fixture(), warnings=True
        )

    def test_lookup_direct_type_affinity(self):
        self._test_lookup_direct(self._type_affinity_fixture())

    def test_round_trip_direct_lookup(self):
        self._test_round_trip(self._fixed_lookup_fixture())

    def test_round_trip_direct_unsupported_args(self):
        self._test_round_trip(self._unsupported_args_fixture(), warnings=True)

    def test_round_trip_direct_type_affinity(self):
        self._test_round_trip(self._type_affinity_fixture())


class ReflectInternalSchemaTables(fixtures.TablesTest):
    __only_on__ = "sqlite"
    __backend__ = True

    @classmethod
    def define_tables(cls, metadata):
        Table(
            "sqliteatable",
            metadata,
            Column("id", Integer, primary_key=True),
            Column("other", String(42)),
            sqlite_autoincrement=True,
        )
        view = "CREATE VIEW sqliteview AS SELECT * FROM sqliteatable"
        event.listen(metadata, "after_create", DDL(view))
        event.listen(metadata, "before_drop", DDL("DROP VIEW sqliteview"))

    def test_get_table_names(self, connection):
        insp = inspect(connection)

        res = insp.get_table_names(sqlite_include_internal=True)
        eq_(res, ["sqlite_sequence", "sqliteatable"])
        res = insp.get_table_names()
        eq_(res, ["sqliteatable"])

        meta = MetaData()
        meta.reflect(connection)
        eq_(len(meta.tables), 1)
        eq_(set(meta.tables), {"sqliteatable"})

    def test_get_view_names(self, connection):
        insp = inspect(connection)

        res = insp.get_view_names(sqlite_include_internal=True)
        eq_(res, ["sqliteview"])
        res = insp.get_view_names()
        eq_(res, ["sqliteview"])

    def test_get_temp_table_names(self, connection, metadata):
        Table(
            "sqlitetemptable",
            metadata,
            Column("id", Integer, primary_key=True),
            Column("other", String(42)),
            sqlite_autoincrement=True,
            prefixes=["TEMPORARY"],
        ).create(connection)
        insp = inspect(connection)

        res = insp.get_temp_table_names(sqlite_include_internal=True)
        eq_(res, ["sqlite_sequence", "sqlitetemptable"])
        res = insp.get_temp_table_names()
        eq_(res, ["sqlitetemptable"])

    def test_get_temp_view_names(self, connection):
        view = (
            "CREATE TEMPORARY VIEW sqlitetempview AS "
            "SELECT * FROM sqliteatable"
        )
        connection.exec_driver_sql(view)
        insp = inspect(connection)
        try:
            res = insp.get_temp_view_names(sqlite_include_internal=True)
            eq_(res, ["sqlitetempview"])
            res = insp.get_temp_view_names()
            eq_(res, ["sqlitetempview"])
        finally:
            connection.exec_driver_sql("DROP VIEW sqlitetempview")


class ComputedReflectionTest(fixtures.TestBase):
    __only_on__ = "sqlite"
    __backend__ = True

    @testing.combinations(
        (
            """CREATE TABLE test1 (
                s VARCHAR,
                x VARCHAR GENERATED ALWAYS AS (s || 'x')
            );""",
            "test1",
            {"x": {"text": "s || 'x'", "stored": False}},
        ),
        (
            """CREATE TABLE test2 (
                s VARCHAR,
                x VARCHAR GENERATED ALWAYS AS (s || 'x'),
                y VARCHAR GENERATED ALWAYS AS (s || 'y')
            );""",
            "test2",
            {
                "x": {"text": "s || 'x'", "stored": False},
                "y": {"text": "s || 'y'", "stored": False},
            },
        ),
        (
            """CREATE TABLE test3 (
                s VARCHAR,
                x INTEGER GENERATED ALWAYS AS (INSTR(s, ","))
            );""",
            "test3",
            {"x": {"text": 'INSTR(s, ",")', "stored": False}},
        ),
        (
            """CREATE TABLE test4 (
                s VARCHAR,
                x INTEGER GENERATED ALWAYS AS (INSTR(s, ",")),
                y INTEGER GENERATED ALWAYS AS (INSTR(x, ",")));""",
            "test4",
            {
                "x": {"text": 'INSTR(s, ",")', "stored": False},
                "y": {"text": 'INSTR(x, ",")', "stored": False},
            },
        ),
        (
            """CREATE TABLE test5 (
                s VARCHAR,
                x VARCHAR GENERATED ALWAYS AS (s || 'x') STORED
            );""",
            "test5",
            {"x": {"text": "s || 'x'", "stored": True}},
        ),
        (
            """CREATE TABLE test6 (
                s VARCHAR,
                x VARCHAR GENERATED ALWAYS AS (s || 'x') STORED,
                y VARCHAR GENERATED ALWAYS AS (s || 'y') STORED
            );""",
            "test6",
            {
                "x": {"text": "s || 'x'", "stored": True},
                "y": {"text": "s || 'y'", "stored": True},
            },
        ),
        (
            """CREATE TABLE test7 (
                s VARCHAR,
                x INTEGER GENERATED ALWAYS AS (INSTR(s, ",")) STORED
            );""",
            "test7",
            {"x": {"text": 'INSTR(s, ",")', "stored": True}},
        ),
        (
            """CREATE TABLE test8 (
                s VARCHAR,
                x INTEGER GENERATED ALWAYS AS (INSTR(s, ",")) STORED,
                y INTEGER GENERATED ALWAYS AS (INSTR(x, ",")) STORED
            );""",
            "test8",
            {
                "x": {"text": 'INSTR(s, ",")', "stored": True},
                "y": {"text": 'INSTR(x, ",")', "stored": True},
            },
        ),
        (
            """CREATE TABLE test9 (
                id INTEGER PRIMARY KEY,
                s VARCHAR,
                x VARCHAR GENERATED ALWAYS AS (s || 'x')
            ) WITHOUT ROWID;""",
            "test9",
            {"x": {"text": "s || 'x'", "stored": False}},
        ),
        (
            """CREATE TABLE test_strict1 (
                s TEXT,
                x TEXT GENERATED ALWAYS AS (s || 'x')
            ) STRICT;""",
            "test_strict1",
            {"x": {"text": "s || 'x'", "stored": False}},
            testing.only_on("sqlite>=3.37.0"),
        ),
        (
            """CREATE TABLE test_strict2 (
                id INTEGER PRIMARY KEY,
                s TEXT,
                x TEXT GENERATED ALWAYS AS (s || 'x')
            ) STRICT, WITHOUT ROWID;""",
            "test_strict2",
            {"x": {"text": "s || 'x'", "stored": False}},
            testing.only_on("sqlite>=3.37.0"),
        ),
        (
            """CREATE TABLE test_strict3 (
                id INTEGER PRIMARY KEY,
                s TEXT,
                x TEXT GENERATED ALWAYS AS (s || 'x')
            ) WITHOUT ROWID, STRICT;""",
            "test_strict3",
            {"x": {"text": "s || 'x'", "stored": False}},
            testing.only_on("sqlite>=3.37.0"),
        ),
        argnames="table_ddl,table_name,spec",
        id_="asa",
    )
    @testing.requires.computed_columns
    def test_reflection(
        self, metadata, connection, table_ddl, table_name, spec
    ):
        connection.exec_driver_sql(table_ddl)

        tbl = Table(table_name, metadata, autoload_with=connection)
        seen = set(spec).intersection(tbl.c.keys())

        for col in tbl.c:
            if col.name not in seen:
                is_(col.computed, None)
            else:
                info = spec[col.name]
                msg = f"{tbl.name}-{col.name}"
                is_true(bool(col.computed))
                eq_(col.computed.sqltext.text, info["text"], msg)
                eq_(col.computed.persisted, info["stored"], msg)