summaryrefslogtreecommitdiff
path: root/src/bin/psql/tab-complete.c
blob: 3a5fe0ab1f6d662220e698d36b0175f524538274 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
/*
 * psql - the PostgreSQL interactive terminal
 *
 * Copyright (c) 2000-2005, PostgreSQL Global Development Group
 *
 * $PostgreSQL: pgsql/src/bin/psql/tab-complete.c,v 1.137 2005/08/14 18:49:30 tgl Exp $
 */

/*----------------------------------------------------------------------
 * This file implements a somewhat more sophisticated readline "TAB
 * completion" in psql. It is not intended to be AI, to replace
 * learning SQL, or to relieve you from thinking about what you're
 * doing. Also it does not always give you all the syntactically legal
 * completions, only those that are the most common or the ones that
 * the programmer felt most like implementing.
 *
 * CAVEAT: Tab completion causes queries to be sent to the backend.
 * The number of tuples returned gets limited, in most default
 * installations to 1000, but if you still don't like this prospect,
 * you can turn off tab completion in your ~/.inputrc (or else
 * ${INPUTRC}) file so:
 *
 *	 $if psql
 *	 set disable-completion on
 *	 $endif
 *
 * See `man 3 readline' or `info readline' for the full details. Also,
 * hence the
 *
 * BUGS:
 *
 * - If you split your queries across lines, this whole thing gets
 *	 confused. (To fix this, one would have to read psql's query
 *	 buffer rather than readline's line buffer, which would require
 *	 some major revisions of things.)
 *
 * - Table or attribute names with spaces in it may confuse it.
 *
 * - Quotes, parenthesis, and other funny characters are not handled
 *	 all that gracefully.
 *----------------------------------------------------------------------
 */

#include "postgres_fe.h"
#include "tab-complete.h"
#include "input.h"

/* If we don't have this, we might as well forget about the whole thing: */
#ifdef USE_READLINE

#include <ctype.h>
#include "libpq-fe.h"
#include "pqexpbuffer.h"
#include "common.h"
#include "settings.h"


#ifdef HAVE_RL_FILENAME_COMPLETION_FUNCTION
#define filename_completion_function rl_filename_completion_function
#else
/* missing in some header files */
extern char *filename_completion_function();
#endif

#ifdef HAVE_RL_COMPLETION_MATCHES
#define completion_matches rl_completion_matches
#endif


/*
 * This struct is used to define "schema queries", which are custom-built
 * to obtain possibly-schema-qualified names of database objects.  There is
 * enough similarity in the structure that we don't want to repeat it each
 * time.  So we put the components of each query into this struct and
 * assemble them with the common boilerplate in _complete_from_query().
 */
typedef struct SchemaQuery
{
	/*
	 * Name of catalog or catalogs to be queried, with alias, eg.
	 * "pg_catalog.pg_class c".  Note that "pg_namespace n" will be added.
	 */
	const char *catname;

	/*
	 * Selection condition --- only rows meeting this condition are
	 * candidates to display.  If catname mentions multiple tables,
	 * include the necessary join condition here.  For example, "c.relkind
	 * = 'r'". Write NULL (not an empty string) if not needed.
	 */
	const char *selcondition;

	/*
	 * Visibility condition --- which rows are visible without schema
	 * qualification?  For example,
	 * "pg_catalog.pg_table_is_visible(c.oid)".
	 */
	const char *viscondition;

	/*
	 * Namespace --- name of field to join to pg_namespace.oid. For
	 * example, "c.relnamespace".
	 */
	const char *namespace;

	/*
	 * Result --- the appropriately-quoted name to return, in the case of
	 * an unqualified name.  For example,
	 * "pg_catalog.quote_ident(c.relname)".
	 */
	const char *result;

	/*
	 * In some cases a different result must be used for qualified names.
	 * Enter that here, or write NULL if result can be used.
	 */
	const char *qualresult;
} SchemaQuery;


/* Store maximum number of records we want from database queries
 * (implemented via SELECT ... LIMIT xx).
 */
static int	completion_max_records;

/*
 * Communication variables set by COMPLETE_WITH_FOO macros and then used by
 * the completion callback functions.  Ugly but there is no better way.
 */
static const char *completion_charp;	/* to pass a string */
static const char *const * completion_charpp;	/* to pass a list of
												 * strings */
static const char *completion_info_charp;		/* to pass a second string */
static const SchemaQuery *completion_squery;	/* to pass a SchemaQuery */

/* A couple of macros to ease typing. You can use these to complete the given
   string with
   1) The results from a query you pass it. (Perhaps one of those below?)
   2) The results from a schema query you pass it.
   3) The items from a null-pointer-terminated list.
   4) A string constant
   5) The list of attributes to the given table.
*/
#define COMPLETE_WITH_QUERY(query) \
do { completion_charp = query; matches = completion_matches(text, complete_from_query); } while(0)
#define COMPLETE_WITH_SCHEMA_QUERY(query,addon) \
do { completion_squery = &(query); completion_charp = addon; matches = completion_matches(text, complete_from_schema_query); } while(0)
#define COMPLETE_WITH_LIST(list) \
do { completion_charpp = list; matches = completion_matches(text, complete_from_list); } while(0)
#define COMPLETE_WITH_CONST(string) \
do { completion_charp = string; matches = completion_matches(text, complete_from_const); } while(0)
#define COMPLETE_WITH_ATTR(table) \
do {completion_charp = Query_for_list_of_attributes; completion_info_charp = table; matches = completion_matches(text, complete_from_query); } while(0)

/*
 * Assembly instructions for schema queries
 */

static const SchemaQuery Query_for_list_of_aggregates = {
	/* catname */
	"pg_catalog.pg_proc p",
	/* selcondition */
	"p.proisagg",
	/* viscondition */
	"pg_catalog.pg_function_is_visible(p.oid)",
	/* namespace */
	"p.pronamespace",
	/* result */
	"pg_catalog.quote_ident(p.proname)",
	/* qualresult */
	NULL
};

static const SchemaQuery Query_for_list_of_datatypes = {
	/* catname */
	"pg_catalog.pg_type t",
	/* selcondition --- ignore table rowtypes and array types */
	"(t.typrelid = 0 "
	" OR (SELECT c.relkind = 'c' FROM pg_catalog.pg_class c WHERE c.oid = t.typrelid)) "
	"AND t.typname !~ '^_'",
	/* viscondition */
	"pg_catalog.pg_type_is_visible(t.oid)",
	/* namespace */
	"t.typnamespace",
	/* result */
	"pg_catalog.format_type(t.oid, NULL)",
	/* qualresult */
	"pg_catalog.quote_ident(t.typname)"
};

static const SchemaQuery Query_for_list_of_domains = {
	/* catname */
	"pg_catalog.pg_type t",
	/* selcondition */
	"t.typtype = 'd'",
	/* viscondition */
	"pg_catalog.pg_type_is_visible(t.oid)",
	/* namespace */
	"t.typnamespace",
	/* result */
	"pg_catalog.quote_ident(t.typname)",
	/* qualresult */
	NULL
};

static const SchemaQuery Query_for_list_of_functions = {
	/* catname */
	"pg_catalog.pg_proc p",
	/* selcondition */
	NULL,
	/* viscondition */
	"pg_catalog.pg_function_is_visible(p.oid)",
	/* namespace */
	"p.pronamespace",
	/* result */
	"pg_catalog.quote_ident(p.proname)",
	/* qualresult */
	NULL
};

static const SchemaQuery Query_for_list_of_indexes = {
	/* catname */
	"pg_catalog.pg_class c",
	/* selcondition */
	"c.relkind IN ('i')",
	/* viscondition */
	"pg_catalog.pg_table_is_visible(c.oid)",
	/* namespace */
	"c.relnamespace",
	/* result */
	"pg_catalog.quote_ident(c.relname)",
	/* qualresult */
	NULL
};

static const SchemaQuery Query_for_list_of_sequences = {
	/* catname */
	"pg_catalog.pg_class c",
	/* selcondition */
	"c.relkind IN ('S')",
	/* viscondition */
	"pg_catalog.pg_table_is_visible(c.oid)",
	/* namespace */
	"c.relnamespace",
	/* result */
	"pg_catalog.quote_ident(c.relname)",
	/* qualresult */
	NULL
};

static const SchemaQuery Query_for_list_of_tables = {
	/* catname */
	"pg_catalog.pg_class c",
	/* selcondition */
	"c.relkind IN ('r')",
	/* viscondition */
	"pg_catalog.pg_table_is_visible(c.oid)",
	/* namespace */
	"c.relnamespace",
	/* result */
	"pg_catalog.quote_ident(c.relname)",
	/* qualresult */
	NULL
};

static const SchemaQuery Query_for_list_of_tisv = {
	/* catname */
	"pg_catalog.pg_class c",
	/* selcondition */
	"c.relkind IN ('r', 'i', 'S', 'v')",
	/* viscondition */
	"pg_catalog.pg_table_is_visible(c.oid)",
	/* namespace */
	"c.relnamespace",
	/* result */
	"pg_catalog.quote_ident(c.relname)",
	/* qualresult */
	NULL
};

static const SchemaQuery Query_for_list_of_tsv = {
	/* catname */
	"pg_catalog.pg_class c",
	/* selcondition */
	"c.relkind IN ('r', 'S', 'v')",
	/* viscondition */
	"pg_catalog.pg_table_is_visible(c.oid)",
	/* namespace */
	"c.relnamespace",
	/* result */
	"pg_catalog.quote_ident(c.relname)",
	/* qualresult */
	NULL
};

static const SchemaQuery Query_for_list_of_views = {
	/* catname */
	"pg_catalog.pg_class c",
	/* selcondition */
	"c.relkind IN ('v')",
	/* viscondition */
	"pg_catalog.pg_table_is_visible(c.oid)",
	/* namespace */
	"c.relnamespace",
	/* result */
	"pg_catalog.quote_ident(c.relname)",
	/* qualresult */
	NULL
};


/*
 * Queries to get lists of names of various kinds of things, possibly
 * restricted to names matching a partially entered name.  In these queries,
 * %s will be replaced by the text entered so far (suitably escaped to
 * become a SQL literal string).  %d will be replaced by the length of the
 * string (in unescaped form).	A second %s, if present, will be replaced
 * by a suitably-escaped version of the string provided in
 * completion_info_charp.
 *
 * Beware that the allowed sequences of %s and %d are determined by
 * _complete_from_query().
 */

#define Query_for_list_of_attributes \
"SELECT pg_catalog.quote_ident(attname) "\
"  FROM pg_catalog.pg_attribute a, pg_catalog.pg_class c "\
" WHERE c.oid = a.attrelid "\
"   AND a.attnum > 0 "\
"   AND NOT a.attisdropped "\
"   AND substring(pg_catalog.quote_ident(attname),1,%d)='%s' "\
"   AND pg_catalog.quote_ident(relname)='%s' "\
"   AND pg_catalog.pg_table_is_visible(c.oid)"

#define Query_for_list_of_databases \
"SELECT pg_catalog.quote_ident(datname) FROM pg_catalog.pg_database "\
" WHERE substring(pg_catalog.quote_ident(datname),1,%d)='%s'"

#define Query_for_list_of_tablespaces \
"SELECT pg_catalog.quote_ident(spcname) FROM pg_catalog.pg_tablespace "\
" WHERE substring(pg_catalog.quote_ident(spcname),1,%d)='%s'"

#define Query_for_list_of_encodings \
" SELECT DISTINCT pg_catalog.pg_encoding_to_char(conforencoding) "\
"   FROM pg_catalog.pg_conversion "\
"  WHERE substring(pg_catalog.pg_encoding_to_char(conforencoding),1,%d)=UPPER('%s')"

#define Query_for_list_of_languages \
"SELECT pg_catalog.quote_ident(lanname) "\
"  FROM pg_language "\
" WHERE lanname != 'internal' "\
"   AND substring(pg_catalog.quote_ident(lanname),1,%d)='%s' "

#define Query_for_list_of_schemas \
"SELECT pg_catalog.quote_ident(nspname) FROM pg_catalog.pg_namespace "\
" WHERE substring(pg_catalog.quote_ident(nspname),1,%d)='%s'"

