1 /*
2 * psql - the PostgreSQL interactive terminal
3 *
4 * Copyright (c) 2000-2021, PostgreSQL Global Development Group
5 *
6 * src/bin/psql/tab-complete.c
7 */
8
9 /*----------------------------------------------------------------------
10 * This file implements a somewhat more sophisticated readline "TAB
11 * completion" in psql. It is not intended to be AI, to replace
12 * learning SQL, or to relieve you from thinking about what you're
13 * doing. Also it does not always give you all the syntactically legal
14 * completions, only those that are the most common or the ones that
15 * the programmer felt most like implementing.
16 *
17 * CAVEAT: Tab completion causes queries to be sent to the backend.
18 * The number of tuples returned gets limited, in most default
19 * installations to 1000, but if you still don't like this prospect,
20 * you can turn off tab completion in your ~/.inputrc (or else
21 * ${INPUTRC}) file so:
22 *
23 * $if psql
24 * set disable-completion on
25 * $endif
26 *
27 * See `man 3 readline' or `info readline' for the full details.
28 *
29 * BUGS:
30 * - Quotes, parentheses, and other funny characters are not handled
31 * all that gracefully.
32 *----------------------------------------------------------------------
33 */
34
35 #include "postgres_fe.h"
36
37 #include "input.h"
38 #include "tab-complete.h"
39
40 /* If we don't have this, we might as well forget about the whole thing: */
41 #ifdef USE_READLINE
42
43 #include <ctype.h>
44 #include <sys/stat.h>
45
46 #include "catalog/pg_am_d.h"
47 #include "catalog/pg_class_d.h"
48 #include "common.h"
49 #include "libpq-fe.h"
50 #include "pqexpbuffer.h"
51 #include "settings.h"
52 #include "stringutils.h"
53
54 /*
55 * Ancient versions of libedit provide filename_completion_function()
56 * instead of rl_filename_completion_function(). Likewise for
57 * [rl_]completion_matches().
58 */
59 #ifndef HAVE_RL_FILENAME_COMPLETION_FUNCTION
60 #define rl_filename_completion_function filename_completion_function
61 #endif
62
63 #ifndef HAVE_RL_COMPLETION_MATCHES
64 #define rl_completion_matches completion_matches
65 #endif
66
67 /*
68 * Currently we assume that rl_filename_dequoting_function exists if
69 * rl_filename_quoting_function does. If that proves not to be the case,
70 * we'd need to test for the former, or possibly both, in configure.
71 */
72 #ifdef HAVE_RL_FILENAME_QUOTING_FUNCTION
73 #define USE_FILENAME_QUOTING_FUNCTIONS 1
74 #endif
75
76 /* word break characters */
77 #define WORD_BREAKS "\t\n@$><=;|&{() "
78
79 /*
80 * Since readline doesn't let us pass any state through to the tab completion
81 * callback, we have to use this global variable to let get_previous_words()
82 * get at the previous lines of the current command. Ick.
83 */
84 PQExpBuffer tab_completion_query_buf = NULL;
85
86 /*
87 * In some situations, the query to find out what names are available to
88 * complete with must vary depending on server version. We handle this by
89 * storing a list of queries, each tagged with the minimum server version
90 * it will work for. Each list must be stored in descending server version
91 * order, so that the first satisfactory query is the one to use.
92 *
93 * When the query string is otherwise constant, an array of VersionedQuery
94 * suffices. Terminate the array with an entry having min_server_version = 0.
95 * That entry's query string can be a query that works in all supported older
96 * server versions, or NULL to give up and do no completion.
97 */
98 typedef struct VersionedQuery
99 {
100 int min_server_version;
101 const char *query;
102 } VersionedQuery;
103
104 /*
105 * This struct is used to define "schema queries", which are custom-built
106 * to obtain possibly-schema-qualified names of database objects. There is
107 * enough similarity in the structure that we don't want to repeat it each
108 * time. So we put the components of each query into this struct and
109 * assemble them with the common boilerplate in _complete_from_query().
110 *
111 * As with VersionedQuery, we can use an array of these if the query details
112 * must vary across versions.
113 */
114 typedef struct SchemaQuery
115 {
116 /*
117 * If not zero, minimum server version this struct applies to. If not
118 * zero, there should be a following struct with a smaller minimum server
119 * version; use catname == NULL in the last entry if we should do nothing.
120 */
121 int min_server_version;
122
123 /*
124 * Name of catalog or catalogs to be queried, with alias, eg.
125 * "pg_catalog.pg_class c". Note that "pg_namespace n" will be added.
126 */
127 const char *catname;
128
129 /*
130 * Selection condition --- only rows meeting this condition are candidates
131 * to display. If catname mentions multiple tables, include the necessary
132 * join condition here. For example, this might look like "c.relkind = "
133 * CppAsString2(RELKIND_RELATION). Write NULL (not an empty string) if
134 * not needed.
135 */
136 const char *selcondition;
137
138 /*
139 * Visibility condition --- which rows are visible without schema
140 * qualification? For example, "pg_catalog.pg_table_is_visible(c.oid)".
141 */
142 const char *viscondition;
143
144 /*
145 * Namespace --- name of field to join to pg_namespace.oid. For example,
146 * "c.relnamespace".
147 */
148 const char *namespace;
149
150 /*
151 * Result --- the appropriately-quoted name to return, in the case of an
152 * unqualified name. For example, "pg_catalog.quote_ident(c.relname)".
153 */
154 const char *result;
155
156 /*
157 * In some cases a different result must be used for qualified names.
158 * Enter that here, or write NULL if result can be used.
159 */
160 const char *qualresult;
161 } SchemaQuery;
162
163
164 /* Store maximum number of records we want from database queries
165 * (implemented via SELECT ... LIMIT xx).
166 */
167 static int completion_max_records;
168
169 /*
170 * Communication variables set by psql_completion (mostly in COMPLETE_WITH_FOO
171 * macros) and then used by the completion callback functions. Ugly but there
172 * is no better way.
173 */
174 static char completion_last_char; /* last char of input word */
175 static const char *completion_charp; /* to pass a string */
176 static const char *const *completion_charpp; /* to pass a list of strings */
177 static const char *completion_info_charp; /* to pass a second string */
178 static const char *completion_info_charp2; /* to pass a third string */
179 static const VersionedQuery *completion_vquery; /* to pass a VersionedQuery */
180 static const SchemaQuery *completion_squery; /* to pass a SchemaQuery */
181 static bool completion_case_sensitive; /* completion is case sensitive */
182 static bool completion_force_quote; /* true to force-quote filenames */
183
184 /*
185 * A few macros to ease typing. You can use these to complete the given
186 * string with
187 * 1) The results from a query you pass it. (Perhaps one of those below?)
188 * We support both simple and versioned queries.
189 * 2) The results from a schema query you pass it.
190 * We support both simple and versioned schema queries.
191 * 3) The items from a null-pointer-terminated list (with or without
192 * case-sensitive comparison); if the list is constant you can build it
193 * with COMPLETE_WITH() or COMPLETE_WITH_CS().
194 * 4) The list of attributes of the given table (possibly schema-qualified).
195 * 5) The list of arguments to the given function (possibly schema-qualified).
196 */
197 #define COMPLETE_WITH_QUERY(query) \
198 do { \
199 completion_charp = query; \
200 matches = rl_completion_matches(text, complete_from_query); \
201 } while (0)
202
203 #define COMPLETE_WITH_VERSIONED_QUERY(query) \
204 do { \
205 completion_vquery = query; \
206 matches = rl_completion_matches(text, complete_from_versioned_query); \
207 } while (0)
208
209 #define COMPLETE_WITH_SCHEMA_QUERY(query, addon) \
210 do { \
211 completion_squery = &(query); \
212 completion_charp = addon; \
213 matches = rl_completion_matches(text, complete_from_schema_query); \
214 } while (0)
215
216 #define COMPLETE_WITH_VERSIONED_SCHEMA_QUERY(query, addon) \
217 do { \
218 completion_squery = query; \
219 completion_vquery = addon; \
220 matches = rl_completion_matches(text, complete_from_versioned_schema_query); \
221 } while (0)
222
223 /*
224 * Caution: COMPLETE_WITH_CONST is not for general-purpose use; you probably
225 * want COMPLETE_WITH() with one element, instead.
226 */
227 #define COMPLETE_WITH_CONST(cs, con) \
228 do { \
229 completion_case_sensitive = (cs); \
230 completion_charp = (con); \
231 matches = rl_completion_matches(text, complete_from_const); \
232 } while (0)
233
234 #define COMPLETE_WITH_LIST_INT(cs, list) \
235 do { \
236 completion_case_sensitive = (cs); \
237 completion_charpp = (list); \
238 matches = rl_completion_matches(text, complete_from_list); \
239 } while (0)
240
241 #define COMPLETE_WITH_LIST(list) COMPLETE_WITH_LIST_INT(false, list)
242 #define COMPLETE_WITH_LIST_CS(list) COMPLETE_WITH_LIST_INT(true, list)
243
244 #define COMPLETE_WITH(...) \
245 do { \
246 static const char *const list[] = { __VA_ARGS__, NULL }; \
247 COMPLETE_WITH_LIST(list); \
248 } while (0)
249
250 #define COMPLETE_WITH_CS(...) \
251 do { \
252 static const char *const list[] = { __VA_ARGS__, NULL }; \
253 COMPLETE_WITH_LIST_CS(list); \
254 } while (0)
255
256 #define COMPLETE_WITH_ATTR(relation, addon) \
257 do { \
258 char *_completion_schema; \
259 char *_completion_table; \
260 \
261 _completion_schema = strtokx(relation, " \t\n\r", ".", "\"", 0, \
262 false, false, pset.encoding); \
263 (void) strtokx(NULL, " \t\n\r", ".", "\"", 0, \
264 false, false, pset.encoding); \
265 _completion_table = strtokx(NULL, " \t\n\r", ".", "\"", 0, \
266 false, false, pset.encoding); \
267 if (_completion_table == NULL) \
268 { \
269 completion_charp = Query_for_list_of_attributes addon; \
270 completion_info_charp = relation; \
271 } \
272 else \
273 { \
274 completion_charp = Query_for_list_of_attributes_with_schema addon; \
275 completion_info_charp = _completion_table; \
276 completion_info_charp2 = _completion_schema; \
277 } \
278 matches = rl_completion_matches(text, complete_from_query); \
279 } while (0)
280
281 #define COMPLETE_WITH_ENUM_VALUE(type) \
282 do { \
283 char *_completion_schema; \
284 char *_completion_type; \
285 \
286 _completion_schema = strtokx(type, " \t\n\r", ".", "\"", 0, \
287 false, false, pset.encoding); \
288 (void) strtokx(NULL, " \t\n\r", ".", "\"", 0, \
289 false, false, pset.encoding); \
290 _completion_type = strtokx(NULL, " \t\n\r", ".", "\"", 0, \
291 false, false, pset.encoding); \
292 if (_completion_type == NULL)\
293 { \
294 completion_charp = Query_for_list_of_enum_values; \
295 completion_info_charp = type; \
296 } \
297 else \
298 { \
299 completion_charp = Query_for_list_of_enum_values_with_schema; \
300 completion_info_charp = _completion_type; \
301 completion_info_charp2 = _completion_schema; \
302 } \
303 matches = rl_completion_matches(text, complete_from_query); \
304 } while (0)
305
306 #define COMPLETE_WITH_FUNCTION_ARG(function) \
307 do { \
308 char *_completion_schema; \
309 char *_completion_function; \
310 \
311 _completion_schema = strtokx(function, " \t\n\r", ".", "\"", 0, \
312 false, false, pset.encoding); \
313 (void) strtokx(NULL, " \t\n\r", ".", "\"", 0, \
314 false, false, pset.encoding); \
315 _completion_function = strtokx(NULL, " \t\n\r", ".", "\"", 0, \
316 false, false, pset.encoding); \
317 if (_completion_function == NULL) \
318 { \
319 completion_charp = Query_for_list_of_arguments; \
320 completion_info_charp = function; \
321 } \
322 else \
323 { \
324 completion_charp = Query_for_list_of_arguments_with_schema; \
325 completion_info_charp = _completion_function; \
326 completion_info_charp2 = _completion_schema; \
327 } \
328 matches = rl_completion_matches(text, complete_from_query); \
329 } while (0)
330
331 /*
332 * Assembly instructions for schema queries
333 *
334 * Note that toast tables are not included in those queries to avoid
335 * unnecessary bloat in the completions generated.
336 */
337
338 static const SchemaQuery Query_for_list_of_aggregates[] = {
339 {
340 .min_server_version = 110000,
341 .catname = "pg_catalog.pg_proc p",
342 .selcondition = "p.prokind = 'a'",
343 .viscondition = "pg_catalog.pg_function_is_visible(p.oid)",
344 .namespace = "p.pronamespace",
345 .result = "pg_catalog.quote_ident(p.proname)",
346 },
347 {
348 .catname = "pg_catalog.pg_proc p",
349 .selcondition = "p.proisagg",
350 .viscondition = "pg_catalog.pg_function_is_visible(p.oid)",
351 .namespace = "p.pronamespace",
352 .result = "pg_catalog.quote_ident(p.proname)",
353 }
354 };
355
356 static const SchemaQuery Query_for_list_of_datatypes = {
357 .catname = "pg_catalog.pg_type t",
358 /* selcondition --- ignore table rowtypes and array types */
359 .selcondition = "(t.typrelid = 0 "
360 " OR (SELECT c.relkind = " CppAsString2(RELKIND_COMPOSITE_TYPE)
361 " FROM pg_catalog.pg_class c WHERE c.oid = t.typrelid)) "
362 "AND t.typname !~ '^_'",
363 .viscondition = "pg_catalog.pg_type_is_visible(t.oid)",
364 .namespace = "t.typnamespace",
365 .result = "pg_catalog.format_type(t.oid, NULL)",
366 .qualresult = "pg_catalog.quote_ident(t.typname)",
367 };
368
369 static const SchemaQuery Query_for_list_of_composite_datatypes = {
370 .catname = "pg_catalog.pg_type t",
371 /* selcondition --- only get composite types */
372 .selcondition = "(SELECT c.relkind = " CppAsString2(RELKIND_COMPOSITE_TYPE)
373 " FROM pg_catalog.pg_class c WHERE c.oid = t.typrelid) "
374 "AND t.typname !~ '^_'",
375 .viscondition = "pg_catalog.pg_type_is_visible(t.oid)",
376 .namespace = "t.typnamespace",
377 .result = "pg_catalog.format_type(t.oid, NULL)",
378 .qualresult = "pg_catalog.quote_ident(t.typname)",
379 };
380
381 static const SchemaQuery Query_for_list_of_domains = {
382 .catname = "pg_catalog.pg_type t",
383 .selcondition = "t.typtype = 'd'",
384 .viscondition = "pg_catalog.pg_type_is_visible(t.oid)",
385 .namespace = "t.typnamespace",
386 .result = "pg_catalog.quote_ident(t.typname)",
387 };
388
389 /* Note: this intentionally accepts aggregates as well as plain functions */
390 static const SchemaQuery Query_for_list_of_functions[] = {
391 {
392 .min_server_version = 110000,
393 .catname = "pg_catalog.pg_proc p",
394 .selcondition = "p.prokind != 'p'",
395 .viscondition = "pg_catalog.pg_function_is_visible(p.oid)",
396 .namespace = "p.pronamespace",
397 .result = "pg_catalog.quote_ident(p.proname)",
398 },
399 {
400 .catname = "pg_catalog.pg_proc p",
401 .viscondition = "pg_catalog.pg_function_is_visible(p.oid)",
402 .namespace = "p.pronamespace",
403 .result = "pg_catalog.quote_ident(p.proname)",
404 }
405 };
406
407 static const SchemaQuery Query_for_list_of_procedures[] = {
408 {
409 .min_server_version = 110000,
410 .catname = "pg_catalog.pg_proc p",
411 .selcondition = "p.prokind = 'p'",
412 .viscondition = "pg_catalog.pg_function_is_visible(p.oid)",
413 .namespace = "p.pronamespace",
414 .result = "pg_catalog.quote_ident(p.proname)",
415 },
416 {
417 /* not supported in older versions */
418 .catname = NULL,
419 }
420 };
421
422 static const SchemaQuery Query_for_list_of_routines = {
423 .catname = "pg_catalog.pg_proc p",
424 .viscondition = "pg_catalog.pg_function_is_visible(p.oid)",
425 .namespace = "p.pronamespace",
426 .result = "pg_catalog.quote_ident(p.proname)",
427 };
428
429 static const SchemaQuery Query_for_list_of_sequences = {
430 .catname = "pg_catalog.pg_class c",
431 .selcondition = "c.relkind IN (" CppAsString2(RELKIND_SEQUENCE) ")",
432 .viscondition = "pg_catalog.pg_table_is_visible(c.oid)",
433 .namespace = "c.relnamespace",
434 .result = "pg_catalog.quote_ident(c.relname)",
435 };
436
437 static const SchemaQuery Query_for_list_of_foreign_tables = {
438 .catname = "pg_catalog.pg_class c",
439 .selcondition = "c.relkind IN (" CppAsString2(RELKIND_FOREIGN_TABLE) ")",
440 .viscondition = "pg_catalog.pg_table_is_visible(c.oid)",
441 .namespace = "c.relnamespace",
442 .result = "pg_catalog.quote_ident(c.relname)",
443 };
444
445 static const SchemaQuery Query_for_list_of_tables = {
446 .catname = "pg_catalog.pg_class c",
447 .selcondition =
448 "c.relkind IN (" CppAsString2(RELKIND_RELATION) ", "
449 CppAsString2(RELKIND_PARTITIONED_TABLE) ")",
450 .viscondition = "pg_catalog.pg_table_is_visible(c.oid)",
451 .namespace = "c.relnamespace",
452 .result = "pg_catalog.quote_ident(c.relname)",
453 };
454
455 static const SchemaQuery Query_for_list_of_partitioned_tables = {
456 .catname = "pg_catalog.pg_class c",
457 .selcondition = "c.relkind IN (" CppAsString2(RELKIND_PARTITIONED_TABLE) ")",
458 .viscondition = "pg_catalog.pg_table_is_visible(c.oid)",
459 .namespace = "c.relnamespace",
460 .result = "pg_catalog.quote_ident(c.relname)",
461 };
462
463 static const SchemaQuery Query_for_list_of_views = {
464 .catname = "pg_catalog.pg_class c",
465 .selcondition = "c.relkind IN (" CppAsString2(RELKIND_VIEW) ")",
466 .viscondition = "pg_catalog.pg_table_is_visible(c.oid)",
467 .namespace = "c.relnamespace",
468 .result = "pg_catalog.quote_ident(c.relname)",
469 };
470
471 static const SchemaQuery Query_for_list_of_matviews = {
472 .catname = "pg_catalog.pg_class c",
473 .selcondition = "c.relkind IN (" CppAsString2(RELKIND_MATVIEW) ")",
474 .viscondition = "pg_catalog.pg_table_is_visible(c.oid)",
475 .namespace = "c.relnamespace",
476 .result = "pg_catalog.quote_ident(c.relname)",
477 };
478
479 static const SchemaQuery Query_for_list_of_indexes = {
480 .catname = "pg_catalog.pg_class c",
481 .selcondition =
482 "c.relkind IN (" CppAsString2(RELKIND_INDEX) ", "
483 CppAsString2(RELKIND_PARTITIONED_INDEX) ")",
484 .viscondition = "pg_catalog.pg_table_is_visible(c.oid)",
485 .namespace = "c.relnamespace",
486 .result = "pg_catalog.quote_ident(c.relname)",
487 };
488
489 static const SchemaQuery Query_for_list_of_partitioned_indexes = {
490 .catname = "pg_catalog.pg_class c",
491 .selcondition = "c.relkind = " CppAsString2(RELKIND_PARTITIONED_INDEX),
492 .viscondition = "pg_catalog.pg_table_is_visible(c.oid)",
493 .namespace = "c.relnamespace",
494 .result = "pg_catalog.quote_ident(c.relname)",
495 };
496
497
498 /* All relations */
499 static const SchemaQuery Query_for_list_of_relations = {
500 .catname = "pg_catalog.pg_class c",
501 .viscondition = "pg_catalog.pg_table_is_visible(c.oid)",
502 .namespace = "c.relnamespace",
503 .result = "pg_catalog.quote_ident(c.relname)",
504 };
505
506 /* partitioned relations */
507 static const SchemaQuery Query_for_list_of_partitioned_relations = {
508 .catname = "pg_catalog.pg_class c",
509 .selcondition = "c.relkind IN (" CppAsString2(RELKIND_PARTITIONED_TABLE)
510 ", " CppAsString2(RELKIND_PARTITIONED_INDEX) ")",
511 .viscondition = "pg_catalog.pg_table_is_visible(c.oid)",
512 .namespace = "c.relnamespace",
513 .result = "pg_catalog.quote_ident(c.relname)",
514 };
515
516 static const SchemaQuery Query_for_list_of_operator_families = {
517 .catname = "pg_catalog.pg_opfamily c",
518 .viscondition = "pg_catalog.pg_opfamily_is_visible(c.oid)",
519 .namespace = "c.opfnamespace",
520 .result = "pg_catalog.quote_ident(c.opfname)",
521 };
522
523 /* Relations supporting INSERT, UPDATE or DELETE */
524 static const SchemaQuery Query_for_list_of_updatables = {
525 .catname = "pg_catalog.pg_class c",
526 .selcondition =
527 "c.relkind IN (" CppAsString2(RELKIND_RELATION) ", "
528 CppAsString2(RELKIND_FOREIGN_TABLE) ", "
529 CppAsString2(RELKIND_VIEW) ", "
530 CppAsString2(RELKIND_PARTITIONED_TABLE) ")",
531 .viscondition = "pg_catalog.pg_table_is_visible(c.oid)",
532 .namespace = "c.relnamespace",
533 .result = "pg_catalog.quote_ident(c.relname)",
534 };
535
536 /* Relations supporting SELECT */
537 static const SchemaQuery Query_for_list_of_selectables = {
538 .catname = "pg_catalog.pg_class c",
539 .selcondition =
540 "c.relkind IN (" CppAsString2(RELKIND_RELATION) ", "
541 CppAsString2(RELKIND_SEQUENCE) ", "
542 CppAsString2(RELKIND_VIEW) ", "
543 CppAsString2(RELKIND_MATVIEW) ", "
544 CppAsString2(RELKIND_FOREIGN_TABLE) ", "
545 CppAsString2(RELKIND_PARTITIONED_TABLE) ")",
546 .viscondition = "pg_catalog.pg_table_is_visible(c.oid)",
547 .namespace = "c.relnamespace",
548 .result = "pg_catalog.quote_ident(c.relname)",
549 };
550
551 /* Relations supporting TRUNCATE */
552 static const SchemaQuery Query_for_list_of_truncatables = {
553 .catname = "pg_catalog.pg_class c",
554 .selcondition =
555 "c.relkind IN (" CppAsString2(RELKIND_RELATION) ", "
556 CppAsString2(RELKIND_FOREIGN_TABLE) ", "
557 CppAsString2(RELKIND_PARTITIONED_TABLE) ")",
558 .viscondition = "pg_catalog.pg_table_is_visible(c.oid)",
559 .namespace = "c.relnamespace",
560 .result = "pg_catalog.quote_ident(c.relname)",
561 };
562
563 /* Relations supporting GRANT are currently same as those supporting SELECT */
564 #define Query_for_list_of_grantables Query_for_list_of_selectables
565
566 /* Relations supporting ANALYZE */
567 static const SchemaQuery Query_for_list_of_analyzables = {
568 .catname = "pg_catalog.pg_class c",
569 .selcondition =
570 "c.relkind IN (" CppAsString2(RELKIND_RELATION) ", "
571 CppAsString2(RELKIND_PARTITIONED_TABLE) ", "
572 CppAsString2(RELKIND_MATVIEW) ", "
573 CppAsString2(RELKIND_FOREIGN_TABLE) ")",
574 .viscondition = "pg_catalog.pg_table_is_visible(c.oid)",
575 .namespace = "c.relnamespace",
576 .result = "pg_catalog.quote_ident(c.relname)",
577 };
578
579 /* Relations supporting index creation */
580 static const SchemaQuery Query_for_list_of_indexables = {
581 .catname = "pg_catalog.pg_class c",
582 .selcondition =
583 "c.relkind IN (" CppAsString2(RELKIND_RELATION) ", "
584 CppAsString2(RELKIND_PARTITIONED_TABLE) ", "
585 CppAsString2(RELKIND_MATVIEW) ")",
586 .viscondition = "pg_catalog.pg_table_is_visible(c.oid)",
587 .namespace = "c.relnamespace",
588 .result = "pg_catalog.quote_ident(c.relname)",
589 };
590
591 /*
592 * Relations supporting VACUUM are currently same as those supporting
593 * indexing.
594 */
595 #define Query_for_list_of_vacuumables Query_for_list_of_indexables
596
597 /* Relations supporting CLUSTER */
598 static const SchemaQuery Query_for_list_of_clusterables = {
599 .catname = "pg_catalog.pg_class c",
600 .selcondition =
601 "c.relkind IN (" CppAsString2(RELKIND_RELATION) ", "
602 CppAsString2(RELKIND_MATVIEW) ")",
603 .viscondition = "pg_catalog.pg_table_is_visible(c.oid)",
604 .namespace = "c.relnamespace",
605 .result = "pg_catalog.quote_ident(c.relname)",
606 };
607
608 static const SchemaQuery Query_for_list_of_constraints_with_schema = {
609 .catname = "pg_catalog.pg_constraint c",
610 .selcondition = "c.conrelid <> 0",
611 .viscondition = "true", /* there is no pg_constraint_is_visible */
612 .namespace = "c.connamespace",
613 .result = "pg_catalog.quote_ident(c.conname)",
614 };
615
616 static const SchemaQuery Query_for_list_of_statistics = {
617 .catname = "pg_catalog.pg_statistic_ext s",
618 .viscondition = "pg_catalog.pg_statistics_obj_is_visible(s.oid)",
619 .namespace = "s.stxnamespace",
620 .result = "pg_catalog.quote_ident(s.stxname)",
621 };
622
623 static const SchemaQuery Query_for_list_of_collations = {
624 .catname = "pg_catalog.pg_collation c",
625 .selcondition = "c.collencoding IN (-1, pg_catalog.pg_char_to_encoding(pg_catalog.getdatabaseencoding()))",
626 .viscondition = "pg_catalog.pg_collation_is_visible(c.oid)",
627 .namespace = "c.collnamespace",
628 .result = "pg_catalog.quote_ident(c.collname)",
629 };
630
631
632 /*
633 * Queries to get lists of names of various kinds of things, possibly
634 * restricted to names matching a partially entered name. In these queries,
635 * the first %s will be replaced by the text entered so far (suitably escaped
636 * to become a SQL literal string). %d will be replaced by the length of the
637 * string (in unescaped form). A second and third %s, if present, will be
638 * replaced by a suitably-escaped version of the string provided in
639 * completion_info_charp. A fourth and fifth %s are similarly replaced by
640 * completion_info_charp2.
641 *
642 * Beware that the allowed sequences of %s and %d are determined by
643 * _complete_from_query().
644 */
645
646 #define Query_for_list_of_attributes \
647 "SELECT pg_catalog.quote_ident(attname) "\
648 " FROM pg_catalog.pg_attribute a, pg_catalog.pg_class c "\
649 " WHERE c.oid = a.attrelid "\
650 " AND a.attnum > 0 "\
651 " AND NOT a.attisdropped "\
652 " AND substring(pg_catalog.quote_ident(attname),1,%d)='%s' "\
653 " AND (pg_catalog.quote_ident(relname)='%s' "\
654 " OR '\"' || relname || '\"'='%s') "\
655 " AND pg_catalog.pg_table_is_visible(c.oid)"
656
657 #define Query_for_list_of_attribute_numbers \
658 "SELECT attnum "\
659 " FROM pg_catalog.pg_attribute a, pg_catalog.pg_class c "\
660 " WHERE c.oid = a.attrelid "\
661 " AND a.attnum > 0 "\
662 " AND NOT a.attisdropped "\
663 " AND substring(attnum::pg_catalog.text,1,%d)='%s' "\
664 " AND (pg_catalog.quote_ident(relname)='%s' "\
665 " OR '\"' || relname || '\"'='%s') "\
666 " AND pg_catalog.pg_table_is_visible(c.oid)"
667
668 #define Query_for_list_of_attributes_with_schema \
669 "SELECT pg_catalog.quote_ident(attname) "\
670 " FROM pg_catalog.pg_attribute a, pg_catalog.pg_class c, pg_catalog.pg_namespace n "\
671 " WHERE c.oid = a.attrelid "\
672 " AND n.oid = c.relnamespace "\
673 " AND a.attnum > 0 "\
674 " AND NOT a.attisdropped "\
675 " AND substring(pg_catalog.quote_ident(attname),1,%d)='%s' "\
676 " AND (pg_catalog.quote_ident(relname)='%s' "\
677 " OR '\"' || relname || '\"' ='%s') "\
678 " AND (pg_catalog.quote_ident(nspname)='%s' "\
679 " OR '\"' || nspname || '\"' ='%s') "
680
681 #define Query_for_list_of_enum_values \
682 "SELECT pg_catalog.quote_literal(enumlabel) "\
683 " FROM pg_catalog.pg_enum e, pg_catalog.pg_type t "\
684 " WHERE t.oid = e.enumtypid "\
685 " AND substring(pg_catalog.quote_literal(enumlabel),1,%d)='%s' "\
686 " AND (pg_catalog.quote_ident(typname)='%s' "\
687 " OR '\"' || typname || '\"'='%s') "\
688 " AND pg_catalog.pg_type_is_visible(t.oid)"
689
690 #define Query_for_list_of_enum_values_with_schema \
691 "SELECT pg_catalog.quote_literal(enumlabel) "\
692 " FROM pg_catalog.pg_enum e, pg_catalog.pg_type t, pg_catalog.pg_namespace n "\
693 " WHERE t.oid = e.enumtypid "\
694 " AND n.oid = t.typnamespace "\
695 " AND substring(pg_catalog.quote_literal(enumlabel),1,%d)='%s' "\
696 " AND (pg_catalog.quote_ident(typname)='%s' "\
697 " OR '\"' || typname || '\"'='%s') "\
698 " AND (pg_catalog.quote_ident(nspname)='%s' "\
699 " OR '\"' || nspname || '\"' ='%s') "
700
701 #define Query_for_list_of_template_databases \
702 "SELECT pg_catalog.quote_ident(d.datname) "\
703 " FROM pg_catalog.pg_database d "\
704 " WHERE substring(pg_catalog.quote_ident(d.datname),1,%d)='%s' "\
705 " AND (d.datistemplate OR pg_catalog.pg_has_role(d.datdba, 'USAGE'))"
706
707 #define Query_for_list_of_databases \
708 "SELECT pg_catalog.quote_ident(datname) FROM pg_catalog.pg_database "\
709 " WHERE substring(pg_catalog.quote_ident(datname),1,%d)='%s'"
710
711 #define Query_for_list_of_tablespaces \
712 "SELECT pg_catalog.quote_ident(spcname) FROM pg_catalog.pg_tablespace "\
713 " WHERE substring(pg_catalog.quote_ident(spcname),1,%d)='%s'"
714
715 #define Query_for_list_of_encodings \
716 " SELECT DISTINCT pg_catalog.pg_encoding_to_char(conforencoding) "\
717 " FROM pg_catalog.pg_conversion "\
718 " WHERE substring(pg_catalog.pg_encoding_to_char(conforencoding),1,%d)=UPPER('%s')"
719
720 #define Query_for_list_of_languages \
721 "SELECT pg_catalog.quote_ident(lanname) "\
722 " FROM pg_catalog.pg_language "\
723 " WHERE lanname != 'internal' "\
724 " AND substring(pg_catalog.quote_ident(lanname),1,%d)='%s'"
725
726 #define Query_for_list_of_schemas \
727 "SELECT pg_catalog.quote_ident(nspname) FROM pg_catalog.pg_namespace "\
728 " WHERE substring(pg_catalog.quote_ident(nspname),1,%d)='%s'"
729
730 #define Query_for_list_of_alter_system_set_vars \
731 "SELECT name FROM "\
732 " (SELECT pg_catalog.lower(name) AS name FROM pg_catalog.pg_settings "\
733 " WHERE context != 'internal' "\
734 " UNION ALL SELECT 'all') ss "\
735 " WHERE substring(name,1,%d)='%s'"
736
737 #define Query_for_list_of_set_vars \
738 "SELECT name FROM "\
739 " (SELECT pg_catalog.lower(name) AS name FROM pg_catalog.pg_settings "\
740 " WHERE context IN ('user', 'superuser') "\
741 " UNION ALL SELECT 'constraints' "\
742 " UNION ALL SELECT 'transaction' "\
743 " UNION ALL SELECT 'session' "\
744 " UNION ALL SELECT 'role' "\
745 " UNION ALL SELECT 'tablespace' "\
746 " UNION ALL SELECT 'all') ss "\
747 " WHERE substring(name,1,%d)='%s'"
748
749 #define Query_for_list_of_show_vars \
750 "SELECT name FROM "\
751 " (SELECT pg_catalog.lower(name) AS name FROM pg_catalog.pg_settings "\
752 " UNION ALL SELECT 'session authorization' "\
753 " UNION ALL SELECT 'all') ss "\
754 " WHERE substring(name,1,%d)='%s'"
755
756 #define Query_for_list_of_roles \
757 " SELECT pg_catalog.quote_ident(rolname) "\
758 " FROM pg_catalog.pg_roles "\
759 " WHERE substring(pg_catalog.quote_ident(rolname),1,%d)='%s'"
760
761 #define Query_for_list_of_grant_roles \
762 " SELECT pg_catalog.quote_ident(rolname) "\
763 " FROM pg_catalog.pg_roles "\
764 " WHERE substring(pg_catalog.quote_ident(rolname),1,%d)='%s'"\
765 " UNION ALL SELECT 'PUBLIC'"\
766 " UNION ALL SELECT 'CURRENT_ROLE'"\
767 " UNION ALL SELECT 'CURRENT_USER'"\
768 " UNION ALL SELECT 'SESSION_USER'"
769
770 /* the silly-looking length condition is just to eat up the current word */
771 #define Query_for_index_of_table \
772 "SELECT pg_catalog.quote_ident(c2.relname) "\
773 " FROM pg_catalog.pg_class c1, pg_catalog.pg_class c2, pg_catalog.pg_index i"\
774 " WHERE c1.oid=i.indrelid and i.indexrelid=c2.oid"\
775 " and (%d = pg_catalog.length('%s'))"\
776 " and pg_catalog.quote_ident(c1.relname)='%s'"\
777 " and pg_catalog.pg_table_is_visible(c2.oid)"
778
779 /* the silly-looking length condition is just to eat up the current word */
780 #define Query_for_constraint_of_table \
781 "SELECT pg_catalog.quote_ident(conname) "\
782 " FROM pg_catalog.pg_class c1, pg_catalog.pg_constraint con "\
783 " WHERE c1.oid=conrelid and (%d = pg_catalog.length('%s'))"\
784 " and pg_catalog.quote_ident(c1.relname)='%s'"\
785 " and pg_catalog.pg_table_is_visible(c1.oid)"
786
787 #define Query_for_all_table_constraints \
788 "SELECT pg_catalog.quote_ident(conname) "\
789 " FROM pg_catalog.pg_constraint c "\
790 " WHERE c.conrelid <> 0 "
791
792 /* the silly-looking length condition is just to eat up the current word */
793 #define Query_for_constraint_of_type \
794 "SELECT pg_catalog.quote_ident(conname) "\
795 " FROM pg_catalog.pg_type t, pg_catalog.pg_constraint con "\
796 " WHERE t.oid=contypid and (%d = pg_catalog.length('%s'))"\
797 " and pg_catalog.quote_ident(t.typname)='%s'"\
798 " and pg_catalog.pg_type_is_visible(t.oid)"
799
800 /* the silly-looking length condition is just to eat up the current word */
801 #define Query_for_list_of_tables_for_constraint \
802 "SELECT pg_catalog.quote_ident(relname) "\
803 " FROM pg_catalog.pg_class"\
804 " WHERE (%d = pg_catalog.length('%s'))"\
805 " AND oid IN "\
806 " (SELECT conrelid FROM pg_catalog.pg_constraint "\
807 " WHERE pg_catalog.quote_ident(conname)='%s')"
808
809 /* the silly-looking length condition is just to eat up the current word */
810 #define Query_for_rule_of_table \
811 "SELECT pg_catalog.quote_ident(rulename) "\
812 " FROM pg_catalog.pg_class c1, pg_catalog.pg_rewrite "\
813 " WHERE c1.oid=ev_class and (%d = pg_catalog.length('%s'))"\
814 " and pg_catalog.quote_ident(c1.relname)='%s'"\
815 " and pg_catalog.pg_table_is_visible(c1.oid)"
816
817 /* the silly-looking length condition is just to eat up the current word */
818 #define Query_for_list_of_tables_for_rule \
819 "SELECT pg_catalog.quote_ident(relname) "\
820 " FROM pg_catalog.pg_class"\
821 " WHERE (%d = pg_catalog.length('%s'))"\
822 " AND oid IN "\
823 " (SELECT ev_class FROM pg_catalog.pg_rewrite "\
824 " WHERE pg_catalog.quote_ident(rulename)='%s')"
825
826 /* the silly-looking length condition is just to eat up the current word */
827 #define Query_for_trigger_of_table \
828 "SELECT pg_catalog.quote_ident(tgname) "\
829 " FROM pg_catalog.pg_class c1, pg_catalog.pg_trigger "\
830 " WHERE c1.oid=tgrelid and (%d = pg_catalog.length('%s'))"\
831 " and pg_catalog.quote_ident(c1.relname)='%s'"\
832 " and pg_catalog.pg_table_is_visible(c1.oid)"\
833 " and not tgisinternal"
834
835 /* the silly-looking length condition is just to eat up the current word */
836 #define Query_for_list_of_tables_for_trigger \
837 "SELECT pg_catalog.quote_ident(relname) "\
838 " FROM pg_catalog.pg_class"\
839 " WHERE (%d = pg_catalog.length('%s'))"\
840 " AND oid IN "\
841 " (SELECT tgrelid FROM pg_catalog.pg_trigger "\
842 " WHERE pg_catalog.quote_ident(tgname)='%s')"
843
844 #define Query_for_list_of_ts_configurations \
845 "SELECT pg_catalog.quote_ident(cfgname) FROM pg_catalog.pg_ts_config "\
846 " WHERE substring(pg_catalog.quote_ident(cfgname),1,%d)='%s'"
847
848 #define Query_for_list_of_ts_dictionaries \
849 "SELECT pg_catalog.quote_ident(dictname) FROM pg_catalog.pg_ts_dict "\
850 " WHERE substring(pg_catalog.quote_ident(dictname),1,%d)='%s'"
851
852 #define Query_for_list_of_ts_parsers \
853 "SELECT pg_catalog.quote_ident(prsname) FROM pg_catalog.pg_ts_parser "\
854 " WHERE substring(pg_catalog.quote_ident(prsname),1,%d)='%s'"
855
856 #define Query_for_list_of_ts_templates \
857 "SELECT pg_catalog.quote_ident(tmplname) FROM pg_catalog.pg_ts_template "\
858 " WHERE substring(pg_catalog.quote_ident(tmplname),1,%d)='%s'"
859
860 #define Query_for_list_of_fdws \
861 " SELECT pg_catalog.quote_ident(fdwname) "\
862 " FROM pg_catalog.pg_foreign_data_wrapper "\
863 " WHERE substring(pg_catalog.quote_ident(fdwname),1,%d)='%s'"
864
865 #define Query_for_list_of_servers \
866 " SELECT pg_catalog.quote_ident(srvname) "\
867 " FROM pg_catalog.pg_foreign_server "\
868 " WHERE substring(pg_catalog.quote_ident(srvname),1,%d)='%s'"
869
870 #define Query_for_list_of_user_mappings \
871 " SELECT pg_catalog.quote_ident(usename) "\
872 " FROM pg_catalog.pg_user_mappings "\
873 " WHERE substring(pg_catalog.quote_ident(usename),1,%d)='%s'"
874
875 #define Query_for_list_of_access_methods \
876 " SELECT pg_catalog.quote_ident(amname) "\
877 " FROM pg_catalog.pg_am "\
878 " WHERE substring(pg_catalog.quote_ident(amname),1,%d)='%s'"
879
880 #define Query_for_list_of_index_access_methods \
881 " SELECT pg_catalog.quote_ident(amname) "\
882 " FROM pg_catalog.pg_am "\
883 " WHERE substring(pg_catalog.quote_ident(amname),1,%d)='%s' AND "\
884 " amtype=" CppAsString2(AMTYPE_INDEX)
885
886 #define Query_for_list_of_table_access_methods \
887 " SELECT pg_catalog.quote_ident(amname) "\
888 " FROM pg_catalog.pg_am "\
889 " WHERE substring(pg_catalog.quote_ident(amname),1,%d)='%s' AND "\
890 " amtype=" CppAsString2(AMTYPE_TABLE)
891
892 /* the silly-looking length condition is just to eat up the current word */
893 #define Query_for_list_of_arguments \
894 "SELECT pg_catalog.oidvectortypes(proargtypes)||')' "\
895 " FROM pg_catalog.pg_proc "\
896 " WHERE (%d = pg_catalog.length('%s'))"\
897 " AND (pg_catalog.quote_ident(proname)='%s'"\
898 " OR '\"' || proname || '\"'='%s') "\
899 " AND (pg_catalog.pg_function_is_visible(pg_proc.oid))"
900
901 /* the silly-looking length condition is just to eat up the current word */
902 #define Query_for_list_of_arguments_with_schema \
903 "SELECT pg_catalog.oidvectortypes(proargtypes)||')' "\
904 " FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n "\
905 " WHERE (%d = pg_catalog.length('%s'))"\
906 " AND n.oid = p.pronamespace "\
907 " AND (pg_catalog.quote_ident(proname)='%s' "\
908 " OR '\"' || proname || '\"' ='%s') "\
909 " AND (pg_catalog.quote_ident(nspname)='%s' "\
910 " OR '\"' || nspname || '\"' ='%s') "
911
912 #define Query_for_list_of_extensions \
913 " SELECT pg_catalog.quote_ident(extname) "\
914 " FROM pg_catalog.pg_extension "\
915 " WHERE substring(pg_catalog.quote_ident(extname),1,%d)='%s'"
916
917 #define Query_for_list_of_available_extensions \
918 " SELECT pg_catalog.quote_ident(name) "\
919 " FROM pg_catalog.pg_available_extensions "\
920 " WHERE substring(pg_catalog.quote_ident(name),1,%d)='%s' AND installed_version IS NULL"
921
922 /* the silly-looking length condition is just to eat up the current word */
923 #define Query_for_list_of_available_extension_versions \
924 " SELECT pg_catalog.quote_ident(version) "\
925 " FROM pg_catalog.pg_available_extension_versions "\
926 " WHERE (%d = pg_catalog.length('%s'))"\
927 " AND pg_catalog.quote_ident(name)='%s'"
928
929 /* the silly-looking length condition is just to eat up the current word */
930 #define Query_for_list_of_available_extension_versions_with_TO \
931 " SELECT 'TO ' || pg_catalog.quote_ident(version) "\
932 " FROM pg_catalog.pg_available_extension_versions "\
933 " WHERE (%d = pg_catalog.length('%s'))"\
934 " AND pg_catalog.quote_ident(name)='%s'"
935
936 #define Query_for_list_of_prepared_statements \
937 " SELECT pg_catalog.quote_ident(name) "\
938 " FROM pg_catalog.pg_prepared_statements "\
939 " WHERE substring(pg_catalog.quote_ident(name),1,%d)='%s'"
940
941 #define Query_for_list_of_event_triggers \
942 " SELECT pg_catalog.quote_ident(evtname) "\
943 " FROM pg_catalog.pg_event_trigger "\
944 " WHERE substring(pg_catalog.quote_ident(evtname),1,%d)='%s'"
945
946 #define Query_for_list_of_tablesample_methods \
947 " SELECT pg_catalog.quote_ident(proname) "\
948 " FROM pg_catalog.pg_proc "\
949 " WHERE prorettype = 'pg_catalog.tsm_handler'::pg_catalog.regtype AND "\
950 " proargtypes[0] = 'pg_catalog.internal'::pg_catalog.regtype AND "\
951 " substring(pg_catalog.quote_ident(proname),1,%d)='%s'"
952
953 #define Query_for_list_of_policies \
954 " SELECT pg_catalog.quote_ident(polname) "\
955 " FROM pg_catalog.pg_policy "\
956 " WHERE substring(pg_catalog.quote_ident(polname),1,%d)='%s'"
957
958 #define Query_for_list_of_tables_for_policy \
959 "SELECT pg_catalog.quote_ident(relname) "\
960 " FROM pg_catalog.pg_class"\
961 " WHERE (%d = pg_catalog.length('%s'))"\
962 " AND oid IN "\
963 " (SELECT polrelid FROM pg_catalog.pg_policy "\
964 " WHERE pg_catalog.quote_ident(polname)='%s')"
965
966 #define Query_for_enum \
967 " SELECT name FROM ( "\
968 " SELECT pg_catalog.quote_ident(pg_catalog.unnest(enumvals)) AS name "\
969 " FROM pg_catalog.pg_settings "\
970 " WHERE pg_catalog.lower(name)=pg_catalog.lower('%s') "\
971 " UNION ALL " \
972 " SELECT 'DEFAULT' ) ss "\
973 " WHERE pg_catalog.substring(name,1,%%d)='%%s'"
974
975 /* the silly-looking length condition is just to eat up the current word */
976 #define Query_for_partition_of_table \
977 "SELECT pg_catalog.quote_ident(c2.relname) "\
978 " FROM pg_catalog.pg_class c1, pg_catalog.pg_class c2, pg_catalog.pg_inherits i"\
979 " WHERE c1.oid=i.inhparent and i.inhrelid=c2.oid"\
980 " and (%d = pg_catalog.length('%s'))"\
981 " and pg_catalog.quote_ident(c1.relname)='%s'"\
982 " and pg_catalog.pg_table_is_visible(c2.oid)"\
983 " and c2.relispartition = 'true'"
984
985 #define Query_for_list_of_cursors \
986 " SELECT pg_catalog.quote_ident(name) "\
987 " FROM pg_catalog.pg_cursors "\
988 " WHERE substring(pg_catalog.quote_ident(name),1,%d)='%s'"
989
990 /*
991 * These object types were introduced later than our support cutoff of
992 * server version 7.4. We use the VersionedQuery infrastructure so that
993 * we don't send certain-to-fail queries to older servers.
994 */
995
996 static const VersionedQuery Query_for_list_of_publications[] = {
997 {100000,
998 " SELECT pg_catalog.quote_ident(pubname) "
999 " FROM pg_catalog.pg_publication "
1000 " WHERE substring(pg_catalog.quote_ident(pubname),1,%d)='%s'"
1001 },
1002 {0, NULL}
1003 };
1004
1005 static const VersionedQuery Query_for_list_of_subscriptions[] = {
1006 {100000,
1007 " SELECT pg_catalog.quote_ident(s.subname) "
1008 " FROM pg_catalog.pg_subscription s, pg_catalog.pg_database d "
1009 " WHERE substring(pg_catalog.quote_ident(s.subname),1,%d)='%s' "
1010 " AND d.datname = pg_catalog.current_database() "
1011 " AND s.subdbid = d.oid"
1012 },
1013 {0, NULL}
1014 };
1015
1016 /*
1017 * This is a list of all "things" in Pgsql, which can show up after CREATE or
1018 * DROP; and there is also a query to get a list of them.
1019 */
1020
1021 typedef struct
1022 {
1023 const char *name;
1024 const char *query; /* simple query, or NULL */
1025 const VersionedQuery *vquery; /* versioned query, or NULL */
1026 const SchemaQuery *squery; /* schema query, or NULL */
1027 const bits32 flags; /* visibility flags, see below */
1028 } pgsql_thing_t;
1029
1030 #define THING_NO_CREATE (1 << 0) /* should not show up after CREATE */
1031 #define THING_NO_DROP (1 << 1) /* should not show up after DROP */
1032 #define THING_NO_ALTER (1 << 2) /* should not show up after ALTER */
1033 #define THING_NO_SHOW (THING_NO_CREATE | THING_NO_DROP | THING_NO_ALTER)
1034
1035 static const pgsql_thing_t words_after_create[] = {
1036 {"ACCESS METHOD", NULL, NULL, NULL, THING_NO_ALTER},
1037 {"AGGREGATE", NULL, NULL, Query_for_list_of_aggregates},
1038 {"CAST", NULL, NULL, NULL}, /* Casts have complex structures for names, so
1039 * skip it */
1040 {"COLLATION", NULL, NULL, &Query_for_list_of_collations},
1041
1042 /*
1043 * CREATE CONSTRAINT TRIGGER is not supported here because it is designed
1044 * to be used only by pg_dump.
1045 */
1046 {"CONFIGURATION", Query_for_list_of_ts_configurations, NULL, NULL, THING_NO_SHOW},
1047 {"CONVERSION", "SELECT pg_catalog.quote_ident(conname) FROM pg_catalog.pg_conversion WHERE substring(pg_catalog.quote_ident(conname),1,%d)='%s'"},
1048 {"DATABASE", Query_for_list_of_databases},
1049 {"DEFAULT PRIVILEGES", NULL, NULL, NULL, THING_NO_CREATE | THING_NO_DROP},
1050 {"DICTIONARY", Query_for_list_of_ts_dictionaries, NULL, NULL, THING_NO_SHOW},
1051 {"DOMAIN", NULL, NULL, &Query_for_list_of_domains},
1052 {"EVENT TRIGGER", NULL, NULL, NULL},
1053 {"EXTENSION", Query_for_list_of_extensions},
1054 {"FOREIGN DATA WRAPPER", NULL, NULL, NULL},
1055 {"FOREIGN TABLE", NULL, NULL, NULL},
1056 {"FUNCTION", NULL, NULL, Query_for_list_of_functions},
1057 {"GROUP", Query_for_list_of_roles},
1058 {"INDEX", NULL, NULL, &Query_for_list_of_indexes},
1059 {"LANGUAGE", Query_for_list_of_languages},
1060 {"LARGE OBJECT", NULL, NULL, NULL, THING_NO_CREATE | THING_NO_DROP},
1061 {"MATERIALIZED VIEW", NULL, NULL, &Query_for_list_of_matviews},
1062 {"OPERATOR", NULL, NULL, NULL}, /* Querying for this is probably not such
1063 * a good idea. */
1064 {"OR REPLACE", NULL, NULL, NULL, THING_NO_DROP | THING_NO_ALTER},
1065 {"OWNED", NULL, NULL, NULL, THING_NO_CREATE | THING_NO_ALTER}, /* for DROP OWNED BY ... */
1066 {"PARSER", Query_for_list_of_ts_parsers, NULL, NULL, THING_NO_SHOW},
1067 {"POLICY", NULL, NULL, NULL},
1068 {"PROCEDURE", NULL, NULL, Query_for_list_of_procedures},
1069 {"PUBLICATION", NULL, Query_for_list_of_publications},
1070 {"ROLE", Query_for_list_of_roles},
1071 {"ROUTINE", NULL, NULL, &Query_for_list_of_routines, THING_NO_CREATE},
1072 {"RULE", "SELECT pg_catalog.quote_ident(rulename) FROM pg_catalog.pg_rules WHERE substring(pg_catalog.quote_ident(rulename),1,%d)='%s'"},
1073 {"SCHEMA", Query_for_list_of_schemas},
1074 {"SEQUENCE", NULL, NULL, &Query_for_list_of_sequences},
1075 {"SERVER", Query_for_list_of_servers},
1076 {"STATISTICS", NULL, NULL, &Query_for_list_of_statistics},
1077 {"SUBSCRIPTION", NULL, Query_for_list_of_subscriptions},
1078 {"SYSTEM", NULL, NULL, NULL, THING_NO_CREATE | THING_NO_DROP},
1079 {"TABLE", NULL, NULL, &Query_for_list_of_tables},
1080 {"TABLESPACE", Query_for_list_of_tablespaces},
1081 {"TEMP", NULL, NULL, NULL, THING_NO_DROP | THING_NO_ALTER}, /* for CREATE TEMP TABLE
1082 * ... */
1083 {"TEMPLATE", Query_for_list_of_ts_templates, NULL, NULL, THING_NO_SHOW},
1084 {"TEMPORARY", NULL, NULL, NULL, THING_NO_DROP | THING_NO_ALTER}, /* for CREATE TEMPORARY
1085 * TABLE ... */
1086 {"TEXT SEARCH", NULL, NULL, NULL},
1087 {"TRANSFORM", NULL, NULL, NULL},
1088 {"TRIGGER", "SELECT pg_catalog.quote_ident(tgname) FROM pg_catalog.pg_trigger WHERE substring(pg_catalog.quote_ident(tgname),1,%d)='%s' AND NOT tgisinternal"},
1089 {"TYPE", NULL, NULL, &Query_for_list_of_datatypes},
1090 {"UNIQUE", NULL, NULL, NULL, THING_NO_DROP | THING_NO_ALTER}, /* for CREATE UNIQUE
1091 * INDEX ... */
1092 {"UNLOGGED", NULL, NULL, NULL, THING_NO_DROP | THING_NO_ALTER}, /* for CREATE UNLOGGED
1093 * TABLE ... */
1094 {"USER", Query_for_list_of_roles " UNION SELECT 'MAPPING FOR'"},
1095 {"USER MAPPING FOR", NULL, NULL, NULL},
1096 {"VIEW", NULL, NULL, &Query_for_list_of_views},
1097 {NULL} /* end of list */
1098 };
1099
1100 /* Storage parameters for CREATE TABLE and ALTER TABLE */
1101 static const char *const table_storage_parameters[] = {
1102 "autovacuum_analyze_scale_factor",
1103 "autovacuum_analyze_threshold",
1104 "autovacuum_enabled",
1105 "autovacuum_freeze_max_age",
1106 "autovacuum_freeze_min_age",
1107 "autovacuum_freeze_table_age",
1108 "autovacuum_multixact_freeze_max_age",
1109 "autovacuum_multixact_freeze_min_age",
1110 "autovacuum_multixact_freeze_table_age",
1111 "autovacuum_vacuum_cost_delay",
1112 "autovacuum_vacuum_cost_limit",
1113 "autovacuum_vacuum_insert_scale_factor",
1114 "autovacuum_vacuum_insert_threshold",
1115 "autovacuum_vacuum_scale_factor",
1116 "autovacuum_vacuum_threshold",
1117 "fillfactor",
1118 "log_autovacuum_min_duration",
1119 "parallel_workers",
1120 "toast.autovacuum_enabled",
1121 "toast.autovacuum_freeze_max_age",
1122 "toast.autovacuum_freeze_min_age",
1123 "toast.autovacuum_freeze_table_age",
1124 "toast.autovacuum_multixact_freeze_max_age",
1125 "toast.autovacuum_multixact_freeze_min_age",
1126 "toast.autovacuum_multixact_freeze_table_age",
1127 "toast.autovacuum_vacuum_cost_delay",
1128 "toast.autovacuum_vacuum_cost_limit",
1129 "toast.autovacuum_vacuum_insert_scale_factor",
1130 "toast.autovacuum_vacuum_insert_threshold",
1131 "toast.autovacuum_vacuum_scale_factor",
1132 "toast.autovacuum_vacuum_threshold",
1133 "toast.log_autovacuum_min_duration",
1134 "toast.vacuum_index_cleanup",
1135 "toast.vacuum_truncate",
1136 "toast_tuple_target",
1137 "user_catalog_table",
1138 "vacuum_index_cleanup",
1139 "vacuum_truncate",
1140 NULL
1141 };
1142
1143
1144 /* Forward declaration of functions */
1145 static char **psql_completion(const char *text, int start, int end);
1146 static char *create_command_generator(const char *text, int state);
1147 static char *drop_command_generator(const char *text, int state);
1148 static char *alter_command_generator(const char *text, int state);
1149 static char *complete_from_query(const char *text, int state);
1150 static char *complete_from_versioned_query(const char *text, int state);
1151 static char *complete_from_schema_query(const char *text, int state);
1152 static char *complete_from_versioned_schema_query(const char *text, int state);
1153 static char *_complete_from_query(const char *simple_query,
1154 const SchemaQuery *schema_query,
1155 const char *text, int state);
1156 static char *complete_from_list(const char *text, int state);
1157 static char *complete_from_const(const char *text, int state);
1158 static void append_variable_names(char ***varnames, int *nvars,
1159 int *maxvars, const char *varname,
1160 const char *prefix, const char *suffix);
1161 static char **complete_from_variables(const char *text,
1162 const char *prefix, const char *suffix, bool need_value);
1163 static char *complete_from_files(const char *text, int state);
1164
1165 static char *pg_strdup_keyword_case(const char *s, const char *ref);
1166 static char *escape_string(const char *text);
1167 static PGresult *exec_query(const char *query);
1168
1169 static char **get_previous_words(int point, char **buffer, int *nwords);
1170
1171 static char *get_guctype(const char *varname);
1172
1173 #ifdef USE_FILENAME_QUOTING_FUNCTIONS
1174 static char *quote_file_name(char *fname, int match_type, char *quote_pointer);
1175 static char *dequote_file_name(char *fname, int quote_char);
1176 #endif
1177
1178
1179 /*
1180 * Initialize the readline library for our purposes.
1181 */
1182 void
initialize_readline(void)1183 initialize_readline(void)
1184 {
1185 rl_readline_name = (char *) pset.progname;
1186 rl_attempted_completion_function = psql_completion;
1187
1188 #ifdef USE_FILENAME_QUOTING_FUNCTIONS
1189 rl_filename_quoting_function = quote_file_name;
1190 rl_filename_dequoting_function = dequote_file_name;
1191 #endif
1192
1193 rl_basic_word_break_characters = WORD_BREAKS;
1194
1195 /*
1196 * We should include '"' in rl_completer_quote_characters too, but that
1197 * will require some upgrades to how we handle quoted identifiers, so
1198 * that's for another day.
1199 */
1200 rl_completer_quote_characters = "'";
1201
1202 /*
1203 * Set rl_filename_quote_characters to "all possible characters",
1204 * otherwise Readline will skip filename quoting if it thinks a filename
1205 * doesn't need quoting. Readline actually interprets this as bytes, so
1206 * there are no encoding considerations here.
1207 */
1208 #ifdef HAVE_RL_FILENAME_QUOTE_CHARACTERS
1209 {
1210 unsigned char *fqc = (unsigned char *) pg_malloc(256);
1211
1212 for (int i = 0; i < 255; i++)
1213 fqc[i] = (unsigned char) (i + 1);
1214 fqc[255] = '\0';
1215 rl_filename_quote_characters = (const char *) fqc;
1216 }
1217 #endif
1218
1219 completion_max_records = 1000;
1220
1221 /*
1222 * There is a variable rl_completion_query_items for this but apparently
1223 * it's not defined everywhere.
1224 */
1225 }
1226
1227 /*
1228 * Check if 'word' matches any of the '|'-separated strings in 'pattern',
1229 * using case-insensitive or case-sensitive comparisons.
1230 *
1231 * If pattern is NULL, it's a wild card that matches any word.
1232 * If pattern begins with '!', the result is negated, ie we check that 'word'
1233 * does *not* match any alternative appearing in the rest of 'pattern'.
1234 * Any alternative can contain '*' which is a wild card, i.e., it can match
1235 * any substring; however, we allow at most one '*' per alternative.
1236 *
1237 * For readability, callers should use the macros MatchAny and MatchAnyExcept
1238 * to invoke those two special cases for 'pattern'. (But '|' and '*' must
1239 * just be written directly in patterns.)
1240 */
1241 #define MatchAny NULL
1242 #define MatchAnyExcept(pattern) ("!" pattern)
1243
1244 static bool
word_matches(const char * pattern,const char * word,bool case_sensitive)1245 word_matches(const char *pattern,
1246 const char *word,
1247 bool case_sensitive)
1248 {
1249 size_t wordlen;
1250
1251 #define cimatch(s1, s2, n) \
1252 (case_sensitive ? strncmp(s1, s2, n) == 0 : pg_strncasecmp(s1, s2, n) == 0)
1253
1254 /* NULL pattern matches anything. */
1255 if (pattern == NULL)
1256 return true;
1257
1258 /* Handle negated patterns from the MatchAnyExcept macro. */
1259 if (*pattern == '!')
1260 return !word_matches(pattern + 1, word, case_sensitive);
1261
1262 /* Else consider each alternative in the pattern. */
1263 wordlen = strlen(word);
1264 for (;;)
1265 {
1266 const char *star = NULL;
1267 const char *c;
1268
1269 /* Find end of current alternative, and locate any wild card. */
1270 c = pattern;
1271 while (*c != '\0' && *c != '|')
1272 {
1273 if (*c == '*')
1274 star = c;
1275 c++;
1276 }
1277 /* Was there a wild card? */
1278 if (star)
1279 {
1280 /* Yes, wildcard match? */
1281 size_t beforelen = star - pattern,
1282 afterlen = c - star - 1;
1283
1284 if (wordlen >= (beforelen + afterlen) &&
1285 cimatch(word, pattern, beforelen) &&
1286 cimatch(word + wordlen - afterlen, star + 1, afterlen))
1287 return true;
1288 }
1289 else
1290 {
1291 /* No, plain match? */
1292 if (wordlen == (c - pattern) &&
1293 cimatch(word, pattern, wordlen))
1294 return true;
1295 }
1296 /* Out of alternatives? */
1297 if (*c == '\0')
1298 break;
1299 /* Nope, try next alternative. */
1300 pattern = c + 1;
1301 }
1302
1303 return false;
1304 }
1305
1306 /*
1307 * Implementation of TailMatches and TailMatchesCS macros: do the last N words
1308 * in previous_words match the variadic arguments?
1309 *
1310 * The array indexing might look backwards, but remember that
1311 * previous_words[0] contains the *last* word on the line, not the first.
1312 */
1313 static bool
TailMatchesImpl(bool case_sensitive,int previous_words_count,char ** previous_words,int narg,...)1314 TailMatchesImpl(bool case_sensitive,
1315 int previous_words_count, char **previous_words,
1316 int narg,...)
1317 {
1318 va_list args;
1319
1320 if (previous_words_count < narg)
1321 return false;
1322
1323 va_start(args, narg);
1324
1325 for (int argno = 0; argno < narg; argno++)
1326 {
1327 const char *arg = va_arg(args, const char *);
1328
1329 if (!word_matches(arg, previous_words[narg - argno - 1],
1330 case_sensitive))
1331 {
1332 va_end(args);
1333 return false;
1334 }
1335 }
1336
1337 va_end(args);
1338
1339 return true;
1340 }
1341
1342 /*
1343 * Implementation of Matches and MatchesCS macros: do all of the words
1344 * in previous_words match the variadic arguments?
1345 */
1346 static bool
MatchesImpl(bool case_sensitive,int previous_words_count,char ** previous_words,int narg,...)1347 MatchesImpl(bool case_sensitive,
1348 int previous_words_count, char **previous_words,
1349 int narg,...)
1350 {
1351 va_list args;
1352
1353 if (previous_words_count != narg)
1354 return false;
1355
1356 va_start(args, narg);
1357
1358 for (int argno = 0; argno < narg; argno++)
1359 {
1360 const char *arg = va_arg(args, const char *);
1361
1362 if (!word_matches(arg, previous_words[narg - argno - 1],
1363 case_sensitive))
1364 {
1365 va_end(args);
1366 return false;
1367 }
1368 }
1369
1370 va_end(args);
1371
1372 return true;
1373 }
1374
1375 /*
1376 * Implementation of HeadMatches and HeadMatchesCS macros: do the first N
1377 * words in previous_words match the variadic arguments?
1378 */
1379 static bool
HeadMatchesImpl(bool case_sensitive,int previous_words_count,char ** previous_words,int narg,...)1380 HeadMatchesImpl(bool case_sensitive,
1381 int previous_words_count, char **previous_words,
1382 int narg,...)
1383 {
1384 va_list args;
1385
1386 if (previous_words_count < narg)
1387 return false;
1388
1389 va_start(args, narg);
1390
1391 for (int argno = 0; argno < narg; argno++)
1392 {
1393 const char *arg = va_arg(args, const char *);
1394
1395 if (!word_matches(arg, previous_words[previous_words_count - argno - 1],
1396 case_sensitive))
1397 {
1398 va_end(args);
1399 return false;
1400 }
1401 }
1402
1403 va_end(args);
1404
1405 return true;
1406 }
1407
1408 /*
1409 * Check if the final character of 's' is 'c'.
1410 */
1411 static bool
ends_with(const char * s,char c)1412 ends_with(const char *s, char c)
1413 {
1414 size_t length = strlen(s);
1415
1416 return (length > 0 && s[length - 1] == c);
1417 }
1418
1419 /*
1420 * The completion function.
1421 *
1422 * According to readline spec this gets passed the text entered so far and its
1423 * start and end positions in the readline buffer. The return value is some
1424 * partially obscure list format that can be generated by readline's
1425 * rl_completion_matches() function, so we don't have to worry about it.
1426 */
1427 static char **
psql_completion(const char * text,int start,int end)1428 psql_completion(const char *text, int start, int end)
1429 {
1430 /* This is the variable we'll return. */
1431 char **matches = NULL;
1432
1433 /* Workspace for parsed words. */
1434 char *words_buffer;
1435
1436 /* This array will contain pointers to parsed words. */
1437 char **previous_words;
1438
1439 /* The number of words found on the input line. */
1440 int previous_words_count;
1441
1442 /*
1443 * For compactness, we use these macros to reference previous_words[].
1444 * Caution: do not access a previous_words[] entry without having checked
1445 * previous_words_count to be sure it's valid. In most cases below, that
1446 * check is implicit in a TailMatches() or similar macro, but in some
1447 * places we have to check it explicitly.
1448 */
1449 #define prev_wd (previous_words[0])
1450 #define prev2_wd (previous_words[1])
1451 #define prev3_wd (previous_words[2])
1452 #define prev4_wd (previous_words[3])
1453 #define prev5_wd (previous_words[4])
1454 #define prev6_wd (previous_words[5])
1455 #define prev7_wd (previous_words[6])
1456 #define prev8_wd (previous_words[7])
1457 #define prev9_wd (previous_words[8])
1458
1459 /* Match the last N words before point, case-insensitively. */
1460 #define TailMatches(...) \
1461 TailMatchesImpl(false, previous_words_count, previous_words, \
1462 VA_ARGS_NARGS(__VA_ARGS__), __VA_ARGS__)
1463
1464 /* Match the last N words before point, case-sensitively. */
1465 #define TailMatchesCS(...) \
1466 TailMatchesImpl(true, previous_words_count, previous_words, \
1467 VA_ARGS_NARGS(__VA_ARGS__), __VA_ARGS__)
1468
1469 /* Match N words representing all of the line, case-insensitively. */
1470 #define Matches(...) \
1471 MatchesImpl(false, previous_words_count, previous_words, \
1472 VA_ARGS_NARGS(__VA_ARGS__), __VA_ARGS__)
1473
1474 /* Match N words representing all of the line, case-sensitively. */
1475 #define MatchesCS(...) \
1476 MatchesImpl(true, previous_words_count, previous_words, \
1477 VA_ARGS_NARGS(__VA_ARGS__), __VA_ARGS__)
1478
1479 /* Match the first N words on the line, case-insensitively. */
1480 #define HeadMatches(...) \
1481 HeadMatchesImpl(false, previous_words_count, previous_words, \
1482 VA_ARGS_NARGS(__VA_ARGS__), __VA_ARGS__)
1483
1484 /* Match the first N words on the line, case-sensitively. */
1485 #define HeadMatchesCS(...) \
1486 HeadMatchesImpl(true, previous_words_count, previous_words, \
1487 VA_ARGS_NARGS(__VA_ARGS__), __VA_ARGS__)
1488
1489 /* Known command-starting keywords. */
1490 static const char *const sql_commands[] = {
1491 "ABORT", "ALTER", "ANALYZE", "BEGIN", "CALL", "CHECKPOINT", "CLOSE", "CLUSTER",
1492 "COMMENT", "COMMIT", "COPY", "CREATE", "DEALLOCATE", "DECLARE",
1493 "DELETE FROM", "DISCARD", "DO", "DROP", "END", "EXECUTE", "EXPLAIN",
1494 "FETCH", "GRANT", "IMPORT FOREIGN SCHEMA", "INSERT INTO", "LISTEN", "LOAD", "LOCK",
1495 "MOVE", "NOTIFY", "PREPARE",
1496 "REASSIGN", "REFRESH MATERIALIZED VIEW", "REINDEX", "RELEASE",
1497 "RESET", "REVOKE", "ROLLBACK",
1498 "SAVEPOINT", "SECURITY LABEL", "SELECT", "SET", "SHOW", "START",
1499 "TABLE", "TRUNCATE", "UNLISTEN", "UPDATE", "VACUUM", "VALUES", "WITH",
1500 NULL
1501 };
1502
1503 /* psql's backslash commands. */
1504 static const char *const backslash_commands[] = {
1505 "\\a",
1506 "\\connect", "\\conninfo", "\\C", "\\cd", "\\copy",
1507 "\\copyright", "\\crosstabview",
1508 "\\d", "\\da", "\\dA", "\\dAc", "\\dAf", "\\dAo", "\\dAp",
1509 "\\db", "\\dc", "\\dC", "\\dd", "\\ddp", "\\dD",
1510 "\\des", "\\det", "\\deu", "\\dew", "\\dE", "\\df",
1511 "\\dF", "\\dFd", "\\dFp", "\\dFt", "\\dg", "\\di", "\\dl", "\\dL",
1512 "\\dm", "\\dn", "\\do", "\\dO", "\\dp", "\\dP", "\\dPi", "\\dPt",
1513 "\\drds", "\\dRs", "\\dRp", "\\ds", "\\dS",
1514 "\\dt", "\\dT", "\\dv", "\\du", "\\dx", "\\dX", "\\dy",
1515 "\\e", "\\echo", "\\ef", "\\elif", "\\else", "\\encoding",
1516 "\\endif", "\\errverbose", "\\ev",
1517 "\\f",
1518 "\\g", "\\gdesc", "\\gexec", "\\gset", "\\gx",
1519 "\\h", "\\help", "\\H",
1520 "\\i", "\\if", "\\ir",
1521 "\\l", "\\lo_import", "\\lo_export", "\\lo_list", "\\lo_unlink",
1522 "\\o",
1523 "\\p", "\\password", "\\prompt", "\\pset",
1524 "\\q", "\\qecho",
1525 "\\r",
1526 "\\s", "\\set", "\\setenv", "\\sf", "\\sv",
1527 "\\t", "\\T", "\\timing",
1528 "\\unset",
1529 "\\x",
1530 "\\w", "\\warn", "\\watch",
1531 "\\z",
1532 "\\!", "\\?",
1533 NULL
1534 };
1535
1536 /*
1537 * Temporary workaround for a bug in recent (2019) libedit: it incorrectly
1538 * de-escapes the input "text", causing us to fail to recognize backslash
1539 * commands. So get the string to look at from rl_line_buffer instead.
1540 */
1541 char *text_copy = pnstrdup(rl_line_buffer + start, end - start);
1542 text = text_copy;
1543
1544 /* Remember last char of the given input word. */
1545 completion_last_char = (end > start) ? text[end - start - 1] : '\0';
1546
1547 /* We usually want the append character to be a space. */
1548 #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
1549 rl_completion_append_character = ' ';
1550 #endif
1551
1552 /* Clear a few things. */
1553 completion_charp = NULL;
1554 completion_charpp = NULL;
1555 completion_info_charp = NULL;
1556 completion_info_charp2 = NULL;
1557
1558 /*
1559 * Scan the input line to extract the words before our current position.
1560 * According to those we'll make some smart decisions on what the user is
1561 * probably intending to type.
1562 */
1563 previous_words = get_previous_words(start,
1564 &words_buffer,
1565 &previous_words_count);
1566
1567 /* If current word is a backslash command, offer completions for that */
1568 if (text[0] == '\\')
1569 COMPLETE_WITH_LIST_CS(backslash_commands);
1570
1571 /* If current word is a variable interpolation, handle that case */
1572 else if (text[0] == ':' && text[1] != ':')
1573 {
1574 if (text[1] == '\'')
1575 matches = complete_from_variables(text, ":'", "'", true);
1576 else if (text[1] == '"')
1577 matches = complete_from_variables(text, ":\"", "\"", true);
1578 else
1579 matches = complete_from_variables(text, ":", "", true);
1580 }
1581
1582 /* If no previous word, suggest one of the basic sql commands */
1583 else if (previous_words_count == 0)
1584 COMPLETE_WITH_LIST(sql_commands);
1585
1586 /* CREATE */
1587 /* complete with something you can create */
1588 else if (TailMatches("CREATE"))
1589 matches = rl_completion_matches(text, create_command_generator);
1590
1591 /* complete with something you can create or replace */
1592 else if (TailMatches("CREATE", "OR", "REPLACE"))
1593 COMPLETE_WITH("FUNCTION", "PROCEDURE", "LANGUAGE", "RULE", "VIEW",
1594 "AGGREGATE", "TRANSFORM", "TRIGGER");
1595
1596 /* DROP, but not DROP embedded in other commands */
1597 /* complete with something you can drop */
1598 else if (Matches("DROP"))
1599 matches = rl_completion_matches(text, drop_command_generator);
1600
1601 /* ALTER */
1602
1603 /* ALTER TABLE */
1604 else if (Matches("ALTER", "TABLE"))
1605 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables,
1606 "UNION SELECT 'ALL IN TABLESPACE'");
1607
1608 /* ALTER something */
1609 else if (Matches("ALTER"))
1610 matches = rl_completion_matches(text, alter_command_generator);
1611 /* ALTER TABLE,INDEX,MATERIALIZED VIEW ALL IN TABLESPACE xxx */
1612 else if (TailMatches("ALL", "IN", "TABLESPACE", MatchAny))
1613 COMPLETE_WITH("SET TABLESPACE", "OWNED BY");
1614 /* ALTER TABLE,INDEX,MATERIALIZED VIEW ALL IN TABLESPACE xxx OWNED BY */
1615 else if (TailMatches("ALL", "IN", "TABLESPACE", MatchAny, "OWNED", "BY"))
1616 COMPLETE_WITH_QUERY(Query_for_list_of_roles);
1617 /* ALTER TABLE,INDEX,MATERIALIZED VIEW ALL IN TABLESPACE xxx OWNED BY xxx */
1618 else if (TailMatches("ALL", "IN", "TABLESPACE", MatchAny, "OWNED", "BY", MatchAny))
1619 COMPLETE_WITH("SET TABLESPACE");
1620 /* ALTER AGGREGATE,FUNCTION,PROCEDURE,ROUTINE <name> */
1621 else if (Matches("ALTER", "AGGREGATE|FUNCTION|PROCEDURE|ROUTINE", MatchAny))
1622 COMPLETE_WITH("(");
1623 /* ALTER AGGREGATE <name> (...) */
1624 else if (Matches("ALTER", "AGGREGATE", MatchAny, MatchAny))
1625 {
1626 if (ends_with(prev_wd, ')'))
1627 COMPLETE_WITH("OWNER TO", "RENAME TO", "SET SCHEMA");
1628 else
1629 COMPLETE_WITH_FUNCTION_ARG(prev2_wd);
1630 }
1631 /* ALTER FUNCTION,PROCEDURE,ROUTINE <name> (...) */
1632 else if (Matches("ALTER", "FUNCTION|PROCEDURE|ROUTINE", MatchAny, MatchAny))
1633 {
1634 if (ends_with(prev_wd, ')'))
1635 COMPLETE_WITH("OWNER TO", "RENAME TO", "SET SCHEMA",
1636 "DEPENDS ON EXTENSION", "NO DEPENDS ON EXTENSION");
1637 else
1638 COMPLETE_WITH_FUNCTION_ARG(prev2_wd);
1639 }
1640
1641 /* ALTER PUBLICATION <name> */
1642 else if (Matches("ALTER", "PUBLICATION", MatchAny))
1643 COMPLETE_WITH("ADD TABLE", "DROP TABLE", "OWNER TO", "RENAME TO", "SET");
1644 /* ALTER PUBLICATION <name> SET */
1645 else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET"))
1646 COMPLETE_WITH("(", "TABLE");
1647 /* ALTER PUBLICATION <name> SET ( */
1648 else if (HeadMatches("ALTER", "PUBLICATION", MatchAny) && TailMatches("SET", "("))
1649 COMPLETE_WITH("publish", "publish_via_partition_root");
1650 /* ALTER SUBSCRIPTION <name> */
1651 else if (Matches("ALTER", "SUBSCRIPTION", MatchAny))
1652 COMPLETE_WITH("CONNECTION", "ENABLE", "DISABLE", "OWNER TO",
1653 "RENAME TO", "REFRESH PUBLICATION", "SET",
1654 "ADD PUBLICATION", "DROP PUBLICATION");
1655 /* ALTER SUBSCRIPTION <name> REFRESH PUBLICATION */
1656 else if (HeadMatches("ALTER", "SUBSCRIPTION", MatchAny) &&
1657 TailMatches("REFRESH", "PUBLICATION"))
1658 COMPLETE_WITH("WITH (");
1659 /* ALTER SUBSCRIPTION <name> REFRESH PUBLICATION WITH ( */
1660 else if (HeadMatches("ALTER", "SUBSCRIPTION", MatchAny) &&
1661 TailMatches("REFRESH", "PUBLICATION", "WITH", "("))
1662 COMPLETE_WITH("copy_data");
1663 /* ALTER SUBSCRIPTION <name> SET */
1664 else if (Matches("ALTER", "SUBSCRIPTION", MatchAny, "SET"))
1665 COMPLETE_WITH("(", "PUBLICATION");
1666 /* ALTER SUBSCRIPTION <name> SET ( */
1667 else if (HeadMatches("ALTER", "SUBSCRIPTION", MatchAny) && TailMatches("SET", "("))
1668 COMPLETE_WITH("binary", "slot_name", "streaming", "synchronous_commit");
1669 /* ALTER SUBSCRIPTION <name> SET PUBLICATION */
1670 else if (HeadMatches("ALTER", "SUBSCRIPTION", MatchAny) && TailMatches("SET", "PUBLICATION"))
1671 {
1672 /* complete with nothing here as this refers to remote publications */
1673 }
1674 /* ALTER SUBSCRIPTION <name> ADD|DROP|SET PUBLICATION <name> */
1675 else if (HeadMatches("ALTER", "SUBSCRIPTION", MatchAny) &&
1676 TailMatches("ADD|DROP|SET", "PUBLICATION", MatchAny))
1677 COMPLETE_WITH("WITH (");
1678 /* ALTER SUBSCRIPTION <name> ADD|DROP|SET PUBLICATION <name> WITH ( */
1679 else if (HeadMatches("ALTER", "SUBSCRIPTION", MatchAny) &&
1680 TailMatches("ADD|DROP|SET", "PUBLICATION", MatchAny, "WITH", "("))
1681 COMPLETE_WITH("copy_data", "refresh");
1682
1683 /* ALTER SCHEMA <name> */
1684 else if (Matches("ALTER", "SCHEMA", MatchAny))
1685 COMPLETE_WITH("OWNER TO", "RENAME TO");
1686
1687 /* ALTER COLLATION <name> */
1688 else if (Matches("ALTER", "COLLATION", MatchAny))
1689 COMPLETE_WITH("OWNER TO", "RENAME TO", "SET SCHEMA");
1690
1691 /* ALTER CONVERSION <name> */
1692 else if (Matches("ALTER", "CONVERSION", MatchAny))
1693 COMPLETE_WITH("OWNER TO", "RENAME TO", "SET SCHEMA");
1694
1695 /* ALTER DATABASE <name> */
1696 else if (Matches("ALTER", "DATABASE", MatchAny))
1697 COMPLETE_WITH("RESET", "SET", "OWNER TO", "RENAME TO",
1698 "IS_TEMPLATE", "ALLOW_CONNECTIONS",
1699 "CONNECTION LIMIT");
1700
1701 /* ALTER DATABASE <name> SET TABLESPACE */
1702 else if (Matches("ALTER", "DATABASE", MatchAny, "SET", "TABLESPACE"))
1703 COMPLETE_WITH_QUERY(Query_for_list_of_tablespaces);
1704
1705 /* ALTER EVENT TRIGGER */
1706 else if (Matches("ALTER", "EVENT", "TRIGGER"))
1707 COMPLETE_WITH_QUERY(Query_for_list_of_event_triggers);
1708
1709 /* ALTER EVENT TRIGGER <name> */
1710 else if (Matches("ALTER", "EVENT", "TRIGGER", MatchAny))
1711 COMPLETE_WITH("DISABLE", "ENABLE", "OWNER TO", "RENAME TO");
1712
1713 /* ALTER EVENT TRIGGER <name> ENABLE */
1714 else if (Matches("ALTER", "EVENT", "TRIGGER", MatchAny, "ENABLE"))
1715 COMPLETE_WITH("REPLICA", "ALWAYS");
1716
1717 /* ALTER EXTENSION <name> */
1718 else if (Matches("ALTER", "EXTENSION", MatchAny))
1719 COMPLETE_WITH("ADD", "DROP", "UPDATE", "SET SCHEMA");
1720
1721 /* ALTER EXTENSION <name> UPDATE */
1722 else if (Matches("ALTER", "EXTENSION", MatchAny, "UPDATE"))
1723 {
1724 completion_info_charp = prev2_wd;
1725 COMPLETE_WITH_QUERY(Query_for_list_of_available_extension_versions_with_TO);
1726 }
1727
1728 /* ALTER EXTENSION <name> UPDATE TO */
1729 else if (Matches("ALTER", "EXTENSION", MatchAny, "UPDATE", "TO"))
1730 {
1731 completion_info_charp = prev3_wd;
1732 COMPLETE_WITH_QUERY(Query_for_list_of_available_extension_versions);
1733 }
1734
1735 /* ALTER FOREIGN */
1736 else if (Matches("ALTER", "FOREIGN"))
1737 COMPLETE_WITH("DATA WRAPPER", "TABLE");
1738
1739 /* ALTER FOREIGN DATA WRAPPER <name> */
1740 else if (Matches("ALTER", "FOREIGN", "DATA", "WRAPPER", MatchAny))
1741 COMPLETE_WITH("HANDLER", "VALIDATOR", "OPTIONS", "OWNER TO", "RENAME TO");
1742
1743 /* ALTER FOREIGN TABLE <name> */
1744 else if (Matches("ALTER", "FOREIGN", "TABLE", MatchAny))
1745 COMPLETE_WITH("ADD", "ALTER", "DISABLE TRIGGER", "DROP", "ENABLE",
1746 "INHERIT", "NO INHERIT", "OPTIONS", "OWNER TO",
1747 "RENAME", "SET", "VALIDATE CONSTRAINT");
1748
1749 /* ALTER INDEX */
1750 else if (Matches("ALTER", "INDEX"))
1751 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_indexes,
1752 "UNION SELECT 'ALL IN TABLESPACE'");
1753 /* ALTER INDEX <name> */
1754 else if (Matches("ALTER", "INDEX", MatchAny))
1755 COMPLETE_WITH("ALTER COLUMN", "OWNER TO", "RENAME TO", "SET",
1756 "RESET", "ATTACH PARTITION",
1757 "DEPENDS ON EXTENSION", "NO DEPENDS ON EXTENSION");
1758 else if (Matches("ALTER", "INDEX", MatchAny, "ATTACH"))
1759 COMPLETE_WITH("PARTITION");
1760 else if (Matches("ALTER", "INDEX", MatchAny, "ATTACH", "PARTITION"))
1761 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_indexes, NULL);
1762 /* ALTER INDEX <name> ALTER */
1763 else if (Matches("ALTER", "INDEX", MatchAny, "ALTER"))
1764 COMPLETE_WITH("COLUMN");
1765 /* ALTER INDEX <name> ALTER COLUMN */
1766 else if (Matches("ALTER", "INDEX", MatchAny, "ALTER", "COLUMN"))
1767 {
1768 completion_info_charp = prev3_wd;
1769 COMPLETE_WITH_QUERY(Query_for_list_of_attribute_numbers);
1770 }
1771 /* ALTER INDEX <name> ALTER COLUMN <colnum> */
1772 else if (Matches("ALTER", "INDEX", MatchAny, "ALTER", "COLUMN", MatchAny))
1773 COMPLETE_WITH("SET STATISTICS");
1774 /* ALTER INDEX <name> ALTER COLUMN <colnum> SET */
1775 else if (Matches("ALTER", "INDEX", MatchAny, "ALTER", "COLUMN", MatchAny, "SET"))
1776 COMPLETE_WITH("STATISTICS");
1777 /* ALTER INDEX <name> ALTER COLUMN <colnum> SET STATISTICS */
1778 else if (Matches("ALTER", "INDEX", MatchAny, "ALTER", "COLUMN", MatchAny, "SET", "STATISTICS"))
1779 {
1780 /* Enforce no completion here, as an integer has to be specified */
1781 }
1782 /* ALTER INDEX <name> SET */
1783 else if (Matches("ALTER", "INDEX", MatchAny, "SET"))
1784 COMPLETE_WITH("(", "TABLESPACE");
1785 /* ALTER INDEX <name> RESET */
1786 else if (Matches("ALTER", "INDEX", MatchAny, "RESET"))
1787 COMPLETE_WITH("(");
1788 /* ALTER INDEX <foo> SET|RESET ( */
1789 else if (Matches("ALTER", "INDEX", MatchAny, "RESET", "("))
1790 COMPLETE_WITH("fillfactor",
1791 "deduplicate_items", /* BTREE */
1792 "fastupdate", "gin_pending_list_limit", /* GIN */
1793 "buffering", /* GiST */
1794 "pages_per_range", "autosummarize" /* BRIN */
1795 );
1796 else if (Matches("ALTER", "INDEX", MatchAny, "SET", "("))
1797 COMPLETE_WITH("fillfactor =",
1798 "deduplicate_items =", /* BTREE */
1799 "fastupdate =", "gin_pending_list_limit =", /* GIN */
1800 "buffering =", /* GiST */
1801 "pages_per_range =", "autosummarize =" /* BRIN */
1802 );
1803 else if (Matches("ALTER", "INDEX", MatchAny, "NO", "DEPENDS"))
1804 COMPLETE_WITH("ON EXTENSION");
1805 else if (Matches("ALTER", "INDEX", MatchAny, "DEPENDS"))
1806 COMPLETE_WITH("ON EXTENSION");
1807
1808 /* ALTER LANGUAGE <name> */
1809 else if (Matches("ALTER", "LANGUAGE", MatchAny))
1810 COMPLETE_WITH("OWNER TO", "RENAME TO");
1811
1812 /* ALTER LARGE OBJECT <oid> */
1813 else if (Matches("ALTER", "LARGE", "OBJECT", MatchAny))
1814 COMPLETE_WITH("OWNER TO");
1815
1816 /* ALTER MATERIALIZED VIEW */
1817 else if (Matches("ALTER", "MATERIALIZED", "VIEW"))
1818 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_matviews,
1819 "UNION SELECT 'ALL IN TABLESPACE'");
1820
1821 /* ALTER USER,ROLE <name> */
1822 else if (Matches("ALTER", "USER|ROLE", MatchAny) &&
1823 !TailMatches("USER", "MAPPING"))
1824 COMPLETE_WITH("BYPASSRLS", "CONNECTION LIMIT", "CREATEDB", "CREATEROLE",
1825 "ENCRYPTED PASSWORD", "INHERIT", "LOGIN", "NOBYPASSRLS",
1826 "NOCREATEDB", "NOCREATEROLE", "NOINHERIT",
1827 "NOLOGIN", "NOREPLICATION", "NOSUPERUSER", "PASSWORD",
1828 "RENAME TO", "REPLICATION", "RESET", "SET", "SUPERUSER",
1829 "VALID UNTIL", "WITH");
1830
1831 /* ALTER USER,ROLE <name> WITH */
1832 else if (Matches("ALTER", "USER|ROLE", MatchAny, "WITH"))
1833 /* Similar to the above, but don't complete "WITH" again. */
1834 COMPLETE_WITH("BYPASSRLS", "CONNECTION LIMIT", "CREATEDB", "CREATEROLE",
1835 "ENCRYPTED PASSWORD", "INHERIT", "LOGIN", "NOBYPASSRLS",
1836 "NOCREATEDB", "NOCREATEROLE", "NOINHERIT",
1837 "NOLOGIN", "NOREPLICATION", "NOSUPERUSER", "PASSWORD",
1838 "RENAME TO", "REPLICATION", "RESET", "SET", "SUPERUSER",
1839 "VALID UNTIL");
1840
1841 /* ALTER DEFAULT PRIVILEGES */
1842 else if (Matches("ALTER", "DEFAULT", "PRIVILEGES"))
1843 COMPLETE_WITH("FOR ROLE", "IN SCHEMA");
1844 /* ALTER DEFAULT PRIVILEGES FOR */
1845 else if (Matches("ALTER", "DEFAULT", "PRIVILEGES", "FOR"))
1846 COMPLETE_WITH("ROLE");
1847 /* ALTER DEFAULT PRIVILEGES IN */
1848 else if (Matches("ALTER", "DEFAULT", "PRIVILEGES", "IN"))
1849 COMPLETE_WITH("SCHEMA");
1850 /* ALTER DEFAULT PRIVILEGES FOR ROLE|USER ... */
1851 else if (Matches("ALTER", "DEFAULT", "PRIVILEGES", "FOR", "ROLE|USER",
1852 MatchAny))
1853 COMPLETE_WITH("GRANT", "REVOKE", "IN SCHEMA");
1854 /* ALTER DEFAULT PRIVILEGES IN SCHEMA ... */
1855 else if (Matches("ALTER", "DEFAULT", "PRIVILEGES", "IN", "SCHEMA",
1856 MatchAny))
1857 COMPLETE_WITH("GRANT", "REVOKE", "FOR ROLE");
1858 /* ALTER DEFAULT PRIVILEGES IN SCHEMA ... FOR */
1859 else if (Matches("ALTER", "DEFAULT", "PRIVILEGES", "IN", "SCHEMA",
1860 MatchAny, "FOR"))
1861 COMPLETE_WITH("ROLE");
1862 /* ALTER DEFAULT PRIVILEGES FOR ROLE|USER ... IN SCHEMA ... */
1863 /* ALTER DEFAULT PRIVILEGES IN SCHEMA ... FOR ROLE|USER ... */
1864 else if (Matches("ALTER", "DEFAULT", "PRIVILEGES", "FOR", "ROLE|USER",
1865 MatchAny, "IN", "SCHEMA", MatchAny) ||
1866 Matches("ALTER", "DEFAULT", "PRIVILEGES", "IN", "SCHEMA",
1867 MatchAny, "FOR", "ROLE|USER", MatchAny))
1868 COMPLETE_WITH("GRANT", "REVOKE");
1869 /* ALTER DOMAIN <name> */
1870 else if (Matches("ALTER", "DOMAIN", MatchAny))
1871 COMPLETE_WITH("ADD", "DROP", "OWNER TO", "RENAME", "SET",
1872 "VALIDATE CONSTRAINT");
1873 /* ALTER DOMAIN <sth> DROP */
1874 else if (Matches("ALTER", "DOMAIN", MatchAny, "DROP"))
1875 COMPLETE_WITH("CONSTRAINT", "DEFAULT", "NOT NULL");
1876 /* ALTER DOMAIN <sth> DROP|RENAME|VALIDATE CONSTRAINT */
1877 else if (Matches("ALTER", "DOMAIN", MatchAny, "DROP|RENAME|VALIDATE", "CONSTRAINT"))
1878 {
1879 completion_info_charp = prev3_wd;
1880 COMPLETE_WITH_QUERY(Query_for_constraint_of_type);
1881 }
1882 /* ALTER DOMAIN <sth> RENAME */
1883 else if (Matches("ALTER", "DOMAIN", MatchAny, "RENAME"))
1884 COMPLETE_WITH("CONSTRAINT", "TO");
1885 /* ALTER DOMAIN <sth> RENAME CONSTRAINT <sth> */
1886 else if (Matches("ALTER", "DOMAIN", MatchAny, "RENAME", "CONSTRAINT", MatchAny))
1887 COMPLETE_WITH("TO");
1888
1889 /* ALTER DOMAIN <sth> SET */
1890 else if (Matches("ALTER", "DOMAIN", MatchAny, "SET"))
1891 COMPLETE_WITH("DEFAULT", "NOT NULL", "SCHEMA");
1892 /* ALTER SEQUENCE <name> */
1893 else if (Matches("ALTER", "SEQUENCE", MatchAny))
1894 COMPLETE_WITH("INCREMENT", "MINVALUE", "MAXVALUE", "RESTART", "NO",
1895 "CACHE", "CYCLE", "SET SCHEMA", "OWNED BY", "OWNER TO",
1896 "RENAME TO");
1897 /* ALTER SEQUENCE <name> NO */
1898 else if (Matches("ALTER", "SEQUENCE", MatchAny, "NO"))
1899 COMPLETE_WITH("MINVALUE", "MAXVALUE", "CYCLE");
1900 /* ALTER SERVER <name> */
1901 else if (Matches("ALTER", "SERVER", MatchAny))
1902 COMPLETE_WITH("VERSION", "OPTIONS", "OWNER TO", "RENAME TO");
1903 /* ALTER SERVER <name> VERSION <version> */
1904 else if (Matches("ALTER", "SERVER", MatchAny, "VERSION", MatchAny))
1905 COMPLETE_WITH("OPTIONS");
1906 /* ALTER SYSTEM SET, RESET, RESET ALL */
1907 else if (Matches("ALTER", "SYSTEM"))
1908 COMPLETE_WITH("SET", "RESET");
1909 else if (Matches("ALTER", "SYSTEM", "SET|RESET"))
1910 COMPLETE_WITH_QUERY(Query_for_list_of_alter_system_set_vars);
1911 else if (Matches("ALTER", "SYSTEM", "SET", MatchAny))
1912 COMPLETE_WITH("TO");
1913 /* ALTER VIEW <name> */
1914 else if (Matches("ALTER", "VIEW", MatchAny))
1915 COMPLETE_WITH("ALTER COLUMN", "OWNER TO", "RENAME",
1916 "SET SCHEMA");
1917 /* ALTER VIEW xxx RENAME */
1918 else if (Matches("ALTER", "VIEW", MatchAny, "RENAME"))
1919 COMPLETE_WITH_ATTR(prev2_wd, " UNION SELECT 'COLUMN' UNION SELECT 'TO'");
1920 else if (Matches("ALTER", "VIEW", MatchAny, "ALTER|RENAME", "COLUMN"))
1921 COMPLETE_WITH_ATTR(prev3_wd, "");
1922 /* ALTER VIEW xxx RENAME yyy */
1923 else if (Matches("ALTER", "VIEW", MatchAny, "RENAME", MatchAnyExcept("TO")))
1924 COMPLETE_WITH("TO");
1925 /* ALTER VIEW xxx RENAME COLUMN yyy */
1926 else if (Matches("ALTER", "VIEW", MatchAny, "RENAME", "COLUMN", MatchAnyExcept("TO")))
1927 COMPLETE_WITH("TO");
1928
1929 /* ALTER MATERIALIZED VIEW <name> */
1930 else if (Matches("ALTER", "MATERIALIZED", "VIEW", MatchAny))
1931 COMPLETE_WITH("ALTER COLUMN", "CLUSTER ON", "DEPENDS ON EXTENSION",
1932 "NO DEPENDS ON EXTENSION", "OWNER TO", "RENAME",
1933 "RESET (", "SET");
1934 /* ALTER MATERIALIZED VIEW xxx RENAME */
1935 else if (Matches("ALTER", "MATERIALIZED", "VIEW", MatchAny, "RENAME"))
1936 COMPLETE_WITH_ATTR(prev2_wd, " UNION SELECT 'COLUMN' UNION SELECT 'TO'");
1937 else if (Matches("ALTER", "MATERIALIZED", "VIEW", MatchAny, "ALTER|RENAME", "COLUMN"))
1938 COMPLETE_WITH_ATTR(prev3_wd, "");
1939 /* ALTER MATERIALIZED VIEW xxx RENAME yyy */
1940 else if (Matches("ALTER", "MATERIALIZED", "VIEW", MatchAny, "RENAME", MatchAnyExcept("TO")))
1941 COMPLETE_WITH("TO");
1942 /* ALTER MATERIALIZED VIEW xxx RENAME COLUMN yyy */
1943 else if (Matches("ALTER", "MATERIALIZED", "VIEW", MatchAny, "RENAME", "COLUMN", MatchAnyExcept("TO")))
1944 COMPLETE_WITH("TO");
1945 /* ALTER MATERIALIZED VIEW xxx SET */
1946 else if (Matches("ALTER", "MATERIALIZED", "VIEW", MatchAny, "SET"))
1947 COMPLETE_WITH("(", "SCHEMA", "TABLESPACE", "WITHOUT CLUSTER");
1948 /* ALTER POLICY <name> */
1949 else if (Matches("ALTER", "POLICY"))
1950 COMPLETE_WITH_QUERY(Query_for_list_of_policies);
1951 /* ALTER POLICY <name> ON */
1952 else if (Matches("ALTER", "POLICY", MatchAny))
1953 COMPLETE_WITH("ON");
1954 /* ALTER POLICY <name> ON <table> */
1955 else if (Matches("ALTER", "POLICY", MatchAny, "ON"))
1956 {
1957 completion_info_charp = prev2_wd;
1958 COMPLETE_WITH_QUERY(Query_for_list_of_tables_for_policy);
1959 }
1960 /* ALTER POLICY <name> ON <table> - show options */
1961 else if (Matches("ALTER", "POLICY", MatchAny, "ON", MatchAny))
1962 COMPLETE_WITH("RENAME TO", "TO", "USING (", "WITH CHECK (");
1963 /* ALTER POLICY <name> ON <table> TO <role> */
1964 else if (Matches("ALTER", "POLICY", MatchAny, "ON", MatchAny, "TO"))
1965 COMPLETE_WITH_QUERY(Query_for_list_of_grant_roles);
1966 /* ALTER POLICY <name> ON <table> USING ( */
1967 else if (Matches("ALTER", "POLICY", MatchAny, "ON", MatchAny, "USING"))
1968 COMPLETE_WITH("(");
1969 /* ALTER POLICY <name> ON <table> WITH CHECK ( */
1970 else if (Matches("ALTER", "POLICY", MatchAny, "ON", MatchAny, "WITH", "CHECK"))
1971 COMPLETE_WITH("(");
1972
1973 /* ALTER RULE <name>, add ON */
1974 else if (Matches("ALTER", "RULE", MatchAny))
1975 COMPLETE_WITH("ON");
1976
1977 /* If we have ALTER RULE <name> ON, then add the correct tablename */
1978 else if (Matches("ALTER", "RULE", MatchAny, "ON"))
1979 {
1980 completion_info_charp = prev2_wd;
1981 COMPLETE_WITH_QUERY(Query_for_list_of_tables_for_rule);
1982 }
1983
1984 /* ALTER RULE <name> ON <name> */
1985 else if (Matches("ALTER", "RULE", MatchAny, "ON", MatchAny))
1986 COMPLETE_WITH("RENAME TO");
1987
1988 /* ALTER STATISTICS <name> */
1989 else if (Matches("ALTER", "STATISTICS", MatchAny))
1990 COMPLETE_WITH("OWNER TO", "RENAME TO", "SET SCHEMA", "SET STATISTICS");
1991
1992 /* ALTER TRIGGER <name>, add ON */
1993 else if (Matches("ALTER", "TRIGGER", MatchAny))
1994 COMPLETE_WITH("ON");
1995
1996 else if (Matches("ALTER", "TRIGGER", MatchAny, MatchAny))
1997 {
1998 completion_info_charp = prev2_wd;
1999 COMPLETE_WITH_QUERY(Query_for_list_of_tables_for_trigger);
2000 }
2001
2002 /*
2003 * If we have ALTER TRIGGER <sth> ON, then add the correct tablename
2004 */
2005 else if (Matches("ALTER", "TRIGGER", MatchAny, "ON"))
2006 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, NULL);
2007
2008 /* ALTER TRIGGER <name> ON <name> */
2009 else if (Matches("ALTER", "TRIGGER", MatchAny, "ON", MatchAny))
2010 COMPLETE_WITH("RENAME TO", "DEPENDS ON EXTENSION",
2011 "NO DEPENDS ON EXTENSION");
2012
2013 /*
2014 * If we detect ALTER TABLE <name>, suggest sub commands
2015 */
2016 else if (Matches("ALTER", "TABLE", MatchAny))
2017 COMPLETE_WITH("ADD", "ALTER", "CLUSTER ON", "DISABLE", "DROP",
2018 "ENABLE", "INHERIT", "NO", "RENAME", "RESET",
2019 "OWNER TO", "SET", "VALIDATE CONSTRAINT",
2020 "REPLICA IDENTITY", "ATTACH PARTITION",
2021 "DETACH PARTITION", "FORCE ROW LEVEL SECURITY");
2022 /* ALTER TABLE xxx ENABLE */
2023 else if (Matches("ALTER", "TABLE", MatchAny, "ENABLE"))
2024 COMPLETE_WITH("ALWAYS", "REPLICA", "ROW LEVEL SECURITY", "RULE",
2025 "TRIGGER");
2026 else if (Matches("ALTER", "TABLE", MatchAny, "ENABLE", "REPLICA|ALWAYS"))
2027 COMPLETE_WITH("RULE", "TRIGGER");
2028 else if (Matches("ALTER", "TABLE", MatchAny, "ENABLE", "RULE"))
2029 {
2030 completion_info_charp = prev3_wd;
2031 COMPLETE_WITH_QUERY(Query_for_rule_of_table);
2032 }
2033 else if (Matches("ALTER", "TABLE", MatchAny, "ENABLE", MatchAny, "RULE"))
2034 {
2035 completion_info_charp = prev4_wd;
2036 COMPLETE_WITH_QUERY(Query_for_rule_of_table);
2037 }
2038 else if (Matches("ALTER", "TABLE", MatchAny, "ENABLE", "TRIGGER"))
2039 {
2040 completion_info_charp = prev3_wd;
2041 COMPLETE_WITH_QUERY(Query_for_trigger_of_table);
2042 }
2043 else if (Matches("ALTER", "TABLE", MatchAny, "ENABLE", MatchAny, "TRIGGER"))
2044 {
2045 completion_info_charp = prev4_wd;
2046 COMPLETE_WITH_QUERY(Query_for_trigger_of_table);
2047 }
2048 /* ALTER TABLE xxx INHERIT */
2049 else if (Matches("ALTER", "TABLE", MatchAny, "INHERIT"))
2050 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, "");
2051 /* ALTER TABLE xxx NO */
2052 else if (Matches("ALTER", "TABLE", MatchAny, "NO"))
2053 COMPLETE_WITH("FORCE ROW LEVEL SECURITY", "INHERIT");
2054 /* ALTER TABLE xxx NO INHERIT */
2055 else if (Matches("ALTER", "TABLE", MatchAny, "NO", "INHERIT"))
2056 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, "");
2057 /* ALTER TABLE xxx DISABLE */
2058 else if (Matches("ALTER", "TABLE", MatchAny, "DISABLE"))
2059 COMPLETE_WITH("ROW LEVEL SECURITY", "RULE", "TRIGGER");
2060 else if (Matches("ALTER", "TABLE", MatchAny, "DISABLE", "RULE"))
2061 {
2062 completion_info_charp = prev3_wd;
2063 COMPLETE_WITH_QUERY(Query_for_rule_of_table);
2064 }
2065 else if (Matches("ALTER", "TABLE", MatchAny, "DISABLE", "TRIGGER"))
2066 {
2067 completion_info_charp = prev3_wd;
2068 COMPLETE_WITH_QUERY(Query_for_trigger_of_table);
2069 }
2070
2071 /* ALTER TABLE xxx ALTER */
2072 else if (Matches("ALTER", "TABLE", MatchAny, "ALTER"))
2073 COMPLETE_WITH_ATTR(prev2_wd, " UNION SELECT 'COLUMN' UNION SELECT 'CONSTRAINT'");
2074
2075 /* ALTER TABLE xxx RENAME */
2076 else if (Matches("ALTER", "TABLE", MatchAny, "RENAME"))
2077 COMPLETE_WITH_ATTR(prev2_wd, " UNION SELECT 'COLUMN' UNION SELECT 'CONSTRAINT' UNION SELECT 'TO'");
2078 else if (Matches("ALTER", "TABLE", MatchAny, "ALTER|RENAME", "COLUMN"))
2079 COMPLETE_WITH_ATTR(prev3_wd, "");
2080
2081 /* ALTER TABLE xxx RENAME yyy */
2082 else if (Matches("ALTER", "TABLE", MatchAny, "RENAME", MatchAnyExcept("CONSTRAINT|TO")))
2083 COMPLETE_WITH("TO");
2084
2085 /* ALTER TABLE xxx RENAME COLUMN/CONSTRAINT yyy */
2086 else if (Matches("ALTER", "TABLE", MatchAny, "RENAME", "COLUMN|CONSTRAINT", MatchAnyExcept("TO")))
2087 COMPLETE_WITH("TO");
2088
2089 /* If we have ALTER TABLE <sth> DROP, provide COLUMN or CONSTRAINT */
2090 else if (Matches("ALTER", "TABLE", MatchAny, "DROP"))
2091 COMPLETE_WITH("COLUMN", "CONSTRAINT");
2092 /* If we have ALTER TABLE <sth> DROP COLUMN, provide list of columns */
2093 else if (Matches("ALTER", "TABLE", MatchAny, "DROP", "COLUMN"))
2094 COMPLETE_WITH_ATTR(prev3_wd, "");
2095
2096 /*
2097 * If we have ALTER TABLE <sth> ALTER|DROP|RENAME|VALIDATE CONSTRAINT,
2098 * provide list of constraints
2099 */
2100 else if (Matches("ALTER", "TABLE", MatchAny, "ALTER|DROP|RENAME|VALIDATE", "CONSTRAINT"))
2101 {
2102 completion_info_charp = prev3_wd;
2103 COMPLETE_WITH_QUERY(Query_for_constraint_of_table);
2104 }
2105 /* ALTER TABLE ALTER [COLUMN] <foo> */
2106 else if (Matches("ALTER", "TABLE", MatchAny, "ALTER", "COLUMN", MatchAny) ||
2107 Matches("ALTER", "TABLE", MatchAny, "ALTER", MatchAny))
2108 COMPLETE_WITH("TYPE", "SET", "RESET", "RESTART", "ADD", "DROP");
2109 /* ALTER TABLE ALTER [COLUMN] <foo> SET */
2110 else if (Matches("ALTER", "TABLE", MatchAny, "ALTER", "COLUMN", MatchAny, "SET") ||
2111 Matches("ALTER", "TABLE", MatchAny, "ALTER", MatchAny, "SET"))
2112 COMPLETE_WITH("(", "COMPRESSION", "DEFAULT", "NOT NULL", "STATISTICS", "STORAGE");
2113 /* ALTER TABLE ALTER [COLUMN] <foo> SET ( */
2114 else if (Matches("ALTER", "TABLE", MatchAny, "ALTER", "COLUMN", MatchAny, "SET", "(") ||
2115 Matches("ALTER", "TABLE", MatchAny, "ALTER", MatchAny, "SET", "("))
2116 COMPLETE_WITH("n_distinct", "n_distinct_inherited");
2117 /* ALTER TABLE ALTER [COLUMN] <foo> SET STORAGE */
2118 else if (Matches("ALTER", "TABLE", MatchAny, "ALTER", "COLUMN", MatchAny, "SET", "STORAGE") ||
2119 Matches("ALTER", "TABLE", MatchAny, "ALTER", MatchAny, "SET", "STORAGE"))
2120 COMPLETE_WITH("PLAIN", "EXTERNAL", "EXTENDED", "MAIN");
2121 /* ALTER TABLE ALTER [COLUMN] <foo> SET STATISTICS */
2122 else if (Matches("ALTER", "TABLE", MatchAny, "ALTER", "COLUMN", MatchAny, "SET", "STATISTICS") ||
2123 Matches("ALTER", "TABLE", MatchAny, "ALTER", MatchAny, "SET", "STATISTICS"))
2124 {
2125 /* Enforce no completion here, as an integer has to be specified */
2126 }
2127 /* ALTER TABLE ALTER [COLUMN] <foo> DROP */
2128 else if (Matches("ALTER", "TABLE", MatchAny, "ALTER", "COLUMN", MatchAny, "DROP") ||
2129 Matches("ALTER", "TABLE", MatchAny, "ALTER", MatchAny, "DROP"))
2130 COMPLETE_WITH("DEFAULT", "EXPRESSION", "IDENTITY", "NOT NULL");
2131 else if (Matches("ALTER", "TABLE", MatchAny, "CLUSTER"))
2132 COMPLETE_WITH("ON");
2133 else if (Matches("ALTER", "TABLE", MatchAny, "CLUSTER", "ON"))
2134 {
2135 completion_info_charp = prev3_wd;
2136 COMPLETE_WITH_QUERY(Query_for_index_of_table);
2137 }
2138 /* If we have ALTER TABLE <sth> SET, provide list of attributes and '(' */
2139 else if (Matches("ALTER", "TABLE", MatchAny, "SET"))
2140 COMPLETE_WITH("(", "LOGGED", "SCHEMA", "TABLESPACE", "UNLOGGED",
2141 "WITH", "WITHOUT");
2142
2143 /*
2144 * If we have ALTER TABLE <sth> SET TABLESPACE provide a list of
2145 * tablespaces
2146 */
2147 else if (Matches("ALTER", "TABLE", MatchAny, "SET", "TABLESPACE"))
2148 COMPLETE_WITH_QUERY(Query_for_list_of_tablespaces);
2149 /* If we have ALTER TABLE <sth> SET WITHOUT provide CLUSTER or OIDS */
2150 else if (Matches("ALTER", "TABLE", MatchAny, "SET", "WITHOUT"))
2151 COMPLETE_WITH("CLUSTER", "OIDS");
2152 /* ALTER TABLE <foo> RESET */
2153 else if (Matches("ALTER", "TABLE", MatchAny, "RESET"))
2154 COMPLETE_WITH("(");
2155 /* ALTER TABLE <foo> SET|RESET ( */
2156 else if (Matches("ALTER", "TABLE", MatchAny, "SET|RESET", "("))
2157 COMPLETE_WITH_LIST(table_storage_parameters);
2158 else if (Matches("ALTER", "TABLE", MatchAny, "REPLICA", "IDENTITY", "USING", "INDEX"))
2159 {
2160 completion_info_charp = prev5_wd;
2161 COMPLETE_WITH_QUERY(Query_for_index_of_table);
2162 }
2163 else if (Matches("ALTER", "TABLE", MatchAny, "REPLICA", "IDENTITY", "USING"))
2164 COMPLETE_WITH("INDEX");
2165 else if (Matches("ALTER", "TABLE", MatchAny, "REPLICA", "IDENTITY"))
2166 COMPLETE_WITH("FULL", "NOTHING", "DEFAULT", "USING");
2167 else if (Matches("ALTER", "TABLE", MatchAny, "REPLICA"))
2168 COMPLETE_WITH("IDENTITY");
2169
2170 /*
2171 * If we have ALTER TABLE <foo> ATTACH PARTITION, provide a list of
2172 * tables.
2173 */
2174 else if (Matches("ALTER", "TABLE", MatchAny, "ATTACH", "PARTITION"))
2175 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, "");
2176 /* Limited completion support for partition bound specification */
2177 else if (TailMatches("ATTACH", "PARTITION", MatchAny))
2178 COMPLETE_WITH("FOR VALUES", "DEFAULT");
2179 else if (TailMatches("FOR", "VALUES"))
2180 COMPLETE_WITH("FROM (", "IN (", "WITH (");
2181
2182 /*
2183 * If we have ALTER TABLE <foo> DETACH PARTITION, provide a list of
2184 * partitions of <foo>.
2185 */
2186 else if (Matches("ALTER", "TABLE", MatchAny, "DETACH", "PARTITION"))
2187 {
2188 completion_info_charp = prev3_wd;
2189 COMPLETE_WITH_QUERY(Query_for_partition_of_table);
2190 }
2191 else if (Matches("ALTER", "TABLE", MatchAny, "DETACH", "PARTITION", MatchAny))
2192 COMPLETE_WITH("CONCURRENTLY", "FINALIZE");
2193
2194 /* ALTER TABLESPACE <foo> with RENAME TO, OWNER TO, SET, RESET */
2195 else if (Matches("ALTER", "TABLESPACE", MatchAny))
2196 COMPLETE_WITH("RENAME TO", "OWNER TO", "SET", "RESET");
2197 /* ALTER TABLESPACE <foo> SET|RESET */
2198 else if (Matches("ALTER", "TABLESPACE", MatchAny, "SET|RESET"))
2199 COMPLETE_WITH("(");
2200 /* ALTER TABLESPACE <foo> SET|RESET ( */
2201 else if (Matches("ALTER", "TABLESPACE", MatchAny, "SET|RESET", "("))
2202 COMPLETE_WITH("seq_page_cost", "random_page_cost",
2203 "effective_io_concurrency", "maintenance_io_concurrency");
2204
2205 /* ALTER TEXT SEARCH */
2206 else if (Matches("ALTER", "TEXT", "SEARCH"))
2207 COMPLETE_WITH("CONFIGURATION", "DICTIONARY", "PARSER", "TEMPLATE");
2208 else if (Matches("ALTER", "TEXT", "SEARCH", "TEMPLATE|PARSER", MatchAny))
2209 COMPLETE_WITH("RENAME TO", "SET SCHEMA");
2210 else if (Matches("ALTER", "TEXT", "SEARCH", "DICTIONARY", MatchAny))
2211 COMPLETE_WITH("(", "OWNER TO", "RENAME TO", "SET SCHEMA");
2212 else if (Matches("ALTER", "TEXT", "SEARCH", "CONFIGURATION", MatchAny))
2213 COMPLETE_WITH("ADD MAPPING FOR", "ALTER MAPPING",
2214 "DROP MAPPING FOR",
2215 "OWNER TO", "RENAME TO", "SET SCHEMA");
2216
2217 /* complete ALTER TYPE <foo> with actions */
2218 else if (Matches("ALTER", "TYPE", MatchAny))
2219 COMPLETE_WITH("ADD ATTRIBUTE", "ADD VALUE", "ALTER ATTRIBUTE",
2220 "DROP ATTRIBUTE",
2221 "OWNER TO", "RENAME", "SET SCHEMA", "SET (");
2222 /* complete ALTER TYPE <foo> ADD with actions */
2223 else if (Matches("ALTER", "TYPE", MatchAny, "ADD"))
2224 COMPLETE_WITH("ATTRIBUTE", "VALUE");
2225 /* ALTER TYPE <foo> RENAME */
2226 else if (Matches("ALTER", "TYPE", MatchAny, "RENAME"))
2227 COMPLETE_WITH("ATTRIBUTE", "TO", "VALUE");
2228 /* ALTER TYPE xxx RENAME (ATTRIBUTE|VALUE) yyy */
2229 else if (Matches("ALTER", "TYPE", MatchAny, "RENAME", "ATTRIBUTE|VALUE", MatchAny))
2230 COMPLETE_WITH("TO");
2231
2232 /*
2233 * If we have ALTER TYPE <sth> ALTER/DROP/RENAME ATTRIBUTE, provide list
2234 * of attributes
2235 */
2236 else if (Matches("ALTER", "TYPE", MatchAny, "ALTER|DROP|RENAME", "ATTRIBUTE"))
2237 COMPLETE_WITH_ATTR(prev3_wd, "");
2238 /* ALTER TYPE ALTER ATTRIBUTE <foo> */
2239 else if (Matches("ALTER", "TYPE", MatchAny, "ALTER", "ATTRIBUTE", MatchAny))
2240 COMPLETE_WITH("TYPE");
2241 /* complete ALTER GROUP <foo> */
2242 else if (Matches("ALTER", "GROUP", MatchAny))
2243 COMPLETE_WITH("ADD USER", "DROP USER", "RENAME TO");
2244 /* complete ALTER GROUP <foo> ADD|DROP with USER */
2245 else if (Matches("ALTER", "GROUP", MatchAny, "ADD|DROP"))
2246 COMPLETE_WITH("USER");
2247 /* complete ALTER GROUP <foo> ADD|DROP USER with a user name */
2248 else if (Matches("ALTER", "GROUP", MatchAny, "ADD|DROP", "USER"))
2249 COMPLETE_WITH_QUERY(Query_for_list_of_roles);
2250
2251 /*
2252 * If we have ALTER TYPE <sth> RENAME VALUE, provide list of enum values
2253 */
2254 else if (Matches("ALTER", "TYPE", MatchAny, "RENAME", "VALUE"))
2255 COMPLETE_WITH_ENUM_VALUE(prev3_wd);
2256
2257 /*
2258 * ANALYZE [ ( option [, ...] ) ] [ table_and_columns [, ...] ]
2259 * ANALYZE [ VERBOSE ] [ table_and_columns [, ...] ]
2260 */
2261 else if (Matches("ANALYZE"))
2262 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_analyzables,
2263 " UNION SELECT 'VERBOSE'");
2264 else if (HeadMatches("ANALYZE", "(*") &&
2265 !HeadMatches("ANALYZE", "(*)"))
2266 {
2267 /*
2268 * This fires if we're in an unfinished parenthesized option list.
2269 * get_previous_words treats a completed parenthesized option list as
2270 * one word, so the above test is correct.
2271 */
2272 if (ends_with(prev_wd, '(') || ends_with(prev_wd, ','))
2273 COMPLETE_WITH("VERBOSE", "SKIP_LOCKED");
2274 else if (TailMatches("VERBOSE|SKIP_LOCKED"))
2275 COMPLETE_WITH("ON", "OFF");
2276 }
2277 else if (HeadMatches("ANALYZE") && TailMatches("("))
2278 /* "ANALYZE (" should be caught above, so assume we want columns */
2279 COMPLETE_WITH_ATTR(prev2_wd, "");
2280 else if (HeadMatches("ANALYZE"))
2281 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_analyzables, NULL);
2282
2283 /* BEGIN */
2284 else if (Matches("BEGIN"))
2285 COMPLETE_WITH("WORK", "TRANSACTION", "ISOLATION LEVEL", "READ", "DEFERRABLE", "NOT DEFERRABLE");
2286 /* END, ABORT */
2287 else if (Matches("END|ABORT"))
2288 COMPLETE_WITH("AND", "WORK", "TRANSACTION");
2289 /* COMMIT */
2290 else if (Matches("COMMIT"))
2291 COMPLETE_WITH("AND", "WORK", "TRANSACTION", "PREPARED");
2292 /* RELEASE SAVEPOINT */
2293 else if (Matches("RELEASE"))
2294 COMPLETE_WITH("SAVEPOINT");
2295 /* ROLLBACK */
2296 else if (Matches("ROLLBACK"))
2297 COMPLETE_WITH("AND", "WORK", "TRANSACTION", "TO SAVEPOINT", "PREPARED");
2298 else if (Matches("ABORT|END|COMMIT|ROLLBACK", "AND"))
2299 COMPLETE_WITH("CHAIN");
2300 /* CALL */
2301 else if (Matches("CALL"))
2302 COMPLETE_WITH_VERSIONED_SCHEMA_QUERY(Query_for_list_of_procedures, NULL);
2303 else if (Matches("CALL", MatchAny))
2304 COMPLETE_WITH("(");
2305 /* CLOSE */
2306 else if (Matches("CLOSE"))
2307 COMPLETE_WITH_QUERY(Query_for_list_of_cursors
2308 " UNION SELECT 'ALL'");
2309 /* CLUSTER */
2310 else if (Matches("CLUSTER"))
2311 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_clusterables, "UNION SELECT 'VERBOSE'");
2312 else if (Matches("CLUSTER", "VERBOSE") ||
2313 Matches("CLUSTER", "(*)"))
2314 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_clusterables, NULL);
2315 /* If we have CLUSTER <sth>, then add "USING" */
2316 else if (Matches("CLUSTER", MatchAnyExcept("VERBOSE|ON|(|(*)")))
2317 COMPLETE_WITH("USING");
2318 /* If we have CLUSTER VERBOSE <sth>, then add "USING" */
2319 else if (Matches("CLUSTER", "VERBOSE|(*)", MatchAny))
2320 COMPLETE_WITH("USING");
2321 /* If we have CLUSTER <sth> USING, then add the index as well */
2322 else if (Matches("CLUSTER", MatchAny, "USING") ||
2323 Matches("CLUSTER", "VERBOSE|(*)", MatchAny, "USING"))
2324 {
2325 completion_info_charp = prev2_wd;
2326 COMPLETE_WITH_QUERY(Query_for_index_of_table);
2327 }
2328 else if (HeadMatches("CLUSTER", "(*") &&
2329 !HeadMatches("CLUSTER", "(*)"))
2330 {
2331 /*
2332 * This fires if we're in an unfinished parenthesized option list.
2333 * get_previous_words treats a completed parenthesized option list as
2334 * one word, so the above test is correct.
2335 */
2336 if (ends_with(prev_wd, '(') || ends_with(prev_wd, ','))
2337 COMPLETE_WITH("VERBOSE");
2338 }
2339
2340 /* COMMENT */
2341 else if (Matches("COMMENT"))
2342 COMPLETE_WITH("ON");
2343 else if (Matches("COMMENT", "ON"))
2344 COMPLETE_WITH("ACCESS METHOD", "CAST", "COLLATION", "CONVERSION",
2345 "DATABASE", "EVENT TRIGGER", "EXTENSION",
2346 "FOREIGN DATA WRAPPER", "FOREIGN TABLE", "SERVER",
2347 "INDEX", "LANGUAGE", "POLICY", "PUBLICATION", "RULE",
2348 "SCHEMA", "SEQUENCE", "STATISTICS", "SUBSCRIPTION",
2349 "TABLE", "TYPE", "VIEW", "MATERIALIZED VIEW",
2350 "COLUMN", "AGGREGATE", "FUNCTION",
2351 "PROCEDURE", "ROUTINE",
2352 "OPERATOR", "TRIGGER", "CONSTRAINT", "DOMAIN",
2353 "LARGE OBJECT", "TABLESPACE", "TEXT SEARCH", "ROLE");
2354 else if (Matches("COMMENT", "ON", "ACCESS", "METHOD"))
2355 COMPLETE_WITH_QUERY(Query_for_list_of_access_methods);
2356 else if (Matches("COMMENT", "ON", "FOREIGN"))
2357 COMPLETE_WITH("DATA WRAPPER", "TABLE");
2358 else if (Matches("COMMENT", "ON", "TEXT", "SEARCH"))
2359 COMPLETE_WITH("CONFIGURATION", "DICTIONARY", "PARSER", "TEMPLATE");
2360 else if (Matches("COMMENT", "ON", "CONSTRAINT"))
2361 COMPLETE_WITH_QUERY(Query_for_all_table_constraints);
2362 else if (Matches("COMMENT", "ON", "CONSTRAINT", MatchAny))
2363 COMPLETE_WITH("ON");
2364 else if (Matches("COMMENT", "ON", "CONSTRAINT", MatchAny, "ON"))
2365 {
2366 completion_info_charp = prev2_wd;
2367 COMPLETE_WITH_QUERY(Query_for_list_of_tables_for_constraint);
2368 }
2369 else if (Matches("COMMENT", "ON", "MATERIALIZED", "VIEW"))
2370 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_matviews, NULL);
2371 else if (Matches("COMMENT", "ON", "EVENT", "TRIGGER"))
2372 COMPLETE_WITH_QUERY(Query_for_list_of_event_triggers);
2373 else if (Matches("COMMENT", "ON", MatchAny, MatchAnyExcept("IS")) ||
2374 Matches("COMMENT", "ON", MatchAny, MatchAny, MatchAnyExcept("IS")) ||
2375 Matches("COMMENT", "ON", MatchAny, MatchAny, MatchAny, MatchAnyExcept("IS")))
2376 COMPLETE_WITH("IS");
2377
2378 /* COPY */
2379
2380 /*
2381 * If we have COPY, offer list of tables or "(" (Also cover the analogous
2382 * backslash command).
2383 */
2384 else if (Matches("COPY|\\copy"))
2385 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables,
2386 " UNION ALL SELECT '('");
2387 /* Complete COPY ( with legal query commands */
2388 else if (Matches("COPY|\\copy", "("))
2389 COMPLETE_WITH("SELECT", "TABLE", "VALUES", "INSERT INTO", "UPDATE", "DELETE FROM", "WITH");
2390 /* Complete COPY <sth> */
2391 else if (Matches("COPY|\\copy", MatchAny))
2392 COMPLETE_WITH("FROM", "TO");
2393 /* Complete COPY <sth> FROM|TO with filename */
2394 else if (Matches("COPY", MatchAny, "FROM|TO"))
2395 {
2396 completion_charp = "";
2397 completion_force_quote = true; /* COPY requires quoted filename */
2398 matches = rl_completion_matches(text, complete_from_files);
2399 }
2400 else if (Matches("\\copy", MatchAny, "FROM|TO"))
2401 {
2402 completion_charp = "";
2403 completion_force_quote = false;
2404 matches = rl_completion_matches(text, complete_from_files);
2405 }
2406
2407 /* Complete COPY <sth> TO <sth> */
2408 else if (Matches("COPY|\\copy", MatchAny, "TO", MatchAny))
2409 COMPLETE_WITH("WITH (");
2410
2411 /* Complete COPY <sth> FROM <sth> */
2412 else if (Matches("COPY|\\copy", MatchAny, "FROM", MatchAny))
2413 COMPLETE_WITH("WITH (", "WHERE");
2414
2415 /* Complete COPY <sth> FROM|TO filename WITH ( */
2416 else if (Matches("COPY|\\copy", MatchAny, "FROM|TO", MatchAny, "WITH", "("))
2417 COMPLETE_WITH("FORMAT", "FREEZE", "DELIMITER", "NULL",
2418 "HEADER", "QUOTE", "ESCAPE", "FORCE_QUOTE",
2419 "FORCE_NOT_NULL", "FORCE_NULL", "ENCODING");
2420
2421 /* Complete COPY <sth> FROM|TO filename WITH (FORMAT */
2422 else if (Matches("COPY|\\copy", MatchAny, "FROM|TO", MatchAny, "WITH", "(", "FORMAT"))
2423 COMPLETE_WITH("binary", "csv", "text");
2424
2425 /* Complete COPY <sth> FROM <sth> WITH (<options>) */
2426 else if (Matches("COPY|\\copy", MatchAny, "FROM", MatchAny, "WITH", MatchAny))
2427 COMPLETE_WITH("WHERE");
2428
2429 /* CREATE ACCESS METHOD */
2430 /* Complete "CREATE ACCESS METHOD <name>" */
2431 else if (Matches("CREATE", "ACCESS", "METHOD", MatchAny))
2432 COMPLETE_WITH("TYPE");
2433 /* Complete "CREATE ACCESS METHOD <name> TYPE" */
2434 else if (Matches("CREATE", "ACCESS", "METHOD", MatchAny, "TYPE"))
2435 COMPLETE_WITH("INDEX", "TABLE");
2436 /* Complete "CREATE ACCESS METHOD <name> TYPE <type>" */
2437 else if (Matches("CREATE", "ACCESS", "METHOD", MatchAny, "TYPE", MatchAny))
2438 COMPLETE_WITH("HANDLER");
2439
2440 /* CREATE COLLATION */
2441 else if (Matches("CREATE", "COLLATION", MatchAny))
2442 COMPLETE_WITH("(", "FROM");
2443 else if (Matches("CREATE", "COLLATION", MatchAny, "FROM"))
2444 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_collations, NULL);
2445 else if (HeadMatches("CREATE", "COLLATION", MatchAny, "(*"))
2446 {
2447 if (TailMatches("(|*,"))
2448 COMPLETE_WITH("LOCALE =", "LC_COLLATE =", "LC_CTYPE =",
2449 "PROVIDER =", "DETERMINISTIC =");
2450 else if (TailMatches("PROVIDER", "="))
2451 COMPLETE_WITH("libc", "icu");
2452 else if (TailMatches("DETERMINISTIC", "="))
2453 COMPLETE_WITH("true", "false");
2454 }
2455
2456 /* CREATE DATABASE */
2457 else if (Matches("CREATE", "DATABASE", MatchAny))
2458 COMPLETE_WITH("OWNER", "TEMPLATE", "ENCODING", "TABLESPACE",
2459 "IS_TEMPLATE",
2460 "ALLOW_CONNECTIONS", "CONNECTION LIMIT",
2461 "LC_COLLATE", "LC_CTYPE", "LOCALE");
2462
2463 else if (Matches("CREATE", "DATABASE", MatchAny, "TEMPLATE"))
2464 COMPLETE_WITH_QUERY(Query_for_list_of_template_databases);
2465
2466 /* CREATE EXTENSION */
2467 /* Complete with available extensions rather than installed ones. */
2468 else if (Matches("CREATE", "EXTENSION"))
2469 COMPLETE_WITH_QUERY(Query_for_list_of_available_extensions);
2470 /* CREATE EXTENSION <name> */
2471 else if (Matches("CREATE", "EXTENSION", MatchAny))
2472 COMPLETE_WITH("WITH SCHEMA", "CASCADE", "VERSION");
2473 /* CREATE EXTENSION <name> VERSION */
2474 else if (Matches("CREATE", "EXTENSION", MatchAny, "VERSION"))
2475 {
2476 completion_info_charp = prev2_wd;
2477 COMPLETE_WITH_QUERY(Query_for_list_of_available_extension_versions);
2478 }
2479
2480 /* CREATE FOREIGN */
2481 else if (Matches("CREATE", "FOREIGN"))
2482 COMPLETE_WITH("DATA WRAPPER", "TABLE");
2483
2484 /* CREATE FOREIGN DATA WRAPPER */
2485 else if (Matches("CREATE", "FOREIGN", "DATA", "WRAPPER", MatchAny))
2486 COMPLETE_WITH("HANDLER", "VALIDATOR", "OPTIONS");
2487
2488 /* CREATE INDEX --- is allowed inside CREATE SCHEMA, so use TailMatches */
2489 /* First off we complete CREATE UNIQUE with "INDEX" */
2490 else if (TailMatches("CREATE", "UNIQUE"))
2491 COMPLETE_WITH("INDEX");
2492
2493 /*
2494 * If we have CREATE|UNIQUE INDEX, then add "ON", "CONCURRENTLY", and
2495 * existing indexes
2496 */
2497 else if (TailMatches("CREATE|UNIQUE", "INDEX"))
2498 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_indexes,
2499 " UNION SELECT 'ON'"
2500 " UNION SELECT 'CONCURRENTLY'");
2501
2502 /*
2503 * Complete ... INDEX|CONCURRENTLY [<name>] ON with a list of relations
2504 * that indexes can be created on
2505 */
2506 else if (TailMatches("INDEX|CONCURRENTLY", MatchAny, "ON") ||
2507 TailMatches("INDEX|CONCURRENTLY", "ON"))
2508 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_indexables, NULL);
2509
2510 /*
2511 * Complete CREATE|UNIQUE INDEX CONCURRENTLY with "ON" and existing
2512 * indexes
2513 */
2514 else if (TailMatches("CREATE|UNIQUE", "INDEX", "CONCURRENTLY"))
2515 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_indexes,
2516 " UNION SELECT 'ON'");
2517 /* Complete CREATE|UNIQUE INDEX [CONCURRENTLY] <sth> with "ON" */
2518 else if (TailMatches("CREATE|UNIQUE", "INDEX", MatchAny) ||
2519 TailMatches("CREATE|UNIQUE", "INDEX", "CONCURRENTLY", MatchAny))
2520 COMPLETE_WITH("ON");
2521
2522 /*
2523 * Complete INDEX <name> ON <table> with a list of table columns (which
2524 * should really be in parens)
2525 */
2526 else if (TailMatches("INDEX", MatchAny, "ON", MatchAny) ||
2527 TailMatches("INDEX|CONCURRENTLY", "ON", MatchAny))
2528 COMPLETE_WITH("(", "USING");
2529 else if (TailMatches("INDEX", MatchAny, "ON", MatchAny, "(") ||
2530 TailMatches("INDEX|CONCURRENTLY", "ON", MatchAny, "("))
2531 COMPLETE_WITH_ATTR(prev2_wd, "");
2532 /* same if you put in USING */
2533 else if (TailMatches("ON", MatchAny, "USING", MatchAny, "("))
2534 COMPLETE_WITH_ATTR(prev4_wd, "");
2535 /* Complete USING with an index method */
2536 else if (TailMatches("INDEX", MatchAny, MatchAny, "ON", MatchAny, "USING") ||
2537 TailMatches("INDEX", MatchAny, "ON", MatchAny, "USING") ||
2538 TailMatches("INDEX", "ON", MatchAny, "USING"))
2539 COMPLETE_WITH_QUERY(Query_for_list_of_index_access_methods);
2540 else if (TailMatches("ON", MatchAny, "USING", MatchAny) &&
2541 !TailMatches("POLICY", MatchAny, MatchAny, MatchAny, MatchAny, MatchAny) &&
2542 !TailMatches("FOR", MatchAny, MatchAny, MatchAny))
2543 COMPLETE_WITH("(");
2544
2545 /* CREATE OR REPLACE */
2546 else if (Matches("CREATE", "OR"))
2547 COMPLETE_WITH("REPLACE");
2548
2549 /* CREATE POLICY */
2550 /* Complete "CREATE POLICY <name> ON" */
2551 else if (Matches("CREATE", "POLICY", MatchAny))
2552 COMPLETE_WITH("ON");
2553 /* Complete "CREATE POLICY <name> ON <table>" */
2554 else if (Matches("CREATE", "POLICY", MatchAny, "ON"))
2555 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, NULL);
2556 /* Complete "CREATE POLICY <name> ON <table> AS|FOR|TO|USING|WITH CHECK" */
2557 else if (Matches("CREATE", "POLICY", MatchAny, "ON", MatchAny))
2558 COMPLETE_WITH("AS", "FOR", "TO", "USING (", "WITH CHECK (");
2559 /* CREATE POLICY <name> ON <table> AS PERMISSIVE|RESTRICTIVE */
2560 else if (Matches("CREATE", "POLICY", MatchAny, "ON", MatchAny, "AS"))
2561 COMPLETE_WITH("PERMISSIVE", "RESTRICTIVE");
2562
2563 /*
2564 * CREATE POLICY <name> ON <table> AS PERMISSIVE|RESTRICTIVE
2565 * FOR|TO|USING|WITH CHECK
2566 */
2567 else if (Matches("CREATE", "POLICY", MatchAny, "ON", MatchAny, "AS", MatchAny))
2568 COMPLETE_WITH("FOR", "TO", "USING", "WITH CHECK");
2569 /* CREATE POLICY <name> ON <table> FOR ALL|SELECT|INSERT|UPDATE|DELETE */
2570 else if (Matches("CREATE", "POLICY", MatchAny, "ON", MatchAny, "FOR"))
2571 COMPLETE_WITH("ALL", "SELECT", "INSERT", "UPDATE", "DELETE");
2572 /* Complete "CREATE POLICY <name> ON <table> FOR INSERT TO|WITH CHECK" */
2573 else if (Matches("CREATE", "POLICY", MatchAny, "ON", MatchAny, "FOR", "INSERT"))
2574 COMPLETE_WITH("TO", "WITH CHECK (");
2575 /* Complete "CREATE POLICY <name> ON <table> FOR SELECT|DELETE TO|USING" */
2576 else if (Matches("CREATE", "POLICY", MatchAny, "ON", MatchAny, "FOR", "SELECT|DELETE"))
2577 COMPLETE_WITH("TO", "USING (");
2578 /* CREATE POLICY <name> ON <table> FOR ALL|UPDATE TO|USING|WITH CHECK */
2579 else if (Matches("CREATE", "POLICY", MatchAny, "ON", MatchAny, "FOR", "ALL|UPDATE"))
2580 COMPLETE_WITH("TO", "USING (", "WITH CHECK (");
2581 /* Complete "CREATE POLICY <name> ON <table> TO <role>" */
2582 else if (Matches("CREATE", "POLICY", MatchAny, "ON", MatchAny, "TO"))
2583 COMPLETE_WITH_QUERY(Query_for_list_of_grant_roles);
2584 /* Complete "CREATE POLICY <name> ON <table> USING (" */
2585 else if (Matches("CREATE", "POLICY", MatchAny, "ON", MatchAny, "USING"))
2586 COMPLETE_WITH("(");
2587
2588 /*
2589 * CREATE POLICY <name> ON <table> AS PERMISSIVE|RESTRICTIVE FOR
2590 * ALL|SELECT|INSERT|UPDATE|DELETE
2591 */
2592 else if (Matches("CREATE", "POLICY", MatchAny, "ON", MatchAny, "AS", MatchAny, "FOR"))
2593 COMPLETE_WITH("ALL", "SELECT", "INSERT", "UPDATE", "DELETE");
2594
2595 /*
2596 * Complete "CREATE POLICY <name> ON <table> AS PERMISSIVE|RESTRICTIVE FOR
2597 * INSERT TO|WITH CHECK"
2598 */
2599 else if (Matches("CREATE", "POLICY", MatchAny, "ON", MatchAny, "AS", MatchAny, "FOR", "INSERT"))
2600 COMPLETE_WITH("TO", "WITH CHECK (");
2601
2602 /*
2603 * Complete "CREATE POLICY <name> ON <table> AS PERMISSIVE|RESTRICTIVE FOR
2604 * SELECT|DELETE TO|USING"
2605 */
2606 else if (Matches("CREATE", "POLICY", MatchAny, "ON", MatchAny, "AS", MatchAny, "FOR", "SELECT|DELETE"))
2607 COMPLETE_WITH("TO", "USING (");
2608
2609 /*
2610 * CREATE POLICY <name> ON <table> AS PERMISSIVE|RESTRICTIVE FOR
2611 * ALL|UPDATE TO|USING|WITH CHECK
2612 */
2613 else if (Matches("CREATE", "POLICY", MatchAny, "ON", MatchAny, "AS", MatchAny, "FOR", "ALL|UPDATE"))
2614 COMPLETE_WITH("TO", "USING (", "WITH CHECK (");
2615
2616 /*
2617 * Complete "CREATE POLICY <name> ON <table> AS PERMISSIVE|RESTRICTIVE TO
2618 * <role>"
2619 */
2620 else if (Matches("CREATE", "POLICY", MatchAny, "ON", MatchAny, "AS", MatchAny, "TO"))
2621 COMPLETE_WITH_QUERY(Query_for_list_of_grant_roles);
2622
2623 /*
2624 * Complete "CREATE POLICY <name> ON <table> AS PERMISSIVE|RESTRICTIVE
2625 * USING ("
2626 */
2627 else if (Matches("CREATE", "POLICY", MatchAny, "ON", MatchAny, "AS", MatchAny, "USING"))
2628 COMPLETE_WITH("(");
2629
2630
2631 /* CREATE PUBLICATION */
2632 else if (Matches("CREATE", "PUBLICATION", MatchAny))
2633 COMPLETE_WITH("FOR TABLE", "FOR ALL TABLES", "WITH (");
2634 else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR"))
2635 COMPLETE_WITH("TABLE", "ALL TABLES");
2636 /* Complete "CREATE PUBLICATION <name> FOR TABLE <table>, ..." */
2637 else if (HeadMatches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLE"))
2638 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, NULL);
2639 /* Complete "CREATE PUBLICATION <name> [...] WITH" */
2640 else if (HeadMatches("CREATE", "PUBLICATION") && TailMatches("WITH", "("))
2641 COMPLETE_WITH("publish", "publish_via_partition_root");
2642
2643 /* CREATE RULE */
2644 /* Complete "CREATE [ OR REPLACE ] RULE <sth>" with "AS ON" */
2645 else if (Matches("CREATE", "RULE", MatchAny) ||
2646 Matches("CREATE", "OR", "REPLACE", "RULE", MatchAny))
2647 COMPLETE_WITH("AS ON");
2648 /* Complete "CREATE [ OR REPLACE ] RULE <sth> AS" with "ON" */
2649 else if (Matches("CREATE", "RULE", MatchAny, "AS") ||
2650 Matches("CREATE", "OR", "REPLACE", "RULE", MatchAny, "AS"))
2651 COMPLETE_WITH("ON");
2652
2653 /*
2654 * Complete "CREATE [ OR REPLACE ] RULE <sth> AS ON" with
2655 * SELECT|UPDATE|INSERT|DELETE
2656 */
2657 else if (Matches("CREATE", "RULE", MatchAny, "AS", "ON") ||
2658 Matches("CREATE", "OR", "REPLACE", "RULE", MatchAny, "AS", "ON"))
2659 COMPLETE_WITH("SELECT", "UPDATE", "INSERT", "DELETE");
2660 /* Complete "AS ON SELECT|UPDATE|INSERT|DELETE" with a "TO" */
2661 else if (TailMatches("AS", "ON", "SELECT|UPDATE|INSERT|DELETE"))
2662 COMPLETE_WITH("TO");
2663 /* Complete "AS ON <sth> TO" with a table name */
2664 else if (TailMatches("AS", "ON", "SELECT|UPDATE|INSERT|DELETE", "TO"))
2665 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, NULL);
2666
2667 /* CREATE SEQUENCE --- is allowed inside CREATE SCHEMA, so use TailMatches */
2668 else if (TailMatches("CREATE", "SEQUENCE", MatchAny) ||
2669 TailMatches("CREATE", "TEMP|TEMPORARY", "SEQUENCE", MatchAny))
2670 COMPLETE_WITH("INCREMENT BY", "MINVALUE", "MAXVALUE", "NO", "CACHE",
2671 "CYCLE", "OWNED BY", "START WITH");
2672 else if (TailMatches("CREATE", "SEQUENCE", MatchAny, "NO") ||
2673 TailMatches("CREATE", "TEMP|TEMPORARY", "SEQUENCE", MatchAny, "NO"))
2674 COMPLETE_WITH("MINVALUE", "MAXVALUE", "CYCLE");
2675
2676 /* CREATE SERVER <name> */
2677 else if (Matches("CREATE", "SERVER", MatchAny))
2678 COMPLETE_WITH("TYPE", "VERSION", "FOREIGN DATA WRAPPER");
2679
2680 /* CREATE STATISTICS <name> */
2681 else if (Matches("CREATE", "STATISTICS", MatchAny))
2682 COMPLETE_WITH("(", "ON");
2683 else if (Matches("CREATE", "STATISTICS", MatchAny, "("))
2684 COMPLETE_WITH("ndistinct", "dependencies", "mcv");
2685 else if (Matches("CREATE", "STATISTICS", MatchAny, "(*)"))
2686 COMPLETE_WITH("ON");
2687 else if (HeadMatches("CREATE", "STATISTICS", MatchAny) &&
2688 TailMatches("FROM"))
2689 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, NULL);
2690
2691 /* CREATE TABLE --- is allowed inside CREATE SCHEMA, so use TailMatches */
2692 /* Complete "CREATE TEMP/TEMPORARY" with the possible temp objects */
2693 else if (TailMatches("CREATE", "TEMP|TEMPORARY"))
2694 COMPLETE_WITH("SEQUENCE", "TABLE", "VIEW");
2695 /* Complete "CREATE UNLOGGED" with TABLE or MATVIEW */
2696 else if (TailMatches("CREATE", "UNLOGGED"))
2697 COMPLETE_WITH("TABLE", "MATERIALIZED VIEW");
2698 /* Complete PARTITION BY with RANGE ( or LIST ( or ... */
2699 else if (TailMatches("PARTITION", "BY"))
2700 COMPLETE_WITH("RANGE (", "LIST (", "HASH (");
2701 /* If we have xxx PARTITION OF, provide a list of partitioned tables */
2702 else if (TailMatches("PARTITION", "OF"))
2703 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_partitioned_tables, "");
2704 /* Limited completion support for partition bound specification */
2705 else if (TailMatches("PARTITION", "OF", MatchAny))
2706 COMPLETE_WITH("FOR VALUES", "DEFAULT");
2707 /* Complete CREATE TABLE <name> with '(', OF or PARTITION OF */
2708 else if (TailMatches("CREATE", "TABLE", MatchAny) ||
2709 TailMatches("CREATE", "TEMP|TEMPORARY|UNLOGGED", "TABLE", MatchAny))
2710 COMPLETE_WITH("(", "OF", "PARTITION OF");
2711 /* Complete CREATE TABLE <name> OF with list of composite types */
2712 else if (TailMatches("CREATE", "TABLE", MatchAny, "OF") ||
2713 TailMatches("CREATE", "TEMP|TEMPORARY|UNLOGGED", "TABLE", MatchAny, "OF"))
2714 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_composite_datatypes, NULL);
2715 /* Complete CREATE TABLE name (...) with supported options */
2716 else if (TailMatches("CREATE", "TABLE", MatchAny, "(*)") ||
2717 TailMatches("CREATE", "UNLOGGED", "TABLE", MatchAny, "(*)"))
2718 COMPLETE_WITH("INHERITS (", "PARTITION BY", "USING", "TABLESPACE", "WITH (");
2719 else if (TailMatches("CREATE", "TEMP|TEMPORARY", "TABLE", MatchAny, "(*)"))
2720 COMPLETE_WITH("INHERITS (", "ON COMMIT", "PARTITION BY",
2721 "TABLESPACE", "WITH (");
2722 /* Complete CREATE TABLE (...) USING with table access methods */
2723 else if (TailMatches("CREATE", "TABLE", MatchAny, "(*)", "USING") ||
2724 TailMatches("CREATE", "TEMP|TEMPORARY|UNLOGGED", "TABLE", MatchAny, "(*)", "USING"))
2725 COMPLETE_WITH_QUERY(Query_for_list_of_table_access_methods);
2726 /* Complete CREATE TABLE (...) WITH with storage parameters */
2727 else if (TailMatches("CREATE", "TABLE", MatchAny, "(*)", "WITH", "(") ||
2728 TailMatches("CREATE", "TEMP|TEMPORARY|UNLOGGED", "TABLE", MatchAny, "(*)", "WITH", "("))
2729 COMPLETE_WITH_LIST(table_storage_parameters);
2730 /* Complete CREATE TABLE ON COMMIT with actions */
2731 else if (TailMatches("CREATE", "TEMP|TEMPORARY", "TABLE", MatchAny, "(*)", "ON", "COMMIT"))
2732 COMPLETE_WITH("DELETE ROWS", "DROP", "PRESERVE ROWS");
2733
2734 /* CREATE TABLESPACE */
2735 else if (Matches("CREATE", "TABLESPACE", MatchAny))
2736 COMPLETE_WITH("OWNER", "LOCATION");
2737 /* Complete CREATE TABLESPACE name OWNER name with "LOCATION" */
2738 else if (Matches("CREATE", "TABLESPACE", MatchAny, "OWNER", MatchAny))
2739 COMPLETE_WITH("LOCATION");
2740
2741 /* CREATE TEXT SEARCH */
2742 else if (Matches("CREATE", "TEXT", "SEARCH"))
2743 COMPLETE_WITH("CONFIGURATION", "DICTIONARY", "PARSER", "TEMPLATE");
2744 else if (Matches("CREATE", "TEXT", "SEARCH", "CONFIGURATION|DICTIONARY|PARSER|TEMPLATE", MatchAny))
2745 COMPLETE_WITH("(");
2746
2747 /* CREATE SUBSCRIPTION */
2748 else if (Matches("CREATE", "SUBSCRIPTION", MatchAny))
2749 COMPLETE_WITH("CONNECTION");
2750 else if (Matches("CREATE", "SUBSCRIPTION", MatchAny, "CONNECTION", MatchAny))
2751 COMPLETE_WITH("PUBLICATION");
2752 else if (Matches("CREATE", "SUBSCRIPTION", MatchAny, "CONNECTION",
2753 MatchAny, "PUBLICATION"))
2754 {
2755 /* complete with nothing here as this refers to remote publications */
2756 }
2757 else if (HeadMatches("CREATE", "SUBSCRIPTION") && TailMatches("PUBLICATION", MatchAny))
2758 COMPLETE_WITH("WITH (");
2759 /* Complete "CREATE SUBSCRIPTION <name> ... WITH ( <opt>" */
2760 else if (HeadMatches("CREATE", "SUBSCRIPTION") && TailMatches("WITH", "("))
2761 COMPLETE_WITH("binary", "connect", "copy_data", "create_slot",
2762 "enabled", "slot_name", "streaming",
2763 "synchronous_commit");
2764
2765 /* CREATE TRIGGER --- is allowed inside CREATE SCHEMA, so use TailMatches */
2766
2767 /*
2768 * Complete CREATE [ OR REPLACE ] TRIGGER <name> with BEFORE|AFTER|INSTEAD
2769 * OF.
2770 */
2771 else if (TailMatches("CREATE", "TRIGGER", MatchAny) ||
2772 TailMatches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAny))
2773 COMPLETE_WITH("BEFORE", "AFTER", "INSTEAD OF");
2774
2775 /*
2776 * Complete CREATE [ OR REPLACE ] TRIGGER <name> BEFORE,AFTER with an
2777 * event.
2778 */
2779 else if (TailMatches("CREATE", "TRIGGER", MatchAny, "BEFORE|AFTER") ||
2780 TailMatches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAny, "BEFORE|AFTER"))
2781 COMPLETE_WITH("INSERT", "DELETE", "UPDATE", "TRUNCATE");
2782 /* Complete CREATE [ OR REPLACE ] TRIGGER <name> INSTEAD OF with an event */
2783 else if (TailMatches("CREATE", "TRIGGER", MatchAny, "INSTEAD", "OF") ||
2784 TailMatches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAny, "INSTEAD", "OF"))
2785 COMPLETE_WITH("INSERT", "DELETE", "UPDATE");
2786
2787 /*
2788 * Complete CREATE [ OR REPLACE ] TRIGGER <name> BEFORE,AFTER sth with
2789 * OR|ON.
2790 */
2791 else if (TailMatches("CREATE", "TRIGGER", MatchAny, "BEFORE|AFTER", MatchAny) ||
2792 TailMatches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAny, "BEFORE|AFTER", MatchAny) ||
2793 TailMatches("CREATE", "TRIGGER", MatchAny, "INSTEAD", "OF", MatchAny) ||
2794 TailMatches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAny, "INSTEAD", "OF", MatchAny))
2795 COMPLETE_WITH("ON", "OR");
2796
2797 /*
2798 * Complete CREATE [ OR REPLACE ] TRIGGER <name> BEFORE,AFTER event ON
2799 * with a list of tables. EXECUTE FUNCTION is the recommended grammar
2800 * instead of EXECUTE PROCEDURE in version 11 and upwards.
2801 */
2802 else if (TailMatches("CREATE", "TRIGGER", MatchAny, "BEFORE|AFTER", MatchAny, "ON") ||
2803 TailMatches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAny, "BEFORE|AFTER", MatchAny, "ON"))
2804 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, NULL);
2805
2806 /*
2807 * Complete CREATE [ OR REPLACE ] TRIGGER ... INSTEAD OF event ON with a
2808 * list of views.
2809 */
2810 else if (TailMatches("CREATE", "TRIGGER", MatchAny, "INSTEAD", "OF", MatchAny, "ON") ||
2811 TailMatches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAny, "INSTEAD", "OF", MatchAny, "ON"))
2812 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_views, NULL);
2813 else if ((HeadMatches("CREATE", "TRIGGER") ||
2814 HeadMatches("CREATE", "OR", "REPLACE", "TRIGGER")) &&
2815 TailMatches("ON", MatchAny))
2816 {
2817 if (pset.sversion >= 110000)
2818 COMPLETE_WITH("NOT DEFERRABLE", "DEFERRABLE", "INITIALLY",
2819 "REFERENCING", "FOR", "WHEN (", "EXECUTE FUNCTION");
2820 else
2821 COMPLETE_WITH("NOT DEFERRABLE", "DEFERRABLE", "INITIALLY",
2822 "REFERENCING", "FOR", "WHEN (", "EXECUTE PROCEDURE");
2823 }
2824 else if ((HeadMatches("CREATE", "TRIGGER") ||
2825 HeadMatches("CREATE", "OR", "REPLACE", "TRIGGER")) &&
2826 (TailMatches("DEFERRABLE") || TailMatches("INITIALLY", "IMMEDIATE|DEFERRED")))
2827 {
2828 if (pset.sversion >= 110000)
2829 COMPLETE_WITH("REFERENCING", "FOR", "WHEN (", "EXECUTE FUNCTION");
2830 else
2831 COMPLETE_WITH("REFERENCING", "FOR", "WHEN (", "EXECUTE PROCEDURE");
2832 }
2833 else if ((HeadMatches("CREATE", "TRIGGER") ||
2834 HeadMatches("CREATE", "OR", "REPLACE", "TRIGGER")) &&
2835 TailMatches("REFERENCING"))
2836 COMPLETE_WITH("OLD TABLE", "NEW TABLE");
2837 else if ((HeadMatches("CREATE", "TRIGGER") ||
2838 HeadMatches("CREATE", "OR", "REPLACE", "TRIGGER")) &&
2839 TailMatches("OLD|NEW", "TABLE"))
2840 COMPLETE_WITH("AS");
2841 else if ((HeadMatches("CREATE", "TRIGGER") ||
2842 HeadMatches("CREATE", "OR", "REPLACE", "TRIGGER")) &&
2843 (TailMatches("REFERENCING", "OLD", "TABLE", "AS", MatchAny) ||
2844 TailMatches("REFERENCING", "OLD", "TABLE", MatchAny)))
2845 {
2846 if (pset.sversion >= 110000)
2847 COMPLETE_WITH("NEW TABLE", "FOR", "WHEN (", "EXECUTE FUNCTION");
2848 else
2849 COMPLETE_WITH("NEW TABLE", "FOR", "WHEN (", "EXECUTE PROCEDURE");
2850 }
2851 else if ((HeadMatches("CREATE", "TRIGGER") ||
2852 HeadMatches("CREATE", "OR", "REPLACE", "TRIGGER")) &&
2853 (TailMatches("REFERENCING", "NEW", "TABLE", "AS", MatchAny) ||
2854 TailMatches("REFERENCING", "NEW", "TABLE", MatchAny)))
2855 {
2856 if (pset.sversion >= 110000)
2857 COMPLETE_WITH("OLD TABLE", "FOR", "WHEN (", "EXECUTE FUNCTION");
2858 else
2859 COMPLETE_WITH("OLD TABLE", "FOR", "WHEN (", "EXECUTE PROCEDURE");
2860 }
2861 else if ((HeadMatches("CREATE", "TRIGGER") ||
2862 HeadMatches("CREATE", "OR", "REPLACE", "TRIGGER")) &&
2863 (TailMatches("REFERENCING", "OLD|NEW", "TABLE", "AS", MatchAny, "OLD|NEW", "TABLE", "AS", MatchAny) ||
2864 TailMatches("REFERENCING", "OLD|NEW", "TABLE", MatchAny, "OLD|NEW", "TABLE", "AS", MatchAny) ||
2865 TailMatches("REFERENCING", "OLD|NEW", "TABLE", "AS", MatchAny, "OLD|NEW", "TABLE", MatchAny) ||
2866 TailMatches("REFERENCING", "OLD|NEW", "TABLE", MatchAny, "OLD|NEW", "TABLE", MatchAny)))
2867 {
2868 if (pset.sversion >= 110000)
2869 COMPLETE_WITH("FOR", "WHEN (", "EXECUTE FUNCTION");
2870 else
2871 COMPLETE_WITH("FOR", "WHEN (", "EXECUTE PROCEDURE");
2872 }
2873 else if ((HeadMatches("CREATE", "TRIGGER") ||
2874 HeadMatches("CREATE", "OR", "REPLACE", "TRIGGER")) &&
2875 TailMatches("FOR"))
2876 COMPLETE_WITH("EACH", "ROW", "STATEMENT");
2877 else if ((HeadMatches("CREATE", "TRIGGER") ||
2878 HeadMatches("CREATE", "OR", "REPLACE", "TRIGGER")) &&
2879 TailMatches("FOR", "EACH"))
2880 COMPLETE_WITH("ROW", "STATEMENT");
2881 else if ((HeadMatches("CREATE", "TRIGGER") ||
2882 HeadMatches("CREATE", "OR", "REPLACE", "TRIGGER")) &&
2883 (TailMatches("FOR", "EACH", "ROW|STATEMENT") ||
2884 TailMatches("FOR", "ROW|STATEMENT")))
2885 {
2886 if (pset.sversion >= 110000)
2887 COMPLETE_WITH("WHEN (", "EXECUTE FUNCTION");
2888 else
2889 COMPLETE_WITH("WHEN (", "EXECUTE PROCEDURE");
2890 }
2891 else if ((HeadMatches("CREATE", "TRIGGER") ||
2892 HeadMatches("CREATE", "OR", "REPLACE", "TRIGGER")) &&
2893 TailMatches("WHEN", "(*)"))
2894 {
2895 if (pset.sversion >= 110000)
2896 COMPLETE_WITH("EXECUTE FUNCTION");
2897 else
2898 COMPLETE_WITH("EXECUTE PROCEDURE");
2899 }
2900
2901 /*
2902 * Complete CREATE [ OR REPLACE ] TRIGGER ... EXECUTE with
2903 * PROCEDURE|FUNCTION.
2904 */
2905 else if ((HeadMatches("CREATE", "TRIGGER") ||
2906 HeadMatches("CREATE", "OR", "REPLACE", "TRIGGER")) &&
2907 TailMatches("EXECUTE"))
2908 {
2909 if (pset.sversion >= 110000)
2910 COMPLETE_WITH("FUNCTION");
2911 else
2912 COMPLETE_WITH("PROCEDURE");
2913 }
2914 else if ((HeadMatches("CREATE", "TRIGGER") ||
2915 HeadMatches("CREATE", "OR", "REPLACE", "TRIGGER")) &&
2916 TailMatches("EXECUTE", "FUNCTION|PROCEDURE"))
2917 COMPLETE_WITH_VERSIONED_SCHEMA_QUERY(Query_for_list_of_functions, NULL);
2918
2919 /* CREATE ROLE,USER,GROUP <name> */
2920 else if (Matches("CREATE", "ROLE|GROUP|USER", MatchAny) &&
2921 !TailMatches("USER", "MAPPING"))
2922 COMPLETE_WITH("ADMIN", "BYPASSRLS", "CONNECTION LIMIT", "CREATEDB",
2923 "CREATEROLE", "ENCRYPTED PASSWORD", "IN", "INHERIT",
2924 "LOGIN", "NOBYPASSRLS",
2925 "NOCREATEDB", "NOCREATEROLE", "NOINHERIT",
2926 "NOLOGIN", "NOREPLICATION", "NOSUPERUSER", "PASSWORD",
2927 "REPLICATION", "ROLE", "SUPERUSER", "SYSID",
2928 "VALID UNTIL", "WITH");
2929
2930 /* CREATE ROLE,USER,GROUP <name> WITH */
2931 else if (Matches("CREATE", "ROLE|GROUP|USER", MatchAny, "WITH"))
2932 /* Similar to the above, but don't complete "WITH" again. */
2933 COMPLETE_WITH("ADMIN", "BYPASSRLS", "CONNECTION LIMIT", "CREATEDB",
2934 "CREATEROLE", "ENCRYPTED PASSWORD", "IN", "INHERIT",
2935 "LOGIN", "NOBYPASSRLS",
2936 "NOCREATEDB", "NOCREATEROLE", "NOINHERIT",
2937 "NOLOGIN", "NOREPLICATION", "NOSUPERUSER", "PASSWORD",
2938 "REPLICATION", "ROLE", "SUPERUSER", "SYSID",
2939 "VALID UNTIL");
2940
2941 /* complete CREATE ROLE,USER,GROUP <name> IN with ROLE,GROUP */
2942 else if (Matches("CREATE", "ROLE|USER|GROUP", MatchAny, "IN"))
2943 COMPLETE_WITH("GROUP", "ROLE");
2944
2945 /* CREATE TYPE */
2946 else if (Matches("CREATE", "TYPE", MatchAny))
2947 COMPLETE_WITH("(", "AS");
2948 else if (Matches("CREATE", "TYPE", MatchAny, "AS"))
2949 COMPLETE_WITH("ENUM", "RANGE", "(");
2950 else if (HeadMatches("CREATE", "TYPE", MatchAny, "AS", "("))
2951 {
2952 if (TailMatches("(|*,", MatchAny))
2953 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_datatypes, NULL);
2954 else if (TailMatches("(|*,", MatchAny, MatchAnyExcept("*)")))
2955 COMPLETE_WITH("COLLATE", ",", ")");
2956 }
2957 else if (Matches("CREATE", "TYPE", MatchAny, "AS", "ENUM|RANGE"))
2958 COMPLETE_WITH("(");
2959 else if (HeadMatches("CREATE", "TYPE", MatchAny, "("))
2960 {
2961 if (TailMatches("(|*,"))
2962 COMPLETE_WITH("INPUT", "OUTPUT", "RECEIVE", "SEND",
2963 "TYPMOD_IN", "TYPMOD_OUT", "ANALYZE", "SUBSCRIPT",
2964 "INTERNALLENGTH", "PASSEDBYVALUE", "ALIGNMENT",
2965 "STORAGE", "LIKE", "CATEGORY", "PREFERRED",
2966 "DEFAULT", "ELEMENT", "DELIMITER",
2967 "COLLATABLE");
2968 else if (TailMatches("(*|*,", MatchAnyExcept("*=")))
2969 COMPLETE_WITH("=");
2970 else if (TailMatches("=", MatchAnyExcept("*)")))
2971 COMPLETE_WITH(",", ")");
2972 }
2973 else if (HeadMatches("CREATE", "TYPE", MatchAny, "AS", "RANGE", "("))
2974 {
2975 if (TailMatches("(|*,"))
2976 COMPLETE_WITH("SUBTYPE", "SUBTYPE_OPCLASS", "COLLATION",
2977 "CANONICAL", "SUBTYPE_DIFF",
2978 "MULTIRANGE_TYPE_NAME");
2979 else if (TailMatches("(*|*,", MatchAnyExcept("*=")))
2980 COMPLETE_WITH("=");
2981 else if (TailMatches("=", MatchAnyExcept("*)")))
2982 COMPLETE_WITH(",", ")");
2983 }
2984
2985 /* CREATE VIEW --- is allowed inside CREATE SCHEMA, so use TailMatches */
2986 /* Complete CREATE [ OR REPLACE ] VIEW <name> with AS */
2987 else if (TailMatches("CREATE", "VIEW", MatchAny) ||
2988 TailMatches("CREATE", "OR", "REPLACE", "VIEW", MatchAny))
2989 COMPLETE_WITH("AS");
2990 /* Complete "CREATE [ OR REPLACE ] VIEW <sth> AS with "SELECT" */
2991 else if (TailMatches("CREATE", "VIEW", MatchAny, "AS") ||
2992 TailMatches("CREATE", "OR", "REPLACE", "VIEW", MatchAny, "AS"))
2993 COMPLETE_WITH("SELECT");
2994
2995 /* CREATE MATERIALIZED VIEW */
2996 else if (Matches("CREATE", "MATERIALIZED"))
2997 COMPLETE_WITH("VIEW");
2998 /* Complete CREATE MATERIALIZED VIEW <name> with AS */
2999 else if (Matches("CREATE", "MATERIALIZED", "VIEW", MatchAny))
3000 COMPLETE_WITH("AS");
3001 /* Complete "CREATE MATERIALIZED VIEW <sth> AS with "SELECT" */
3002 else if (Matches("CREATE", "MATERIALIZED", "VIEW", MatchAny, "AS"))
3003 COMPLETE_WITH("SELECT");
3004
3005 /* CREATE EVENT TRIGGER */
3006 else if (Matches("CREATE", "EVENT"))
3007 COMPLETE_WITH("TRIGGER");
3008 /* Complete CREATE EVENT TRIGGER <name> with ON */
3009 else if (Matches("CREATE", "EVENT", "TRIGGER", MatchAny))
3010 COMPLETE_WITH("ON");
3011 /* Complete CREATE EVENT TRIGGER <name> ON with event_type */
3012 else if (Matches("CREATE", "EVENT", "TRIGGER", MatchAny, "ON"))
3013 COMPLETE_WITH("ddl_command_start", "ddl_command_end", "sql_drop");
3014
3015 /*
3016 * Complete CREATE EVENT TRIGGER <name> ON <event_type>. EXECUTE FUNCTION
3017 * is the recommended grammar instead of EXECUTE PROCEDURE in version 11
3018 * and upwards.
3019 */
3020 else if (Matches("CREATE", "EVENT", "TRIGGER", MatchAny, "ON", MatchAny))
3021 {
3022 if (pset.sversion >= 110000)
3023 COMPLETE_WITH("WHEN TAG IN (", "EXECUTE FUNCTION");
3024 else
3025 COMPLETE_WITH("WHEN TAG IN (", "EXECUTE PROCEDURE");
3026 }
3027 else if (HeadMatches("CREATE", "EVENT", "TRIGGER") &&
3028 TailMatches("WHEN|AND", MatchAny, "IN", "(*)"))
3029 {
3030 if (pset.sversion >= 110000)
3031 COMPLETE_WITH("EXECUTE FUNCTION");
3032 else
3033 COMPLETE_WITH("EXECUTE PROCEDURE");
3034 }
3035 else if (HeadMatches("CREATE", "EVENT", "TRIGGER") &&
3036 TailMatches("EXECUTE", "FUNCTION|PROCEDURE"))
3037 COMPLETE_WITH_VERSIONED_SCHEMA_QUERY(Query_for_list_of_functions, NULL);
3038
3039 /* DEALLOCATE */
3040 else if (Matches("DEALLOCATE"))
3041 COMPLETE_WITH_QUERY(Query_for_list_of_prepared_statements
3042 " UNION SELECT 'ALL'");
3043
3044 /* DECLARE */
3045
3046 /*
3047 * Complete DECLARE <name> with one of BINARY, INSENSITIVE, SCROLL, NO
3048 * SCROLL, and CURSOR.
3049 */
3050 else if (Matches("DECLARE", MatchAny))
3051 COMPLETE_WITH("BINARY", "ASENSITIVE", "INSENSITIVE", "SCROLL", "NO SCROLL",
3052 "CURSOR");
3053
3054 /*
3055 * Complete DECLARE ... <option> with other options. The PostgreSQL parser
3056 * allows DECLARE options to be specified in any order. But the
3057 * tab-completion follows the ordering of them that the SQL standard
3058 * provides, like the syntax of DECLARE command in the documentation
3059 * indicates.
3060 */
3061 else if (HeadMatches("DECLARE") && TailMatches("BINARY"))
3062 COMPLETE_WITH("INSENSITIVE", "SCROLL", "NO SCROLL", "CURSOR");
3063 else if (HeadMatches("DECLARE") && TailMatches("INSENSITIVE"))
3064 COMPLETE_WITH("SCROLL", "NO SCROLL", "CURSOR");
3065 else if (HeadMatches("DECLARE") && TailMatches("SCROLL"))
3066 COMPLETE_WITH("CURSOR");
3067 /* Complete DECLARE ... [options] NO with SCROLL */
3068 else if (HeadMatches("DECLARE") && TailMatches("NO"))
3069 COMPLETE_WITH("SCROLL");
3070
3071 /*
3072 * Complete DECLARE ... CURSOR with one of WITH HOLD, WITHOUT HOLD, and
3073 * FOR
3074 */
3075 else if (HeadMatches("DECLARE") && TailMatches("CURSOR"))
3076 COMPLETE_WITH("WITH HOLD", "WITHOUT HOLD", "FOR");
3077 /* Complete DECLARE ... CURSOR WITH|WITHOUT with HOLD */
3078 else if (HeadMatches("DECLARE") && TailMatches("CURSOR", "WITH|WITHOUT"))
3079 COMPLETE_WITH("HOLD");
3080 /* Complete DECLARE ... CURSOR WITH|WITHOUT HOLD with FOR */
3081 else if (HeadMatches("DECLARE") && TailMatches("CURSOR", "WITH|WITHOUT", "HOLD"))
3082 COMPLETE_WITH("FOR");
3083
3084 /* DELETE --- can be inside EXPLAIN, RULE, etc */
3085 /* Complete DELETE with "FROM" */
3086 else if (Matches("DELETE"))
3087 COMPLETE_WITH("FROM");
3088 /* Complete DELETE FROM with a list of tables */
3089 else if (TailMatches("DELETE", "FROM"))
3090 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_updatables, NULL);
3091 /* Complete DELETE FROM <table> */
3092 else if (TailMatches("DELETE", "FROM", MatchAny))
3093 COMPLETE_WITH("USING", "WHERE");
3094 /* XXX: implement tab completion for DELETE ... USING */
3095
3096 /* DISCARD */
3097 else if (Matches("DISCARD"))
3098 COMPLETE_WITH("ALL", "PLANS", "SEQUENCES", "TEMP");
3099
3100 /* DO */
3101 else if (Matches("DO"))
3102 COMPLETE_WITH("LANGUAGE");
3103
3104 /* DROP */
3105 /* Complete DROP object with CASCADE / RESTRICT */
3106 else if (Matches("DROP",
3107 "COLLATION|CONVERSION|DOMAIN|EXTENSION|LANGUAGE|PUBLICATION|SCHEMA|SEQUENCE|SERVER|SUBSCRIPTION|STATISTICS|TABLE|TYPE|VIEW",
3108 MatchAny) ||
3109 Matches("DROP", "ACCESS", "METHOD", MatchAny) ||
3110 (Matches("DROP", "AGGREGATE|FUNCTION|PROCEDURE|ROUTINE", MatchAny, MatchAny) &&
3111 ends_with(prev_wd, ')')) ||
3112 Matches("DROP", "EVENT", "TRIGGER", MatchAny) ||
3113 Matches("DROP", "FOREIGN", "DATA", "WRAPPER", MatchAny) ||
3114 Matches("DROP", "FOREIGN", "TABLE", MatchAny) ||
3115 Matches("DROP", "TEXT", "SEARCH", "CONFIGURATION|DICTIONARY|PARSER|TEMPLATE", MatchAny))
3116 COMPLETE_WITH("CASCADE", "RESTRICT");
3117
3118 /* help completing some of the variants */
3119 else if (Matches("DROP", "AGGREGATE|FUNCTION|PROCEDURE|ROUTINE", MatchAny))
3120 COMPLETE_WITH("(");
3121 else if (Matches("DROP", "AGGREGATE|FUNCTION|PROCEDURE|ROUTINE", MatchAny, "("))
3122 COMPLETE_WITH_FUNCTION_ARG(prev2_wd);
3123 else if (Matches("DROP", "FOREIGN"))
3124 COMPLETE_WITH("DATA WRAPPER", "TABLE");
3125 else if (Matches("DROP", "DATABASE", MatchAny))
3126 COMPLETE_WITH("WITH (");
3127 else if (HeadMatches("DROP", "DATABASE") && (ends_with(prev_wd, '(')))
3128 COMPLETE_WITH("FORCE");
3129
3130 /* DROP INDEX */
3131 else if (Matches("DROP", "INDEX"))
3132 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_indexes,
3133 " UNION SELECT 'CONCURRENTLY'");
3134 else if (Matches("DROP", "INDEX", "CONCURRENTLY"))
3135 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_indexes, NULL);
3136 else if (Matches("DROP", "INDEX", MatchAny))
3137 COMPLETE_WITH("CASCADE", "RESTRICT");
3138 else if (Matches("DROP", "INDEX", "CONCURRENTLY", MatchAny))
3139 COMPLETE_WITH("CASCADE", "RESTRICT");
3140
3141 /* DROP MATERIALIZED VIEW */
3142 else if (Matches("DROP", "MATERIALIZED"))
3143 COMPLETE_WITH("VIEW");
3144 else if (Matches("DROP", "MATERIALIZED", "VIEW"))
3145 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_matviews, NULL);
3146
3147 /* DROP OWNED BY */
3148 else if (Matches("DROP", "OWNED"))
3149 COMPLETE_WITH("BY");
3150 else if (Matches("DROP", "OWNED", "BY"))
3151 COMPLETE_WITH_QUERY(Query_for_list_of_roles);
3152
3153 /* DROP TEXT SEARCH */
3154 else if (Matches("DROP", "TEXT", "SEARCH"))
3155 COMPLETE_WITH("CONFIGURATION", "DICTIONARY", "PARSER", "TEMPLATE");
3156
3157 /* DROP TRIGGER */
3158 else if (Matches("DROP", "TRIGGER", MatchAny))
3159 COMPLETE_WITH("ON");
3160 else if (Matches("DROP", "TRIGGER", MatchAny, "ON"))
3161 {
3162 completion_info_charp = prev2_wd;
3163 COMPLETE_WITH_QUERY(Query_for_list_of_tables_for_trigger);
3164 }
3165 else if (Matches("DROP", "TRIGGER", MatchAny, "ON", MatchAny))
3166 COMPLETE_WITH("CASCADE", "RESTRICT");
3167
3168 /* DROP ACCESS METHOD */
3169 else if (Matches("DROP", "ACCESS"))
3170 COMPLETE_WITH("METHOD");
3171 else if (Matches("DROP", "ACCESS", "METHOD"))
3172 COMPLETE_WITH_QUERY(Query_for_list_of_access_methods);
3173
3174 /* DROP EVENT TRIGGER */
3175 else if (Matches("DROP", "EVENT"))
3176 COMPLETE_WITH("TRIGGER");
3177 else if (Matches("DROP", "EVENT", "TRIGGER"))
3178 COMPLETE_WITH_QUERY(Query_for_list_of_event_triggers);
3179
3180 /* DROP POLICY <name> */
3181 else if (Matches("DROP", "POLICY"))
3182 COMPLETE_WITH_QUERY(Query_for_list_of_policies);
3183 /* DROP POLICY <name> ON */
3184 else if (Matches("DROP", "POLICY", MatchAny))
3185 COMPLETE_WITH("ON");
3186 /* DROP POLICY <name> ON <table> */
3187 else if (Matches("DROP", "POLICY", MatchAny, "ON"))
3188 {
3189 completion_info_charp = prev2_wd;
3190 COMPLETE_WITH_QUERY(Query_for_list_of_tables_for_policy);
3191 }
3192
3193 /* DROP RULE */
3194 else if (Matches("DROP", "RULE", MatchAny))
3195 COMPLETE_WITH("ON");
3196 else if (Matches("DROP", "RULE", MatchAny, "ON"))
3197 {
3198 completion_info_charp = prev2_wd;
3199 COMPLETE_WITH_QUERY(Query_for_list_of_tables_for_rule);
3200 }
3201 else if (Matches("DROP", "RULE", MatchAny, "ON", MatchAny))
3202 COMPLETE_WITH("CASCADE", "RESTRICT");
3203
3204 /* EXECUTE */
3205 else if (Matches("EXECUTE"))
3206 COMPLETE_WITH_QUERY(Query_for_list_of_prepared_statements);
3207
3208 /*
3209 * EXPLAIN [ ( option [, ...] ) ] statement
3210 * EXPLAIN [ ANALYZE ] [ VERBOSE ] statement
3211 */
3212 else if (Matches("EXPLAIN"))
3213 COMPLETE_WITH("SELECT", "INSERT INTO", "DELETE FROM", "UPDATE", "DECLARE",
3214 "ANALYZE", "VERBOSE");
3215 else if (HeadMatches("EXPLAIN", "(*") &&
3216 !HeadMatches("EXPLAIN", "(*)"))
3217 {
3218 /*
3219 * This fires if we're in an unfinished parenthesized option list.
3220 * get_previous_words treats a completed parenthesized option list as
3221 * one word, so the above test is correct.
3222 */
3223 if (ends_with(prev_wd, '(') || ends_with(prev_wd, ','))
3224 COMPLETE_WITH("ANALYZE", "VERBOSE", "COSTS", "SETTINGS",
3225 "BUFFERS", "WAL", "TIMING", "SUMMARY", "FORMAT");
3226 else if (TailMatches("ANALYZE|VERBOSE|COSTS|SETTINGS|BUFFERS|WAL|TIMING|SUMMARY"))
3227 COMPLETE_WITH("ON", "OFF");
3228 else if (TailMatches("FORMAT"))
3229 COMPLETE_WITH("TEXT", "XML", "JSON", "YAML");
3230 }
3231 else if (Matches("EXPLAIN", "ANALYZE"))
3232 COMPLETE_WITH("SELECT", "INSERT INTO", "DELETE FROM", "UPDATE", "DECLARE",
3233 "VERBOSE");
3234 else if (Matches("EXPLAIN", "(*)") ||
3235 Matches("EXPLAIN", "VERBOSE") ||
3236 Matches("EXPLAIN", "ANALYZE", "VERBOSE"))
3237 COMPLETE_WITH("SELECT", "INSERT INTO", "DELETE FROM", "UPDATE", "DECLARE");
3238
3239 /* FETCH && MOVE */
3240
3241 /*
3242 * Complete FETCH with one of ABSOLUTE, BACKWARD, FORWARD, RELATIVE, ALL,
3243 * NEXT, PRIOR, FIRST, LAST, FROM, IN, and a list of cursors
3244 */
3245 else if (Matches("FETCH|MOVE"))
3246 COMPLETE_WITH_QUERY(Query_for_list_of_cursors
3247 " UNION SELECT 'ABSOLUTE'"
3248 " UNION SELECT 'BACKWARD'"
3249 " UNION SELECT 'FORWARD'"
3250 " UNION SELECT 'RELATIVE'"
3251 " UNION SELECT 'ALL'"
3252 " UNION SELECT 'NEXT'"
3253 " UNION SELECT 'PRIOR'"
3254 " UNION SELECT 'FIRST'"
3255 " UNION SELECT 'LAST'"
3256 " UNION SELECT 'FROM'"
3257 " UNION SELECT 'IN'");
3258
3259 /*
3260 * Complete FETCH BACKWARD or FORWARD with one of ALL, FROM, IN, and a
3261 * list of cursors
3262 */
3263 else if (Matches("FETCH|MOVE", "BACKWARD|FORWARD"))
3264 COMPLETE_WITH_QUERY(Query_for_list_of_cursors
3265 " UNION SELECT 'ALL'"
3266 " UNION SELECT 'FROM'"
3267 " UNION SELECT 'IN'");
3268
3269 /*
3270 * Complete FETCH <direction> with "FROM" or "IN". These are equivalent,
3271 * but we may as well tab-complete both: perhaps some users prefer one
3272 * variant or the other.
3273 */
3274 else if (Matches("FETCH|MOVE", "ABSOLUTE|BACKWARD|FORWARD|RELATIVE",
3275 MatchAnyExcept("FROM|IN")) ||
3276 Matches("FETCH|MOVE", "ALL|NEXT|PRIOR|FIRST|LAST"))
3277 COMPLETE_WITH_QUERY(Query_for_list_of_cursors
3278 " UNION SELECT 'FROM'"
3279 " UNION SELECT 'IN'");
3280 /* Complete FETCH <direction> "FROM" or "IN" with a list of cursors */
3281 else if (HeadMatches("FETCH|MOVE") &&
3282 TailMatches("FROM|IN"))
3283 COMPLETE_WITH_QUERY(Query_for_list_of_cursors);
3284
3285 /* FOREIGN DATA WRAPPER */
3286 /* applies in ALTER/DROP FDW and in CREATE SERVER */
3287 else if (TailMatches("FOREIGN", "DATA", "WRAPPER") &&
3288 !TailMatches("CREATE", MatchAny, MatchAny, MatchAny))
3289 COMPLETE_WITH_QUERY(Query_for_list_of_fdws);
3290 /* applies in CREATE SERVER */
3291 else if (TailMatches("FOREIGN", "DATA", "WRAPPER", MatchAny) &&
3292 HeadMatches("CREATE", "SERVER"))
3293 COMPLETE_WITH("OPTIONS");
3294
3295 /* FOREIGN TABLE */
3296 else if (TailMatches("FOREIGN", "TABLE") &&
3297 !TailMatches("CREATE", MatchAny, MatchAny))
3298 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_foreign_tables, NULL);
3299
3300 /* FOREIGN SERVER */
3301 else if (TailMatches("FOREIGN", "SERVER"))
3302 COMPLETE_WITH_QUERY(Query_for_list_of_servers);
3303
3304 /*
3305 * GRANT and REVOKE are allowed inside CREATE SCHEMA and
3306 * ALTER DEFAULT PRIVILEGES, so use TailMatches
3307 */
3308 /* Complete GRANT/REVOKE with a list of roles and privileges */
3309 else if (TailMatches("GRANT|REVOKE"))
3310 {
3311 /*
3312 * With ALTER DEFAULT PRIVILEGES, restrict completion to grantable
3313 * privileges (can't grant roles)
3314 */
3315 if (HeadMatches("ALTER", "DEFAULT", "PRIVILEGES"))
3316 COMPLETE_WITH("SELECT", "INSERT", "UPDATE",
3317 "DELETE", "TRUNCATE", "REFERENCES", "TRIGGER",
3318 "EXECUTE", "USAGE", "ALL");
3319 else
3320 COMPLETE_WITH_QUERY(Query_for_list_of_roles
3321 " UNION SELECT 'SELECT'"
3322 " UNION SELECT 'INSERT'"
3323 " UNION SELECT 'UPDATE'"
3324 " UNION SELECT 'DELETE'"
3325 " UNION SELECT 'TRUNCATE'"
3326 " UNION SELECT 'REFERENCES'"
3327 " UNION SELECT 'TRIGGER'"
3328 " UNION SELECT 'CREATE'"
3329 " UNION SELECT 'CONNECT'"
3330 " UNION SELECT 'TEMPORARY'"
3331 " UNION SELECT 'EXECUTE'"
3332 " UNION SELECT 'USAGE'"
3333 " UNION SELECT 'ALL'");
3334 }
3335
3336 /*
3337 * Complete GRANT/REVOKE <privilege> with "ON", GRANT/REVOKE <role> with
3338 * TO/FROM
3339 */
3340 else if (TailMatches("GRANT|REVOKE", MatchAny))
3341 {
3342 if (TailMatches("SELECT|INSERT|UPDATE|DELETE|TRUNCATE|REFERENCES|TRIGGER|CREATE|CONNECT|TEMPORARY|TEMP|EXECUTE|USAGE|ALL"))
3343 COMPLETE_WITH("ON");
3344 else if (TailMatches("GRANT", MatchAny))
3345 COMPLETE_WITH("TO");
3346 else
3347 COMPLETE_WITH("FROM");
3348 }
3349
3350 /*
3351 * Complete GRANT/REVOKE <sth> ON with a list of appropriate relations.
3352 *
3353 * Keywords like DATABASE, FUNCTION, LANGUAGE and SCHEMA added to query
3354 * result via UNION; seems to work intuitively.
3355 *
3356 * Note: GRANT/REVOKE can get quite complex; tab-completion as implemented
3357 * here will only work if the privilege list contains exactly one
3358 * privilege.
3359 */
3360 else if (TailMatches("GRANT|REVOKE", MatchAny, "ON"))
3361 {
3362 /*
3363 * With ALTER DEFAULT PRIVILEGES, restrict completion to the kinds of
3364 * objects supported.
3365 */
3366 if (HeadMatches("ALTER", "DEFAULT", "PRIVILEGES"))
3367 COMPLETE_WITH("TABLES", "SEQUENCES", "FUNCTIONS", "PROCEDURES", "ROUTINES", "TYPES", "SCHEMAS");
3368 else
3369 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_grantables,
3370 " UNION SELECT 'ALL FUNCTIONS IN SCHEMA'"
3371 " UNION SELECT 'ALL PROCEDURES IN SCHEMA'"
3372 " UNION SELECT 'ALL ROUTINES IN SCHEMA'"
3373 " UNION SELECT 'ALL SEQUENCES IN SCHEMA'"
3374 " UNION SELECT 'ALL TABLES IN SCHEMA'"
3375 " UNION SELECT 'DATABASE'"
3376 " UNION SELECT 'DOMAIN'"
3377 " UNION SELECT 'FOREIGN DATA WRAPPER'"
3378 " UNION SELECT 'FOREIGN SERVER'"
3379 " UNION SELECT 'FUNCTION'"
3380 " UNION SELECT 'LANGUAGE'"
3381 " UNION SELECT 'LARGE OBJECT'"
3382 " UNION SELECT 'PROCEDURE'"
3383 " UNION SELECT 'ROUTINE'"
3384 " UNION SELECT 'SCHEMA'"
3385 " UNION SELECT 'SEQUENCE'"
3386 " UNION SELECT 'TABLE'"
3387 " UNION SELECT 'TABLESPACE'"
3388 " UNION SELECT 'TYPE'");
3389 }
3390 else if (TailMatches("GRANT|REVOKE", MatchAny, "ON", "ALL"))
3391 COMPLETE_WITH("FUNCTIONS IN SCHEMA",
3392 "PROCEDURES IN SCHEMA",
3393 "ROUTINES IN SCHEMA",
3394 "SEQUENCES IN SCHEMA",
3395 "TABLES IN SCHEMA");
3396 else if (TailMatches("GRANT|REVOKE", MatchAny, "ON", "FOREIGN"))
3397 COMPLETE_WITH("DATA WRAPPER", "SERVER");
3398
3399 /*
3400 * Complete "GRANT/REVOKE * ON DATABASE/DOMAIN/..." with a list of
3401 * appropriate objects.
3402 *
3403 * Complete "GRANT/REVOKE * ON *" with "TO/FROM".
3404 */
3405 else if (TailMatches("GRANT|REVOKE", MatchAny, "ON", MatchAny))
3406 {
3407 if (TailMatches("DATABASE"))
3408 COMPLETE_WITH_QUERY(Query_for_list_of_databases);
3409 else if (TailMatches("DOMAIN"))
3410 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_domains, NULL);
3411 else if (TailMatches("FUNCTION"))
3412 COMPLETE_WITH_VERSIONED_SCHEMA_QUERY(Query_for_list_of_functions, NULL);
3413 else if (TailMatches("LANGUAGE"))
3414 COMPLETE_WITH_QUERY(Query_for_list_of_languages);
3415 else if (TailMatches("PROCEDURE"))
3416 COMPLETE_WITH_VERSIONED_SCHEMA_QUERY(Query_for_list_of_procedures, NULL);
3417 else if (TailMatches("ROUTINE"))
3418 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_routines, NULL);
3419 else if (TailMatches("SCHEMA"))
3420 COMPLETE_WITH_QUERY(Query_for_list_of_schemas);
3421 else if (TailMatches("SEQUENCE"))
3422 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_sequences, NULL);
3423 else if (TailMatches("TABLE"))
3424 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_grantables, NULL);
3425 else if (TailMatches("TABLESPACE"))
3426 COMPLETE_WITH_QUERY(Query_for_list_of_tablespaces);
3427 else if (TailMatches("TYPE"))
3428 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_datatypes, NULL);
3429 else if (TailMatches("GRANT", MatchAny, MatchAny, MatchAny))
3430 COMPLETE_WITH("TO");
3431 else
3432 COMPLETE_WITH("FROM");
3433 }
3434
3435 /*
3436 * Complete "GRANT/REVOKE ... TO/FROM" with username, PUBLIC,
3437 * CURRENT_ROLE, CURRENT_USER, or SESSION_USER.
3438 */
3439 else if ((HeadMatches("GRANT") && TailMatches("TO")) ||
3440 (HeadMatches("REVOKE") && TailMatches("FROM")))
3441 COMPLETE_WITH_QUERY(Query_for_list_of_grant_roles);
3442 /* Complete "ALTER DEFAULT PRIVILEGES ... GRANT/REVOKE ... TO/FROM */
3443 else if (HeadMatches("ALTER", "DEFAULT", "PRIVILEGES") && TailMatches("TO|FROM"))
3444 COMPLETE_WITH_QUERY(Query_for_list_of_grant_roles);
3445 /* Complete "GRANT/REVOKE ... ON * *" with TO/FROM */
3446 else if (HeadMatches("GRANT") && TailMatches("ON", MatchAny, MatchAny))
3447 COMPLETE_WITH("TO");
3448 else if (HeadMatches("REVOKE") && TailMatches("ON", MatchAny, MatchAny))
3449 COMPLETE_WITH("FROM");
3450
3451 /* Complete "GRANT/REVOKE * ON ALL * IN SCHEMA *" with TO/FROM */
3452 else if (TailMatches("GRANT|REVOKE", MatchAny, "ON", "ALL", MatchAny, "IN", "SCHEMA", MatchAny))
3453 {
3454 if (TailMatches("GRANT", MatchAny, MatchAny, MatchAny, MatchAny, MatchAny, MatchAny, MatchAny))
3455 COMPLETE_WITH("TO");
3456 else
3457 COMPLETE_WITH("FROM");
3458 }
3459
3460 /* Complete "GRANT/REVOKE * ON FOREIGN DATA WRAPPER *" with TO/FROM */
3461 else if (TailMatches("GRANT|REVOKE", MatchAny, "ON", "FOREIGN", "DATA", "WRAPPER", MatchAny))
3462 {
3463 if (TailMatches("GRANT", MatchAny, MatchAny, MatchAny, MatchAny, MatchAny, MatchAny))
3464 COMPLETE_WITH("TO");
3465 else
3466 COMPLETE_WITH("FROM");
3467 }
3468
3469 /* Complete "GRANT/REVOKE * ON FOREIGN SERVER *" with TO/FROM */
3470 else if (TailMatches("GRANT|REVOKE", MatchAny, "ON", "FOREIGN", "SERVER", MatchAny))
3471 {
3472 if (TailMatches("GRANT", MatchAny, MatchAny, MatchAny, MatchAny, MatchAny))
3473 COMPLETE_WITH("TO");
3474 else
3475 COMPLETE_WITH("FROM");
3476 }
3477
3478 /* GROUP BY */
3479 else if (TailMatches("FROM", MatchAny, "GROUP"))
3480 COMPLETE_WITH("BY");
3481
3482 /* IMPORT FOREIGN SCHEMA */
3483 else if (Matches("IMPORT"))
3484 COMPLETE_WITH("FOREIGN SCHEMA");
3485 else if (Matches("IMPORT", "FOREIGN"))
3486 COMPLETE_WITH("SCHEMA");
3487 else if (Matches("IMPORT", "FOREIGN", "SCHEMA", MatchAny))
3488 COMPLETE_WITH("EXCEPT (", "FROM SERVER", "LIMIT TO (");
3489 else if (TailMatches("LIMIT", "TO", "(*)") ||
3490 TailMatches("EXCEPT", "(*)"))
3491 COMPLETE_WITH("FROM SERVER");
3492 else if (TailMatches("FROM", "SERVER", MatchAny))
3493 COMPLETE_WITH("INTO");
3494 else if (TailMatches("FROM", "SERVER", MatchAny, "INTO"))
3495 COMPLETE_WITH_QUERY(Query_for_list_of_schemas);
3496 else if (TailMatches("FROM", "SERVER", MatchAny, "INTO", MatchAny))
3497 COMPLETE_WITH("OPTIONS (");
3498
3499 /* INSERT --- can be inside EXPLAIN, RULE, etc */
3500 /* Complete INSERT with "INTO" */
3501 else if (TailMatches("INSERT"))
3502 COMPLETE_WITH("INTO");
3503 /* Complete INSERT INTO with table names */
3504 else if (TailMatches("INSERT", "INTO"))
3505 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_updatables, NULL);
3506 /* Complete "INSERT INTO <table> (" with attribute names */
3507 else if (TailMatches("INSERT", "INTO", MatchAny, "("))
3508 COMPLETE_WITH_ATTR(prev2_wd, "");
3509
3510 /*
3511 * Complete INSERT INTO <table> with "(" or "VALUES" or "SELECT" or
3512 * "TABLE" or "DEFAULT VALUES" or "OVERRIDING"
3513 */
3514 else if (TailMatches("INSERT", "INTO", MatchAny))
3515 COMPLETE_WITH("(", "DEFAULT VALUES", "SELECT", "TABLE", "VALUES", "OVERRIDING");
3516
3517 /*
3518 * Complete INSERT INTO <table> (attribs) with "VALUES" or "SELECT" or
3519 * "TABLE" or "OVERRIDING"
3520 */
3521 else if (TailMatches("INSERT", "INTO", MatchAny, MatchAny) &&
3522 ends_with(prev_wd, ')'))
3523 COMPLETE_WITH("SELECT", "TABLE", "VALUES", "OVERRIDING");
3524
3525 /* Complete OVERRIDING */
3526 else if (TailMatches("OVERRIDING"))
3527 COMPLETE_WITH("SYSTEM VALUE", "USER VALUE");
3528
3529 /* Complete after OVERRIDING clause */
3530 else if (TailMatches("OVERRIDING", MatchAny, "VALUE"))
3531 COMPLETE_WITH("SELECT", "TABLE", "VALUES");
3532
3533 /* Insert an open parenthesis after "VALUES" */
3534 else if (TailMatches("VALUES") && !TailMatches("DEFAULT", "VALUES"))
3535 COMPLETE_WITH("(");
3536
3537 /* LOCK */
3538 /* Complete LOCK [TABLE] with a list of tables */
3539 else if (Matches("LOCK"))
3540 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables,
3541 " UNION SELECT 'TABLE'");
3542 else if (Matches("LOCK", "TABLE"))
3543 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, "");
3544
3545 /* For the following, handle the case of a single table only for now */
3546
3547 /* Complete LOCK [TABLE] <table> with "IN" */
3548 else if (Matches("LOCK", MatchAnyExcept("TABLE")) ||
3549 Matches("LOCK", "TABLE", MatchAny))
3550 COMPLETE_WITH("IN");
3551
3552 /* Complete LOCK [TABLE] <table> IN with a lock mode */
3553 else if (Matches("LOCK", MatchAny, "IN") ||
3554 Matches("LOCK", "TABLE", MatchAny, "IN"))
3555 COMPLETE_WITH("ACCESS SHARE MODE",
3556 "ROW SHARE MODE", "ROW EXCLUSIVE MODE",
3557 "SHARE UPDATE EXCLUSIVE MODE", "SHARE MODE",
3558 "SHARE ROW EXCLUSIVE MODE",
3559 "EXCLUSIVE MODE", "ACCESS EXCLUSIVE MODE");
3560
3561 /* Complete LOCK [TABLE] <table> IN ACCESS|ROW with rest of lock mode */
3562 else if (Matches("LOCK", MatchAny, "IN", "ACCESS|ROW") ||
3563 Matches("LOCK", "TABLE", MatchAny, "IN", "ACCESS|ROW"))
3564 COMPLETE_WITH("EXCLUSIVE MODE", "SHARE MODE");
3565
3566 /* Complete LOCK [TABLE] <table> IN SHARE with rest of lock mode */
3567 else if (Matches("LOCK", MatchAny, "IN", "SHARE") ||
3568 Matches("LOCK", "TABLE", MatchAny, "IN", "SHARE"))
3569 COMPLETE_WITH("MODE", "ROW EXCLUSIVE MODE",
3570 "UPDATE EXCLUSIVE MODE");
3571
3572 /* NOTIFY --- can be inside EXPLAIN, RULE, etc */
3573 else if (TailMatches("NOTIFY"))
3574 COMPLETE_WITH_QUERY("SELECT pg_catalog.quote_ident(channel) FROM pg_catalog.pg_listening_channels() AS channel WHERE substring(pg_catalog.quote_ident(channel),1,%d)='%s'");
3575
3576 /* OPTIONS */
3577 else if (TailMatches("OPTIONS"))
3578 COMPLETE_WITH("(");
3579
3580 /* OWNER TO - complete with available roles */
3581 else if (TailMatches("OWNER", "TO"))
3582 COMPLETE_WITH_QUERY(Query_for_list_of_roles);
3583
3584 /* ORDER BY */
3585 else if (TailMatches("FROM", MatchAny, "ORDER"))
3586 COMPLETE_WITH("BY");
3587 else if (TailMatches("FROM", MatchAny, "ORDER", "BY"))
3588 COMPLETE_WITH_ATTR(prev3_wd, "");
3589
3590 /* PREPARE xx AS */
3591 else if (Matches("PREPARE", MatchAny, "AS"))
3592 COMPLETE_WITH("SELECT", "UPDATE", "INSERT INTO", "DELETE FROM");
3593
3594 /*
3595 * PREPARE TRANSACTION is missing on purpose. It's intended for transaction
3596 * managers, not for manual use in interactive sessions.
3597 */
3598
3599 /* REASSIGN OWNED BY xxx TO yyy */
3600 else if (Matches("REASSIGN"))
3601 COMPLETE_WITH("OWNED BY");
3602 else if (Matches("REASSIGN", "OWNED"))
3603 COMPLETE_WITH("BY");
3604 else if (Matches("REASSIGN", "OWNED", "BY"))
3605 COMPLETE_WITH_QUERY(Query_for_list_of_roles);
3606 else if (Matches("REASSIGN", "OWNED", "BY", MatchAny))
3607 COMPLETE_WITH("TO");
3608 else if (Matches("REASSIGN", "OWNED", "BY", MatchAny, "TO"))
3609 COMPLETE_WITH_QUERY(Query_for_list_of_roles);
3610
3611 /* REFRESH MATERIALIZED VIEW */
3612 else if (Matches("REFRESH"))
3613 COMPLETE_WITH("MATERIALIZED VIEW");
3614 else if (Matches("REFRESH", "MATERIALIZED"))
3615 COMPLETE_WITH("VIEW");
3616 else if (Matches("REFRESH", "MATERIALIZED", "VIEW"))
3617 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_matviews,
3618 " UNION SELECT 'CONCURRENTLY'");
3619 else if (Matches("REFRESH", "MATERIALIZED", "VIEW", "CONCURRENTLY"))
3620 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_matviews, NULL);
3621 else if (Matches("REFRESH", "MATERIALIZED", "VIEW", MatchAny))
3622 COMPLETE_WITH("WITH");
3623 else if (Matches("REFRESH", "MATERIALIZED", "VIEW", "CONCURRENTLY", MatchAny))
3624 COMPLETE_WITH("WITH");
3625 else if (Matches("REFRESH", "MATERIALIZED", "VIEW", MatchAny, "WITH"))
3626 COMPLETE_WITH("NO DATA", "DATA");
3627 else if (Matches("REFRESH", "MATERIALIZED", "VIEW", "CONCURRENTLY", MatchAny, "WITH"))
3628 COMPLETE_WITH("NO DATA", "DATA");
3629 else if (Matches("REFRESH", "MATERIALIZED", "VIEW", MatchAny, "WITH", "NO"))
3630 COMPLETE_WITH("DATA");
3631 else if (Matches("REFRESH", "MATERIALIZED", "VIEW", "CONCURRENTLY", MatchAny, "WITH", "NO"))
3632 COMPLETE_WITH("DATA");
3633
3634 /* REINDEX */
3635 else if (Matches("REINDEX") ||
3636 Matches("REINDEX", "(*)"))
3637 COMPLETE_WITH("TABLE", "INDEX", "SYSTEM", "SCHEMA", "DATABASE");
3638 else if (Matches("REINDEX", "TABLE") ||
3639 Matches("REINDEX", "(*)", "TABLE"))
3640 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_indexables,
3641 " UNION SELECT 'CONCURRENTLY'");
3642 else if (Matches("REINDEX", "INDEX") ||
3643 Matches("REINDEX", "(*)", "INDEX"))
3644 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_indexes,
3645 " UNION SELECT 'CONCURRENTLY'");
3646 else if (Matches("REINDEX", "SCHEMA") ||
3647 Matches("REINDEX", "(*)", "SCHEMA"))
3648 COMPLETE_WITH_QUERY(Query_for_list_of_schemas
3649 " UNION SELECT 'CONCURRENTLY'");
3650 else if (Matches("REINDEX", "SYSTEM|DATABASE") ||
3651 Matches("REINDEX", "(*)", "SYSTEM|DATABASE"))
3652 COMPLETE_WITH_QUERY(Query_for_list_of_databases
3653 " UNION SELECT 'CONCURRENTLY'");
3654 else if (Matches("REINDEX", "TABLE", "CONCURRENTLY") ||
3655 Matches("REINDEX", "(*)", "TABLE", "CONCURRENTLY"))
3656 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_indexables, NULL);
3657 else if (Matches("REINDEX", "INDEX", "CONCURRENTLY") ||
3658 Matches("REINDEX", "(*)", "INDEX", "CONCURRENTLY"))
3659 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_indexes, NULL);
3660 else if (Matches("REINDEX", "SCHEMA", "CONCURRENTLY") ||
3661 Matches("REINDEX", "(*)", "SCHEMA", "CONCURRENTLY"))
3662 COMPLETE_WITH_QUERY(Query_for_list_of_schemas);
3663 else if (Matches("REINDEX", "SYSTEM|DATABASE", "CONCURRENTLY") ||
3664 Matches("REINDEX", "(*)", "SYSTEM|DATABASE", "CONCURRENTLY"))
3665 COMPLETE_WITH_QUERY(Query_for_list_of_databases);
3666 else if (HeadMatches("REINDEX", "(*") &&
3667 !HeadMatches("REINDEX", "(*)"))
3668 {
3669 /*
3670 * This fires if we're in an unfinished parenthesized option list.
3671 * get_previous_words treats a completed parenthesized option list as
3672 * one word, so the above test is correct.
3673 */
3674 if (ends_with(prev_wd, '(') || ends_with(prev_wd, ','))
3675 COMPLETE_WITH("CONCURRENTLY", "TABLESPACE", "VERBOSE");
3676 else if (TailMatches("TABLESPACE"))
3677 COMPLETE_WITH_QUERY(Query_for_list_of_tablespaces);
3678 }
3679
3680 /* SECURITY LABEL */
3681 else if (Matches("SECURITY"))
3682 COMPLETE_WITH("LABEL");
3683 else if (Matches("SECURITY", "LABEL"))
3684 COMPLETE_WITH("ON", "FOR");
3685 else if (Matches("SECURITY", "LABEL", "FOR", MatchAny))
3686 COMPLETE_WITH("ON");
3687 else if (Matches("SECURITY", "LABEL", "ON") ||
3688 Matches("SECURITY", "LABEL", "FOR", MatchAny, "ON"))
3689 COMPLETE_WITH("TABLE", "COLUMN", "AGGREGATE", "DATABASE", "DOMAIN",
3690 "EVENT TRIGGER", "FOREIGN TABLE", "FUNCTION",
3691 "LARGE OBJECT", "MATERIALIZED VIEW", "LANGUAGE",
3692 "PUBLICATION", "PROCEDURE", "ROLE", "ROUTINE", "SCHEMA",
3693 "SEQUENCE", "SUBSCRIPTION", "TABLESPACE", "TYPE", "VIEW");
3694 else if (Matches("SECURITY", "LABEL", "ON", MatchAny, MatchAny))
3695 COMPLETE_WITH("IS");
3696
3697 /* SELECT */
3698 /* naah . . . */
3699
3700 /* SET, RESET, SHOW */
3701 /* Complete with a variable name */
3702 else if (TailMatches("SET|RESET") && !TailMatches("UPDATE", MatchAny, "SET"))
3703 COMPLETE_WITH_QUERY(Query_for_list_of_set_vars);
3704 else if (Matches("SHOW"))
3705 COMPLETE_WITH_QUERY(Query_for_list_of_show_vars);
3706 /* Complete "SET TRANSACTION" */
3707 else if (Matches("SET", "TRANSACTION"))
3708 COMPLETE_WITH("SNAPSHOT", "ISOLATION LEVEL", "READ", "DEFERRABLE", "NOT DEFERRABLE");
3709 else if (Matches("BEGIN|START", "TRANSACTION") ||
3710 Matches("BEGIN", "WORK") ||
3711 Matches("BEGIN") ||
3712 Matches("SET", "SESSION", "CHARACTERISTICS", "AS", "TRANSACTION"))
3713 COMPLETE_WITH("ISOLATION LEVEL", "READ", "DEFERRABLE", "NOT DEFERRABLE");
3714 else if (Matches("SET|BEGIN|START", "TRANSACTION|WORK", "NOT") ||
3715 Matches("BEGIN", "NOT") ||
3716 Matches("SET", "SESSION", "CHARACTERISTICS", "AS", "TRANSACTION", "NOT"))
3717 COMPLETE_WITH("DEFERRABLE");
3718 else if (Matches("SET|BEGIN|START", "TRANSACTION|WORK", "ISOLATION") ||
3719 Matches("BEGIN", "ISOLATION") ||
3720 Matches("SET", "SESSION", "CHARACTERISTICS", "AS", "TRANSACTION", "ISOLATION"))
3721 COMPLETE_WITH("LEVEL");
3722 else if (Matches("SET|BEGIN|START", "TRANSACTION|WORK", "ISOLATION", "LEVEL") ||
3723 Matches("BEGIN", "ISOLATION", "LEVEL") ||
3724 Matches("SET", "SESSION", "CHARACTERISTICS", "AS", "TRANSACTION", "ISOLATION", "LEVEL"))
3725 COMPLETE_WITH("READ", "REPEATABLE READ", "SERIALIZABLE");
3726 else if (Matches("SET|BEGIN|START", "TRANSACTION|WORK", "ISOLATION", "LEVEL", "READ") ||
3727 Matches("BEGIN", "ISOLATION", "LEVEL", "READ") ||
3728 Matches("SET", "SESSION", "CHARACTERISTICS", "AS", "TRANSACTION", "ISOLATION", "LEVEL", "READ"))
3729 COMPLETE_WITH("UNCOMMITTED", "COMMITTED");
3730 else if (Matches("SET|BEGIN|START", "TRANSACTION|WORK", "ISOLATION", "LEVEL", "REPEATABLE") ||
3731 Matches("BEGIN", "ISOLATION", "LEVEL", "REPEATABLE") ||
3732 Matches("SET", "SESSION", "CHARACTERISTICS", "AS", "TRANSACTION", "ISOLATION", "LEVEL", "REPEATABLE"))
3733 COMPLETE_WITH("READ");
3734 else if (Matches("SET|BEGIN|START", "TRANSACTION|WORK", "READ") ||
3735 Matches("BEGIN", "READ") ||
3736 Matches("SET", "SESSION", "CHARACTERISTICS", "AS", "TRANSACTION", "READ"))
3737 COMPLETE_WITH("ONLY", "WRITE");
3738 /* SET CONSTRAINTS */
3739 else if (Matches("SET", "CONSTRAINTS"))
3740 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_constraints_with_schema, "UNION SELECT 'ALL'");
3741 /* Complete SET CONSTRAINTS <foo> with DEFERRED|IMMEDIATE */
3742 else if (Matches("SET", "CONSTRAINTS", MatchAny))
3743 COMPLETE_WITH("DEFERRED", "IMMEDIATE");
3744 /* Complete SET ROLE */
3745 else if (Matches("SET", "ROLE"))
3746 COMPLETE_WITH_QUERY(Query_for_list_of_roles);
3747 /* Complete SET SESSION with AUTHORIZATION or CHARACTERISTICS... */
3748 else if (Matches("SET", "SESSION"))
3749 COMPLETE_WITH("AUTHORIZATION", "CHARACTERISTICS AS TRANSACTION");
3750 /* Complete SET SESSION AUTHORIZATION with username */
3751 else if (Matches("SET", "SESSION", "AUTHORIZATION"))
3752 COMPLETE_WITH_QUERY(Query_for_list_of_roles " UNION SELECT 'DEFAULT'");
3753 /* Complete RESET SESSION with AUTHORIZATION */
3754 else if (Matches("RESET", "SESSION"))
3755 COMPLETE_WITH("AUTHORIZATION");
3756 /* Complete SET <var> with "TO" */
3757 else if (Matches("SET", MatchAny))
3758 COMPLETE_WITH("TO");
3759
3760 /*
3761 * Complete ALTER DATABASE|FUNCTION||PROCEDURE|ROLE|ROUTINE|USER ... SET
3762 * <name>
3763 */
3764 else if (HeadMatches("ALTER", "DATABASE|FUNCTION|PROCEDURE|ROLE|ROUTINE|USER") &&
3765 TailMatches("SET", MatchAny))
3766 COMPLETE_WITH("FROM CURRENT", "TO");
3767
3768 /*
3769 * Suggest possible variable values in SET variable TO|=, along with the
3770 * preceding ALTER syntaxes.
3771 */
3772 else if (TailMatches("SET", MatchAny, "TO|=") &&
3773 !TailMatches("UPDATE", MatchAny, "SET", MatchAny, "TO|="))
3774 {
3775 /* special cased code for individual GUCs */
3776 if (TailMatches("DateStyle", "TO|="))
3777 COMPLETE_WITH("ISO", "SQL", "Postgres", "German",
3778 "YMD", "DMY", "MDY",
3779 "US", "European", "NonEuropean",
3780 "DEFAULT");
3781 else if (TailMatches("search_path", "TO|="))
3782 COMPLETE_WITH_QUERY(Query_for_list_of_schemas
3783 " AND nspname not like 'pg\\_toast%%' "
3784 " AND nspname not like 'pg\\_temp%%' "
3785 " UNION SELECT 'DEFAULT' ");
3786 else
3787 {
3788 /* generic, type based, GUC support */
3789 char *guctype = get_guctype(prev2_wd);
3790
3791 /*
3792 * Note: if we don't recognize the GUC name, it's important to not
3793 * offer any completions, as most likely we've misinterpreted the
3794 * context and this isn't a GUC-setting command at all.
3795 */
3796 if (guctype)
3797 {
3798 if (strcmp(guctype, "enum") == 0)
3799 {
3800 char querybuf[1024];
3801
3802 snprintf(querybuf, sizeof(querybuf),
3803 Query_for_enum, prev2_wd);
3804 COMPLETE_WITH_QUERY(querybuf);
3805 }
3806 else if (strcmp(guctype, "bool") == 0)
3807 COMPLETE_WITH("on", "off", "true", "false", "yes", "no",
3808 "1", "0", "DEFAULT");
3809 else
3810 COMPLETE_WITH("DEFAULT");
3811
3812 free(guctype);
3813 }
3814 }
3815 }
3816
3817 /* START TRANSACTION */
3818 else if (Matches("START"))
3819 COMPLETE_WITH("TRANSACTION");
3820
3821 /* TABLE, but not TABLE embedded in other commands */
3822 else if (Matches("TABLE"))
3823 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_selectables, NULL);
3824
3825 /* TABLESAMPLE */
3826 else if (TailMatches("TABLESAMPLE"))
3827 COMPLETE_WITH_QUERY(Query_for_list_of_tablesample_methods);
3828 else if (TailMatches("TABLESAMPLE", MatchAny))
3829 COMPLETE_WITH("(");
3830
3831 /* TRUNCATE */
3832 else if (Matches("TRUNCATE"))
3833 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_truncatables,
3834 " UNION SELECT 'TABLE'"
3835 " UNION SELECT 'ONLY'");
3836 else if (Matches("TRUNCATE", "TABLE"))
3837 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_truncatables,
3838 " UNION SELECT 'ONLY'");
3839 else if (HeadMatches("TRUNCATE") && TailMatches("ONLY"))
3840 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_truncatables, NULL);
3841 else if (Matches("TRUNCATE", MatchAny) ||
3842 Matches("TRUNCATE", "TABLE|ONLY", MatchAny) ||
3843 Matches("TRUNCATE", "TABLE", "ONLY", MatchAny))
3844 COMPLETE_WITH("RESTART IDENTITY", "CONTINUE IDENTITY", "CASCADE", "RESTRICT");
3845 else if (HeadMatches("TRUNCATE") && TailMatches("IDENTITY"))
3846 COMPLETE_WITH("CASCADE", "RESTRICT");
3847
3848 /* UNLISTEN */
3849 else if (Matches("UNLISTEN"))
3850 COMPLETE_WITH_QUERY("SELECT pg_catalog.quote_ident(channel) FROM pg_catalog.pg_listening_channels() AS channel WHERE substring(pg_catalog.quote_ident(channel),1,%d)='%s' UNION SELECT '*'");
3851
3852 /* UPDATE --- can be inside EXPLAIN, RULE, etc */
3853 /* If prev. word is UPDATE suggest a list of tables */
3854 else if (TailMatches("UPDATE"))
3855 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_updatables, NULL);
3856 /* Complete UPDATE <table> with "SET" */
3857 else if (TailMatches("UPDATE", MatchAny))
3858 COMPLETE_WITH("SET");
3859 /* Complete UPDATE <table> SET with list of attributes */
3860 else if (TailMatches("UPDATE", MatchAny, "SET"))
3861 COMPLETE_WITH_ATTR(prev2_wd, "");
3862 /* UPDATE <table> SET <attr> = */
3863 else if (TailMatches("UPDATE", MatchAny, "SET", MatchAnyExcept("*=")))
3864 COMPLETE_WITH("=");
3865
3866 /* USER MAPPING */
3867 else if (Matches("ALTER|CREATE|DROP", "USER", "MAPPING"))
3868 COMPLETE_WITH("FOR");
3869 else if (Matches("CREATE", "USER", "MAPPING", "FOR"))
3870 COMPLETE_WITH_QUERY(Query_for_list_of_roles
3871 " UNION SELECT 'CURRENT_ROLE'"
3872 " UNION SELECT 'CURRENT_USER'"
3873 " UNION SELECT 'PUBLIC'"
3874 " UNION SELECT 'USER'");
3875 else if (Matches("ALTER|DROP", "USER", "MAPPING", "FOR"))
3876 COMPLETE_WITH_QUERY(Query_for_list_of_user_mappings);
3877 else if (Matches("CREATE|ALTER|DROP", "USER", "MAPPING", "FOR", MatchAny))
3878 COMPLETE_WITH("SERVER");
3879 else if (Matches("CREATE|ALTER", "USER", "MAPPING", "FOR", MatchAny, "SERVER", MatchAny))
3880 COMPLETE_WITH("OPTIONS");
3881
3882 /*
3883 * VACUUM [ ( option [, ...] ) ] [ table_and_columns [, ...] ]
3884 * VACUUM [ FULL ] [ FREEZE ] [ VERBOSE ] [ ANALYZE ] [ table_and_columns [, ...] ]
3885 */
3886 else if (Matches("VACUUM"))
3887 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_vacuumables,
3888 " UNION SELECT 'FULL'"
3889 " UNION SELECT 'FREEZE'"
3890 " UNION SELECT 'ANALYZE'"
3891 " UNION SELECT 'VERBOSE'");
3892 else if (Matches("VACUUM", "FULL"))
3893 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_vacuumables,
3894 " UNION SELECT 'FREEZE'"
3895 " UNION SELECT 'ANALYZE'"
3896 " UNION SELECT 'VERBOSE'");
3897 else if (Matches("VACUUM", "FREEZE") ||
3898 Matches("VACUUM", "FULL", "FREEZE"))
3899 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_vacuumables,
3900 " UNION SELECT 'VERBOSE'"
3901 " UNION SELECT 'ANALYZE'");
3902 else if (Matches("VACUUM", "VERBOSE") ||
3903 Matches("VACUUM", "FULL|FREEZE", "VERBOSE") ||
3904 Matches("VACUUM", "FULL", "FREEZE", "VERBOSE"))
3905 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_vacuumables,
3906 " UNION SELECT 'ANALYZE'");
3907 else if (HeadMatches("VACUUM", "(*") &&
3908 !HeadMatches("VACUUM", "(*)"))
3909 {
3910 /*
3911 * This fires if we're in an unfinished parenthesized option list.
3912 * get_previous_words treats a completed parenthesized option list as
3913 * one word, so the above test is correct.
3914 */
3915 if (ends_with(prev_wd, '(') || ends_with(prev_wd, ','))
3916 COMPLETE_WITH("FULL", "FREEZE", "ANALYZE", "VERBOSE",
3917 "DISABLE_PAGE_SKIPPING", "SKIP_LOCKED",
3918 "INDEX_CLEANUP", "PROCESS_TOAST",
3919 "TRUNCATE", "PARALLEL");
3920 else if (TailMatches("FULL|FREEZE|ANALYZE|VERBOSE|DISABLE_PAGE_SKIPPING|SKIP_LOCKED|PROCESS_TOAST|TRUNCATE"))
3921 COMPLETE_WITH("ON", "OFF");
3922 else if (TailMatches("INDEX_CLEANUP"))
3923 COMPLETE_WITH("AUTO", "ON", "OFF");
3924 }
3925 else if (HeadMatches("VACUUM") && TailMatches("("))
3926 /* "VACUUM (" should be caught above, so assume we want columns */
3927 COMPLETE_WITH_ATTR(prev2_wd, "");
3928 else if (HeadMatches("VACUUM"))
3929 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_vacuumables, NULL);
3930
3931 /* WITH [RECURSIVE] */
3932
3933 /*
3934 * Only match when WITH is the first word, as WITH may appear in many
3935 * other contexts.
3936 */
3937 else if (Matches("WITH"))
3938 COMPLETE_WITH("RECURSIVE");
3939
3940 /* WHERE */
3941 /* Simple case of the word before the where being the table name */
3942 else if (TailMatches(MatchAny, "WHERE"))
3943 COMPLETE_WITH_ATTR(prev2_wd, "");
3944
3945 /* ... FROM ... */
3946 /* TODO: also include SRF ? */
3947 else if (TailMatches("FROM") && !Matches("COPY|\\copy", MatchAny, "FROM"))
3948 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_selectables, NULL);
3949
3950 /* ... JOIN ... */
3951 else if (TailMatches("JOIN"))
3952 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_selectables, NULL);
3953
3954 /* Backslash commands */
3955 /* TODO: \dc \dd \dl */
3956 else if (TailMatchesCS("\\?"))
3957 COMPLETE_WITH_CS("commands", "options", "variables");
3958 else if (TailMatchesCS("\\connect|\\c"))
3959 {
3960 if (!recognized_connection_string(text))
3961 COMPLETE_WITH_QUERY(Query_for_list_of_databases);
3962 }
3963 else if (TailMatchesCS("\\connect|\\c", MatchAny))
3964 {
3965 if (!recognized_connection_string(prev_wd))
3966 COMPLETE_WITH_QUERY(Query_for_list_of_roles);
3967 }
3968 else if (TailMatchesCS("\\da*"))
3969 COMPLETE_WITH_VERSIONED_SCHEMA_QUERY(Query_for_list_of_aggregates, NULL);
3970 else if (TailMatchesCS("\\dAc*", MatchAny) ||
3971 TailMatchesCS("\\dAf*", MatchAny))
3972 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_datatypes, NULL);
3973 else if (TailMatchesCS("\\dAo*", MatchAny) ||
3974 TailMatchesCS("\\dAp*", MatchAny))
3975 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_operator_families, NULL);
3976 else if (TailMatchesCS("\\dA*"))
3977 COMPLETE_WITH_QUERY(Query_for_list_of_access_methods);
3978 else if (TailMatchesCS("\\db*"))
3979 COMPLETE_WITH_QUERY(Query_for_list_of_tablespaces);
3980 else if (TailMatchesCS("\\dD*"))
3981 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_domains, NULL);
3982 else if (TailMatchesCS("\\des*"))
3983 COMPLETE_WITH_QUERY(Query_for_list_of_servers);
3984 else if (TailMatchesCS("\\deu*"))
3985 COMPLETE_WITH_QUERY(Query_for_list_of_user_mappings);
3986 else if (TailMatchesCS("\\dew*"))
3987 COMPLETE_WITH_QUERY(Query_for_list_of_fdws);
3988 else if (TailMatchesCS("\\df*"))
3989 COMPLETE_WITH_VERSIONED_SCHEMA_QUERY(Query_for_list_of_functions, NULL);
3990 else if (HeadMatchesCS("\\df*"))
3991 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_datatypes, NULL);
3992
3993 else if (TailMatchesCS("\\dFd*"))
3994 COMPLETE_WITH_QUERY(Query_for_list_of_ts_dictionaries);
3995 else if (TailMatchesCS("\\dFp*"))
3996 COMPLETE_WITH_QUERY(Query_for_list_of_ts_parsers);
3997 else if (TailMatchesCS("\\dFt*"))
3998 COMPLETE_WITH_QUERY(Query_for_list_of_ts_templates);
3999 /* must be at end of \dF alternatives: */
4000 else if (TailMatchesCS("\\dF*"))
4001 COMPLETE_WITH_QUERY(Query_for_list_of_ts_configurations);
4002
4003 else if (TailMatchesCS("\\di*"))
4004 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_indexes, NULL);
4005 else if (TailMatchesCS("\\dL*"))
4006 COMPLETE_WITH_QUERY(Query_for_list_of_languages);
4007 else if (TailMatchesCS("\\dn*"))
4008 COMPLETE_WITH_QUERY(Query_for_list_of_schemas);
4009 /* no support for completing operators, but we can complete types: */
4010 else if (HeadMatchesCS("\\do*", MatchAny))
4011 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_datatypes, NULL);
4012 else if (TailMatchesCS("\\dp") || TailMatchesCS("\\z"))
4013 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_grantables, NULL);
4014 else if (TailMatchesCS("\\dPi*"))
4015 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_partitioned_indexes, NULL);
4016 else if (TailMatchesCS("\\dPt*"))
4017 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_partitioned_tables, NULL);
4018 else if (TailMatchesCS("\\dP*"))
4019 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_partitioned_relations, NULL);
4020 else if (TailMatchesCS("\\ds*"))
4021 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_sequences, NULL);
4022 else if (TailMatchesCS("\\dt*"))
4023 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, NULL);
4024 else if (TailMatchesCS("\\dT*"))
4025 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_datatypes, NULL);
4026 else if (TailMatchesCS("\\du*") || TailMatchesCS("\\dg*"))
4027 COMPLETE_WITH_QUERY(Query_for_list_of_roles);
4028 else if (TailMatchesCS("\\dv*"))
4029 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_views, NULL);
4030 else if (TailMatchesCS("\\dx*"))
4031 COMPLETE_WITH_QUERY(Query_for_list_of_extensions);
4032 else if (TailMatchesCS("\\dX*"))
4033 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_statistics, NULL);
4034 else if (TailMatchesCS("\\dm*"))
4035 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_matviews, NULL);
4036 else if (TailMatchesCS("\\dE*"))
4037 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_foreign_tables, NULL);
4038 else if (TailMatchesCS("\\dy*"))
4039 COMPLETE_WITH_QUERY(Query_for_list_of_event_triggers);
4040
4041 /* must be at end of \d alternatives: */
4042 else if (TailMatchesCS("\\d*"))
4043 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_relations, NULL);
4044
4045 else if (TailMatchesCS("\\ef"))
4046 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_routines, NULL);
4047 else if (TailMatchesCS("\\ev"))
4048 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_views, NULL);
4049
4050 else if (TailMatchesCS("\\encoding"))
4051 COMPLETE_WITH_QUERY(Query_for_list_of_encodings);
4052 else if (TailMatchesCS("\\h|\\help"))
4053 COMPLETE_WITH_LIST(sql_commands);
4054 else if (TailMatchesCS("\\h|\\help", MatchAny))
4055 {
4056 if (TailMatches("DROP"))
4057 matches = rl_completion_matches(text, drop_command_generator);
4058 else if (TailMatches("ALTER"))
4059 matches = rl_completion_matches(text, alter_command_generator);
4060
4061 /*
4062 * CREATE is recognized by tail match elsewhere, so doesn't need to be
4063 * repeated here
4064 */
4065 }
4066 else if (TailMatchesCS("\\h|\\help", MatchAny, MatchAny))
4067 {
4068 if (TailMatches("CREATE|DROP", "ACCESS"))
4069 COMPLETE_WITH("METHOD");
4070 else if (TailMatches("ALTER", "DEFAULT"))
4071 COMPLETE_WITH("PRIVILEGES");
4072 else if (TailMatches("CREATE|ALTER|DROP", "EVENT"))
4073 COMPLETE_WITH("TRIGGER");
4074 else if (TailMatches("CREATE|ALTER|DROP", "FOREIGN"))
4075 COMPLETE_WITH("DATA WRAPPER", "TABLE");
4076 else if (TailMatches("ALTER", "LARGE"))
4077 COMPLETE_WITH("OBJECT");
4078 else if (TailMatches("CREATE|ALTER|DROP", "MATERIALIZED"))
4079 COMPLETE_WITH("VIEW");
4080 else if (TailMatches("CREATE|ALTER|DROP", "TEXT"))
4081 COMPLETE_WITH("SEARCH");
4082 else if (TailMatches("CREATE|ALTER|DROP", "USER"))
4083 COMPLETE_WITH("MAPPING FOR");
4084 }
4085 else if (TailMatchesCS("\\h|\\help", MatchAny, MatchAny, MatchAny))
4086 {
4087 if (TailMatches("CREATE|ALTER|DROP", "FOREIGN", "DATA"))
4088 COMPLETE_WITH("WRAPPER");
4089 else if (TailMatches("CREATE|ALTER|DROP", "TEXT", "SEARCH"))
4090 COMPLETE_WITH("CONFIGURATION", "DICTIONARY", "PARSER", "TEMPLATE");
4091 else if (TailMatches("CREATE|ALTER|DROP", "USER", "MAPPING"))
4092 COMPLETE_WITH("FOR");
4093 }
4094 else if (TailMatchesCS("\\l*") && !TailMatchesCS("\\lo*"))
4095 COMPLETE_WITH_QUERY(Query_for_list_of_databases);
4096 else if (TailMatchesCS("\\password"))
4097 COMPLETE_WITH_QUERY(Query_for_list_of_roles);
4098 else if (TailMatchesCS("\\pset"))
4099 COMPLETE_WITH_CS("border", "columns", "csv_fieldsep", "expanded",
4100 "fieldsep", "fieldsep_zero", "footer", "format",
4101 "linestyle", "null", "numericlocale",
4102 "pager", "pager_min_lines",
4103 "recordsep", "recordsep_zero",
4104 "tableattr", "title", "tuples_only",
4105 "unicode_border_linestyle",
4106 "unicode_column_linestyle",
4107 "unicode_header_linestyle");
4108 else if (TailMatchesCS("\\pset", MatchAny))
4109 {
4110 if (TailMatchesCS("format"))
4111 COMPLETE_WITH_CS("aligned", "asciidoc", "csv", "html", "latex",
4112 "latex-longtable", "troff-ms", "unaligned",
4113 "wrapped");
4114 else if (TailMatchesCS("linestyle"))
4115 COMPLETE_WITH_CS("ascii", "old-ascii", "unicode");
4116 else if (TailMatchesCS("pager"))
4117 COMPLETE_WITH_CS("on", "off", "always");
4118 else if (TailMatchesCS("unicode_border_linestyle|"
4119 "unicode_column_linestyle|"
4120 "unicode_header_linestyle"))
4121 COMPLETE_WITH_CS("single", "double");
4122 }
4123 else if (TailMatchesCS("\\unset"))
4124 matches = complete_from_variables(text, "", "", true);
4125 else if (TailMatchesCS("\\set"))
4126 matches = complete_from_variables(text, "", "", false);
4127 else if (TailMatchesCS("\\set", MatchAny))
4128 {
4129 if (TailMatchesCS("AUTOCOMMIT|ON_ERROR_STOP|QUIET|"
4130 "SINGLELINE|SINGLESTEP"))
4131 COMPLETE_WITH_CS("on", "off");
4132 else if (TailMatchesCS("COMP_KEYWORD_CASE"))
4133 COMPLETE_WITH_CS("lower", "upper",
4134 "preserve-lower", "preserve-upper");
4135 else if (TailMatchesCS("ECHO"))
4136 COMPLETE_WITH_CS("errors", "queries", "all", "none");
4137 else if (TailMatchesCS("ECHO_HIDDEN"))
4138 COMPLETE_WITH_CS("noexec", "off", "on");
4139 else if (TailMatchesCS("HISTCONTROL"))
4140 COMPLETE_WITH_CS("ignorespace", "ignoredups",
4141 "ignoreboth", "none");
4142 else if (TailMatchesCS("ON_ERROR_ROLLBACK"))
4143 COMPLETE_WITH_CS("on", "off", "interactive");
4144 else if (TailMatchesCS("SHOW_CONTEXT"))
4145 COMPLETE_WITH_CS("never", "errors", "always");
4146 else if (TailMatchesCS("VERBOSITY"))
4147 COMPLETE_WITH_CS("default", "verbose", "terse", "sqlstate");
4148 }
4149 else if (TailMatchesCS("\\sf*"))
4150 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_routines, NULL);
4151 else if (TailMatchesCS("\\sv*"))
4152 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_views, NULL);
4153 else if (TailMatchesCS("\\cd|\\e|\\edit|\\g|\\gx|\\i|\\include|"
4154 "\\ir|\\include_relative|\\o|\\out|"
4155 "\\s|\\w|\\write|\\lo_import"))
4156 {
4157 completion_charp = "\\";
4158 completion_force_quote = false;
4159 matches = rl_completion_matches(text, complete_from_files);
4160 }
4161
4162 /*
4163 * Finally, we look through the list of "things", such as TABLE, INDEX and
4164 * check if that was the previous word. If so, execute the query to get a
4165 * list of them.
4166 */
4167 else
4168 {
4169 int i;
4170
4171 for (i = 0; words_after_create[i].name; i++)
4172 {
4173 if (pg_strcasecmp(prev_wd, words_after_create[i].name) == 0)
4174 {
4175 if (words_after_create[i].query)
4176 COMPLETE_WITH_QUERY(words_after_create[i].query);
4177 else if (words_after_create[i].vquery)
4178 COMPLETE_WITH_VERSIONED_QUERY(words_after_create[i].vquery);
4179 else if (words_after_create[i].squery)
4180 COMPLETE_WITH_VERSIONED_SCHEMA_QUERY(words_after_create[i].squery,
4181 NULL);
4182 break;
4183 }
4184 }
4185 }
4186
4187 /*
4188 * If we still don't have anything to match we have to fabricate some sort
4189 * of default list. If we were to just return NULL, readline automatically
4190 * attempts filename completion, and that's usually no good.
4191 */
4192 if (matches == NULL)
4193 {
4194 COMPLETE_WITH_CONST(true, "");
4195 #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
4196 rl_completion_append_character = '\0';
4197 #endif
4198 }
4199
4200 /* free storage */
4201 free(previous_words);
4202 free(words_buffer);
4203 free(text_copy);
4204
4205 /* Return our Grand List O' Matches */
4206 return matches;
4207 }
4208
4209
4210 /*
4211 * GENERATOR FUNCTIONS
4212 *
4213 * These functions do all the actual work of completing the input. They get
4214 * passed the text so far and the count how many times they have been called
4215 * so far with the same text.
4216 * If you read the above carefully, you'll see that these don't get called
4217 * directly but through the readline interface.
4218 * The return value is expected to be the full completion of the text, going
4219 * through a list each time, or NULL if there are no more matches. The string
4220 * will be free()'d by readline, so you must run it through strdup() or
4221 * something of that sort.
4222 */
4223
4224 /*
4225 * Common routine for create_command_generator and drop_command_generator.
4226 * Entries that have 'excluded' flags are not returned.
4227 */
4228 static char *
create_or_drop_command_generator(const char * text,int state,bits32 excluded)4229 create_or_drop_command_generator(const char *text, int state, bits32 excluded)
4230 {
4231 static int list_index,
4232 string_length;
4233 const char *name;
4234
4235 /* If this is the first time for this completion, init some values */
4236 if (state == 0)
4237 {
4238 list_index = 0;
4239 string_length = strlen(text);
4240 }
4241
4242 /* find something that matches */
4243 while ((name = words_after_create[list_index++].name))
4244 {
4245 if ((pg_strncasecmp(name, text, string_length) == 0) &&
4246 !(words_after_create[list_index - 1].flags & excluded))
4247 return pg_strdup_keyword_case(name, text);
4248 }
4249 /* if nothing matches, return NULL */
4250 return NULL;
4251 }
4252
4253 /*
4254 * This one gives you one from a list of things you can put after CREATE
4255 * as defined above.
4256 */
4257 static char *
create_command_generator(const char * text,int state)4258 create_command_generator(const char *text, int state)
4259 {
4260 return create_or_drop_command_generator(text, state, THING_NO_CREATE);
4261 }
4262
4263 /*
4264 * This function gives you a list of things you can put after a DROP command.
4265 */
4266 static char *
drop_command_generator(const char * text,int state)4267 drop_command_generator(const char *text, int state)
4268 {
4269 return create_or_drop_command_generator(text, state, THING_NO_DROP);
4270 }
4271
4272 /*
4273 * This function gives you a list of things you can put after an ALTER command.
4274 */
4275 static char *
alter_command_generator(const char * text,int state)4276 alter_command_generator(const char *text, int state)
4277 {
4278 return create_or_drop_command_generator(text, state, THING_NO_ALTER);
4279 }
4280
4281 /*
4282 * These functions generate lists using server queries.
4283 * They are all wrappers for _complete_from_query.
4284 */
4285
4286 static char *
complete_from_query(const char * text,int state)4287 complete_from_query(const char *text, int state)
4288 {
4289 /* query is assumed to work for any server version */
4290 return _complete_from_query(completion_charp, NULL, text, state);
4291 }
4292
4293 static char *
complete_from_versioned_query(const char * text,int state)4294 complete_from_versioned_query(const char *text, int state)
4295 {
4296 const VersionedQuery *vquery = completion_vquery;
4297
4298 /* Find appropriate array element */
4299 while (pset.sversion < vquery->min_server_version)
4300 vquery++;
4301 /* Fail completion if server is too old */
4302 if (vquery->query == NULL)
4303 return NULL;
4304
4305 return _complete_from_query(vquery->query, NULL, text, state);
4306 }
4307
4308 static char *
complete_from_schema_query(const char * text,int state)4309 complete_from_schema_query(const char *text, int state)
4310 {
4311 /* query is assumed to work for any server version */
4312 return _complete_from_query(completion_charp, completion_squery,
4313 text, state);
4314 }
4315
4316 static char *
complete_from_versioned_schema_query(const char * text,int state)4317 complete_from_versioned_schema_query(const char *text, int state)
4318 {
4319 const SchemaQuery *squery = completion_squery;
4320 const VersionedQuery *vquery = completion_vquery;
4321
4322 /* Find appropriate array element */
4323 while (pset.sversion < squery->min_server_version)
4324 squery++;
4325 /* Fail completion if server is too old */
4326 if (squery->catname == NULL)
4327 return NULL;
4328
4329 /* Likewise for the add-on text, if any */
4330 if (vquery)
4331 {
4332 while (pset.sversion < vquery->min_server_version)
4333 vquery++;
4334 if (vquery->query == NULL)
4335 return NULL;
4336 }
4337
4338 return _complete_from_query(vquery ? vquery->query : NULL,
4339 squery, text, state);
4340 }
4341
4342
4343 /*
4344 * This creates a list of matching things, according to a query described by
4345 * the initial arguments. The caller has already done any work needed to
4346 * select the appropriate query for the server's version.
4347 *
4348 * The query can be one of two kinds:
4349 *
4350 * 1. A simple query which must contain a %d and a %s, which will be replaced
4351 * by the string length of the text and the text itself. The query may also
4352 * have up to four more %s in it; the first two such will be replaced by the
4353 * value of completion_info_charp, the next two by the value of
4354 * completion_info_charp2.
4355 *
4356 * 2. A schema query used for completion of both schema and relation names.
4357 * These are more complex and must contain in the following order:
4358 * %d %s %d %s %d %s %s %d %s
4359 * where %d is the string length of the text and %s the text itself.
4360 *
4361 * If both simple_query and schema_query are non-NULL, then we construct
4362 * a schema query and append the (uninterpreted) string simple_query to it.
4363 *
4364 * It is assumed that strings should be escaped to become SQL literals
4365 * (that is, what is in the query is actually ... '%s' ...)
4366 *
4367 * See top of file for examples of both kinds of query.
4368 *
4369 * "text" and "state" are supplied by readline.
4370 */
4371 static char *
_complete_from_query(const char * simple_query,const SchemaQuery * schema_query,const char * text,int state)4372 _complete_from_query(const char *simple_query,
4373 const SchemaQuery *schema_query,
4374 const char *text, int state)
4375 {
4376 static int list_index,
4377 byte_length;
4378 static PGresult *result = NULL;
4379
4380 /*
4381 * If this is the first time for this completion, we fetch a list of our
4382 * "things" from the backend.
4383 */
4384 if (state == 0)
4385 {
4386 PQExpBufferData query_buffer;
4387 char *e_text;
4388 char *e_info_charp;
4389 char *e_info_charp2;
4390 const char *pstr = text;
4391 int char_length = 0;
4392
4393 list_index = 0;
4394 byte_length = strlen(text);
4395
4396 /*
4397 * Count length as number of characters (not bytes), for passing to
4398 * substring
4399 */
4400 while (*pstr)
4401 {
4402 char_length++;
4403 pstr += PQmblenBounded(pstr, pset.encoding);
4404 }
4405
4406 /* Free any prior result */
4407 PQclear(result);
4408 result = NULL;
4409
4410 /* Set up suitably-escaped copies of textual inputs */
4411 e_text = escape_string(text);
4412
4413 if (completion_info_charp)
4414 e_info_charp = escape_string(completion_info_charp);
4415 else
4416 e_info_charp = NULL;
4417
4418 if (completion_info_charp2)
4419 e_info_charp2 = escape_string(completion_info_charp2);
4420 else
4421 e_info_charp2 = NULL;
4422
4423 initPQExpBuffer(&query_buffer);
4424
4425 if (schema_query)
4426 {
4427 /* schema_query gives us the pieces to assemble */
4428 const char *qualresult = schema_query->qualresult;
4429
4430 if (qualresult == NULL)
4431 qualresult = schema_query->result;
4432
4433 /* Get unqualified names matching the input-so-far */
4434 appendPQExpBuffer(&query_buffer, "SELECT %s FROM %s WHERE ",
4435 schema_query->result,
4436 schema_query->catname);
4437 if (schema_query->selcondition)
4438 appendPQExpBuffer(&query_buffer, "%s AND ",
4439 schema_query->selcondition);
4440 appendPQExpBuffer(&query_buffer, "substring(%s,1,%d)='%s'",
4441 schema_query->result,
4442 char_length, e_text);
4443 appendPQExpBuffer(&query_buffer, " AND %s",
4444 schema_query->viscondition);
4445
4446 /*
4447 * When fetching relation names, suppress system catalogs unless
4448 * the input-so-far begins with "pg_". This is a compromise
4449 * between not offering system catalogs for completion at all, and
4450 * having them swamp the result when the input is just "p".
4451 */
4452 if (strcmp(schema_query->catname,
4453 "pg_catalog.pg_class c") == 0 &&
4454 strncmp(text, "pg_", 3) != 0)
4455 {
4456 appendPQExpBufferStr(&query_buffer,
4457 " AND c.relnamespace <> (SELECT oid FROM"
4458 " pg_catalog.pg_namespace WHERE nspname = 'pg_catalog')");
4459 }
4460
4461 /*
4462 * Add in matching schema names, but only if there is more than
4463 * one potential match among schema names.
4464 */
4465 appendPQExpBuffer(&query_buffer, "\nUNION\n"
4466 "SELECT pg_catalog.quote_ident(n.nspname) || '.' "
4467 "FROM pg_catalog.pg_namespace n "
4468 "WHERE substring(pg_catalog.quote_ident(n.nspname) || '.',1,%d)='%s'",
4469 char_length, e_text);
4470 appendPQExpBuffer(&query_buffer,
4471 " AND (SELECT pg_catalog.count(*)"
4472 " FROM pg_catalog.pg_namespace"
4473 " WHERE substring(pg_catalog.quote_ident(nspname) || '.',1,%d) ="
4474 " substring('%s',1,pg_catalog.length(pg_catalog.quote_ident(nspname))+1)) > 1",
4475 char_length, e_text);
4476
4477 /*
4478 * Add in matching qualified names, but only if there is exactly
4479 * one schema matching the input-so-far.
4480 */
4481 appendPQExpBuffer(&query_buffer, "\nUNION\n"
4482 "SELECT pg_catalog.quote_ident(n.nspname) || '.' || %s "
4483 "FROM %s, pg_catalog.pg_namespace n "
4484 "WHERE %s = n.oid AND ",
4485 qualresult,
4486 schema_query->catname,
4487 schema_query->namespace);
4488 if (schema_query->selcondition)
4489 appendPQExpBuffer(&query_buffer, "%s AND ",
4490 schema_query->selcondition);
4491 appendPQExpBuffer(&query_buffer, "substring(pg_catalog.quote_ident(n.nspname) || '.' || %s,1,%d)='%s'",
4492 qualresult,
4493 char_length, e_text);
4494
4495 /*
4496 * This condition exploits the single-matching-schema rule to
4497 * speed up the query
4498 */
4499 appendPQExpBuffer(&query_buffer,
4500 " AND substring(pg_catalog.quote_ident(n.nspname) || '.',1,%d) ="
4501 " substring('%s',1,pg_catalog.length(pg_catalog.quote_ident(n.nspname))+1)",
4502 char_length, e_text);
4503 appendPQExpBuffer(&query_buffer,
4504 " AND (SELECT pg_catalog.count(*)"
4505 " FROM pg_catalog.pg_namespace"
4506 " WHERE substring(pg_catalog.quote_ident(nspname) || '.',1,%d) ="
4507 " substring('%s',1,pg_catalog.length(pg_catalog.quote_ident(nspname))+1)) = 1",
4508 char_length, e_text);
4509
4510 /* If an addon query was provided, use it */
4511 if (simple_query)
4512 appendPQExpBuffer(&query_buffer, "\n%s", simple_query);
4513 }
4514 else
4515 {
4516 Assert(simple_query);
4517 /* simple_query is an sprintf-style format string */
4518 appendPQExpBuffer(&query_buffer, simple_query,
4519 char_length, e_text,
4520 e_info_charp, e_info_charp,
4521 e_info_charp2, e_info_charp2);
4522 }
4523
4524 /* Limit the number of records in the result */
4525 appendPQExpBuffer(&query_buffer, "\nLIMIT %d",
4526 completion_max_records);
4527
4528 result = exec_query(query_buffer.data);
4529
4530 termPQExpBuffer(&query_buffer);
4531 free(e_text);
4532 if (e_info_charp)
4533 free(e_info_charp);
4534 if (e_info_charp2)
4535 free(e_info_charp2);
4536 }
4537
4538 /* Find something that matches */
4539 if (result && PQresultStatus(result) == PGRES_TUPLES_OK)
4540 {
4541 const char *item;
4542
4543 while (list_index < PQntuples(result) &&
4544 (item = PQgetvalue(result, list_index++, 0)))
4545 if (pg_strncasecmp(text, item, byte_length) == 0)
4546 return pg_strdup(item);
4547 }
4548
4549 /* If nothing matches, free the db structure and return null */
4550 PQclear(result);
4551 result = NULL;
4552 return NULL;
4553 }
4554
4555
4556 /*
4557 * This function returns in order one of a fixed, NULL pointer terminated list
4558 * of strings (if matching). This can be used if there are only a fixed number
4559 * SQL words that can appear at certain spot.
4560 */
4561 static char *
complete_from_list(const char * text,int state)4562 complete_from_list(const char *text, int state)
4563 {
4564 static int string_length,
4565 list_index,
4566 matches;
4567 static bool casesensitive;
4568 const char *item;
4569
4570 /* need to have a list */
4571 Assert(completion_charpp != NULL);
4572
4573 /* Initialization */
4574 if (state == 0)
4575 {
4576 list_index = 0;
4577 string_length = strlen(text);
4578 casesensitive = completion_case_sensitive;
4579 matches = 0;
4580 }
4581
4582 while ((item = completion_charpp[list_index++]))
4583 {
4584 /* First pass is case sensitive */
4585 if (casesensitive && strncmp(text, item, string_length) == 0)
4586 {
4587 matches++;
4588 return pg_strdup(item);
4589 }
4590
4591 /* Second pass is case insensitive, don't bother counting matches */
4592 if (!casesensitive && pg_strncasecmp(text, item, string_length) == 0)
4593 {
4594 if (completion_case_sensitive)
4595 return pg_strdup(item);
4596 else
4597
4598 /*
4599 * If case insensitive matching was requested initially,
4600 * adjust the case according to setting.
4601 */
4602 return pg_strdup_keyword_case(item, text);
4603 }
4604 }
4605
4606 /*
4607 * No matches found. If we're not case insensitive already, lets switch to
4608 * being case insensitive and try again
4609 */
4610 if (casesensitive && matches == 0)
4611 {
4612 casesensitive = false;
4613 list_index = 0;
4614 state++;
4615 return complete_from_list(text, state);
4616 }
4617
4618 /* If no more matches, return null. */
4619 return NULL;
4620 }
4621
4622
4623 /*
4624 * This function returns one fixed string the first time even if it doesn't
4625 * match what's there, and nothing the second time. The string
4626 * to be used must be in completion_charp.
4627 *
4628 * If the given string is "", this has the effect of preventing readline
4629 * from doing any completion. (Without this, readline tries to do filename
4630 * completion which is seldom the right thing.)
4631 *
4632 * If the given string is not empty, readline will replace whatever the
4633 * user typed with that string. This behavior might be useful if it's
4634 * completely certain that we know what must appear at a certain spot,
4635 * so that it's okay to overwrite misspellings. In practice, given the
4636 * relatively lame parsing technology used in this file, the level of
4637 * certainty is seldom that high, so that you probably don't want to
4638 * use this. Use complete_from_list with a one-element list instead;
4639 * that won't try to auto-correct "misspellings".
4640 */
4641 static char *
complete_from_const(const char * text,int state)4642 complete_from_const(const char *text, int state)
4643 {
4644 Assert(completion_charp != NULL);
4645 if (state == 0)
4646 {
4647 if (completion_case_sensitive)
4648 return pg_strdup(completion_charp);
4649 else
4650
4651 /*
4652 * If case insensitive matching was requested initially, adjust
4653 * the case according to setting.
4654 */
4655 return pg_strdup_keyword_case(completion_charp, text);
4656 }
4657 else
4658 return NULL;
4659 }
4660
4661
4662 /*
4663 * This function appends the variable name with prefix and suffix to
4664 * the variable names array.
4665 */
4666 static void
append_variable_names(char *** varnames,int * nvars,int * maxvars,const char * varname,const char * prefix,const char * suffix)4667 append_variable_names(char ***varnames, int *nvars,
4668 int *maxvars, const char *varname,
4669 const char *prefix, const char *suffix)
4670 {
4671 if (*nvars >= *maxvars)
4672 {
4673 *maxvars *= 2;
4674 *varnames = (char **) pg_realloc(*varnames,
4675 ((*maxvars) + 1) * sizeof(char *));
4676 }
4677
4678 (*varnames)[(*nvars)++] = psprintf("%s%s%s", prefix, varname, suffix);
4679 }
4680
4681
4682 /*
4683 * This function supports completion with the name of a psql variable.
4684 * The variable names can be prefixed and suffixed with additional text
4685 * to support quoting usages. If need_value is true, only variables
4686 * that are currently set are included; otherwise, special variables
4687 * (those that have hooks) are included even if currently unset.
4688 */
4689 static char **
complete_from_variables(const char * text,const char * prefix,const char * suffix,bool need_value)4690 complete_from_variables(const char *text, const char *prefix, const char *suffix,
4691 bool need_value)
4692 {
4693 char **matches;
4694 char **varnames;
4695 int nvars = 0;
4696 int maxvars = 100;
4697 int i;
4698 struct _variable *ptr;
4699
4700 varnames = (char **) pg_malloc((maxvars + 1) * sizeof(char *));
4701
4702 for (ptr = pset.vars->next; ptr; ptr = ptr->next)
4703 {
4704 if (need_value && !(ptr->value))
4705 continue;
4706 append_variable_names(&varnames, &nvars, &maxvars, ptr->name,
4707 prefix, suffix);
4708 }
4709
4710 varnames[nvars] = NULL;
4711 COMPLETE_WITH_LIST_CS((const char *const *) varnames);
4712
4713 for (i = 0; i < nvars; i++)
4714 free(varnames[i]);
4715 free(varnames);
4716
4717 return matches;
4718 }
4719
4720
4721 /*
4722 * This function wraps rl_filename_completion_function() to strip quotes from
4723 * the input before searching for matches and to quote any matches for which
4724 * the consuming command will require it.
4725 *
4726 * Caller must set completion_charp to a zero- or one-character string
4727 * containing the escape character. This is necessary since \copy has no
4728 * escape character, but every other backslash command recognizes "\" as an
4729 * escape character.
4730 *
4731 * Caller must also set completion_force_quote to indicate whether to force
4732 * quotes around the result. (The SQL COPY command requires that.)
4733 */
4734 static char *
complete_from_files(const char * text,int state)4735 complete_from_files(const char *text, int state)
4736 {
4737 #ifdef USE_FILENAME_QUOTING_FUNCTIONS
4738
4739 /*
4740 * If we're using a version of Readline that supports filename quoting
4741 * hooks, rely on those, and invoke rl_filename_completion_function()
4742 * without messing with its arguments. Readline does stuff internally
4743 * that does not work well at all if we try to handle dequoting here.
4744 * Instead, Readline will call quote_file_name() and dequote_file_name()
4745 * (see below) at appropriate times.
4746 *
4747 * ... or at least, mostly it will. There are some paths involving
4748 * unmatched file names in which Readline never calls quote_file_name(),
4749 * and if left to its own devices it will incorrectly append a quote
4750 * anyway. Set rl_completion_suppress_quote to prevent that. If we do
4751 * get to quote_file_name(), we'll clear this again. (Yes, this seems
4752 * like it's working around Readline bugs.)
4753 */
4754 #ifdef HAVE_RL_COMPLETION_SUPPRESS_QUOTE
4755 rl_completion_suppress_quote = 1;
4756 #endif
4757
4758 /* If user typed a quote, force quoting (never remove user's quote) */
4759 if (*text == '\'')
4760 completion_force_quote = true;
4761
4762 return rl_filename_completion_function(text, state);
4763 #else
4764
4765 /*
4766 * Otherwise, we have to do the best we can.
4767 */
4768 static const char *unquoted_text;
4769 char *unquoted_match;
4770 char *ret = NULL;
4771
4772 /* If user typed a quote, force quoting (never remove user's quote) */
4773 if (*text == '\'')
4774 completion_force_quote = true;
4775
4776 if (state == 0)
4777 {
4778 /* Initialization: stash the unquoted input. */
4779 unquoted_text = strtokx(text, "", NULL, "'", *completion_charp,
4780 false, true, pset.encoding);
4781 /* expect a NULL return for the empty string only */
4782 if (!unquoted_text)
4783 {
4784 Assert(*text == '\0');
4785 unquoted_text = text;
4786 }
4787 }
4788
4789 unquoted_match = rl_filename_completion_function(unquoted_text, state);
4790 if (unquoted_match)
4791 {
4792 struct stat statbuf;
4793 bool is_dir = (stat(unquoted_match, &statbuf) == 0 &&
4794 S_ISDIR(statbuf.st_mode) != 0);
4795
4796 /* Re-quote the result, if needed. */
4797 ret = quote_if_needed(unquoted_match, " \t\r\n\"`",
4798 '\'', *completion_charp,
4799 completion_force_quote,
4800 pset.encoding);
4801 if (ret)
4802 free(unquoted_match);
4803 else
4804 ret = unquoted_match;
4805
4806 /*
4807 * If it's a directory, replace trailing quote with a slash; this is
4808 * usually more convenient. (If we didn't quote, leave this to
4809 * libedit.)
4810 */
4811 if (*ret == '\'' && is_dir)
4812 {
4813 char *retend = ret + strlen(ret) - 1;
4814
4815 Assert(*retend == '\'');
4816 *retend = '/';
4817 /* Try to prevent libedit from adding a space, too */
4818 #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
4819 rl_completion_append_character = '\0';
4820 #endif
4821 }
4822 }
4823
4824 return ret;
4825 #endif /* USE_FILENAME_QUOTING_FUNCTIONS */
4826 }
4827
4828
4829 /* HELPER FUNCTIONS */
4830
4831
4832 /*
4833 * Make a pg_strdup copy of s and convert the case according to
4834 * COMP_KEYWORD_CASE setting, using ref as the text that was already entered.
4835 */
4836 static char *
pg_strdup_keyword_case(const char * s,const char * ref)4837 pg_strdup_keyword_case(const char *s, const char *ref)
4838 {
4839 char *ret,
4840 *p;
4841 unsigned char first = ref[0];
4842
4843 ret = pg_strdup(s);
4844
4845 if (pset.comp_case == PSQL_COMP_CASE_LOWER ||
4846 ((pset.comp_case == PSQL_COMP_CASE_PRESERVE_LOWER ||
4847 pset.comp_case == PSQL_COMP_CASE_PRESERVE_UPPER) && islower(first)) ||
4848 (pset.comp_case == PSQL_COMP_CASE_PRESERVE_LOWER && !isalpha(first)))
4849 {
4850 for (p = ret; *p; p++)
4851 *p = pg_tolower((unsigned char) *p);
4852 }
4853 else
4854 {
4855 for (p = ret; *p; p++)
4856 *p = pg_toupper((unsigned char) *p);
4857 }
4858
4859 return ret;
4860 }
4861
4862
4863 /*
4864 * escape_string - Escape argument for use as string literal.
4865 *
4866 * The returned value has to be freed.
4867 */
4868 static char *
escape_string(const char * text)4869 escape_string(const char *text)
4870 {
4871 size_t text_length;
4872 char *result;
4873
4874 text_length = strlen(text);
4875
4876 result = pg_malloc(text_length * 2 + 1);
4877 PQescapeStringConn(pset.db, result, text, text_length, NULL);
4878
4879 return result;
4880 }
4881
4882
4883 /*
4884 * Execute a query and report any errors. This should be the preferred way of
4885 * talking to the database in this file.
4886 */
4887 static PGresult *
exec_query(const char * query)4888 exec_query(const char *query)
4889 {
4890 PGresult *result;
4891
4892 if (query == NULL || !pset.db || PQstatus(pset.db) != CONNECTION_OK)
4893 return NULL;
4894
4895 result = PQexec(pset.db, query);
4896
4897 if (PQresultStatus(result) != PGRES_TUPLES_OK)
4898 {
4899 #ifdef NOT_USED
4900 pg_log_error("tab completion query failed: %s\nQuery was:\n%s",
4901 PQerrorMessage(pset.db), query);
4902 #endif
4903 PQclear(result);
4904 result = NULL;
4905 }
4906
4907 return result;
4908 }
4909
4910
4911 /*
4912 * Parse all the word(s) before point.
4913 *
4914 * Returns a malloc'd array of character pointers that point into the malloc'd
4915 * data array returned to *buffer; caller must free() both of these when done.
4916 * *nwords receives the number of words found, ie, the valid length of the
4917 * return array.
4918 *
4919 * Words are returned right to left, that is, previous_words[0] gets the last
4920 * word before point, previous_words[1] the next-to-last, etc.
4921 */
4922 static char **
get_previous_words(int point,char ** buffer,int * nwords)4923 get_previous_words(int point, char **buffer, int *nwords)
4924 {
4925 char **previous_words;
4926 char *buf;
4927 char *outptr;
4928 int words_found = 0;
4929 int i;
4930
4931 /*
4932 * If we have anything in tab_completion_query_buf, paste it together with
4933 * rl_line_buffer to construct the full query. Otherwise we can just use
4934 * rl_line_buffer as the input string.
4935 */
4936 if (tab_completion_query_buf && tab_completion_query_buf->len > 0)
4937 {
4938 i = tab_completion_query_buf->len;
4939 buf = pg_malloc(point + i + 2);
4940 memcpy(buf, tab_completion_query_buf->data, i);
4941 buf[i++] = '\n';
4942 memcpy(buf + i, rl_line_buffer, point);
4943 i += point;
4944 buf[i] = '\0';
4945 /* Readjust point to reference appropriate offset in buf */
4946 point = i;
4947 }
4948 else
4949 buf = rl_line_buffer;
4950
4951 /*
4952 * Allocate an array of string pointers and a buffer to hold the strings
4953 * themselves. The worst case is that the line contains only
4954 * non-whitespace WORD_BREAKS characters, making each one a separate word.
4955 * This is usually much more space than we need, but it's cheaper than
4956 * doing a separate malloc() for each word.
4957 */
4958 previous_words = (char **) pg_malloc(point * sizeof(char *));
4959 *buffer = outptr = (char *) pg_malloc(point * 2);
4960
4961 /*
4962 * First we look for a non-word char before the current point. (This is
4963 * probably useless, if readline is on the same page as we are about what
4964 * is a word, but if so it's cheap.)
4965 */
4966 for (i = point - 1; i >= 0; i--)
4967 {
4968 if (strchr(WORD_BREAKS, buf[i]))
4969 break;
4970 }
4971 point = i;
4972
4973 /*
4974 * Now parse words, working backwards, until we hit start of line. The
4975 * backwards scan has some interesting but intentional properties
4976 * concerning parenthesis handling.
4977 */
4978 while (point >= 0)
4979 {
4980 int start,
4981 end;
4982 bool inquotes = false;
4983 int parentheses = 0;
4984
4985 /* now find the first non-space which then constitutes the end */
4986 end = -1;
4987 for (i = point; i >= 0; i--)
4988 {
4989 if (!isspace((unsigned char) buf[i]))
4990 {
4991 end = i;
4992 break;
4993 }
4994 }
4995 /* if no end found, we're done */
4996 if (end < 0)
4997 break;
4998
4999 /*
5000 * Otherwise we now look for the start. The start is either the last
5001 * character before any word-break character going backwards from the
5002 * end, or it's simply character 0. We also handle open quotes and
5003 * parentheses.
5004 */
5005 for (start = end; start > 0; start--)
5006 {
5007 if (buf[start] == '"')
5008 inquotes = !inquotes;
5009 if (!inquotes)
5010 {
5011 if (buf[start] == ')')
5012 parentheses++;
5013 else if (buf[start] == '(')
5014 {
5015 if (--parentheses <= 0)
5016 break;
5017 }
5018 else if (parentheses == 0 &&
5019 strchr(WORD_BREAKS, buf[start - 1]))
5020 break;
5021 }
5022 }
5023
5024 /* Return the word located at start to end inclusive */
5025 previous_words[words_found++] = outptr;
5026 i = end - start + 1;
5027 memcpy(outptr, &buf[start], i);
5028 outptr += i;
5029 *outptr++ = '\0';
5030
5031 /* Continue searching */
5032 point = start - 1;
5033 }
5034
5035 /* Release parsing input workspace, if we made one above */
5036 if (buf != rl_line_buffer)
5037 free(buf);
5038
5039 *nwords = words_found;
5040 return previous_words;
5041 }
5042
5043 /*
5044 * Look up the type for the GUC variable with the passed name.
5045 *
5046 * Returns NULL if the variable is unknown. Otherwise the returned string,
5047 * containing the type, has to be freed.
5048 */
5049 static char *
get_guctype(const char * varname)5050 get_guctype(const char *varname)
5051 {
5052 PQExpBufferData query_buffer;
5053 char *e_varname;
5054 PGresult *result;
5055 char *guctype = NULL;
5056
5057 e_varname = escape_string(varname);
5058
5059 initPQExpBuffer(&query_buffer);
5060 appendPQExpBuffer(&query_buffer,
5061 "SELECT vartype FROM pg_catalog.pg_settings "
5062 "WHERE pg_catalog.lower(name) = pg_catalog.lower('%s')",
5063 e_varname);
5064
5065 result = exec_query(query_buffer.data);
5066 termPQExpBuffer(&query_buffer);
5067 free(e_varname);
5068
5069 if (PQresultStatus(result) == PGRES_TUPLES_OK && PQntuples(result) > 0)
5070 guctype = pg_strdup(PQgetvalue(result, 0, 0));
5071
5072 PQclear(result);
5073
5074 return guctype;
5075 }
5076
5077 #ifdef USE_FILENAME_QUOTING_FUNCTIONS
5078
5079 /*
5080 * Quote a filename according to SQL rules, returning a malloc'd string.
5081 * completion_charp must point to escape character or '\0', and
5082 * completion_force_quote must be set correctly, as per comments for
5083 * complete_from_files().
5084 */
5085 static char *
quote_file_name(char * fname,int match_type,char * quote_pointer)5086 quote_file_name(char *fname, int match_type, char *quote_pointer)
5087 {
5088 char *s;
5089 struct stat statbuf;
5090
5091 /* Quote if needed. */
5092 s = quote_if_needed(fname, " \t\r\n\"`",
5093 '\'', *completion_charp,
5094 completion_force_quote,
5095 pset.encoding);
5096 if (!s)
5097 s = pg_strdup(fname);
5098
5099 /*
5100 * However, some of the time we have to strip the trailing quote from what
5101 * we send back. Never strip the trailing quote if the user already typed
5102 * one; otherwise, suppress the trailing quote if we have multiple/no
5103 * matches (because we don't want to add a quote if the input is seemingly
5104 * unfinished), or if the input was already quoted (because Readline will
5105 * do arguably-buggy things otherwise), or if the file does not exist, or
5106 * if it's a directory.
5107 */
5108 if (*s == '\'' &&
5109 completion_last_char != '\'' &&
5110 (match_type != SINGLE_MATCH ||
5111 (quote_pointer && *quote_pointer == '\'') ||
5112 stat(fname, &statbuf) != 0 ||
5113 S_ISDIR(statbuf.st_mode)))
5114 {
5115 char *send = s + strlen(s) - 1;
5116
5117 Assert(*send == '\'');
5118 *send = '\0';
5119 }
5120
5121 /*
5122 * And now we can let Readline do its thing with possibly adding a quote
5123 * on its own accord. (This covers some additional cases beyond those
5124 * dealt with above.)
5125 */
5126 #ifdef HAVE_RL_COMPLETION_SUPPRESS_QUOTE
5127 rl_completion_suppress_quote = 0;
5128 #endif
5129
5130 /*
5131 * If user typed a leading quote character other than single quote (i.e.,
5132 * double quote), zap it, so that we replace it with the correct single
5133 * quote.
5134 */
5135 if (quote_pointer && *quote_pointer != '\'')
5136 *quote_pointer = '\0';
5137
5138 return s;
5139 }
5140
5141 /*
5142 * Dequote a filename, if it's quoted.
5143 * completion_charp must point to escape character or '\0', as per
5144 * comments for complete_from_files().
5145 */
5146 static char *
dequote_file_name(char * fname,int quote_char)5147 dequote_file_name(char *fname, int quote_char)
5148 {
5149 char *unquoted_fname;
5150
5151 /*
5152 * If quote_char is set, it's not included in "fname". We have to add it
5153 * or strtokx will not interpret the string correctly (notably, it won't
5154 * recognize escapes).
5155 */
5156 if (quote_char == '\'')
5157 {
5158 char *workspace = (char *) pg_malloc(strlen(fname) + 2);
5159
5160 workspace[0] = quote_char;
5161 strcpy(workspace + 1, fname);
5162 unquoted_fname = strtokx(workspace, "", NULL, "'", *completion_charp,
5163 false, true, pset.encoding);
5164 free(workspace);
5165 }
5166 else
5167 unquoted_fname = strtokx(fname, "", NULL, "'", *completion_charp,
5168 false, true, pset.encoding);
5169
5170 /* expect a NULL return for the empty string only */
5171 if (!unquoted_fname)
5172 {
5173 Assert(*fname == '\0');
5174 unquoted_fname = fname;
5175 }
5176
5177 /* readline expects a malloc'd result that it is to free */
5178 return pg_strdup(unquoted_fname);
5179 }
5180
5181 #endif /* USE_FILENAME_QUOTING_FUNCTIONS */
5182
5183 #endif /* USE_READLINE */
5184