PostgreSQL Source Code git master
tab-complete.in.c
Go to the documentation of this file.
1/*
2 * psql - the PostgreSQL interactive terminal
3 *
4 * Copyright (c) 2000-2025, PostgreSQL Global Development Group
5 *
6 * src/bin/psql/tab-complete.in.c
7 *
8 * Note: this will compile and work as-is if SWITCH_CONVERSION_APPLIED
9 * is not defined. However, the expected usage is that it's first run
10 * through gen_tabcomplete.pl, which will #define that symbol, fill in the
11 * tcpatterns[] array, and convert the else-if chain in match_previous_words()
12 * into a switch. See comments for match_previous_words() and the header
13 * comment in gen_tabcomplete.pl for more detail.
14 */
15
16/*----------------------------------------------------------------------
17 * This file implements a somewhat more sophisticated readline "TAB
18 * completion" in psql. It is not intended to be AI, to replace
19 * learning SQL, or to relieve you from thinking about what you're
20 * doing. Also it does not always give you all the syntactically legal
21 * completions, only those that are the most common or the ones that
22 * the programmer felt most like implementing.
23 *
24 * CAVEAT: Tab completion causes queries to be sent to the backend.
25 * The number of tuples returned gets limited, in most default
26 * installations to 1000, but if you still don't like this prospect,
27 * you can turn off tab completion in your ~/.inputrc (or else
28 * ${INPUTRC}) file so:
29 *
30 * $if psql
31 * set disable-completion on
32 * $endif
33 *
34 * See `man 3 readline' or `info readline' for the full details.
35 *
36 * BUGS:
37 * - Quotes, parentheses, and other funny characters are not handled
38 * all that gracefully.
39 *----------------------------------------------------------------------
40 */
41
42#include "postgres_fe.h"
43
44#include "input.h"
45#include "tab-complete.h"
46
47/* If we don't have this, we might as well forget about the whole thing: */
48#ifdef USE_READLINE
49
50#include <ctype.h>
51#include <sys/stat.h>
52
53#include "catalog/pg_am_d.h"
54#include "catalog/pg_class_d.h"
55#include "common.h"
56#include "common/keywords.h"
57#include "libpq-fe.h"
58#include "mb/pg_wchar.h"
59#include "pqexpbuffer.h"
60#include "settings.h"
61#include "stringutils.h"
62
63/*
64 * Ancient versions of libedit provide filename_completion_function()
65 * instead of rl_filename_completion_function(). Likewise for
66 * [rl_]completion_matches().
67 */
68#ifndef HAVE_RL_FILENAME_COMPLETION_FUNCTION
69#define rl_filename_completion_function filename_completion_function
70#endif
71
72#ifndef HAVE_RL_COMPLETION_MATCHES
73#define rl_completion_matches completion_matches
74#endif
75
76/*
77 * Currently we assume that rl_filename_dequoting_function exists if
78 * rl_filename_quoting_function does. If that proves not to be the case,
79 * we'd need to test for the former, or possibly both, in configure.
80 */
81#ifdef HAVE_RL_FILENAME_QUOTING_FUNCTION
82#define USE_FILENAME_QUOTING_FUNCTIONS 1
83#endif
84
85/* word break characters */
86#define WORD_BREAKS "\t\n@><=;|&() "
87
88/*
89 * Since readline doesn't let us pass any state through to the tab completion
90 * callback, we have to use this global variable to let get_previous_words()
91 * get at the previous lines of the current command. Ick.
92 */
94
95/*
96 * In some situations, the query to find out what names are available to
97 * complete with must vary depending on server version. We handle this by
98 * storing a list of queries, each tagged with the minimum server version
99 * it will work for. Each list must be stored in descending server version
100 * order, so that the first satisfactory query is the one to use.
101 *
102 * When the query string is otherwise constant, an array of VersionedQuery
103 * suffices. Terminate the array with an entry having min_server_version = 0.
104 * That entry's query string can be a query that works in all supported older
105 * server versions, or NULL to give up and do no completion.
106 */
107typedef struct VersionedQuery
108{
109 int min_server_version;
110 const char *query;
111} VersionedQuery;
112
113/*
114 * This struct is used to define "schema queries", which are custom-built
115 * to obtain possibly-schema-qualified names of database objects. There is
116 * enough similarity in the structure that we don't want to repeat it each
117 * time. So we put the components of each query into this struct and
118 * assemble them with the common boilerplate in _complete_from_query().
119 *
120 * We also use this struct to define queries that use completion_ref_object,
121 * which is some object related to the one(s) we want to get the names of
122 * (for example, the table we want the indexes of). In that usage the
123 * objects we're completing might not have a schema of their own, but the
124 * reference object almost always does (passed in completion_ref_schema).
125 *
126 * As with VersionedQuery, we can use an array of these if the query details
127 * must vary across versions.
128 */
129typedef struct SchemaQuery
130{
131 /*
132 * If not zero, minimum server version this struct applies to. If not
133 * zero, there should be a following struct with a smaller minimum server
134 * version; use catname == NULL in the last entry if we should do nothing.
135 */
136 int min_server_version;
137
138 /*
139 * Name of catalog or catalogs to be queried, with alias(es), eg.
140 * "pg_catalog.pg_class c". Note that "pg_namespace n" and/or
141 * "pg_namespace nr" will be added automatically when needed.
142 */
143 const char *catname;
144
145 /*
146 * Selection condition --- only rows meeting this condition are candidates
147 * to display. If catname mentions multiple tables, include the necessary
148 * join condition here. For example, this might look like "c.relkind = "
149 * CppAsString2(RELKIND_RELATION). Write NULL (not an empty string) if
150 * not needed.
151 */
152 const char *selcondition;
153
154 /*
155 * Visibility condition --- which rows are visible without schema
156 * qualification? For example, "pg_catalog.pg_table_is_visible(c.oid)".
157 * NULL if not needed.
158 */
159 const char *viscondition;
160
161 /*
162 * Namespace --- name of field to join to pg_namespace.oid when there is
163 * schema qualification. For example, "c.relnamespace". NULL if we don't
164 * want to join to pg_namespace (then any schema part in the input word
165 * will be ignored).
166 */
167 const char *namespace;
168
169 /*
170 * Result --- the base object name to return. For example, "c.relname".
171 */
172 const char *result;
173
174 /*
175 * In some cases, it's difficult to keep the query from returning the same
176 * object multiple times. Specify use_distinct to filter out duplicates.
177 */
178 bool use_distinct;
179
180 /*
181 * Additional literal strings (usually keywords) to be offered along with
182 * the query results. Provide a NULL-terminated array of constant
183 * strings, or NULL if none.
184 */
185 const char *const *keywords;
186
187 /*
188 * If this query uses completion_ref_object/completion_ref_schema,
189 * populate the remaining fields, else leave them NULL. When using this
190 * capability, catname must include the catalog that defines the
191 * completion_ref_object, and selcondition must include the join condition
192 * that connects it to the result's catalog.
193 *
194 * refname is the field that should be equated to completion_ref_object,
195 * for example "cr.relname".
196 */
197 const char *refname;
198
199 /*
200 * Visibility condition to use when completion_ref_schema is not set. For
201 * example, "pg_catalog.pg_table_is_visible(cr.oid)". NULL if not needed.
202 */
203 const char *refviscondition;
204
205 /*
206 * Name of field to join to pg_namespace.oid when completion_ref_schema is
207 * set. For example, "cr.relnamespace". NULL if we don't want to
208 * consider completion_ref_schema.
209 */
210 const char *refnamespace;
211} SchemaQuery;
212
213
214/* Store maximum number of records we want from database queries
215 * (implemented via SELECT ... LIMIT xx).
216 */
217static int completion_max_records;
218
219/*
220 * Communication variables set by psql_completion (mostly in COMPLETE_WITH_FOO
221 * macros) and then used by the completion callback functions. Ugly but there
222 * is no better way.
223 */
224static char completion_last_char; /* last char of input word */
225static const char *completion_charp; /* to pass a string */
226static const char *const *completion_charpp; /* to pass a list of strings */
227static const VersionedQuery *completion_vquery; /* to pass a VersionedQuery */
228static const SchemaQuery *completion_squery; /* to pass a SchemaQuery */
229static char *completion_ref_object; /* name of reference object */
230static char *completion_ref_schema; /* schema name of reference object */
231static bool completion_case_sensitive; /* completion is case sensitive */
232static bool completion_verbatim; /* completion is verbatim */
233static bool completion_force_quote; /* true to force-quote filenames */
234
235/*
236 * A few macros to ease typing. You can use these to complete the given
237 * string with
238 * 1) The result from a query you pass it. (Perhaps one of those below?)
239 * We support both simple and versioned queries.
240 * 2) The result from a schema query you pass it.
241 * We support both simple and versioned schema queries.
242 * 3) The items from a null-pointer-terminated list (with or without
243 * case-sensitive comparison); if the list is constant you can build it
244 * with COMPLETE_WITH() or COMPLETE_WITH_CS(). The QUERY_LIST and
245 * QUERY_PLUS forms combine such literal lists with a query result.
246 * 4) The list of attributes of the given table (possibly schema-qualified).
247 * 5) The list of arguments to the given function (possibly schema-qualified).
248 *
249 * The query is generally expected to return raw SQL identifiers; matching
250 * to what the user typed is done in a quoting-aware fashion. If what is
251 * returned is not SQL identifiers, use one of the VERBATIM forms, in which
252 * case the query results are matched to the user's text without double-quote
253 * processing (so if quoting is needed, you must provide it in the query
254 * results).
255 */
256#define COMPLETE_WITH_QUERY(query) \
257 COMPLETE_WITH_QUERY_LIST(query, NULL)
258
259#define COMPLETE_WITH_QUERY_LIST(query, list) \
260do { \
261 completion_charp = query; \
262 completion_charpp = list; \
263 completion_verbatim = false; \
264 matches = rl_completion_matches(text, complete_from_query); \
265} while (0)
266
267#define COMPLETE_WITH_QUERY_PLUS(query, ...) \
268do { \
269 static const char *const list[] = { __VA_ARGS__, NULL }; \
270 COMPLETE_WITH_QUERY_LIST(query, list); \
271} while (0)
272
273#define COMPLETE_WITH_QUERY_VERBATIM(query) \
274 COMPLETE_WITH_QUERY_VERBATIM_LIST(query, NULL)
275
276#define COMPLETE_WITH_QUERY_VERBATIM_LIST(query, list) \
277do { \
278 completion_charp = query; \
279 completion_charpp = list; \
280 completion_verbatim = true; \
281 matches = rl_completion_matches(text, complete_from_query); \
282} while (0)
283
284#define COMPLETE_WITH_QUERY_VERBATIM_PLUS(query, ...) \
285do { \
286 static const char *const list[] = { __VA_ARGS__, NULL }; \
287 COMPLETE_WITH_QUERY_VERBATIM_LIST(query, list); \
288} while (0)
289
290#define COMPLETE_WITH_VERSIONED_QUERY(query) \
291 COMPLETE_WITH_VERSIONED_QUERY_LIST(query, NULL)
292
293#define COMPLETE_WITH_VERSIONED_QUERY_LIST(query, list) \
294do { \
295 completion_vquery = query; \
296 completion_charpp = list; \
297 completion_verbatim = false; \
298 matches = rl_completion_matches(text, complete_from_versioned_query); \
299} while (0)
300
301#define COMPLETE_WITH_VERSIONED_QUERY_PLUS(query, ...) \
302do { \
303 static const char *const list[] = { __VA_ARGS__, NULL }; \
304 COMPLETE_WITH_VERSIONED_QUERY_LIST(query, list); \
305} while (0)
306
307#define COMPLETE_WITH_SCHEMA_QUERY(query) \
308 COMPLETE_WITH_SCHEMA_QUERY_LIST(query, NULL)
309
310#define COMPLETE_WITH_SCHEMA_QUERY_LIST(query, list) \
311do { \
312 completion_squery = &(query); \
313 completion_charpp = list; \
314 completion_verbatim = false; \
315 matches = rl_completion_matches(text, complete_from_schema_query); \
316} while (0)
317
318#define COMPLETE_WITH_SCHEMA_QUERY_PLUS(query, ...) \
319do { \
320 static const char *const list[] = { __VA_ARGS__, NULL }; \
321 COMPLETE_WITH_SCHEMA_QUERY_LIST(query, list); \
322} while (0)
323
324#define COMPLETE_WITH_SCHEMA_QUERY_VERBATIM(query) \
325do { \
326 completion_squery = &(query); \
327 completion_charpp = NULL; \
328 completion_verbatim = true; \
329 matches = rl_completion_matches(text, complete_from_schema_query); \
330} while (0)
331
332#define COMPLETE_WITH_VERSIONED_SCHEMA_QUERY(query) \
333 COMPLETE_WITH_VERSIONED_SCHEMA_QUERY_LIST(query, NULL)
334
335#define COMPLETE_WITH_VERSIONED_SCHEMA_QUERY_LIST(query, list) \
336do { \
337 completion_squery = query; \
338 completion_charpp = list; \
339 completion_verbatim = false; \
340 matches = rl_completion_matches(text, complete_from_versioned_schema_query); \
341} while (0)
342
343#define COMPLETE_WITH_VERSIONED_SCHEMA_QUERY_PLUS(query, ...) \
344do { \
345 static const char *const list[] = { __VA_ARGS__, NULL }; \
346 COMPLETE_WITH_VERSIONED_SCHEMA_QUERY_LIST(query, list); \
347} while (0)
348
349/*
350 * Caution: COMPLETE_WITH_CONST is not for general-purpose use; you probably
351 * want COMPLETE_WITH() with one element, instead.
352 */
353#define COMPLETE_WITH_CONST(cs, con) \
354do { \
355 completion_case_sensitive = (cs); \
356 completion_charp = (con); \
357 matches = rl_completion_matches(text, complete_from_const); \
358} while (0)
359
360#define COMPLETE_WITH_LIST_INT(cs, list) \
361do { \
362 completion_case_sensitive = (cs); \
363 completion_charpp = (list); \
364 matches = rl_completion_matches(text, complete_from_list); \
365} while (0)
366
367#define COMPLETE_WITH_LIST(list) COMPLETE_WITH_LIST_INT(false, list)
368#define COMPLETE_WITH_LIST_CS(list) COMPLETE_WITH_LIST_INT(true, list)
369
370#define COMPLETE_WITH(...) \
371do { \
372 static const char *const list[] = { __VA_ARGS__, NULL }; \
373 COMPLETE_WITH_LIST(list); \
374} while (0)
375
376#define COMPLETE_WITH_CS(...) \
377do { \
378 static const char *const list[] = { __VA_ARGS__, NULL }; \
379 COMPLETE_WITH_LIST_CS(list); \
380} while (0)
381
382#define COMPLETE_WITH_ATTR(relation) \
383 COMPLETE_WITH_ATTR_LIST(relation, NULL)
384
385#define COMPLETE_WITH_ATTR_LIST(relation, list) \
386do { \
387 set_completion_reference(relation); \
388 completion_squery = &(Query_for_list_of_attributes); \
389 completion_charpp = list; \
390 completion_verbatim = false; \
391 matches = rl_completion_matches(text, complete_from_schema_query); \
392} while (0)
393
394#define COMPLETE_WITH_ATTR_PLUS(relation, ...) \
395do { \
396 static const char *const list[] = { __VA_ARGS__, NULL }; \
397 COMPLETE_WITH_ATTR_LIST(relation, list); \
398} while (0)
399
400/*
401 * libedit will typically include the literal's leading single quote in
402 * "text", while readline will not. Adapt our offered strings to fit.
403 * But include a quote if there's not one just before "text", to get the
404 * user off to the right start.
405 */
406#define COMPLETE_WITH_ENUM_VALUE(type) \
407do { \
408 set_completion_reference(type); \
409 if (text[0] == '\'' || \
410 start == 0 || rl_line_buffer[start - 1] != '\'') \
411 completion_squery = &(Query_for_list_of_enum_values_quoted); \
412 else \
413 completion_squery = &(Query_for_list_of_enum_values_unquoted); \
414 completion_charpp = NULL; \
415 completion_verbatim = true; \
416 matches = rl_completion_matches(text, complete_from_schema_query); \
417} while (0)
418
419/*
420 * Timezone completion is mostly like enum label completion, but we work
421 * a little harder since this is a more common use-case.
422 */
423#define COMPLETE_WITH_TIMEZONE_NAME() \
424do { \
425 static const char *const list[] = { "DEFAULT", NULL }; \
426 if (text[0] == '\'') \
427 completion_charp = Query_for_list_of_timezone_names_quoted_in; \
428 else if (start == 0 || rl_line_buffer[start - 1] != '\'') \
429 completion_charp = Query_for_list_of_timezone_names_quoted_out; \
430 else \
431 completion_charp = Query_for_list_of_timezone_names_unquoted; \
432 completion_charpp = list; \
433 completion_verbatim = true; \
434 matches = rl_completion_matches(text, complete_from_query); \
435} while (0)
436
437#define COMPLETE_WITH_FUNCTION_ARG(function) \
438do { \
439 set_completion_reference(function); \
440 completion_squery = &(Query_for_list_of_arguments); \
441 completion_charpp = NULL; \
442 completion_verbatim = true; \
443 matches = rl_completion_matches(text, complete_from_schema_query); \
444} while (0)
445
446#define COMPLETE_WITH_FILES_LIST(escape, force_quote, list) \
447do { \
448 completion_charp = escape; \
449 completion_charpp = list; \
450 completion_force_quote = force_quote; \
451 matches = rl_completion_matches(text, complete_from_files); \
452} while (0)
453
454#define COMPLETE_WITH_FILES(escape, force_quote) \
455 COMPLETE_WITH_FILES_LIST(escape, force_quote, NULL)
456
457#define COMPLETE_WITH_FILES_PLUS(escape, force_quote, ...) \
458do { \
459 static const char *const list[] = { __VA_ARGS__, NULL }; \
460 COMPLETE_WITH_FILES_LIST(escape, force_quote, list); \
461} while (0)
462
463#define COMPLETE_WITH_GENERATOR(generator) \
464 matches = rl_completion_matches(text, generator)
465
466/*
467 * Assembly instructions for schema queries
468 *
469 * Note that toast tables are not included in those queries to avoid
470 * unnecessary bloat in the completions generated.
471 */
472
473static const SchemaQuery Query_for_constraint_of_table = {
474 .catname = "pg_catalog.pg_constraint con, pg_catalog.pg_class c1",
475 .selcondition = "con.conrelid=c1.oid",
476 .result = "con.conname",
477 .refname = "c1.relname",
478 .refviscondition = "pg_catalog.pg_table_is_visible(c1.oid)",
479 .refnamespace = "c1.relnamespace",
480};
481
482static const SchemaQuery Query_for_constraint_of_table_not_validated = {
483 .catname = "pg_catalog.pg_constraint con, pg_catalog.pg_class c1",
484 .selcondition = "con.conrelid=c1.oid and not con.convalidated",
485 .result = "con.conname",
486 .refname = "c1.relname",
487 .refviscondition = "pg_catalog.pg_table_is_visible(c1.oid)",
488 .refnamespace = "c1.relnamespace",
489};
490
491static const SchemaQuery Query_for_constraint_of_type = {
492 .catname = "pg_catalog.pg_constraint con, pg_catalog.pg_type t",
493 .selcondition = "con.contypid=t.oid",
494 .result = "con.conname",
495 .refname = "t.typname",
496 .refviscondition = "pg_catalog.pg_type_is_visible(t.oid)",
497 .refnamespace = "t.typnamespace",
498};
499
500static const SchemaQuery Query_for_index_of_table = {
501 .catname = "pg_catalog.pg_class c1, pg_catalog.pg_class c2, pg_catalog.pg_index i",
502 .selcondition = "c1.oid=i.indrelid and i.indexrelid=c2.oid",
503 .result = "c2.relname",
504 .refname = "c1.relname",
505 .refviscondition = "pg_catalog.pg_table_is_visible(c1.oid)",
506 .refnamespace = "c1.relnamespace",
507};
508
509static const SchemaQuery Query_for_unique_index_of_table = {
510 .catname = "pg_catalog.pg_class c1, pg_catalog.pg_class c2, pg_catalog.pg_index i",
511 .selcondition = "c1.oid=i.indrelid and i.indexrelid=c2.oid and i.indisunique",
512 .result = "c2.relname",
513 .refname = "c1.relname",
514 .refviscondition = "pg_catalog.pg_table_is_visible(c1.oid)",
515 .refnamespace = "c1.relnamespace",
516};
517
518static const SchemaQuery Query_for_list_of_aggregates[] = {
519 {
520 .min_server_version = 110000,
521 .catname = "pg_catalog.pg_proc p",
522 .selcondition = "p.prokind = 'a'",
523 .viscondition = "pg_catalog.pg_function_is_visible(p.oid)",
524 .namespace = "p.pronamespace",
525 .result = "p.proname",
526 },
527 {
528 .catname = "pg_catalog.pg_proc p",
529 .selcondition = "p.proisagg",
530 .viscondition = "pg_catalog.pg_function_is_visible(p.oid)",
531 .namespace = "p.pronamespace",
532 .result = "p.proname",
533 }
534};
535
536static const SchemaQuery Query_for_list_of_arguments = {
537 .catname = "pg_catalog.pg_proc p",
538 .result = "pg_catalog.oidvectortypes(p.proargtypes)||')'",
539 .refname = "p.proname",
540 .refviscondition = "pg_catalog.pg_function_is_visible(p.oid)",
541 .refnamespace = "p.pronamespace",
542};
543
544static const SchemaQuery Query_for_list_of_attributes = {
545 .catname = "pg_catalog.pg_attribute a, pg_catalog.pg_class c",
546 .selcondition = "c.oid = a.attrelid and a.attnum > 0 and not a.attisdropped",
547 .result = "a.attname",
548 .refname = "c.relname",
549 .refviscondition = "pg_catalog.pg_table_is_visible(c.oid)",
550 .refnamespace = "c.relnamespace",
551};
552
553static const SchemaQuery Query_for_list_of_attribute_numbers = {
554 .catname = "pg_catalog.pg_attribute a, pg_catalog.pg_class c",
555 .selcondition = "c.oid = a.attrelid and a.attnum > 0 and not a.attisdropped",
556 .result = "a.attnum::pg_catalog.text",
557 .refname = "c.relname",
558 .refviscondition = "pg_catalog.pg_table_is_visible(c.oid)",
559 .refnamespace = "c.relnamespace",
560};
561
562static const char *const Keywords_for_list_of_datatypes[] = {
563 "bigint",
564 "boolean",
565 "character",
566 "double precision",
567 "integer",
568 "real",
569 "smallint",
570
571 /*
572 * Note: currently there's no value in offering the following multiword
573 * type names, because tab completion cannot succeed for them: we can't
574 * disambiguate until somewhere in the second word, at which point we
575 * won't have the first word as context. ("double precision" does work,
576 * as long as no other type name begins with "double".) Leave them out to
577 * encourage users to use the PG-specific aliases, which we can complete.
578 */
579#ifdef NOT_USED
580 "bit varying",
581 "character varying",
582 "time with time zone",
583 "time without time zone",
584 "timestamp with time zone",
585 "timestamp without time zone",
586#endif
587 NULL
588};
589
590static const SchemaQuery Query_for_list_of_datatypes = {
591 .catname = "pg_catalog.pg_type t",
592 /* selcondition --- ignore table rowtypes and array types */
593 .selcondition = "(t.typrelid = 0 "
594 " OR (SELECT c.relkind = " CppAsString2(RELKIND_COMPOSITE_TYPE)
595 " FROM pg_catalog.pg_class c WHERE c.oid = t.typrelid)) "
596 "AND t.typname !~ '^_'",
597 .viscondition = "pg_catalog.pg_type_is_visible(t.oid)",
598 .namespace = "t.typnamespace",
599 .result = "t.typname",
600 .keywords = Keywords_for_list_of_datatypes,
601};
602
603static const SchemaQuery Query_for_list_of_composite_datatypes = {
604 .catname = "pg_catalog.pg_type t",
605 /* selcondition --- only get composite types */
606 .selcondition = "(SELECT c.relkind = " CppAsString2(RELKIND_COMPOSITE_TYPE)
607 " FROM pg_catalog.pg_class c WHERE c.oid = t.typrelid) "
608 "AND t.typname !~ '^_'",
609 .viscondition = "pg_catalog.pg_type_is_visible(t.oid)",
610 .namespace = "t.typnamespace",
611 .result = "t.typname",
612};
613
614static const SchemaQuery Query_for_list_of_domains = {
615 .catname = "pg_catalog.pg_type t",
616 .selcondition = "t.typtype = 'd'",
617 .viscondition = "pg_catalog.pg_type_is_visible(t.oid)",
618 .namespace = "t.typnamespace",
619 .result = "t.typname",
620};
621
622static const SchemaQuery Query_for_list_of_enum_values_quoted = {
623 .catname = "pg_catalog.pg_enum e, pg_catalog.pg_type t",
624 .selcondition = "t.oid = e.enumtypid",
625 .result = "pg_catalog.quote_literal(enumlabel)",
626 .refname = "t.typname",
627 .refviscondition = "pg_catalog.pg_type_is_visible(t.oid)",
628 .refnamespace = "t.typnamespace",
629};
630
631static const SchemaQuery Query_for_list_of_enum_values_unquoted = {
632 .catname = "pg_catalog.pg_enum e, pg_catalog.pg_type t",
633 .selcondition = "t.oid = e.enumtypid",
634 .result = "e.enumlabel",
635 .refname = "t.typname",
636 .refviscondition = "pg_catalog.pg_type_is_visible(t.oid)",
637 .refnamespace = "t.typnamespace",
638};
639
640/* Note: this intentionally accepts aggregates as well as plain functions */
641static const SchemaQuery Query_for_list_of_functions[] = {
642 {
643 .min_server_version = 110000,
644 .catname = "pg_catalog.pg_proc p",
645 .selcondition = "p.prokind != 'p'",
646 .viscondition = "pg_catalog.pg_function_is_visible(p.oid)",
647 .namespace = "p.pronamespace",
648 .result = "p.proname",
649 },
650 {
651 .catname = "pg_catalog.pg_proc p",
652 .viscondition = "pg_catalog.pg_function_is_visible(p.oid)",
653 .namespace = "p.pronamespace",
654 .result = "p.proname",
655 }
656};
657
658static const SchemaQuery Query_for_list_of_procedures[] = {
659 {
660 .min_server_version = 110000,
661 .catname = "pg_catalog.pg_proc p",
662 .selcondition = "p.prokind = 'p'",
663 .viscondition = "pg_catalog.pg_function_is_visible(p.oid)",
664 .namespace = "p.pronamespace",
665 .result = "p.proname",
666 },
667 {
668 /* not supported in older versions */
669 .catname = NULL,
670 }
671};
672
673static const SchemaQuery Query_for_list_of_routines = {
674 .catname = "pg_catalog.pg_proc p",
675 .viscondition = "pg_catalog.pg_function_is_visible(p.oid)",
676 .namespace = "p.pronamespace",
677 .result = "p.proname",
678};
679
680static const SchemaQuery Query_for_list_of_sequences = {
681 .catname = "pg_catalog.pg_class c",
682 .selcondition = "c.relkind IN (" CppAsString2(RELKIND_SEQUENCE) ")",
683 .viscondition = "pg_catalog.pg_table_is_visible(c.oid)",
684 .namespace = "c.relnamespace",
685 .result = "c.relname",
686};
687
688static const SchemaQuery Query_for_list_of_foreign_tables = {
689 .catname = "pg_catalog.pg_class c",
690 .selcondition = "c.relkind IN (" CppAsString2(RELKIND_FOREIGN_TABLE) ")",
691 .viscondition = "pg_catalog.pg_table_is_visible(c.oid)",
692 .namespace = "c.relnamespace",
693 .result = "c.relname",
694};
695
696static const SchemaQuery Query_for_list_of_tables = {
697 .catname = "pg_catalog.pg_class c",
698 .selcondition =
699 "c.relkind IN (" CppAsString2(RELKIND_RELATION) ", "
700 CppAsString2(RELKIND_PARTITIONED_TABLE) ")",
701 .viscondition = "pg_catalog.pg_table_is_visible(c.oid)",
702 .namespace = "c.relnamespace",
703 .result = "c.relname",
704};
705
706static const SchemaQuery Query_for_list_of_partitioned_tables = {
707 .catname = "pg_catalog.pg_class c",
708 .selcondition = "c.relkind IN (" CppAsString2(RELKIND_PARTITIONED_TABLE) ")",
709 .viscondition = "pg_catalog.pg_table_is_visible(c.oid)",
710 .namespace = "c.relnamespace",
711 .result = "c.relname",
712};
713
714static const SchemaQuery Query_for_list_of_tables_for_constraint = {
715 .catname = "pg_catalog.pg_class c, pg_catalog.pg_constraint con",
716 .selcondition = "c.oid=con.conrelid and c.relkind IN ("
717 CppAsString2(RELKIND_RELATION) ", "
718 CppAsString2(RELKIND_PARTITIONED_TABLE) ")",
719 .viscondition = "pg_catalog.pg_table_is_visible(c.oid)",
720 .namespace = "c.relnamespace",
721 .result = "c.relname",
722 .use_distinct = true,
723 .refname = "con.conname",
724};
725
726static const SchemaQuery Query_for_list_of_tables_for_policy = {
727 .catname = "pg_catalog.pg_class c, pg_catalog.pg_policy p",
728 .selcondition = "c.oid=p.polrelid",
729 .viscondition = "pg_catalog.pg_table_is_visible(c.oid)",
730 .namespace = "c.relnamespace",
731 .result = "c.relname",
732 .use_distinct = true,
733 .refname = "p.polname",
734};
735
736static const SchemaQuery Query_for_list_of_tables_for_rule = {
737 .catname = "pg_catalog.pg_class c, pg_catalog.pg_rewrite r",
738 .selcondition = "c.oid=r.ev_class",
739 .viscondition = "pg_catalog.pg_table_is_visible(c.oid)",
740 .namespace = "c.relnamespace",
741 .result = "c.relname",
742 .use_distinct = true,
743 .refname = "r.rulename",
744};
745
746static const SchemaQuery Query_for_list_of_tables_for_trigger = {
747 .catname = "pg_catalog.pg_class c, pg_catalog.pg_trigger t",
748 .selcondition = "c.oid=t.tgrelid",
749 .viscondition = "pg_catalog.pg_table_is_visible(c.oid)",
750 .namespace = "c.relnamespace",
751 .result = "c.relname",
752 .use_distinct = true,
753 .refname = "t.tgname",
754};
755
756static const SchemaQuery Query_for_list_of_ts_configurations = {
757 .catname = "pg_catalog.pg_ts_config c",
758 .viscondition = "pg_catalog.pg_ts_config_is_visible(c.oid)",
759 .namespace = "c.cfgnamespace",
760 .result = "c.cfgname",
761};
762
763static const SchemaQuery Query_for_list_of_ts_dictionaries = {
764 .catname = "pg_catalog.pg_ts_dict d",
765 .viscondition = "pg_catalog.pg_ts_dict_is_visible(d.oid)",
766 .namespace = "d.dictnamespace",
767 .result = "d.dictname",
768};
769
770static const SchemaQuery Query_for_list_of_ts_parsers = {
771 .catname = "pg_catalog.pg_ts_parser p",
772 .viscondition = "pg_catalog.pg_ts_parser_is_visible(p.oid)",
773 .namespace = "p.prsnamespace",
774 .result = "p.prsname",
775};
776
777static const SchemaQuery Query_for_list_of_ts_templates = {
778 .catname = "pg_catalog.pg_ts_template t",
779 .viscondition = "pg_catalog.pg_ts_template_is_visible(t.oid)",
780 .namespace = "t.tmplnamespace",
781 .result = "t.tmplname",
782};
783
784static const SchemaQuery Query_for_list_of_views = {
785 .catname = "pg_catalog.pg_class c",
786 .selcondition = "c.relkind IN (" CppAsString2(RELKIND_VIEW) ")",
787 .viscondition = "pg_catalog.pg_table_is_visible(c.oid)",
788 .namespace = "c.relnamespace",
789 .result = "c.relname",
790};
791
792static const SchemaQuery Query_for_list_of_matviews = {
793 .catname = "pg_catalog.pg_class c",
794 .selcondition = "c.relkind IN (" CppAsString2(RELKIND_MATVIEW) ")",
795 .viscondition = "pg_catalog.pg_table_is_visible(c.oid)",
796 .namespace = "c.relnamespace",
797 .result = "c.relname",
798};
799
800static const SchemaQuery Query_for_list_of_indexes = {
801 .catname = "pg_catalog.pg_class c",
802 .selcondition =
803 "c.relkind IN (" CppAsString2(RELKIND_INDEX) ", "
804 CppAsString2(RELKIND_PARTITIONED_INDEX) ")",
805 .viscondition = "pg_catalog.pg_table_is_visible(c.oid)",
806 .namespace = "c.relnamespace",
807 .result = "c.relname",
808};
809
810static const SchemaQuery Query_for_list_of_partitioned_indexes = {
811 .catname = "pg_catalog.pg_class c",
812 .selcondition = "c.relkind = " CppAsString2(RELKIND_PARTITIONED_INDEX),
813 .viscondition = "pg_catalog.pg_table_is_visible(c.oid)",
814 .namespace = "c.relnamespace",
815 .result = "c.relname",
816};
817
818
819/* All relations */
820static const SchemaQuery Query_for_list_of_relations = {
821 .catname = "pg_catalog.pg_class c",
822 .viscondition = "pg_catalog.pg_table_is_visible(c.oid)",
823 .namespace = "c.relnamespace",
824 .result = "c.relname",
825};
826
827/* partitioned relations */
828static const SchemaQuery Query_for_list_of_partitioned_relations = {
829 .catname = "pg_catalog.pg_class c",
830 .selcondition = "c.relkind IN (" CppAsString2(RELKIND_PARTITIONED_TABLE)
831 ", " CppAsString2(RELKIND_PARTITIONED_INDEX) ")",
832 .viscondition = "pg_catalog.pg_table_is_visible(c.oid)",
833 .namespace = "c.relnamespace",
834 .result = "c.relname",
835};
836
837static const SchemaQuery Query_for_list_of_operator_families = {
838 .catname = "pg_catalog.pg_opfamily c",
839 .viscondition = "pg_catalog.pg_opfamily_is_visible(c.oid)",
840 .namespace = "c.opfnamespace",
841 .result = "c.opfname",
842};
843
844/* Relations supporting INSERT, UPDATE or DELETE */
845static const SchemaQuery Query_for_list_of_updatables = {
846 .catname = "pg_catalog.pg_class c",
847 .selcondition =
848 "c.relkind IN (" CppAsString2(RELKIND_RELATION) ", "
849 CppAsString2(RELKIND_FOREIGN_TABLE) ", "
850 CppAsString2(RELKIND_VIEW) ", "
851 CppAsString2(RELKIND_PARTITIONED_TABLE) ")",
852 .viscondition = "pg_catalog.pg_table_is_visible(c.oid)",
853 .namespace = "c.relnamespace",
854 .result = "c.relname",
855};
856
857/* Relations supporting MERGE */
858static const SchemaQuery Query_for_list_of_mergetargets = {
859 .catname = "pg_catalog.pg_class c",
860 .selcondition =
861 "c.relkind IN (" CppAsString2(RELKIND_RELATION) ", "
862 CppAsString2(RELKIND_VIEW) ", "
863 CppAsString2(RELKIND_PARTITIONED_TABLE) ") ",
864 .viscondition = "pg_catalog.pg_table_is_visible(c.oid)",
865 .namespace = "c.relnamespace",
866 .result = "c.relname",
867};
868
869/* Relations supporting SELECT */
870static const SchemaQuery Query_for_list_of_selectables = {
871 .catname = "pg_catalog.pg_class c",
872 .selcondition =
873 "c.relkind IN (" CppAsString2(RELKIND_RELATION) ", "
874 CppAsString2(RELKIND_SEQUENCE) ", "
875 CppAsString2(RELKIND_VIEW) ", "
876 CppAsString2(RELKIND_MATVIEW) ", "
877 CppAsString2(RELKIND_FOREIGN_TABLE) ", "
878 CppAsString2(RELKIND_PARTITIONED_TABLE) ")",
879 .viscondition = "pg_catalog.pg_table_is_visible(c.oid)",
880 .namespace = "c.relnamespace",
881 .result = "c.relname",
882};
883
884/* Relations supporting TRUNCATE */
885static const SchemaQuery Query_for_list_of_truncatables = {
886 .catname = "pg_catalog.pg_class c",
887 .selcondition =
888 "c.relkind IN (" CppAsString2(RELKIND_RELATION) ", "
889 CppAsString2(RELKIND_FOREIGN_TABLE) ", "
890 CppAsString2(RELKIND_PARTITIONED_TABLE) ")",
891 .viscondition = "pg_catalog.pg_table_is_visible(c.oid)",
892 .namespace = "c.relnamespace",
893 .result = "c.relname",
894};
895
896/* Relations supporting GRANT are currently same as those supporting SELECT */
897#define Query_for_list_of_grantables Query_for_list_of_selectables
898
899/* Relations supporting ANALYZE */
900static const SchemaQuery Query_for_list_of_analyzables = {
901 .catname = "pg_catalog.pg_class c",
902 .selcondition =
903 "c.relkind IN (" CppAsString2(RELKIND_RELATION) ", "
904 CppAsString2(RELKIND_PARTITIONED_TABLE) ", "
905 CppAsString2(RELKIND_MATVIEW) ", "
906 CppAsString2(RELKIND_FOREIGN_TABLE) ")",
907 .viscondition = "pg_catalog.pg_table_is_visible(c.oid)",
908 .namespace = "c.relnamespace",
909 .result = "c.relname",
910};
911
912/*
913 * Relations supporting COPY TO/FROM are currently almost the same as
914 * those supporting ANALYZE. Although views with INSTEAD OF INSERT triggers
915 * can be used with COPY FROM, they are rarely used for this purpose,
916 * so plain views are intentionally excluded from this tab completion.
917 */
918#define Query_for_list_of_tables_for_copy Query_for_list_of_analyzables
919
920/* Relations supporting index creation */
921static const SchemaQuery Query_for_list_of_indexables = {
922 .catname = "pg_catalog.pg_class c",
923 .selcondition =
924 "c.relkind IN (" CppAsString2(RELKIND_RELATION) ", "
925 CppAsString2(RELKIND_PARTITIONED_TABLE) ", "
926 CppAsString2(RELKIND_MATVIEW) ")",
927 .viscondition = "pg_catalog.pg_table_is_visible(c.oid)",
928 .namespace = "c.relnamespace",
929 .result = "c.relname",
930};
931
932/*
933 * Relations supporting VACUUM are currently same as those supporting
934 * indexing.
935 */
936#define Query_for_list_of_vacuumables Query_for_list_of_indexables
937
938/* Relations supporting CLUSTER */
939static const SchemaQuery Query_for_list_of_clusterables = {
940 .catname = "pg_catalog.pg_class c",
941 .selcondition =
942 "c.relkind IN (" CppAsString2(RELKIND_RELATION) ", "
943 CppAsString2(RELKIND_PARTITIONED_TABLE) ", "
944 CppAsString2(RELKIND_MATVIEW) ")",
945 .viscondition = "pg_catalog.pg_table_is_visible(c.oid)",
946 .namespace = "c.relnamespace",
947 .result = "c.relname",
948};
949
950static const SchemaQuery Query_for_list_of_constraints_with_schema = {
951 .catname = "pg_catalog.pg_constraint c",
952 .selcondition = "c.conrelid <> 0",
953 .namespace = "c.connamespace",
954 .result = "c.conname",
955};
956
957static const SchemaQuery Query_for_list_of_statistics = {
958 .catname = "pg_catalog.pg_statistic_ext s",
959 .viscondition = "pg_catalog.pg_statistics_obj_is_visible(s.oid)",
960 .namespace = "s.stxnamespace",
961 .result = "s.stxname",
962};
963
964static const SchemaQuery Query_for_list_of_collations = {
965 .catname = "pg_catalog.pg_collation c",
966 .selcondition = "c.collencoding IN (-1, pg_catalog.pg_char_to_encoding(pg_catalog.getdatabaseencoding()))",
967 .viscondition = "pg_catalog.pg_collation_is_visible(c.oid)",
968 .namespace = "c.collnamespace",
969 .result = "c.collname",
970};
971
972static const SchemaQuery Query_for_partition_of_table = {
973 .catname = "pg_catalog.pg_class c1, pg_catalog.pg_class c2, pg_catalog.pg_inherits i",
974 .selcondition = "c1.oid=i.inhparent and i.inhrelid=c2.oid and c2.relispartition",
975 .viscondition = "pg_catalog.pg_table_is_visible(c2.oid)",
976 .namespace = "c2.relnamespace",
977 .result = "c2.relname",
978 .refname = "c1.relname",
979 .refviscondition = "pg_catalog.pg_table_is_visible(c1.oid)",
980 .refnamespace = "c1.relnamespace",
981};
982
983static const SchemaQuery Query_for_rule_of_table = {
984 .catname = "pg_catalog.pg_rewrite r, pg_catalog.pg_class c1",
985 .selcondition = "r.ev_class=c1.oid",
986 .result = "r.rulename",
987 .refname = "c1.relname",
988 .refviscondition = "pg_catalog.pg_table_is_visible(c1.oid)",
989 .refnamespace = "c1.relnamespace",
990};
991
992static const SchemaQuery Query_for_trigger_of_table = {
993 .catname = "pg_catalog.pg_trigger t, pg_catalog.pg_class c1",
994 .selcondition = "t.tgrelid=c1.oid and not t.tgisinternal",
995 .result = "t.tgname",
996 .refname = "c1.relname",
997 .refviscondition = "pg_catalog.pg_table_is_visible(c1.oid)",
998 .refnamespace = "c1.relnamespace",
999};
1000
1001
1002/*
1003 * Queries to get lists of names of various kinds of things, possibly
1004 * restricted to names matching a partially entered name. Don't use
1005 * this method where the user might wish to enter a schema-qualified
1006 * name; make a SchemaQuery instead.
1007 *
1008 * In these queries, there must be a restriction clause of the form
1009 * output LIKE '%s'
1010 * where "output" is the same string that the query returns. The %s
1011 * will be replaced by a LIKE pattern to match the already-typed text.
1012 *
1013 * There can be a second '%s', which will be replaced by a suitably-escaped
1014 * version of the string provided in completion_ref_object. If there is a
1015 * third '%s', it will be replaced by a suitably-escaped version of the string
1016 * provided in completion_ref_schema. NOTE: using completion_ref_object
1017 * that way is usually the wrong thing, and using completion_ref_schema
1018 * that way is always the wrong thing. Make a SchemaQuery instead.
1019 */
1020
1021#define Query_for_list_of_template_databases \
1022"SELECT d.datname "\
1023" FROM pg_catalog.pg_database d "\
1024" WHERE d.datname LIKE '%s' "\
1025" AND (d.datistemplate OR pg_catalog.pg_has_role(d.datdba, 'USAGE'))"
1026
1027#define Query_for_list_of_databases \
1028"SELECT datname FROM pg_catalog.pg_database "\
1029" WHERE datname LIKE '%s'"
1030
1031#define Query_for_list_of_database_vars \
1032"SELECT conf FROM ("\
1033" SELECT setdatabase, pg_catalog.split_part(pg_catalog.unnest(setconfig),'=',1) conf"\
1034" FROM pg_db_role_setting "\
1035" ) s, pg_database d "\
1036" WHERE s.setdatabase = d.oid "\
1037" AND conf LIKE '%s'"\
1038" AND d.datname LIKE '%s'"
1039
1040#define Query_for_list_of_tablespaces \
1041"SELECT spcname FROM pg_catalog.pg_tablespace "\
1042" WHERE spcname LIKE '%s'"
1043
1044#define Query_for_list_of_encodings \
1045" SELECT DISTINCT pg_catalog.pg_encoding_to_char(conforencoding) "\
1046" FROM pg_catalog.pg_conversion "\
1047" WHERE pg_catalog.pg_encoding_to_char(conforencoding) LIKE pg_catalog.upper('%s')"
1048
1049#define Query_for_list_of_languages \
1050"SELECT lanname "\
1051" FROM pg_catalog.pg_language "\
1052" WHERE lanname != 'internal' "\
1053" AND lanname LIKE '%s'"
1054
1055#define Query_for_list_of_schemas \
1056"SELECT nspname FROM pg_catalog.pg_namespace "\
1057" WHERE nspname LIKE '%s'"
1058
1059/* Use COMPLETE_WITH_QUERY_VERBATIM with these queries for GUC names: */
1060#define Query_for_list_of_alter_system_set_vars \
1061"SELECT pg_catalog.lower(name) FROM pg_catalog.pg_settings "\
1062" WHERE context != 'internal' "\
1063" AND pg_catalog.lower(name) LIKE pg_catalog.lower('%s')"
1064
1065#define Query_for_list_of_set_vars \
1066"SELECT pg_catalog.lower(name) FROM pg_catalog.pg_settings "\
1067" WHERE context IN ('user', 'superuser') "\
1068" AND pg_catalog.lower(name) LIKE pg_catalog.lower('%s')"
1069
1070#define Query_for_list_of_show_vars \
1071"SELECT pg_catalog.lower(name) FROM pg_catalog.pg_settings "\
1072" WHERE pg_catalog.lower(name) LIKE pg_catalog.lower('%s')"
1073
1074#define Query_for_list_of_roles \
1075" SELECT rolname "\
1076" FROM pg_catalog.pg_roles "\
1077" WHERE rolname LIKE '%s'"
1078
1079/* add these to Query_for_list_of_roles in OWNER contexts */
1080#define Keywords_for_list_of_owner_roles \
1081"CURRENT_ROLE", "CURRENT_USER", "SESSION_USER"
1082
1083/* add these to Query_for_list_of_roles in GRANT contexts */
1084#define Keywords_for_list_of_grant_roles \
1085Keywords_for_list_of_owner_roles, "PUBLIC"
1086
1087#define Query_for_all_table_constraints \
1088"SELECT conname "\
1089" FROM pg_catalog.pg_constraint c "\
1090" WHERE c.conrelid <> 0 "\
1091" and conname LIKE '%s'"
1092
1093#define Query_for_list_of_fdws \
1094" SELECT fdwname "\
1095" FROM pg_catalog.pg_foreign_data_wrapper "\
1096" WHERE fdwname LIKE '%s'"
1097
1098#define Query_for_list_of_servers \
1099" SELECT srvname "\
1100" FROM pg_catalog.pg_foreign_server "\
1101" WHERE srvname LIKE '%s'"
1102
1103#define Query_for_list_of_user_mappings \
1104" SELECT usename "\
1105" FROM pg_catalog.pg_user_mappings "\
1106" WHERE usename LIKE '%s'"
1107
1108#define Query_for_list_of_user_vars \
1109"SELECT conf FROM ("\
1110" SELECT rolname, pg_catalog.split_part(pg_catalog.unnest(rolconfig),'=',1) conf"\
1111" FROM pg_catalog.pg_roles"\
1112" ) s"\
1113" WHERE s.conf like '%s' "\
1114" AND s.rolname LIKE '%s'"
1115
1116#define Query_for_list_of_access_methods \
1117" SELECT amname "\
1118" FROM pg_catalog.pg_am "\
1119" WHERE amname LIKE '%s'"
1120
1121#define Query_for_list_of_index_access_methods \
1122" SELECT amname "\
1123" FROM pg_catalog.pg_am "\
1124" WHERE amname LIKE '%s' AND "\
1125" amtype=" CppAsString2(AMTYPE_INDEX)
1126
1127#define Query_for_list_of_table_access_methods \
1128" SELECT amname "\
1129" FROM pg_catalog.pg_am "\
1130" WHERE amname LIKE '%s' AND "\
1131" amtype=" CppAsString2(AMTYPE_TABLE)
1132
1133#define Query_for_list_of_extensions \
1134" SELECT extname "\
1135" FROM pg_catalog.pg_extension "\
1136" WHERE extname LIKE '%s'"
1137
1138#define Query_for_list_of_available_extensions \
1139" SELECT name "\
1140" FROM pg_catalog.pg_available_extensions "\
1141" WHERE name LIKE '%s' AND installed_version IS NULL"
1142
1143#define Query_for_list_of_available_extension_versions \
1144" SELECT version "\
1145" FROM pg_catalog.pg_available_extension_versions "\
1146" WHERE version LIKE '%s' AND name='%s'"
1147
1148#define Query_for_list_of_prepared_statements \
1149" SELECT name "\
1150" FROM pg_catalog.pg_prepared_statements "\
1151" WHERE name LIKE '%s'"
1152
1153#define Query_for_list_of_event_triggers \
1154" SELECT evtname "\
1155" FROM pg_catalog.pg_event_trigger "\
1156" WHERE evtname LIKE '%s'"
1157
1158#define Query_for_list_of_tablesample_methods \
1159" SELECT proname "\
1160" FROM pg_catalog.pg_proc "\
1161" WHERE prorettype = 'pg_catalog.tsm_handler'::pg_catalog.regtype AND "\
1162" proargtypes[0] = 'pg_catalog.internal'::pg_catalog.regtype AND "\
1163" proname LIKE '%s'"
1164
1165#define Query_for_list_of_policies \
1166" SELECT polname "\
1167" FROM pg_catalog.pg_policy "\
1168" WHERE polname LIKE '%s'"
1169
1170#define Query_for_values_of_enum_GUC \
1171" SELECT val FROM ( "\
1172" SELECT name, pg_catalog.unnest(enumvals) AS val "\
1173" FROM pg_catalog.pg_settings "\
1174" ) ss "\
1175" WHERE val LIKE '%s'"\
1176" and pg_catalog.lower(name)=pg_catalog.lower('%s')"
1177
1178#define Query_for_list_of_channels \
1179" SELECT channel "\
1180" FROM pg_catalog.pg_listening_channels() AS channel "\
1181" WHERE channel LIKE '%s'"
1182
1183#define Query_for_list_of_cursors \
1184" SELECT name "\
1185" FROM pg_catalog.pg_cursors "\
1186" WHERE name LIKE '%s'"
1187
1188#define Query_for_list_of_timezone_names_unquoted \
1189" SELECT name "\
1190" FROM pg_catalog.pg_timezone_names() "\
1191" WHERE pg_catalog.lower(name) LIKE pg_catalog.lower('%s')"
1192
1193#define Query_for_list_of_timezone_names_quoted_out \
1194"SELECT pg_catalog.quote_literal(name) AS name "\
1195" FROM pg_catalog.pg_timezone_names() "\
1196" WHERE pg_catalog.lower(name) LIKE pg_catalog.lower('%s')"
1197
1198#define Query_for_list_of_timezone_names_quoted_in \
1199"SELECT pg_catalog.quote_literal(name) AS name "\
1200" FROM pg_catalog.pg_timezone_names() "\
1201" WHERE pg_catalog.quote_literal(pg_catalog.lower(name)) LIKE pg_catalog.lower('%s')"
1202
1203/* Privilege options shared between GRANT and REVOKE */
1204#define Privilege_options_of_grant_and_revoke \
1205"SELECT", "INSERT", "UPDATE", "DELETE", "TRUNCATE", "REFERENCES", "TRIGGER", \
1206"CREATE", "CONNECT", "TEMPORARY", "EXECUTE", "USAGE", "SET", "ALTER SYSTEM", \
1207"MAINTAIN", "ALL"
1208
1209/* ALTER PROCEDURE options */
1210#define Alter_procedure_options \
1211"DEPENDS ON EXTENSION", "EXTERNAL SECURITY", "NO DEPENDS ON EXTENSION", \
1212"OWNER TO", "RENAME TO", "RESET", "SECURITY", "SET"
1213
1214/* ALTER ROUTINE options */
1215#define Alter_routine_options \
1216Alter_procedure_options, "COST", "IMMUTABLE", "LEAKPROOF", "NOT LEAKPROOF", \
1217"PARALLEL", "ROWS", "STABLE", "VOLATILE"
1218
1219/* ALTER FUNCTION options */
1220#define Alter_function_options \
1221Alter_routine_options, "CALLED ON NULL INPUT", "RETURNS NULL ON NULL INPUT", \
1222"STRICT", "SUPPORT"
1223
1224/* COPY options shared between FROM and TO */
1225#define Copy_common_options \
1226"DELIMITER", "ENCODING", "ESCAPE", "FORMAT", "HEADER", "NULL", "QUOTE"
1227
1228/* COPY FROM options */
1229#define Copy_from_options \
1230Copy_common_options, "DEFAULT", "FORCE_NOT_NULL", "FORCE_NULL", "FREEZE", \
1231"LOG_VERBOSITY", "ON_ERROR", "REJECT_LIMIT"
1232
1233/* COPY TO options */
1234#define Copy_to_options \
1235Copy_common_options, "FORCE_QUOTE"
1236
1237/*
1238 * These object types were introduced later than our support cutoff of
1239 * server version 9.2. We use the VersionedQuery infrastructure so that
1240 * we don't send certain-to-fail queries to older servers.
1241 */
1242
1243static const VersionedQuery Query_for_list_of_publications[] = {
1244 {100000,
1245 " SELECT pubname "
1246 " FROM pg_catalog.pg_publication "
1247 " WHERE pubname LIKE '%s'"
1248 },
1249 {0, NULL}
1250};
1251
1252static const VersionedQuery Query_for_list_of_subscriptions[] = {
1253 {100000,
1254 " SELECT s.subname "
1255 " FROM pg_catalog.pg_subscription s, pg_catalog.pg_database d "
1256 " WHERE s.subname LIKE '%s' "
1257 " AND d.datname = pg_catalog.current_database() "
1258 " AND s.subdbid = d.oid"
1259 },
1260 {0, NULL}
1261};
1262
1263 /* Known command-starting keywords. */
1264static const char *const sql_commands[] = {
1265 "ABORT", "ALTER", "ANALYZE", "BEGIN", "CALL", "CHECKPOINT", "CLOSE", "CLUSTER",
1266 "COMMENT", "COMMIT", "COPY", "CREATE", "DEALLOCATE", "DECLARE",
1267 "DELETE FROM", "DISCARD", "DO", "DROP", "END", "EXECUTE", "EXPLAIN",
1268 "FETCH", "GRANT", "IMPORT FOREIGN SCHEMA", "INSERT INTO", "LISTEN", "LOAD", "LOCK",
1269 "MERGE INTO", "MOVE", "NOTIFY", "PREPARE",
1270 "REASSIGN", "REFRESH MATERIALIZED VIEW", "REINDEX", "RELEASE",
1271 "RESET", "REVOKE", "ROLLBACK",
1272 "SAVEPOINT", "SECURITY LABEL", "SELECT", "SET", "SHOW", "START",
1273 "TABLE", "TRUNCATE", "UNLISTEN", "UPDATE", "VACUUM", "VALUES",
1274 "WAIT FOR", "WITH",
1275 NULL
1276};
1277
1278/*
1279 * This is a list of all "things" in Pgsql, which can show up after CREATE or
1280 * DROP; and there is also a query to get a list of them.
1281 */
1282
1283typedef struct
1284{
1285 const char *name;
1286 /* Provide at most one of these three types of query: */
1287 const char *query; /* simple query, or NULL */
1288 const VersionedQuery *vquery; /* versioned query, or NULL */
1289 const SchemaQuery *squery; /* schema query, or NULL */
1290 const char *const *keywords; /* keywords to be offered as well */
1291 const bits32 flags; /* visibility flags, see below */
1292} pgsql_thing_t;
1293
1294#define THING_NO_CREATE (1 << 0) /* should not show up after CREATE */
1295#define THING_NO_DROP (1 << 1) /* should not show up after DROP */
1296#define THING_NO_ALTER (1 << 2) /* should not show up after ALTER */
1297#define THING_NO_SHOW (THING_NO_CREATE | THING_NO_DROP | THING_NO_ALTER)
1298
1299/* When we have DROP USER etc, also offer MAPPING FOR */
1300static const char *const Keywords_for_user_thing[] = {
1301 "MAPPING FOR",
1302 NULL
1303};
1304
1305static const pgsql_thing_t words_after_create[] = {
1306 {"ACCESS METHOD", NULL, NULL, NULL, NULL, THING_NO_ALTER},
1307 {"AGGREGATE", NULL, NULL, Query_for_list_of_aggregates},
1308 {"CAST", NULL, NULL, NULL}, /* Casts have complex structures for names, so
1309 * skip it */
1310 {"COLLATION", NULL, NULL, &Query_for_list_of_collations},
1311
1312 /*
1313 * CREATE CONSTRAINT TRIGGER is not supported here because it is designed
1314 * to be used only by pg_dump.
1315 */
1316 {"CONFIGURATION", NULL, NULL, &Query_for_list_of_ts_configurations, NULL, THING_NO_SHOW},
1317 {"CONVERSION", "SELECT conname FROM pg_catalog.pg_conversion WHERE conname LIKE '%s'"},
1318 {"DATABASE", Query_for_list_of_databases},
1319 {"DEFAULT PRIVILEGES", NULL, NULL, NULL, NULL, THING_NO_CREATE | THING_NO_DROP},
1320 {"DICTIONARY", NULL, NULL, &Query_for_list_of_ts_dictionaries, NULL, THING_NO_SHOW},
1321 {"DOMAIN", NULL, NULL, &Query_for_list_of_domains},
1322 {"EVENT TRIGGER", NULL, NULL, NULL},
1323 {"EXTENSION", Query_for_list_of_extensions},
1324 {"FOREIGN DATA WRAPPER", NULL, NULL, NULL},
1325 {"FOREIGN TABLE", NULL, NULL, NULL},
1326 {"FUNCTION", NULL, NULL, Query_for_list_of_functions},
1327 {"GROUP", Query_for_list_of_roles},
1328 {"INDEX", NULL, NULL, &Query_for_list_of_indexes},
1329 {"LANGUAGE", Query_for_list_of_languages},
1330 {"LARGE OBJECT", NULL, NULL, NULL, NULL, THING_NO_CREATE | THING_NO_DROP},
1331 {"MATERIALIZED VIEW", NULL, NULL, &Query_for_list_of_matviews},
1332 {"OPERATOR", NULL, NULL, NULL}, /* Querying for this is probably not such
1333 * a good idea. */
1334 {"OR REPLACE", NULL, NULL, NULL, NULL, THING_NO_DROP | THING_NO_ALTER},
1335 {"OWNED", NULL, NULL, NULL, NULL, THING_NO_CREATE | THING_NO_ALTER}, /* for DROP OWNED BY ... */
1336 {"PARSER", NULL, NULL, &Query_for_list_of_ts_parsers, NULL, THING_NO_SHOW},
1337 {"POLICY", NULL, NULL, NULL},
1338 {"PROCEDURE", NULL, NULL, Query_for_list_of_procedures},
1339 {"PUBLICATION", NULL, Query_for_list_of_publications},
1340 {"ROLE", Query_for_list_of_roles},
1341 {"ROUTINE", NULL, NULL, &Query_for_list_of_routines, NULL, THING_NO_CREATE},
1342 {"RULE", "SELECT rulename FROM pg_catalog.pg_rules WHERE rulename LIKE '%s'"},
1343 {"SCHEMA", Query_for_list_of_schemas},
1344 {"SEQUENCE", NULL, NULL, &Query_for_list_of_sequences},
1345 {"SERVER", Query_for_list_of_servers},
1346 {"STATISTICS", NULL, NULL, &Query_for_list_of_statistics},
1347 {"SUBSCRIPTION", NULL, Query_for_list_of_subscriptions},
1348 {"SYSTEM", NULL, NULL, NULL, NULL, THING_NO_CREATE | THING_NO_DROP},
1349 {"TABLE", NULL, NULL, &Query_for_list_of_tables},
1350 {"TABLESPACE", Query_for_list_of_tablespaces},
1351 {"TEMP", NULL, NULL, NULL, NULL, THING_NO_DROP | THING_NO_ALTER}, /* for CREATE TEMP TABLE
1352 * ... */
1353 {"TEMPLATE", NULL, NULL, &Query_for_list_of_ts_templates, NULL, THING_NO_SHOW},
1354 {"TEMPORARY", NULL, NULL, NULL, NULL, THING_NO_DROP | THING_NO_ALTER}, /* for CREATE TEMPORARY
1355 * TABLE ... */
1356 {"TEXT SEARCH", NULL, NULL, NULL},
1357 {"TRANSFORM", NULL, NULL, NULL, NULL, THING_NO_ALTER},
1358 {"TRIGGER", "SELECT tgname FROM pg_catalog.pg_trigger WHERE tgname LIKE '%s' AND NOT tgisinternal"},
1359 {"TYPE", NULL, NULL, &Query_for_list_of_datatypes},
1360 {"UNIQUE", NULL, NULL, NULL, NULL, THING_NO_DROP | THING_NO_ALTER}, /* for CREATE UNIQUE
1361 * INDEX ... */
1362 {"UNLOGGED", NULL, NULL, NULL, NULL, THING_NO_DROP | THING_NO_ALTER}, /* for CREATE UNLOGGED
1363 * TABLE ... */
1364 {"USER", Query_for_list_of_roles, NULL, NULL, Keywords_for_user_thing},
1365 {"USER MAPPING FOR", NULL, NULL, NULL},
1366 {"VIEW", NULL, NULL, &Query_for_list_of_views},
1367 {NULL} /* end of list */
1368};
1369
1370/*
1371 * The tcpatterns[] table provides the initial pattern-match rule for each
1372 * switch case in match_previous_words(). The contents of the table
1373 * are constructed by gen_tabcomplete.pl.
1374 */
1375
1376/* Basic match rules appearing in tcpatterns[].kind */
1377enum TCPatternKind
1378{
1379 Match,
1380 MatchCS,
1381 HeadMatch,
1382 HeadMatchCS,
1383 TailMatch,
1384 TailMatchCS,
1385};
1386
1387/* Things besides string literals that can appear in tcpatterns[].words */
1388#define MatchAny NULL
1389#define MatchAnyExcept(pattern) ("!" pattern)
1390#define MatchAnyN ""
1391
1392/* One entry in tcpatterns[] */
1393typedef struct
1394{
1395 int id; /* case label used in match_previous_words */
1396 enum TCPatternKind kind; /* match kind, see above */
1397 int nwords; /* length of words[] array */
1398 const char *const *words; /* array of match words */
1399} TCPattern;
1400
1401/* Macro emitted by gen_tabcomplete.pl to fill a tcpatterns[] entry */
1402#define TCPAT(id, kind, ...) \
1403 { (id), (kind), VA_ARGS_NARGS(__VA_ARGS__), \
1404 (const char * const []) { __VA_ARGS__ } }
1405
1406#ifdef SWITCH_CONVERSION_APPLIED
1407
1408static const TCPattern tcpatterns[] =
1409{
1410 /* Insert tab-completion pattern data here. */
1411};
1412
1413#endif /* SWITCH_CONVERSION_APPLIED */
1414
1415/* Storage parameters for CREATE TABLE and ALTER TABLE */
1416static const char *const table_storage_parameters[] = {
1417 "autovacuum_analyze_scale_factor",
1418 "autovacuum_analyze_threshold",
1419 "autovacuum_enabled",
1420 "autovacuum_freeze_max_age",
1421 "autovacuum_freeze_min_age",
1422 "autovacuum_freeze_table_age",
1423 "autovacuum_multixact_freeze_max_age",
1424 "autovacuum_multixact_freeze_min_age",
1425 "autovacuum_multixact_freeze_table_age",
1426 "autovacuum_vacuum_cost_delay",
1427 "autovacuum_vacuum_cost_limit",
1428 "autovacuum_vacuum_insert_scale_factor",
1429 "autovacuum_vacuum_insert_threshold",
1430 "autovacuum_vacuum_max_threshold",
1431 "autovacuum_vacuum_scale_factor",
1432 "autovacuum_vacuum_threshold",
1433 "fillfactor",
1434 "log_autovacuum_min_duration",
1435 "log_autoanalyze_min_duration",
1436 "parallel_workers",
1437 "toast.autovacuum_enabled",
1438 "toast.autovacuum_freeze_max_age",
1439 "toast.autovacuum_freeze_min_age",
1440 "toast.autovacuum_freeze_table_age",
1441 "toast.autovacuum_multixact_freeze_max_age",
1442 "toast.autovacuum_multixact_freeze_min_age",
1443 "toast.autovacuum_multixact_freeze_table_age",
1444 "toast.autovacuum_vacuum_cost_delay",
1445 "toast.autovacuum_vacuum_cost_limit",
1446 "toast.autovacuum_vacuum_insert_scale_factor",
1447 "toast.autovacuum_vacuum_insert_threshold",
1448 "toast.autovacuum_vacuum_max_threshold",
1449 "toast.autovacuum_vacuum_scale_factor",
1450 "toast.autovacuum_vacuum_threshold",
1451 "toast.log_autovacuum_min_duration",
1452 "toast.vacuum_index_cleanup",
1453 "toast.vacuum_max_eager_freeze_failure_rate",
1454 "toast.vacuum_truncate",
1455 "toast_tuple_target",
1456 "user_catalog_table",
1457 "vacuum_index_cleanup",
1458 "vacuum_max_eager_freeze_failure_rate",
1459 "vacuum_truncate",
1460 NULL
1461};
1462
1463/* Optional parameters for CREATE VIEW and ALTER VIEW */
1464static const char *const view_optional_parameters[] = {
1465 "check_option",
1466 "security_barrier",
1467 "security_invoker",
1468 NULL
1469};
1470
1471/* Forward declaration of functions */
1472static char **psql_completion(const char *text, int start, int end);
1473static char **match_previous_words(int pattern_id,
1474 const char *text, int start, int end,
1475 char **previous_words,
1476 int previous_words_count);
1477static char *create_command_generator(const char *text, int state);
1478static char *drop_command_generator(const char *text, int state);
1479static char *alter_command_generator(const char *text, int state);
1480static char *complete_from_query(const char *text, int state);
1481static char *complete_from_versioned_query(const char *text, int state);
1482static char *complete_from_schema_query(const char *text, int state);
1483static char *complete_from_versioned_schema_query(const char *text, int state);
1484static char *_complete_from_query(const char *simple_query,
1485 const SchemaQuery *schema_query,
1486 const char *const *keywords,
1487 bool verbatim,
1488 const char *text, int state);
1489static void set_completion_reference(const char *word);
1490static void set_completion_reference_verbatim(const char *word);
1491static char *complete_from_list(const char *text, int state);
1492static char *complete_from_const(const char *text, int state);
1493static void append_variable_names(char ***varnames, int *nvars,
1494 int *maxvars, const char *varname,
1495 const char *prefix, const char *suffix);
1496static char **complete_from_variables(const char *text,
1497 const char *prefix, const char *suffix, bool need_value);
1498static char *complete_from_files(const char *text, int state);
1499static char *_complete_from_files(const char *text, int state);
1500
1501static char *pg_strdup_keyword_case(const char *s, const char *ref);
1502static char *escape_string(const char *text);
1503static char *make_like_pattern(const char *word);
1504static void parse_identifier(const char *ident,
1505 char **schemaname, char **objectname,
1506 bool *schemaquoted, bool *objectquoted);
1507static char *requote_identifier(const char *schemaname, const char *objectname,
1508 bool quote_schema, bool quote_object);
1509static bool identifier_needs_quotes(const char *ident);
1510static PGresult *exec_query(const char *query);
1511
1512static char **get_previous_words(int point, char **buffer, int *nwords);
1513
1514static char *get_guctype(const char *varname);
1515
1516#ifdef USE_FILENAME_QUOTING_FUNCTIONS
1517static char *quote_file_name(char *fname, int match_type, char *quote_pointer);
1518static char *dequote_file_name(char *fname, int quote_char);
1519#endif
1520
1521
1522/*
1523 * Initialize the readline library for our purposes.
1524 */
1525void
1527{
1528 rl_readline_name = (char *) pset.progname;
1529 rl_attempted_completion_function = psql_completion;
1530
1531#ifdef USE_FILENAME_QUOTING_FUNCTIONS
1532 rl_filename_quoting_function = quote_file_name;
1533 rl_filename_dequoting_function = dequote_file_name;
1534#endif
1535
1536 rl_basic_word_break_characters = WORD_BREAKS;
1537
1538 /*
1539 * Ideally we'd include '"' in rl_completer_quote_characters too, which
1540 * should allow us to complete quoted identifiers that include spaces.
1541 * However, the library support for rl_completer_quote_characters is
1542 * presently too inconsistent to want to mess with that. (Note in
1543 * particular that libedit has this variable but completely ignores it.)
1544 */
1545 rl_completer_quote_characters = "'";
1546
1547 /*
1548 * Set rl_filename_quote_characters to "all possible characters",
1549 * otherwise Readline will skip filename quoting if it thinks a filename
1550 * doesn't need quoting. Readline actually interprets this as bytes, so
1551 * there are no encoding considerations here.
1552 */
1553#ifdef HAVE_RL_FILENAME_QUOTE_CHARACTERS
1554 {
1555 unsigned char *fqc = (unsigned char *) pg_malloc(256);
1556
1557 for (int i = 0; i < 255; i++)
1558 fqc[i] = (unsigned char) (i + 1);
1559 fqc[255] = '\0';
1560 rl_filename_quote_characters = (const char *) fqc;
1561 }
1562#endif
1563
1564 completion_max_records = 1000;
1565
1566 /*
1567 * There is a variable rl_completion_query_items for this but apparently
1568 * it's not defined everywhere.
1569 */
1570}
1571
1572/*
1573 * Check if 'word' matches any of the '|'-separated strings in 'pattern',
1574 * using case-insensitive or case-sensitive comparisons.
1575 *
1576 * If pattern is NULL, it's a wild card that matches any word.
1577 * If pattern begins with '!', the result is negated, ie we check that 'word'
1578 * does *not* match any alternative appearing in the rest of 'pattern'.
1579 * Any alternative can contain '*' which is a wild card, i.e., it can match
1580 * any substring; however, we allow at most one '*' per alternative.
1581 *
1582 * For readability, callers should use the macros MatchAny and MatchAnyExcept
1583 * to invoke those two special cases for 'pattern'. (But '|' and '*' must
1584 * just be written directly in patterns.) There is also MatchAnyN, but that
1585 * is supported only in Matches/MatchesCS and is not handled here.
1586 */
1587static bool
1588word_matches(const char *pattern,
1589 const char *word,
1590 bool case_sensitive)
1591{
1592 size_t wordlen;
1593
1594#define cimatch(s1, s2, n) \
1595 (case_sensitive ? strncmp(s1, s2, n) == 0 : pg_strncasecmp(s1, s2, n) == 0)
1596
1597 /* NULL pattern matches anything. */
1598 if (pattern == NULL)
1599 return true;
1600
1601 /* Handle negated patterns from the MatchAnyExcept macro. */
1602 if (*pattern == '!')
1603 return !word_matches(pattern + 1, word, case_sensitive);
1604
1605 /* Else consider each alternative in the pattern. */
1606 wordlen = strlen(word);
1607 for (;;)
1608 {
1609 const char *star = NULL;
1610 const char *c;
1611
1612 /* Find end of current alternative, and locate any wild card. */
1613 c = pattern;
1614 while (*c != '\0' && *c != '|')
1615 {
1616 if (*c == '*')
1617 star = c;
1618 c++;
1619 }
1620 /* Was there a wild card? */
1621 if (star)
1622 {
1623 /* Yes, wildcard match? */
1624 size_t beforelen = star - pattern,
1625 afterlen = c - star - 1;
1626
1627 if (wordlen >= (beforelen + afterlen) &&
1628 cimatch(word, pattern, beforelen) &&
1629 cimatch(word + wordlen - afterlen, star + 1, afterlen))
1630 return true;
1631 }
1632 else
1633 {
1634 /* No, plain match? */
1635 if (wordlen == (c - pattern) &&
1636 cimatch(word, pattern, wordlen))
1637 return true;
1638 }
1639 /* Out of alternatives? */
1640 if (*c == '\0')
1641 break;
1642 /* Nope, try next alternative. */
1643 pattern = c + 1;
1644 }
1645
1646 return false;
1647}
1648
1649/*
1650 * Implementation of TailMatches and TailMatchesCS tests: do the last N words
1651 * in previous_words match the pattern arguments?
1652 *
1653 * The array indexing might look backwards, but remember that
1654 * previous_words[0] contains the *last* word on the line, not the first.
1655 */
1656static bool
1657TailMatchesArray(bool case_sensitive,
1658 int previous_words_count, char **previous_words,
1659 int narg, const char *const *args)
1660{
1661 if (previous_words_count < narg)
1662 return false;
1663
1664 for (int argno = 0; argno < narg; argno++)
1665 {
1666 const char *arg = args[argno];
1667
1668 if (!word_matches(arg, previous_words[narg - argno - 1],
1669 case_sensitive))
1670 return false;
1671 }
1672
1673 return true;
1674}
1675
1676/*
1677 * As above, but the pattern is passed as a variadic argument list.
1678 */
1679static bool
1680TailMatchesImpl(bool case_sensitive,
1681 int previous_words_count, char **previous_words,
1682 int narg,...)
1683{
1684 const char *argarray[64];
1685 va_list args;
1686
1687 Assert(narg <= lengthof(argarray));
1688
1689 if (previous_words_count < narg)
1690 return false;
1691
1692 va_start(args, narg);
1693 for (int argno = 0; argno < narg; argno++)
1694 argarray[argno] = va_arg(args, const char *);
1695 va_end(args);
1696
1697 return TailMatchesArray(case_sensitive,
1698 previous_words_count, previous_words,
1699 narg, argarray);
1700}
1701
1702/*
1703 * Implementation of HeadMatches and HeadMatchesCS tests: do the first N
1704 * words in previous_words match the pattern arguments?
1705 */
1706static bool
1707HeadMatchesArray(bool case_sensitive,
1708 int previous_words_count, char **previous_words,
1709 int narg, const char *const *args)
1710{
1711 if (previous_words_count < narg)
1712 return false;
1713
1714 for (int argno = 0; argno < narg; argno++)
1715 {
1716 const char *arg = args[argno];
1717
1718 if (!word_matches(arg, previous_words[previous_words_count - argno - 1],
1719 case_sensitive))
1720 return false;
1721 }
1722
1723 return true;
1724}
1725
1726/*
1727 * As above, but the pattern is passed as a variadic argument list.
1728 */
1729static bool
1730HeadMatchesImpl(bool case_sensitive,
1731 int previous_words_count, char **previous_words,
1732 int narg,...)
1733{
1734 const char *argarray[64];
1735 va_list args;
1736
1737 Assert(narg <= lengthof(argarray));
1738
1739 if (previous_words_count < narg)
1740 return false;
1741
1742 va_start(args, narg);
1743 for (int argno = 0; argno < narg; argno++)
1744 argarray[argno] = va_arg(args, const char *);
1745 va_end(args);
1746
1747 return HeadMatchesArray(case_sensitive,
1748 previous_words_count, previous_words,
1749 narg, argarray);
1750}
1751
1752/*
1753 * Implementation of Matches and MatchesCS tests: do all of the words
1754 * in previous_words match the pattern arguments?
1755 *
1756 * This supports an additional kind of wildcard: MatchAnyN (represented as "")
1757 * can match any number of words, including zero, in the middle of the list.
1758 */
1759static bool
1760MatchesArray(bool case_sensitive,
1761 int previous_words_count, char **previous_words,
1762 int narg, const char *const *args)
1763{
1764 int match_any_pos = -1;
1765
1766 /* Even with MatchAnyN, there must be at least N-1 words */
1767 if (previous_words_count < narg - 1)
1768 return false;
1769
1770 /* Check for MatchAnyN */
1771 for (int argno = 0; argno < narg; argno++)
1772 {
1773 const char *arg = args[argno];
1774
1775 if (arg != NULL && arg[0] == '\0')
1776 {
1777 match_any_pos = argno;
1778 break;
1779 }
1780 }
1781
1782 if (match_any_pos < 0)
1783 {
1784 /* Standard case without MatchAnyN */
1785 if (previous_words_count != narg)
1786 return false;
1787
1788 /* Either Head or Tail match will do for the rest */
1789 if (!HeadMatchesArray(case_sensitive,
1790 previous_words_count, previous_words,
1791 narg, args))
1792 return false;
1793 }
1794 else
1795 {
1796 /* Match against head */
1797 if (!HeadMatchesArray(case_sensitive,
1798 previous_words_count, previous_words,
1799 match_any_pos, args))
1800 return false;
1801
1802 /* Match against tail */
1803 if (!TailMatchesArray(case_sensitive,
1804 previous_words_count, previous_words,
1805 narg - match_any_pos - 1,
1806 args + match_any_pos + 1))
1807 return false;
1808 }
1809
1810 return true;
1811}
1812
1813/*
1814 * As above, but the pattern is passed as a variadic argument list.
1815 */
1816static bool
1817MatchesImpl(bool case_sensitive,
1818 int previous_words_count, char **previous_words,
1819 int narg,...)
1820{
1821 const char *argarray[64];
1822 va_list args;
1823
1824 Assert(narg <= lengthof(argarray));
1825
1826 /* Even with MatchAnyN, there must be at least N-1 words */
1827 if (previous_words_count < narg - 1)
1828 return false;
1829
1830 va_start(args, narg);
1831 for (int argno = 0; argno < narg; argno++)
1832 argarray[argno] = va_arg(args, const char *);
1833 va_end(args);
1834
1835 return MatchesArray(case_sensitive,
1836 previous_words_count, previous_words,
1837 narg, argarray);
1838}
1839
1840/*
1841 * Check if the final character of 's' is 'c'.
1842 */
1843static bool
1844ends_with(const char *s, char c)
1845{
1846 size_t length = strlen(s);
1847
1848 return (length > 0 && s[length - 1] == c);
1849}
1850
1851/*
1852 * The completion function.
1853 *
1854 * According to readline spec this gets passed the text entered so far and its
1855 * start and end positions in the readline buffer. The return value is some
1856 * partially obscure list format that can be generated by readline's
1857 * rl_completion_matches() function, so we don't have to worry about it.
1858 */
1859static char **
1860psql_completion(const char *text, int start, int end)
1861{
1862 /* This is the variable we'll return. */
1863 char **matches = NULL;
1864
1865 /* Workspace for parsed words. */
1866 char *words_buffer;
1867
1868 /* This array will contain pointers to parsed words. */
1869 char **previous_words;
1870
1871 /* The number of words found on the input line. */
1872 int previous_words_count;
1873
1874 /*
1875 * For compactness, we use these macros to reference previous_words[].
1876 * Caution: do not access a previous_words[] entry without having checked
1877 * previous_words_count to be sure it's valid. In most cases below, that
1878 * check is implicit in a TailMatches() or similar macro, but in some
1879 * places we have to check it explicitly.
1880 */
1881#define prev_wd (previous_words[0])
1882#define prev2_wd (previous_words[1])
1883#define prev3_wd (previous_words[2])
1884#define prev4_wd (previous_words[3])
1885#define prev5_wd (previous_words[4])
1886#define prev6_wd (previous_words[5])
1887#define prev7_wd (previous_words[6])
1888#define prev8_wd (previous_words[7])
1889#define prev9_wd (previous_words[8])
1890
1891 /* Match the last N words before point, case-insensitively. */
1892#define TailMatches(...) \
1893 TailMatchesImpl(false, previous_words_count, previous_words, \
1894 VA_ARGS_NARGS(__VA_ARGS__), __VA_ARGS__)
1895
1896 /* Match the last N words before point, case-sensitively. */
1897#define TailMatchesCS(...) \
1898 TailMatchesImpl(true, previous_words_count, previous_words, \
1899 VA_ARGS_NARGS(__VA_ARGS__), __VA_ARGS__)
1900
1901 /* Match N words representing all of the line, case-insensitively. */
1902#define Matches(...) \
1903 MatchesImpl(false, previous_words_count, previous_words, \
1904 VA_ARGS_NARGS(__VA_ARGS__), __VA_ARGS__)
1905
1906 /* Match N words representing all of the line, case-sensitively. */
1907#define MatchesCS(...) \
1908 MatchesImpl(true, previous_words_count, previous_words, \
1909 VA_ARGS_NARGS(__VA_ARGS__), __VA_ARGS__)
1910
1911 /* Match the first N words on the line, case-insensitively. */
1912#define HeadMatches(...) \
1913 HeadMatchesImpl(false, previous_words_count, previous_words, \
1914 VA_ARGS_NARGS(__VA_ARGS__), __VA_ARGS__)
1915
1916 /* Match the first N words on the line, case-sensitively. */
1917#define HeadMatchesCS(...) \
1918 HeadMatchesImpl(true, previous_words_count, previous_words, \
1919 VA_ARGS_NARGS(__VA_ARGS__), __VA_ARGS__)
1920
1921 /* psql's backslash commands. */
1922 static const char *const backslash_commands[] = {
1923 "\\a",
1924 "\\bind", "\\bind_named",
1925 "\\connect", "\\conninfo", "\\C", "\\cd", "\\close_prepared", "\\copy",
1926 "\\copyright", "\\crosstabview",
1927 "\\d", "\\da", "\\dA", "\\dAc", "\\dAf", "\\dAo", "\\dAp",
1928 "\\db", "\\dc", "\\dconfig", "\\dC", "\\dd", "\\ddp", "\\dD",
1929 "\\des", "\\det", "\\deu", "\\dew", "\\dE", "\\df",
1930 "\\dF", "\\dFd", "\\dFp", "\\dFt", "\\dg", "\\di", "\\dl", "\\dL",
1931 "\\dm", "\\dn", "\\do", "\\dO", "\\dp", "\\dP", "\\dPi", "\\dPt",
1932 "\\drds", "\\drg", "\\dRs", "\\dRp", "\\ds",
1933 "\\dt", "\\dT", "\\dv", "\\du", "\\dx", "\\dX", "\\dy",
1934 "\\echo", "\\edit", "\\ef", "\\elif", "\\else", "\\encoding",
1935 "\\endif", "\\endpipeline", "\\errverbose", "\\ev",
1936 "\\f", "\\flush", "\\flushrequest",
1937 "\\g", "\\gdesc", "\\getenv", "\\getresults", "\\gexec", "\\gset", "\\gx",
1938 "\\help", "\\html",
1939 "\\if", "\\include", "\\include_relative", "\\ir",
1940 "\\list", "\\lo_import", "\\lo_export", "\\lo_list", "\\lo_unlink",
1941 "\\out",
1942 "\\parse", "\\password", "\\print", "\\prompt", "\\pset",
1943 "\\qecho", "\\quit",
1944 "\\reset", "\\restrict",
1945 "\\s", "\\sendpipeline", "\\set", "\\setenv", "\\sf",
1946 "\\startpipeline", "\\sv", "\\syncpipeline",
1947 "\\t", "\\T", "\\timing",
1948 "\\unrestrict", "\\unset",
1949 "\\x",
1950 "\\warn", "\\watch", "\\write",
1951 "\\z",
1952 "\\!", "\\?",
1953 NULL
1954 };
1955
1956 /*
1957 * Temporary workaround for a bug in recent (2019) libedit: it incorrectly
1958 * de-escapes the input "text", causing us to fail to recognize backslash
1959 * commands. So get the string to look at from rl_line_buffer instead.
1960 */
1961 char *text_copy = pnstrdup(rl_line_buffer + start, end - start);
1962 text = text_copy;
1963
1964 /* Remember last char of the given input word. */
1965 completion_last_char = (end > start) ? text[end - start - 1] : '\0';
1966
1967 /* We usually want the append character to be a space. */
1968 rl_completion_append_character = ' ';
1969
1970 /* Clear a few things. */
1971 completion_charp = NULL;
1972 completion_charpp = NULL;
1973 completion_vquery = NULL;
1974 completion_squery = NULL;
1975 completion_ref_object = NULL;
1976 completion_ref_schema = NULL;
1977
1978 /*
1979 * Scan the input line to extract the words before our current position.
1980 * According to those we'll make some smart decisions on what the user is
1981 * probably intending to type.
1982 */
1983 previous_words = get_previous_words(start,
1984 &words_buffer,
1985 &previous_words_count);
1986
1987 /* If current word is a backslash command, offer completions for that */
1988 if (text[0] == '\\')
1989 COMPLETE_WITH_LIST_CS(backslash_commands);
1990
1991 /* If current word is a variable interpolation, handle that case */
1992 else if (text[0] == ':' && text[1] != ':')
1993 {
1994 if (text[1] == '\'')
1995 matches = complete_from_variables(text, ":'", "'", true);
1996 else if (text[1] == '"')
1997 matches = complete_from_variables(text, ":\"", "\"", true);
1998 else if (text[1] == '{' && text[2] == '?')
1999 matches = complete_from_variables(text, ":{?", "}", true);
2000 else
2001 matches = complete_from_variables(text, ":", "", true);
2002 }
2003
2004 /* If no previous word, suggest one of the basic sql commands */
2005 else if (previous_words_count == 0)
2006 COMPLETE_WITH_LIST(sql_commands);
2007
2008 /* Else try completions based on matching patterns of previous words */
2009 else
2010 {
2011#ifdef SWITCH_CONVERSION_APPLIED
2012 /*
2013 * If we have transformed match_previous_words into a switch, iterate
2014 * through tcpatterns[] to see which pattern ids match.
2015 *
2016 * For now, we have to try the patterns in the order they are stored
2017 * (matching the order of switch cases in match_previous_words),
2018 * because some of the logic in match_previous_words assumes that
2019 * previous matches have been eliminated. This is fairly
2020 * unprincipled, and it is likely that there are undesirable as well
2021 * as desirable interactions hidden in the order of the pattern
2022 * checks. TODO: think about a better way to manage that.
2023 */
2024 for (int tindx = 0; tindx < lengthof(tcpatterns); tindx++)
2025 {
2026 const TCPattern *tcpat = tcpatterns + tindx;
2027 bool match = false;
2028
2029 switch (tcpat->kind)
2030 {
2031 case Match:
2032 match = MatchesArray(false,
2033 previous_words_count,
2034 previous_words,
2035 tcpat->nwords, tcpat->words);
2036 break;
2037 case MatchCS:
2038 match = MatchesArray(true,
2039 previous_words_count,
2040 previous_words,
2041 tcpat->nwords, tcpat->words);
2042 break;
2043 case HeadMatch:
2044 match = HeadMatchesArray(false,
2045 previous_words_count,
2046 previous_words,
2047 tcpat->nwords, tcpat->words);
2048 break;
2049 case HeadMatchCS:
2050 match = HeadMatchesArray(true,
2051 previous_words_count,
2052 previous_words,
2053 tcpat->nwords, tcpat->words);
2054 break;
2055 case TailMatch:
2056 match = TailMatchesArray(false,
2057 previous_words_count,
2058 previous_words,
2059 tcpat->nwords, tcpat->words);
2060 break;
2061 case TailMatchCS:
2062 match = TailMatchesArray(true,
2063 previous_words_count,
2064 previous_words,
2065 tcpat->nwords, tcpat->words);
2066 break;
2067 }
2068 if (match)
2069 {
2070 matches = match_previous_words(tcpat->id, text, start, end,
2071 previous_words,
2072 previous_words_count);
2073 if (matches != NULL)
2074 break;
2075 }
2076 }
2077#else /* !SWITCH_CONVERSION_APPLIED */
2078 /*
2079 * If gen_tabcomplete.pl hasn't been applied to this code, just let
2080 * match_previous_words scan through all its patterns.
2081 */
2082 matches = match_previous_words(0, text, start, end,
2083 previous_words,
2084 previous_words_count);
2085#endif /* SWITCH_CONVERSION_APPLIED */
2086 }
2087
2088 /*
2089 * Finally, we look through the list of "things", such as TABLE, INDEX and
2090 * check if that was the previous word. If so, execute the query to get a
2091 * list of them.
2092 */
2093 if (matches == NULL && previous_words_count > 0)
2094 {
2095 const pgsql_thing_t *wac;
2096
2097 for (wac = words_after_create; wac->name != NULL; wac++)
2098 {
2099 if (pg_strcasecmp(prev_wd, wac->name) == 0)
2100 {
2101 if (wac->query)
2102 COMPLETE_WITH_QUERY_LIST(wac->query,
2103 wac->keywords);
2104 else if (wac->vquery)
2105 COMPLETE_WITH_VERSIONED_QUERY_LIST(wac->vquery,
2106 wac->keywords);
2107 else if (wac->squery)
2108 COMPLETE_WITH_VERSIONED_SCHEMA_QUERY_LIST(wac->squery,
2109 wac->keywords);
2110 break;
2111 }
2112 }
2113 }
2114
2115 /*
2116 * If we still don't have anything to match we have to fabricate some sort
2117 * of default list. If we were to just return NULL, readline automatically
2118 * attempts filename completion, and that's usually no good.
2119 */
2120 if (matches == NULL)
2121 {
2122 COMPLETE_WITH_CONST(true, "");
2123 /* Also, prevent Readline from appending stuff to the non-match */
2124 rl_completion_append_character = '\0';
2125#ifdef HAVE_RL_COMPLETION_SUPPRESS_QUOTE
2126 rl_completion_suppress_quote = 1;
2127#endif
2128 }
2129
2130 /* free storage */
2131 free(previous_words);
2132 free(words_buffer);
2133 free(text_copy);
2134 free(completion_ref_object);
2135 completion_ref_object = NULL;
2136 free(completion_ref_schema);
2137 completion_ref_schema = NULL;
2138
2139 /* Return our Grand List O' Matches */
2140 return matches;
2141}
2142
2143/*
2144 * Subroutine to try matches based on previous_words.
2145 *
2146 * This can operate in one of two modes. As presented, the body of the
2147 * function is a long if-else-if chain that sequentially tries each known
2148 * match rule. That works, but some C compilers have trouble with such a long
2149 * else-if chain, either taking extra time to compile or failing altogether.
2150 * Therefore, we prefer to transform the else-if chain into a switch, and then
2151 * each call of this function considers just one match rule (under control of
2152 * a loop in psql_completion()). Compilers tend to be more ready to deal
2153 * with many-arm switches than many-arm else-if chains.
2154 *
2155 * Each if-condition in this function must begin with a call of one of the
2156 * functions Matches, HeadMatches, TailMatches, MatchesCS, HeadMatchesCS, or
2157 * TailMatchesCS. The preprocessor gen_tabcomplete.pl strips out those
2158 * calls and converts them into entries in tcpatterns[], which are evaluated
2159 * by the calling loop in psql_completion(). Successful matches result in
2160 * calls to this function with the appropriate pattern_id, causing just the
2161 * corresponding switch case to be executed.
2162 *
2163 * If-conditions in this function can be more complex than a single *Matches
2164 * function call in one of two ways (but not both!). They can be OR's
2165 * of *Matches calls, such as
2166 * else if (Matches("ALTER", "VIEW", MatchAny, "ALTER", MatchAny) ||
2167 * Matches("ALTER", "VIEW", MatchAny, "ALTER", "COLUMN", MatchAny))
2168 * or they can be a *Matches call AND'ed with some other condition, e.g.
2169 * else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLE", MatchAny) &&
2170 * !ends_with(prev_wd, ','))
2171 * The former case is transformed into multiple tcpatterns[] entries and
2172 * multiple case labels for the same bit of code. The latter case is
2173 * transformed into a case label and a contained if-statement.
2174 *
2175 * This is split out of psql_completion() primarily to separate code that
2176 * gen_tabcomplete.pl should process from code that it should not, although
2177 * doing so also helps to avoid extra indentation of this code.
2178 *
2179 * Returns a matches list, or NULL if no match.
2180 */
2181static char **
2182match_previous_words(int pattern_id,
2183 const char *text, int start, int end,
2184 char **previous_words, int previous_words_count)
2185{
2186 /* This is the variable we'll return. */
2187 char **matches = NULL;
2188
2189 /* Dummy statement, allowing all the match rules to look like "else if" */
2190 if (0)
2191 {
2192 /* skip */
2193 }
2194
2195 /* gen_tabcomplete.pl begins special processing here */
2196 /* BEGIN GEN_TABCOMPLETE */
2197
2198/* CREATE */
2199 /* complete with something you can create */
2200 else if (TailMatches("CREATE"))
2201 {
2202 /* only some object types can be created as part of CREATE SCHEMA */
2203 if (HeadMatches("CREATE", "SCHEMA"))
2204 COMPLETE_WITH("TABLE", "VIEW", "INDEX", "SEQUENCE", "TRIGGER",
2205 /* for INDEX and TABLE/SEQUENCE, respectively */
2206 "UNIQUE", "UNLOGGED");
2207 else
2208 COMPLETE_WITH_GENERATOR(create_command_generator);
2209 }
2210 /* complete with something you can create or replace */
2211 else if (TailMatches("CREATE", "OR", "REPLACE"))
2212 COMPLETE_WITH("FUNCTION", "PROCEDURE", "LANGUAGE", "RULE", "VIEW",
2213 "AGGREGATE", "TRANSFORM", "TRIGGER");
2214
2215/* DROP, but not DROP embedded in other commands */
2216 /* complete with something you can drop */
2217 else if (Matches("DROP"))
2218 COMPLETE_WITH_GENERATOR(drop_command_generator);
2219
2220/* ALTER */
2221
2222 /* ALTER TABLE */
2223 else if (Matches("ALTER", "TABLE"))
2224 COMPLETE_WITH_SCHEMA_QUERY_PLUS(Query_for_list_of_tables,
2225 "ALL IN TABLESPACE");
2226
2227 /* ALTER something */
2228 else if (Matches("ALTER"))
2229 COMPLETE_WITH_GENERATOR(alter_command_generator);
2230 /* ALTER TABLE,INDEX,MATERIALIZED VIEW ALL IN TABLESPACE xxx */
2231 else if (TailMatches("ALL", "IN", "TABLESPACE", MatchAny))
2232 COMPLETE_WITH("SET TABLESPACE", "OWNED BY");
2233 /* ALTER TABLE,INDEX,MATERIALIZED VIEW ALL IN TABLESPACE xxx OWNED BY */
2234 else if (TailMatches("ALL", "IN", "TABLESPACE", MatchAny, "OWNED", "BY"))
2235 COMPLETE_WITH_QUERY(Query_for_list_of_roles);
2236 /* ALTER TABLE,INDEX,MATERIALIZED VIEW ALL IN TABLESPACE xxx OWNED BY xxx */
2237 else if (TailMatches("ALL", "IN", "TABLESPACE", MatchAny, "OWNED", "BY", MatchAny))
2238 COMPLETE_WITH("SET TABLESPACE");
2239 /* ALTER AGGREGATE,FUNCTION,PROCEDURE,ROUTINE <name> */
2240 else if (Matches("ALTER", "AGGREGATE|FUNCTION|PROCEDURE|ROUTINE", MatchAny))
2241 COMPLETE_WITH("(");
2242 /* ALTER AGGREGATE <name> (...) */
2243 else if (Matches("ALTER", "AGGREGATE", MatchAny, MatchAny))
2244 {
2245 if (ends_with(prev_wd, ')'))
2246 COMPLETE_WITH("OWNER TO", "RENAME TO", "SET SCHEMA");
2247 else
2248 COMPLETE_WITH_FUNCTION_ARG(prev2_wd);
2249 }
2250 /* ALTER FUNCTION <name> (...) */
2251 else if (Matches("ALTER", "FUNCTION", MatchAny, MatchAny))
2252 {
2253 if (ends_with(prev_wd, ')'))
2254 COMPLETE_WITH(Alter_function_options);
2255 else
2256 COMPLETE_WITH_FUNCTION_ARG(prev2_wd);
2257 }
2258 /* ALTER PROCEDURE <name> (...) */
2259 else if (Matches("ALTER", "PROCEDURE", MatchAny, MatchAny))
2260 {
2261 if (ends_with(prev_wd, ')'))
2262 COMPLETE_WITH(Alter_procedure_options);
2263 else
2264 COMPLETE_WITH_FUNCTION_ARG(prev2_wd);
2265 }
2266 /* ALTER ROUTINE <name> (...) */
2267 else if (Matches("ALTER", "ROUTINE", MatchAny, MatchAny))
2268 {
2269 if (ends_with(prev_wd, ')'))
2270 COMPLETE_WITH(Alter_routine_options);
2271 else
2272 COMPLETE_WITH_FUNCTION_ARG(prev2_wd);
2273 }
2274 /* ALTER FUNCTION|ROUTINE <name> (...) PARALLEL */
2275 else if (Matches("ALTER", "FUNCTION|ROUTINE", MatchAny, MatchAny, "PARALLEL"))
2276 COMPLETE_WITH("RESTRICTED", "SAFE", "UNSAFE");
2277 /* ALTER FUNCTION|PROCEDURE|ROUTINE <name> (...) [EXTERNAL] SECURITY */
2278 else if (Matches("ALTER", "FUNCTION|PROCEDURE|ROUTINE", MatchAny, MatchAny, "SECURITY") ||
2279 Matches("ALTER", "FUNCTION|PROCEDURE|ROUTINE", MatchAny, MatchAny, "EXTERNAL", "SECURITY"))
2280 COMPLETE_WITH("DEFINER", "INVOKER");
2281 /* ALTER FUNCTION|PROCEDURE|ROUTINE <name> (...) RESET */
2282 else if (Matches("ALTER", "FUNCTION|PROCEDURE|ROUTINE", MatchAny, MatchAny, "RESET"))
2283 COMPLETE_WITH_QUERY_VERBATIM_PLUS(Query_for_list_of_set_vars,
2284 "ALL");
2285 /* ALTER FUNCTION|PROCEDURE|ROUTINE <name> (...) SET */
2286 else if (Matches("ALTER", "FUNCTION|PROCEDURE|ROUTINE", MatchAny, MatchAny, "SET"))
2287 COMPLETE_WITH_QUERY_VERBATIM_PLUS(Query_for_list_of_set_vars,
2288 "SCHEMA");
2289
2290 /* ALTER PUBLICATION <name> */
2291 else if (Matches("ALTER", "PUBLICATION", MatchAny))
2292 COMPLETE_WITH("ADD", "DROP", "OWNER TO", "RENAME TO", "SET");
2293 /* ALTER PUBLICATION <name> ADD */
2294 else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD"))
2295 COMPLETE_WITH("TABLES IN SCHEMA", "TABLE");
2296 else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD|SET", "TABLE"))
2297 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables);
2298 else if (HeadMatches("ALTER", "PUBLICATION", MatchAny, "ADD|SET", "TABLE") &&
2299 ends_with(prev_wd, ','))
2300 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables);
2301
2302 /*
2303 * "ALTER PUBLICATION <name> SET TABLE <name> WHERE (" - complete with
2304 * table attributes
2305 *
2306 * "ALTER PUBLICATION <name> ADD TABLE <name> WHERE (" - complete with
2307 * table attributes
2308 */
2309 else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "WHERE"))
2310 COMPLETE_WITH("(");
2311 else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "WHERE", "("))
2312 COMPLETE_WITH_ATTR(prev3_wd);
2313 else if (HeadMatches("ALTER", "PUBLICATION", MatchAny, "ADD|SET", "TABLE") &&
2314 !TailMatches("WHERE", "(*)"))
2315 COMPLETE_WITH(",", "WHERE (");
2316 else if (HeadMatches("ALTER", "PUBLICATION", MatchAny, "ADD|SET", "TABLE"))
2317 COMPLETE_WITH(",");
2318 /* ALTER PUBLICATION <name> DROP */
2319 else if (Matches("ALTER", "PUBLICATION", MatchAny, "DROP"))
2320 COMPLETE_WITH("TABLES IN SCHEMA", "TABLE");
2321 /* ALTER PUBLICATION <name> SET */
2322 else if (Matches("ALTER", "PUBLICATION", MatchAny, "SET"))
2323 COMPLETE_WITH("(", "TABLES IN SCHEMA", "TABLE");
2324 else if (Matches("ALTER", "PUBLICATION", MatchAny, "ADD|DROP|SET", "TABLES", "IN", "SCHEMA"))
2325 COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas
2326 " AND nspname NOT LIKE E'pg\\\\_%%'",
2327 "CURRENT_SCHEMA");
2328 /* ALTER PUBLICATION <name> SET ( */
2329 else if (Matches("ALTER", "PUBLICATION", MatchAny, MatchAnyN, "SET", "("))
2330 COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root");
2331 /* ALTER SUBSCRIPTION <name> */
2332 else if (Matches("ALTER", "SUBSCRIPTION", MatchAny))
2333 COMPLETE_WITH("CONNECTION", "ENABLE", "DISABLE", "OWNER TO",
2334 "RENAME TO", "REFRESH PUBLICATION", "REFRESH SEQUENCES",
2335 "SET", "SKIP (", "ADD PUBLICATION", "DROP PUBLICATION");
2336 /* ALTER SUBSCRIPTION <name> REFRESH */
2337 else if (Matches("ALTER", "SUBSCRIPTION", MatchAny, MatchAnyN, "REFRESH"))
2338 COMPLETE_WITH("PUBLICATION", "SEQUENCES");
2339 /* ALTER SUBSCRIPTION <name> REFRESH PUBLICATION WITH ( */
2340 else if (Matches("ALTER", "SUBSCRIPTION", MatchAny, MatchAnyN, "REFRESH", "PUBLICATION", "WITH", "("))
2341 COMPLETE_WITH("copy_data");
2342 /* ALTER SUBSCRIPTION <name> SET */
2343 else if (Matches("ALTER", "SUBSCRIPTION", MatchAny, "SET"))
2344 COMPLETE_WITH("(", "PUBLICATION");
2345 /* ALTER SUBSCRIPTION <name> SET ( */
2346 else if (Matches("ALTER", "SUBSCRIPTION", MatchAny, MatchAnyN, "SET", "("))
2347 COMPLETE_WITH("binary", "disable_on_error", "failover",
2348 "max_retention_duration", "origin",
2349 "password_required", "retain_dead_tuples",
2350 "run_as_owner", "slot_name", "streaming",
2351 "synchronous_commit", "two_phase");
2352 /* ALTER SUBSCRIPTION <name> SKIP ( */
2353 else if (Matches("ALTER", "SUBSCRIPTION", MatchAny, MatchAnyN, "SKIP", "("))
2354 COMPLETE_WITH("lsn");
2355 /* ALTER SUBSCRIPTION <name> SET PUBLICATION */
2356 else if (Matches("ALTER", "SUBSCRIPTION", MatchAny, MatchAnyN, "SET", "PUBLICATION"))
2357 {
2358 /* complete with nothing here as this refers to remote publications */
2359 }
2360 /* ALTER SUBSCRIPTION <name> ADD|DROP|SET PUBLICATION <name> */
2361 else if (Matches("ALTER", "SUBSCRIPTION", MatchAny, MatchAnyN,
2362 "ADD|DROP|SET", "PUBLICATION", MatchAny))
2363 COMPLETE_WITH("WITH (");
2364 /* ALTER SUBSCRIPTION <name> ADD|DROP|SET PUBLICATION <name> WITH ( */
2365 else if (Matches("ALTER", "SUBSCRIPTION", MatchAny, MatchAnyN,
2366 "ADD|DROP|SET", "PUBLICATION", MatchAny, "WITH", "("))
2367 COMPLETE_WITH("copy_data", "refresh");
2368
2369 /* ALTER SCHEMA <name> */
2370 else if (Matches("ALTER", "SCHEMA", MatchAny))
2371 COMPLETE_WITH("OWNER TO", "RENAME TO");
2372
2373 /* ALTER COLLATION <name> */
2374 else if (Matches("ALTER", "COLLATION", MatchAny))
2375 COMPLETE_WITH("OWNER TO", "REFRESH VERSION", "RENAME TO", "SET SCHEMA");
2376
2377 /* ALTER CONVERSION <name> */
2378 else if (Matches("ALTER", "CONVERSION", MatchAny))
2379 COMPLETE_WITH("OWNER TO", "RENAME TO", "SET SCHEMA");
2380
2381 /* ALTER DATABASE <name> */
2382 else if (Matches("ALTER", "DATABASE", MatchAny))
2383 COMPLETE_WITH("RESET", "SET", "OWNER TO", "REFRESH COLLATION VERSION", "RENAME TO",
2384 "IS_TEMPLATE", "ALLOW_CONNECTIONS",
2385 "CONNECTION LIMIT");
2386
2387 /* ALTER DATABASE <name> RESET */
2388 else if (Matches("ALTER", "DATABASE", MatchAny, "RESET"))
2389 {
2390 set_completion_reference(prev2_wd);
2391 COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_database_vars, "ALL");
2392 }
2393
2394 /* ALTER DATABASE <name> SET TABLESPACE */
2395 else if (Matches("ALTER", "DATABASE", MatchAny, "SET", "TABLESPACE"))
2396 COMPLETE_WITH_QUERY(Query_for_list_of_tablespaces);
2397
2398 /* ALTER EVENT TRIGGER */
2399 else if (Matches("ALTER", "EVENT", "TRIGGER"))
2400 COMPLETE_WITH_QUERY(Query_for_list_of_event_triggers);
2401
2402 /* ALTER EVENT TRIGGER <name> */
2403 else if (Matches("ALTER", "EVENT", "TRIGGER", MatchAny))
2404 COMPLETE_WITH("DISABLE", "ENABLE", "OWNER TO", "RENAME TO");
2405
2406 /* ALTER EVENT TRIGGER <name> ENABLE */
2407 else if (Matches("ALTER", "EVENT", "TRIGGER", MatchAny, "ENABLE"))
2408 COMPLETE_WITH("REPLICA", "ALWAYS");
2409
2410 /* ALTER EXTENSION <name> */
2411 else if (Matches("ALTER", "EXTENSION", MatchAny))
2412 COMPLETE_WITH("ADD", "DROP", "UPDATE", "SET SCHEMA");
2413
2414 /* ALTER EXTENSION <name> ADD|DROP */
2415 else if (Matches("ALTER", "EXTENSION", MatchAny, "ADD|DROP"))
2416 COMPLETE_WITH("ACCESS METHOD", "AGGREGATE", "CAST", "COLLATION",
2417 "CONVERSION", "DOMAIN", "EVENT TRIGGER", "FOREIGN",
2418 "FUNCTION", "MATERIALIZED VIEW", "OPERATOR",
2419 "LANGUAGE", "PROCEDURE", "ROUTINE", "SCHEMA",
2420 "SEQUENCE", "SERVER", "TABLE", "TEXT SEARCH",
2421 "TRANSFORM FOR", "TYPE", "VIEW");
2422
2423 /* ALTER EXTENSION <name> ADD|DROP FOREIGN */
2424 else if (Matches("ALTER", "EXTENSION", MatchAny, "ADD|DROP", "FOREIGN"))
2425 COMPLETE_WITH("DATA WRAPPER", "TABLE");
2426
2427 /* ALTER EXTENSION <name> ADD|DROP OPERATOR */
2428 else if (Matches("ALTER", "EXTENSION", MatchAny, "ADD|DROP", "OPERATOR"))
2429 COMPLETE_WITH("CLASS", "FAMILY");
2430
2431 /* ALTER EXTENSION <name> ADD|DROP TEXT SEARCH */
2432 else if (Matches("ALTER", "EXTENSION", MatchAny, "ADD|DROP", "TEXT", "SEARCH"))
2433 COMPLETE_WITH("CONFIGURATION", "DICTIONARY", "PARSER", "TEMPLATE");
2434
2435 /* ALTER EXTENSION <name> UPDATE */
2436 else if (Matches("ALTER", "EXTENSION", MatchAny, "UPDATE"))
2437 COMPLETE_WITH("TO");
2438
2439 /* ALTER EXTENSION <name> UPDATE TO */
2440 else if (Matches("ALTER", "EXTENSION", MatchAny, "UPDATE", "TO"))
2441 {
2442 set_completion_reference(prev3_wd);
2443 COMPLETE_WITH_QUERY(Query_for_list_of_available_extension_versions);
2444 }
2445
2446 /* ALTER FOREIGN */
2447 else if (Matches("ALTER", "FOREIGN"))
2448 COMPLETE_WITH("DATA WRAPPER", "TABLE");
2449
2450 /* ALTER FOREIGN DATA WRAPPER <name> */
2451 else if (Matches("ALTER", "FOREIGN", "DATA", "WRAPPER", MatchAny))
2452 COMPLETE_WITH("HANDLER", "VALIDATOR", "NO",
2453 "OPTIONS", "OWNER TO", "RENAME TO");
2454 else if (Matches("ALTER", "FOREIGN", "DATA", "WRAPPER", MatchAny, "NO"))
2455 COMPLETE_WITH("HANDLER", "VALIDATOR");
2456
2457 /* ALTER FOREIGN TABLE <name> */
2458 else if (Matches("ALTER", "FOREIGN", "TABLE", MatchAny))
2459 COMPLETE_WITH("ADD", "ALTER", "DISABLE TRIGGER", "DROP", "ENABLE",
2460 "INHERIT", "NO INHERIT", "OPTIONS", "OWNER TO",
2461 "RENAME", "SET", "VALIDATE CONSTRAINT");
2462
2463 /* ALTER INDEX */
2464 else if (Matches("ALTER", "INDEX"))
2465 COMPLETE_WITH_SCHEMA_QUERY_PLUS(Query_for_list_of_indexes,
2466 "ALL IN TABLESPACE");
2467 /* ALTER INDEX <name> */
2468 else if (Matches("ALTER", "INDEX", MatchAny))
2469 COMPLETE_WITH("ALTER COLUMN", "OWNER TO", "RENAME TO", "SET",
2470 "RESET", "ATTACH PARTITION",
2471 "DEPENDS ON EXTENSION", "NO DEPENDS ON EXTENSION");
2472 else if (Matches("ALTER", "INDEX", MatchAny, "ATTACH"))
2473 COMPLETE_WITH("PARTITION");
2474 else if (Matches("ALTER", "INDEX", MatchAny, "ATTACH", "PARTITION"))
2475 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_indexes);
2476 /* ALTER INDEX <name> ALTER */
2477 else if (Matches("ALTER", "INDEX", MatchAny, "ALTER"))
2478 COMPLETE_WITH("COLUMN");
2479 /* ALTER INDEX <name> ALTER COLUMN */
2480 else if (Matches("ALTER", "INDEX", MatchAny, "ALTER", "COLUMN"))
2481 {
2482 set_completion_reference(prev3_wd);
2483 COMPLETE_WITH_SCHEMA_QUERY_VERBATIM(Query_for_list_of_attribute_numbers);
2484 }
2485 /* ALTER INDEX <name> ALTER COLUMN <colnum> */
2486 else if (Matches("ALTER", "INDEX", MatchAny, "ALTER", "COLUMN", MatchAny))
2487 COMPLETE_WITH("SET STATISTICS");
2488 /* ALTER INDEX <name> ALTER COLUMN <colnum> SET */
2489 else if (Matches("ALTER", "INDEX", MatchAny, "ALTER", "COLUMN", MatchAny, "SET"))
2490 COMPLETE_WITH("STATISTICS");
2491 /* ALTER INDEX <name> ALTER COLUMN <colnum> SET STATISTICS */
2492 else if (Matches("ALTER", "INDEX", MatchAny, "ALTER", "COLUMN", MatchAny, "SET", "STATISTICS"))
2493 {
2494 /* Enforce no completion here, as an integer has to be specified */
2495 }
2496 /* ALTER INDEX <name> SET */
2497 else if (Matches("ALTER", "INDEX", MatchAny, "SET"))
2498 COMPLETE_WITH("(", "TABLESPACE");
2499 /* ALTER INDEX <name> RESET */
2500 else if (Matches("ALTER", "INDEX", MatchAny, "RESET"))
2501 COMPLETE_WITH("(");
2502 /* ALTER INDEX <foo> SET|RESET ( */
2503 else if (Matches("ALTER", "INDEX", MatchAny, "RESET", "("))
2504 COMPLETE_WITH("fillfactor",
2505 "deduplicate_items", /* BTREE */
2506 "fastupdate", "gin_pending_list_limit", /* GIN */
2507 "buffering", /* GiST */
2508 "pages_per_range", "autosummarize" /* BRIN */
2509 );
2510 else if (Matches("ALTER", "INDEX", MatchAny, "SET", "("))
2511 COMPLETE_WITH("fillfactor =",
2512 "deduplicate_items =", /* BTREE */
2513 "fastupdate =", "gin_pending_list_limit =", /* GIN */
2514 "buffering =", /* GiST */
2515 "pages_per_range =", "autosummarize =" /* BRIN */
2516 );
2517 else if (Matches("ALTER", "INDEX", MatchAny, "NO", "DEPENDS"))
2518 COMPLETE_WITH("ON EXTENSION");
2519 else if (Matches("ALTER", "INDEX", MatchAny, "DEPENDS"))
2520 COMPLETE_WITH("ON EXTENSION");
2521
2522 /* ALTER LANGUAGE <name> */
2523 else if (Matches("ALTER", "LANGUAGE", MatchAny))
2524 COMPLETE_WITH("OWNER TO", "RENAME TO");
2525
2526 /* ALTER LARGE OBJECT <oid> */
2527 else if (Matches("ALTER", "LARGE", "OBJECT", MatchAny))
2528 COMPLETE_WITH("OWNER TO");
2529
2530 /* ALTER MATERIALIZED VIEW */
2531 else if (Matches("ALTER", "MATERIALIZED", "VIEW"))
2532 COMPLETE_WITH_SCHEMA_QUERY_PLUS(Query_for_list_of_matviews,
2533 "ALL IN TABLESPACE");
2534
2535 /* ALTER USER,ROLE <name> */
2536 else if (Matches("ALTER", "USER|ROLE", MatchAny) &&
2537 !TailMatches("USER", "MAPPING"))
2538 COMPLETE_WITH("BYPASSRLS", "CONNECTION LIMIT", "CREATEDB", "CREATEROLE",
2539 "ENCRYPTED PASSWORD", "INHERIT", "LOGIN", "NOBYPASSRLS",
2540 "NOCREATEDB", "NOCREATEROLE", "NOINHERIT",
2541 "NOLOGIN", "NOREPLICATION", "NOSUPERUSER", "PASSWORD",
2542 "RENAME TO", "REPLICATION", "RESET", "SET", "SUPERUSER",
2543 "VALID UNTIL", "WITH");
2544
2545 /* ALTER USER,ROLE <name> RESET */
2546 else if (Matches("ALTER", "USER|ROLE", MatchAny, "RESET"))
2547 {
2548 set_completion_reference(prev2_wd);
2549 COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_user_vars, "ALL");
2550 }
2551
2552 /* ALTER USER,ROLE <name> WITH */
2553 else if (Matches("ALTER", "USER|ROLE", MatchAny, "WITH"))
2554 /* Similar to the above, but don't complete "WITH" again. */
2555 COMPLETE_WITH("BYPASSRLS", "CONNECTION LIMIT", "CREATEDB", "CREATEROLE",
2556 "ENCRYPTED PASSWORD", "INHERIT", "LOGIN", "NOBYPASSRLS",
2557 "NOCREATEDB", "NOCREATEROLE", "NOINHERIT",
2558 "NOLOGIN", "NOREPLICATION", "NOSUPERUSER", "PASSWORD",
2559 "RENAME TO", "REPLICATION", "RESET", "SET", "SUPERUSER",
2560 "VALID UNTIL");
2561
2562 /* ALTER DEFAULT PRIVILEGES */
2563 else if (Matches("ALTER", "DEFAULT", "PRIVILEGES"))
2564 COMPLETE_WITH("FOR", "GRANT", "IN SCHEMA", "REVOKE");
2565 /* ALTER DEFAULT PRIVILEGES FOR */
2566 else if (Matches("ALTER", "DEFAULT", "PRIVILEGES", "FOR"))
2567 COMPLETE_WITH("ROLE");
2568 /* ALTER DEFAULT PRIVILEGES IN */
2569 else if (Matches("ALTER", "DEFAULT", "PRIVILEGES", "IN"))
2570 COMPLETE_WITH("SCHEMA");
2571 /* ALTER DEFAULT PRIVILEGES FOR ROLE|USER ... */
2572 else if (Matches("ALTER", "DEFAULT", "PRIVILEGES", "FOR", "ROLE|USER",
2573 MatchAny))
2574 COMPLETE_WITH("GRANT", "REVOKE", "IN SCHEMA");
2575 /* ALTER DEFAULT PRIVILEGES IN SCHEMA ... */
2576 else if (Matches("ALTER", "DEFAULT", "PRIVILEGES", "IN", "SCHEMA",
2577 MatchAny))
2578 COMPLETE_WITH("GRANT", "REVOKE", "FOR ROLE");
2579 /* ALTER DEFAULT PRIVILEGES IN SCHEMA ... FOR */
2580 else if (Matches("ALTER", "DEFAULT", "PRIVILEGES", "IN", "SCHEMA",
2581 MatchAny, "FOR"))
2582 COMPLETE_WITH("ROLE");
2583 /* ALTER DEFAULT PRIVILEGES FOR ROLE|USER ... IN SCHEMA ... */
2584 /* ALTER DEFAULT PRIVILEGES IN SCHEMA ... FOR ROLE|USER ... */
2585 else if (Matches("ALTER", "DEFAULT", "PRIVILEGES", "FOR", "ROLE|USER",
2586 MatchAny, "IN", "SCHEMA", MatchAny) ||
2587 Matches("ALTER", "DEFAULT", "PRIVILEGES", "IN", "SCHEMA",
2588 MatchAny, "FOR", "ROLE|USER", MatchAny))
2589 COMPLETE_WITH("GRANT", "REVOKE");
2590 /* ALTER DOMAIN <name> */
2591 else if (Matches("ALTER", "DOMAIN", MatchAny))
2592 COMPLETE_WITH("ADD", "DROP", "OWNER TO", "RENAME", "SET",
2593 "VALIDATE CONSTRAINT");
2594 /* ALTER DOMAIN <sth> ADD */
2595 else if (Matches("ALTER", "DOMAIN", MatchAny, "ADD"))
2596 COMPLETE_WITH("CONSTRAINT", "NOT NULL", "CHECK (");
2597 /* ALTER DOMAIN <sth> ADD CONSTRAINT <sth> */
2598 else if (Matches("ALTER", "DOMAIN", MatchAny, "ADD", "CONSTRAINT", MatchAny))
2599 COMPLETE_WITH("NOT NULL", "CHECK (");
2600 /* ALTER DOMAIN <sth> DROP */
2601 else if (Matches("ALTER", "DOMAIN", MatchAny, "DROP"))
2602 COMPLETE_WITH("CONSTRAINT", "DEFAULT", "NOT NULL");
2603 /* ALTER DOMAIN <sth> DROP|RENAME|VALIDATE CONSTRAINT */
2604 else if (Matches("ALTER", "DOMAIN", MatchAny, "DROP|RENAME|VALIDATE", "CONSTRAINT"))
2605 {
2606 set_completion_reference(prev3_wd);
2607 COMPLETE_WITH_SCHEMA_QUERY(Query_for_constraint_of_type);
2608 }
2609 /* ALTER DOMAIN <sth> RENAME */
2610 else if (Matches("ALTER", "DOMAIN", MatchAny, "RENAME"))
2611 COMPLETE_WITH("CONSTRAINT", "TO");
2612 /* ALTER DOMAIN <sth> RENAME CONSTRAINT <sth> */
2613 else if (Matches("ALTER", "DOMAIN", MatchAny, "RENAME", "CONSTRAINT", MatchAny))
2614 COMPLETE_WITH("TO");
2615
2616 /* ALTER DOMAIN <sth> SET */
2617 else if (Matches("ALTER", "DOMAIN", MatchAny, "SET"))
2618 COMPLETE_WITH("DEFAULT", "NOT NULL", "SCHEMA");
2619 /* ALTER SEQUENCE <name> */
2620 else if (Matches("ALTER", "SEQUENCE", MatchAny))
2621 COMPLETE_WITH("AS", "INCREMENT", "MINVALUE", "MAXVALUE", "RESTART",
2622 "START", "NO", "CACHE", "CYCLE", "SET", "OWNED BY",
2623 "OWNER TO", "RENAME TO");
2624 /* ALTER SEQUENCE <name> AS */
2625 else if (TailMatches("ALTER", "SEQUENCE", MatchAny, "AS"))
2626 COMPLETE_WITH_CS("smallint", "integer", "bigint");
2627 /* ALTER SEQUENCE <name> NO */
2628 else if (Matches("ALTER", "SEQUENCE", MatchAny, "NO"))
2629 COMPLETE_WITH("MINVALUE", "MAXVALUE", "CYCLE");
2630 /* ALTER SEQUENCE <name> SET */
2631 else if (Matches("ALTER", "SEQUENCE", MatchAny, "SET"))
2632 COMPLETE_WITH("SCHEMA", "LOGGED", "UNLOGGED");
2633 /* ALTER SERVER <name> */
2634 else if (Matches("ALTER", "SERVER", MatchAny))
2635 COMPLETE_WITH("VERSION", "OPTIONS", "OWNER TO", "RENAME TO");
2636 /* ALTER SERVER <name> VERSION <version> */
2637 else if (Matches("ALTER", "SERVER", MatchAny, "VERSION", MatchAny))
2638 COMPLETE_WITH("OPTIONS");
2639 /* ALTER SYSTEM SET, RESET, RESET ALL */
2640 else if (Matches("ALTER", "SYSTEM"))
2641 COMPLETE_WITH("SET", "RESET");
2642 else if (Matches("ALTER", "SYSTEM", "SET|RESET"))
2643 COMPLETE_WITH_QUERY_VERBATIM_PLUS(Query_for_list_of_alter_system_set_vars,
2644 "ALL");
2645 else if (Matches("ALTER", "SYSTEM", "SET", MatchAny))
2646 COMPLETE_WITH("TO");
2647 /* ALTER VIEW <name> */
2648 else if (Matches("ALTER", "VIEW", MatchAny))
2649 COMPLETE_WITH("ALTER COLUMN", "OWNER TO", "RENAME", "RESET", "SET");
2650 /* ALTER VIEW xxx RENAME */
2651 else if (Matches("ALTER", "VIEW", MatchAny, "RENAME"))
2652 COMPLETE_WITH_ATTR_PLUS(prev2_wd, "COLUMN", "TO");
2653 else if (Matches("ALTER", "VIEW", MatchAny, "ALTER|RENAME", "COLUMN"))
2654 COMPLETE_WITH_ATTR(prev3_wd);
2655 /* ALTER VIEW xxx ALTER [ COLUMN ] yyy */
2656 else if (Matches("ALTER", "VIEW", MatchAny, "ALTER", MatchAny) ||
2657 Matches("ALTER", "VIEW", MatchAny, "ALTER", "COLUMN", MatchAny))
2658 COMPLETE_WITH("SET DEFAULT", "DROP DEFAULT");
2659 /* ALTER VIEW xxx RENAME yyy */
2660 else if (Matches("ALTER", "VIEW", MatchAny, "RENAME", MatchAnyExcept("TO")))
2661 COMPLETE_WITH("TO");
2662 /* ALTER VIEW xxx RENAME COLUMN yyy */
2663 else if (Matches("ALTER", "VIEW", MatchAny, "RENAME", "COLUMN", MatchAnyExcept("TO")))
2664 COMPLETE_WITH("TO");
2665 /* ALTER VIEW xxx RESET ( */
2666 else if (Matches("ALTER", "VIEW", MatchAny, "RESET"))
2667 COMPLETE_WITH("(");
2668 /* Complete ALTER VIEW xxx SET with "(" or "SCHEMA" */
2669 else if (Matches("ALTER", "VIEW", MatchAny, "SET"))
2670 COMPLETE_WITH("(", "SCHEMA");
2671 /* ALTER VIEW xxx SET|RESET ( yyy [= zzz] ) */
2672 else if (Matches("ALTER", "VIEW", MatchAny, "SET|RESET", "("))
2673 COMPLETE_WITH_LIST(view_optional_parameters);
2674 else if (Matches("ALTER", "VIEW", MatchAny, "SET", "(", MatchAny))
2675 COMPLETE_WITH("=");
2676 else if (Matches("ALTER", "VIEW", MatchAny, "SET", "(", "check_option", "="))
2677 COMPLETE_WITH("local", "cascaded");
2678 else if (Matches("ALTER", "VIEW", MatchAny, "SET", "(", "security_barrier|security_invoker", "="))
2679 COMPLETE_WITH("true", "false");
2680
2681 /* ALTER MATERIALIZED VIEW <name> */
2682 else if (Matches("ALTER", "MATERIALIZED", "VIEW", MatchAny))
2683 COMPLETE_WITH("ALTER COLUMN", "CLUSTER ON", "DEPENDS ON EXTENSION",
2684 "NO DEPENDS ON EXTENSION", "OWNER TO", "RENAME",
2685 "RESET (", "SET");
2686 /* ALTER MATERIALIZED VIEW xxx RENAME */
2687 else if (Matches("ALTER", "MATERIALIZED", "VIEW", MatchAny, "RENAME"))
2688 COMPLETE_WITH_ATTR_PLUS(prev2_wd, "COLUMN", "TO");
2689 else if (Matches("ALTER", "MATERIALIZED", "VIEW", MatchAny, "ALTER|RENAME", "COLUMN"))
2690 COMPLETE_WITH_ATTR(prev3_wd);
2691 /* ALTER MATERIALIZED VIEW xxx RENAME yyy */
2692 else if (Matches("ALTER", "MATERIALIZED", "VIEW", MatchAny, "RENAME", MatchAnyExcept("TO")))
2693 COMPLETE_WITH("TO");
2694 /* ALTER MATERIALIZED VIEW xxx RENAME COLUMN yyy */
2695 else if (Matches("ALTER", "MATERIALIZED", "VIEW", MatchAny, "RENAME", "COLUMN", MatchAnyExcept("TO")))
2696 COMPLETE_WITH("TO");
2697 /* ALTER MATERIALIZED VIEW xxx SET */
2698 else if (Matches("ALTER", "MATERIALIZED", "VIEW", MatchAny, "SET"))
2699 COMPLETE_WITH("(", "ACCESS METHOD", "SCHEMA", "TABLESPACE", "WITHOUT CLUSTER");
2700 /* ALTER MATERIALIZED VIEW xxx SET ACCESS METHOD */
2701 else if (Matches("ALTER", "MATERIALIZED", "VIEW", MatchAny, "SET", "ACCESS", "METHOD"))
2702 COMPLETE_WITH_QUERY(Query_for_list_of_table_access_methods);
2703
2704 /* ALTER POLICY <name> */
2705 else if (Matches("ALTER", "POLICY"))
2706 COMPLETE_WITH_QUERY(Query_for_list_of_policies);
2707 /* ALTER POLICY <name> ON */
2708 else if (Matches("ALTER", "POLICY", MatchAny))
2709 COMPLETE_WITH("ON");
2710 /* ALTER POLICY <name> ON <table> */
2711 else if (Matches("ALTER", "POLICY", MatchAny, "ON"))
2712 {
2713 set_completion_reference(prev2_wd);
2714 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables_for_policy);
2715 }
2716 /* ALTER POLICY <name> ON <table> - show options */
2717 else if (Matches("ALTER", "POLICY", MatchAny, "ON", MatchAny))
2718 COMPLETE_WITH("RENAME TO", "TO", "USING (", "WITH CHECK (");
2719 /* ALTER POLICY <name> ON <table> TO <role> */
2720 else if (Matches("ALTER", "POLICY", MatchAny, "ON", MatchAny, "TO"))
2721 COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_roles,
2722 Keywords_for_list_of_grant_roles);
2723 /* ALTER POLICY <name> ON <table> USING ( */
2724 else if (Matches("ALTER", "POLICY", MatchAny, "ON", MatchAny, "USING"))
2725 COMPLETE_WITH("(");
2726 /* ALTER POLICY <name> ON <table> WITH CHECK ( */
2727 else if (Matches("ALTER", "POLICY", MatchAny, "ON", MatchAny, "WITH", "CHECK"))
2728 COMPLETE_WITH("(");
2729
2730 /* ALTER RULE <name>, add ON */
2731 else if (Matches("ALTER", "RULE", MatchAny))
2732 COMPLETE_WITH("ON");
2733
2734 /* If we have ALTER RULE <name> ON, then add the correct tablename */
2735 else if (Matches("ALTER", "RULE", MatchAny, "ON"))
2736 {
2737 set_completion_reference(prev2_wd);
2738 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables_for_rule);
2739 }
2740
2741 /* ALTER RULE <name> ON <name> */
2742 else if (Matches("ALTER", "RULE", MatchAny, "ON", MatchAny))
2743 COMPLETE_WITH("RENAME TO");
2744
2745 /* ALTER STATISTICS <name> */
2746 else if (Matches("ALTER", "STATISTICS", MatchAny))
2747 COMPLETE_WITH("OWNER TO", "RENAME TO", "SET SCHEMA", "SET STATISTICS");
2748 /* ALTER STATISTICS <name> SET */
2749 else if (Matches("ALTER", "STATISTICS", MatchAny, "SET"))
2750 COMPLETE_WITH("SCHEMA", "STATISTICS");
2751
2752 /* ALTER TRIGGER <name>, add ON */
2753 else if (Matches("ALTER", "TRIGGER", MatchAny))
2754 COMPLETE_WITH("ON");
2755
2756 else if (Matches("ALTER", "TRIGGER", MatchAny, "ON"))
2757 {
2758 set_completion_reference(prev2_wd);
2759 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables_for_trigger);
2760 }
2761
2762 /* ALTER TRIGGER <name> ON <name> */
2763 else if (Matches("ALTER", "TRIGGER", MatchAny, "ON", MatchAny))
2764 COMPLETE_WITH("RENAME TO", "DEPENDS ON EXTENSION",
2765 "NO DEPENDS ON EXTENSION");
2766
2767 /*
2768 * If we detect ALTER TABLE <name>, suggest sub commands
2769 */
2770 else if (Matches("ALTER", "TABLE", MatchAny))
2771 COMPLETE_WITH("ADD", "ALTER", "CLUSTER ON", "DISABLE", "DROP",
2772 "ENABLE", "INHERIT", "NO", "RENAME", "RESET",
2773 "OWNER TO", "SET", "VALIDATE CONSTRAINT",
2774 "REPLICA IDENTITY", "ATTACH PARTITION",
2775 "DETACH PARTITION", "FORCE ROW LEVEL SECURITY",
2776 "OF", "NOT OF");
2777 /* ALTER TABLE xxx ADD */
2778 else if (Matches("ALTER", "TABLE", MatchAny, "ADD"))
2779 {
2780 /*
2781 * make sure to keep this list and the MatchAnyExcept() below in sync
2782 */
2783 COMPLETE_WITH("COLUMN", "CONSTRAINT", "CHECK (", "NOT NULL", "UNIQUE",
2784 "PRIMARY KEY", "EXCLUDE", "FOREIGN KEY");
2785 }
2786 /* ALTER TABLE xxx ADD [COLUMN] yyy */
2787 else if (Matches("ALTER", "TABLE", MatchAny, "ADD", "COLUMN", MatchAny) ||
2788 Matches("ALTER", "TABLE", MatchAny, "ADD", MatchAnyExcept("COLUMN|CONSTRAINT|CHECK|UNIQUE|PRIMARY|NOT|EXCLUDE|FOREIGN")))
2789 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_datatypes);
2790 /* ALTER TABLE xxx ADD CONSTRAINT yyy */
2791 else if (Matches("ALTER", "TABLE", MatchAny, "ADD", "CONSTRAINT", MatchAny))
2792 COMPLETE_WITH("CHECK (", "NOT NULL", "UNIQUE", "PRIMARY KEY", "EXCLUDE", "FOREIGN KEY");
2793 /* ALTER TABLE xxx ADD NOT NULL */
2794 else if (Matches("ALTER", "TABLE", MatchAny, "ADD", "NOT", "NULL"))
2795 COMPLETE_WITH_ATTR(prev4_wd);
2796 else if (Matches("ALTER", "TABLE", MatchAny, "ADD", "CONSTRAINT", MatchAny, "NOT", "NULL"))
2797 COMPLETE_WITH_ATTR(prev6_wd);
2798 /* ALTER TABLE xxx ADD [CONSTRAINT yyy] (PRIMARY KEY|UNIQUE) */
2799 else if (Matches("ALTER", "TABLE", MatchAny, "ADD", "PRIMARY", "KEY") ||
2800 Matches("ALTER", "TABLE", MatchAny, "ADD", "UNIQUE") ||
2801 Matches("ALTER", "TABLE", MatchAny, "ADD", "CONSTRAINT", MatchAny, "PRIMARY", "KEY") ||
2802 Matches("ALTER", "TABLE", MatchAny, "ADD", "CONSTRAINT", MatchAny, "UNIQUE"))
2803 COMPLETE_WITH("(", "USING INDEX");
2804 /* ALTER TABLE xxx ADD PRIMARY KEY USING INDEX */
2805 else if (Matches("ALTER", "TABLE", MatchAny, "ADD", "PRIMARY", "KEY", "USING", "INDEX"))
2806 {
2807 set_completion_reference(prev6_wd);
2808 COMPLETE_WITH_SCHEMA_QUERY(Query_for_unique_index_of_table);
2809 }
2810 /* ALTER TABLE xxx ADD UNIQUE USING INDEX */
2811 else if (Matches("ALTER", "TABLE", MatchAny, "ADD", "UNIQUE", "USING", "INDEX"))
2812 {
2813 set_completion_reference(prev5_wd);
2814 COMPLETE_WITH_SCHEMA_QUERY(Query_for_unique_index_of_table);
2815 }
2816 /* ALTER TABLE xxx ADD CONSTRAINT yyy PRIMARY KEY USING INDEX */
2817 else if (Matches("ALTER", "TABLE", MatchAny, "ADD", "CONSTRAINT", MatchAny,
2818 "PRIMARY", "KEY", "USING", "INDEX"))
2819 {
2820 set_completion_reference(prev8_wd);
2821 COMPLETE_WITH_SCHEMA_QUERY(Query_for_unique_index_of_table);
2822 }
2823 /* ALTER TABLE xxx ADD CONSTRAINT yyy UNIQUE USING INDEX */
2824 else if (Matches("ALTER", "TABLE", MatchAny, "ADD", "CONSTRAINT", MatchAny,
2825 "UNIQUE", "USING", "INDEX"))
2826 {
2827 set_completion_reference(prev7_wd);
2828 COMPLETE_WITH_SCHEMA_QUERY(Query_for_unique_index_of_table);
2829 }
2830 /* ALTER TABLE xxx ENABLE */
2831 else if (Matches("ALTER", "TABLE", MatchAny, "ENABLE"))
2832 COMPLETE_WITH("ALWAYS", "REPLICA", "ROW LEVEL SECURITY", "RULE",
2833 "TRIGGER");
2834 else if (Matches("ALTER", "TABLE", MatchAny, "ENABLE", "REPLICA|ALWAYS"))
2835 COMPLETE_WITH("RULE", "TRIGGER");
2836 else if (Matches("ALTER", "TABLE", MatchAny, "ENABLE", "RULE"))
2837 {
2838 set_completion_reference(prev3_wd);
2839 COMPLETE_WITH_SCHEMA_QUERY(Query_for_rule_of_table);
2840 }
2841 else if (Matches("ALTER", "TABLE", MatchAny, "ENABLE", MatchAny, "RULE"))
2842 {
2843 set_completion_reference(prev4_wd);
2844 COMPLETE_WITH_SCHEMA_QUERY(Query_for_rule_of_table);
2845 }
2846 else if (Matches("ALTER", "TABLE", MatchAny, "ENABLE", "TRIGGER"))
2847 {
2848 set_completion_reference(prev3_wd);
2849 COMPLETE_WITH_SCHEMA_QUERY(Query_for_trigger_of_table);
2850 }
2851 else if (Matches("ALTER", "TABLE", MatchAny, "ENABLE", MatchAny, "TRIGGER"))
2852 {
2853 set_completion_reference(prev4_wd);
2854 COMPLETE_WITH_SCHEMA_QUERY(Query_for_trigger_of_table);
2855 }
2856 /* ALTER TABLE xxx INHERIT */
2857 else if (Matches("ALTER", "TABLE", MatchAny, "INHERIT"))
2858 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables);
2859 /* ALTER TABLE xxx NO */
2860 else if (Matches("ALTER", "TABLE", MatchAny, "NO"))
2861 COMPLETE_WITH("FORCE ROW LEVEL SECURITY", "INHERIT");
2862 /* ALTER TABLE xxx NO INHERIT */
2863 else if (Matches("ALTER", "TABLE", MatchAny, "NO", "INHERIT"))
2864 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables);
2865 /* ALTER TABLE xxx DISABLE */
2866 else if (Matches("ALTER", "TABLE", MatchAny, "DISABLE"))
2867 COMPLETE_WITH("ROW LEVEL SECURITY", "RULE", "TRIGGER");
2868 else if (Matches("ALTER", "TABLE", MatchAny, "DISABLE", "RULE"))
2869 {
2870 set_completion_reference(prev3_wd);
2871 COMPLETE_WITH_SCHEMA_QUERY(Query_for_rule_of_table);
2872 }
2873 else if (Matches("ALTER", "TABLE", MatchAny, "DISABLE", "TRIGGER"))
2874 {
2875 set_completion_reference(prev3_wd);
2876 COMPLETE_WITH_SCHEMA_QUERY(Query_for_trigger_of_table);
2877 }
2878
2879 /* ALTER TABLE xxx ALTER */
2880 else if (Matches("ALTER", "TABLE", MatchAny, "ALTER"))
2881 COMPLETE_WITH_ATTR_PLUS(prev2_wd, "COLUMN", "CONSTRAINT");
2882
2883 /* ALTER TABLE xxx RENAME */
2884 else if (Matches("ALTER", "TABLE", MatchAny, "RENAME"))
2885 COMPLETE_WITH_ATTR_PLUS(prev2_wd, "COLUMN", "CONSTRAINT", "TO");
2886 else if (Matches("ALTER", "TABLE", MatchAny, "ALTER|RENAME", "COLUMN"))
2887 COMPLETE_WITH_ATTR(prev3_wd);
2888
2889 /* ALTER TABLE xxx RENAME yyy */
2890 else if (Matches("ALTER", "TABLE", MatchAny, "RENAME", MatchAnyExcept("CONSTRAINT|TO")))
2891 COMPLETE_WITH("TO");
2892
2893 /* ALTER TABLE xxx RENAME COLUMN/CONSTRAINT yyy */
2894 else if (Matches("ALTER", "TABLE", MatchAny, "RENAME", "COLUMN|CONSTRAINT", MatchAnyExcept("TO")))
2895 COMPLETE_WITH("TO");
2896
2897 /* If we have ALTER TABLE <sth> DROP, provide COLUMN or CONSTRAINT */
2898 else if (Matches("ALTER", "TABLE", MatchAny, "DROP"))
2899 COMPLETE_WITH("COLUMN", "CONSTRAINT");
2900 /* If we have ALTER TABLE <sth> DROP COLUMN, provide list of columns */
2901 else if (Matches("ALTER", "TABLE", MatchAny, "DROP", "COLUMN"))
2902 COMPLETE_WITH_ATTR(prev3_wd);
2903 /* ALTER TABLE <sth> ALTER|DROP|RENAME CONSTRAINT <constraint> */
2904 else if (Matches("ALTER", "TABLE", MatchAny, "ALTER|DROP|RENAME", "CONSTRAINT"))
2905 {
2906 set_completion_reference(prev3_wd);
2907 COMPLETE_WITH_SCHEMA_QUERY(Query_for_constraint_of_table);
2908 }
2909 /* ALTER TABLE <sth> VALIDATE CONSTRAINT <non-validated constraint> */
2910 else if (Matches("ALTER", "TABLE", MatchAny, "VALIDATE", "CONSTRAINT"))
2911 {
2912 set_completion_reference(prev3_wd);
2913 COMPLETE_WITH_SCHEMA_QUERY(Query_for_constraint_of_table_not_validated);
2914 }
2915 /* ALTER TABLE ALTER [COLUMN] <foo> */
2916 else if (Matches("ALTER", "TABLE", MatchAny, "ALTER", "COLUMN", MatchAny) ||
2917 Matches("ALTER", "TABLE", MatchAny, "ALTER", MatchAny))
2918 COMPLETE_WITH("TYPE", "SET", "RESET", "RESTART", "ADD", "DROP");
2919 /* ALTER TABLE ALTER [COLUMN] <foo> ADD */
2920 else if (Matches("ALTER", "TABLE", MatchAny, "ALTER", "COLUMN", MatchAny, "ADD") ||
2921 Matches("ALTER", "TABLE", MatchAny, "ALTER", MatchAny, "ADD"))
2922 COMPLETE_WITH("GENERATED");
2923 /* ALTER TABLE ALTER [COLUMN] <foo> ADD GENERATED */
2924 else if (Matches("ALTER", "TABLE", MatchAny, "ALTER", "COLUMN", MatchAny, "ADD", "GENERATED") ||
2925 Matches("ALTER", "TABLE", MatchAny, "ALTER", MatchAny, "ADD", "GENERATED"))
2926 COMPLETE_WITH("ALWAYS", "BY DEFAULT");
2927 /* ALTER TABLE ALTER [COLUMN] <foo> ADD GENERATED */
2928 else if (Matches("ALTER", "TABLE", MatchAny, "ALTER", "COLUMN", MatchAny, "ADD", "GENERATED", "ALWAYS") ||
2929 Matches("ALTER", "TABLE", MatchAny, "ALTER", MatchAny, "ADD", "GENERATED", "ALWAYS") ||
2930 Matches("ALTER", "TABLE", MatchAny, "ALTER", "COLUMN", MatchAny, "ADD", "GENERATED", "BY", "DEFAULT") ||
2931 Matches("ALTER", "TABLE", MatchAny, "ALTER", MatchAny, "ADD", "GENERATED", "BY", "DEFAULT"))
2932 COMPLETE_WITH("AS IDENTITY");
2933 /* ALTER TABLE ALTER [COLUMN] <foo> SET */
2934 else if (Matches("ALTER", "TABLE", MatchAny, "ALTER", "COLUMN", MatchAny, "SET") ||
2935 Matches("ALTER", "TABLE", MatchAny, "ALTER", MatchAny, "SET"))
2936 COMPLETE_WITH("(", "COMPRESSION", "DATA TYPE", "DEFAULT", "EXPRESSION", "GENERATED", "NOT NULL",
2937 "STATISTICS", "STORAGE",
2938 /* a subset of ALTER SEQUENCE options */
2939 "INCREMENT", "MINVALUE", "MAXVALUE", "START", "NO", "CACHE", "CYCLE");
2940 /* ALTER TABLE ALTER [COLUMN] <foo> SET ( */
2941 else if (Matches("ALTER", "TABLE", MatchAny, "ALTER", "COLUMN", MatchAny, "SET", "(") ||
2942 Matches("ALTER", "TABLE", MatchAny, "ALTER", MatchAny, "SET", "("))
2943 COMPLETE_WITH("n_distinct", "n_distinct_inherited");
2944 /* ALTER TABLE ALTER [COLUMN] <foo> SET COMPRESSION */
2945 else if (Matches("ALTER", "TABLE", MatchAny, "ALTER", "COLUMN", MatchAny, "SET", "COMPRESSION") ||
2946 Matches("ALTER", "TABLE", MatchAny, "ALTER", MatchAny, "SET", "COMPRESSION"))
2947 COMPLETE_WITH("DEFAULT", "PGLZ", "LZ4");
2948 /* ALTER TABLE ALTER [COLUMN] <foo> SET EXPRESSION */
2949 else if (Matches("ALTER", "TABLE", MatchAny, "ALTER", "COLUMN", MatchAny, "SET", "EXPRESSION") ||
2950 Matches("ALTER", "TABLE", MatchAny, "ALTER", MatchAny, "SET", "EXPRESSION"))
2951 COMPLETE_WITH("AS");
2952 /* ALTER TABLE ALTER [COLUMN] <foo> SET EXPRESSION AS */
2953 else if (Matches("ALTER", "TABLE", MatchAny, "ALTER", "COLUMN", MatchAny, "SET", "EXPRESSION", "AS") ||
2954 Matches("ALTER", "TABLE", MatchAny, "ALTER", MatchAny, "SET", "EXPRESSION", "AS"))
2955 COMPLETE_WITH("(");
2956 /* ALTER TABLE ALTER [COLUMN] <foo> SET GENERATED */
2957 else if (Matches("ALTER", "TABLE", MatchAny, "ALTER", "COLUMN", MatchAny, "SET", "GENERATED") ||
2958 Matches("ALTER", "TABLE", MatchAny, "ALTER", MatchAny, "SET", "GENERATED"))
2959 COMPLETE_WITH("ALWAYS", "BY DEFAULT");
2960 /* ALTER TABLE ALTER [COLUMN] <foo> SET NO */
2961 else if (Matches("ALTER", "TABLE", MatchAny, "ALTER", "COLUMN", MatchAny, "SET", "NO") ||
2962 Matches("ALTER", "TABLE", MatchAny, "ALTER", MatchAny, "SET", "NO"))
2963 COMPLETE_WITH("MINVALUE", "MAXVALUE", "CYCLE");
2964 /* ALTER TABLE ALTER [COLUMN] <foo> SET STORAGE */
2965 else if (Matches("ALTER", "TABLE", MatchAny, "ALTER", "COLUMN", MatchAny, "SET", "STORAGE") ||
2966 Matches("ALTER", "TABLE", MatchAny, "ALTER", MatchAny, "SET", "STORAGE"))
2967 COMPLETE_WITH("DEFAULT", "PLAIN", "EXTERNAL", "EXTENDED", "MAIN");
2968 /* ALTER TABLE ALTER [COLUMN] <foo> SET STATISTICS */
2969 else if (Matches("ALTER", "TABLE", MatchAny, "ALTER", "COLUMN", MatchAny, "SET", "STATISTICS") ||
2970 Matches("ALTER", "TABLE", MatchAny, "ALTER", MatchAny, "SET", "STATISTICS"))
2971 {
2972 /* Enforce no completion here, as an integer has to be specified */
2973 }
2974 /* ALTER TABLE ALTER [COLUMN] <foo> DROP */
2975 else if (Matches("ALTER", "TABLE", MatchAny, "ALTER", "COLUMN", MatchAny, "DROP") ||
2976 Matches("ALTER", "TABLE", MatchAny, "ALTER", MatchAny, "DROP"))
2977 COMPLETE_WITH("DEFAULT", "EXPRESSION", "IDENTITY", "NOT NULL");
2978 else if (Matches("ALTER", "TABLE", MatchAny, "CLUSTER"))
2979 COMPLETE_WITH("ON");
2980 else if (Matches("ALTER", "TABLE", MatchAny, "CLUSTER", "ON"))
2981 {
2982 set_completion_reference(prev3_wd);
2983 COMPLETE_WITH_SCHEMA_QUERY(Query_for_index_of_table);
2984 }
2985 /* If we have ALTER TABLE <sth> SET, provide list of attributes and '(' */
2986 else if (Matches("ALTER", "TABLE", MatchAny, "SET"))
2987 COMPLETE_WITH("(", "ACCESS METHOD", "LOGGED", "SCHEMA",
2988 "TABLESPACE", "UNLOGGED", "WITH", "WITHOUT");
2989
2990 /*
2991 * If we have ALTER TABLE <sth> SET ACCESS METHOD provide a list of table
2992 * AMs.
2993 */
2994 else if (Matches("ALTER", "TABLE", MatchAny, "SET", "ACCESS", "METHOD"))
2995 COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_table_access_methods,
2996 "DEFAULT");
2997
2998 /*
2999 * If we have ALTER TABLE <sth> SET TABLESPACE provide a list of
3000 * tablespaces
3001 */
3002 else if (Matches("ALTER", "TABLE", MatchAny, "SET", "TABLESPACE"))
3003 COMPLETE_WITH_QUERY(Query_for_list_of_tablespaces);
3004 /* If we have ALTER TABLE <sth> SET WITHOUT provide CLUSTER or OIDS */
3005 else if (Matches("ALTER", "TABLE", MatchAny, "SET", "WITHOUT"))
3006 COMPLETE_WITH("CLUSTER", "OIDS");
3007 /* ALTER TABLE <foo> RESET */
3008 else if (Matches("ALTER", "TABLE", MatchAny, "RESET"))
3009 COMPLETE_WITH("(");
3010 /* ALTER TABLE <foo> SET|RESET ( */
3011 else if (Matches("ALTER", "TABLE", MatchAny, "SET|RESET", "("))
3012 COMPLETE_WITH_LIST(table_storage_parameters);
3013 else if (Matches("ALTER", "TABLE", MatchAny, "REPLICA", "IDENTITY", "USING", "INDEX"))
3014 {
3015 set_completion_reference(prev5_wd);
3016 COMPLETE_WITH_SCHEMA_QUERY(Query_for_index_of_table);
3017 }
3018 else if (Matches("ALTER", "TABLE", MatchAny, "REPLICA", "IDENTITY", "USING"))
3019 COMPLETE_WITH("INDEX");
3020 else if (Matches("ALTER", "TABLE", MatchAny, "REPLICA", "IDENTITY"))
3021 COMPLETE_WITH("FULL", "NOTHING", "DEFAULT", "USING");
3022 else if (Matches("ALTER", "TABLE", MatchAny, "REPLICA"))
3023 COMPLETE_WITH("IDENTITY");
3024
3025 /*
3026 * If we have ALTER TABLE <foo> ATTACH PARTITION, provide a list of
3027 * tables.
3028 */
3029 else if (Matches("ALTER", "TABLE", MatchAny, "ATTACH", "PARTITION"))
3030 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables);
3031 /* Limited completion support for partition bound specification */
3032 else if (TailMatches("ATTACH", "PARTITION", MatchAny))
3033 COMPLETE_WITH("FOR VALUES", "DEFAULT");
3034 else if (TailMatches("FOR", "VALUES"))
3035 COMPLETE_WITH("FROM (", "IN (", "WITH (");
3036
3037 /*
3038 * If we have ALTER TABLE <foo> DETACH PARTITION, provide a list of
3039 * partitions of <foo>.
3040 */
3041 else if (Matches("ALTER", "TABLE", MatchAny, "DETACH", "PARTITION"))
3042 {
3043 set_completion_reference(prev3_wd);
3044 COMPLETE_WITH_SCHEMA_QUERY(Query_for_partition_of_table);
3045 }
3046 else if (Matches("ALTER", "TABLE", MatchAny, "DETACH", "PARTITION", MatchAny))
3047 COMPLETE_WITH("CONCURRENTLY", "FINALIZE");
3048
3049 /* ALTER TABLE <name> OF */
3050 else if (Matches("ALTER", "TABLE", MatchAny, "OF"))
3051 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_composite_datatypes);
3052
3053 /* ALTER TABLESPACE <foo> with RENAME TO, OWNER TO, SET, RESET */
3054 else if (Matches("ALTER", "TABLESPACE", MatchAny))
3055 COMPLETE_WITH("RENAME TO", "OWNER TO", "SET", "RESET");
3056 /* ALTER TABLESPACE <foo> SET|RESET */
3057 else if (Matches("ALTER", "TABLESPACE", MatchAny, "SET|RESET"))
3058 COMPLETE_WITH("(");
3059 /* ALTER TABLESPACE <foo> SET|RESET ( */
3060 else if (Matches("ALTER", "TABLESPACE", MatchAny, "SET|RESET", "("))
3061 COMPLETE_WITH("seq_page_cost", "random_page_cost",
3062 "effective_io_concurrency", "maintenance_io_concurrency");
3063
3064 /* ALTER TEXT SEARCH */
3065 else if (Matches("ALTER", "TEXT", "SEARCH"))
3066 COMPLETE_WITH("CONFIGURATION", "DICTIONARY", "PARSER", "TEMPLATE");
3067 else if (Matches("ALTER", "TEXT", "SEARCH", "TEMPLATE|PARSER", MatchAny))
3068 COMPLETE_WITH("RENAME TO", "SET SCHEMA");
3069 else if (Matches("ALTER", "TEXT", "SEARCH", "DICTIONARY", MatchAny))
3070 COMPLETE_WITH("(", "OWNER TO", "RENAME TO", "SET SCHEMA");
3071 else if (Matches("ALTER", "TEXT", "SEARCH", "CONFIGURATION", MatchAny))
3072 COMPLETE_WITH("ADD MAPPING FOR", "ALTER MAPPING",
3073 "DROP MAPPING FOR",
3074 "OWNER TO", "RENAME TO", "SET SCHEMA");
3075
3076 /* complete ALTER TYPE <foo> with actions */
3077 else if (Matches("ALTER", "TYPE", MatchAny))
3078 COMPLETE_WITH("ADD ATTRIBUTE", "ADD VALUE", "ALTER ATTRIBUTE",
3079 "DROP ATTRIBUTE",
3080 "OWNER TO", "RENAME", "SET SCHEMA", "SET (");
3081 /* complete ALTER TYPE <foo> ADD with actions */
3082 else if (Matches("ALTER", "TYPE", MatchAny, "ADD"))
3083 COMPLETE_WITH("ATTRIBUTE", "VALUE");
3084 /* ALTER TYPE <foo> RENAME */
3085 else if (Matches("ALTER", "TYPE", MatchAny, "RENAME"))
3086 COMPLETE_WITH("ATTRIBUTE", "TO", "VALUE");
3087 /* ALTER TYPE xxx RENAME (ATTRIBUTE|VALUE) yyy */
3088 else if (Matches("ALTER", "TYPE", MatchAny, "RENAME", "ATTRIBUTE|VALUE", MatchAny))
3089 COMPLETE_WITH("TO");
3090 /* ALTER TYPE xxx RENAME ATTRIBUTE yyy TO zzz */
3091 else if (Matches("ALTER", "TYPE", MatchAny, "RENAME", "ATTRIBUTE", MatchAny, "TO", MatchAny))
3092 COMPLETE_WITH("CASCADE", "RESTRICT");
3093
3094 /*
3095 * If we have ALTER TYPE <sth> ALTER/DROP/RENAME ATTRIBUTE, provide list
3096 * of attributes
3097 */
3098 else if (Matches("ALTER", "TYPE", MatchAny, "ALTER|DROP|RENAME", "ATTRIBUTE"))
3099 COMPLETE_WITH_ATTR(prev3_wd);
3100 /* complete ALTER TYPE ADD ATTRIBUTE <foo> with list of types */
3101 else if (Matches("ALTER", "TYPE", MatchAny, "ADD", "ATTRIBUTE", MatchAny))
3102 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_datatypes);
3103 /* complete ALTER TYPE ADD ATTRIBUTE <foo> <footype> with CASCADE/RESTRICT */
3104 else if (Matches("ALTER", "TYPE", MatchAny, "ADD", "ATTRIBUTE", MatchAny, MatchAny))
3105 COMPLETE_WITH("CASCADE", "RESTRICT");
3106 /* complete ALTER TYPE DROP ATTRIBUTE <foo> with CASCADE/RESTRICT */
3107 else if (Matches("ALTER", "TYPE", MatchAny, "DROP", "ATTRIBUTE", MatchAny))
3108 COMPLETE_WITH("CASCADE", "RESTRICT");
3109 /* ALTER TYPE ALTER ATTRIBUTE <foo> */
3110 else if (Matches("ALTER", "TYPE", MatchAny, "ALTER", "ATTRIBUTE", MatchAny))
3111 COMPLETE_WITH("TYPE");
3112 /* ALTER TYPE ALTER ATTRIBUTE <foo> TYPE <footype> */
3113 else if (Matches("ALTER", "TYPE", MatchAny, "ALTER", "ATTRIBUTE", MatchAny, "TYPE", MatchAny))
3114 COMPLETE_WITH("CASCADE", "RESTRICT");
3115 /* complete ALTER TYPE <sth> RENAME VALUE with list of enum values */
3116 else if (Matches("ALTER", "TYPE", MatchAny, "RENAME", "VALUE"))
3117 COMPLETE_WITH_ENUM_VALUE(prev3_wd);
3118 /* ALTER TYPE <foo> SET */
3119 else if (Matches("ALTER", "TYPE", MatchAny, "SET"))
3120 COMPLETE_WITH("(", "SCHEMA");
3121 /* complete ALTER TYPE <foo> SET ( with settable properties */
3122 else if (Matches("ALTER", "TYPE", MatchAny, "SET", "("))
3123 COMPLETE_WITH("ANALYZE", "RECEIVE", "SEND", "STORAGE", "SUBSCRIPT",
3124 "TYPMOD_IN", "TYPMOD_OUT");
3125
3126 /* complete ALTER GROUP <foo> */
3127 else if (Matches("ALTER", "GROUP", MatchAny))
3128 COMPLETE_WITH("ADD USER", "DROP USER", "RENAME TO");
3129 /* complete ALTER GROUP <foo> ADD|DROP with USER */
3130 else if (Matches("ALTER", "GROUP", MatchAny, "ADD|DROP"))
3131 COMPLETE_WITH("USER");
3132 /* complete ALTER GROUP <foo> ADD|DROP USER with a user name */
3133 else if (Matches("ALTER", "GROUP", MatchAny, "ADD|DROP", "USER"))
3134 COMPLETE_WITH_QUERY(Query_for_list_of_roles);
3135
3136/*
3137 * ANALYZE [ ( option [, ...] ) ] [ [ ONLY ] table_and_columns [, ...] ]
3138 * ANALYZE [ VERBOSE ] [ [ ONLY ] table_and_columns [, ...] ]
3139 */
3140 else if (Matches("ANALYZE"))
3141 COMPLETE_WITH_SCHEMA_QUERY_PLUS(Query_for_list_of_analyzables,
3142 "(", "VERBOSE", "ONLY");
3143 else if (Matches("ANALYZE", "VERBOSE"))
3144 COMPLETE_WITH_SCHEMA_QUERY_PLUS(Query_for_list_of_analyzables,
3145 "ONLY");
3146 else if (HeadMatches("ANALYZE", "(*") &&
3147 !HeadMatches("ANALYZE", "(*)"))
3148 {
3149 /*
3150 * This fires if we're in an unfinished parenthesized option list.
3151 * get_previous_words treats a completed parenthesized option list as
3152 * one word, so the above test is correct.
3153 */
3154 if (ends_with(prev_wd, '(') || ends_with(prev_wd, ','))
3155 COMPLETE_WITH("VERBOSE", "SKIP_LOCKED", "BUFFER_USAGE_LIMIT");
3156 else if (TailMatches("VERBOSE|SKIP_LOCKED"))
3157 COMPLETE_WITH("ON", "OFF");
3158 }
3159 else if (Matches("ANALYZE", MatchAnyN, "("))
3160 /* "ANALYZE (" should be caught above, so assume we want columns */
3161 COMPLETE_WITH_ATTR(prev2_wd);
3162 else if (HeadMatches("ANALYZE"))
3163 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_analyzables);
3164
3165/* BEGIN */
3166 else if (Matches("BEGIN"))
3167 COMPLETE_WITH("WORK", "TRANSACTION", "ISOLATION LEVEL", "READ", "DEFERRABLE", "NOT DEFERRABLE");
3168/* END, ABORT */
3169 else if (Matches("END|ABORT"))
3170 COMPLETE_WITH("AND", "WORK", "TRANSACTION");
3171/* COMMIT */
3172 else if (Matches("COMMIT"))
3173 COMPLETE_WITH("AND", "WORK", "TRANSACTION", "PREPARED");
3174/* RELEASE SAVEPOINT */
3175 else if (Matches("RELEASE"))
3176 COMPLETE_WITH("SAVEPOINT");
3177/* ROLLBACK */
3178 else if (Matches("ROLLBACK"))
3179 COMPLETE_WITH("AND", "WORK", "TRANSACTION", "TO SAVEPOINT", "PREPARED");
3180 else if (Matches("ABORT|END|COMMIT|ROLLBACK", "AND"))
3181 COMPLETE_WITH("CHAIN");
3182/* CALL */
3183 else if (Matches("CALL"))
3184 COMPLETE_WITH_VERSIONED_SCHEMA_QUERY(Query_for_list_of_procedures);
3185 else if (Matches("CALL", MatchAny))
3186 COMPLETE_WITH("(");
3187/* CHECKPOINT */
3188 else if (Matches("CHECKPOINT"))
3189 COMPLETE_WITH("(");
3190 else if (HeadMatches("CHECKPOINT", "(*") &&
3191 !HeadMatches("CHECKPOINT", "(*)"))
3192 {
3193 /*
3194 * This fires if we're in an unfinished parenthesized option list.
3195 * get_previous_words treats a completed parenthesized option list as
3196 * one word, so the above test is correct.
3197 */
3198 if (ends_with(prev_wd, '(') || ends_with(prev_wd, ','))
3199 COMPLETE_WITH("MODE", "FLUSH_UNLOGGED");
3200 else if (TailMatches("MODE"))
3201 COMPLETE_WITH("FAST", "SPREAD");
3202 }
3203/* CLOSE */
3204 else if (Matches("CLOSE"))
3205 COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_cursors,
3206 "ALL");
3207/* CLUSTER */
3208 else if (Matches("CLUSTER"))
3209 COMPLETE_WITH_SCHEMA_QUERY_PLUS(Query_for_list_of_clusterables,
3210 "VERBOSE");
3211 else if (Matches("CLUSTER", "VERBOSE") ||
3212 Matches("CLUSTER", "(*)"))
3213 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_clusterables);
3214 /* If we have CLUSTER <sth>, then add "USING" */
3215 else if (Matches("CLUSTER", MatchAnyExcept("VERBOSE|ON|(|(*)")))
3216 COMPLETE_WITH("USING");
3217 /* If we have CLUSTER VERBOSE <sth>, then add "USING" */
3218 else if (Matches("CLUSTER", "VERBOSE|(*)", MatchAny))
3219 COMPLETE_WITH("USING");
3220 /* If we have CLUSTER <sth> USING, then add the index as well */
3221 else if (Matches("CLUSTER", MatchAny, "USING") ||
3222 Matches("CLUSTER", "VERBOSE|(*)", MatchAny, "USING"))
3223 {
3224 set_completion_reference(prev2_wd);
3225 COMPLETE_WITH_SCHEMA_QUERY(Query_for_index_of_table);
3226 }
3227 else if (HeadMatches("CLUSTER", "(*") &&
3228 !HeadMatches("CLUSTER", "(*)"))
3229 {
3230 /*
3231 * This fires if we're in an unfinished parenthesized option list.
3232 * get_previous_words treats a completed parenthesized option list as
3233 * one word, so the above test is correct.
3234 */
3235 if (ends_with(prev_wd, '(') || ends_with(prev_wd, ','))
3236 COMPLETE_WITH("VERBOSE");
3237 }
3238
3239/* COMMENT */
3240 else if (Matches("COMMENT"))
3241 COMPLETE_WITH("ON");
3242 else if (Matches("COMMENT", "ON"))
3243 COMPLETE_WITH("ACCESS METHOD", "AGGREGATE", "CAST", "COLLATION",
3244 "COLUMN", "CONSTRAINT", "CONVERSION", "DATABASE",
3245 "DOMAIN", "EXTENSION", "EVENT TRIGGER",
3246 "FOREIGN DATA WRAPPER", "FOREIGN TABLE",
3247 "FUNCTION", "INDEX", "LANGUAGE", "LARGE OBJECT",
3248 "MATERIALIZED VIEW", "OPERATOR", "POLICY",
3249 "PROCEDURE", "PROCEDURAL LANGUAGE", "PUBLICATION", "ROLE",
3250 "ROUTINE", "RULE", "SCHEMA", "SEQUENCE", "SERVER",
3251 "STATISTICS", "SUBSCRIPTION", "TABLE",
3252 "TABLESPACE", "TEXT SEARCH", "TRANSFORM FOR",
3253 "TRIGGER", "TYPE", "VIEW");
3254 else if (Matches("COMMENT", "ON", "ACCESS", "METHOD"))
3255 COMPLETE_WITH_QUERY(Query_for_list_of_access_methods);
3256 else if (Matches("COMMENT", "ON", "CONSTRAINT"))
3257 COMPLETE_WITH_QUERY(Query_for_all_table_constraints);
3258 else if (Matches("COMMENT", "ON", "CONSTRAINT", MatchAny))
3259 COMPLETE_WITH("ON");
3260 else if (Matches("COMMENT", "ON", "CONSTRAINT", MatchAny, "ON"))
3261 {
3262 set_completion_reference(prev2_wd);
3263 COMPLETE_WITH_SCHEMA_QUERY_PLUS(Query_for_list_of_tables_for_constraint,
3264 "DOMAIN");
3265 }
3266 else if (Matches("COMMENT", "ON", "CONSTRAINT", MatchAny, "ON", "DOMAIN"))
3267 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_domains);
3268 else if (Matches("COMMENT", "ON", "EVENT", "TRIGGER"))
3269 COMPLETE_WITH_QUERY(Query_for_list_of_event_triggers);
3270 else if (Matches("COMMENT", "ON", "FOREIGN"))
3271 COMPLETE_WITH("DATA WRAPPER", "TABLE");
3272 else if (Matches("COMMENT", "ON", "FOREIGN", "TABLE"))
3273 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_foreign_tables);
3274 else if (Matches("COMMENT", "ON", "MATERIALIZED", "VIEW"))
3275 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_matviews);
3276 else if (Matches("COMMENT", "ON", "POLICY"))
3277 COMPLETE_WITH_QUERY(Query_for_list_of_policies);
3278 else if (Matches("COMMENT", "ON", "POLICY", MatchAny))
3279 COMPLETE_WITH("ON");
3280 else if (Matches("COMMENT", "ON", "POLICY", MatchAny, "ON"))
3281 {
3282 set_completion_reference(prev2_wd);
3283 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables_for_policy);
3284 }
3285 else if (Matches("COMMENT", "ON", "PROCEDURAL", "LANGUAGE"))
3286 COMPLETE_WITH_QUERY(Query_for_list_of_languages);
3287 else if (Matches("COMMENT", "ON", "RULE", MatchAny))
3288 COMPLETE_WITH("ON");
3289 else if (Matches("COMMENT", "ON", "RULE", MatchAny, "ON"))
3290 {
3291 set_completion_reference(prev2_wd);
3292 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables_for_rule);
3293 }
3294 else if (Matches("COMMENT", "ON", "TEXT", "SEARCH"))
3295 COMPLETE_WITH("CONFIGURATION", "DICTIONARY", "PARSER", "TEMPLATE");
3296 else if (Matches("COMMENT", "ON", "TEXT", "SEARCH", "CONFIGURATION"))
3297 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_ts_configurations);
3298 else if (Matches("COMMENT", "ON", "TEXT", "SEARCH", "DICTIONARY"))
3299 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_ts_dictionaries);
3300 else if (Matches("COMMENT", "ON", "TEXT", "SEARCH", "PARSER"))
3301 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_ts_parsers);
3302 else if (Matches("COMMENT", "ON", "TEXT", "SEARCH", "TEMPLATE"))
3303 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_ts_templates);
3304 else if (Matches("COMMENT", "ON", "TRANSFORM", "FOR"))
3305 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_datatypes);
3306 else if (Matches("COMMENT", "ON", "TRANSFORM", "FOR", MatchAny))
3307 COMPLETE_WITH("LANGUAGE");
3308 else if (Matches("COMMENT", "ON", "TRANSFORM", "FOR", MatchAny, "LANGUAGE"))
3309 {
3310 set_completion_reference(prev2_wd);
3311 COMPLETE_WITH_QUERY(Query_for_list_of_languages);
3312 }
3313 else if (Matches("COMMENT", "ON", "TRIGGER", MatchAny))
3314 COMPLETE_WITH("ON");
3315 else if (Matches("COMMENT", "ON", "TRIGGER", MatchAny, "ON"))
3316 {
3317 set_completion_reference(prev2_wd);
3318 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables_for_trigger);
3319 }
3320 else if (Matches("COMMENT", "ON", MatchAny, MatchAnyExcept("IS")) ||
3321 Matches("COMMENT", "ON", MatchAny, MatchAny, MatchAnyExcept("IS")) ||
3322 Matches("COMMENT", "ON", MatchAny, MatchAny, MatchAny, MatchAnyExcept("IS")) ||
3323 Matches("COMMENT", "ON", MatchAny, MatchAny, MatchAny, MatchAny, MatchAnyExcept("IS")))
3324 COMPLETE_WITH("IS");
3325
3326/* COPY */
3327
3328 /*
3329 * If we have COPY, offer list of tables or "(" (Also cover the analogous
3330 * backslash command).
3331 */
3332 else if (Matches("COPY|\\copy"))
3333 COMPLETE_WITH_SCHEMA_QUERY_PLUS(Query_for_list_of_tables_for_copy, "(");
3334 /* Complete COPY ( with legal query commands */
3335 else if (Matches("COPY|\\copy", "("))
3336 COMPLETE_WITH("SELECT", "TABLE", "VALUES", "INSERT INTO", "UPDATE", "DELETE FROM", "MERGE INTO", "WITH");
3337 /* Complete COPY <sth> */
3338 else if (Matches("COPY|\\copy", MatchAny))
3339 COMPLETE_WITH("FROM", "TO");
3340 /* Complete COPY|\copy <sth> FROM|TO with filename or STDIN/STDOUT/PROGRAM */
3341 else if (Matches("COPY|\\copy", MatchAny, "FROM|TO"))
3342 {
3343 /* COPY requires quoted filename */
3344 bool force_quote = HeadMatches("COPY");
3345
3346 if (TailMatches("FROM"))
3347 COMPLETE_WITH_FILES_PLUS("", force_quote, "STDIN", "PROGRAM");
3348 else
3349 COMPLETE_WITH_FILES_PLUS("", force_quote, "STDOUT", "PROGRAM");
3350 }
3351
3352 /* Complete COPY|\copy <sth> FROM|TO PROGRAM */
3353 else if (Matches("COPY|\\copy", MatchAny, "FROM|TO", "PROGRAM"))
3354 COMPLETE_WITH_FILES("", HeadMatches("COPY")); /* COPY requires quoted
3355 * filename */
3356
3357 /* Complete COPY <sth> TO [PROGRAM] <sth> */
3358 else if (Matches("COPY|\\copy", MatchAny, "TO", MatchAnyExcept("PROGRAM")) ||
3359 Matches("COPY|\\copy", MatchAny, "TO", "PROGRAM", MatchAny))
3360 COMPLETE_WITH("WITH (");
3361
3362 /* Complete COPY <sth> FROM [PROGRAM] <sth> */
3363 else if (Matches("COPY|\\copy", MatchAny, "FROM", MatchAnyExcept("PROGRAM")) ||
3364 Matches("COPY|\\copy", MatchAny, "FROM", "PROGRAM", MatchAny))
3365 COMPLETE_WITH("WITH (", "WHERE");
3366
3367 /* Complete COPY <sth> FROM [PROGRAM] filename WITH ( */
3368 else if (Matches("COPY|\\copy", MatchAny, "FROM", MatchAnyExcept("PROGRAM"), "WITH", "(") ||
3369 Matches("COPY|\\copy", MatchAny, "FROM", "PROGRAM", MatchAny, "WITH", "("))
3370 COMPLETE_WITH(Copy_from_options);
3371
3372 /* Complete COPY <sth> TO [PROGRAM] filename WITH ( */
3373 else if (Matches("COPY|\\copy", MatchAny, "TO", MatchAnyExcept("PROGRAM"), "WITH", "(") ||
3374 Matches("COPY|\\copy", MatchAny, "TO", "PROGRAM", MatchAny, "WITH", "("))
3375 COMPLETE_WITH(Copy_to_options);
3376
3377 /* Complete COPY <sth> FROM|TO [PROGRAM] <sth> WITH (FORMAT */
3378 else if (Matches("COPY|\\copy", MatchAny, "FROM|TO", MatchAnyExcept("PROGRAM"), "WITH", "(", "FORMAT") ||
3379 Matches("COPY|\\copy", MatchAny, "FROM|TO", "PROGRAM", MatchAny, "WITH", "(", "FORMAT"))
3380 COMPLETE_WITH("binary", "csv", "text");
3381
3382 /* Complete COPY <sth> FROM [PROGRAM] filename WITH (ON_ERROR */
3383 else if (Matches("COPY|\\copy", MatchAny, "FROM", MatchAnyExcept("PROGRAM"), "WITH", "(", "ON_ERROR") ||
3384 Matches("COPY|\\copy", MatchAny, "FROM", "PROGRAM", MatchAny, "WITH", "(", "ON_ERROR"))
3385 COMPLETE_WITH("stop", "ignore");
3386
3387 /* Complete COPY <sth> FROM [PROGRAM] filename WITH (LOG_VERBOSITY */
3388 else if (Matches("COPY|\\copy", MatchAny, "FROM", MatchAnyExcept("PROGRAM"), "WITH", "(", "LOG_VERBOSITY") ||
3389 Matches("COPY|\\copy", MatchAny, "FROM", "PROGRAM", MatchAny, "WITH", "(", "LOG_VERBOSITY"))
3390 COMPLETE_WITH("silent", "default", "verbose");
3391
3392 /* Complete COPY <sth> FROM [PROGRAM] <sth> WITH (<options>) */
3393 else if (Matches("COPY|\\copy", MatchAny, "FROM", MatchAnyExcept("PROGRAM"), "WITH", MatchAny) ||
3394 Matches("COPY|\\copy", MatchAny, "FROM", "PROGRAM", MatchAny, "WITH", MatchAny))
3395 COMPLETE_WITH("WHERE");
3396
3397 /* CREATE ACCESS METHOD */
3398 /* Complete "CREATE ACCESS METHOD <name>" */
3399 else if (Matches("CREATE", "ACCESS", "METHOD", MatchAny))
3400 COMPLETE_WITH("TYPE");
3401 /* Complete "CREATE ACCESS METHOD <name> TYPE" */
3402 else if (Matches("CREATE", "ACCESS", "METHOD", MatchAny, "TYPE"))
3403 COMPLETE_WITH("INDEX", "TABLE");
3404 /* Complete "CREATE ACCESS METHOD <name> TYPE <type>" */
3405 else if (Matches("CREATE", "ACCESS", "METHOD", MatchAny, "TYPE", MatchAny))
3406 COMPLETE_WITH("HANDLER");
3407
3408 /* CREATE COLLATION */
3409 else if (Matches("CREATE", "COLLATION", MatchAny))
3410 COMPLETE_WITH("(", "FROM");
3411 else if (Matches("CREATE", "COLLATION", MatchAny, "FROM"))
3412 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_collations);
3413 else if (HeadMatches("CREATE", "COLLATION", MatchAny, "(*"))
3414 {
3415 if (TailMatches("(|*,"))
3416 COMPLETE_WITH("LOCALE =", "LC_COLLATE =", "LC_CTYPE =",
3417 "PROVIDER =", "DETERMINISTIC =");
3418 else if (TailMatches("PROVIDER", "="))
3419 COMPLETE_WITH("libc", "icu");
3420 else if (TailMatches("DETERMINISTIC", "="))
3421 COMPLETE_WITH("true", "false");
3422 }
3423
3424 /* CREATE DATABASE */
3425 else if (Matches("CREATE", "DATABASE", MatchAny))
3426 COMPLETE_WITH("OWNER", "TEMPLATE", "ENCODING", "TABLESPACE",
3427 "IS_TEMPLATE", "STRATEGY",
3428 "ALLOW_CONNECTIONS", "CONNECTION LIMIT",
3429 "LC_COLLATE", "LC_CTYPE", "LOCALE", "OID",
3430 "LOCALE_PROVIDER", "ICU_LOCALE");
3431
3432 else if (Matches("CREATE", "DATABASE", MatchAny, "TEMPLATE"))
3433 COMPLETE_WITH_QUERY(Query_for_list_of_template_databases);
3434 else if (Matches("CREATE", "DATABASE", MatchAny, "STRATEGY"))
3435 COMPLETE_WITH("WAL_LOG", "FILE_COPY");
3436
3437 /* CREATE DOMAIN */
3438 else if (Matches("CREATE", "DOMAIN", MatchAny))
3439 COMPLETE_WITH("AS");
3440 else if (Matches("CREATE", "DOMAIN", MatchAny, "AS"))
3441 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_datatypes);
3442 else if (Matches("CREATE", "DOMAIN", MatchAny, "AS", MatchAny))
3443 COMPLETE_WITH("COLLATE", "DEFAULT", "CONSTRAINT",
3444 "NOT NULL", "NULL", "CHECK (");
3445 else if (Matches("CREATE", "DOMAIN", MatchAny, "COLLATE"))
3446 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_collations);
3447
3448 /* CREATE EXTENSION */
3449 /* Complete with available extensions rather than installed ones. */
3450 else if (Matches("CREATE", "EXTENSION"))
3451 COMPLETE_WITH_QUERY(Query_for_list_of_available_extensions);
3452 /* CREATE EXTENSION <name> */
3453 else if (Matches("CREATE", "EXTENSION", MatchAny))
3454 COMPLETE_WITH("WITH SCHEMA", "CASCADE", "VERSION");
3455 /* CREATE EXTENSION <name> VERSION */
3456 else if (Matches("CREATE", "EXTENSION", MatchAny, "VERSION"))
3457 {
3458 set_completion_reference(prev2_wd);
3459 COMPLETE_WITH_QUERY(Query_for_list_of_available_extension_versions);
3460 }
3461
3462 /* CREATE FOREIGN */
3463 else if (Matches("CREATE", "FOREIGN"))
3464 COMPLETE_WITH("DATA WRAPPER", "TABLE");
3465
3466 /* CREATE FOREIGN DATA WRAPPER */
3467 else if (Matches("CREATE", "FOREIGN", "DATA", "WRAPPER", MatchAny))
3468 COMPLETE_WITH("HANDLER", "VALIDATOR", "OPTIONS");
3469
3470 /* CREATE FOREIGN TABLE */
3471 else if (Matches("CREATE", "FOREIGN", "TABLE", MatchAny))
3472 COMPLETE_WITH("(", "PARTITION OF");
3473
3474 /* CREATE INDEX --- is allowed inside CREATE SCHEMA, so use TailMatches */
3475 /* First off we complete CREATE UNIQUE with "INDEX" */
3476 else if (TailMatches("CREATE", "UNIQUE"))
3477 COMPLETE_WITH("INDEX");
3478
3479 /*
3480 * If we have CREATE|UNIQUE INDEX, then add "ON", "CONCURRENTLY", and
3481 * existing indexes
3482 */
3483 else if (TailMatches("CREATE|UNIQUE", "INDEX"))
3484 COMPLETE_WITH_SCHEMA_QUERY_PLUS(Query_for_list_of_indexes,
3485 "ON", "CONCURRENTLY");
3486
3487 /*
3488 * Complete ... INDEX|CONCURRENTLY [<name>] ON with a list of relations
3489 * that indexes can be created on
3490 */
3491 else if (TailMatches("INDEX|CONCURRENTLY", MatchAny, "ON") ||
3492 TailMatches("INDEX|CONCURRENTLY", "ON"))
3493 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_indexables);
3494
3495 /*
3496 * Complete CREATE|UNIQUE INDEX CONCURRENTLY with "ON" and existing
3497 * indexes
3498 */
3499 else if (TailMatches("CREATE|UNIQUE", "INDEX", "CONCURRENTLY"))
3500 COMPLETE_WITH_SCHEMA_QUERY_PLUS(Query_for_list_of_indexes,
3501 "ON");
3502 /* Complete CREATE|UNIQUE INDEX [CONCURRENTLY] <sth> with "ON" */
3503 else if (TailMatches("CREATE|UNIQUE", "INDEX", MatchAny) ||
3504 TailMatches("CREATE|UNIQUE", "INDEX", "CONCURRENTLY", MatchAny))
3505 COMPLETE_WITH("ON");
3506
3507 /*
3508 * Complete INDEX <name> ON <table> with a list of table columns (which
3509 * should really be in parens)
3510 */
3511 else if (TailMatches("INDEX", MatchAny, "ON", MatchAny) ||
3512 TailMatches("INDEX|CONCURRENTLY", "ON", MatchAny))
3513 COMPLETE_WITH("(", "USING");
3514 else if (TailMatches("INDEX", MatchAny, "ON", MatchAny, "(") ||
3515 TailMatches("INDEX|CONCURRENTLY", "ON", MatchAny, "("))
3516 COMPLETE_WITH_ATTR(prev2_wd);
3517 /* same if you put in USING */
3518 else if (TailMatches("ON", MatchAny, "USING", MatchAny, "("))
3519 COMPLETE_WITH_ATTR(prev4_wd);
3520 /* Complete USING with an index method */
3521 else if (TailMatches("INDEX", MatchAny, MatchAny, "ON", MatchAny, "USING") ||
3522 TailMatches("INDEX", MatchAny, "ON", MatchAny, "USING") ||
3523 TailMatches("INDEX", "ON", MatchAny, "USING"))
3524 COMPLETE_WITH_QUERY(Query_for_list_of_index_access_methods);
3525 else if (TailMatches("ON", MatchAny, "USING", MatchAny) &&
3526 !TailMatches("POLICY", MatchAny, MatchAny, MatchAny, MatchAny, MatchAny) &&
3527 !TailMatches("FOR", MatchAny, MatchAny, MatchAny))
3528 COMPLETE_WITH("(");
3529
3530 /* CREATE OR REPLACE */
3531 else if (Matches("CREATE", "OR"))
3532 COMPLETE_WITH("REPLACE");
3533
3534 /* CREATE POLICY */
3535 /* Complete "CREATE POLICY <name> ON" */
3536 else if (Matches("CREATE", "POLICY", MatchAny))
3537 COMPLETE_WITH("ON");
3538 /* Complete "CREATE POLICY <name> ON <table>" */
3539 else if (Matches("CREATE", "POLICY", MatchAny, "ON"))
3540 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables);
3541 /* Complete "CREATE POLICY <name> ON <table> AS|FOR|TO|USING|WITH CHECK" */
3542 else if (Matches("CREATE", "POLICY", MatchAny, "ON", MatchAny))
3543 COMPLETE_WITH("AS", "FOR", "TO", "USING (", "WITH CHECK (");
3544 /* CREATE POLICY <name> ON <table> AS PERMISSIVE|RESTRICTIVE */
3545 else if (Matches("CREATE", "POLICY", MatchAny, "ON", MatchAny, "AS"))
3546 COMPLETE_WITH("PERMISSIVE", "RESTRICTIVE");
3547
3548 /*
3549 * CREATE POLICY <name> ON <table> AS PERMISSIVE|RESTRICTIVE
3550 * FOR|TO|USING|WITH CHECK
3551 */
3552 else if (Matches("CREATE", "POLICY", MatchAny, "ON", MatchAny, "AS", MatchAny))
3553 COMPLETE_WITH("FOR", "TO", "USING", "WITH CHECK");
3554 /* CREATE POLICY <name> ON <table> FOR ALL|SELECT|INSERT|UPDATE|DELETE */
3555 else if (Matches("CREATE", "POLICY", MatchAny, "ON", MatchAny, "FOR"))
3556 COMPLETE_WITH("ALL", "SELECT", "INSERT", "UPDATE", "DELETE");
3557 /* Complete "CREATE POLICY <name> ON <table> FOR INSERT TO|WITH CHECK" */
3558 else if (Matches("CREATE", "POLICY", MatchAny, "ON", MatchAny, "FOR", "INSERT"))
3559 COMPLETE_WITH("TO", "WITH CHECK (");
3560 /* Complete "CREATE POLICY <name> ON <table> FOR SELECT|DELETE TO|USING" */
3561 else if (Matches("CREATE", "POLICY", MatchAny, "ON", MatchAny, "FOR", "SELECT|DELETE"))
3562 COMPLETE_WITH("TO", "USING (");
3563 /* CREATE POLICY <name> ON <table> FOR ALL|UPDATE TO|USING|WITH CHECK */
3564 else if (Matches("CREATE", "POLICY", MatchAny, "ON", MatchAny, "FOR", "ALL|UPDATE"))
3565 COMPLETE_WITH("TO", "USING (", "WITH CHECK (");
3566 /* Complete "CREATE POLICY <name> ON <table> TO <role>" */
3567 else if (Matches("CREATE", "POLICY", MatchAny, "ON", MatchAny, "TO"))
3568 COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_roles,
3569 Keywords_for_list_of_grant_roles);
3570 /* Complete "CREATE POLICY <name> ON <table> USING (" */
3571 else if (Matches("CREATE", "POLICY", MatchAny, "ON", MatchAny, "USING"))
3572 COMPLETE_WITH("(");
3573
3574 /*
3575 * CREATE POLICY <name> ON <table> AS PERMISSIVE|RESTRICTIVE FOR
3576 * ALL|SELECT|INSERT|UPDATE|DELETE
3577 */
3578 else if (Matches("CREATE", "POLICY", MatchAny, "ON", MatchAny, "AS", MatchAny, "FOR"))
3579 COMPLETE_WITH("ALL", "SELECT", "INSERT", "UPDATE", "DELETE");
3580
3581 /*
3582 * Complete "CREATE POLICY <name> ON <table> AS PERMISSIVE|RESTRICTIVE FOR
3583 * INSERT TO|WITH CHECK"
3584 */
3585 else if (Matches("CREATE", "POLICY", MatchAny, "ON", MatchAny, "AS", MatchAny, "FOR", "INSERT"))
3586 COMPLETE_WITH("TO", "WITH CHECK (");
3587
3588 /*
3589 * Complete "CREATE POLICY <name> ON <table> AS PERMISSIVE|RESTRICTIVE FOR
3590 * SELECT|DELETE TO|USING"
3591 */
3592 else if (Matches("CREATE", "POLICY", MatchAny, "ON", MatchAny, "AS", MatchAny, "FOR", "SELECT|DELETE"))
3593 COMPLETE_WITH("TO", "USING (");
3594
3595 /*
3596 * CREATE POLICY <name> ON <table> AS PERMISSIVE|RESTRICTIVE FOR
3597 * ALL|UPDATE TO|USING|WITH CHECK
3598 */
3599 else if (Matches("CREATE", "POLICY", MatchAny, "ON", MatchAny, "AS", MatchAny, "FOR", "ALL|UPDATE"))
3600 COMPLETE_WITH("TO", "USING (", "WITH CHECK (");
3601
3602 /*
3603 * Complete "CREATE POLICY <name> ON <table> AS PERMISSIVE|RESTRICTIVE TO
3604 * <role>"
3605 */
3606 else if (Matches("CREATE", "POLICY", MatchAny, "ON", MatchAny, "AS", MatchAny, "TO"))
3607 COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_roles,
3608 Keywords_for_list_of_grant_roles);
3609
3610 /*
3611 * Complete "CREATE POLICY <name> ON <table> AS PERMISSIVE|RESTRICTIVE
3612 * USING ("
3613 */
3614 else if (Matches("CREATE", "POLICY", MatchAny, "ON", MatchAny, "AS", MatchAny, "USING"))
3615 COMPLETE_WITH("(");
3616
3617
3618/* CREATE PUBLICATION */
3619 else if (Matches("CREATE", "PUBLICATION", MatchAny))
3620 COMPLETE_WITH("FOR TABLE", "FOR TABLES IN SCHEMA", "FOR ALL TABLES", "FOR ALL SEQUENCES", "WITH (");
3621 else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR"))
3622 COMPLETE_WITH("TABLE", "TABLES IN SCHEMA", "ALL TABLES", "ALL SEQUENCES");
3623 else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "ALL"))
3624 COMPLETE_WITH("TABLES", "SEQUENCES");
3625 else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "ALL", "TABLES"))
3626 COMPLETE_WITH("WITH (");
3627 else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES"))
3628 COMPLETE_WITH("IN SCHEMA");
3629 else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLE", MatchAny) && !ends_with(prev_wd, ','))
3630 COMPLETE_WITH("WHERE (", "WITH (");
3631 /* Complete "CREATE PUBLICATION <name> FOR TABLE" with "<table>, ..." */
3632 else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLE"))
3633 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables);
3634
3635 /*
3636 * "CREATE PUBLICATION <name> FOR TABLE <name> WHERE (" - complete with
3637 * table attributes
3638 */
3639 else if (Matches("CREATE", "PUBLICATION", MatchAny, MatchAnyN, "WHERE"))
3640 COMPLETE_WITH("(");
3641 else if (Matches("CREATE", "PUBLICATION", MatchAny, MatchAnyN, "WHERE", "("))
3642 COMPLETE_WITH_ATTR(prev3_wd);
3643 else if (Matches("CREATE", "PUBLICATION", MatchAny, MatchAnyN, "WHERE", "(*)"))
3644 COMPLETE_WITH(" WITH (");
3645
3646 /*
3647 * Complete "CREATE PUBLICATION <name> FOR TABLES IN SCHEMA <schema>, ..."
3648 */
3649 else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA"))
3650 COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas
3651 " AND nspname NOT LIKE E'pg\\\\_%%'",
3652 "CURRENT_SCHEMA");
3653 else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && (!ends_with(prev_wd, ',')))
3654 COMPLETE_WITH("WITH (");
3655 /* Complete "CREATE PUBLICATION <name> [...] WITH" */
3656 else if (Matches("CREATE", "PUBLICATION", MatchAnyN, "WITH", "("))
3657 COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root");
3658
3659/* CREATE RULE */
3660 /* Complete "CREATE [ OR REPLACE ] RULE <sth>" with "AS ON" */
3661 else if (Matches("CREATE", "RULE", MatchAny) ||
3662 Matches("CREATE", "OR", "REPLACE", "RULE", MatchAny))
3663 COMPLETE_WITH("AS ON");
3664 /* Complete "CREATE [ OR REPLACE ] RULE <sth> AS" with "ON" */
3665 else if (Matches("CREATE", "RULE", MatchAny, "AS") ||
3666 Matches("CREATE", "OR", "REPLACE", "RULE", MatchAny, "AS"))
3667 COMPLETE_WITH("ON");
3668
3669 /*
3670 * Complete "CREATE [ OR REPLACE ] RULE <sth> AS ON" with
3671 * SELECT|UPDATE|INSERT|DELETE
3672 */
3673 else if (Matches("CREATE", "RULE", MatchAny, "AS", "ON") ||
3674 Matches("CREATE", "OR", "REPLACE", "RULE", MatchAny, "AS", "ON"))
3675 COMPLETE_WITH("SELECT", "UPDATE", "INSERT", "DELETE");
3676 /* Complete "AS ON SELECT|UPDATE|INSERT|DELETE" with a "TO" */
3677 else if (TailMatches("AS", "ON", "SELECT|UPDATE|INSERT|DELETE"))
3678 COMPLETE_WITH("TO");
3679 /* Complete "AS ON <sth> TO" with a table name */
3680 else if (TailMatches("AS", "ON", "SELECT|UPDATE|INSERT|DELETE", "TO"))
3681 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables);
3682
3683/* CREATE SCHEMA [ <name> ] [ AUTHORIZATION ] */
3684 else if (Matches("CREATE", "SCHEMA"))
3685 COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas,
3686 "AUTHORIZATION");
3687 else if (Matches("CREATE", "SCHEMA", "AUTHORIZATION") ||
3688 Matches("CREATE", "SCHEMA", MatchAny, "AUTHORIZATION"))
3689 COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_roles,
3690 Keywords_for_list_of_owner_roles);
3691 else if (Matches("CREATE", "SCHEMA", "AUTHORIZATION", MatchAny) ||
3692 Matches("CREATE", "SCHEMA", MatchAny, "AUTHORIZATION", MatchAny))
3693 COMPLETE_WITH("CREATE", "GRANT");
3694 else if (Matches("CREATE", "SCHEMA", MatchAny))
3695 COMPLETE_WITH("AUTHORIZATION", "CREATE", "GRANT");
3696
3697/* CREATE SEQUENCE --- is allowed inside CREATE SCHEMA, so use TailMatches */
3698 else if (TailMatches("CREATE", "SEQUENCE", MatchAny) ||
3699 TailMatches("CREATE", "TEMP|TEMPORARY", "SEQUENCE", MatchAny))
3700 COMPLETE_WITH("AS", "INCREMENT BY", "MINVALUE", "MAXVALUE", "NO",
3701 "CACHE", "CYCLE", "OWNED BY", "START WITH");
3702 else if (TailMatches("CREATE", "SEQUENCE", MatchAny, "AS") ||
3703 TailMatches("CREATE", "TEMP|TEMPORARY", "SEQUENCE", MatchAny, "AS"))
3704 COMPLETE_WITH_CS("smallint", "integer", "bigint");
3705 else if (TailMatches("CREATE", "SEQUENCE", MatchAny, "NO") ||
3706 TailMatches("CREATE", "TEMP|TEMPORARY", "SEQUENCE", MatchAny, "NO"))
3707 COMPLETE_WITH("MINVALUE", "MAXVALUE", "CYCLE");
3708
3709/* CREATE SERVER <name> */
3710 else if (Matches("CREATE", "SERVER", MatchAny))
3711 COMPLETE_WITH("TYPE", "VERSION", "FOREIGN DATA WRAPPER");
3712
3713/* CREATE STATISTICS <name> */
3714 else if (Matches("CREATE", "STATISTICS", MatchAny))
3715 COMPLETE_WITH("(", "ON");
3716 else if (Matches("CREATE", "STATISTICS", MatchAny, "("))
3717 COMPLETE_WITH("ndistinct", "dependencies", "mcv");
3718 else if (Matches("CREATE", "STATISTICS", MatchAny, "(*)"))
3719 COMPLETE_WITH("ON");
3720 else if (Matches("CREATE", "STATISTICS", MatchAny, MatchAnyN, "FROM"))
3721 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables);
3722
3723/* CREATE TABLE --- is allowed inside CREATE SCHEMA, so use TailMatches */
3724 /* Complete "CREATE TEMP/TEMPORARY" with the possible temp objects */
3725 else if (TailMatches("CREATE", "TEMP|TEMPORARY"))
3726 COMPLETE_WITH("SEQUENCE", "TABLE", "VIEW");
3727 /* Complete "CREATE UNLOGGED" with TABLE or SEQUENCE */
3728 else if (TailMatches("CREATE", "UNLOGGED"))
3729 COMPLETE_WITH("TABLE", "SEQUENCE");
3730 /* Complete PARTITION BY with RANGE ( or LIST ( or ... */
3731 else if (TailMatches("PARTITION", "BY"))
3732 COMPLETE_WITH("RANGE (", "LIST (", "HASH (");
3733 /* If we have xxx PARTITION OF, provide a list of partitioned tables */
3734 else if (TailMatches("PARTITION", "OF"))
3735 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_partitioned_tables);
3736 /* Limited completion support for partition bound specification */
3737 else if (TailMatches("PARTITION", "OF", MatchAny))
3738 COMPLETE_WITH("FOR VALUES", "DEFAULT");
3739 /* Complete CREATE TABLE <name> with '(', AS, OF or PARTITION OF */
3740 else if (TailMatches("CREATE", "TABLE", MatchAny) ||
3741 TailMatches("CREATE", "TEMP|TEMPORARY|UNLOGGED", "TABLE", MatchAny))
3742 COMPLETE_WITH("(", "AS", "OF", "PARTITION OF");
3743 /* Complete CREATE TABLE <name> OF with list of composite types */
3744 else if (TailMatches("CREATE", "TABLE", MatchAny, "OF") ||
3745 TailMatches("CREATE", "TEMP|TEMPORARY|UNLOGGED", "TABLE", MatchAny, "OF"))
3746 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_composite_datatypes);
3747 /* Complete CREATE TABLE <name> [ (...) ] AS with list of keywords */
3748 else if (TailMatches("CREATE", "TABLE", MatchAny, "AS") ||
3749 TailMatches("CREATE", "TABLE", MatchAny, "(*)", "AS") ||
3750 TailMatches("CREATE", "TEMP|TEMPORARY|UNLOGGED", "TABLE", MatchAny, "AS") ||
3751 TailMatches("CREATE", "TEMP|TEMPORARY|UNLOGGED", "TABLE", MatchAny, "(*)", "AS"))
3752 COMPLETE_WITH("EXECUTE", "SELECT", "TABLE", "VALUES", "WITH");
3753 /* Complete CREATE TABLE name (...) with supported options */
3754 else if (TailMatches("CREATE", "TABLE", MatchAny, "(*)"))
3755 COMPLETE_WITH("AS", "INHERITS (", "PARTITION BY", "USING", "TABLESPACE", "WITH (");
3756 else if (TailMatches("CREATE", "UNLOGGED", "TABLE", MatchAny, "(*)"))
3757 COMPLETE_WITH("AS", "INHERITS (", "USING", "TABLESPACE", "WITH (");
3758 else if (TailMatches("CREATE", "TEMP|TEMPORARY", "TABLE", MatchAny, "(*)"))
3759 COMPLETE_WITH("AS", "INHERITS (", "ON COMMIT", "PARTITION BY", "USING",
3760 "TABLESPACE", "WITH (");
3761 /* Complete CREATE TABLE (...) USING with table access methods */
3762 else if (TailMatches("CREATE", "TABLE", MatchAny, "(*)", "USING") ||
3763 TailMatches("CREATE", "TEMP|TEMPORARY|UNLOGGED", "TABLE", MatchAny, "(*)", "USING"))
3764 COMPLETE_WITH_QUERY(Query_for_list_of_table_access_methods);
3765 /* Complete CREATE TABLE (...) WITH with storage parameters */
3766 else if (TailMatches("CREATE", "TABLE", MatchAny, "(*)", "WITH", "(") ||
3767 TailMatches("CREATE", "TEMP|TEMPORARY|UNLOGGED", "TABLE", MatchAny, "(*)", "WITH", "("))
3768 COMPLETE_WITH_LIST(table_storage_parameters);
3769 /* Complete CREATE TABLE ON COMMIT with actions */
3770 else if (TailMatches("CREATE", "TEMP|TEMPORARY", "TABLE", MatchAny, "(*)", "ON", "COMMIT"))
3771 COMPLETE_WITH("DELETE ROWS", "DROP", "PRESERVE ROWS");
3772
3773/* CREATE TABLESPACE */
3774 else if (Matches("CREATE", "TABLESPACE", MatchAny))
3775 COMPLETE_WITH("OWNER", "LOCATION");
3776 /* Complete CREATE TABLESPACE name OWNER name with "LOCATION" */
3777 else if (Matches("CREATE", "TABLESPACE", MatchAny, "OWNER", MatchAny))
3778 COMPLETE_WITH("LOCATION");
3779
3780/* CREATE TEXT SEARCH */
3781 else if (Matches("CREATE", "TEXT", "SEARCH"))
3782 COMPLETE_WITH("CONFIGURATION", "DICTIONARY", "PARSER", "TEMPLATE");
3783 else if (Matches("CREATE", "TEXT", "SEARCH", "CONFIGURATION|DICTIONARY|PARSER|TEMPLATE", MatchAny))
3784 COMPLETE_WITH("(");
3785
3786/* CREATE TRANSFORM */
3787 else if (Matches("CREATE", "TRANSFORM") ||
3788 Matches("CREATE", "OR", "REPLACE", "TRANSFORM"))
3789 COMPLETE_WITH("FOR");
3790 else if (Matches("CREATE", "TRANSFORM", "FOR") ||
3791 Matches("CREATE", "OR", "REPLACE", "TRANSFORM", "FOR"))
3792 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_datatypes);
3793 else if (Matches("CREATE", "TRANSFORM", "FOR", MatchAny) ||
3794 Matches("CREATE", "OR", "REPLACE", "TRANSFORM", "FOR", MatchAny))
3795 COMPLETE_WITH("LANGUAGE");
3796 else if (Matches("CREATE", "TRANSFORM", "FOR", MatchAny, "LANGUAGE") ||
3797 Matches("CREATE", "OR", "REPLACE", "TRANSFORM", "FOR", MatchAny, "LANGUAGE"))
3798 {
3799 set_completion_reference(prev2_wd);
3800 COMPLETE_WITH_QUERY(Query_for_list_of_languages);
3801 }
3802
3803/* CREATE SUBSCRIPTION */
3804 else if (Matches("CREATE", "SUBSCRIPTION", MatchAny))
3805 COMPLETE_WITH("CONNECTION");
3806 else if (Matches("CREATE", "SUBSCRIPTION", MatchAny, "CONNECTION", MatchAny))
3807 COMPLETE_WITH("PUBLICATION");
3808 else if (Matches("CREATE", "SUBSCRIPTION", MatchAny, "CONNECTION",
3809 MatchAny, "PUBLICATION"))
3810 {
3811 /* complete with nothing here as this refers to remote publications */
3812 }
3813 else if (Matches("CREATE", "SUBSCRIPTION", MatchAnyN, "PUBLICATION", MatchAny))
3814 COMPLETE_WITH("WITH (");
3815 /* Complete "CREATE SUBSCRIPTION <name> ... WITH ( <opt>" */
3816 else if (Matches("CREATE", "SUBSCRIPTION", MatchAnyN, "WITH", "("))
3817 COMPLETE_WITH("binary", "connect", "copy_data", "create_slot",
3818 "disable_on_error", "enabled", "failover",
3819 "max_retention_duration", "origin",
3820 "password_required", "retain_dead_tuples",
3821 "run_as_owner", "slot_name", "streaming",
3822 "synchronous_commit", "two_phase");
3823
3824/* CREATE TRIGGER --- is allowed inside CREATE SCHEMA, so use TailMatches */
3825
3826 /*
3827 * Complete CREATE [ OR REPLACE ] TRIGGER <name> with BEFORE|AFTER|INSTEAD
3828 * OF.
3829 */
3830 else if (TailMatches("CREATE", "TRIGGER", MatchAny) ||
3831 TailMatches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAny))
3832 COMPLETE_WITH("BEFORE", "AFTER", "INSTEAD OF");
3833
3834 /*
3835 * Complete CREATE [ OR REPLACE ] TRIGGER <name> BEFORE,AFTER with an
3836 * event.
3837 */
3838 else if (TailMatches("CREATE", "TRIGGER", MatchAny, "BEFORE|AFTER") ||
3839 TailMatches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAny, "BEFORE|AFTER"))
3840 COMPLETE_WITH("INSERT", "DELETE", "UPDATE", "TRUNCATE");
3841 /* Complete CREATE [ OR REPLACE ] TRIGGER <name> INSTEAD OF with an event */
3842 else if (TailMatches("CREATE", "TRIGGER", MatchAny, "INSTEAD", "OF") ||
3843 TailMatches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAny, "INSTEAD", "OF"))
3844 COMPLETE_WITH("INSERT", "DELETE", "UPDATE");
3845
3846 /*
3847 * Complete CREATE [ OR REPLACE ] TRIGGER <name> BEFORE,AFTER sth with
3848 * OR|ON.
3849 */
3850 else if (TailMatches("CREATE", "TRIGGER", MatchAny, "BEFORE|AFTER", MatchAny) ||
3851 TailMatches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAny, "BEFORE|AFTER", MatchAny) ||
3852 TailMatches("CREATE", "TRIGGER", MatchAny, "INSTEAD", "OF", MatchAny) ||
3853 TailMatches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAny, "INSTEAD", "OF", MatchAny))
3854 COMPLETE_WITH("ON", "OR");
3855
3856 /*
3857 * Complete CREATE [ OR REPLACE ] TRIGGER <name> BEFORE,AFTER event ON
3858 * with a list of tables. EXECUTE FUNCTION is the recommended grammar
3859 * instead of EXECUTE PROCEDURE in version 11 and upwards.
3860 */
3861 else if (TailMatches("CREATE", "TRIGGER", MatchAny, "BEFORE|AFTER", MatchAny, "ON") ||
3862 TailMatches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAny, "BEFORE|AFTER", MatchAny, "ON"))
3863 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables);
3864
3865 /*
3866 * Complete CREATE [ OR REPLACE ] TRIGGER ... INSTEAD OF event ON with a
3867 * list of views.
3868 */
3869 else if (TailMatches("CREATE", "TRIGGER", MatchAny, "INSTEAD", "OF", MatchAny, "ON") ||
3870 TailMatches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAny, "INSTEAD", "OF", MatchAny, "ON"))
3871 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_views);
3872 else if (Matches("CREATE", "TRIGGER", MatchAnyN,
3873 "ON", MatchAny) ||
3874 Matches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAnyN,
3875 "ON", MatchAny))
3876 {
3877 if (pset.sversion >= 110000)
3878 COMPLETE_WITH("NOT DEFERRABLE", "DEFERRABLE", "INITIALLY",
3879 "REFERENCING", "FOR", "WHEN (", "EXECUTE FUNCTION");
3880 else
3881 COMPLETE_WITH("NOT DEFERRABLE", "DEFERRABLE", "INITIALLY",
3882 "REFERENCING", "FOR", "WHEN (", "EXECUTE PROCEDURE");
3883 }
3884 else if (Matches("CREATE", "TRIGGER", MatchAnyN,
3885 "DEFERRABLE") ||
3886 Matches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAnyN,
3887 "DEFERRABLE") ||
3888 Matches("CREATE", "TRIGGER", MatchAnyN,
3889 "INITIALLY", "IMMEDIATE|DEFERRED") ||
3890 Matches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAnyN,
3891 "INITIALLY", "IMMEDIATE|DEFERRED"))
3892 {
3893 if (pset.sversion >= 110000)
3894 COMPLETE_WITH("REFERENCING", "FOR", "WHEN (", "EXECUTE FUNCTION");
3895 else
3896 COMPLETE_WITH("REFERENCING", "FOR", "WHEN (", "EXECUTE PROCEDURE");
3897 }
3898 else if (Matches("CREATE", "TRIGGER", MatchAnyN,
3899 "REFERENCING") ||
3900 Matches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAnyN,
3901 "REFERENCING"))
3902 COMPLETE_WITH("OLD TABLE", "NEW TABLE");
3903 else if (Matches("CREATE", "TRIGGER", MatchAnyN,
3904 "OLD|NEW", "TABLE") ||
3905 Matches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAnyN,
3906 "OLD|NEW", "TABLE"))
3907 COMPLETE_WITH("AS");
3908 else if (Matches("CREATE", "TRIGGER", MatchAnyN,
3909 "REFERENCING", "OLD", "TABLE", "AS", MatchAny) ||
3910 Matches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAnyN,
3911 "REFERENCING", "OLD", "TABLE", "AS", MatchAny) ||
3912 Matches("CREATE", "TRIGGER", MatchAnyN,
3913 "REFERENCING", "OLD", "TABLE", MatchAny) ||
3914 Matches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAnyN,
3915 "REFERENCING", "OLD", "TABLE", MatchAny))
3916 {
3917 if (pset.sversion >= 110000)
3918 COMPLETE_WITH("NEW TABLE", "FOR", "WHEN (", "EXECUTE FUNCTION");
3919 else
3920 COMPLETE_WITH("NEW TABLE", "FOR", "WHEN (", "EXECUTE PROCEDURE");
3921 }
3922 else if (Matches("CREATE", "TRIGGER", MatchAnyN,
3923 "REFERENCING", "NEW", "TABLE", "AS", MatchAny) ||
3924 Matches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAnyN,
3925 "REFERENCING", "NEW", "TABLE", "AS", MatchAny) ||
3926 Matches("CREATE", "TRIGGER", MatchAnyN,
3927 "REFERENCING", "NEW", "TABLE", MatchAny) ||
3928 Matches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAnyN,
3929 "REFERENCING", "NEW", "TABLE", MatchAny))
3930 {
3931 if (pset.sversion >= 110000)
3932 COMPLETE_WITH("OLD TABLE", "FOR", "WHEN (", "EXECUTE FUNCTION");
3933 else
3934 COMPLETE_WITH("OLD TABLE", "FOR", "WHEN (", "EXECUTE PROCEDURE");
3935 }
3936 else if (Matches("CREATE", "TRIGGER", MatchAnyN,
3937 "REFERENCING", "OLD|NEW", "TABLE", "AS", MatchAny, "OLD|NEW", "TABLE", "AS", MatchAny) ||
3938 Matches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAnyN,
3939 "REFERENCING", "OLD|NEW", "TABLE", "AS", MatchAny, "OLD|NEW", "TABLE", "AS", MatchAny) ||
3940 Matches("CREATE", "TRIGGER", MatchAnyN,
3941 "REFERENCING", "OLD|NEW", "TABLE", MatchAny, "OLD|NEW", "TABLE", "AS", MatchAny) ||
3942 Matches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAnyN,
3943 "REFERENCING", "OLD|NEW", "TABLE", MatchAny, "OLD|NEW", "TABLE", "AS", MatchAny) ||
3944 Matches("CREATE", "TRIGGER", MatchAnyN,
3945 "REFERENCING", "OLD|NEW", "TABLE", "AS", MatchAny, "OLD|NEW", "TABLE", MatchAny) ||
3946 Matches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAnyN,
3947 "REFERENCING", "OLD|NEW", "TABLE", "AS", MatchAny, "OLD|NEW", "TABLE", MatchAny) ||
3948 Matches("CREATE", "TRIGGER", MatchAnyN,
3949 "REFERENCING", "OLD|NEW", "TABLE", MatchAny, "OLD|NEW", "TABLE", MatchAny) ||
3950 Matches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAnyN,
3951 "REFERENCING", "OLD|NEW", "TABLE", MatchAny, "OLD|NEW", "TABLE", MatchAny))
3952 {
3953 if (pset.sversion >= 110000)
3954 COMPLETE_WITH("FOR", "WHEN (", "EXECUTE FUNCTION");
3955 else
3956 COMPLETE_WITH("FOR", "WHEN (", "EXECUTE PROCEDURE");
3957 }
3958 else if (Matches("CREATE", "TRIGGER", MatchAnyN,
3959 "FOR") ||
3960 Matches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAnyN,
3961 "FOR"))
3962 COMPLETE_WITH("EACH", "ROW", "STATEMENT");
3963 else if (Matches("CREATE", "TRIGGER", MatchAnyN,
3964 "FOR", "EACH") ||
3965 Matches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAnyN,
3966 "FOR", "EACH"))
3967 COMPLETE_WITH("ROW", "STATEMENT");
3968 else if (Matches("CREATE", "TRIGGER", MatchAnyN,
3969 "FOR", "EACH", "ROW|STATEMENT") ||
3970 Matches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAnyN,
3971 "FOR", "EACH", "ROW|STATEMENT") ||
3972 Matches("CREATE", "TRIGGER", MatchAnyN,
3973 "FOR", "ROW|STATEMENT") ||
3974 Matches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAnyN,
3975 "FOR", "ROW|STATEMENT"))
3976 {
3977 if (pset.sversion >= 110000)
3978 COMPLETE_WITH("WHEN (", "EXECUTE FUNCTION");
3979 else
3980 COMPLETE_WITH("WHEN (", "EXECUTE PROCEDURE");
3981 }
3982 else if (Matches("CREATE", "TRIGGER", MatchAnyN,
3983 "WHEN", "(*)") ||
3984 Matches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAnyN,
3985 "WHEN", "(*)"))
3986 {
3987 if (pset.sversion >= 110000)
3988 COMPLETE_WITH("EXECUTE FUNCTION");
3989 else
3990 COMPLETE_WITH("EXECUTE PROCEDURE");
3991 }
3992
3993 /*
3994 * Complete CREATE [ OR REPLACE ] TRIGGER ... EXECUTE with
3995 * PROCEDURE|FUNCTION.
3996 */
3997 else if (Matches("CREATE", "TRIGGER", MatchAnyN,
3998 "EXECUTE") ||
3999 Matches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAnyN,
4000 "EXECUTE"))
4001 {
4002 if (pset.sversion >= 110000)
4003 COMPLETE_WITH("FUNCTION");
4004 else
4005 COMPLETE_WITH("PROCEDURE");
4006 }
4007 else if (Matches("CREATE", "TRIGGER", MatchAnyN,
4008 "EXECUTE", "FUNCTION|PROCEDURE") ||
4009 Matches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAnyN,
4010 "EXECUTE", "FUNCTION|PROCEDURE"))
4011 COMPLETE_WITH_VERSIONED_SCHEMA_QUERY(Query_for_list_of_functions);
4012
4013/* CREATE ROLE,USER,GROUP <name> */
4014 else if (Matches("CREATE", "ROLE|GROUP|USER", MatchAny) &&
4015 !TailMatches("USER", "MAPPING"))
4016 COMPLETE_WITH("ADMIN", "BYPASSRLS", "CONNECTION LIMIT", "CREATEDB",
4017 "CREATEROLE", "ENCRYPTED PASSWORD", "IN", "INHERIT",
4018 "LOGIN", "NOBYPASSRLS",
4019 "NOCREATEDB", "NOCREATEROLE", "NOINHERIT",
4020 "NOLOGIN", "NOREPLICATION", "NOSUPERUSER", "PASSWORD",
4021 "REPLICATION", "ROLE", "SUPERUSER", "SYSID",
4022 "VALID UNTIL", "WITH");
4023
4024/* CREATE ROLE,USER,GROUP <name> WITH */
4025 else if (Matches("CREATE", "ROLE|GROUP|USER", MatchAny, "WITH"))
4026 /* Similar to the above, but don't complete "WITH" again. */
4027 COMPLETE_WITH("ADMIN", "BYPASSRLS", "CONNECTION LIMIT", "CREATEDB",
4028 "CREATEROLE", "ENCRYPTED PASSWORD", "IN", "INHERIT",
4029 "LOGIN", "NOBYPASSRLS",
4030 "NOCREATEDB", "NOCREATEROLE", "NOINHERIT",
4031 "NOLOGIN", "NOREPLICATION", "NOSUPERUSER", "PASSWORD",
4032 "REPLICATION", "ROLE", "SUPERUSER", "SYSID",
4033 "VALID UNTIL");
4034
4035 /* complete CREATE ROLE,USER,GROUP <name> IN with ROLE,GROUP */
4036 else if (Matches("CREATE", "ROLE|USER|GROUP", MatchAny, "IN"))
4037 COMPLETE_WITH("GROUP", "ROLE");
4038
4039/* CREATE TYPE */
4040 else if (Matches("CREATE", "TYPE", MatchAny))
4041 COMPLETE_WITH("(", "AS");
4042 else if (Matches("CREATE", "TYPE", MatchAny, "AS"))
4043 COMPLETE_WITH("ENUM", "RANGE", "(");
4044 else if (HeadMatches("CREATE", "TYPE", MatchAny, "AS", "("))
4045 {
4046 if (TailMatches("(|*,", MatchAny))
4047 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_datatypes);
4048 else if (TailMatches("(|*,", MatchAny, MatchAnyExcept("*)")))
4049 COMPLETE_WITH("COLLATE", ",", ")");
4050 }
4051 else if (Matches("CREATE", "TYPE", MatchAny, "AS", "ENUM|RANGE"))
4052 COMPLETE_WITH("(");
4053 else if (HeadMatches("CREATE", "TYPE", MatchAny, "("))
4054 {
4055 if (TailMatches("(|*,"))
4056 COMPLETE_WITH("INPUT", "OUTPUT", "RECEIVE", "SEND",
4057 "TYPMOD_IN", "TYPMOD_OUT", "ANALYZE", "SUBSCRIPT",
4058 "INTERNALLENGTH", "PASSEDBYVALUE", "ALIGNMENT",
4059 "STORAGE", "LIKE", "CATEGORY", "PREFERRED",
4060 "DEFAULT", "ELEMENT", "DELIMITER",
4061 "COLLATABLE");
4062 else if (TailMatches("(*|*,", MatchAnyExcept("*=")))
4063 COMPLETE_WITH("=");
4064 else if (TailMatches("=", MatchAnyExcept("*)")))
4065 COMPLETE_WITH(",", ")");
4066 }
4067 else if (HeadMatches("CREATE", "TYPE", MatchAny, "AS", "RANGE", "("))
4068 {
4069 if (TailMatches("(|*,"))
4070 COMPLETE_WITH("SUBTYPE", "SUBTYPE_OPCLASS", "COLLATION",
4071 "CANONICAL", "SUBTYPE_DIFF",
4072 "MULTIRANGE_TYPE_NAME");
4073 else if (TailMatches("(*|*,", MatchAnyExcept("*=")))
4074 COMPLETE_WITH("=");
4075 else if (TailMatches("=", MatchAnyExcept("*)")))
4076 COMPLETE_WITH(",", ")");
4077 }
4078
4079/* CREATE VIEW --- is allowed inside CREATE SCHEMA, so use TailMatches */
4080 /* Complete CREATE [ OR REPLACE ] VIEW <name> with AS or WITH */
4081 else if (TailMatches("CREATE", "VIEW", MatchAny) ||
4082 TailMatches("CREATE", "OR", "REPLACE", "VIEW", MatchAny))
4083 COMPLETE_WITH("AS", "WITH");
4084 /* Complete "CREATE [ OR REPLACE ] VIEW <sth> AS with "SELECT" */
4085 else if (TailMatches("CREATE", "VIEW", MatchAny, "AS") ||
4086 TailMatches("CREATE", "OR", "REPLACE", "VIEW", MatchAny, "AS"))
4087 COMPLETE_WITH("SELECT");
4088 /* CREATE [ OR REPLACE ] VIEW <name> WITH ( yyy [= zzz] ) */
4089 else if (TailMatches("CREATE", "VIEW", MatchAny, "WITH") ||
4090 TailMatches("CREATE", "OR", "REPLACE", "VIEW", MatchAny, "WITH"))
4091 COMPLETE_WITH("(");
4092 else if (TailMatches("CREATE", "VIEW", MatchAny, "WITH", "(") ||
4093 TailMatches("CREATE", "OR", "REPLACE", "VIEW", MatchAny, "WITH", "("))
4094 COMPLETE_WITH_LIST(view_optional_parameters);
4095 else if (TailMatches("CREATE", "VIEW", MatchAny, "WITH", "(", "check_option") ||
4096 TailMatches("CREATE", "OR", "REPLACE", "VIEW", MatchAny, "WITH", "(", "check_option"))
4097 COMPLETE_WITH("=");
4098 else if (TailMatches("CREATE", "VIEW", MatchAny, "WITH", "(", "check_option", "=") ||
4099 TailMatches("CREATE", "OR", "REPLACE", "VIEW", MatchAny, "WITH", "(", "check_option", "="))
4100 COMPLETE_WITH("local", "cascaded");
4101 /* CREATE [ OR REPLACE ] VIEW <name> WITH ( ... ) AS */
4102 else if (TailMatches("CREATE", "VIEW", MatchAny, "WITH", "(*)") ||
4103 TailMatches("CREATE", "OR", "REPLACE", "VIEW", MatchAny, "WITH", "(*)"))
4104 COMPLETE_WITH("AS");
4105 /* CREATE [ OR REPLACE ] VIEW <name> WITH ( ... ) AS SELECT */
4106 else if (TailMatches("CREATE", "VIEW", MatchAny, "WITH", "(*)", "AS") ||
4107 TailMatches("CREATE", "OR", "REPLACE", "VIEW", MatchAny, "WITH", "(*)", "AS"))
4108 COMPLETE_WITH("SELECT");
4109
4110/* CREATE MATERIALIZED VIEW */
4111 else if (Matches("CREATE", "MATERIALIZED"))
4112 COMPLETE_WITH("VIEW");
4113 /* Complete CREATE MATERIALIZED VIEW <name> with AS or USING */
4114 else if (Matches("CREATE", "MATERIALIZED", "VIEW", MatchAny))
4115 COMPLETE_WITH("AS", "USING");
4116
4117 /*
4118 * Complete CREATE MATERIALIZED VIEW <name> USING with list of access
4119 * methods
4120 */
4121 else if (Matches("CREATE", "MATERIALIZED", "VIEW", MatchAny, "USING"))
4122 COMPLETE_WITH_QUERY(Query_for_list_of_table_access_methods);
4123 /* Complete CREATE MATERIALIZED VIEW <name> USING <access method> with AS */
4124 else if (Matches("CREATE", "MATERIALIZED", "VIEW", MatchAny, "USING", MatchAny))
4125 COMPLETE_WITH("AS");
4126
4127 /*
4128 * Complete CREATE MATERIALIZED VIEW <name> [USING <access method> ] AS
4129 * with "SELECT"
4130 */
4131 else if (Matches("CREATE", "MATERIALIZED", "VIEW", MatchAny, "AS") ||
4132 Matches("CREATE", "MATERIALIZED", "VIEW", MatchAny, "USING", MatchAny, "AS"))
4133 COMPLETE_WITH("SELECT");
4134
4135/* CREATE EVENT TRIGGER */
4136 else if (Matches("CREATE", "EVENT"))
4137 COMPLETE_WITH("TRIGGER");
4138 /* Complete CREATE EVENT TRIGGER <name> with ON */
4139 else if (Matches("CREATE", "EVENT", "TRIGGER", MatchAny))
4140 COMPLETE_WITH("ON");
4141 /* Complete CREATE EVENT TRIGGER <name> ON with event_type */
4142 else if (Matches("CREATE", "EVENT", "TRIGGER", MatchAny, "ON"))
4143 COMPLETE_WITH("ddl_command_start", "ddl_command_end", "login",
4144 "sql_drop", "table_rewrite");
4145
4146 /*
4147 * Complete CREATE EVENT TRIGGER <name> ON <event_type>. EXECUTE FUNCTION
4148 * is the recommended grammar instead of EXECUTE PROCEDURE in version 11
4149 * and upwards.
4150 */
4151 else if (Matches("CREATE", "EVENT", "TRIGGER", MatchAny, "ON", MatchAny))
4152 {
4153 if (pset.sversion >= 110000)
4154 COMPLETE_WITH("WHEN TAG IN (", "EXECUTE FUNCTION");
4155 else
4156 COMPLETE_WITH("WHEN TAG IN (", "EXECUTE PROCEDURE");
4157 }
4158 else if (Matches("CREATE", "EVENT", "TRIGGER", MatchAnyN, "WHEN|AND", MatchAny, "IN", "(*)"))
4159 {
4160 if (pset.sversion >= 110000)
4161 COMPLETE_WITH("EXECUTE FUNCTION");
4162 else
4163 COMPLETE_WITH("EXECUTE PROCEDURE");
4164 }
4165 else if (Matches("CREATE", "EVENT", "TRIGGER", MatchAnyN, "EXECUTE", "FUNCTION|PROCEDURE"))
4166 COMPLETE_WITH_VERSIONED_SCHEMA_QUERY(Query_for_list_of_functions);
4167
4168/* DEALLOCATE */
4169 else if (Matches("DEALLOCATE"))
4170 COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_prepared_statements,
4171 "ALL");
4172
4173/* DECLARE */
4174
4175 /*
4176 * Complete DECLARE <name> with one of BINARY, ASENSITIVE, INSENSITIVE,
4177 * SCROLL, NO SCROLL, and CURSOR.
4178 */
4179 else if (Matches("DECLARE", MatchAny))
4180 COMPLETE_WITH("BINARY", "ASENSITIVE", "INSENSITIVE", "SCROLL", "NO SCROLL",
4181 "CURSOR");
4182
4183 /*
4184 * Complete DECLARE ... <option> with other options. The PostgreSQL parser
4185 * allows DECLARE options to be specified in any order. But the
4186 * tab-completion follows the ordering of them that the SQL standard
4187 * provides, like the syntax of DECLARE command in the documentation
4188 * indicates.
4189 */
4190 else if (Matches("DECLARE", MatchAnyN, "BINARY"))
4191 COMPLETE_WITH("ASENSITIVE", "INSENSITIVE", "SCROLL", "NO SCROLL", "CURSOR");
4192 else if (Matches("DECLARE", MatchAnyN, "ASENSITIVE|INSENSITIVE"))
4193 COMPLETE_WITH("SCROLL", "NO SCROLL", "CURSOR");
4194 else if (Matches("DECLARE", MatchAnyN, "SCROLL"))
4195 COMPLETE_WITH("CURSOR");
4196 /* Complete DECLARE ... [options] NO with SCROLL */
4197 else if (Matches("DECLARE", MatchAnyN, "NO"))
4198 COMPLETE_WITH("SCROLL");
4199
4200 /*
4201 * Complete DECLARE ... CURSOR with one of WITH HOLD, WITHOUT HOLD, and
4202 * FOR
4203 */
4204 else if (Matches("DECLARE", MatchAnyN, "CURSOR"))
4205 COMPLETE_WITH("WITH HOLD", "WITHOUT HOLD", "FOR");
4206 /* Complete DECLARE ... CURSOR WITH|WITHOUT with HOLD */
4207 else if (Matches("DECLARE", MatchAnyN, "CURSOR", "WITH|WITHOUT"))
4208 COMPLETE_WITH("HOLD");
4209 /* Complete DECLARE ... CURSOR WITH|WITHOUT HOLD with FOR */
4210 else if (Matches("DECLARE", MatchAnyN, "CURSOR", "WITH|WITHOUT", "HOLD"))
4211 COMPLETE_WITH("FOR");
4212
4213/* DELETE --- can be inside EXPLAIN, RULE, etc */
4214 /* Complete DELETE with "FROM" */
4215 else if (Matches("DELETE"))
4216 COMPLETE_WITH("FROM");
4217 /* Complete DELETE FROM with a list of tables */
4218 else if (TailMatches("DELETE", "FROM"))
4219 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_updatables);
4220 /* Complete DELETE FROM <table> */
4221 else if (TailMatches("DELETE", "FROM", MatchAny))
4222 COMPLETE_WITH("USING", "WHERE");
4223 /* XXX: implement tab completion for DELETE ... USING */
4224
4225/* DISCARD */
4226 else if (Matches("DISCARD"))
4227 COMPLETE_WITH("ALL", "PLANS", "SEQUENCES", "TEMP");
4228
4229/* DO */
4230 else if (Matches("DO"))
4231 COMPLETE_WITH("LANGUAGE");
4232
4233/* DROP */
4234 /* Complete DROP object with CASCADE / RESTRICT */
4235 else if (Matches("DROP",
4236 "COLLATION|CONVERSION|DOMAIN|EXTENSION|LANGUAGE|PUBLICATION|SCHEMA|SEQUENCE|SERVER|SUBSCRIPTION|STATISTICS|TABLE|TYPE|VIEW",
4237 MatchAny) ||
4238 Matches("DROP", "ACCESS", "METHOD", MatchAny) ||
4239 Matches("DROP", "EVENT", "TRIGGER", MatchAny) ||
4240 Matches("DROP", "FOREIGN", "DATA", "WRAPPER", MatchAny) ||
4241 Matches("DROP", "FOREIGN", "TABLE", MatchAny) ||
4242 Matches("DROP", "TEXT", "SEARCH", "CONFIGURATION|DICTIONARY|PARSER|TEMPLATE", MatchAny))
4243 COMPLETE_WITH("CASCADE", "RESTRICT");
4244 else if (Matches("DROP", "AGGREGATE|FUNCTION|PROCEDURE|ROUTINE", MatchAny, MatchAny) &&
4245 ends_with(prev_wd, ')'))
4246 COMPLETE_WITH("CASCADE", "RESTRICT");
4247
4248 /* help completing some of the variants */
4249 else if (Matches("DROP", "AGGREGATE|FUNCTION|PROCEDURE|ROUTINE", MatchAny))
4250 COMPLETE_WITH("(");
4251 else if (Matches("DROP", "AGGREGATE|FUNCTION|PROCEDURE|ROUTINE", MatchAny, "("))
4252 COMPLETE_WITH_FUNCTION_ARG(prev2_wd);
4253 else if (Matches("DROP", "FOREIGN"))
4254 COMPLETE_WITH("DATA WRAPPER", "TABLE");
4255 else if (Matches("DROP", "DATABASE", MatchAny))
4256 COMPLETE_WITH("WITH (");
4257 else if (HeadMatches("DROP", "DATABASE") && (ends_with(prev_wd, '(')))
4258 COMPLETE_WITH("FORCE");
4259
4260 /* DROP INDEX */
4261 else if (Matches("DROP", "INDEX"))
4262 COMPLETE_WITH_SCHEMA_QUERY_PLUS(Query_for_list_of_indexes,
4263 "CONCURRENTLY");
4264 else if (Matches("DROP", "INDEX", "CONCURRENTLY"))
4265 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_indexes);
4266 else if (Matches("DROP", "INDEX", MatchAny))
4267 COMPLETE_WITH("CASCADE", "RESTRICT");
4268 else if (Matches("DROP", "INDEX", "CONCURRENTLY", MatchAny))
4269 COMPLETE_WITH("CASCADE", "RESTRICT");
4270
4271 /* DROP MATERIALIZED VIEW */
4272 else if (Matches("DROP", "MATERIALIZED"))
4273 COMPLETE_WITH("VIEW");
4274 else if (Matches("DROP", "MATERIALIZED", "VIEW"))
4275 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_matviews);
4276 else if (Matches("DROP", "MATERIALIZED", "VIEW", MatchAny))
4277 COMPLETE_WITH("CASCADE", "RESTRICT");
4278
4279 /* DROP OWNED BY */
4280 else if (Matches("DROP", "OWNED"))
4281 COMPLETE_WITH("BY");
4282 else if (Matches("DROP", "OWNED", "BY"))
4283 COMPLETE_WITH_QUERY(Query_for_list_of_roles);
4284 else if (Matches("DROP", "OWNED", "BY", MatchAny))
4285 COMPLETE_WITH("CASCADE", "RESTRICT");
4286
4287 /* DROP TEXT SEARCH */
4288 else if (Matches("DROP", "TEXT", "SEARCH"))
4289 COMPLETE_WITH("CONFIGURATION", "DICTIONARY", "PARSER", "TEMPLATE");
4290
4291 /* DROP TRIGGER */
4292 else if (Matches("DROP", "TRIGGER", MatchAny))
4293 COMPLETE_WITH("ON");
4294 else if (Matches("DROP", "TRIGGER", MatchAny, "ON"))
4295 {
4296 set_completion_reference(prev2_wd);
4297 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables_for_trigger);
4298 }
4299 else if (Matches("DROP", "TRIGGER", MatchAny, "ON", MatchAny))
4300 COMPLETE_WITH("CASCADE", "RESTRICT");
4301
4302 /* DROP ACCESS METHOD */
4303 else if (Matches("DROP", "ACCESS"))
4304 COMPLETE_WITH("METHOD");
4305 else if (Matches("DROP", "ACCESS", "METHOD"))
4306 COMPLETE_WITH_QUERY(Query_for_list_of_access_methods);
4307
4308 /* DROP EVENT TRIGGER */
4309 else if (Matches("DROP", "EVENT"))
4310 COMPLETE_WITH("TRIGGER");
4311 else if (Matches("DROP", "EVENT", "TRIGGER"))
4312 COMPLETE_WITH_QUERY(Query_for_list_of_event_triggers);
4313
4314 /* DROP POLICY <name> */
4315 else if (Matches("DROP", "POLICY"))
4316 COMPLETE_WITH_QUERY(Query_for_list_of_policies);
4317 /* DROP POLICY <name> ON */
4318 else if (Matches("DROP", "POLICY", MatchAny))
4319 COMPLETE_WITH("ON");
4320 /* DROP POLICY <name> ON <table> */
4321 else if (Matches("DROP", "POLICY", MatchAny, "ON"))
4322 {
4323 set_completion_reference(prev2_wd);
4324 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables_for_policy);
4325 }
4326 else if (Matches("DROP", "POLICY", MatchAny, "ON", MatchAny))
4327 COMPLETE_WITH("CASCADE", "RESTRICT");
4328
4329 /* DROP RULE */
4330 else if (Matches("DROP", "RULE", MatchAny))
4331 COMPLETE_WITH("ON");
4332 else if (Matches("DROP", "RULE", MatchAny, "ON"))
4333 {
4334 set_completion_reference(prev2_wd);
4335 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables_for_rule);
4336 }
4337 else if (Matches("DROP", "RULE", MatchAny, "ON", MatchAny))
4338 COMPLETE_WITH("CASCADE", "RESTRICT");
4339
4340 /* DROP TRANSFORM */
4341 else if (Matches("DROP", "TRANSFORM"))
4342 COMPLETE_WITH("FOR");
4343 else if (Matches("DROP", "TRANSFORM", "FOR"))
4344 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_datatypes);
4345 else if (Matches("DROP", "TRANSFORM", "FOR", MatchAny))
4346 COMPLETE_WITH("LANGUAGE");
4347 else if (Matches("DROP", "TRANSFORM", "FOR", MatchAny, "LANGUAGE"))
4348 {
4349 set_completion_reference(prev2_wd);
4350 COMPLETE_WITH_QUERY(Query_for_list_of_languages);
4351 }
4352 else if (Matches("DROP", "TRANSFORM", "FOR", MatchAny, "LANGUAGE", MatchAny))
4353 COMPLETE_WITH("CASCADE", "RESTRICT");
4354
4355/* EXECUTE */
4356 else if (Matches("EXECUTE"))
4357 COMPLETE_WITH_QUERY(Query_for_list_of_prepared_statements);
4358
4359/*
4360 * EXPLAIN [ ( option [, ...] ) ] statement
4361 * EXPLAIN [ ANALYZE ] [ VERBOSE ] statement
4362 */
4363 else if (Matches("EXPLAIN"))
4364 COMPLETE_WITH("SELECT", "INSERT INTO", "DELETE FROM", "UPDATE", "DECLARE",
4365 "MERGE INTO", "EXECUTE", "ANALYZE", "VERBOSE");
4366 else if (HeadMatches("EXPLAIN", "(*") &&
4367 !HeadMatches("EXPLAIN", "(*)"))
4368 {
4369 /*
4370 * This fires if we're in an unfinished parenthesized option list.
4371 * get_previous_words treats a completed parenthesized option list as
4372 * one word, so the above test is correct.
4373 */
4374 if (ends_with(prev_wd, '(') || ends_with(prev_wd, ','))
4375 COMPLETE_WITH("ANALYZE", "VERBOSE", "COSTS", "SETTINGS", "GENERIC_PLAN",
4376 "BUFFERS", "SERIALIZE", "WAL", "TIMING", "SUMMARY",
4377 "MEMORY", "FORMAT");
4378 else if (TailMatches("ANALYZE|VERBOSE|COSTS|SETTINGS|GENERIC_PLAN|BUFFERS|WAL|TIMING|SUMMARY|MEMORY"))
4379 COMPLETE_WITH("ON", "OFF");
4380 else if (TailMatches("SERIALIZE"))
4381 COMPLETE_WITH("TEXT", "NONE", "BINARY");
4382 else if (TailMatches("FORMAT"))
4383 COMPLETE_WITH("TEXT", "XML", "JSON", "YAML");
4384 }
4385 else if (Matches("EXPLAIN", "ANALYZE"))
4386 COMPLETE_WITH("SELECT", "INSERT INTO", "DELETE FROM", "UPDATE", "DECLARE",
4387 "MERGE INTO", "EXECUTE", "VERBOSE");
4388 else if (Matches("EXPLAIN", "(*)") ||
4389 Matches("EXPLAIN", "VERBOSE") ||
4390 Matches("EXPLAIN", "ANALYZE", "VERBOSE"))
4391 COMPLETE_WITH("SELECT", "INSERT INTO", "DELETE FROM", "UPDATE", "DECLARE",
4392 "MERGE INTO", "EXECUTE");
4393
4394/* FETCH && MOVE */
4395
4396 /*
4397 * Complete FETCH with one of ABSOLUTE, BACKWARD, FORWARD, RELATIVE, ALL,
4398 * NEXT, PRIOR, FIRST, LAST, FROM, IN, and a list of cursors
4399 */
4400 else if (Matches("FETCH|MOVE"))
4401 COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_cursors,
4402 "ABSOLUTE",
4403 "BACKWARD",
4404 "FORWARD",
4405 "RELATIVE",
4406 "ALL",
4407 "NEXT",
4408 "PRIOR",
4409 "FIRST",
4410 "LAST",
4411 "FROM",
4412 "IN");
4413
4414 /*
4415 * Complete FETCH BACKWARD or FORWARD with one of ALL, FROM, IN, and a
4416 * list of cursors
4417 */
4418 else if (Matches("FETCH|MOVE", "BACKWARD|FORWARD"))
4419 COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_cursors,
4420 "ALL",
4421 "FROM",
4422 "IN");
4423
4424 /*
4425 * Complete FETCH <direction> with "FROM" or "IN". These are equivalent,
4426 * but we may as well tab-complete both: perhaps some users prefer one
4427 * variant or the other.
4428 */
4429 else if (Matches("FETCH|MOVE", "ABSOLUTE|BACKWARD|FORWARD|RELATIVE",
4430 MatchAnyExcept("FROM|IN")) ||
4431 Matches("FETCH|MOVE", "ALL|NEXT|PRIOR|FIRST|LAST"))
4432 COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_cursors,
4433 "FROM",
4434 "IN");
4435 /* Complete FETCH <direction> "FROM" or "IN" with a list of cursors */
4436 else if (Matches("FETCH|MOVE", MatchAnyN, "FROM|IN"))
4437 COMPLETE_WITH_QUERY(Query_for_list_of_cursors);
4438
4439/* FOREIGN DATA WRAPPER */
4440 /* applies in ALTER/DROP FDW and in CREATE SERVER */
4441 else if (TailMatches("FOREIGN", "DATA", "WRAPPER") &&
4442 !TailMatches("CREATE", MatchAny, MatchAny, MatchAny))
4443 COMPLETE_WITH_QUERY(Query_for_list_of_fdws);
4444 /* applies in CREATE SERVER */
4445 else if (Matches("CREATE", "SERVER", MatchAnyN, "FOREIGN", "DATA", "WRAPPER", MatchAny))
4446 COMPLETE_WITH("OPTIONS");
4447
4448/* FOREIGN TABLE */
4449 else if (TailMatches("FOREIGN", "TABLE") &&
4450 !TailMatches("CREATE", MatchAny, MatchAny))
4451 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_foreign_tables);
4452
4453/* FOREIGN SERVER */
4454 else if (TailMatches("FOREIGN", "SERVER"))
4455 COMPLETE_WITH_QUERY(Query_for_list_of_servers);
4456
4457/*
4458 * GRANT and REVOKE are allowed inside CREATE SCHEMA and
4459 * ALTER DEFAULT PRIVILEGES, so use TailMatches
4460 */
4461 /* Complete GRANT/REVOKE with a list of roles and privileges */
4462 else if (TailMatches("GRANT|REVOKE") ||
4463 TailMatches("REVOKE", "ADMIN|GRANT|INHERIT|SET", "OPTION", "FOR"))
4464 {
4465 /*
4466 * With ALTER DEFAULT PRIVILEGES, restrict completion to grantable
4467 * privileges (can't grant roles)
4468 */
4469 if (HeadMatches("ALTER", "DEFAULT", "PRIVILEGES"))
4470 {
4471 if (TailMatches("GRANT") ||
4472 TailMatches("REVOKE", "GRANT", "OPTION", "FOR"))
4473 COMPLETE_WITH("SELECT", "INSERT", "UPDATE",
4474 "DELETE", "TRUNCATE", "REFERENCES", "TRIGGER",
4475 "CREATE", "EXECUTE", "USAGE", "MAINTAIN", "ALL");
4476 else if (TailMatches("REVOKE"))
4477 COMPLETE_WITH("SELECT", "INSERT", "UPDATE",
4478 "DELETE", "TRUNCATE", "REFERENCES", "TRIGGER",
4479 "CREATE", "EXECUTE", "USAGE", "MAINTAIN", "ALL",
4480 "GRANT OPTION FOR");
4481 }
4482 else if (TailMatches("GRANT"))
4483 COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_roles,
4484 Privilege_options_of_grant_and_revoke);
4485 else if (TailMatches("REVOKE"))
4486 COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_roles,
4487 Privilege_options_of_grant_and_revoke,
4488 "GRANT OPTION FOR",
4489 "ADMIN OPTION FOR",
4490 "INHERIT OPTION FOR",
4491 "SET OPTION FOR");
4492 else if (TailMatches("REVOKE", "GRANT", "OPTION", "FOR"))
4493 COMPLETE_WITH(Privilege_options_of_grant_and_revoke);
4494 else if (TailMatches("REVOKE", "ADMIN|INHERIT|SET", "OPTION", "FOR"))
4495 COMPLETE_WITH_QUERY(Query_for_list_of_roles);
4496 }
4497
4498 else if (TailMatches("GRANT|REVOKE", "ALTER") ||
4499 TailMatches("REVOKE", "GRANT", "OPTION", "FOR", "ALTER"))
4500 COMPLETE_WITH("SYSTEM");
4501
4502 else if (TailMatches("REVOKE", "SET"))
4503 COMPLETE_WITH("ON PARAMETER", "OPTION FOR");
4504 else if (TailMatches("GRANT", "SET") ||
4505 TailMatches("REVOKE", "GRANT", "OPTION", "FOR", "SET") ||
4506 TailMatches("GRANT|REVOKE", "ALTER", "SYSTEM") ||
4507 TailMatches("REVOKE", "GRANT", "OPTION", "FOR", "ALTER", "SYSTEM"))
4508 COMPLETE_WITH("ON PARAMETER");
4509
4510 else if (TailMatches("GRANT|REVOKE", MatchAny, "ON", "PARAMETER") ||
4511 TailMatches("GRANT|REVOKE", MatchAny, MatchAny, "ON", "PARAMETER") ||
4512 TailMatches("REVOKE", "GRANT", "OPTION", "FOR", MatchAny, "ON", "PARAMETER") ||
4513 TailMatches("REVOKE", "GRANT", "OPTION", "FOR", MatchAny, MatchAny, "ON", "PARAMETER"))
4514 COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_alter_system_set_vars);
4515
4516 else if (TailMatches("GRANT", MatchAny, "ON", "PARAMETER", MatchAny) ||
4517 TailMatches("GRANT", MatchAny, MatchAny, "ON", "PARAMETER", MatchAny))
4518 COMPLETE_WITH("TO");
4519
4520 else if (TailMatches("REVOKE", MatchAny, "ON", "PARAMETER", MatchAny) ||
4521 TailMatches("REVOKE", MatchAny, MatchAny, "ON", "PARAMETER", MatchAny) ||
4522 TailMatches("REVOKE", "GRANT", "OPTION", "FOR", MatchAny, "ON", "PARAMETER", MatchAny) ||
4523 TailMatches("REVOKE", "GRANT", "OPTION", "FOR", MatchAny, MatchAny, "ON", "PARAMETER", MatchAny))
4524 COMPLETE_WITH("FROM");
4525
4526 /*
4527 * Complete GRANT/REVOKE <privilege> with "ON", GRANT/REVOKE <role> with
4528 * TO/FROM
4529 */
4530 else if (TailMatches("GRANT|REVOKE", MatchAny) ||
4531 TailMatches("REVOKE", "GRANT", "OPTION", "FOR", MatchAny))
4532 {
4533 if (TailMatches("SELECT|INSERT|UPDATE|DELETE|TRUNCATE|REFERENCES|TRIGGER|CREATE|CONNECT|TEMPORARY|TEMP|EXECUTE|USAGE|MAINTAIN|ALL"))
4534 COMPLETE_WITH("ON");
4535 else if (TailMatches("GRANT", MatchAny))
4536 COMPLETE_WITH("TO");
4537 else
4538 COMPLETE_WITH("FROM");
4539 }
4540
4541 /*
4542 * Complete GRANT/REVOKE <sth> ON with a list of appropriate relations.
4543 *
4544 * Note: GRANT/REVOKE can get quite complex; tab-completion as implemented
4545 * here will only work if the privilege list contains exactly one
4546 * privilege.
4547 */
4548 else if (TailMatches("GRANT|REVOKE", MatchAny, "ON") ||
4549 TailMatches("REVOKE", "GRANT", "OPTION", "FOR", MatchAny, "ON"))
4550 {
4551 /*
4552 * With ALTER DEFAULT PRIVILEGES, restrict completion to the kinds of
4553 * objects supported.
4554 */
4555 if (HeadMatches("ALTER", "DEFAULT", "PRIVILEGES"))
4556 COMPLETE_WITH("TABLES", "SEQUENCES", "FUNCTIONS", "PROCEDURES", "ROUTINES", "TYPES", "SCHEMAS", "LARGE OBJECTS");
4557 else
4558 COMPLETE_WITH_SCHEMA_QUERY_PLUS(Query_for_list_of_grantables,
4559 "ALL FUNCTIONS IN SCHEMA",
4560 "ALL PROCEDURES IN SCHEMA",
4561 "ALL ROUTINES IN SCHEMA",
4562 "ALL SEQUENCES IN SCHEMA",
4563 "ALL TABLES IN SCHEMA",
4564 "DATABASE",
4565 "DOMAIN",
4566 "FOREIGN DATA WRAPPER",
4567 "FOREIGN SERVER",
4568 "FUNCTION",
4569 "LANGUAGE",
4570 "LARGE OBJECT",
4571 "PARAMETER",
4572 "PROCEDURE",
4573 "ROUTINE",
4574 "SCHEMA",
4575 "SEQUENCE",
4576 "TABLE",
4577 "TABLESPACE",
4578 "TYPE");
4579 }
4580 else if (TailMatches("GRANT|REVOKE", MatchAny, "ON", "ALL") ||
4581 TailMatches("REVOKE", "GRANT", "OPTION", "FOR", MatchAny, "ON", "ALL"))
4582 COMPLETE_WITH("FUNCTIONS IN SCHEMA",
4583 "PROCEDURES IN SCHEMA",
4584 "ROUTINES IN SCHEMA",
4585 "SEQUENCES IN SCHEMA",
4586 "TABLES IN SCHEMA");
4587
4588 /*
4589 * Complete "GRANT/REVOKE * ON DATABASE/DOMAIN/..." with a list of
4590 * appropriate objects or keywords.
4591 *
4592 * Complete "GRANT/REVOKE * ON *" with "TO/FROM".
4593 */
4594 else if (TailMatches("GRANT|REVOKE", MatchAny, "ON", MatchAny) ||
4595 TailMatches("REVOKE", "GRANT", "OPTION", "FOR", MatchAny, "ON", MatchAny))
4596 {
4597 if (TailMatches("DATABASE"))
4598 COMPLETE_WITH_QUERY(Query_for_list_of_databases);
4599 else if (TailMatches("DOMAIN"))
4600 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_domains);
4601 else if (TailMatches("FUNCTION"))
4602 COMPLETE_WITH_VERSIONED_SCHEMA_QUERY(Query_for_list_of_functions);
4603 else if (TailMatches("FOREIGN"))
4604 COMPLETE_WITH("DATA WRAPPER", "SERVER");
4605 else if (TailMatches("LANGUAGE"))
4606 COMPLETE_WITH_QUERY(Query_for_list_of_languages);
4607 else if (TailMatches("LARGE"))
4608 {
4609 if (HeadMatches("ALTER", "DEFAULT", "PRIVILEGES"))
4610 COMPLETE_WITH("OBJECTS");
4611 else
4612 COMPLETE_WITH("OBJECT");
4613 }
4614 else if (TailMatches("PROCEDURE"))
4615 COMPLETE_WITH_VERSIONED_SCHEMA_QUERY(Query_for_list_of_procedures);
4616 else if (TailMatches("ROUTINE"))
4617 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_routines);
4618 else if (TailMatches("SCHEMA"))
4619 COMPLETE_WITH_QUERY(Query_for_list_of_schemas);
4620 else if (TailMatches("SEQUENCE"))
4621 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_sequences);
4622 else if (TailMatches("TABLE"))
4623 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_grantables);
4624 else if (TailMatches("TABLESPACE"))
4625 COMPLETE_WITH_QUERY(Query_for_list_of_tablespaces);
4626 else if (TailMatches("TYPE"))
4627 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_datatypes);
4628 else if (TailMatches("GRANT", MatchAny, MatchAny, MatchAny))
4629 COMPLETE_WITH("TO");
4630 else
4631 COMPLETE_WITH("FROM");
4632 }
4633
4634 /*
4635 * Complete "GRANT/REVOKE ... TO/FROM" with username, PUBLIC,
4636 * CURRENT_ROLE, CURRENT_USER, or SESSION_USER.
4637 */
4638 else if (Matches("GRANT", MatchAnyN, "TO") ||
4639 Matches("REVOKE", MatchAnyN, "FROM"))
4640 COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_roles,
4641 Keywords_for_list_of_grant_roles);
4642
4643 /*
4644 * Offer grant options after that.
4645 */
4646 else if (Matches("GRANT", MatchAnyN, "TO", MatchAny))
4647 COMPLETE_WITH("WITH ADMIN",
4648 "WITH INHERIT",
4649 "WITH SET",
4650 "WITH GRANT OPTION",
4651 "GRANTED BY");
4652 else if (Matches("GRANT", MatchAnyN, "TO", MatchAny, "WITH"))
4653 COMPLETE_WITH("ADMIN",
4654 "INHERIT",
4655 "SET",
4656 "GRANT OPTION");
4657 else if (Matches("GRANT", MatchAnyN, "TO", MatchAny, "WITH", "ADMIN|INHERIT|SET"))
4658 COMPLETE_WITH("OPTION", "TRUE", "FALSE");
4659 else if (Matches("GRANT", MatchAnyN, "TO", MatchAny, "WITH", MatchAny, "OPTION"))
4660 COMPLETE_WITH("GRANTED BY");
4661 else if (Matches("GRANT", MatchAnyN, "TO", MatchAny, "WITH", MatchAny, "OPTION", "GRANTED", "BY"))
4662 COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_roles,
4663 Keywords_for_list_of_grant_roles);
4664 /* Complete "ALTER DEFAULT PRIVILEGES ... GRANT/REVOKE ... TO/FROM */
4665 else if (Matches("ALTER", "DEFAULT", "PRIVILEGES", MatchAnyN, "TO|FROM"))
4666 COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_roles,
4667 Keywords_for_list_of_grant_roles);
4668 /* Offer WITH GRANT OPTION after that */
4669 else if (Matches("ALTER", "DEFAULT", "PRIVILEGES", MatchAnyN, "TO", MatchAny))
4670 COMPLETE_WITH("WITH GRANT OPTION");
4671 /* Complete "GRANT/REVOKE ... ON * *" with TO/FROM */
4672 else if (Matches("GRANT|REVOKE", MatchAnyN, "ON", MatchAny, MatchAny) &&
4673 !TailMatches("FOREIGN", "SERVER") && !TailMatches("LARGE", "OBJECT"))
4674 {
4675 if (Matches("GRANT", MatchAnyN, "ON", MatchAny, MatchAny))
4676 COMPLETE_WITH("TO");
4677 else
4678 COMPLETE_WITH("FROM");
4679 }
4680
4681 /* Complete "GRANT/REVOKE * ON ALL * IN SCHEMA *" with TO/FROM */
4682 else if (TailMatches("GRANT|REVOKE", MatchAny, "ON", "ALL", MatchAny, "IN", "SCHEMA", MatchAny) ||
4683 TailMatches("REVOKE", "GRANT", "OPTION", "FOR", MatchAny, "ON", "ALL", MatchAny, "IN", "SCHEMA", MatchAny))
4684 {
4685 if (TailMatches("GRANT", MatchAny, MatchAny, MatchAny, MatchAny, MatchAny, MatchAny, MatchAny))
4686 COMPLETE_WITH("TO");
4687 else
4688 COMPLETE_WITH("FROM");
4689 }
4690
4691 /* Complete "GRANT/REVOKE * ON FOREIGN DATA WRAPPER *" with TO/FROM */
4692 else if (TailMatches("GRANT|REVOKE", MatchAny, "ON", "FOREIGN", "DATA", "WRAPPER", MatchAny) ||
4693 TailMatches("REVOKE", "GRANT", "OPTION", "FOR", MatchAny, "ON", "FOREIGN", "DATA", "WRAPPER", MatchAny))
4694 {
4695 if (TailMatches("GRANT", MatchAny, MatchAny, MatchAny, MatchAny, MatchAny, MatchAny))
4696 COMPLETE_WITH("TO");
4697 else
4698 COMPLETE_WITH("FROM");
4699 }
4700
4701 /* Complete "GRANT/REVOKE * ON FOREIGN SERVER *" with TO/FROM */
4702 else if (TailMatches("GRANT|REVOKE", MatchAny, "ON", "FOREIGN", "SERVER", MatchAny) ||
4703 TailMatches("REVOKE", "GRANT", "OPTION", "FOR", MatchAny, "ON", "FOREIGN", "SERVER", MatchAny))
4704 {
4705 if (TailMatches("GRANT", MatchAny, MatchAny, MatchAny, MatchAny, MatchAny))
4706 COMPLETE_WITH("TO");
4707 else
4708 COMPLETE_WITH("FROM");
4709 }
4710
4711 /* Complete "GRANT/REVOKE * ON LARGE OBJECT *" with TO/FROM */
4712 else if (TailMatches("GRANT|REVOKE", MatchAny, "ON", "LARGE", "OBJECT", MatchAny) ||
4713 TailMatches("REVOKE", "GRANT", "OPTION", "FOR", MatchAny, "ON", "LARGE", "OBJECT", MatchAny))
4714 {
4715 if (TailMatches("GRANT", MatchAny, MatchAny, MatchAny, MatchAny, MatchAny))
4716 COMPLETE_WITH("TO");
4717 else
4718 COMPLETE_WITH("FROM");
4719 }
4720
4721 /* Complete "GRANT/REVOKE * ON LARGE OBJECTS" with TO/FROM */
4722 else if (TailMatches("GRANT|REVOKE", MatchAny, "ON", "LARGE", "OBJECTS") ||
4723 TailMatches("REVOKE", "GRANT", "OPTION", "FOR", MatchAny, "ON", "LARGE", "OBJECTS"))
4724 {
4725 if (TailMatches("GRANT", MatchAny, MatchAny, MatchAny, MatchAny))
4726 COMPLETE_WITH("TO");
4727 else
4728 COMPLETE_WITH("FROM");
4729 }
4730
4731/* GROUP BY */
4732 else if (TailMatches("FROM", MatchAny, "GROUP"))
4733 COMPLETE_WITH("BY");
4734
4735/* IMPORT FOREIGN SCHEMA */
4736 else if (Matches("IMPORT"))
4737 COMPLETE_WITH("FOREIGN SCHEMA");
4738 else if (Matches("IMPORT", "FOREIGN"))
4739 COMPLETE_WITH("SCHEMA");
4740 else if (Matches("IMPORT", "FOREIGN", "SCHEMA", MatchAny))
4741 COMPLETE_WITH("EXCEPT (", "FROM SERVER", "LIMIT TO (");
4742 else if (TailMatches("LIMIT", "TO", "(*)") ||
4743 TailMatches("EXCEPT", "(*)"))
4744 COMPLETE_WITH("FROM SERVER");
4745 else if (TailMatches("FROM", "SERVER", MatchAny))
4746 COMPLETE_WITH("INTO");
4747 else if (TailMatches("FROM", "SERVER", MatchAny, "INTO"))
4748 COMPLETE_WITH_QUERY(Query_for_list_of_schemas);
4749 else if (TailMatches("FROM", "SERVER", MatchAny, "INTO", MatchAny))
4750 COMPLETE_WITH("OPTIONS (");
4751
4752/* INSERT --- can be inside EXPLAIN, RULE, etc */
4753 /* Complete NOT MATCHED THEN INSERT */
4754 else if (TailMatches("NOT", "MATCHED", "THEN", "INSERT"))
4755 COMPLETE_WITH("VALUES", "(");
4756 /* Complete INSERT with "INTO" */
4757 else if (TailMatches("INSERT"))
4758 COMPLETE_WITH("INTO");
4759 /* Complete INSERT INTO with table names */
4760 else if (TailMatches("INSERT", "INTO"))
4761 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_updatables);
4762 /* Complete "INSERT INTO <table> (" with attribute names */
4763 else if (TailMatches("INSERT", "INTO", MatchAny, "("))
4764 COMPLETE_WITH_ATTR(prev2_wd);
4765
4766 /*
4767 * Complete INSERT INTO <table> with "(" or "VALUES" or "SELECT" or
4768 * "TABLE" or "DEFAULT VALUES" or "OVERRIDING"
4769 */
4770 else if (TailMatches("INSERT", "INTO", MatchAny))
4771 COMPLETE_WITH("(", "DEFAULT VALUES", "SELECT", "TABLE", "VALUES", "OVERRIDING");
4772
4773 /*
4774 * Complete INSERT INTO <table> (attribs) with "VALUES" or "SELECT" or
4775 * "TABLE" or "OVERRIDING"
4776 */
4777 else if (TailMatches("INSERT", "INTO", MatchAny, MatchAny) &&
4778 ends_with(prev_wd, ')'))
4779 COMPLETE_WITH("SELECT", "TABLE", "VALUES", "OVERRIDING");
4780
4781 /* Complete OVERRIDING */
4782 else if (TailMatches("OVERRIDING"))
4783 COMPLETE_WITH("SYSTEM VALUE", "USER VALUE");
4784
4785 /* Complete after OVERRIDING clause */
4786 else if (TailMatches("OVERRIDING", MatchAny, "VALUE"))
4787 COMPLETE_WITH("SELECT", "TABLE", "VALUES");
4788
4789 /* Insert an open parenthesis after "VALUES" */
4790 else if (TailMatches("VALUES") && !TailMatches("DEFAULT", "VALUES"))
4791 COMPLETE_WITH("(");
4792
4793/* LOCK */
4794 /* Complete LOCK [TABLE] [ONLY] with a list of tables */
4795 else if (Matches("LOCK"))
4796 COMPLETE_WITH_SCHEMA_QUERY_PLUS(Query_for_list_of_tables,
4797 "TABLE", "ONLY");
4798 else if (Matches("LOCK", "TABLE"))
4799 COMPLETE_WITH_SCHEMA_QUERY_PLUS(Query_for_list_of_tables,
4800 "ONLY");
4801 else if (Matches("LOCK", "TABLE", "ONLY") || Matches("LOCK", "ONLY"))
4802 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables);
4803 /* For the following, handle the case of a single table only for now */
4804
4805 /* Complete LOCK [TABLE] [ONLY] <table> with IN or NOWAIT */
4806 else if (Matches("LOCK", MatchAnyExcept("TABLE|ONLY")) ||
4807 Matches("LOCK", "TABLE", MatchAnyExcept("ONLY")) ||
4808 Matches("LOCK", "ONLY", MatchAny) ||
4809 Matches("LOCK", "TABLE", "ONLY", MatchAny))
4810 COMPLETE_WITH("IN", "NOWAIT");
4811
4812 /* Complete LOCK [TABLE] [ONLY] <table> IN with a lock mode */
4813 else if (Matches("LOCK", MatchAnyN, "IN"))
4814 COMPLETE_WITH("ACCESS SHARE MODE",
4815 "ROW SHARE MODE", "ROW EXCLUSIVE MODE",
4816 "SHARE UPDATE EXCLUSIVE MODE", "SHARE MODE",
4817 "SHARE ROW EXCLUSIVE MODE",
4818 "EXCLUSIVE MODE", "ACCESS EXCLUSIVE MODE");
4819
4820 /*
4821 * Complete LOCK [TABLE][ONLY] <table> IN ACCESS|ROW with rest of lock
4822 * mode
4823 */
4824 else if (Matches("LOCK", MatchAnyN, "IN", "ACCESS|ROW"))
4825 COMPLETE_WITH("EXCLUSIVE MODE", "SHARE MODE");
4826
4827 /* Complete LOCK [TABLE] [ONLY] <table> IN SHARE with rest of lock mode */
4828 else if (Matches("LOCK", MatchAnyN, "IN", "SHARE"))
4829 COMPLETE_WITH("MODE", "ROW EXCLUSIVE MODE",
4830 "UPDATE EXCLUSIVE MODE");
4831
4832 /* Complete LOCK [TABLE] [ONLY] <table> [IN lockmode MODE] with "NOWAIT" */
4833 else if (Matches("LOCK", MatchAnyN, "MODE"))
4834 COMPLETE_WITH("NOWAIT");
4835
4836/* MERGE --- can be inside EXPLAIN */
4837 else if (TailMatches("MERGE"))
4838 COMPLETE_WITH("INTO");
4839 else if (TailMatches("MERGE", "INTO"))
4840 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_mergetargets);
4841
4842 /* Complete MERGE INTO <table> [[AS] <alias>] with USING */
4843 else if (TailMatches("MERGE", "INTO", MatchAny))
4844 COMPLETE_WITH("USING", "AS");
4845 else if (TailMatches("MERGE", "INTO", MatchAny, "AS", MatchAny) ||
4846 TailMatches("MERGE", "INTO", MatchAny, MatchAnyExcept("USING|AS")))
4847 COMPLETE_WITH("USING");
4848
4849 /*
4850 * Complete MERGE INTO ... USING with a list of relations supporting
4851 * SELECT
4852 */
4853 else if (TailMatches("MERGE", "INTO", MatchAny, "USING") ||
4854 TailMatches("MERGE", "INTO", MatchAny, "AS", MatchAny, "USING") ||
4855 TailMatches("MERGE", "INTO", MatchAny, MatchAny, "USING"))
4856 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_selectables);
4857
4858 /*
4859 * Complete MERGE INTO <table> [[AS] <alias>] USING <relations> [[AS]
4860 * alias] with ON
4861 */
4862 else if (TailMatches("MERGE", "INTO", MatchAny, "USING", MatchAny) ||
4863 TailMatches("MERGE", "INTO", MatchAny, "AS", MatchAny, "USING", MatchAny) ||
4864 TailMatches("MERGE", "INTO", MatchAny, MatchAny, "USING", MatchAny))
4865 COMPLETE_WITH("AS", "ON");
4866 else if (TailMatches("MERGE", "INTO", MatchAny, "USING", MatchAny, "AS", MatchAny) ||
4867 TailMatches("MERGE", "INTO", MatchAny, "AS", MatchAny, "USING", MatchAny, "AS", MatchAny) ||
4868 TailMatches("MERGE", "INTO", MatchAny, MatchAny, "USING", MatchAny, "AS", MatchAny) ||
4869 TailMatches("MERGE", "INTO", MatchAny, "USING", MatchAny, MatchAnyExcept("ON|AS")) ||
4870 TailMatches("MERGE", "INTO", MatchAny, "AS", MatchAny, "USING", MatchAny, MatchAnyExcept("ON|AS")) ||
4871 TailMatches("MERGE", "INTO", MatchAny, MatchAny, "USING", MatchAny, MatchAnyExcept("ON|AS")))
4872 COMPLETE_WITH("ON");
4873
4874 /* Complete MERGE INTO ... ON with target table attributes */
4875 else if (TailMatches("INTO", MatchAny, "USING", MatchAny, "ON"))
4876 COMPLETE_WITH_ATTR(prev4_wd);
4877 else if (TailMatches("INTO", MatchAny, "AS", MatchAny, "USING", MatchAny, "AS", MatchAny, "ON"))
4878 COMPLETE_WITH_ATTR(prev8_wd);
4879 else if (TailMatches("INTO", MatchAny, MatchAny, "USING", MatchAny, MatchAny, "ON"))
4880 COMPLETE_WITH_ATTR(prev6_wd);
4881
4882 /*
4883 * Complete ... USING <relation> [[AS] alias] ON join condition
4884 * (consisting of one or three words typically used) with WHEN [NOT]
4885 * MATCHED
4886 */
4887 else if (TailMatches("USING", MatchAny, "ON", MatchAny) ||
4888 TailMatches("USING", MatchAny, "AS", MatchAny, "ON", MatchAny) ||
4889 TailMatches("USING", MatchAny, MatchAny, "ON", MatchAny) ||
4890 TailMatches("USING", MatchAny, "ON", MatchAny, MatchAnyExcept("WHEN"), MatchAnyExcept("WHEN")) ||
4891 TailMatches("USING", MatchAny, "AS", MatchAny, "ON", MatchAny, MatchAnyExcept("WHEN"), MatchAnyExcept("WHEN")) ||
4892 TailMatches("USING", MatchAny, MatchAny, "ON", MatchAny, MatchAnyExcept("WHEN"), MatchAnyExcept("WHEN")))
4893 COMPLETE_WITH("WHEN MATCHED", "WHEN NOT MATCHED");
4894 else if (TailMatches("USING", MatchAny, "ON", MatchAny, "WHEN") ||
4895 TailMatches("USING", MatchAny, "AS", MatchAny, "ON", MatchAny, "WHEN") ||
4896 TailMatches("USING", MatchAny, MatchAny, "ON", MatchAny, "WHEN") ||
4897 TailMatches("USING", MatchAny, "ON", MatchAny, MatchAny, MatchAny, "WHEN") ||
4898 TailMatches("USING", MatchAny, "AS", MatchAny, "ON", MatchAny, MatchAny, MatchAny, "WHEN") ||
4899 TailMatches("USING", MatchAny, MatchAny, "ON", MatchAny, MatchAny, MatchAny, "WHEN"))
4900 COMPLETE_WITH("MATCHED", "NOT MATCHED");
4901
4902 /*
4903 * Complete ... WHEN MATCHED and WHEN NOT MATCHED BY SOURCE|TARGET with
4904 * THEN/AND
4905 */
4906 else if (TailMatches("WHEN", "MATCHED") ||
4907 TailMatches("WHEN", "NOT", "MATCHED", "BY", "SOURCE|TARGET"))
4908 COMPLETE_WITH("THEN", "AND");
4909
4910 /* Complete ... WHEN NOT MATCHED with BY/THEN/AND */
4911 else if (TailMatches("WHEN", "NOT", "MATCHED"))
4912 COMPLETE_WITH("BY", "THEN", "AND");
4913
4914 /* Complete ... WHEN NOT MATCHED BY with SOURCE/TARGET */
4915 else if (TailMatches("WHEN", "NOT", "MATCHED", "BY"))
4916 COMPLETE_WITH("SOURCE", "TARGET");
4917
4918 /*
4919 * Complete ... WHEN MATCHED THEN and WHEN NOT MATCHED BY SOURCE THEN with
4920 * UPDATE SET/DELETE/DO NOTHING
4921 */
4922 else if (TailMatches("WHEN", "MATCHED", "THEN") ||
4923 TailMatches("WHEN", "NOT", "MATCHED", "BY", "SOURCE", "THEN"))
4924 COMPLETE_WITH("UPDATE SET", "DELETE", "DO NOTHING");
4925
4926 /*
4927 * Complete ... WHEN NOT MATCHED [BY TARGET] THEN with INSERT/DO NOTHING
4928 */
4929 else if (TailMatches("WHEN", "NOT", "MATCHED", "THEN") ||
4930 TailMatches("WHEN", "NOT", "MATCHED", "BY", "TARGET", "THEN"))
4931 COMPLETE_WITH("INSERT", "DO NOTHING");
4932
4933/* NOTIFY --- can be inside EXPLAIN, RULE, etc */
4934 else if (TailMatches("NOTIFY"))
4935 COMPLETE_WITH_QUERY(Query_for_list_of_channels);
4936
4937/* OPTIONS */
4938 else if (TailMatches("OPTIONS"))
4939 COMPLETE_WITH("(");
4940
4941/* OWNER TO - complete with available roles */
4942 else if (TailMatches("OWNER", "TO"))
4943 COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_roles,
4944 Keywords_for_list_of_owner_roles);
4945
4946/* ORDER BY */
4947 else if (TailMatches("FROM", MatchAny, "ORDER"))
4948 COMPLETE_WITH("BY");
4949 else if (TailMatches("FROM", MatchAny, "ORDER", "BY"))
4950 COMPLETE_WITH_ATTR(prev3_wd);
4951
4952/* PREPARE xx AS */
4953 else if (Matches("PREPARE", MatchAny, "AS"))
4954 COMPLETE_WITH("SELECT", "UPDATE", "INSERT INTO", "DELETE FROM",
4955 "MERGE INTO", "VALUES", "WITH", "TABLE");
4956
4957/*
4958 * PREPARE TRANSACTION is missing on purpose. It's intended for transaction
4959 * managers, not for manual use in interactive sessions.
4960 */
4961
4962/* REASSIGN OWNED BY xxx TO yyy */
4963 else if (Matches("REASSIGN"))
4964 COMPLETE_WITH("OWNED BY");
4965 else if (Matches("REASSIGN", "OWNED"))
4966 COMPLETE_WITH("BY");
4967 else if (Matches("REASSIGN", "OWNED", "BY"))
4968 COMPLETE_WITH_QUERY(Query_for_list_of_roles);
4969 else if (Matches("REASSIGN", "OWNED", "BY", MatchAny))
4970 COMPLETE_WITH("TO");
4971 else if (Matches("REASSIGN", "OWNED", "BY", MatchAny, "TO"))
4972 COMPLETE_WITH_QUERY(Query_for_list_of_roles);
4973
4974/* REFRESH MATERIALIZED VIEW */
4975 else if (Matches("REFRESH"))
4976 COMPLETE_WITH("MATERIALIZED VIEW");
4977 else if (Matches("REFRESH", "MATERIALIZED"))
4978 COMPLETE_WITH("VIEW");
4979 else if (Matches("REFRESH", "MATERIALIZED", "VIEW"))
4980 COMPLETE_WITH_SCHEMA_QUERY_PLUS(Query_for_list_of_matviews,
4981 "CONCURRENTLY");
4982 else if (Matches("REFRESH", "MATERIALIZED", "VIEW", "CONCURRENTLY"))
4983 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_matviews);
4984 else if (Matches("REFRESH", "MATERIALIZED", "VIEW", MatchAny))
4985 COMPLETE_WITH("WITH");
4986 else if (Matches("REFRESH", "MATERIALIZED", "VIEW", "CONCURRENTLY", MatchAny))
4987 COMPLETE_WITH("WITH");
4988 else if (Matches("REFRESH", "MATERIALIZED", "VIEW", MatchAny, "WITH"))
4989 COMPLETE_WITH("NO DATA", "DATA");
4990 else if (Matches("REFRESH", "MATERIALIZED", "VIEW", "CONCURRENTLY", MatchAny, "WITH"))
4991 COMPLETE_WITH("NO DATA", "DATA");
4992 else if (Matches("REFRESH", "MATERIALIZED", "VIEW", MatchAny, "WITH", "NO"))
4993 COMPLETE_WITH("DATA");
4994 else if (Matches("REFRESH", "MATERIALIZED", "VIEW", "CONCURRENTLY", MatchAny, "WITH", "NO"))
4995 COMPLETE_WITH("DATA");
4996
4997/* REINDEX */
4998 else if (Matches("REINDEX") ||
4999 Matches("REINDEX", "(*)"))
5000 COMPLETE_WITH("TABLE", "INDEX", "SYSTEM", "SCHEMA", "DATABASE");
5001 else if (Matches("REINDEX", "TABLE") ||
5002 Matches("REINDEX", "(*)", "TABLE"))
5003 COMPLETE_WITH_SCHEMA_QUERY_PLUS(Query_for_list_of_indexables,
5004 "CONCURRENTLY");
5005 else if (Matches("REINDEX", "INDEX") ||
5006 Matches("REINDEX", "(*)", "INDEX"))
5007 COMPLETE_WITH_SCHEMA_QUERY_PLUS(Query_for_list_of_indexes,
5008 "CONCURRENTLY");
5009 else if (Matches("REINDEX", "SCHEMA") ||
5010 Matches("REINDEX", "(*)", "SCHEMA"))
5011 COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas,
5012 "CONCURRENTLY");
5013 else if (Matches("REINDEX", "SYSTEM|DATABASE") ||
5014 Matches("REINDEX", "(*)", "SYSTEM|DATABASE"))
5015 COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_databases,
5016 "CONCURRENTLY");
5017 else if (Matches("REINDEX", "TABLE", "CONCURRENTLY") ||
5018 Matches("REINDEX", "(*)", "TABLE", "CONCURRENTLY"))
5019 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_indexables);
5020 else if (Matches("REINDEX", "INDEX", "CONCURRENTLY") ||
5021 Matches("REINDEX", "(*)", "INDEX", "CONCURRENTLY"))
5022 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_indexes);
5023 else if (Matches("REINDEX", "SCHEMA", "CONCURRENTLY") ||
5024 Matches("REINDEX", "(*)", "SCHEMA", "CONCURRENTLY"))
5025 COMPLETE_WITH_QUERY(Query_for_list_of_schemas);
5026 else if (Matches("REINDEX", "SYSTEM|DATABASE", "CONCURRENTLY") ||
5027 Matches("REINDEX", "(*)", "SYSTEM|DATABASE", "CONCURRENTLY"))
5028 COMPLETE_WITH_QUERY(Query_for_list_of_databases);
5029 else if (HeadMatches("REINDEX", "(*") &&
5030 !HeadMatches("REINDEX", "(*)"))
5031 {
5032 /*
5033 * This fires if we're in an unfinished parenthesized option list.
5034 * get_previous_words treats a completed parenthesized option list as
5035 * one word, so the above test is correct.
5036 */
5037 if (ends_with(prev_wd, '(') || ends_with(prev_wd, ','))
5038 COMPLETE_WITH("CONCURRENTLY", "TABLESPACE", "VERBOSE");
5039 else if (TailMatches("TABLESPACE"))
5040 COMPLETE_WITH_QUERY(Query_for_list_of_tablespaces);
5041 }
5042
5043/* SECURITY LABEL */
5044 else if (Matches("SECURITY"))
5045 COMPLETE_WITH("LABEL");
5046 else if (Matches("SECURITY", "LABEL"))
5047 COMPLETE_WITH("ON", "FOR");
5048 else if (Matches("SECURITY", "LABEL", "FOR", MatchAny))
5049 COMPLETE_WITH("ON");
5050 else if (Matches("SECURITY", "LABEL", "ON") ||
5051 Matches("SECURITY", "LABEL", "FOR", MatchAny, "ON"))
5052 COMPLETE_WITH("TABLE", "COLUMN", "AGGREGATE", "DATABASE", "DOMAIN",
5053 "EVENT TRIGGER", "FOREIGN TABLE", "FUNCTION",
5054 "LARGE OBJECT", "MATERIALIZED VIEW", "LANGUAGE",
5055 "PUBLICATION", "PROCEDURE", "ROLE", "ROUTINE", "SCHEMA",
5056 "SEQUENCE", "SUBSCRIPTION", "TABLESPACE", "TYPE", "VIEW");
5057 else if (Matches("SECURITY", "LABEL", "ON", MatchAny, MatchAny))
5058 COMPLETE_WITH("IS");
5059
5060/* SELECT */
5061 /* naah . . . */
5062
5063/* SET, RESET, SHOW */
5064 /* Complete with a variable name */
5065 else if (TailMatches("SET|RESET") &&
5066 !TailMatches("UPDATE", MatchAny, "SET") &&
5067 !TailMatches("ALTER", "DATABASE|USER|ROLE", MatchAny, "RESET"))
5068 COMPLETE_WITH_QUERY_VERBATIM_PLUS(Query_for_list_of_set_vars,
5069 "CONSTRAINTS",
5070 "TRANSACTION",
5071 "SESSION",
5072 "ROLE",
5073 "TABLESPACE",
5074 "ALL");
5075 else if (Matches("SHOW"))
5076 COMPLETE_WITH_QUERY_VERBATIM_PLUS(Query_for_list_of_show_vars,
5077 "SESSION AUTHORIZATION",
5078 "ALL");
5079 else if (Matches("SHOW", "SESSION"))
5080 COMPLETE_WITH("AUTHORIZATION");
5081 /* Complete "SET TRANSACTION" */
5082 else if (Matches("SET", "TRANSACTION"))
5083 COMPLETE_WITH("SNAPSHOT", "ISOLATION LEVEL", "READ", "DEFERRABLE", "NOT DEFERRABLE");
5084 else if (Matches("BEGIN|START", "TRANSACTION") ||
5085 Matches("BEGIN", "WORK") ||
5086 Matches("BEGIN") ||
5087 Matches("SET", "SESSION", "CHARACTERISTICS", "AS", "TRANSACTION"))
5088 COMPLETE_WITH("ISOLATION LEVEL", "READ", "DEFERRABLE", "NOT DEFERRABLE");
5089 else if (Matches("SET|BEGIN|START", "TRANSACTION|WORK", "NOT") ||
5090 Matches("BEGIN", "NOT") ||
5091 Matches("SET", "SESSION", "CHARACTERISTICS", "AS", "TRANSACTION", "NOT"))
5092 COMPLETE_WITH("DEFERRABLE");
5093 else if (Matches("SET|BEGIN|START", "TRANSACTION|WORK", "ISOLATION") ||
5094 Matches("BEGIN", "ISOLATION") ||
5095 Matches("SET", "SESSION", "CHARACTERISTICS", "AS", "TRANSACTION", "ISOLATION"))
5096 COMPLETE_WITH("LEVEL");
5097 else if (Matches("SET|BEGIN|START", "TRANSACTION|WORK", "ISOLATION", "LEVEL") ||
5098 Matches("BEGIN", "ISOLATION", "LEVEL") ||
5099 Matches("SET", "SESSION", "CHARACTERISTICS", "AS", "TRANSACTION", "ISOLATION", "LEVEL"))
5100 COMPLETE_WITH("READ", "REPEATABLE READ", "SERIALIZABLE");
5101 else if (Matches("SET|BEGIN|START", "TRANSACTION|WORK", "ISOLATION", "LEVEL", "READ") ||
5102 Matches("BEGIN", "ISOLATION", "LEVEL", "READ") ||
5103 Matches("SET", "SESSION", "CHARACTERISTICS", "AS", "TRANSACTION", "ISOLATION", "LEVEL", "READ"))
5104 COMPLETE_WITH("UNCOMMITTED", "COMMITTED");
5105 else if (Matches("SET|BEGIN|START", "TRANSACTION|WORK", "ISOLATION", "LEVEL", "REPEATABLE") ||
5106 Matches("BEGIN", "ISOLATION", "LEVEL", "REPEATABLE") ||
5107 Matches("SET", "SESSION", "CHARACTERISTICS", "AS", "TRANSACTION", "ISOLATION", "LEVEL", "REPEATABLE"))
5108 COMPLETE_WITH("READ");
5109 else if (Matches("SET|BEGIN|START", "TRANSACTION|WORK", "READ") ||
5110 Matches("BEGIN", "READ") ||
5111 Matches("SET", "SESSION", "CHARACTERISTICS", "AS", "TRANSACTION", "READ"))
5112 COMPLETE_WITH("ONLY", "WRITE");
5113 /* SET CONSTRAINTS */
5114 else if (Matches("SET", "CONSTRAINTS"))
5115 COMPLETE_WITH_SCHEMA_QUERY_PLUS(Query_for_list_of_constraints_with_schema,
5116 "ALL");
5117 /* Complete SET CONSTRAINTS <foo> with DEFERRED|IMMEDIATE */
5118 else if (Matches("SET", "CONSTRAINTS", MatchAny))
5119 COMPLETE_WITH("DEFERRED", "IMMEDIATE");
5120 /* Complete SET ROLE */
5121 else if (Matches("SET", "ROLE"))
5122 COMPLETE_WITH_QUERY(Query_for_list_of_roles);
5123 /* Complete SET SESSION with AUTHORIZATION or CHARACTERISTICS... */
5124 else if (Matches("SET", "SESSION"))
5125 COMPLETE_WITH("AUTHORIZATION", "CHARACTERISTICS AS TRANSACTION");
5126 /* Complete SET SESSION AUTHORIZATION with username */
5127 else if (Matches("SET", "SESSION", "AUTHORIZATION"))
5128 COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_roles,
5129 "DEFAULT");
5130 /* Complete RESET SESSION with AUTHORIZATION */
5131 else if (Matches("RESET", "SESSION"))
5132 COMPLETE_WITH("AUTHORIZATION");
5133 /* Complete SET <var> with "TO" */
5134 else if (Matches("SET", MatchAny))
5135 COMPLETE_WITH("TO");
5136
5137 /*
5138 * Complete ALTER DATABASE|FUNCTION|PROCEDURE|ROLE|ROUTINE|USER ... SET
5139 * <name>
5140 */
5141 else if (Matches("ALTER", "DATABASE|FUNCTION|PROCEDURE|ROLE|ROUTINE|USER", MatchAnyN, "SET", MatchAnyExcept("SCHEMA")))
5142 COMPLETE_WITH("FROM CURRENT", "TO");
5143
5144 /*
5145 * Suggest possible variable values in SET variable TO|=, along with the
5146 * preceding ALTER syntaxes.
5147 */
5148 else if (TailMatches("SET", MatchAny, "TO|=") &&
5149 !TailMatches("UPDATE", MatchAny, "SET", MatchAny, "TO|="))
5150 {
5151 /* special cased code for individual GUCs */
5152 if (TailMatches("DateStyle", "TO|="))
5153 COMPLETE_WITH("ISO", "SQL", "Postgres", "German",
5154 "YMD", "DMY", "MDY",
5155 "US", "European", "NonEuropean",
5156 "DEFAULT");
5157 else if (TailMatches("search_path", "TO|="))
5158 {
5159 /* Here, we want to allow pg_catalog, so use narrower exclusion */
5160 COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas
5161 " AND nspname NOT LIKE E'pg\\\\_toast%%'"
5162 " AND nspname NOT LIKE E'pg\\\\_temp%%'",
5163 "DEFAULT");
5164 }
5165 else if (TailMatches("TimeZone", "TO|="))
5166 COMPLETE_WITH_TIMEZONE_NAME();
5167 else
5168 {
5169 /* generic, type based, GUC support */
5170 char *guctype = get_guctype(prev2_wd);
5171
5172 /*
5173 * Note: if we don't recognize the GUC name, it's important to not
5174 * offer any completions, as most likely we've misinterpreted the
5175 * context and this isn't a GUC-setting command at all.
5176 */
5177 if (guctype)
5178 {
5179 if (strcmp(guctype, "enum") == 0)
5180 {
5181 set_completion_reference_verbatim(prev2_wd);
5182 COMPLETE_WITH_QUERY_PLUS(Query_for_values_of_enum_GUC,
5183 "DEFAULT");
5184 }
5185 else if (strcmp(guctype, "bool") == 0)
5186 COMPLETE_WITH("on", "off", "true", "false", "yes", "no",
5187 "1", "0", "DEFAULT");
5188 else
5189 COMPLETE_WITH("DEFAULT");
5190
5191 free(guctype);
5192 }
5193 }
5194 }
5195
5196/* START TRANSACTION */
5197 else if (Matches("START"))
5198 COMPLETE_WITH("TRANSACTION");
5199
5200/* TABLE, but not TABLE embedded in other commands */
5201 else if (Matches("TABLE"))
5202 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_selectables);
5203
5204/* TABLESAMPLE */
5205 else if (TailMatches("TABLESAMPLE"))
5206 COMPLETE_WITH_QUERY(Query_for_list_of_tablesample_methods);
5207 else if (TailMatches("TABLESAMPLE", MatchAny))
5208 COMPLETE_WITH("(");
5209
5210/* TRUNCATE */
5211 else if (Matches("TRUNCATE"))
5212 COMPLETE_WITH_SCHEMA_QUERY_PLUS(Query_for_list_of_truncatables,
5213 "TABLE", "ONLY");
5214 else if (Matches("TRUNCATE", "TABLE"))
5215 COMPLETE_WITH_SCHEMA_QUERY_PLUS(Query_for_list_of_truncatables,
5216 "ONLY");
5217 else if (Matches("TRUNCATE", MatchAnyN, "ONLY"))
5218 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_truncatables);
5219 else if (Matches("TRUNCATE", MatchAny) ||
5220 Matches("TRUNCATE", "TABLE|ONLY", MatchAny) ||
5221 Matches("TRUNCATE", "TABLE", "ONLY", MatchAny))
5222 COMPLETE_WITH("RESTART IDENTITY", "CONTINUE IDENTITY", "CASCADE", "RESTRICT");
5223 else if (Matches("TRUNCATE", MatchAnyN, "IDENTITY"))
5224 COMPLETE_WITH("CASCADE", "RESTRICT");
5225
5226/* UNLISTEN */
5227 else if (Matches("UNLISTEN"))
5228 COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_channels, "*");
5229
5230/* UPDATE --- can be inside EXPLAIN, RULE, etc */
5231 /* If prev. word is UPDATE suggest a list of tables */
5232 else if (TailMatches("UPDATE"))
5233 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_updatables);
5234 /* Complete UPDATE <table> with "SET" */
5235 else if (TailMatches("UPDATE", MatchAny))
5236 COMPLETE_WITH("SET");
5237 /* Complete UPDATE <table> SET with list of attributes */
5238 else if (TailMatches("UPDATE", MatchAny, "SET"))
5239 COMPLETE_WITH_ATTR(prev2_wd);
5240 /* UPDATE <table> SET <attr> = */
5241 else if (TailMatches("UPDATE", MatchAny, "SET", MatchAnyExcept("*=")))
5242 COMPLETE_WITH("=");
5243
5244/* USER MAPPING */
5245 else if (Matches("ALTER|CREATE|DROP", "USER", "MAPPING"))
5246 COMPLETE_WITH("FOR");
5247 else if (Matches("CREATE", "USER", "MAPPING", "FOR"))
5248 COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_roles,
5249 "CURRENT_ROLE",
5250 "CURRENT_USER",
5251 "PUBLIC",
5252 "USER");
5253 else if (Matches("ALTER|DROP", "USER", "MAPPING", "FOR"))
5254 COMPLETE_WITH_QUERY(Query_for_list_of_user_mappings);
5255 else if (Matches("CREATE|ALTER|DROP", "USER", "MAPPING", "FOR", MatchAny))
5256 COMPLETE_WITH("SERVER");
5257 else if (Matches("CREATE|ALTER", "USER", "MAPPING", "FOR", MatchAny, "SERVER", MatchAny))
5258 COMPLETE_WITH("OPTIONS");
5259
5260/*
5261 * VACUUM [ ( option [, ...] ) ] [ [ ONLY ] table_and_columns [, ...] ]
5262 * VACUUM [ FULL ] [ FREEZE ] [ VERBOSE ] [ ANALYZE ] [ [ ONLY ] table_and_columns [, ...] ]
5263 */
5264 else if (Matches("VACUUM"))
5265 COMPLETE_WITH_SCHEMA_QUERY_PLUS(Query_for_list_of_vacuumables,
5266 "(",
5267 "FULL",
5268 "FREEZE",
5269 "VERBOSE",
5270 "ANALYZE",
5271 "ONLY");
5272 else if (Matches("VACUUM", "FULL"))
5273 COMPLETE_WITH_SCHEMA_QUERY_PLUS(Query_for_list_of_vacuumables,
5274 "FREEZE",
5275 "VERBOSE",
5276 "ANALYZE",
5277 "ONLY");
5278 else if (Matches("VACUUM", MatchAnyN, "FREEZE"))
5279 COMPLETE_WITH_SCHEMA_QUERY_PLUS(Query_for_list_of_vacuumables,
5280 "VERBOSE",
5281 "ANALYZE",
5282 "ONLY");
5283 else if (Matches("VACUUM", MatchAnyN, "VERBOSE"))
5284 COMPLETE_WITH_SCHEMA_QUERY_PLUS(Query_for_list_of_vacuumables,
5285 "ANALYZE",
5286 "ONLY");
5287 else if (Matches("VACUUM", MatchAnyN, "ANALYZE"))
5288 COMPLETE_WITH_SCHEMA_QUERY_PLUS(Query_for_list_of_vacuumables,
5289 "ONLY");
5290 else if (HeadMatches("VACUUM", "(*") &&
5291 !HeadMatches("VACUUM", "(*)"))
5292 {
5293 /*
5294 * This fires if we're in an unfinished parenthesized option list.
5295 * get_previous_words treats a completed parenthesized option list as
5296 * one word, so the above test is correct.
5297 */
5298 if (ends_with(prev_wd, '(') || ends_with(prev_wd, ','))
5299 COMPLETE_WITH("FULL", "FREEZE", "ANALYZE", "VERBOSE",
5300 "DISABLE_PAGE_SKIPPING", "SKIP_LOCKED",
5301 "INDEX_CLEANUP", "PROCESS_MAIN", "PROCESS_TOAST",
5302 "TRUNCATE", "PARALLEL", "SKIP_DATABASE_STATS",
5303 "ONLY_DATABASE_STATS", "BUFFER_USAGE_LIMIT");
5304 else if (TailMatches("FULL|FREEZE|ANALYZE|VERBOSE|DISABLE_PAGE_SKIPPING|SKIP_LOCKED|PROCESS_MAIN|PROCESS_TOAST|TRUNCATE|SKIP_DATABASE_STATS|ONLY_DATABASE_STATS"))
5305 COMPLETE_WITH("ON", "OFF");
5306 else if (TailMatches("INDEX_CLEANUP"))
5307 COMPLETE_WITH("AUTO", "ON", "OFF");
5308 }
5309 else if (Matches("VACUUM", MatchAnyN, "("))
5310 /* "VACUUM (" should be caught above, so assume we want columns */
5311 COMPLETE_WITH_ATTR(prev2_wd);
5312 else if (HeadMatches("VACUUM"))
5313 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_vacuumables);
5314
5315/*
5316 * WAIT FOR LSN '<lsn>' [ WITH ( option [, ...] ) ]
5317 * where option can be:
5318 * TIMEOUT '<timeout>'
5319 * NO_THROW
5320 */
5321 else if (Matches("WAIT"))
5322 COMPLETE_WITH("FOR");
5323 else if (Matches("WAIT", "FOR"))
5324 COMPLETE_WITH("LSN");
5325 else if (Matches("WAIT", "FOR", "LSN"))
5326 /* No completion for LSN value - user must provide manually */
5327 ;
5328 else if (Matches("WAIT", "FOR", "LSN", MatchAny))
5329 COMPLETE_WITH("WITH");
5330 else if (Matches("WAIT", "FOR", "LSN", MatchAny, "WITH"))
5331 COMPLETE_WITH("(");
5332 else if (HeadMatches("WAIT", "FOR", "LSN", MatchAny, "WITH", "(*") &&
5333 !HeadMatches("WAIT", "FOR", "LSN", MatchAny, "WITH", "(*)"))
5334 {
5335 /*
5336 * This fires if we're in an unfinished parenthesized option list.
5337 * get_previous_words treats a completed parenthesized option list as
5338 * one word, so the above test is correct.
5339 */
5340 if (ends_with(prev_wd, '(') || ends_with(prev_wd, ','))
5341 COMPLETE_WITH("timeout", "no_throw");
5342
5343 /*
5344 * timeout takes a string value, no_throw takes no value. We don't
5345 * offer completions for these values.
5346 */
5347 }
5348
5349/* WITH [RECURSIVE] */
5350
5351 /*
5352 * Only match when WITH is the first word, as WITH may appear in many
5353 * other contexts.
5354 */
5355 else if (Matches("WITH"))
5356 COMPLETE_WITH("RECURSIVE");
5357
5358/* WHERE */
5359 /* Simple case of the word before the where being the table name */
5360 else if (TailMatches(MatchAny, "WHERE"))
5361 COMPLETE_WITH_ATTR(prev2_wd);
5362
5363/* ... FROM ... */
5364/* TODO: also include SRF ? */
5365 else if (TailMatches("FROM") && !Matches("COPY|\\copy", MatchAny, "FROM"))
5366 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_selectables);
5367
5368/* ... JOIN ... */
5369 else if (TailMatches("JOIN"))
5370 COMPLETE_WITH_SCHEMA_QUERY_PLUS(Query_for_list_of_selectables, "LATERAL");
5371 else if (TailMatches("JOIN", MatchAny) && !TailMatches("CROSS|NATURAL", "JOIN", MatchAny))
5372 COMPLETE_WITH("ON", "USING (");
5373 else if (TailMatches("JOIN", MatchAny, MatchAny) &&
5374 !TailMatches("CROSS|NATURAL", "JOIN", MatchAny, MatchAny) && !TailMatches("ON|USING"))
5375 COMPLETE_WITH("ON", "USING (");
5376 else if (TailMatches("JOIN", "LATERAL", MatchAny, MatchAny) &&
5377 !TailMatches("CROSS|NATURAL", "JOIN", "LATERAL", MatchAny, MatchAny) && !TailMatches("ON|USING"))
5378 COMPLETE_WITH("ON", "USING (");
5379 else if (TailMatches("JOIN", MatchAny, "USING") ||
5380 TailMatches("JOIN", MatchAny, MatchAny, "USING") ||
5381 TailMatches("JOIN", "LATERAL", MatchAny, MatchAny, "USING"))
5382 COMPLETE_WITH("(");
5383 else if (TailMatches("JOIN", MatchAny, "USING", "("))
5384 COMPLETE_WITH_ATTR(prev3_wd);
5385 else if (TailMatches("JOIN", MatchAny, MatchAny, "USING", "("))
5386 COMPLETE_WITH_ATTR(prev4_wd);
5387
5388/* ... AT [ LOCAL | TIME ZONE ] ... */
5389 else if (TailMatches("AT"))
5390 COMPLETE_WITH("LOCAL", "TIME ZONE");
5391 else if (TailMatches("AT", "TIME", "ZONE"))
5392 COMPLETE_WITH_TIMEZONE_NAME();
5393
5394/* Backslash commands */
5395/* TODO: \dc \dd \dl */
5396 else if (TailMatchesCS("\\?"))
5397 COMPLETE_WITH_CS("commands", "options", "variables");
5398 else if (TailMatchesCS("\\connect|\\c"))
5399 {
5401 COMPLETE_WITH_QUERY(Query_for_list_of_databases);
5402 }
5403 else if (TailMatchesCS("\\connect|\\c", MatchAny))
5404 {
5405 if (!recognized_connection_string(prev_wd))
5406 COMPLETE_WITH_QUERY(Query_for_list_of_roles);
5407 }
5408 else if (TailMatchesCS("\\da*"))
5409 COMPLETE_WITH_VERSIONED_SCHEMA_QUERY(Query_for_list_of_aggregates);
5410 else if (TailMatchesCS("\\dAc*", MatchAny) ||
5411 TailMatchesCS("\\dAf*", MatchAny))
5412 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_datatypes);
5413 else if (TailMatchesCS("\\dAo*", MatchAny) ||
5414 TailMatchesCS("\\dAp*", MatchAny))
5415 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_operator_families);
5416 else if (TailMatchesCS("\\dA*"))
5417 COMPLETE_WITH_QUERY(Query_for_list_of_access_methods);
5418 else if (TailMatchesCS("\\db*"))
5419 COMPLETE_WITH_QUERY(Query_for_list_of_tablespaces);
5420 else if (TailMatchesCS("\\dconfig*"))
5421 COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_show_vars);
5422 else if (TailMatchesCS("\\dD*"))
5423 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_domains);
5424 else if (TailMatchesCS("\\des*"))
5425 COMPLETE_WITH_QUERY(Query_for_list_of_servers);
5426 else if (TailMatchesCS("\\deu*"))
5427 COMPLETE_WITH_QUERY(Query_for_list_of_user_mappings);
5428 else if (TailMatchesCS("\\dew*"))
5429 COMPLETE_WITH_QUERY(Query_for_list_of_fdws);
5430 else if (TailMatchesCS("\\df*"))
5431 COMPLETE_WITH_VERSIONED_SCHEMA_QUERY(Query_for_list_of_functions);
5432 else if (HeadMatchesCS("\\df*"))
5433 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_datatypes);
5434
5435 else if (TailMatchesCS("\\dFd*"))
5436 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_ts_dictionaries);
5437 else if (TailMatchesCS("\\dFp*"))
5438 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_ts_parsers);
5439 else if (TailMatchesCS("\\dFt*"))
5440 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_ts_templates);
5441 /* must be at end of \dF alternatives: */
5442 else if (TailMatchesCS("\\dF*"))
5443 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_ts_configurations);
5444
5445 else if (TailMatchesCS("\\di*"))
5446 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_indexes);
5447 else if (TailMatchesCS("\\dL*"))
5448 COMPLETE_WITH_QUERY(Query_for_list_of_languages);
5449 else if (TailMatchesCS("\\dn*"))
5450 COMPLETE_WITH_QUERY(Query_for_list_of_schemas);
5451 /* no support for completing operators, but we can complete types: */
5452 else if (HeadMatchesCS("\\do*", MatchAny))
5453 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_datatypes);
5454 else if (TailMatchesCS("\\dp") || TailMatchesCS("\\z"))
5455 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_grantables);
5456 else if (TailMatchesCS("\\dPi*"))
5457 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_partitioned_indexes);
5458 else if (TailMatchesCS("\\dPt*"))
5459 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_partitioned_tables);
5460 else if (TailMatchesCS("\\dP*"))
5461 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_partitioned_relations);
5462 else if (TailMatchesCS("\\dRp*"))
5463 COMPLETE_WITH_VERSIONED_QUERY(Query_for_list_of_publications);
5464 else if (TailMatchesCS("\\dRs*"))
5465 COMPLETE_WITH_VERSIONED_QUERY(Query_for_list_of_subscriptions);
5466 else if (TailMatchesCS("\\ds*"))
5467 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_sequences);
5468 else if (TailMatchesCS("\\dt*"))
5469 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables);
5470 else if (TailMatchesCS("\\dT*"))
5471 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_datatypes);
5472 else if (TailMatchesCS("\\du*") ||
5473 TailMatchesCS("\\dg*") ||
5474 TailMatchesCS("\\drg*"))
5475 COMPLETE_WITH_QUERY(Query_for_list_of_roles);
5476 else if (TailMatchesCS("\\dv*"))
5477 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_views);
5478 else if (TailMatchesCS("\\dx*"))
5479 COMPLETE_WITH_QUERY(Query_for_list_of_extensions);
5480 else if (TailMatchesCS("\\dX*"))
5481 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_statistics);
5482 else if (TailMatchesCS("\\dm*"))
5483 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_matviews);
5484 else if (TailMatchesCS("\\dE*"))
5485 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_foreign_tables);
5486 else if (TailMatchesCS("\\dy*"))
5487 COMPLETE_WITH_QUERY(Query_for_list_of_event_triggers);
5488
5489 /* must be at end of \d alternatives: */
5490 else if (TailMatchesCS("\\d*"))
5491 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_relations);
5492
5493 else if (TailMatchesCS("\\ef"))
5494 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_routines);
5495 else if (TailMatchesCS("\\ev"))
5496 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_views);
5497
5498 else if (TailMatchesCS("\\encoding"))
5499 COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_encodings);
5500 else if (TailMatchesCS("\\h|\\help"))
5501 COMPLETE_WITH_LIST(sql_commands);
5502 else if (TailMatchesCS("\\h|\\help", MatchAny))
5503 {
5504 if (TailMatches("DROP"))
5505 COMPLETE_WITH_GENERATOR(drop_command_generator);
5506 else if (TailMatches("ALTER"))
5507 COMPLETE_WITH_GENERATOR(alter_command_generator);
5508
5509 /*
5510 * CREATE is recognized by tail match elsewhere, so doesn't need to be
5511 * repeated here
5512 */
5513 }
5514 else if (TailMatchesCS("\\h|\\help", MatchAny, MatchAny))
5515 {
5516 if (TailMatches("CREATE|DROP", "ACCESS"))
5517 COMPLETE_WITH("METHOD");
5518 else if (TailMatches("ALTER", "DEFAULT"))
5519 COMPLETE_WITH("PRIVILEGES");
5520 else if (TailMatches("CREATE|ALTER|DROP", "EVENT"))
5521 COMPLETE_WITH("TRIGGER");
5522 else if (TailMatches("CREATE|ALTER|DROP", "FOREIGN"))
5523 COMPLETE_WITH("DATA WRAPPER", "TABLE");
5524 else if (TailMatches("ALTER", "LARGE"))
5525 COMPLETE_WITH("OBJECT");
5526 else if (TailMatches("CREATE|ALTER|DROP", "MATERIALIZED"))
5527 COMPLETE_WITH("VIEW");
5528 else if (TailMatches("CREATE|ALTER|DROP", "TEXT"))
5529 COMPLETE_WITH("SEARCH");
5530 else if (TailMatches("CREATE|ALTER|DROP", "USER"))
5531 COMPLETE_WITH("MAPPING FOR");
5532 }
5533 else if (TailMatchesCS("\\h|\\help", MatchAny, MatchAny, MatchAny))
5534 {
5535 if (TailMatches("CREATE|ALTER|DROP", "FOREIGN", "DATA"))
5536 COMPLETE_WITH("WRAPPER");
5537 else if (TailMatches("CREATE|ALTER|DROP", "TEXT", "SEARCH"))
5538 COMPLETE_WITH("CONFIGURATION", "DICTIONARY", "PARSER", "TEMPLATE");
5539 else if (TailMatches("CREATE|ALTER|DROP", "USER", "MAPPING"))
5540 COMPLETE_WITH("FOR");
5541 }
5542 else if (TailMatchesCS("\\l*") && !TailMatchesCS("\\lo*"))
5543 COMPLETE_WITH_QUERY(Query_for_list_of_databases);
5544 else if (TailMatchesCS("\\password"))
5545 COMPLETE_WITH_QUERY(Query_for_list_of_roles);
5546 else if (TailMatchesCS("\\pset"))
5547 COMPLETE_WITH_CS("border", "columns", "csv_fieldsep",
5548 "display_false", "display_true", "expanded",
5549 "fieldsep", "fieldsep_zero", "footer", "format",
5550 "linestyle", "null", "numericlocale",
5551 "pager", "pager_min_lines",
5552 "recordsep", "recordsep_zero",
5553 "tableattr", "title", "tuples_only",
5554 "unicode_border_linestyle",
5555 "unicode_column_linestyle",
5556 "unicode_header_linestyle",
5557 "xheader_width");
5558 else if (TailMatchesCS("\\pset", MatchAny))
5559 {
5560 if (TailMatchesCS("format"))
5561 COMPLETE_WITH_CS("aligned", "asciidoc", "csv", "html", "latex",
5562 "latex-longtable", "troff-ms", "unaligned",
5563 "wrapped");
5564 else if (TailMatchesCS("xheader_width"))
5565 COMPLETE_WITH_CS("full", "column", "page");
5566 else if (TailMatchesCS("linestyle"))
5567 COMPLETE_WITH_CS("ascii", "old-ascii", "unicode");
5568 else if (TailMatchesCS("pager"))
5569 COMPLETE_WITH_CS("on", "off", "always");
5570 else if (TailMatchesCS("unicode_border_linestyle|"
5571 "unicode_column_linestyle|"
5572 "unicode_header_linestyle"))
5573 COMPLETE_WITH_CS("single", "double");
5574 }
5575 else if (TailMatchesCS("\\unset"))
5576 matches = complete_from_variables(text, "", "", true);
5577 else if (TailMatchesCS("\\set"))
5578 matches = complete_from_variables(text, "", "", false);
5579 else if (TailMatchesCS("\\set", MatchAny))
5580 {
5581 if (TailMatchesCS("AUTOCOMMIT|ON_ERROR_STOP|QUIET|SHOW_ALL_RESULTS|"
5582 "SINGLELINE|SINGLESTEP"))
5583 COMPLETE_WITH_CS("on", "off");
5584 else if (TailMatchesCS("COMP_KEYWORD_CASE"))
5585 COMPLETE_WITH_CS("lower", "upper",
5586 "preserve-lower", "preserve-upper");
5587 else if (TailMatchesCS("ECHO"))
5588 COMPLETE_WITH_CS("errors", "queries", "all", "none");
5589 else if (TailMatchesCS("ECHO_HIDDEN"))
5590 COMPLETE_WITH_CS("noexec", "off", "on");
5591 else if (TailMatchesCS("HISTCONTROL"))
5592 COMPLETE_WITH_CS("ignorespace", "ignoredups",
5593 "ignoreboth", "none");
5594 else if (TailMatchesCS("ON_ERROR_ROLLBACK"))
5595 COMPLETE_WITH_CS("on", "off", "interactive");
5596 else if (TailMatchesCS("SHOW_CONTEXT"))
5597 COMPLETE_WITH_CS("never", "errors", "always");
5598 else if (TailMatchesCS("VERBOSITY"))
5599 COMPLETE_WITH_CS("default", "verbose", "terse", "sqlstate");
5600 }
5601 else if (TailMatchesCS("\\sf*"))
5602 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_routines);
5603 else if (TailMatchesCS("\\sv*"))
5604 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_views);
5605 else if (TailMatchesCS("\\cd|\\e|\\edit|\\g|\\gx|\\i|\\include|"
5606 "\\ir|\\include_relative|\\o|\\out|"
5607 "\\s|\\w|\\write|\\lo_import") ||
5608 TailMatchesCS("\\lo_export", MatchAny))
5609 COMPLETE_WITH_FILES("\\", false);
5610
5611 /* gen_tabcomplete.pl ends special processing here */
5612 /* END GEN_TABCOMPLETE */
5613
5614 return matches;
5615}
5616
5617
5618/*
5619 * GENERATOR FUNCTIONS
5620 *
5621 * These functions do all the actual work of completing the input. They get
5622 * passed the text so far and the count how many times they have been called
5623 * so far with the same text.
5624 * If you read the above carefully, you'll see that these don't get called
5625 * directly but through the readline interface.
5626 * The return value is expected to be the full completion of the text, going
5627 * through a list each time, or NULL if there are no more matches. The string
5628 * will be free()'d by readline, so you must run it through strdup() or
5629 * something of that sort.
5630 */
5631
5632/*
5633 * Common routine for create_command_generator and drop_command_generator.
5634 * Entries that have 'excluded' flags are not returned.
5635 */
5636static char *
5637create_or_drop_command_generator(const char *text, int state, bits32 excluded)
5638{
5639 static int list_index,
5640 string_length;
5641 const char *name;
5642
5643 /* If this is the first time for this completion, init some values */
5644 if (state == 0)
5645 {
5646 list_index = 0;
5647 string_length = strlen(text);
5648 }
5649
5650 /* find something that matches */
5651 while ((name = words_after_create[list_index++].name))
5652 {
5653 if ((pg_strncasecmp(name, text, string_length) == 0) &&
5654 !(words_after_create[list_index - 1].flags & excluded))
5655 return pg_strdup_keyword_case(name, text);
5656 }
5657 /* if nothing matches, return NULL */
5658 return NULL;
5659}
5660
5661/*
5662 * This one gives you one from a list of things you can put after CREATE
5663 * as defined above.
5664 */
5665static char *
5666create_command_generator(const char *text, int state)
5667{
5668 return create_or_drop_command_generator(text, state, THING_NO_CREATE);
5669}
5670
5671/*
5672 * This function gives you a list of things you can put after a DROP command.
5673 */
5674static char *
5675drop_command_generator(const char *text, int state)
5676{
5677 return create_or_drop_command_generator(text, state, THING_NO_DROP);
5678}
5679
5680/*
5681 * This function gives you a list of things you can put after an ALTER command.
5682 */
5683static char *
5684alter_command_generator(const char *text, int state)
5685{
5686 return create_or_drop_command_generator(text, state, THING_NO_ALTER);
5687}
5688
5689/*
5690 * These functions generate lists using server queries.
5691 * They are all wrappers for _complete_from_query.
5692 */
5693
5694static char *
5695complete_from_query(const char *text, int state)
5696{
5697 /* query is assumed to work for any server version */
5698 return _complete_from_query(completion_charp, NULL, completion_charpp,
5699 completion_verbatim, text, state);
5700}
5701
5702static char *
5703complete_from_versioned_query(const char *text, int state)
5704{
5705 const VersionedQuery *vquery = completion_vquery;
5706
5707 /* Find appropriate array element */
5708 while (pset.sversion < vquery->min_server_version)
5709 vquery++;
5710 /* Fail completion if server is too old */
5711 if (vquery->query == NULL)
5712 return NULL;
5713
5714 return _complete_from_query(vquery->query, NULL, completion_charpp,
5715 completion_verbatim, text, state);
5716}
5717
5718static char *
5719complete_from_schema_query(const char *text, int state)
5720{
5721 /* query is assumed to work for any server version */
5722 return _complete_from_query(NULL, completion_squery, completion_charpp,
5723 completion_verbatim, text, state);
5724}
5725
5726static char *
5727complete_from_versioned_schema_query(const char *text, int state)
5728{
5729 const SchemaQuery *squery = completion_squery;
5730
5731 /* Find appropriate array element */
5732 while (pset.sversion < squery->min_server_version)
5733 squery++;
5734 /* Fail completion if server is too old */
5735 if (squery->catname == NULL)
5736 return NULL;
5737
5738 return _complete_from_query(NULL, squery, completion_charpp,
5739 completion_verbatim, text, state);
5740}
5741
5742
5743/*
5744 * This creates a list of matching things, according to a query described by
5745 * the initial arguments. The caller has already done any work needed to
5746 * select the appropriate query for the server's version.
5747 *
5748 * The query can be one of two kinds:
5749 *
5750 * 1. A simple query, which must contain a restriction clause of the form
5751 * output LIKE '%s'
5752 * where "output" is the same string that the query returns. The %s
5753 * will be replaced by a LIKE pattern to match the already-typed text.
5754 * There can be a second '%s', which will be replaced by a suitably-escaped
5755 * version of the string provided in completion_ref_object. If there is a
5756 * third '%s', it will be replaced by a suitably-escaped version of the string
5757 * provided in completion_ref_schema. Those strings should be set up
5758 * by calling set_completion_reference or set_completion_reference_verbatim.
5759 * Simple queries should return a single column of matches. If "verbatim"
5760 * is true, the matches are returned as-is; otherwise, they are taken to
5761 * be SQL identifiers and quoted if necessary.
5762 *
5763 * 2. A schema query used for completion of both schema and relation names.
5764 * This is represented by a SchemaQuery object; see that typedef for details.
5765 *
5766 * See top of file for examples of both kinds of query.
5767 *
5768 * In addition to the query itself, we accept a null-terminated array of
5769 * literal keywords, which will be returned if they match the input-so-far
5770 * (case insensitively). (These are in addition to keywords specified
5771 * within the schema_query, if any.)
5772 *
5773 * If "verbatim" is true, then we use the given text as-is to match the
5774 * query results; otherwise we parse it as a possibly-qualified identifier,
5775 * and reconstruct suitable quoting afterward.
5776 *
5777 * "text" and "state" are supplied by Readline. "text" is the word we are
5778 * trying to complete. "state" is zero on first call, nonzero later.
5779 *
5780 * readline will call this repeatedly with the same text and varying
5781 * state. On each call, we are supposed to return a malloc'd string
5782 * that is a candidate completion. Return NULL when done.
5783 */
5784static char *
5785_complete_from_query(const char *simple_query,
5786 const SchemaQuery *schema_query,
5787 const char *const *keywords,
5788 bool verbatim,
5789 const char *text, int state)
5790{
5791 static int list_index,
5792 num_schema_only,
5793 num_query_other,
5794 num_keywords;
5795 static PGresult *result = NULL;
5796 static bool non_empty_object;
5797 static bool schemaquoted;
5798 static bool objectquoted;
5799
5800 /*
5801 * If this is the first time for this completion, we fetch a list of our
5802 * "things" from the backend.
5803 */
5804 if (state == 0)
5805 {
5806 PQExpBufferData query_buffer;
5807 char *schemaname;
5808 char *objectname;
5809 char *e_object_like;
5810 char *e_schemaname;
5811 char *e_ref_object;
5812 char *e_ref_schema;
5813
5814 /* Reset static state, ensuring no memory leaks */
5815 list_index = 0;
5816 num_schema_only = 0;
5817 num_query_other = 0;
5818 num_keywords = 0;
5819 PQclear(result);
5820 result = NULL;
5821
5822 /* Parse text, splitting into schema and object name if needed */
5823 if (verbatim)
5824 {
5825 objectname = pg_strdup(text);
5826 schemaname = NULL;
5827 }
5828 else
5829 {
5830 parse_identifier(text,
5831 &schemaname, &objectname,
5832 &schemaquoted, &objectquoted);
5833 }
5834
5835 /* Remember whether the user has typed anything in the object part */
5836 non_empty_object = (*objectname != '\0');
5837
5838 /*
5839 * Convert objectname to a LIKE prefix pattern (e.g. 'foo%'), and set
5840 * up suitably-escaped copies of all the strings we need.
5841 */
5842 e_object_like = make_like_pattern(objectname);
5843
5844 if (schemaname)
5845 e_schemaname = escape_string(schemaname);
5846 else
5847 e_schemaname = NULL;
5848
5849 if (completion_ref_object)
5850 e_ref_object = escape_string(completion_ref_object);
5851 else
5852 e_ref_object = NULL;
5853
5854 if (completion_ref_schema)
5855 e_ref_schema = escape_string(completion_ref_schema);
5856 else
5857 e_ref_schema = NULL;
5858
5859 initPQExpBuffer(&query_buffer);
5860
5861 if (schema_query)
5862 {
5863 Assert(simple_query == NULL);
5864
5865 /*
5866 * We issue different queries depending on whether the input is
5867 * already qualified or not. schema_query gives us the pieces to
5868 * assemble.
5869 */
5870 if (schemaname == NULL || schema_query->namespace == NULL)
5871 {
5872 /* Get unqualified names matching the input-so-far */
5873 appendPQExpBufferStr(&query_buffer, "SELECT ");
5874 if (schema_query->use_distinct)
5875 appendPQExpBufferStr(&query_buffer, "DISTINCT ");
5876 appendPQExpBuffer(&query_buffer,
5877 "%s, NULL::pg_catalog.text FROM %s",
5878 schema_query->result,
5879 schema_query->catname);
5880 if (schema_query->refnamespace && completion_ref_schema)
5881 appendPQExpBufferStr(&query_buffer,
5882 ", pg_catalog.pg_namespace nr");
5883 appendPQExpBufferStr(&query_buffer, " WHERE ");
5884 if (schema_query->selcondition)
5885 appendPQExpBuffer(&query_buffer, "%s AND ",
5886 schema_query->selcondition);
5887 appendPQExpBuffer(&query_buffer, "(%s) LIKE '%s'",
5888 schema_query->result,
5889 e_object_like);
5890 if (schema_query->viscondition)
5891 appendPQExpBuffer(&query_buffer, " AND %s",
5892 schema_query->viscondition);
5893 if (schema_query->refname)
5894 {
5895 Assert(completion_ref_object);
5896 appendPQExpBuffer(&query_buffer, " AND %s = '%s'",
5897 schema_query->refname, e_ref_object);
5898 if (schema_query->refnamespace && completion_ref_schema)
5899 appendPQExpBuffer(&query_buffer,
5900 " AND %s = nr.oid AND nr.nspname = '%s'",
5901 schema_query->refnamespace,
5902 e_ref_schema);
5903 else if (schema_query->refviscondition)
5904 appendPQExpBuffer(&query_buffer,
5905 " AND %s",
5906 schema_query->refviscondition);
5907 }
5908
5909 /*
5910 * When fetching relation names, suppress system catalogs
5911 * unless the input-so-far begins with "pg_". This is a
5912 * compromise between not offering system catalogs for
5913 * completion at all, and having them swamp the result when
5914 * the input is just "p".
5915 */
5916 if (strcmp(schema_query->catname,
5917 "pg_catalog.pg_class c") == 0 &&
5918 strncmp(objectname, "pg_", 3) != 0)
5919 {
5920 appendPQExpBufferStr(&query_buffer,
5921 " AND c.relnamespace <> (SELECT oid FROM"
5922 " pg_catalog.pg_namespace WHERE nspname = 'pg_catalog')");
5923 }
5924
5925 /*
5926 * If the target object type can be schema-qualified, add in
5927 * schema names matching the input-so-far.
5928 */
5929 if (schema_query->namespace)
5930 {
5931 appendPQExpBuffer(&query_buffer, "\nUNION ALL\n"
5932 "SELECT NULL::pg_catalog.text, n.nspname "
5933 "FROM pg_catalog.pg_namespace n "
5934 "WHERE n.nspname LIKE '%s'",
5935 e_object_like);
5936
5937 /*
5938 * Likewise, suppress system schemas unless the
5939 * input-so-far begins with "pg_".
5940 */
5941 if (strncmp(objectname, "pg_", 3) != 0)
5942 appendPQExpBufferStr(&query_buffer,
5943 " AND n.nspname NOT LIKE E'pg\\\\_%'");
5944
5945 /*
5946 * Since we're matching these schema names to the object
5947 * name, handle their quoting using the object name's
5948 * quoting state.
5949 */
5950 schemaquoted = objectquoted;
5951 }
5952 }
5953 else
5954 {
5955 /* Input is qualified, so produce only qualified names */
5956 appendPQExpBufferStr(&query_buffer, "SELECT ");
5957 if (schema_query->use_distinct)
5958 appendPQExpBufferStr(&query_buffer, "DISTINCT ");
5959 appendPQExpBuffer(&query_buffer, "%s, n.nspname "
5960 "FROM %s, pg_catalog.pg_namespace n",
5961 schema_query->result,
5962 schema_query->catname);
5963 if (schema_query->refnamespace && completion_ref_schema)
5964 appendPQExpBufferStr(&query_buffer,
5965 ", pg_catalog.pg_namespace nr");
5966 appendPQExpBuffer(&query_buffer, " WHERE %s = n.oid AND ",
5967 schema_query->namespace);
5968 if (schema_query->selcondition)
5969 appendPQExpBuffer(&query_buffer, "%s AND ",
5970 schema_query->selcondition);
5971 appendPQExpBuffer(&query_buffer, "(%s) LIKE '%s' AND ",
5972 schema_query->result,
5973 e_object_like);
5974 appendPQExpBuffer(&query_buffer, "n.nspname = '%s'",
5975 e_schemaname);
5976 if (schema_query->refname)
5977 {
5978 Assert(completion_ref_object);
5979 appendPQExpBuffer(&query_buffer, " AND %s = '%s'",
5980 schema_query->refname, e_ref_object);
5981 if (schema_query->refnamespace && completion_ref_schema)
5982 appendPQExpBuffer(&query_buffer,
5983 " AND %s = nr.oid AND nr.nspname = '%s'",
5984 schema_query->refnamespace,
5985 e_ref_schema);
5986 else if (schema_query->refviscondition)
5987 appendPQExpBuffer(&query_buffer,
5988 " AND %s",
5989 schema_query->refviscondition);
5990 }
5991 }
5992 }
5993 else
5994 {
5995 Assert(simple_query);
5996 /* simple_query is an sprintf-style format string */
5997 appendPQExpBuffer(&query_buffer, simple_query,
5998 e_object_like,
5999 e_ref_object, e_ref_schema);
6000 }
6001
6002 /* Limit the number of records in the result */
6003 appendPQExpBuffer(&query_buffer, "\nLIMIT %d",
6004 completion_max_records);
6005
6006 /* Finally, we can issue the query */
6007 result = exec_query(query_buffer.data);
6008
6009 /* Clean up */
6010 termPQExpBuffer(&query_buffer);
6011 free(schemaname);
6012 free(objectname);
6013 free(e_object_like);
6014 free(e_schemaname);
6015 free(e_ref_object);
6016 free(e_ref_schema);
6017 }
6018
6019 /* Return the next result, if any, but not if the query failed */
6020 if (result && PQresultStatus(result) == PGRES_TUPLES_OK)
6021 {
6022 int nskip;
6023
6024 while (list_index < PQntuples(result))
6025 {
6026 const char *item = NULL;
6027 const char *nsp = NULL;
6028
6029 if (!PQgetisnull(result, list_index, 0))
6030 item = PQgetvalue(result, list_index, 0);
6031 if (PQnfields(result) > 1 &&
6032 !PQgetisnull(result, list_index, 1))
6033 nsp = PQgetvalue(result, list_index, 1);
6034 list_index++;
6035
6036 /* In verbatim mode, we return all the items as-is */
6037 if (verbatim)
6038 {
6039 num_query_other++;
6040 return pg_strdup(item);
6041 }
6042
6043 /*
6044 * In normal mode, a name requiring quoting will be returned only
6045 * if the input was empty or quoted. Otherwise the user might see
6046 * completion inserting a quote she didn't type, which is
6047 * surprising. This restriction also dodges some odd behaviors of
6048 * some versions of readline/libedit.
6049 */
6050 if (non_empty_object)
6051 {
6052 if (item && !objectquoted && identifier_needs_quotes(item))
6053 continue;
6054 if (nsp && !schemaquoted && identifier_needs_quotes(nsp))
6055 continue;
6056 }
6057
6058 /* Count schema-only results for hack below */
6059 if (item == NULL && nsp != NULL)
6060 num_schema_only++;
6061 else
6062 num_query_other++;
6063
6064 return requote_identifier(nsp, item, schemaquoted, objectquoted);
6065 }
6066
6067 /*
6068 * When the query result is exhausted, check for hard-wired keywords.
6069 * These will only be returned if they match the input-so-far,
6070 * ignoring case.
6071 */
6072 nskip = list_index - PQntuples(result);
6073 if (schema_query && schema_query->keywords)
6074 {
6075 const char *const *itemp = schema_query->keywords;
6076
6077 while (*itemp)
6078 {
6079 const char *item = *itemp++;
6080
6081 if (nskip-- > 0)
6082 continue;
6083 list_index++;
6084 if (pg_strncasecmp(text, item, strlen(text)) == 0)
6085 {
6086 num_keywords++;
6087 return pg_strdup_keyword_case(item, text);
6088 }
6089 }
6090 }
6091 if (keywords)
6092 {
6093 const char *const *itemp = keywords;
6094
6095 while (*itemp)
6096 {
6097 const char *item = *itemp++;
6098
6099 if (nskip-- > 0)
6100 continue;
6101 list_index++;
6102 if (pg_strncasecmp(text, item, strlen(text)) == 0)
6103 {
6104 num_keywords++;
6105 return pg_strdup_keyword_case(item, text);
6106 }
6107 }
6108 }
6109 }
6110
6111 /*
6112 * Hack: if we returned only bare schema names, don't let Readline add a
6113 * space afterwards. Otherwise the schema will stop being part of the
6114 * completion subject text, which is not what we want.
6115 */
6116 if (num_schema_only > 0 && num_query_other == 0 && num_keywords == 0)
6117 rl_completion_append_character = '\0';
6118
6119 /* No more matches, so free the result structure and return null */
6120 PQclear(result);
6121 result = NULL;
6122 return NULL;
6123}
6124
6125
6126/*
6127 * Set up completion_ref_object and completion_ref_schema
6128 * by parsing the given word. These variables can then be
6129 * used in a query passed to _complete_from_query.
6130 */
6131static void
6132set_completion_reference(const char *word)
6133{
6134 bool schemaquoted,
6135 objectquoted;
6136
6137 parse_identifier(word,
6138 &completion_ref_schema, &completion_ref_object,
6139 &schemaquoted, &objectquoted);
6140}
6141
6142/*
6143 * Set up completion_ref_object when it should just be
6144 * the given word verbatim.
6145 */
6146static void
6147set_completion_reference_verbatim(const char *word)
6148{
6149 completion_ref_schema = NULL;
6150 completion_ref_object = pg_strdup(word);
6151}
6152
6153
6154/*
6155 * This function returns in order one of a fixed, NULL pointer terminated list
6156 * of strings (if matching). This can be used if there are only a fixed number
6157 * SQL words that can appear at certain spot.
6158 */
6159static char *
6160complete_from_list(const char *text, int state)
6161{
6162 static int string_length,
6163 list_index,
6164 matches;
6165 static bool casesensitive;
6166 const char *item;
6167
6168 /* need to have a list */
6169 Assert(completion_charpp != NULL);
6170
6171 /* Initialization */
6172 if (state == 0)
6173 {
6174 list_index = 0;
6175 string_length = strlen(text);
6176 casesensitive = completion_case_sensitive;
6177 matches = 0;
6178 }
6179
6180 while ((item = completion_charpp[list_index++]))
6181 {
6182 /* First pass is case sensitive */
6183 if (casesensitive && strncmp(text, item, string_length) == 0)
6184 {
6185 matches++;
6186 return pg_strdup(item);
6187 }
6188
6189 /* Second pass is case insensitive, don't bother counting matches */
6190 if (!casesensitive && pg_strncasecmp(text, item, string_length) == 0)
6191 {
6192 if (completion_case_sensitive)
6193 return pg_strdup(item);
6194 else
6195
6196 /*
6197 * If case insensitive matching was requested initially,
6198 * adjust the case according to setting.
6199 */
6200 return pg_strdup_keyword_case(item, text);
6201 }
6202 }
6203
6204 /*
6205 * No matches found. If we're not case insensitive already, lets switch to
6206 * being case insensitive and try again
6207 */
6208 if (casesensitive && matches == 0)
6209 {
6210 casesensitive = false;
6211 list_index = 0;
6212 state++;
6213 return complete_from_list(text, state);
6214 }
6215
6216 /* If no more matches, return null. */
6217 return NULL;
6218}
6219
6220
6221/*
6222 * This function returns one fixed string the first time even if it doesn't
6223 * match what's there, and nothing the second time. The string
6224 * to be used must be in completion_charp.
6225 *
6226 * If the given string is "", this has the effect of preventing readline
6227 * from doing any completion. (Without this, readline tries to do filename
6228 * completion which is seldom the right thing.)
6229 *
6230 * If the given string is not empty, readline will replace whatever the
6231 * user typed with that string. This behavior might be useful if it's
6232 * completely certain that we know what must appear at a certain spot,
6233 * so that it's okay to overwrite misspellings. In practice, given the
6234 * relatively lame parsing technology used in this file, the level of
6235 * certainty is seldom that high, so that you probably don't want to
6236 * use this. Use complete_from_list with a one-element list instead;
6237 * that won't try to auto-correct "misspellings".
6238 */
6239static char *
6240complete_from_const(const char *text, int state)
6241{
6242 Assert(completion_charp != NULL);
6243 if (state == 0)
6244 {
6245 if (completion_case_sensitive)
6246 return pg_strdup(completion_charp);
6247 else
6248
6249 /*
6250 * If case insensitive matching was requested initially, adjust
6251 * the case according to setting.
6252 */
6253 return pg_strdup_keyword_case(completion_charp, text);
6254 }
6255 else
6256 return NULL;
6257}
6258
6259
6260/*
6261 * This function appends the variable name with prefix and suffix to
6262 * the variable names array.
6263 */
6264static void
6265append_variable_names(char ***varnames, int *nvars,
6266 int *maxvars, const char *varname,
6267 const char *prefix, const char *suffix)
6268{
6269 if (*nvars >= *maxvars)
6270 {
6271 *maxvars *= 2;
6272 *varnames = (char **) pg_realloc(*varnames,
6273 ((*maxvars) + 1) * sizeof(char *));
6274 }
6275
6276 (*varnames)[(*nvars)++] = psprintf("%s%s%s", prefix, varname, suffix);
6277}
6278
6279
6280/*
6281 * This function supports completion with the name of a psql variable.
6282 * The variable names can be prefixed and suffixed with additional text
6283 * to support quoting usages. If need_value is true, only variables
6284 * that are currently set are included; otherwise, special variables
6285 * (those that have hooks) are included even if currently unset.
6286 */
6287static char **
6288complete_from_variables(const char *text, const char *prefix, const char *suffix,
6289 bool need_value)
6290{
6291 char **matches;
6292 char **varnames;
6293 int nvars = 0;
6294 int maxvars = 100;
6295 int i;
6296 struct _variable *ptr;
6297
6298 varnames = (char **) pg_malloc((maxvars + 1) * sizeof(char *));
6299
6300 for (ptr = pset.vars->next; ptr; ptr = ptr->next)
6301 {
6302 if (need_value && !(ptr->value))
6303 continue;
6304 append_variable_names(&varnames, &nvars, &maxvars, ptr->name,
6305 prefix, suffix);
6306 }
6307
6308 varnames[nvars] = NULL;
6309 COMPLETE_WITH_LIST_CS((const char *const *) varnames);
6310
6311 for (i = 0; i < nvars; i++)
6312 free(varnames[i]);
6313 free(varnames);
6314
6315 return matches;
6316}
6317
6318
6319/*
6320 * This function returns in order one of a fixed, NULL pointer terminated list
6321 * of string that matches file names or optionally specified list of keywords.
6322 *
6323 * If completion_charpp is set to a null-terminated array of literal keywords,
6324 * those keywords are added to the completion results alongside filenames if
6325 * they case-insensitively match the current input.
6326 */
6327static char *
6328complete_from_files(const char *text, int state)
6329{
6330 static int list_index;
6331 static bool files_done;
6332 const char *item;
6333
6334 /* Initialization */
6335 if (state == 0)
6336 {
6337 list_index = 0;
6338 files_done = false;
6339 }
6340
6341 if (!files_done)
6342 {
6343 char *result = _complete_from_files(text, state);
6344
6345 /* Return a filename that matches */
6346 if (result)
6347 return result;
6348
6349 /* There are no more matching files */
6350 files_done = true;
6351 }
6352
6353 if (!completion_charpp)
6354 return NULL;
6355
6356 /*
6357 * Check for hard-wired keywords. These will only be returned if they
6358 * match the input-so-far, ignoring case.
6359 */
6360 while ((item = completion_charpp[list_index++]))
6361 {
6362 if (pg_strncasecmp(text, item, strlen(text)) == 0)
6363 {
6364 completion_force_quote = false;
6365 return pg_strdup_keyword_case(item, text);
6366 }
6367 }
6368
6369 return NULL;
6370}
6371
6372/*
6373 * This function wraps rl_filename_completion_function() to strip quotes from
6374 * the input before searching for matches and to quote any matches for which
6375 * the consuming command will require it.
6376 *
6377 * Caller must set completion_charp to a zero- or one-character string
6378 * containing the escape character. This is necessary since \copy has no
6379 * escape character, but every other backslash command recognizes "\" as an
6380 * escape character.
6381 *
6382 * Caller must also set completion_force_quote to indicate whether to force
6383 * quotes around the result. (The SQL COPY command requires that.)
6384 */
6385static char *
6386_complete_from_files(const char *text, int state)
6387{
6388#ifdef USE_FILENAME_QUOTING_FUNCTIONS
6389
6390 /*
6391 * If we're using a version of Readline that supports filename quoting
6392 * hooks, rely on those, and invoke rl_filename_completion_function()
6393 * without messing with its arguments. Readline does stuff internally
6394 * that does not work well at all if we try to handle dequoting here.
6395 * Instead, Readline will call quote_file_name() and dequote_file_name()
6396 * (see below) at appropriate times.
6397 *
6398 * ... or at least, mostly it will. There are some paths involving
6399 * unmatched file names in which Readline never calls quote_file_name(),
6400 * and if left to its own devices it will incorrectly append a quote
6401 * anyway. Set rl_completion_suppress_quote to prevent that. If we do
6402 * get to quote_file_name(), we'll clear this again. (Yes, this seems
6403 * like it's working around Readline bugs.)
6404 */
6405#ifdef HAVE_RL_COMPLETION_SUPPRESS_QUOTE
6406 rl_completion_suppress_quote = 1;
6407#endif
6408
6409 /* If user typed a quote, force quoting (never remove user's quote) */
6410 if (*text == '\'')
6411 completion_force_quote = true;
6412
6413 return rl_filename_completion_function(text, state);
6414#else
6415
6416 /*
6417 * Otherwise, we have to do the best we can.
6418 */
6419 static const char *unquoted_text;
6420 char *unquoted_match;
6421 char *ret = NULL;
6422
6423 /* If user typed a quote, force quoting (never remove user's quote) */
6424 if (*text == '\'')
6425 completion_force_quote = true;
6426
6427 if (state == 0)
6428 {
6429 /* Initialization: stash the unquoted input. */
6430 unquoted_text = strtokx(text, "", NULL, "'", *completion_charp,
6431 false, true, pset.encoding);
6432 /* expect a NULL return for the empty string only */
6433 if (!unquoted_text)
6434 {
6435 Assert(*text == '\0');
6436 unquoted_text = text;
6437 }
6438 }
6439
6440 unquoted_match = rl_filename_completion_function(unquoted_text, state);
6441 if (unquoted_match)
6442 {
6443 struct stat statbuf;
6444 bool is_dir = (stat(unquoted_match, &statbuf) == 0 &&
6445 S_ISDIR(statbuf.st_mode) != 0);
6446
6447 /* Re-quote the result, if needed. */
6448 ret = quote_if_needed(unquoted_match, " \t\r\n\"`",
6449 '\'', *completion_charp,
6450 completion_force_quote,
6451 pset.encoding);
6452 if (ret)
6453 free(unquoted_match);
6454 else
6455 ret = unquoted_match;
6456
6457 /*
6458 * If it's a directory, replace trailing quote with a slash; this is
6459 * usually more convenient. (If we didn't quote, leave this to
6460 * libedit.)
6461 */
6462 if (*ret == '\'' && is_dir)
6463 {
6464 char *retend = ret + strlen(ret) - 1;
6465
6466 Assert(*retend == '\'');
6467 *retend = '/';
6468 /* Prevent libedit from adding a space, too */
6469 rl_completion_append_character = '\0';
6470 }
6471 }
6472
6473 return ret;
6474#endif /* USE_FILENAME_QUOTING_FUNCTIONS */
6475}
6476
6477
6478/* HELPER FUNCTIONS */
6479
6480
6481/*
6482 * Make a pg_strdup copy of s and convert the case according to
6483 * COMP_KEYWORD_CASE setting, using ref as the text that was already entered.
6484 */
6485static char *
6486pg_strdup_keyword_case(const char *s, const char *ref)
6487{
6488 char *ret,
6489 *p;
6490 unsigned char first = ref[0];
6491
6492 ret = pg_strdup(s);
6493
6496 pset.comp_case == PSQL_COMP_CASE_PRESERVE_UPPER) && islower(first)) ||
6497 (pset.comp_case == PSQL_COMP_CASE_PRESERVE_LOWER && !isalpha(first)))
6498 {
6499 for (p = ret; *p; p++)
6500 *p = pg_tolower((unsigned char) *p);
6501 }
6502 else
6503 {
6504 for (p = ret; *p; p++)
6505 *p = pg_toupper((unsigned char) *p);
6506 }
6507
6508 return ret;
6509}
6510
6511
6512/*
6513 * escape_string - Escape argument for use as string literal.
6514 *
6515 * The returned value has to be freed.
6516 */
6517static char *
6518escape_string(const char *text)
6519{
6520 size_t text_length;
6521 char *result;
6522
6523 text_length = strlen(text);
6524
6525 result = pg_malloc(text_length * 2 + 1);
6526 PQescapeStringConn(pset.db, result, text, text_length, NULL);
6527
6528 return result;
6529}
6530
6531
6532/*
6533 * make_like_pattern - Convert argument to a LIKE prefix pattern.
6534 *
6535 * We escape _ and % in the given text by backslashing, append a % to
6536 * represent "any subsequent characters", and then pass the string through
6537 * escape_string() so it's ready to insert in a query. The result needs
6538 * to be freed.
6539 */
6540static char *
6541make_like_pattern(const char *word)
6542{
6543 char *result;
6544 char *buffer = pg_malloc(strlen(word) * 2 + 2);
6545 char *bptr = buffer;
6546
6547 while (*word)
6548 {
6549 if (*word == '_' || *word == '%')
6550 *bptr++ = '\\';
6551 if (IS_HIGHBIT_SET(*word))
6552 {
6553 /*
6554 * Transfer multibyte characters without further processing, to
6555 * avoid getting confused in unsafe client encodings.
6556 */
6557 int chlen = PQmblenBounded(word, pset.encoding);
6558
6559 while (chlen-- > 0)
6560 *bptr++ = *word++;
6561 }
6562 else
6563 *bptr++ = *word++;
6564 }
6565 *bptr++ = '%';
6566 *bptr = '\0';
6567
6568 result = escape_string(buffer);
6569 free(buffer);
6570 return result;
6571}
6572
6573
6574/*
6575 * parse_identifier - Parse a possibly-schema-qualified SQL identifier.
6576 *
6577 * This involves splitting off the schema name if present, de-quoting,
6578 * and downcasing any unquoted text. We are a bit laxer than the backend
6579 * in that we allow just portions of a name to be quoted --- that's because
6580 * psql metacommands have traditionally behaved that way.
6581 *
6582 * Outputs are a malloc'd schema name (NULL if none), malloc'd object name,
6583 * and booleans telling whether any part of the schema and object name was
6584 * double-quoted.
6585 */
6586static void
6587parse_identifier(const char *ident,
6588 char **schemaname, char **objectname,
6589 bool *schemaquoted, bool *objectquoted)
6590{
6591 size_t buflen = strlen(ident) + 1;
6592 bool enc_is_single_byte = (pg_encoding_max_length(pset.encoding) == 1);
6593 char *sname;
6594 char *oname;
6595 char *optr;
6596 bool inquotes;
6597
6598 /* Initialize, making a certainly-large-enough output buffer */
6599 sname = NULL;
6600 oname = pg_malloc(buflen);
6601 *schemaquoted = *objectquoted = false;
6602 /* Scan */
6603 optr = oname;
6604 inquotes = false;
6605 while (*ident)
6606 {
6607 unsigned char ch = (unsigned char) *ident++;
6608
6609 if (ch == '"')
6610 {
6611 if (inquotes && *ident == '"')
6612 {
6613 /* two quote marks within a quoted identifier = emit quote */
6614 *optr++ = '"';
6615 ident++;
6616 }
6617 else
6618 {
6619 inquotes = !inquotes;
6620 *objectquoted = true;
6621 }
6622 }
6623 else if (ch == '.' && !inquotes)
6624 {
6625 /* Found a schema name, transfer it to sname / *schemaquoted */
6626 *optr = '\0';
6627 free(sname); /* drop any catalog name */
6628 sname = oname;
6629 oname = pg_malloc(buflen);
6630 optr = oname;
6631 *schemaquoted = *objectquoted;
6632 *objectquoted = false;
6633 }
6634 else if (!enc_is_single_byte && IS_HIGHBIT_SET(ch))
6635 {
6636 /*
6637 * Transfer multibyte characters without further processing. They
6638 * wouldn't be affected by our downcasing rule anyway, and this
6639 * avoids possibly doing the wrong thing in unsafe client
6640 * encodings.
6641 */
6642 int chlen = PQmblenBounded(ident - 1, pset.encoding);
6643
6644 *optr++ = (char) ch;
6645 while (--chlen > 0)
6646 *optr++ = *ident++;
6647 }
6648 else
6649 {
6650 if (!inquotes)
6651 {
6652 /*
6653 * This downcasing transformation should match the backend's
6654 * downcase_identifier() as best we can. We do not know the
6655 * backend's locale, though, so it's necessarily approximate.
6656 * We assume that psql is operating in the same locale and
6657 * encoding as the backend.
6658 */
6659 if (ch >= 'A' && ch <= 'Z')
6660 ch += 'a' - 'A';
6661 else if (enc_is_single_byte && IS_HIGHBIT_SET(ch) && isupper(ch))
6662 ch = tolower(ch);
6663 }
6664 *optr++ = (char) ch;
6665 }
6666 }
6667
6668 *optr = '\0';
6669 *schemaname = sname;
6670 *objectname = oname;
6671}
6672
6673
6674/*
6675 * requote_identifier - Reconstruct a possibly-schema-qualified SQL identifier.
6676 *
6677 * Build a malloc'd string containing the identifier, with quoting applied
6678 * as necessary. This is more or less the inverse of parse_identifier;
6679 * in particular, if an input component was quoted, we'll quote the output
6680 * even when that isn't strictly required.
6681 *
6682 * Unlike parse_identifier, we handle the case where a schema and no
6683 * object name is provided, producing just "schema.".
6684 */
6685static char *
6686requote_identifier(const char *schemaname, const char *objectname,
6687 bool quote_schema, bool quote_object)
6688{
6689 char *result;
6690 size_t buflen = 1; /* count the trailing \0 */
6691 char *ptr;
6692
6693 /*
6694 * We could use PQescapeIdentifier for some of this, but not all, and it
6695 * adds more notational cruft than it seems worth.
6696 */
6697 if (schemaname)
6698 {
6699 buflen += strlen(schemaname) + 1; /* +1 for the dot */
6700 if (!quote_schema)
6701 quote_schema = identifier_needs_quotes(schemaname);
6702 if (quote_schema)
6703 {
6704 buflen += 2; /* account for quote marks */
6705 for (const char *p = schemaname; *p; p++)
6706 {
6707 if (*p == '"')
6708 buflen++;
6709 }
6710 }
6711 }
6712 if (objectname)
6713 {
6714 buflen += strlen(objectname);
6715 if (!quote_object)
6716 quote_object = identifier_needs_quotes(objectname);
6717 if (quote_object)
6718 {
6719 buflen += 2; /* account for quote marks */
6720 for (const char *p = objectname; *p; p++)
6721 {
6722 if (*p == '"')
6723 buflen++;
6724 }
6725 }
6726 }
6727 result = pg_malloc(buflen);
6728 ptr = result;
6729 if (schemaname)
6730 {
6731 if (quote_schema)
6732 *ptr++ = '"';
6733 for (const char *p = schemaname; *p; p++)
6734 {
6735 *ptr++ = *p;
6736 if (*p == '"')
6737 *ptr++ = '"';
6738 }
6739 if (quote_schema)
6740 *ptr++ = '"';
6741 *ptr++ = '.';
6742 }
6743 if (objectname)
6744 {
6745 if (quote_object)
6746 *ptr++ = '"';
6747 for (const char *p = objectname; *p; p++)
6748 {
6749 *ptr++ = *p;
6750 if (*p == '"')
6751 *ptr++ = '"';
6752 }
6753 if (quote_object)
6754 *ptr++ = '"';
6755 }
6756 *ptr = '\0';
6757 return result;
6758}
6759
6760
6761/*
6762 * Detect whether an identifier must be double-quoted.
6763 *
6764 * Note we'll quote anything that's not ASCII; the backend's quote_ident()
6765 * does the same. Perhaps this could be relaxed in future.
6766 */
6767static bool
6768identifier_needs_quotes(const char *ident)
6769{
6770 int kwnum;
6771
6772 /* Check syntax. */
6773 if (!((ident[0] >= 'a' && ident[0] <= 'z') || ident[0] == '_'))
6774 return true;
6775 if (strspn(ident, "abcdefghijklmnopqrstuvwxyz0123456789_$") != strlen(ident))
6776 return true;
6777
6778 /*
6779 * Check for keyword. We quote keywords except for unreserved ones.
6780 *
6781 * It is possible that our keyword list doesn't quite agree with the
6782 * server's, but this should be close enough for tab-completion purposes.
6783 *
6784 * Note: ScanKeywordLookup() does case-insensitive comparison, but that's
6785 * fine, since we already know we have all-lower-case.
6786 */
6788
6789 if (kwnum >= 0 && ScanKeywordCategories[kwnum] != UNRESERVED_KEYWORD)
6790 return true;
6791
6792 return false;
6793}
6794
6795
6796/*
6797 * Execute a query, returning NULL if there was any error.
6798 * This should be the preferred way of talking to the database in this file.
6799 */
6800static PGresult *
6801exec_query(const char *query)
6802{
6803 PGresult *result;
6804
6805 if (query == NULL || !pset.db || PQstatus(pset.db) != CONNECTION_OK)
6806 return NULL;
6807
6808 result = PQexec(pset.db, query);
6809
6810 if (PQresultStatus(result) != PGRES_TUPLES_OK)
6811 {
6812 /*
6813 * Printing an error while the user is typing would be quite annoying,
6814 * so we don't. This does complicate debugging of this code; but you
6815 * can look in the server log instead.
6816 */
6817#ifdef NOT_USED
6818 pg_log_error("tab completion query failed: %s\nQuery was:\n%s",
6819 PQerrorMessage(pset.db), query);
6820#endif
6821 PQclear(result);
6822 result = NULL;
6823 }
6824
6825 return result;
6826}
6827
6828
6829/*
6830 * Parse all the word(s) before point.
6831 *
6832 * Returns a malloc'd array of character pointers that point into the malloc'd
6833 * data array returned to *buffer; caller must free() both of these when done.
6834 * *nwords receives the number of words found, ie, the valid length of the
6835 * return array.
6836 *
6837 * Words are returned right to left, that is, previous_words[0] gets the last
6838 * word before point, previous_words[1] the next-to-last, etc.
6839 */
6840static char **
6841get_previous_words(int point, char **buffer, int *nwords)
6842{
6843 char **previous_words;
6844 char *buf;
6845 char *outptr;
6846 int words_found = 0;
6847 int i;
6848
6849 /*
6850 * If we have anything in tab_completion_query_buf, paste it together with
6851 * rl_line_buffer to construct the full query. Otherwise we can just use
6852 * rl_line_buffer as the input string.
6853 */
6855 {
6857 buf = pg_malloc(point + i + 2);
6859 buf[i++] = '\n';
6860 memcpy(buf + i, rl_line_buffer, point);
6861 i += point;
6862 buf[i] = '\0';
6863 /* Readjust point to reference appropriate offset in buf */
6864 point = i;
6865 }
6866 else
6867 buf = rl_line_buffer;
6868
6869 /*
6870 * Allocate an array of string pointers and a buffer to hold the strings
6871 * themselves. The worst case is that the line contains only
6872 * non-whitespace WORD_BREAKS characters, making each one a separate word.
6873 * This is usually much more space than we need, but it's cheaper than
6874 * doing a separate malloc() for each word.
6875 */
6876 previous_words = (char **) pg_malloc(point * sizeof(char *));
6877 *buffer = outptr = (char *) pg_malloc(point * 2);
6878
6879 /*
6880 * First we look for a non-word char before the current point. (This is
6881 * probably useless, if readline is on the same page as we are about what
6882 * is a word, but if so it's cheap.)
6883 */
6884 for (i = point - 1; i >= 0; i--)
6885 {
6886 if (strchr(WORD_BREAKS, buf[i]))
6887 break;
6888 }
6889 point = i;
6890
6891 /*
6892 * Now parse words, working backwards, until we hit start of line. The
6893 * backwards scan has some interesting but intentional properties
6894 * concerning parenthesis handling.
6895 */
6896 while (point >= 0)
6897 {
6898 int start,
6899 end;
6900 bool inquotes = false;
6901 int parentheses = 0;
6902
6903 /* now find the first non-space which then constitutes the end */
6904 end = -1;
6905 for (i = point; i >= 0; i--)
6906 {
6907 if (!isspace((unsigned char) buf[i]))
6908 {
6909 end = i;
6910 break;
6911 }
6912 }
6913 /* if no end found, we're done */
6914 if (end < 0)
6915 break;
6916
6917 /*
6918 * Otherwise we now look for the start. The start is either the last
6919 * character before any word-break character going backwards from the
6920 * end, or it's simply character 0. We also handle open quotes and
6921 * parentheses.
6922 */
6923 for (start = end; start > 0; start--)
6924 {
6925 if (buf[start] == '"')
6926 inquotes = !inquotes;
6927 if (!inquotes)
6928 {
6929 if (buf[start] == ')')
6930 parentheses++;
6931 else if (buf[start] == '(')
6932 {
6933 if (--parentheses <= 0)
6934 break;
6935 }
6936 else if (parentheses == 0 &&
6937 strchr(WORD_BREAKS, buf[start - 1]))
6938 break;
6939 }
6940 }
6941
6942 /* Return the word located at start to end inclusive */
6943 previous_words[words_found++] = outptr;
6944 i = end - start + 1;
6945 memcpy(outptr, &buf[start], i);
6946 outptr += i;
6947 *outptr++ = '\0';
6948
6949 /* Continue searching */
6950 point = start - 1;
6951 }
6952
6953 /* Release parsing input workspace, if we made one above */
6954 if (buf != rl_line_buffer)
6955 free(buf);
6956
6957 *nwords = words_found;
6958 return previous_words;
6959}
6960
6961/*
6962 * Look up the type for the GUC variable with the passed name.
6963 *
6964 * Returns NULL if the variable is unknown. Otherwise the returned string,
6965 * containing the type, has to be freed.
6966 */
6967static char *
6968get_guctype(const char *varname)
6969{
6970 PQExpBufferData query_buffer;
6971 char *e_varname;
6972 PGresult *result;
6973 char *guctype = NULL;
6974
6975 e_varname = escape_string(varname);
6976
6977 initPQExpBuffer(&query_buffer);
6978 appendPQExpBuffer(&query_buffer,
6979 "SELECT vartype FROM pg_catalog.pg_settings "
6980 "WHERE pg_catalog.lower(name) = pg_catalog.lower('%s')",
6981 e_varname);
6982
6983 result = exec_query(query_buffer.data);
6984 termPQExpBuffer(&query_buffer);
6985 free(e_varname);
6986
6987 if (PQresultStatus(result) == PGRES_TUPLES_OK && PQntuples(result) > 0)
6988 guctype = pg_strdup(PQgetvalue(result, 0, 0));
6989
6990 PQclear(result);
6991
6992 return guctype;
6993}
6994
6995#ifdef USE_FILENAME_QUOTING_FUNCTIONS
6996
6997/*
6998 * Quote a filename according to SQL rules, returning a malloc'd string.
6999 * completion_charp must point to escape character or '\0', and
7000 * completion_force_quote must be set correctly, as per comments for
7001 * complete_from_files().
7002 */
7003static char *
7004quote_file_name(char *fname, int match_type, char *quote_pointer)
7005{
7006 char *s;
7007 struct stat statbuf;
7008
7009 /* Quote if needed. */
7010 s = quote_if_needed(fname, " \t\r\n\"`",
7011 '\'', *completion_charp,
7012 completion_force_quote,
7013 pset.encoding);
7014 if (!s)
7015 s = pg_strdup(fname);
7016
7017 /*
7018 * However, some of the time we have to strip the trailing quote from what
7019 * we send back. Never strip the trailing quote if the user already typed
7020 * one; otherwise, suppress the trailing quote if we have multiple/no
7021 * matches (because we don't want to add a quote if the input is seemingly
7022 * unfinished), or if the input was already quoted (because Readline will
7023 * do arguably-buggy things otherwise), or if the file does not exist, or
7024 * if it's a directory.
7025 */
7026 if (*s == '\'' &&
7027 completion_last_char != '\'' &&
7028 (match_type != SINGLE_MATCH ||
7029 (quote_pointer && *quote_pointer == '\'') ||
7030 stat(fname, &statbuf) != 0 ||
7031 S_ISDIR(statbuf.st_mode)))
7032 {
7033 char *send = s + strlen(s) - 1;
7034
7035 Assert(*send == '\'');
7036 *send = '\0';
7037 }
7038
7039 /*
7040 * And now we can let Readline do its thing with possibly adding a quote
7041 * on its own accord. (This covers some additional cases beyond those
7042 * dealt with above.)
7043 */
7044#ifdef HAVE_RL_COMPLETION_SUPPRESS_QUOTE
7045 rl_completion_suppress_quote = 0;
7046#endif
7047
7048 /*
7049 * If user typed a leading quote character other than single quote (i.e.,
7050 * double quote), zap it, so that we replace it with the correct single
7051 * quote.
7052 */
7053 if (quote_pointer && *quote_pointer != '\'')
7054 *quote_pointer = '\0';
7055
7056 return s;
7057}
7058
7059/*
7060 * Dequote a filename, if it's quoted.
7061 * completion_charp must point to escape character or '\0', as per
7062 * comments for complete_from_files().
7063 */
7064static char *
7065dequote_file_name(char *fname, int quote_char)
7066{
7067 char *unquoted_fname;
7068
7069 /*
7070 * If quote_char is set, it's not included in "fname". We have to add it
7071 * or strtokx will not interpret the string correctly (notably, it won't
7072 * recognize escapes).
7073 */
7074 if (quote_char == '\'')
7075 {
7076 char *workspace = (char *) pg_malloc(strlen(fname) + 2);
7077
7078 workspace[0] = quote_char;
7079 strcpy(workspace + 1, fname);
7080 unquoted_fname = strtokx(workspace, "", NULL, "'", *completion_charp,
7081 false, true, pset.encoding);
7082 free(workspace);
7083 }
7084 else
7085 unquoted_fname = strtokx(fname, "", NULL, "'", *completion_charp,
7086 false, true, pset.encoding);
7087
7088 /* expect a NULL return for the empty string only */
7089 if (!unquoted_fname)
7090 {
7091 Assert(*fname == '\0');
7092 unquoted_fname = fname;
7093 }
7094
7095 /* readline expects a malloc'd result that it is to free */
7096 return pg_strdup(unquoted_fname);
7097}
7098
7099#endif /* USE_FILENAME_QUOTING_FUNCTIONS */
7100
7101#endif /* USE_READLINE */
bool recognized_connection_string(const char *connstr)
Definition: common.c:2704
struct varlena text
Definition: c.h:708
#define IS_HIGHBIT_SET(ch)
Definition: c.h:1143
uint32 bits32
Definition: c.h:550
#define CppAsString2(x)
Definition: c.h:423
#define lengthof(array)
Definition: c.h:790
const uint8 ScanKeywordCategories[SCANKEYWORDS_NUM_KEYWORDS]
Definition: keywords.c:29
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:7641
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:7704
size_t PQescapeStringConn(PGconn *conn, char *to, const char *from, size_t length, int *error)
Definition: fe-exec.c:4194
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:2279
int PQmblenBounded(const char *s, int encoding)
Definition: fe-misc.c:1266
void * pg_malloc(size_t size)
Definition: fe_memutils.c:47
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
void * pg_realloc(void *ptr, size_t size)
Definition: fe_memutils.c:65
Assert(PointerIsAligned(start, uint64))
return str start
#define free(a)
Definition: header.h:65
#define ident
Definition: indent_codes.h:47
int i
Definition: isn.c:77
static const JsonPathKeyword keywords[]
PGDLLIMPORT const ScanKeywordList ScanKeywords
#define UNRESERVED_KEYWORD
Definition: keywords.h:20
int ScanKeywordLookup(const char *str, const ScanKeywordList *keywords)
Definition: kwlookup.c:38
#define PQgetvalue
Definition: libpq-be-fe.h:253
#define PQclear
Definition: libpq-be-fe.h:245
#define PQnfields
Definition: libpq-be-fe.h:252
#define PQresultStatus
Definition: libpq-be-fe.h:247
#define PQgetisnull
Definition: libpq-be-fe.h:255
#define PQntuples
Definition: libpq-be-fe.h:251
@ CONNECTION_OK
Definition: libpq-fe.h:84
@ PGRES_TUPLES_OK
Definition: libpq-fe.h:128
#define pg_log_error(...)
Definition: logging.h:106
char * pnstrdup(const char *in, Size len)
Definition: mcxt.c:1770
void * arg
static char * buf
Definition: pg_test_fsync.c:72
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:32
unsigned char pg_toupper(unsigned char ch)
Definition: pgstrcasecmp.c:101
unsigned char pg_tolower(unsigned char ch)
Definition: pgstrcasecmp.c:118
int pg_strncasecmp(const char *s1, const char *s2, size_t n)
Definition: pgstrcasecmp.c:65
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:90
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:265
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:367
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:129
char * c
char * psprintf(const char *fmt,...)
Definition: psprintf.c:43
static void word(struct vars *v, int dir, struct state *lp, struct state *rp)
Definition: regcomp.c:1476
PsqlSettings pset
Definition: startup.c:32
@ PSQL_COMP_CASE_PRESERVE_LOWER
Definition: settings.h:66
@ PSQL_COMP_CASE_LOWER
Definition: settings.h:68
@ PSQL_COMP_CASE_PRESERVE_UPPER
Definition: settings.h:65
char * strtokx(const char *s, const char *whitespace, const char *delim, const char *quote, char escape, bool e_strings, bool del_quotes, int encoding)
Definition: stringutils.c:52
char * quote_if_needed(const char *source, const char *entails_quote, char quote, char escape, bool force_quote, int encoding)
Definition: stringutils.c:292
VariableSpace vars
Definition: settings.h:151
PSQL_COMP_CASE comp_case
Definition: settings.h:179
PGconn * db
Definition: settings.h:103
const char * progname
Definition: settings.h:142
struct _variable * next
Definition: variables.h:68
char * name
Definition: variables.h:64
char * value
Definition: variables.h:65
Definition: regguts.h:323
Definition: c.h:695
void initialize_readline(void)
PQExpBuffer tab_completion_query_buf
static bool escape_string(PGconn *conn, PQExpBuffer target, const char *unescaped, size_t unescaped_len, PQExpBuffer escape_err)
Definition: test_escape.c:327
static int32 text_length(Datum str)
Definition: varlena.c:407
const char * name
int pg_encoding_max_length(int encoding)
Definition: wchar.c:2213
#define stat
Definition: win32_port.h:274
#define S_ISDIR(m)
Definition: win32_port.h:315
#define send(s, buf, len, flags)
Definition: win32_port.h:505