#define Query_for_list_of_set_vars \
"SELECT name FROM "\
" (SELECT pg_catalog.lower(name) AS name FROM pg_catalog.pg_settings "\
"  WHERE context IN ('user', 'superuser') "\
"  UNION ALL SELECT 'constraints' "\
"  UNION ALL SELECT 'transaction' "\
"  UNION ALL SELECT 'session' "\
"  UNION ALL SELECT 'role' "\
"  UNION ALL SELECT 'all') ss "\
" WHERE substring(name,1,%d)='%s'"

#define Query_for_list_of_show_vars \
"SELECT name FROM "\
" (SELECT pg_catalog.lower(name) AS name FROM pg_catalog.pg_settings "\
"  UNION ALL SELECT 'session authorization' "\
"  UNION ALL SELECT 'all') ss "\
" WHERE substring(name,1,%d)='%s'"

#define Query_for_list_of_system_relations \
"SELECT pg_catalog.quote_ident(relname) "\
"  FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "\
" WHERE c.relkind IN ('r', 'v', 's', 'S') "\
"   AND substring(pg_catalog.quote_ident(relname),1,%d)='%s' "\
"   AND c.relnamespace = n.oid "\
"   AND n.nspname = 'pg_catalog'"

#define Query_for_list_of_roles \
" SELECT pg_catalog.quote_ident(rolname) "\
"   FROM pg_catalog.pg_roles "\
"  WHERE substring(pg_catalog.quote_ident(rolname),1,%d)='%s'"

#define Query_for_list_of_grant_roles \
" SELECT pg_catalog.quote_ident(rolname) "\
"   FROM pg_catalog.pg_roles "\
"  WHERE substring(pg_catalog.quote_ident(rolname),1,%d)='%s'"\
" UNION ALL SELECT 'PUBLIC'"

/* the silly-looking length condition is just to eat up the current word */
#define Query_for_table_owning_index \
"SELECT pg_catalog.quote_ident(c1.relname) "\
"  FROM pg_catalog.pg_class c1, pg_catalog.pg_class c2, pg_catalog.pg_index i"\
" WHERE c1.oid=i.indrelid and i.indexrelid=c2.oid"\
"       and (%d = length('%s'))"\
"       and pg_catalog.quote_ident(c2.relname)='%s'"\
"       and pg_catalog.pg_table_is_visible(c2.oid)"

/* the silly-looking length condition is just to eat up the current word */
#define Query_for_index_of_table \
"SELECT pg_catalog.quote_ident(c2.relname) "\
"  FROM pg_catalog.pg_class c1, pg_catalog.pg_class c2, pg_catalog.pg_index i"\
" WHERE c1.oid=i.indrelid and i.indexrelid=c2.oid"\
"       and (%d = length('%s'))"\
"       and pg_catalog.quote_ident(c1.relname)='%s'"\
"       and pg_catalog.pg_table_is_visible(c2.oid)"

/* the silly-looking length condition is just to eat up the current word */
#define Query_for_list_of_tables_for_trigger \
"SELECT pg_catalog.quote_ident(relname) "\
"  FROM pg_catalog.pg_class"\
" WHERE (%d = length('%s'))"\
"   AND oid IN "\
"       (SELECT tgrelid FROM pg_catalog.pg_trigger "\
"         WHERE pg_catalog.quote_ident(tgname)='%s')"

/*
 * This is a list of all "things" in Pgsql, which can show up after CREATE or
 * DROP; and there is also a query to get a list of them.
 */

typedef struct
{
	const char *name;
	const char *query;			/* simple query, or NULL */
	const SchemaQuery *squery;	/* schema query, or NULL */
} pgsql_thing_t;

static const pgsql_thing_t words_after_create[] = {
	{"AGGREGATE", NULL, &Query_for_list_of_aggregates},
	{"CAST", NULL, NULL},		/* Casts have complex structures for
								 * names, so skip it */
	/* CREATE CONSTRAINT TRIGGER is not supported here because it is designed to be used only by pg_dump. */
	{"CONVERSION", "SELECT pg_catalog.quote_ident(conname) FROM pg_catalog.pg_conversion WHERE substring(pg_catalog.quote_ident(conname),1,%d)='%s'"},
	{"DATABASE", Query_for_list_of_databases},
	{"DOMAIN", NULL, &Query_for_list_of_domains},
	{"FUNCTION", NULL, &Query_for_list_of_functions},
	{"GROUP", Query_for_list_of_roles},
	{"LANGUAGE", Query_for_list_of_languages},
	{"INDEX", NULL, &Query_for_list_of_indexes},
	{"OPERATOR", NULL, NULL},	/* Querying for this is probably not such
								 * a good idea. */
	{"ROLE", Query_for_list_of_roles},
	{"RULE", "SELECT pg_catalog.quote_ident(rulename) FROM pg_catalog.pg_rules WHERE substring(pg_catalog.quote_ident(rulename),1,%d)='%s'"},
	{"SCHEMA", Query_for_list_of_schemas},
	{"SEQUENCE", NULL, &Query_for_list_of_sequences},
	{"TABLE", NULL, &Query_for_list_of_tables},
	{"TABLESPACE", Query_for_list_of_tablespaces},
	{"TEMP", NULL, NULL},		/* for CREATE TEMP TABLE ... */
	{"TRIGGER", "SELECT pg_catalog.quote_ident(tgname) FROM pg_catalog.pg_trigger WHERE substring(pg_catalog.quote_ident(tgname),1,%d)='%s'"},
	{"TYPE", NULL, &Query_for_list_of_datatypes},
	{"UNIQUE", NULL, NULL},		/* for CREATE UNIQUE INDEX ... */
	{"USER", Query_for_list_of_roles},
	{"VIEW", NULL, &Query_for_list_of_views},
	{NULL, NULL, NULL}			/* end of list */
};


/* Forward declaration of functions */
static char **psql_completion(char *text, int start, int end);
static char *create_command_generator(const char *text, int state);
static char *complete_from_query(const char *text, int state);
static char *complete_from_schema_query(const char *text, int state);
static char *_complete_from_query(int is_schema_query,
					 const char *text, int state);
static char *complete_from_const(const char *text, int state);
static char *complete_from_list(const char *text, int state);

static PGresult *exec_query(const char *query);

static char *previous_word(int point, int skip);

#if 0
static char *quote_file_name(char *text, int match_type, char *quote_pointer);
static char *dequote_file_name(char *text, char quote_char);
#endif


/* Initialize the readline library for our purposes. */
void
initialize_readline(void)
{
	rl_readline_name = (char *) pset.progname;
	rl_attempted_completion_function = (void *) psql_completion;

	rl_basic_word_break_characters = "\t\n@$><=;|&{( ";

	completion_max_records = 1000;

	/*
	 * There is a variable rl_completion_query_items for this but
	 * apparently it's not defined everywhere.
	 */
}


