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
|
/*-------------------------------------------------------------------------
*
* typecmds.c
* Routines for SQL commands that manipulate types (and domains).
*
* Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
*
* IDENTIFICATION
* src/backend/commands/typecmds.c
*
* DESCRIPTION
* The "DefineFoo" routines take the parse tree and pick out the
* appropriate arguments/flags, passing the results to the
* corresponding "FooDefine" routines (in src/catalog) that do
* the actual catalog-munging. These routines also verify permission
* of the user to execute the command.
*
* NOTES
* These things must be defined and committed in the following order:
* "create function":
* input/output, recv/send functions
* "create type":
* type
* "create operator":
* operators
*
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "access/htup_details.h"
#include "access/xact.h"
#include "catalog/binary_upgrade.h"
#include "catalog/catalog.h"
#include "catalog/heap.h"
#include "catalog/objectaccess.h"
#include "catalog/pg_am.h"
#include "catalog/pg_authid.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_constraint.h"
#include "catalog/pg_constraint_fn.h"
#include "catalog/pg_depend.h"
#include "catalog/pg_enum.h"
#include "catalog/pg_language.h"
#include "catalog/pg_namespace.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_proc_fn.h"
#include "catalog/pg_range.h"
#include "catalog/pg_type.h"
#include "catalog/pg_type_fn.h"
#include "commands/defrem.h"
#include "commands/tablecmds.h"
#include "commands/typecmds.h"
#include "executor/executor.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "optimizer/var.h"
#include "parser/parse_coerce.h"
#include "parser/parse_collate.h"
#include "parser/parse_expr.h"
#include "parser/parse_func.h"
#include "parser/parse_type.h"
#include "utils/builtins.h"
#include "utils/fmgroids.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/ruleutils.h"
#include "utils/snapmgr.h"
#include "utils/syscache.h"
/* result structure for get_rels_with_domain() */
typedef struct
{
Relation rel; /* opened and locked relation */
int natts; /* number of attributes of interest */
int *atts; /* attribute numbers */
/* atts[] is of allocated length RelationGetNumberOfAttributes(rel) */
} RelToCheck;
/* Potentially set by pg_upgrade_support functions */
Oid binary_upgrade_next_array_pg_type_oid = InvalidOid;
static void makeRangeConstructors(const char *name, Oid namespace,
Oid rangeOid, Oid subtype);
static Oid findTypeInputFunction(List *procname, Oid typeOid);
static Oid findTypeOutputFunction(List *procname, Oid typeOid);
static Oid findTypeReceiveFunction(List *procname, Oid typeOid);
static Oid findTypeSendFunction(List *procname, Oid typeOid);
static Oid findTypeTypmodinFunction(List *procname);
static Oid findTypeTypmodoutFunction(List *procname);
static Oid findTypeAnalyzeFunction(List *procname, Oid typeOid);
static Oid findRangeSubOpclass(List *opcname, Oid subtype);
static Oid findRangeCanonicalFunction(List *procname, Oid typeOid);
static Oid findRangeSubtypeDiffFunction(List *procname, Oid subtype);
static void validateDomainConstraint(Oid domainoid, char *ccbin);
static List *get_rels_with_domain(Oid domainOid, LOCKMODE lockmode);
static void checkEnumOwner(HeapTuple tup);
static char *domainAddConstraint(Oid domainOid, Oid domainNamespace,
Oid baseTypeOid,
int typMod, Constraint *constr,
char *domainName, ObjectAddress *constrAddr);
static Node *replace_domain_constraint_value(ParseState *pstate,
ColumnRef *cref);
/*
* DefineType
* Registers a new base type.
*/
ObjectAddress
DefineType(ParseState *pstate, List *names, List *parameters)
{
char *typeName;
Oid typeNamespace;
int16 internalLength = -1; /* default: variable-length */
List *inputName = NIL;
List *outputName = NIL;
List *receiveName = NIL;
List *sendName = NIL;
List *typmodinName = NIL;
List *typmodoutName = NIL;
List *analyzeName = NIL;
char category = TYPCATEGORY_USER;
bool preferred = false;
char delimiter = DEFAULT_TYPDELIM;
Oid elemType = InvalidOid;
char *defaultValue = NULL;
bool byValue = false;
char alignment = 'i'; /* default alignment */
char storage = 'p'; /* default TOAST storage method */
Oid collation = InvalidOid;
DefElem *likeTypeEl = NULL;
DefElem *internalLengthEl = NULL;
DefElem *inputNameEl = NULL;
DefElem *outputNameEl = NULL;
DefElem *receiveNameEl = NULL;
DefElem *sendNameEl = NULL;
DefElem *typmodinNameEl = NULL;
DefElem *typmodoutNameEl = NULL;
DefElem *analyzeNameEl = NULL;
DefElem *categoryEl = NULL;
DefElem *preferredEl = NULL;
DefElem *delimiterEl = NULL;
DefElem *elemTypeEl = NULL;
DefElem *defaultValueEl = NULL;
DefElem *byValueEl = NULL;
DefElem *alignmentEl = NULL;
DefElem *storageEl = NULL;
DefElem *collatableEl = NULL;
Oid inputOid;
Oid outputOid;
Oid receiveOid = InvalidOid;
Oid sendOid = InvalidOid;
Oid typmodinOid = InvalidOid;
Oid typmodoutOid = InvalidOid;
Oid analyzeOid = InvalidOid;
char *array_type;
Oid array_oid;
Oid typoid;
Oid resulttype;
ListCell *pl;
ObjectAddress address;
/*
* As of Postgres 8.4, we require superuser privilege to create a base
* type. This is simple paranoia: there are too many ways to mess up the
* system with an incorrect type definition (for instance, representation
* parameters that don't match what the C code expects). In practice it
* takes superuser privilege to create the I/O functions, and so the
* former requirement that you own the I/O functions pretty much forced
* superuserness anyway. We're just making doubly sure here.
*
* XXX re-enable NOT_USED code sections below if you remove this test.
*/
if (!superuser())
ereport(ERROR,
(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
errmsg("must be superuser to create a base type")));
/* Convert list of names to a name and namespace */
typeNamespace = QualifiedNameGetCreationNamespace(names, &typeName);
#ifdef NOT_USED
/* XXX this is unnecessary given the superuser check above */
/* Check we have creation rights in target namespace */
aclresult = pg_namespace_aclcheck(typeNamespace, GetUserId(), ACL_CREATE);
if (aclresult != ACLCHECK_OK)
aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
get_namespace_name(typeNamespace));
#endif
/*
* Look to see if type already exists (presumably as a shell; if not,
* TypeCreate will complain).
*/
typoid = GetSysCacheOid2(TYPENAMENSP,
CStringGetDatum(typeName),
ObjectIdGetDatum(typeNamespace));
/*
* If it's not a shell, see if it's an autogenerated array type, and if so
* rename it out of the way.
*/
if (OidIsValid(typoid) && get_typisdefined(typoid))
{
if (moveArrayTypeName(typoid, typeName, typeNamespace))
typoid = InvalidOid;
}
/*
* If it doesn't exist, create it as a shell, so that the OID is known for
* use in the I/O function definitions.
*/
if (!OidIsValid(typoid))
{
address = TypeShellMake(typeName, typeNamespace, GetUserId());
typoid = address.objectId;
/* Make new shell type visible for modification below */
CommandCounterIncrement();
/*
* If the command was a parameterless CREATE TYPE, we're done ---
* creating the shell type was all we're supposed to do.
*/
if (parameters == NIL)
return address;
}
else
{
/* Complain if dummy CREATE TYPE and entry already exists */
if (parameters == NIL)
ereport(ERROR,
(errcode(ERRCODE_DUPLICATE_OBJECT),
errmsg("type \"%s\" already exists", typeName)));
}
/* Extract the parameters from the parameter list */
foreach(pl, parameters)
{
DefElem *defel = (DefElem *) lfirst(pl);
DefElem **defelp;
if (pg_strcasecmp(defel->defname, "like") == 0)
defelp = &likeTypeEl;
else if (pg_strcasecmp(defel->defname, "internallength") == 0)
defelp = &internalLengthEl;
else if (pg_strcasecmp(defel->defname, "input") == 0)
defelp = &inputNameEl;
else if (pg_strcasecmp(defel->defname, "output") == 0)
defelp = &outputNameEl;
else if (pg_strcasecmp(defel->defname, "receive") == 0)
defelp = &receiveNameEl;
else if (pg_strcasecmp(defel->defname, "send") == 0)
defelp = &sendNameEl;
else if (pg_strcasecmp(defel->defname, "typmod_in") == 0)
defelp = &typmodinNameEl;
else if (pg_strcasecmp(defel->defname, "typmod_out") == 0)
defelp = &typmodoutNameEl;
else if (pg_strcasecmp(defel->defname, "analyze") == 0 ||
pg_strcasecmp(defel->defname, "analyse") == 0)
defelp = &analyzeNameEl;
else if (pg_strcasecmp(defel->defname, "category") == 0)
defelp = &categoryEl;
else if (pg_strcasecmp(defel->defname, "preferred") == 0)
defelp = &preferredEl;
else if (pg_strcasecmp(defel->defname, "delimiter") == 0)
defelp = &delimiterEl;
else if (pg_strcasecmp(defel->defname, "element") == 0)
defelp = &elemTypeEl;
else if (pg_strcasecmp(defel->defname, "default") == 0)
defelp = &defaultValueEl;
else if (pg_strcasecmp(defel->defname, "passedbyvalue") == 0)
defelp = &byValueEl;
else if (pg_strcasecmp(defel->defname, "alignment") == 0)
defelp = &alignmentEl;
else if (pg_strcasecmp(defel->defname, "storage") == 0)
defelp = &storageEl;
else if (pg_strcasecmp(defel->defname, "collatable") == 0)
defelp = &collatableEl;
else
{
/* WARNING, not ERROR, for historical backwards-compatibility */
ereport(WARNING,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("type attribute \"%s\" not recognized",
defel->defname),
parser_errposition(pstate, defel->location)));
continue;
}
if (*defelp != NULL)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting or redundant options"),
parser_errposition(pstate, defel->location)));
*defelp = defel;
}
/*
* Now interpret the options; we do this separately so that LIKE can be
* overridden by other options regardless of the ordering in the parameter
* list.
*/
if (likeTypeEl)
{
Type likeType;
Form_pg_type likeForm;
likeType = typenameType(NULL, defGetTypeName(likeTypeEl), NULL);
likeForm = (Form_pg_type) GETSTRUCT(likeType);
internalLength = likeForm->typlen;
byValue = likeForm->typbyval;
alignment = likeForm->typalign;
storage = likeForm->typstorage;
ReleaseSysCache(likeType);
}
if (internalLengthEl)
internalLength = defGetTypeLength(internalLengthEl);
if (inputNameEl)
inputName = defGetQualifiedName(inputNameEl);
if (outputNameEl)
outputName = defGetQualifiedName(outputNameEl);
if (receiveNameEl)
receiveName = defGetQualifiedName(receiveNameEl);
if (sendNameEl)
sendName = defGetQualifiedName(sendNameEl);
if (typmodinNameEl)
typmodinName = defGetQualifiedName(typmodinNameEl);
if (typmodoutNameEl)
typmodoutName = defGetQualifiedName(typmodoutNameEl);
if (analyzeNameEl)
analyzeName = defGetQualifiedName(analyzeNameEl);
if (categoryEl)
{
char *p = defGetString(categoryEl);
category = p[0];
/* restrict to non-control ASCII */
if (category < 32 || category > 126)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("invalid type category \"%s\": must be simple ASCII",
p)));
}
if (preferredEl)
preferred = defGetBoolean(preferredEl);
if (delimiterEl)
{
char *p = defGetString(delimiterEl);
delimiter = p[0];
/* XXX shouldn't we restrict the delimiter? */
}
if (elemTypeEl)
{
elemType = typenameTypeId(NULL, defGetTypeName(elemTypeEl));
/* disallow arrays of pseudotypes */
if (get_typtype(elemType) == TYPTYPE_PSEUDO)
ereport(ERROR,
(errcode(ERRCODE_DATATYPE_MISMATCH),
errmsg("array element type cannot be %s",
format_type_be(elemType))));
}
if (defaultValueEl)
defaultValue = defGetString(defaultValueEl);
if (byValueEl)
byValue = defGetBoolean(byValueEl);
if (alignmentEl)
{
char *a = defGetString(alignmentEl);
/*
* Note: if argument was an unquoted identifier, parser will have
* applied translations to it, so be prepared to recognize translated
* type names as well as the nominal form.
*/
if (pg_strcasecmp(a, "double") == 0 ||
pg_strcasecmp(a, "float8") == 0 ||
pg_strcasecmp(a, "pg_catalog.float8") == 0)
alignment = 'd';
else if (pg_strcasecmp(a, "int4") == 0 ||
pg_strcasecmp(a, "pg_catalog.int4") == 0)
alignment = 'i';
else if (pg_strcasecmp(a, "int2") == 0 ||
pg_strcasecmp(a, "pg_catalog.int2") == 0)
alignment = 's';
else if (pg_strcasecmp(a, "char") == 0 ||
pg_strcasecmp(a, "pg_catalog.bpchar") == 0)
alignment = 'c';
else
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("alignment \"%s\" not recognized", a)));
}
if (storageEl)
{
char *a = defGetString(storageEl);
if (pg_strcasecmp(a, "plain") == 0)
storage = 'p';
else if (pg_strcasecmp(a, "external") == 0)
storage = 'e';
else if (pg_strcasecmp(a, "extended") == 0)
storage = 'x';
else if (pg_strcasecmp(a, "main") == 0)
storage = 'm';
else
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("storage \"%s\" not recognized", a)));
}
if (collatableEl)
collation = defGetBoolean(collatableEl) ? DEFAULT_COLLATION_OID : InvalidOid;
/*
* make sure we have our required definitions
*/
if (inputName == NIL)
ereport(ERROR,
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
errmsg("type input function must be specified")));
if (outputName == NIL)
ereport(ERROR,
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
errmsg("type output function must be specified")));
if (typmodinName == NIL && typmodoutName != NIL)
ereport(ERROR,
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
errmsg("type modifier output function is useless without a type modifier input function")));
/*
* Convert I/O proc names to OIDs
*/
inputOid = findTypeInputFunction(inputName, typoid);
outputOid = findTypeOutputFunction(outputName, typoid);
if (receiveName)
receiveOid = findTypeReceiveFunction(receiveName, typoid);
if (sendName)
sendOid = findTypeSendFunction(sendName, typoid);
/*
* Verify that I/O procs return the expected thing. If we see OPAQUE,
* complain and change it to the correct type-safe choice.
*/
resulttype = get_func_rettype(inputOid);
if (resulttype != typoid)
{
if (resulttype == OPAQUEOID)
{
/* backwards-compatibility hack */
ereport(WARNING,
(errmsg("changing return type of function %s from %s to %s",
NameListToString(inputName), "opaque", typeName)));
SetFunctionReturnType(inputOid, typoid);
}
else
ereport(ERROR,
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
errmsg("type input function %s must return type %s",
NameListToString(inputName), typeName)));
}
resulttype = get_func_rettype(outputOid);
if (resulttype != CSTRINGOID)
{
if (resulttype == OPAQUEOID)
{
/* backwards-compatibility hack */
ereport(WARNING,
(errmsg("changing return type of function %s from %s to %s",
NameListToString(outputName), "opaque", "cstring")));
SetFunctionReturnType(outputOid, CSTRINGOID);
}
else
ereport(ERROR,
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
errmsg("type output function %s must return type %s",
NameListToString(outputName), "cstring")));
}
if (receiveOid)
{
resulttype = get_func_rettype(receiveOid);
if (resulttype != typoid)
ereport(ERROR,
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
errmsg("type receive function %s must return type %s",
NameListToString(receiveName), typeName)));
}
if (sendOid)
{
resulttype = get_func_rettype(sendOid);
if (resulttype != BYTEAOID)
ereport(ERROR,
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
errmsg("type send function %s must return type %s",
NameListToString(sendName), "bytea")));
}
/*
* Convert typmodin/out function proc names to OIDs.
*/
if (typmodinName)
typmodinOid = findTypeTypmodinFunction(typmodinName);
if (typmodoutName)
typmodoutOid = findTypeTypmodoutFunction(typmodoutName);
/*
* Convert analysis function proc name to an OID. If no analysis function
* is specified, we'll use zero to select the built-in default algorithm.
*/
if (analyzeName)
analyzeOid = findTypeAnalyzeFunction(analyzeName, typoid);
/*
* Check permissions on functions. We choose to require the creator/owner
* of a type to also own the underlying functions. Since creating a type
* is tantamount to granting public execute access on the functions, the
* minimum sane check would be for execute-with-grant-option. But we
* don't have a way to make the type go away if the grant option is
* revoked, so ownership seems better.
*/
#ifdef NOT_USED
/* XXX this is unnecessary given the superuser check above */
if (inputOid && !pg_proc_ownercheck(inputOid, GetUserId()))
aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_PROC,
NameListToString(inputName));
if (outputOid && !pg_proc_ownercheck(outputOid, GetUserId()))
aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_PROC,
NameListToString(outputName));
if (receiveOid && !pg_proc_ownercheck(receiveOid, GetUserId()))
aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_PROC,
NameListToString(receiveName));
if (sendOid && !pg_proc_ownercheck(sendOid, GetUserId()))
aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_PROC,
NameListToString(sendName));
if (typmodinOid && !pg_proc_ownercheck(typmodinOid, GetUserId()))
aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_PROC,
NameListToString(typmodinName));
if (typmodoutOid && !pg_proc_ownercheck(typmodoutOid, GetUserId()))
aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_PROC,
NameListToString(typmodoutName));
if (analyzeOid && !pg_proc_ownercheck(analyzeOid, GetUserId()))
aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_PROC,
NameListToString(analyzeName));
#endif
/*
* Print warnings if any of the type's I/O functions are marked volatile.
* There is a general assumption that I/O functions are stable or
* immutable; this allows us for example to mark record_in/record_out
* stable rather than volatile. Ideally we would throw errors not just
* warnings here; but since this check is new as of 9.5, and since the
* volatility marking might be just an error-of-omission and not a true
* indication of how the function behaves, we'll let it pass as a warning
* for now.
*/
if (inputOid && func_volatile(inputOid) == PROVOLATILE_VOLATILE)
ereport(WARNING,
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
errmsg("type input function %s should not be volatile",
NameListToString(inputName))));
if (outputOid && func_volatile(outputOid) == PROVOLATILE_VOLATILE)
ereport(WARNING,
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
errmsg("type output function %s should not be volatile",
NameListToString(outputName))));
if (receiveOid && func_volatile(receiveOid) == PROVOLATILE_VOLATILE)
ereport(WARNING,
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
errmsg("type receive function %s should not be volatile",
NameListToString(receiveName))));
if (sendOid && func_volatile(sendOid) == PROVOLATILE_VOLATILE)
ereport(WARNING,
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
errmsg("type send function %s should not be volatile",
NameListToString(sendName))));
if (typmodinOid && func_volatile(typmodinOid) == PROVOLATILE_VOLATILE)
ereport(WARNING,
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
errmsg("type modifier input function %s should not be volatile",
NameListToString(typmodinName))));
if (typmodoutOid && func_volatile(typmodoutOid) == PROVOLATILE_VOLATILE)
ereport(WARNING,
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
errmsg("type modifier output function %s should not be volatile",
NameListToString(typmodoutName))));
/*
* OK, we're done checking, time to make the type. We must assign the
* array type OID ahead of calling TypeCreate, since the base type and
* array type each refer to the other.
*/
array_oid = AssignTypeArrayOid();
/*
* now have TypeCreate do all the real work.
*
* Note: the pg_type.oid is stored in user tables as array elements (base
* types) in ArrayType and in composite types in DatumTupleFields. This
* oid must be preserved by binary upgrades.
*/
address =
TypeCreate(InvalidOid, /* no predetermined type OID */
typeName, /* type name */
typeNamespace, /* namespace */
InvalidOid, /* relation oid (n/a here) */
0, /* relation kind (ditto) */
GetUserId(), /* owner's ID */
internalLength, /* internal size */
TYPTYPE_BASE, /* type-type (base type) */
category, /* type-category */
preferred, /* is it a preferred type? */
delimiter, /* array element delimiter */
inputOid, /* input procedure */
outputOid, /* output procedure */
receiveOid, /* receive procedure */
sendOid, /* send procedure */
typmodinOid, /* typmodin procedure */
typmodoutOid, /* typmodout procedure */
analyzeOid, /* analyze procedure */
elemType, /* element type ID */
false, /* this is not an array type */
array_oid, /* array type we are about to create */
InvalidOid, /* base type ID (only for domains) */
defaultValue, /* default type value */
NULL, /* no binary form available */
byValue, /* passed by value */
alignment, /* required alignment */
storage, /* TOAST strategy */
-1, /* typMod (Domains only) */
0, /* Array Dimensions of typbasetype */
false, /* Type NOT NULL */
collation); /* type's collation */
Assert(typoid == address.objectId);
/*
* Create the array type that goes with it.
*/
array_type = makeArrayTypeName(typeName, typeNamespace);
/* alignment must be 'i' or 'd' for arrays */
alignment = (alignment == 'd') ? 'd' : 'i';
TypeCreate(array_oid, /* force assignment of this type OID */
array_type, /* type name */
typeNamespace, /* namespace */
InvalidOid, /* relation oid (n/a here) */
0, /* relation kind (ditto) */
GetUserId(), /* owner's ID */
-1, /* internal size (always varlena) */
TYPTYPE_BASE, /* type-type (base type) */
TYPCATEGORY_ARRAY, /* type-category (array) */
false, /* array types are never preferred */
delimiter, /* array element delimiter */
F_ARRAY_IN, /* input procedure */
F_ARRAY_OUT, /* output procedure */
F_ARRAY_RECV, /* receive procedure */
F_ARRAY_SEND, /* send procedure */
typmodinOid, /* typmodin procedure */
typmodoutOid, /* typmodout procedure */
F_ARRAY_TYPANALYZE, /* analyze procedure */
typoid, /* element type ID */
true, /* yes this is an array type */
InvalidOid, /* no further array type */
InvalidOid, /* base type ID */
NULL, /* never a default type value */
NULL, /* binary default isn't sent either */
false, /* never passed by value */
alignment, /* see above */
'x', /* ARRAY is always toastable */
-1, /* typMod (Domains only) */
0, /* Array dimensions of typbasetype */
false, /* Type NOT NULL */
collation); /* type's collation */
pfree(array_type);
return address;
}
/*
* Guts of type deletion.
*/
void
RemoveTypeById(Oid typeOid)
{
Relation relation;
HeapTuple tup;
relation = heap_open(TypeRelationId, RowExclusiveLock);
tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typeOid));
if (!HeapTupleIsValid(tup))
elog(ERROR, "cache lookup failed for type %u", typeOid);
CatalogTupleDelete(relation, &tup->t_self);
/*
* If it is an enum, delete the pg_enum entries too; we don't bother with
* making dependency entries for those, so it has to be done "by hand"
* here.
*/
if (((Form_pg_type) GETSTRUCT(tup))->typtype == TYPTYPE_ENUM)
EnumValuesDelete(typeOid);
/*
* If it is a range type, delete the pg_range entry too; we don't bother
* with making a dependency entry for that, so it has to be done "by hand"
* here.
*/
if (((Form_pg_type) GETSTRUCT(tup))->typtype == TYPTYPE_RANGE)
RangeDelete(typeOid);
ReleaseSysCache(tup);
heap_close(relation, RowExclusiveLock);
}
/*
* DefineDomain
* Registers a new domain.
*/
ObjectAddress
DefineDomain(CreateDomainStmt *stmt)
{
char *domainName;
char *domainArrayName;
Oid domainNamespace;
AclResult aclresult;
int16 internalLength;
Oid inputProcedure;
Oid outputProcedure;
Oid receiveProcedure;
Oid sendProcedure;
Oid analyzeProcedure;
bool byValue;
char category;
char delimiter;
char alignment;
char storage;
char typtype;
Datum datum;
bool isnull;
char *defaultValue = NULL;
char *defaultValueBin = NULL;
bool saw_default = false;
bool typNotNull = false;
bool nullDefined = false;
int32 typNDims = list_length(stmt->typeName->arrayBounds);
HeapTuple typeTup;
List *schema = stmt->constraints;
ListCell *listptr;
Oid basetypeoid;
Oid old_type_oid;
Oid domaincoll;
Oid domainArrayOid;
Form_pg_type baseType;
int32 basetypeMod;
Oid baseColl;
ObjectAddress address;
/* Convert list of names to a name and namespace */
domainNamespace = QualifiedNameGetCreationNamespace(stmt->domainname,
&domainName);
/* Check we have creation rights in target namespace */
aclresult = pg_namespace_aclcheck(domainNamespace, GetUserId(),
ACL_CREATE);
if (aclresult != ACLCHECK_OK)
aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
get_namespace_name(domainNamespace));
/*
* Check for collision with an existing type name. If there is one and
* it's an autogenerated array, we can rename it out of the way.
*/
old_type_oid = GetSysCacheOid2(TYPENAMENSP,
CStringGetDatum(domainName),
ObjectIdGetDatum(domainNamespace));
if (OidIsValid(old_type_oid))
{
if (!moveArrayTypeName(old_type_oid, domainName, domainNamespace))
ereport(ERROR,
(errcode(ERRCODE_DUPLICATE_OBJECT),
errmsg("type \"%s\" already exists", domainName)));
}
/*
* Look up the base type.
*/
typeTup = typenameType(NULL, stmt->typeName, &basetypeMod);
baseType = (Form_pg_type) GETSTRUCT(typeTup);
basetypeoid = HeapTupleGetOid(typeTup);
/*
* Base type must be a plain base type, a composite type, another domain,
* an enum or a range type. Domains over pseudotypes would create a
* security hole. (It would be shorter to code this to just check for
* pseudotypes; but it seems safer to call out the specific typtypes that
* are supported, rather than assume that all future typtypes would be
* automatically supported.)
*/
typtype = baseType->typtype;
if (typtype != TYPTYPE_BASE &&
typtype != TYPTYPE_COMPOSITE &&
typtype != TYPTYPE_DOMAIN &&
typtype != TYPTYPE_ENUM &&
typtype != TYPTYPE_RANGE)
ereport(ERROR,
(errcode(ERRCODE_DATATYPE_MISMATCH),
errmsg("\"%s\" is not a valid base type for a domain",
TypeNameToString(stmt->typeName))));
aclresult = pg_type_aclcheck(basetypeoid, GetUserId(), ACL_USAGE);
if (aclresult != ACLCHECK_OK)
aclcheck_error_type(aclresult, basetypeoid);
/*
* Identify the collation if any
*/
baseColl = baseType->typcollation;
if (stmt->collClause)
domaincoll = get_collation_oid(stmt->collClause->collname, false);
else
domaincoll = baseColl;
/* Complain if COLLATE is applied to an uncollatable type */
if (OidIsValid(domaincoll) && !OidIsValid(baseColl))
ereport(ERROR,
(errcode(ERRCODE_DATATYPE_MISMATCH),
errmsg("collations are not supported by type %s",
format_type_be(basetypeoid))));
/* passed by value */
byValue = baseType->typbyval;
/* Required Alignment */
alignment = baseType->typalign;
/* TOAST Strategy */
storage = baseType->typstorage;
/* Storage Length */
internalLength = baseType->typlen;
/* Type Category */
category = baseType->typcategory;
/* Array element Delimiter */
delimiter = baseType->typdelim;
/* I/O Functions */
inputProcedure = F_DOMAIN_IN;
outputProcedure = baseType->typoutput;
receiveProcedure = F_DOMAIN_RECV;
sendProcedure = baseType->typsend;
/* Domains never accept typmods, so no typmodin/typmodout needed */
/* Analysis function */
analyzeProcedure = baseType->typanalyze;
/* Inherited default value */
datum = SysCacheGetAttr(TYPEOID, typeTup,
Anum_pg_type_typdefault, &isnull);
if (!isnull)
defaultValue = TextDatumGetCString(datum);
/* Inherited default binary value */
datum = SysCacheGetAttr(TYPEOID, typeTup,
Anum_pg_type_typdefaultbin, &isnull);
if (!isnull)
defaultValueBin = TextDatumGetCString(datum);
/*
* Run through constraints manually to avoid the additional processing
* conducted by DefineRelation() and friends.
*/
foreach(listptr, schema)
{
Constraint *constr = lfirst(listptr);
if (!IsA(constr, Constraint))
elog(ERROR, "unrecognized node type: %d",
(int) nodeTag(constr));
switch (constr->contype)
{
case CONSTR_DEFAULT:
/*
* The inherited default value may be overridden by the user
* with the DEFAULT <expr> clause ... but only once.
*/
if (saw_default)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("multiple default expressions")));
saw_default = true;
if (constr->raw_expr)
{
ParseState *pstate;
Node *defaultExpr;
/* Create a dummy ParseState for transformExpr */
pstate = make_parsestate(NULL);
/*
* Cook the constr->raw_expr into an expression. Note:
* name is strictly for error message
*/
defaultExpr = cookDefault(pstate, constr->raw_expr,
basetypeoid,
basetypeMod,
domainName);
/*
* If the expression is just a NULL constant, we treat it
* like not having a default.
*
* Note that if the basetype is another domain, we'll see
* a CoerceToDomain expr here and not discard the default.
* This is critical because the domain default needs to be
* retained to override any default that the base domain
* might have.
*/
if (defaultExpr == NULL ||
(IsA(defaultExpr, Const) &&
((Const *) defaultExpr)->constisnull))
{
defaultValue = NULL;
defaultValueBin = NULL;
}
else
{
/*
* Expression must be stored as a nodeToString result,
* but we also require a valid textual representation
* (mainly to make life easier for pg_dump).
*/
defaultValue =
deparse_expression(defaultExpr,
NIL, false, false);
defaultValueBin = nodeToString(defaultExpr);
}
}
else
{
/* No default (can this still happen?) */
defaultValue = NULL;
defaultValueBin = NULL;
}
break;
case CONSTR_NOTNULL:
if (nullDefined && !typNotNull)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting NULL/NOT NULL constraints")));
typNotNull = true;
nullDefined = true;
break;
case CONSTR_NULL:
if (nullDefined && typNotNull)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting NULL/NOT NULL constraints")));
typNotNull = false;
nullDefined = true;
break;
case CONSTR_CHECK:
/*
* Check constraints are handled after domain creation, as
* they require the Oid of the domain; at this point we can
* only check that they're not marked NO INHERIT, because that
* would be bogus.
*/
if (constr->is_no_inherit)
ereport(ERROR,
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
errmsg("check constraints for domains cannot be marked NO INHERIT")));
break;
/*
* All else are error cases
*/
case CONSTR_UNIQUE:
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("unique constraints not possible for domains")));
break;
case CONSTR_PRIMARY:
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("primary key constraints not possible for domains")));
break;
case CONSTR_EXCLUSION:
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("exclusion constraints not possible for domains")));
break;
case CONSTR_FOREIGN:
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("foreign key constraints not possible for domains")));
break;
case CONSTR_ATTR_DEFERRABLE:
case CONSTR_ATTR_NOT_DEFERRABLE:
case CONSTR_ATTR_DEFERRED:
case CONSTR_ATTR_IMMEDIATE:
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("specifying constraint deferrability not supported for domains")));
break;
default:
elog(ERROR, "unrecognized constraint subtype: %d",
(int) constr->contype);
break;
}
}
/* Allocate OID for array type */
domainArrayOid = AssignTypeArrayOid();
/*
* Have TypeCreate do all the real work.
*/
address =
TypeCreate(InvalidOid, /* no predetermined type OID */
domainName, /* type name */
domainNamespace, /* namespace */
InvalidOid, /* relation oid (n/a here) */
0, /* relation kind (ditto) */
GetUserId(), /* owner's ID */
internalLength, /* internal size */
TYPTYPE_DOMAIN, /* type-type (domain type) */
category, /* type-category */
false, /* domain types are never preferred */
delimiter, /* array element delimiter */
inputProcedure, /* input procedure */
outputProcedure, /* output procedure */
receiveProcedure, /* receive procedure */
sendProcedure, /* send procedure */
InvalidOid, /* typmodin procedure - none */
InvalidOid, /* typmodout procedure - none */
analyzeProcedure, /* analyze procedure */
InvalidOid, /* no array element type */
false, /* this isn't an array */
domainArrayOid, /* array type we are about to create */
basetypeoid, /* base type ID */
defaultValue, /* default type value (text) */
defaultValueBin, /* default type value (binary) */
byValue, /* passed by value */
alignment, /* required alignment */
storage, /* TOAST strategy */
basetypeMod, /* typeMod value */
typNDims, /* Array dimensions for base type */
typNotNull, /* Type NOT NULL */
domaincoll); /* type's collation */
/*
* Create the array type that goes with it.
*/
domainArrayName = makeArrayTypeName(domainName, domainNamespace);
/* alignment must be 'i' or 'd' for arrays */
alignment = (alignment == 'd') ? 'd' : 'i';
TypeCreate(domainArrayOid, /* force assignment of this type OID */
domainArrayName, /* type name */
domainNamespace, /* namespace */
InvalidOid, /* relation oid (n/a here) */
0, /* relation kind (ditto) */
GetUserId(), /* owner's ID */
-1, /* internal size (always varlena) */
TYPTYPE_BASE, /* type-type (base type) */
TYPCATEGORY_ARRAY, /* type-category (array) */
false, /* array types are never preferred */
delimiter, /* array element delimiter */
F_ARRAY_IN, /* input procedure */
F_ARRAY_OUT, /* output procedure */
F_ARRAY_RECV, /* receive procedure */
F_ARRAY_SEND, /* send procedure */
InvalidOid, /* typmodin procedure - none */
InvalidOid, /* typmodout procedure - none */
F_ARRAY_TYPANALYZE, /* analyze procedure */
address.objectId, /* element type ID */
true, /* yes this is an array type */
InvalidOid, /* no further array type */
InvalidOid, /* base type ID */
NULL, /* never a default type value */
NULL, /* binary default isn't sent either */
false, /* never passed by value */
alignment, /* see above */
'x', /* ARRAY is always toastable */
-1, /* typMod (Domains only) */
0, /* Array dimensions of typbasetype */
false, /* Type NOT NULL */
domaincoll); /* type's collation */
pfree(domainArrayName);
/*
* Process constraints which refer to the domain ID returned by TypeCreate
*/
foreach(listptr, schema)
{
Constraint *constr = lfirst(listptr);
/* it must be a Constraint, per check above */
switch (constr->contype)
{
case CONSTR_CHECK:
domainAddConstraint(address.objectId, domainNamespace,
basetypeoid, basetypeMod,
constr, domainName, NULL);
break;
/* Other constraint types were fully processed above */
default:
break;
}
/* CCI so we can detect duplicate constraint names */
CommandCounterIncrement();
}
/*
* Now we can clean up.
*/
ReleaseSysCache(typeTup);
return address;
}
/*
* DefineEnum
* Registers a new enum.
*/
ObjectAddress
DefineEnum(CreateEnumStmt *stmt)
{
char *enumName;
char *enumArrayName;
Oid enumNamespace;
AclResult aclresult;
Oid old_type_oid;
Oid enumArrayOid;
ObjectAddress enumTypeAddr;
/* Convert list of names to a name and namespace */
enumNamespace = QualifiedNameGetCreationNamespace(stmt->typeName,
&enumName);
/* Check we have creation rights in target namespace */
aclresult = pg_namespace_aclcheck(enumNamespace, GetUserId(), ACL_CREATE);
if (aclresult != ACLCHECK_OK)
aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
get_namespace_name(enumNamespace));
/*
* Check for collision with an existing type name. If there is one and
* it's an autogenerated array, we can rename it out of the way.
*/
old_type_oid = GetSysCacheOid2(TYPENAMENSP,
CStringGetDatum(enumName),
ObjectIdGetDatum(enumNamespace));
if (OidIsValid(old_type_oid))
{
if (!moveArrayTypeName(old_type_oid, enumName, enumNamespace))
ereport(ERROR,
(errcode(ERRCODE_DUPLICATE_OBJECT),
errmsg("type \"%s\" already exists", enumName)));
}
/* Allocate OID for array type */
enumArrayOid = AssignTypeArrayOid();
/* Create the pg_type entry */
enumTypeAddr =
TypeCreate(InvalidOid, /* no predetermined type OID */
enumName, /* type name */
enumNamespace, /* namespace */
InvalidOid, /* relation oid (n/a here) */
0, /* relation kind (ditto) */
GetUserId(), /* owner's ID */
sizeof(Oid), /* internal size */
TYPTYPE_ENUM, /* type-type (enum type) */
TYPCATEGORY_ENUM, /* type-category (enum type) */
false, /* enum types are never preferred */
DEFAULT_TYPDELIM, /* array element delimiter */
F_ENUM_IN, /* input procedure */
F_ENUM_OUT, /* output procedure */
F_ENUM_RECV, /* receive procedure */
F_ENUM_SEND, /* send procedure */
InvalidOid, /* typmodin procedure - none */
InvalidOid, /* typmodout procedure - none */
InvalidOid, /* analyze procedure - default */
InvalidOid, /* element type ID */
false, /* this is not an array type */
enumArrayOid, /* array type we are about to create */
InvalidOid, /* base type ID (only for domains) */
NULL, /* never a default type value */
NULL, /* binary default isn't sent either */
true, /* always passed by value */
'i', /* int alignment */
'p', /* TOAST strategy always plain */
-1, /* typMod (Domains only) */
0, /* Array dimensions of typbasetype */
false, /* Type NOT NULL */
InvalidOid); /* type's collation */
/* Enter the enum's values into pg_enum */
EnumValuesCreate(enumTypeAddr.objectId, stmt->vals);
/*
* Create the array type that goes with it.
*/
enumArrayName = makeArrayTypeName(enumName, enumNamespace);
TypeCreate(enumArrayOid, /* force assignment of this type OID */
enumArrayName, /* type name */
enumNamespace, /* namespace */
InvalidOid, /* relation oid (n/a here) */
0, /* relation kind (ditto) */
GetUserId(), /* owner's ID */
-1, /* internal size (always varlena) */
TYPTYPE_BASE, /* type-type (base type) */
TYPCATEGORY_ARRAY, /* type-category (array) */
false, /* array types are never preferred */
DEFAULT_TYPDELIM, /* array element delimiter */
F_ARRAY_IN, /* input procedure */
F_ARRAY_OUT, /* output procedure */
F_ARRAY_RECV, /* receive procedure */
F_ARRAY_SEND, /* send procedure */
InvalidOid, /* typmodin procedure - none */
InvalidOid, /* typmodout procedure - none */
F_ARRAY_TYPANALYZE, /* analyze procedure */
enumTypeAddr.objectId, /* element type ID */
true, /* yes this is an array type */
InvalidOid, /* no further array type */
InvalidOid, /* base type ID */
NULL, /* never a default type value */
NULL, /* binary default isn't sent either */
false, /* never passed by value */
'i', /* enums have align i, so do their arrays */
'x', /* ARRAY is always toastable */
-1, /* typMod (Domains only) */
0, /* Array dimensions of typbasetype */
false, /* Type NOT NULL */
InvalidOid); /* type's collation */
pfree(enumArrayName);
return enumTypeAddr;
}
/*
* AlterEnum
* ALTER TYPE on an enum.
*/
ObjectAddress
AlterEnum(AlterEnumStmt *stmt, bool isTopLevel)
{
Oid enum_type_oid;
TypeName *typename;
HeapTuple tup;
ObjectAddress address;
/* Make a TypeName so we can use standard type lookup machinery */
typename = makeTypeNameFromNameList(stmt->typeName);
enum_type_oid = typenameTypeId(NULL, typename);
tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(enum_type_oid));
if (!HeapTupleIsValid(tup))
elog(ERROR, "cache lookup failed for type %u", enum_type_oid);
/* Check it's an enum and check user has permission to ALTER the enum */
checkEnumOwner(tup);
if (stmt->oldVal)
{
/* Rename an existing label */
RenameEnumLabel(enum_type_oid, stmt->oldVal, stmt->newVal);
}
else
{
/* Add a new label */
/*
* Ordinarily we disallow adding values within transaction blocks,
* because we can't cope with enum OID values getting into indexes and
* then having their defining pg_enum entries go away. However, it's
* okay if the enum type was created in the current transaction, since
* then there can be no such indexes that wouldn't themselves go away
* on rollback. (We support this case because pg_dump
* --binary-upgrade needs it.) We test this by seeing if the pg_type
* row has xmin == current XID and is not HEAP_UPDATED. If it is
* HEAP_UPDATED, we can't be sure whether the type was created or only
* modified in this xact. So we are disallowing some cases that could
* theoretically be safe; but fortunately pg_dump only needs the
* simplest case.
*/
if (HeapTupleHeaderGetXmin(tup->t_data) == GetCurrentTransactionId() &&
!(tup->t_data->t_infomask & HEAP_UPDATED))
/* safe to do inside transaction block */ ;
else
PreventTransactionChain(isTopLevel, "ALTER TYPE ... ADD");
AddEnumLabel(enum_type_oid, stmt->newVal,
stmt->newValNeighbor, stmt->newValIsAfter,
stmt->skipIfNewValExists);
}
InvokeObjectPostAlterHook(TypeRelationId, enum_type_oid, 0);
ObjectAddressSet(address, TypeRelationId, enum_type_oid);
ReleaseSysCache(tup);
return address;
}
/*
* checkEnumOwner
*
* Check that the type is actually an enum and that the current user
* has permission to do ALTER TYPE on it. Throw an error if not.
*/
static void
checkEnumOwner(HeapTuple tup)
{
Form_pg_type typTup = (Form_pg_type) GETSTRUCT(tup);
/* Check that this is actually an enum */
if (typTup->typtype != TYPTYPE_ENUM)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("%s is not an enum",
format_type_be(HeapTupleGetOid(tup)))));
/* Permission check: must own type */
if (!pg_type_ownercheck(HeapTupleGetOid(tup), GetUserId()))
aclcheck_error_type(ACLCHECK_NOT_OWNER, HeapTupleGetOid(tup));
}
/*
* DefineRange
* Registers a new range type.
*/
ObjectAddress
DefineRange(CreateRangeStmt *stmt)
{
char *typeName;
Oid typeNamespace;
Oid typoid;
char *rangeArrayName;
Oid rangeArrayOid;
Oid rangeSubtype = InvalidOid;
List *rangeSubOpclassName = NIL;
List *rangeCollationName = NIL;
List *rangeCanonicalName = NIL;
List *rangeSubtypeDiffName = NIL;
Oid rangeSubOpclass;
Oid rangeCollation;
regproc rangeCanonical;
regproc rangeSubtypeDiff;
int16 subtyplen;
bool subtypbyval;
char subtypalign;
char alignment;
AclResult aclresult;
ListCell *lc;
ObjectAddress address;
/* Convert list of names to a name and namespace */
typeNamespace = QualifiedNameGetCreationNamespace(stmt->typeName,
&typeName);
/* Check we have creation rights in target namespace */
aclresult = pg_namespace_aclcheck(typeNamespace, GetUserId(), ACL_CREATE);
if (aclresult != ACLCHECK_OK)
aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
get_namespace_name(typeNamespace));
/*
* Look to see if type already exists.
*/
typoid = GetSysCacheOid2(TYPENAMENSP,
CStringGetDatum(typeName),
ObjectIdGetDatum(typeNamespace));
/*
* If it's not a shell, see if it's an autogenerated array type, and if so
* rename it out of the way.
*/
if (OidIsValid(typoid) && get_typisdefined(typoid))
{
if (moveArrayTypeName(typoid, typeName, typeNamespace))
typoid = InvalidOid;
else
ereport(ERROR,
(errcode(ERRCODE_DUPLICATE_OBJECT),
errmsg("type \"%s\" already exists", typeName)));
}
/*
* If it doesn't exist, create it as a shell, so that the OID is known for
* use in the range function definitions.
*/
if (!OidIsValid(typoid))
{
address = TypeShellMake(typeName, typeNamespace, GetUserId());
typoid = address.objectId;
/* Make new shell type visible for modification below */
CommandCounterIncrement();
}
/* Extract the parameters from the parameter list */
foreach(lc, stmt->params)
{
DefElem *defel = (DefElem *) lfirst(lc);
if (pg_strcasecmp(defel->defname, "subtype") == 0)
{
if (OidIsValid(rangeSubtype))
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting or redundant options")));
/* we can look up the subtype name immediately */
rangeSubtype = typenameTypeId(NULL, defGetTypeName(defel));
}
else if (pg_strcasecmp(defel->defname, "subtype_opclass") == 0)
{
if (rangeSubOpclassName != NIL)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting or redundant options")));
rangeSubOpclassName = defGetQualifiedName(defel);
}
else if (pg_strcasecmp(defel->defname, "collation") == 0)
{
if (rangeCollationName != NIL)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting or redundant options")));
rangeCollationName = defGetQualifiedName(defel);
}
else if (pg_strcasecmp(defel->defname, "canonical") == 0)
{
if (rangeCanonicalName != NIL)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting or redundant options")));
rangeCanonicalName = defGetQualifiedName(defel);
}
else if (pg_strcasecmp(defel->defname, "subtype_diff") == 0)
{
if (rangeSubtypeDiffName != NIL)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting or redundant options")));
rangeSubtypeDiffName = defGetQualifiedName(defel);
}
else
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("type attribute \"%s\" not recognized",
defel->defname)));
}
/* Must have a subtype */
if (!OidIsValid(rangeSubtype))
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("type attribute \"subtype\" is required")));
/* disallow ranges of pseudotypes */
if (get_typtype(rangeSubtype) == TYPTYPE_PSEUDO)
ereport(ERROR,
(errcode(ERRCODE_DATATYPE_MISMATCH),
errmsg("range subtype cannot be %s",
format_type_be(rangeSubtype))));
/* Identify subopclass */
rangeSubOpclass = findRangeSubOpclass(rangeSubOpclassName, rangeSubtype);
/* Identify collation to use, if any */
if (type_is_collatable(rangeSubtype))
{
if (rangeCollationName != NIL)
rangeCollation = get_collation_oid(rangeCollationName, false);
else
rangeCollation = get_typcollation(rangeSubtype);
}
else
{
if (rangeCollationName != NIL)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("range collation specified but subtype does not support collation")));
rangeCollation = InvalidOid;
}
/* Identify support functions, if provided */
if (rangeCanonicalName != NIL)
rangeCanonical = findRangeCanonicalFunction(rangeCanonicalName,
typoid);
else
rangeCanonical = InvalidOid;
if (rangeSubtypeDiffName != NIL)
rangeSubtypeDiff = findRangeSubtypeDiffFunction(rangeSubtypeDiffName,
rangeSubtype);
else
rangeSubtypeDiff = InvalidOid;
get_typlenbyvalalign(rangeSubtype,
&subtyplen, &subtypbyval, &subtypalign);
/* alignment must be 'i' or 'd' for ranges */
alignment = (subtypalign == 'd') ? 'd' : 'i';
/* Allocate OID for array type */
rangeArrayOid = AssignTypeArrayOid();
/* Create the pg_type entry */
address =
TypeCreate(InvalidOid, /* no predetermined type OID */
typeName, /* type name */
typeNamespace, /* namespace */
InvalidOid, /* relation oid (n/a here) */
0, /* relation kind (ditto) */
GetUserId(), /* owner's ID */
-1, /* internal size (always varlena) */
TYPTYPE_RANGE, /* type-type (range type) */
TYPCATEGORY_RANGE, /* type-category (range type) */
false, /* range types are never preferred */
DEFAULT_TYPDELIM, /* array element delimiter */
F_RANGE_IN, /* input procedure */
F_RANGE_OUT, /* output procedure */
F_RANGE_RECV, /* receive procedure */
F_RANGE_SEND, /* send procedure */
InvalidOid, /* typmodin procedure - none */
InvalidOid, /* typmodout procedure - none */
F_RANGE_TYPANALYZE, /* analyze procedure */
InvalidOid, /* element type ID - none */
false, /* this is not an array type */
rangeArrayOid, /* array type we are about to create */
InvalidOid, /* base type ID (only for domains) */
NULL, /* never a default type value */
NULL, /* no binary form available either */
false, /* never passed by value */
alignment, /* alignment */
'x', /* TOAST strategy (always extended) */
-1, /* typMod (Domains only) */
0, /* Array dimensions of typbasetype */
false, /* Type NOT NULL */
InvalidOid); /* type's collation (ranges never have one) */
Assert(typoid == address.objectId);
/* Create the entry in pg_range */
RangeCreate(typoid, rangeSubtype, rangeCollation, rangeSubOpclass,
rangeCanonical, rangeSubtypeDiff);
/*
* Create the array type that goes with it.
*/
rangeArrayName = makeArrayTypeName(typeName, typeNamespace);
TypeCreate(rangeArrayOid, /* force assignment of this type OID */
rangeArrayName, /* type name */
typeNamespace, /* namespace */
InvalidOid, /* relation oid (n/a here) */
0, /* relation kind (ditto) */
GetUserId(), /* owner's ID */
-1, /* internal size (always varlena) */
TYPTYPE_BASE, /* type-type (base type) */
TYPCATEGORY_ARRAY, /* type-category (array) */
false, /* array types are never preferred */
DEFAULT_TYPDELIM, /* array element delimiter */
F_ARRAY_IN, /* input procedure */
F_ARRAY_OUT, /* output procedure */
F_ARRAY_RECV, /* receive procedure */
F_ARRAY_SEND, /* send procedure */
InvalidOid, /* typmodin procedure - none */
InvalidOid, /* typmodout procedure - none */
F_ARRAY_TYPANALYZE, /* analyze procedure */
typoid, /* element type ID */
true, /* yes this is an array type */
InvalidOid, /* no further array type */
InvalidOid, /* base type ID */
NULL, /* never a default type value */
NULL, /* binary default isn't sent either */
false, /* never passed by value */
alignment, /* alignment - same as range's */
'x', /* ARRAY is always toastable */
-1, /* typMod (Domains only) */
0, /* Array dimensions of typbasetype */
false, /* Type NOT NULL */
InvalidOid); /* typcollation */
pfree(rangeArrayName);
/* And create the constructor functions for this range type */
makeRangeConstructors(typeName, typeNamespace, typoid, rangeSubtype);
return address;
}
/*
* Because there may exist several range types over the same subtype, the
* range type can't be uniquely determined from the subtype. So it's
* impossible to define a polymorphic constructor; we have to generate new
* constructor functions explicitly for each range type.
*
* We actually define 4 functions, with 0 through 3 arguments. This is just
* to offer more convenience for the user.
*/
static void
makeRangeConstructors(const char *name, Oid namespace,
Oid rangeOid, Oid subtype)
{
static const char *const prosrc[2] = {"range_constructor2",
"range_constructor3"};
static const int pronargs[2] = {2, 3};
Oid constructorArgTypes[3];
ObjectAddress myself,
referenced;
int i;
constructorArgTypes[0] = subtype;
constructorArgTypes[1] = subtype;
constructorArgTypes[2] = TEXTOID;
referenced.classId = TypeRelationId;
referenced.objectId = rangeOid;
referenced.objectSubId = 0;
for (i = 0; i < lengthof(prosrc); i++)
{
oidvector *constructorArgTypesVector;
constructorArgTypesVector = buildoidvector(constructorArgTypes,
pronargs[i]);
myself = ProcedureCreate(name, /* name: same as range type */
namespace, /* namespace */
false, /* replace */
false, /* returns set */
rangeOid, /* return type */
BOOTSTRAP_SUPERUSERID, /* proowner */
INTERNALlanguageId, /* language */
F_FMGR_INTERNAL_VALIDATOR, /* language validator */
prosrc[i], /* prosrc */
NULL, /* probin */
false, /* isAgg */
false, /* isWindowFunc */
false, /* security_definer */
false, /* leakproof */
false, /* isStrict */
PROVOLATILE_IMMUTABLE, /* volatility */
PROPARALLEL_SAFE, /* parallel safety */
constructorArgTypesVector, /* parameterTypes */
PointerGetDatum(NULL), /* allParameterTypes */
PointerGetDatum(NULL), /* parameterModes */
PointerGetDatum(NULL), /* parameterNames */
NIL, /* parameterDefaults */
PointerGetDatum(NULL), /* trftypes */
PointerGetDatum(NULL), /* proconfig */
1.0, /* procost */
0.0); /* prorows */
/*
* Make the constructors internally-dependent on the range type so
* that they go away silently when the type is dropped. Note that
* pg_dump depends on this choice to avoid dumping the constructors.
*/
recordDependencyOn(&myself, &referenced, DEPENDENCY_INTERNAL);
}
}
/*
* Find suitable I/O functions for a type.
*
* typeOid is the type's OID (which will already exist, if only as a shell
* type).
*/
static Oid
findTypeInputFunction(List *procname, Oid typeOid)
{
Oid argList[3];
Oid procOid;
/*
* Input functions can take a single argument of type CSTRING, or three
* arguments (string, typioparam OID, typmod).
*
* For backwards compatibility we allow OPAQUE in place of CSTRING; if we
* see this, we issue a warning and fix up the pg_proc entry.
*/
argList[0] = CSTRINGOID;
procOid = LookupFuncName(procname, 1, argList, true);
if (OidIsValid(procOid))
return procOid;
argList[1] = OIDOID;
argList[2] = INT4OID;
procOid = LookupFuncName(procname, 3, argList, true);
if (OidIsValid(procOid))
return procOid;
/* No luck, try it with OPAQUE */
argList[0] = OPAQUEOID;
procOid = LookupFuncName(procname, 1, argList, true);
if (!OidIsValid(procOid))
{
argList[1] = OIDOID;
argList[2] = INT4OID;
procOid = LookupFuncName(procname, 3, argList, true);
}
if (OidIsValid(procOid))
{
/* Found, but must complain and fix the pg_proc entry */
ereport(WARNING,
(errmsg("changing argument type of function %s from \"opaque\" to \"cstring\"",
NameListToString(procname))));
SetFunctionArgType(procOid, 0, CSTRINGOID);
/*
* Need CommandCounterIncrement since DefineType will likely try to
* alter the pg_proc tuple again.
*/
CommandCounterIncrement();
return procOid;
}
/* Use CSTRING (preferred) in the error message */
argList[0] = CSTRINGOID;
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_FUNCTION),
errmsg("function %s does not exist",
func_signature_string(procname, 1, NIL, argList))));
return InvalidOid; /* keep compiler quiet */
}
static Oid
findTypeOutputFunction(List *procname, Oid typeOid)
{
Oid argList[1];
Oid procOid;
/*
* Output functions can take a single argument of the type.
*
* For backwards compatibility we allow OPAQUE in place of the actual type
* name; if we see this, we issue a warning and fix up the pg_proc entry.
*/
argList[0] = typeOid;
procOid = LookupFuncName(procname, 1, argList, true);
if (OidIsValid(procOid))
return procOid;
/* No luck, try it with OPAQUE */
argList[0] = OPAQUEOID;
procOid = LookupFuncName(procname, 1, argList, true);
if (OidIsValid(procOid))
{
/* Found, but must complain and fix the pg_proc entry */
ereport(WARNING,
(errmsg("changing argument type of function %s from \"opaque\" to %s",
NameListToString(procname), format_type_be(typeOid))));
SetFunctionArgType(procOid, 0, typeOid);
/*
* Need CommandCounterIncrement since DefineType will likely try to
* alter the pg_proc tuple again.
*/
CommandCounterIncrement();
return procOid;
}
/* Use type name, not OPAQUE, in the failure message. */
argList[0] = typeOid;
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_FUNCTION),
errmsg("function %s does not exist",
func_signature_string(procname, 1, NIL, argList))));
return InvalidOid; /* keep compiler quiet */
}
static Oid
findTypeReceiveFunction(List *procname, Oid typeOid)
{
Oid argList[3];
Oid procOid;
/*
* Receive functions can take a single argument of type INTERNAL, or three
* arguments (internal, typioparam OID, typmod).
*/
argList[0] = INTERNALOID;
procOid = LookupFuncName(procname, 1, argList, true);
if (OidIsValid(procOid))
return procOid;
argList[1] = OIDOID;
argList[2] = INT4OID;
procOid = LookupFuncName(procname, 3, argList, true);
if (OidIsValid(procOid))
return procOid;
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_FUNCTION),
errmsg("function %s does not exist",
func_signature_string(procname, 1, NIL, argList))));
return InvalidOid; /* keep compiler quiet */
}
static Oid
findTypeSendFunction(List *procname, Oid typeOid)
{
Oid argList[1];
Oid procOid;
/*
* Send functions can take a single argument of the type.
*/
argList[0] = typeOid;
procOid = LookupFuncName(procname, 1, argList, true);
if (OidIsValid(procOid))
return procOid;
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_FUNCTION),
errmsg("function %s does not exist",
func_signature_string(procname, 1, NIL, argList))));
return InvalidOid; /* keep compiler quiet */
}
static Oid
findTypeTypmodinFunction(List *procname)
{
Oid argList[1];
Oid procOid;
/*
* typmodin functions always take one cstring[] argument and return int4.
*/
argList[0] = CSTRINGARRAYOID;
procOid = LookupFuncName(procname, 1, argList, true);
if (!OidIsValid(procOid))
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_FUNCTION),
errmsg("function %s does not exist",
func_signature_string(procname, 1, NIL, argList))));
if (get_func_rettype(procOid) != INT4OID)
ereport(ERROR,
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
errmsg("typmod_in function %s must return type %s",
NameListToString(procname), "integer")));
return procOid;
}
static Oid
findTypeTypmodoutFunction(List *procname)
{
Oid argList[1];
Oid procOid;
/*
* typmodout functions always take one int4 argument and return cstring.
*/
argList[0] = INT4OID;
procOid = LookupFuncName(procname, 1, argList, true);
if (!OidIsValid(procOid))
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_FUNCTION),
errmsg("function %s does not exist",
func_signature_string(procname, 1, NIL, argList))));
if (get_func_rettype(procOid) != CSTRINGOID)
ereport(ERROR,
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
errmsg("typmod_out function %s must return type %s",
NameListToString(procname), "cstring")));
return procOid;
}
static Oid
findTypeAnalyzeFunction(List *procname, Oid typeOid)
{
Oid argList[1];
Oid procOid;
/*
* Analyze functions always take one INTERNAL argument and return bool.
*/
argList[0] = INTERNALOID;
procOid = LookupFuncName(procname, 1, argList, true);
if (!OidIsValid(procOid))
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_FUNCTION),
errmsg("function %s does not exist",
func_signature_string(procname, 1, NIL, argList))));
if (get_func_rettype(procOid) != BOOLOID)
ereport(ERROR,
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
errmsg("type analyze function %s must return type %s",
NameListToString(procname), "boolean")));
return procOid;
}
/*
* Find suitable support functions and opclasses for a range type.
*/
/*
* Find named btree opclass for subtype, or default btree opclass if
* opcname is NIL.
*/
static Oid
findRangeSubOpclass(List *opcname, Oid subtype)
{
Oid opcid;
Oid opInputType;
if (opcname != NIL)
{
opcid = get_opclass_oid(BTREE_AM_OID, opcname, false);
/*
* Verify that the operator class accepts this datatype. Note we will
* accept binary compatibility.
*/
opInputType = get_opclass_input_type(opcid);
if (!IsBinaryCoercible(subtype, opInputType))
ereport(ERROR,
(errcode(ERRCODE_DATATYPE_MISMATCH),
errmsg("operator class \"%s\" does not accept data type %s",
NameListToString(opcname),
format_type_be(subtype))));
}
else
{
opcid = GetDefaultOpClass(subtype, BTREE_AM_OID);
if (!OidIsValid(opcid))
{
/* We spell the error message identically to GetIndexOpClass */
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_OBJECT),
errmsg("data type %s has no default operator class for access method \"%s\"",
format_type_be(subtype), "btree"),
errhint("You must specify an operator class for the range type or define a default operator class for the subtype.")));
}
}
return opcid;
}
static Oid
findRangeCanonicalFunction(List *procname, Oid typeOid)
{
Oid argList[1];
Oid procOid;
AclResult aclresult;
/*
* Range canonical functions must take and return the range type, and must
* be immutable.
*/
argList[0] = typeOid;
procOid = LookupFuncName(procname, 1, argList, true);
if (!OidIsValid(procOid))
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_FUNCTION),
errmsg("function %s does not exist",
func_signature_string(procname, 1, NIL, argList))));
if (get_func_rettype(procOid) != typeOid)
ereport(ERROR,
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
errmsg("range canonical function %s must return range type",
func_signature_string(procname, 1, NIL, argList))));
if (func_volatile(procOid) != PROVOLATILE_IMMUTABLE)
ereport(ERROR,
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
errmsg("range canonical function %s must be immutable",
func_signature_string(procname, 1, NIL, argList))));
/* Also, range type's creator must have permission to call function */
aclresult = pg_proc_aclcheck(procOid, GetUserId(), ACL_EXECUTE);
if (aclresult != ACLCHECK_OK)
aclcheck_error(aclresult, ACL_KIND_PROC, get_func_name(procOid));
return procOid;
}
static Oid
findRangeSubtypeDiffFunction(List *procname, Oid subtype)
{
Oid argList[2];
Oid procOid;
AclResult aclresult;
/*
* Range subtype diff functions must take two arguments of the subtype,
* must return float8, and must be immutable.
*/
argList[0] = subtype;
argList[1] = subtype;
procOid = LookupFuncName(procname, 2, argList, true);
if (!OidIsValid(procOid))
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_FUNCTION),
errmsg("function %s does not exist",
func_signature_string(procname, 2, NIL, argList))));
if (get_func_rettype(procOid) != FLOAT8OID)
ereport(ERROR,
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
errmsg("range subtype diff function %s must return type %s",
func_signature_string(procname, 2, NIL, argList),
"double precision")));
if (func_volatile(procOid) != PROVOLATILE_IMMUTABLE)
ereport(ERROR,
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
errmsg("range subtype diff function %s must be immutable",
func_signature_string(procname, 2, NIL, argList))));
/* Also, range type's creator must have permission to call function */
aclresult = pg_proc_aclcheck(procOid, GetUserId(), ACL_EXECUTE);
if (aclresult != ACLCHECK_OK)
aclcheck_error(aclresult, ACL_KIND_PROC, get_func_name(procOid));
return procOid;
}
/*
* AssignTypeArrayOid
*
* Pre-assign the type's array OID for use in pg_type.typarray
*/
Oid
AssignTypeArrayOid(void)
{
Oid type_array_oid;
/* Use binary-upgrade override for pg_type.typarray? */
if (IsBinaryUpgrade)
{
if (!OidIsValid(binary_upgrade_next_array_pg_type_oid))
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("pg_type array OID value not set when in binary upgrade mode")));
type_array_oid = binary_upgrade_next_array_pg_type_oid;
binary_upgrade_next_array_pg_type_oid = InvalidOid;
}
else
{
Relation pg_type = heap_open(TypeRelationId, AccessShareLock);
type_array_oid = GetNewOid(pg_type);
heap_close(pg_type, AccessShareLock);
}
return type_array_oid;
}
/*-------------------------------------------------------------------
* DefineCompositeType
*
* Create a Composite Type relation.
* `DefineRelation' does all the work, we just provide the correct
* arguments!
*
* If the relation already exists, then 'DefineRelation' will abort
* the xact...
*
* Return type is the new type's object address.
*-------------------------------------------------------------------
*/
ObjectAddress
DefineCompositeType(RangeVar *typevar, List *coldeflist)
{
CreateStmt *createStmt = makeNode(CreateStmt);
Oid old_type_oid;
Oid typeNamespace;
ObjectAddress address;
/*
* now set the parameters for keys/inheritance etc. All of these are
* uninteresting for composite types...
*/
createStmt->relation = typevar;
createStmt->tableElts = coldeflist;
createStmt->inhRelations = NIL;
createStmt->constraints = NIL;
createStmt->options = NIL;
createStmt->oncommit = ONCOMMIT_NOOP;
createStmt->tablespacename = NULL;
createStmt->if_not_exists = false;
/*
* Check for collision with an existing type name. If there is one and
* it's an autogenerated array, we can rename it out of the way. This
* check is here mainly to get a better error message about a "type"
* instead of below about a "relation".
*/
typeNamespace = RangeVarGetAndCheckCreationNamespace(createStmt->relation,
NoLock, NULL);
RangeVarAdjustRelationPersistence(createStmt->relation, typeNamespace);
old_type_oid =
GetSysCacheOid2(TYPENAMENSP,
CStringGetDatum(createStmt->relation->relname),
ObjectIdGetDatum(typeNamespace));
if (OidIsValid(old_type_oid))
{
if (!moveArrayTypeName(old_type_oid, createStmt->relation->relname, typeNamespace))
ereport(ERROR,
(errcode(ERRCODE_DUPLICATE_OBJECT),
errmsg("type \"%s\" already exists", createStmt->relation->relname)));
}
/*
* Finally create the relation. This also creates the type.
*/
DefineRelation(createStmt, RELKIND_COMPOSITE_TYPE, InvalidOid, &address,
NULL);
return address;
}
/*
* AlterDomainDefault
*
* Routine implementing ALTER DOMAIN SET/DROP DEFAULT statements.
*
* Returns ObjectAddress of the modified domain.
*/
ObjectAddress
AlterDomainDefault(List *names, Node *defaultRaw)
{
TypeName *typename;
Oid domainoid;
HeapTuple tup;
ParseState *pstate;
Relation rel;
char *defaultValue;
Node *defaultExpr = NULL; /* NULL if no default specified */
Datum new_record[Natts_pg_type];
bool new_record_nulls[Natts_pg_type];
bool new_record_repl[Natts_pg_type];
HeapTuple newtuple;
Form_pg_type typTup;
ObjectAddress address;
/* Make a TypeName so we can use standard type lookup machinery */
typename = makeTypeNameFromNameList(names);
domainoid = typenameTypeId(NULL, typename);
/* Look up the domain in the type table */
rel = heap_open(TypeRelationId, RowExclusiveLock);
tup = SearchSysCacheCopy1(TYPEOID, ObjectIdGetDatum(domainoid));
if (!HeapTupleIsValid(tup))
elog(ERROR, "cache lookup failed for type %u", domainoid);
typTup = (Form_pg_type) GETSTRUCT(tup);
/* Check it's a domain and check user has permission for ALTER DOMAIN */
checkDomainOwner(tup);
/* Setup new tuple */
MemSet(new_record, (Datum) 0, sizeof(new_record));
MemSet(new_record_nulls, false, sizeof(new_record_nulls));
MemSet(new_record_repl, false, sizeof(new_record_repl));
/* Store the new default into the tuple */
if (defaultRaw)
{
/* Create a dummy ParseState for transformExpr */
pstate = make_parsestate(NULL);
/*
* Cook the colDef->raw_expr into an expression. Note: Name is
* strictly for error message
*/
defaultExpr = cookDefault(pstate, defaultRaw,
typTup->typbasetype,
typTup->typtypmod,
NameStr(typTup->typname));
/*
* If the expression is just a NULL constant, we treat the command
* like ALTER ... DROP DEFAULT. (But see note for same test in
* DefineDomain.)
*/
if (defaultExpr == NULL ||
(IsA(defaultExpr, Const) &&((Const *) defaultExpr)->constisnull))
{
/* Default is NULL, drop it */
new_record_nulls[Anum_pg_type_typdefaultbin - 1] = true;
new_record_repl[Anum_pg_type_typdefaultbin - 1] = true;
new_record_nulls[Anum_pg_type_typdefault - 1] = true;
new_record_repl[Anum_pg_type_typdefault - 1] = true;
}
else
{
/*
* Expression must be stored as a nodeToString result, but we also
* require a valid textual representation (mainly to make life
* easier for pg_dump).
*/
defaultValue = deparse_expression(defaultExpr,
NIL, false, false);
/*
* Form an updated tuple with the new default and write it back.
*/
new_record[Anum_pg_type_typdefaultbin - 1] = CStringGetTextDatum(nodeToString(defaultExpr));
new_record_repl[Anum_pg_type_typdefaultbin - 1] = true;
new_record[Anum_pg_type_typdefault - 1] = CStringGetTextDatum(defaultValue);
new_record_repl[Anum_pg_type_typdefault - 1] = true;
}
}
else
{
/* ALTER ... DROP DEFAULT */
new_record_nulls[Anum_pg_type_typdefaultbin - 1] = true;
new_record_repl[Anum_pg_type_typdefaultbin - 1] = true;
new_record_nulls[Anum_pg_type_typdefault - 1] = true;
new_record_repl[Anum_pg_type_typdefault - 1] = true;
}
newtuple = heap_modify_tuple(tup, RelationGetDescr(rel),
new_record, new_record_nulls,
new_record_repl);
CatalogTupleUpdate(rel, &tup->t_self, newtuple);
/* Rebuild dependencies */
GenerateTypeDependencies(typTup->typnamespace,
domainoid,
InvalidOid, /* typrelid is n/a */
0, /* relation kind is n/a */
typTup->typowner,
typTup->typinput,
typTup->typoutput,
typTup->typreceive,
typTup->typsend,
typTup->typmodin,
typTup->typmodout,
typTup->typanalyze,
InvalidOid,
false, /* a domain isn't an implicit array */
typTup->typbasetype,
typTup->typcollation,
defaultExpr,
true); /* Rebuild is true */
InvokeObjectPostAlterHook(TypeRelationId, domainoid, 0);
ObjectAddressSet(address, TypeRelationId, domainoid);
/* Clean up */
heap_close(rel, NoLock);
heap_freetuple(newtuple);
return address;
}
/*
* AlterDomainNotNull
*
* Routine implementing ALTER DOMAIN SET/DROP NOT NULL statements.
*
* Returns ObjectAddress of the modified domain.
*/
ObjectAddress
AlterDomainNotNull(List *names, bool notNull)
{
TypeName *typename;
Oid domainoid;
Relation typrel;
HeapTuple tup;
Form_pg_type typTup;
ObjectAddress address = InvalidObjectAddress;
/* Make a TypeName so we can use standard type lookup machinery */
typename = makeTypeNameFromNameList(names);
domainoid = typenameTypeId(NULL, typename);
/* Look up the domain in the type table */
typrel = heap_open(TypeRelationId, RowExclusiveLock);
tup = SearchSysCacheCopy1(TYPEOID, ObjectIdGetDatum(domainoid));
if (!HeapTupleIsValid(tup))
elog(ERROR, "cache lookup failed for type %u", domainoid);
typTup = (Form_pg_type) GETSTRUCT(tup);
/* Check it's a domain and check user has permission for ALTER DOMAIN */
checkDomainOwner(tup);
/* Is the domain already set to the desired constraint? */
if (typTup->typnotnull == notNull)
{
heap_close(typrel, RowExclusiveLock);
return address;
}
/* Adding a NOT NULL constraint requires checking existing columns */
if (notNull)
{
List *rels;
ListCell *rt;
/* Fetch relation list with attributes based on this domain */
/* ShareLock is sufficient to prevent concurrent data changes */
rels = get_rels_with_domain(domainoid, ShareLock);
foreach(rt, rels)
{
RelToCheck *rtc = (RelToCheck *) lfirst(rt);
Relation testrel = rtc->rel;
TupleDesc tupdesc = RelationGetDescr(testrel);
HeapScanDesc scan;
HeapTuple tuple;
Snapshot snapshot;
/* Scan all tuples in this relation */
snapshot = RegisterSnapshot(GetLatestSnapshot());
scan = heap_beginscan(testrel, snapshot, 0, NULL);
while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
{
int i;
/* Test attributes that are of the domain */
for (i = 0; i < rtc->natts; i++)
{
int attnum = rtc->atts[i];
Form_pg_attribute attr = TupleDescAttr(tupdesc, attnum - 1);
if (heap_attisnull(tuple, attnum))
{
/*
* In principle the auxiliary information for this
* error should be errdatatype(), but errtablecol()
* seems considerably more useful in practice. Since
* this code only executes in an ALTER DOMAIN command,
* the client should already know which domain is in
* question.
*/
ereport(ERROR,
(errcode(ERRCODE_NOT_NULL_VIOLATION),
errmsg("column \"%s\" of table \"%s\" contains null values",
NameStr(attr->attname),
RelationGetRelationName(testrel)),
errtablecol(testrel, attnum)));
}
}
}
heap_endscan(scan);
UnregisterSnapshot(snapshot);
/* Close each rel after processing, but keep lock */
heap_close(testrel, NoLock);
}
}
/*
* Okay to update pg_type row. We can scribble on typTup because it's a
* copy.
*/
typTup->typnotnull = notNull;
CatalogTupleUpdate(typrel, &tup->t_self, tup);
InvokeObjectPostAlterHook(TypeRelationId, domainoid, 0);
ObjectAddressSet(address, TypeRelationId, domainoid);
/* Clean up */
heap_freetuple(tup);
heap_close(typrel, RowExclusiveLock);
return address;
}
/*
* AlterDomainDropConstraint
*
* Implements the ALTER DOMAIN DROP CONSTRAINT statement
*/
ObjectAddress
AlterDomainDropConstraint(List *names, const char *constrName,
DropBehavior behavior, bool missing_ok)
{
TypeName *typename;
Oid domainoid;
HeapTuple tup;
Relation rel;
Relation conrel;
SysScanDesc conscan;
ScanKeyData key[1];
HeapTuple contup;
bool found = false;
ObjectAddress address = InvalidObjectAddress;
/* Make a TypeName so we can use standard type lookup machinery */
typename = makeTypeNameFromNameList(names);
domainoid = typenameTypeId(NULL, typename);
/* Look up the domain in the type table */
rel = heap_open(TypeRelationId, RowExclusiveLock);
tup = SearchSysCacheCopy1(TYPEOID, ObjectIdGetDatum(domainoid));
if (!HeapTupleIsValid(tup))
elog(ERROR, "cache lookup failed for type %u", domainoid);
/* Check it's a domain and check user has permission for ALTER DOMAIN */
checkDomainOwner(tup);
/* Grab an appropriate lock on the pg_constraint relation */
conrel = heap_open(ConstraintRelationId, RowExclusiveLock);
/* Use the index to scan only constraints of the target relation */
ScanKeyInit(&key[0],
Anum_pg_constraint_contypid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(HeapTupleGetOid(tup)));
conscan = systable_beginscan(conrel, ConstraintTypidIndexId, true,
NULL, 1, key);
/*
* Scan over the result set, removing any matching entries.
*/
while ((contup = systable_getnext(conscan)) != NULL)
{
Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(contup);
if (strcmp(NameStr(con->conname), constrName) == 0)
{
ObjectAddress conobj;
conobj.classId = ConstraintRelationId;
conobj.objectId = HeapTupleGetOid(contup);
conobj.objectSubId = 0;
performDeletion(&conobj, behavior, 0);
found = true;
}
}
ObjectAddressSet(address, TypeRelationId, domainoid);
/* Clean up after the scan */
systable_endscan(conscan);
heap_close(conrel, RowExclusiveLock);
heap_close(rel, NoLock);
if (!found)
{
if (!missing_ok)
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_OBJECT),
errmsg("constraint \"%s\" of domain \"%s\" does not exist",
constrName, TypeNameToString(typename))));
else
ereport(NOTICE,
(errmsg("constraint \"%s\" of domain \"%s\" does not exist, skipping",
constrName, TypeNameToString(typename))));
}
return address;
}
/*
* AlterDomainAddConstraint
*
* Implements the ALTER DOMAIN .. ADD CONSTRAINT statement.
*/
ObjectAddress
AlterDomainAddConstraint(List *names, Node *newConstraint,
ObjectAddress *constrAddr)
{
TypeName *typename;
Oid domainoid;
Relation typrel;
HeapTuple tup;
Form_pg_type typTup;
Constraint *constr;
char *ccbin;
ObjectAddress address;
/* Make a TypeName so we can use standard type lookup machinery */
typename = makeTypeNameFromNameList(names);
domainoid = typenameTypeId(NULL, typename);
/* Look up the domain in the type table */
typrel = heap_open(TypeRelationId, RowExclusiveLock);
tup = SearchSysCacheCopy1(TYPEOID, ObjectIdGetDatum(domainoid));
if (!HeapTupleIsValid(tup))
elog(ERROR, "cache lookup failed for type %u", domainoid);
typTup = (Form_pg_type) GETSTRUCT(tup);
/* Check it's a domain and check user has permission for ALTER DOMAIN */
checkDomainOwner(tup);
if (!IsA(newConstraint, Constraint))
elog(ERROR, "unrecognized node type: %d",
(int) nodeTag(newConstraint));
constr = (Constraint *) newConstraint;
switch (constr->contype)
{
case CONSTR_CHECK:
/* processed below */
break;
case CONSTR_UNIQUE:
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("unique constraints not possible for domains")));
break;
case CONSTR_PRIMARY:
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("primary key constraints not possible for domains")));
break;
case CONSTR_EXCLUSION:
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("exclusion constraints not possible for domains")));
break;
case CONSTR_FOREIGN:
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("foreign key constraints not possible for domains")));
break;
case CONSTR_ATTR_DEFERRABLE:
case CONSTR_ATTR_NOT_DEFERRABLE:
case CONSTR_ATTR_DEFERRED:
case CONSTR_ATTR_IMMEDIATE:
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("specifying constraint deferrability not supported for domains")));
break;
default:
elog(ERROR, "unrecognized constraint subtype: %d",
(int) constr->contype);
break;
}
/*
* Since all other constraint types throw errors, this must be a check
* constraint. First, process the constraint expression and add an entry
* to pg_constraint.
*/
ccbin = domainAddConstraint(domainoid, typTup->typnamespace,
typTup->typbasetype, typTup->typtypmod,
constr, NameStr(typTup->typname), constrAddr);
/*
* If requested to validate the constraint, test all values stored in the
* attributes based on the domain the constraint is being added to.
*/
if (!constr->skip_validation)
validateDomainConstraint(domainoid, ccbin);
ObjectAddressSet(address, TypeRelationId, domainoid);
/* Clean up */
heap_close(typrel, RowExclusiveLock);
return address;
}
/*
* AlterDomainValidateConstraint
*
* Implements the ALTER DOMAIN .. VALIDATE CONSTRAINT statement.
*/
ObjectAddress
AlterDomainValidateConstraint(List *names, char *constrName)
{
TypeName *typename;
Oid domainoid;
Relation typrel;
Relation conrel;
HeapTuple tup;
Form_pg_constraint con = NULL;
Form_pg_constraint copy_con;
char *conbin;
SysScanDesc scan;
Datum val;
bool found = false;
bool isnull;
HeapTuple tuple;
HeapTuple copyTuple;
ScanKeyData key;
ObjectAddress address;
/* Make a TypeName so we can use standard type lookup machinery */
typename = makeTypeNameFromNameList(names);
domainoid = typenameTypeId(NULL, typename);
/* Look up the domain in the type table */
typrel = heap_open(TypeRelationId, AccessShareLock);
tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(domainoid));
if (!HeapTupleIsValid(tup))
elog(ERROR, "cache lookup failed for type %u", domainoid);
/* Check it's a domain and check user has permission for ALTER DOMAIN */
checkDomainOwner(tup);
/*
* Find and check the target constraint
*/
conrel = heap_open(ConstraintRelationId, RowExclusiveLock);
ScanKeyInit(&key,
Anum_pg_constraint_contypid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(domainoid));
scan = systable_beginscan(conrel, ConstraintTypidIndexId,
true, NULL, 1, &key);
while (HeapTupleIsValid(tuple = systable_getnext(scan)))
{
con = (Form_pg_constraint) GETSTRUCT(tuple);
if (strcmp(NameStr(con->conname), constrName) == 0)
{
found = true;
break;
}
}
if (!found)
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_OBJECT),
errmsg("constraint \"%s\" of domain \"%s\" does not exist",
constrName, TypeNameToString(typename))));
if (con->contype != CONSTRAINT_CHECK)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("constraint \"%s\" of domain \"%s\" is not a check constraint",
constrName, TypeNameToString(typename))));
val = SysCacheGetAttr(CONSTROID, tuple,
Anum_pg_constraint_conbin,
&isnull);
if (isnull)
elog(ERROR, "null conbin for constraint %u",
HeapTupleGetOid(tuple));
conbin = TextDatumGetCString(val);
validateDomainConstraint(domainoid, conbin);
/*
* Now update the catalog, while we have the door open.
*/
copyTuple = heap_copytuple(tuple);
copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
copy_con->convalidated = true;
CatalogTupleUpdate(conrel, ©Tuple->t_self, copyTuple);
InvokeObjectPostAlterHook(ConstraintRelationId,
HeapTupleGetOid(copyTuple), 0);
ObjectAddressSet(address, TypeRelationId, domainoid);
heap_freetuple(copyTuple);
systable_endscan(scan);
heap_close(typrel, AccessShareLock);
heap_close(conrel, RowExclusiveLock);
ReleaseSysCache(tup);
return address;
}
static void
validateDomainConstraint(Oid domainoid, char *ccbin)
{
Expr *expr = (Expr *) stringToNode(ccbin);
List *rels;
ListCell *rt;
EState *estate;
ExprContext *econtext;
ExprState *exprstate;
/* Need an EState to run ExecEvalExpr */
estate = CreateExecutorState();
econtext = GetPerTupleExprContext(estate);
/* build execution state for expr */
exprstate = ExecPrepareExpr(expr, estate);
/* Fetch relation list with attributes based on this domain */
/* ShareLock is sufficient to prevent concurrent data changes */
rels = get_rels_with_domain(domainoid, ShareLock);
foreach(rt, rels)
{
RelToCheck *rtc = (RelToCheck *) lfirst(rt);
Relation testrel = rtc->rel;
TupleDesc tupdesc = RelationGetDescr(testrel);
HeapScanDesc scan;
HeapTuple tuple;
Snapshot snapshot;
/* Scan all tuples in this relation */
snapshot = RegisterSnapshot(GetLatestSnapshot());
scan = heap_beginscan(testrel, snapshot, 0, NULL);
while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
{
int i;
/* Test attributes that are of the domain */
for (i = 0; i < rtc->natts; i++)
{
int attnum = rtc->atts[i];
Datum d;
bool isNull;
Datum conResult;
Form_pg_attribute attr = TupleDescAttr(tupdesc, attnum - 1);
d = heap_getattr(tuple, attnum, tupdesc, &isNull);
econtext->domainValue_datum = d;
econtext->domainValue_isNull = isNull;
conResult = ExecEvalExprSwitchContext(exprstate,
econtext,
&isNull);
if (!isNull && !DatumGetBool(conResult))
{
/*
* In principle the auxiliary information for this error
* should be errdomainconstraint(), but errtablecol()
* seems considerably more useful in practice. Since this
* code only executes in an ALTER DOMAIN command, the
* client should already know which domain is in question,
* and which constraint too.
*/
ereport(ERROR,
(errcode(ERRCODE_CHECK_VIOLATION),
errmsg("column \"%s\" of table \"%s\" contains values that violate the new constraint",
NameStr(attr->attname),
RelationGetRelationName(testrel)),
errtablecol(testrel, attnum)));
}
}
ResetExprContext(econtext);
}
heap_endscan(scan);
UnregisterSnapshot(snapshot);
/* Hold relation lock till commit (XXX bad for concurrency) */
heap_close(testrel, NoLock);
}
FreeExecutorState(estate);
}
/*
* get_rels_with_domain
*
* Fetch all relations / attributes which are using the domain
*
* The result is a list of RelToCheck structs, one for each distinct
* relation, each containing one or more attribute numbers that are of
* the domain type. We have opened each rel and acquired the specified lock
* type on it.
*
* We support nested domains by including attributes that are of derived
* domain types. Current callers do not need to distinguish between attributes
* that are of exactly the given domain and those that are of derived domains.
*
* XXX this is completely broken because there is no way to lock the domain
* to prevent columns from being added or dropped while our command runs.
* We can partially protect against column drops by locking relations as we
* come across them, but there is still a race condition (the window between
* seeing a pg_depend entry and acquiring lock on the relation it references).
* Also, holding locks on all these relations simultaneously creates a non-
* trivial risk of deadlock. We can minimize but not eliminate the deadlock
* risk by using the weakest suitable lock (ShareLock for most callers).
*
* XXX the API for this is not sufficient to support checking domain values
* that are inside container types, such as composite types, arrays, or
* ranges. Currently we just error out if a container type containing the
* target domain is stored anywhere.
*
* Generally used for retrieving a list of tests when adding
* new constraints to a domain.
*/
static List *
get_rels_with_domain(Oid domainOid, LOCKMODE lockmode)
{
List *result = NIL;
char *domainTypeName = format_type_be(domainOid);
Relation depRel;
ScanKeyData key[2];
SysScanDesc depScan;
HeapTuple depTup;
Assert(lockmode != NoLock);
/* since this function recurses, it could be driven to stack overflow */
check_stack_depth();
/*
* We scan pg_depend to find those things that depend on the domain. (We
* assume we can ignore refobjsubid for a domain.)
*/
depRel = heap_open(DependRelationId, AccessShareLock);
ScanKeyInit(&key[0],
Anum_pg_depend_refclassid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(TypeRelationId));
ScanKeyInit(&key[1],
Anum_pg_depend_refobjid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(domainOid));
depScan = systable_beginscan(depRel, DependReferenceIndexId, true,
NULL, 2, key);
while (HeapTupleIsValid(depTup = systable_getnext(depScan)))
{
Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup);
RelToCheck *rtc = NULL;
ListCell *rellist;
Form_pg_attribute pg_att;
int ptr;
/* Check for directly dependent types */
if (pg_depend->classid == TypeRelationId)
{
if (get_typtype(pg_depend->objid) == TYPTYPE_DOMAIN)
{
/*
* This is a sub-domain, so recursively add dependent columns
* to the output list. This is a bit inefficient since we may
* fail to combine RelToCheck entries when attributes of the
* same rel have different derived domain types, but it's
* probably not worth improving.
*/
result = list_concat(result,
get_rels_with_domain(pg_depend->objid,
lockmode));
}
else
{
/*
* Otherwise, it is some container type using the domain, so
* fail if there are any columns of this type.
*/
find_composite_type_dependencies(pg_depend->objid,
NULL,
domainTypeName);
}
continue;
}
/* Else, ignore dependees that aren't user columns of relations */
/* (we assume system columns are never of domain types) */
if (pg_depend->classid != RelationRelationId ||
pg_depend->objsubid <= 0)
continue;
/* See if we already have an entry for this relation */
foreach(rellist, result)
{
RelToCheck *rt = (RelToCheck *) lfirst(rellist);
if (RelationGetRelid(rt->rel) == pg_depend->objid)
{
rtc = rt;
break;
}
}
if (rtc == NULL)
{
/* First attribute found for this relation */
Relation rel;
/* Acquire requested lock on relation */
rel = relation_open(pg_depend->objid, lockmode);
/*
* Check to see if rowtype is stored anyplace as a composite-type
* column; if so we have to fail, for now anyway.
*/
if (OidIsValid(rel->rd_rel->reltype))
find_composite_type_dependencies(rel->rd_rel->reltype,
NULL,
domainTypeName);
/*
* Otherwise, we can ignore relations except those with both
* storage and user-chosen column types.
*
* XXX If an index-only scan could satisfy "col::some_domain" from
* a suitable expression index, this should also check expression
* index columns.
*/
if (rel->rd_rel->relkind != RELKIND_RELATION &&
rel->rd_rel->relkind != RELKIND_MATVIEW)
{
relation_close(rel, lockmode);
continue;
}
/* Build the RelToCheck entry with enough space for all atts */
rtc = (RelToCheck *) palloc(sizeof(RelToCheck));
rtc->rel = rel;
rtc->natts = 0;
rtc->atts = (int *) palloc(sizeof(int) * RelationGetNumberOfAttributes(rel));
result = lcons(rtc, result);
}
/*
* Confirm column has not been dropped, and is of the expected type.
* This defends against an ALTER DROP COLUMN occurring just before we
* acquired lock ... but if the whole table were dropped, we'd still
* have a problem.
*/
if (pg_depend->objsubid > RelationGetNumberOfAttributes(rtc->rel))
continue;
pg_att = TupleDescAttr(rtc->rel->rd_att, pg_depend->objsubid - 1);
if (pg_att->attisdropped || pg_att->atttypid != domainOid)
continue;
/*
* Okay, add column to result. We store the columns in column-number
* order; this is just a hack to improve predictability of regression
* test output ...
*/
Assert(rtc->natts < RelationGetNumberOfAttributes(rtc->rel));
ptr = rtc->natts++;
while (ptr > 0 && rtc->atts[ptr - 1] > pg_depend->objsubid)
{
rtc->atts[ptr] = rtc->atts[ptr - 1];
ptr--;
}
rtc->atts[ptr] = pg_depend->objsubid;
}
systable_endscan(depScan);
relation_close(depRel, AccessShareLock);
return result;
}
/*
* checkDomainOwner
*
* Check that the type is actually a domain and that the current user
* has permission to do ALTER DOMAIN on it. Throw an error if not.
*/
void
checkDomainOwner(HeapTuple tup)
{
Form_pg_type typTup = (Form_pg_type) GETSTRUCT(tup);
/* Check that this is actually a domain */
if (typTup->typtype != TYPTYPE_DOMAIN)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("%s is not a domain",
format_type_be(HeapTupleGetOid(tup)))));
/* Permission check: must own type */
if (!pg_type_ownercheck(HeapTupleGetOid(tup), GetUserId()))
aclcheck_error_type(ACLCHECK_NOT_OWNER, HeapTupleGetOid(tup));
}
/*
* domainAddConstraint - code shared between CREATE and ALTER DOMAIN
*/
static char *
domainAddConstraint(Oid domainOid, Oid domainNamespace, Oid baseTypeOid,
int typMod, Constraint *constr,
char *domainName, ObjectAddress *constrAddr)
{
Node *expr;
char *ccsrc;
char *ccbin;
ParseState *pstate;
CoerceToDomainValue *domVal;
Oid ccoid;
/*
* Assign or validate constraint name
*/
if (constr->conname)
{
if (ConstraintNameIsUsed(CONSTRAINT_DOMAIN,
domainOid,
domainNamespace,
constr->conname))
ereport(ERROR,
(errcode(ERRCODE_DUPLICATE_OBJECT),
errmsg("constraint \"%s\" for domain \"%s\" already exists",
constr->conname, domainName)));
}
else
constr->conname = ChooseConstraintName(domainName,
NULL,
"check",
domainNamespace,
NIL);
/*
* Convert the A_EXPR in raw_expr into an EXPR
*/
pstate = make_parsestate(NULL);
/*
* Set up a CoerceToDomainValue to represent the occurrence of VALUE in
* the expression. Note that it will appear to have the type of the base
* type, not the domain. This seems correct since within the check
* expression, we should not assume the input value can be considered a
* member of the domain.
*/
domVal = makeNode(CoerceToDomainValue);
domVal->typeId = baseTypeOid;
domVal->typeMod = typMod;
domVal->collation = get_typcollation(baseTypeOid);
domVal->location = -1; /* will be set when/if used */
pstate->p_pre_columnref_hook = replace_domain_constraint_value;
pstate->p_ref_hook_state = (void *) domVal;
expr = transformExpr(pstate, constr->raw_expr, EXPR_KIND_DOMAIN_CHECK);
/*
* Make sure it yields a boolean result.
*/
expr = coerce_to_boolean(pstate, expr, "CHECK");
/*
* Fix up collation information.
*/
assign_expr_collations(pstate, expr);
/*
* Domains don't allow variables (this is probably dead code now that
* add_missing_from is history, but let's be sure).
*/
if (list_length(pstate->p_rtable) != 0 ||
contain_var_clause(expr))
ereport(ERROR,
(errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
errmsg("cannot use table references in domain check constraint")));
/*
* Convert to string form for storage.
*/
ccbin = nodeToString(expr);
/*
* Deparse it to produce text for consrc.
*/
ccsrc = deparse_expression(expr,
NIL, false, false);
/*
* Store the constraint in pg_constraint
*/
ccoid =
CreateConstraintEntry(constr->conname, /* Constraint Name */
domainNamespace, /* namespace */
CONSTRAINT_CHECK, /* Constraint Type */
false, /* Is Deferrable */
false, /* Is Deferred */
!constr->skip_validation, /* Is Validated */
InvalidOid, /* not a relation constraint */
NULL,
0,
domainOid, /* domain constraint */
InvalidOid, /* no associated index */
InvalidOid, /* Foreign key fields */
NULL,
NULL,
NULL,
NULL,
0,
' ',
' ',
' ',
NULL, /* not an exclusion constraint */
expr, /* Tree form of check constraint */
ccbin, /* Binary form of check constraint */
ccsrc, /* Source form of check constraint */
true, /* is local */
0, /* inhcount */
false, /* connoinherit */
false); /* is_internal */
if (constrAddr)
ObjectAddressSet(*constrAddr, ConstraintRelationId, ccoid);
/*
* Return the compiled constraint expression so the calling routine can
* perform any additional required tests.
*/
return ccbin;
}
/* Parser pre_columnref_hook for domain CHECK constraint parsing */
static Node *
replace_domain_constraint_value(ParseState *pstate, ColumnRef *cref)
{
/*
* Check for a reference to "value", and if that's what it is, replace
* with a CoerceToDomainValue as prepared for us by domainAddConstraint.
* (We handle VALUE as a name, not a keyword, to avoid breaking a lot of
* applications that have used VALUE as a column name in the past.)
*/
if (list_length(cref->fields) == 1)
{
Node *field1 = (Node *) linitial(cref->fields);
char *colname;
Assert(IsA(field1, String));
colname = strVal(field1);
if (strcmp(colname, "value") == 0)
{
CoerceToDomainValue *domVal = copyObject(pstate->p_ref_hook_state);
/* Propagate location knowledge, if any */
domVal->location = cref->location;
return (Node *) domVal;
}
}
return NULL;
}
/*
* Execute ALTER TYPE RENAME
*/
ObjectAddress
RenameType(RenameStmt *stmt)
{
List *names = castNode(List, stmt->object);
const char *newTypeName = stmt->newname;
TypeName *typename;
Oid typeOid;
Relation rel;
HeapTuple tup;
Form_pg_type typTup;
ObjectAddress address;
/* Make a TypeName so we can use standard type lookup machinery */
typename = makeTypeNameFromNameList(names);
typeOid = typenameTypeId(NULL, typename);
/* Look up the type in the type table */
rel = heap_open(TypeRelationId, RowExclusiveLock);
tup = SearchSysCacheCopy1(TYPEOID, ObjectIdGetDatum(typeOid));
if (!HeapTupleIsValid(tup))
elog(ERROR, "cache lookup failed for type %u", typeOid);
typTup = (Form_pg_type) GETSTRUCT(tup);
/* check permissions on type */
if (!pg_type_ownercheck(typeOid, GetUserId()))
aclcheck_error_type(ACLCHECK_NOT_OWNER, typeOid);
/* ALTER DOMAIN used on a non-domain? */
if (stmt->renameType == OBJECT_DOMAIN && typTup->typtype != TYPTYPE_DOMAIN)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("%s is not a domain",
format_type_be(typeOid))));
/*
* If it's a composite type, we need to check that it really is a
* free-standing composite type, and not a table's rowtype. We want people
* to use ALTER TABLE not ALTER TYPE for that case.
*/
if (typTup->typtype == TYPTYPE_COMPOSITE &&
get_rel_relkind(typTup->typrelid) != RELKIND_COMPOSITE_TYPE)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("%s is a table's row type",
format_type_be(typeOid)),
errhint("Use ALTER TABLE instead.")));
/* don't allow direct alteration of array types, either */
if (OidIsValid(typTup->typelem) &&
get_array_type(typTup->typelem) == typeOid)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("cannot alter array type %s",
format_type_be(typeOid)),
errhint("You can alter type %s, which will alter the array type as well.",
format_type_be(typTup->typelem))));
/*
* If type is composite we need to rename associated pg_class entry too.
* RenameRelationInternal will call RenameTypeInternal automatically.
*/
if (typTup->typtype == TYPTYPE_COMPOSITE)
RenameRelationInternal(typTup->typrelid, newTypeName, false);
else
RenameTypeInternal(typeOid, newTypeName,
typTup->typnamespace);
ObjectAddressSet(address, TypeRelationId, typeOid);
/* Clean up */
heap_close(rel, RowExclusiveLock);
return address;
}
/*
* Change the owner of a type.
*/
ObjectAddress
AlterTypeOwner(List *names, Oid newOwnerId, ObjectType objecttype)
{
TypeName *typename;
Oid typeOid;
Relation rel;
HeapTuple tup;
HeapTuple newtup;
Form_pg_type typTup;
AclResult aclresult;
ObjectAddress address;
rel = heap_open(TypeRelationId, RowExclusiveLock);
/* Make a TypeName so we can use standard type lookup machinery */
typename = makeTypeNameFromNameList(names);
/* Use LookupTypeName here so that shell types can be processed */
tup = LookupTypeName(NULL, typename, NULL, false);
if (tup == NULL)
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_OBJECT),
errmsg("type \"%s\" does not exist",
TypeNameToString(typename))));
typeOid = typeTypeId(tup);
/* Copy the syscache entry so we can scribble on it below */
newtup = heap_copytuple(tup);
ReleaseSysCache(tup);
tup = newtup;
typTup = (Form_pg_type) GETSTRUCT(tup);
/* Don't allow ALTER DOMAIN on a type */
if (objecttype == OBJECT_DOMAIN && typTup->typtype != TYPTYPE_DOMAIN)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("%s is not a domain",
format_type_be(typeOid))));
/*
* If it's a composite type, we need to check that it really is a
* free-standing composite type, and not a table's rowtype. We want people
* to use ALTER TABLE not ALTER TYPE for that case.
*/
if (typTup->typtype == TYPTYPE_COMPOSITE &&
get_rel_relkind(typTup->typrelid) != RELKIND_COMPOSITE_TYPE)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("%s is a table's row type",
format_type_be(typeOid)),
errhint("Use ALTER TABLE instead.")));
/* don't allow direct alteration of array types, either */
if (OidIsValid(typTup->typelem) &&
get_array_type(typTup->typelem) == typeOid)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("cannot alter array type %s",
format_type_be(typeOid)),
errhint("You can alter type %s, which will alter the array type as well.",
format_type_be(typTup->typelem))));
/*
* If the new owner is the same as the existing owner, consider the
* command to have succeeded. This is for dump restoration purposes.
*/
if (typTup->typowner != newOwnerId)
{
/* Superusers can always do it */
if (!superuser())
{
/* Otherwise, must be owner of the existing object */
if (!pg_type_ownercheck(HeapTupleGetOid(tup), GetUserId()))
aclcheck_error_type(ACLCHECK_NOT_OWNER, HeapTupleGetOid(tup));
/* Must be able to become new owner */
check_is_member_of_role(GetUserId(), newOwnerId);
/* New owner must have CREATE privilege on namespace */
aclresult = pg_namespace_aclcheck(typTup->typnamespace,
newOwnerId,
ACL_CREATE);
if (aclresult != ACLCHECK_OK)
aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
get_namespace_name(typTup->typnamespace));
}
AlterTypeOwner_oid(typeOid, newOwnerId, true);
}
ObjectAddressSet(address, TypeRelationId, typeOid);
/* Clean up */
heap_close(rel, RowExclusiveLock);
return address;
}
/*
* AlterTypeOwner_oid - change type owner unconditionally
*
* This function recurses to handle a pg_class entry, if necessary. It
* invokes any necessary access object hooks. If hasDependEntry is true, this
* function modifies the pg_shdepend entry appropriately (this should be
* passed as false only for table rowtypes and array types).
*
* This is used by ALTER TABLE/TYPE OWNER commands, as well as by REASSIGN
* OWNED BY. It assumes the caller has done all needed check.
*/
void
AlterTypeOwner_oid(Oid typeOid, Oid newOwnerId, bool hasDependEntry)
{
Relation rel;
HeapTuple tup;
Form_pg_type typTup;
rel = heap_open(TypeRelationId, RowExclusiveLock);
tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typeOid));
if (!HeapTupleIsValid(tup))
elog(ERROR, "cache lookup failed for type %u", typeOid);
typTup = (Form_pg_type) GETSTRUCT(tup);
/*
* If it's a composite type, invoke ATExecChangeOwner so that we fix up
* the pg_class entry properly. That will call back to
* AlterTypeOwnerInternal to take care of the pg_type entry(s).
*/
if (typTup->typtype == TYPTYPE_COMPOSITE)
ATExecChangeOwner(typTup->typrelid, newOwnerId, true, AccessExclusiveLock);
else
AlterTypeOwnerInternal(typeOid, newOwnerId);
/* Update owner dependency reference */
if (hasDependEntry)
changeDependencyOnOwner(TypeRelationId, typeOid, newOwnerId);
InvokeObjectPostAlterHook(TypeRelationId, typeOid, 0);
ReleaseSysCache(tup);
heap_close(rel, RowExclusiveLock);
}
/*
* AlterTypeOwnerInternal - bare-bones type owner change.
*
* This routine simply modifies the owner of a pg_type entry, and recurses
* to handle a possible array type.
*/
void
AlterTypeOwnerInternal(Oid typeOid, Oid newOwnerId)
{
Relation rel;
HeapTuple tup;
Form_pg_type typTup;
Datum repl_val[Natts_pg_type];
bool repl_null[Natts_pg_type];
bool repl_repl[Natts_pg_type];
Acl *newAcl;
Datum aclDatum;
bool isNull;
rel = heap_open(TypeRelationId, RowExclusiveLock);
tup = SearchSysCacheCopy1(TYPEOID, ObjectIdGetDatum(typeOid));
if (!HeapTupleIsValid(tup))
elog(ERROR, "cache lookup failed for type %u", typeOid);
typTup = (Form_pg_type) GETSTRUCT(tup);
memset(repl_null, false, sizeof(repl_null));
memset(repl_repl, false, sizeof(repl_repl));
repl_repl[Anum_pg_type_typowner - 1] = true;
repl_val[Anum_pg_type_typowner - 1] = ObjectIdGetDatum(newOwnerId);
aclDatum = heap_getattr(tup,
Anum_pg_type_typacl,
RelationGetDescr(rel),
&isNull);
/* Null ACLs do not require changes */
if (!isNull)
{
newAcl = aclnewowner(DatumGetAclP(aclDatum),
typTup->typowner, newOwnerId);
repl_repl[Anum_pg_type_typacl - 1] = true;
repl_val[Anum_pg_type_typacl - 1] = PointerGetDatum(newAcl);
}
tup = heap_modify_tuple(tup, RelationGetDescr(rel), repl_val, repl_null,
repl_repl);
CatalogTupleUpdate(rel, &tup->t_self, tup);
/* If it has an array type, update that too */
if (OidIsValid(typTup->typarray))
AlterTypeOwnerInternal(typTup->typarray, newOwnerId);
/* Clean up */
heap_close(rel, RowExclusiveLock);
}
/*
* Execute ALTER TYPE SET SCHEMA
*/
ObjectAddress
AlterTypeNamespace(List *names, const char *newschema, ObjectType objecttype,
Oid *oldschema)
{
TypeName *typename;
Oid typeOid;
Oid nspOid;
Oid oldNspOid;
ObjectAddresses *objsMoved;
ObjectAddress myself;
/* Make a TypeName so we can use standard type lookup machinery */
typename = makeTypeNameFromNameList(names);
typeOid = typenameTypeId(NULL, typename);
/* Don't allow ALTER DOMAIN on a type */
if (objecttype == OBJECT_DOMAIN && get_typtype(typeOid) != TYPTYPE_DOMAIN)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("%s is not a domain",
format_type_be(typeOid))));
/* get schema OID and check its permissions */
nspOid = LookupCreationNamespace(newschema);
objsMoved = new_object_addresses();
oldNspOid = AlterTypeNamespace_oid(typeOid, nspOid, objsMoved);
free_object_addresses(objsMoved);
if (oldschema)
*oldschema = oldNspOid;
ObjectAddressSet(myself, TypeRelationId, typeOid);
return myself;
}
Oid
AlterTypeNamespace_oid(Oid typeOid, Oid nspOid, ObjectAddresses *objsMoved)
{
Oid elemOid;
/* check permissions on type */
if (!pg_type_ownercheck(typeOid, GetUserId()))
aclcheck_error_type(ACLCHECK_NOT_OWNER, typeOid);
/* don't allow direct alteration of array types */
elemOid = get_element_type(typeOid);
if (OidIsValid(elemOid) && get_array_type(elemOid) == typeOid)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("cannot alter array type %s",
format_type_be(typeOid)),
errhint("You can alter type %s, which will alter the array type as well.",
format_type_be(elemOid))));
/* and do the work */
return AlterTypeNamespaceInternal(typeOid, nspOid, false, true, objsMoved);
}
/*
* Move specified type to new namespace.
*
* Caller must have already checked privileges.
*
* The function automatically recurses to process the type's array type,
* if any. isImplicitArray should be true only when doing this internal
* recursion (outside callers must never try to move an array type directly).
*
* If errorOnTableType is true, the function errors out if the type is
* a table type. ALTER TABLE has to be used to move a table to a new
* namespace.
*
* Returns the type's old namespace OID.
*/
Oid
AlterTypeNamespaceInternal(Oid typeOid, Oid nspOid,
bool isImplicitArray,
bool errorOnTableType,
ObjectAddresses *objsMoved)
{
Relation rel;
HeapTuple tup;
Form_pg_type typform;
Oid oldNspOid;
Oid arrayOid;
bool isCompositeType;
ObjectAddress thisobj;
/*
* Make sure we haven't moved this object previously.
*/
thisobj.classId = TypeRelationId;
thisobj.objectId = typeOid;
thisobj.objectSubId = 0;
if (object_address_present(&thisobj, objsMoved))
return InvalidOid;
rel = heap_open(TypeRelationId, RowExclusiveLock);
tup = SearchSysCacheCopy1(TYPEOID, ObjectIdGetDatum(typeOid));
if (!HeapTupleIsValid(tup))
elog(ERROR, "cache lookup failed for type %u", typeOid);
typform = (Form_pg_type) GETSTRUCT(tup);
oldNspOid = typform->typnamespace;
arrayOid = typform->typarray;
/* If the type is already there, we scan skip these next few checks. */
if (oldNspOid != nspOid)
{
/* common checks on switching namespaces */
CheckSetNamespace(oldNspOid, nspOid);
/* check for duplicate name (more friendly than unique-index failure) */
if (SearchSysCacheExists2(TYPENAMENSP,
NameGetDatum(&typform->typname),
ObjectIdGetDatum(nspOid)))
ereport(ERROR,
(errcode(ERRCODE_DUPLICATE_OBJECT),
errmsg("type \"%s\" already exists in schema \"%s\"",
NameStr(typform->typname),
get_namespace_name(nspOid))));
}
/* Detect whether type is a composite type (but not a table rowtype) */
isCompositeType =
(typform->typtype == TYPTYPE_COMPOSITE &&
get_rel_relkind(typform->typrelid) == RELKIND_COMPOSITE_TYPE);
/* Enforce not-table-type if requested */
if (typform->typtype == TYPTYPE_COMPOSITE && !isCompositeType &&
errorOnTableType)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("%s is a table's row type",
format_type_be(typeOid)),
errhint("Use ALTER TABLE instead.")));
if (oldNspOid != nspOid)
{
/* OK, modify the pg_type row */
/* tup is a copy, so we can scribble directly on it */
typform->typnamespace = nspOid;
CatalogTupleUpdate(rel, &tup->t_self, tup);
}
/*
* Composite types have pg_class entries.
*
* We need to modify the pg_class tuple as well to reflect the change of
* schema.
*/
if (isCompositeType)
{
Relation classRel;
classRel = heap_open(RelationRelationId, RowExclusiveLock);
AlterRelationNamespaceInternal(classRel, typform->typrelid,
oldNspOid, nspOid,
false, objsMoved);
heap_close(classRel, RowExclusiveLock);
/*
* Check for constraints associated with the composite type (we don't
* currently support this, but probably will someday).
*/
AlterConstraintNamespaces(typform->typrelid, oldNspOid,
nspOid, false, objsMoved);
}
else
{
/* If it's a domain, it might have constraints */
if (typform->typtype == TYPTYPE_DOMAIN)
AlterConstraintNamespaces(typeOid, oldNspOid, nspOid, true,
objsMoved);
}
/*
* Update dependency on schema, if any --- a table rowtype has not got
* one, and neither does an implicit array.
*/
if (oldNspOid != nspOid &&
(isCompositeType || typform->typtype != TYPTYPE_COMPOSITE) &&
!isImplicitArray)
if (changeDependencyFor(TypeRelationId, typeOid,
NamespaceRelationId, oldNspOid, nspOid) != 1)
elog(ERROR, "failed to change schema dependency for type %s",
format_type_be(typeOid));
InvokeObjectPostAlterHook(TypeRelationId, typeOid, 0);
heap_freetuple(tup);
heap_close(rel, RowExclusiveLock);
add_exact_object_address(&thisobj, objsMoved);
/* Recursively alter the associated array type, if any */
if (OidIsValid(arrayOid))
AlterTypeNamespaceInternal(arrayOid, nspOid, true, true, objsMoved);
return oldNspOid;
}
|