1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
|
/*
* psql - the PostgreSQL interactive terminal
*
* Copyright (c) 2000-2023, PostgreSQL Global Development Group
*
* src/bin/psql/command.c
*/
#include "postgres_fe.h"
#include <ctype.h>
#include <time.h>
#include <pwd.h>
#include <utime.h>
#ifndef WIN32
#include <sys/stat.h> /* for stat() */
#include <sys/time.h> /* for setitimer() */
#include <fcntl.h> /* open() flags */
#include <unistd.h> /* for geteuid(), getpid(), stat() */
#else
#include <win32.h>
#include <io.h>
#include <fcntl.h>
#include <direct.h>
#include <sys/stat.h> /* for stat() */
#endif
#include "catalog/pg_class_d.h"
#include "command.h"
#include "common.h"
#include "common/logging.h"
#include "common/string.h"
#include "copy.h"
#include "crosstabview.h"
#include "describe.h"
#include "fe_utils/cancel.h"
#include "fe_utils/print.h"
#include "fe_utils/string_utils.h"
#include "help.h"
#include "input.h"
#include "large_obj.h"
#include "libpq-fe.h"
#include "libpq/pqcomm.h"
#include "mainloop.h"
#include "portability/instr_time.h"
#include "pqexpbuffer.h"
#include "psqlscanslash.h"
#include "settings.h"
#include "variables.h"
/*
* Editable database object types.
*/
typedef enum EditableObjectType
{
EditableFunction,
EditableView
} EditableObjectType;
/* local function declarations */
static backslashResult exec_command(const char *cmd,
PsqlScanState scan_state,
ConditionalStack cstack,
PQExpBuffer query_buf,
PQExpBuffer previous_buf);
static backslashResult exec_command_a(PsqlScanState scan_state, bool active_branch);
static backslashResult exec_command_bind(PsqlScanState scan_state, bool active_branch);
static backslashResult exec_command_C(PsqlScanState scan_state, bool active_branch);
static backslashResult exec_command_connect(PsqlScanState scan_state, bool active_branch);
static backslashResult exec_command_cd(PsqlScanState scan_state, bool active_branch,
const char *cmd);
static backslashResult exec_command_conninfo(PsqlScanState scan_state, bool active_branch);
static backslashResult exec_command_copy(PsqlScanState scan_state, bool active_branch);
static backslashResult exec_command_copyright(PsqlScanState scan_state, bool active_branch);
static backslashResult exec_command_crosstabview(PsqlScanState scan_state, bool active_branch);
static backslashResult exec_command_d(PsqlScanState scan_state, bool active_branch,
const char *cmd);
static bool exec_command_dfo(PsqlScanState scan_state, const char *cmd,
const char *pattern,
bool show_verbose, bool show_system);
static backslashResult exec_command_edit(PsqlScanState scan_state, bool active_branch,
PQExpBuffer query_buf, PQExpBuffer previous_buf);
static backslashResult exec_command_ef_ev(PsqlScanState scan_state, bool active_branch,
PQExpBuffer query_buf, bool is_func);
static backslashResult exec_command_echo(PsqlScanState scan_state, bool active_branch,
const char *cmd);
static backslashResult exec_command_elif(PsqlScanState scan_state, ConditionalStack cstack,
PQExpBuffer query_buf);
static backslashResult exec_command_else(PsqlScanState scan_state, ConditionalStack cstack,
PQExpBuffer query_buf);
static backslashResult exec_command_endif(PsqlScanState scan_state, ConditionalStack cstack,
PQExpBuffer query_buf);
static backslashResult exec_command_encoding(PsqlScanState scan_state, bool active_branch);
static backslashResult exec_command_errverbose(PsqlScanState scan_state, bool active_branch);
static backslashResult exec_command_f(PsqlScanState scan_state, bool active_branch);
static backslashResult exec_command_g(PsqlScanState scan_state, bool active_branch,
const char *cmd);
static backslashResult process_command_g_options(char *first_option,
PsqlScanState scan_state,
bool active_branch,
const char *cmd);
static backslashResult exec_command_gdesc(PsqlScanState scan_state, bool active_branch);
static backslashResult exec_command_getenv(PsqlScanState scan_state, bool active_branch,
const char *cmd);
static backslashResult exec_command_gexec(PsqlScanState scan_state, bool active_branch);
static backslashResult exec_command_gset(PsqlScanState scan_state, bool active_branch);
static backslashResult exec_command_help(PsqlScanState scan_state, bool active_branch);
static backslashResult exec_command_html(PsqlScanState scan_state, bool active_branch);
static backslashResult exec_command_include(PsqlScanState scan_state, bool active_branch,
const char *cmd);
static backslashResult exec_command_if(PsqlScanState scan_state, ConditionalStack cstack,
PQExpBuffer query_buf);
static backslashResult exec_command_list(PsqlScanState scan_state, bool active_branch,
const char *cmd);
static backslashResult exec_command_lo(PsqlScanState scan_state, bool active_branch,
const char *cmd);
static backslashResult exec_command_out(PsqlScanState scan_state, bool active_branch);
static backslashResult exec_command_print(PsqlScanState scan_state, bool active_branch,
PQExpBuffer query_buf, PQExpBuffer previous_buf);
static backslashResult exec_command_password(PsqlScanState scan_state, bool active_branch);
static backslashResult exec_command_prompt(PsqlScanState scan_state, bool active_branch,
const char *cmd);
static backslashResult exec_command_pset(PsqlScanState scan_state, bool active_branch);
static backslashResult exec_command_quit(PsqlScanState scan_state, bool active_branch);
static backslashResult exec_command_reset(PsqlScanState scan_state, bool active_branch,
PQExpBuffer query_buf);
static backslashResult exec_command_s(PsqlScanState scan_state, bool active_branch);
static backslashResult exec_command_set(PsqlScanState scan_state, bool active_branch);
static backslashResult exec_command_setenv(PsqlScanState scan_state, bool active_branch,
const char *cmd);
static backslashResult exec_command_sf_sv(PsqlScanState scan_state, bool active_branch,
const char *cmd, bool is_func);
static backslashResult exec_command_t(PsqlScanState scan_state, bool active_branch);
static backslashResult exec_command_T(PsqlScanState scan_state, bool active_branch);
static backslashResult exec_command_timing(PsqlScanState scan_state, bool active_branch);
static backslashResult exec_command_unset(PsqlScanState scan_state, bool active_branch,
const char *cmd);
static backslashResult exec_command_write(PsqlScanState scan_state, bool active_branch,
const char *cmd,
PQExpBuffer query_buf, PQExpBuffer previous_buf);
static backslashResult exec_command_watch(PsqlScanState scan_state, bool active_branch,
PQExpBuffer query_buf, PQExpBuffer previous_buf);
static backslashResult exec_command_x(PsqlScanState scan_state, bool active_branch);
static backslashResult exec_command_z(PsqlScanState scan_state, bool active_branch,
const char *cmd);
static backslashResult exec_command_shell_escape(PsqlScanState scan_state, bool active_branch);
static backslashResult exec_command_slash_command_help(PsqlScanState scan_state, bool active_branch);
static char *read_connect_arg(PsqlScanState scan_state);
static PQExpBuffer gather_boolean_expression(PsqlScanState scan_state);
static bool is_true_boolean_expression(PsqlScanState scan_state, const char *name);
static void ignore_boolean_expression(PsqlScanState scan_state);
static void ignore_slash_options(PsqlScanState scan_state);
static void ignore_slash_filepipe(PsqlScanState scan_state);
static void ignore_slash_whole_line(PsqlScanState scan_state);
static bool is_branching_command(const char *cmd);
static void save_query_text_state(PsqlScanState scan_state, ConditionalStack cstack,
PQExpBuffer query_buf);
static void discard_query_text(PsqlScanState scan_state, ConditionalStack cstack,
PQExpBuffer query_buf);
static bool copy_previous_query(PQExpBuffer query_buf, PQExpBuffer previous_buf);
static bool do_connect(enum trivalue reuse_previous_specification,
char *dbname, char *user, char *host, char *port);
static bool do_edit(const char *filename_arg, PQExpBuffer query_buf,
int lineno, bool discard_on_quit, bool *edited);
static bool do_shell(const char *command);
static bool do_watch(PQExpBuffer query_buf, double sleep, int iter);
static bool lookup_object_oid(EditableObjectType obj_type, const char *desc,
Oid *obj_oid);
static bool get_create_object_cmd(EditableObjectType obj_type, Oid oid,
PQExpBuffer buf);
static int strip_lineno_from_objdesc(char *obj);
static int count_lines_in_buf(PQExpBuffer buf);
static void print_with_linenumbers(FILE *output, char *lines, bool is_func);
static void minimal_error_message(PGresult *res);
static void printSSLInfo(void);
static void printGSSInfo(void);
static bool printPsetInfo(const char *param, printQueryOpt *popt);
static char *pset_value_string(const char *param, printQueryOpt *popt);
#ifdef WIN32
static void checkWin32Codepage(void);
#endif
/*----------
* HandleSlashCmds:
*
* Handles all the different commands that start with '\'.
* Ordinarily called by MainLoop().
*
* scan_state is a lexer working state that is set to continue scanning
* just after the '\'. The lexer is advanced past the command and all
* arguments on return.
*
* cstack is the current \if stack state. This will be examined, and
* possibly modified by conditional commands.
*
* query_buf contains the query-so-far, which may be modified by
* execution of the backslash command (for example, \r clears it).
*
* previous_buf contains the query most recently sent to the server
* (empty if none yet). This should not be modified here, but some
* commands copy its content into query_buf.
*
* query_buf and previous_buf will be NULL when executing a "-c"
* command-line option.
*
* Returns a status code indicating what action is desired, see command.h.
*----------
*/
backslashResult
HandleSlashCmds(PsqlScanState scan_state,
ConditionalStack cstack,
PQExpBuffer query_buf,
PQExpBuffer previous_buf)
{
backslashResult status;
char *cmd;
char *arg;
Assert(scan_state != NULL);
Assert(cstack != NULL);
/* Parse off the command name */
cmd = psql_scan_slash_command(scan_state);
/* And try to execute it */
status = exec_command(cmd, scan_state, cstack, query_buf, previous_buf);
if (status == PSQL_CMD_UNKNOWN)
{
pg_log_error("invalid command \\%s", cmd);
if (pset.cur_cmd_interactive)
pg_log_error_hint("Try \\? for help.");
status = PSQL_CMD_ERROR;
}
if (status != PSQL_CMD_ERROR)
{
/*
* Eat any remaining arguments after a valid command. We want to
* suppress evaluation of backticks in this situation, so transiently
* push an inactive conditional-stack entry.
*/
bool active_branch = conditional_active(cstack);
conditional_stack_push(cstack, IFSTATE_IGNORED);
while ((arg = psql_scan_slash_option(scan_state,
OT_NORMAL, NULL, false)))
{
if (active_branch)
pg_log_warning("\\%s: extra argument \"%s\" ignored", cmd, arg);
free(arg);
}
conditional_stack_pop(cstack);
}
else
{
/* silently throw away rest of line after an erroneous command */
while ((arg = psql_scan_slash_option(scan_state,
OT_WHOLE_LINE, NULL, false)))
free(arg);
}
/* if there is a trailing \\, swallow it */
psql_scan_slash_command_end(scan_state);
free(cmd);
/* some commands write to queryFout, so make sure output is sent */
fflush(pset.queryFout);
return status;
}
/*
* Subroutine to actually try to execute a backslash command.
*
* The typical "success" result code is PSQL_CMD_SKIP_LINE, although some
* commands return something else. Failure result code is PSQL_CMD_ERROR,
* unless PSQL_CMD_UNKNOWN is more appropriate.
*/
static backslashResult
exec_command(const char *cmd,
PsqlScanState scan_state,
ConditionalStack cstack,
PQExpBuffer query_buf,
PQExpBuffer previous_buf)
{
backslashResult status;
bool active_branch = conditional_active(cstack);
/*
* In interactive mode, warn when we're ignoring a command within a false
* \if-branch. But we continue on, so as to parse and discard the right
* amount of parameter text. Each individual backslash command subroutine
* is responsible for doing nothing after discarding appropriate
* arguments, if !active_branch.
*/
if (pset.cur_cmd_interactive && !active_branch &&
!is_branching_command(cmd))
{
pg_log_warning("\\%s command ignored; use \\endif or Ctrl-C to exit current \\if block",
cmd);
}
if (strcmp(cmd, "a") == 0)
status = exec_command_a(scan_state, active_branch);
else if (strcmp(cmd, "bind") == 0)
status = exec_command_bind(scan_state, active_branch);
else if (strcmp(cmd, "C") == 0)
status = exec_command_C(scan_state, active_branch);
else if (strcmp(cmd, "c") == 0 || strcmp(cmd, "connect") == 0)
status = exec_command_connect(scan_state, active_branch);
else if (strcmp(cmd, "cd") == 0)
status = exec_command_cd(scan_state, active_branch, cmd);
else if (strcmp(cmd, "conninfo") == 0)
status = exec_command_conninfo(scan_state, active_branch);
else if (pg_strcasecmp(cmd, "copy") == 0)
status = exec_command_copy(scan_state, active_branch);
else if (strcmp(cmd, "copyright") == 0)
status = exec_command_copyright(scan_state, active_branch);
else if (strcmp(cmd, "crosstabview") == 0)
status = exec_command_crosstabview(scan_state, active_branch);
else if (cmd[0] == 'd')
status = exec_command_d(scan_state, active_branch, cmd);
else if (strcmp(cmd, "e") == 0 || strcmp(cmd, "edit") == 0)
status = exec_command_edit(scan_state, active_branch,
query_buf, previous_buf);
else if (strcmp(cmd, "ef") == 0)
status = exec_command_ef_ev(scan_state, active_branch, query_buf, true);
else if (strcmp(cmd, "ev") == 0)
status = exec_command_ef_ev(scan_state, active_branch, query_buf, false);
else if (strcmp(cmd, "echo") == 0 || strcmp(cmd, "qecho") == 0 ||
strcmp(cmd, "warn") == 0)
status = exec_command_echo(scan_state, active_branch, cmd);
else if (strcmp(cmd, "elif") == 0)
status = exec_command_elif(scan_state, cstack, query_buf);
else if (strcmp(cmd, "else") == 0)
status = exec_command_else(scan_state, cstack, query_buf);
else if (strcmp(cmd, "endif") == 0)
status = exec_command_endif(scan_state, cstack, query_buf);
else if (strcmp(cmd, "encoding") == 0)
status = exec_command_encoding(scan_state, active_branch);
else if (strcmp(cmd, "errverbose") == 0)
status = exec_command_errverbose(scan_state, active_branch);
else if (strcmp(cmd, "f") == 0)
status = exec_command_f(scan_state, active_branch);
else if (strcmp(cmd, "g") == 0 || strcmp(cmd, "gx") == 0)
status = exec_command_g(scan_state, active_branch, cmd);
else if (strcmp(cmd, "gdesc") == 0)
status = exec_command_gdesc(scan_state, active_branch);
else if (strcmp(cmd, "getenv") == 0)
status = exec_command_getenv(scan_state, active_branch, cmd);
else if (strcmp(cmd, "gexec") == 0)
status = exec_command_gexec(scan_state, active_branch);
else if (strcmp(cmd, "gset") == 0)
status = exec_command_gset(scan_state, active_branch);
else if (strcmp(cmd, "h") == 0 || strcmp(cmd, "help") == 0)
status = exec_command_help(scan_state, active_branch);
else if (strcmp(cmd, "H") == 0 || strcmp(cmd, "html") == 0)
status = exec_command_html(scan_state, active_branch);
else if (strcmp(cmd, "i") == 0 || strcmp(cmd, "include") == 0 ||
strcmp(cmd, "ir") == 0 || strcmp(cmd, "include_relative") == 0)
status = exec_command_include(scan_state, active_branch, cmd);
else if (strcmp(cmd, "if") == 0)
status = exec_command_if(scan_state, cstack, query_buf);
else if (strcmp(cmd, "l") == 0 || strcmp(cmd, "list") == 0 ||
strcmp(cmd, "l+") == 0 || strcmp(cmd, "list+") == 0)
status = exec_command_list(scan_state, active_branch, cmd);
else if (strncmp(cmd, "lo_", 3) == 0)
status = exec_command_lo(scan_state, active_branch, cmd);
else if (strcmp(cmd, "o") == 0 || strcmp(cmd, "out") == 0)
status = exec_command_out(scan_state, active_branch);
else if (strcmp(cmd, "p") == 0 || strcmp(cmd, "print") == 0)
status = exec_command_print(scan_state, active_branch,
query_buf, previous_buf);
else if (strcmp(cmd, "password") == 0)
status = exec_command_password(scan_state, active_branch);
else if (strcmp(cmd, "prompt") == 0)
status = exec_command_prompt(scan_state, active_branch, cmd);
else if (strcmp(cmd, "pset") == 0)
status = exec_command_pset(scan_state, active_branch);
else if (strcmp(cmd, "q") == 0 || strcmp(cmd, "quit") == 0)
status = exec_command_quit(scan_state, active_branch);
else if (strcmp(cmd, "r") == 0 || strcmp(cmd, "reset") == 0)
status = exec_command_reset(scan_state, active_branch, query_buf);
else if (strcmp(cmd, "s") == 0)
status = exec_command_s(scan_state, active_branch);
else if (strcmp(cmd, "set") == 0)
status = exec_command_set(scan_state, active_branch);
else if (strcmp(cmd, "setenv") == 0)
status = exec_command_setenv(scan_state, active_branch, cmd);
else if (strcmp(cmd, "sf") == 0 || strcmp(cmd, "sf+") == 0)
status = exec_command_sf_sv(scan_state, active_branch, cmd, true);
else if (strcmp(cmd, "sv") == 0 || strcmp(cmd, "sv+") == 0)
status = exec_command_sf_sv(scan_state, active_branch, cmd, false);
else if (strcmp(cmd, "t") == 0)
status = exec_command_t(scan_state, active_branch);
else if (strcmp(cmd, "T") == 0)
status = exec_command_T(scan_state, active_branch);
else if (strcmp(cmd, "timing") == 0)
status = exec_command_timing(scan_state, active_branch);
else if (strcmp(cmd, "unset") == 0)
status = exec_command_unset(scan_state, active_branch, cmd);
else if (strcmp(cmd, "w") == 0 || strcmp(cmd, "write") == 0)
status = exec_command_write(scan_state, active_branch, cmd,
query_buf, previous_buf);
else if (strcmp(cmd, "watch") == 0)
status = exec_command_watch(scan_state, active_branch,
query_buf, previous_buf);
else if (strcmp(cmd, "x") == 0)
status = exec_command_x(scan_state, active_branch);
else if (strcmp(cmd, "z") == 0 || strcmp(cmd, "zS") == 0)
status = exec_command_z(scan_state, active_branch, cmd);
else if (strcmp(cmd, "!") == 0)
status = exec_command_shell_escape(scan_state, active_branch);
else if (strcmp(cmd, "?") == 0)
status = exec_command_slash_command_help(scan_state, active_branch);
else
status = PSQL_CMD_UNKNOWN;
/*
* All the commands that return PSQL_CMD_SEND want to execute previous_buf
* if query_buf is empty. For convenience we implement that here, not in
* the individual command subroutines.
*/
if (status == PSQL_CMD_SEND)
(void) copy_previous_query(query_buf, previous_buf);
return status;
}
/*
* \a -- toggle field alignment
*
* This makes little sense but we keep it around.
*/
static backslashResult
exec_command_a(PsqlScanState scan_state, bool active_branch)
{
bool success = true;
if (active_branch)
{
if (pset.popt.topt.format != PRINT_ALIGNED)
success = do_pset("format", "aligned", &pset.popt, pset.quiet);
else
success = do_pset("format", "unaligned", &pset.popt, pset.quiet);
}
return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
}
/*
* \bind -- set query parameters
*/
static backslashResult
exec_command_bind(PsqlScanState scan_state, bool active_branch)
{
backslashResult status = PSQL_CMD_SKIP_LINE;
if (active_branch)
{
char *opt;
int nparams = 0;
int nalloc = 0;
pset.bind_params = NULL;
while ((opt = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false)))
{
nparams++;
if (nparams > nalloc)
{
nalloc = nalloc ? nalloc * 2 : 1;
pset.bind_params = pg_realloc_array(pset.bind_params, char *, nalloc);
}
pset.bind_params[nparams - 1] = opt;
}
pset.bind_nparams = nparams;
pset.bind_flag = true;
}
return status;
}
/*
* \C -- override table title (formerly change HTML caption)
*/
static backslashResult
exec_command_C(PsqlScanState scan_state, bool active_branch)
{
bool success = true;
if (active_branch)
{
char *opt = psql_scan_slash_option(scan_state,
OT_NORMAL, NULL, true);
success = do_pset("title", opt, &pset.popt, pset.quiet);
free(opt);
}
else
ignore_slash_options(scan_state);
return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
}
/*
* \c or \connect -- connect to database using the specified parameters.
*
* \c [-reuse-previous=BOOL] dbname user host port
*
* Specifying a parameter as '-' is equivalent to omitting it. Examples:
*
* \c - - hst Connect to current database on current port of
* host "hst" as current user.
* \c - usr - prt Connect to current database on port "prt" of current host
* as user "usr".
* \c dbs Connect to database "dbs" on current port of current host
* as current user.
*/
static backslashResult
exec_command_connect(PsqlScanState scan_state, bool active_branch)
{
bool success = true;
if (active_branch)
{
static const char prefix[] = "-reuse-previous=";
char *opt1,
*opt2,
*opt3,
*opt4;
enum trivalue reuse_previous = TRI_DEFAULT;
opt1 = read_connect_arg(scan_state);
if (opt1 != NULL && strncmp(opt1, prefix, sizeof(prefix) - 1) == 0)
{
bool on_off;
success = ParseVariableBool(opt1 + sizeof(prefix) - 1,
"-reuse-previous",
&on_off);
if (success)
{
reuse_previous = on_off ? TRI_YES : TRI_NO;
free(opt1);
opt1 = read_connect_arg(scan_state);
}
}
if (success) /* give up if reuse_previous was invalid */
{
opt2 = read_connect_arg(scan_state);
opt3 = read_connect_arg(scan_state);
opt4 = read_connect_arg(scan_state);
success = do_connect(reuse_previous, opt1, opt2, opt3, opt4);
free(opt2);
free(opt3);
free(opt4);
}
free(opt1);
}
else
ignore_slash_options(scan_state);
return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
}
/*
* \cd -- change directory
*/
static backslashResult
exec_command_cd(PsqlScanState scan_state, bool active_branch, const char *cmd)
{
bool success = true;
if (active_branch)
{
char *opt = psql_scan_slash_option(scan_state,
OT_NORMAL, NULL, true);
char *dir;
if (opt)
dir = opt;
else
{
#ifndef WIN32
/* This should match get_home_path() */
dir = getenv("HOME");
if (dir == NULL || dir[0] == '\0')
{
uid_t user_id = geteuid();
struct passwd *pw;
errno = 0; /* clear errno before call */
pw = getpwuid(user_id);
if (pw)
dir = pw->pw_dir;
else
{
pg_log_error("could not get home directory for user ID %ld: %s",
(long) user_id,
errno ? strerror(errno) : _("user does not exist"));
success = false;
}
}
#else /* WIN32 */
/*
* On Windows, 'cd' without arguments prints the current
* directory, so if someone wants to code this here instead...
*/
dir = "/";
#endif /* WIN32 */
}
if (success &&
chdir(dir) < 0)
{
pg_log_error("\\%s: could not change directory to \"%s\": %m",
cmd, dir);
success = false;
}
free(opt);
}
else
ignore_slash_options(scan_state);
return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
}
/*
* \conninfo -- display information about the current connection
*/
static backslashResult
exec_command_conninfo(PsqlScanState scan_state, bool active_branch)
{
if (active_branch)
{
char *db = PQdb(pset.db);
if (db == NULL)
printf(_("You are currently not connected to a database.\n"));
else
{
char *host = PQhost(pset.db);
char *hostaddr = PQhostaddr(pset.db);
if (is_unixsock_path(host))
{
/* hostaddr overrides host */
if (hostaddr && *hostaddr)
printf(_("You are connected to database \"%s\" as user \"%s\" on address \"%s\" at port \"%s\".\n"),
db, PQuser(pset.db), hostaddr, PQport(pset.db));
else
printf(_("You are connected to database \"%s\" as user \"%s\" via socket in \"%s\" at port \"%s\".\n"),
db, PQuser(pset.db), host, PQport(pset.db));
}
else
{
if (hostaddr && *hostaddr && strcmp(host, hostaddr) != 0)
printf(_("You are connected to database \"%s\" as user \"%s\" on host \"%s\" (address \"%s\") at port \"%s\".\n"),
db, PQuser(pset.db), host, hostaddr, PQport(pset.db));
else
printf(_("You are connected to database \"%s\" as user \"%s\" on host \"%s\" at port \"%s\".\n"),
db, PQuser(pset.db), host, PQport(pset.db));
}
printSSLInfo();
printGSSInfo();
}
}
return PSQL_CMD_SKIP_LINE;
}
/*
* \copy -- run a COPY command
*/
static backslashResult
exec_command_copy(PsqlScanState scan_state, bool active_branch)
{
bool success = true;
if (active_branch)
{
char *opt = psql_scan_slash_option(scan_state,
OT_WHOLE_LINE, NULL, false);
success = do_copy(opt);
free(opt);
}
else
ignore_slash_whole_line(scan_state);
return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
}
/*
* \copyright -- print copyright notice
*/
static backslashResult
exec_command_copyright(PsqlScanState scan_state, bool active_branch)
{
if (active_branch)
print_copyright();
return PSQL_CMD_SKIP_LINE;
}
/*
* \crosstabview -- execute a query and display result in crosstab
*/
static backslashResult
exec_command_crosstabview(PsqlScanState scan_state, bool active_branch)
{
backslashResult status = PSQL_CMD_SKIP_LINE;
if (active_branch)
{
int i;
for (i = 0; i < lengthof(pset.ctv_args); i++)
pset.ctv_args[i] = psql_scan_slash_option(scan_state,
OT_NORMAL, NULL, true);
pset.crosstab_flag = true;
status = PSQL_CMD_SEND;
}
else
ignore_slash_options(scan_state);
return status;
}
/*
* \d* commands
*/
static backslashResult
exec_command_d(PsqlScanState scan_state, bool active_branch, const char *cmd)
{
backslashResult status = PSQL_CMD_SKIP_LINE;
bool success = true;
if (active_branch)
{
char *pattern;
bool show_verbose,
show_system;
/* We don't do SQLID reduction on the pattern yet */
pattern = psql_scan_slash_option(scan_state,
OT_NORMAL, NULL, true);
show_verbose = strchr(cmd, '+') ? true : false;
show_system = strchr(cmd, 'S') ? true : false;
switch (cmd[1])
{
case '\0':
case '+':
case 'S':
if (pattern)
success = describeTableDetails(pattern, show_verbose, show_system);
else
/* standard listing of interesting things */
success = listTables("tvmsE", NULL, show_verbose, show_system);
break;
case 'A':
{
char *pattern2 = NULL;
if (pattern && cmd[2] != '\0' && cmd[2] != '+')
pattern2 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, true);
switch (cmd[2])
{
case '\0':
case '+':
success = describeAccessMethods(pattern, show_verbose);
break;
case 'c':
success = listOperatorClasses(pattern, pattern2, show_verbose);
break;
case 'f':
success = listOperatorFamilies(pattern, pattern2, show_verbose);
break;
case 'o':
success = listOpFamilyOperators(pattern, pattern2, show_verbose);
break;
case 'p':
success = listOpFamilyFunctions(pattern, pattern2, show_verbose);
break;
default:
status = PSQL_CMD_UNKNOWN;
break;
}
free(pattern2);
}
break;
case 'a':
success = describeAggregates(pattern, show_verbose, show_system);
break;
case 'b':
success = describeTablespaces(pattern, show_verbose);
break;
case 'c':
if (strncmp(cmd, "dconfig", 7) == 0)
success = describeConfigurationParameters(pattern,
show_verbose,
show_system);
else
success = listConversions(pattern,
show_verbose,
show_system);
break;
case 'C':
success = listCasts(pattern, show_verbose);
break;
case 'd':
if (strncmp(cmd, "ddp", 3) == 0)
success = listDefaultACLs(pattern);
else
success = objectDescription(pattern, show_system);
break;
case 'D':
success = listDomains(pattern, show_verbose, show_system);
break;
case 'f': /* function subsystem */
switch (cmd[2])
{
case '\0':
case '+':
case 'S':
case 'a':
case 'n':
case 'p':
case 't':
case 'w':
success = exec_command_dfo(scan_state, cmd, pattern,
show_verbose, show_system);
break;
default:
status = PSQL_CMD_UNKNOWN;
break;
}
break;
case 'g':
/* no longer distinct from \du */
success = describeRoles(pattern, show_verbose, show_system);
break;
case 'l':
success = listLargeObjects(show_verbose);
break;
case 'L':
success = listLanguages(pattern, show_verbose, show_system);
break;
case 'n':
success = listSchemas(pattern, show_verbose, show_system);
break;
case 'o':
success = exec_command_dfo(scan_state, cmd, pattern,
show_verbose, show_system);
break;
case 'O':
success = listCollations(pattern, show_verbose, show_system);
break;
case 'p':
success = permissionsList(pattern, show_system);
break;
case 'P':
{
switch (cmd[2])
{
case '\0':
case '+':
case 't':
case 'i':
case 'n':
success = listPartitionedTables(&cmd[2], pattern, show_verbose);
break;
default:
status = PSQL_CMD_UNKNOWN;
break;
}
}
break;
case 'T':
success = describeTypes(pattern, show_verbose, show_system);
break;
case 't':
case 'v':
case 'm':
case 'i':
case 's':
case 'E':
success = listTables(&cmd[1], pattern, show_verbose, show_system);
break;
case 'r':
if (cmd[2] == 'd' && cmd[3] == 's')
{
char *pattern2 = NULL;
if (pattern)
pattern2 = psql_scan_slash_option(scan_state,
OT_NORMAL, NULL, true);
success = listDbRoleSettings(pattern, pattern2);
free(pattern2);
}
else if (cmd[2] == 'g')
success = describeRoleGrants(pattern, show_system);
else
status = PSQL_CMD_UNKNOWN;
break;
case 'R':
switch (cmd[2])
{
case 'p':
if (show_verbose)
success = describePublications(pattern);
else
success = listPublications(pattern);
break;
case 's':
success = describeSubscriptions(pattern, show_verbose);
break;
default:
status = PSQL_CMD_UNKNOWN;
}
break;
case 'u':
success = describeRoles(pattern, show_verbose, show_system);
break;
case 'F': /* text search subsystem */
switch (cmd[2])
{
case '\0':
case '+':
success = listTSConfigs(pattern, show_verbose);
break;
case 'p':
success = listTSParsers(pattern, show_verbose);
break;
case 'd':
success = listTSDictionaries(pattern, show_verbose);
break;
case 't':
success = listTSTemplates(pattern, show_verbose);
break;
default:
status = PSQL_CMD_UNKNOWN;
break;
}
break;
case 'e': /* SQL/MED subsystem */
switch (cmd[2])
{
case 's':
success = listForeignServers(pattern, show_verbose);
break;
case 'u':
success = listUserMappings(pattern, show_verbose);
break;
case 'w':
success = listForeignDataWrappers(pattern, show_verbose);
break;
case 't':
success = listForeignTables(pattern, show_verbose);
break;
default:
status = PSQL_CMD_UNKNOWN;
break;
}
break;
case 'x': /* Extensions */
if (show_verbose)
success = listExtensionContents(pattern);
else
success = listExtensions(pattern);
break;
case 'X': /* Extended Statistics */
success = listExtendedStats(pattern);
break;
case 'y': /* Event Triggers */
success = listEventTriggers(pattern, show_verbose);
break;
default:
status = PSQL_CMD_UNKNOWN;
}
free(pattern);
}
else
ignore_slash_options(scan_state);
if (!success)
status = PSQL_CMD_ERROR;
return status;
}
/* \df and \do; messy enough to split out of exec_command_d */
static bool
exec_command_dfo(PsqlScanState scan_state, const char *cmd,
const char *pattern,
bool show_verbose, bool show_system)
{
bool success;
char *arg_patterns[FUNC_MAX_ARGS];
int num_arg_patterns = 0;
/* Collect argument-type patterns too */
if (pattern) /* otherwise it was just \df or \do */
{
char *ap;
while ((ap = psql_scan_slash_option(scan_state,
OT_NORMAL, NULL, true)) != NULL)
{
arg_patterns[num_arg_patterns++] = ap;
if (num_arg_patterns >= FUNC_MAX_ARGS)
break; /* protect limited-size array */
}
}
if (cmd[1] == 'f')
success = describeFunctions(&cmd[2], pattern,
arg_patterns, num_arg_patterns,
show_verbose, show_system);
else
success = describeOperators(pattern,
arg_patterns, num_arg_patterns,
show_verbose, show_system);
while (--num_arg_patterns >= 0)
free(arg_patterns[num_arg_patterns]);
return success;
}
/*
* \e or \edit -- edit the current query buffer, or edit a file and
* make it the query buffer
*/
static backslashResult
exec_command_edit(PsqlScanState scan_state, bool active_branch,
PQExpBuffer query_buf, PQExpBuffer previous_buf)
{
backslashResult status = PSQL_CMD_SKIP_LINE;
if (active_branch)
{
if (!query_buf)
{
pg_log_error("no query buffer");
status = PSQL_CMD_ERROR;
}
else
{
char *fname;
char *ln = NULL;
int lineno = -1;
fname = psql_scan_slash_option(scan_state,
OT_NORMAL, NULL, true);
if (fname)
{
/* try to get separate lineno arg */
ln = psql_scan_slash_option(scan_state,
OT_NORMAL, NULL, true);
if (ln == NULL)
{
/* only one arg; maybe it is lineno not fname */
if (fname[0] &&
strspn(fname, "0123456789") == strlen(fname))
{
/* all digits, so assume it is lineno */
ln = fname;
fname = NULL;
}
}
}
if (ln)
{
lineno = atoi(ln);
if (lineno < 1)
{
pg_log_error("invalid line number: %s", ln);
status = PSQL_CMD_ERROR;
}
}
if (status != PSQL_CMD_ERROR)
{
bool discard_on_quit;
expand_tilde(&fname);
if (fname)
{
canonicalize_path(fname);
/* Always clear buffer if the file isn't modified */
discard_on_quit = true;
}
else
{
/*
* If query_buf is empty, recall previous query for
* editing. But in that case, the query buffer should be
* emptied if editing doesn't modify the file.
*/
discard_on_quit = copy_previous_query(query_buf,
previous_buf);
}
if (do_edit(fname, query_buf, lineno, discard_on_quit, NULL))
status = PSQL_CMD_NEWEDIT;
else
status = PSQL_CMD_ERROR;
}
free(fname);
free(ln);
}
}
else
ignore_slash_options(scan_state);
return status;
}
/*
* \ef/\ev -- edit the named function/view, or
* present a blank CREATE FUNCTION/VIEW template if no argument is given
*/
static backslashResult
exec_command_ef_ev(PsqlScanState scan_state, bool active_branch,
PQExpBuffer query_buf, bool is_func)
{
backslashResult status = PSQL_CMD_SKIP_LINE;
if (active_branch)
{
char *obj_desc = psql_scan_slash_option(scan_state,
OT_WHOLE_LINE,
NULL, true);
int lineno = -1;
if (!query_buf)
{
pg_log_error("no query buffer");
status = PSQL_CMD_ERROR;
}
else
{
Oid obj_oid = InvalidOid;
EditableObjectType eot = is_func ? EditableFunction : EditableView;
lineno = strip_lineno_from_objdesc(obj_desc);
if (lineno == 0)
{
/* error already reported */
status = PSQL_CMD_ERROR;
}
else if (!obj_desc)
{
/* set up an empty command to fill in */
resetPQExpBuffer(query_buf);
if (is_func)
appendPQExpBufferStr(query_buf,
"CREATE FUNCTION ( )\n"
" RETURNS \n"
" LANGUAGE \n"
" -- common options: IMMUTABLE STABLE STRICT SECURITY DEFINER\n"
"AS $function$\n"
"\n$function$\n");
else
appendPQExpBufferStr(query_buf,
"CREATE VIEW AS\n"
" SELECT \n"
" -- something...\n");
}
else if (!lookup_object_oid(eot, obj_desc, &obj_oid))
{
/* error already reported */
status = PSQL_CMD_ERROR;
}
else if (!get_create_object_cmd(eot, obj_oid, query_buf))
{
/* error already reported */
status = PSQL_CMD_ERROR;
}
else if (is_func && lineno > 0)
{
/*
* lineno "1" should correspond to the first line of the
* function body. We expect that pg_get_functiondef() will
* emit that on a line beginning with "AS ", "BEGIN ", or
* "RETURN ", and that there can be no such line before the
* real start of the function body. Increment lineno by the
* number of lines before that line, so that it becomes
* relative to the first line of the function definition.
*/
const char *lines = query_buf->data;
while (*lines != '\0')
{
if (strncmp(lines, "AS ", 3) == 0 ||
strncmp(lines, "BEGIN ", 6) == 0 ||
strncmp(lines, "RETURN ", 7) == 0)
break;
lineno++;
/* find start of next line */
lines = strchr(lines, '\n');
if (!lines)
break;
lines++;
}
}
}
if (status != PSQL_CMD_ERROR)
{
bool edited = false;
if (!do_edit(NULL, query_buf, lineno, true, &edited))
status = PSQL_CMD_ERROR;
else if (!edited)
puts(_("No changes"));
else
status = PSQL_CMD_NEWEDIT;
}
free(obj_desc);
}
else
ignore_slash_whole_line(scan_state);
return status;
}
/*
* \echo, \qecho, and \warn -- echo arguments to stdout, query output, or stderr
*/
static backslashResult
exec_command_echo(PsqlScanState scan_state, bool active_branch, const char *cmd)
{
if (active_branch)
{
char *value;
char quoted;
bool no_newline = false;
bool first = true;
FILE *fout;
if (strcmp(cmd, "qecho") == 0)
fout = pset.queryFout;
else if (strcmp(cmd, "warn") == 0)
fout = stderr;
else
fout = stdout;
while ((value = psql_scan_slash_option(scan_state,
OT_NORMAL, "ed, false)))
{
if (first && !no_newline && !quoted && strcmp(value, "-n") == 0)
no_newline = true;
else
{
if (first)
first = false;
else
fputc(' ', fout);
fputs(value, fout);
}
free(value);
}
if (!no_newline)
fputs("\n", fout);
}
else
ignore_slash_options(scan_state);
return PSQL_CMD_SKIP_LINE;
}
/*
* \encoding -- set/show client side encoding
*/
static backslashResult
exec_command_encoding(PsqlScanState scan_state, bool active_branch)
{
if (active_branch)
{
char *encoding = psql_scan_slash_option(scan_state,
OT_NORMAL, NULL, false);
if (!encoding)
{
/* show encoding */
puts(pg_encoding_to_char(pset.encoding));
}
else
{
/* set encoding */
if (PQsetClientEncoding(pset.db, encoding) == -1)
pg_log_error("%s: invalid encoding name or conversion procedure not found", encoding);
else
{
/* save encoding info into psql internal data */
pset.encoding = PQclientEncoding(pset.db);
pset.popt.topt.encoding = pset.encoding;
SetVariable(pset.vars, "ENCODING",
pg_encoding_to_char(pset.encoding));
}
free(encoding);
}
}
else
ignore_slash_options(scan_state);
return PSQL_CMD_SKIP_LINE;
}
/*
* \errverbose -- display verbose message from last failed query
*/
static backslashResult
exec_command_errverbose(PsqlScanState scan_state, bool active_branch)
{
if (active_branch)
{
if (pset.last_error_result)
{
char *msg;
msg = PQresultVerboseErrorMessage(pset.last_error_result,
PQERRORS_VERBOSE,
PQSHOW_CONTEXT_ALWAYS);
if (msg)
{
pg_log_error("%s", msg);
PQfreemem(msg);
}
else
puts(_("out of memory"));
}
else
puts(_("There is no previous error."));
}
return PSQL_CMD_SKIP_LINE;
}
/*
* \f -- change field separator
*/
static backslashResult
exec_command_f(PsqlScanState scan_state, bool active_branch)
{
bool success = true;
if (active_branch)
{
char *fname = psql_scan_slash_option(scan_state,
OT_NORMAL, NULL, false);
success = do_pset("fieldsep", fname, &pset.popt, pset.quiet);
free(fname);
}
else
ignore_slash_options(scan_state);
return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
}
/*
* \g [(pset-option[=pset-value] ...)] [filename/shell-command]
* \gx [(pset-option[=pset-value] ...)] [filename/shell-command]
*
* Send the current query. If pset options are specified, they are made
* active just for this query. If a filename or pipe command is given,
* the query output goes there. \gx implicitly sets "expanded=on" along
* with any other pset options that are specified.
*/
static backslashResult
exec_command_g(PsqlScanState scan_state, bool active_branch, const char *cmd)
{
backslashResult status = PSQL_CMD_SKIP_LINE;
char *fname;
/*
* Because the option processing for this is fairly complicated, we do it
* and then decide whether the branch is active.
*/
fname = psql_scan_slash_option(scan_state,
OT_FILEPIPE, NULL, false);
if (fname && fname[0] == '(')
{
/* Consume pset options through trailing ')' ... */
status = process_command_g_options(fname + 1, scan_state,
active_branch, cmd);
free(fname);
/* ... and again attempt to scan the filename. */
fname = psql_scan_slash_option(scan_state,
OT_FILEPIPE, NULL, false);
}
if (status == PSQL_CMD_SKIP_LINE && active_branch)
{
if (!fname)
pset.gfname = NULL;
else
{
expand_tilde(&fname);
pset.gfname = pg_strdup(fname);
}
if (strcmp(cmd, "gx") == 0)
{
/* save settings if not done already, then force expanded=on */
if (pset.gsavepopt == NULL)
pset.gsavepopt = savePsetInfo(&pset.popt);
pset.popt.topt.expanded = 1;
}
status = PSQL_CMD_SEND;
}
free(fname);
return status;
}
/*
* Process parenthesized pset options for \g
*
* Note: okay to modify first_option, but not to free it; caller does that
*/
static backslashResult
process_command_g_options(char *first_option, PsqlScanState scan_state,
bool active_branch, const char *cmd)
{
bool success = true;
bool found_r_paren = false;
do
{
char *option;
size_t optlen;
/* If not first time through, collect a new option */
if (first_option)
option = first_option;
else
{
option = psql_scan_slash_option(scan_state,
OT_NORMAL, NULL, false);
if (!option)
{
if (active_branch)
{
pg_log_error("\\%s: missing right parenthesis", cmd);
success = false;
}
break;
}
}
/* Check for terminating right paren, and remove it from string */
optlen = strlen(option);
if (optlen > 0 && option[optlen - 1] == ')')
{
option[--optlen] = '\0';
found_r_paren = true;
}
/* If there was anything besides parentheses, parse/execute it */
if (optlen > 0)
{
/* We can have either "name" or "name=value" */
char *valptr = strchr(option, '=');
if (valptr)
*valptr++ = '\0';
if (active_branch)
{
/* save settings if not done already, then apply option */
if (pset.gsavepopt == NULL)
pset.gsavepopt = savePsetInfo(&pset.popt);
success &= do_pset(option, valptr, &pset.popt, true);
}
}
/* Clean up after this option. We should not free first_option. */
if (first_option)
first_option = NULL;
else
free(option);
} while (!found_r_paren);
/* If we failed after already changing some options, undo side-effects */
if (!success && active_branch && pset.gsavepopt)
{
restorePsetInfo(&pset.popt, pset.gsavepopt);
pset.gsavepopt = NULL;
}
return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
}
/*
* \gdesc -- describe query result
*/
static backslashResult
exec_command_gdesc(PsqlScanState scan_state, bool active_branch)
{
backslashResult status = PSQL_CMD_SKIP_LINE;
if (active_branch)
{
pset.gdesc_flag = true;
status = PSQL_CMD_SEND;
}
return status;
}
/*
* \getenv -- set variable from environment variable
*/
static backslashResult
exec_command_getenv(PsqlScanState scan_state, bool active_branch,
const char *cmd)
{
bool success = true;
if (active_branch)
{
char *myvar = psql_scan_slash_option(scan_state,
OT_NORMAL, NULL, false);
char *envvar = psql_scan_slash_option(scan_state,
OT_NORMAL, NULL, false);
if (!myvar || !envvar)
{
pg_log_error("\\%s: missing required argument", cmd);
success = false;
}
else
{
char *envval = getenv(envvar);
if (envval && !SetVariable(pset.vars, myvar, envval))
success = false;
}
free(myvar);
free(envvar);
}
else
ignore_slash_options(scan_state);
return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
}
/*
* \gexec -- send query and execute each field of result
*/
static backslashResult
exec_command_gexec(PsqlScanState scan_state, bool active_branch)
{
backslashResult status = PSQL_CMD_SKIP_LINE;
if (active_branch)
{
pset.gexec_flag = true;
status = PSQL_CMD_SEND;
}
return status;
}
/*
* \gset [prefix] -- send query and store result into variables
*/
static backslashResult
exec_command_gset(PsqlScanState scan_state, bool active_branch)
{
backslashResult status = PSQL_CMD_SKIP_LINE;
if (active_branch)
{
char *prefix = psql_scan_slash_option(scan_state,
OT_NORMAL, NULL, false);
if (prefix)
pset.gset_prefix = prefix;
else
{
/* we must set a non-NULL prefix to trigger storing */
pset.gset_prefix = pg_strdup("");
}
/* gset_prefix is freed later */
status = PSQL_CMD_SEND;
}
else
ignore_slash_options(scan_state);
return status;
}
/*
* \help [topic] -- print help about SQL commands
*/
static backslashResult
exec_command_help(PsqlScanState scan_state, bool active_branch)
{
if (active_branch)
{
char *opt = psql_scan_slash_option(scan_state,
OT_WHOLE_LINE, NULL, false);
size_t len;
/* strip any trailing spaces and semicolons */
if (opt)
{
len = strlen(opt);
while (len > 0 &&
(isspace((unsigned char) opt[len - 1])
|| opt[len - 1] == ';'))
opt[--len] = '\0';
}
helpSQL(opt, pset.popt.topt.pager);
free(opt);
}
else
ignore_slash_whole_line(scan_state);
return PSQL_CMD_SKIP_LINE;
}
/*
* \H and \html -- toggle HTML formatting
*/
static backslashResult
exec_command_html(PsqlScanState scan_state, bool active_branch)
{
bool success = true;
if (active_branch)
{
if (pset.popt.topt.format != PRINT_HTML)
success = do_pset("format", "html", &pset.popt, pset.quiet);
else
success = do_pset("format", "aligned", &pset.popt, pset.quiet);
}
return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
}
/*
* \i and \ir -- include a file
*/
static backslashResult
exec_command_include(PsqlScanState scan_state, bool active_branch, const char *cmd)
{
bool success = true;
if (active_branch)
{
char *fname = psql_scan_slash_option(scan_state,
OT_NORMAL, NULL, true);
if (!fname)
{
pg_log_error("\\%s: missing required argument", cmd);
success = false;
}
else
{
bool include_relative;
include_relative = (strcmp(cmd, "ir") == 0
|| strcmp(cmd, "include_relative") == 0);
expand_tilde(&fname);
success = (process_file(fname, include_relative) == EXIT_SUCCESS);
free(fname);
}
}
else
ignore_slash_options(scan_state);
return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
}
/*
* \if <expr> -- beginning of an \if..\endif block
*
* <expr> is parsed as a boolean expression. Invalid expressions will emit a
* warning and be treated as false. Statements that follow a false expression
* will be parsed but ignored. Note that in the case where an \if statement
* is itself within an inactive section of a block, then the entire inner
* \if..\endif block will be parsed but ignored.
*/
static backslashResult
exec_command_if(PsqlScanState scan_state, ConditionalStack cstack,
PQExpBuffer query_buf)
{
if (conditional_active(cstack))
{
/*
* First, push a new active stack entry; this ensures that the lexer
* will perform variable substitution and backtick evaluation while
* scanning the expression. (That should happen anyway, since we know
* we're in an active outer branch, but let's be sure.)
*/
conditional_stack_push(cstack, IFSTATE_TRUE);
/* Remember current query state in case we need to restore later */
save_query_text_state(scan_state, cstack, query_buf);
/*
* Evaluate the expression; if it's false, change to inactive state.
*/
if (!is_true_boolean_expression(scan_state, "\\if expression"))
conditional_stack_poke(cstack, IFSTATE_FALSE);
}
else
{
/*
* We're within an inactive outer branch, so this entire \if block
* will be ignored. We don't want to evaluate the expression, so push
* the "ignored" stack state before scanning it.
*/
conditional_stack_push(cstack, IFSTATE_IGNORED);
/* Remember current query state in case we need to restore later */
save_query_text_state(scan_state, cstack, query_buf);
ignore_boolean_expression(scan_state);
}
return PSQL_CMD_SKIP_LINE;
}
/*
* \elif <expr> -- alternative branch in an \if..\endif block
*
* <expr> is evaluated the same as in \if <expr>.
*/
static backslashResult
exec_command_elif(PsqlScanState scan_state, ConditionalStack cstack,
PQExpBuffer query_buf)
{
bool success = true;
switch (conditional_stack_peek(cstack))
{
case IFSTATE_TRUE:
/*
* Just finished active branch of this \if block. Update saved
* state so we will keep whatever data was put in query_buf by the
* active branch.
*/
save_query_text_state(scan_state, cstack, query_buf);
/*
* Discard \elif expression and ignore the rest until \endif.
* Switch state before reading expression to ensure proper lexer
* behavior.
*/
conditional_stack_poke(cstack, IFSTATE_IGNORED);
ignore_boolean_expression(scan_state);
break;
case IFSTATE_FALSE:
/*
* Discard any query text added by the just-skipped branch.
*/
discard_query_text(scan_state, cstack, query_buf);
/*
* Have not yet found a true expression in this \if block, so this
* might be the first. We have to change state before examining
* the expression, or the lexer won't do the right thing.
*/
conditional_stack_poke(cstack, IFSTATE_TRUE);
if (!is_true_boolean_expression(scan_state, "\\elif expression"))
conditional_stack_poke(cstack, IFSTATE_FALSE);
break;
case IFSTATE_IGNORED:
/*
* Discard any query text added by the just-skipped branch.
*/
discard_query_text(scan_state, cstack, query_buf);
/*
* Skip expression and move on. Either the \if block already had
* an active section, or whole block is being skipped.
*/
ignore_boolean_expression(scan_state);
break;
case IFSTATE_ELSE_TRUE:
case IFSTATE_ELSE_FALSE:
pg_log_error("\\elif: cannot occur after \\else");
success = false;
break;
case IFSTATE_NONE:
/* no \if to elif from */
pg_log_error("\\elif: no matching \\if");
success = false;
break;
}
return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
}
/*
* \else -- final alternative in an \if..\endif block
*
* Statements within an \else branch will only be executed if
* all previous \if and \elif expressions evaluated to false
* and the block was not itself being ignored.
*/
static backslashResult
exec_command_else(PsqlScanState scan_state, ConditionalStack cstack,
PQExpBuffer query_buf)
{
bool success = true;
switch (conditional_stack_peek(cstack))
{
case IFSTATE_TRUE:
/*
* Just finished active branch of this \if block. Update saved
* state so we will keep whatever data was put in query_buf by the
* active branch.
*/
save_query_text_state(scan_state, cstack, query_buf);
/* Now skip the \else branch */
conditional_stack_poke(cstack, IFSTATE_ELSE_FALSE);
break;
case IFSTATE_FALSE:
/*
* Discard any query text added by the just-skipped branch.
*/
discard_query_text(scan_state, cstack, query_buf);
/*
* We've not found any true \if or \elif expression, so execute
* the \else branch.
*/
conditional_stack_poke(cstack, IFSTATE_ELSE_TRUE);
break;
case IFSTATE_IGNORED:
/*
* Discard any query text added by the just-skipped branch.
*/
discard_query_text(scan_state, cstack, query_buf);
/*
* Either we previously processed the active branch of this \if,
* or the whole \if block is being skipped. Either way, skip the
* \else branch.
*/
conditional_stack_poke(cstack, IFSTATE_ELSE_FALSE);
break;
case IFSTATE_ELSE_TRUE:
case IFSTATE_ELSE_FALSE:
pg_log_error("\\else: cannot occur after \\else");
success = false;
break;
case IFSTATE_NONE:
/* no \if to else from */
pg_log_error("\\else: no matching \\if");
success = false;
break;
}
return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
}
/*
* \endif -- ends an \if...\endif block
*/
static backslashResult
exec_command_endif(PsqlScanState scan_state, ConditionalStack cstack,
PQExpBuffer query_buf)
{
bool success = true;
switch (conditional_stack_peek(cstack))
{
case IFSTATE_TRUE:
case IFSTATE_ELSE_TRUE:
/* Close the \if block, keeping the query text */
success = conditional_stack_pop(cstack);
Assert(success);
break;
case IFSTATE_FALSE:
case IFSTATE_IGNORED:
case IFSTATE_ELSE_FALSE:
/*
* Discard any query text added by the just-skipped branch.
*/
discard_query_text(scan_state, cstack, query_buf);
/* Close the \if block */
success = conditional_stack_pop(cstack);
Assert(success);
break;
case IFSTATE_NONE:
/* no \if to end */
pg_log_error("\\endif: no matching \\if");
success = false;
break;
}
return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
}
/*
* \l -- list databases
*/
static backslashResult
exec_command_list(PsqlScanState scan_state, bool active_branch, const char *cmd)
{
bool success = true;
if (active_branch)
{
char *pattern;
bool show_verbose;
pattern = psql_scan_slash_option(scan_state,
OT_NORMAL, NULL, true);
show_verbose = strchr(cmd, '+') ? true : false;
success = listAllDbs(pattern, show_verbose);
free(pattern);
}
else
ignore_slash_options(scan_state);
return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
}
/*
* \lo_* -- large object operations
*/
static backslashResult
exec_command_lo(PsqlScanState scan_state, bool active_branch, const char *cmd)
{
backslashResult status = PSQL_CMD_SKIP_LINE;
bool success = true;
if (active_branch)
{
char *opt1,
*opt2;
opt1 = psql_scan_slash_option(scan_state,
OT_NORMAL, NULL, true);
opt2 = psql_scan_slash_option(scan_state,
OT_NORMAL, NULL, true);
if (strcmp(cmd + 3, "export") == 0)
{
if (!opt2)
{
pg_log_error("\\%s: missing required argument", cmd);
success = false;
}
else
{
expand_tilde(&opt2);
success = do_lo_export(opt1, opt2);
}
}
else if (strcmp(cmd + 3, "import") == 0)
{
if (!opt1)
{
pg_log_error("\\%s: missing required argument", cmd);
success = false;
}
else
{
expand_tilde(&opt1);
success = do_lo_import(opt1, opt2);
}
}
else if (strcmp(cmd + 3, "list") == 0)
success = listLargeObjects(false);
else if (strcmp(cmd + 3, "list+") == 0)
success = listLargeObjects(true);
else if (strcmp(cmd + 3, "unlink") == 0)
{
if (!opt1)
{
pg_log_error("\\%s: missing required argument", cmd);
success = false;
}
else
success = do_lo_unlink(opt1);
}
else
status = PSQL_CMD_UNKNOWN;
free(opt1);
free(opt2);
}
else
ignore_slash_options(scan_state);
if (!success)
status = PSQL_CMD_ERROR;
return status;
}
/*
* \o -- set query output
*/
static backslashResult
exec_command_out(PsqlScanState scan_state, bool active_branch)
{
bool success = true;
if (active_branch)
{
char *fname = psql_scan_slash_option(scan_state,
OT_FILEPIPE, NULL, true);
expand_tilde(&fname);
success = setQFout(fname);
free(fname);
}
else
ignore_slash_filepipe(scan_state);
return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
}
/*
* \p -- print the current query buffer
*/
static backslashResult
exec_command_print(PsqlScanState scan_state, bool active_branch,
PQExpBuffer query_buf, PQExpBuffer previous_buf)
{
if (active_branch)
{
/*
* We want to print the same thing \g would execute, but not to change
* the query buffer state; so we can't use copy_previous_query().
* Also, beware of possibility that buffer pointers are NULL.
*/
if (query_buf && query_buf->len > 0)
puts(query_buf->data);
else if (previous_buf && previous_buf->len > 0)
puts(previous_buf->data);
else if (!pset.quiet)
puts(_("Query buffer is empty."));
fflush(stdout);
}
return PSQL_CMD_SKIP_LINE;
}
/*
* \password -- set user password
*/
static backslashResult
exec_command_password(PsqlScanState scan_state, bool active_branch)
{
bool success = true;
if (active_branch)
{
char *user = psql_scan_slash_option(scan_state,
OT_SQLID, NULL, true);
char *pw1 = NULL;
char *pw2 = NULL;
PQExpBufferData buf;
PromptInterruptContext prompt_ctx;
if (user == NULL)
{
/* By default, the command applies to CURRENT_USER */
PGresult *res;
res = PSQLexec("SELECT CURRENT_USER");
if (!res)
return PSQL_CMD_ERROR;
user = pg_strdup(PQgetvalue(res, 0, 0));
PQclear(res);
}
/* Set up to let SIGINT cancel simple_prompt_extended() */
prompt_ctx.jmpbuf = sigint_interrupt_jmp;
prompt_ctx.enabled = &sigint_interrupt_enabled;
prompt_ctx.canceled = false;
initPQExpBuffer(&buf);
printfPQExpBuffer(&buf, _("Enter new password for user \"%s\": "), user);
pw1 = simple_prompt_extended(buf.data, false, &prompt_ctx);
if (!prompt_ctx.canceled)
pw2 = simple_prompt_extended("Enter it again: ", false, &prompt_ctx);
if (prompt_ctx.canceled)
{
/* fail silently */
success = false;
}
else if (strcmp(pw1, pw2) != 0)
{
pg_log_error("Passwords didn't match.");
success = false;
}
else
{
char *encrypted_password;
encrypted_password = PQencryptPasswordConn(pset.db, pw1, user, NULL);
if (!encrypted_password)
{
pg_log_info("%s", PQerrorMessage(pset.db));
success = false;
}
else
{
PGresult *res;
printfPQExpBuffer(&buf, "ALTER USER %s PASSWORD ",
fmtId(user));
appendStringLiteralConn(&buf, encrypted_password, pset.db);
res = PSQLexec(buf.data);
if (!res)
success = false;
else
PQclear(res);
PQfreemem(encrypted_password);
}
}
free(user);
free(pw1);
free(pw2);
termPQExpBuffer(&buf);
}
else
ignore_slash_options(scan_state);
return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
}
/*
* \prompt -- prompt and set variable
*/
static backslashResult
exec_command_prompt(PsqlScanState scan_state, bool active_branch,
const char *cmd)
{
bool success = true;
if (active_branch)
{
char *opt,
*prompt_text = NULL;
char *arg1,
*arg2;
arg1 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
arg2 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
if (!arg1)
{
pg_log_error("\\%s: missing required argument", cmd);
success = false;
}
else
{
char *result;
PromptInterruptContext prompt_ctx;
/* Set up to let SIGINT cancel simple_prompt_extended() */
prompt_ctx.jmpbuf = sigint_interrupt_jmp;
prompt_ctx.enabled = &sigint_interrupt_enabled;
prompt_ctx.canceled = false;
if (arg2)
{
prompt_text = arg1;
opt = arg2;
}
else
opt = arg1;
if (!pset.inputfile)
{
result = simple_prompt_extended(prompt_text, true, &prompt_ctx);
}
else
{
if (prompt_text)
{
fputs(prompt_text, stdout);
fflush(stdout);
}
result = gets_fromFile(stdin);
if (!result)
{
pg_log_error("\\%s: could not read value for variable",
cmd);
success = false;
}
}
if (prompt_ctx.canceled ||
(result && !SetVariable(pset.vars, opt, result)))
success = false;
free(result);
free(prompt_text);
free(opt);
}
}
else
ignore_slash_options(scan_state);
return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
}
/*
* \pset -- set printing parameters
*/
static backslashResult
exec_command_pset(PsqlScanState scan_state, bool active_branch)
{
bool success = true;
if (active_branch)
{
char *opt0 = psql_scan_slash_option(scan_state,
OT_NORMAL, NULL, false);
char *opt1 = psql_scan_slash_option(scan_state,
OT_NORMAL, NULL, false);
if (!opt0)
{
/* list all variables */
int i;
static const char *const my_list[] = {
"border", "columns", "csv_fieldsep", "expanded", "fieldsep",
"fieldsep_zero", "footer", "format", "linestyle", "null",
"numericlocale", "pager", "pager_min_lines",
"recordsep", "recordsep_zero",
"tableattr", "title", "tuples_only",
"unicode_border_linestyle",
"unicode_column_linestyle",
"unicode_header_linestyle",
"xheader_width",
NULL
};
for (i = 0; my_list[i] != NULL; i++)
{
char *val = pset_value_string(my_list[i], &pset.popt);
printf("%-24s %s\n", my_list[i], val);
free(val);
}
success = true;
}
else
success = do_pset(opt0, opt1, &pset.popt, pset.quiet);
free(opt0);
free(opt1);
}
else
ignore_slash_options(scan_state);
return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
}
/*
* \q or \quit -- exit psql
*/
static backslashResult
exec_command_quit(PsqlScanState scan_state, bool active_branch)
{
backslashResult status = PSQL_CMD_SKIP_LINE;
if (active_branch)
status = PSQL_CMD_TERMINATE;
return status;
}
/*
* \r -- reset (clear) the query buffer
*/
static backslashResult
exec_command_reset(PsqlScanState scan_state, bool active_branch,
PQExpBuffer query_buf)
{
if (active_branch)
{
resetPQExpBuffer(query_buf);
psql_scan_reset(scan_state);
if (!pset.quiet)
puts(_("Query buffer reset (cleared)."));
}
return PSQL_CMD_SKIP_LINE;
}
/*
* \s -- save history in a file or show it on the screen
*/
static backslashResult
exec_command_s(PsqlScanState scan_state, bool active_branch)
{
bool success = true;
if (active_branch)
{
char *fname = psql_scan_slash_option(scan_state,
OT_NORMAL, NULL, true);
expand_tilde(&fname);
success = printHistory(fname, pset.popt.topt.pager);
if (success && !pset.quiet && fname)
printf(_("Wrote history to file \"%s\".\n"), fname);
if (!fname)
putchar('\n');
free(fname);
}
else
ignore_slash_options(scan_state);
return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
}
/*
* \set -- set variable
*/
static backslashResult
exec_command_set(PsqlScanState scan_state, bool active_branch)
{
bool success = true;
if (active_branch)
{
char *opt0 = psql_scan_slash_option(scan_state,
OT_NORMAL, NULL, false);
if (!opt0)
{
/* list all variables */
PrintVariables(pset.vars);
success = true;
}
else
{
/*
* Set variable to the concatenation of the arguments.
*/
char *newval;
char *opt;
opt = psql_scan_slash_option(scan_state,
OT_NORMAL, NULL, false);
newval = pg_strdup(opt ? opt : "");
free(opt);
while ((opt = psql_scan_slash_option(scan_state,
OT_NORMAL, NULL, false)))
{
newval = pg_realloc(newval, strlen(newval) + strlen(opt) + 1);
strcat(newval, opt);
free(opt);
}
if (!SetVariable(pset.vars, opt0, newval))
success = false;
free(newval);
}
free(opt0);
}
else
ignore_slash_options(scan_state);
return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
}
/*
* \setenv -- set environment variable
*/
static backslashResult
exec_command_setenv(PsqlScanState scan_state, bool active_branch,
const char *cmd)
{
bool success = true;
if (active_branch)
{
char *envvar = psql_scan_slash_option(scan_state,
OT_NORMAL, NULL, false);
char *envval = psql_scan_slash_option(scan_state,
OT_NORMAL, NULL, false);
if (!envvar)
{
pg_log_error("\\%s: missing required argument", cmd);
success = false;
}
else if (strchr(envvar, '=') != NULL)
{
pg_log_error("\\%s: environment variable name must not contain \"=\"",
cmd);
success = false;
}
else if (!envval)
{
/* No argument - unset the environment variable */
unsetenv(envvar);
success = true;
}
else
{
/* Set variable to the value of the next argument */
setenv(envvar, envval, 1);
success = true;
}
free(envvar);
free(envval);
}
else
ignore_slash_options(scan_state);
return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
}
/*
* \sf/\sv -- show a function/view's source code
*/
static backslashResult
exec_command_sf_sv(PsqlScanState scan_state, bool active_branch,
const char *cmd, bool is_func)
{
backslashResult status = PSQL_CMD_SKIP_LINE;
if (active_branch)
{
bool show_linenumbers = (strchr(cmd, '+') != NULL);
PQExpBuffer buf;
char *obj_desc;
Oid obj_oid = InvalidOid;
EditableObjectType eot = is_func ? EditableFunction : EditableView;
buf = createPQExpBuffer();
obj_desc = psql_scan_slash_option(scan_state,
OT_WHOLE_LINE, NULL, true);
if (!obj_desc)
{
if (is_func)
pg_log_error("function name is required");
else
pg_log_error("view name is required");
status = PSQL_CMD_ERROR;
}
else if (!lookup_object_oid(eot, obj_desc, &obj_oid))
{
/* error already reported */
status = PSQL_CMD_ERROR;
}
else if (!get_create_object_cmd(eot, obj_oid, buf))
{
/* error already reported */
status = PSQL_CMD_ERROR;
}
else
{
FILE *output;
bool is_pager;
/* Select output stream: stdout, pager, or file */
if (pset.queryFout == stdout)
{
/* count lines in function to see if pager is needed */
int lineno = count_lines_in_buf(buf);
output = PageOutput(lineno, &(pset.popt.topt));
is_pager = true;
}
else
{
/* use previously set output file, without pager */
output = pset.queryFout;
is_pager = false;
}
if (show_linenumbers)
{
/* add line numbers */
print_with_linenumbers(output, buf->data, is_func);
}
else
{
/* just send the definition to output */
fputs(buf->data, output);
}
if (is_pager)
ClosePager(output);
}
free(obj_desc);
destroyPQExpBuffer(buf);
}
else
ignore_slash_whole_line(scan_state);
return status;
}
/*
* \t -- turn off table headers and row count
*/
static backslashResult
exec_command_t(PsqlScanState scan_state, bool active_branch)
{
bool success = true;
if (active_branch)
{
char *opt = psql_scan_slash_option(scan_state,
OT_NORMAL, NULL, true);
success = do_pset("tuples_only", opt, &pset.popt, pset.quiet);
free(opt);
}
else
ignore_slash_options(scan_state);
return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
}
/*
* \T -- define html <table ...> attributes
*/
static backslashResult
exec_command_T(PsqlScanState scan_state, bool active_branch)
{
bool success = true;
if (active_branch)
{
char *value = psql_scan_slash_option(scan_state,
OT_NORMAL, NULL, false);
success = do_pset("tableattr", value, &pset.popt, pset.quiet);
free(value);
}
else
ignore_slash_options(scan_state);
return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
}
/*
* \timing -- enable/disable timing of queries
*/
static backslashResult
exec_command_timing(PsqlScanState scan_state, bool active_branch)
{
bool success = true;
if (active_branch)
{
char *opt = psql_scan_slash_option(scan_state,
OT_NORMAL, NULL, false);
if (opt)
success = ParseVariableBool(opt, "\\timing", &pset.timing);
else
pset.timing = !pset.timing;
if (!pset.quiet)
{
if (pset.timing)
puts(_("Timing is on."));
else
puts(_("Timing is off."));
}
free(opt);
}
else
ignore_slash_options(scan_state);
return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
}
/*
* \unset -- unset variable
*/
static backslashResult
exec_command_unset(PsqlScanState scan_state, bool active_branch,
const char *cmd)
{
bool success = true;
if (active_branch)
{
char *opt = psql_scan_slash_option(scan_state,
OT_NORMAL, NULL, false);
if (!opt)
{
pg_log_error("\\%s: missing required argument", cmd);
success = false;
}
else if (!SetVariable(pset.vars, opt, NULL))
success = false;
free(opt);
}
else
ignore_slash_options(scan_state);
return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
}
/*
* \w -- write query buffer to file
*/
static backslashResult
exec_command_write(PsqlScanState scan_state, bool active_branch,
const char *cmd,
PQExpBuffer query_buf, PQExpBuffer previous_buf)
{
backslashResult status = PSQL_CMD_SKIP_LINE;
if (active_branch)
{
char *fname = psql_scan_slash_option(scan_state,
OT_FILEPIPE, NULL, true);
FILE *fd = NULL;
bool is_pipe = false;
if (!query_buf)
{
pg_log_error("no query buffer");
status = PSQL_CMD_ERROR;
}
else
{
if (!fname)
{
pg_log_error("\\%s: missing required argument", cmd);
status = PSQL_CMD_ERROR;
}
else
{
expand_tilde(&fname);
if (fname[0] == '|')
{
is_pipe = true;
fflush(NULL);
disable_sigpipe_trap();
fd = popen(&fname[1], "w");
}
else
{
canonicalize_path(fname);
fd = fopen(fname, "w");
}
if (!fd)
{
pg_log_error("%s: %m", fname);
status = PSQL_CMD_ERROR;
}
}
}
if (fd)
{
int result;
/*
* We want to print the same thing \g would execute, but not to
* change the query buffer state; so we can't use
* copy_previous_query(). Also, beware of possibility that buffer
* pointers are NULL.
*/
if (query_buf && query_buf->len > 0)
fprintf(fd, "%s\n", query_buf->data);
else if (previous_buf && previous_buf->len > 0)
fprintf(fd, "%s\n", previous_buf->data);
if (is_pipe)
{
result = pclose(fd);
if (result != 0)
{
pg_log_error("%s: %s", fname, wait_result_to_str(result));
status = PSQL_CMD_ERROR;
}
SetShellResultVariables(result);
}
else
{
result = fclose(fd);
if (result == EOF)
{
pg_log_error("%s: %m", fname);
status = PSQL_CMD_ERROR;
}
}
}
if (is_pipe)
restore_sigpipe_trap();
free(fname);
}
else
ignore_slash_filepipe(scan_state);
return status;
}
/*
* \watch -- execute a query every N seconds.
* Optionally, stop after M iterations.
*/
static backslashResult
exec_command_watch(PsqlScanState scan_state, bool active_branch,
PQExpBuffer query_buf, PQExpBuffer previous_buf)
{
bool success = true;
if (active_branch)
{
bool have_sleep = false;
bool have_iter = false;
double sleep = 2;
int iter = 0;
/*
* Parse arguments. We allow either an unlabeled interval or
* "name=value", where name is from the set ('i', 'interval', 'c',
* 'count').
*/
while (success)
{
char *opt = psql_scan_slash_option(scan_state,
OT_NORMAL, NULL, true);
char *valptr;
char *opt_end;
if (!opt)
break; /* no more arguments */
valptr = strchr(opt, '=');
if (valptr)
{
/* Labeled argument */
valptr++;
if (strncmp("i=", opt, strlen("i=")) == 0 ||
strncmp("interval=", opt, strlen("interval=")) == 0)
{
if (have_sleep)
{
pg_log_error("\\watch: interval value is specified more than once");
success = false;
}
else
{
have_sleep = true;
errno = 0;
sleep = strtod(valptr, &opt_end);
if (sleep < 0 || *opt_end || errno == ERANGE)
{
pg_log_error("\\watch: incorrect interval value \"%s\"", valptr);
success = false;
}
}
}
else if (strncmp("c=", opt, strlen("c=")) == 0 ||
strncmp("count=", opt, strlen("count=")) == 0)
{
if (have_iter)
{
pg_log_error("\\watch: iteration count is specified more than once");
success = false;
}
else
{
have_iter = true;
errno = 0;
iter = strtoint(valptr, &opt_end, 10);
if (iter <= 0 || *opt_end || errno == ERANGE)
{
pg_log_error("\\watch: incorrect iteration count \"%s\"", valptr);
success = false;
}
}
}
else
{
pg_log_error("\\watch: unrecognized parameter \"%s\"", opt);
success = false;
}
}
else
{
/* Unlabeled argument: take it as interval */
if (have_sleep)
{
pg_log_error("\\watch: interval value is specified more than once");
success = false;
}
else
{
have_sleep = true;
errno = 0;
sleep = strtod(opt, &opt_end);
if (sleep < 0 || *opt_end || errno == ERANGE)
{
pg_log_error("\\watch: incorrect interval value \"%s\"", opt);
success = false;
}
}
}
free(opt);
}
/* If we parsed arguments successfully, do the command */
if (success)
{
/* If query_buf is empty, recall and execute previous query */
(void) copy_previous_query(query_buf, previous_buf);
success = do_watch(query_buf, sleep, iter);
}
/* Reset the query buffer as though for \r */
resetPQExpBuffer(query_buf);
psql_scan_reset(scan_state);
}
else
ignore_slash_options(scan_state);
return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
}
/*
* \x -- set or toggle expanded table representation
*/
static backslashResult
exec_command_x(PsqlScanState scan_state, bool active_branch)
{
bool success = true;
if (active_branch)
{
char *opt = psql_scan_slash_option(scan_state,
OT_NORMAL, NULL, true);
success = do_pset("expanded", opt, &pset.popt, pset.quiet);
free(opt);
}
else
ignore_slash_options(scan_state);
return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
}
/*
* \z -- list table privileges (equivalent to \dp)
*/
static backslashResult
exec_command_z(PsqlScanState scan_state, bool active_branch, const char *cmd)
{
bool success = true;
if (active_branch)
{
char *pattern;
bool show_system;
pattern = psql_scan_slash_option(scan_state,
OT_NORMAL, NULL, true);
show_system = strchr(cmd, 'S') ? true : false;
success = permissionsList(pattern, show_system);
free(pattern);
}
else
ignore_slash_options(scan_state);
return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
}
/*
* \! -- execute shell command
*/
static backslashResult
exec_command_shell_escape(PsqlScanState scan_state, bool active_branch)
{
bool success = true;
if (active_branch)
{
char *opt = psql_scan_slash_option(scan_state,
OT_WHOLE_LINE, NULL, false);
success = do_shell(opt);
free(opt);
}
else
ignore_slash_whole_line(scan_state);
return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
}
/*
* \? -- print help about backslash commands
*/
static backslashResult
exec_command_slash_command_help(PsqlScanState scan_state, bool active_branch)
{
if (active_branch)
{
char *opt0 = psql_scan_slash_option(scan_state,
OT_NORMAL, NULL, false);
if (!opt0 || strcmp(opt0, "commands") == 0)
slashUsage(pset.popt.topt.pager);
else if (strcmp(opt0, "options") == 0)
usage(pset.popt.topt.pager);
else if (strcmp(opt0, "variables") == 0)
helpVariables(pset.popt.topt.pager);
else
slashUsage(pset.popt.topt.pager);
free(opt0);
}
else
ignore_slash_options(scan_state);
return PSQL_CMD_SKIP_LINE;
}
/*
* Read and interpret an argument to the \connect slash command.
*
* Returns a malloc'd string, or NULL if no/empty argument.
*/
static char *
read_connect_arg(PsqlScanState scan_state)
{
char *result;
char quote;
/*
* Ideally we should treat the arguments as SQL identifiers. But for
* backwards compatibility with 7.2 and older pg_dump files, we have to
* take unquoted arguments verbatim (don't downcase them). For now,
* double-quoted arguments may be stripped of double quotes (as if SQL
* identifiers). By 7.4 or so, pg_dump files can be expected to
* double-quote all mixed-case \connect arguments, and then we can get rid
* of OT_SQLIDHACK.
*/
result = psql_scan_slash_option(scan_state, OT_SQLIDHACK, "e, true);
if (!result)
return NULL;
if (quote)
return result;
if (*result == '\0' || strcmp(result, "-") == 0)
{
free(result);
return NULL;
}
return result;
}
/*
* Read a boolean expression, return it as a PQExpBuffer string.
*
* Note: anything more or less than one token will certainly fail to be
* parsed by ParseVariableBool, so we don't worry about complaining here.
* This routine's return data structure will need to be rethought anyway
* to support likely future extensions such as "\if defined VARNAME".
*/
static PQExpBuffer
gather_boolean_expression(PsqlScanState scan_state)
{
PQExpBuffer exp_buf = createPQExpBuffer();
int num_options = 0;
char *value;
/* collect all arguments for the conditional command into exp_buf */
while ((value = psql_scan_slash_option(scan_state,
OT_NORMAL, NULL, false)) != NULL)
{
/* add spaces between tokens */
if (num_options > 0)
appendPQExpBufferChar(exp_buf, ' ');
appendPQExpBufferStr(exp_buf, value);
num_options++;
free(value);
}
return exp_buf;
}
/*
* Read a boolean expression, return true if the expression
* was a valid boolean expression that evaluated to true.
* Otherwise return false.
*
* Note: conditional stack's top state must be active, else lexer will
* fail to expand variables and backticks.
*/
static bool
is_true_boolean_expression(PsqlScanState scan_state, const char *name)
{
PQExpBuffer buf = gather_boolean_expression(scan_state);
bool value = false;
bool success = ParseVariableBool(buf->data, name, &value);
destroyPQExpBuffer(buf);
return success && value;
}
/*
* Read a boolean expression, but do nothing with it.
*
* Note: conditional stack's top state must be INACTIVE, else lexer will
* expand variables and backticks, which we do not want here.
*/
static void
ignore_boolean_expression(PsqlScanState scan_state)
{
PQExpBuffer buf = gather_boolean_expression(scan_state);
destroyPQExpBuffer(buf);
}
/*
* Read and discard "normal" slash command options.
*
* This should be used for inactive-branch processing of any slash command
* that eats one or more OT_NORMAL, OT_SQLID, or OT_SQLIDHACK parameters.
* We don't need to worry about exactly how many it would eat, since the
* cleanup logic in HandleSlashCmds would silently discard any extras anyway.
*/
static void
ignore_slash_options(PsqlScanState scan_state)
{
char *arg;
while ((arg = psql_scan_slash_option(scan_state,
OT_NORMAL, NULL, false)) != NULL)
free(arg);
}
/*
* Read and discard FILEPIPE slash command argument.
*
* This *MUST* be used for inactive-branch processing of any slash command
* that takes an OT_FILEPIPE option. Otherwise we might consume a different
* amount of option text in active and inactive cases.
*/
static void
ignore_slash_filepipe(PsqlScanState scan_state)
{
char *arg = psql_scan_slash_option(scan_state,
OT_FILEPIPE, NULL, false);
free(arg);
}
/*
* Read and discard whole-line slash command argument.
*
* This *MUST* be used for inactive-branch processing of any slash command
* that takes an OT_WHOLE_LINE option. Otherwise we might consume a different
* amount of option text in active and inactive cases.
*/
static void
ignore_slash_whole_line(PsqlScanState scan_state)
{
char *arg = psql_scan_slash_option(scan_state,
OT_WHOLE_LINE, NULL, false);
free(arg);
}
/*
* Return true if the command given is a branching command.
*/
static bool
is_branching_command(const char *cmd)
{
return (strcmp(cmd, "if") == 0 ||
strcmp(cmd, "elif") == 0 ||
strcmp(cmd, "else") == 0 ||
strcmp(cmd, "endif") == 0);
}
/*
* Prepare to possibly restore query buffer to its current state
* (cf. discard_query_text).
*
* We need to remember the length of the query buffer, and the lexer's
* notion of the parenthesis nesting depth.
*/
static void
save_query_text_state(PsqlScanState scan_state, ConditionalStack cstack,
PQExpBuffer query_buf)
{
if (query_buf)
conditional_stack_set_query_len(cstack, query_buf->len);
conditional_stack_set_paren_depth(cstack,
psql_scan_get_paren_depth(scan_state));
}
/*
* Discard any query text absorbed during an inactive conditional branch.
*
* We must discard data that was appended to query_buf during an inactive
* \if branch. We don't have to do anything there if there's no query_buf.
*
* Also, reset the lexer state to the same paren depth there was before.
* (The rest of its state doesn't need attention, since we could not be
* inside a comment or literal or partial token.)
*/
static void
discard_query_text(PsqlScanState scan_state, ConditionalStack cstack,
PQExpBuffer query_buf)
{
if (query_buf)
{
int new_len = conditional_stack_get_query_len(cstack);
Assert(new_len >= 0 && new_len <= query_buf->len);
query_buf->len = new_len;
query_buf->data[new_len] = '\0';
}
psql_scan_set_paren_depth(scan_state,
conditional_stack_get_paren_depth(cstack));
}
/*
* If query_buf is empty, copy previous_buf into it.
*
* This is used by various slash commands for which re-execution of a
* previous query is a common usage. For convenience, we allow the
* case of query_buf == NULL (and do nothing).
*
* Returns "true" if the previous query was copied into the query
* buffer, else "false".
*/
static bool
copy_previous_query(PQExpBuffer query_buf, PQExpBuffer previous_buf)
{
if (query_buf && query_buf->len == 0)
{
appendPQExpBufferStr(query_buf, previous_buf->data);
return true;
}
return false;
}
/*
* Ask the user for a password; 'username' is the username the
* password is for, if one has been explicitly specified.
* Returns a malloc'd string.
* If 'canceled' is provided, *canceled will be set to true if the prompt
* is canceled via SIGINT, and to false otherwise.
*/
static char *
prompt_for_password(const char *username, bool *canceled)
{
char *result;
PromptInterruptContext prompt_ctx;
/* Set up to let SIGINT cancel simple_prompt_extended() */
prompt_ctx.jmpbuf = sigint_interrupt_jmp;
prompt_ctx.enabled = &sigint_interrupt_enabled;
prompt_ctx.canceled = false;
if (username == NULL || username[0] == '\0')
result = simple_prompt_extended("Password: ", false, &prompt_ctx);
else
{
char *prompt_text;
prompt_text = psprintf(_("Password for user %s: "), username);
result = simple_prompt_extended(prompt_text, false, &prompt_ctx);
free(prompt_text);
}
if (canceled)
*canceled = prompt_ctx.canceled;
return result;
}
static bool
param_is_newly_set(const char *old_val, const char *new_val)
{
if (new_val == NULL)
return false;
if (old_val == NULL || strcmp(old_val, new_val) != 0)
return true;
return false;
}
/*
* do_connect -- handler for \connect
*
* Connects to a database with given parameters. If we are told to re-use
* parameters, parameters from the previous connection are used where the
* command's own options do not supply a value. Otherwise, libpq defaults
* are used.
*
* In interactive mode, if connection fails with the given parameters,
* the old connection will be kept.
*/
static bool
do_connect(enum trivalue reuse_previous_specification,
char *dbname, char *user, char *host, char *port)
{
PGconn *o_conn = pset.db,
*n_conn = NULL;
PQconninfoOption *cinfo;
int nconnopts = 0;
bool same_host = false;
char *password = NULL;
char *client_encoding;
bool success = true;
bool keep_password = true;
bool has_connection_string;
bool reuse_previous;
has_connection_string = dbname ?
recognized_connection_string(dbname) : false;
/* Complain if we have additional arguments after a connection string. */
if (has_connection_string && (user || host || port))
{
pg_log_error("Do not give user, host, or port separately when using a connection string");
return false;
}
switch (reuse_previous_specification)
{
case TRI_YES:
reuse_previous = true;
break;
case TRI_NO:
reuse_previous = false;
break;
default:
reuse_previous = !has_connection_string;
break;
}
/*
* If we intend to re-use connection parameters, collect them out of the
* old connection, then replace individual values as necessary. (We may
* need to resort to looking at pset.dead_conn, if the connection died
* previously.) Otherwise, obtain a PQconninfoOption array containing
* libpq's defaults, and modify that. Note this function assumes that
* PQconninfo, PQconndefaults, and PQconninfoParse will all produce arrays
* containing the same options in the same order.
*/
if (reuse_previous)
{
if (o_conn)
cinfo = PQconninfo(o_conn);
else if (pset.dead_conn)
cinfo = PQconninfo(pset.dead_conn);
else
{
/* This is reachable after a non-interactive \connect failure */
pg_log_error("No database connection exists to re-use parameters from");
return false;
}
}
else
cinfo = PQconndefaults();
if (cinfo)
{
if (has_connection_string)
{
/* Parse the connstring and insert values into cinfo */
PQconninfoOption *replcinfo;
char *errmsg;
replcinfo = PQconninfoParse(dbname, &errmsg);
if (replcinfo)
{
PQconninfoOption *ci;
PQconninfoOption *replci;
bool have_password = false;
for (ci = cinfo, replci = replcinfo;
ci->keyword && replci->keyword;
ci++, replci++)
{
Assert(strcmp(ci->keyword, replci->keyword) == 0);
/* Insert value from connstring if one was provided */
if (replci->val)
{
/*
* We know that both val strings were allocated by
* libpq, so the least messy way to avoid memory leaks
* is to swap them.
*/
char *swap = replci->val;
replci->val = ci->val;
ci->val = swap;
/*
* Check whether connstring provides options affecting
* password re-use. While any change in user, host,
* hostaddr, or port causes us to ignore the old
* connection's password, we don't force that for
* dbname, since passwords aren't database-specific.
*/
if (replci->val == NULL ||
strcmp(ci->val, replci->val) != 0)
{
if (strcmp(replci->keyword, "user") == 0 ||
strcmp(replci->keyword, "host") == 0 ||
strcmp(replci->keyword, "hostaddr") == 0 ||
strcmp(replci->keyword, "port") == 0)
keep_password = false;
}
/* Also note whether connstring contains a password. */
if (strcmp(replci->keyword, "password") == 0)
have_password = true;
}
else if (!reuse_previous)
{
/*
* When we have a connstring and are not re-using
* parameters, swap *all* entries, even those not set
* by the connstring. This avoids absorbing
* environment-dependent defaults from the result of
* PQconndefaults(). We don't want to do that because
* they'd override service-file entries if the
* connstring specifies a service parameter, whereas
* the priority should be the other way around. libpq
* can certainly recompute any defaults we don't pass
* here. (In this situation, it's a bit wasteful to
* have called PQconndefaults() at all, but not doing
* so would require yet another major code path here.)
*/
replci->val = ci->val;
ci->val = NULL;
}
}
Assert(ci->keyword == NULL && replci->keyword == NULL);
/* While here, determine how many option slots there are */
nconnopts = ci - cinfo;
PQconninfoFree(replcinfo);
/*
* If the connstring contains a password, tell the loop below
* that we may use it, regardless of other settings (i.e.,
* cinfo's password is no longer an "old" password).
*/
if (have_password)
keep_password = true;
/* Don't let code below try to inject dbname into params. */
dbname = NULL;
}
else
{
/* PQconninfoParse failed */
if (errmsg)
{
pg_log_error("%s", errmsg);
PQfreemem(errmsg);
}
else
pg_log_error("out of memory");
success = false;
}
}
else
{
/*
* If dbname isn't a connection string, then we'll inject it and
* the other parameters into the keyword array below. (We can't
* easily insert them into the cinfo array because of memory
* management issues: PQconninfoFree would misbehave on Windows.)
* However, to avoid dependencies on the order in which parameters
* appear in the array, make a preliminary scan to set
* keep_password and same_host correctly.
*
* While any change in user, host, or port causes us to ignore the
* old connection's password, we don't force that for dbname,
* since passwords aren't database-specific.
*/
PQconninfoOption *ci;
for (ci = cinfo; ci->keyword; ci++)
{
if (user && strcmp(ci->keyword, "user") == 0)
{
if (!(ci->val && strcmp(user, ci->val) == 0))
keep_password = false;
}
else if (host && strcmp(ci->keyword, "host") == 0)
{
if (ci->val && strcmp(host, ci->val) == 0)
same_host = true;
else
keep_password = false;
}
else if (port && strcmp(ci->keyword, "port") == 0)
{
if (!(ci->val && strcmp(port, ci->val) == 0))
keep_password = false;
}
}
/* While here, determine how many option slots there are */
nconnopts = ci - cinfo;
}
}
else
{
/* We failed to create the cinfo structure */
pg_log_error("out of memory");
success = false;
}
/*
* If the user asked to be prompted for a password, ask for one now. If
* not, use the password from the old connection, provided the username
* etc have not changed. Otherwise, try to connect without a password
* first, and then ask for a password if needed.
*
* XXX: this behavior leads to spurious connection attempts recorded in
* the postmaster's log. But libpq offers no API that would let us obtain
* a password and then continue with the first connection attempt.
*/
if (pset.getPassword == TRI_YES && success)
{
bool canceled = false;
/*
* If a connstring or URI is provided, we don't know which username
* will be used, since we haven't dug that out of the connstring.
* Don't risk issuing a misleading prompt. As in startup.c, it does
* not seem worth working harder, since this getPassword setting is
* normally only used in noninteractive cases.
*/
password = prompt_for_password(has_connection_string ? NULL : user,
&canceled);
success = !canceled;
}
/*
* Consider whether to force client_encoding to "auto" (overriding
* anything in the connection string). We do so if we have a terminal
* connection and there is no PGCLIENTENCODING environment setting.
*/
if (pset.notty || getenv("PGCLIENTENCODING"))
client_encoding = NULL;
else
client_encoding = "auto";
/* Loop till we have a connection or fail, which we might've already */
while (success)
{
const char **keywords = pg_malloc((nconnopts + 1) * sizeof(*keywords));
const char **values = pg_malloc((nconnopts + 1) * sizeof(*values));
int paramnum = 0;
PQconninfoOption *ci;
/*
* Copy non-default settings into the PQconnectdbParams parameter
* arrays; but inject any values specified old-style, as well as any
* interactively-obtained password, and a couple of fields we want to
* set forcibly.
*
* If you change this code, see also the initial-connection code in
* main().
*/
for (ci = cinfo; ci->keyword; ci++)
{
keywords[paramnum] = ci->keyword;
if (dbname && strcmp(ci->keyword, "dbname") == 0)
values[paramnum++] = dbname;
else if (user && strcmp(ci->keyword, "user") == 0)
values[paramnum++] = user;
else if (host && strcmp(ci->keyword, "host") == 0)
values[paramnum++] = host;
else if (host && !same_host && strcmp(ci->keyword, "hostaddr") == 0)
{
/* If we're changing the host value, drop any old hostaddr */
values[paramnum++] = NULL;
}
else if (port && strcmp(ci->keyword, "port") == 0)
values[paramnum++] = port;
/* If !keep_password, we unconditionally drop old password */
else if ((password || !keep_password) &&
strcmp(ci->keyword, "password") == 0)
values[paramnum++] = password;
else if (strcmp(ci->keyword, "fallback_application_name") == 0)
values[paramnum++] = pset.progname;
else if (client_encoding &&
strcmp(ci->keyword, "client_encoding") == 0)
values[paramnum++] = client_encoding;
else if (ci->val)
values[paramnum++] = ci->val;
/* else, don't bother making libpq parse this keyword */
}
/* add array terminator */
keywords[paramnum] = NULL;
values[paramnum] = NULL;
/* Note we do not want libpq to re-expand the dbname parameter */
n_conn = PQconnectdbParams(keywords, values, false);
pg_free(keywords);
pg_free(values);
if (PQstatus(n_conn) == CONNECTION_OK)
break;
/*
* Connection attempt failed; either retry the connection attempt with
* a new password, or give up.
*/
if (!password && PQconnectionNeedsPassword(n_conn) && pset.getPassword != TRI_NO)
{
bool canceled = false;
/*
* Prompt for password using the username we actually connected
* with --- it might've come out of "dbname" rather than "user".
*/
password = prompt_for_password(PQuser(n_conn), &canceled);
PQfinish(n_conn);
n_conn = NULL;
success = !canceled;
continue;
}
/*
* We'll report the error below ... unless n_conn is NULL, indicating
* that libpq didn't have enough memory to make a PGconn.
*/
if (n_conn == NULL)
pg_log_error("out of memory");
success = false;
} /* end retry loop */
/* Release locally allocated data, whether we succeeded or not */
pg_free(password);
PQconninfoFree(cinfo);
if (!success)
{
/*
* Failed to connect to the database. In interactive mode, keep the
* previous connection to the DB; in scripting mode, close our
* previous connection as well.
*/
if (pset.cur_cmd_interactive)
{
if (n_conn)
{
pg_log_info("%s", PQerrorMessage(n_conn));
PQfinish(n_conn);
}
/* pset.db is left unmodified */
if (o_conn)
pg_log_info("Previous connection kept");
}
else
{
if (n_conn)
{
pg_log_error("\\connect: %s", PQerrorMessage(n_conn));
PQfinish(n_conn);
}
if (o_conn)
{
/*
* Transition to having no connection.
*
* Unlike CheckConnection(), we close the old connection
* immediately to prevent its parameters from being re-used.
* This is so that a script cannot accidentally reuse
* parameters it did not expect to. Otherwise, the state
* cleanup should be the same as in CheckConnection().
*/
PQfinish(o_conn);
pset.db = NULL;
ResetCancelConn();
UnsyncVariables();
}
/* On the same reasoning, release any dead_conn to prevent reuse */
if (pset.dead_conn)
{
PQfinish(pset.dead_conn);
pset.dead_conn = NULL;
}
}
return false;
}
/*
* Replace the old connection with the new one, and update
* connection-dependent variables. Keep the resynchronization logic in
* sync with CheckConnection().
*/
PQsetNoticeProcessor(n_conn, NoticeProcessor, NULL);
pset.db = n_conn;
SyncVariables();
connection_warnings(false); /* Must be after SyncVariables */
/* Tell the user about the new connection */
if (!pset.quiet)
{
if (!o_conn ||
param_is_newly_set(PQhost(o_conn), PQhost(pset.db)) ||
param_is_newly_set(PQport(o_conn), PQport(pset.db)))
{
char *connhost = PQhost(pset.db);
char *hostaddr = PQhostaddr(pset.db);
if (is_unixsock_path(connhost))
{
/* hostaddr overrides connhost */
if (hostaddr && *hostaddr)
printf(_("You are now connected to database \"%s\" as user \"%s\" on address \"%s\" at port \"%s\".\n"),
PQdb(pset.db), PQuser(pset.db), hostaddr, PQport(pset.db));
else
printf(_("You are now connected to database \"%s\" as user \"%s\" via socket in \"%s\" at port \"%s\".\n"),
PQdb(pset.db), PQuser(pset.db), connhost, PQport(pset.db));
}
else
{
if (hostaddr && *hostaddr && strcmp(connhost, hostaddr) != 0)
printf(_("You are now connected to database \"%s\" as user \"%s\" on host \"%s\" (address \"%s\") at port \"%s\".\n"),
PQdb(pset.db), PQuser(pset.db), connhost, hostaddr, PQport(pset.db));
else
printf(_("You are now connected to database \"%s\" as user \"%s\" on host \"%s\" at port \"%s\".\n"),
PQdb(pset.db), PQuser(pset.db), connhost, PQport(pset.db));
}
}
else
printf(_("You are now connected to database \"%s\" as user \"%s\".\n"),
PQdb(pset.db), PQuser(pset.db));
}
/* Drop no-longer-needed connection(s) */
if (o_conn)
PQfinish(o_conn);
if (pset.dead_conn)
{
PQfinish(pset.dead_conn);
pset.dead_conn = NULL;
}
return true;
}
void
connection_warnings(bool in_startup)
{
if (!pset.quiet && !pset.notty)
{
int client_ver = PG_VERSION_NUM;
char cverbuf[32];
char sverbuf[32];
if (pset.sversion != client_ver)
{
const char *server_version;
/* Try to get full text form, might include "devel" etc */
server_version = PQparameterStatus(pset.db, "server_version");
/* Otherwise fall back on pset.sversion */
if (!server_version)
{
formatPGVersionNumber(pset.sversion, true,
sverbuf, sizeof(sverbuf));
server_version = sverbuf;
}
printf(_("%s (%s, server %s)\n"),
pset.progname, PG_VERSION, server_version);
}
/* For version match, only print psql banner on startup. */
else if (in_startup)
printf("%s (%s)\n", pset.progname, PG_VERSION);
/*
* Warn if server's major version is newer than ours, or if server
* predates our support cutoff (currently 9.2).
*/
if (pset.sversion / 100 > client_ver / 100 ||
pset.sversion < 90200)
printf(_("WARNING: %s major version %s, server major version %s.\n"
" Some psql features might not work.\n"),
pset.progname,
formatPGVersionNumber(client_ver, false,
cverbuf, sizeof(cverbuf)),
formatPGVersionNumber(pset.sversion, false,
sverbuf, sizeof(sverbuf)));
#ifdef WIN32
if (in_startup)
checkWin32Codepage();
#endif
printSSLInfo();
printGSSInfo();
}
}
/*
* printSSLInfo
*
* Prints information about the current SSL connection, if SSL is in use
*/
static void
printSSLInfo(void)
{
const char *protocol;
const char *cipher;
const char *compression;
if (!PQsslInUse(pset.db))
return; /* no SSL */
protocol = PQsslAttribute(pset.db, "protocol");
cipher = PQsslAttribute(pset.db, "cipher");
compression = PQsslAttribute(pset.db, "compression");
printf(_("SSL connection (protocol: %s, cipher: %s, compression: %s)\n"),
protocol ? protocol : _("unknown"),
cipher ? cipher : _("unknown"),
(compression && strcmp(compression, "off") != 0) ? _("on") : _("off"));
}
/*
* printGSSInfo
*
* Prints information about the current GSSAPI connection, if GSSAPI encryption is in use
*/
static void
printGSSInfo(void)
{
if (!PQgssEncInUse(pset.db))
return; /* no GSSAPI encryption in use */
printf(_("GSSAPI-encrypted connection\n"));
}
/*
* checkWin32Codepage
*
* Prints a warning when win32 console codepage differs from Windows codepage
*/
#ifdef WIN32
static void
checkWin32Codepage(void)
{
unsigned int wincp,
concp;
wincp = GetACP();
concp = GetConsoleCP();
if (wincp != concp)
{
printf(_("WARNING: Console code page (%u) differs from Windows code page (%u)\n"
" 8-bit characters might not work correctly. See psql reference\n"
" page \"Notes for Windows users\" for details.\n"),
concp, wincp);
}
}
#endif
/*
* SyncVariables
*
* Make psql's internal variables agree with connection state upon
* establishing a new connection.
*/
void
SyncVariables(void)
{
char vbuf[32];
const char *server_version;
/* get stuff from connection */
pset.encoding = PQclientEncoding(pset.db);
pset.popt.topt.encoding = pset.encoding;
pset.sversion = PQserverVersion(pset.db);
SetVariable(pset.vars, "DBNAME", PQdb(pset.db));
SetVariable(pset.vars, "USER", PQuser(pset.db));
SetVariable(pset.vars, "HOST", PQhost(pset.db));
SetVariable(pset.vars, "PORT", PQport(pset.db));
SetVariable(pset.vars, "ENCODING", pg_encoding_to_char(pset.encoding));
/* this bit should match connection_warnings(): */
/* Try to get full text form of version, might include "devel" etc */
server_version = PQparameterStatus(pset.db, "server_version");
/* Otherwise fall back on pset.sversion */
if (!server_version)
{
formatPGVersionNumber(pset.sversion, true, vbuf, sizeof(vbuf));
server_version = vbuf;
}
SetVariable(pset.vars, "SERVER_VERSION_NAME", server_version);
snprintf(vbuf, sizeof(vbuf), "%d", pset.sversion);
SetVariable(pset.vars, "SERVER_VERSION_NUM", vbuf);
/* send stuff to it, too */
PQsetErrorVerbosity(pset.db, pset.verbosity);
PQsetErrorContextVisibility(pset.db, pset.show_context);
}
/*
* UnsyncVariables
*
* Clear variables that should be not be set when there is no connection.
*/
void
UnsyncVariables(void)
{
SetVariable(pset.vars, "DBNAME", NULL);
SetVariable(pset.vars, "USER", NULL);
SetVariable(pset.vars, "HOST", NULL);
SetVariable(pset.vars, "PORT", NULL);
SetVariable(pset.vars, "ENCODING", NULL);
SetVariable(pset.vars, "SERVER_VERSION_NAME", NULL);
SetVariable(pset.vars, "SERVER_VERSION_NUM", NULL);
}
/*
* helper for do_edit(): actually invoke the editor
*
* Returns true on success, false if we failed to invoke the editor or
* it returned nonzero status. (An error message is printed for failed-
* to-invoke cases, but not if the editor returns nonzero status.)
*/
static bool
editFile(const char *fname, int lineno)
{
const char *editorName;
const char *editor_lineno_arg = NULL;
char *sys;
int result;
Assert(fname != NULL);
/* Find an editor to use */
editorName = getenv("PSQL_EDITOR");
if (!editorName)
editorName = getenv("EDITOR");
if (!editorName)
editorName = getenv("VISUAL");
if (!editorName)
editorName = DEFAULT_EDITOR;
/* Get line number argument, if we need it. */
if (lineno > 0)
{
editor_lineno_arg = getenv("PSQL_EDITOR_LINENUMBER_ARG");
#ifdef DEFAULT_EDITOR_LINENUMBER_ARG
if (!editor_lineno_arg)
editor_lineno_arg = DEFAULT_EDITOR_LINENUMBER_ARG;
#endif
if (!editor_lineno_arg)
{
pg_log_error("environment variable PSQL_EDITOR_LINENUMBER_ARG must be set to specify a line number");
return false;
}
}
/*
* On Unix the EDITOR value should *not* be quoted, since it might include
* switches, eg, EDITOR="pico -t"; it's up to the user to put quotes in it
* if necessary. But this policy is not very workable on Windows, due to
* severe brain damage in their command shell plus the fact that standard
* program paths include spaces.
*/
#ifndef WIN32
if (lineno > 0)
sys = psprintf("exec %s %s%d '%s'",
editorName, editor_lineno_arg, lineno, fname);
else
sys = psprintf("exec %s '%s'",
editorName, fname);
#else
if (lineno > 0)
sys = psprintf("\"%s\" %s%d \"%s\"",
editorName, editor_lineno_arg, lineno, fname);
else
sys = psprintf("\"%s\" \"%s\"",
editorName, fname);
#endif
fflush(NULL);
result = system(sys);
if (result == -1)
pg_log_error("could not start editor \"%s\"", editorName);
else if (result == 127)
pg_log_error("could not start /bin/sh");
free(sys);
return result == 0;
}
/*
* do_edit -- handler for \e
*
* If you do not specify a filename, the current query buffer will be copied
* into a temporary file.
*
* After this function is done, the resulting file will be copied back into the
* query buffer. As an exception to this, the query buffer will be emptied
* if the file was not modified (or the editor failed) and the caller passes
* "discard_on_quit" = true.
*
* If "edited" isn't NULL, *edited will be set to true if the query buffer
* is successfully replaced.
*/
static bool
do_edit(const char *filename_arg, PQExpBuffer query_buf,
int lineno, bool discard_on_quit, bool *edited)
{
char fnametmp[MAXPGPATH];
FILE *stream = NULL;
const char *fname;
bool error = false;
int fd;
struct stat before,
after;
if (filename_arg)
fname = filename_arg;
else
{
/* make a temp file to edit */
#ifndef WIN32
const char *tmpdir = getenv("TMPDIR");
if (!tmpdir)
tmpdir = "/tmp";
#else
char tmpdir[MAXPGPATH];
int ret;
ret = GetTempPath(MAXPGPATH, tmpdir);
if (ret == 0 || ret > MAXPGPATH)
{
pg_log_error("could not locate temporary directory: %s",
!ret ? strerror(errno) : "");
return false;
}
#endif
/*
* No canonicalize_path() here. EDIT.EXE run from CMD.EXE prepends the
* current directory to the supplied path unless we use only
* backslashes, so we do that.
*/
#ifndef WIN32
snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d.sql", tmpdir,
"/", (int) getpid());
#else
snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d.sql", tmpdir,
"" /* trailing separator already present */ , (int) getpid());
#endif
fname = (const char *) fnametmp;
fd = open(fname, O_WRONLY | O_CREAT | O_EXCL, 0600);
if (fd != -1)
stream = fdopen(fd, "w");
if (fd == -1 || !stream)
{
pg_log_error("could not open temporary file \"%s\": %m", fname);
error = true;
}
else
{
unsigned int ql = query_buf->len;
/* force newline-termination of what we send to editor */
if (ql > 0 && query_buf->data[ql - 1] != '\n')
{
appendPQExpBufferChar(query_buf, '\n');
ql++;
}
if (fwrite(query_buf->data, 1, ql, stream) != ql)
{
pg_log_error("%s: %m", fname);
if (fclose(stream) != 0)
pg_log_error("%s: %m", fname);
if (remove(fname) != 0)
pg_log_error("%s: %m", fname);
error = true;
}
else if (fclose(stream) != 0)
{
pg_log_error("%s: %m", fname);
if (remove(fname) != 0)
pg_log_error("%s: %m", fname);
error = true;
}
else
{
struct utimbuf ut;
/*
* Try to set the file modification time of the temporary file
* a few seconds in the past. Otherwise, the low granularity
* (one second, or even worse on some filesystems) that we can
* portably measure with stat(2) could lead us to not
* recognize a modification, if the user typed very quickly.
*
* This is a rather unlikely race condition, so don't error
* out if the utime(2) call fails --- that would make the cure
* worse than the disease.
*/
ut.modtime = ut.actime = time(NULL) - 2;
(void) utime(fname, &ut);
}
}
}
if (!error && stat(fname, &before) != 0)
{
pg_log_error("%s: %m", fname);
error = true;
}
/* call editor */
if (!error)
error = !editFile(fname, lineno);
if (!error && stat(fname, &after) != 0)
{
pg_log_error("%s: %m", fname);
error = true;
}
/* file was edited if the size or modification time has changed */
if (!error &&
(before.st_size != after.st_size ||
before.st_mtime != after.st_mtime))
{
stream = fopen(fname, PG_BINARY_R);
if (!stream)
{
pg_log_error("%s: %m", fname);
error = true;
}
else
{
/* read file back into query_buf */
char line[1024];
resetPQExpBuffer(query_buf);
while (fgets(line, sizeof(line), stream) != NULL)
appendPQExpBufferStr(query_buf, line);
if (ferror(stream))
{
pg_log_error("%s: %m", fname);
error = true;
resetPQExpBuffer(query_buf);
}
else if (edited)
{
*edited = true;
}
fclose(stream);
}
}
else
{
/*
* If the file was not modified, and the caller requested it, discard
* the query buffer.
*/
if (discard_on_quit)
resetPQExpBuffer(query_buf);
}
/* remove temp file */
if (!filename_arg)
{
if (remove(fname) == -1)
{
pg_log_error("%s: %m", fname);
error = true;
}
}
return !error;
}
/*
* process_file
*
* Reads commands from filename and passes them to the main processing loop.
* Handler for \i and \ir, but can be used for other things as well. Returns
* MainLoop() error code.
*
* If use_relative_path is true and filename is not an absolute path, then open
* the file from where the currently processed file (if any) is located.
*/
int
process_file(char *filename, bool use_relative_path)
{
FILE *fd;
int result;
char *oldfilename;
char relpath[MAXPGPATH];
if (!filename)
{
fd = stdin;
filename = NULL;
}
else if (strcmp(filename, "-") != 0)
{
canonicalize_path(filename);
/*
* If we were asked to resolve the pathname relative to the location
* of the currently executing script, and there is one, and this is a
* relative pathname, then prepend all but the last pathname component
* of the current script to this pathname.
*/
if (use_relative_path && pset.inputfile &&
!is_absolute_path(filename) && !has_drive_prefix(filename))
{
strlcpy(relpath, pset.inputfile, sizeof(relpath));
get_parent_directory(relpath);
join_path_components(relpath, relpath, filename);
canonicalize_path(relpath);
filename = relpath;
}
fd = fopen(filename, PG_BINARY_R);
if (!fd)
{
pg_log_error("%s: %m", filename);
return EXIT_FAILURE;
}
}
else
{
fd = stdin;
filename = "<stdin>"; /* for future error messages */
}
oldfilename = pset.inputfile;
pset.inputfile = filename;
pg_logging_config(pset.inputfile ? 0 : PG_LOG_FLAG_TERSE);
result = MainLoop(fd);
if (fd != stdin)
fclose(fd);
pset.inputfile = oldfilename;
pg_logging_config(pset.inputfile ? 0 : PG_LOG_FLAG_TERSE);
return result;
}
static const char *
_align2string(enum printFormat in)
{
switch (in)
{
case PRINT_NOTHING:
return "nothing";
break;
case PRINT_ALIGNED:
return "aligned";
break;
case PRINT_ASCIIDOC:
return "asciidoc";
break;
case PRINT_CSV:
return "csv";
break;
case PRINT_HTML:
return "html";
break;
case PRINT_LATEX:
return "latex";
break;
case PRINT_LATEX_LONGTABLE:
return "latex-longtable";
break;
case PRINT_TROFF_MS:
return "troff-ms";
break;
case PRINT_UNALIGNED:
return "unaligned";
break;
case PRINT_WRAPPED:
return "wrapped";
break;
}
return "unknown";
}
/*
* Parse entered Unicode linestyle. If ok, update *linestyle and return
* true, else return false.
*/
static bool
set_unicode_line_style(const char *value, size_t vallen,
unicode_linestyle *linestyle)
{
if (pg_strncasecmp("single", value, vallen) == 0)
*linestyle = UNICODE_LINESTYLE_SINGLE;
else if (pg_strncasecmp("double", value, vallen) == 0)
*linestyle = UNICODE_LINESTYLE_DOUBLE;
else
return false;
return true;
}
static const char *
_unicode_linestyle2string(int linestyle)
{
switch (linestyle)
{
case UNICODE_LINESTYLE_SINGLE:
return "single";
break;
case UNICODE_LINESTYLE_DOUBLE:
return "double";
break;
}
return "unknown";
}
/*
* do_pset
*
* Performs the assignment "param = value", where value could be NULL;
* for some params that has an effect such as inversion, for others
* it does nothing.
*
* Adjusts the state of the formatting options at *popt. (In practice that
* is always pset.popt, but maybe someday it could be different.)
*
* If successful and quiet is false, then invokes printPsetInfo() to report
* the change.
*
* Returns true if successful, else false (eg for invalid param or value).
*/
bool
do_pset(const char *param, const char *value, printQueryOpt *popt, bool quiet)
{
size_t vallen = 0;
Assert(param != NULL);
if (value)
vallen = strlen(value);
/* set format */
if (strcmp(param, "format") == 0)
{
static const struct fmt
{
const char *name;
enum printFormat number;
} formats[] =
{
/* remember to update error message below when adding more */
{"aligned", PRINT_ALIGNED},
{"asciidoc", PRINT_ASCIIDOC},
{"csv", PRINT_CSV},
{"html", PRINT_HTML},
{"latex", PRINT_LATEX},
{"troff-ms", PRINT_TROFF_MS},
{"unaligned", PRINT_UNALIGNED},
{"wrapped", PRINT_WRAPPED}
};
if (!value)
;
else
{
int match_pos = -1;
for (int i = 0; i < lengthof(formats); i++)
{
if (pg_strncasecmp(formats[i].name, value, vallen) == 0)
{
if (match_pos < 0)
match_pos = i;
else
{
pg_log_error("\\pset: ambiguous abbreviation \"%s\" matches both \"%s\" and \"%s\"",
value,
formats[match_pos].name, formats[i].name);
return false;
}
}
}
if (match_pos >= 0)
popt->topt.format = formats[match_pos].number;
else if (pg_strncasecmp("latex-longtable", value, vallen) == 0)
{
/*
* We must treat latex-longtable specially because latex is a
* prefix of it; if both were in the table above, we'd think
* "latex" is ambiguous.
*/
popt->topt.format = PRINT_LATEX_LONGTABLE;
}
else
{
pg_log_error("\\pset: allowed formats are aligned, asciidoc, csv, html, latex, latex-longtable, troff-ms, unaligned, wrapped");
return false;
}
}
}
/* set table line style */
else if (strcmp(param, "linestyle") == 0)
{
if (!value)
;
else if (pg_strncasecmp("ascii", value, vallen) == 0)
popt->topt.line_style = &pg_asciiformat;
else if (pg_strncasecmp("old-ascii", value, vallen) == 0)
popt->topt.line_style = &pg_asciiformat_old;
else if (pg_strncasecmp("unicode", value, vallen) == 0)
popt->topt.line_style = &pg_utf8format;
else
{
pg_log_error("\\pset: allowed line styles are ascii, old-ascii, unicode");
return false;
}
}
/* set unicode border line style */
else if (strcmp(param, "unicode_border_linestyle") == 0)
{
if (!value)
;
else if (set_unicode_line_style(value, vallen,
&popt->topt.unicode_border_linestyle))
refresh_utf8format(&(popt->topt));
else
{
pg_log_error("\\pset: allowed Unicode border line styles are single, double");
return false;
}
}
/* set unicode column line style */
else if (strcmp(param, "unicode_column_linestyle") == 0)
{
if (!value)
;
else if (set_unicode_line_style(value, vallen,
&popt->topt.unicode_column_linestyle))
refresh_utf8format(&(popt->topt));
else
{
pg_log_error("\\pset: allowed Unicode column line styles are single, double");
return false;
}
}
/* set unicode header line style */
else if (strcmp(param, "unicode_header_linestyle") == 0)
{
if (!value)
;
else if (set_unicode_line_style(value, vallen,
&popt->topt.unicode_header_linestyle))
refresh_utf8format(&(popt->topt));
else
{
pg_log_error("\\pset: allowed Unicode header line styles are single, double");
return false;
}
}
/* set border style/width */
else if (strcmp(param, "border") == 0)
{
if (value)
popt->topt.border = atoi(value);
}
/* set expanded/vertical mode */
else if (strcmp(param, "x") == 0 ||
strcmp(param, "expanded") == 0 ||
strcmp(param, "vertical") == 0)
{
if (value && pg_strcasecmp(value, "auto") == 0)
popt->topt.expanded = 2;
else if (value)
{
bool on_off;
if (ParseVariableBool(value, NULL, &on_off))
popt->topt.expanded = on_off ? 1 : 0;
else
{
PsqlVarEnumError(param, value, "on, off, auto");
return false;
}
}
else
popt->topt.expanded = !popt->topt.expanded;
}
/* header line width in expanded mode */
else if (strcmp(param, "xheader_width") == 0)
{
if (!value)
;
else if (pg_strcasecmp(value, "full") == 0)
popt->topt.expanded_header_width_type = PRINT_XHEADER_FULL;
else if (pg_strcasecmp(value, "column") == 0)
popt->topt.expanded_header_width_type = PRINT_XHEADER_COLUMN;
else if (pg_strcasecmp(value, "page") == 0)
popt->topt.expanded_header_width_type = PRINT_XHEADER_PAGE;
else
{
int intval = atoi(value);
if (intval == 0)
{
pg_log_error("\\pset: allowed xheader_width values are \"%s\" (default), \"%s\", \"%s\", or a number specifying the exact width", "full", "column", "page");
return false;
}
popt->topt.expanded_header_width_type = PRINT_XHEADER_EXACT_WIDTH;
popt->topt.expanded_header_exact_width = intval;
}
}
/* field separator for CSV format */
else if (strcmp(param, "csv_fieldsep") == 0)
{
if (value)
{
/* CSV separator has to be a one-byte character */
if (strlen(value) != 1)
{
pg_log_error("\\pset: csv_fieldsep must be a single one-byte character");
return false;
}
if (value[0] == '"' || value[0] == '\n' || value[0] == '\r')
{
pg_log_error("\\pset: csv_fieldsep cannot be a double quote, a newline, or a carriage return");
return false;
}
popt->topt.csvFieldSep[0] = value[0];
}
}
/* locale-aware numeric output */
else if (strcmp(param, "numericlocale") == 0)
{
if (value)
return ParseVariableBool(value, param, &popt->topt.numericLocale);
else
popt->topt.numericLocale = !popt->topt.numericLocale;
}
/* null display */
else if (strcmp(param, "null") == 0)
{
if (value)
{
free(popt->nullPrint);
popt->nullPrint = pg_strdup(value);
}
}
/* field separator for unaligned text */
else if (strcmp(param, "fieldsep") == 0)
{
if (value)
{
free(popt->topt.fieldSep.separator);
popt->topt.fieldSep.separator = pg_strdup(value);
popt->topt.fieldSep.separator_zero = false;
}
}
else if (strcmp(param, "fieldsep_zero") == 0)
{
free(popt->topt.fieldSep.separator);
popt->topt.fieldSep.separator = NULL;
popt->topt.fieldSep.separator_zero = true;
}
/* record separator for unaligned text */
else if (strcmp(param, "recordsep") == 0)
{
if (value)
{
free(popt->topt.recordSep.separator);
popt->topt.recordSep.separator = pg_strdup(value);
popt->topt.recordSep.separator_zero = false;
}
}
else if (strcmp(param, "recordsep_zero") == 0)
{
free(popt->topt.recordSep.separator);
popt->topt.recordSep.separator = NULL;
popt->topt.recordSep.separator_zero = true;
}
/* toggle between full and tuples-only format */
else if (strcmp(param, "t") == 0 || strcmp(param, "tuples_only") == 0)
{
if (value)
return ParseVariableBool(value, param, &popt->topt.tuples_only);
else
popt->topt.tuples_only = !popt->topt.tuples_only;
}
/* set title override */
else if (strcmp(param, "C") == 0 || strcmp(param, "title") == 0)
{
free(popt->title);
if (!value)
popt->title = NULL;
else
popt->title = pg_strdup(value);
}
/* set HTML table tag options */
else if (strcmp(param, "T") == 0 || strcmp(param, "tableattr") == 0)
{
free(popt->topt.tableAttr);
if (!value)
popt->topt.tableAttr = NULL;
else
popt->topt.tableAttr = pg_strdup(value);
}
/* toggle use of pager */
else if (strcmp(param, "pager") == 0)
{
if (value && pg_strcasecmp(value, "always") == 0)
popt->topt.pager = 2;
else if (value)
{
bool on_off;
if (!ParseVariableBool(value, NULL, &on_off))
{
PsqlVarEnumError(param, value, "on, off, always");
return false;
}
popt->topt.pager = on_off ? 1 : 0;
}
else if (popt->topt.pager == 1)
popt->topt.pager = 0;
else
popt->topt.pager = 1;
}
/* set minimum lines for pager use */
else if (strcmp(param, "pager_min_lines") == 0)
{
if (value &&
!ParseVariableNum(value, "pager_min_lines", &popt->topt.pager_min_lines))
return false;
}
/* disable "(x rows)" footer */
else if (strcmp(param, "footer") == 0)
{
if (value)
return ParseVariableBool(value, param, &popt->topt.default_footer);
else
popt->topt.default_footer = !popt->topt.default_footer;
}
/* set border style/width */
else if (strcmp(param, "columns") == 0)
{
if (value)
popt->topt.columns = atoi(value);
}
else
{
pg_log_error("\\pset: unknown option: %s", param);
return false;
}
if (!quiet)
printPsetInfo(param, &pset.popt);
return true;
}
/*
* printPsetInfo: print the state of the "param" formatting parameter in popt.
*/
static bool
printPsetInfo(const char *param, printQueryOpt *popt)
{
Assert(param != NULL);
/* show border style/width */
if (strcmp(param, "border") == 0)
printf(_("Border style is %d.\n"), popt->topt.border);
/* show the target width for the wrapped format */
else if (strcmp(param, "columns") == 0)
{
if (!popt->topt.columns)
printf(_("Target width is unset.\n"));
else
printf(_("Target width is %d.\n"), popt->topt.columns);
}
/* show expanded/vertical mode */
else if (strcmp(param, "x") == 0 || strcmp(param, "expanded") == 0 || strcmp(param, "vertical") == 0)
{
if (popt->topt.expanded == 1)
printf(_("Expanded display is on.\n"));
else if (popt->topt.expanded == 2)
printf(_("Expanded display is used automatically.\n"));
else
printf(_("Expanded display is off.\n"));
}
/* show xheader width value */
else if (strcmp(param, "xheader_width") == 0)
{
if (popt->topt.expanded_header_width_type == PRINT_XHEADER_FULL)
printf(_("Expanded header width is \"%s\".\n"), "full");
else if (popt->topt.expanded_header_width_type == PRINT_XHEADER_COLUMN)
printf(_("Expanded header width is \"%s\".\n"), "column");
else if (popt->topt.expanded_header_width_type == PRINT_XHEADER_PAGE)
printf(_("Expanded header width is \"%s\".\n"), "page");
else if (popt->topt.expanded_header_width_type == PRINT_XHEADER_EXACT_WIDTH)
printf(_("Expanded header width is %d.\n"), popt->topt.expanded_header_exact_width);
}
/* show field separator for CSV format */
else if (strcmp(param, "csv_fieldsep") == 0)
{
printf(_("Field separator for CSV is \"%s\".\n"),
popt->topt.csvFieldSep);
}
/* show field separator for unaligned text */
else if (strcmp(param, "fieldsep") == 0)
{
if (popt->topt.fieldSep.separator_zero)
printf(_("Field separator is zero byte.\n"));
else
printf(_("Field separator is \"%s\".\n"),
popt->topt.fieldSep.separator);
}
else if (strcmp(param, "fieldsep_zero") == 0)
{
printf(_("Field separator is zero byte.\n"));
}
/* show disable "(x rows)" footer */
else if (strcmp(param, "footer") == 0)
{
if (popt->topt.default_footer)
printf(_("Default footer is on.\n"));
else
printf(_("Default footer is off.\n"));
}
/* show format */
else if (strcmp(param, "format") == 0)
{
printf(_("Output format is %s.\n"), _align2string(popt->topt.format));
}
/* show table line style */
else if (strcmp(param, "linestyle") == 0)
{
printf(_("Line style is %s.\n"),
get_line_style(&popt->topt)->name);
}
/* show null display */
else if (strcmp(param, "null") == 0)
{
printf(_("Null display is \"%s\".\n"),
popt->nullPrint ? popt->nullPrint : "");
}
/* show locale-aware numeric output */
else if (strcmp(param, "numericlocale") == 0)
{
if (popt->topt.numericLocale)
printf(_("Locale-adjusted numeric output is on.\n"));
else
printf(_("Locale-adjusted numeric output is off.\n"));
}
/* show toggle use of pager */
else if (strcmp(param, "pager") == 0)
{
if (popt->topt.pager == 1)
printf(_("Pager is used for long output.\n"));
else if (popt->topt.pager == 2)
printf(_("Pager is always used.\n"));
else
printf(_("Pager usage is off.\n"));
}
/* show minimum lines for pager use */
else if (strcmp(param, "pager_min_lines") == 0)
{
printf(ngettext("Pager won't be used for less than %d line.\n",
"Pager won't be used for less than %d lines.\n",
popt->topt.pager_min_lines),
popt->topt.pager_min_lines);
}
/* show record separator for unaligned text */
else if (strcmp(param, "recordsep") == 0)
{
if (popt->topt.recordSep.separator_zero)
printf(_("Record separator is zero byte.\n"));
else if (strcmp(popt->topt.recordSep.separator, "\n") == 0)
printf(_("Record separator is <newline>.\n"));
else
printf(_("Record separator is \"%s\".\n"),
popt->topt.recordSep.separator);
}
else if (strcmp(param, "recordsep_zero") == 0)
{
printf(_("Record separator is zero byte.\n"));
}
/* show HTML table tag options */
else if (strcmp(param, "T") == 0 || strcmp(param, "tableattr") == 0)
{
if (popt->topt.tableAttr)
printf(_("Table attributes are \"%s\".\n"),
popt->topt.tableAttr);
else
printf(_("Table attributes unset.\n"));
}
/* show title override */
else if (strcmp(param, "C") == 0 || strcmp(param, "title") == 0)
{
if (popt->title)
printf(_("Title is \"%s\".\n"), popt->title);
else
printf(_("Title is unset.\n"));
}
/* show toggle between full and tuples-only format */
else if (strcmp(param, "t") == 0 || strcmp(param, "tuples_only") == 0)
{
if (popt->topt.tuples_only)
printf(_("Tuples only is on.\n"));
else
printf(_("Tuples only is off.\n"));
}
/* Unicode style formatting */
else if (strcmp(param, "unicode_border_linestyle") == 0)
{
printf(_("Unicode border line style is \"%s\".\n"),
_unicode_linestyle2string(popt->topt.unicode_border_linestyle));
}
else if (strcmp(param, "unicode_column_linestyle") == 0)
{
printf(_("Unicode column line style is \"%s\".\n"),
_unicode_linestyle2string(popt->topt.unicode_column_linestyle));
}
else if (strcmp(param, "unicode_header_linestyle") == 0)
{
printf(_("Unicode header line style is \"%s\".\n"),
_unicode_linestyle2string(popt->topt.unicode_header_linestyle));
}
else
{
pg_log_error("\\pset: unknown option: %s", param);
return false;
}
return true;
}
/*
* savePsetInfo: make a malloc'd copy of the data in *popt.
*
* Possibly this should be somewhere else, but it's a bit specific to psql.
*/
printQueryOpt *
savePsetInfo(const printQueryOpt *popt)
{
printQueryOpt *save;
save = (printQueryOpt *) pg_malloc(sizeof(printQueryOpt));
/* Flat-copy all the scalar fields, then duplicate sub-structures. */
memcpy(save, popt, sizeof(printQueryOpt));
/* topt.line_style points to const data that need not be duplicated */
if (popt->topt.fieldSep.separator)
save->topt.fieldSep.separator = pg_strdup(popt->topt.fieldSep.separator);
if (popt->topt.recordSep.separator)
save->topt.recordSep.separator = pg_strdup(popt->topt.recordSep.separator);
if (popt->topt.tableAttr)
save->topt.tableAttr = pg_strdup(popt->topt.tableAttr);
if (popt->nullPrint)
save->nullPrint = pg_strdup(popt->nullPrint);
if (popt->title)
save->title = pg_strdup(popt->title);
/*
* footers and translate_columns are never set in psql's print settings,
* so we needn't write code to duplicate them.
*/
Assert(popt->footers == NULL);
Assert(popt->translate_columns == NULL);
return save;
}
/*
* restorePsetInfo: restore *popt from the previously-saved copy *save,
* then free *save.
*/
void
restorePsetInfo(printQueryOpt *popt, printQueryOpt *save)
{
/* Free all the old data we're about to overwrite the pointers to. */
/* topt.line_style points to const data that need not be duplicated */
free(popt->topt.fieldSep.separator);
free(popt->topt.recordSep.separator);
free(popt->topt.tableAttr);
free(popt->nullPrint);
free(popt->title);
/*
* footers and translate_columns are never set in psql's print settings,
* so we needn't write code to duplicate them.
*/
Assert(popt->footers == NULL);
Assert(popt->translate_columns == NULL);
/* Now we may flat-copy all the fields, including pointers. */
memcpy(popt, save, sizeof(printQueryOpt));
/* Lastly, free "save" ... but its sub-structures now belong to popt. */
free(save);
}
static const char *
pset_bool_string(bool val)
{
return val ? "on" : "off";
}
static char *
pset_quoted_string(const char *str)
{
char *ret = pg_malloc(strlen(str) * 2 + 3);
char *r = ret;
*r++ = '\'';
for (; *str; str++)
{
if (*str == '\n')
{
*r++ = '\\';
*r++ = 'n';
}
else if (*str == '\'')
{
*r++ = '\\';
*r++ = '\'';
}
else
*r++ = *str;
}
*r++ = '\'';
*r = '\0';
return ret;
}
/*
* Return a malloc'ed string for the \pset value.
*
* Note that for some string parameters, print.c distinguishes between unset
* and empty string, but for others it doesn't. This function should produce
* output that produces the correct setting when fed back into \pset.
*/
static char *
pset_value_string(const char *param, printQueryOpt *popt)
{
Assert(param != NULL);
if (strcmp(param, "border") == 0)
return psprintf("%d", popt->topt.border);
else if (strcmp(param, "columns") == 0)
return psprintf("%d", popt->topt.columns);
else if (strcmp(param, "csv_fieldsep") == 0)
return pset_quoted_string(popt->topt.csvFieldSep);
else if (strcmp(param, "expanded") == 0)
return pstrdup(popt->topt.expanded == 2
? "auto"
: pset_bool_string(popt->topt.expanded));
else if (strcmp(param, "fieldsep") == 0)
return pset_quoted_string(popt->topt.fieldSep.separator
? popt->topt.fieldSep.separator
: "");
else if (strcmp(param, "fieldsep_zero") == 0)
return pstrdup(pset_bool_string(popt->topt.fieldSep.separator_zero));
else if (strcmp(param, "footer") == 0)
return pstrdup(pset_bool_string(popt->topt.default_footer));
else if (strcmp(param, "format") == 0)
return pstrdup(_align2string(popt->topt.format));
else if (strcmp(param, "linestyle") == 0)
return pstrdup(get_line_style(&popt->topt)->name);
else if (strcmp(param, "null") == 0)
return pset_quoted_string(popt->nullPrint
? popt->nullPrint
: "");
else if (strcmp(param, "numericlocale") == 0)
return pstrdup(pset_bool_string(popt->topt.numericLocale));
else if (strcmp(param, "pager") == 0)
return psprintf("%d", popt->topt.pager);
else if (strcmp(param, "pager_min_lines") == 0)
return psprintf("%d", popt->topt.pager_min_lines);
else if (strcmp(param, "recordsep") == 0)
return pset_quoted_string(popt->topt.recordSep.separator
? popt->topt.recordSep.separator
: "");
else if (strcmp(param, "recordsep_zero") == 0)
return pstrdup(pset_bool_string(popt->topt.recordSep.separator_zero));
else if (strcmp(param, "tableattr") == 0)
return popt->topt.tableAttr ? pset_quoted_string(popt->topt.tableAttr) : pstrdup("");
else if (strcmp(param, "title") == 0)
return popt->title ? pset_quoted_string(popt->title) : pstrdup("");
else if (strcmp(param, "tuples_only") == 0)
return pstrdup(pset_bool_string(popt->topt.tuples_only));
else if (strcmp(param, "unicode_border_linestyle") == 0)
return pstrdup(_unicode_linestyle2string(popt->topt.unicode_border_linestyle));
else if (strcmp(param, "unicode_column_linestyle") == 0)
return pstrdup(_unicode_linestyle2string(popt->topt.unicode_column_linestyle));
else if (strcmp(param, "unicode_header_linestyle") == 0)
return pstrdup(_unicode_linestyle2string(popt->topt.unicode_header_linestyle));
else if (strcmp(param, "xheader_width") == 0)
{
if (popt->topt.expanded_header_width_type == PRINT_XHEADER_FULL)
return pstrdup("full");
else if (popt->topt.expanded_header_width_type == PRINT_XHEADER_COLUMN)
return pstrdup("column");
else if (popt->topt.expanded_header_width_type == PRINT_XHEADER_PAGE)
return pstrdup("page");
else
{
/* must be PRINT_XHEADER_EXACT_WIDTH */
char wbuff[32];
snprintf(wbuff, sizeof(wbuff), "%d",
popt->topt.expanded_header_exact_width);
return pstrdup(wbuff);
}
}
else
return pstrdup("ERROR");
}
#ifndef WIN32
#define DEFAULT_SHELL "/bin/sh"
#else
/*
* CMD.EXE is in different places in different Win32 releases so we
* have to rely on the path to find it.
*/
#define DEFAULT_SHELL "cmd.exe"
#endif
static bool
do_shell(const char *command)
{
int result;
fflush(NULL);
if (!command)
{
char *sys;
const char *shellName;
shellName = getenv("SHELL");
#ifdef WIN32
if (shellName == NULL)
shellName = getenv("COMSPEC");
#endif
if (shellName == NULL)
shellName = DEFAULT_SHELL;
/* See EDITOR handling comment for an explanation */
#ifndef WIN32
sys = psprintf("exec %s", shellName);
#else
sys = psprintf("\"%s\"", shellName);
#endif
result = system(sys);
free(sys);
}
else
result = system(command);
SetShellResultVariables(result);
if (result == 127 || result == -1)
{
pg_log_error("\\!: failed");
return false;
}
return true;
}
/*
* do_watch -- handler for \watch
*
* We break this out of exec_command to avoid having to plaster "volatile"
* onto a bunch of exec_command's variables to silence stupider compilers.
*/
static bool
do_watch(PQExpBuffer query_buf, double sleep, int iter)
{
long sleep_ms = (long) (sleep * 1000);
printQueryOpt myopt = pset.popt;
const char *strftime_fmt;
const char *user_title;
char *title;
const char *pagerprog = NULL;
FILE *pagerpipe = NULL;
int title_len;
int res = 0;
#ifndef WIN32
sigset_t sigalrm_sigchld_sigint;
sigset_t sigalrm_sigchld;
sigset_t sigint;
struct itimerval interval;
bool done = false;
#endif
if (!query_buf || query_buf->len <= 0)
{
pg_log_error("\\watch cannot be used with an empty query");
return false;
}
#ifndef WIN32
sigemptyset(&sigalrm_sigchld_sigint);
sigaddset(&sigalrm_sigchld_sigint, SIGCHLD);
sigaddset(&sigalrm_sigchld_sigint, SIGALRM);
sigaddset(&sigalrm_sigchld_sigint, SIGINT);
sigemptyset(&sigalrm_sigchld);
sigaddset(&sigalrm_sigchld, SIGCHLD);
sigaddset(&sigalrm_sigchld, SIGALRM);
sigemptyset(&sigint);
sigaddset(&sigint, SIGINT);
/*
* Block SIGALRM and SIGCHLD before we start the timer and the pager (if
* configured), to avoid races. sigwait() will receive them.
*/
sigprocmask(SIG_BLOCK, &sigalrm_sigchld, NULL);
/*
* Set a timer to interrupt sigwait() so we can run the query at the
* requested intervals.
*/
interval.it_value.tv_sec = sleep_ms / 1000;
interval.it_value.tv_usec = (sleep_ms % 1000) * 1000;
interval.it_interval = interval.it_value;
if (setitimer(ITIMER_REAL, &interval, NULL) < 0)
{
pg_log_error("could not set timer: %m");
done = true;
}
#endif
/*
* For \watch, we ignore the size of the result and always use the pager
* as long as we're talking to a terminal and "\pset pager" is enabled.
* However, we'll only use the pager identified by PSQL_WATCH_PAGER. We
* ignore the regular PSQL_PAGER or PAGER environment variables, because
* traditional pagers probably won't be very useful for showing a stream
* of results.
*/
#ifndef WIN32
pagerprog = getenv("PSQL_WATCH_PAGER");
/* if variable is empty or all-white-space, don't use pager */
if (pagerprog && strspn(pagerprog, " \t\r\n") == strlen(pagerprog))
pagerprog = NULL;
#endif
if (pagerprog && myopt.topt.pager &&
isatty(fileno(stdin)) && isatty(fileno(stdout)))
{
fflush(NULL);
disable_sigpipe_trap();
pagerpipe = popen(pagerprog, "w");
if (!pagerpipe)
/* silently proceed without pager */
restore_sigpipe_trap();
}
/*
* Choose format for timestamps. We might eventually make this a \pset
* option. In the meantime, using a variable for the format suppresses
* overly-anal-retentive gcc warnings about %c being Y2K sensitive.
*/
strftime_fmt = "%c";
/*
* Set up rendering options, in particular, disable the pager unless
* PSQL_WATCH_PAGER was successfully launched.
*/
if (!pagerpipe)
myopt.topt.pager = 0;
/*
* If there's a title in the user configuration, make sure we have room
* for it in the title buffer. Allow 128 bytes for the timestamp plus 128
* bytes for the rest.
*/
user_title = myopt.title;
title_len = (user_title ? strlen(user_title) : 0) + 256;
title = pg_malloc(title_len);
for (;;)
{
time_t timer;
char timebuf[128];
/*
* Prepare title for output. Note that we intentionally include a
* newline at the end of the title; this is somewhat historical but it
* makes for reasonably nicely formatted output in simple cases.
*/
timer = time(NULL);
strftime(timebuf, sizeof(timebuf), strftime_fmt, localtime(&timer));
if (user_title)
snprintf(title, title_len, _("%s\t%s (every %gs)\n"),
user_title, timebuf, sleep);
else
snprintf(title, title_len, _("%s (every %gs)\n"),
timebuf, sleep);
myopt.title = title;
/* Run the query and print out the result */
res = PSQLexecWatch(query_buf->data, &myopt, pagerpipe);
/*
* PSQLexecWatch handles the case where we can no longer repeat the
* query, and returns 0 or -1.
*/
if (res <= 0)
break;
/* If we have iteration count, check that it's not exceeded yet */
if (iter && (--iter <= 0))
break;
if (pagerpipe && ferror(pagerpipe))
break;
if (sleep == 0)
continue;
#ifdef WIN32
/*
* Set up cancellation of 'watch' via SIGINT. We redo this each time
* through the loop since it's conceivable something inside
* PSQLexecWatch could change sigint_interrupt_jmp.
*/
if (sigsetjmp(sigint_interrupt_jmp, 1) != 0)
break;
/*
* Enable 'watch' cancellations and wait a while before running the
* query again. Break the sleep into short intervals (at most 1s).
*/
sigint_interrupt_enabled = true;
for (long i = sleep_ms; i > 0;)
{
long s = Min(i, 1000L);
pg_usleep(s * 1000L);
if (cancel_pressed)
break;
i -= s;
}
sigint_interrupt_enabled = false;
#else
/* sigwait() will handle SIGINT. */
sigprocmask(SIG_BLOCK, &sigint, NULL);
if (cancel_pressed)
done = true;
/* Wait for SIGINT, SIGCHLD or SIGALRM. */
while (!done)
{
int signal_received;
errno = sigwait(&sigalrm_sigchld_sigint, &signal_received);
if (errno != 0)
{
/* Some other signal arrived? */
if (errno == EINTR)
continue;
else
{
pg_log_error("could not wait for signals: %m");
done = true;
break;
}
}
/* On ^C or pager exit, it's time to stop running the query. */
if (signal_received == SIGINT || signal_received == SIGCHLD)
done = true;
/* Otherwise, we must have SIGALRM. Time to run the query again. */
break;
}
/* Unblock SIGINT so that slow queries can be interrupted. */
sigprocmask(SIG_UNBLOCK, &sigint, NULL);
if (done)
break;
#endif
}
if (pagerpipe)
{
pclose(pagerpipe);
restore_sigpipe_trap();
}
else
{
/*
* If the terminal driver echoed "^C", libedit/libreadline might be
* confused about the cursor position. Therefore, inject a newline
* before the next prompt is displayed. We only do this when not
* using a pager, because pagers are expected to restore the screen to
* a sane state on exit.
*/
fprintf(stdout, "\n");
fflush(stdout);
}
#ifndef WIN32
/* Disable the interval timer. */
memset(&interval, 0, sizeof(interval));
setitimer(ITIMER_REAL, &interval, NULL);
/* Unblock SIGINT, SIGCHLD and SIGALRM. */
sigprocmask(SIG_UNBLOCK, &sigalrm_sigchld_sigint, NULL);
#endif
pg_free(title);
return (res >= 0);
}
/*
* a little code borrowed from PSQLexec() to manage ECHO_HIDDEN output.
* returns true unless we have ECHO_HIDDEN_NOEXEC.
*/
static bool
echo_hidden_command(const char *query)
{
if (pset.echo_hidden != PSQL_ECHO_HIDDEN_OFF)
{
printf(_("********* QUERY **********\n"
"%s\n"
"**************************\n\n"), query);
fflush(stdout);
if (pset.logfile)
{
fprintf(pset.logfile,
_("********* QUERY **********\n"
"%s\n"
"**************************\n\n"), query);
fflush(pset.logfile);
}
if (pset.echo_hidden == PSQL_ECHO_HIDDEN_NOEXEC)
return false;
}
return true;
}
/*
* Look up the object identified by obj_type and desc. If successful,
* store its OID in *obj_oid and return true, else return false.
*
* Note that we'll fail if the object doesn't exist OR if there are multiple
* matching candidates OR if there's something syntactically wrong with the
* object description; unfortunately it can be hard to tell the difference.
*/
static bool
lookup_object_oid(EditableObjectType obj_type, const char *desc,
Oid *obj_oid)
{
bool result = true;
PQExpBuffer query = createPQExpBuffer();
PGresult *res;
switch (obj_type)
{
case EditableFunction:
/*
* We have a function description, e.g. "x" or "x(int)". Issue a
* query to retrieve the function's OID using a cast to regproc or
* regprocedure (as appropriate).
*/
appendPQExpBufferStr(query, "SELECT ");
appendStringLiteralConn(query, desc, pset.db);
appendPQExpBuffer(query, "::pg_catalog.%s::pg_catalog.oid",
strchr(desc, '(') ? "regprocedure" : "regproc");
break;
case EditableView:
/*
* Convert view name (possibly schema-qualified) to OID. Note:
* this code doesn't check if the relation is actually a view.
* We'll detect that in get_create_object_cmd().
*/
appendPQExpBufferStr(query, "SELECT ");
appendStringLiteralConn(query, desc, pset.db);
appendPQExpBufferStr(query, "::pg_catalog.regclass::pg_catalog.oid");
break;
}
if (!echo_hidden_command(query->data))
{
destroyPQExpBuffer(query);
return false;
}
res = PQexec(pset.db, query->data);
if (PQresultStatus(res) == PGRES_TUPLES_OK && PQntuples(res) == 1)
*obj_oid = atooid(PQgetvalue(res, 0, 0));
else
{
minimal_error_message(res);
result = false;
}
PQclear(res);
destroyPQExpBuffer(query);
return result;
}
/*
* Construct a "CREATE OR REPLACE ..." command that describes the specified
* database object. If successful, the result is stored in buf.
*/
static bool
get_create_object_cmd(EditableObjectType obj_type, Oid oid,
PQExpBuffer buf)
{
bool result = true;
PQExpBuffer query = createPQExpBuffer();
PGresult *res;
switch (obj_type)
{
case EditableFunction:
printfPQExpBuffer(query,
"SELECT pg_catalog.pg_get_functiondef(%u)",
oid);
break;
case EditableView:
/*
* pg_get_viewdef() just prints the query, so we must prepend
* CREATE for ourselves. We must fully qualify the view name to
* ensure the right view gets replaced. Also, check relation kind
* to be sure it's a view.
*
* Starting with PG 9.4, views may have WITH [LOCAL|CASCADED]
* CHECK OPTION. These are not part of the view definition
* returned by pg_get_viewdef() and so need to be retrieved
* separately. Materialized views (introduced in 9.3) may have
* arbitrary storage parameter reloptions.
*/
if (pset.sversion >= 90400)
{
printfPQExpBuffer(query,
"SELECT nspname, relname, relkind, "
"pg_catalog.pg_get_viewdef(c.oid, true), "
"pg_catalog.array_remove(pg_catalog.array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
"CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
"WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption "
"FROM pg_catalog.pg_class c "
"LEFT JOIN pg_catalog.pg_namespace n "
"ON c.relnamespace = n.oid WHERE c.oid = %u",
oid);
}
else
{
printfPQExpBuffer(query,
"SELECT nspname, relname, relkind, "
"pg_catalog.pg_get_viewdef(c.oid, true), "
"c.reloptions AS reloptions, "
"NULL AS checkoption "
"FROM pg_catalog.pg_class c "
"LEFT JOIN pg_catalog.pg_namespace n "
"ON c.relnamespace = n.oid WHERE c.oid = %u",
oid);
}
break;
}
if (!echo_hidden_command(query->data))
{
destroyPQExpBuffer(query);
return false;
}
res = PQexec(pset.db, query->data);
if (PQresultStatus(res) == PGRES_TUPLES_OK && PQntuples(res) == 1)
{
resetPQExpBuffer(buf);
switch (obj_type)
{
case EditableFunction:
appendPQExpBufferStr(buf, PQgetvalue(res, 0, 0));
break;
case EditableView:
{
char *nspname = PQgetvalue(res, 0, 0);
char *relname = PQgetvalue(res, 0, 1);
char *relkind = PQgetvalue(res, 0, 2);
char *viewdef = PQgetvalue(res, 0, 3);
char *reloptions = PQgetvalue(res, 0, 4);
char *checkoption = PQgetvalue(res, 0, 5);
/*
* If the backend ever supports CREATE OR REPLACE
* MATERIALIZED VIEW, allow that here; but as of today it
* does not, so editing a matview definition in this way
* is impossible.
*/
switch (relkind[0])
{
#ifdef NOT_USED
case RELKIND_MATVIEW:
appendPQExpBufferStr(buf, "CREATE OR REPLACE MATERIALIZED VIEW ");
break;
#endif
case RELKIND_VIEW:
appendPQExpBufferStr(buf, "CREATE OR REPLACE VIEW ");
break;
default:
pg_log_error("\"%s.%s\" is not a view",
nspname, relname);
result = false;
break;
}
appendPQExpBuffer(buf, "%s.", fmtId(nspname));
appendPQExpBufferStr(buf, fmtId(relname));
/* reloptions, if not an empty array "{}" */
if (reloptions != NULL && strlen(reloptions) > 2)
{
appendPQExpBufferStr(buf, "\n WITH (");
if (!appendReloptionsArray(buf, reloptions, "",
pset.encoding,
standard_strings()))
{
pg_log_error("could not parse reloptions array");
result = false;
}
appendPQExpBufferChar(buf, ')');
}
/* View definition from pg_get_viewdef (a SELECT query) */
appendPQExpBuffer(buf, " AS\n%s", viewdef);
/* Get rid of the semicolon that pg_get_viewdef appends */
if (buf->len > 0 && buf->data[buf->len - 1] == ';')
buf->data[--(buf->len)] = '\0';
/* WITH [LOCAL|CASCADED] CHECK OPTION */
if (checkoption && checkoption[0] != '\0')
appendPQExpBuffer(buf, "\n WITH %s CHECK OPTION",
checkoption);
}
break;
}
/* Make sure result ends with a newline */
if (buf->len > 0 && buf->data[buf->len - 1] != '\n')
appendPQExpBufferChar(buf, '\n');
}
else
{
minimal_error_message(res);
result = false;
}
PQclear(res);
destroyPQExpBuffer(query);
return result;
}
/*
* If the given argument of \ef or \ev ends with a line number, delete the line
* number from the argument string and return it as an integer. (We need
* this kluge because we're too lazy to parse \ef's function or \ev's view
* argument carefully --- we just slop it up in OT_WHOLE_LINE mode.)
*
* Returns -1 if no line number is present, 0 on error, or a positive value
* on success.
*/
static int
strip_lineno_from_objdesc(char *obj)
{
char *c;
int lineno;
if (!obj || obj[0] == '\0')
return -1;
c = obj + strlen(obj) - 1;
/*
* This business of parsing backwards is dangerous as can be in a
* multibyte environment: there is no reason to believe that we are
* looking at the first byte of a character, nor are we necessarily
* working in a "safe" encoding. Fortunately the bitpatterns we are
* looking for are unlikely to occur as non-first bytes, but beware of
* trying to expand the set of cases that can be recognized. We must
* guard the <ctype.h> macros by using isascii() first, too.
*/
/* skip trailing whitespace */
while (c > obj && isascii((unsigned char) *c) && isspace((unsigned char) *c))
c--;
/* must have a digit as last non-space char */
if (c == obj || !isascii((unsigned char) *c) || !isdigit((unsigned char) *c))
return -1;
/* find start of digit string */
while (c > obj && isascii((unsigned char) *c) && isdigit((unsigned char) *c))
c--;
/* digits must be separated from object name by space or closing paren */
/* notice also that we are not allowing an empty object name ... */
if (c == obj || !isascii((unsigned char) *c) ||
!(isspace((unsigned char) *c) || *c == ')'))
return -1;
/* parse digit string */
c++;
lineno = atoi(c);
if (lineno < 1)
{
pg_log_error("invalid line number: %s", c);
return 0;
}
/* strip digit string from object name */
*c = '\0';
return lineno;
}
/*
* Count number of lines in the buffer.
* This is used to test if pager is needed or not.
*/
static int
count_lines_in_buf(PQExpBuffer buf)
{
int lineno = 0;
const char *lines = buf->data;
while (*lines != '\0')
{
lineno++;
/* find start of next line */
lines = strchr(lines, '\n');
if (!lines)
break;
lines++;
}
return lineno;
}
/*
* Write text at *lines to output with line numbers.
*
* For functions, lineno "1" should correspond to the first line of the
* function body; lines before that are unnumbered. We expect that
* pg_get_functiondef() will emit that on a line beginning with "AS ",
* "BEGIN ", or "RETURN ", and that there can be no such line before
* the real start of the function body.
*
* Caution: this scribbles on *lines.
*/
static void
print_with_linenumbers(FILE *output, char *lines, bool is_func)
{
bool in_header = is_func;
int lineno = 0;
while (*lines != '\0')
{
char *eol;
if (in_header &&
(strncmp(lines, "AS ", 3) == 0 ||
strncmp(lines, "BEGIN ", 6) == 0 ||
strncmp(lines, "RETURN ", 7) == 0))
in_header = false;
/* increment lineno only for body's lines */
if (!in_header)
lineno++;
/* find and mark end of current line */
eol = strchr(lines, '\n');
if (eol != NULL)
*eol = '\0';
/* show current line as appropriate */
if (in_header)
fprintf(output, " %s\n", lines);
else
fprintf(output, "%-7d %s\n", lineno, lines);
/* advance to next line, if any */
if (eol == NULL)
break;
lines = ++eol;
}
}
/*
* Report just the primary error; this is to avoid cluttering the output
* with, for instance, a redisplay of the internally generated query
*/
static void
minimal_error_message(PGresult *res)
{
PQExpBuffer msg;
const char *fld;
msg = createPQExpBuffer();
fld = PQresultErrorField(res, PG_DIAG_SEVERITY);
if (fld)
printfPQExpBuffer(msg, "%s: ", fld);
else
printfPQExpBuffer(msg, "ERROR: ");
fld = PQresultErrorField(res, PG_DIAG_MESSAGE_PRIMARY);
if (fld)
appendPQExpBufferStr(msg, fld);
else
appendPQExpBufferStr(msg, "(not available)");
appendPQExpBufferChar(msg, '\n');
pg_log_error("%s", msg->data);
destroyPQExpBuffer(msg);
}
|