/* The completion function. Acc. to readline spec this gets passed the text
   entered to far and its start and end in the readline buffer. The return value
   is some partially obscure list format that can be generated by the readline
   libraries completion_matches() function, so we don't have to worry about it.
*/
static char **
psql_completion(char *text, int start, int end)
{
	/* This is the variable we'll return. */
	char	  **matches = NULL;

	/* These are going to contain some scannage of the input line. */
	char	   *prev_wd,
			   *prev2_wd,
			   *prev3_wd,
			   *prev4_wd,
			   *prev5_wd;

	static const char *const sql_commands[] = {
		"ABORT", "ALTER", "ANALYZE", "BEGIN", "CHECKPOINT", "CLOSE", "CLUSTER", "COMMENT",
		"COMMIT", "COPY", "CREATE", "DEALLOCATE", "DECLARE", "DELETE FROM", "DROP", "END", "EXECUTE",
		"EXPLAIN", "FETCH", "GRANT", "INSERT", "LISTEN", "LOAD", "LOCK", "MOVE", "NOTIFY",
		"PREPARE", "REINDEX", "RELEASE", "RESET", "REVOKE", "ROLLBACK", "SAVEPOINT",
		"SELECT", "SET", "SHOW", "START", "TRUNCATE", "UNLISTEN", "UPDATE", "VACUUM", NULL
	};

	static const char *const backslash_commands[] = {
		"\\a", "\\connect", "\\C", "\\cd", "\\copy", "\\copyright",
		"\\d", "\\da", "\\db", "\\dc", "\\dC", "\\dd", "\\dD", "\\df",
		"\\dg", "\\di", "\\dl", "\\dn", "\\do", "\\dp", "\\ds", "\\dS",
		"\\dt", "\\dT", "\\dv", "\\du",
		"\\e", "\\echo", "\\encoding",
		"\\f", "\\g", "\\h", "\\help", "\\H", "\\i", "\\l",
		"\\lo_import", "\\lo_export", "\\lo_list", "\\lo_unlink",
		"\\o", "\\p", "\\pset", "\\q", "\\qecho", "\\r", "\\set", "\\t", "\\T",
		"\\timing", "\\unset", "\\x", "\\w", "\\z", "\\!", NULL
	};

	(void) end;					/* not used */

#ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
	rl_completion_append_character = ' ';
#endif

	/* Clear a few things. */
	completion_charp = NULL;
	completion_charpp = NULL;
	completion_info_charp = NULL;

	/*
	 * Scan the input line before our current position for the last four
	 * words. According to those we'll make some smart decisions on what
	 * the user is probably intending to type. TODO: Use strtokx() to do
	 * this.
	 */
	prev_wd = previous_word(start, 0);
	prev2_wd = previous_word(start, 1);
	prev3_wd = previous_word(start, 2);
	prev4_wd = previous_word(start, 3);
	prev5_wd = previous_word(start, 4);

	/* If a backslash command was started, continue */
	if (text[0] == '\\')
		COMPLETE_WITH_LIST(backslash_commands);

	/* If no previous word, suggest one of the basic sql commands */
	else if (!prev_wd)
		COMPLETE_WITH_LIST(sql_commands);

/* CREATE or DROP but not ALTER (TABLE|DOMAIN|GROUP) sth DROP */
	/* complete with something you can create or drop */
	else if (pg_strcasecmp(prev_wd, "CREATE") == 0 ||
			 (pg_strcasecmp(prev_wd, "DROP") == 0 &&
			  pg_strcasecmp(prev3_wd, "TABLE") != 0 &&
			  pg_strcasecmp(prev3_wd, "DOMAIN") != 0 &&
			  pg_strcasecmp(prev3_wd, "GROUP") != 0))
		matches = completion_matches(text, create_command_generator);

/* ALTER */

	/*
	 * complete with what you can alter (TABLE, GROUP, USER, ...) unless
	 * we're in ALTER TABLE sth ALTER
	 */
	else if (pg_strcasecmp(prev_wd, "ALTER") == 0 &&
			 pg_strcasecmp(prev3_wd, "TABLE") != 0)
	{
		static const char *const list_ALTER[] =
		{"AGGREGATE", "CONVERSION", "DATABASE", "DOMAIN", "FUNCTION",
			"GROUP", "INDEX", "LANGUAGE", "OPERATOR", "ROLE", "SCHEMA", "SEQUENCE", "TABLE",
		"TABLESPACE", "TRIGGER", "TYPE", "USER", NULL};

		COMPLETE_WITH_LIST(list_ALTER);
	}
	/* ALTER AGGREGATE,FUNCTION <name> */
	else if (pg_strcasecmp(prev3_wd, "ALTER") == 0 &&
			(pg_strcasecmp(prev2_wd, "AGGREGATE") == 0 ||
			  pg_strcasecmp(prev2_wd, "FUNCTION") == 0))
	{
		static const char *const list_ALTERAGG[] =
                {"OWNER TO", "RENAME TO","SET SCHEMA", NULL};

                COMPLETE_WITH_LIST(list_ALTERAGG);
	}

	/* ALTER CONVERSION,SCHEMA <name> */
	else if (pg_strcasecmp(prev3_wd, "ALTER") == 0 &&
			  (pg_strcasecmp(prev2_wd, "CONVERSION") == 0 ||
			  pg_strcasecmp(prev2_wd, "SCHEMA") == 0))
	{
		static const char *const list_ALTERGEN[] =
		{"OWNER TO", "RENAME TO", NULL};

		COMPLETE_WITH_LIST(list_ALTERGEN);
	}

	/* ALTER DATABASE <name> */
	else if (pg_strcasecmp(prev3_wd, "ALTER") == 0 &&
			 pg_strcasecmp(prev2_wd, "DATABASE") == 0)
	{
		static const char *const list_ALTERDATABASE[] =
		{"RESET", "SET", "OWNER TO", "RENAME TO", "CONNECTION LIMIT", NULL};

		COMPLETE_WITH_LIST(list_ALTERDATABASE);
	}

	/* ALTER INDEX <name> */
	else if (pg_strcasecmp(prev3_wd, "ALTER") == 0 &&
			 pg_strcasecmp(prev2_wd, "INDEX") == 0)
	{
		static const char *const list_ALTERINDEX[] =
		{"SET TABLESPACE", "OWNER TO", "RENAME TO", NULL};

		COMPLETE_WITH_LIST(list_ALTERINDEX);
	}

	/* ALTER LANGUAGE <name> */
	else if (pg_strcasecmp(prev3_wd, "ALTER") == 0 &&
			 pg_strcasecmp(prev2_wd, "LANGUAGE") == 0)
		COMPLETE_WITH_CONST("RENAME TO");

	/* ALTER USER,ROLE <name> */
	else if (pg_strcasecmp(prev3_wd, "ALTER") == 0 &&
			 (pg_strcasecmp(prev2_wd, "USER") == 0 ||
				pg_strcasecmp(prev2_wd, "ROLE") == 0))
	{
		static const char *const list_ALTERUSER[] =
		{"ENCRYPTED", "UNENCRYPTED", "CREATEDB", "NOCREATEDB", "CREATEUSER",
		 "NOCREATEUSER","CREATEROLE","NOCREATEROLE","INHERIT","NOINHERIT",
		 "LOGIN","NOLOGIN","CONNECTION LIMIT", "VALID UNTIL", "RENAME TO",
		 "SUPERUSER","NOSUPERUSER", "SET", "RESET", NULL};

		COMPLETE_WITH_LIST(list_ALTERUSER);
	}

	/* complete ALTER USER,ROLE <name> ENCRYPTED,UNENCRYPTED with PASSWORD */
	else if (pg_strcasecmp(prev4_wd, "ALTER") == 0 &&
			(pg_strcasecmp(prev3_wd, "ROLE") == 0 || pg_strcasecmp(prev3_wd, "USER") == 0) &&
			(pg_strcasecmp(prev_wd, "ENCRYPTED") == 0 || pg_strcasecmp(prev_wd, "UNENCRYPTED") == 0))
	{
                COMPLETE_WITH_CONST("PASSWORD");
	}
	/* ALTER DOMAIN <name> */
	else if (pg_strcasecmp(prev3_wd, "ALTER") == 0 &&
			 pg_strcasecmp(prev2_wd, "DOMAIN") == 0)
	{
		static const char *const list_ALTERDOMAIN[] =
		{"ADD", "DROP", "OWNER TO", "SET", NULL};

		COMPLETE_WITH_LIST(list_ALTERDOMAIN);
	}
	/* ALTER DOMAIN <sth> DROP */
	else if (pg_strcasecmp(prev4_wd, "ALTER") == 0 &&
			 pg_strcasecmp(prev3_wd, "DOMAIN") == 0 &&
			 pg_strcasecmp(prev_wd, "DROP") == 0)
	{
		static const char *const list_ALTERDOMAIN2[] =
		{"CONSTRAINT", "DEFAULT", "NOT NULL", NULL};

		COMPLETE_WITH_LIST(list_ALTERDOMAIN2);
	}
	/* ALTER DOMAIN <sth> SET */
	else if (pg_strcasecmp(prev4_wd, "ALTER") == 0 &&
			 pg_strcasecmp(prev3_wd, "DOMAIN") == 0 &&
			 pg_strcasecmp(prev_wd, "SET") == 0)
	{
		static const char *const list_ALTERDOMAIN3[] =
		{"DEFAULT", "NOT NULL", "SCHEMA", NULL};

		COMPLETE_WITH_LIST(list_ALTERDOMAIN3);
	}
	/* ALTER SEQUENCE <name> */
	else if (pg_strcasecmp(prev3_wd, "ALTER") == 0 &&
			 pg_strcasecmp(prev2_wd, "SEQUENCE") == 0)
	{
			static const char *const list_ALTERSEQUENCE[] =
			{"INCREMENT", "MINVALUE", "MAXVALUE", "RESTART", "NO", "CACHE", "CYCLE",
			 "SET SCHEMA", NULL};

			COMPLETE_WITH_LIST(list_ALTERSEQUENCE);
	}
	/* ALTER SEQUENCE <name> NO */
	else if (pg_strcasecmp(prev4_wd, "ALTER") == 0 &&
			 pg_strcasecmp(prev3_wd, "SEQUENCE") == 0 &&
			 pg_strcasecmp(prev_wd, "NO") == 0)
	{
			static const char *const list_ALTERSEQUENCE2[] =
			{"MINVALUE", "MAXVALUE", "CYCLE", NULL};

			COMPLETE_WITH_LIST(list_ALTERSEQUENCE2);
	}
	/* ALTER TRIGGER <name>, add ON */
	else if (pg_strcasecmp(prev3_wd, "ALTER") == 0 &&
			 pg_strcasecmp(prev2_wd, "TRIGGER") == 0)
		COMPLETE_WITH_CONST("ON");

	else if (pg_strcasecmp(prev4_wd, "ALTER") == 0 &&
			 pg_strcasecmp(prev3_wd, "TRIGGER") == 0)
	{
		completion_info_charp = prev2_wd;
		COMPLETE_WITH_QUERY(Query_for_list_of_tables_for_trigger);
	}

	/*
	 * If we have ALTER TRIGGER <sth> ON, then add the correct tablename
	 */
	else if (pg_strcasecmp(prev4_wd, "ALTER") == 0 &&
			 pg_strcasecmp(prev3_wd, "TRIGGER") == 0 &&
			 pg_strcasecmp(prev_wd, "ON") == 0)
		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, NULL);

	/* ALTER TRIGGER <name> ON <name> */
	else if (pg_strcasecmp(prev4_wd, "TRIGGER") == 0 &&
			 pg_strcasecmp(prev2_wd, "ON") == 0)
		COMPLETE_WITH_CONST("RENAME TO");

	/*
	 * If we detect ALTER TABLE <name>, suggest either ADD, DROP, ALTER,
	 * RENAME, CLUSTER ON or OWNER
	 */
	else if (pg_strcasecmp(prev3_wd, "ALTER") == 0 &&
			 pg_strcasecmp(prev2_wd, "TABLE") == 0)
	{
		static const char *const list_ALTER2[] =
		{"ADD", "ALTER", "CLUSTER ON", "DROP", "RENAME", "OWNER TO",
		"SET", NULL};

		COMPLETE_WITH_LIST(list_ALTER2);
	}
	/* If we have TABLE <sth> ALTER|RENAME, provide list of columns */
	else if (pg_strcasecmp(prev3_wd, "TABLE") == 0 &&
			 (pg_strcasecmp(prev_wd, "ALTER") == 0 ||
			  pg_strcasecmp(prev_wd, "RENAME") == 0))
		COMPLETE_WITH_ATTR(prev2_wd);

	/* ALTER TABLE xxx RENAME yyy */
	else if (pg_strcasecmp(prev4_wd, "TABLE") == 0 &&
			 pg_strcasecmp(prev2_wd, "RENAME") == 0 &&
			 pg_strcasecmp(prev_wd, "TO") != 0)
		COMPLETE_WITH_CONST("TO");

	/* If we have TABLE <sth> DROP, provide COLUMN or CONSTRAINT */
	else if (pg_strcasecmp(prev3_wd, "TABLE") == 0 &&
			 pg_strcasecmp(prev_wd, "DROP") == 0)
	{
		static const char *const list_TABLEDROP[] =
		{"COLUMN", "CONSTRAINT", NULL};

		COMPLETE_WITH_LIST(list_TABLEDROP);
	}
	/* If we have TABLE <sth> DROP COLUMN, provide list of columns */
	else if (pg_strcasecmp(prev4_wd, "TABLE") == 0 &&
			 pg_strcasecmp(prev2_wd, "DROP") == 0 &&
			 pg_strcasecmp(prev_wd, "COLUMN") == 0)
		COMPLETE_WITH_ATTR(prev3_wd);
	/* ALTER TABLE ALTER [COLUMN] <foo> */
	else if ((pg_strcasecmp(prev3_wd, "ALTER") == 0 &&
			  pg_strcasecmp(prev2_wd, "COLUMN") == 0) ||
			 (pg_strcasecmp(prev4_wd, "TABLE") == 0 &&
			  pg_strcasecmp(prev2_wd, "ALTER") == 0))
	{
		/* DROP ... does not work well yet */
		static const char *const list_COLUMNALTER[] = 
		{"TYPE", "SET DEFAULT", "DROP DEFAULT", "SET NOT NULL",
		 "DROP NOT NULL", "SET STATISTICS", "SET STORAGE", NULL};

		COMPLETE_WITH_LIST(list_COLUMNALTER);
	}
	else if (pg_strcasecmp(prev3_wd, "TABLE") == 0 &&
			 pg_strcasecmp(prev_wd, "CLUSTER") == 0)
		COMPLETE_WITH_CONST("ON");
	else if (pg_strcasecmp(prev4_wd, "TABLE") == 0 &&
			 pg_strcasecmp(prev2_wd, "CLUSTER") == 0 &&
			 pg_strcasecmp(prev_wd, "ON") == 0)
	{
		completion_info_charp = prev3_wd;
		COMPLETE_WITH_QUERY(Query_for_index_of_table);
	}
	/* If we have TABLE <sth> SET, provide WITHOUT,TABLESPACE and SCHEMA */
	else if (pg_strcasecmp(prev3_wd, "TABLE") == 0 &&
			 pg_strcasecmp(prev_wd, "SET") == 0)
	{
		static const char *const list_TABLESET[] =
		{"WITHOUT", "TABLESPACE","SCHEMA", NULL};

		COMPLETE_WITH_LIST(list_TABLESET);
	}
	/* If we have TABLE <sth> SET TABLESPACE provide a list of tablespaces */
	else if (pg_strcasecmp(prev4_wd, "TABLE") == 0 &&
			 pg_strcasecmp(prev2_wd, "SET") == 0 &&
			 pg_strcasecmp(prev_wd, "TABLESPACE") == 0)
		COMPLETE_WITH_QUERY(Query_for_list_of_tablespaces);
	/* If we have TABLE <sth> SET WITHOUT provide CLUSTER or OIDS */
	else if (pg_strcasecmp(prev4_wd, "TABLE") == 0 &&
			 pg_strcasecmp(prev2_wd, "SET") == 0 &&
			 pg_strcasecmp(prev_wd, "WITHOUT") == 0)
	{
		static const char *const list_TABLESET2[] =
		{"CLUSTER", "OIDS", NULL};

		COMPLETE_WITH_LIST(list_TABLESET2);
	}
	/* we have ALTER TABLESPACE, so suggest RENAME TO, OWNER TO */
	else if (pg_strcasecmp(prev3_wd, "ALTER") == 0 &&
			 pg_strcasecmp(prev2_wd, "TABLESPACE") == 0)
	{
		static const char *const list_ALTERTSPC[] =
		{"RENAME TO", "OWNER TO", NULL};

		COMPLETE_WITH_LIST(list_ALTERTSPC);
	}
	/* complete ALTER TYPE <foo> with OWNER TO, SET SCHEMA */
	else if (pg_strcasecmp(prev3_wd, "ALTER") == 0 &&
			 pg_strcasecmp(prev2_wd, "TYPE") == 0)
	{
		static const char *const list_ALTERTYPE[] =
		{"OWNER TO", "SET SCHEMA", NULL};
		COMPLETE_WITH_LIST(list_ALTERTYPE);
	}
	/* complete ALTER GROUP <foo> */
	else if (pg_strcasecmp(prev3_wd, "ALTER") == 0 &&
			 pg_strcasecmp(prev2_wd, "GROUP") == 0)
	{
		static const char *const list_ALTERGROUP[] =
		{"ADD USER", "DROP USER", "RENAME TO", NULL};

		COMPLETE_WITH_LIST(list_ALTERGROUP);
	}
	/* complete ALTER GROUP <foo> ADD|DROP with USER */
	else if (pg_strcasecmp(prev4_wd, "ALTER") == 0 &&
			 pg_strcasecmp(prev3_wd, "GROUP") == 0 &&
			 (pg_strcasecmp(prev_wd, "ADD") == 0 ||
			  pg_strcasecmp(prev_wd, "DROP") == 0))
		COMPLETE_WITH_CONST("USER");
	/* complete {ALTER} GROUP <foo> ADD|DROP USER with a user name */
	else if (pg_strcasecmp(prev4_wd, "GROUP") == 0 &&
			 (pg_strcasecmp(prev2_wd, "ADD") == 0 ||
			  pg_strcasecmp(prev2_wd, "DROP") == 0) &&
			 pg_strcasecmp(prev_wd, "USER") == 0)
		COMPLETE_WITH_QUERY(Query_for_list_of_roles);

