summaryrefslogtreecommitdiff
path: root/tests/schema/tests.py
blob: 688a9f1fcf1e9e843ba3a588b85bc5f0061373d1 (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
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
import datetime
import itertools
import unittest
from copy import copy
from unittest import mock

from django.core.exceptions import FieldError
from django.core.management.color import no_style
from django.db import (
    DatabaseError,
    DataError,
    IntegrityError,
    OperationalError,
    connection,
)
from django.db.backends.utils import truncate_name
from django.db.models import (
    CASCADE,
    PROTECT,
    AutoField,
    BigAutoField,
    BigIntegerField,
    BinaryField,
    BooleanField,
    CharField,
    CheckConstraint,
    DateField,
    DateTimeField,
    DecimalField,
    DurationField,
    F,
    FloatField,
    ForeignKey,
    ForeignObject,
    Index,
    IntegerField,
    JSONField,
    ManyToManyField,
    Model,
    OneToOneField,
    OrderBy,
    PositiveIntegerField,
    Q,
    SlugField,
    SmallAutoField,
    SmallIntegerField,
    TextField,
    TimeField,
    UniqueConstraint,
    UUIDField,
    Value,
)
from django.db.models.fields.json import KeyTextTransform
from django.db.models.functions import Abs, Cast, Collate, Lower, Random, Upper
from django.db.models.indexes import IndexExpression
from django.db.transaction import TransactionManagementError, atomic
from django.test import (
    TransactionTestCase,
    ignore_warnings,
    skipIfDBFeature,
    skipUnlessDBFeature,
)
from django.test.utils import CaptureQueriesContext, isolate_apps, register_lookup
from django.utils.deprecation import RemovedInDjango51Warning

from .fields import CustomManyToManyField, InheritedManyToManyField, MediumBlobField
from .models import (
    Author,
    AuthorCharFieldWithIndex,
    AuthorTextFieldWithIndex,
    AuthorWithDefaultHeight,
    AuthorWithEvenLongerName,
    AuthorWithIndexedName,
    AuthorWithUniqueName,
    AuthorWithUniqueNameAndBirthday,
    Book,
    BookForeignObj,
    BookWeak,
    BookWithLongName,
    BookWithO2O,
    BookWithoutAuthor,
    BookWithSlug,
    IntegerPK,
    Node,
    Note,
    NoteRename,
    Tag,
    TagM2MTest,
    TagUniqueRename,
    Thing,
    UniqueTest,
    new_apps,
)


class SchemaTests(TransactionTestCase):
    """
    Tests for the schema-alteration code.

    Be aware that these tests are more liable than most to false results,
    as sometimes the code to check if a test has worked is almost as complex
    as the code it is testing.
    """

    available_apps = []

    models = [
        Author,
        AuthorCharFieldWithIndex,
        AuthorTextFieldWithIndex,
        AuthorWithDefaultHeight,
        AuthorWithEvenLongerName,
        Book,
        BookWeak,
        BookWithLongName,
        BookWithO2O,
        BookWithSlug,
        IntegerPK,
        Node,
        Note,
        Tag,
        TagM2MTest,
        TagUniqueRename,
        Thing,
        UniqueTest,
    ]

    # Utility functions

    def setUp(self):
        # local_models should contain test dependent model classes that will be
        # automatically removed from the app cache on test tear down.
        self.local_models = []
        # isolated_local_models contains models that are in test methods
        # decorated with @isolate_apps.
        self.isolated_local_models = []

    def tearDown(self):
        # Delete any tables made for our models
        self.delete_tables()
        new_apps.clear_cache()
        for model in new_apps.get_models():
            model._meta._expire_cache()
        if "schema" in new_apps.all_models:
            for model in self.local_models:
                for many_to_many in model._meta.many_to_many:
                    through = many_to_many.remote_field.through
                    if through and through._meta.auto_created:
                        del new_apps.all_models["schema"][through._meta.model_name]
                del new_apps.all_models["schema"][model._meta.model_name]
        if self.isolated_local_models:
            with connection.schema_editor() as editor:
                for model in self.isolated_local_models:
                    editor.delete_model(model)

    def delete_tables(self):
        "Deletes all model tables for our models for a clean test environment"
        converter = connection.introspection.identifier_converter
        with connection.schema_editor() as editor:
            connection.disable_constraint_checking()
            table_names = connection.introspection.table_names()
            if connection.features.ignores_table_name_case:
                table_names = [table_name.lower() for table_name in table_names]
            for model in itertools.chain(SchemaTests.models, self.local_models):
                tbl = converter(model._meta.db_table)
                if connection.features.ignores_table_name_case:
                    tbl = tbl.lower()
                if tbl in table_names:
                    editor.delete_model(model)
                    table_names.remove(tbl)
            connection.enable_constraint_checking()

    def column_classes(self, model):
        with connection.cursor() as cursor:
            columns = {
                d[0]: (connection.introspection.get_field_type(d[1], d), d)
                for d in connection.introspection.get_table_description(
                    cursor,
                    model._meta.db_table,
                )
            }
        # SQLite has a different format for field_type
        for name, (type, desc) in columns.items():
            if isinstance(type, tuple):
                columns[name] = (type[0], desc)
        return columns

    def get_primary_key(self, table):
        with connection.cursor() as cursor:
            return connection.introspection.get_primary_key_column(cursor, table)

    def get_indexes(self, table):
        """
        Get the indexes on the table using a new cursor.
        """
        with connection.cursor() as cursor:
            return [
                c["columns"][0]
                for c in connection.introspection.get_constraints(
                    cursor, table
                ).values()
                if c["index"] and len(c["columns"]) == 1
            ]

    def get_uniques(self, table):
        with connection.cursor() as cursor:
            return [
                c["columns"][0]
                for c in connection.introspection.get_constraints(
                    cursor, table
                ).values()
                if c["unique"] and len(c["columns"]) == 1
            ]

    def get_constraints(self, table):
        """
        Get the constraints on a table using a new cursor.
        """
        with connection.cursor() as cursor:
            return connection.introspection.get_constraints(cursor, table)

    def get_constraints_for_column(self, model, column_name):
        constraints = self.get_constraints(model._meta.db_table)
        constraints_for_column = []
        for name, details in constraints.items():
            if details["columns"] == [column_name]:
                constraints_for_column.append(name)
        return sorted(constraints_for_column)

    def check_added_field_default(
        self,
        schema_editor,
        model,
        field,
        field_name,
        expected_default,
        cast_function=None,
    ):
        with connection.cursor() as cursor:
            schema_editor.add_field(model, field)
            cursor.execute(
                "SELECT {} FROM {};".format(field_name, model._meta.db_table)
            )
            database_default = cursor.fetchall()[0][0]
            if cast_function and type(database_default) != type(expected_default):
                database_default = cast_function(database_default)
            self.assertEqual(database_default, expected_default)

    def get_constraints_count(self, table, column, fk_to):
        """
        Return a dict with keys 'fks', 'uniques, and 'indexes' indicating the
        number of foreign keys, unique constraints, and indexes on
        `table`.`column`. The `fk_to` argument is a 2-tuple specifying the
        expected foreign key relationship's (table, column).
        """
        with connection.cursor() as cursor:
            constraints = connection.introspection.get_constraints(cursor, table)
        counts = {"fks": 0, "uniques": 0, "indexes": 0}
        for c in constraints.values():
            if c["columns"] == [column]:
                if c["foreign_key"] == fk_to:
                    counts["fks"] += 1
                if c["unique"]:
                    counts["uniques"] += 1
                elif c["index"]:
                    counts["indexes"] += 1
        return counts

    def get_column_collation(self, table, column):
        with connection.cursor() as cursor:
            return next(
                f.collation
                for f in connection.introspection.get_table_description(cursor, table)
                if f.name == column
            )

    def get_column_comment(self, table, column):
        with connection.cursor() as cursor:
            return next(
                f.comment
                for f in connection.introspection.get_table_description(cursor, table)
                if f.name == column
            )

    def get_table_comment(self, table):
        with connection.cursor() as cursor:
            return next(
                t.comment
                for t in connection.introspection.get_table_list(cursor)
                if t.name == table
            )

    def assert_column_comment_not_exists(self, table, column):
        with connection.cursor() as cursor:
            columns = connection.introspection.get_table_description(cursor, table)
        self.assertFalse(any([c.name == column and c.comment for c in columns]))

    def assertIndexOrder(self, table, index, order):
        constraints = self.get_constraints(table)
        self.assertIn(index, constraints)
        index_orders = constraints[index]["orders"]
        self.assertTrue(
            all(val == expected for val, expected in zip(index_orders, order))
        )

    def assertForeignKeyExists(self, model, column, expected_fk_table, field="id"):
        """
        Fail if the FK constraint on `model.Meta.db_table`.`column` to
        `expected_fk_table`.id doesn't exist.
        """
        if not connection.features.can_introspect_foreign_keys:
            return
        constraints = self.get_constraints(model._meta.db_table)
        constraint_fk = None
        for details in constraints.values():
            if details["columns"] == [column] and details["foreign_key"]:
                constraint_fk = details["foreign_key"]
                break
        self.assertEqual(constraint_fk, (expected_fk_table, field))

    def assertForeignKeyNotExists(self, model, column, expected_fk_table):
        if not connection.features.can_introspect_foreign_keys:
            return
        with self.assertRaises(AssertionError):
            self.assertForeignKeyExists(model, column, expected_fk_table)

    # Tests
    def test_creation_deletion(self):
        """
        Tries creating a model's table, and then deleting it.
        """
        with connection.schema_editor() as editor:
            # Create the table
            editor.create_model(Author)
            # The table is there
            list(Author.objects.all())
            # Clean up that table
            editor.delete_model(Author)
            # No deferred SQL should be left over.
            self.assertEqual(editor.deferred_sql, [])
        # The table is gone
        with self.assertRaises(DatabaseError):
            list(Author.objects.all())

    @skipUnlessDBFeature("supports_foreign_keys")
    def test_fk(self):
        "Creating tables out of FK order, then repointing, works"
        # Create the table
        with connection.schema_editor() as editor:
            editor.create_model(Book)
            editor.create_model(Author)
            editor.create_model(Tag)
        # Initial tables are there
        list(Author.objects.all())
        list(Book.objects.all())
        # Make sure the FK constraint is present
        with self.assertRaises(IntegrityError):
            Book.objects.create(
                author_id=1,
                title="Much Ado About Foreign Keys",
                pub_date=datetime.datetime.now(),
            )
        # Repoint the FK constraint
        old_field = Book._meta.get_field("author")
        new_field = ForeignKey(Tag, CASCADE)
        new_field.set_attributes_from_name("author")
        with connection.schema_editor() as editor:
            editor.alter_field(Book, old_field, new_field, strict=True)
        self.assertForeignKeyExists(Book, "author_id", "schema_tag")

    @skipUnlessDBFeature("can_create_inline_fk")
    def test_inline_fk(self):
        # Create some tables.
        with connection.schema_editor() as editor:
            editor.create_model(Author)
            editor.create_model(Book)
            editor.create_model(Note)
        self.assertForeignKeyNotExists(Note, "book_id", "schema_book")
        # Add a foreign key from one to the other.
        with connection.schema_editor() as editor:
            new_field = ForeignKey(Book, CASCADE)
            new_field.set_attributes_from_name("book")
            editor.add_field(Note, new_field)
        self.assertForeignKeyExists(Note, "book_id", "schema_book")
        # Creating a FK field with a constraint uses a single statement without
        # a deferred ALTER TABLE.
        self.assertFalse(
            [
                sql
                for sql in (str(statement) for statement in editor.deferred_sql)
                if sql.startswith("ALTER TABLE") and "ADD CONSTRAINT" in sql
            ]
        )

    @skipUnlessDBFeature("can_create_inline_fk")
    def test_add_inline_fk_update_data(self):
        with connection.schema_editor() as editor:
            editor.create_model(Node)
        # Add an inline foreign key and update data in the same transaction.
        new_field = ForeignKey(Node, CASCADE, related_name="new_fk", null=True)
        new_field.set_attributes_from_name("new_parent_fk")
        parent = Node.objects.create()
        with connection.schema_editor() as editor:
            editor.add_field(Node, new_field)
            editor.execute("UPDATE schema_node SET new_parent_fk_id = %s;", [parent.pk])
        assertIndex = (
            self.assertIn
            if connection.features.indexes_foreign_keys
            else self.assertNotIn
        )
        assertIndex("new_parent_fk_id", self.get_indexes(Node._meta.db_table))

    @skipUnlessDBFeature(
        "can_create_inline_fk",
        "allows_multiple_constraints_on_same_fields",
    )
    @isolate_apps("schema")
    def test_add_inline_fk_index_update_data(self):
        class Node(Model):
            class Meta:
                app_label = "schema"

        with connection.schema_editor() as editor:
            editor.create_model(Node)
        # Add an inline foreign key, update data, and an index in the same
        # transaction.
        new_field = ForeignKey(Node, CASCADE, related_name="new_fk", null=True)
        new_field.set_attributes_from_name("new_parent_fk")
        parent = Node.objects.create()
        with connection.schema_editor() as editor:
            editor.add_field(Node, new_field)
            Node._meta.add_field(new_field)
            editor.execute("UPDATE schema_node SET new_parent_fk_id = %s;", [parent.pk])
            editor.add_index(
                Node, Index(fields=["new_parent_fk"], name="new_parent_inline_fk_idx")
            )
        self.assertIn("new_parent_fk_id", self.get_indexes(Node._meta.db_table))

    @skipUnlessDBFeature("supports_foreign_keys")
    def test_char_field_with_db_index_to_fk(self):
        # Create the table
        with connection.schema_editor() as editor:
            editor.create_model(Author)
            editor.create_model(AuthorCharFieldWithIndex)
        # Change CharField to FK
        old_field = AuthorCharFieldWithIndex._meta.get_field("char_field")
        new_field = ForeignKey(Author, CASCADE, blank=True)
        new_field.set_attributes_from_name("char_field")
        with connection.schema_editor() as editor:
            editor.alter_field(
                AuthorCharFieldWithIndex, old_field, new_field, strict=True
            )
        self.assertForeignKeyExists(
            AuthorCharFieldWithIndex, "char_field_id", "schema_author"
        )

    @skipUnlessDBFeature("supports_foreign_keys")
    @skipUnlessDBFeature("supports_index_on_text_field")
    def test_text_field_with_db_index_to_fk(self):
        # Create the table
        with connection.schema_editor() as editor:
            editor.create_model(Author)
            editor.create_model(AuthorTextFieldWithIndex)
        # Change TextField to FK
        old_field = AuthorTextFieldWithIndex._meta.get_field("text_field")
        new_field = ForeignKey(Author, CASCADE, blank=True)
        new_field.set_attributes_from_name("text_field")
        with connection.schema_editor() as editor:
            editor.alter_field(
                AuthorTextFieldWithIndex, old_field, new_field, strict=True
            )
        self.assertForeignKeyExists(
            AuthorTextFieldWithIndex, "text_field_id", "schema_author"
        )

    @isolate_apps("schema")
    def test_char_field_pk_to_auto_field(self):
        class Foo(Model):
            id = CharField(max_length=255, primary_key=True)

            class Meta:
                app_label = "schema"

        with connection.schema_editor() as editor:
            editor.create_model(Foo)
        self.isolated_local_models = [Foo]
        old_field = Foo._meta.get_field("id")
        new_field = AutoField(primary_key=True)
        new_field.set_attributes_from_name("id")
        new_field.model = Foo
        with connection.schema_editor() as editor:
            editor.alter_field(Foo, old_field, new_field, strict=True)

    @skipUnlessDBFeature("supports_foreign_keys")
    def test_fk_to_proxy(self):
        "Creating a FK to a proxy model creates database constraints."

        class AuthorProxy(Author):
            class Meta:
                app_label = "schema"
                apps = new_apps
                proxy = True

        class AuthorRef(Model):
            author = ForeignKey(AuthorProxy, on_delete=CASCADE)

            class Meta:
                app_label = "schema"
                apps = new_apps

        self.local_models = [AuthorProxy, AuthorRef]

        # Create the table
        with connection.schema_editor() as editor:
            editor.create_model(Author)
            editor.create_model(AuthorRef)
        self.assertForeignKeyExists(AuthorRef, "author_id", "schema_author")

    @skipUnlessDBFeature("supports_foreign_keys", "can_introspect_foreign_keys")
    def test_fk_db_constraint(self):
        "The db_constraint parameter is respected"
        # Create the table
        with connection.schema_editor() as editor:
            editor.create_model(Tag)
            editor.create_model(Author)
            editor.create_model(BookWeak)
        # Initial tables are there
        list(Author.objects.all())
        list(Tag.objects.all())
        list(BookWeak.objects.all())
        self.assertForeignKeyNotExists(BookWeak, "author_id", "schema_author")
        # Make a db_constraint=False FK
        new_field = ForeignKey(Tag, CASCADE, db_constraint=False)
        new_field.set_attributes_from_name("tag")
        with connection.schema_editor() as editor:
            editor.add_field(Author, new_field)
        self.assertForeignKeyNotExists(Author, "tag_id", "schema_tag")
        # Alter to one with a constraint
        new_field2 = ForeignKey(Tag, CASCADE)
        new_field2.set_attributes_from_name("tag")
        with connection.schema_editor() as editor:
            editor.alter_field(Author, new_field, new_field2, strict=True)
        self.assertForeignKeyExists(Author, "tag_id", "schema_tag")
        # Alter to one without a constraint again
        new_field2 = ForeignKey(Tag, CASCADE)
        new_field2.set_attributes_from_name("tag")
        with connection.schema_editor() as editor:
            editor.alter_field(Author, new_field2, new_field, strict=True)
        self.assertForeignKeyNotExists(Author, "tag_id", "schema_tag")

    @isolate_apps("schema")
    def test_no_db_constraint_added_during_primary_key_change(self):
        """
        When a primary key that's pointed to by a ForeignKey with
        db_constraint=False is altered, a foreign key constraint isn't added.
        """

        class Author(Model):
            class Meta:
                app_label = "schema"

        class BookWeak(Model):
            author = ForeignKey(Author, CASCADE, db_constraint=False)

            class Meta:
                app_label = "schema"

        with connection.schema_editor() as editor:
            editor.create_model(Author)
            editor.create_model(BookWeak)
        self.assertForeignKeyNotExists(BookWeak, "author_id", "schema_author")
        old_field = Author._meta.get_field("id")
        new_field = BigAutoField(primary_key=True)
        new_field.model = Author
        new_field.set_attributes_from_name("id")
        # @isolate_apps() and inner models are needed to have the model
        # relations populated, otherwise this doesn't act as a regression test.
        self.assertEqual(len(new_field.model._meta.related_objects), 1)
        with connection.schema_editor() as editor:
            editor.alter_field(Author, old_field, new_field, strict=True)
        self.assertForeignKeyNotExists(BookWeak, "author_id", "schema_author")

    def _test_m2m_db_constraint(self, M2MFieldClass):
        class LocalAuthorWithM2M(Model):
            name = CharField(max_length=255)

            class Meta:
                app_label = "schema"
                apps = new_apps

        self.local_models = [LocalAuthorWithM2M]

        # Create the table
        with connection.schema_editor() as editor:
            editor.create_model(Tag)
            editor.create_model(LocalAuthorWithM2M)
        # Initial tables are there
        list(LocalAuthorWithM2M.objects.all())
        list(Tag.objects.all())
        # Make a db_constraint=False FK
        new_field = M2MFieldClass(Tag, related_name="authors", db_constraint=False)
        new_field.contribute_to_class(LocalAuthorWithM2M, "tags")
        # Add the field
        with connection.schema_editor() as editor:
            editor.add_field(LocalAuthorWithM2M, new_field)
        self.assertForeignKeyNotExists(
            new_field.remote_field.through, "tag_id", "schema_tag"
        )

    @skipUnlessDBFeature("supports_foreign_keys")
    def test_m2m_db_constraint(self):
        self._test_m2m_db_constraint(ManyToManyField)

    @skipUnlessDBFeature("supports_foreign_keys")
    def test_m2m_db_constraint_custom(self):
        self._test_m2m_db_constraint(CustomManyToManyField)

    @skipUnlessDBFeature("supports_foreign_keys")
    def test_m2m_db_constraint_inherited(self):
        self._test_m2m_db_constraint(InheritedManyToManyField)

    def test_add_field(self):
        """
        Tests adding fields to models
        """
        # Create the table
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        # Ensure there's no age field
        columns = self.column_classes(Author)
        self.assertNotIn("age", columns)
        # Add the new field
        new_field = IntegerField(null=True)
        new_field.set_attributes_from_name("age")
        with CaptureQueriesContext(
            connection
        ) as ctx, connection.schema_editor() as editor:
            editor.add_field(Author, new_field)
        drop_default_sql = editor.sql_alter_column_no_default % {
            "column": editor.quote_name(new_field.name),
        }
        self.assertFalse(
            any(drop_default_sql in query["sql"] for query in ctx.captured_queries)
        )
        # Table is not rebuilt.
        self.assertIs(
            any("CREATE TABLE" in query["sql"] for query in ctx.captured_queries), False
        )
        self.assertIs(
            any("DROP TABLE" in query["sql"] for query in ctx.captured_queries), False
        )
        columns = self.column_classes(Author)
        self.assertEqual(
            columns["age"][0],
            connection.features.introspected_field_types["IntegerField"],
        )
        self.assertTrue(columns["age"][1][6])

    def test_add_field_remove_field(self):
        """
        Adding a field and removing it removes all deferred sql referring to it.
        """
        with connection.schema_editor() as editor:
            # Create a table with a unique constraint on the slug field.
            editor.create_model(Tag)
            # Remove the slug column.
            editor.remove_field(Tag, Tag._meta.get_field("slug"))
        self.assertEqual(editor.deferred_sql, [])

    def test_add_field_temp_default(self):
        """
        Tests adding fields to models with a temporary default
        """
        # Create the table
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        # Ensure there's no age field
        columns = self.column_classes(Author)
        self.assertNotIn("age", columns)
        # Add some rows of data
        Author.objects.create(name="Andrew", height=30)
        Author.objects.create(name="Andrea")
        # Add a not-null field
        new_field = CharField(max_length=30, default="Godwin")
        new_field.set_attributes_from_name("surname")
        with connection.schema_editor() as editor:
            editor.add_field(Author, new_field)
        columns = self.column_classes(Author)
        self.assertEqual(
            columns["surname"][0],
            connection.features.introspected_field_types["CharField"],
        )
        self.assertEqual(
            columns["surname"][1][6],
            connection.features.interprets_empty_strings_as_nulls,
        )

    def test_add_field_temp_default_boolean(self):
        """
        Tests adding fields to models with a temporary default where
        the default is False. (#21783)
        """
        # Create the table
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        # Ensure there's no age field
        columns = self.column_classes(Author)
        self.assertNotIn("age", columns)
        # Add some rows of data
        Author.objects.create(name="Andrew", height=30)
        Author.objects.create(name="Andrea")
        # Add a not-null field
        new_field = BooleanField(default=False)
        new_field.set_attributes_from_name("awesome")
        with connection.schema_editor() as editor:
            editor.add_field(Author, new_field)
        columns = self.column_classes(Author)
        # BooleanField are stored as TINYINT(1) on MySQL.
        field_type = columns["awesome"][0]
        self.assertEqual(
            field_type, connection.features.introspected_field_types["BooleanField"]
        )

    def test_add_field_default_transform(self):
        """
        Tests adding fields to models with a default that is not directly
        valid in the database (#22581)
        """

        class TestTransformField(IntegerField):
            # Weird field that saves the count of items in its value
            def get_default(self):
                return self.default

            def get_prep_value(self, value):
                if value is None:
                    return 0
                return len(value)

        # Create the table
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        # Add some rows of data
        Author.objects.create(name="Andrew", height=30)
        Author.objects.create(name="Andrea")
        # Add the field with a default it needs to cast (to string in this case)
        new_field = TestTransformField(default={1: 2})
        new_field.set_attributes_from_name("thing")
        with connection.schema_editor() as editor:
            editor.add_field(Author, new_field)
        # Ensure the field is there
        columns = self.column_classes(Author)
        field_type, field_info = columns["thing"]
        self.assertEqual(
            field_type, connection.features.introspected_field_types["IntegerField"]
        )
        # Make sure the values were transformed correctly
        self.assertEqual(Author.objects.extra(where=["thing = 1"]).count(), 2)

    def test_add_field_o2o_nullable(self):
        with connection.schema_editor() as editor:
            editor.create_model(Author)
            editor.create_model(Note)
        new_field = OneToOneField(Note, CASCADE, null=True)
        new_field.set_attributes_from_name("note")
        with connection.schema_editor() as editor:
            editor.add_field(Author, new_field)
        columns = self.column_classes(Author)
        self.assertIn("note_id", columns)
        self.assertTrue(columns["note_id"][1][6])

    def test_add_field_binary(self):
        """
        Tests binary fields get a sane default (#22851)
        """
        # Create the table
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        # Add the new field
        new_field = BinaryField(blank=True)
        new_field.set_attributes_from_name("bits")
        with connection.schema_editor() as editor:
            editor.add_field(Author, new_field)
        columns = self.column_classes(Author)
        # MySQL annoyingly uses the same backend, so it'll come back as one of
        # these two types.
        self.assertIn(columns["bits"][0], ("BinaryField", "TextField"))

    def test_add_field_durationfield_with_default(self):
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        new_field = DurationField(default=datetime.timedelta(minutes=10))
        new_field.set_attributes_from_name("duration")
        with connection.schema_editor() as editor:
            editor.add_field(Author, new_field)
        columns = self.column_classes(Author)
        self.assertEqual(
            columns["duration"][0],
            connection.features.introspected_field_types["DurationField"],
        )

    @unittest.skipUnless(connection.vendor == "mysql", "MySQL specific")
    def test_add_binaryfield_mediumblob(self):
        """
        Test adding a custom-sized binary field on MySQL (#24846).
        """
        # Create the table
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        # Add the new field with default
        new_field = MediumBlobField(blank=True, default=b"123")
        new_field.set_attributes_from_name("bits")
        with connection.schema_editor() as editor:
            editor.add_field(Author, new_field)
        columns = self.column_classes(Author)
        # Introspection treats BLOBs as TextFields
        self.assertEqual(columns["bits"][0], "TextField")

    @isolate_apps("schema")
    def test_add_auto_field(self):
        class AddAutoFieldModel(Model):
            name = CharField(max_length=255, primary_key=True)

            class Meta:
                app_label = "schema"

        with connection.schema_editor() as editor:
            editor.create_model(AddAutoFieldModel)
        self.isolated_local_models = [AddAutoFieldModel]
        old_field = AddAutoFieldModel._meta.get_field("name")
        new_field = CharField(max_length=255)
        new_field.set_attributes_from_name("name")
        new_field.model = AddAutoFieldModel
        with connection.schema_editor() as editor:
            editor.alter_field(AddAutoFieldModel, old_field, new_field)
        new_auto_field = AutoField(primary_key=True)
        new_auto_field.set_attributes_from_name("id")
        new_auto_field.model = AddAutoFieldModel()
        with connection.schema_editor() as editor:
            editor.add_field(AddAutoFieldModel, new_auto_field)
        # Crashes on PostgreSQL when the GENERATED BY suffix is missing.
        AddAutoFieldModel.objects.create(name="test")

    def test_remove_field(self):
        with connection.schema_editor() as editor:
            editor.create_model(Author)
            with CaptureQueriesContext(connection) as ctx:
                editor.remove_field(Author, Author._meta.get_field("name"))
        columns = self.column_classes(Author)
        self.assertNotIn("name", columns)
        if getattr(connection.features, "can_alter_table_drop_column", True):
            # Table is not rebuilt.
            self.assertIs(
                any("CREATE TABLE" in query["sql"] for query in ctx.captured_queries),
                False,
            )
            self.assertIs(
                any("DROP TABLE" in query["sql"] for query in ctx.captured_queries),
                False,
            )

    def test_remove_indexed_field(self):
        with connection.schema_editor() as editor:
            editor.create_model(AuthorCharFieldWithIndex)
        with connection.schema_editor() as editor:
            editor.remove_field(
                AuthorCharFieldWithIndex,
                AuthorCharFieldWithIndex._meta.get_field("char_field"),
            )
        columns = self.column_classes(AuthorCharFieldWithIndex)
        self.assertNotIn("char_field", columns)

    def test_alter(self):
        """
        Tests simple altering of fields
        """
        # Create the table
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        # Ensure the field is right to begin with
        columns = self.column_classes(Author)
        self.assertEqual(
            columns["name"][0],
            connection.features.introspected_field_types["CharField"],
        )
        self.assertEqual(
            bool(columns["name"][1][6]),
            bool(connection.features.interprets_empty_strings_as_nulls),
        )
        # Alter the name field to a TextField
        old_field = Author._meta.get_field("name")
        new_field = TextField(null=True)
        new_field.set_attributes_from_name("name")
        with connection.schema_editor() as editor:
            editor.alter_field(Author, old_field, new_field, strict=True)
        columns = self.column_classes(Author)
        self.assertEqual(columns["name"][0], "TextField")
        self.assertTrue(columns["name"][1][6])
        # Change nullability again
        new_field2 = TextField(null=False)
        new_field2.set_attributes_from_name("name")
        with connection.schema_editor() as editor:
            editor.alter_field(Author, new_field, new_field2, strict=True)
        columns = self.column_classes(Author)
        self.assertEqual(columns["name"][0], "TextField")
        self.assertEqual(
            bool(columns["name"][1][6]),
            bool(connection.features.interprets_empty_strings_as_nulls),
        )

    def test_alter_auto_field_to_integer_field(self):
        # Create the table
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        # Change AutoField to IntegerField
        old_field = Author._meta.get_field("id")
        new_field = IntegerField(primary_key=True)
        new_field.set_attributes_from_name("id")
        new_field.model = Author
        with connection.schema_editor() as editor:
            editor.alter_field(Author, old_field, new_field, strict=True)
        # Now that ID is an IntegerField, the database raises an error if it
        # isn't provided.
        if not connection.features.supports_unspecified_pk:
            with self.assertRaises(DatabaseError):
                Author.objects.create()

    def test_alter_auto_field_to_char_field(self):
        # Create the table
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        # Change AutoField to CharField
        old_field = Author._meta.get_field("id")
        new_field = CharField(primary_key=True, max_length=50)
        new_field.set_attributes_from_name("id")
        new_field.model = Author
        with connection.schema_editor() as editor:
            editor.alter_field(Author, old_field, new_field, strict=True)

    @isolate_apps("schema")
    def test_alter_auto_field_quoted_db_column(self):
        class Foo(Model):
            id = AutoField(primary_key=True, db_column='"quoted_id"')

            class Meta:
                app_label = "schema"

        with connection.schema_editor() as editor:
            editor.create_model(Foo)
        self.isolated_local_models = [Foo]
        old_field = Foo._meta.get_field("id")
        new_field = BigAutoField(primary_key=True)
        new_field.model = Foo
        new_field.db_column = '"quoted_id"'
        new_field.set_attributes_from_name("id")
        with connection.schema_editor() as editor:
            editor.alter_field(Foo, old_field, new_field, strict=True)
        Foo.objects.create()

    def test_alter_not_unique_field_to_primary_key(self):
        # Create the table.
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        # Change UUIDField to primary key.
        old_field = Author._meta.get_field("uuid")
        new_field = UUIDField(primary_key=True)
        new_field.set_attributes_from_name("uuid")
        new_field.model = Author
        with connection.schema_editor() as editor:
            editor.remove_field(Author, Author._meta.get_field("id"))
            editor.alter_field(Author, old_field, new_field, strict=True)
        # Redundant unique constraint is not added.
        count = self.get_constraints_count(
            Author._meta.db_table,
            Author._meta.get_field("uuid").column,
            None,
        )
        self.assertLessEqual(count["uniques"], 1)

    @isolate_apps("schema")
    def test_alter_primary_key_quoted_db_table(self):
        class Foo(Model):
            class Meta:
                app_label = "schema"
                db_table = '"foo"'

        with connection.schema_editor() as editor:
            editor.create_model(Foo)
        self.isolated_local_models = [Foo]
        old_field = Foo._meta.get_field("id")
        new_field = BigAutoField(primary_key=True)
        new_field.model = Foo
        new_field.set_attributes_from_name("id")
        with connection.schema_editor() as editor:
            editor.alter_field(Foo, old_field, new_field, strict=True)
        Foo.objects.create()

    def test_alter_text_field(self):
        # Regression for "BLOB/TEXT column 'info' can't have a default value")
        # on MySQL.
        # Create the table
        with connection.schema_editor() as editor:
            editor.create_model(Note)
        old_field = Note._meta.get_field("info")
        new_field = TextField(blank=True)
        new_field.set_attributes_from_name("info")
        with connection.schema_editor() as editor:
            editor.alter_field(Note, old_field, new_field, strict=True)

    def test_alter_text_field_to_not_null_with_default_value(self):
        with connection.schema_editor() as editor:
            editor.create_model(Note)
        old_field = Note._meta.get_field("address")
        new_field = TextField(blank=True, default="", null=False)
        new_field.set_attributes_from_name("address")
        with connection.schema_editor() as editor:
            editor.alter_field(Note, old_field, new_field, strict=True)

    @skipUnlessDBFeature("can_defer_constraint_checks", "can_rollback_ddl")
    def test_alter_fk_checks_deferred_constraints(self):
        """
        #25492 - Altering a foreign key's structure and data in the same
        transaction.
        """
        with connection.schema_editor() as editor:
            editor.create_model(Node)
        old_field = Node._meta.get_field("parent")
        new_field = ForeignKey(Node, CASCADE)
        new_field.set_attributes_from_name("parent")
        parent = Node.objects.create()
        with connection.schema_editor() as editor:
            # Update the parent FK to create a deferred constraint check.
            Node.objects.update(parent=parent)
            editor.alter_field(Node, old_field, new_field, strict=True)

    @isolate_apps("schema")
    def test_alter_null_with_default_value_deferred_constraints(self):
        class Publisher(Model):
            class Meta:
                app_label = "schema"

        class Article(Model):
            publisher = ForeignKey(Publisher, CASCADE)
            title = CharField(max_length=50, null=True)
            description = CharField(max_length=100, null=True)

            class Meta:
                app_label = "schema"

        with connection.schema_editor() as editor:
            editor.create_model(Publisher)
            editor.create_model(Article)
        self.isolated_local_models = [Article, Publisher]

        publisher = Publisher.objects.create()
        Article.objects.create(publisher=publisher)

        old_title = Article._meta.get_field("title")
        new_title = CharField(max_length=50, null=False, default="")
        new_title.set_attributes_from_name("title")
        old_description = Article._meta.get_field("description")
        new_description = CharField(max_length=100, null=False, default="")
        new_description.set_attributes_from_name("description")
        with connection.schema_editor() as editor:
            editor.alter_field(Article, old_title, new_title, strict=True)
            editor.alter_field(Article, old_description, new_description, strict=True)

    def test_alter_text_field_to_date_field(self):
        """
        #25002 - Test conversion of text field to date field.
        """
        with connection.schema_editor() as editor:
            editor.create_model(Note)
        Note.objects.create(info="1988-05-05")
        old_field = Note._meta.get_field("info")
        new_field = DateField(blank=True)
        new_field.set_attributes_from_name("info")
        with connection.schema_editor() as editor:
            editor.alter_field(Note, old_field, new_field, strict=True)
        # Make sure the field isn't nullable
        columns = self.column_classes(Note)
        self.assertFalse(columns["info"][1][6])

    def test_alter_text_field_to_datetime_field(self):
        """
        #25002 - Test conversion of text field to datetime field.
        """
        with connection.schema_editor() as editor:
            editor.create_model(Note)
        Note.objects.create(info="1988-05-05 3:16:17.4567")
        old_field = Note._meta.get_field("info")
        new_field = DateTimeField(blank=True)
        new_field.set_attributes_from_name("info")
        with connection.schema_editor() as editor:
            editor.alter_field(Note, old_field, new_field, strict=True)
        # Make sure the field isn't nullable
        columns = self.column_classes(Note)
        self.assertFalse(columns["info"][1][6])

    def test_alter_text_field_to_time_field(self):
        """
        #25002 - Test conversion of text field to time field.
        """
        with connection.schema_editor() as editor:
            editor.create_model(Note)
        Note.objects.create(info="3:16:17.4567")
        old_field = Note._meta.get_field("info")
        new_field = TimeField(blank=True)
        new_field.set_attributes_from_name("info")
        with connection.schema_editor() as editor:
            editor.alter_field(Note, old_field, new_field, strict=True)
        # Make sure the field isn't nullable
        columns = self.column_classes(Note)
        self.assertFalse(columns["info"][1][6])

    @skipIfDBFeature("interprets_empty_strings_as_nulls")
    def test_alter_textual_field_keep_null_status(self):
        """
        Changing a field type shouldn't affect the not null status.
        """
        with connection.schema_editor() as editor:
            editor.create_model(Note)
        with self.assertRaises(IntegrityError):
            Note.objects.create(info=None)
        old_field = Note._meta.get_field("info")
        new_field = CharField(max_length=50)
        new_field.set_attributes_from_name("info")
        with connection.schema_editor() as editor:
            editor.alter_field(Note, old_field, new_field, strict=True)
        with self.assertRaises(IntegrityError):
            Note.objects.create(info=None)

    @skipUnlessDBFeature("interprets_empty_strings_as_nulls")
    def test_alter_textual_field_not_null_to_null(self):
        """
        Nullability for textual fields is preserved on databases that
        interpret empty strings as NULLs.
        """
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        columns = self.column_classes(Author)
        # Field is nullable.
        self.assertTrue(columns["uuid"][1][6])
        # Change to NOT NULL.
        old_field = Author._meta.get_field("uuid")
        new_field = SlugField(null=False, blank=True)
        new_field.set_attributes_from_name("uuid")
        with connection.schema_editor() as editor:
            editor.alter_field(Author, old_field, new_field, strict=True)
        columns = self.column_classes(Author)
        # Nullability is preserved.
        self.assertTrue(columns["uuid"][1][6])

    def test_alter_numeric_field_keep_null_status(self):
        """
        Changing a field type shouldn't affect the not null status.
        """
        with connection.schema_editor() as editor:
            editor.create_model(UniqueTest)
        with self.assertRaises(IntegrityError):
            UniqueTest.objects.create(year=None, slug="aaa")
        old_field = UniqueTest._meta.get_field("year")
        new_field = BigIntegerField()
        new_field.set_attributes_from_name("year")
        with connection.schema_editor() as editor:
            editor.alter_field(UniqueTest, old_field, new_field, strict=True)
        with self.assertRaises(IntegrityError):
            UniqueTest.objects.create(year=None, slug="bbb")

    def test_alter_null_to_not_null(self):
        """
        #23609 - Tests handling of default values when altering from NULL to NOT NULL.
        """
        # Create the table
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        # Ensure the field is right to begin with
        columns = self.column_classes(Author)
        self.assertTrue(columns["height"][1][6])
        # Create some test data
        Author.objects.create(name="Not null author", height=12)
        Author.objects.create(name="Null author")
        # Verify null value
        self.assertEqual(Author.objects.get(name="Not null author").height, 12)
        self.assertIsNone(Author.objects.get(name="Null author").height)
        # Alter the height field to NOT NULL with default
        old_field = Author._meta.get_field("height")
        new_field = PositiveIntegerField(default=42)
        new_field.set_attributes_from_name("height")
        with connection.schema_editor() as editor:
            editor.alter_field(Author, old_field, new_field, strict=True)
        columns = self.column_classes(Author)
        self.assertFalse(columns["height"][1][6])
        # Verify default value
        self.assertEqual(Author.objects.get(name="Not null author").height, 12)
        self.assertEqual(Author.objects.get(name="Null author").height, 42)

    def test_alter_charfield_to_null(self):
        """
        #24307 - Should skip an alter statement on databases with
        interprets_empty_strings_as_nulls when changing a CharField to null.
        """
        # Create the table
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        # Change the CharField to null
        old_field = Author._meta.get_field("name")
        new_field = copy(old_field)
        new_field.null = True
        with connection.schema_editor() as editor:
            editor.alter_field(Author, old_field, new_field, strict=True)

    @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific")
    def test_alter_char_field_decrease_length(self):
        # Create the table.
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        Author.objects.create(name="x" * 255)
        # Change max_length of CharField.
        old_field = Author._meta.get_field("name")
        new_field = CharField(max_length=254)
        new_field.set_attributes_from_name("name")
        with connection.schema_editor() as editor:
            msg = "value too long for type character varying(254)"
            with self.assertRaisesMessage(DataError, msg):
                editor.alter_field(Author, old_field, new_field, strict=True)

    @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific")
    def test_alter_field_with_custom_db_type(self):
        from django.contrib.postgres.fields import ArrayField

        class Foo(Model):
            field = ArrayField(CharField(max_length=255))

            class Meta:
                app_label = "schema"

        with connection.schema_editor() as editor:
            editor.create_model(Foo)
        self.isolated_local_models = [Foo]
        old_field = Foo._meta.get_field("field")
        new_field = ArrayField(CharField(max_length=16))
        new_field.set_attributes_from_name("field")
        new_field.model = Foo
        with connection.schema_editor() as editor:
            editor.alter_field(Foo, old_field, new_field, strict=True)

    @isolate_apps("schema")
    @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific")
    def test_alter_array_field_decrease_base_field_length(self):
        from django.contrib.postgres.fields import ArrayField

        class ArrayModel(Model):
            field = ArrayField(CharField(max_length=16))

            class Meta:
                app_label = "schema"

        with connection.schema_editor() as editor:
            editor.create_model(ArrayModel)
        self.isolated_local_models = [ArrayModel]
        ArrayModel.objects.create(field=["x" * 16])
        old_field = ArrayModel._meta.get_field("field")
        new_field = ArrayField(CharField(max_length=15))
        new_field.set_attributes_from_name("field")
        new_field.model = ArrayModel
        with connection.schema_editor() as editor:
            msg = "value too long for type character varying(15)"
            with self.assertRaisesMessage(DataError, msg):
                editor.alter_field(ArrayModel, old_field, new_field, strict=True)

    @isolate_apps("schema")
    @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific")
    def test_alter_array_field_decrease_nested_base_field_length(self):
        from django.contrib.postgres.fields import ArrayField

        class ArrayModel(Model):
            field = ArrayField(ArrayField(CharField(max_length=16)))

            class Meta:
                app_label = "schema"

        with connection.schema_editor() as editor:
            editor.create_model(ArrayModel)
        self.isolated_local_models = [ArrayModel]
        ArrayModel.objects.create(field=[["x" * 16]])
        old_field = ArrayModel._meta.get_field("field")
        new_field = ArrayField(ArrayField(CharField(max_length=15)))
        new_field.set_attributes_from_name("field")
        new_field.model = ArrayModel
        with connection.schema_editor() as editor:
            msg = "value too long for type character varying(15)"
            with self.assertRaisesMessage(DataError, msg):
                editor.alter_field(ArrayModel, old_field, new_field, strict=True)

    def _add_ci_collation(self):
        ci_collation = "case_insensitive"

        def drop_collation():
            with connection.cursor() as cursor:
                cursor.execute(f"DROP COLLATION IF EXISTS {ci_collation}")

        with connection.cursor() as cursor:
            cursor.execute(
                f"CREATE COLLATION IF NOT EXISTS {ci_collation} (provider=icu, "
                f"locale='und-u-ks-level2', deterministic=false)"
            )
        self.addCleanup(drop_collation)
        return ci_collation

    @isolate_apps("schema")
    @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific")
    @skipUnlessDBFeature(
        "supports_collation_on_charfield",
        "supports_non_deterministic_collations",
    )
    def test_db_collation_arrayfield(self):
        from django.contrib.postgres.fields import ArrayField

        ci_collation = self._add_ci_collation()
        cs_collation = "en-x-icu"

        class ArrayModel(Model):
            field = ArrayField(CharField(max_length=16, db_collation=ci_collation))

            class Meta:
                app_label = "schema"

        # Create the table.
        with connection.schema_editor() as editor:
            editor.create_model(ArrayModel)
        self.isolated_local_models = [ArrayModel]
        self.assertEqual(
            self.get_column_collation(ArrayModel._meta.db_table, "field"),
            ci_collation,
        )
        # Alter collation.
        old_field = ArrayModel._meta.get_field("field")
        new_field_cs = ArrayField(CharField(max_length=16, db_collation=cs_collation))
        new_field_cs.set_attributes_from_name("field")
        new_field_cs.model = ArrayField
        with connection.schema_editor() as editor:
            editor.alter_field(ArrayModel, old_field, new_field_cs, strict=True)
        self.assertEqual(
            self.get_column_collation(ArrayModel._meta.db_table, "field"),
            cs_collation,
        )

    @isolate_apps("schema")
    @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific")
    @skipUnlessDBFeature(
        "supports_collation_on_charfield",
        "supports_non_deterministic_collations",
    )
    def test_unique_with_collation_charfield(self):
        ci_collation = self._add_ci_collation()

        class CiCharModel(Model):
            field = CharField(max_length=16, db_collation=ci_collation, unique=True)

            class Meta:
                app_label = "schema"

        # Create the table.
        with connection.schema_editor() as editor:
            editor.create_model(CiCharModel)
        self.isolated_local_models = [CiCharModel]
        self.assertEqual(
            self.get_column_collation(CiCharModel._meta.db_table, "field"),
            ci_collation,
        )
        self.assertIn("field", self.get_uniques(CiCharModel._meta.db_table))

    @isolate_apps("schema")
    @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific")
    @skipUnlessDBFeature(
        "supports_collation_on_charfield",
        "supports_non_deterministic_collations",
    )
    def test_relation_to_collation_charfield(self):
        ci_collation = self._add_ci_collation()

        class CiCharModel(Model):
            field = CharField(max_length=16, db_collation=ci_collation, unique=True)

            class Meta:
                app_label = "schema"

        class RelationModel(Model):
            field = OneToOneField(CiCharModel, CASCADE, to_field="field")

            class Meta:
                app_label = "schema"

        # Create the table.
        with connection.schema_editor() as editor:
            editor.create_model(CiCharModel)
            editor.create_model(RelationModel)
        self.isolated_local_models = [CiCharModel, RelationModel]
        self.assertEqual(
            self.get_column_collation(RelationModel._meta.db_table, "field_id"),
            ci_collation,
        )
        self.assertEqual(
            self.get_column_collation(CiCharModel._meta.db_table, "field"),
            ci_collation,
        )
        self.assertIn("field_id", self.get_uniques(RelationModel._meta.db_table))

    def test_alter_textfield_to_null(self):
        """
        #24307 - Should skip an alter statement on databases with
        interprets_empty_strings_as_nulls when changing a TextField to null.
        """
        # Create the table
        with connection.schema_editor() as editor:
            editor.create_model(Note)
        # Change the TextField to null
        old_field = Note._meta.get_field("info")
        new_field = copy(old_field)
        new_field.null = True
        with connection.schema_editor() as editor:
            editor.alter_field(Note, old_field, new_field, strict=True)

    def test_alter_null_to_not_null_keeping_default(self):
        """
        #23738 - Can change a nullable field with default to non-nullable
        with the same default.
        """
        # Create the table
        with connection.schema_editor() as editor:
            editor.create_model(AuthorWithDefaultHeight)
        # Ensure the field is right to begin with
        columns = self.column_classes(AuthorWithDefaultHeight)
        self.assertTrue(columns["height"][1][6])
        # Alter the height field to NOT NULL keeping the previous default
        old_field = AuthorWithDefaultHeight._meta.get_field("height")
        new_field = PositiveIntegerField(default=42)
        new_field.set_attributes_from_name("height")
        with connection.schema_editor() as editor:
            editor.alter_field(
                AuthorWithDefaultHeight, old_field, new_field, strict=True
            )
        columns = self.column_classes(AuthorWithDefaultHeight)
        self.assertFalse(columns["height"][1][6])

    @skipUnlessDBFeature("supports_foreign_keys")
    def test_alter_fk(self):
        """
        Tests altering of FKs
        """
        # Create the table
        with connection.schema_editor() as editor:
            editor.create_model(Author)
            editor.create_model(Book)
        # Ensure the field is right to begin with
        columns = self.column_classes(Book)
        self.assertEqual(
            columns["author_id"][0],
            connection.features.introspected_field_types["IntegerField"],
        )
        self.assertForeignKeyExists(Book, "author_id", "schema_author")
        # Alter the FK
        old_field = Book._meta.get_field("author")
        new_field = ForeignKey(Author, CASCADE, editable=False)
        new_field.set_attributes_from_name("author")
        with connection.schema_editor() as editor:
            editor.alter_field(Book, old_field, new_field, strict=True)
        columns = self.column_classes(Book)
        self.assertEqual(
            columns["author_id"][0],
            connection.features.introspected_field_types["IntegerField"],
        )
        self.assertForeignKeyExists(Book, "author_id", "schema_author")

    @skipUnlessDBFeature("supports_foreign_keys")
    def test_alter_to_fk(self):
        """
        #24447 - Tests adding a FK constraint for an existing column
        """

        class LocalBook(Model):
            author = IntegerField()
            title = CharField(max_length=100, db_index=True)
            pub_date = DateTimeField()

            class Meta:
                app_label = "schema"
                apps = new_apps

        self.local_models = [LocalBook]

        # Create the tables
        with connection.schema_editor() as editor:
            editor.create_model(Author)
            editor.create_model(LocalBook)
        # Ensure no FK constraint exists
        constraints = self.get_constraints(LocalBook._meta.db_table)
        for details in constraints.values():
            if details["foreign_key"]:
                self.fail(
                    "Found an unexpected FK constraint to %s" % details["columns"]
                )
        old_field = LocalBook._meta.get_field("author")
        new_field = ForeignKey(Author, CASCADE)
        new_field.set_attributes_from_name("author")
        with connection.schema_editor() as editor:
            editor.alter_field(LocalBook, old_field, new_field, strict=True)
        self.assertForeignKeyExists(LocalBook, "author_id", "schema_author")

    @skipUnlessDBFeature("supports_foreign_keys", "can_introspect_foreign_keys")
    def test_alter_o2o_to_fk(self):
        """
        #24163 - Tests altering of OneToOneField to ForeignKey
        """
        # Create the table
        with connection.schema_editor() as editor:
            editor.create_model(Author)
            editor.create_model(BookWithO2O)
        # Ensure the field is right to begin with
        columns = self.column_classes(BookWithO2O)
        self.assertEqual(
            columns["author_id"][0],
            connection.features.introspected_field_types["IntegerField"],
        )
        # Ensure the field is unique
        author = Author.objects.create(name="Joe")
        BookWithO2O.objects.create(
            author=author, title="Django 1", pub_date=datetime.datetime.now()
        )
        with self.assertRaises(IntegrityError):
            BookWithO2O.objects.create(
                author=author, title="Django 2", pub_date=datetime.datetime.now()
            )
        BookWithO2O.objects.all().delete()
        self.assertForeignKeyExists(BookWithO2O, "author_id", "schema_author")
        # Alter the OneToOneField to ForeignKey
        old_field = BookWithO2O._meta.get_field("author")
        new_field = ForeignKey(Author, CASCADE)
        new_field.set_attributes_from_name("author")
        with connection.schema_editor() as editor:
            editor.alter_field(BookWithO2O, old_field, new_field, strict=True)
        columns = self.column_classes(Book)
        self.assertEqual(
            columns["author_id"][0],
            connection.features.introspected_field_types["IntegerField"],
        )
        # Ensure the field is not unique anymore
        Book.objects.create(
            author=author, title="Django 1", pub_date=datetime.datetime.now()
        )
        Book.objects.create(
            author=author, title="Django 2", pub_date=datetime.datetime.now()
        )
        self.assertForeignKeyExists(Book, "author_id", "schema_author")

    @skipUnlessDBFeature("supports_foreign_keys", "can_introspect_foreign_keys")
    def test_alter_fk_to_o2o(self):
        """
        #24163 - Tests altering of ForeignKey to OneToOneField
        """
        # Create the table
        with connection.schema_editor() as editor:
            editor.create_model(Author)
            editor.create_model(Book)
        # Ensure the field is right to begin with
        columns = self.column_classes(Book)
        self.assertEqual(
            columns["author_id"][0],
            connection.features.introspected_field_types["IntegerField"],
        )
        # Ensure the field is not unique
        author = Author.objects.create(name="Joe")
        Book.objects.create(
            author=author, title="Django 1", pub_date=datetime.datetime.now()
        )
        Book.objects.create(
            author=author, title="Django 2", pub_date=datetime.datetime.now()
        )
        Book.objects.all().delete()
        self.assertForeignKeyExists(Book, "author_id", "schema_author")
        # Alter the ForeignKey to OneToOneField
        old_field = Book._meta.get_field("author")
        new_field = OneToOneField(Author, CASCADE)
        new_field.set_attributes_from_name("author")
        with connection.schema_editor() as editor:
            editor.alter_field(Book, old_field, new_field, strict=True)
        columns = self.column_classes(BookWithO2O)
        self.assertEqual(
            columns["author_id"][0],
            connection.features.introspected_field_types["IntegerField"],
        )
        # Ensure the field is unique now
        BookWithO2O.objects.create(
            author=author, title="Django 1", pub_date=datetime.datetime.now()
        )
        with self.assertRaises(IntegrityError):
            BookWithO2O.objects.create(
                author=author, title="Django 2", pub_date=datetime.datetime.now()
            )
        self.assertForeignKeyExists(BookWithO2O, "author_id", "schema_author")

    def test_alter_field_fk_to_o2o(self):
        with connection.schema_editor() as editor:
            editor.create_model(Author)
            editor.create_model(Book)
        expected_fks = (
            1
            if connection.features.supports_foreign_keys
            and connection.features.can_introspect_foreign_keys
            else 0
        )
        expected_indexes = 1 if connection.features.indexes_foreign_keys else 0

        # Check the index is right to begin with.
        counts = self.get_constraints_count(
            Book._meta.db_table,
            Book._meta.get_field("author").column,
            (Author._meta.db_table, Author._meta.pk.column),
        )
        self.assertEqual(
            counts,
            {"fks": expected_fks, "uniques": 0, "indexes": expected_indexes},
        )

        old_field = Book._meta.get_field("author")
        new_field = OneToOneField(Author, CASCADE)
        new_field.set_attributes_from_name("author")
        with connection.schema_editor() as editor:
            editor.alter_field(Book, old_field, new_field)

        counts = self.get_constraints_count(
            Book._meta.db_table,
            Book._meta.get_field("author").column,
            (Author._meta.db_table, Author._meta.pk.column),
        )
        # The index on ForeignKey is replaced with a unique constraint for
        # OneToOneField.
        self.assertEqual(counts, {"fks": expected_fks, "uniques": 1, "indexes": 0})

    def test_autofield_to_o2o(self):
        with connection.schema_editor() as editor:
            editor.create_model(Author)
            editor.create_model(Note)

        # Rename the field.
        old_field = Author._meta.get_field("id")
        new_field = AutoField(primary_key=True)
        new_field.set_attributes_from_name("note_ptr")
        new_field.model = Author

        with connection.schema_editor() as editor:
            editor.alter_field(Author, old_field, new_field, strict=True)
        # Alter AutoField to OneToOneField.
        new_field_o2o = OneToOneField(Note, CASCADE)
        new_field_o2o.set_attributes_from_name("note_ptr")
        new_field_o2o.model = Author

        with connection.schema_editor() as editor:
            editor.alter_field(Author, new_field, new_field_o2o, strict=True)
        columns = self.column_classes(Author)
        field_type, _ = columns["note_ptr_id"]
        self.assertEqual(
            field_type, connection.features.introspected_field_types["IntegerField"]
        )

    def test_alter_field_fk_keeps_index(self):
        with connection.schema_editor() as editor:
            editor.create_model(Author)
            editor.create_model(Book)
        expected_fks = (
            1
            if connection.features.supports_foreign_keys
            and connection.features.can_introspect_foreign_keys
            else 0
        )
        expected_indexes = 1 if connection.features.indexes_foreign_keys else 0

        # Check the index is right to begin with.
        counts = self.get_constraints_count(
            Book._meta.db_table,
            Book._meta.get_field("author").column,
            (Author._meta.db_table, Author._meta.pk.column),
        )
        self.assertEqual(
            counts,
            {"fks": expected_fks, "uniques": 0, "indexes": expected_indexes},
        )

        old_field = Book._meta.get_field("author")
        # on_delete changed from CASCADE.
        new_field = ForeignKey(Author, PROTECT)
        new_field.set_attributes_from_name("author")
        with connection.schema_editor() as editor:
            editor.alter_field(Book, old_field, new_field, strict=True)

        counts = self.get_constraints_count(
            Book._meta.db_table,
            Book._meta.get_field("author").column,
            (Author._meta.db_table, Author._meta.pk.column),
        )
        # The index remains.
        self.assertEqual(
            counts,
            {"fks": expected_fks, "uniques": 0, "indexes": expected_indexes},
        )

    def test_alter_field_o2o_to_fk(self):
        with connection.schema_editor() as editor:
            editor.create_model(Author)
            editor.create_model(BookWithO2O)
        expected_fks = (
            1
            if connection.features.supports_foreign_keys
            and connection.features.can_introspect_foreign_keys
            else 0
        )

        # Check the unique constraint is right to begin with.
        counts = self.get_constraints_count(
            BookWithO2O._meta.db_table,
            BookWithO2O._meta.get_field("author").column,
            (Author._meta.db_table, Author._meta.pk.column),
        )
        self.assertEqual(counts, {"fks": expected_fks, "uniques": 1, "indexes": 0})

        old_field = BookWithO2O._meta.get_field("author")
        new_field = ForeignKey(Author, CASCADE)
        new_field.set_attributes_from_name("author")
        with connection.schema_editor() as editor:
            editor.alter_field(BookWithO2O, old_field, new_field)

        counts = self.get_constraints_count(
            BookWithO2O._meta.db_table,
            BookWithO2O._meta.get_field("author").column,
            (Author._meta.db_table, Author._meta.pk.column),
        )
        # The unique constraint on OneToOneField is replaced with an index for
        # ForeignKey.
        self.assertEqual(counts, {"fks": expected_fks, "uniques": 0, "indexes": 1})

    def test_alter_field_o2o_keeps_unique(self):
        with connection.schema_editor() as editor:
            editor.create_model(Author)
            editor.create_model(BookWithO2O)
        expected_fks = (
            1
            if connection.features.supports_foreign_keys
            and connection.features.can_introspect_foreign_keys
            else 0
        )

        # Check the unique constraint is right to begin with.
        counts = self.get_constraints_count(
            BookWithO2O._meta.db_table,
            BookWithO2O._meta.get_field("author").column,
            (Author._meta.db_table, Author._meta.pk.column),
        )
        self.assertEqual(counts, {"fks": expected_fks, "uniques": 1, "indexes": 0})

        old_field = BookWithO2O._meta.get_field("author")
        # on_delete changed from CASCADE.
        new_field = OneToOneField(Author, PROTECT)
        new_field.set_attributes_from_name("author")
        with connection.schema_editor() as editor:
            editor.alter_field(BookWithO2O, old_field, new_field, strict=True)

        counts = self.get_constraints_count(
            BookWithO2O._meta.db_table,
            BookWithO2O._meta.get_field("author").column,
            (Author._meta.db_table, Author._meta.pk.column),
        )
        # The unique constraint remains.
        self.assertEqual(counts, {"fks": expected_fks, "uniques": 1, "indexes": 0})

    @skipUnlessDBFeature("ignores_table_name_case")
    def test_alter_db_table_case(self):
        # Create the table
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        # Alter the case of the table
        old_table_name = Author._meta.db_table
        with connection.schema_editor() as editor:
            editor.alter_db_table(Author, old_table_name, old_table_name.upper())

    def test_alter_implicit_id_to_explicit(self):
        """
        Should be able to convert an implicit "id" field to an explicit "id"
        primary key field.
        """
        with connection.schema_editor() as editor:
            editor.create_model(Author)

        old_field = Author._meta.get_field("id")
        new_field = AutoField(primary_key=True)
        new_field.set_attributes_from_name("id")
        new_field.model = Author
        with connection.schema_editor() as editor:
            editor.alter_field(Author, old_field, new_field, strict=True)
        # This will fail if DROP DEFAULT is inadvertently executed on this
        # field which drops the id sequence, at least on PostgreSQL.
        Author.objects.create(name="Foo")
        Author.objects.create(name="Bar")

    def test_alter_autofield_pk_to_bigautofield_pk(self):
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        old_field = Author._meta.get_field("id")
        new_field = BigAutoField(primary_key=True)
        new_field.set_attributes_from_name("id")
        new_field.model = Author
        with connection.schema_editor() as editor:
            editor.alter_field(Author, old_field, new_field, strict=True)

        Author.objects.create(name="Foo", pk=1)
        with connection.cursor() as cursor:
            sequence_reset_sqls = connection.ops.sequence_reset_sql(
                no_style(), [Author]
            )
            if sequence_reset_sqls:
                cursor.execute(sequence_reset_sqls[0])
        self.assertIsNotNone(Author.objects.create(name="Bar"))

    def test_alter_autofield_pk_to_smallautofield_pk(self):
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        old_field = Author._meta.get_field("id")
        new_field = SmallAutoField(primary_key=True)
        new_field.set_attributes_from_name("id")
        new_field.model = Author
        with connection.schema_editor() as editor:
            editor.alter_field(Author, old_field, new_field, strict=True)

        Author.objects.create(name="Foo", pk=1)
        with connection.cursor() as cursor:
            sequence_reset_sqls = connection.ops.sequence_reset_sql(
                no_style(), [Author]
            )
            if sequence_reset_sqls:
                cursor.execute(sequence_reset_sqls[0])
        self.assertIsNotNone(Author.objects.create(name="Bar"))

    def test_alter_int_pk_to_autofield_pk(self):
        """
        Should be able to rename an IntegerField(primary_key=True) to
        AutoField(primary_key=True).
        """
        with connection.schema_editor() as editor:
            editor.create_model(IntegerPK)

        old_field = IntegerPK._meta.get_field("i")
        new_field = AutoField(primary_key=True)
        new_field.model = IntegerPK
        new_field.set_attributes_from_name("i")

        with connection.schema_editor() as editor:
            editor.alter_field(IntegerPK, old_field, new_field, strict=True)

        # A model representing the updated model.
        class IntegerPKToAutoField(Model):
            i = AutoField(primary_key=True)
            j = IntegerField(unique=True)

            class Meta:
                app_label = "schema"
                apps = new_apps
                db_table = IntegerPK._meta.db_table

        # An id (i) is generated by the database.
        obj = IntegerPKToAutoField.objects.create(j=1)
        self.assertIsNotNone(obj.i)

    def test_alter_int_pk_to_bigautofield_pk(self):
        """
        Should be able to rename an IntegerField(primary_key=True) to
        BigAutoField(primary_key=True).
        """
        with connection.schema_editor() as editor:
            editor.create_model(IntegerPK)

        old_field = IntegerPK._meta.get_field("i")
        new_field = BigAutoField(primary_key=True)
        new_field.model = IntegerPK
        new_field.set_attributes_from_name("i")

        with connection.schema_editor() as editor:
            editor.alter_field(IntegerPK, old_field, new_field, strict=True)

        # A model representing the updated model.
        class IntegerPKToBigAutoField(Model):
            i = BigAutoField(primary_key=True)
            j = IntegerField(unique=True)

            class Meta:
                app_label = "schema"
                apps = new_apps
                db_table = IntegerPK._meta.db_table

        # An id (i) is generated by the database.
        obj = IntegerPKToBigAutoField.objects.create(j=1)
        self.assertIsNotNone(obj.i)

    @isolate_apps("schema")
    def test_alter_smallint_pk_to_smallautofield_pk(self):
        """
        Should be able to rename an SmallIntegerField(primary_key=True) to
        SmallAutoField(primary_key=True).
        """

        class SmallIntegerPK(Model):
            i = SmallIntegerField(primary_key=True)

            class Meta:
                app_label = "schema"

        with connection.schema_editor() as editor:
            editor.create_model(SmallIntegerPK)
        self.isolated_local_models = [SmallIntegerPK]
        old_field = SmallIntegerPK._meta.get_field("i")
        new_field = SmallAutoField(primary_key=True)
        new_field.model = SmallIntegerPK
        new_field.set_attributes_from_name("i")
        with connection.schema_editor() as editor:
            editor.alter_field(SmallIntegerPK, old_field, new_field, strict=True)

    @isolate_apps("schema")
    @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific")
    def test_alter_serial_auto_field_to_bigautofield(self):
        class SerialAutoField(Model):
            id = SmallAutoField(primary_key=True)

            class Meta:
                app_label = "schema"

        table = SerialAutoField._meta.db_table
        column = SerialAutoField._meta.get_field("id").column
        with connection.cursor() as cursor:
            cursor.execute(
                f'CREATE TABLE "{table}" '
                f'("{column}" smallserial NOT NULL PRIMARY KEY)'
            )
        try:
            old_field = SerialAutoField._meta.get_field("id")
            new_field = BigAutoField(primary_key=True)
            new_field.model = SerialAutoField
            new_field.set_attributes_from_name("id")
            with connection.schema_editor() as editor:
                editor.alter_field(SerialAutoField, old_field, new_field, strict=True)
            sequence_name = f"{table}_{column}_seq"
            with connection.cursor() as cursor:
                cursor.execute(
                    "SELECT data_type FROM pg_sequences WHERE sequencename = %s",
                    [sequence_name],
                )
                row = cursor.fetchone()
                sequence_data_type = row[0] if row and row[0] else None
                self.assertEqual(sequence_data_type, "bigint")
            # Rename the column.
            old_field = new_field
            new_field = AutoField(primary_key=True)
            new_field.model = SerialAutoField
            new_field.set_attributes_from_name("renamed_id")
            with connection.schema_editor() as editor:
                editor.alter_field(SerialAutoField, old_field, new_field, strict=True)
            with connection.cursor() as cursor:
                cursor.execute(
                    "SELECT data_type FROM pg_sequences WHERE sequencename = %s",
                    [sequence_name],
                )
                row = cursor.fetchone()
                sequence_data_type = row[0] if row and row[0] else None
                self.assertEqual(sequence_data_type, "integer")
        finally:
            with connection.cursor() as cursor:
                cursor.execute(f'DROP TABLE "{table}"')

    def test_alter_int_pk_to_int_unique(self):
        """
        Should be able to rename an IntegerField(primary_key=True) to
        IntegerField(unique=True).
        """
        with connection.schema_editor() as editor:
            editor.create_model(IntegerPK)
        # Delete the old PK
        old_field = IntegerPK._meta.get_field("i")
        new_field = IntegerField(unique=True)
        new_field.model = IntegerPK
        new_field.set_attributes_from_name("i")
        with connection.schema_editor() as editor:
            editor.alter_field(IntegerPK, old_field, new_field, strict=True)
        # The primary key constraint is gone. Result depends on database:
        # 'id' for SQLite, None for others (must not be 'i').
        self.assertIn(self.get_primary_key(IntegerPK._meta.db_table), ("id", None))

        # Set up a model class as it currently stands. The original IntegerPK
        # class is now out of date and some backends make use of the whole
        # model class when modifying a field (such as sqlite3 when remaking a
        # table) so an outdated model class leads to incorrect results.
        class Transitional(Model):
            i = IntegerField(unique=True)
            j = IntegerField(unique=True)

            class Meta:
                app_label = "schema"
                apps = new_apps
                db_table = "INTEGERPK"

        # model requires a new PK
        old_field = Transitional._meta.get_field("j")
        new_field = IntegerField(primary_key=True)
        new_field.model = Transitional
        new_field.set_attributes_from_name("j")

        with connection.schema_editor() as editor:
            editor.alter_field(Transitional, old_field, new_field, strict=True)

        # Create a model class representing the updated model.
        class IntegerUnique(Model):
            i = IntegerField(unique=True)
            j = IntegerField(primary_key=True)

            class Meta:
                app_label = "schema"
                apps = new_apps
                db_table = "INTEGERPK"

        # Ensure unique constraint works.
        IntegerUnique.objects.create(i=1, j=1)
        with self.assertRaises(IntegrityError):
            IntegerUnique.objects.create(i=1, j=2)

    def test_rename(self):
        """
        Tests simple altering of fields
        """
        # Create the table
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        # Ensure the field is right to begin with
        columns = self.column_classes(Author)
        self.assertEqual(
            columns["name"][0],
            connection.features.introspected_field_types["CharField"],
        )
        self.assertNotIn("display_name", columns)
        # Alter the name field's name
        old_field = Author._meta.get_field("name")
        new_field = CharField(max_length=254)
        new_field.set_attributes_from_name("display_name")
        with connection.schema_editor() as editor:
            editor.alter_field(Author, old_field, new_field, strict=True)
        columns = self.column_classes(Author)
        self.assertEqual(
            columns["display_name"][0],
            connection.features.introspected_field_types["CharField"],
        )
        self.assertNotIn("name", columns)

    @isolate_apps("schema")
    def test_rename_referenced_field(self):
        class Author(Model):
            name = CharField(max_length=255, unique=True)

            class Meta:
                app_label = "schema"

        class Book(Model):
            author = ForeignKey(Author, CASCADE, to_field="name")

            class Meta:
                app_label = "schema"

        with connection.schema_editor() as editor:
            editor.create_model(Author)
            editor.create_model(Book)
        new_field = CharField(max_length=255, unique=True)
        new_field.set_attributes_from_name("renamed")
        with connection.schema_editor(
            atomic=connection.features.supports_atomic_references_rename
        ) as editor:
            editor.alter_field(Author, Author._meta.get_field("name"), new_field)
        # Ensure the foreign key reference was updated.
        self.assertForeignKeyExists(Book, "author_id", "schema_author", "renamed")

    @skipIfDBFeature("interprets_empty_strings_as_nulls")
    def test_rename_keep_null_status(self):
        """
        Renaming a field shouldn't affect the not null status.
        """
        with connection.schema_editor() as editor:
            editor.create_model(Note)
        with self.assertRaises(IntegrityError):
            Note.objects.create(info=None)
        old_field = Note._meta.get_field("info")
        new_field = TextField()
        new_field.set_attributes_from_name("detail_info")
        with connection.schema_editor() as editor:
            editor.alter_field(Note, old_field, new_field, strict=True)
        columns = self.column_classes(Note)
        self.assertEqual(columns["detail_info"][0], "TextField")
        self.assertNotIn("info", columns)
        with self.assertRaises(IntegrityError):
            NoteRename.objects.create(detail_info=None)

    @isolate_apps("schema")
    def test_rename_keep_db_default(self):
        """Renaming a field shouldn't affect a database default."""

        class AuthorDbDefault(Model):
            birth_year = IntegerField(db_default=1985)

            class Meta:
                app_label = "schema"

        self.isolated_local_models = [AuthorDbDefault]
        with connection.schema_editor() as editor:
            editor.create_model(AuthorDbDefault)
        columns = self.column_classes(AuthorDbDefault)
        self.assertEqual(columns["birth_year"][1].default, "1985")

        old_field = AuthorDbDefault._meta.get_field("birth_year")
        new_field = IntegerField(db_default=1985)
        new_field.set_attributes_from_name("renamed_year")
        new_field.model = AuthorDbDefault
        with connection.schema_editor(
            atomic=connection.features.supports_atomic_references_rename
        ) as editor:
            editor.alter_field(AuthorDbDefault, old_field, new_field, strict=True)
        columns = self.column_classes(AuthorDbDefault)
        self.assertEqual(columns["renamed_year"][1].default, "1985")

    @skipUnlessDBFeature(
        "supports_column_check_constraints", "can_introspect_check_constraints"
    )
    @isolate_apps("schema")
    def test_rename_field_with_check_to_truncated_name(self):
        class AuthorWithLongColumn(Model):
            field_with_very_looooooong_name = PositiveIntegerField(null=True)

            class Meta:
                app_label = "schema"

        self.isolated_local_models = [AuthorWithLongColumn]
        with connection.schema_editor() as editor:
            editor.create_model(AuthorWithLongColumn)
        old_field = AuthorWithLongColumn._meta.get_field(
            "field_with_very_looooooong_name"
        )
        new_field = PositiveIntegerField(null=True)
        new_field.set_attributes_from_name("renamed_field_with_very_long_name")
        with connection.schema_editor() as editor:
            editor.alter_field(AuthorWithLongColumn, old_field, new_field, strict=True)

        new_field_name = truncate_name(
            new_field.column, connection.ops.max_name_length()
        )
        constraints = self.get_constraints(AuthorWithLongColumn._meta.db_table)
        check_constraints = [
            name
            for name, details in constraints.items()
            if details["columns"] == [new_field_name] and details["check"]
        ]
        self.assertEqual(len(check_constraints), 1)

    def _test_m2m_create(self, M2MFieldClass):
        """
        Tests M2M fields on models during creation
        """

        class LocalBookWithM2M(Model):
            author = ForeignKey(Author, CASCADE)
            title = CharField(max_length=100, db_index=True)
            pub_date = DateTimeField()
            tags = M2MFieldClass("TagM2MTest", related_name="books")

            class Meta:
                app_label = "schema"
                apps = new_apps

        self.local_models = [LocalBookWithM2M]
        # Create the tables
        with connection.schema_editor() as editor:
            editor.create_model(Author)
            editor.create_model(TagM2MTest)
            editor.create_model(LocalBookWithM2M)
        # Ensure there is now an m2m table there
        columns = self.column_classes(
            LocalBookWithM2M._meta.get_field("tags").remote_field.through
        )
        self.assertEqual(
            columns["tagm2mtest_id"][0],
            connection.features.introspected_field_types["IntegerField"],
        )

    def test_m2m_create(self):
        self._test_m2m_create(ManyToManyField)

    def test_m2m_create_custom(self):
        self._test_m2m_create(CustomManyToManyField)

    def test_m2m_create_inherited(self):
        self._test_m2m_create(InheritedManyToManyField)

    def _test_m2m_create_through(self, M2MFieldClass):
        """
        Tests M2M fields on models during creation with through models
        """

        class LocalTagThrough(Model):
            book = ForeignKey("schema.LocalBookWithM2MThrough", CASCADE)
            tag = ForeignKey("schema.TagM2MTest", CASCADE)

            class Meta:
                app_label = "schema"
                apps = new_apps

        class LocalBookWithM2MThrough(Model):
            tags = M2MFieldClass(
                "TagM2MTest", related_name="books", through=LocalTagThrough
            )

            class Meta:
                app_label = "schema"
                apps = new_apps

        self.local_models = [LocalTagThrough, LocalBookWithM2MThrough]

        # Create the tables
        with connection.schema_editor() as editor:
            editor.create_model(LocalTagThrough)
            editor.create_model(TagM2MTest)
            editor.create_model(LocalBookWithM2MThrough)
        # Ensure there is now an m2m table there
        columns = self.column_classes(LocalTagThrough)
        self.assertEqual(
            columns["book_id"][0],
            connection.features.introspected_field_types["IntegerField"],
        )
        self.assertEqual(
            columns["tag_id"][0],
            connection.features.introspected_field_types["IntegerField"],
        )

    def test_m2m_create_through(self):
        self._test_m2m_create_through(ManyToManyField)

    def test_m2m_create_through_custom(self):
        self._test_m2m_create_through(CustomManyToManyField)

    def test_m2m_create_through_inherited(self):
        self._test_m2m_create_through(InheritedManyToManyField)

    def test_m2m_through_remove(self):
        class LocalAuthorNoteThrough(Model):
            book = ForeignKey("schema.Author", CASCADE)
            tag = ForeignKey("self", CASCADE)

            class Meta:
                app_label = "schema"
                apps = new_apps

        class LocalNoteWithM2MThrough(Model):
            authors = ManyToManyField("schema.Author", through=LocalAuthorNoteThrough)

            class Meta:
                app_label = "schema"
                apps = new_apps

        self.local_models = [LocalAuthorNoteThrough, LocalNoteWithM2MThrough]
        # Create the tables.
        with connection.schema_editor() as editor:
            editor.create_model(Author)
            editor.create_model(LocalAuthorNoteThrough)
            editor.create_model(LocalNoteWithM2MThrough)
        # Remove the through parameter.
        old_field = LocalNoteWithM2MThrough._meta.get_field("authors")
        new_field = ManyToManyField("Author")
        new_field.set_attributes_from_name("authors")
        msg = (
            f"Cannot alter field {old_field} into {new_field} - they are not "
            f"compatible types (you cannot alter to or from M2M fields, or add or "
            f"remove through= on M2M fields)"
        )
        with connection.schema_editor() as editor:
            with self.assertRaisesMessage(ValueError, msg):
                editor.alter_field(LocalNoteWithM2MThrough, old_field, new_field)

    def _test_m2m(self, M2MFieldClass):
        """
        Tests adding/removing M2M fields on models
        """

        class LocalAuthorWithM2M(Model):
            name = CharField(max_length=255)

            class Meta:
                app_label = "schema"
                apps = new_apps

        self.local_models = [LocalAuthorWithM2M]

        # Create the tables
        with connection.schema_editor() as editor:
            editor.create_model(LocalAuthorWithM2M)
            editor.create_model(TagM2MTest)
        # Create an M2M field
        new_field = M2MFieldClass("schema.TagM2MTest", related_name="authors")
        new_field.contribute_to_class(LocalAuthorWithM2M, "tags")
        # Ensure there's no m2m table there
        with self.assertRaises(DatabaseError):
            self.column_classes(new_field.remote_field.through)
        # Add the field
        with CaptureQueriesContext(
            connection
        ) as ctx, connection.schema_editor() as editor:
            editor.add_field(LocalAuthorWithM2M, new_field)
        # Table is not rebuilt.
        self.assertEqual(
            len(
                [
                    query["sql"]
                    for query in ctx.captured_queries
                    if "CREATE TABLE" in query["sql"]
                ]
            ),
            1,
        )
        self.assertIs(
            any("DROP TABLE" in query["sql"] for query in ctx.captured_queries),
            False,
        )
        # Ensure there is now an m2m table there
        columns = self.column_classes(new_field.remote_field.through)
        self.assertEqual(
            columns["tagm2mtest_id"][0],
            connection.features.introspected_field_types["IntegerField"],
        )

        # "Alter" the field. This should not rename the DB table to itself.
        with connection.schema_editor() as editor:
            editor.alter_field(LocalAuthorWithM2M, new_field, new_field, strict=True)

        # Remove the M2M table again
        with connection.schema_editor() as editor:
            editor.remove_field(LocalAuthorWithM2M, new_field)
        # Ensure there's no m2m table there
        with self.assertRaises(DatabaseError):
            self.column_classes(new_field.remote_field.through)

        # Make sure the model state is coherent with the table one now that
        # we've removed the tags field.
        opts = LocalAuthorWithM2M._meta
        opts.local_many_to_many.remove(new_field)
        del new_apps.all_models["schema"][
            new_field.remote_field.through._meta.model_name
        ]
        opts._expire_cache()

    def test_m2m(self):
        self._test_m2m(ManyToManyField)

    def test_m2m_custom(self):
        self._test_m2m(CustomManyToManyField)

    def test_m2m_inherited(self):
        self._test_m2m(InheritedManyToManyField)

    def _test_m2m_through_alter(self, M2MFieldClass):
        """
        Tests altering M2Ms with explicit through models (should no-op)
        """

        class LocalAuthorTag(Model):
            author = ForeignKey("schema.LocalAuthorWithM2MThrough", CASCADE)
            tag = ForeignKey("schema.TagM2MTest", CASCADE)

            class Meta:
                app_label = "schema"
                apps = new_apps

        class LocalAuthorWithM2MThrough(Model):
            name = CharField(max_length=255)
            tags = M2MFieldClass(
                "schema.TagM2MTest", related_name="authors", through=LocalAuthorTag
            )

            class Meta:
                app_label = "schema"
                apps = new_apps

        self.local_models = [LocalAuthorTag, LocalAuthorWithM2MThrough]

        # Create the tables
        with connection.schema_editor() as editor:
            editor.create_model(LocalAuthorTag)
            editor.create_model(LocalAuthorWithM2MThrough)
            editor.create_model(TagM2MTest)
        # Ensure the m2m table is there
        self.assertEqual(len(self.column_classes(LocalAuthorTag)), 3)
        # "Alter" the field's blankness. This should not actually do anything.
        old_field = LocalAuthorWithM2MThrough._meta.get_field("tags")
        new_field = M2MFieldClass(
            "schema.TagM2MTest", related_name="authors", through=LocalAuthorTag
        )
        new_field.contribute_to_class(LocalAuthorWithM2MThrough, "tags")
        with connection.schema_editor() as editor:
            editor.alter_field(
                LocalAuthorWithM2MThrough, old_field, new_field, strict=True
            )
        # Ensure the m2m table is still there
        self.assertEqual(len(self.column_classes(LocalAuthorTag)), 3)

    def test_m2m_through_alter(self):
        self._test_m2m_through_alter(ManyToManyField)

    def test_m2m_through_alter_custom(self):
        self._test_m2m_through_alter(CustomManyToManyField)

    def test_m2m_through_alter_inherited(self):
        self._test_m2m_through_alter(InheritedManyToManyField)

    def _test_m2m_repoint(self, M2MFieldClass):
        """
        Tests repointing M2M fields
        """

        class LocalBookWithM2M(Model):
            author = ForeignKey(Author, CASCADE)
            title = CharField(max_length=100, db_index=True)
            pub_date = DateTimeField()
            tags = M2MFieldClass("TagM2MTest", related_name="books")

            class Meta:
                app_label = "schema"
                apps = new_apps

        self.local_models = [LocalBookWithM2M]
        # Create the tables
        with connection.schema_editor() as editor:
            editor.create_model(Author)
            editor.create_model(LocalBookWithM2M)
            editor.create_model(TagM2MTest)
            editor.create_model(UniqueTest)
        # Ensure the M2M exists and points to TagM2MTest
        if connection.features.supports_foreign_keys:
            self.assertForeignKeyExists(
                LocalBookWithM2M._meta.get_field("tags").remote_field.through,
                "tagm2mtest_id",
                "schema_tagm2mtest",
            )
        # Repoint the M2M
        old_field = LocalBookWithM2M._meta.get_field("tags")
        new_field = M2MFieldClass(UniqueTest)
        new_field.contribute_to_class(LocalBookWithM2M, "uniques")
        with connection.schema_editor() as editor:
            editor.alter_field(LocalBookWithM2M, old_field, new_field, strict=True)
        # Ensure old M2M is gone
        with self.assertRaises(DatabaseError):
            self.column_classes(
                LocalBookWithM2M._meta.get_field("tags").remote_field.through
            )

        # This model looks like the new model and is used for teardown.
        opts = LocalBookWithM2M._meta
        opts.local_many_to_many.remove(old_field)
        # Ensure the new M2M exists and points to UniqueTest
        if connection.features.supports_foreign_keys:
            self.assertForeignKeyExists(
                new_field.remote_field.through, "uniquetest_id", "schema_uniquetest"
            )

    def test_m2m_repoint(self):
        self._test_m2m_repoint(ManyToManyField)

    def test_m2m_repoint_custom(self):
        self._test_m2m_repoint(CustomManyToManyField)

    def test_m2m_repoint_inherited(self):
        self._test_m2m_repoint(InheritedManyToManyField)

    @isolate_apps("schema")
    def test_m2m_rename_field_in_target_model(self):
        class LocalTagM2MTest(Model):
            title = CharField(max_length=255)

            class Meta:
                app_label = "schema"

        class LocalM2M(Model):
            tags = ManyToManyField(LocalTagM2MTest)

            class Meta:
                app_label = "schema"

        # Create the tables.
        with connection.schema_editor() as editor:
            editor.create_model(LocalM2M)
            editor.create_model(LocalTagM2MTest)
        self.isolated_local_models = [LocalM2M, LocalTagM2MTest]
        # Ensure the m2m table is there.
        self.assertEqual(len(self.column_classes(LocalM2M)), 1)
        # Alter a field in LocalTagM2MTest.
        old_field = LocalTagM2MTest._meta.get_field("title")
        new_field = CharField(max_length=254)
        new_field.contribute_to_class(LocalTagM2MTest, "title1")
        # @isolate_apps() and inner models are needed to have the model
        # relations populated, otherwise this doesn't act as a regression test.
        self.assertEqual(len(new_field.model._meta.related_objects), 1)
        with connection.schema_editor() as editor:
            editor.alter_field(LocalTagM2MTest, old_field, new_field, strict=True)
        # Ensure the m2m table is still there.
        self.assertEqual(len(self.column_classes(LocalM2M)), 1)

    @skipUnlessDBFeature(
        "supports_column_check_constraints", "can_introspect_check_constraints"
    )
    def test_check_constraints(self):
        """
        Tests creating/deleting CHECK constraints
        """
        # Create the tables
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        # Ensure the constraint exists
        constraints = self.get_constraints(Author._meta.db_table)
        if not any(
            details["columns"] == ["height"] and details["check"]
            for details in constraints.values()
        ):
            self.fail("No check constraint for height found")
        # Alter the column to remove it
        old_field = Author._meta.get_field("height")
        new_field = IntegerField(null=True, blank=True)
        new_field.set_attributes_from_name("height")
        with connection.schema_editor() as editor:
            editor.alter_field(Author, old_field, new_field, strict=True)
        constraints = self.get_constraints(Author._meta.db_table)
        for details in constraints.values():
            if details["columns"] == ["height"] and details["check"]:
                self.fail("Check constraint for height found")
        # Alter the column to re-add it
        new_field2 = Author._meta.get_field("height")
        with connection.schema_editor() as editor:
            editor.alter_field(Author, new_field, new_field2, strict=True)
        constraints = self.get_constraints(Author._meta.db_table)
        if not any(
            details["columns"] == ["height"] and details["check"]
            for details in constraints.values()
        ):
            self.fail("No check constraint for height found")

    @skipUnlessDBFeature(
        "supports_column_check_constraints", "can_introspect_check_constraints"
    )
    @isolate_apps("schema")
    def test_check_constraint_timedelta_param(self):
        class DurationModel(Model):
            duration = DurationField()

            class Meta:
                app_label = "schema"

        with connection.schema_editor() as editor:
            editor.create_model(DurationModel)
        self.isolated_local_models = [DurationModel]
        constraint_name = "duration_gte_5_minutes"
        constraint = CheckConstraint(
            check=Q(duration__gt=datetime.timedelta(minutes=5)),
            name=constraint_name,
        )
        DurationModel._meta.constraints = [constraint]
        with connection.schema_editor() as editor:
            editor.add_constraint(DurationModel, constraint)
        constraints = self.get_constraints(DurationModel._meta.db_table)
        self.assertIn(constraint_name, constraints)
        with self.assertRaises(IntegrityError), atomic():
            DurationModel.objects.create(duration=datetime.timedelta(minutes=4))
        DurationModel.objects.create(duration=datetime.timedelta(minutes=10))

    @skipUnlessDBFeature(
        "supports_column_check_constraints", "can_introspect_check_constraints"
    )
    def test_remove_field_check_does_not_remove_meta_constraints(self):
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        # Add the custom check constraint
        constraint = CheckConstraint(
            check=Q(height__gte=0), name="author_height_gte_0_check"
        )
        custom_constraint_name = constraint.name
        Author._meta.constraints = [constraint]
        with connection.schema_editor() as editor:
            editor.add_constraint(Author, constraint)
        # Ensure the constraints exist
        constraints = self.get_constraints(Author._meta.db_table)
        self.assertIn(custom_constraint_name, constraints)
        other_constraints = [
            name
            for name, details in constraints.items()
            if details["columns"] == ["height"]
            and details["check"]
            and name != custom_constraint_name
        ]
        self.assertEqual(len(other_constraints), 1)
        # Alter the column to remove field check
        old_field = Author._meta.get_field("height")
        new_field = IntegerField(null=True, blank=True)
        new_field.set_attributes_from_name("height")
        with connection.schema_editor() as editor:
            editor.alter_field(Author, old_field, new_field, strict=True)
        constraints = self.get_constraints(Author._meta.db_table)
        self.assertIn(custom_constraint_name, constraints)
        other_constraints = [
            name
            for name, details in constraints.items()
            if details["columns"] == ["height"]
            and details["check"]
            and name != custom_constraint_name
        ]
        self.assertEqual(len(other_constraints), 0)
        # Alter the column to re-add field check
        new_field2 = Author._meta.get_field("height")
        with connection.schema_editor() as editor:
            editor.alter_field(Author, new_field, new_field2, strict=True)
        constraints = self.get_constraints(Author._meta.db_table)
        self.assertIn(custom_constraint_name, constraints)
        other_constraints = [
            name
            for name, details in constraints.items()
            if details["columns"] == ["height"]
            and details["check"]
            and name != custom_constraint_name
        ]
        self.assertEqual(len(other_constraints), 1)
        # Drop the check constraint
        with connection.schema_editor() as editor:
            Author._meta.constraints = []
            editor.remove_constraint(Author, constraint)

    def test_unique(self):
        """
        Tests removing and adding unique constraints to a single column.
        """
        # Create the table
        with connection.schema_editor() as editor:
            editor.create_model(Tag)
        # Ensure the field is unique to begin with
        Tag.objects.create(title="foo", slug="foo")
        with self.assertRaises(IntegrityError):
            Tag.objects.create(title="bar", slug="foo")
        Tag.objects.all().delete()
        # Alter the slug field to be non-unique
        old_field = Tag._meta.get_field("slug")
        new_field = SlugField(unique=False)
        new_field.set_attributes_from_name("slug")
        with connection.schema_editor() as editor:
            editor.alter_field(Tag, old_field, new_field, strict=True)
        # Ensure the field is no longer unique
        Tag.objects.create(title="foo", slug="foo")
        Tag.objects.create(title="bar", slug="foo")
        Tag.objects.all().delete()
        # Alter the slug field to be unique
        new_field2 = SlugField(unique=True)
        new_field2.set_attributes_from_name("slug")
        with connection.schema_editor() as editor:
            editor.alter_field(Tag, new_field, new_field2, strict=True)
        # Ensure the field is unique again
        Tag.objects.create(title="foo", slug="foo")
        with self.assertRaises(IntegrityError):
            Tag.objects.create(title="bar", slug="foo")
        Tag.objects.all().delete()
        # Rename the field
        new_field3 = SlugField(unique=True)
        new_field3.set_attributes_from_name("slug2")
        with connection.schema_editor() as editor:
            editor.alter_field(Tag, new_field2, new_field3, strict=True)
        # Ensure the field is still unique
        TagUniqueRename.objects.create(title="foo", slug2="foo")
        with self.assertRaises(IntegrityError):
            TagUniqueRename.objects.create(title="bar", slug2="foo")
        Tag.objects.all().delete()

    def test_unique_name_quoting(self):
        old_table_name = TagUniqueRename._meta.db_table
        try:
            with connection.schema_editor() as editor:
                editor.create_model(TagUniqueRename)
                editor.alter_db_table(TagUniqueRename, old_table_name, "unique-table")
                TagUniqueRename._meta.db_table = "unique-table"
                # This fails if the unique index name isn't quoted.
                editor.alter_unique_together(TagUniqueRename, [], (("title", "slug2"),))
        finally:
            with connection.schema_editor() as editor:
                editor.delete_model(TagUniqueRename)
            TagUniqueRename._meta.db_table = old_table_name

    @isolate_apps("schema")
    @skipUnlessDBFeature("supports_foreign_keys")
    def test_unique_no_unnecessary_fk_drops(self):
        """
        If AlterField isn't selective about dropping foreign key constraints
        when modifying a field with a unique constraint, the AlterField
        incorrectly drops and recreates the Book.author foreign key even though
        it doesn't restrict the field being changed (#29193).
        """

        class Author(Model):
            name = CharField(max_length=254, unique=True)

            class Meta:
                app_label = "schema"

        class Book(Model):
            author = ForeignKey(Author, CASCADE)

            class Meta:
                app_label = "schema"

        with connection.schema_editor() as editor:
            editor.create_model(Author)
            editor.create_model(Book)
        new_field = CharField(max_length=255, unique=True)
        new_field.model = Author
        new_field.set_attributes_from_name("name")
        with self.assertLogs("django.db.backends.schema", "DEBUG") as cm:
            with connection.schema_editor() as editor:
                editor.alter_field(Author, Author._meta.get_field("name"), new_field)
        # One SQL statement is executed to alter the field.
        self.assertEqual(len(cm.records), 1)

    @isolate_apps("schema")
    def test_unique_and_reverse_m2m(self):
        """
        AlterField can modify a unique field when there's a reverse M2M
        relation on the model.
        """

        class Tag(Model):
            title = CharField(max_length=255)
            slug = SlugField(unique=True)

            class Meta:
                app_label = "schema"

        class Book(Model):
            tags = ManyToManyField(Tag, related_name="books")

            class Meta:
                app_label = "schema"

        self.isolated_local_models = [Book._meta.get_field("tags").remote_field.through]
        with connection.schema_editor() as editor:
            editor.create_model(Tag)
            editor.create_model(Book)
        new_field = SlugField(max_length=75, unique=True)
        new_field.model = Tag
        new_field.set_attributes_from_name("slug")
        with self.assertLogs("django.db.backends.schema", "DEBUG") as cm:
            with connection.schema_editor() as editor:
                editor.alter_field(Tag, Tag._meta.get_field("slug"), new_field)
        # One SQL statement is executed to alter the field.
        self.assertEqual(len(cm.records), 1)
        # Ensure that the field is still unique.
        Tag.objects.create(title="foo", slug="foo")
        with self.assertRaises(IntegrityError):
            Tag.objects.create(title="bar", slug="foo")

    def test_remove_ignored_unique_constraint_not_create_fk_index(self):
        with connection.schema_editor() as editor:
            editor.create_model(Author)
            editor.create_model(Book)
        constraint = UniqueConstraint(
            "author",
            condition=Q(title__in=["tHGttG", "tRatEotU"]),
            name="book_author_condition_uniq",
        )
        # Add unique constraint.
        with connection.schema_editor() as editor:
            editor.add_constraint(Book, constraint)
        old_constraints = self.get_constraints_for_column(
            Book,
            Book._meta.get_field("author").column,
        )
        # Remove unique constraint.
        with connection.schema_editor() as editor:
            editor.remove_constraint(Book, constraint)
        new_constraints = self.get_constraints_for_column(
            Book,
            Book._meta.get_field("author").column,
        )
        # Redundant foreign key index is not added.
        self.assertEqual(
            len(old_constraints) - 1
            if connection.features.supports_partial_indexes
            else len(old_constraints),
            len(new_constraints),
        )

    @skipUnlessDBFeature("allows_multiple_constraints_on_same_fields")
    def test_remove_field_unique_does_not_remove_meta_constraints(self):
        with connection.schema_editor() as editor:
            editor.create_model(AuthorWithUniqueName)
        self.local_models = [AuthorWithUniqueName]
        # Add the custom unique constraint
        constraint = UniqueConstraint(fields=["name"], name="author_name_uniq")
        custom_constraint_name = constraint.name
        AuthorWithUniqueName._meta.constraints = [constraint]
        with connection.schema_editor() as editor:
            editor.add_constraint(AuthorWithUniqueName, constraint)
        # Ensure the constraints exist
        constraints = self.get_constraints(AuthorWithUniqueName._meta.db_table)
        self.assertIn(custom_constraint_name, constraints)
        other_constraints = [
            name
            for name, details in constraints.items()
            if details["columns"] == ["name"]
            and details["unique"]
            and name != custom_constraint_name
        ]
        self.assertEqual(len(other_constraints), 1)
        # Alter the column to remove field uniqueness
        old_field = AuthorWithUniqueName._meta.get_field("name")
        new_field = CharField(max_length=255)
        new_field.set_attributes_from_name("name")
        with connection.schema_editor() as editor:
            editor.alter_field(AuthorWithUniqueName, old_field, new_field, strict=True)
        constraints = self.get_constraints(AuthorWithUniqueName._meta.db_table)
        self.assertIn(custom_constraint_name, constraints)
        other_constraints = [
            name
            for name, details in constraints.items()
            if details["columns"] == ["name"]
            and details["unique"]
            and name != custom_constraint_name
        ]
        self.assertEqual(len(other_constraints), 0)
        # Alter the column to re-add field uniqueness
        new_field2 = AuthorWithUniqueName._meta.get_field("name")
        with connection.schema_editor() as editor:
            editor.alter_field(AuthorWithUniqueName, new_field, new_field2, strict=True)
        constraints = self.get_constraints(AuthorWithUniqueName._meta.db_table)
        self.assertIn(custom_constraint_name, constraints)
        other_constraints = [
            name
            for name, details in constraints.items()
            if details["columns"] == ["name"]
            and details["unique"]
            and name != custom_constraint_name
        ]
        self.assertEqual(len(other_constraints), 1)
        # Drop the unique constraint
        with connection.schema_editor() as editor:
            AuthorWithUniqueName._meta.constraints = []
            editor.remove_constraint(AuthorWithUniqueName, constraint)

    def test_unique_together(self):
        """
        Tests removing and adding unique_together constraints on a model.
        """
        # Create the table
        with connection.schema_editor() as editor:
            editor.create_model(UniqueTest)
        # Ensure the fields are unique to begin with
        UniqueTest.objects.create(year=2012, slug="foo")
        UniqueTest.objects.create(year=2011, slug="foo")
        UniqueTest.objects.create(year=2011, slug="bar")
        with self.assertRaises(IntegrityError):
            UniqueTest.objects.create(year=2012, slug="foo")
        UniqueTest.objects.all().delete()
        # Alter the model to its non-unique-together companion
        with connection.schema_editor() as editor:
            editor.alter_unique_together(
                UniqueTest, UniqueTest._meta.unique_together, []
            )
        # Ensure the fields are no longer unique
        UniqueTest.objects.create(year=2012, slug="foo")
        UniqueTest.objects.create(year=2012, slug="foo")
        UniqueTest.objects.all().delete()
        # Alter it back
        new_field2 = SlugField(unique=True)
        new_field2.set_attributes_from_name("slug")
        with connection.schema_editor() as editor:
            editor.alter_unique_together(
                UniqueTest, [], UniqueTest._meta.unique_together
            )
        # Ensure the fields are unique again
        UniqueTest.objects.create(year=2012, slug="foo")
        with self.assertRaises(IntegrityError):
            UniqueTest.objects.create(year=2012, slug="foo")
        UniqueTest.objects.all().delete()

    def test_unique_together_with_fk(self):
        """
        Tests removing and adding unique_together constraints that include
        a foreign key.
        """
        # Create the table
        with connection.schema_editor() as editor:
            editor.create_model(Author)
            editor.create_model(Book)
        # Ensure the fields are unique to begin with
        self.assertEqual(Book._meta.unique_together, ())
        # Add the unique_together constraint
        with connection.schema_editor() as editor:
            editor.alter_unique_together(Book, [], [["author", "title"]])
        # Alter it back
        with connection.schema_editor() as editor:
            editor.alter_unique_together(Book, [["author", "title"]], [])

    def test_unique_together_with_fk_with_existing_index(self):
        """
        Tests removing and adding unique_together constraints that include
        a foreign key, where the foreign key is added after the model is
        created.
        """
        # Create the tables
        with connection.schema_editor() as editor:
            editor.create_model(Author)
            editor.create_model(BookWithoutAuthor)
            new_field = ForeignKey(Author, CASCADE)
            new_field.set_attributes_from_name("author")
            editor.add_field(BookWithoutAuthor, new_field)
        # Ensure the fields aren't unique to begin with
        self.assertEqual(Book._meta.unique_together, ())
        # Add the unique_together constraint
        with connection.schema_editor() as editor:
            editor.alter_unique_together(Book, [], [["author", "title"]])
        # Alter it back
        with connection.schema_editor() as editor:
            editor.alter_unique_together(Book, [["author", "title"]], [])

    def _test_composed_index_with_fk(self, index):
        with connection.schema_editor() as editor:
            editor.create_model(Author)
            editor.create_model(Book)
        table = Book._meta.db_table
        self.assertEqual(Book._meta.indexes, [])
        Book._meta.indexes = [index]
        with connection.schema_editor() as editor:
            editor.add_index(Book, index)
        self.assertIn(index.name, self.get_constraints(table))
        Book._meta.indexes = []
        with connection.schema_editor() as editor:
            editor.remove_index(Book, index)
        self.assertNotIn(index.name, self.get_constraints(table))

    def test_composed_index_with_fk(self):
        index = Index(fields=["author", "title"], name="book_author_title_idx")
        self._test_composed_index_with_fk(index)

    def test_composed_desc_index_with_fk(self):
        index = Index(fields=["-author", "title"], name="book_author_title_idx")
        self._test_composed_index_with_fk(index)

    @skipUnlessDBFeature("supports_expression_indexes")
    def test_composed_func_index_with_fk(self):
        index = Index(F("author"), F("title"), name="book_author_title_idx")
        self._test_composed_index_with_fk(index)

    @skipUnlessDBFeature("supports_expression_indexes")
    def test_composed_desc_func_index_with_fk(self):
        index = Index(F("author").desc(), F("title"), name="book_author_title_idx")
        self._test_composed_index_with_fk(index)

    @skipUnlessDBFeature("supports_expression_indexes")
    def test_composed_func_transform_index_with_fk(self):
        index = Index(F("title__lower"), name="book_title_lower_idx")
        with register_lookup(CharField, Lower):
            self._test_composed_index_with_fk(index)

    def _test_composed_constraint_with_fk(self, constraint):
        with connection.schema_editor() as editor:
            editor.create_model(Author)
            editor.create_model(Book)
        table = Book._meta.db_table
        self.assertEqual(Book._meta.constraints, [])
        Book._meta.constraints = [constraint]
        with connection.schema_editor() as editor:
            editor.add_constraint(Book, constraint)
        self.assertIn(constraint.name, self.get_constraints(table))
        Book._meta.constraints = []
        with connection.schema_editor() as editor:
            editor.remove_constraint(Book, constraint)
        self.assertNotIn(constraint.name, self.get_constraints(table))

    def test_composed_constraint_with_fk(self):
        constraint = UniqueConstraint(
            fields=["author", "title"],
            name="book_author_title_uniq",
        )
        self._test_composed_constraint_with_fk(constraint)

    @skipUnlessDBFeature(
        "supports_column_check_constraints", "can_introspect_check_constraints"
    )
    def test_composed_check_constraint_with_fk(self):
        constraint = CheckConstraint(check=Q(author__gt=0), name="book_author_check")
        self._test_composed_constraint_with_fk(constraint)

    @skipUnlessDBFeature("allows_multiple_constraints_on_same_fields")
    def test_remove_unique_together_does_not_remove_meta_constraints(self):
        with connection.schema_editor() as editor:
            editor.create_model(AuthorWithUniqueNameAndBirthday)
        self.local_models = [AuthorWithUniqueNameAndBirthday]
        # Add the custom unique constraint
        constraint = UniqueConstraint(
            fields=["name", "birthday"], name="author_name_birthday_uniq"
        )
        custom_constraint_name = constraint.name
        AuthorWithUniqueNameAndBirthday._meta.constraints = [constraint]
        with connection.schema_editor() as editor:
            editor.add_constraint(AuthorWithUniqueNameAndBirthday, constraint)
        # Ensure the constraints exist
        constraints = self.get_constraints(
            AuthorWithUniqueNameAndBirthday._meta.db_table
        )
        self.assertIn(custom_constraint_name, constraints)
        other_constraints = [
            name
            for name, details in constraints.items()
            if details["columns"] == ["name", "birthday"]
            and details["unique"]
            and name != custom_constraint_name
        ]
        self.assertEqual(len(other_constraints), 1)
        # Remove unique together
        unique_together = AuthorWithUniqueNameAndBirthday._meta.unique_together
        with connection.schema_editor() as editor:
            editor.alter_unique_together(
                AuthorWithUniqueNameAndBirthday, unique_together, []
            )
        constraints = self.get_constraints(
            AuthorWithUniqueNameAndBirthday._meta.db_table
        )
        self.assertIn(custom_constraint_name, constraints)
        other_constraints = [
            name
            for name, details in constraints.items()
            if details["columns"] == ["name", "birthday"]
            and details["unique"]
            and name != custom_constraint_name
        ]
        self.assertEqual(len(other_constraints), 0)
        # Re-add unique together
        with connection.schema_editor() as editor:
            editor.alter_unique_together(
                AuthorWithUniqueNameAndBirthday, [], unique_together
            )
        constraints = self.get_constraints(
            AuthorWithUniqueNameAndBirthday._meta.db_table
        )
        self.assertIn(custom_constraint_name, constraints)
        other_constraints = [
            name
            for name, details in constraints.items()
            if details["columns"] == ["name", "birthday"]
            and details["unique"]
            and name != custom_constraint_name
        ]
        self.assertEqual(len(other_constraints), 1)
        # Drop the unique constraint
        with connection.schema_editor() as editor:
            AuthorWithUniqueNameAndBirthday._meta.constraints = []
            editor.remove_constraint(AuthorWithUniqueNameAndBirthday, constraint)

    def test_unique_constraint(self):
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        constraint = UniqueConstraint(fields=["name"], name="name_uq")
        # Add constraint.
        with connection.schema_editor() as editor:
            editor.add_constraint(Author, constraint)
            sql = constraint.create_sql(Author, editor)
        table = Author._meta.db_table
        self.assertIs(sql.references_table(table), True)
        self.assertIs(sql.references_column(table, "name"), True)
        # Remove constraint.
        with connection.schema_editor() as editor:
            editor.remove_constraint(Author, constraint)
        self.assertNotIn(constraint.name, self.get_constraints(table))

    @skipUnlessDBFeature("supports_expression_indexes")
    def test_func_unique_constraint(self):
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        constraint = UniqueConstraint(Upper("name").desc(), name="func_upper_uq")
        # Add constraint.
        with connection.schema_editor() as editor:
            editor.add_constraint(Author, constraint)
            sql = constraint.create_sql(Author, editor)
        table = Author._meta.db_table
        constraints = self.get_constraints(table)
        if connection.features.supports_index_column_ordering:
            self.assertIndexOrder(table, constraint.name, ["DESC"])
        self.assertIn(constraint.name, constraints)
        self.assertIs(constraints[constraint.name]["unique"], True)
        # SQL contains a database function.
        self.assertIs(sql.references_column(table, "name"), True)
        self.assertIn("UPPER(%s)" % editor.quote_name("name"), str(sql))
        # Remove constraint.
        with connection.schema_editor() as editor:
            editor.remove_constraint(Author, constraint)
        self.assertNotIn(constraint.name, self.get_constraints(table))

    @skipUnlessDBFeature("supports_expression_indexes")
    def test_composite_func_unique_constraint(self):
        with connection.schema_editor() as editor:
            editor.create_model(Author)
            editor.create_model(BookWithSlug)
        constraint = UniqueConstraint(
            Upper("title"),
            Lower("slug"),
            name="func_upper_lower_unq",
        )
        # Add constraint.
        with connection.schema_editor() as editor:
            editor.add_constraint(BookWithSlug, constraint)
            sql = constraint.create_sql(BookWithSlug, editor)
        table = BookWithSlug._meta.db_table
        constraints = self.get_constraints(table)
        self.assertIn(constraint.name, constraints)
        self.assertIs(constraints[constraint.name]["unique"], True)
        # SQL contains database functions.
        self.assertIs(sql.references_column(table, "title"), True)
        self.assertIs(sql.references_column(table, "slug"), True)
        sql = str(sql)
        self.assertIn("UPPER(%s)" % editor.quote_name("title"), sql)
        self.assertIn("LOWER(%s)" % editor.quote_name("slug"), sql)
        self.assertLess(sql.index("UPPER"), sql.index("LOWER"))
        # Remove constraint.
        with connection.schema_editor() as editor:
            editor.remove_constraint(BookWithSlug, constraint)
        self.assertNotIn(constraint.name, self.get_constraints(table))

    @skipUnlessDBFeature("supports_expression_indexes")
    def test_unique_constraint_field_and_expression(self):
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        constraint = UniqueConstraint(
            F("height").desc(),
            "uuid",
            Lower("name").asc(),
            name="func_f_lower_field_unq",
        )
        # Add constraint.
        with connection.schema_editor() as editor:
            editor.add_constraint(Author, constraint)
            sql = constraint.create_sql(Author, editor)
        table = Author._meta.db_table
        if connection.features.supports_index_column_ordering:
            self.assertIndexOrder(table, constraint.name, ["DESC", "ASC", "ASC"])
        constraints = self.get_constraints(table)
        self.assertIs(constraints[constraint.name]["unique"], True)
        self.assertEqual(len(constraints[constraint.name]["columns"]), 3)
        self.assertEqual(constraints[constraint.name]["columns"][1], "uuid")
        # SQL contains database functions and columns.
        self.assertIs(sql.references_column(table, "height"), True)
        self.assertIs(sql.references_column(table, "name"), True)
        self.assertIs(sql.references_column(table, "uuid"), True)
        self.assertIn("LOWER(%s)" % editor.quote_name("name"), str(sql))
        # Remove constraint.
        with connection.schema_editor() as editor:
            editor.remove_constraint(Author, constraint)
        self.assertNotIn(constraint.name, self.get_constraints(table))

    @skipUnlessDBFeature("supports_expression_indexes", "supports_partial_indexes")
    def test_func_unique_constraint_partial(self):
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        constraint = UniqueConstraint(
            Upper("name"),
            name="func_upper_cond_weight_uq",
            condition=Q(weight__isnull=False),
        )
        # Add constraint.
        with connection.schema_editor() as editor:
            editor.add_constraint(Author, constraint)
            sql = constraint.create_sql(Author, editor)
        table = Author._meta.db_table
        constraints = self.get_constraints(table)
        self.assertIn(constraint.name, constraints)
        self.assertIs(constraints[constraint.name]["unique"], True)
        self.assertIs(sql.references_column(table, "name"), True)
        self.assertIn("UPPER(%s)" % editor.quote_name("name"), str(sql))
        self.assertIn(
            "WHERE %s IS NOT NULL" % editor.quote_name("weight"),
            str(sql),
        )
        # Remove constraint.
        with connection.schema_editor() as editor:
            editor.remove_constraint(Author, constraint)
        self.assertNotIn(constraint.name, self.get_constraints(table))

    @skipUnlessDBFeature("supports_expression_indexes", "supports_covering_indexes")
    def test_func_unique_constraint_covering(self):
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        constraint = UniqueConstraint(
            Upper("name"),
            name="func_upper_covering_uq",
            include=["weight", "height"],
        )
        # Add constraint.
        with connection.schema_editor() as editor:
            editor.add_constraint(Author, constraint)
            sql = constraint.create_sql(Author, editor)
        table = Author._meta.db_table
        constraints = self.get_constraints(table)
        self.assertIn(constraint.name, constraints)
        self.assertIs(constraints[constraint.name]["unique"], True)
        self.assertEqual(
            constraints[constraint.name]["columns"],
            [None, "weight", "height"],
        )
        self.assertIs(sql.references_column(table, "name"), True)
        self.assertIs(sql.references_column(table, "weight"), True)
        self.assertIs(sql.references_column(table, "height"), True)
        self.assertIn("UPPER(%s)" % editor.quote_name("name"), str(sql))
        self.assertIn(
            "INCLUDE (%s, %s)"
            % (
                editor.quote_name("weight"),
                editor.quote_name("height"),
            ),
            str(sql),
        )
        # Remove constraint.
        with connection.schema_editor() as editor:
            editor.remove_constraint(Author, constraint)
        self.assertNotIn(constraint.name, self.get_constraints(table))

    @skipUnlessDBFeature("supports_expression_indexes")
    def test_func_unique_constraint_lookups(self):
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        with register_lookup(CharField, Lower), register_lookup(IntegerField, Abs):
            constraint = UniqueConstraint(
                F("name__lower"),
                F("weight__abs"),
                name="func_lower_abs_lookup_uq",
            )
            # Add constraint.
            with connection.schema_editor() as editor:
                editor.add_constraint(Author, constraint)
                sql = constraint.create_sql(Author, editor)
            table = Author._meta.db_table
            constraints = self.get_constraints(table)
            self.assertIn(constraint.name, constraints)
            self.assertIs(constraints[constraint.name]["unique"], True)
            # SQL contains columns.
            self.assertIs(sql.references_column(table, "name"), True)
            self.assertIs(sql.references_column(table, "weight"), True)
            # Remove constraint.
            with connection.schema_editor() as editor:
                editor.remove_constraint(Author, constraint)
        self.assertNotIn(constraint.name, self.get_constraints(table))

    @skipUnlessDBFeature("supports_expression_indexes")
    def test_func_unique_constraint_collate(self):
        collation = connection.features.test_collations.get("non_default")
        if not collation:
            self.skipTest("This backend does not support case-insensitive collations.")
        with connection.schema_editor() as editor:
            editor.create_model(Author)
            editor.create_model(BookWithSlug)
        constraint = UniqueConstraint(
            Collate(F("title"), collation=collation).desc(),
            Collate("slug", collation=collation),
            name="func_collate_uq",
        )
        # Add constraint.
        with connection.schema_editor() as editor:
            editor.add_constraint(BookWithSlug, constraint)
            sql = constraint.create_sql(BookWithSlug, editor)
        table = BookWithSlug._meta.db_table
        constraints = self.get_constraints(table)
        self.assertIn(constraint.name, constraints)
        self.assertIs(constraints[constraint.name]["unique"], True)
        if connection.features.supports_index_column_ordering:
            self.assertIndexOrder(table, constraint.name, ["DESC", "ASC"])
        # SQL contains columns and a collation.
        self.assertIs(sql.references_column(table, "title"), True)
        self.assertIs(sql.references_column(table, "slug"), True)
        self.assertIn("COLLATE %s" % editor.quote_name(collation), str(sql))
        # Remove constraint.
        with connection.schema_editor() as editor:
            editor.remove_constraint(BookWithSlug, constraint)
        self.assertNotIn(constraint.name, self.get_constraints(table))

    @skipIfDBFeature("supports_expression_indexes")
    def test_func_unique_constraint_unsupported(self):
        # UniqueConstraint is ignored on databases that don't support indexes on
        # expressions.
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        constraint = UniqueConstraint(F("name"), name="func_name_uq")
        with connection.schema_editor() as editor, self.assertNumQueries(0):
            self.assertIsNone(editor.add_constraint(Author, constraint))
            self.assertIsNone(editor.remove_constraint(Author, constraint))

    @skipUnlessDBFeature("supports_expression_indexes")
    def test_func_unique_constraint_nonexistent_field(self):
        constraint = UniqueConstraint(Lower("nonexistent"), name="func_nonexistent_uq")
        msg = (
            "Cannot resolve keyword 'nonexistent' into field. Choices are: "
            "height, id, name, uuid, weight"
        )
        with self.assertRaisesMessage(FieldError, msg):
            with connection.schema_editor() as editor:
                editor.add_constraint(Author, constraint)

    @skipUnlessDBFeature("supports_expression_indexes")
    def test_func_unique_constraint_nondeterministic(self):
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        constraint = UniqueConstraint(Random(), name="func_random_uq")
        with connection.schema_editor() as editor:
            with self.assertRaises(DatabaseError):
                editor.add_constraint(Author, constraint)

    @ignore_warnings(category=RemovedInDjango51Warning)
    def test_index_together(self):
        """
        Tests removing and adding index_together constraints on a model.
        """
        # Create the table
        with connection.schema_editor() as editor:
            editor.create_model(Tag)
        # Ensure there's no index on the year/slug columns first
        self.assertIs(
            any(
                c["index"]
                for c in self.get_constraints("schema_tag").values()
                if c["columns"] == ["slug", "title"]
            ),
            False,
        )
        # Alter the model to add an index
        with connection.schema_editor() as editor:
            editor.alter_index_together(Tag, [], [("slug", "title")])
        # Ensure there is now an index
        self.assertIs(
            any(
                c["index"]
                for c in self.get_constraints("schema_tag").values()
                if c["columns"] == ["slug", "title"]
            ),
            True,
        )
        # Alter it back
        new_field2 = SlugField(unique=True)
        new_field2.set_attributes_from_name("slug")
        with connection.schema_editor() as editor:
            editor.alter_index_together(Tag, [("slug", "title")], [])
        # Ensure there's no index
        self.assertIs(
            any(
                c["index"]
                for c in self.get_constraints("schema_tag").values()
                if c["columns"] == ["slug", "title"]
            ),
            False,
        )

    @ignore_warnings(category=RemovedInDjango51Warning)
    def test_index_together_with_fk(self):
        """
        Tests removing and adding index_together constraints that include
        a foreign key.
        """
        # Create the table
        with connection.schema_editor() as editor:
            editor.create_model(Author)
            editor.create_model(Book)
        # Ensure the fields are unique to begin with
        self.assertEqual(Book._meta.index_together, ())
        # Add the unique_together constraint
        with connection.schema_editor() as editor:
            editor.alter_index_together(Book, [], [["author", "title"]])
        # Alter it back
        with connection.schema_editor() as editor:
            editor.alter_index_together(Book, [["author", "title"]], [])

    @ignore_warnings(category=RemovedInDjango51Warning)
    @isolate_apps("schema")
    def test_create_index_together(self):
        """
        Tests creating models with index_together already defined
        """

        class TagIndexed(Model):
            title = CharField(max_length=255)
            slug = SlugField(unique=True)

            class Meta:
                app_label = "schema"
                index_together = [["slug", "title"]]

        # Create the table
        with connection.schema_editor() as editor:
            editor.create_model(TagIndexed)
        self.isolated_local_models = [TagIndexed]
        # Ensure there is an index
        self.assertIs(
            any(
                c["index"]
                for c in self.get_constraints("schema_tagindexed").values()
                if c["columns"] == ["slug", "title"]
            ),
            True,
        )

    @skipUnlessDBFeature("allows_multiple_constraints_on_same_fields")
    @ignore_warnings(category=RemovedInDjango51Warning)
    @isolate_apps("schema")
    def test_remove_index_together_does_not_remove_meta_indexes(self):
        class AuthorWithIndexedNameAndBirthday(Model):
            name = CharField(max_length=255)
            birthday = DateField()

            class Meta:
                app_label = "schema"
                index_together = [["name", "birthday"]]

        with connection.schema_editor() as editor:
            editor.create_model(AuthorWithIndexedNameAndBirthday)
        self.isolated_local_models = [AuthorWithIndexedNameAndBirthday]
        # Add the custom index
        index = Index(fields=["name", "birthday"], name="author_name_birthday_idx")
        custom_index_name = index.name
        AuthorWithIndexedNameAndBirthday._meta.indexes = [index]
        with connection.schema_editor() as editor:
            editor.add_index(AuthorWithIndexedNameAndBirthday, index)
        # Ensure the indexes exist
        constraints = self.get_constraints(
            AuthorWithIndexedNameAndBirthday._meta.db_table
        )
        self.assertIn(custom_index_name, constraints)
        other_constraints = [
            name
            for name, details in constraints.items()
            if details["columns"] == ["name", "birthday"]
            and details["index"]
            and name != custom_index_name
        ]
        self.assertEqual(len(other_constraints), 1)
        # Remove index together
        index_together = AuthorWithIndexedNameAndBirthday._meta.index_together
        with connection.schema_editor() as editor:
            editor.alter_index_together(
                AuthorWithIndexedNameAndBirthday, index_together, []
            )
        constraints = self.get_constraints(
            AuthorWithIndexedNameAndBirthday._meta.db_table
        )
        self.assertIn(custom_index_name, constraints)
        other_constraints = [
            name
            for name, details in constraints.items()
            if details["columns"] == ["name", "birthday"]
            and details["index"]
            and name != custom_index_name
        ]
        self.assertEqual(len(other_constraints), 0)
        # Re-add index together
        with connection.schema_editor() as editor:
            editor.alter_index_together(
                AuthorWithIndexedNameAndBirthday, [], index_together
            )
        constraints = self.get_constraints(
            AuthorWithIndexedNameAndBirthday._meta.db_table
        )
        self.assertIn(custom_index_name, constraints)
        other_constraints = [
            name
            for name, details in constraints.items()
            if details["columns"] == ["name", "birthday"]
            and details["index"]
            and name != custom_index_name
        ]
        self.assertEqual(len(other_constraints), 1)
        # Drop the index
        with connection.schema_editor() as editor:
            AuthorWithIndexedNameAndBirthday._meta.indexes = []
            editor.remove_index(AuthorWithIndexedNameAndBirthday, index)

    @isolate_apps("schema")
    def test_db_table(self):
        """
        Tests renaming of the table
        """

        class Author(Model):
            name = CharField(max_length=255)

            class Meta:
                app_label = "schema"

        class Book(Model):
            author = ForeignKey(Author, CASCADE)

            class Meta:
                app_label = "schema"

        # Create the table and one referring it.
        with connection.schema_editor() as editor:
            editor.create_model(Author)
            editor.create_model(Book)
        # Ensure the table is there to begin with
        columns = self.column_classes(Author)
        self.assertEqual(
            columns["name"][0],
            connection.features.introspected_field_types["CharField"],
        )
        # Alter the table
        with connection.schema_editor(
            atomic=connection.features.supports_atomic_references_rename
        ) as editor:
            editor.alter_db_table(Author, "schema_author", "schema_otherauthor")
        Author._meta.db_table = "schema_otherauthor"
        columns = self.column_classes(Author)
        self.assertEqual(
            columns["name"][0],
            connection.features.introspected_field_types["CharField"],
        )
        # Ensure the foreign key reference was updated
        self.assertForeignKeyExists(Book, "author_id", "schema_otherauthor")
        # Alter the table again
        with connection.schema_editor(
            atomic=connection.features.supports_atomic_references_rename
        ) as editor:
            editor.alter_db_table(Author, "schema_otherauthor", "schema_author")
        # Ensure the table is still there
        Author._meta.db_table = "schema_author"
        columns = self.column_classes(Author)
        self.assertEqual(
            columns["name"][0],
            connection.features.introspected_field_types["CharField"],
        )

    def test_add_remove_index(self):
        """
        Tests index addition and removal
        """
        # Create the table
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        # Ensure the table is there and has no index
        self.assertNotIn("title", self.get_indexes(Author._meta.db_table))
        # Add the index
        index = Index(fields=["name"], name="author_title_idx")
        with connection.schema_editor() as editor:
            editor.add_index(Author, index)
        self.assertIn("name", self.get_indexes(Author._meta.db_table))
        # Drop the index
        with connection.schema_editor() as editor:
            editor.remove_index(Author, index)
        self.assertNotIn("name", self.get_indexes(Author._meta.db_table))

    def test_remove_db_index_doesnt_remove_custom_indexes(self):
        """
        Changing db_index to False doesn't remove indexes from Meta.indexes.
        """
        with connection.schema_editor() as editor:
            editor.create_model(AuthorWithIndexedName)
        self.local_models = [AuthorWithIndexedName]
        # Ensure the table has its index
        self.assertIn("name", self.get_indexes(AuthorWithIndexedName._meta.db_table))

        # Add the custom index
        index = Index(fields=["-name"], name="author_name_idx")
        author_index_name = index.name
        with connection.schema_editor() as editor:
            db_index_name = editor._create_index_name(
                table_name=AuthorWithIndexedName._meta.db_table,
                column_names=("name",),
            )
        try:
            AuthorWithIndexedName._meta.indexes = [index]
            with connection.schema_editor() as editor:
                editor.add_index(AuthorWithIndexedName, index)
            old_constraints = self.get_constraints(AuthorWithIndexedName._meta.db_table)
            self.assertIn(author_index_name, old_constraints)
            self.assertIn(db_index_name, old_constraints)
            # Change name field to db_index=False
            old_field = AuthorWithIndexedName._meta.get_field("name")
            new_field = CharField(max_length=255)
            new_field.set_attributes_from_name("name")
            with connection.schema_editor() as editor:
                editor.alter_field(
                    AuthorWithIndexedName, old_field, new_field, strict=True
                )
            new_constraints = self.get_constraints(AuthorWithIndexedName._meta.db_table)
            self.assertNotIn(db_index_name, new_constraints)
            # The index from Meta.indexes is still in the database.
            self.assertIn(author_index_name, new_constraints)
            # Drop the index
            with connection.schema_editor() as editor:
                editor.remove_index(AuthorWithIndexedName, index)
        finally:
            AuthorWithIndexedName._meta.indexes = []

    def test_order_index(self):
        """
        Indexes defined with ordering (ASC/DESC) defined on column
        """
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        # The table doesn't have an index
        self.assertNotIn("title", self.get_indexes(Author._meta.db_table))
        index_name = "author_name_idx"
        # Add the index
        index = Index(fields=["name", "-weight"], name=index_name)
        with connection.schema_editor() as editor:
            editor.add_index(Author, index)
        if connection.features.supports_index_column_ordering:
            self.assertIndexOrder(Author._meta.db_table, index_name, ["ASC", "DESC"])
        # Drop the index
        with connection.schema_editor() as editor:
            editor.remove_index(Author, index)

    def test_indexes(self):
        """
        Tests creation/altering of indexes
        """
        # Create the table
        with connection.schema_editor() as editor:
            editor.create_model(Author)
            editor.create_model(Book)
        # Ensure the table is there and has the right index
        self.assertIn(
            "title",
            self.get_indexes(Book._meta.db_table),
        )
        # Alter to remove the index
        old_field = Book._meta.get_field("title")
        new_field = CharField(max_length=100, db_index=False)
        new_field.set_attributes_from_name("title")
        with connection.schema_editor() as editor:
            editor.alter_field(Book, old_field, new_field, strict=True)
        # Ensure the table is there and has no index
        self.assertNotIn(
            "title",
            self.get_indexes(Book._meta.db_table),
        )
        # Alter to re-add the index
        new_field2 = Book._meta.get_field("title")
        with connection.schema_editor() as editor:
            editor.alter_field(Book, new_field, new_field2, strict=True)
        # Ensure the table is there and has the index again
        self.assertIn(
            "title",
            self.get_indexes(Book._meta.db_table),
        )
        # Add a unique column, verify that creates an implicit index
        new_field3 = BookWithSlug._meta.get_field("slug")
        with connection.schema_editor() as editor:
            editor.add_field(Book, new_field3)
        self.assertIn(
            "slug",
            self.get_uniques(Book._meta.db_table),
        )
        # Remove the unique, check the index goes with it
        new_field4 = CharField(max_length=20, unique=False)
        new_field4.set_attributes_from_name("slug")
        with connection.schema_editor() as editor:
            editor.alter_field(BookWithSlug, new_field3, new_field4, strict=True)
        self.assertNotIn(
            "slug",
            self.get_uniques(Book._meta.db_table),
        )

    def test_text_field_with_db_index(self):
        with connection.schema_editor() as editor:
            editor.create_model(AuthorTextFieldWithIndex)
        # The text_field index is present if the database supports it.
        assertion = (
            self.assertIn
            if connection.features.supports_index_on_text_field
            else self.assertNotIn
        )
        assertion(
            "text_field", self.get_indexes(AuthorTextFieldWithIndex._meta.db_table)
        )

    def _index_expressions_wrappers(self):
        index_expression = IndexExpression()
        index_expression.set_wrapper_classes(connection)
        return ", ".join(
            [
                wrapper_cls.__qualname__
                for wrapper_cls in index_expression.wrapper_classes
            ]
        )

    @skipUnlessDBFeature("supports_expression_indexes")
    def test_func_index_multiple_wrapper_references(self):
        index = Index(OrderBy(F("name").desc(), descending=True), name="name")
        msg = (
            "Multiple references to %s can't be used in an indexed expression."
            % self._index_expressions_wrappers()
        )
        with connection.schema_editor() as editor:
            with self.assertRaisesMessage(ValueError, msg):
                editor.add_index(Author, index)

    @skipUnlessDBFeature("supports_expression_indexes")
    def test_func_index_invalid_topmost_expressions(self):
        index = Index(Upper(F("name").desc()), name="name")
        msg = (
            "%s must be topmost expressions in an indexed expression."
            % self._index_expressions_wrappers()
        )
        with connection.schema_editor() as editor:
            with self.assertRaisesMessage(ValueError, msg):
                editor.add_index(Author, index)

    @skipUnlessDBFeature("supports_expression_indexes")
    def test_func_index(self):
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        index = Index(Lower("name").desc(), name="func_lower_idx")
        # Add index.
        with connection.schema_editor() as editor:
            editor.add_index(Author, index)
            sql = index.create_sql(Author, editor)
        table = Author._meta.db_table
        if connection.features.supports_index_column_ordering:
            self.assertIndexOrder(table, index.name, ["DESC"])
        # SQL contains a database function.
        self.assertIs(sql.references_column(table, "name"), True)
        self.assertIn("LOWER(%s)" % editor.quote_name("name"), str(sql))
        # Remove index.
        with connection.schema_editor() as editor:
            editor.remove_index(Author, index)
        self.assertNotIn(index.name, self.get_constraints(table))

    @skipUnlessDBFeature("supports_expression_indexes")
    def test_func_index_f(self):
        with connection.schema_editor() as editor:
            editor.create_model(Tag)
        index = Index("slug", F("title").desc(), name="func_f_idx")
        # Add index.
        with connection.schema_editor() as editor:
            editor.add_index(Tag, index)
            sql = index.create_sql(Tag, editor)
        table = Tag._meta.db_table
        self.assertIn(index.name, self.get_constraints(table))
        if connection.features.supports_index_column_ordering:
            self.assertIndexOrder(Tag._meta.db_table, index.name, ["ASC", "DESC"])
        # SQL contains columns.
        self.assertIs(sql.references_column(table, "slug"), True)
        self.assertIs(sql.references_column(table, "title"), True)
        # Remove index.
        with connection.schema_editor() as editor:
            editor.remove_index(Tag, index)
        self.assertNotIn(index.name, self.get_constraints(table))

    @skipUnlessDBFeature("supports_expression_indexes")
    def test_func_index_lookups(self):
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        with register_lookup(CharField, Lower), register_lookup(IntegerField, Abs):
            index = Index(
                F("name__lower"),
                F("weight__abs"),
                name="func_lower_abs_lookup_idx",
            )
            # Add index.
            with connection.schema_editor() as editor:
                editor.add_index(Author, index)
                sql = index.create_sql(Author, editor)
        table = Author._meta.db_table
        self.assertIn(index.name, self.get_constraints(table))
        # SQL contains columns.
        self.assertIs(sql.references_column(table, "name"), True)
        self.assertIs(sql.references_column(table, "weight"), True)
        # Remove index.
        with connection.schema_editor() as editor:
            editor.remove_index(Author, index)
        self.assertNotIn(index.name, self.get_constraints(table))

    @skipUnlessDBFeature("supports_expression_indexes")
    def test_composite_func_index(self):
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        index = Index(Lower("name"), Upper("name"), name="func_lower_upper_idx")
        # Add index.
        with connection.schema_editor() as editor:
            editor.add_index(Author, index)
            sql = index.create_sql(Author, editor)
        table = Author._meta.db_table
        self.assertIn(index.name, self.get_constraints(table))
        # SQL contains database functions.
        self.assertIs(sql.references_column(table, "name"), True)
        sql = str(sql)
        self.assertIn("LOWER(%s)" % editor.quote_name("name"), sql)
        self.assertIn("UPPER(%s)" % editor.quote_name("name"), sql)
        self.assertLess(sql.index("LOWER"), sql.index("UPPER"))
        # Remove index.
        with connection.schema_editor() as editor:
            editor.remove_index(Author, index)
        self.assertNotIn(index.name, self.get_constraints(table))

    @skipUnlessDBFeature("supports_expression_indexes")
    def test_composite_func_index_field_and_expression(self):
        with connection.schema_editor() as editor:
            editor.create_model(Author)
            editor.create_model(Book)
        index = Index(
            F("author").desc(),
            Lower("title").asc(),
            "pub_date",
            name="func_f_lower_field_idx",
        )
        # Add index.
        with connection.schema_editor() as editor:
            editor.add_index(Book, index)
            sql = index.create_sql(Book, editor)
        table = Book._meta.db_table
        constraints = self.get_constraints(table)
        if connection.features.supports_index_column_ordering:
            self.assertIndexOrder(table, index.name, ["DESC", "ASC", "ASC"])
        self.assertEqual(len(constraints[index.name]["columns"]), 3)
        self.assertEqual(constraints[index.name]["columns"][2], "pub_date")
        # SQL contains database functions and columns.
        self.assertIs(sql.references_column(table, "author_id"), True)
        self.assertIs(sql.references_column(table, "title"), True)
        self.assertIs(sql.references_column(table, "pub_date"), True)
        self.assertIn("LOWER(%s)" % editor.quote_name("title"), str(sql))
        # Remove index.
        with connection.schema_editor() as editor:
            editor.remove_index(Book, index)
        self.assertNotIn(index.name, self.get_constraints(table))

    @skipUnlessDBFeature("supports_expression_indexes")
    @isolate_apps("schema")
    def test_func_index_f_decimalfield(self):
        class Node(Model):
            value = DecimalField(max_digits=5, decimal_places=2)

            class Meta:
                app_label = "schema"

        with connection.schema_editor() as editor:
            editor.create_model(Node)
        index = Index(F("value"), name="func_f_decimalfield_idx")
        # Add index.
        with connection.schema_editor() as editor:
            editor.add_index(Node, index)
            sql = index.create_sql(Node, editor)
        table = Node._meta.db_table
        self.assertIn(index.name, self.get_constraints(table))
        self.assertIs(sql.references_column(table, "value"), True)
        # SQL doesn't contain casting.
        self.assertNotIn("CAST", str(sql))
        # Remove index.
        with connection.schema_editor() as editor:
            editor.remove_index(Node, index)
        self.assertNotIn(index.name, self.get_constraints(table))

    @skipUnlessDBFeature("supports_expression_indexes")
    def test_func_index_cast(self):
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        index = Index(Cast("weight", FloatField()), name="func_cast_idx")
        # Add index.
        with connection.schema_editor() as editor:
            editor.add_index(Author, index)
            sql = index.create_sql(Author, editor)
        table = Author._meta.db_table
        self.assertIn(index.name, self.get_constraints(table))
        self.assertIs(sql.references_column(table, "weight"), True)
        # Remove index.
        with connection.schema_editor() as editor:
            editor.remove_index(Author, index)
        self.assertNotIn(index.name, self.get_constraints(table))

    @skipUnlessDBFeature("supports_expression_indexes")
    def test_func_index_collate(self):
        collation = connection.features.test_collations.get("non_default")
        if not collation:
            self.skipTest("This backend does not support case-insensitive collations.")
        with connection.schema_editor() as editor:
            editor.create_model(Author)
            editor.create_model(BookWithSlug)
        index = Index(
            Collate(F("title"), collation=collation).desc(),
            Collate("slug", collation=collation),
            name="func_collate_idx",
        )
        # Add index.
        with connection.schema_editor() as editor:
            editor.add_index(BookWithSlug, index)
            sql = index.create_sql(BookWithSlug, editor)
        table = Book._meta.db_table
        self.assertIn(index.name, self.get_constraints(table))
        if connection.features.supports_index_column_ordering:
            self.assertIndexOrder(table, index.name, ["DESC", "ASC"])
        # SQL contains columns and a collation.
        self.assertIs(sql.references_column(table, "title"), True)
        self.assertIs(sql.references_column(table, "slug"), True)
        self.assertIn("COLLATE %s" % editor.quote_name(collation), str(sql))
        # Remove index.
        with connection.schema_editor() as editor:
            editor.remove_index(Book, index)
        self.assertNotIn(index.name, self.get_constraints(table))

    @skipUnlessDBFeature("supports_expression_indexes")
    @skipIfDBFeature("collate_as_index_expression")
    def test_func_index_collate_f_ordered(self):
        collation = connection.features.test_collations.get("non_default")
        if not collation:
            self.skipTest("This backend does not support case-insensitive collations.")
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        index = Index(
            Collate(F("name").desc(), collation=collation),
            name="func_collate_f_desc_idx",
        )
        # Add index.
        with connection.schema_editor() as editor:
            editor.add_index(Author, index)
            sql = index.create_sql(Author, editor)
        table = Author._meta.db_table
        self.assertIn(index.name, self.get_constraints(table))
        if connection.features.supports_index_column_ordering:
            self.assertIndexOrder(table, index.name, ["DESC"])
        # SQL contains columns and a collation.
        self.assertIs(sql.references_column(table, "name"), True)
        self.assertIn("COLLATE %s" % editor.quote_name(collation), str(sql))
        # Remove index.
        with connection.schema_editor() as editor:
            editor.remove_index(Author, index)
        self.assertNotIn(index.name, self.get_constraints(table))

    @skipUnlessDBFeature("supports_expression_indexes")
    def test_func_index_calc(self):
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        index = Index(F("height") / (F("weight") + Value(5)), name="func_calc_idx")
        # Add index.
        with connection.schema_editor() as editor:
            editor.add_index(Author, index)
            sql = index.create_sql(Author, editor)
        table = Author._meta.db_table
        self.assertIn(index.name, self.get_constraints(table))
        # SQL contains columns and expressions.
        self.assertIs(sql.references_column(table, "height"), True)
        self.assertIs(sql.references_column(table, "weight"), True)
        sql = str(sql)
        self.assertIs(
            sql.index(editor.quote_name("height"))
            < sql.index("/")
            < sql.index(editor.quote_name("weight"))
            < sql.index("+")
            < sql.index("5"),
            True,
        )
        # Remove index.
        with connection.schema_editor() as editor:
            editor.remove_index(Author, index)
        self.assertNotIn(index.name, self.get_constraints(table))

    @skipUnlessDBFeature("supports_expression_indexes", "supports_json_field")
    @isolate_apps("schema")
    def test_func_index_json_key_transform(self):
        class JSONModel(Model):
            field = JSONField()

            class Meta:
                app_label = "schema"

        with connection.schema_editor() as editor:
            editor.create_model(JSONModel)
        self.isolated_local_models = [JSONModel]
        index = Index("field__some_key", name="func_json_key_idx")
        with connection.schema_editor() as editor:
            editor.add_index(JSONModel, index)
            sql = index.create_sql(JSONModel, editor)
        table = JSONModel._meta.db_table
        self.assertIn(index.name, self.get_constraints(table))
        self.assertIs(sql.references_column(table, "field"), True)
        with connection.schema_editor() as editor:
            editor.remove_index(JSONModel, index)
        self.assertNotIn(index.name, self.get_constraints(table))

    @skipUnlessDBFeature("supports_expression_indexes", "supports_json_field")
    @isolate_apps("schema")
    def test_func_index_json_key_transform_cast(self):
        class JSONModel(Model):
            field = JSONField()

            class Meta:
                app_label = "schema"

        with connection.schema_editor() as editor:
            editor.create_model(JSONModel)
        self.isolated_local_models = [JSONModel]
        index = Index(
            Cast(KeyTextTransform("some_key", "field"), IntegerField()),
            name="func_json_key_cast_idx",
        )
        with connection.schema_editor() as editor:
            editor.add_index(JSONModel, index)
            sql = index.create_sql(JSONModel, editor)
        table = JSONModel._meta.db_table
        self.assertIn(index.name, self.get_constraints(table))
        self.assertIs(sql.references_column(table, "field"), True)
        with connection.schema_editor() as editor:
            editor.remove_index(JSONModel, index)
        self.assertNotIn(index.name, self.get_constraints(table))

    @skipIfDBFeature("supports_expression_indexes")
    def test_func_index_unsupported(self):
        # Index is ignored on databases that don't support indexes on
        # expressions.
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        index = Index(F("name"), name="random_idx")
        with connection.schema_editor() as editor, self.assertNumQueries(0):
            self.assertIsNone(editor.add_index(Author, index))
            self.assertIsNone(editor.remove_index(Author, index))

    @skipUnlessDBFeature("supports_expression_indexes")
    def test_func_index_nonexistent_field(self):
        index = Index(Lower("nonexistent"), name="func_nonexistent_idx")
        msg = (
            "Cannot resolve keyword 'nonexistent' into field. Choices are: "
            "height, id, name, uuid, weight"
        )
        with self.assertRaisesMessage(FieldError, msg):
            with connection.schema_editor() as editor:
                editor.add_index(Author, index)

    @skipUnlessDBFeature("supports_expression_indexes")
    def test_func_index_nondeterministic(self):
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        index = Index(Random(), name="func_random_idx")
        with connection.schema_editor() as editor:
            with self.assertRaises(DatabaseError):
                editor.add_index(Author, index)

    def test_primary_key(self):
        """
        Tests altering of the primary key
        """
        # Create the table
        with connection.schema_editor() as editor:
            editor.create_model(Tag)
        # Ensure the table is there and has the right PK
        self.assertEqual(self.get_primary_key(Tag._meta.db_table), "id")
        # Alter to change the PK
        id_field = Tag._meta.get_field("id")
        old_field = Tag._meta.get_field("slug")
        new_field = SlugField(primary_key=True)
        new_field.set_attributes_from_name("slug")
        new_field.model = Tag
        with connection.schema_editor() as editor:
            editor.remove_field(Tag, id_field)
            editor.alter_field(Tag, old_field, new_field)
        # Ensure the PK changed
        self.assertNotIn(
            "id",
            self.get_indexes(Tag._meta.db_table),
        )
        self.assertEqual(self.get_primary_key(Tag._meta.db_table), "slug")

    def test_alter_primary_key_the_same_name(self):
        with connection.schema_editor() as editor:
            editor.create_model(Thing)

        old_field = Thing._meta.get_field("when")
        new_field = CharField(max_length=2, primary_key=True)
        new_field.set_attributes_from_name("when")
        new_field.model = Thing
        with connection.schema_editor() as editor:
            editor.alter_field(Thing, old_field, new_field, strict=True)
        self.assertEqual(self.get_primary_key(Thing._meta.db_table), "when")
        with connection.schema_editor() as editor:
            editor.alter_field(Thing, new_field, old_field, strict=True)
        self.assertEqual(self.get_primary_key(Thing._meta.db_table), "when")

    def test_context_manager_exit(self):
        """
        Ensures transaction is correctly closed when an error occurs
        inside a SchemaEditor context.
        """

        class SomeError(Exception):
            pass

        try:
            with connection.schema_editor():
                raise SomeError
        except SomeError:
            self.assertFalse(connection.in_atomic_block)

    @skipIfDBFeature("can_rollback_ddl")
    def test_unsupported_transactional_ddl_disallowed(self):
        message = (
            "Executing DDL statements while in a transaction on databases "
            "that can't perform a rollback is prohibited."
        )
        with atomic(), connection.schema_editor() as editor:
            with self.assertRaisesMessage(TransactionManagementError, message):
                editor.execute(
                    editor.sql_create_table % {"table": "foo", "definition": ""}
                )

    @skipUnlessDBFeature("supports_foreign_keys", "indexes_foreign_keys")
    def test_foreign_key_index_long_names_regression(self):
        """
        Regression test for #21497.
        Only affects databases that supports foreign keys.
        """
        # Create the table
        with connection.schema_editor() as editor:
            editor.create_model(AuthorWithEvenLongerName)
            editor.create_model(BookWithLongName)
        # Find the properly shortened column name
        column_name = connection.ops.quote_name(
            "author_foreign_key_with_really_long_field_name_id"
        )
        column_name = column_name[1:-1].lower()  # unquote, and, for Oracle, un-upcase
        # Ensure the table is there and has an index on the column
        self.assertIn(
            column_name,
            self.get_indexes(BookWithLongName._meta.db_table),
        )

    @skipUnlessDBFeature("supports_foreign_keys")
    def test_add_foreign_key_long_names(self):
        """
        Regression test for #23009.
        Only affects databases that supports foreign keys.
        """
        # Create the initial tables
        with connection.schema_editor() as editor:
            editor.create_model(AuthorWithEvenLongerName)
            editor.create_model(BookWithLongName)
        # Add a second FK, this would fail due to long ref name before the fix
        new_field = ForeignKey(
            AuthorWithEvenLongerName, CASCADE, related_name="something"
        )
        new_field.set_attributes_from_name(
            "author_other_really_long_named_i_mean_so_long_fk"
        )
        with connection.schema_editor() as editor:
            editor.add_field(BookWithLongName, new_field)

    @isolate_apps("schema")
    @skipUnlessDBFeature("supports_foreign_keys")
    def test_add_foreign_key_quoted_db_table(self):
        class Author(Model):
            class Meta:
                db_table = '"table_author_double_quoted"'
                app_label = "schema"

        class Book(Model):
            author = ForeignKey(Author, CASCADE)

            class Meta:
                app_label = "schema"

        with connection.schema_editor() as editor:
            editor.create_model(Author)
            editor.create_model(Book)
        self.isolated_local_models = [Author]
        if connection.vendor == "mysql":
            self.assertForeignKeyExists(
                Book, "author_id", '"table_author_double_quoted"'
            )
        else:
            self.assertForeignKeyExists(Book, "author_id", "table_author_double_quoted")

    def test_add_foreign_object(self):
        with connection.schema_editor() as editor:
            editor.create_model(BookForeignObj)
        self.local_models = [BookForeignObj]

        new_field = ForeignObject(
            Author, on_delete=CASCADE, from_fields=["author_id"], to_fields=["id"]
        )
        new_field.set_attributes_from_name("author")
        with connection.schema_editor() as editor:
            editor.add_field(BookForeignObj, new_field)

    def test_creation_deletion_reserved_names(self):
        """
        Tries creating a model's table, and then deleting it when it has a
        SQL reserved name.
        """
        # Create the table
        with connection.schema_editor() as editor:
            try:
                editor.create_model(Thing)
            except OperationalError as e:
                self.fail(
                    "Errors when applying initial migration for a model "
                    "with a table named after an SQL reserved word: %s" % e
                )
        # The table is there
        list(Thing.objects.all())
        # Clean up that table
        with connection.schema_editor() as editor:
            editor.delete_model(Thing)
        # The table is gone
        with self.assertRaises(DatabaseError):
            list(Thing.objects.all())

    def test_remove_constraints_capital_letters(self):
        """
        #23065 - Constraint names must be quoted if they contain capital letters.
        """

        def get_field(*args, field_class=IntegerField, **kwargs):
            kwargs["db_column"] = "CamelCase"
            field = field_class(*args, **kwargs)
            field.set_attributes_from_name("CamelCase")
            return field

        model = Author
        field = get_field()
        table = model._meta.db_table
        column = field.column
        identifier_converter = connection.introspection.identifier_converter

        with connection.schema_editor() as editor:
            editor.create_model(model)
            editor.add_field(model, field)

            constraint_name = "CamelCaseIndex"
            expected_constraint_name = identifier_converter(constraint_name)
            editor.execute(
                editor.sql_create_index
                % {
                    "table": editor.quote_name(table),
                    "name": editor.quote_name(constraint_name),
                    "using": "",
                    "columns": editor.quote_name(column),
                    "extra": "",
                    "condition": "",
                    "include": "",
                }
            )
            self.assertIn(
                expected_constraint_name, self.get_constraints(model._meta.db_table)
            )
            editor.alter_field(model, get_field(db_index=True), field, strict=True)
            self.assertNotIn(
                expected_constraint_name, self.get_constraints(model._meta.db_table)
            )

            constraint_name = "CamelCaseUniqConstraint"
            expected_constraint_name = identifier_converter(constraint_name)
            editor.execute(editor._create_unique_sql(model, [field], constraint_name))
            self.assertIn(
                expected_constraint_name, self.get_constraints(model._meta.db_table)
            )
            editor.alter_field(model, get_field(unique=True), field, strict=True)
            self.assertNotIn(
                expected_constraint_name, self.get_constraints(model._meta.db_table)
            )

            if editor.sql_create_fk and connection.features.can_introspect_foreign_keys:
                constraint_name = "CamelCaseFKConstraint"
                expected_constraint_name = identifier_converter(constraint_name)
                editor.execute(
                    editor.sql_create_fk
                    % {
                        "table": editor.quote_name(table),
                        "name": editor.quote_name(constraint_name),
                        "column": editor.quote_name(column),
                        "to_table": editor.quote_name(table),
                        "to_column": editor.quote_name(model._meta.auto_field.column),
                        "deferrable": connection.ops.deferrable_sql(),
                    }
                )
                self.assertIn(
                    expected_constraint_name, self.get_constraints(model._meta.db_table)
                )
                editor.alter_field(
                    model,
                    get_field(Author, CASCADE, field_class=ForeignKey),
                    field,
                    strict=True,
                )
                self.assertNotIn(
                    expected_constraint_name, self.get_constraints(model._meta.db_table)
                )

    def test_add_field_use_effective_default(self):
        """
        #23987 - effective_default() should be used as the field default when
        adding a new field.
        """
        # Create the table
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        # Ensure there's no surname field
        columns = self.column_classes(Author)
        self.assertNotIn("surname", columns)
        # Create a row
        Author.objects.create(name="Anonymous1")
        # Add new CharField to ensure default will be used from effective_default
        new_field = CharField(max_length=15, blank=True)
        new_field.set_attributes_from_name("surname")
        with connection.schema_editor() as editor:
            editor.add_field(Author, new_field)
        # Ensure field was added with the right default
        with connection.cursor() as cursor:
            cursor.execute("SELECT surname FROM schema_author;")
            item = cursor.fetchall()[0]
            self.assertEqual(
                item[0],
                None if connection.features.interprets_empty_strings_as_nulls else "",
            )

    def test_add_field_default_dropped(self):
        # Create the table
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        # Ensure there's no surname field
        columns = self.column_classes(Author)
        self.assertNotIn("surname", columns)
        # Create a row
        Author.objects.create(name="Anonymous1")
        # Add new CharField with a default
        new_field = CharField(max_length=15, blank=True, default="surname default")
        new_field.set_attributes_from_name("surname")
        with connection.schema_editor() as editor:
            editor.add_field(Author, new_field)
        # Ensure field was added with the right default
        with connection.cursor() as cursor:
            cursor.execute("SELECT surname FROM schema_author;")
            item = cursor.fetchall()[0]
            self.assertEqual(item[0], "surname default")
            # And that the default is no longer set in the database.
            field = next(
                f
                for f in connection.introspection.get_table_description(
                    cursor, "schema_author"
                )
                if f.name == "surname"
            )
            if connection.features.can_introspect_default:
                self.assertIsNone(field.default)

    def test_add_field_default_nullable(self):
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        # Add new nullable CharField with a default.
        new_field = CharField(max_length=15, blank=True, null=True, default="surname")
        new_field.set_attributes_from_name("surname")
        with connection.schema_editor() as editor:
            editor.add_field(Author, new_field)
        Author.objects.create(name="Anonymous1")
        with connection.cursor() as cursor:
            cursor.execute("SELECT surname FROM schema_author;")
            item = cursor.fetchall()[0]
            self.assertIsNone(item[0])
            field = next(
                f
                for f in connection.introspection.get_table_description(
                    cursor,
                    "schema_author",
                )
                if f.name == "surname"
            )
            # Field is still nullable.
            self.assertTrue(field.null_ok)
            # The database default is no longer set.
            if connection.features.can_introspect_default:
                self.assertIn(field.default, ["NULL", None])

    def test_add_textfield_default_nullable(self):
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        # Add new nullable TextField with a default.
        new_field = TextField(blank=True, null=True, default="text")
        new_field.set_attributes_from_name("description")
        with connection.schema_editor() as editor:
            editor.add_field(Author, new_field)
        Author.objects.create(name="Anonymous1")
        with connection.cursor() as cursor:
            cursor.execute("SELECT description FROM schema_author;")
            item = cursor.fetchall()[0]
            self.assertIsNone(item[0])
            field = next(
                f
                for f in connection.introspection.get_table_description(
                    cursor,
                    "schema_author",
                )
                if f.name == "description"
            )
            # Field is still nullable.
            self.assertTrue(field.null_ok)
            # The database default is no longer set.
            if connection.features.can_introspect_default:
                self.assertIn(field.default, ["NULL", None])

    def test_alter_field_default_dropped(self):
        # Create the table
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        # Create a row
        Author.objects.create(name="Anonymous1")
        self.assertIsNone(Author.objects.get().height)
        old_field = Author._meta.get_field("height")
        # The default from the new field is used in updating existing rows.
        new_field = IntegerField(blank=True, default=42)
        new_field.set_attributes_from_name("height")
        with connection.schema_editor() as editor:
            editor.alter_field(Author, old_field, new_field, strict=True)
        self.assertEqual(Author.objects.get().height, 42)
        # The database default should be removed.
        with connection.cursor() as cursor:
            field = next(
                f
                for f in connection.introspection.get_table_description(
                    cursor, "schema_author"
                )
                if f.name == "height"
            )
            if connection.features.can_introspect_default:
                self.assertIsNone(field.default)

    def test_alter_field_default_doesnt_perform_queries(self):
        """
        No queries are performed if a field default changes and the field's
        not changing from null to non-null.
        """
        with connection.schema_editor() as editor:
            editor.create_model(AuthorWithDefaultHeight)
        old_field = AuthorWithDefaultHeight._meta.get_field("height")
        new_default = old_field.default * 2
        new_field = PositiveIntegerField(null=True, blank=True, default=new_default)
        new_field.set_attributes_from_name("height")
        with connection.schema_editor() as editor, self.assertNumQueries(0):
            editor.alter_field(
                AuthorWithDefaultHeight, old_field, new_field, strict=True
            )

    @skipUnlessDBFeature("supports_foreign_keys")
    def test_alter_field_fk_attributes_noop(self):
        """
        No queries are performed when changing field attributes that don't
        affect the schema.
        """
        with connection.schema_editor() as editor:
            editor.create_model(Author)
            editor.create_model(Book)
        old_field = Book._meta.get_field("author")
        new_field = ForeignKey(
            Author,
            blank=True,
            editable=False,
            error_messages={"invalid": "error message"},
            help_text="help text",
            limit_choices_to={"limit": "choice"},
            on_delete=PROTECT,
            related_name="related_name",
            related_query_name="related_query_name",
            validators=[lambda x: x],
            verbose_name="verbose name",
        )
        new_field.set_attributes_from_name("author")
        with connection.schema_editor() as editor, self.assertNumQueries(0):
            editor.alter_field(Book, old_field, new_field, strict=True)
        with connection.schema_editor() as editor, self.assertNumQueries(0):
            editor.alter_field(Book, new_field, old_field, strict=True)

    def test_alter_field_choices_noop(self):
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        old_field = Author._meta.get_field("name")
        new_field = CharField(
            choices=(("Jane", "Jane"), ("Joe", "Joe")),
            max_length=255,
        )
        new_field.set_attributes_from_name("name")
        with connection.schema_editor() as editor, self.assertNumQueries(0):
            editor.alter_field(Author, old_field, new_field, strict=True)
        with connection.schema_editor() as editor, self.assertNumQueries(0):
            editor.alter_field(Author, new_field, old_field, strict=True)

    def test_add_textfield_unhashable_default(self):
        # Create the table
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        # Create a row
        Author.objects.create(name="Anonymous1")
        # Create a field that has an unhashable default
        new_field = TextField(default={})
        new_field.set_attributes_from_name("info")
        with connection.schema_editor() as editor:
            editor.add_field(Author, new_field)

    @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific")
    def test_add_indexed_charfield(self):
        field = CharField(max_length=255, db_index=True)
        field.set_attributes_from_name("nom_de_plume")
        with connection.schema_editor() as editor:
            editor.create_model(Author)
            editor.add_field(Author, field)
        # Should create two indexes; one for like operator.
        self.assertEqual(
            self.get_constraints_for_column(Author, "nom_de_plume"),
            [
                "schema_author_nom_de_plume_7570a851",
                "schema_author_nom_de_plume_7570a851_like",
            ],
        )

    @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific")
    def test_add_unique_charfield(self):
        field = CharField(max_length=255, unique=True)
        field.set_attributes_from_name("nom_de_plume")
        with connection.schema_editor() as editor:
            editor.create_model(Author)
            editor.add_field(Author, field)
        # Should create two indexes; one for like operator.
        self.assertEqual(
            self.get_constraints_for_column(Author, "nom_de_plume"),
            [
                "schema_author_nom_de_plume_7570a851_like",
                "schema_author_nom_de_plume_key",
            ],
        )

    @skipUnlessDBFeature("supports_comments")
    def test_add_db_comment_charfield(self):
        comment = "Custom comment"
        field = CharField(max_length=255, db_comment=comment)
        field.set_attributes_from_name("name_with_comment")
        with connection.schema_editor() as editor:
            editor.create_model(Author)
            editor.add_field(Author, field)
        self.assertEqual(
            self.get_column_comment(Author._meta.db_table, "name_with_comment"),
            comment,
        )

    @skipUnlessDBFeature("supports_comments")
    def test_add_db_comment_and_default_charfield(self):
        comment = "Custom comment with default"
        field = CharField(max_length=255, default="Joe Doe", db_comment=comment)
        field.set_attributes_from_name("name_with_comment_default")
        with connection.schema_editor() as editor:
            editor.create_model(Author)
            Author.objects.create(name="Before adding a new field")
            editor.add_field(Author, field)

        self.assertEqual(
            self.get_column_comment(Author._meta.db_table, "name_with_comment_default"),
            comment,
        )
        with connection.cursor() as cursor:
            cursor.execute(
                f"SELECT name_with_comment_default FROM {Author._meta.db_table};"
            )
            for row in cursor.fetchall():
                self.assertEqual(row[0], "Joe Doe")

    @skipUnlessDBFeature("supports_comments")
    def test_alter_db_comment(self):
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        # Add comment.
        old_field = Author._meta.get_field("name")
        new_field = CharField(max_length=255, db_comment="Custom comment")
        new_field.set_attributes_from_name("name")
        with connection.schema_editor() as editor:
            editor.alter_field(Author, old_field, new_field, strict=True)
        self.assertEqual(
            self.get_column_comment(Author._meta.db_table, "name"),
            "Custom comment",
        )
        # Alter comment.
        old_field = new_field
        new_field = CharField(max_length=255, db_comment="New custom comment")
        new_field.set_attributes_from_name("name")
        with connection.schema_editor() as editor:
            editor.alter_field(Author, old_field, new_field, strict=True)
        self.assertEqual(
            self.get_column_comment(Author._meta.db_table, "name"),
            "New custom comment",
        )
        # Remove comment.
        old_field = new_field
        new_field = CharField(max_length=255)
        new_field.set_attributes_from_name("name")
        with connection.schema_editor() as editor:
            editor.alter_field(Author, old_field, new_field, strict=True)
        self.assertIn(
            self.get_column_comment(Author._meta.db_table, "name"),
            [None, ""],
        )

    @skipUnlessDBFeature("supports_comments", "supports_foreign_keys")
    def test_alter_db_comment_foreign_key(self):
        with connection.schema_editor() as editor:
            editor.create_model(Author)
            editor.create_model(Book)

        comment = "FK custom comment"
        old_field = Book._meta.get_field("author")
        new_field = ForeignKey(Author, CASCADE, db_comment=comment)
        new_field.set_attributes_from_name("author")
        with connection.schema_editor() as editor:
            editor.alter_field(Book, old_field, new_field, strict=True)
        self.assertEqual(
            self.get_column_comment(Book._meta.db_table, "author_id"),
            comment,
        )

    @skipUnlessDBFeature("supports_comments")
    def test_alter_field_type_preserve_comment(self):
        with connection.schema_editor() as editor:
            editor.create_model(Author)

        comment = "This is the name."
        old_field = Author._meta.get_field("name")
        new_field = CharField(max_length=255, db_comment=comment)
        new_field.set_attributes_from_name("name")
        new_field.model = Author
        with connection.schema_editor() as editor:
            editor.alter_field(Author, old_field, new_field, strict=True)
        self.assertEqual(
            self.get_column_comment(Author._meta.db_table, "name"),
            comment,
        )
        # Changing a field type should preserve the comment.
        old_field = new_field
        new_field = CharField(max_length=511, db_comment=comment)
        new_field.set_attributes_from_name("name")
        new_field.model = Author
        with connection.schema_editor() as editor:
            editor.alter_field(Author, new_field, old_field, strict=True)
        # Comment is preserved.
        self.assertEqual(
            self.get_column_comment(Author._meta.db_table, "name"),
            comment,
        )

    @isolate_apps("schema")
    @skipUnlessDBFeature("supports_comments")
    def test_db_comment_table(self):
        class ModelWithDbTableComment(Model):
            class Meta:
                app_label = "schema"
                db_table_comment = "Custom table comment"

        with connection.schema_editor() as editor:
            editor.create_model(ModelWithDbTableComment)
        self.isolated_local_models = [ModelWithDbTableComment]
        self.assertEqual(
            self.get_table_comment(ModelWithDbTableComment._meta.db_table),
            "Custom table comment",
        )
        # Alter table comment.
        old_db_table_comment = ModelWithDbTableComment._meta.db_table_comment
        with connection.schema_editor() as editor:
            editor.alter_db_table_comment(
                ModelWithDbTableComment, old_db_table_comment, "New table comment"
            )
        self.assertEqual(
            self.get_table_comment(ModelWithDbTableComment._meta.db_table),
            "New table comment",
        )
        # Remove table comment.
        old_db_table_comment = ModelWithDbTableComment._meta.db_table_comment
        with connection.schema_editor() as editor:
            editor.alter_db_table_comment(
                ModelWithDbTableComment, old_db_table_comment, None
            )
        self.assertIn(
            self.get_table_comment(ModelWithDbTableComment._meta.db_table),
            [None, ""],
        )

    @isolate_apps("schema")
    @skipUnlessDBFeature("supports_comments", "supports_foreign_keys")
    def test_db_comments_from_abstract_model(self):
        class AbstractModelWithDbComments(Model):
            name = CharField(
                max_length=255, db_comment="Custom comment", null=True, blank=True
            )

            class Meta:
                app_label = "schema"
                abstract = True
                db_table_comment = "Custom table comment"

        class ModelWithDbComments(AbstractModelWithDbComments):
            pass

        with connection.schema_editor() as editor:
            editor.create_model(ModelWithDbComments)
        self.isolated_local_models = [ModelWithDbComments]

        self.assertEqual(
            self.get_column_comment(ModelWithDbComments._meta.db_table, "name"),
            "Custom comment",
        )
        self.assertEqual(
            self.get_table_comment(ModelWithDbComments._meta.db_table),
            "Custom table comment",
        )

    @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific")
    def test_alter_field_add_index_to_charfield(self):
        # Create the table and verify no initial indexes.
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        self.assertEqual(self.get_constraints_for_column(Author, "name"), [])
        # Alter to add db_index=True and create 2 indexes.
        old_field = Author._meta.get_field("name")
        new_field = CharField(max_length=255, db_index=True)
        new_field.set_attributes_from_name("name")
        with connection.schema_editor() as editor:
            editor.alter_field(Author, old_field, new_field, strict=True)
        self.assertEqual(
            self.get_constraints_for_column(Author, "name"),
            ["schema_author_name_1fbc5617", "schema_author_name_1fbc5617_like"],
        )
        # Remove db_index=True to drop both indexes.
        with connection.schema_editor() as editor:
            editor.alter_field(Author, new_field, old_field, strict=True)
        self.assertEqual(self.get_constraints_for_column(Author, "name"), [])

    @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific")
    def test_alter_field_add_unique_to_charfield(self):
        # Create the table and verify no initial indexes.
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        self.assertEqual(self.get_constraints_for_column(Author, "name"), [])
        # Alter to add unique=True and create 2 indexes.
        old_field = Author._meta.get_field("name")
        new_field = CharField(max_length=255, unique=True)
        new_field.set_attributes_from_name("name")
        with connection.schema_editor() as editor:
            editor.alter_field(Author, old_field, new_field, strict=True)
        self.assertEqual(
            self.get_constraints_for_column(Author, "name"),
            ["schema_author_name_1fbc5617_like", "schema_author_name_1fbc5617_uniq"],
        )
        # Remove unique=True to drop both indexes.
        with connection.schema_editor() as editor:
            editor.alter_field(Author, new_field, old_field, strict=True)
        self.assertEqual(self.get_constraints_for_column(Author, "name"), [])

    @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific")
    def test_alter_field_add_index_to_textfield(self):
        # Create the table and verify no initial indexes.
        with connection.schema_editor() as editor:
            editor.create_model(Note)
        self.assertEqual(self.get_constraints_for_column(Note, "info"), [])
        # Alter to add db_index=True and create 2 indexes.
        old_field = Note._meta.get_field("info")
        new_field = TextField(db_index=True)
        new_field.set_attributes_from_name("info")
        with connection.schema_editor() as editor:
            editor.alter_field(Note, old_field, new_field, strict=True)
        self.assertEqual(
            self.get_constraints_for_column(Note, "info"),
            ["schema_note_info_4b0ea695", "schema_note_info_4b0ea695_like"],
        )
        # Remove db_index=True to drop both indexes.
        with connection.schema_editor() as editor:
            editor.alter_field(Note, new_field, old_field, strict=True)
        self.assertEqual(self.get_constraints_for_column(Note, "info"), [])

    @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific")
    def test_alter_field_add_unique_to_charfield_with_db_index(self):
        # Create the table and verify initial indexes.
        with connection.schema_editor() as editor:
            editor.create_model(BookWithoutAuthor)
        self.assertEqual(
            self.get_constraints_for_column(BookWithoutAuthor, "title"),
            ["schema_book_title_2dfb2dff", "schema_book_title_2dfb2dff_like"],
        )
        # Alter to add unique=True (should replace the index)
        old_field = BookWithoutAuthor._meta.get_field("title")
        new_field = CharField(max_length=100, db_index=True, unique=True)
        new_field.set_attributes_from_name("title")
        with connection.schema_editor() as editor:
            editor.alter_field(BookWithoutAuthor, old_field, new_field, strict=True)
        self.assertEqual(
            self.get_constraints_for_column(BookWithoutAuthor, "title"),
            ["schema_book_title_2dfb2dff_like", "schema_book_title_2dfb2dff_uniq"],
        )
        # Alter to remove unique=True (should drop unique index)
        new_field2 = CharField(max_length=100, db_index=True)
        new_field2.set_attributes_from_name("title")
        with connection.schema_editor() as editor:
            editor.alter_field(BookWithoutAuthor, new_field, new_field2, strict=True)
        self.assertEqual(
            self.get_constraints_for_column(BookWithoutAuthor, "title"),
            ["schema_book_title_2dfb2dff", "schema_book_title_2dfb2dff_like"],
        )

    @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific")
    def test_alter_field_remove_unique_and_db_index_from_charfield(self):
        # Create the table and verify initial indexes.
        with connection.schema_editor() as editor:
            editor.create_model(BookWithoutAuthor)
        self.assertEqual(
            self.get_constraints_for_column(BookWithoutAuthor, "title"),
            ["schema_book_title_2dfb2dff", "schema_book_title_2dfb2dff_like"],
        )
        # Alter to add unique=True (should replace the index)
        old_field = BookWithoutAuthor._meta.get_field("title")
        new_field = CharField(max_length=100, db_index=True, unique=True)
        new_field.set_attributes_from_name("title")
        with connection.schema_editor() as editor:
            editor.alter_field(BookWithoutAuthor, old_field, new_field, strict=True)
        self.assertEqual(
            self.get_constraints_for_column(BookWithoutAuthor, "title"),
            ["schema_book_title_2dfb2dff_like", "schema_book_title_2dfb2dff_uniq"],
        )
        # Alter to remove both unique=True and db_index=True (should drop all indexes)
        new_field2 = CharField(max_length=100)
        new_field2.set_attributes_from_name("title")
        with connection.schema_editor() as editor:
            editor.alter_field(BookWithoutAuthor, new_field, new_field2, strict=True)
        self.assertEqual(
            self.get_constraints_for_column(BookWithoutAuthor, "title"), []
        )

    @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific")
    def test_alter_field_swap_unique_and_db_index_with_charfield(self):
        # Create the table and verify initial indexes.
        with connection.schema_editor() as editor:
            editor.create_model(BookWithoutAuthor)
        self.assertEqual(
            self.get_constraints_for_column(BookWithoutAuthor, "title"),
            ["schema_book_title_2dfb2dff", "schema_book_title_2dfb2dff_like"],
        )
        # Alter to set unique=True and remove db_index=True (should replace the index)
        old_field = BookWithoutAuthor._meta.get_field("title")
        new_field = CharField(max_length=100, unique=True)
        new_field.set_attributes_from_name("title")
        with connection.schema_editor() as editor:
            editor.alter_field(BookWithoutAuthor, old_field, new_field, strict=True)
        self.assertEqual(
            self.get_constraints_for_column(BookWithoutAuthor, "title"),
            ["schema_book_title_2dfb2dff_like", "schema_book_title_2dfb2dff_uniq"],
        )
        # Alter to set db_index=True and remove unique=True (should restore index)
        new_field2 = CharField(max_length=100, db_index=True)
        new_field2.set_attributes_from_name("title")
        with connection.schema_editor() as editor:
            editor.alter_field(BookWithoutAuthor, new_field, new_field2, strict=True)
        self.assertEqual(
            self.get_constraints_for_column(BookWithoutAuthor, "title"),
            ["schema_book_title_2dfb2dff", "schema_book_title_2dfb2dff_like"],
        )

    @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific")
    def test_alter_field_add_db_index_to_charfield_with_unique(self):
        # Create the table and verify initial indexes.
        with connection.schema_editor() as editor:
            editor.create_model(Tag)
        self.assertEqual(
            self.get_constraints_for_column(Tag, "slug"),
            ["schema_tag_slug_2c418ba3_like", "schema_tag_slug_key"],
        )
        # Alter to add db_index=True
        old_field = Tag._meta.get_field("slug")
        new_field = SlugField(db_index=True, unique=True)
        new_field.set_attributes_from_name("slug")
        with connection.schema_editor() as editor:
            editor.alter_field(Tag, old_field, new_field, strict=True)
        self.assertEqual(
            self.get_constraints_for_column(Tag, "slug"),
            ["schema_tag_slug_2c418ba3_like", "schema_tag_slug_key"],
        )
        # Alter to remove db_index=True
        new_field2 = SlugField(unique=True)
        new_field2.set_attributes_from_name("slug")
        with connection.schema_editor() as editor:
            editor.alter_field(Tag, new_field, new_field2, strict=True)
        self.assertEqual(
            self.get_constraints_for_column(Tag, "slug"),
            ["schema_tag_slug_2c418ba3_like", "schema_tag_slug_key"],
        )

    def test_alter_field_add_index_to_integerfield(self):
        # Create the table and verify no initial indexes.
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        self.assertEqual(self.get_constraints_for_column(Author, "weight"), [])

        # Alter to add db_index=True and create index.
        old_field = Author._meta.get_field("weight")
        new_field = IntegerField(null=True, db_index=True)
        new_field.set_attributes_from_name("weight")
        with connection.schema_editor() as editor:
            editor.alter_field(Author, old_field, new_field, strict=True)
        self.assertEqual(
            self.get_constraints_for_column(Author, "weight"),
            ["schema_author_weight_587740f9"],
        )

        # Remove db_index=True to drop index.
        with connection.schema_editor() as editor:
            editor.alter_field(Author, new_field, old_field, strict=True)
        self.assertEqual(self.get_constraints_for_column(Author, "weight"), [])

    def test_alter_pk_with_self_referential_field(self):
        """
        Changing the primary key field name of a model with a self-referential
        foreign key (#26384).
        """
        with connection.schema_editor() as editor:
            editor.create_model(Node)
        old_field = Node._meta.get_field("node_id")
        new_field = AutoField(primary_key=True)
        new_field.set_attributes_from_name("id")
        with connection.schema_editor() as editor:
            editor.alter_field(Node, old_field, new_field, strict=True)
        self.assertForeignKeyExists(Node, "parent_id", Node._meta.db_table)

    @mock.patch("django.db.backends.base.schema.datetime")
    @mock.patch("django.db.backends.base.schema.timezone")
    def test_add_datefield_and_datetimefield_use_effective_default(
        self, mocked_datetime, mocked_tz
    ):
        """
        effective_default() should be used for DateField, DateTimeField, and
        TimeField if auto_now or auto_now_add is set (#25005).
        """
        now = datetime.datetime(month=1, day=1, year=2000, hour=1, minute=1)
        now_tz = datetime.datetime(
            month=1, day=1, year=2000, hour=1, minute=1, tzinfo=datetime.timezone.utc
        )
        mocked_datetime.now = mock.MagicMock(return_value=now)
        mocked_tz.now = mock.MagicMock(return_value=now_tz)
        # Create the table
        with connection.schema_editor() as editor:
            editor.create_model(Author)
        # Check auto_now/auto_now_add attributes are not defined
        columns = self.column_classes(Author)
        self.assertNotIn("dob_auto_now", columns)
        self.assertNotIn("dob_auto_now_add", columns)
        self.assertNotIn("dtob_auto_now", columns)
        self.assertNotIn("dtob_auto_now_add", columns)
        self.assertNotIn("tob_auto_now", columns)
        self.assertNotIn("tob_auto_now_add", columns)
        # Create a row
        Author.objects.create(name="Anonymous1")
        # Ensure fields were added with the correct defaults
        dob_auto_now = DateField(auto_now=True)
        dob_auto_now.set_attributes_from_name("dob_auto_now")
        self.check_added_field_default(
            editor,
            Author,
            dob_auto_now,
            "dob_auto_now",
            now.date(),
            cast_function=lambda x: x.date(),
        )
        dob_auto_now_add = DateField(auto_now_add=True)
        dob_auto_now_add.set_attributes_from_name("dob_auto_now_add")
        self.check_added_field_default(
            editor,
            Author,
            dob_auto_now_add,
            "dob_auto_now_add",
            now.date(),
            cast_function=lambda x: x.date(),
        )
        dtob_auto_now = DateTimeField(auto_now=True)
        dtob_auto_now.set_attributes_from_name("dtob_auto_now")
        self.check_added_field_default(
            editor,
            Author,
            dtob_auto_now,
            "dtob_auto_now",
            now,
        )
        dt_tm_of_birth_auto_now_add = DateTimeField(auto_now_add=True)
        dt_tm_of_birth_auto_now_add.set_attributes_from_name("dtob_auto_now_add")
        self.check_added_field_default(
            editor,
            Author,
            dt_tm_of_birth_auto_now_add,
            "dtob_auto_now_add",
            now,
        )
        tob_auto_now = TimeField(auto_now=True)
        tob_auto_now.set_attributes_from_name("tob_auto_now")
        self.check_added_field_default(
            editor,
            Author,
            tob_auto_now,
            "tob_auto_now",
            now.time(),
            cast_function=lambda x: x.time(),
        )
        tob_auto_now_add = TimeField(auto_now_add=True)
        tob_auto_now_add.set_attributes_from_name("tob_auto_now_add")
        self.check_added_field_default(
            editor,
            Author,
            tob_auto_now_add,
            "tob_auto_now_add",
            now.time(),
            cast_function=lambda x: x.time(),
        )

    def test_namespaced_db_table_create_index_name(self):
        """
        Table names are stripped of their namespace/schema before being used to
        generate index names.
        """
        with connection.schema_editor() as editor:
            max_name_length = connection.ops.max_name_length() or 200
            namespace = "n" * max_name_length
            table_name = "t" * max_name_length
            namespaced_table_name = '"%s"."%s"' % (namespace, table_name)
            self.assertEqual(
                editor._create_index_name(table_name, []),
                editor._create_index_name(namespaced_table_name, []),
            )

    @unittest.skipUnless(
        connection.vendor == "oracle", "Oracle specific db_table syntax"
    )
    def test_creation_with_db_table_double_quotes(self):
        oracle_user = connection.creation._test_database_user()

        class Student(Model):
            name = CharField(max_length=30)

            class Meta:
                app_label = "schema"
                apps = new_apps
                db_table = '"%s"."DJANGO_STUDENT_TABLE"' % oracle_user

        class Document(Model):
            name = CharField(max_length=30)
            students = ManyToManyField(Student)

            class Meta:
                app_label = "schema"
                apps = new_apps
                db_table = '"%s"."DJANGO_DOCUMENT_TABLE"' % oracle_user

        self.isolated_local_models = [Student, Document]

        with connection.schema_editor() as editor:
            editor.create_model(Student)
            editor.create_model(Document)

        doc = Document.objects.create(name="Test Name")
        student = Student.objects.create(name="Some man")
        doc.students.add(student)

    @isolate_apps("schema")
    @unittest.skipUnless(
        connection.vendor == "postgresql", "PostgreSQL specific db_table syntax."
    )
    def test_namespaced_db_table_foreign_key_reference(self):
        with connection.cursor() as cursor:
            cursor.execute("CREATE SCHEMA django_schema_tests")

        def delete_schema():
            with connection.cursor() as cursor:
                cursor.execute("DROP SCHEMA django_schema_tests CASCADE")

        self.addCleanup(delete_schema)

        class Author(Model):
            class Meta:
                app_label = "schema"

        class Book(Model):
            class Meta:
                app_label = "schema"
                db_table = '"django_schema_tests"."schema_book"'

        author = ForeignKey(Author, CASCADE)
        author.set_attributes_from_name("author")

        with connection.schema_editor() as editor:
            editor.create_model(Author)
            editor.create_model(Book)
            editor.add_field(Book, author)

    def test_rename_table_renames_deferred_sql_references(self):
        atomic_rename = connection.features.supports_atomic_references_rename
        with connection.schema_editor(atomic=atomic_rename) as editor:
            editor.create_model(Author)
            editor.create_model(Book)
            editor.alter_db_table(Author, "schema_author", "schema_renamed_author")
            editor.alter_db_table(Author, "schema_book", "schema_renamed_book")
            try:
                self.assertGreater(len(editor.deferred_sql), 0)
                for statement in editor.deferred_sql:
                    self.assertIs(statement.references_table("schema_author"), False)
                    self.assertIs(statement.references_table("schema_book"), False)
            finally:
                editor.alter_db_table(Author, "schema_renamed_author", "schema_author")
                editor.alter_db_table(Author, "schema_renamed_book", "schema_book")

    def test_rename_column_renames_deferred_sql_references(self):
        with connection.schema_editor() as editor:
            editor.create_model(Author)
            editor.create_model(Book)
            old_title = Book._meta.get_field("title")
            new_title = CharField(max_length=100, db_index=True)
            new_title.set_attributes_from_name("renamed_title")
            editor.alter_field(Book, old_title, new_title)
            old_author = Book._meta.get_field("author")
            new_author = ForeignKey(Author, CASCADE)
            new_author.set_attributes_from_name("renamed_author")
            editor.alter_field(Book, old_author, new_author)
            self.assertGreater(len(editor.deferred_sql), 0)
            for statement in editor.deferred_sql:
                self.assertIs(statement.references_column("book", "title"), False)
                self.assertIs(statement.references_column("book", "author_id"), False)

    @isolate_apps("schema")
    def test_referenced_field_without_constraint_rename_inside_atomic_block(self):
        """
        Foreign keys without database level constraint don't prevent the field
        they reference from being renamed in an atomic block.
        """

        class Foo(Model):
            field = CharField(max_length=255, unique=True)

            class Meta:
                app_label = "schema"

        class Bar(Model):
            foo = ForeignKey(Foo, CASCADE, to_field="field", db_constraint=False)

            class Meta:
                app_label = "schema"

        self.isolated_local_models = [Foo, Bar]
        with connection.schema_editor() as editor:
            editor.create_model(Foo)
            editor.create_model(Bar)

        new_field = CharField(max_length=255, unique=True)
        new_field.set_attributes_from_name("renamed")
        with connection.schema_editor(atomic=True) as editor:
            editor.alter_field(Foo, Foo._meta.get_field("field"), new_field)

    @isolate_apps("schema")
    def test_referenced_table_without_constraint_rename_inside_atomic_block(self):
        """
        Foreign keys without database level constraint don't prevent the table
        they reference from being renamed in an atomic block.
        """

        class Foo(Model):
            field = CharField(max_length=255, unique=True)

            class Meta:
                app_label = "schema"

        class Bar(Model):
            foo = ForeignKey(Foo, CASCADE, to_field="field", db_constraint=False)

            class Meta:
                app_label = "schema"

        self.isolated_local_models = [Foo, Bar]
        with connection.schema_editor() as editor:
            editor.create_model(Foo)
            editor.create_model(Bar)

        new_field = CharField(max_length=255, unique=True)
        new_field.set_attributes_from_name("renamed")
        with connection.schema_editor(atomic=True) as editor:
            editor.alter_db_table(Foo, Foo._meta.db_table, "renamed_table")
        Foo._meta.db_table = "renamed_table"

    @isolate_apps("schema")
    @skipUnlessDBFeature("supports_collation_on_charfield")
    def test_db_collation_charfield(self):
        collation = connection.features.test_collations.get("non_default")
        if not collation:
            self.skipTest("Language collations are not supported.")

        class Foo(Model):
            field = CharField(max_length=255, db_collation=collation)

            class Meta:
                app_label = "schema"

        self.isolated_local_models = [Foo]
        with connection.schema_editor() as editor:
            editor.create_model(Foo)

        self.assertEqual(
            self.get_column_collation(Foo._meta.db_table, "field"),
            collation,
        )

    @isolate_apps("schema")
    @skipUnlessDBFeature("supports_collation_on_textfield")
    def test_db_collation_textfield(self):
        collation = connection.features.test_collations.get("non_default")
        if not collation:
            self.skipTest("Language collations are not supported.")

        class Foo(Model):
            field = TextField(db_collation=collation)

            class Meta:
                app_label = "schema"

        self.isolated_local_models = [Foo]
        with connection.schema_editor() as editor:
            editor.create_model(Foo)

        self.assertEqual(
            self.get_column_collation(Foo._meta.db_table, "field"),
            collation,
        )

    @skipUnlessDBFeature("supports_collation_on_charfield")
    def test_add_field_db_collation(self):
        collation = connection.features.test_collations.get("non_default")
        if not collation:
            self.skipTest("Language collations are not supported.")

        with connection.schema_editor() as editor:
            editor.create_model(Author)

        new_field = CharField(max_length=255, db_collation=collation)
        new_field.set_attributes_from_name("alias")
        with connection.schema_editor() as editor:
            editor.add_field(Author, new_field)
        columns = self.column_classes(Author)
        self.assertEqual(
            columns["alias"][0],
            connection.features.introspected_field_types["CharField"],
        )
        self.assertEqual(columns["alias"][1][8], collation)

    @skipUnlessDBFeature("supports_collation_on_charfield")
    def test_alter_field_db_collation(self):
        collation = connection.features.test_collations.get("non_default")
        if not collation:
            self.skipTest("Language collations are not supported.")

        with connection.schema_editor() as editor:
            editor.create_model(Author)

        old_field = Author._meta.get_field("name")
        new_field = CharField(max_length=255, db_collation=collation)
        new_field.set_attributes_from_name("name")
        new_field.model = Author
        with connection.schema_editor() as editor:
            editor.alter_field(Author, old_field, new_field, strict=True)
        self.assertEqual(
            self.get_column_collation(Author._meta.db_table, "name"),
            collation,
        )
        with connection.schema_editor() as editor:
            editor.alter_field(Author, new_field, old_field, strict=True)
        self.assertIsNone(self.get_column_collation(Author._meta.db_table, "name"))

    @skipUnlessDBFeature("supports_collation_on_charfield")
    def test_alter_field_type_preserve_db_collation(self):
        collation = connection.features.test_collations.get("non_default")
        if not collation:
            self.skipTest("Language collations are not supported.")

        with connection.schema_editor() as editor:
            editor.create_model(Author)

        old_field = Author._meta.get_field("name")
        new_field = CharField(max_length=255, db_collation=collation)
        new_field.set_attributes_from_name("name")
        new_field.model = Author
        with connection.schema_editor() as editor:
            editor.alter_field(Author, old_field, new_field, strict=True)
        self.assertEqual(
            self.get_column_collation(Author._meta.db_table, "name"),
            collation,
        )
        # Changing a field type should preserve the collation.
        old_field = new_field
        new_field = CharField(max_length=511, db_collation=collation)
        new_field.set_attributes_from_name("name")
        new_field.model = Author
        with connection.schema_editor() as editor:
            editor.alter_field(Author, new_field, old_field, strict=True)
        # Collation is preserved.
        self.assertEqual(
            self.get_column_collation(Author._meta.db_table, "name"),
            collation,
        )

    @skipUnlessDBFeature("supports_collation_on_charfield")
    def test_alter_primary_key_db_collation(self):
        collation = connection.features.test_collations.get("non_default")
        if not collation:
            self.skipTest("Language collations are not supported.")

        with connection.schema_editor() as editor:
            editor.create_model(Thing)

        old_field = Thing._meta.get_field("when")
        new_field = CharField(max_length=1, db_collation=collation, primary_key=True)
        new_field.set_attributes_from_name("when")
        new_field.model = Thing
        with connection.schema_editor() as editor:
            editor.alter_field(Thing, old_field, new_field, strict=True)
        self.assertEqual(self.get_primary_key(Thing._meta.db_table), "when")
        self.assertEqual(
            self.get_column_collation(Thing._meta.db_table, "when"),
            collation,
        )
        with connection.schema_editor() as editor:
            editor.alter_field(Thing, new_field, old_field, strict=True)
        self.assertEqual(self.get_primary_key(Thing._meta.db_table), "when")
        self.assertIsNone(self.get_column_collation(Thing._meta.db_table, "when"))

    @skipUnlessDBFeature(
        "supports_collation_on_charfield", "supports_collation_on_textfield"
    )
    def test_alter_field_type_and_db_collation(self):
        collation = connection.features.test_collations.get("non_default")
        if not collation:
            self.skipTest("Language collations are not supported.")

        with connection.schema_editor() as editor:
            editor.create_model(Note)

        old_field = Note._meta.get_field("info")
        new_field = CharField(max_length=255, db_collation=collation)
        new_field.set_attributes_from_name("info")
        new_field.model = Note
        with connection.schema_editor() as editor:
            editor.alter_field(Note, old_field, new_field, strict=True)
        columns = self.column_classes(Note)
        self.assertEqual(
            columns["info"][0],
            connection.features.introspected_field_types["CharField"],
        )
        self.assertEqual(columns["info"][1][8], collation)
        with connection.schema_editor() as editor:
            editor.alter_field(Note, new_field, old_field, strict=True)
        columns = self.column_classes(Note)
        self.assertEqual(columns["info"][0], "TextField")
        self.assertIsNone(columns["info"][1][8])

    @skipUnlessDBFeature(
        "supports_collation_on_charfield",
        "supports_non_deterministic_collations",
    )
    def test_ci_cs_db_collation(self):
        cs_collation = connection.features.test_collations.get("cs")
        ci_collation = connection.features.test_collations.get("ci")
        try:
            if connection.vendor == "mysql":
                cs_collation = "latin1_general_cs"
            elif connection.vendor == "postgresql":
                cs_collation = "en-x-icu"
                with connection.cursor() as cursor:
                    cursor.execute(
                        "CREATE COLLATION IF NOT EXISTS case_insensitive "
                        "(provider = icu, locale = 'und-u-ks-level2', "
                        "deterministic = false)"
                    )
                    ci_collation = "case_insensitive"
            # Create the table.
            with connection.schema_editor() as editor:
                editor.create_model(Author)
            # Case-insensitive collation.
            old_field = Author._meta.get_field("name")
            new_field_ci = CharField(max_length=255, db_collation=ci_collation)
            new_field_ci.set_attributes_from_name("name")
            new_field_ci.model = Author
            with connection.schema_editor() as editor:
                editor.alter_field(Author, old_field, new_field_ci, strict=True)
            Author.objects.create(name="ANDREW")
            self.assertIs(Author.objects.filter(name="Andrew").exists(), True)
            # Case-sensitive collation.
            new_field_cs = CharField(max_length=255, db_collation=cs_collation)
            new_field_cs.set_attributes_from_name("name")
            new_field_cs.model = Author
            with connection.schema_editor() as editor:
                editor.alter_field(Author, new_field_ci, new_field_cs, strict=True)
            self.assertIs(Author.objects.filter(name="Andrew").exists(), False)
        finally:
            if connection.vendor == "postgresql":
                with connection.cursor() as cursor:
                    cursor.execute("DROP COLLATION IF EXISTS case_insensitive")