/* BEGIN, END, ABORT */
	else if (pg_strcasecmp(prev_wd, "BEGIN") == 0 ||
			 pg_strcasecmp(prev_wd, "END") == 0 ||
			 pg_strcasecmp(prev_wd, "ABORT") == 0)
	{
		static const char *const list_TRANS[] =
		{"WORK", "TRANSACTION", NULL};

		COMPLETE_WITH_LIST(list_TRANS);
	} 
/* COMMIT */
	else if(pg_strcasecmp(prev_wd, "COMMIT") == 0)
	{
		static const char *const list_COMMIT[] =
		{"WORK", "TRANSACTION", "PREPARED", NULL};

		COMPLETE_WITH_LIST(list_COMMIT);
	}
/* RELEASE SAVEPOINT */
	else if (pg_strcasecmp(prev_wd, "RELEASE") == 0)
		COMPLETE_WITH_CONST("SAVEPOINT");
/* ROLLBACK*/
	else if (pg_strcasecmp(prev_wd, "ROLLBACK") == 0)
	{
		static const char *const list_TRANS[] =
		{"WORK", "TRANSACTION", "TO SAVEPOINT", "PREPARED", NULL};

		COMPLETE_WITH_LIST(list_TRANS);
	}
/* CLUSTER */

	/*
	 * If the previous word is CLUSTER and not without produce list of
	 * indexes.
	 */
	else if (pg_strcasecmp(prev_wd, "CLUSTER") == 0 &&
			 pg_strcasecmp(prev2_wd, "WITHOUT") != 0)
		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_indexes, NULL);
	/* If we have CLUSTER <sth>, then add "ON" */
	else if (pg_strcasecmp(prev2_wd, "CLUSTER") == 0 &&
			 pg_strcasecmp(prev_wd, "ON") != 0)
		COMPLETE_WITH_CONST("ON");

	/*
	 * If we have CLUSTER <sth> ON, then add the correct tablename as
	 * well.
	 */
	else if (pg_strcasecmp(prev3_wd, "CLUSTER") == 0 &&
			 pg_strcasecmp(prev_wd, "ON") == 0)
	{
		completion_info_charp = prev2_wd;
		COMPLETE_WITH_QUERY(Query_for_table_owning_index);
	}

/* COMMENT */
	else if (pg_strcasecmp(prev_wd, "COMMENT") == 0)
		COMPLETE_WITH_CONST("ON");
	else if (pg_strcasecmp(prev2_wd, "COMMENT") == 0 &&
			 pg_strcasecmp(prev_wd, "ON") == 0)
	{
		static const char *const list_COMMENT[] =
		{"CAST", "CONVERSION", "DATABASE", "INDEX", "LANGUAGE", "RULE", "SCHEMA",
			"SEQUENCE", "TABLE", "TYPE", "VIEW", "COLUMN", "AGGREGATE", "FUNCTION",
		"OPERATOR", "TRIGGER", "CONSTRAINT", "DOMAIN","LARGE OBJECT", NULL};

		COMPLETE_WITH_LIST(list_COMMENT);
	}
	else if (pg_strcasecmp(prev4_wd, "COMMENT") == 0 &&
			 pg_strcasecmp(prev3_wd, "ON") == 0)
		COMPLETE_WITH_CONST("IS");

/* COPY */

	/*
	 * If we have COPY [BINARY] (which you'd have to type yourself), offer
	 * list of tables (Also cover the analogous backslash command)
	 */
	else if (pg_strcasecmp(prev_wd, "COPY") == 0 ||
			 pg_strcasecmp(prev_wd, "\\copy") == 0 ||
			 (pg_strcasecmp(prev2_wd, "COPY") == 0 &&
			  pg_strcasecmp(prev_wd, "BINARY") == 0))
		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, NULL);
	/* If we have COPY|BINARY <sth>, complete it with "TO" or "FROM" */
	else if (pg_strcasecmp(prev2_wd, "COPY") == 0 ||
			 pg_strcasecmp(prev2_wd, "\\copy") == 0 ||
			 pg_strcasecmp(prev2_wd, "BINARY") == 0)
		{
			static const char *const list_FROMTO[] =
			{"FROM", "TO", NULL};

			COMPLETE_WITH_LIST(list_FROMTO);
		}
	/* If we have COPY|BINARY <sth> FROM|TO, complete with filename */
	else if ((pg_strcasecmp(prev3_wd, "COPY") == 0 ||
			  pg_strcasecmp(prev3_wd, "\\copy") == 0 ||
			  pg_strcasecmp(prev3_wd, "BINARY") == 0) &&
			 (pg_strcasecmp(prev_wd, "FROM") == 0 ||
			  pg_strcasecmp(prev_wd, "TO") == 0))
		matches = completion_matches(text, filename_completion_function);

	/* Handle COPY|BINARY <sth> FROM|TO filename */
	else if ((pg_strcasecmp(prev4_wd, "COPY") == 0 ||
			  pg_strcasecmp(prev4_wd, "\\copy") == 0 ||
			  pg_strcasecmp(prev4_wd, "BINARY") == 0) &&
			 (pg_strcasecmp(prev2_wd, "FROM") == 0 ||
			  pg_strcasecmp(prev2_wd, "TO") == 0))
		{
			static const char *const list_COPY[] =
			{"BINARY", "OIDS", "DELIMITER", "NULL", "CSV", NULL};

			COMPLETE_WITH_LIST(list_COPY);
		}

	/* Handle COPY|BINARY <sth> FROM|TO filename CSV */
	else if (pg_strcasecmp(prev_wd, "CSV") == 0 && 
			 (pg_strcasecmp(prev3_wd, "FROM") == 0 ||
			  pg_strcasecmp(prev3_wd, "TO") == 0))
	{
			static const char *const list_CSV[] =
			{"HEADER", "QUOTE", "ESCAPE", "FORCE QUOTE", NULL};

			COMPLETE_WITH_LIST(list_CSV);
	}

	/* CREATE DATABASE */
	else if (pg_strcasecmp(prev3_wd, "CREATE") == 0 &&
			 pg_strcasecmp(prev2_wd, "DATABASE") == 0)
	{
		static const char *const list_DATABASE[] =
		{"OWNER", "TEMPLATE", "ENCODING", "TABLESPACE", "CONNECTION LIMIT",
		 NULL};

		COMPLETE_WITH_LIST(list_DATABASE);
	}

	/* CREATE INDEX */
	/* First off we complete CREATE UNIQUE with "INDEX" */
	else if (pg_strcasecmp(prev2_wd, "CREATE") == 0 &&
			 pg_strcasecmp(prev_wd, "UNIQUE") == 0)
		COMPLETE_WITH_CONST("INDEX");
	/* If we have CREATE|UNIQUE INDEX <sth>, then add "ON" */
	else if (pg_strcasecmp(prev2_wd, "INDEX") == 0 &&
			 (pg_strcasecmp(prev3_wd, "CREATE") == 0 ||
			  pg_strcasecmp(prev3_wd, "UNIQUE") == 0))
		COMPLETE_WITH_CONST("ON");
	/* Complete ... INDEX <name> ON with a list of tables  */
	else if (pg_strcasecmp(prev3_wd, "INDEX") == 0 &&
			 pg_strcasecmp(prev_wd, "ON") == 0)
		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, NULL);

	/*
	 * Complete INDEX <name> ON <table> with a list of table columns
	 * (which should really be in parens)
	 */
	else if (pg_strcasecmp(prev4_wd, "INDEX") == 0 &&
			 pg_strcasecmp(prev2_wd, "ON") == 0)
		COMPLETE_WITH_ATTR(prev_wd);
	/* same if you put in USING */
	else if (pg_strcasecmp(prev4_wd, "ON") == 0 &&
			 pg_strcasecmp(prev2_wd, "USING") == 0)
		COMPLETE_WITH_ATTR(prev3_wd);
	/* Complete USING with an index method */
	else if (pg_strcasecmp(prev_wd, "USING") == 0)
	{
		static const char *const index_mth[] =
		{"BTREE", "RTREE", "HASH", "GIST", NULL};

		COMPLETE_WITH_LIST(index_mth);
	}

/* CREATE RULE */
	/* Complete "CREATE RULE <sth>" with "AS" */
	else if (pg_strcasecmp(prev3_wd, "CREATE") == 0 &&
			 pg_strcasecmp(prev2_wd, "RULE") == 0)
		COMPLETE_WITH_CONST("AS");
	/* Complete "CREATE RULE <sth> AS with "ON" */
	else if (pg_strcasecmp(prev4_wd, "CREATE") == 0 &&
			 pg_strcasecmp(prev3_wd, "RULE") == 0 &&
			 pg_strcasecmp(prev_wd, "AS") == 0)
		COMPLETE_WITH_CONST("ON");
	/* Complete "RULE * AS ON" with SELECT|UPDATE|DELETE|INSERT */
	else if (pg_strcasecmp(prev4_wd, "RULE") == 0 &&
			 pg_strcasecmp(prev2_wd, "AS") == 0 &&
			 pg_strcasecmp(prev_wd, "ON") == 0)
	{
		static const char *const rule_events[] =
		{"SELECT", "UPDATE", "INSERT", "DELETE", NULL};

		COMPLETE_WITH_LIST(rule_events);
	}
	/* Complete "AS ON <sth with a 'T' :)>" with a "TO" */
	else if (pg_strcasecmp(prev3_wd, "AS") == 0 &&
			 pg_strcasecmp(prev2_wd, "ON") == 0 &&
			 (toupper((unsigned char) prev_wd[4]) == 'T' ||
			  toupper((unsigned char) prev_wd[5]) == 'T'))
		COMPLETE_WITH_CONST("TO");
	/* Complete "AS ON <sth> TO" with a table name */
	else if (pg_strcasecmp(prev4_wd, "AS") == 0 &&
			 pg_strcasecmp(prev3_wd, "ON") == 0 &&
			 pg_strcasecmp(prev_wd, "TO") == 0)
		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, NULL);

/* CREATE TABLE */
	/* Complete CREATE TEMP with "TABLE" */
	else if (pg_strcasecmp(prev2_wd, "CREATE") == 0 &&
			 pg_strcasecmp(prev_wd, "TEMP") == 0)
		COMPLETE_WITH_CONST("TABLE");

/* CREATE TABLESPACE */
	else if (pg_strcasecmp(prev3_wd, "CREATE") == 0 &&
			 pg_strcasecmp(prev2_wd, "TABLESPACE") == 0)
	{
		static const char *const list_CREATETABLESPACE[] =
		{"OWNER", "LOCATION", NULL};

		COMPLETE_WITH_LIST(list_CREATETABLESPACE);
	}
	/* Complete CREATE TABLESPACE name OWNER name with "LOCATION" */
	else if (pg_strcasecmp(prev5_wd, "CREATE") == 0 &&
			 pg_strcasecmp(prev4_wd, "TABLESPACE") == 0 &&
			 pg_strcasecmp(prev2_wd, "OWNER") == 0)
	{
		COMPLETE_WITH_CONST("LOCATION");
	}

/* CREATE TRIGGER */
	/* complete CREATE TRIGGER <name> with BEFORE,AFTER */
	else if (pg_strcasecmp(prev3_wd, "CREATE") == 0 &&
			pg_strcasecmp(prev2_wd, "TRIGGER") == 0)
	{
		static const char *const list_CREATETRIGGER[] =
			{"BEFORE", "AFTER", NULL};
		COMPLETE_WITH_LIST(list_CREATETRIGGER);	
	}
	/* complete CREATE TRIGGER <name> BEFORE,AFTER sth with OR,ON */
	else if (pg_strcasecmp(prev5_wd, "CREATE") == 0 &&
			pg_strcasecmp(prev4_wd, "TRIGGER") == 0 &&
			(pg_strcasecmp(prev2_wd, "BEFORE") == 0 ||
			pg_strcasecmp(prev2_wd, "AFTER") == 0))
	{
		static const char *const list_CREATETRIGGER2[] =
			{"ON","OR",NULL};
		COMPLETE_WITH_LIST(list_CREATETRIGGER2);
	}

/* CREATE ROLE,USER,GROUP */
	else if (pg_strcasecmp(prev3_wd, "CREATE") == 0 &&
			 (pg_strcasecmp(prev2_wd, "ROLE") == 0 ||
			  pg_strcasecmp(prev2_wd, "GROUP") == 0 || pg_strcasecmp(prev2_wd, "USER") == 0))
	{
		static const char *const list_CREATEROLE[] =
                        {"ADMIN","CONNECTION LIMIT","CREATEDB","CREATEROLE","CREATEUSER",
			 "ENCRYPTED", "IN", "INHERIT", "LOGIN", "NOINHERIT", "NOLOGIN", "NOCREATEDB", 
			 "NOCREATEROLE", "NOCREATEUSER", "NOSUPERUSER", "ROLE", "SUPERUSER", "SYSID",
			 "UNENCRYPTED",NULL};
                COMPLETE_WITH_LIST(list_CREATEROLE);
	}
	/* complete CREATE ROLE,USER,GROUP <name> ENCRYPTED,UNENCRYPTED with PASSWORD */
	else if (pg_strcasecmp(prev4_wd, "CREATE") == 0 &&
			(pg_strcasecmp(prev3_wd, "ROLE") == 0 ||
                          pg_strcasecmp(prev3_wd, "GROUP") == 0 || pg_strcasecmp(prev3_wd, "USER") == 0) &&
			(pg_strcasecmp(prev_wd, "ENCRYPTED") == 0 || pg_strcasecmp(prev_wd, "UNENCRYPTED") == 0))
	{
                COMPLETE_WITH_CONST("PASSWORD");
	}
	/* complete CREATE ROLE,USER,GROUP <name> IN with ROLE,GROUP */
	else if (pg_strcasecmp(prev4_wd, "CREATE") == 0 &&
			(pg_strcasecmp(prev3_wd, "ROLE") == 0 ||
                          pg_strcasecmp(prev3_wd, "GROUP") == 0 || pg_strcasecmp(prev3_wd, "USER") == 0) &&
			pg_strcasecmp(prev_wd, "IN") == 0)
	{
		static const char *const list_CREATEROLE3[] =
                        {"GROUP","ROLE",NULL};
                COMPLETE_WITH_LIST(list_CREATEROLE3);
	}

/* CREATE VIEW */
	/* Complete CREATE VIEW <name> with AS */
	else if (pg_strcasecmp(prev3_wd, "CREATE") == 0 &&
			 pg_strcasecmp(prev2_wd, "VIEW") == 0)
		COMPLETE_WITH_CONST("AS");
	/* Complete "CREATE VIEW <sth> AS with "SELECT" */
	else if (pg_strcasecmp(prev4_wd, "CREATE") == 0 &&
			 pg_strcasecmp(prev3_wd, "VIEW") == 0 &&
			 pg_strcasecmp(prev_wd, "AS") == 0)
		COMPLETE_WITH_CONST("SELECT");

/* DECLARE */
	else if (pg_strcasecmp(prev2_wd, "DECLARE") == 0)
	{
			static const char *const list_DECLARE[] =
			{"BINARY", "INSENSITIVE", "SCROLL", "NO SCROLL", "CURSOR", NULL};
			COMPLETE_WITH_LIST(list_DECLARE);
	}

	else if (pg_strcasecmp(prev_wd, "CURSOR") == 0)
	{
			static const char *const list_DECLARECURSOR[] =
			{"WITH HOLD", "WITHOUT HOLD", "FOR", NULL};
			COMPLETE_WITH_LIST(list_DECLARECURSOR);
	}


/* DELETE */
	/*
	 * Complete DELETE with FROM (only if the word before that is not "ON"
	 * (cf. rules) or "BEFORE" or "AFTER" (cf. triggers) or GRANT)
	 */
	else if (pg_strcasecmp(prev_wd, "DELETE") == 0 &&
			 !(pg_strcasecmp(prev2_wd, "ON") == 0 ||
			   pg_strcasecmp(prev2_wd, "GRANT") == 0 ||
			   pg_strcasecmp(prev2_wd, "BEFORE") == 0 ||
			   pg_strcasecmp(prev2_wd, "AFTER") == 0))
		COMPLETE_WITH_CONST("FROM");
	/* Complete DELETE FROM with a list of tables */
	else if (pg_strcasecmp(prev2_wd, "DELETE") == 0 &&
			 pg_strcasecmp(prev_wd, "FROM") == 0)
		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, NULL);
	/* Complete DELETE FROM <table> */
	else if (pg_strcasecmp(prev3_wd, "DELETE") == 0 &&
			 pg_strcasecmp(prev2_wd, "FROM") == 0)
	{
		static const char *const list_DELETE[] =
		{"USING", "WHERE", "SET", NULL};

		COMPLETE_WITH_LIST(list_DELETE);
	}
	/* XXX: implement tab completion for DELETE ... USING */

/* DROP (when not the previous word) */
	/* DROP AGGREGATE */
	else if (pg_strcasecmp(prev3_wd, "DROP") == 0 &&
			 pg_strcasecmp(prev2_wd, "AGGREGATE") == 0)
		COMPLETE_WITH_CONST("(");

	/* DROP object with CASCADE / RESTRICT */
	else if ((pg_strcasecmp(prev3_wd, "DROP") == 0 &&
			  (pg_strcasecmp(prev2_wd, "CONVERSION") == 0 ||
			   pg_strcasecmp(prev2_wd, "DOMAIN") == 0 ||
			   pg_strcasecmp(prev2_wd, "FUNCTION") == 0 ||
			   pg_strcasecmp(prev2_wd, "INDEX") == 0 ||
			   pg_strcasecmp(prev2_wd, "LANGUAGE") == 0 ||
			   pg_strcasecmp(prev2_wd, "SCHEMA") == 0 ||
			   pg_strcasecmp(prev2_wd, "SEQUENCE") == 0 ||
			   pg_strcasecmp(prev2_wd, "TABLE") == 0 ||
			   pg_strcasecmp(prev2_wd, "TYPE") == 0 ||
			   pg_strcasecmp(prev2_wd, "VIEW") == 0)) ||
			 (pg_strcasecmp(prev4_wd, "DROP") == 0 &&
			  pg_strcasecmp(prev3_wd, "AGGREGATE") == 0 &&
			  prev_wd[strlen(prev_wd) - 1] == ')'))
	{
			static const char *const list_DROPCR[] =
			{"CASCADE", "RESTRICT", NULL};
			COMPLETE_WITH_LIST(list_DROPCR);
	}

/* EXPLAIN */
	/*
	 * Complete EXPLAIN [ANALYZE] [VERBOSE] with list of EXPLAIN-able commands
	 */
	else if (pg_strcasecmp(prev_wd, "EXPLAIN") == 0)
	{
			static const char *const list_EXPLAIN[] =
			{"SELECT","INSERT","DELETE","UPDATE","DECLARE","ANALYZE","VERBOSE",NULL};
			COMPLETE_WITH_LIST(list_EXPLAIN);
	}
	else if (pg_strcasecmp(prev2_wd, "EXPLAIN") == 0 &&
					 pg_strcasecmp(prev_wd, "ANALYZE") == 0)
	{
			static const char *const list_EXPLAIN[] =
			{"SELECT","INSERT","DELETE","UPDATE","DECLARE","VERBOSE",NULL};
			COMPLETE_WITH_LIST(list_EXPLAIN);
	}
	else if (pg_strcasecmp(prev_wd, "VERBOSE") == 0 &&
			 pg_strcasecmp(prev3_wd, "VACUUM") != 0 &&
			 pg_strcasecmp(prev4_wd, "VACUUM") != 0 &&
			 (pg_strcasecmp(prev2_wd, "ANALYZE") == 0 ||
			  pg_strcasecmp(prev2_wd, "EXPLAIN") == 0))
	{
			static const char *const list_EXPLAIN[] =
			{"SELECT","INSERT","DELETE","UPDATE","DECLARE",NULL};
			COMPLETE_WITH_LIST(list_EXPLAIN);
	}

/* FETCH && MOVE */
	/* Complete FETCH with one of FORWARD, BACKWARD, RELATIVE */
	else if (pg_strcasecmp(prev_wd, "FETCH") == 0 ||
			 pg_strcasecmp(prev_wd, "MOVE") == 0)
	{
		static const char *const list_FETCH1[] =
		{"ABSOLUTE", "BACKWARD", "FORWARD", "RELATIVE", NULL};

		COMPLETE_WITH_LIST(list_FETCH1);
	}
	/* Complete FETCH <sth> with one of ALL, NEXT, PRIOR */
	else if (pg_strcasecmp(prev2_wd, "FETCH") == 0 ||
			 pg_strcasecmp(prev2_wd, "MOVE") == 0)
	{
		static const char *const list_FETCH2[] =
		{"ALL", "NEXT", "PRIOR", NULL};

		COMPLETE_WITH_LIST(list_FETCH2);
	}

	/*
	 * Complete FETCH <sth1> <sth2> with "FROM" or "IN". These are
	 * equivalent, but we may as well tab-complete both: perhaps some
	 * users prefer one variant or the other.
	 */
	else if (pg_strcasecmp(prev3_wd, "FETCH") == 0 ||
			 pg_strcasecmp(prev3_wd, "MOVE") == 0)
	{
		static const char *const list_FROMIN[] =
		{"FROM", "IN", NULL};

		COMPLETE_WITH_LIST(list_FROMIN);
	}

/* GRANT && REVOKE*/
	/* Complete GRANT/REVOKE with a list of privileges */
	else if (pg_strcasecmp(prev_wd, "GRANT") == 0 ||
			 pg_strcasecmp(prev_wd, "REVOKE") == 0)
	{
		static const char *const list_privileg[] =
		{"SELECT", "INSERT", "UPDATE", "DELETE", "RULE", "REFERENCES",
		"TRIGGER", "CREATE", "TEMPORARY", "EXECUTE", "USAGE", "ALL", NULL};

		COMPLETE_WITH_LIST(list_privileg);
	}
	/* Complete GRANT/REVOKE <sth> with "ON" */
	else if (pg_strcasecmp(prev2_wd, "GRANT") == 0 ||
			 pg_strcasecmp(prev2_wd, "REVOKE") == 0)
		COMPLETE_WITH_CONST("ON");

	/*
	 * Complete GRANT/REVOKE <sth> ON with a list of tables, views,
	 * sequences, and indexes
	 *
	 * keywords DATABASE, FUNCTION, LANGUAGE, SCHEMA added to query result
	 * via UNION; seems to work intuitively
	 *
	 * Note: GRANT/REVOKE can get quite complex; tab-completion as
	 * implemented here will only work if the privilege list contains
	 * exactly one privilege
	 */
	else if ((pg_strcasecmp(prev3_wd, "GRANT") == 0 ||
			  pg_strcasecmp(prev3_wd, "REVOKE") == 0) &&
			 pg_strcasecmp(prev_wd, "ON") == 0)
		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tsv,
								   " UNION SELECT 'DATABASE'"
								   " UNION SELECT 'FUNCTION'"
								   " UNION SELECT 'LANGUAGE'"
								   " UNION SELECT 'SCHEMA'"
								   " UNION SELECT 'TABLESPACE'");

	/* Complete "GRANT/REVOKE * ON * " with "TO" */
	else if ((pg_strcasecmp(prev4_wd, "GRANT") == 0 ||
			  pg_strcasecmp(prev4_wd, "REVOKE") == 0) &&
			 pg_strcasecmp(prev2_wd, "ON") == 0)
	{
		if (pg_strcasecmp(prev_wd, "DATABASE") == 0)
			COMPLETE_WITH_QUERY(Query_for_list_of_databases);
		else if (pg_strcasecmp(prev_wd, "FUNCTION") == 0)
			COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_functions, NULL);
		else if (pg_strcasecmp(prev_wd, "LANGUAGE") == 0)
			COMPLETE_WITH_QUERY(Query_for_list_of_languages);
		else if (pg_strcasecmp(prev_wd, "SCHEMA") == 0)
			COMPLETE_WITH_QUERY(Query_for_list_of_schemas);
		else if (pg_strcasecmp(prev_wd, "TABLESPACE") == 0)
			COMPLETE_WITH_QUERY(Query_for_list_of_tablespaces);
		else if (pg_strcasecmp(prev4_wd, "GRANT") == 0)
			COMPLETE_WITH_CONST("TO");
		else
			COMPLETE_WITH_CONST("FROM");
	}

	/* Complete "GRANT/REVOKE * ON * TO/FROM" with username, GROUP, or PUBLIC */
	else if (pg_strcasecmp(prev3_wd, "ON") == 0 &&
			 ((pg_strcasecmp(prev5_wd, "GRANT") == 0 &&
			   pg_strcasecmp(prev_wd, "TO") == 0) ||
			  (pg_strcasecmp(prev5_wd, "REVOKE") == 0 &&
			   pg_strcasecmp(prev_wd, "FROM") == 0)))
		COMPLETE_WITH_QUERY(Query_for_list_of_grant_roles);

/* GROUP BY */
	else if (pg_strcasecmp(prev3_wd, "FROM") == 0 &&
			 pg_strcasecmp(prev_wd, "GROUP") == 0)
		COMPLETE_WITH_CONST("BY");

/* INSERT */
	/* Complete INSERT with "INTO" */
	else if (pg_strcasecmp(prev_wd, "INSERT") == 0)
		COMPLETE_WITH_CONST("INTO");
	/* Complete INSERT INTO with table names */
	else if (pg_strcasecmp(prev2_wd, "INSERT") == 0 &&
			 pg_strcasecmp(prev_wd, "INTO") == 0)
		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, NULL);
	/* Complete "INSERT INTO <table> (" with attribute names */
	else if (rl_line_buffer[start - 1] == '(' &&
			 pg_strcasecmp(prev3_wd, "INSERT") == 0 &&
			 pg_strcasecmp(prev2_wd, "INTO") == 0)
		COMPLETE_WITH_ATTR(prev_wd);

	/*
	 * Complete INSERT INTO <table> with "VALUES" or "SELECT" or "DEFAULT
	 * VALUES"
	 */
	else if (pg_strcasecmp(prev3_wd, "INSERT") == 0 &&
			 pg_strcasecmp(prev2_wd, "INTO") == 0)
	{
		static const char *const list_INSERT[] =
		{"DEFAULT VALUES", "SELECT", "VALUES", NULL};

		COMPLETE_WITH_LIST(list_INSERT);
	}
	/* Complete INSERT INTO <table> (attribs) with "VALUES" or "SELECT" */
	else if (pg_strcasecmp(prev4_wd, "INSERT") == 0 &&
			 pg_strcasecmp(prev3_wd, "INTO") == 0 &&
			 prev_wd[strlen(prev_wd) - 1] == ')')
	{
		static const char *const list_INSERT[] =
		{"SELECT", "VALUES", NULL};

		COMPLETE_WITH_LIST(list_INSERT);
	}

	/* Insert an open parenthesis after "VALUES" */
	else if (pg_strcasecmp(prev_wd, "VALUES") == 0 &&
			 pg_strcasecmp(prev2_wd, "DEFAULT") != 0)
		COMPLETE_WITH_CONST("(");

/* LOCK */
	/* Complete LOCK [TABLE] with a list of tables */
	else if (pg_strcasecmp(prev_wd, "LOCK") == 0 ||
			 (pg_strcasecmp(prev_wd, "TABLE") == 0 &&
			  pg_strcasecmp(prev2_wd, "LOCK") == 0))
		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, NULL);

	/* For the following, handle the case of a single table only for now */

	/* Complete LOCK [TABLE] <table> with "IN" */
	else if ((pg_strcasecmp(prev2_wd, "LOCK") == 0 &&
			  pg_strcasecmp(prev_wd, "TABLE")) ||
			 (pg_strcasecmp(prev2_wd, "TABLE") == 0 &&
			  pg_strcasecmp(prev3_wd, "LOCK") == 0))
		COMPLETE_WITH_CONST("IN");

	/* Complete LOCK [TABLE] <table> IN with a lock mode */
	else if (pg_strcasecmp(prev_wd, "IN") == 0 &&
			 (pg_strcasecmp(prev3_wd, "LOCK") == 0 ||
			  (pg_strcasecmp(prev3_wd, "TABLE") == 0 &&
			   pg_strcasecmp(prev4_wd, "LOCK") == 0)))
	{
		static const char *const lock_modes[] =
		{"ACCESS SHARE MODE",
			"ROW SHARE MODE", "ROW EXCLUSIVE MODE",
			"SHARE UPDATE EXCLUSIVE MODE", "SHARE MODE",
			"SHARE ROW EXCLUSIVE MODE",
		"EXCLUSIVE MODE", "ACCESS EXCLUSIVE MODE", NULL};

		COMPLETE_WITH_LIST(lock_modes);
	}

/* NOTIFY */
	else if (pg_strcasecmp(prev_wd, "NOTIFY") == 0)
		COMPLETE_WITH_QUERY("SELECT pg_catalog.quote_ident(relname) FROM pg_catalog.pg_listener WHERE substring(pg_catalog.quote_ident(relname),1,%d)='%s'");

/* OWNER TO  - complete with available roles*/
	else if (pg_strcasecmp(prev2_wd, "OWNER") == 0 &&
			 pg_strcasecmp(prev_wd, "TO") == 0)
		COMPLETE_WITH_QUERY(Query_for_list_of_roles);

/* ORDER BY */
	else if (pg_strcasecmp(prev3_wd, "FROM") == 0 &&
			 pg_strcasecmp(prev_wd, "ORDER") == 0)
		COMPLETE_WITH_CONST("BY");
	else if (pg_strcasecmp(prev4_wd, "FROM") == 0 &&
			 pg_strcasecmp(prev2_wd, "ORDER") == 0 &&
			 pg_strcasecmp(prev_wd, "BY") == 0)
		COMPLETE_WITH_ATTR(prev3_wd);

/* PREPARE xx AS */
	else if (pg_strcasecmp(prev_wd, "AS") == 0 &&
			 pg_strcasecmp(prev3_wd, "PREPARE") == 0)
	{
		static const char *const list_PREPARE[] =
		{"SELECT", "UPDATE", "INSERT", "DELETE", NULL};

		COMPLETE_WITH_LIST(list_PREPARE);
	}


/* REINDEX */
	else if (pg_strcasecmp(prev_wd, "REINDEX") == 0)
	{
		static const char *const list_REINDEX[] =
		{"TABLE", "INDEX", "SYSTEM", "DATABASE", NULL};

		COMPLETE_WITH_LIST(list_REINDEX);
	}
	else if (pg_strcasecmp(prev2_wd, "REINDEX") == 0)
	{
		if (pg_strcasecmp(prev_wd, "TABLE") == 0)
			COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, NULL);
		else if (pg_strcasecmp(prev_wd, "INDEX") == 0)
			COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_indexes, NULL);
		else if (pg_strcasecmp(prev_wd, "SYSTEM") == 0 ||
				 pg_strcasecmp(prev_wd, "DATABASE") == 0)
			COMPLETE_WITH_QUERY(Query_for_list_of_databases);
	}

/* SELECT */
	/* naah . . . */

/* SET, RESET, SHOW */
	/* Complete with a variable name */
	else if ((pg_strcasecmp(prev_wd, "SET") == 0 &&
			  pg_strcasecmp(prev3_wd, "UPDATE") != 0) ||
			 pg_strcasecmp(prev_wd, "RESET") == 0)
		COMPLETE_WITH_QUERY(Query_for_list_of_set_vars);
	else if (pg_strcasecmp(prev_wd, "SHOW") == 0)
		COMPLETE_WITH_QUERY(Query_for_list_of_show_vars);
	/* Complete "SET TRANSACTION" */
	else if ((pg_strcasecmp(prev2_wd, "SET") == 0 &&
			  pg_strcasecmp(prev_wd, "TRANSACTION") == 0)
			 || (pg_strcasecmp(prev2_wd, "START") == 0
				 && pg_strcasecmp(prev_wd, "TRANSACTION") == 0)
			 || (pg_strcasecmp(prev2_wd, "BEGIN") == 0
				 && pg_strcasecmp(prev_wd, "WORK") == 0)
			 || (pg_strcasecmp(prev2_wd, "BEGIN") == 0
				 && pg_strcasecmp(prev_wd, "TRANSACTION") == 0)
			 || (pg_strcasecmp(prev4_wd, "SESSION") == 0
				 && pg_strcasecmp(prev3_wd, "CHARACTERISTICS") == 0
				 && pg_strcasecmp(prev2_wd, "AS") == 0
				 && pg_strcasecmp(prev_wd, "TRANSACTION") == 0))
	{
		static const char *const my_list[] =
		{"ISOLATION LEVEL", "READ", NULL};

		COMPLETE_WITH_LIST(my_list);
	}
	else if ((pg_strcasecmp(prev3_wd, "SET") == 0
			  || pg_strcasecmp(prev3_wd, "BEGIN") == 0
			  || pg_strcasecmp(prev3_wd, "START") == 0
			  || (pg_strcasecmp(prev4_wd, "CHARACTERISTICS") == 0
				  && pg_strcasecmp(prev3_wd, "AS") == 0))
			 && (pg_strcasecmp(prev2_wd, "TRANSACTION") == 0
				 || pg_strcasecmp(prev2_wd, "WORK") == 0)
			 && pg_strcasecmp(prev_wd, "ISOLATION") == 0)
		COMPLETE_WITH_CONST("LEVEL");
	else if ((pg_strcasecmp(prev4_wd, "SET") == 0
			  || pg_strcasecmp(prev4_wd, "BEGIN") == 0
			  || pg_strcasecmp(prev4_wd, "START") == 0
			  || pg_strcasecmp(prev4_wd, "AS") == 0)
			 && (pg_strcasecmp(prev3_wd, "TRANSACTION") == 0
				 || pg_strcasecmp(prev3_wd, "WORK") == 0)
			 && pg_strcasecmp(prev2_wd, "ISOLATION") == 0
			 && pg_strcasecmp(prev_wd, "LEVEL") == 0)
	{
		static const char *const my_list[] =
		{"READ", "REPEATABLE", "SERIALIZABLE", NULL};

		COMPLETE_WITH_LIST(my_list);
	}
	else if ((pg_strcasecmp(prev4_wd, "TRANSACTION") == 0 ||
			  pg_strcasecmp(prev4_wd, "WORK") == 0) &&
			 pg_strcasecmp(prev3_wd, "ISOLATION") == 0 &&
			 pg_strcasecmp(prev2_wd, "LEVEL") == 0 &&
			 pg_strcasecmp(prev_wd, "READ") == 0)
	{
		static const char *const my_list[] =
		{"UNCOMMITTED", "COMMITTED", NULL};

		COMPLETE_WITH_LIST(my_list);
	}
	else if ((pg_strcasecmp(prev4_wd, "TRANSACTION") == 0 ||
			  pg_strcasecmp(prev4_wd, "WORK") == 0) &&
			 pg_strcasecmp(prev3_wd, "ISOLATION") == 0 &&
			 pg_strcasecmp(prev2_wd, "LEVEL") == 0 &&
			 pg_strcasecmp(prev_wd, "REPEATABLE") == 0)
		COMPLETE_WITH_CONST("READ");
	else if ((pg_strcasecmp(prev3_wd, "SET") == 0 ||
			  pg_strcasecmp(prev3_wd, "BEGIN") == 0 ||
			  pg_strcasecmp(prev3_wd, "START") == 0 ||
			  pg_strcasecmp(prev3_wd, "AS") == 0) &&
			 (pg_strcasecmp(prev2_wd, "TRANSACTION") == 0 ||
			  pg_strcasecmp(prev2_wd, "WORK") == 0) &&
			 pg_strcasecmp(prev_wd, "READ") == 0)
	{
		static const char *const my_list[] =
		{"ONLY", "WRITE", NULL};

		COMPLETE_WITH_LIST(my_list);
	}
	/* Complete SET CONSTRAINTS <foo> with DEFERRED|IMMEDIATE */
	else if (pg_strcasecmp(prev3_wd, "SET") == 0 &&
			 pg_strcasecmp(prev2_wd, "CONSTRAINTS") == 0)
	{
		static const char *const constraint_list[] =
		{"DEFERRED", "IMMEDIATE", NULL};

		COMPLETE_WITH_LIST(constraint_list);
	}
	/* Complete SET ROLE */
	else if (pg_strcasecmp(prev2_wd, "SET") == 0 && 
			 pg_strcasecmp(prev_wd, "ROLE") == 0)
		COMPLETE_WITH_QUERY(Query_for_list_of_roles);
	/* Complete SET SESSION with AUTHORIZATION or CHARACTERISTICS... */
	else if (pg_strcasecmp(prev2_wd, "SET") == 0 &&
			 pg_strcasecmp(prev_wd, "SESSION") == 0)
	{
		static const char *const my_list[] =
		{"AUTHORIZATION", "CHARACTERISTICS AS TRANSACTION", NULL};

		COMPLETE_WITH_LIST(my_list);
	}
	/* Complete SET SESSION AUTHORIZATION with username */
	else if (pg_strcasecmp(prev3_wd, "SET") == 0
			 && pg_strcasecmp(prev2_wd, "SESSION") == 0
			 && pg_strcasecmp(prev_wd, "AUTHORIZATION") == 0)
		COMPLETE_WITH_QUERY(Query_for_list_of_roles);
	/* Complete SET <var> with "TO" */
	else if (pg_strcasecmp(prev2_wd, "SET") == 0 &&
			 pg_strcasecmp(prev4_wd, "UPDATE") != 0 &&
			 pg_strcasecmp(prev_wd, "TABLESPACE") != 0 &&
			 pg_strcasecmp(prev4_wd, "DOMAIN") != 0)
		COMPLETE_WITH_CONST("TO");
	/* Suggest possible variable values */
	else if (pg_strcasecmp(prev3_wd, "SET") == 0 &&
		(pg_strcasecmp(prev_wd, "TO") == 0 || strcmp(prev_wd, "=") == 0))
	{
		if (pg_strcasecmp(prev2_wd, "DateStyle") == 0)
		{
			static const char *const my_list[] =
			{"ISO", "SQL", "Postgres", "German",
			 "YMD", "DMY", "MDY",
			 "US", "European", "NonEuropean",
			"DEFAULT", NULL};

			COMPLETE_WITH_LIST(my_list);
		}
		else if (pg_strcasecmp(prev2_wd, "GEQO") == 0)
		{
			static const char *const my_list[] =
			{"ON", "OFF", "DEFAULT", NULL};

			COMPLETE_WITH_LIST(my_list);
		}
		else
		{
			static const char *const my_list[] =
			{"DEFAULT", NULL};

			COMPLETE_WITH_LIST(my_list);
		}
	}

/* START TRANSACTION */
	else if (pg_strcasecmp(prev_wd, "START") == 0)
		COMPLETE_WITH_CONST("TRANSACTION");

/* TRUNCATE */
	else if (pg_strcasecmp(prev_wd, "TRUNCATE") == 0)
		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, NULL);

/* UNLISTEN */
	else if (pg_strcasecmp(prev_wd, "UNLISTEN") == 0)
		COMPLETE_WITH_QUERY("SELECT pg_catalog.quote_ident(relname) FROM pg_catalog.pg_listener WHERE substring(pg_catalog.quote_ident(relname),1,%d)='%s' UNION SELECT '*'");

/* UPDATE */
	/* If prev. word is UPDATE suggest a list of tables */
	else if (pg_strcasecmp(prev_wd, "UPDATE") == 0)
		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, NULL);
	/* Complete UPDATE <table> with "SET" */
	else if (pg_strcasecmp(prev2_wd, "UPDATE") == 0)
		COMPLETE_WITH_CONST("SET");

	/*
	 * If the previous word is SET (and it wasn't caught above as the
	 * _first_ word) the word before it was (hopefully) a table name and
	 * we'll now make a list of attributes.
	 */
	else if (pg_strcasecmp(prev_wd, "SET") == 0)
		COMPLETE_WITH_ATTR(prev2_wd);

/* UPDATE xx SET yy = */
	else if (pg_strcasecmp(prev2_wd, "SET") == 0 &&
					 pg_strcasecmp(prev4_wd, "UPDATE") == 0)
		COMPLETE_WITH_CONST("=");

/*
 * VACUUM [ FULL | FREEZE ] [ VERBOSE ] [ table ]
 * VACUUM [ FULL | FREEZE ] [ VERBOSE ] ANALYZE [ table [ (column [, ...] ) ] ]
 */
	else if (pg_strcasecmp(prev_wd, "VACUUM") == 0)
		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables,
								   " UNION SELECT 'FULL'"
								   " UNION SELECT 'FREEZE'"
								   " UNION SELECT 'ANALYZE'"
								   " UNION SELECT 'VERBOSE'");
	else if (pg_strcasecmp(prev2_wd, "VACUUM") == 0 &&
			 (pg_strcasecmp(prev_wd, "FULL") == 0 ||
			  pg_strcasecmp(prev_wd, "FREEZE") == 0))
		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables,
								   " UNION SELECT 'ANALYZE'"
								   " UNION SELECT 'VERBOSE'");
	else if (pg_strcasecmp(prev3_wd, "VACUUM") == 0 &&
			 pg_strcasecmp(prev_wd, "ANALYZE") == 0 &&
			 (pg_strcasecmp(prev2_wd, "FULL") == 0 ||
			  pg_strcasecmp(prev2_wd, "FREEZE") == 0))
		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables,
								   " UNION SELECT 'VERBOSE'");
	else if (pg_strcasecmp(prev3_wd, "VACUUM") == 0 &&
			 pg_strcasecmp(prev_wd, "VERBOSE") == 0 &&
			 (pg_strcasecmp(prev2_wd, "FULL") == 0 ||
			  pg_strcasecmp(prev2_wd, "FREEZE") == 0))
		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables,
								   " UNION SELECT 'ANALYZE'");
	else if (pg_strcasecmp(prev2_wd, "VACUUM") == 0 &&
			 pg_strcasecmp(prev_wd, "VERBOSE") == 0)
		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables,
								   " UNION SELECT 'ANALYZE'");
	else if (pg_strcasecmp(prev2_wd, "VACUUM") == 0 &&
			 pg_strcasecmp(prev_wd, "ANALYZE") == 0)
		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables,
								   " UNION SELECT 'VERBOSE'");
	else if ((pg_strcasecmp(prev_wd, "ANALYZE") == 0 &&
			  pg_strcasecmp(prev2_wd, "VERBOSE") == 0) ||
			 (pg_strcasecmp(prev_wd, "VERBOSE") == 0 &&
			  pg_strcasecmp(prev2_wd, "ANALYZE") == 0))
		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, NULL);

/* ANALYZE */
	/* If the previous word is ANALYZE, produce list of tables */
	else if (pg_strcasecmp(prev_wd, "ANALYZE") == 0)
		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, NULL);

/* WHERE */
	/* Simple case of the word before the where being the table name */
	else if (pg_strcasecmp(prev_wd, "WHERE") == 0)
		COMPLETE_WITH_ATTR(prev2_wd);

/* ... FROM ... */
/* TODO: also include SRF ? */
	else if (pg_strcasecmp(prev_wd, "FROM") == 0 &&
			 pg_strcasecmp(prev3_wd, "COPY") != 0 &&
			 pg_strcasecmp(prev3_wd, "\\copy") != 0)
		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tsv, NULL);


/* Backslash commands */
/* TODO:  \dc \dd \dl */
	else if (strcmp(prev_wd, "\\connect") == 0 || strcmp(prev_wd, "\\c") == 0)
		COMPLETE_WITH_QUERY(Query_for_list_of_databases);
	else if (strcmp(prev_wd, "\\d") == 0 || strcmp(prev_wd, "\\d+") == 0)
		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tisv, NULL);
	else if (strcmp(prev_wd, "\\da") == 0)
		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_aggregates, NULL);
	else if (strcmp(prev_wd, "\\db") == 0)
		COMPLETE_WITH_QUERY(Query_for_list_of_tablespaces);
	else if (strcmp(prev_wd, "\\dD") == 0)
		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_domains, NULL);
	else if (strcmp(prev_wd, "\\df") == 0 || strcmp(prev_wd, "\\df+") == 0)
		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_functions, NULL);
	else if (strcmp(prev_wd, "\\di") == 0 || strcmp(prev_wd, "\\di+") == 0)
		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_indexes, NULL);
	else if (strcmp(prev_wd, "\\dn") == 0)
		COMPLETE_WITH_QUERY(Query_for_list_of_schemas);
	else if (strcmp(prev_wd, "\\dp") == 0 || strcmp(prev_wd, "\\z") == 0)
		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tsv, NULL);
	else if (strcmp(prev_wd, "\\ds") == 0 || strcmp(prev_wd, "\\ds+") == 0)
		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_sequences, NULL);
	else if (strcmp(prev_wd, "\\dS") == 0 || strcmp(prev_wd, "\\dS+") == 0)
		COMPLETE_WITH_QUERY(Query_for_list_of_system_relations);
	else if (strcmp(prev_wd, "\\dt") == 0 || strcmp(prev_wd, "\\dt+") == 0)
		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, NULL);
	else if (strcmp(prev_wd, "\\dT") == 0 || strcmp(prev_wd, "\\dT+") == 0)
		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_datatypes, NULL);
	else if (strcmp(prev_wd, "\\du") == 0)
		COMPLETE_WITH_QUERY(Query_for_list_of_roles);
	else if (strcmp(prev_wd, "\\dv") == 0 || strcmp(prev_wd, "\\dv+") == 0)
		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_views, NULL);
	else if (strcmp(prev_wd, "\\encoding") == 0)
		COMPLETE_WITH_QUERY(Query_for_list_of_encodings);
	else if (strcmp(prev_wd, "\\h") == 0 || strcmp(prev_wd, "\\help") == 0)
		COMPLETE_WITH_LIST(sql_commands);
	else if (strcmp(prev_wd, "\\pset") == 0)
	{
		static const char *const my_list[] =
		{"format", "border", "expanded",
			"null", "fieldsep", "tuples_only", "title", "tableattr", "pager",
		"recordsep", NULL};

		COMPLETE_WITH_LIST(my_list);
	}
	else if (strcmp(prev_wd, "\\cd") == 0 ||
		 strcmp(prev_wd, "\\e") == 0 || strcmp(prev_wd, "\\edit") == 0 ||
			 strcmp(prev_wd, "\\g") == 0 ||
			 strcmp(prev_wd, "\\i") == 0 || strcmp(prev_wd, "\\include") == 0 ||
		  strcmp(prev_wd, "\\o") == 0 || strcmp(prev_wd, "\\out") == 0 ||
			 strcmp(prev_wd, "\\s") == 0 ||
		   strcmp(prev_wd, "\\w") == 0 || strcmp(prev_wd, "\\write") == 0
		)
		matches = completion_matches(text, filename_completion_function);


	/*
	 * Finally, we look through the list of "things", such as TABLE, INDEX
	 * and check if that was the previous word. If so, execute the query
	 * to get a list of them.
	 */
	else
	{
		int			i;

		for (i = 0; words_after_create[i].name; i++)
		{
			if (pg_strcasecmp(prev_wd, words_after_create[i].name) == 0)
			{
				if (words_after_create[i].query)
					COMPLETE_WITH_QUERY(words_after_create[i].query);
				else if (words_after_create[i].squery)
					COMPLETE_WITH_SCHEMA_QUERY(*words_after_create[i].squery,
											   NULL);
				break;
			}
		}
	}

	/*
	 * If we still don't have anything to match we have to fabricate some
	 * sort of default list. If we were to just return NULL, readline
	 * automatically attempts filename completion, and that's usually no
	 * good.
	 */
	if (matches == NULL)
	{
		COMPLETE_WITH_CONST("");
#ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
		rl_completion_append_character = '\0';
#endif
	}

	/* free storage */
	free(prev_wd);
	free(prev2_wd);
	free(prev3_wd);
	free(prev4_wd);
	free(prev5_wd);

	/* Return our Grand List O' Matches */
	return matches;
}



/* GENERATOR FUNCTIONS

   These functions do all the actual work of completing the input. They get
   passed the text so far and the count how many times they have been called so
   far with the same text.
   If you read the above carefully, you'll see that these don't get called
   directly but through the readline interface.
   The return value is expected to be the full completion of the text, going
   through a list each time, or NULL if there are no more matches. The string
   will be free()'d by readline, so you must run it through strdup() or
   something of that sort.
*/

/* This one gives you one from a list of things you can put after CREATE or DROP
   as defined above.
*/
static char *
create_command_generator(const char *text, int state)
{
	static int	list_index,
				string_length;
	const char *name;

	/* If this is the first time for this completion, init some values */
	if (state == 0)
	{
		list_index = 0;
		string_length = strlen(text);
	}

	/* find something that matches */
	while ((name = words_after_create[list_index++].name))
		if (pg_strncasecmp(name, text, string_length) == 0)
			return pg_strdup(name);

	/* if nothing matches, return NULL */
	return NULL;
}


/* The following two functions are wrappers for _complete_from_query */

static char *
complete_from_query(const char *text, int state)
{
	return _complete_from_query(0, text, state);
}

static char *
complete_from_schema_query(const char *text, int state)
{
	return _complete_from_query(1, text, state);
}


/* This creates a list of matching things, according to a query pointed to
   by completion_charp.
   The query can be one of two kinds:
   - A simple query which must contain a %d and a %s, which will be replaced
   by the string length of the text and the text itself. The query may also
   have another %s in it, which will be replaced by the value of
   completion_info_charp.
	 or:
   - A schema query used for completion of both schema and relation names;
   these are more complex and must contain in the following order:
	 %d %s %d %s %d %s %s %d %s
   where %d is the string length of the text and %s the text itself.

   It is assumed that strings should be escaped to become SQL literals
   (that is, what is in the query is actually ... '%s' ...)

   See top of file for examples of both kinds of query.
*/

static char *
_complete_from_query(int is_schema_query, const char *text, int state)
{
	static int	list_index,
				string_length;
	static PGresult *result = NULL;

	/*
	 * If this is the first time for this completion, we fetch a list of
	 * our "things" from the backend.
	 */
	if (state == 0)
	{
		PQExpBufferData query_buffer;
		char	   *e_text;
		char	   *e_info_charp;

		list_index = 0;
		string_length = strlen(text);

		/* Free any prior result */
		PQclear(result);
		result = NULL;

		/* Set up suitably-escaped copies of textual inputs */
		e_text = pg_malloc(string_length * 2 + 1);
		PQescapeString(e_text, text, string_length);

		if (completion_info_charp)
		{
			size_t		charp_len;

			charp_len = strlen(completion_info_charp);
			e_info_charp = pg_malloc(charp_len * 2 + 1);
			PQescapeString(e_info_charp, completion_info_charp,
						   charp_len);
		}
		else
			e_info_charp = NULL;

		initPQExpBuffer(&query_buffer);

		if (is_schema_query)
		{
			/* completion_squery gives us the pieces to assemble */
			const char *qualresult = completion_squery->qualresult;

			if (qualresult == NULL)
				qualresult = completion_squery->result;

			/* Get unqualified names matching the input-so-far */
			appendPQExpBuffer(&query_buffer, "SELECT %s FROM %s WHERE ",
							  completion_squery->result,
							  completion_squery->catname);
			if (completion_squery->selcondition)
				appendPQExpBuffer(&query_buffer, "%s AND ",
								  completion_squery->selcondition);
			appendPQExpBuffer(&query_buffer, "substring(%s,1,%d)='%s'",
							  completion_squery->result,
							  string_length, e_text);
			appendPQExpBuffer(&query_buffer, " AND %s",
							  completion_squery->viscondition);

			/*
			 * When fetching relation names, suppress system catalogs
			 * unless the input-so-far begins with "pg_".  This is a
			 * compromise between not offering system catalogs for
			 * completion at all, and having them swamp the result when
			 * the input is just "p".
			 */
			if (strcmp(completion_squery->catname,
					   "pg_catalog.pg_class c") == 0 &&
				strncmp(text, "pg_", 3) !=0)
			{
				appendPQExpBuffer(&query_buffer,
								" AND c.relnamespace <> (SELECT oid FROM"
				" pg_catalog.pg_namespace WHERE nspname = 'pg_catalog')");
			}

			/*
			 * Add in matching schema names, but only if there is more
			 * than one potential match among schema names.
			 */
			appendPQExpBuffer(&query_buffer, "\nUNION\n"
					   "SELECT pg_catalog.quote_ident(n.nspname) || '.' "
							  "FROM pg_catalog.pg_namespace n "
							  "WHERE substring(pg_catalog.quote_ident(n.nspname) || '.',1,%d)='%s'",
							  string_length, e_text);
			appendPQExpBuffer(&query_buffer,
							  " AND (SELECT pg_catalog.count(*)"
							  " FROM pg_catalog.pg_namespace"
							  " WHERE substring(pg_catalog.quote_ident(nspname) || '.',1,%d) ="
							  " substring('%s',1,pg_catalog.length(pg_catalog.quote_ident(nspname))+1)) > 1",
							  string_length, e_text);

			/*
			 * Add in matching qualified names, but only if there is
			 * exactly one schema matching the input-so-far.
			 */
			appendPQExpBuffer(&query_buffer, "\nUNION\n"
				 "SELECT pg_catalog.quote_ident(n.nspname) || '.' || %s "
							  "FROM %s, pg_catalog.pg_namespace n "
							  "WHERE %s = n.oid AND ",
							  qualresult,
							  completion_squery->catname,
							  completion_squery->namespace);
			if (completion_squery->selcondition)
				appendPQExpBuffer(&query_buffer, "%s AND ",
								  completion_squery->selcondition);
			appendPQExpBuffer(&query_buffer, "substring(pg_catalog.quote_ident(n.nspname) || '.' || %s,1,%d)='%s'",
							  qualresult,
							  string_length, e_text);

			/*
			 * This condition exploits the single-matching-schema rule to
			 * speed up the query
			 */
			appendPQExpBuffer(&query_buffer,
							  " AND substring(pg_catalog.quote_ident(n.nspname) || '.',1,%d) ="
							  " substring('%s',1,pg_catalog.length(pg_catalog.quote_ident(n.nspname))+1)",
							  string_length, e_text);
			appendPQExpBuffer(&query_buffer,
							  " AND (SELECT pg_catalog.count(*)"
							  " FROM pg_catalog.pg_namespace"
							  " WHERE substring(pg_catalog.quote_ident(nspname) || '.',1,%d) ="
							  " substring('%s',1,pg_catalog.length(pg_catalog.quote_ident(nspname))+1)) = 1",
							  string_length, e_text);

			/* If an addon query was provided, use it */
			if (completion_charp)
				appendPQExpBuffer(&query_buffer, "\n%s", completion_charp);
		}
		else
		{
			/* completion_charp is an sprintf-style format string */
			appendPQExpBuffer(&query_buffer, completion_charp,
							  string_length, e_text, e_info_charp);
		}

		/* Limit the number of records in the result */
		appendPQExpBuffer(&query_buffer, "\nLIMIT %d",
						  completion_max_records);

		result = exec_query(query_buffer.data);

		termPQExpBuffer(&query_buffer);
		free(e_text);
		if (e_info_charp)
			free(e_info_charp);
	}

	/* Find something that matches */
	if (result && PQresultStatus(result) == PGRES_TUPLES_OK)
	{
		const char *item;

		while (list_index < PQntuples(result) &&
			   (item = PQgetvalue(result, list_index++, 0)))
			if (pg_strncasecmp(text, item, string_length) == 0)
				return pg_strdup(item);
	}

	/* If nothing matches, free the db structure and return null */
	PQclear(result);
	result = NULL;
	return NULL;
}


/* This function returns in order one of a fixed, NULL pointer terminated list
   of strings (if matching). This can be used if there are only a fixed number
   SQL words that can appear at certain spot.
*/
static char *
complete_from_list(const char *text, int state)
{
	static int	string_length,
				list_index,
				matches;
	static bool casesensitive;
	const char *item;

	/* need to have a list */
	psql_assert(completion_charpp);

	/* Initialization */
	if (state == 0)
	{
		list_index = 0;
		string_length = strlen(text);
		casesensitive = true;
		matches = 0;
	}

	while ((item = completion_charpp[list_index++]))
	{
		/* First pass is case sensitive */
		if (casesensitive && strncmp(text, item, string_length) == 0)
		{
			matches++;
			return pg_strdup(item);
		}

		/* Second pass is case insensitive, don't bother counting matches */
		if (!casesensitive && pg_strncasecmp(text, item, string_length) == 0)
			return pg_strdup(item);
	}

	/*
	 * No matches found. If we're not case insensitive already, lets
	 * switch to being case insensitive and try again
	 */
	if (casesensitive && matches == 0)
	{
		casesensitive = false;
		list_index = 0;
		state++;
		return (complete_from_list(text, state));
	}

	/* If no more matches, return null. */
	return NULL;
}


/* This function returns one fixed string the first time even if it doesn't
   match what's there, and nothing the second time. This should be used if there
   is only one possibility that can appear at a certain spot, so misspellings
   will be overwritten.
   The string to be passed must be in completion_charp.
*/
static char *
complete_from_const(const char *text, int state)
{
	(void) text;				/* We don't care about what was entered
								 * already. */

	psql_assert(completion_charp);
	if (state == 0)
		return pg_strdup(completion_charp);
	else
		return NULL;
}



/* HELPER FUNCTIONS */


/*
 * Execute a query and report any errors. This should be the preferred way of
 * talking to the database in this file.
 */
static PGresult *
exec_query(const char *query)
{
	PGresult   *result;

	if (query == NULL || !pset.db || PQstatus(pset.db) != CONNECTION_OK)
		return NULL;

	result = PQexec(pset.db, query);

	if (result != NULL && PQresultStatus(result) != PGRES_TUPLES_OK)
	{
#if 0
		psql_error("tab completion: %s failed - %s\n",
				   query, PQresStatus(PQresultStatus(result)));
#endif
		PQclear(result);
		result = NULL;
	}

	return result;
}



/*
 * Return the word (space delimited) before point. Set skip > 0 to
 * skip that many words; e.g. skip=1 finds the word before the
 * previous one. Return value is NULL or a malloc'ed string.
 */
static char *
previous_word(int point, int skip)
{
	int			i,
				start = 0,
				end = -1,
				inquotes = 0;
	char	   *s;

	while (skip-- >= 0)
	{
		/* first we look for a space before the current word */
		for (i = point; i >= 0; i--)
			if (rl_line_buffer[i] == ' ')
				break;

		/* now find the first non-space which then constitutes the end */
		for (; i >= 0; i--)
			if (rl_line_buffer[i] != ' ')
			{
				end = i;
				break;
			}

		/*
		 * If no end found we return null, because there is no word before
		 * the point
		 */
		if (end == -1)
			return NULL;

		/*
		 * Otherwise we now look for the start. The start is either the
		 * last character before any space going backwards from the end,
		 * or it's simply character 0
		 */
		for (start = end; start > 0; start--)
		{
			if (rl_line_buffer[start] == '"')
				inquotes = !inquotes;
			if ((rl_line_buffer[start - 1] == ' ') && inquotes == 0)
				break;
		}

		point = start;
	}

	/* make a copy */
	s = pg_malloc(end - start + 2);

	strncpy(s, &rl_line_buffer[start], end - start + 1);
	s[end - start + 1] = '\0';

	return s;
}



#if 0

/*
 * Surround a string with single quotes. This works for both SQL and
 * psql internal. Currently disabled because it is reported not to
 * cooperate with certain versions of readline.
 */
static char *
quote_file_name(char *text, int match_type, char *quote_pointer)
{
	char	   *s;
	size_t		length;

	(void) quote_pointer;		/* not used */

	length = strlen(text) +(match_type == SINGLE_MATCH ? 3 : 2);
	s = pg_malloc(length);
	s[0] = '\'';
	strcpy(s + 1, text);
	if (match_type == SINGLE_MATCH)
		s[length - 2] = '\'';
	s[length - 1] = '\0';
	return s;
}



static char *
dequote_file_name(char *text, char quote_char)
{
	char	   *s;
	size_t		length;

	if (!quote_char)
		return pg_strdup(text);

	length = strlen(text);
	s = pg_malloc(length - 2 + 1);
	strncpy(s, text +1, length - 2);
	s[length] = '\0';

	return s;
}
#endif   /* 0 */

#endif   /* USE_READLINE */