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 "SPLIT PARTITION", "MERGE PARTITIONS (",
2777 "OF", "NOT OF");
2778 /* ALTER TABLE xxx ADD */
2779 else if (Matches("ALTER", "TABLE", MatchAny, "ADD"))
2780 {
2781 /*
2782 * make sure to keep this list and the MatchAnyExcept() below in sync
2783 */
2784 COMPLETE_WITH("COLUMN", "CONSTRAINT", "CHECK (", "NOT NULL", "UNIQUE",
2785 "PRIMARY KEY", "EXCLUDE", "FOREIGN KEY");
2786 }
2787 /* ALTER TABLE xxx ADD [COLUMN] yyy */
2788 else if (Matches("ALTER", "TABLE", MatchAny, "ADD", "COLUMN", MatchAny) ||
2789 Matches("ALTER", "TABLE", MatchAny, "ADD", MatchAnyExcept("COLUMN|CONSTRAINT|CHECK|UNIQUE|PRIMARY|NOT|EXCLUDE|FOREIGN")))
2790 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_datatypes);
2791 /* ALTER TABLE xxx ADD CONSTRAINT yyy */
2792 else if (Matches("ALTER", "TABLE", MatchAny, "ADD", "CONSTRAINT", MatchAny))
2793 COMPLETE_WITH("CHECK (", "NOT NULL", "UNIQUE", "PRIMARY KEY", "EXCLUDE", "FOREIGN KEY");
2794 /* ALTER TABLE xxx ADD NOT NULL */
2795 else if (Matches("ALTER", "TABLE", MatchAny, "ADD", "NOT", "NULL"))
2796 COMPLETE_WITH_ATTR(prev4_wd);
2797 else if (Matches("ALTER", "TABLE", MatchAny, "ADD", "CONSTRAINT", MatchAny, "NOT", "NULL"))
2798 COMPLETE_WITH_ATTR(prev6_wd);
2799 /* ALTER TABLE xxx ADD [CONSTRAINT yyy] (PRIMARY KEY|UNIQUE) */
2800 else if (Matches("ALTER", "TABLE", MatchAny, "ADD", "PRIMARY", "KEY") ||
2801 Matches("ALTER", "TABLE", MatchAny, "ADD", "UNIQUE") ||
2802 Matches("ALTER", "TABLE", MatchAny, "ADD", "CONSTRAINT", MatchAny, "PRIMARY", "KEY") ||
2803 Matches("ALTER", "TABLE", MatchAny, "ADD", "CONSTRAINT", MatchAny, "UNIQUE"))
2804 COMPLETE_WITH("(", "USING INDEX");
2805 /* ALTER TABLE xxx ADD PRIMARY KEY USING INDEX */
2806 else if (Matches("ALTER", "TABLE", MatchAny, "ADD", "PRIMARY", "KEY", "USING", "INDEX"))
2807 {
2808 set_completion_reference(prev6_wd);
2809 COMPLETE_WITH_SCHEMA_QUERY(Query_for_unique_index_of_table);
2810 }
2811 /* ALTER TABLE xxx ADD UNIQUE USING INDEX */
2812 else if (Matches("ALTER", "TABLE", MatchAny, "ADD", "UNIQUE", "USING", "INDEX"))
2813 {
2814 set_completion_reference(prev5_wd);
2815 COMPLETE_WITH_SCHEMA_QUERY(Query_for_unique_index_of_table);
2816 }
2817 /* ALTER TABLE xxx ADD CONSTRAINT yyy PRIMARY KEY USING INDEX */
2818 else if (Matches("ALTER", "TABLE", MatchAny, "ADD", "CONSTRAINT", MatchAny,
2819 "PRIMARY", "KEY", "USING", "INDEX"))
2820 {
2821 set_completion_reference(prev8_wd);
2822 COMPLETE_WITH_SCHEMA_QUERY(Query_for_unique_index_of_table);
2823 }
2824 /* ALTER TABLE xxx ADD CONSTRAINT yyy UNIQUE USING INDEX */
2825 else if (Matches("ALTER", "TABLE", MatchAny, "ADD", "CONSTRAINT", MatchAny,
2826 "UNIQUE", "USING", "INDEX"))
2827 {
2828 set_completion_reference(prev7_wd);
2829 COMPLETE_WITH_SCHEMA_QUERY(Query_for_unique_index_of_table);
2830 }
2831 /* ALTER TABLE xxx ENABLE */
2832 else if (Matches("ALTER", "TABLE", MatchAny, "ENABLE"))
2833 COMPLETE_WITH("ALWAYS", "REPLICA", "ROW LEVEL SECURITY", "RULE",
2834 "TRIGGER");
2835 else if (Matches("ALTER", "TABLE", MatchAny, "ENABLE", "REPLICA|ALWAYS"))
2836 COMPLETE_WITH("RULE", "TRIGGER");
2837 else if (Matches("ALTER", "TABLE", MatchAny, "ENABLE", "RULE"))
2838 {
2839 set_completion_reference(prev3_wd);
2840 COMPLETE_WITH_SCHEMA_QUERY(Query_for_rule_of_table);
2841 }
2842 else if (Matches("ALTER", "TABLE", MatchAny, "ENABLE", MatchAny, "RULE"))
2843 {
2844 set_completion_reference(prev4_wd);
2845 COMPLETE_WITH_SCHEMA_QUERY(Query_for_rule_of_table);
2846 }
2847 else if (Matches("ALTER", "TABLE", MatchAny, "ENABLE", "TRIGGER"))
2848 {
2849 set_completion_reference(prev3_wd);
2850 COMPLETE_WITH_SCHEMA_QUERY(Query_for_trigger_of_table);
2851 }
2852 else if (Matches("ALTER", "TABLE", MatchAny, "ENABLE", MatchAny, "TRIGGER"))
2853 {
2854 set_completion_reference(prev4_wd);
2855 COMPLETE_WITH_SCHEMA_QUERY(Query_for_trigger_of_table);
2856 }
2857 /* ALTER TABLE xxx INHERIT */
2858 else if (Matches("ALTER", "TABLE", MatchAny, "INHERIT"))
2859 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables);
2860 /* ALTER TABLE xxx NO */
2861 else if (Matches("ALTER", "TABLE", MatchAny, "NO"))
2862 COMPLETE_WITH("FORCE ROW LEVEL SECURITY", "INHERIT");
2863 /* ALTER TABLE xxx NO INHERIT */
2864 else if (Matches("ALTER", "TABLE", MatchAny, "NO", "INHERIT"))
2865 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables);
2866 /* ALTER TABLE xxx DISABLE */
2867 else if (Matches("ALTER", "TABLE", MatchAny, "DISABLE"))
2868 COMPLETE_WITH("ROW LEVEL SECURITY", "RULE", "TRIGGER");
2869 else if (Matches("ALTER", "TABLE", MatchAny, "DISABLE", "RULE"))
2870 {
2871 set_completion_reference(prev3_wd);
2872 COMPLETE_WITH_SCHEMA_QUERY(Query_for_rule_of_table);
2873 }
2874 else if (Matches("ALTER", "TABLE", MatchAny, "DISABLE", "TRIGGER"))
2875 {
2876 set_completion_reference(prev3_wd);
2877 COMPLETE_WITH_SCHEMA_QUERY(Query_for_trigger_of_table);
2878 }
2879
2880 /* ALTER TABLE xxx ALTER */
2881 else if (Matches("ALTER", "TABLE", MatchAny, "ALTER"))
2882 COMPLETE_WITH_ATTR_PLUS(prev2_wd, "COLUMN", "CONSTRAINT");
2883
2884 /* ALTER TABLE xxx RENAME */
2885 else if (Matches("ALTER", "TABLE", MatchAny, "RENAME"))
2886 COMPLETE_WITH_ATTR_PLUS(prev2_wd, "COLUMN", "CONSTRAINT", "TO");
2887 else if (Matches("ALTER", "TABLE", MatchAny, "ALTER|RENAME", "COLUMN"))
2888 COMPLETE_WITH_ATTR(prev3_wd);
2889
2890 /* ALTER TABLE xxx RENAME yyy */
2891 else if (Matches("ALTER", "TABLE", MatchAny, "RENAME", MatchAnyExcept("CONSTRAINT|TO")))
2892 COMPLETE_WITH("TO");
2893
2894 /* ALTER TABLE xxx RENAME COLUMN/CONSTRAINT yyy */
2895 else if (Matches("ALTER", "TABLE", MatchAny, "RENAME", "COLUMN|CONSTRAINT", MatchAnyExcept("TO")))
2896 COMPLETE_WITH("TO");
2897
2898 /* If we have ALTER TABLE <sth> DROP, provide COLUMN or CONSTRAINT */
2899 else if (Matches("ALTER", "TABLE", MatchAny, "DROP"))
2900 COMPLETE_WITH("COLUMN", "CONSTRAINT");
2901 /* If we have ALTER TABLE <sth> DROP COLUMN, provide list of columns */
2902 else if (Matches("ALTER", "TABLE", MatchAny, "DROP", "COLUMN"))
2903 COMPLETE_WITH_ATTR(prev3_wd);
2904 /* ALTER TABLE <sth> ALTER|DROP|RENAME CONSTRAINT <constraint> */
2905 else if (Matches("ALTER", "TABLE", MatchAny, "ALTER|DROP|RENAME", "CONSTRAINT"))
2906 {
2907 set_completion_reference(prev3_wd);
2908 COMPLETE_WITH_SCHEMA_QUERY(Query_for_constraint_of_table);
2909 }
2910 /* ALTER TABLE <sth> VALIDATE CONSTRAINT <non-validated constraint> */
2911 else if (Matches("ALTER", "TABLE", MatchAny, "VALIDATE", "CONSTRAINT"))
2912 {
2913 set_completion_reference(prev3_wd);
2914 COMPLETE_WITH_SCHEMA_QUERY(Query_for_constraint_of_table_not_validated);
2915 }
2916 /* ALTER TABLE ALTER [COLUMN] <foo> */
2917 else if (Matches("ALTER", "TABLE", MatchAny, "ALTER", "COLUMN", MatchAny) ||
2918 Matches("ALTER", "TABLE", MatchAny, "ALTER", MatchAny))
2919 COMPLETE_WITH("TYPE", "SET", "RESET", "RESTART", "ADD", "DROP");
2920 /* ALTER TABLE ALTER [COLUMN] <foo> ADD */
2921 else if (Matches("ALTER", "TABLE", MatchAny, "ALTER", "COLUMN", MatchAny, "ADD") ||
2922 Matches("ALTER", "TABLE", MatchAny, "ALTER", MatchAny, "ADD"))
2923 COMPLETE_WITH("GENERATED");
2924 /* ALTER TABLE ALTER [COLUMN] <foo> ADD GENERATED */
2925 else if (Matches("ALTER", "TABLE", MatchAny, "ALTER", "COLUMN", MatchAny, "ADD", "GENERATED") ||
2926 Matches("ALTER", "TABLE", MatchAny, "ALTER", MatchAny, "ADD", "GENERATED"))
2927 COMPLETE_WITH("ALWAYS", "BY DEFAULT");
2928 /* ALTER TABLE ALTER [COLUMN] <foo> ADD GENERATED */
2929 else if (Matches("ALTER", "TABLE", MatchAny, "ALTER", "COLUMN", MatchAny, "ADD", "GENERATED", "ALWAYS") ||
2930 Matches("ALTER", "TABLE", MatchAny, "ALTER", MatchAny, "ADD", "GENERATED", "ALWAYS") ||
2931 Matches("ALTER", "TABLE", MatchAny, "ALTER", "COLUMN", MatchAny, "ADD", "GENERATED", "BY", "DEFAULT") ||
2932 Matches("ALTER", "TABLE", MatchAny, "ALTER", MatchAny, "ADD", "GENERATED", "BY", "DEFAULT"))
2933 COMPLETE_WITH("AS IDENTITY");
2934 /* ALTER TABLE ALTER [COLUMN] <foo> SET */
2935 else if (Matches("ALTER", "TABLE", MatchAny, "ALTER", "COLUMN", MatchAny, "SET") ||
2936 Matches("ALTER", "TABLE", MatchAny, "ALTER", MatchAny, "SET"))
2937 COMPLETE_WITH("(", "COMPRESSION", "DATA TYPE", "DEFAULT", "EXPRESSION", "GENERATED", "NOT NULL",
2938 "STATISTICS", "STORAGE",
2939 /* a subset of ALTER SEQUENCE options */
2940 "INCREMENT", "MINVALUE", "MAXVALUE", "START", "NO", "CACHE", "CYCLE");
2941 /* ALTER TABLE ALTER [COLUMN] <foo> SET ( */
2942 else if (Matches("ALTER", "TABLE", MatchAny, "ALTER", "COLUMN", MatchAny, "SET", "(") ||
2943 Matches("ALTER", "TABLE", MatchAny, "ALTER", MatchAny, "SET", "("))
2944 COMPLETE_WITH("n_distinct", "n_distinct_inherited");
2945 /* ALTER TABLE ALTER [COLUMN] <foo> SET COMPRESSION */
2946 else if (Matches("ALTER", "TABLE", MatchAny, "ALTER", "COLUMN", MatchAny, "SET", "COMPRESSION") ||
2947 Matches("ALTER", "TABLE", MatchAny, "ALTER", MatchAny, "SET", "COMPRESSION"))
2948 COMPLETE_WITH("DEFAULT", "PGLZ", "LZ4");
2949 /* ALTER TABLE ALTER [COLUMN] <foo> SET EXPRESSION */
2950 else if (Matches("ALTER", "TABLE", MatchAny, "ALTER", "COLUMN", MatchAny, "SET", "EXPRESSION") ||
2951 Matches("ALTER", "TABLE", MatchAny, "ALTER", MatchAny, "SET", "EXPRESSION"))
2952 COMPLETE_WITH("AS");
2953 /* ALTER TABLE ALTER [COLUMN] <foo> SET EXPRESSION AS */
2954 else if (Matches("ALTER", "TABLE", MatchAny, "ALTER", "COLUMN", MatchAny, "SET", "EXPRESSION", "AS") ||
2955 Matches("ALTER", "TABLE", MatchAny, "ALTER", MatchAny, "SET", "EXPRESSION", "AS"))
2956 COMPLETE_WITH("(");
2957 /* ALTER TABLE ALTER [COLUMN] <foo> SET GENERATED */
2958 else if (Matches("ALTER", "TABLE", MatchAny, "ALTER", "COLUMN", MatchAny, "SET", "GENERATED") ||
2959 Matches("ALTER", "TABLE", MatchAny, "ALTER", MatchAny, "SET", "GENERATED"))
2960 COMPLETE_WITH("ALWAYS", "BY DEFAULT");
2961 /* ALTER TABLE ALTER [COLUMN] <foo> SET NO */
2962 else if (Matches("ALTER", "TABLE", MatchAny, "ALTER", "COLUMN", MatchAny, "SET", "NO") ||
2963 Matches("ALTER", "TABLE", MatchAny, "ALTER", MatchAny, "SET", "NO"))
2964 COMPLETE_WITH("MINVALUE", "MAXVALUE", "CYCLE");
2965 /* ALTER TABLE ALTER [COLUMN] <foo> SET STORAGE */
2966 else if (Matches("ALTER", "TABLE", MatchAny, "ALTER", "COLUMN", MatchAny, "SET", "STORAGE") ||
2967 Matches("ALTER", "TABLE", MatchAny, "ALTER", MatchAny, "SET", "STORAGE"))
2968 COMPLETE_WITH("DEFAULT", "PLAIN", "EXTERNAL", "EXTENDED", "MAIN");
2969 /* ALTER TABLE ALTER [COLUMN] <foo> SET STATISTICS */
2970 else if (Matches("ALTER", "TABLE", MatchAny, "ALTER", "COLUMN", MatchAny, "SET", "STATISTICS") ||
2971 Matches("ALTER", "TABLE", MatchAny, "ALTER", MatchAny, "SET", "STATISTICS"))
2972 {
2973 /* Enforce no completion here, as an integer has to be specified */
2974 }
2975 /* ALTER TABLE ALTER [COLUMN] <foo> DROP */
2976 else if (Matches("ALTER", "TABLE", MatchAny, "ALTER", "COLUMN", MatchAny, "DROP") ||
2977 Matches("ALTER", "TABLE", MatchAny, "ALTER", MatchAny, "DROP"))
2978 COMPLETE_WITH("DEFAULT", "EXPRESSION", "IDENTITY", "NOT NULL");
2979 else if (Matches("ALTER", "TABLE", MatchAny, "CLUSTER"))
2980 COMPLETE_WITH("ON");
2981 else if (Matches("ALTER", "TABLE", MatchAny, "CLUSTER", "ON"))
2982 {
2983 set_completion_reference(prev3_wd);
2984 COMPLETE_WITH_SCHEMA_QUERY(Query_for_index_of_table);
2985 }
2986 /* If we have ALTER TABLE <sth> SET, provide list of attributes and '(' */
2987 else if (Matches("ALTER", "TABLE", MatchAny, "SET"))
2988 COMPLETE_WITH("(", "ACCESS METHOD", "LOGGED", "SCHEMA",
2989 "TABLESPACE", "UNLOGGED", "WITH", "WITHOUT");
2990
2991 /*
2992 * If we have ALTER TABLE <sth> SET ACCESS METHOD provide a list of table
2993 * AMs.
2994 */
2995 else if (Matches("ALTER", "TABLE", MatchAny, "SET", "ACCESS", "METHOD"))
2996 COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_table_access_methods,
2997 "DEFAULT");
2998
2999 /*
3000 * If we have ALTER TABLE <sth> SET TABLESPACE provide a list of
3001 * tablespaces
3002 */
3003 else if (Matches("ALTER", "TABLE", MatchAny, "SET", "TABLESPACE"))
3004 COMPLETE_WITH_QUERY(Query_for_list_of_tablespaces);
3005 /* If we have ALTER TABLE <sth> SET WITHOUT provide CLUSTER or OIDS */
3006 else if (Matches("ALTER", "TABLE", MatchAny, "SET", "WITHOUT"))
3007 COMPLETE_WITH("CLUSTER", "OIDS");
3008 /* ALTER TABLE <foo> RESET */
3009 else if (Matches("ALTER", "TABLE", MatchAny, "RESET"))
3010 COMPLETE_WITH("(");
3011 /* ALTER TABLE <foo> SET|RESET ( */
3012 else if (Matches("ALTER", "TABLE", MatchAny, "SET|RESET", "("))
3013 COMPLETE_WITH_LIST(table_storage_parameters);
3014 else if (Matches("ALTER", "TABLE", MatchAny, "REPLICA", "IDENTITY", "USING", "INDEX"))
3015 {
3016 set_completion_reference(prev5_wd);
3017 COMPLETE_WITH_SCHEMA_QUERY(Query_for_index_of_table);
3018 }
3019 else if (Matches("ALTER", "TABLE", MatchAny, "REPLICA", "IDENTITY", "USING"))
3020 COMPLETE_WITH("INDEX");
3021 else if (Matches("ALTER", "TABLE", MatchAny, "REPLICA", "IDENTITY"))
3022 COMPLETE_WITH("FULL", "NOTHING", "DEFAULT", "USING");
3023 else if (Matches("ALTER", "TABLE", MatchAny, "REPLICA"))
3024 COMPLETE_WITH("IDENTITY");
3025
3026 /*
3027 * If we have ALTER TABLE <foo> ATTACH PARTITION, provide a list of
3028 * tables.
3029 */
3030 else if (Matches("ALTER", "TABLE", MatchAny, "ATTACH", "PARTITION"))
3031 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables);
3032 /* Limited completion support for partition bound specification */
3033 else if (TailMatches("ATTACH", "PARTITION", MatchAny))
3034 COMPLETE_WITH("FOR VALUES", "DEFAULT");
3035 else if (TailMatches("FOR", "VALUES"))
3036 COMPLETE_WITH("FROM (", "IN (", "WITH (");
3037
3038 /*
3039 * If we have ALTER TABLE <foo> DETACH|SPLIT PARTITION, provide a list of
3040 * partitions of <foo>.
3041 */
3042 else if (Matches("ALTER", "TABLE", MatchAny, "DETACH|SPLIT", "PARTITION"))
3043 {
3044 set_completion_reference(prev3_wd);
3045 COMPLETE_WITH_SCHEMA_QUERY(Query_for_partition_of_table);
3046 }
3047 else if (Matches("ALTER", "TABLE", MatchAny, "DETACH", "PARTITION", MatchAny))
3048 COMPLETE_WITH("CONCURRENTLY", "FINALIZE");
3049
3050 /* ALTER TABLE <name> SPLIT PARTITION <name> */
3051 else if (Matches("ALTER", "TABLE", MatchAny, "SPLIT", "PARTITION", MatchAny))
3052 COMPLETE_WITH("INTO ( PARTITION");
3053
3054 /* ALTER TABLE <name> MERGE PARTITIONS ( */
3055 else if (Matches("ALTER", "TABLE", MatchAny, "MERGE", "PARTITIONS", "("))
3056 {
3057 set_completion_reference(prev4_wd);
3058 COMPLETE_WITH_SCHEMA_QUERY(Query_for_partition_of_table);
3059 }
3060 else if (Matches("ALTER", "TABLE", MatchAny, "MERGE", "PARTITIONS", "(*)"))
3061 COMPLETE_WITH("INTO");
3062
3063 /* ALTER TABLE <name> OF */
3064 else if (Matches("ALTER", "TABLE", MatchAny, "OF"))
3065 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_composite_datatypes);
3066
3067 /* ALTER TABLESPACE <foo> with RENAME TO, OWNER TO, SET, RESET */
3068 else if (Matches("ALTER", "TABLESPACE", MatchAny))
3069 COMPLETE_WITH("RENAME TO", "OWNER TO", "SET", "RESET");
3070 /* ALTER TABLESPACE <foo> SET|RESET */
3071 else if (Matches("ALTER", "TABLESPACE", MatchAny, "SET|RESET"))
3072 COMPLETE_WITH("(");
3073 /* ALTER TABLESPACE <foo> SET|RESET ( */
3074 else if (Matches("ALTER", "TABLESPACE", MatchAny, "SET|RESET", "("))
3075 COMPLETE_WITH("seq_page_cost", "random_page_cost",
3076 "effective_io_concurrency", "maintenance_io_concurrency");
3077
3078 /* ALTER TEXT SEARCH */
3079 else if (Matches("ALTER", "TEXT", "SEARCH"))
3080 COMPLETE_WITH("CONFIGURATION", "DICTIONARY", "PARSER", "TEMPLATE");
3081 else if (Matches("ALTER", "TEXT", "SEARCH", "TEMPLATE|PARSER", MatchAny))
3082 COMPLETE_WITH("RENAME TO", "SET SCHEMA");
3083 else if (Matches("ALTER", "TEXT", "SEARCH", "DICTIONARY", MatchAny))
3084 COMPLETE_WITH("(", "OWNER TO", "RENAME TO", "SET SCHEMA");
3085 else if (Matches("ALTER", "TEXT", "SEARCH", "CONFIGURATION", MatchAny))
3086 COMPLETE_WITH("ADD MAPPING FOR", "ALTER MAPPING",
3087 "DROP MAPPING FOR",
3088 "OWNER TO", "RENAME TO", "SET SCHEMA");
3089
3090 /* complete ALTER TYPE <foo> with actions */
3091 else if (Matches("ALTER", "TYPE", MatchAny))
3092 COMPLETE_WITH("ADD ATTRIBUTE", "ADD VALUE", "ALTER ATTRIBUTE",
3093 "DROP ATTRIBUTE",
3094 "OWNER TO", "RENAME", "SET SCHEMA", "SET (");
3095 /* complete ALTER TYPE <foo> ADD with actions */
3096 else if (Matches("ALTER", "TYPE", MatchAny, "ADD"))
3097 COMPLETE_WITH("ATTRIBUTE", "VALUE");
3098 /* ALTER TYPE <foo> RENAME */
3099 else if (Matches("ALTER", "TYPE", MatchAny, "RENAME"))
3100 COMPLETE_WITH("ATTRIBUTE", "TO", "VALUE");
3101 /* ALTER TYPE xxx RENAME (ATTRIBUTE|VALUE) yyy */
3102 else if (Matches("ALTER", "TYPE", MatchAny, "RENAME", "ATTRIBUTE|VALUE", MatchAny))
3103 COMPLETE_WITH("TO");
3104 /* ALTER TYPE xxx RENAME ATTRIBUTE yyy TO zzz */
3105 else if (Matches("ALTER", "TYPE", MatchAny, "RENAME", "ATTRIBUTE", MatchAny, "TO", MatchAny))
3106 COMPLETE_WITH("CASCADE", "RESTRICT");
3107
3108 /*
3109 * If we have ALTER TYPE <sth> ALTER/DROP/RENAME ATTRIBUTE, provide list
3110 * of attributes
3111 */
3112 else if (Matches("ALTER", "TYPE", MatchAny, "ALTER|DROP|RENAME", "ATTRIBUTE"))
3113 COMPLETE_WITH_ATTR(prev3_wd);
3114 /* complete ALTER TYPE ADD ATTRIBUTE <foo> with list of types */
3115 else if (Matches("ALTER", "TYPE", MatchAny, "ADD", "ATTRIBUTE", MatchAny))
3116 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_datatypes);
3117 /* complete ALTER TYPE ADD ATTRIBUTE <foo> <footype> with CASCADE/RESTRICT */
3118 else if (Matches("ALTER", "TYPE", MatchAny, "ADD", "ATTRIBUTE", MatchAny, MatchAny))
3119 COMPLETE_WITH("CASCADE", "RESTRICT");
3120 /* complete ALTER TYPE DROP ATTRIBUTE <foo> with CASCADE/RESTRICT */
3121 else if (Matches("ALTER", "TYPE", MatchAny, "DROP", "ATTRIBUTE", MatchAny))
3122 COMPLETE_WITH("CASCADE", "RESTRICT");
3123 /* ALTER TYPE ALTER ATTRIBUTE <foo> */
3124 else if (Matches("ALTER", "TYPE", MatchAny, "ALTER", "ATTRIBUTE", MatchAny))
3125 COMPLETE_WITH("TYPE");
3126 /* ALTER TYPE ALTER ATTRIBUTE <foo> TYPE <footype> */
3127 else if (Matches("ALTER", "TYPE", MatchAny, "ALTER", "ATTRIBUTE", MatchAny, "TYPE", MatchAny))
3128 COMPLETE_WITH("CASCADE", "RESTRICT");
3129 /* complete ALTER TYPE <sth> RENAME VALUE with list of enum values */
3130 else if (Matches("ALTER", "TYPE", MatchAny, "RENAME", "VALUE"))
3131 COMPLETE_WITH_ENUM_VALUE(prev3_wd);
3132 /* ALTER TYPE <foo> SET */
3133 else if (Matches("ALTER", "TYPE", MatchAny, "SET"))
3134 COMPLETE_WITH("(", "SCHEMA");
3135 /* complete ALTER TYPE <foo> SET ( with settable properties */
3136 else if (Matches("ALTER", "TYPE", MatchAny, "SET", "("))
3137 COMPLETE_WITH("ANALYZE", "RECEIVE", "SEND", "STORAGE", "SUBSCRIPT",
3138 "TYPMOD_IN", "TYPMOD_OUT");
3139
3140 /* complete ALTER GROUP <foo> */
3141 else if (Matches("ALTER", "GROUP", MatchAny))
3142 COMPLETE_WITH("ADD USER", "DROP USER", "RENAME TO");
3143 /* complete ALTER GROUP <foo> ADD|DROP with USER */
3144 else if (Matches("ALTER", "GROUP", MatchAny, "ADD|DROP"))
3145 COMPLETE_WITH("USER");
3146 /* complete ALTER GROUP <foo> ADD|DROP USER with a user name */
3147 else if (Matches("ALTER", "GROUP", MatchAny, "ADD|DROP", "USER"))
3148 COMPLETE_WITH_QUERY(Query_for_list_of_roles);
3149
3150/*
3151 * ANALYZE [ ( option [, ...] ) ] [ [ ONLY ] table_and_columns [, ...] ]
3152 * ANALYZE [ VERBOSE ] [ [ ONLY ] table_and_columns [, ...] ]
3153 */
3154 else if (Matches("ANALYZE"))
3155 COMPLETE_WITH_SCHEMA_QUERY_PLUS(Query_for_list_of_analyzables,
3156 "(", "VERBOSE", "ONLY");
3157 else if (Matches("ANALYZE", "VERBOSE"))
3158 COMPLETE_WITH_SCHEMA_QUERY_PLUS(Query_for_list_of_analyzables,
3159 "ONLY");
3160 else if (HeadMatches("ANALYZE", "(*") &&
3161 !HeadMatches("ANALYZE", "(*)"))
3162 {
3163 /*
3164 * This fires if we're in an unfinished parenthesized option list.
3165 * get_previous_words treats a completed parenthesized option list as
3166 * one word, so the above test is correct.
3167 */
3168 if (ends_with(prev_wd, '(') || ends_with(prev_wd, ','))
3169 COMPLETE_WITH("VERBOSE", "SKIP_LOCKED", "BUFFER_USAGE_LIMIT");
3170 else if (TailMatches("VERBOSE|SKIP_LOCKED"))
3171 COMPLETE_WITH("ON", "OFF");
3172 }
3173 else if (Matches("ANALYZE", MatchAnyN, "("))
3174 /* "ANALYZE (" should be caught above, so assume we want columns */
3175 COMPLETE_WITH_ATTR(prev2_wd);
3176 else if (HeadMatches("ANALYZE"))
3177 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_analyzables);
3178
3179/* BEGIN */
3180 else if (Matches("BEGIN"))
3181 COMPLETE_WITH("WORK", "TRANSACTION", "ISOLATION LEVEL", "READ", "DEFERRABLE", "NOT DEFERRABLE");
3182/* END, ABORT */
3183 else if (Matches("END|ABORT"))
3184 COMPLETE_WITH("AND", "WORK", "TRANSACTION");
3185/* COMMIT */
3186 else if (Matches("COMMIT"))
3187 COMPLETE_WITH("AND", "WORK", "TRANSACTION", "PREPARED");
3188/* RELEASE SAVEPOINT */
3189 else if (Matches("RELEASE"))
3190 COMPLETE_WITH("SAVEPOINT");
3191/* ROLLBACK */
3192 else if (Matches("ROLLBACK"))
3193 COMPLETE_WITH("AND", "WORK", "TRANSACTION", "TO SAVEPOINT", "PREPARED");
3194 else if (Matches("ABORT|END|COMMIT|ROLLBACK", "AND"))
3195 COMPLETE_WITH("CHAIN");
3196/* CALL */
3197 else if (Matches("CALL"))
3198 COMPLETE_WITH_VERSIONED_SCHEMA_QUERY(Query_for_list_of_procedures);
3199 else if (Matches("CALL", MatchAny))
3200 COMPLETE_WITH("(");
3201/* CHECKPOINT */
3202 else if (Matches("CHECKPOINT"))
3203 COMPLETE_WITH("(");
3204 else if (HeadMatches("CHECKPOINT", "(*") &&
3205 !HeadMatches("CHECKPOINT", "(*)"))
3206 {
3207 /*
3208 * This fires if we're in an unfinished parenthesized option list.
3209 * get_previous_words treats a completed parenthesized option list as
3210 * one word, so the above test is correct.
3211 */
3212 if (ends_with(prev_wd, '(') || ends_with(prev_wd, ','))
3213 COMPLETE_WITH("MODE", "FLUSH_UNLOGGED");
3214 else if (TailMatches("MODE"))
3215 COMPLETE_WITH("FAST", "SPREAD");
3216 }
3217/* CLOSE */
3218 else if (Matches("CLOSE"))
3219 COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_cursors,
3220 "ALL");
3221/* CLUSTER */
3222 else if (Matches("CLUSTER"))
3223 COMPLETE_WITH_SCHEMA_QUERY_PLUS(Query_for_list_of_clusterables,
3224 "VERBOSE");
3225 else if (Matches("CLUSTER", "VERBOSE") ||
3226 Matches("CLUSTER", "(*)"))
3227 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_clusterables);
3228 /* If we have CLUSTER <sth>, then add "USING" */
3229 else if (Matches("CLUSTER", MatchAnyExcept("VERBOSE|ON|(|(*)")))
3230 COMPLETE_WITH("USING");
3231 /* If we have CLUSTER VERBOSE <sth>, then add "USING" */
3232 else if (Matches("CLUSTER", "VERBOSE|(*)", MatchAny))
3233 COMPLETE_WITH("USING");
3234 /* If we have CLUSTER <sth> USING, then add the index as well */
3235 else if (Matches("CLUSTER", MatchAny, "USING") ||
3236 Matches("CLUSTER", "VERBOSE|(*)", MatchAny, "USING"))
3237 {
3238 set_completion_reference(prev2_wd);
3239 COMPLETE_WITH_SCHEMA_QUERY(Query_for_index_of_table);
3240 }
3241 else if (HeadMatches("CLUSTER", "(*") &&
3242 !HeadMatches("CLUSTER", "(*)"))
3243 {
3244 /*
3245 * This fires if we're in an unfinished parenthesized option list.
3246 * get_previous_words treats a completed parenthesized option list as
3247 * one word, so the above test is correct.
3248 */
3249 if (ends_with(prev_wd, '(') || ends_with(prev_wd, ','))
3250 COMPLETE_WITH("VERBOSE");
3251 }
3252
3253/* COMMENT */
3254 else if (Matches("COMMENT"))
3255 COMPLETE_WITH("ON");
3256 else if (Matches("COMMENT", "ON"))
3257 COMPLETE_WITH("ACCESS METHOD", "AGGREGATE", "CAST", "COLLATION",
3258 "COLUMN", "CONSTRAINT", "CONVERSION", "DATABASE",
3259 "DOMAIN", "EXTENSION", "EVENT TRIGGER",
3260 "FOREIGN DATA WRAPPER", "FOREIGN TABLE",
3261 "FUNCTION", "INDEX", "LANGUAGE", "LARGE OBJECT",
3262 "MATERIALIZED VIEW", "OPERATOR", "POLICY",
3263 "PROCEDURE", "PROCEDURAL LANGUAGE", "PUBLICATION", "ROLE",
3264 "ROUTINE", "RULE", "SCHEMA", "SEQUENCE", "SERVER",
3265 "STATISTICS", "SUBSCRIPTION", "TABLE",
3266 "TABLESPACE", "TEXT SEARCH", "TRANSFORM FOR",
3267 "TRIGGER", "TYPE", "VIEW");
3268 else if (Matches("COMMENT", "ON", "ACCESS", "METHOD"))
3269 COMPLETE_WITH_QUERY(Query_for_list_of_access_methods);
3270 else if (Matches("COMMENT", "ON", "CONSTRAINT"))
3271 COMPLETE_WITH_QUERY(Query_for_all_table_constraints);
3272 else if (Matches("COMMENT", "ON", "CONSTRAINT", MatchAny))
3273 COMPLETE_WITH("ON");
3274 else if (Matches("COMMENT", "ON", "CONSTRAINT", MatchAny, "ON"))
3275 {
3276 set_completion_reference(prev2_wd);
3277 COMPLETE_WITH_SCHEMA_QUERY_PLUS(Query_for_list_of_tables_for_constraint,
3278 "DOMAIN");
3279 }
3280 else if (Matches("COMMENT", "ON", "CONSTRAINT", MatchAny, "ON", "DOMAIN"))
3281 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_domains);
3282 else if (Matches("COMMENT", "ON", "EVENT", "TRIGGER"))
3283 COMPLETE_WITH_QUERY(Query_for_list_of_event_triggers);
3284 else if (Matches("COMMENT", "ON", "FOREIGN"))
3285 COMPLETE_WITH("DATA WRAPPER", "TABLE");
3286 else if (Matches("COMMENT", "ON", "FOREIGN", "TABLE"))
3287 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_foreign_tables);
3288 else if (Matches("COMMENT", "ON", "MATERIALIZED", "VIEW"))
3289 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_matviews);
3290 else if (Matches("COMMENT", "ON", "POLICY"))
3291 COMPLETE_WITH_QUERY(Query_for_list_of_policies);
3292 else if (Matches("COMMENT", "ON", "POLICY", MatchAny))
3293 COMPLETE_WITH("ON");
3294 else if (Matches("COMMENT", "ON", "POLICY", MatchAny, "ON"))
3295 {
3296 set_completion_reference(prev2_wd);
3297 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables_for_policy);
3298 }
3299 else if (Matches("COMMENT", "ON", "PROCEDURAL", "LANGUAGE"))
3300 COMPLETE_WITH_QUERY(Query_for_list_of_languages);
3301 else if (Matches("COMMENT", "ON", "RULE", MatchAny))
3302 COMPLETE_WITH("ON");
3303 else if (Matches("COMMENT", "ON", "RULE", MatchAny, "ON"))
3304 {
3305 set_completion_reference(prev2_wd);
3306 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables_for_rule);
3307 }
3308 else if (Matches("COMMENT", "ON", "TEXT", "SEARCH"))
3309 COMPLETE_WITH("CONFIGURATION", "DICTIONARY", "PARSER", "TEMPLATE");
3310 else if (Matches("COMMENT", "ON", "TEXT", "SEARCH", "CONFIGURATION"))
3311 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_ts_configurations);
3312 else if (Matches("COMMENT", "ON", "TEXT", "SEARCH", "DICTIONARY"))
3313 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_ts_dictionaries);
3314 else if (Matches("COMMENT", "ON", "TEXT", "SEARCH", "PARSER"))
3315 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_ts_parsers);
3316 else if (Matches("COMMENT", "ON", "TEXT", "SEARCH", "TEMPLATE"))
3317 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_ts_templates);
3318 else if (Matches("COMMENT", "ON", "TRANSFORM", "FOR"))
3319 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_datatypes);
3320 else if (Matches("COMMENT", "ON", "TRANSFORM", "FOR", MatchAny))
3321 COMPLETE_WITH("LANGUAGE");
3322 else if (Matches("COMMENT", "ON", "TRANSFORM", "FOR", MatchAny, "LANGUAGE"))
3323 {
3324 set_completion_reference(prev2_wd);
3325 COMPLETE_WITH_QUERY(Query_for_list_of_languages);
3326 }
3327 else if (Matches("COMMENT", "ON", "TRIGGER", MatchAny))
3328 COMPLETE_WITH("ON");
3329 else if (Matches("COMMENT", "ON", "TRIGGER", MatchAny, "ON"))
3330 {
3331 set_completion_reference(prev2_wd);
3332 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables_for_trigger);
3333 }
3334 else if (Matches("COMMENT", "ON", MatchAny, MatchAnyExcept("IS")) ||
3335 Matches("COMMENT", "ON", MatchAny, MatchAny, MatchAnyExcept("IS")) ||
3336 Matches("COMMENT", "ON", MatchAny, MatchAny, MatchAny, MatchAnyExcept("IS")) ||
3337 Matches("COMMENT", "ON", MatchAny, MatchAny, MatchAny, MatchAny, MatchAnyExcept("IS")))
3338 COMPLETE_WITH("IS");
3339
3340/* COPY */
3341
3342 /*
3343 * If we have COPY, offer list of tables or "(" (Also cover the analogous
3344 * backslash command).
3345 */
3346 else if (Matches("COPY|\\copy"))
3347 COMPLETE_WITH_SCHEMA_QUERY_PLUS(Query_for_list_of_tables_for_copy, "(");
3348 /* Complete COPY ( with legal query commands */
3349 else if (Matches("COPY|\\copy", "("))
3350 COMPLETE_WITH("SELECT", "TABLE", "VALUES", "INSERT INTO", "UPDATE", "DELETE FROM", "MERGE INTO", "WITH");
3351 /* Complete COPY <sth> */
3352 else if (Matches("COPY|\\copy", MatchAny))
3353 COMPLETE_WITH("FROM", "TO");
3354 /* Complete COPY|\copy <sth> FROM|TO with filename or STDIN/STDOUT/PROGRAM */
3355 else if (Matches("COPY|\\copy", MatchAny, "FROM|TO"))
3356 {
3357 /* COPY requires quoted filename */
3358 bool force_quote = HeadMatches("COPY");
3359
3360 if (TailMatches("FROM"))
3361 COMPLETE_WITH_FILES_PLUS("", force_quote, "STDIN", "PROGRAM");
3362 else
3363 COMPLETE_WITH_FILES_PLUS("", force_quote, "STDOUT", "PROGRAM");
3364 }
3365
3366 /* Complete COPY|\copy <sth> FROM|TO PROGRAM */
3367 else if (Matches("COPY|\\copy", MatchAny, "FROM|TO", "PROGRAM"))
3368 COMPLETE_WITH_FILES("", HeadMatches("COPY")); /* COPY requires quoted
3369 * filename */
3370
3371 /* Complete COPY <sth> TO [PROGRAM] <sth> */
3372 else if (Matches("COPY|\\copy", MatchAny, "TO", MatchAnyExcept("PROGRAM")) ||
3373 Matches("COPY|\\copy", MatchAny, "TO", "PROGRAM", MatchAny))
3374 COMPLETE_WITH("WITH (");
3375
3376 /* Complete COPY <sth> FROM [PROGRAM] <sth> */
3377 else if (Matches("COPY|\\copy", MatchAny, "FROM", MatchAnyExcept("PROGRAM")) ||
3378 Matches("COPY|\\copy", MatchAny, "FROM", "PROGRAM", MatchAny))
3379 COMPLETE_WITH("WITH (", "WHERE");
3380
3381 /* Complete COPY <sth> FROM [PROGRAM] filename WITH ( */
3382 else if (Matches("COPY|\\copy", MatchAny, "FROM", MatchAnyExcept("PROGRAM"), "WITH", "(") ||
3383 Matches("COPY|\\copy", MatchAny, "FROM", "PROGRAM", MatchAny, "WITH", "("))
3384 COMPLETE_WITH(Copy_from_options);
3385
3386 /* Complete COPY <sth> TO [PROGRAM] filename WITH ( */
3387 else if (Matches("COPY|\\copy", MatchAny, "TO", MatchAnyExcept("PROGRAM"), "WITH", "(") ||
3388 Matches("COPY|\\copy", MatchAny, "TO", "PROGRAM", MatchAny, "WITH", "("))
3389 COMPLETE_WITH(Copy_to_options);
3390
3391 /* Complete COPY <sth> FROM|TO [PROGRAM] <sth> WITH (FORMAT */
3392 else if (Matches("COPY|\\copy", MatchAny, "FROM|TO", MatchAnyExcept("PROGRAM"), "WITH", "(", "FORMAT") ||
3393 Matches("COPY|\\copy", MatchAny, "FROM|TO", "PROGRAM", MatchAny, "WITH", "(", "FORMAT"))
3394 COMPLETE_WITH("binary", "csv", "text");
3395
3396 /* Complete COPY <sth> FROM [PROGRAM] filename WITH (ON_ERROR */
3397 else if (Matches("COPY|\\copy", MatchAny, "FROM", MatchAnyExcept("PROGRAM"), "WITH", "(", "ON_ERROR") ||
3398 Matches("COPY|\\copy", MatchAny, "FROM", "PROGRAM", MatchAny, "WITH", "(", "ON_ERROR"))
3399 COMPLETE_WITH("stop", "ignore");
3400
3401 /* Complete COPY <sth> FROM [PROGRAM] filename WITH (LOG_VERBOSITY */
3402 else if (Matches("COPY|\\copy", MatchAny, "FROM", MatchAnyExcept("PROGRAM"), "WITH", "(", "LOG_VERBOSITY") ||
3403 Matches("COPY|\\copy", MatchAny, "FROM", "PROGRAM", MatchAny, "WITH", "(", "LOG_VERBOSITY"))
3404 COMPLETE_WITH("silent", "default", "verbose");
3405
3406 /* Complete COPY <sth> FROM [PROGRAM] <sth> WITH (<options>) */
3407 else if (Matches("COPY|\\copy", MatchAny, "FROM", MatchAnyExcept("PROGRAM"), "WITH", MatchAny) ||
3408 Matches("COPY|\\copy", MatchAny, "FROM", "PROGRAM", MatchAny, "WITH", MatchAny))
3409 COMPLETE_WITH("WHERE");
3410
3411 /* CREATE ACCESS METHOD */
3412 /* Complete "CREATE ACCESS METHOD <name>" */
3413 else if (Matches("CREATE", "ACCESS", "METHOD", MatchAny))
3414 COMPLETE_WITH("TYPE");
3415 /* Complete "CREATE ACCESS METHOD <name> TYPE" */
3416 else if (Matches("CREATE", "ACCESS", "METHOD", MatchAny, "TYPE"))
3417 COMPLETE_WITH("INDEX", "TABLE");
3418 /* Complete "CREATE ACCESS METHOD <name> TYPE <type>" */
3419 else if (Matches("CREATE", "ACCESS", "METHOD", MatchAny, "TYPE", MatchAny))
3420 COMPLETE_WITH("HANDLER");
3421
3422 /* CREATE COLLATION */
3423 else if (Matches("CREATE", "COLLATION", MatchAny))
3424 COMPLETE_WITH("(", "FROM");
3425 else if (Matches("CREATE", "COLLATION", MatchAny, "FROM"))
3426 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_collations);
3427 else if (HeadMatches("CREATE", "COLLATION", MatchAny, "(*"))
3428 {
3429 if (TailMatches("(|*,"))
3430 COMPLETE_WITH("LOCALE =", "LC_COLLATE =", "LC_CTYPE =",
3431 "PROVIDER =", "DETERMINISTIC =");
3432 else if (TailMatches("PROVIDER", "="))
3433 COMPLETE_WITH("libc", "icu");
3434 else if (TailMatches("DETERMINISTIC", "="))
3435 COMPLETE_WITH("true", "false");
3436 }
3437
3438 /* CREATE DATABASE */
3439 else if (Matches("CREATE", "DATABASE", MatchAny))
3440 COMPLETE_WITH("OWNER", "TEMPLATE", "ENCODING", "TABLESPACE",
3441 "IS_TEMPLATE", "STRATEGY",
3442 "ALLOW_CONNECTIONS", "CONNECTION LIMIT",
3443 "LC_COLLATE", "LC_CTYPE", "LOCALE", "OID",
3444 "LOCALE_PROVIDER", "ICU_LOCALE");
3445
3446 else if (Matches("CREATE", "DATABASE", MatchAny, "TEMPLATE"))
3447 COMPLETE_WITH_QUERY(Query_for_list_of_template_databases);
3448 else if (Matches("CREATE", "DATABASE", MatchAny, "STRATEGY"))
3449 COMPLETE_WITH("WAL_LOG", "FILE_COPY");
3450
3451 /* CREATE DOMAIN */
3452 else if (Matches("CREATE", "DOMAIN", MatchAny))
3453 COMPLETE_WITH("AS");
3454 else if (Matches("CREATE", "DOMAIN", MatchAny, "AS"))
3455 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_datatypes);
3456 else if (Matches("CREATE", "DOMAIN", MatchAny, "AS", MatchAny))
3457 COMPLETE_WITH("COLLATE", "DEFAULT", "CONSTRAINT",
3458 "NOT NULL", "NULL", "CHECK (");
3459 else if (Matches("CREATE", "DOMAIN", MatchAny, "COLLATE"))
3460 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_collations);
3461
3462 /* CREATE EXTENSION */
3463 /* Complete with available extensions rather than installed ones. */
3464 else if (Matches("CREATE", "EXTENSION"))
3465 COMPLETE_WITH_QUERY(Query_for_list_of_available_extensions);
3466 /* CREATE EXTENSION <name> */
3467 else if (Matches("CREATE", "EXTENSION", MatchAny))
3468 COMPLETE_WITH("WITH SCHEMA", "CASCADE", "VERSION");
3469 /* CREATE EXTENSION <name> VERSION */
3470 else if (Matches("CREATE", "EXTENSION", MatchAny, "VERSION"))
3471 {
3472 set_completion_reference(prev2_wd);
3473 COMPLETE_WITH_QUERY(Query_for_list_of_available_extension_versions);
3474 }
3475
3476 /* CREATE FOREIGN */
3477 else if (Matches("CREATE", "FOREIGN"))
3478 COMPLETE_WITH("DATA WRAPPER", "TABLE");
3479
3480 /* CREATE FOREIGN DATA WRAPPER */
3481 else if (Matches("CREATE", "FOREIGN", "DATA", "WRAPPER", MatchAny))
3482 COMPLETE_WITH("HANDLER", "VALIDATOR", "OPTIONS");
3483
3484 /* CREATE FOREIGN TABLE */
3485 else if (Matches("CREATE", "FOREIGN", "TABLE", MatchAny))
3486 COMPLETE_WITH("(", "PARTITION OF");
3487
3488 /* CREATE INDEX --- is allowed inside CREATE SCHEMA, so use TailMatches */
3489 /* First off we complete CREATE UNIQUE with "INDEX" */
3490 else if (TailMatches("CREATE", "UNIQUE"))
3491 COMPLETE_WITH("INDEX");
3492
3493 /*
3494 * If we have CREATE|UNIQUE INDEX, then add "ON", "CONCURRENTLY", and
3495 * existing indexes
3496 */
3497 else if (TailMatches("CREATE|UNIQUE", "INDEX"))
3498 COMPLETE_WITH_SCHEMA_QUERY_PLUS(Query_for_list_of_indexes,
3499 "ON", "CONCURRENTLY");
3500
3501 /*
3502 * Complete ... INDEX|CONCURRENTLY [<name>] ON with a list of relations
3503 * that indexes can be created on
3504 */
3505 else if (TailMatches("INDEX|CONCURRENTLY", MatchAny, "ON") ||
3506 TailMatches("INDEX|CONCURRENTLY", "ON"))
3507 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_indexables);
3508
3509 /*
3510 * Complete CREATE|UNIQUE INDEX CONCURRENTLY with "ON" and existing
3511 * indexes
3512 */
3513 else if (TailMatches("CREATE|UNIQUE", "INDEX", "CONCURRENTLY"))
3514 COMPLETE_WITH_SCHEMA_QUERY_PLUS(Query_for_list_of_indexes,
3515 "ON");
3516 /* Complete CREATE|UNIQUE INDEX [CONCURRENTLY] <sth> with "ON" */
3517 else if (TailMatches("CREATE|UNIQUE", "INDEX", MatchAny) ||
3518 TailMatches("CREATE|UNIQUE", "INDEX", "CONCURRENTLY", MatchAny))
3519 COMPLETE_WITH("ON");
3520
3521 /*
3522 * Complete INDEX <name> ON <table> with a list of table columns (which
3523 * should really be in parens)
3524 */
3525 else if (TailMatches("INDEX", MatchAny, "ON", MatchAny) ||
3526 TailMatches("INDEX|CONCURRENTLY", "ON", MatchAny))
3527 COMPLETE_WITH("(", "USING");
3528 else if (TailMatches("INDEX", MatchAny, "ON", MatchAny, "(") ||
3529 TailMatches("INDEX|CONCURRENTLY", "ON", MatchAny, "("))
3530 COMPLETE_WITH_ATTR(prev2_wd);
3531 /* same if you put in USING */
3532 else if (TailMatches("ON", MatchAny, "USING", MatchAny, "("))
3533 COMPLETE_WITH_ATTR(prev4_wd);
3534 /* Complete USING with an index method */
3535 else if (TailMatches("INDEX", MatchAny, MatchAny, "ON", MatchAny, "USING") ||
3536 TailMatches("INDEX", MatchAny, "ON", MatchAny, "USING") ||
3537 TailMatches("INDEX", "ON", MatchAny, "USING"))
3538 COMPLETE_WITH_QUERY(Query_for_list_of_index_access_methods);
3539 else if (TailMatches("ON", MatchAny, "USING", MatchAny) &&
3540 !TailMatches("POLICY", MatchAny, MatchAny, MatchAny, MatchAny, MatchAny) &&
3541 !TailMatches("FOR", MatchAny, MatchAny, MatchAny))
3542 COMPLETE_WITH("(");
3543
3544 /* CREATE OR REPLACE */
3545 else if (Matches("CREATE", "OR"))
3546 COMPLETE_WITH("REPLACE");
3547
3548 /* CREATE POLICY */
3549 /* Complete "CREATE POLICY <name> ON" */
3550 else if (Matches("CREATE", "POLICY", MatchAny))
3551 COMPLETE_WITH("ON");
3552 /* Complete "CREATE POLICY <name> ON <table>" */
3553 else if (Matches("CREATE", "POLICY", MatchAny, "ON"))
3554 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables);
3555 /* Complete "CREATE POLICY <name> ON <table> AS|FOR|TO|USING|WITH CHECK" */
3556 else if (Matches("CREATE", "POLICY", MatchAny, "ON", MatchAny))
3557 COMPLETE_WITH("AS", "FOR", "TO", "USING (", "WITH CHECK (");
3558 /* CREATE POLICY <name> ON <table> AS PERMISSIVE|RESTRICTIVE */
3559 else if (Matches("CREATE", "POLICY", MatchAny, "ON", MatchAny, "AS"))
3560 COMPLETE_WITH("PERMISSIVE", "RESTRICTIVE");
3561
3562 /*
3563 * CREATE POLICY <name> ON <table> AS PERMISSIVE|RESTRICTIVE
3564 * FOR|TO|USING|WITH CHECK
3565 */
3566 else if (Matches("CREATE", "POLICY", MatchAny, "ON", MatchAny, "AS", MatchAny))
3567 COMPLETE_WITH("FOR", "TO", "USING", "WITH CHECK");
3568 /* CREATE POLICY <name> ON <table> FOR ALL|SELECT|INSERT|UPDATE|DELETE */
3569 else if (Matches("CREATE", "POLICY", MatchAny, "ON", MatchAny, "FOR"))
3570 COMPLETE_WITH("ALL", "SELECT", "INSERT", "UPDATE", "DELETE");
3571 /* Complete "CREATE POLICY <name> ON <table> FOR INSERT TO|WITH CHECK" */
3572 else if (Matches("CREATE", "POLICY", MatchAny, "ON", MatchAny, "FOR", "INSERT"))
3573 COMPLETE_WITH("TO", "WITH CHECK (");
3574 /* Complete "CREATE POLICY <name> ON <table> FOR SELECT|DELETE TO|USING" */
3575 else if (Matches("CREATE", "POLICY", MatchAny, "ON", MatchAny, "FOR", "SELECT|DELETE"))
3576 COMPLETE_WITH("TO", "USING (");
3577 /* CREATE POLICY <name> ON <table> FOR ALL|UPDATE TO|USING|WITH CHECK */
3578 else if (Matches("CREATE", "POLICY", MatchAny, "ON", MatchAny, "FOR", "ALL|UPDATE"))
3579 COMPLETE_WITH("TO", "USING (", "WITH CHECK (");
3580 /* Complete "CREATE POLICY <name> ON <table> TO <role>" */
3581 else if (Matches("CREATE", "POLICY", MatchAny, "ON", MatchAny, "TO"))
3582 COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_roles,
3583 Keywords_for_list_of_grant_roles);
3584 /* Complete "CREATE POLICY <name> ON <table> USING (" */
3585 else if (Matches("CREATE", "POLICY", MatchAny, "ON", MatchAny, "USING"))
3586 COMPLETE_WITH("(");
3587
3588 /*
3589 * CREATE POLICY <name> ON <table> AS PERMISSIVE|RESTRICTIVE FOR
3590 * ALL|SELECT|INSERT|UPDATE|DELETE
3591 */
3592 else if (Matches("CREATE", "POLICY", MatchAny, "ON", MatchAny, "AS", MatchAny, "FOR"))
3593 COMPLETE_WITH("ALL", "SELECT", "INSERT", "UPDATE", "DELETE");
3594
3595 /*
3596 * Complete "CREATE POLICY <name> ON <table> AS PERMISSIVE|RESTRICTIVE FOR
3597 * INSERT TO|WITH CHECK"
3598 */
3599 else if (Matches("CREATE", "POLICY", MatchAny, "ON", MatchAny, "AS", MatchAny, "FOR", "INSERT"))
3600 COMPLETE_WITH("TO", "WITH CHECK (");
3601
3602 /*
3603 * Complete "CREATE POLICY <name> ON <table> AS PERMISSIVE|RESTRICTIVE FOR
3604 * SELECT|DELETE TO|USING"
3605 */
3606 else if (Matches("CREATE", "POLICY", MatchAny, "ON", MatchAny, "AS", MatchAny, "FOR", "SELECT|DELETE"))
3607 COMPLETE_WITH("TO", "USING (");
3608
3609 /*
3610 * CREATE POLICY <name> ON <table> AS PERMISSIVE|RESTRICTIVE FOR
3611 * ALL|UPDATE TO|USING|WITH CHECK
3612 */
3613 else if (Matches("CREATE", "POLICY", MatchAny, "ON", MatchAny, "AS", MatchAny, "FOR", "ALL|UPDATE"))
3614 COMPLETE_WITH("TO", "USING (", "WITH CHECK (");
3615
3616 /*
3617 * Complete "CREATE POLICY <name> ON <table> AS PERMISSIVE|RESTRICTIVE TO
3618 * <role>"
3619 */
3620 else if (Matches("CREATE", "POLICY", MatchAny, "ON", MatchAny, "AS", MatchAny, "TO"))
3621 COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_roles,
3622 Keywords_for_list_of_grant_roles);
3623
3624 /*
3625 * Complete "CREATE POLICY <name> ON <table> AS PERMISSIVE|RESTRICTIVE
3626 * USING ("
3627 */
3628 else if (Matches("CREATE", "POLICY", MatchAny, "ON", MatchAny, "AS", MatchAny, "USING"))
3629 COMPLETE_WITH("(");
3630
3631
3632/* CREATE PUBLICATION */
3633 else if (Matches("CREATE", "PUBLICATION", MatchAny))
3634 COMPLETE_WITH("FOR TABLE", "FOR TABLES IN SCHEMA", "FOR ALL TABLES", "FOR ALL SEQUENCES", "WITH (");
3635 else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR"))
3636 COMPLETE_WITH("TABLE", "TABLES IN SCHEMA", "ALL TABLES", "ALL SEQUENCES");
3637 else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "ALL"))
3638 COMPLETE_WITH("TABLES", "SEQUENCES");
3639 else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "ALL", "TABLES"))
3640 COMPLETE_WITH("WITH (");
3641 else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES"))
3642 COMPLETE_WITH("IN SCHEMA");
3643 else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLE", MatchAny) && !ends_with(prev_wd, ','))
3644 COMPLETE_WITH("WHERE (", "WITH (");
3645 /* Complete "CREATE PUBLICATION <name> FOR TABLE" with "<table>, ..." */
3646 else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLE"))
3647 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables);
3648
3649 /*
3650 * "CREATE PUBLICATION <name> FOR TABLE <name> WHERE (" - complete with
3651 * table attributes
3652 */
3653 else if (Matches("CREATE", "PUBLICATION", MatchAny, MatchAnyN, "WHERE"))
3654 COMPLETE_WITH("(");
3655 else if (Matches("CREATE", "PUBLICATION", MatchAny, MatchAnyN, "WHERE", "("))
3656 COMPLETE_WITH_ATTR(prev3_wd);
3657 else if (Matches("CREATE", "PUBLICATION", MatchAny, MatchAnyN, "WHERE", "(*)"))
3658 COMPLETE_WITH(" WITH (");
3659
3660 /*
3661 * Complete "CREATE PUBLICATION <name> FOR TABLES IN SCHEMA <schema>, ..."
3662 */
3663 else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA"))
3664 COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas
3665 " AND nspname NOT LIKE E'pg\\\\_%%'",
3666 "CURRENT_SCHEMA");
3667 else if (Matches("CREATE", "PUBLICATION", MatchAny, "FOR", "TABLES", "IN", "SCHEMA", MatchAny) && (!ends_with(prev_wd, ',')))
3668 COMPLETE_WITH("WITH (");
3669 /* Complete "CREATE PUBLICATION <name> [...] WITH" */
3670 else if (Matches("CREATE", "PUBLICATION", MatchAnyN, "WITH", "("))
3671 COMPLETE_WITH("publish", "publish_generated_columns", "publish_via_partition_root");
3672
3673/* CREATE RULE */
3674 /* Complete "CREATE [ OR REPLACE ] RULE <sth>" with "AS ON" */
3675 else if (Matches("CREATE", "RULE", MatchAny) ||
3676 Matches("CREATE", "OR", "REPLACE", "RULE", MatchAny))
3677 COMPLETE_WITH("AS ON");
3678 /* Complete "CREATE [ OR REPLACE ] RULE <sth> AS" with "ON" */
3679 else if (Matches("CREATE", "RULE", MatchAny, "AS") ||
3680 Matches("CREATE", "OR", "REPLACE", "RULE", MatchAny, "AS"))
3681 COMPLETE_WITH("ON");
3682
3683 /*
3684 * Complete "CREATE [ OR REPLACE ] RULE <sth> AS ON" with
3685 * SELECT|UPDATE|INSERT|DELETE
3686 */
3687 else if (Matches("CREATE", "RULE", MatchAny, "AS", "ON") ||
3688 Matches("CREATE", "OR", "REPLACE", "RULE", MatchAny, "AS", "ON"))
3689 COMPLETE_WITH("SELECT", "UPDATE", "INSERT", "DELETE");
3690 /* Complete "AS ON SELECT|UPDATE|INSERT|DELETE" with a "TO" */
3691 else if (TailMatches("AS", "ON", "SELECT|UPDATE|INSERT|DELETE"))
3692 COMPLETE_WITH("TO");
3693 /* Complete "AS ON <sth> TO" with a table name */
3694 else if (TailMatches("AS", "ON", "SELECT|UPDATE|INSERT|DELETE", "TO"))
3695 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables);
3696
3697/* CREATE SCHEMA [ <name> ] [ AUTHORIZATION ] */
3698 else if (Matches("CREATE", "SCHEMA"))
3699 COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas,
3700 "AUTHORIZATION");
3701 else if (Matches("CREATE", "SCHEMA", "AUTHORIZATION") ||
3702 Matches("CREATE", "SCHEMA", MatchAny, "AUTHORIZATION"))
3703 COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_roles,
3704 Keywords_for_list_of_owner_roles);
3705 else if (Matches("CREATE", "SCHEMA", "AUTHORIZATION", MatchAny) ||
3706 Matches("CREATE", "SCHEMA", MatchAny, "AUTHORIZATION", MatchAny))
3707 COMPLETE_WITH("CREATE", "GRANT");
3708 else if (Matches("CREATE", "SCHEMA", MatchAny))
3709 COMPLETE_WITH("AUTHORIZATION", "CREATE", "GRANT");
3710
3711/* CREATE SEQUENCE --- is allowed inside CREATE SCHEMA, so use TailMatches */
3712 else if (TailMatches("CREATE", "SEQUENCE", MatchAny) ||
3713 TailMatches("CREATE", "TEMP|TEMPORARY", "SEQUENCE", MatchAny))
3714 COMPLETE_WITH("AS", "INCREMENT BY", "MINVALUE", "MAXVALUE", "NO",
3715 "CACHE", "CYCLE", "OWNED BY", "START WITH");
3716 else if (TailMatches("CREATE", "SEQUENCE", MatchAny, "AS") ||
3717 TailMatches("CREATE", "TEMP|TEMPORARY", "SEQUENCE", MatchAny, "AS"))
3718 COMPLETE_WITH_CS("smallint", "integer", "bigint");
3719 else if (TailMatches("CREATE", "SEQUENCE", MatchAny, "NO") ||
3720 TailMatches("CREATE", "TEMP|TEMPORARY", "SEQUENCE", MatchAny, "NO"))
3721 COMPLETE_WITH("MINVALUE", "MAXVALUE", "CYCLE");
3722
3723/* CREATE SERVER <name> */
3724 else if (Matches("CREATE", "SERVER", MatchAny))
3725 COMPLETE_WITH("TYPE", "VERSION", "FOREIGN DATA WRAPPER");
3726
3727/* CREATE STATISTICS <name> */
3728 else if (Matches("CREATE", "STATISTICS", MatchAny))
3729 COMPLETE_WITH("(", "ON");
3730 else if (Matches("CREATE", "STATISTICS", MatchAny, "("))
3731 COMPLETE_WITH("ndistinct", "dependencies", "mcv");
3732 else if (Matches("CREATE", "STATISTICS", MatchAny, "(*)"))
3733 COMPLETE_WITH("ON");
3734 else if (Matches("CREATE", "STATISTICS", MatchAny, MatchAnyN, "FROM"))
3735 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables);
3736
3737/* CREATE TABLE --- is allowed inside CREATE SCHEMA, so use TailMatches */
3738 /* Complete "CREATE TEMP/TEMPORARY" with the possible temp objects */
3739 else if (TailMatches("CREATE", "TEMP|TEMPORARY"))
3740 COMPLETE_WITH("SEQUENCE", "TABLE", "VIEW");
3741 /* Complete "CREATE UNLOGGED" with TABLE or SEQUENCE */
3742 else if (TailMatches("CREATE", "UNLOGGED"))
3743 COMPLETE_WITH("TABLE", "SEQUENCE");
3744 /* Complete PARTITION BY with RANGE ( or LIST ( or ... */
3745 else if (TailMatches("PARTITION", "BY"))
3746 COMPLETE_WITH("RANGE (", "LIST (", "HASH (");
3747 /* If we have xxx PARTITION OF, provide a list of partitioned tables */
3748 else if (TailMatches("PARTITION", "OF"))
3749 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_partitioned_tables);
3750 /* Limited completion support for partition bound specification */
3751 else if (TailMatches("PARTITION", "OF", MatchAny))
3752 COMPLETE_WITH("FOR VALUES", "DEFAULT");
3753 /* Complete CREATE TABLE <name> with '(', AS, OF or PARTITION OF */
3754 else if (TailMatches("CREATE", "TABLE", MatchAny) ||
3755 TailMatches("CREATE", "TEMP|TEMPORARY|UNLOGGED", "TABLE", MatchAny))
3756 COMPLETE_WITH("(", "AS", "OF", "PARTITION OF");
3757 /* Complete CREATE TABLE <name> OF with list of composite types */
3758 else if (TailMatches("CREATE", "TABLE", MatchAny, "OF") ||
3759 TailMatches("CREATE", "TEMP|TEMPORARY|UNLOGGED", "TABLE", MatchAny, "OF"))
3760 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_composite_datatypes);
3761 /* Complete CREATE TABLE <name> [ (...) ] AS with list of keywords */
3762 else if (TailMatches("CREATE", "TABLE", MatchAny, "AS") ||
3763 TailMatches("CREATE", "TABLE", MatchAny, "(*)", "AS") ||
3764 TailMatches("CREATE", "TEMP|TEMPORARY|UNLOGGED", "TABLE", MatchAny, "AS") ||
3765 TailMatches("CREATE", "TEMP|TEMPORARY|UNLOGGED", "TABLE", MatchAny, "(*)", "AS"))
3766 COMPLETE_WITH("EXECUTE", "SELECT", "TABLE", "VALUES", "WITH");
3767 /* Complete CREATE TABLE name (...) with supported options */
3768 else if (TailMatches("CREATE", "TABLE", MatchAny, "(*)"))
3769 COMPLETE_WITH("AS", "INHERITS (", "PARTITION BY", "USING", "TABLESPACE", "WITH (");
3770 else if (TailMatches("CREATE", "UNLOGGED", "TABLE", MatchAny, "(*)"))
3771 COMPLETE_WITH("AS", "INHERITS (", "USING", "TABLESPACE", "WITH (");
3772 else if (TailMatches("CREATE", "TEMP|TEMPORARY", "TABLE", MatchAny, "(*)"))
3773 COMPLETE_WITH("AS", "INHERITS (", "ON COMMIT", "PARTITION BY", "USING",
3774 "TABLESPACE", "WITH (");
3775 /* Complete CREATE TABLE (...) USING with table access methods */
3776 else if (TailMatches("CREATE", "TABLE", MatchAny, "(*)", "USING") ||
3777 TailMatches("CREATE", "TEMP|TEMPORARY|UNLOGGED", "TABLE", MatchAny, "(*)", "USING"))
3778 COMPLETE_WITH_QUERY(Query_for_list_of_table_access_methods);
3779 /* Complete CREATE TABLE (...) WITH with storage parameters */
3780 else if (TailMatches("CREATE", "TABLE", MatchAny, "(*)", "WITH", "(") ||
3781 TailMatches("CREATE", "TEMP|TEMPORARY|UNLOGGED", "TABLE", MatchAny, "(*)", "WITH", "("))
3782 COMPLETE_WITH_LIST(table_storage_parameters);
3783 /* Complete CREATE TABLE ON COMMIT with actions */
3784 else if (TailMatches("CREATE", "TEMP|TEMPORARY", "TABLE", MatchAny, "(*)", "ON", "COMMIT"))
3785 COMPLETE_WITH("DELETE ROWS", "DROP", "PRESERVE ROWS");
3786
3787/* CREATE TABLESPACE */
3788 else if (Matches("CREATE", "TABLESPACE", MatchAny))
3789 COMPLETE_WITH("OWNER", "LOCATION");
3790 /* Complete CREATE TABLESPACE name OWNER name with "LOCATION" */
3791 else if (Matches("CREATE", "TABLESPACE", MatchAny, "OWNER", MatchAny))
3792 COMPLETE_WITH("LOCATION");
3793
3794/* CREATE TEXT SEARCH */
3795 else if (Matches("CREATE", "TEXT", "SEARCH"))
3796 COMPLETE_WITH("CONFIGURATION", "DICTIONARY", "PARSER", "TEMPLATE");
3797 else if (Matches("CREATE", "TEXT", "SEARCH", "CONFIGURATION|DICTIONARY|PARSER|TEMPLATE", MatchAny))
3798 COMPLETE_WITH("(");
3799
3800/* CREATE TRANSFORM */
3801 else if (Matches("CREATE", "TRANSFORM") ||
3802 Matches("CREATE", "OR", "REPLACE", "TRANSFORM"))
3803 COMPLETE_WITH("FOR");
3804 else if (Matches("CREATE", "TRANSFORM", "FOR") ||
3805 Matches("CREATE", "OR", "REPLACE", "TRANSFORM", "FOR"))
3806 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_datatypes);
3807 else if (Matches("CREATE", "TRANSFORM", "FOR", MatchAny) ||
3808 Matches("CREATE", "OR", "REPLACE", "TRANSFORM", "FOR", MatchAny))
3809 COMPLETE_WITH("LANGUAGE");
3810 else if (Matches("CREATE", "TRANSFORM", "FOR", MatchAny, "LANGUAGE") ||
3811 Matches("CREATE", "OR", "REPLACE", "TRANSFORM", "FOR", MatchAny, "LANGUAGE"))
3812 {
3813 set_completion_reference(prev2_wd);
3814 COMPLETE_WITH_QUERY(Query_for_list_of_languages);
3815 }
3816
3817/* CREATE SUBSCRIPTION */
3818 else if (Matches("CREATE", "SUBSCRIPTION", MatchAny))
3819 COMPLETE_WITH("CONNECTION");
3820 else if (Matches("CREATE", "SUBSCRIPTION", MatchAny, "CONNECTION", MatchAny))
3821 COMPLETE_WITH("PUBLICATION");
3822 else if (Matches("CREATE", "SUBSCRIPTION", MatchAny, "CONNECTION",
3823 MatchAny, "PUBLICATION"))
3824 {
3825 /* complete with nothing here as this refers to remote publications */
3826 }
3827 else if (Matches("CREATE", "SUBSCRIPTION", MatchAnyN, "PUBLICATION", MatchAny))
3828 COMPLETE_WITH("WITH (");
3829 /* Complete "CREATE SUBSCRIPTION <name> ... WITH ( <opt>" */
3830 else if (Matches("CREATE", "SUBSCRIPTION", MatchAnyN, "WITH", "("))
3831 COMPLETE_WITH("binary", "connect", "copy_data", "create_slot",
3832 "disable_on_error", "enabled", "failover",
3833 "max_retention_duration", "origin",
3834 "password_required", "retain_dead_tuples",
3835 "run_as_owner", "slot_name", "streaming",
3836 "synchronous_commit", "two_phase");
3837
3838/* CREATE TRIGGER --- is allowed inside CREATE SCHEMA, so use TailMatches */
3839
3840 /*
3841 * Complete CREATE [ OR REPLACE ] TRIGGER <name> with BEFORE|AFTER|INSTEAD
3842 * OF.
3843 */
3844 else if (TailMatches("CREATE", "TRIGGER", MatchAny) ||
3845 TailMatches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAny))
3846 COMPLETE_WITH("BEFORE", "AFTER", "INSTEAD OF");
3847
3848 /*
3849 * Complete CREATE [ OR REPLACE ] TRIGGER <name> BEFORE,AFTER with an
3850 * event.
3851 */
3852 else if (TailMatches("CREATE", "TRIGGER", MatchAny, "BEFORE|AFTER") ||
3853 TailMatches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAny, "BEFORE|AFTER"))
3854 COMPLETE_WITH("INSERT", "DELETE", "UPDATE", "TRUNCATE");
3855 /* Complete CREATE [ OR REPLACE ] TRIGGER <name> INSTEAD OF with an event */
3856 else if (TailMatches("CREATE", "TRIGGER", MatchAny, "INSTEAD", "OF") ||
3857 TailMatches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAny, "INSTEAD", "OF"))
3858 COMPLETE_WITH("INSERT", "DELETE", "UPDATE");
3859
3860 /*
3861 * Complete CREATE [ OR REPLACE ] TRIGGER <name> BEFORE,AFTER sth with
3862 * OR|ON.
3863 */
3864 else if (TailMatches("CREATE", "TRIGGER", MatchAny, "BEFORE|AFTER", MatchAny) ||
3865 TailMatches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAny, "BEFORE|AFTER", MatchAny) ||
3866 TailMatches("CREATE", "TRIGGER", MatchAny, "INSTEAD", "OF", MatchAny) ||
3867 TailMatches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAny, "INSTEAD", "OF", MatchAny))
3868 COMPLETE_WITH("ON", "OR");
3869
3870 /*
3871 * Complete CREATE [ OR REPLACE ] TRIGGER <name> BEFORE,AFTER event ON
3872 * with a list of tables. EXECUTE FUNCTION is the recommended grammar
3873 * instead of EXECUTE PROCEDURE in version 11 and upwards.
3874 */
3875 else if (TailMatches("CREATE", "TRIGGER", MatchAny, "BEFORE|AFTER", MatchAny, "ON") ||
3876 TailMatches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAny, "BEFORE|AFTER", MatchAny, "ON"))
3877 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables);
3878
3879 /*
3880 * Complete CREATE [ OR REPLACE ] TRIGGER ... INSTEAD OF event ON with a
3881 * list of views.
3882 */
3883 else if (TailMatches("CREATE", "TRIGGER", MatchAny, "INSTEAD", "OF", MatchAny, "ON") ||
3884 TailMatches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAny, "INSTEAD", "OF", MatchAny, "ON"))
3885 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_views);
3886 else if (Matches("CREATE", "TRIGGER", MatchAnyN,
3887 "ON", MatchAny) ||
3888 Matches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAnyN,
3889 "ON", MatchAny))
3890 {
3891 if (pset.sversion >= 110000)
3892 COMPLETE_WITH("NOT DEFERRABLE", "DEFERRABLE", "INITIALLY",
3893 "REFERENCING", "FOR", "WHEN (", "EXECUTE FUNCTION");
3894 else
3895 COMPLETE_WITH("NOT DEFERRABLE", "DEFERRABLE", "INITIALLY",
3896 "REFERENCING", "FOR", "WHEN (", "EXECUTE PROCEDURE");
3897 }
3898 else if (Matches("CREATE", "TRIGGER", MatchAnyN,
3899 "DEFERRABLE") ||
3900 Matches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAnyN,
3901 "DEFERRABLE") ||
3902 Matches("CREATE", "TRIGGER", MatchAnyN,
3903 "INITIALLY", "IMMEDIATE|DEFERRED") ||
3904 Matches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAnyN,
3905 "INITIALLY", "IMMEDIATE|DEFERRED"))
3906 {
3907 if (pset.sversion >= 110000)
3908 COMPLETE_WITH("REFERENCING", "FOR", "WHEN (", "EXECUTE FUNCTION");
3909 else
3910 COMPLETE_WITH("REFERENCING", "FOR", "WHEN (", "EXECUTE PROCEDURE");
3911 }
3912 else if (Matches("CREATE", "TRIGGER", MatchAnyN,
3913 "REFERENCING") ||
3914 Matches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAnyN,
3915 "REFERENCING"))
3916 COMPLETE_WITH("OLD TABLE", "NEW TABLE");
3917 else if (Matches("CREATE", "TRIGGER", MatchAnyN,
3918 "OLD|NEW", "TABLE") ||
3919 Matches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAnyN,
3920 "OLD|NEW", "TABLE"))
3921 COMPLETE_WITH("AS");
3922 else if (Matches("CREATE", "TRIGGER", MatchAnyN,
3923 "REFERENCING", "OLD", "TABLE", "AS", MatchAny) ||
3924 Matches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAnyN,
3925 "REFERENCING", "OLD", "TABLE", "AS", MatchAny) ||
3926 Matches("CREATE", "TRIGGER", MatchAnyN,
3927 "REFERENCING", "OLD", "TABLE", MatchAny) ||
3928 Matches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAnyN,
3929 "REFERENCING", "OLD", "TABLE", MatchAny))
3930 {
3931 if (pset.sversion >= 110000)
3932 COMPLETE_WITH("NEW TABLE", "FOR", "WHEN (", "EXECUTE FUNCTION");
3933 else
3934 COMPLETE_WITH("NEW TABLE", "FOR", "WHEN (", "EXECUTE PROCEDURE");
3935 }
3936 else if (Matches("CREATE", "TRIGGER", MatchAnyN,
3937 "REFERENCING", "NEW", "TABLE", "AS", MatchAny) ||
3938 Matches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAnyN,
3939 "REFERENCING", "NEW", "TABLE", "AS", MatchAny) ||
3940 Matches("CREATE", "TRIGGER", MatchAnyN,
3941 "REFERENCING", "NEW", "TABLE", MatchAny) ||
3942 Matches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAnyN,
3943 "REFERENCING", "NEW", "TABLE", MatchAny))
3944 {
3945 if (pset.sversion >= 110000)
3946 COMPLETE_WITH("OLD TABLE", "FOR", "WHEN (", "EXECUTE FUNCTION");
3947 else
3948 COMPLETE_WITH("OLD TABLE", "FOR", "WHEN (", "EXECUTE PROCEDURE");
3949 }
3950 else if (Matches("CREATE", "TRIGGER", MatchAnyN,
3951 "REFERENCING", "OLD|NEW", "TABLE", "AS", MatchAny, "OLD|NEW", "TABLE", "AS", MatchAny) ||
3952 Matches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAnyN,
3953 "REFERENCING", "OLD|NEW", "TABLE", "AS", MatchAny, "OLD|NEW", "TABLE", "AS", MatchAny) ||
3954 Matches("CREATE", "TRIGGER", MatchAnyN,
3955 "REFERENCING", "OLD|NEW", "TABLE", MatchAny, "OLD|NEW", "TABLE", "AS", MatchAny) ||
3956 Matches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAnyN,
3957 "REFERENCING", "OLD|NEW", "TABLE", MatchAny, "OLD|NEW", "TABLE", "AS", MatchAny) ||
3958 Matches("CREATE", "TRIGGER", MatchAnyN,
3959 "REFERENCING", "OLD|NEW", "TABLE", "AS", MatchAny, "OLD|NEW", "TABLE", MatchAny) ||
3960 Matches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAnyN,
3961 "REFERENCING", "OLD|NEW", "TABLE", "AS", MatchAny, "OLD|NEW", "TABLE", MatchAny) ||
3962 Matches("CREATE", "TRIGGER", MatchAnyN,
3963 "REFERENCING", "OLD|NEW", "TABLE", MatchAny, "OLD|NEW", "TABLE", MatchAny) ||
3964 Matches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAnyN,
3965 "REFERENCING", "OLD|NEW", "TABLE", MatchAny, "OLD|NEW", "TABLE", MatchAny))
3966 {
3967 if (pset.sversion >= 110000)
3968 COMPLETE_WITH("FOR", "WHEN (", "EXECUTE FUNCTION");
3969 else
3970 COMPLETE_WITH("FOR", "WHEN (", "EXECUTE PROCEDURE");
3971 }
3972 else if (Matches("CREATE", "TRIGGER", MatchAnyN,
3973 "FOR") ||
3974 Matches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAnyN,
3975 "FOR"))
3976 COMPLETE_WITH("EACH", "ROW", "STATEMENT");
3977 else if (Matches("CREATE", "TRIGGER", MatchAnyN,
3978 "FOR", "EACH") ||
3979 Matches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAnyN,
3980 "FOR", "EACH"))
3981 COMPLETE_WITH("ROW", "STATEMENT");
3982 else if (Matches("CREATE", "TRIGGER", MatchAnyN,
3983 "FOR", "EACH", "ROW|STATEMENT") ||
3984 Matches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAnyN,
3985 "FOR", "EACH", "ROW|STATEMENT") ||
3986 Matches("CREATE", "TRIGGER", MatchAnyN,
3987 "FOR", "ROW|STATEMENT") ||
3988 Matches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAnyN,
3989 "FOR", "ROW|STATEMENT"))
3990 {
3991 if (pset.sversion >= 110000)
3992 COMPLETE_WITH("WHEN (", "EXECUTE FUNCTION");
3993 else
3994 COMPLETE_WITH("WHEN (", "EXECUTE PROCEDURE");
3995 }
3996 else if (Matches("CREATE", "TRIGGER", MatchAnyN,
3997 "WHEN", "(*)") ||
3998 Matches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAnyN,
3999 "WHEN", "(*)"))
4000 {
4001 if (pset.sversion >= 110000)
4002 COMPLETE_WITH("EXECUTE FUNCTION");
4003 else
4004 COMPLETE_WITH("EXECUTE PROCEDURE");
4005 }
4006
4007 /*
4008 * Complete CREATE [ OR REPLACE ] TRIGGER ... EXECUTE with
4009 * PROCEDURE|FUNCTION.
4010 */
4011 else if (Matches("CREATE", "TRIGGER", MatchAnyN,
4012 "EXECUTE") ||
4013 Matches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAnyN,
4014 "EXECUTE"))
4015 {
4016 if (pset.sversion >= 110000)
4017 COMPLETE_WITH("FUNCTION");
4018 else
4019 COMPLETE_WITH("PROCEDURE");
4020 }
4021 else if (Matches("CREATE", "TRIGGER", MatchAnyN,
4022 "EXECUTE", "FUNCTION|PROCEDURE") ||
4023 Matches("CREATE", "OR", "REPLACE", "TRIGGER", MatchAnyN,
4024 "EXECUTE", "FUNCTION|PROCEDURE"))
4025 COMPLETE_WITH_VERSIONED_SCHEMA_QUERY(Query_for_list_of_functions);
4026
4027/* CREATE ROLE,USER,GROUP <name> */
4028 else if (Matches("CREATE", "ROLE|GROUP|USER", MatchAny) &&
4029 !TailMatches("USER", "MAPPING"))
4030 COMPLETE_WITH("ADMIN", "BYPASSRLS", "CONNECTION LIMIT", "CREATEDB",
4031 "CREATEROLE", "ENCRYPTED PASSWORD", "IN", "INHERIT",
4032 "LOGIN", "NOBYPASSRLS",
4033 "NOCREATEDB", "NOCREATEROLE", "NOINHERIT",
4034 "NOLOGIN", "NOREPLICATION", "NOSUPERUSER", "PASSWORD",
4035 "REPLICATION", "ROLE", "SUPERUSER", "SYSID",
4036 "VALID UNTIL", "WITH");
4037
4038/* CREATE ROLE,USER,GROUP <name> WITH */
4039 else if (Matches("CREATE", "ROLE|GROUP|USER", MatchAny, "WITH"))
4040 /* Similar to the above, but don't complete "WITH" again. */
4041 COMPLETE_WITH("ADMIN", "BYPASSRLS", "CONNECTION LIMIT", "CREATEDB",
4042 "CREATEROLE", "ENCRYPTED PASSWORD", "IN", "INHERIT",
4043 "LOGIN", "NOBYPASSRLS",
4044 "NOCREATEDB", "NOCREATEROLE", "NOINHERIT",
4045 "NOLOGIN", "NOREPLICATION", "NOSUPERUSER", "PASSWORD",
4046 "REPLICATION", "ROLE", "SUPERUSER", "SYSID",
4047 "VALID UNTIL");
4048
4049 /* complete CREATE ROLE,USER,GROUP <name> IN with ROLE,GROUP */
4050 else if (Matches("CREATE", "ROLE|USER|GROUP", MatchAny, "IN"))
4051 COMPLETE_WITH("GROUP", "ROLE");
4052
4053/* CREATE TYPE */
4054 else if (Matches("CREATE", "TYPE", MatchAny))
4055 COMPLETE_WITH("(", "AS");
4056 else if (Matches("CREATE", "TYPE", MatchAny, "AS"))
4057 COMPLETE_WITH("ENUM", "RANGE", "(");
4058 else if (HeadMatches("CREATE", "TYPE", MatchAny, "AS", "("))
4059 {
4060 if (TailMatches("(|*,", MatchAny))
4061 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_datatypes);
4062 else if (TailMatches("(|*,", MatchAny, MatchAnyExcept("*)")))
4063 COMPLETE_WITH("COLLATE", ",", ")");
4064 }
4065 else if (Matches("CREATE", "TYPE", MatchAny, "AS", "ENUM|RANGE"))
4066 COMPLETE_WITH("(");
4067 else if (HeadMatches("CREATE", "TYPE", MatchAny, "("))
4068 {
4069 if (TailMatches("(|*,"))
4070 COMPLETE_WITH("INPUT", "OUTPUT", "RECEIVE", "SEND",
4071 "TYPMOD_IN", "TYPMOD_OUT", "ANALYZE", "SUBSCRIPT",
4072 "INTERNALLENGTH", "PASSEDBYVALUE", "ALIGNMENT",
4073 "STORAGE", "LIKE", "CATEGORY", "PREFERRED",
4074 "DEFAULT", "ELEMENT", "DELIMITER",
4075 "COLLATABLE");
4076 else if (TailMatches("(*|*,", MatchAnyExcept("*=")))
4077 COMPLETE_WITH("=");
4078 else if (TailMatches("=", MatchAnyExcept("*)")))
4079 COMPLETE_WITH(",", ")");
4080 }
4081 else if (HeadMatches("CREATE", "TYPE", MatchAny, "AS", "RANGE", "("))
4082 {
4083 if (TailMatches("(|*,"))
4084 COMPLETE_WITH("SUBTYPE", "SUBTYPE_OPCLASS", "COLLATION",
4085 "CANONICAL", "SUBTYPE_DIFF",
4086 "MULTIRANGE_TYPE_NAME");
4087 else if (TailMatches("(*|*,", MatchAnyExcept("*=")))
4088 COMPLETE_WITH("=");
4089 else if (TailMatches("=", MatchAnyExcept("*)")))
4090 COMPLETE_WITH(",", ")");
4091 }
4092
4093/* CREATE VIEW --- is allowed inside CREATE SCHEMA, so use TailMatches */
4094 /* Complete CREATE [ OR REPLACE ] VIEW <name> with AS or WITH */
4095 else if (TailMatches("CREATE", "VIEW", MatchAny) ||
4096 TailMatches("CREATE", "OR", "REPLACE", "VIEW", MatchAny))
4097 COMPLETE_WITH("AS", "WITH");
4098 /* Complete "CREATE [ OR REPLACE ] VIEW <sth> AS with "SELECT" */
4099 else if (TailMatches("CREATE", "VIEW", MatchAny, "AS") ||
4100 TailMatches("CREATE", "OR", "REPLACE", "VIEW", MatchAny, "AS"))
4101 COMPLETE_WITH("SELECT");
4102 /* CREATE [ OR REPLACE ] VIEW <name> WITH ( yyy [= zzz] ) */
4103 else if (TailMatches("CREATE", "VIEW", MatchAny, "WITH") ||
4104 TailMatches("CREATE", "OR", "REPLACE", "VIEW", MatchAny, "WITH"))
4105 COMPLETE_WITH("(");
4106 else if (TailMatches("CREATE", "VIEW", MatchAny, "WITH", "(") ||
4107 TailMatches("CREATE", "OR", "REPLACE", "VIEW", MatchAny, "WITH", "("))
4108 COMPLETE_WITH_LIST(view_optional_parameters);
4109 else if (TailMatches("CREATE", "VIEW", MatchAny, "WITH", "(", "check_option") ||
4110 TailMatches("CREATE", "OR", "REPLACE", "VIEW", MatchAny, "WITH", "(", "check_option"))
4111 COMPLETE_WITH("=");
4112 else if (TailMatches("CREATE", "VIEW", MatchAny, "WITH", "(", "check_option", "=") ||
4113 TailMatches("CREATE", "OR", "REPLACE", "VIEW", MatchAny, "WITH", "(", "check_option", "="))
4114 COMPLETE_WITH("local", "cascaded");
4115 /* CREATE [ OR REPLACE ] VIEW <name> WITH ( ... ) AS */
4116 else if (TailMatches("CREATE", "VIEW", MatchAny, "WITH", "(*)") ||
4117 TailMatches("CREATE", "OR", "REPLACE", "VIEW", MatchAny, "WITH", "(*)"))
4118 COMPLETE_WITH("AS");
4119 /* CREATE [ OR REPLACE ] VIEW <name> WITH ( ... ) AS SELECT */
4120 else if (TailMatches("CREATE", "VIEW", MatchAny, "WITH", "(*)", "AS") ||
4121 TailMatches("CREATE", "OR", "REPLACE", "VIEW", MatchAny, "WITH", "(*)", "AS"))
4122 COMPLETE_WITH("SELECT");
4123
4124/* CREATE MATERIALIZED VIEW */
4125 else if (Matches("CREATE", "MATERIALIZED"))
4126 COMPLETE_WITH("VIEW");
4127 /* Complete CREATE MATERIALIZED VIEW <name> with AS or USING */
4128 else if (Matches("CREATE", "MATERIALIZED", "VIEW", MatchAny))
4129 COMPLETE_WITH("AS", "USING");
4130
4131 /*
4132 * Complete CREATE MATERIALIZED VIEW <name> USING with list of access
4133 * methods
4134 */
4135 else if (Matches("CREATE", "MATERIALIZED", "VIEW", MatchAny, "USING"))
4136 COMPLETE_WITH_QUERY(Query_for_list_of_table_access_methods);
4137 /* Complete CREATE MATERIALIZED VIEW <name> USING <access method> with AS */
4138 else if (Matches("CREATE", "MATERIALIZED", "VIEW", MatchAny, "USING", MatchAny))
4139 COMPLETE_WITH("AS");
4140
4141 /*
4142 * Complete CREATE MATERIALIZED VIEW <name> [USING <access method> ] AS
4143 * with "SELECT"
4144 */
4145 else if (Matches("CREATE", "MATERIALIZED", "VIEW", MatchAny, "AS") ||
4146 Matches("CREATE", "MATERIALIZED", "VIEW", MatchAny, "USING", MatchAny, "AS"))
4147 COMPLETE_WITH("SELECT");
4148
4149/* CREATE EVENT TRIGGER */
4150 else if (Matches("CREATE", "EVENT"))
4151 COMPLETE_WITH("TRIGGER");
4152 /* Complete CREATE EVENT TRIGGER <name> with ON */
4153 else if (Matches("CREATE", "EVENT", "TRIGGER", MatchAny))
4154 COMPLETE_WITH("ON");
4155 /* Complete CREATE EVENT TRIGGER <name> ON with event_type */
4156 else if (Matches("CREATE", "EVENT", "TRIGGER", MatchAny, "ON"))
4157 COMPLETE_WITH("ddl_command_start", "ddl_command_end", "login",
4158 "sql_drop", "table_rewrite");
4159
4160 /*
4161 * Complete CREATE EVENT TRIGGER <name> ON <event_type>. EXECUTE FUNCTION
4162 * is the recommended grammar instead of EXECUTE PROCEDURE in version 11
4163 * and upwards.
4164 */
4165 else if (Matches("CREATE", "EVENT", "TRIGGER", MatchAny, "ON", MatchAny))
4166 {
4167 if (pset.sversion >= 110000)
4168 COMPLETE_WITH("WHEN TAG IN (", "EXECUTE FUNCTION");
4169 else
4170 COMPLETE_WITH("WHEN TAG IN (", "EXECUTE PROCEDURE");
4171 }
4172 else if (Matches("CREATE", "EVENT", "TRIGGER", MatchAnyN, "WHEN|AND", MatchAny, "IN", "(*)"))
4173 {
4174 if (pset.sversion >= 110000)
4175 COMPLETE_WITH("EXECUTE FUNCTION");
4176 else
4177 COMPLETE_WITH("EXECUTE PROCEDURE");
4178 }
4179 else if (Matches("CREATE", "EVENT", "TRIGGER", MatchAnyN, "EXECUTE", "FUNCTION|PROCEDURE"))
4180 COMPLETE_WITH_VERSIONED_SCHEMA_QUERY(Query_for_list_of_functions);
4181
4182/* DEALLOCATE */
4183 else if (Matches("DEALLOCATE"))
4184 COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_prepared_statements,
4185 "ALL");
4186
4187/* DECLARE */
4188
4189 /*
4190 * Complete DECLARE <name> with one of BINARY, ASENSITIVE, INSENSITIVE,
4191 * SCROLL, NO SCROLL, and CURSOR.
4192 */
4193 else if (Matches("DECLARE", MatchAny))
4194 COMPLETE_WITH("BINARY", "ASENSITIVE", "INSENSITIVE", "SCROLL", "NO SCROLL",
4195 "CURSOR");
4196
4197 /*
4198 * Complete DECLARE ... <option> with other options. The PostgreSQL parser
4199 * allows DECLARE options to be specified in any order. But the
4200 * tab-completion follows the ordering of them that the SQL standard
4201 * provides, like the syntax of DECLARE command in the documentation
4202 * indicates.
4203 */
4204 else if (Matches("DECLARE", MatchAnyN, "BINARY"))
4205 COMPLETE_WITH("ASENSITIVE", "INSENSITIVE", "SCROLL", "NO SCROLL", "CURSOR");
4206 else if (Matches("DECLARE", MatchAnyN, "ASENSITIVE|INSENSITIVE"))
4207 COMPLETE_WITH("SCROLL", "NO SCROLL", "CURSOR");
4208 else if (Matches("DECLARE", MatchAnyN, "SCROLL"))
4209 COMPLETE_WITH("CURSOR");
4210 /* Complete DECLARE ... [options] NO with SCROLL */
4211 else if (Matches("DECLARE", MatchAnyN, "NO"))
4212 COMPLETE_WITH("SCROLL");
4213
4214 /*
4215 * Complete DECLARE ... CURSOR with one of WITH HOLD, WITHOUT HOLD, and
4216 * FOR
4217 */
4218 else if (Matches("DECLARE", MatchAnyN, "CURSOR"))
4219 COMPLETE_WITH("WITH HOLD", "WITHOUT HOLD", "FOR");
4220 /* Complete DECLARE ... CURSOR WITH|WITHOUT with HOLD */
4221 else if (Matches("DECLARE", MatchAnyN, "CURSOR", "WITH|WITHOUT"))
4222 COMPLETE_WITH("HOLD");
4223 /* Complete DECLARE ... CURSOR WITH|WITHOUT HOLD with FOR */
4224 else if (Matches("DECLARE", MatchAnyN, "CURSOR", "WITH|WITHOUT", "HOLD"))
4225 COMPLETE_WITH("FOR");
4226
4227/* DELETE --- can be inside EXPLAIN, RULE, etc */
4228 /* Complete DELETE with "FROM" */
4229 else if (Matches("DELETE"))
4230 COMPLETE_WITH("FROM");
4231 /* Complete DELETE FROM with a list of tables */
4232 else if (TailMatches("DELETE", "FROM"))
4233 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_updatables);
4234 /* Complete DELETE FROM <table> */
4235 else if (TailMatches("DELETE", "FROM", MatchAny))
4236 COMPLETE_WITH("USING", "WHERE");
4237 /* XXX: implement tab completion for DELETE ... USING */
4238
4239/* DISCARD */
4240 else if (Matches("DISCARD"))
4241 COMPLETE_WITH("ALL", "PLANS", "SEQUENCES", "TEMP");
4242
4243/* DO */
4244 else if (Matches("DO"))
4245 COMPLETE_WITH("LANGUAGE");
4246
4247/* DROP */
4248 /* Complete DROP object with CASCADE / RESTRICT */
4249 else if (Matches("DROP",
4250 "COLLATION|CONVERSION|DOMAIN|EXTENSION|LANGUAGE|PUBLICATION|SCHEMA|SEQUENCE|SERVER|SUBSCRIPTION|STATISTICS|TABLE|TYPE|VIEW",
4251 MatchAny) ||
4252 Matches("DROP", "ACCESS", "METHOD", MatchAny) ||
4253 Matches("DROP", "EVENT", "TRIGGER", MatchAny) ||
4254 Matches("DROP", "FOREIGN", "DATA", "WRAPPER", MatchAny) ||
4255 Matches("DROP", "FOREIGN", "TABLE", MatchAny) ||
4256 Matches("DROP", "TEXT", "SEARCH", "CONFIGURATION|DICTIONARY|PARSER|TEMPLATE", MatchAny))
4257 COMPLETE_WITH("CASCADE", "RESTRICT");
4258 else if (Matches("DROP", "AGGREGATE|FUNCTION|PROCEDURE|ROUTINE", MatchAny, MatchAny) &&
4259 ends_with(prev_wd, ')'))
4260 COMPLETE_WITH("CASCADE", "RESTRICT");
4261
4262 /* help completing some of the variants */
4263 else if (Matches("DROP", "AGGREGATE|FUNCTION|PROCEDURE|ROUTINE", MatchAny))
4264 COMPLETE_WITH("(");
4265 else if (Matches("DROP", "AGGREGATE|FUNCTION|PROCEDURE|ROUTINE", MatchAny, "("))
4266 COMPLETE_WITH_FUNCTION_ARG(prev2_wd);
4267 else if (Matches("DROP", "FOREIGN"))
4268 COMPLETE_WITH("DATA WRAPPER", "TABLE");
4269 else if (Matches("DROP", "DATABASE", MatchAny))
4270 COMPLETE_WITH("WITH (");
4271 else if (HeadMatches("DROP", "DATABASE") && (ends_with(prev_wd, '(')))
4272 COMPLETE_WITH("FORCE");
4273
4274 /* DROP INDEX */
4275 else if (Matches("DROP", "INDEX"))
4276 COMPLETE_WITH_SCHEMA_QUERY_PLUS(Query_for_list_of_indexes,
4277 "CONCURRENTLY");
4278 else if (Matches("DROP", "INDEX", "CONCURRENTLY"))
4279 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_indexes);
4280 else if (Matches("DROP", "INDEX", MatchAny))
4281 COMPLETE_WITH("CASCADE", "RESTRICT");
4282 else if (Matches("DROP", "INDEX", "CONCURRENTLY", MatchAny))
4283 COMPLETE_WITH("CASCADE", "RESTRICT");
4284
4285 /* DROP MATERIALIZED VIEW */
4286 else if (Matches("DROP", "MATERIALIZED"))
4287 COMPLETE_WITH("VIEW");
4288 else if (Matches("DROP", "MATERIALIZED", "VIEW"))
4289 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_matviews);
4290 else if (Matches("DROP", "MATERIALIZED", "VIEW", MatchAny))
4291 COMPLETE_WITH("CASCADE", "RESTRICT");
4292
4293 /* DROP OWNED BY */
4294 else if (Matches("DROP", "OWNED"))
4295 COMPLETE_WITH("BY");
4296 else if (Matches("DROP", "OWNED", "BY"))
4297 COMPLETE_WITH_QUERY(Query_for_list_of_roles);
4298 else if (Matches("DROP", "OWNED", "BY", MatchAny))
4299 COMPLETE_WITH("CASCADE", "RESTRICT");
4300
4301 /* DROP TEXT SEARCH */
4302 else if (Matches("DROP", "TEXT", "SEARCH"))
4303 COMPLETE_WITH("CONFIGURATION", "DICTIONARY", "PARSER", "TEMPLATE");
4304
4305 /* DROP TRIGGER */
4306 else if (Matches("DROP", "TRIGGER", MatchAny))
4307 COMPLETE_WITH("ON");
4308 else if (Matches("DROP", "TRIGGER", MatchAny, "ON"))
4309 {
4310 set_completion_reference(prev2_wd);
4311 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables_for_trigger);
4312 }
4313 else if (Matches("DROP", "TRIGGER", MatchAny, "ON", MatchAny))
4314 COMPLETE_WITH("CASCADE", "RESTRICT");
4315
4316 /* DROP ACCESS METHOD */
4317 else if (Matches("DROP", "ACCESS"))
4318 COMPLETE_WITH("METHOD");
4319 else if (Matches("DROP", "ACCESS", "METHOD"))
4320 COMPLETE_WITH_QUERY(Query_for_list_of_access_methods);
4321
4322 /* DROP EVENT TRIGGER */
4323 else if (Matches("DROP", "EVENT"))
4324 COMPLETE_WITH("TRIGGER");
4325 else if (Matches("DROP", "EVENT", "TRIGGER"))
4326 COMPLETE_WITH_QUERY(Query_for_list_of_event_triggers);
4327
4328 /* DROP POLICY <name> */
4329 else if (Matches("DROP", "POLICY"))
4330 COMPLETE_WITH_QUERY(Query_for_list_of_policies);
4331 /* DROP POLICY <name> ON */
4332 else if (Matches("DROP", "POLICY", MatchAny))
4333 COMPLETE_WITH("ON");
4334 /* DROP POLICY <name> ON <table> */
4335 else if (Matches("DROP", "POLICY", MatchAny, "ON"))
4336 {
4337 set_completion_reference(prev2_wd);
4338 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables_for_policy);
4339 }
4340 else if (Matches("DROP", "POLICY", MatchAny, "ON", MatchAny))
4341 COMPLETE_WITH("CASCADE", "RESTRICT");
4342
4343 /* DROP RULE */
4344 else if (Matches("DROP", "RULE", MatchAny))
4345 COMPLETE_WITH("ON");
4346 else if (Matches("DROP", "RULE", MatchAny, "ON"))
4347 {
4348 set_completion_reference(prev2_wd);
4349 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables_for_rule);
4350 }
4351 else if (Matches("DROP", "RULE", MatchAny, "ON", MatchAny))
4352 COMPLETE_WITH("CASCADE", "RESTRICT");
4353
4354 /* DROP TRANSFORM */
4355 else if (Matches("DROP", "TRANSFORM"))
4356 COMPLETE_WITH("FOR");
4357 else if (Matches("DROP", "TRANSFORM", "FOR"))
4358 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_datatypes);
4359 else if (Matches("DROP", "TRANSFORM", "FOR", MatchAny))
4360 COMPLETE_WITH("LANGUAGE");
4361 else if (Matches("DROP", "TRANSFORM", "FOR", MatchAny, "LANGUAGE"))
4362 {
4363 set_completion_reference(prev2_wd);
4364 COMPLETE_WITH_QUERY(Query_for_list_of_languages);
4365 }
4366 else if (Matches("DROP", "TRANSFORM", "FOR", MatchAny, "LANGUAGE", MatchAny))
4367 COMPLETE_WITH("CASCADE", "RESTRICT");
4368
4369/* EXECUTE */
4370 else if (Matches("EXECUTE"))
4371 COMPLETE_WITH_QUERY(Query_for_list_of_prepared_statements);
4372
4373/*
4374 * EXPLAIN [ ( option [, ...] ) ] statement
4375 * EXPLAIN [ ANALYZE ] [ VERBOSE ] statement
4376 */
4377 else if (Matches("EXPLAIN"))
4378 COMPLETE_WITH("SELECT", "INSERT INTO", "DELETE FROM", "UPDATE", "DECLARE",
4379 "MERGE INTO", "EXECUTE", "ANALYZE", "VERBOSE");
4380 else if (HeadMatches("EXPLAIN", "(*") &&
4381 !HeadMatches("EXPLAIN", "(*)"))
4382 {
4383 /*
4384 * This fires if we're in an unfinished parenthesized option list.
4385 * get_previous_words treats a completed parenthesized option list as
4386 * one word, so the above test is correct.
4387 */
4388 if (ends_with(prev_wd, '(') || ends_with(prev_wd, ','))
4389 COMPLETE_WITH("ANALYZE", "VERBOSE", "COSTS", "SETTINGS", "GENERIC_PLAN",
4390 "BUFFERS", "SERIALIZE", "WAL", "TIMING", "SUMMARY",
4391 "MEMORY", "FORMAT");
4392 else if (TailMatches("ANALYZE|VERBOSE|COSTS|SETTINGS|GENERIC_PLAN|BUFFERS|WAL|TIMING|SUMMARY|MEMORY"))
4393 COMPLETE_WITH("ON", "OFF");
4394 else if (TailMatches("SERIALIZE"))
4395 COMPLETE_WITH("TEXT", "NONE", "BINARY");
4396 else if (TailMatches("FORMAT"))
4397 COMPLETE_WITH("TEXT", "XML", "JSON", "YAML");
4398 }
4399 else if (Matches("EXPLAIN", "ANALYZE"))
4400 COMPLETE_WITH("SELECT", "INSERT INTO", "DELETE FROM", "UPDATE", "DECLARE",
4401 "MERGE INTO", "EXECUTE", "VERBOSE");
4402 else if (Matches("EXPLAIN", "(*)") ||
4403 Matches("EXPLAIN", "VERBOSE") ||
4404 Matches("EXPLAIN", "ANALYZE", "VERBOSE"))
4405 COMPLETE_WITH("SELECT", "INSERT INTO", "DELETE FROM", "UPDATE", "DECLARE",
4406 "MERGE INTO", "EXECUTE");
4407
4408/* FETCH && MOVE */
4409
4410 /*
4411 * Complete FETCH with one of ABSOLUTE, BACKWARD, FORWARD, RELATIVE, ALL,
4412 * NEXT, PRIOR, FIRST, LAST, FROM, IN, and a list of cursors
4413 */
4414 else if (Matches("FETCH|MOVE"))
4415 COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_cursors,
4416 "ABSOLUTE",
4417 "BACKWARD",
4418 "FORWARD",
4419 "RELATIVE",
4420 "ALL",
4421 "NEXT",
4422 "PRIOR",
4423 "FIRST",
4424 "LAST",
4425 "FROM",
4426 "IN");
4427
4428 /*
4429 * Complete FETCH BACKWARD or FORWARD with one of ALL, FROM, IN, and a
4430 * list of cursors
4431 */
4432 else if (Matches("FETCH|MOVE", "BACKWARD|FORWARD"))
4433 COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_cursors,
4434 "ALL",
4435 "FROM",
4436 "IN");
4437
4438 /*
4439 * Complete FETCH <direction> with "FROM" or "IN". These are equivalent,
4440 * but we may as well tab-complete both: perhaps some users prefer one
4441 * variant or the other.
4442 */
4443 else if (Matches("FETCH|MOVE", "ABSOLUTE|BACKWARD|FORWARD|RELATIVE",
4444 MatchAnyExcept("FROM|IN")) ||
4445 Matches("FETCH|MOVE", "ALL|NEXT|PRIOR|FIRST|LAST"))
4446 COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_cursors,
4447 "FROM",
4448 "IN");
4449 /* Complete FETCH <direction> "FROM" or "IN" with a list of cursors */
4450 else if (Matches("FETCH|MOVE", MatchAnyN, "FROM|IN"))
4451 COMPLETE_WITH_QUERY(Query_for_list_of_cursors);
4452
4453/* FOREIGN DATA WRAPPER */
4454 /* applies in ALTER/DROP FDW and in CREATE SERVER */
4455 else if (TailMatches("FOREIGN", "DATA", "WRAPPER") &&
4456 !TailMatches("CREATE", MatchAny, MatchAny, MatchAny))
4457 COMPLETE_WITH_QUERY(Query_for_list_of_fdws);
4458 /* applies in CREATE SERVER */
4459 else if (Matches("CREATE", "SERVER", MatchAnyN, "FOREIGN", "DATA", "WRAPPER", MatchAny))
4460 COMPLETE_WITH("OPTIONS");
4461
4462/* FOREIGN TABLE */
4463 else if (TailMatches("FOREIGN", "TABLE") &&
4464 !TailMatches("CREATE", MatchAny, MatchAny))
4465 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_foreign_tables);
4466
4467/* FOREIGN SERVER */
4468 else if (TailMatches("FOREIGN", "SERVER"))
4469 COMPLETE_WITH_QUERY(Query_for_list_of_servers);
4470
4471/*
4472 * GRANT and REVOKE are allowed inside CREATE SCHEMA and
4473 * ALTER DEFAULT PRIVILEGES, so use TailMatches
4474 */
4475 /* Complete GRANT/REVOKE with a list of roles and privileges */
4476 else if (TailMatches("GRANT|REVOKE") ||
4477 TailMatches("REVOKE", "ADMIN|GRANT|INHERIT|SET", "OPTION", "FOR"))
4478 {
4479 /*
4480 * With ALTER DEFAULT PRIVILEGES, restrict completion to grantable
4481 * privileges (can't grant roles)
4482 */
4483 if (HeadMatches("ALTER", "DEFAULT", "PRIVILEGES"))
4484 {
4485 if (TailMatches("GRANT") ||
4486 TailMatches("REVOKE", "GRANT", "OPTION", "FOR"))
4487 COMPLETE_WITH("SELECT", "INSERT", "UPDATE",
4488 "DELETE", "TRUNCATE", "REFERENCES", "TRIGGER",
4489 "CREATE", "EXECUTE", "USAGE", "MAINTAIN", "ALL");
4490 else if (TailMatches("REVOKE"))
4491 COMPLETE_WITH("SELECT", "INSERT", "UPDATE",
4492 "DELETE", "TRUNCATE", "REFERENCES", "TRIGGER",
4493 "CREATE", "EXECUTE", "USAGE", "MAINTAIN", "ALL",
4494 "GRANT OPTION FOR");
4495 }
4496 else if (TailMatches("GRANT"))
4497 COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_roles,
4498 Privilege_options_of_grant_and_revoke);
4499 else if (TailMatches("REVOKE"))
4500 COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_roles,
4501 Privilege_options_of_grant_and_revoke,
4502 "GRANT OPTION FOR",
4503 "ADMIN OPTION FOR",
4504 "INHERIT OPTION FOR",
4505 "SET OPTION FOR");
4506 else if (TailMatches("REVOKE", "GRANT", "OPTION", "FOR"))
4507 COMPLETE_WITH(Privilege_options_of_grant_and_revoke);
4508 else if (TailMatches("REVOKE", "ADMIN|INHERIT|SET", "OPTION", "FOR"))
4509 COMPLETE_WITH_QUERY(Query_for_list_of_roles);
4510 }
4511
4512 else if (TailMatches("GRANT|REVOKE", "ALTER") ||
4513 TailMatches("REVOKE", "GRANT", "OPTION", "FOR", "ALTER"))
4514 COMPLETE_WITH("SYSTEM");
4515
4516 else if (TailMatches("REVOKE", "SET"))
4517 COMPLETE_WITH("ON PARAMETER", "OPTION FOR");
4518 else if (TailMatches("GRANT", "SET") ||
4519 TailMatches("REVOKE", "GRANT", "OPTION", "FOR", "SET") ||
4520 TailMatches("GRANT|REVOKE", "ALTER", "SYSTEM") ||
4521 TailMatches("REVOKE", "GRANT", "OPTION", "FOR", "ALTER", "SYSTEM"))
4522 COMPLETE_WITH("ON PARAMETER");
4523
4524 else if (TailMatches("GRANT|REVOKE", MatchAny, "ON", "PARAMETER") ||
4525 TailMatches("GRANT|REVOKE", MatchAny, MatchAny, "ON", "PARAMETER") ||
4526 TailMatches("REVOKE", "GRANT", "OPTION", "FOR", MatchAny, "ON", "PARAMETER") ||
4527 TailMatches("REVOKE", "GRANT", "OPTION", "FOR", MatchAny, MatchAny, "ON", "PARAMETER"))
4528 COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_alter_system_set_vars);
4529
4530 else if (TailMatches("GRANT", MatchAny, "ON", "PARAMETER", MatchAny) ||
4531 TailMatches("GRANT", MatchAny, MatchAny, "ON", "PARAMETER", MatchAny))
4532 COMPLETE_WITH("TO");
4533
4534 else if (TailMatches("REVOKE", MatchAny, "ON", "PARAMETER", MatchAny) ||
4535 TailMatches("REVOKE", MatchAny, MatchAny, "ON", "PARAMETER", MatchAny) ||
4536 TailMatches("REVOKE", "GRANT", "OPTION", "FOR", MatchAny, "ON", "PARAMETER", MatchAny) ||
4537 TailMatches("REVOKE", "GRANT", "OPTION", "FOR", MatchAny, MatchAny, "ON", "PARAMETER", MatchAny))
4538 COMPLETE_WITH("FROM");
4539
4540 /*
4541 * Complete GRANT/REVOKE <privilege> with "ON", GRANT/REVOKE <role> with
4542 * TO/FROM
4543 */
4544 else if (TailMatches("GRANT|REVOKE", MatchAny) ||
4545 TailMatches("REVOKE", "GRANT", "OPTION", "FOR", MatchAny))
4546 {
4547 if (TailMatches("SELECT|INSERT|UPDATE|DELETE|TRUNCATE|REFERENCES|TRIGGER|CREATE|CONNECT|TEMPORARY|TEMP|EXECUTE|USAGE|MAINTAIN|ALL"))
4548 COMPLETE_WITH("ON");
4549 else if (TailMatches("GRANT", MatchAny))
4550 COMPLETE_WITH("TO");
4551 else
4552 COMPLETE_WITH("FROM");
4553 }
4554
4555 /*
4556 * Complete GRANT/REVOKE <sth> ON with a list of appropriate relations.
4557 *
4558 * Note: GRANT/REVOKE can get quite complex; tab-completion as implemented
4559 * here will only work if the privilege list contains exactly one
4560 * privilege.
4561 */
4562 else if (TailMatches("GRANT|REVOKE", MatchAny, "ON") ||
4563 TailMatches("REVOKE", "GRANT", "OPTION", "FOR", MatchAny, "ON"))
4564 {
4565 /*
4566 * With ALTER DEFAULT PRIVILEGES, restrict completion to the kinds of
4567 * objects supported.
4568 */
4569 if (HeadMatches("ALTER", "DEFAULT", "PRIVILEGES"))
4570 COMPLETE_WITH("TABLES", "SEQUENCES", "FUNCTIONS", "PROCEDURES", "ROUTINES", "TYPES", "SCHEMAS", "LARGE OBJECTS");
4571 else
4572 COMPLETE_WITH_SCHEMA_QUERY_PLUS(Query_for_list_of_grantables,
4573 "ALL FUNCTIONS IN SCHEMA",
4574 "ALL PROCEDURES IN SCHEMA",
4575 "ALL ROUTINES IN SCHEMA",
4576 "ALL SEQUENCES IN SCHEMA",
4577 "ALL TABLES IN SCHEMA",
4578 "DATABASE",
4579 "DOMAIN",
4580 "FOREIGN DATA WRAPPER",
4581 "FOREIGN SERVER",
4582 "FUNCTION",
4583 "LANGUAGE",
4584 "LARGE OBJECT",
4585 "PARAMETER",
4586 "PROCEDURE",
4587 "ROUTINE",
4588 "SCHEMA",
4589 "SEQUENCE",
4590 "TABLE",
4591 "TABLESPACE",
4592 "TYPE");
4593 }
4594 else if (TailMatches("GRANT|REVOKE", MatchAny, "ON", "ALL") ||
4595 TailMatches("REVOKE", "GRANT", "OPTION", "FOR", MatchAny, "ON", "ALL"))
4596 COMPLETE_WITH("FUNCTIONS IN SCHEMA",
4597 "PROCEDURES IN SCHEMA",
4598 "ROUTINES IN SCHEMA",
4599 "SEQUENCES IN SCHEMA",
4600 "TABLES IN SCHEMA");
4601
4602 /*
4603 * Complete "GRANT/REVOKE * ON DATABASE/DOMAIN/..." with a list of
4604 * appropriate objects or keywords.
4605 *
4606 * Complete "GRANT/REVOKE * ON *" with "TO/FROM".
4607 */
4608 else if (TailMatches("GRANT|REVOKE", MatchAny, "ON", MatchAny) ||
4609 TailMatches("REVOKE", "GRANT", "OPTION", "FOR", MatchAny, "ON", MatchAny))
4610 {
4611 if (TailMatches("DATABASE"))
4612 COMPLETE_WITH_QUERY(Query_for_list_of_databases);
4613 else if (TailMatches("DOMAIN"))
4614 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_domains);
4615 else if (TailMatches("FUNCTION"))
4616 COMPLETE_WITH_VERSIONED_SCHEMA_QUERY(Query_for_list_of_functions);
4617 else if (TailMatches("FOREIGN"))
4618 COMPLETE_WITH("DATA WRAPPER", "SERVER");
4619 else if (TailMatches("LANGUAGE"))
4620 COMPLETE_WITH_QUERY(Query_for_list_of_languages);
4621 else if (TailMatches("LARGE"))
4622 {
4623 if (HeadMatches("ALTER", "DEFAULT", "PRIVILEGES"))
4624 COMPLETE_WITH("OBJECTS");
4625 else
4626 COMPLETE_WITH("OBJECT");
4627 }
4628 else if (TailMatches("PROCEDURE"))
4629 COMPLETE_WITH_VERSIONED_SCHEMA_QUERY(Query_for_list_of_procedures);
4630 else if (TailMatches("ROUTINE"))
4631 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_routines);
4632 else if (TailMatches("SCHEMA"))
4633 COMPLETE_WITH_QUERY(Query_for_list_of_schemas);
4634 else if (TailMatches("SEQUENCE"))
4635 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_sequences);
4636 else if (TailMatches("TABLE"))
4637 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_grantables);
4638 else if (TailMatches("TABLESPACE"))
4639 COMPLETE_WITH_QUERY(Query_for_list_of_tablespaces);
4640 else if (TailMatches("TYPE"))
4641 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_datatypes);
4642 else if (TailMatches("GRANT", MatchAny, MatchAny, MatchAny))
4643 COMPLETE_WITH("TO");
4644 else
4645 COMPLETE_WITH("FROM");
4646 }
4647
4648 /*
4649 * Complete "GRANT/REVOKE ... TO/FROM" with username, PUBLIC,
4650 * CURRENT_ROLE, CURRENT_USER, or SESSION_USER.
4651 */
4652 else if (Matches("GRANT", MatchAnyN, "TO") ||
4653 Matches("REVOKE", MatchAnyN, "FROM"))
4654 COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_roles,
4655 Keywords_for_list_of_grant_roles);
4656
4657 /*
4658 * Offer grant options after that.
4659 */
4660 else if (Matches("GRANT", MatchAnyN, "TO", MatchAny))
4661 COMPLETE_WITH("WITH ADMIN",
4662 "WITH INHERIT",
4663 "WITH SET",
4664 "WITH GRANT OPTION",
4665 "GRANTED BY");
4666 else if (Matches("GRANT", MatchAnyN, "TO", MatchAny, "WITH"))
4667 COMPLETE_WITH("ADMIN",
4668 "INHERIT",
4669 "SET",
4670 "GRANT OPTION");
4671 else if (Matches("GRANT", MatchAnyN, "TO", MatchAny, "WITH", "ADMIN|INHERIT|SET"))
4672 COMPLETE_WITH("OPTION", "TRUE", "FALSE");
4673 else if (Matches("GRANT", MatchAnyN, "TO", MatchAny, "WITH", MatchAny, "OPTION"))
4674 COMPLETE_WITH("GRANTED BY");
4675 else if (Matches("GRANT", MatchAnyN, "TO", MatchAny, "WITH", MatchAny, "OPTION", "GRANTED", "BY"))
4676 COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_roles,
4677 Keywords_for_list_of_grant_roles);
4678 /* Complete "ALTER DEFAULT PRIVILEGES ... GRANT/REVOKE ... TO/FROM */
4679 else if (Matches("ALTER", "DEFAULT", "PRIVILEGES", MatchAnyN, "TO|FROM"))
4680 COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_roles,
4681 Keywords_for_list_of_grant_roles);
4682 /* Offer WITH GRANT OPTION after that */
4683 else if (Matches("ALTER", "DEFAULT", "PRIVILEGES", MatchAnyN, "TO", MatchAny))
4684 COMPLETE_WITH("WITH GRANT OPTION");
4685 /* Complete "GRANT/REVOKE ... ON * *" with TO/FROM */
4686 else if (Matches("GRANT|REVOKE", MatchAnyN, "ON", MatchAny, MatchAny) &&
4687 !TailMatches("FOREIGN", "SERVER") && !TailMatches("LARGE", "OBJECT"))
4688 {
4689 if (Matches("GRANT", MatchAnyN, "ON", MatchAny, MatchAny))
4690 COMPLETE_WITH("TO");
4691 else
4692 COMPLETE_WITH("FROM");
4693 }
4694
4695 /* Complete "GRANT/REVOKE * ON ALL * IN SCHEMA *" with TO/FROM */
4696 else if (TailMatches("GRANT|REVOKE", MatchAny, "ON", "ALL", MatchAny, "IN", "SCHEMA", MatchAny) ||
4697 TailMatches("REVOKE", "GRANT", "OPTION", "FOR", MatchAny, "ON", "ALL", MatchAny, "IN", "SCHEMA", MatchAny))
4698 {
4699 if (TailMatches("GRANT", MatchAny, MatchAny, MatchAny, MatchAny, MatchAny, MatchAny, MatchAny))
4700 COMPLETE_WITH("TO");
4701 else
4702 COMPLETE_WITH("FROM");
4703 }
4704
4705 /* Complete "GRANT/REVOKE * ON FOREIGN DATA WRAPPER *" with TO/FROM */
4706 else if (TailMatches("GRANT|REVOKE", MatchAny, "ON", "FOREIGN", "DATA", "WRAPPER", MatchAny) ||
4707 TailMatches("REVOKE", "GRANT", "OPTION", "FOR", MatchAny, "ON", "FOREIGN", "DATA", "WRAPPER", MatchAny))
4708 {
4709 if (TailMatches("GRANT", MatchAny, MatchAny, MatchAny, MatchAny, MatchAny, MatchAny))
4710 COMPLETE_WITH("TO");
4711 else
4712 COMPLETE_WITH("FROM");
4713 }
4714
4715 /* Complete "GRANT/REVOKE * ON FOREIGN SERVER *" with TO/FROM */
4716 else if (TailMatches("GRANT|REVOKE", MatchAny, "ON", "FOREIGN", "SERVER", MatchAny) ||
4717 TailMatches("REVOKE", "GRANT", "OPTION", "FOR", MatchAny, "ON", "FOREIGN", "SERVER", MatchAny))
4718 {
4719 if (TailMatches("GRANT", MatchAny, MatchAny, MatchAny, MatchAny, MatchAny))
4720 COMPLETE_WITH("TO");
4721 else
4722 COMPLETE_WITH("FROM");
4723 }
4724
4725 /* Complete "GRANT/REVOKE * ON LARGE OBJECT *" with TO/FROM */
4726 else if (TailMatches("GRANT|REVOKE", MatchAny, "ON", "LARGE", "OBJECT", MatchAny) ||
4727 TailMatches("REVOKE", "GRANT", "OPTION", "FOR", MatchAny, "ON", "LARGE", "OBJECT", MatchAny))
4728 {
4729 if (TailMatches("GRANT", MatchAny, MatchAny, MatchAny, MatchAny, MatchAny))
4730 COMPLETE_WITH("TO");
4731 else
4732 COMPLETE_WITH("FROM");
4733 }
4734
4735 /* Complete "GRANT/REVOKE * ON LARGE OBJECTS" with TO/FROM */
4736 else if (TailMatches("GRANT|REVOKE", MatchAny, "ON", "LARGE", "OBJECTS") ||
4737 TailMatches("REVOKE", "GRANT", "OPTION", "FOR", MatchAny, "ON", "LARGE", "OBJECTS"))
4738 {
4739 if (TailMatches("GRANT", MatchAny, MatchAny, MatchAny, MatchAny))
4740 COMPLETE_WITH("TO");
4741 else
4742 COMPLETE_WITH("FROM");
4743 }
4744
4745/* GROUP BY */
4746 else if (TailMatches("FROM", MatchAny, "GROUP"))
4747 COMPLETE_WITH("BY");
4748
4749/* IMPORT FOREIGN SCHEMA */
4750 else if (Matches("IMPORT"))
4751 COMPLETE_WITH("FOREIGN SCHEMA");
4752 else if (Matches("IMPORT", "FOREIGN"))
4753 COMPLETE_WITH("SCHEMA");
4754 else if (Matches("IMPORT", "FOREIGN", "SCHEMA", MatchAny))
4755 COMPLETE_WITH("EXCEPT (", "FROM SERVER", "LIMIT TO (");
4756 else if (TailMatches("LIMIT", "TO", "(*)") ||
4757 TailMatches("EXCEPT", "(*)"))
4758 COMPLETE_WITH("FROM SERVER");
4759 else if (TailMatches("FROM", "SERVER", MatchAny))
4760 COMPLETE_WITH("INTO");
4761 else if (TailMatches("FROM", "SERVER", MatchAny, "INTO"))
4762 COMPLETE_WITH_QUERY(Query_for_list_of_schemas);
4763 else if (TailMatches("FROM", "SERVER", MatchAny, "INTO", MatchAny))
4764 COMPLETE_WITH("OPTIONS (");
4765
4766/* INSERT --- can be inside EXPLAIN, RULE, etc */
4767 /* Complete NOT MATCHED THEN INSERT */
4768 else if (TailMatches("NOT", "MATCHED", "THEN", "INSERT"))
4769 COMPLETE_WITH("VALUES", "(");
4770 /* Complete INSERT with "INTO" */
4771 else if (TailMatches("INSERT"))
4772 COMPLETE_WITH("INTO");
4773 /* Complete INSERT INTO with table names */
4774 else if (TailMatches("INSERT", "INTO"))
4775 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_updatables);
4776 /* Complete "INSERT INTO <table> (" with attribute names */
4777 else if (TailMatches("INSERT", "INTO", MatchAny, "("))
4778 COMPLETE_WITH_ATTR(prev2_wd);
4779
4780 /*
4781 * Complete INSERT INTO <table> with "(" or "VALUES" or "SELECT" or
4782 * "TABLE" or "DEFAULT VALUES" or "OVERRIDING"
4783 */
4784 else if (TailMatches("INSERT", "INTO", MatchAny))
4785 COMPLETE_WITH("(", "DEFAULT VALUES", "SELECT", "TABLE", "VALUES", "OVERRIDING");
4786
4787 /*
4788 * Complete INSERT INTO <table> (attribs) with "VALUES" or "SELECT" or
4789 * "TABLE" or "OVERRIDING"
4790 */
4791 else if (TailMatches("INSERT", "INTO", MatchAny, MatchAny) &&
4792 ends_with(prev_wd, ')'))
4793 COMPLETE_WITH("SELECT", "TABLE", "VALUES", "OVERRIDING");
4794
4795 /* Complete OVERRIDING */
4796 else if (TailMatches("OVERRIDING"))
4797 COMPLETE_WITH("SYSTEM VALUE", "USER VALUE");
4798
4799 /* Complete after OVERRIDING clause */
4800 else if (TailMatches("OVERRIDING", MatchAny, "VALUE"))
4801 COMPLETE_WITH("SELECT", "TABLE", "VALUES");
4802
4803 /* Insert an open parenthesis after "VALUES" */
4804 else if (TailMatches("VALUES") && !TailMatches("DEFAULT", "VALUES"))
4805 COMPLETE_WITH("(");
4806
4807/* LOCK */
4808 /* Complete LOCK [TABLE] [ONLY] with a list of tables */
4809 else if (Matches("LOCK"))
4810 COMPLETE_WITH_SCHEMA_QUERY_PLUS(Query_for_list_of_tables,
4811 "TABLE", "ONLY");
4812 else if (Matches("LOCK", "TABLE"))
4813 COMPLETE_WITH_SCHEMA_QUERY_PLUS(Query_for_list_of_tables,
4814 "ONLY");
4815 else if (Matches("LOCK", "TABLE", "ONLY") || Matches("LOCK", "ONLY"))
4816 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables);
4817 /* For the following, handle the case of a single table only for now */
4818
4819 /* Complete LOCK [TABLE] [ONLY] <table> with IN or NOWAIT */
4820 else if (Matches("LOCK", MatchAnyExcept("TABLE|ONLY")) ||
4821 Matches("LOCK", "TABLE", MatchAnyExcept("ONLY")) ||
4822 Matches("LOCK", "ONLY", MatchAny) ||
4823 Matches("LOCK", "TABLE", "ONLY", MatchAny))
4824 COMPLETE_WITH("IN", "NOWAIT");
4825
4826 /* Complete LOCK [TABLE] [ONLY] <table> IN with a lock mode */
4827 else if (Matches("LOCK", MatchAnyN, "IN"))
4828 COMPLETE_WITH("ACCESS SHARE MODE",
4829 "ROW SHARE MODE", "ROW EXCLUSIVE MODE",
4830 "SHARE UPDATE EXCLUSIVE MODE", "SHARE MODE",
4831 "SHARE ROW EXCLUSIVE MODE",
4832 "EXCLUSIVE MODE", "ACCESS EXCLUSIVE MODE");
4833
4834 /*
4835 * Complete LOCK [TABLE][ONLY] <table> IN ACCESS|ROW with rest of lock
4836 * mode
4837 */
4838 else if (Matches("LOCK", MatchAnyN, "IN", "ACCESS|ROW"))
4839 COMPLETE_WITH("EXCLUSIVE MODE", "SHARE MODE");
4840
4841 /* Complete LOCK [TABLE] [ONLY] <table> IN SHARE with rest of lock mode */
4842 else if (Matches("LOCK", MatchAnyN, "IN", "SHARE"))
4843 COMPLETE_WITH("MODE", "ROW EXCLUSIVE MODE",
4844 "UPDATE EXCLUSIVE MODE");
4845
4846 /* Complete LOCK [TABLE] [ONLY] <table> [IN lockmode MODE] with "NOWAIT" */
4847 else if (Matches("LOCK", MatchAnyN, "MODE"))
4848 COMPLETE_WITH("NOWAIT");
4849
4850/* MERGE --- can be inside EXPLAIN */
4851 else if (TailMatches("MERGE"))
4852 COMPLETE_WITH("INTO");
4853 else if (TailMatches("MERGE", "INTO"))
4854 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_mergetargets);
4855
4856 /* Complete MERGE INTO <table> [[AS] <alias>] with USING */
4857 else if (TailMatches("MERGE", "INTO", MatchAny))
4858 COMPLETE_WITH("USING", "AS");
4859 else if (TailMatches("MERGE", "INTO", MatchAny, "AS", MatchAny) ||
4860 TailMatches("MERGE", "INTO", MatchAny, MatchAnyExcept("USING|AS")))
4861 COMPLETE_WITH("USING");
4862
4863 /*
4864 * Complete MERGE INTO ... USING with a list of relations supporting
4865 * SELECT
4866 */
4867 else if (TailMatches("MERGE", "INTO", MatchAny, "USING") ||
4868 TailMatches("MERGE", "INTO", MatchAny, "AS", MatchAny, "USING") ||
4869 TailMatches("MERGE", "INTO", MatchAny, MatchAny, "USING"))
4870 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_selectables);
4871
4872 /*
4873 * Complete MERGE INTO <table> [[AS] <alias>] USING <relations> [[AS]
4874 * alias] with ON
4875 */
4876 else if (TailMatches("MERGE", "INTO", MatchAny, "USING", MatchAny) ||
4877 TailMatches("MERGE", "INTO", MatchAny, "AS", MatchAny, "USING", MatchAny) ||
4878 TailMatches("MERGE", "INTO", MatchAny, MatchAny, "USING", MatchAny))
4879 COMPLETE_WITH("AS", "ON");
4880 else if (TailMatches("MERGE", "INTO", MatchAny, "USING", MatchAny, "AS", MatchAny) ||
4881 TailMatches("MERGE", "INTO", MatchAny, "AS", MatchAny, "USING", MatchAny, "AS", MatchAny) ||
4882 TailMatches("MERGE", "INTO", MatchAny, MatchAny, "USING", MatchAny, "AS", MatchAny) ||
4883 TailMatches("MERGE", "INTO", MatchAny, "USING", MatchAny, MatchAnyExcept("ON|AS")) ||
4884 TailMatches("MERGE", "INTO", MatchAny, "AS", MatchAny, "USING", MatchAny, MatchAnyExcept("ON|AS")) ||
4885 TailMatches("MERGE", "INTO", MatchAny, MatchAny, "USING", MatchAny, MatchAnyExcept("ON|AS")))
4886 COMPLETE_WITH("ON");
4887
4888 /* Complete MERGE INTO ... ON with target table attributes */
4889 else if (TailMatches("INTO", MatchAny, "USING", MatchAny, "ON"))
4890 COMPLETE_WITH_ATTR(prev4_wd);
4891 else if (TailMatches("INTO", MatchAny, "AS", MatchAny, "USING", MatchAny, "AS", MatchAny, "ON"))
4892 COMPLETE_WITH_ATTR(prev8_wd);
4893 else if (TailMatches("INTO", MatchAny, MatchAny, "USING", MatchAny, MatchAny, "ON"))
4894 COMPLETE_WITH_ATTR(prev6_wd);
4895
4896 /*
4897 * Complete ... USING <relation> [[AS] alias] ON join condition
4898 * (consisting of one or three words typically used) with WHEN [NOT]
4899 * MATCHED
4900 */
4901 else if (TailMatches("USING", MatchAny, "ON", MatchAny) ||
4902 TailMatches("USING", MatchAny, "AS", MatchAny, "ON", MatchAny) ||
4903 TailMatches("USING", MatchAny, MatchAny, "ON", MatchAny) ||
4904 TailMatches("USING", MatchAny, "ON", MatchAny, MatchAnyExcept("WHEN"), MatchAnyExcept("WHEN")) ||
4905 TailMatches("USING", MatchAny, "AS", MatchAny, "ON", MatchAny, MatchAnyExcept("WHEN"), MatchAnyExcept("WHEN")) ||
4906 TailMatches("USING", MatchAny, MatchAny, "ON", MatchAny, MatchAnyExcept("WHEN"), MatchAnyExcept("WHEN")))
4907 COMPLETE_WITH("WHEN MATCHED", "WHEN NOT MATCHED");
4908 else if (TailMatches("USING", MatchAny, "ON", MatchAny, "WHEN") ||
4909 TailMatches("USING", MatchAny, "AS", MatchAny, "ON", MatchAny, "WHEN") ||
4910 TailMatches("USING", MatchAny, MatchAny, "ON", MatchAny, "WHEN") ||
4911 TailMatches("USING", MatchAny, "ON", MatchAny, MatchAny, MatchAny, "WHEN") ||
4912 TailMatches("USING", MatchAny, "AS", MatchAny, "ON", MatchAny, MatchAny, MatchAny, "WHEN") ||
4913 TailMatches("USING", MatchAny, MatchAny, "ON", MatchAny, MatchAny, MatchAny, "WHEN"))
4914 COMPLETE_WITH("MATCHED", "NOT MATCHED");
4915
4916 /*
4917 * Complete ... WHEN MATCHED and WHEN NOT MATCHED BY SOURCE|TARGET with
4918 * THEN/AND
4919 */
4920 else if (TailMatches("WHEN", "MATCHED") ||
4921 TailMatches("WHEN", "NOT", "MATCHED", "BY", "SOURCE|TARGET"))
4922 COMPLETE_WITH("THEN", "AND");
4923
4924 /* Complete ... WHEN NOT MATCHED with BY/THEN/AND */
4925 else if (TailMatches("WHEN", "NOT", "MATCHED"))
4926 COMPLETE_WITH("BY", "THEN", "AND");
4927
4928 /* Complete ... WHEN NOT MATCHED BY with SOURCE/TARGET */
4929 else if (TailMatches("WHEN", "NOT", "MATCHED", "BY"))
4930 COMPLETE_WITH("SOURCE", "TARGET");
4931
4932 /*
4933 * Complete ... WHEN MATCHED THEN and WHEN NOT MATCHED BY SOURCE THEN with
4934 * UPDATE SET/DELETE/DO NOTHING
4935 */
4936 else if (TailMatches("WHEN", "MATCHED", "THEN") ||
4937 TailMatches("WHEN", "NOT", "MATCHED", "BY", "SOURCE", "THEN"))
4938 COMPLETE_WITH("UPDATE SET", "DELETE", "DO NOTHING");
4939
4940 /*
4941 * Complete ... WHEN NOT MATCHED [BY TARGET] THEN with INSERT/DO NOTHING
4942 */
4943 else if (TailMatches("WHEN", "NOT", "MATCHED", "THEN") ||
4944 TailMatches("WHEN", "NOT", "MATCHED", "BY", "TARGET", "THEN"))
4945 COMPLETE_WITH("INSERT", "DO NOTHING");
4946
4947/* NOTIFY --- can be inside EXPLAIN, RULE, etc */
4948 else if (TailMatches("NOTIFY"))
4949 COMPLETE_WITH_QUERY(Query_for_list_of_channels);
4950
4951/* OPTIONS */
4952 else if (TailMatches("OPTIONS"))
4953 COMPLETE_WITH("(");
4954
4955/* OWNER TO - complete with available roles */
4956 else if (TailMatches("OWNER", "TO"))
4957 COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_roles,
4958 Keywords_for_list_of_owner_roles);
4959
4960/* ORDER BY */
4961 else if (TailMatches("FROM", MatchAny, "ORDER"))
4962 COMPLETE_WITH("BY");
4963 else if (TailMatches("FROM", MatchAny, "ORDER", "BY"))
4964 COMPLETE_WITH_ATTR(prev3_wd);
4965
4966/* PREPARE xx AS */
4967 else if (Matches("PREPARE", MatchAny, "AS"))
4968 COMPLETE_WITH("SELECT", "UPDATE", "INSERT INTO", "DELETE FROM",
4969 "MERGE INTO", "VALUES", "WITH", "TABLE");
4970
4971/*
4972 * PREPARE TRANSACTION is missing on purpose. It's intended for transaction
4973 * managers, not for manual use in interactive sessions.
4974 */
4975
4976/* REASSIGN OWNED BY xxx TO yyy */
4977 else if (Matches("REASSIGN"))
4978 COMPLETE_WITH("OWNED BY");
4979 else if (Matches("REASSIGN", "OWNED"))
4980 COMPLETE_WITH("BY");
4981 else if (Matches("REASSIGN", "OWNED", "BY"))
4982 COMPLETE_WITH_QUERY(Query_for_list_of_roles);
4983 else if (Matches("REASSIGN", "OWNED", "BY", MatchAny))
4984 COMPLETE_WITH("TO");
4985 else if (Matches("REASSIGN", "OWNED", "BY", MatchAny, "TO"))
4986 COMPLETE_WITH_QUERY(Query_for_list_of_roles);
4987
4988/* REFRESH MATERIALIZED VIEW */
4989 else if (Matches("REFRESH"))
4990 COMPLETE_WITH("MATERIALIZED VIEW");
4991 else if (Matches("REFRESH", "MATERIALIZED"))
4992 COMPLETE_WITH("VIEW");
4993 else if (Matches("REFRESH", "MATERIALIZED", "VIEW"))
4994 COMPLETE_WITH_SCHEMA_QUERY_PLUS(Query_for_list_of_matviews,
4995 "CONCURRENTLY");
4996 else if (Matches("REFRESH", "MATERIALIZED", "VIEW", "CONCURRENTLY"))
4997 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_matviews);
4998 else if (Matches("REFRESH", "MATERIALIZED", "VIEW", MatchAny))
4999 COMPLETE_WITH("WITH");
5000 else if (Matches("REFRESH", "MATERIALIZED", "VIEW", "CONCURRENTLY", MatchAny))
5001 COMPLETE_WITH("WITH");
5002 else if (Matches("REFRESH", "MATERIALIZED", "VIEW", MatchAny, "WITH"))
5003 COMPLETE_WITH("NO DATA", "DATA");
5004 else if (Matches("REFRESH", "MATERIALIZED", "VIEW", "CONCURRENTLY", MatchAny, "WITH"))
5005 COMPLETE_WITH("NO DATA", "DATA");
5006 else if (Matches("REFRESH", "MATERIALIZED", "VIEW", MatchAny, "WITH", "NO"))
5007 COMPLETE_WITH("DATA");
5008 else if (Matches("REFRESH", "MATERIALIZED", "VIEW", "CONCURRENTLY", MatchAny, "WITH", "NO"))
5009 COMPLETE_WITH("DATA");
5010
5011/* REINDEX */
5012 else if (Matches("REINDEX") ||
5013 Matches("REINDEX", "(*)"))
5014 COMPLETE_WITH("TABLE", "INDEX", "SYSTEM", "SCHEMA", "DATABASE");
5015 else if (Matches("REINDEX", "TABLE") ||
5016 Matches("REINDEX", "(*)", "TABLE"))
5017 COMPLETE_WITH_SCHEMA_QUERY_PLUS(Query_for_list_of_indexables,
5018 "CONCURRENTLY");
5019 else if (Matches("REINDEX", "INDEX") ||
5020 Matches("REINDEX", "(*)", "INDEX"))
5021 COMPLETE_WITH_SCHEMA_QUERY_PLUS(Query_for_list_of_indexes,
5022 "CONCURRENTLY");
5023 else if (Matches("REINDEX", "SCHEMA") ||
5024 Matches("REINDEX", "(*)", "SCHEMA"))
5025 COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas,
5026 "CONCURRENTLY");
5027 else if (Matches("REINDEX", "SYSTEM|DATABASE") ||
5028 Matches("REINDEX", "(*)", "SYSTEM|DATABASE"))
5029 COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_databases,
5030 "CONCURRENTLY");
5031 else if (Matches("REINDEX", "TABLE", "CONCURRENTLY") ||
5032 Matches("REINDEX", "(*)", "TABLE", "CONCURRENTLY"))
5033 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_indexables);
5034 else if (Matches("REINDEX", "INDEX", "CONCURRENTLY") ||
5035 Matches("REINDEX", "(*)", "INDEX", "CONCURRENTLY"))
5036 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_indexes);
5037 else if (Matches("REINDEX", "SCHEMA", "CONCURRENTLY") ||
5038 Matches("REINDEX", "(*)", "SCHEMA", "CONCURRENTLY"))
5039 COMPLETE_WITH_QUERY(Query_for_list_of_schemas);
5040 else if (Matches("REINDEX", "SYSTEM|DATABASE", "CONCURRENTLY") ||
5041 Matches("REINDEX", "(*)", "SYSTEM|DATABASE", "CONCURRENTLY"))
5042 COMPLETE_WITH_QUERY(Query_for_list_of_databases);
5043 else if (HeadMatches("REINDEX", "(*") &&
5044 !HeadMatches("REINDEX", "(*)"))
5045 {
5046 /*
5047 * This fires if we're in an unfinished parenthesized option list.
5048 * get_previous_words treats a completed parenthesized option list as
5049 * one word, so the above test is correct.
5050 */
5051 if (ends_with(prev_wd, '(') || ends_with(prev_wd, ','))
5052 COMPLETE_WITH("CONCURRENTLY", "TABLESPACE", "VERBOSE");
5053 else if (TailMatches("TABLESPACE"))
5054 COMPLETE_WITH_QUERY(Query_for_list_of_tablespaces);
5055 }
5056
5057/* SECURITY LABEL */
5058 else if (Matches("SECURITY"))
5059 COMPLETE_WITH("LABEL");
5060 else if (Matches("SECURITY", "LABEL"))
5061 COMPLETE_WITH("ON", "FOR");
5062 else if (Matches("SECURITY", "LABEL", "FOR", MatchAny))
5063 COMPLETE_WITH("ON");
5064 else if (Matches("SECURITY", "LABEL", "ON") ||
5065 Matches("SECURITY", "LABEL", "FOR", MatchAny, "ON"))
5066 COMPLETE_WITH("TABLE", "COLUMN", "AGGREGATE", "DATABASE", "DOMAIN",
5067 "EVENT TRIGGER", "FOREIGN TABLE", "FUNCTION",
5068 "LARGE OBJECT", "MATERIALIZED VIEW", "LANGUAGE",
5069 "PUBLICATION", "PROCEDURE", "ROLE", "ROUTINE", "SCHEMA",
5070 "SEQUENCE", "SUBSCRIPTION", "TABLESPACE", "TYPE", "VIEW");
5071 else if (Matches("SECURITY", "LABEL", "ON", MatchAny, MatchAny))
5072 COMPLETE_WITH("IS");
5073
5074/* SELECT */
5075 /* naah . . . */
5076
5077/* SET, RESET, SHOW */
5078 /* Complete with a variable name */
5079 else if (TailMatches("SET|RESET") &&
5080 !TailMatches("UPDATE", MatchAny, "SET") &&
5081 !TailMatches("ALTER", "DATABASE|USER|ROLE", MatchAny, "RESET"))
5082 COMPLETE_WITH_QUERY_VERBATIM_PLUS(Query_for_list_of_set_vars,
5083 "CONSTRAINTS",
5084 "TRANSACTION",
5085 "SESSION",
5086 "ROLE",
5087 "TABLESPACE",
5088 "ALL");
5089 else if (Matches("SHOW"))
5090 COMPLETE_WITH_QUERY_VERBATIM_PLUS(Query_for_list_of_show_vars,
5091 "SESSION AUTHORIZATION",
5092 "ALL");
5093 else if (Matches("SHOW", "SESSION"))
5094 COMPLETE_WITH("AUTHORIZATION");
5095 /* Complete "SET TRANSACTION" */
5096 else if (Matches("SET", "TRANSACTION"))
5097 COMPLETE_WITH("SNAPSHOT", "ISOLATION LEVEL", "READ", "DEFERRABLE", "NOT DEFERRABLE");
5098 else if (Matches("BEGIN|START", "TRANSACTION") ||
5099 Matches("BEGIN", "WORK") ||
5100 Matches("BEGIN") ||
5101 Matches("SET", "SESSION", "CHARACTERISTICS", "AS", "TRANSACTION"))
5102 COMPLETE_WITH("ISOLATION LEVEL", "READ", "DEFERRABLE", "NOT DEFERRABLE");
5103 else if (Matches("SET|BEGIN|START", "TRANSACTION|WORK", "NOT") ||
5104 Matches("BEGIN", "NOT") ||
5105 Matches("SET", "SESSION", "CHARACTERISTICS", "AS", "TRANSACTION", "NOT"))
5106 COMPLETE_WITH("DEFERRABLE");
5107 else if (Matches("SET|BEGIN|START", "TRANSACTION|WORK", "ISOLATION") ||
5108 Matches("BEGIN", "ISOLATION") ||
5109 Matches("SET", "SESSION", "CHARACTERISTICS", "AS", "TRANSACTION", "ISOLATION"))
5110 COMPLETE_WITH("LEVEL");
5111 else if (Matches("SET|BEGIN|START", "TRANSACTION|WORK", "ISOLATION", "LEVEL") ||
5112 Matches("BEGIN", "ISOLATION", "LEVEL") ||
5113 Matches("SET", "SESSION", "CHARACTERISTICS", "AS", "TRANSACTION", "ISOLATION", "LEVEL"))
5114 COMPLETE_WITH("READ", "REPEATABLE READ", "SERIALIZABLE");
5115 else if (Matches("SET|BEGIN|START", "TRANSACTION|WORK", "ISOLATION", "LEVEL", "READ") ||
5116 Matches("BEGIN", "ISOLATION", "LEVEL", "READ") ||
5117 Matches("SET", "SESSION", "CHARACTERISTICS", "AS", "TRANSACTION", "ISOLATION", "LEVEL", "READ"))
5118 COMPLETE_WITH("UNCOMMITTED", "COMMITTED");
5119 else if (Matches("SET|BEGIN|START", "TRANSACTION|WORK", "ISOLATION", "LEVEL", "REPEATABLE") ||
5120 Matches("BEGIN", "ISOLATION", "LEVEL", "REPEATABLE") ||
5121 Matches("SET", "SESSION", "CHARACTERISTICS", "AS", "TRANSACTION", "ISOLATION", "LEVEL", "REPEATABLE"))
5122 COMPLETE_WITH("READ");
5123 else if (Matches("SET|BEGIN|START", "TRANSACTION|WORK", "READ") ||
5124 Matches("BEGIN", "READ") ||
5125 Matches("SET", "SESSION", "CHARACTERISTICS", "AS", "TRANSACTION", "READ"))
5126 COMPLETE_WITH("ONLY", "WRITE");
5127 /* SET CONSTRAINTS */
5128 else if (Matches("SET", "CONSTRAINTS"))
5129 COMPLETE_WITH_SCHEMA_QUERY_PLUS(Query_for_list_of_constraints_with_schema,
5130 "ALL");
5131 /* Complete SET CONSTRAINTS <foo> with DEFERRED|IMMEDIATE */
5132 else if (Matches("SET", "CONSTRAINTS", MatchAny))
5133 COMPLETE_WITH("DEFERRED", "IMMEDIATE");
5134 /* Complete SET ROLE */
5135 else if (Matches("SET", "ROLE"))
5136 COMPLETE_WITH_QUERY(Query_for_list_of_roles);
5137 /* Complete SET SESSION with AUTHORIZATION or CHARACTERISTICS... */
5138 else if (Matches("SET", "SESSION"))
5139 COMPLETE_WITH("AUTHORIZATION", "CHARACTERISTICS AS TRANSACTION");
5140 /* Complete SET SESSION AUTHORIZATION with username */
5141 else if (Matches("SET", "SESSION", "AUTHORIZATION"))
5142 COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_roles,
5143 "DEFAULT");
5144 /* Complete RESET SESSION with AUTHORIZATION */
5145 else if (Matches("RESET", "SESSION"))
5146 COMPLETE_WITH("AUTHORIZATION");
5147 /* Complete SET <var> with "TO" */
5148 else if (Matches("SET", MatchAny))
5149 COMPLETE_WITH("TO");
5150
5151 /*
5152 * Complete ALTER DATABASE|FUNCTION|PROCEDURE|ROLE|ROUTINE|USER ... SET
5153 * <name>
5154 */
5155 else if (Matches("ALTER", "DATABASE|FUNCTION|PROCEDURE|ROLE|ROUTINE|USER", MatchAnyN, "SET", MatchAnyExcept("SCHEMA")))
5156 COMPLETE_WITH("FROM CURRENT", "TO");
5157
5158 /*
5159 * Suggest possible variable values in SET variable TO|=, along with the
5160 * preceding ALTER syntaxes.
5161 */
5162 else if (TailMatches("SET", MatchAny, "TO|=") &&
5163 !TailMatches("UPDATE", MatchAny, "SET", MatchAny, "TO|="))
5164 {
5165 /* special cased code for individual GUCs */
5166 if (TailMatches("DateStyle", "TO|="))
5167 COMPLETE_WITH("ISO", "SQL", "Postgres", "German",
5168 "YMD", "DMY", "MDY",
5169 "US", "European", "NonEuropean",
5170 "DEFAULT");
5171 else if (TailMatches("search_path", "TO|="))
5172 {
5173 /* Here, we want to allow pg_catalog, so use narrower exclusion */
5174 COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_schemas
5175 " AND nspname NOT LIKE E'pg\\\\_toast%%'"
5176 " AND nspname NOT LIKE E'pg\\\\_temp%%'",
5177 "DEFAULT");
5178 }
5179 else if (TailMatches("TimeZone", "TO|="))
5180 COMPLETE_WITH_TIMEZONE_NAME();
5181 else
5182 {
5183 /* generic, type based, GUC support */
5184 char *guctype = get_guctype(prev2_wd);
5185
5186 /*
5187 * Note: if we don't recognize the GUC name, it's important to not
5188 * offer any completions, as most likely we've misinterpreted the
5189 * context and this isn't a GUC-setting command at all.
5190 */
5191 if (guctype)
5192 {
5193 if (strcmp(guctype, "enum") == 0)
5194 {
5195 set_completion_reference_verbatim(prev2_wd);
5196 COMPLETE_WITH_QUERY_PLUS(Query_for_values_of_enum_GUC,
5197 "DEFAULT");
5198 }
5199 else if (strcmp(guctype, "bool") == 0)
5200 COMPLETE_WITH("on", "off", "true", "false", "yes", "no",
5201 "1", "0", "DEFAULT");
5202 else
5203 COMPLETE_WITH("DEFAULT");
5204
5205 free(guctype);
5206 }
5207 }
5208 }
5209
5210/* START TRANSACTION */
5211 else if (Matches("START"))
5212 COMPLETE_WITH("TRANSACTION");
5213
5214/* TABLE, but not TABLE embedded in other commands */
5215 else if (Matches("TABLE"))
5216 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_selectables);
5217
5218/* TABLESAMPLE */
5219 else if (TailMatches("TABLESAMPLE"))
5220 COMPLETE_WITH_QUERY(Query_for_list_of_tablesample_methods);
5221 else if (TailMatches("TABLESAMPLE", MatchAny))
5222 COMPLETE_WITH("(");
5223
5224/* TRUNCATE */
5225 else if (Matches("TRUNCATE"))
5226 COMPLETE_WITH_SCHEMA_QUERY_PLUS(Query_for_list_of_truncatables,
5227 "TABLE", "ONLY");
5228 else if (Matches("TRUNCATE", "TABLE"))
5229 COMPLETE_WITH_SCHEMA_QUERY_PLUS(Query_for_list_of_truncatables,
5230 "ONLY");
5231 else if (Matches("TRUNCATE", MatchAnyN, "ONLY"))
5232 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_truncatables);
5233 else if (Matches("TRUNCATE", MatchAny) ||
5234 Matches("TRUNCATE", "TABLE|ONLY", MatchAny) ||
5235 Matches("TRUNCATE", "TABLE", "ONLY", MatchAny))
5236 COMPLETE_WITH("RESTART IDENTITY", "CONTINUE IDENTITY", "CASCADE", "RESTRICT");
5237 else if (Matches("TRUNCATE", MatchAnyN, "IDENTITY"))
5238 COMPLETE_WITH("CASCADE", "RESTRICT");
5239
5240/* UNLISTEN */
5241 else if (Matches("UNLISTEN"))
5242 COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_channels, "*");
5243
5244/* UPDATE --- can be inside EXPLAIN, RULE, etc */
5245 /* If prev. word is UPDATE suggest a list of tables */
5246 else if (TailMatches("UPDATE"))
5247 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_updatables);
5248 /* Complete UPDATE <table> with "SET" */
5249 else if (TailMatches("UPDATE", MatchAny))
5250 COMPLETE_WITH("SET");
5251 /* Complete UPDATE <table> SET with list of attributes */
5252 else if (TailMatches("UPDATE", MatchAny, "SET"))
5253 COMPLETE_WITH_ATTR(prev2_wd);
5254 /* UPDATE <table> SET <attr> = */
5255 else if (TailMatches("UPDATE", MatchAny, "SET", MatchAnyExcept("*=")))
5256 COMPLETE_WITH("=");
5257
5258/* USER MAPPING */
5259 else if (Matches("ALTER|CREATE|DROP", "USER", "MAPPING"))
5260 COMPLETE_WITH("FOR");
5261 else if (Matches("CREATE", "USER", "MAPPING", "FOR"))
5262 COMPLETE_WITH_QUERY_PLUS(Query_for_list_of_roles,
5263 "CURRENT_ROLE",
5264 "CURRENT_USER",
5265 "PUBLIC",
5266 "USER");
5267 else if (Matches("ALTER|DROP", "USER", "MAPPING", "FOR"))
5268 COMPLETE_WITH_QUERY(Query_for_list_of_user_mappings);
5269 else if (Matches("CREATE|ALTER|DROP", "USER", "MAPPING", "FOR", MatchAny))
5270 COMPLETE_WITH("SERVER");
5271 else if (Matches("CREATE|ALTER", "USER", "MAPPING", "FOR", MatchAny, "SERVER", MatchAny))
5272 COMPLETE_WITH("OPTIONS");
5273
5274/*
5275 * VACUUM [ ( option [, ...] ) ] [ [ ONLY ] table_and_columns [, ...] ]
5276 * VACUUM [ FULL ] [ FREEZE ] [ VERBOSE ] [ ANALYZE ] [ [ ONLY ] table_and_columns [, ...] ]
5277 */
5278 else if (Matches("VACUUM"))
5279 COMPLETE_WITH_SCHEMA_QUERY_PLUS(Query_for_list_of_vacuumables,
5280 "(",
5281 "FULL",
5282 "FREEZE",
5283 "VERBOSE",
5284 "ANALYZE",
5285 "ONLY");
5286 else if (Matches("VACUUM", "FULL"))
5287 COMPLETE_WITH_SCHEMA_QUERY_PLUS(Query_for_list_of_vacuumables,
5288 "FREEZE",
5289 "VERBOSE",
5290 "ANALYZE",
5291 "ONLY");
5292 else if (Matches("VACUUM", MatchAnyN, "FREEZE"))
5293 COMPLETE_WITH_SCHEMA_QUERY_PLUS(Query_for_list_of_vacuumables,
5294 "VERBOSE",
5295 "ANALYZE",
5296 "ONLY");
5297 else if (Matches("VACUUM", MatchAnyN, "VERBOSE"))
5298 COMPLETE_WITH_SCHEMA_QUERY_PLUS(Query_for_list_of_vacuumables,
5299 "ANALYZE",
5300 "ONLY");
5301 else if (Matches("VACUUM", MatchAnyN, "ANALYZE"))
5302 COMPLETE_WITH_SCHEMA_QUERY_PLUS(Query_for_list_of_vacuumables,
5303 "ONLY");
5304 else if (HeadMatches("VACUUM", "(*") &&
5305 !HeadMatches("VACUUM", "(*)"))
5306 {
5307 /*
5308 * This fires if we're in an unfinished parenthesized option list.
5309 * get_previous_words treats a completed parenthesized option list as
5310 * one word, so the above test is correct.
5311 */
5312 if (ends_with(prev_wd, '(') || ends_with(prev_wd, ','))
5313 COMPLETE_WITH("FULL", "FREEZE", "ANALYZE", "VERBOSE",
5314 "DISABLE_PAGE_SKIPPING", "SKIP_LOCKED",
5315 "INDEX_CLEANUP", "PROCESS_MAIN", "PROCESS_TOAST",
5316 "TRUNCATE", "PARALLEL", "SKIP_DATABASE_STATS",
5317 "ONLY_DATABASE_STATS", "BUFFER_USAGE_LIMIT");
5318 else if (TailMatches("FULL|FREEZE|ANALYZE|VERBOSE|DISABLE_PAGE_SKIPPING|SKIP_LOCKED|PROCESS_MAIN|PROCESS_TOAST|TRUNCATE|SKIP_DATABASE_STATS|ONLY_DATABASE_STATS"))
5319 COMPLETE_WITH("ON", "OFF");
5320 else if (TailMatches("INDEX_CLEANUP"))
5321 COMPLETE_WITH("AUTO", "ON", "OFF");
5322 }
5323 else if (Matches("VACUUM", MatchAnyN, "("))
5324 /* "VACUUM (" should be caught above, so assume we want columns */
5325 COMPLETE_WITH_ATTR(prev2_wd);
5326 else if (HeadMatches("VACUUM"))
5327 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_vacuumables);
5328
5329/*
5330 * WAIT FOR LSN '<lsn>' [ WITH ( option [, ...] ) ]
5331 * where option can be:
5332 * TIMEOUT '<timeout>'
5333 * NO_THROW
5334 */
5335 else if (Matches("WAIT"))
5336 COMPLETE_WITH("FOR");
5337 else if (Matches("WAIT", "FOR"))
5338 COMPLETE_WITH("LSN");
5339 else if (Matches("WAIT", "FOR", "LSN"))
5340 /* No completion for LSN value - user must provide manually */
5341 ;
5342 else if (Matches("WAIT", "FOR", "LSN", MatchAny))
5343 COMPLETE_WITH("WITH");
5344 else if (Matches("WAIT", "FOR", "LSN", MatchAny, "WITH"))
5345 COMPLETE_WITH("(");
5346 else if (HeadMatches("WAIT", "FOR", "LSN", MatchAny, "WITH", "(*") &&
5347 !HeadMatches("WAIT", "FOR", "LSN", MatchAny, "WITH", "(*)"))
5348 {
5349 /*
5350 * This fires if we're in an unfinished parenthesized option list.
5351 * get_previous_words treats a completed parenthesized option list as
5352 * one word, so the above test is correct.
5353 */
5354 if (ends_with(prev_wd, '(') || ends_with(prev_wd, ','))
5355 COMPLETE_WITH("timeout", "no_throw");
5356
5357 /*
5358 * timeout takes a string value, no_throw takes no value. We don't
5359 * offer completions for these values.
5360 */
5361 }
5362
5363/* WITH [RECURSIVE] */
5364
5365 /*
5366 * Only match when WITH is the first word, as WITH may appear in many
5367 * other contexts.
5368 */
5369 else if (Matches("WITH"))
5370 COMPLETE_WITH("RECURSIVE");
5371
5372/* WHERE */
5373 /* Simple case of the word before the where being the table name */
5374 else if (TailMatches(MatchAny, "WHERE"))
5375 COMPLETE_WITH_ATTR(prev2_wd);
5376
5377/* ... FROM ... */
5378/* TODO: also include SRF ? */
5379 else if (TailMatches("FROM") && !Matches("COPY|\\copy", MatchAny, "FROM"))
5380 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_selectables);
5381
5382/* ... JOIN ... */
5383 else if (TailMatches("JOIN"))
5384 COMPLETE_WITH_SCHEMA_QUERY_PLUS(Query_for_list_of_selectables, "LATERAL");
5385 else if (TailMatches("JOIN", MatchAny) && !TailMatches("CROSS|NATURAL", "JOIN", MatchAny))
5386 COMPLETE_WITH("ON", "USING (");
5387 else if (TailMatches("JOIN", MatchAny, MatchAny) &&
5388 !TailMatches("CROSS|NATURAL", "JOIN", MatchAny, MatchAny) && !TailMatches("ON|USING"))
5389 COMPLETE_WITH("ON", "USING (");
5390 else if (TailMatches("JOIN", "LATERAL", MatchAny, MatchAny) &&
5391 !TailMatches("CROSS|NATURAL", "JOIN", "LATERAL", MatchAny, MatchAny) && !TailMatches("ON|USING"))
5392 COMPLETE_WITH("ON", "USING (");
5393 else if (TailMatches("JOIN", MatchAny, "USING") ||
5394 TailMatches("JOIN", MatchAny, MatchAny, "USING") ||
5395 TailMatches("JOIN", "LATERAL", MatchAny, MatchAny, "USING"))
5396 COMPLETE_WITH("(");
5397 else if (TailMatches("JOIN", MatchAny, "USING", "("))
5398 COMPLETE_WITH_ATTR(prev3_wd);
5399 else if (TailMatches("JOIN", MatchAny, MatchAny, "USING", "("))
5400 COMPLETE_WITH_ATTR(prev4_wd);
5401
5402/* ... AT [ LOCAL | TIME ZONE ] ... */
5403 else if (TailMatches("AT"))
5404 COMPLETE_WITH("LOCAL", "TIME ZONE");
5405 else if (TailMatches("AT", "TIME", "ZONE"))
5406 COMPLETE_WITH_TIMEZONE_NAME();
5407
5408/* Backslash commands */
5409/* TODO: \dc \dd \dl */
5410 else if (TailMatchesCS("\\?"))
5411 COMPLETE_WITH_CS("commands", "options", "variables");
5412 else if (TailMatchesCS("\\connect|\\c"))
5413 {
5415 COMPLETE_WITH_QUERY(Query_for_list_of_databases);
5416 }
5417 else if (TailMatchesCS("\\connect|\\c", MatchAny))
5418 {
5419 if (!recognized_connection_string(prev_wd))
5420 COMPLETE_WITH_QUERY(Query_for_list_of_roles);
5421 }
5422 else if (TailMatchesCS("\\da*"))
5423 COMPLETE_WITH_VERSIONED_SCHEMA_QUERY(Query_for_list_of_aggregates);
5424 else if (TailMatchesCS("\\dAc*", MatchAny) ||
5425 TailMatchesCS("\\dAf*", MatchAny))
5426 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_datatypes);
5427 else if (TailMatchesCS("\\dAo*", MatchAny) ||
5428 TailMatchesCS("\\dAp*", MatchAny))
5429 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_operator_families);
5430 else if (TailMatchesCS("\\dA*"))
5431 COMPLETE_WITH_QUERY(Query_for_list_of_access_methods);
5432 else if (TailMatchesCS("\\db*"))
5433 COMPLETE_WITH_QUERY(Query_for_list_of_tablespaces);
5434 else if (TailMatchesCS("\\dconfig*"))
5435 COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_show_vars);
5436 else if (TailMatchesCS("\\dD*"))
5437 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_domains);
5438 else if (TailMatchesCS("\\des*"))
5439 COMPLETE_WITH_QUERY(Query_for_list_of_servers);
5440 else if (TailMatchesCS("\\deu*"))
5441 COMPLETE_WITH_QUERY(Query_for_list_of_user_mappings);
5442 else if (TailMatchesCS("\\dew*"))
5443 COMPLETE_WITH_QUERY(Query_for_list_of_fdws);
5444 else if (TailMatchesCS("\\df*"))
5445 COMPLETE_WITH_VERSIONED_SCHEMA_QUERY(Query_for_list_of_functions);
5446 else if (HeadMatchesCS("\\df*"))
5447 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_datatypes);
5448
5449 else if (TailMatchesCS("\\dFd*"))
5450 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_ts_dictionaries);
5451 else if (TailMatchesCS("\\dFp*"))
5452 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_ts_parsers);
5453 else if (TailMatchesCS("\\dFt*"))
5454 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_ts_templates);
5455 /* must be at end of \dF alternatives: */
5456 else if (TailMatchesCS("\\dF*"))
5457 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_ts_configurations);
5458
5459 else if (TailMatchesCS("\\di*"))
5460 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_indexes);
5461 else if (TailMatchesCS("\\dL*"))
5462 COMPLETE_WITH_QUERY(Query_for_list_of_languages);
5463 else if (TailMatchesCS("\\dn*"))
5464 COMPLETE_WITH_QUERY(Query_for_list_of_schemas);
5465 /* no support for completing operators, but we can complete types: */
5466 else if (HeadMatchesCS("\\do*", MatchAny))
5467 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_datatypes);
5468 else if (TailMatchesCS("\\dp") || TailMatchesCS("\\z"))
5469 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_grantables);
5470 else if (TailMatchesCS("\\dPi*"))
5471 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_partitioned_indexes);
5472 else if (TailMatchesCS("\\dPt*"))
5473 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_partitioned_tables);
5474 else if (TailMatchesCS("\\dP*"))
5475 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_partitioned_relations);
5476 else if (TailMatchesCS("\\dRp*"))
5477 COMPLETE_WITH_VERSIONED_QUERY(Query_for_list_of_publications);
5478 else if (TailMatchesCS("\\dRs*"))
5479 COMPLETE_WITH_VERSIONED_QUERY(Query_for_list_of_subscriptions);
5480 else if (TailMatchesCS("\\ds*"))
5481 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_sequences);
5482 else if (TailMatchesCS("\\dt*"))
5483 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables);
5484 else if (TailMatchesCS("\\dT*"))
5485 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_datatypes);
5486 else if (TailMatchesCS("\\du*") ||
5487 TailMatchesCS("\\dg*") ||
5488 TailMatchesCS("\\drg*"))
5489 COMPLETE_WITH_QUERY(Query_for_list_of_roles);
5490 else if (TailMatchesCS("\\dv*"))
5491 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_views);
5492 else if (TailMatchesCS("\\dx*"))
5493 COMPLETE_WITH_QUERY(Query_for_list_of_extensions);
5494 else if (TailMatchesCS("\\dX*"))
5495 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_statistics);
5496 else if (TailMatchesCS("\\dm*"))
5497 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_matviews);
5498 else if (TailMatchesCS("\\dE*"))
5499 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_foreign_tables);
5500 else if (TailMatchesCS("\\dy*"))
5501 COMPLETE_WITH_QUERY(Query_for_list_of_event_triggers);
5502
5503 /* must be at end of \d alternatives: */
5504 else if (TailMatchesCS("\\d*"))
5505 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_relations);
5506
5507 else if (TailMatchesCS("\\ef"))
5508 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_routines);
5509 else if (TailMatchesCS("\\ev"))
5510 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_views);
5511
5512 else if (TailMatchesCS("\\encoding"))
5513 COMPLETE_WITH_QUERY_VERBATIM(Query_for_list_of_encodings);
5514 else if (TailMatchesCS("\\h|\\help"))
5515 COMPLETE_WITH_LIST(sql_commands);
5516 else if (TailMatchesCS("\\h|\\help", MatchAny))
5517 {
5518 if (TailMatches("DROP"))
5519 COMPLETE_WITH_GENERATOR(drop_command_generator);
5520 else if (TailMatches("ALTER"))
5521 COMPLETE_WITH_GENERATOR(alter_command_generator);
5522
5523 /*
5524 * CREATE is recognized by tail match elsewhere, so doesn't need to be
5525 * repeated here
5526 */
5527 }
5528 else if (TailMatchesCS("\\h|\\help", MatchAny, MatchAny))
5529 {
5530 if (TailMatches("CREATE|DROP", "ACCESS"))
5531 COMPLETE_WITH("METHOD");
5532 else if (TailMatches("ALTER", "DEFAULT"))
5533 COMPLETE_WITH("PRIVILEGES");
5534 else if (TailMatches("CREATE|ALTER|DROP", "EVENT"))
5535 COMPLETE_WITH("TRIGGER");
5536 else if (TailMatches("CREATE|ALTER|DROP", "FOREIGN"))
5537 COMPLETE_WITH("DATA WRAPPER", "TABLE");
5538 else if (TailMatches("ALTER", "LARGE"))
5539 COMPLETE_WITH("OBJECT");
5540 else if (TailMatches("CREATE|ALTER|DROP", "MATERIALIZED"))
5541 COMPLETE_WITH("VIEW");
5542 else if (TailMatches("CREATE|ALTER|DROP", "TEXT"))
5543 COMPLETE_WITH("SEARCH");
5544 else if (TailMatches("CREATE|ALTER|DROP", "USER"))
5545 COMPLETE_WITH("MAPPING FOR");
5546 }
5547 else if (TailMatchesCS("\\h|\\help", MatchAny, MatchAny, MatchAny))
5548 {
5549 if (TailMatches("CREATE|ALTER|DROP", "FOREIGN", "DATA"))
5550 COMPLETE_WITH("WRAPPER");
5551 else if (TailMatches("CREATE|ALTER|DROP", "TEXT", "SEARCH"))
5552 COMPLETE_WITH("CONFIGURATION", "DICTIONARY", "PARSER", "TEMPLATE");
5553 else if (TailMatches("CREATE|ALTER|DROP", "USER", "MAPPING"))
5554 COMPLETE_WITH("FOR");
5555 }
5556 else if (TailMatchesCS("\\l*") && !TailMatchesCS("\\lo*"))
5557 COMPLETE_WITH_QUERY(Query_for_list_of_databases);
5558 else if (TailMatchesCS("\\password"))
5559 COMPLETE_WITH_QUERY(Query_for_list_of_roles);
5560 else if (TailMatchesCS("\\pset"))
5561 COMPLETE_WITH_CS("border", "columns", "csv_fieldsep",
5562 "display_false", "display_true", "expanded",
5563 "fieldsep", "fieldsep_zero", "footer", "format",
5564 "linestyle", "null", "numericlocale",
5565 "pager", "pager_min_lines",
5566 "recordsep", "recordsep_zero",
5567 "tableattr", "title", "tuples_only",
5568 "unicode_border_linestyle",
5569 "unicode_column_linestyle",
5570 "unicode_header_linestyle",
5571 "xheader_width");
5572 else if (TailMatchesCS("\\pset", MatchAny))
5573 {
5574 if (TailMatchesCS("format"))
5575 COMPLETE_WITH_CS("aligned", "asciidoc", "csv", "html", "latex",
5576 "latex-longtable", "troff-ms", "unaligned",
5577 "wrapped");
5578 else if (TailMatchesCS("xheader_width"))
5579 COMPLETE_WITH_CS("full", "column", "page");
5580 else if (TailMatchesCS("linestyle"))
5581 COMPLETE_WITH_CS("ascii", "old-ascii", "unicode");
5582 else if (TailMatchesCS("pager"))
5583 COMPLETE_WITH_CS("on", "off", "always");
5584 else if (TailMatchesCS("unicode_border_linestyle|"
5585 "unicode_column_linestyle|"
5586 "unicode_header_linestyle"))
5587 COMPLETE_WITH_CS("single", "double");
5588 }
5589 else if (TailMatchesCS("\\unset"))
5590 matches = complete_from_variables(text, "", "", true);
5591 else if (TailMatchesCS("\\set"))
5592 matches = complete_from_variables(text, "", "", false);
5593 else if (TailMatchesCS("\\set", MatchAny))
5594 {
5595 if (TailMatchesCS("AUTOCOMMIT|ON_ERROR_STOP|QUIET|SHOW_ALL_RESULTS|"
5596 "SINGLELINE|SINGLESTEP"))
5597 COMPLETE_WITH_CS("on", "off");
5598 else if (TailMatchesCS("COMP_KEYWORD_CASE"))
5599 COMPLETE_WITH_CS("lower", "upper",
5600 "preserve-lower", "preserve-upper");
5601 else if (TailMatchesCS("ECHO"))
5602 COMPLETE_WITH_CS("errors", "queries", "all", "none");
5603 else if (TailMatchesCS("ECHO_HIDDEN"))
5604 COMPLETE_WITH_CS("noexec", "off", "on");
5605 else if (TailMatchesCS("HISTCONTROL"))
5606 COMPLETE_WITH_CS("ignorespace", "ignoredups",
5607 "ignoreboth", "none");
5608 else if (TailMatchesCS("ON_ERROR_ROLLBACK"))
5609 COMPLETE_WITH_CS("on", "off", "interactive");
5610 else if (TailMatchesCS("SHOW_CONTEXT"))
5611 COMPLETE_WITH_CS("never", "errors", "always");
5612 else if (TailMatchesCS("VERBOSITY"))
5613 COMPLETE_WITH_CS("default", "verbose", "terse", "sqlstate");
5614 }
5615 else if (TailMatchesCS("\\sf*"))
5616 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_routines);
5617 else if (TailMatchesCS("\\sv*"))
5618 COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_views);
5619 else if (TailMatchesCS("\\cd|\\e|\\edit|\\g|\\gx|\\i|\\include|"
5620 "\\ir|\\include_relative|\\o|\\out|"
5621 "\\s|\\w|\\write|\\lo_import") ||
5622 TailMatchesCS("\\lo_export", MatchAny))
5623 COMPLETE_WITH_FILES("\\", false);
5624
5625 /* gen_tabcomplete.pl ends special processing here */
5626 /* END GEN_TABCOMPLETE */
5627
5628 return matches;
5629}
5630
5631
5632/*
5633 * GENERATOR FUNCTIONS
5634 *
5635 * These functions do all the actual work of completing the input. They get
5636 * passed the text so far and the count how many times they have been called
5637 * so far with the same text.
5638 * If you read the above carefully, you'll see that these don't get called
5639 * directly but through the readline interface.
5640 * The return value is expected to be the full completion of the text, going
5641 * through a list each time, or NULL if there are no more matches. The string
5642 * will be free()'d by readline, so you must run it through strdup() or
5643 * something of that sort.
5644 */
5645
5646/*
5647 * Common routine for create_command_generator and drop_command_generator.
5648 * Entries that have 'excluded' flags are not returned.
5649 */
5650static char *
5651create_or_drop_command_generator(const char *text, int state, bits32 excluded)
5652{
5653 static int list_index,
5654 string_length;
5655 const char *name;
5656
5657 /* If this is the first time for this completion, init some values */
5658 if (state == 0)
5659 {
5660 list_index = 0;
5661 string_length = strlen(text);
5662 }
5663
5664 /* find something that matches */
5665 while ((name = words_after_create[list_index++].name))
5666 {
5667 if ((pg_strncasecmp(name, text, string_length) == 0) &&
5668 !(words_after_create[list_index - 1].flags & excluded))
5669 return pg_strdup_keyword_case(name, text);
5670 }
5671 /* if nothing matches, return NULL */
5672 return NULL;
5673}
5674
5675/*
5676 * This one gives you one from a list of things you can put after CREATE
5677 * as defined above.
5678 */
5679static char *
5680create_command_generator(const char *text, int state)
5681{
5682 return create_or_drop_command_generator(text, state, THING_NO_CREATE);
5683}
5684
5685/*
5686 * This function gives you a list of things you can put after a DROP command.
5687 */
5688static char *
5689drop_command_generator(const char *text, int state)
5690{
5691 return create_or_drop_command_generator(text, state, THING_NO_DROP);
5692}
5693
5694/*
5695 * This function gives you a list of things you can put after an ALTER command.
5696 */
5697static char *
5698alter_command_generator(const char *text, int state)
5699{
5700 return create_or_drop_command_generator(text, state, THING_NO_ALTER);
5701}
5702
5703/*
5704 * These functions generate lists using server queries.
5705 * They are all wrappers for _complete_from_query.
5706 */
5707
5708static char *
5709complete_from_query(const char *text, int state)
5710{
5711 /* query is assumed to work for any server version */
5712 return _complete_from_query(completion_charp, NULL, completion_charpp,
5713 completion_verbatim, text, state);
5714}
5715
5716static char *
5717complete_from_versioned_query(const char *text, int state)
5718{
5719 const VersionedQuery *vquery = completion_vquery;
5720
5721 /* Find appropriate array element */
5722 while (pset.sversion < vquery->min_server_version)
5723 vquery++;
5724 /* Fail completion if server is too old */
5725 if (vquery->query == NULL)
5726 return NULL;
5727
5728 return _complete_from_query(vquery->query, NULL, completion_charpp,
5729 completion_verbatim, text, state);
5730}
5731
5732static char *
5733complete_from_schema_query(const char *text, int state)
5734{
5735 /* query is assumed to work for any server version */
5736 return _complete_from_query(NULL, completion_squery, completion_charpp,
5737 completion_verbatim, text, state);
5738}
5739
5740static char *
5741complete_from_versioned_schema_query(const char *text, int state)
5742{
5743 const SchemaQuery *squery = completion_squery;
5744
5745 /* Find appropriate array element */
5746 while (pset.sversion < squery->min_server_version)
5747 squery++;
5748 /* Fail completion if server is too old */
5749 if (squery->catname == NULL)
5750 return NULL;
5751
5752 return _complete_from_query(NULL, squery, completion_charpp,
5753 completion_verbatim, text, state);
5754}
5755
5756
5757/*
5758 * This creates a list of matching things, according to a query described by
5759 * the initial arguments. The caller has already done any work needed to
5760 * select the appropriate query for the server's version.
5761 *
5762 * The query can be one of two kinds:
5763 *
5764 * 1. A simple query, which must contain a restriction clause of the form
5765 * output LIKE '%s'
5766 * where "output" is the same string that the query returns. The %s
5767 * will be replaced by a LIKE pattern to match the already-typed text.
5768 * There can be a second '%s', which will be replaced by a suitably-escaped
5769 * version of the string provided in completion_ref_object. If there is a
5770 * third '%s', it will be replaced by a suitably-escaped version of the string
5771 * provided in completion_ref_schema. Those strings should be set up
5772 * by calling set_completion_reference or set_completion_reference_verbatim.
5773 * Simple queries should return a single column of matches. If "verbatim"
5774 * is true, the matches are returned as-is; otherwise, they are taken to
5775 * be SQL identifiers and quoted if necessary.
5776 *
5777 * 2. A schema query used for completion of both schema and relation names.
5778 * This is represented by a SchemaQuery object; see that typedef for details.
5779 *
5780 * See top of file for examples of both kinds of query.
5781 *
5782 * In addition to the query itself, we accept a null-terminated array of
5783 * literal keywords, which will be returned if they match the input-so-far
5784 * (case insensitively). (These are in addition to keywords specified
5785 * within the schema_query, if any.)
5786 *
5787 * If "verbatim" is true, then we use the given text as-is to match the
5788 * query results; otherwise we parse it as a possibly-qualified identifier,
5789 * and reconstruct suitable quoting afterward.
5790 *
5791 * "text" and "state" are supplied by Readline. "text" is the word we are
5792 * trying to complete. "state" is zero on first call, nonzero later.
5793 *
5794 * readline will call this repeatedly with the same text and varying
5795 * state. On each call, we are supposed to return a malloc'd string
5796 * that is a candidate completion. Return NULL when done.
5797 */
5798static char *
5799_complete_from_query(const char *simple_query,
5800 const SchemaQuery *schema_query,
5801 const char *const *keywords,
5802 bool verbatim,
5803 const char *text, int state)
5804{
5805 static int list_index,
5806 num_schema_only,
5807 num_query_other,
5808 num_keywords;
5809 static PGresult *result = NULL;
5810 static bool non_empty_object;
5811 static bool schemaquoted;
5812 static bool objectquoted;
5813
5814 /*
5815 * If this is the first time for this completion, we fetch a list of our
5816 * "things" from the backend.
5817 */
5818 if (state == 0)
5819 {
5820 PQExpBufferData query_buffer;
5821 char *schemaname;
5822 char *objectname;
5823 char *e_object_like;
5824 char *e_schemaname;
5825 char *e_ref_object;
5826 char *e_ref_schema;
5827
5828 /* Reset static state, ensuring no memory leaks */
5829 list_index = 0;
5830 num_schema_only = 0;
5831 num_query_other = 0;
5832 num_keywords = 0;
5833 PQclear(result);
5834 result = NULL;
5835
5836 /* Parse text, splitting into schema and object name if needed */
5837 if (verbatim)
5838 {
5839 objectname = pg_strdup(text);
5840 schemaname = NULL;
5841 }
5842 else
5843 {
5844 parse_identifier(text,
5845 &schemaname, &objectname,
5846 &schemaquoted, &objectquoted);
5847 }
5848
5849 /* Remember whether the user has typed anything in the object part */
5850 non_empty_object = (*objectname != '\0');
5851
5852 /*
5853 * Convert objectname to a LIKE prefix pattern (e.g. 'foo%'), and set
5854 * up suitably-escaped copies of all the strings we need.
5855 */
5856 e_object_like = make_like_pattern(objectname);
5857
5858 if (schemaname)
5859 e_schemaname = escape_string(schemaname);
5860 else
5861 e_schemaname = NULL;
5862
5863 if (completion_ref_object)
5864 e_ref_object = escape_string(completion_ref_object);
5865 else
5866 e_ref_object = NULL;
5867
5868 if (completion_ref_schema)
5869 e_ref_schema = escape_string(completion_ref_schema);
5870 else
5871 e_ref_schema = NULL;
5872
5873 initPQExpBuffer(&query_buffer);
5874
5875 if (schema_query)
5876 {
5877 Assert(simple_query == NULL);
5878
5879 /*
5880 * We issue different queries depending on whether the input is
5881 * already qualified or not. schema_query gives us the pieces to
5882 * assemble.
5883 */
5884 if (schemaname == NULL || schema_query->namespace == NULL)
5885 {
5886 /* Get unqualified names matching the input-so-far */
5887 appendPQExpBufferStr(&query_buffer, "SELECT ");
5888 if (schema_query->use_distinct)
5889 appendPQExpBufferStr(&query_buffer, "DISTINCT ");
5890 appendPQExpBuffer(&query_buffer,
5891 "%s, NULL::pg_catalog.text FROM %s",
5892 schema_query->result,
5893 schema_query->catname);
5894 if (schema_query->refnamespace && completion_ref_schema)
5895 appendPQExpBufferStr(&query_buffer,
5896 ", pg_catalog.pg_namespace nr");
5897 appendPQExpBufferStr(&query_buffer, " WHERE ");
5898 if (schema_query->selcondition)
5899 appendPQExpBuffer(&query_buffer, "%s AND ",
5900 schema_query->selcondition);
5901 appendPQExpBuffer(&query_buffer, "(%s) LIKE '%s'",
5902 schema_query->result,
5903 e_object_like);
5904 if (schema_query->viscondition)
5905 appendPQExpBuffer(&query_buffer, " AND %s",
5906 schema_query->viscondition);
5907 if (schema_query->refname)
5908 {
5909 Assert(completion_ref_object);
5910 appendPQExpBuffer(&query_buffer, " AND %s = '%s'",
5911 schema_query->refname, e_ref_object);
5912 if (schema_query->refnamespace && completion_ref_schema)
5913 appendPQExpBuffer(&query_buffer,
5914 " AND %s = nr.oid AND nr.nspname = '%s'",
5915 schema_query->refnamespace,
5916 e_ref_schema);
5917 else if (schema_query->refviscondition)
5918 appendPQExpBuffer(&query_buffer,
5919 " AND %s",
5920 schema_query->refviscondition);
5921 }
5922
5923 /*
5924 * When fetching relation names, suppress system catalogs
5925 * unless the input-so-far begins with "pg_". This is a
5926 * compromise between not offering system catalogs for
5927 * completion at all, and having them swamp the result when
5928 * the input is just "p".
5929 */
5930 if (strcmp(schema_query->catname,
5931 "pg_catalog.pg_class c") == 0 &&
5932 strncmp(objectname, "pg_", 3) != 0)
5933 {
5934 appendPQExpBufferStr(&query_buffer,
5935 " AND c.relnamespace <> (SELECT oid FROM"
5936 " pg_catalog.pg_namespace WHERE nspname = 'pg_catalog')");
5937 }
5938
5939 /*
5940 * If the target object type can be schema-qualified, add in
5941 * schema names matching the input-so-far.
5942 */
5943 if (schema_query->namespace)
5944 {
5945 appendPQExpBuffer(&query_buffer, "\nUNION ALL\n"
5946 "SELECT NULL::pg_catalog.text, n.nspname "
5947 "FROM pg_catalog.pg_namespace n "
5948 "WHERE n.nspname LIKE '%s'",
5949 e_object_like);
5950
5951 /*
5952 * Likewise, suppress system schemas unless the
5953 * input-so-far begins with "pg_".
5954 */
5955 if (strncmp(objectname, "pg_", 3) != 0)
5956 appendPQExpBufferStr(&query_buffer,
5957 " AND n.nspname NOT LIKE E'pg\\\\_%'");
5958
5959 /*
5960 * Since we're matching these schema names to the object
5961 * name, handle their quoting using the object name's
5962 * quoting state.
5963 */
5964 schemaquoted = objectquoted;
5965 }
5966 }
5967 else
5968 {
5969 /* Input is qualified, so produce only qualified names */
5970 appendPQExpBufferStr(&query_buffer, "SELECT ");
5971 if (schema_query->use_distinct)
5972 appendPQExpBufferStr(&query_buffer, "DISTINCT ");
5973 appendPQExpBuffer(&query_buffer, "%s, n.nspname "
5974 "FROM %s, pg_catalog.pg_namespace n",
5975 schema_query->result,
5976 schema_query->catname);
5977 if (schema_query->refnamespace && completion_ref_schema)
5978 appendPQExpBufferStr(&query_buffer,
5979 ", pg_catalog.pg_namespace nr");
5980 appendPQExpBuffer(&query_buffer, " WHERE %s = n.oid AND ",
5981 schema_query->namespace);
5982 if (schema_query->selcondition)
5983 appendPQExpBuffer(&query_buffer, "%s AND ",
5984 schema_query->selcondition);
5985 appendPQExpBuffer(&query_buffer, "(%s) LIKE '%s' AND ",
5986 schema_query->result,
5987 e_object_like);
5988 appendPQExpBuffer(&query_buffer, "n.nspname = '%s'",
5989 e_schemaname);
5990 if (schema_query->refname)
5991 {
5992 Assert(completion_ref_object);
5993 appendPQExpBuffer(&query_buffer, " AND %s = '%s'",
5994 schema_query->refname, e_ref_object);
5995 if (schema_query->refnamespace && completion_ref_schema)
5996 appendPQExpBuffer(&query_buffer,
5997 " AND %s = nr.oid AND nr.nspname = '%s'",
5998 schema_query->refnamespace,
5999 e_ref_schema);
6000 else if (schema_query->refviscondition)
6001 appendPQExpBuffer(&query_buffer,
6002 " AND %s",
6003 schema_query->refviscondition);
6004 }
6005 }
6006 }
6007 else
6008 {
6009 Assert(simple_query);
6010 /* simple_query is an sprintf-style format string */
6011 appendPQExpBuffer(&query_buffer, simple_query,
6012 e_object_like,
6013 e_ref_object, e_ref_schema);
6014 }
6015
6016 /* Limit the number of records in the result */
6017 appendPQExpBuffer(&query_buffer, "\nLIMIT %d",
6018 completion_max_records);
6019
6020 /* Finally, we can issue the query */
6021 result = exec_query(query_buffer.data);
6022
6023 /* Clean up */
6024 termPQExpBuffer(&query_buffer);
6025 free(schemaname);
6026 free(objectname);
6027 free(e_object_like);
6028 free(e_schemaname);
6029 free(e_ref_object);
6030 free(e_ref_schema);
6031 }
6032
6033 /* Return the next result, if any, but not if the query failed */
6034 if (result && PQresultStatus(result) == PGRES_TUPLES_OK)
6035 {
6036 int nskip;
6037
6038 while (list_index < PQntuples(result))
6039 {
6040 const char *item = NULL;
6041 const char *nsp = NULL;
6042
6043 if (!PQgetisnull(result, list_index, 0))
6044 item = PQgetvalue(result, list_index, 0);
6045 if (PQnfields(result) > 1 &&
6046 !PQgetisnull(result, list_index, 1))
6047 nsp = PQgetvalue(result, list_index, 1);
6048 list_index++;
6049
6050 /* In verbatim mode, we return all the items as-is */
6051 if (verbatim)
6052 {
6053 num_query_other++;
6054 return pg_strdup(item);
6055 }
6056
6057 /*
6058 * In normal mode, a name requiring quoting will be returned only
6059 * if the input was empty or quoted. Otherwise the user might see
6060 * completion inserting a quote she didn't type, which is
6061 * surprising. This restriction also dodges some odd behaviors of
6062 * some versions of readline/libedit.
6063 */
6064 if (non_empty_object)
6065 {
6066 if (item && !objectquoted && identifier_needs_quotes(item))
6067 continue;
6068 if (nsp && !schemaquoted && identifier_needs_quotes(nsp))
6069 continue;
6070 }
6071
6072 /* Count schema-only results for hack below */
6073 if (item == NULL && nsp != NULL)
6074 num_schema_only++;
6075 else
6076 num_query_other++;
6077
6078 return requote_identifier(nsp, item, schemaquoted, objectquoted);
6079 }
6080
6081 /*
6082 * When the query result is exhausted, check for hard-wired keywords.
6083 * These will only be returned if they match the input-so-far,
6084 * ignoring case.
6085 */
6086 nskip = list_index - PQntuples(result);
6087 if (schema_query && schema_query->keywords)
6088 {
6089 const char *const *itemp = schema_query->keywords;
6090
6091 while (*itemp)
6092 {
6093 const char *item = *itemp++;
6094
6095 if (nskip-- > 0)
6096 continue;
6097 list_index++;
6098 if (pg_strncasecmp(text, item, strlen(text)) == 0)
6099 {
6100 num_keywords++;
6101 return pg_strdup_keyword_case(item, text);
6102 }
6103 }
6104 }
6105 if (keywords)
6106 {
6107 const char *const *itemp = keywords;
6108
6109 while (*itemp)
6110 {
6111 const char *item = *itemp++;
6112
6113 if (nskip-- > 0)
6114 continue;
6115 list_index++;
6116 if (pg_strncasecmp(text, item, strlen(text)) == 0)
6117 {
6118 num_keywords++;
6119 return pg_strdup_keyword_case(item, text);
6120 }
6121 }
6122 }
6123 }
6124
6125 /*
6126 * Hack: if we returned only bare schema names, don't let Readline add a
6127 * space afterwards. Otherwise the schema will stop being part of the
6128 * completion subject text, which is not what we want.
6129 */
6130 if (num_schema_only > 0 && num_query_other == 0 && num_keywords == 0)
6131 rl_completion_append_character = '\0';
6132
6133 /* No more matches, so free the result structure and return null */
6134 PQclear(result);
6135 result = NULL;
6136 return NULL;
6137}
6138
6139
6140/*
6141 * Set up completion_ref_object and completion_ref_schema
6142 * by parsing the given word. These variables can then be
6143 * used in a query passed to _complete_from_query.
6144 */
6145static void
6146set_completion_reference(const char *word)
6147{
6148 bool schemaquoted,
6149 objectquoted;
6150
6151 parse_identifier(word,
6152 &completion_ref_schema, &completion_ref_object,
6153 &schemaquoted, &objectquoted);
6154}
6155
6156/*
6157 * Set up completion_ref_object when it should just be
6158 * the given word verbatim.
6159 */
6160static void
6161set_completion_reference_verbatim(const char *word)
6162{
6163 completion_ref_schema = NULL;
6164 completion_ref_object = pg_strdup(word);
6165}
6166
6167
6168/*
6169 * This function returns in order one of a fixed, NULL pointer terminated list
6170 * of strings (if matching). This can be used if there are only a fixed number
6171 * SQL words that can appear at certain spot.
6172 */
6173static char *
6174complete_from_list(const char *text, int state)
6175{
6176 static int string_length,
6177 list_index,
6178 matches;
6179 static bool casesensitive;
6180 const char *item;
6181
6182 /* need to have a list */
6183 Assert(completion_charpp != NULL);
6184
6185 /* Initialization */
6186 if (state == 0)
6187 {
6188 list_index = 0;
6189 string_length = strlen(text);
6190 casesensitive = completion_case_sensitive;
6191 matches = 0;
6192 }
6193
6194 while ((item = completion_charpp[list_index++]))
6195 {
6196 /* First pass is case sensitive */
6197 if (casesensitive && strncmp(text, item, string_length) == 0)
6198 {
6199 matches++;
6200 return pg_strdup(item);
6201 }
6202
6203 /* Second pass is case insensitive, don't bother counting matches */
6204 if (!casesensitive && pg_strncasecmp(text, item, string_length) == 0)
6205 {
6206 if (completion_case_sensitive)
6207 return pg_strdup(item);
6208 else
6209
6210 /*
6211 * If case insensitive matching was requested initially,
6212 * adjust the case according to setting.
6213 */
6214 return pg_strdup_keyword_case(item, text);
6215 }
6216 }
6217
6218 /*
6219 * No matches found. If we're not case insensitive already, lets switch to
6220 * being case insensitive and try again
6221 */
6222 if (casesensitive && matches == 0)
6223 {
6224 casesensitive = false;
6225 list_index = 0;
6226 state++;
6227 return complete_from_list(text, state);
6228 }
6229
6230 /* If no more matches, return null. */
6231 return NULL;
6232}
6233
6234
6235/*
6236 * This function returns one fixed string the first time even if it doesn't
6237 * match what's there, and nothing the second time. The string
6238 * to be used must be in completion_charp.
6239 *
6240 * If the given string is "", this has the effect of preventing readline
6241 * from doing any completion. (Without this, readline tries to do filename
6242 * completion which is seldom the right thing.)
6243 *
6244 * If the given string is not empty, readline will replace whatever the
6245 * user typed with that string. This behavior might be useful if it's
6246 * completely certain that we know what must appear at a certain spot,
6247 * so that it's okay to overwrite misspellings. In practice, given the
6248 * relatively lame parsing technology used in this file, the level of
6249 * certainty is seldom that high, so that you probably don't want to
6250 * use this. Use complete_from_list with a one-element list instead;
6251 * that won't try to auto-correct "misspellings".
6252 */
6253static char *
6254complete_from_const(const char *text, int state)
6255{
6256 Assert(completion_charp != NULL);
6257 if (state == 0)
6258 {
6259 if (completion_case_sensitive)
6260 return pg_strdup(completion_charp);
6261 else
6262
6263 /*
6264 * If case insensitive matching was requested initially, adjust
6265 * the case according to setting.
6266 */
6267 return pg_strdup_keyword_case(completion_charp, text);
6268 }
6269 else
6270 return NULL;
6271}
6272
6273
6274/*
6275 * This function appends the variable name with prefix and suffix to
6276 * the variable names array.
6277 */
6278static void
6279append_variable_names(char ***varnames, int *nvars,
6280 int *maxvars, const char *varname,
6281 const char *prefix, const char *suffix)
6282{
6283 if (*nvars >= *maxvars)
6284 {
6285 *maxvars *= 2;
6286 *varnames = (char **) pg_realloc(*varnames,
6287 ((*maxvars) + 1) * sizeof(char *));
6288 }
6289
6290 (*varnames)[(*nvars)++] = psprintf("%s%s%s", prefix, varname, suffix);
6291}
6292
6293
6294/*
6295 * This function supports completion with the name of a psql variable.
6296 * The variable names can be prefixed and suffixed with additional text
6297 * to support quoting usages. If need_value is true, only variables
6298 * that are currently set are included; otherwise, special variables
6299 * (those that have hooks) are included even if currently unset.
6300 */
6301static char **
6302complete_from_variables(const char *text, const char *prefix, const char *suffix,
6303 bool need_value)
6304{
6305 char **matches;
6306 char **varnames;
6307 int nvars = 0;
6308 int maxvars = 100;
6309 int i;
6310 struct _variable *ptr;
6311
6312 varnames = (char **) pg_malloc((maxvars + 1) * sizeof(char *));
6313
6314 for (ptr = pset.vars->next; ptr; ptr = ptr->next)
6315 {
6316 if (need_value && !(ptr->value))
6317 continue;
6318 append_variable_names(&varnames, &nvars, &maxvars, ptr->name,
6319 prefix, suffix);
6320 }
6321
6322 varnames[nvars] = NULL;
6323 COMPLETE_WITH_LIST_CS((const char *const *) varnames);
6324
6325 for (i = 0; i < nvars; i++)
6326 free(varnames[i]);
6327 free(varnames);
6328
6329 return matches;
6330}
6331
6332
6333/*
6334 * This function returns in order one of a fixed, NULL pointer terminated list
6335 * of string that matches file names or optionally specified list of keywords.
6336 *
6337 * If completion_charpp is set to a null-terminated array of literal keywords,
6338 * those keywords are added to the completion results alongside filenames if
6339 * they case-insensitively match the current input.
6340 */
6341static char *
6342complete_from_files(const char *text, int state)
6343{
6344 static int list_index;
6345 static bool files_done;
6346 const char *item;
6347
6348 /* Initialization */
6349 if (state == 0)
6350 {
6351 list_index = 0;
6352 files_done = false;
6353 }
6354
6355 if (!files_done)
6356 {
6357 char *result = _complete_from_files(text, state);
6358
6359 /* Return a filename that matches */
6360 if (result)
6361 return result;
6362
6363 /* There are no more matching files */
6364 files_done = true;
6365 }
6366
6367 if (!completion_charpp)
6368 return NULL;
6369
6370 /*
6371 * Check for hard-wired keywords. These will only be returned if they
6372 * match the input-so-far, ignoring case.
6373 */
6374 while ((item = completion_charpp[list_index++]))
6375 {
6376 if (pg_strncasecmp(text, item, strlen(text)) == 0)
6377 {
6378 completion_force_quote = false;
6379 return pg_strdup_keyword_case(item, text);
6380 }
6381 }
6382
6383 return NULL;
6384}
6385
6386/*
6387 * This function wraps rl_filename_completion_function() to strip quotes from
6388 * the input before searching for matches and to quote any matches for which
6389 * the consuming command will require it.
6390 *
6391 * Caller must set completion_charp to a zero- or one-character string
6392 * containing the escape character. This is necessary since \copy has no
6393 * escape character, but every other backslash command recognizes "\" as an
6394 * escape character.
6395 *
6396 * Caller must also set completion_force_quote to indicate whether to force
6397 * quotes around the result. (The SQL COPY command requires that.)
6398 */
6399static char *
6400_complete_from_files(const char *text, int state)
6401{
6402#ifdef USE_FILENAME_QUOTING_FUNCTIONS
6403
6404 /*
6405 * If we're using a version of Readline that supports filename quoting
6406 * hooks, rely on those, and invoke rl_filename_completion_function()
6407 * without messing with its arguments. Readline does stuff internally
6408 * that does not work well at all if we try to handle dequoting here.
6409 * Instead, Readline will call quote_file_name() and dequote_file_name()
6410 * (see below) at appropriate times.
6411 *
6412 * ... or at least, mostly it will. There are some paths involving
6413 * unmatched file names in which Readline never calls quote_file_name(),
6414 * and if left to its own devices it will incorrectly append a quote
6415 * anyway. Set rl_completion_suppress_quote to prevent that. If we do
6416 * get to quote_file_name(), we'll clear this again. (Yes, this seems
6417 * like it's working around Readline bugs.)
6418 */
6419#ifdef HAVE_RL_COMPLETION_SUPPRESS_QUOTE
6420 rl_completion_suppress_quote = 1;
6421#endif
6422
6423 /* If user typed a quote, force quoting (never remove user's quote) */
6424 if (*text == '\'')
6425 completion_force_quote = true;
6426
6427 return rl_filename_completion_function(text, state);
6428#else
6429
6430 /*
6431 * Otherwise, we have to do the best we can.
6432 */
6433 static const char *unquoted_text;
6434 char *unquoted_match;
6435 char *ret = NULL;
6436
6437 /* If user typed a quote, force quoting (never remove user's quote) */
6438 if (*text == '\'')
6439 completion_force_quote = true;
6440
6441 if (state == 0)
6442 {
6443 /* Initialization: stash the unquoted input. */
6444 unquoted_text = strtokx(text, "", NULL, "'", *completion_charp,
6445 false, true, pset.encoding);
6446 /* expect a NULL return for the empty string only */
6447 if (!unquoted_text)
6448 {
6449 Assert(*text == '\0');
6450 unquoted_text = text;
6451 }
6452 }
6453
6454 unquoted_match = rl_filename_completion_function(unquoted_text, state);
6455 if (unquoted_match)
6456 {
6457 struct stat statbuf;
6458 bool is_dir = (stat(unquoted_match, &statbuf) == 0 &&
6459 S_ISDIR(statbuf.st_mode) != 0);
6460
6461 /* Re-quote the result, if needed. */
6462 ret = quote_if_needed(unquoted_match, " \t\r\n\"`",
6463 '\'', *completion_charp,
6464 completion_force_quote,
6465 pset.encoding);
6466 if (ret)
6467 free(unquoted_match);
6468 else
6469 ret = unquoted_match;
6470
6471 /*
6472 * If it's a directory, replace trailing quote with a slash; this is
6473 * usually more convenient. (If we didn't quote, leave this to
6474 * libedit.)
6475 */
6476 if (*ret == '\'' && is_dir)
6477 {
6478 char *retend = ret + strlen(ret) - 1;
6479
6480 Assert(*retend == '\'');
6481 *retend = '/';
6482 /* Prevent libedit from adding a space, too */
6483 rl_completion_append_character = '\0';
6484 }
6485 }
6486
6487 return ret;
6488#endif /* USE_FILENAME_QUOTING_FUNCTIONS */
6489}
6490
6491
6492/* HELPER FUNCTIONS */
6493
6494
6495/*
6496 * Make a pg_strdup copy of s and convert the case according to
6497 * COMP_KEYWORD_CASE setting, using ref as the text that was already entered.
6498 */
6499static char *
6500pg_strdup_keyword_case(const char *s, const char *ref)
6501{
6502 char *ret,
6503 *p;
6504 unsigned char first = ref[0];
6505
6506 ret = pg_strdup(s);
6507
6510 pset.comp_case == PSQL_COMP_CASE_PRESERVE_UPPER) && islower(first)) ||
6511 (pset.comp_case == PSQL_COMP_CASE_PRESERVE_LOWER && !isalpha(first)))
6512 {
6513 for (p = ret; *p; p++)
6514 *p = pg_tolower((unsigned char) *p);
6515 }
6516 else
6517 {
6518 for (p = ret; *p; p++)
6519 *p = pg_toupper((unsigned char) *p);
6520 }
6521
6522 return ret;
6523}
6524
6525
6526/*
6527 * escape_string - Escape argument for use as string literal.
6528 *
6529 * The returned value has to be freed.
6530 */
6531static char *
6532escape_string(const char *text)
6533{
6534 size_t text_length;
6535 char *result;
6536
6537 text_length = strlen(text);
6538
6539 result = pg_malloc(text_length * 2 + 1);
6540 PQescapeStringConn(pset.db, result, text, text_length, NULL);
6541
6542 return result;
6543}
6544
6545
6546/*
6547 * make_like_pattern - Convert argument to a LIKE prefix pattern.
6548 *
6549 * We escape _ and % in the given text by backslashing, append a % to
6550 * represent "any subsequent characters", and then pass the string through
6551 * escape_string() so it's ready to insert in a query. The result needs
6552 * to be freed.
6553 */
6554static char *
6555make_like_pattern(const char *word)
6556{
6557 char *result;
6558 char *buffer = pg_malloc(strlen(word) * 2 + 2);
6559 char *bptr = buffer;
6560
6561 while (*word)
6562 {
6563 if (*word == '_' || *word == '%')
6564 *bptr++ = '\\';
6565 if (IS_HIGHBIT_SET(*word))
6566 {
6567 /*
6568 * Transfer multibyte characters without further processing, to
6569 * avoid getting confused in unsafe client encodings.
6570 */
6571 int chlen = PQmblenBounded(word, pset.encoding);
6572
6573 while (chlen-- > 0)
6574 *bptr++ = *word++;
6575 }
6576 else
6577 *bptr++ = *word++;
6578 }
6579 *bptr++ = '%';
6580 *bptr = '\0';
6581
6582 result = escape_string(buffer);
6583 free(buffer);
6584 return result;
6585}
6586
6587
6588/*
6589 * parse_identifier - Parse a possibly-schema-qualified SQL identifier.
6590 *
6591 * This involves splitting off the schema name if present, de-quoting,
6592 * and downcasing any unquoted text. We are a bit laxer than the backend
6593 * in that we allow just portions of a name to be quoted --- that's because
6594 * psql metacommands have traditionally behaved that way.
6595 *
6596 * Outputs are a malloc'd schema name (NULL if none), malloc'd object name,
6597 * and booleans telling whether any part of the schema and object name was
6598 * double-quoted.
6599 */
6600static void
6601parse_identifier(const char *ident,
6602 char **schemaname, char **objectname,
6603 bool *schemaquoted, bool *objectquoted)
6604{
6605 size_t buflen = strlen(ident) + 1;
6606 bool enc_is_single_byte = (pg_encoding_max_length(pset.encoding) == 1);
6607 char *sname;
6608 char *oname;
6609 char *optr;
6610 bool inquotes;
6611
6612 /* Initialize, making a certainly-large-enough output buffer */
6613 sname = NULL;
6614 oname = pg_malloc(buflen);
6615 *schemaquoted = *objectquoted = false;
6616 /* Scan */
6617 optr = oname;
6618 inquotes = false;
6619 while (*ident)
6620 {
6621 unsigned char ch = (unsigned char) *ident++;
6622
6623 if (ch == '"')
6624 {
6625 if (inquotes && *ident == '"')
6626 {
6627 /* two quote marks within a quoted identifier = emit quote */
6628 *optr++ = '"';
6629 ident++;
6630 }
6631 else
6632 {
6633 inquotes = !inquotes;
6634 *objectquoted = true;
6635 }
6636 }
6637 else if (ch == '.' && !inquotes)
6638 {
6639 /* Found a schema name, transfer it to sname / *schemaquoted */
6640 *optr = '\0';
6641 free(sname); /* drop any catalog name */
6642 sname = oname;
6643 oname = pg_malloc(buflen);
6644 optr = oname;
6645 *schemaquoted = *objectquoted;
6646 *objectquoted = false;
6647 }
6648 else if (!enc_is_single_byte && IS_HIGHBIT_SET(ch))
6649 {
6650 /*
6651 * Transfer multibyte characters without further processing. They
6652 * wouldn't be affected by our downcasing rule anyway, and this
6653 * avoids possibly doing the wrong thing in unsafe client
6654 * encodings.
6655 */
6656 int chlen = PQmblenBounded(ident - 1, pset.encoding);
6657
6658 *optr++ = (char) ch;
6659 while (--chlen > 0)
6660 *optr++ = *ident++;
6661 }
6662 else
6663 {
6664 if (!inquotes)
6665 {
6666 /*
6667 * This downcasing transformation should match the backend's
6668 * downcase_identifier() as best we can. We do not know the
6669 * backend's locale, though, so it's necessarily approximate.
6670 * We assume that psql is operating in the same locale and
6671 * encoding as the backend.
6672 */
6673 if (ch >= 'A' && ch <= 'Z')
6674 ch += 'a' - 'A';
6675 else if (enc_is_single_byte && IS_HIGHBIT_SET(ch) && isupper(ch))
6676 ch = tolower(ch);
6677 }
6678 *optr++ = (char) ch;
6679 }
6680 }
6681
6682 *optr = '\0';
6683 *schemaname = sname;
6684 *objectname = oname;
6685}
6686
6687
6688/*
6689 * requote_identifier - Reconstruct a possibly-schema-qualified SQL identifier.
6690 *
6691 * Build a malloc'd string containing the identifier, with quoting applied
6692 * as necessary. This is more or less the inverse of parse_identifier;
6693 * in particular, if an input component was quoted, we'll quote the output
6694 * even when that isn't strictly required.
6695 *
6696 * Unlike parse_identifier, we handle the case where a schema and no
6697 * object name is provided, producing just "schema.".
6698 */
6699static char *
6700requote_identifier(const char *schemaname, const char *objectname,
6701 bool quote_schema, bool quote_object)
6702{
6703 char *result;
6704 size_t buflen = 1; /* count the trailing \0 */
6705 char *ptr;
6706
6707 /*
6708 * We could use PQescapeIdentifier for some of this, but not all, and it
6709 * adds more notational cruft than it seems worth.
6710 */
6711 if (schemaname)
6712 {
6713 buflen += strlen(schemaname) + 1; /* +1 for the dot */
6714 if (!quote_schema)
6715 quote_schema = identifier_needs_quotes(schemaname);
6716 if (quote_schema)
6717 {
6718 buflen += 2; /* account for quote marks */
6719 for (const char *p = schemaname; *p; p++)
6720 {
6721 if (*p == '"')
6722 buflen++;
6723 }
6724 }
6725 }
6726 if (objectname)
6727 {
6728 buflen += strlen(objectname);
6729 if (!quote_object)
6730 quote_object = identifier_needs_quotes(objectname);
6731 if (quote_object)
6732 {
6733 buflen += 2; /* account for quote marks */
6734 for (const char *p = objectname; *p; p++)
6735 {
6736 if (*p == '"')
6737 buflen++;
6738 }
6739 }
6740 }
6741 result = pg_malloc(buflen);
6742 ptr = result;
6743 if (schemaname)
6744 {
6745 if (quote_schema)
6746 *ptr++ = '"';
6747 for (const char *p = schemaname; *p; p++)
6748 {
6749 *ptr++ = *p;
6750 if (*p == '"')
6751 *ptr++ = '"';
6752 }
6753 if (quote_schema)
6754 *ptr++ = '"';
6755 *ptr++ = '.';
6756 }
6757 if (objectname)
6758 {
6759 if (quote_object)
6760 *ptr++ = '"';
6761 for (const char *p = objectname; *p; p++)
6762 {
6763 *ptr++ = *p;
6764 if (*p == '"')
6765 *ptr++ = '"';
6766 }
6767 if (quote_object)
6768 *ptr++ = '"';
6769 }
6770 *ptr = '\0';
6771 return result;
6772}
6773
6774
6775/*
6776 * Detect whether an identifier must be double-quoted.
6777 *
6778 * Note we'll quote anything that's not ASCII; the backend's quote_ident()
6779 * does the same. Perhaps this could be relaxed in future.
6780 */
6781static bool
6782identifier_needs_quotes(const char *ident)
6783{
6784 int kwnum;
6785
6786 /* Check syntax. */
6787 if (!((ident[0] >= 'a' && ident[0] <= 'z') || ident[0] == '_'))
6788 return true;
6789 if (strspn(ident, "abcdefghijklmnopqrstuvwxyz0123456789_$") != strlen(ident))
6790 return true;
6791
6792 /*
6793 * Check for keyword. We quote keywords except for unreserved ones.
6794 *
6795 * It is possible that our keyword list doesn't quite agree with the
6796 * server's, but this should be close enough for tab-completion purposes.
6797 *
6798 * Note: ScanKeywordLookup() does case-insensitive comparison, but that's
6799 * fine, since we already know we have all-lower-case.
6800 */
6802
6803 if (kwnum >= 0 && ScanKeywordCategories[kwnum] != UNRESERVED_KEYWORD)
6804 return true;
6805
6806 return false;
6807}
6808
6809
6810/*
6811 * Execute a query, returning NULL if there was any error.
6812 * This should be the preferred way of talking to the database in this file.
6813 */
6814static PGresult *
6815exec_query(const char *query)
6816{
6817 PGresult *result;
6818
6819 if (query == NULL || !pset.db || PQstatus(pset.db) != CONNECTION_OK)
6820 return NULL;
6821
6822 result = PQexec(pset.db, query);
6823
6824 if (PQresultStatus(result) != PGRES_TUPLES_OK)
6825 {
6826 /*
6827 * Printing an error while the user is typing would be quite annoying,
6828 * so we don't. This does complicate debugging of this code; but you
6829 * can look in the server log instead.
6830 */
6831#ifdef NOT_USED
6832 pg_log_error("tab completion query failed: %s\nQuery was:\n%s",
6833 PQerrorMessage(pset.db), query);
6834#endif
6835 PQclear(result);
6836 result = NULL;
6837 }
6838
6839 return result;
6840}
6841
6842
6843/*
6844 * Parse all the word(s) before point.
6845 *
6846 * Returns a malloc'd array of character pointers that point into the malloc'd
6847 * data array returned to *buffer; caller must free() both of these when done.
6848 * *nwords receives the number of words found, ie, the valid length of the
6849 * return array.
6850 *
6851 * Words are returned right to left, that is, previous_words[0] gets the last
6852 * word before point, previous_words[1] the next-to-last, etc.
6853 */
6854static char **
6855get_previous_words(int point, char **buffer, int *nwords)
6856{
6857 char **previous_words;
6858 char *buf;
6859 char *outptr;
6860 int words_found = 0;
6861 int i;
6862
6863 /*
6864 * If we have anything in tab_completion_query_buf, paste it together with
6865 * rl_line_buffer to construct the full query. Otherwise we can just use
6866 * rl_line_buffer as the input string.
6867 */
6869 {
6871 buf = pg_malloc(point + i + 2);
6873 buf[i++] = '\n';
6874 memcpy(buf + i, rl_line_buffer, point);
6875 i += point;
6876 buf[i] = '\0';
6877 /* Readjust point to reference appropriate offset in buf */
6878 point = i;
6879 }
6880 else
6881 buf = rl_line_buffer;
6882
6883 /*
6884 * Allocate an array of string pointers and a buffer to hold the strings
6885 * themselves. The worst case is that the line contains only
6886 * non-whitespace WORD_BREAKS characters, making each one a separate word.
6887 * This is usually much more space than we need, but it's cheaper than
6888 * doing a separate malloc() for each word.
6889 */
6890 previous_words = (char **) pg_malloc(point * sizeof(char *));
6891 *buffer = outptr = (char *) pg_malloc(point * 2);
6892
6893 /*
6894 * First we look for a non-word char before the current point. (This is
6895 * probably useless, if readline is on the same page as we are about what
6896 * is a word, but if so it's cheap.)
6897 */
6898 for (i = point - 1; i >= 0; i--)
6899 {
6900 if (strchr(WORD_BREAKS, buf[i]))
6901 break;
6902 }
6903 point = i;
6904
6905 /*
6906 * Now parse words, working backwards, until we hit start of line. The
6907 * backwards scan has some interesting but intentional properties
6908 * concerning parenthesis handling.
6909 */
6910 while (point >= 0)
6911 {
6912 int start,
6913 end;
6914 bool inquotes = false;
6915 int parentheses = 0;
6916
6917 /* now find the first non-space which then constitutes the end */
6918 end = -1;
6919 for (i = point; i >= 0; i--)
6920 {
6921 if (!isspace((unsigned char) buf[i]))
6922 {
6923 end = i;
6924 break;
6925 }
6926 }
6927 /* if no end found, we're done */
6928 if (end < 0)
6929 break;
6930
6931 /*
6932 * Otherwise we now look for the start. The start is either the last
6933 * character before any word-break character going backwards from the
6934 * end, or it's simply character 0. We also handle open quotes and
6935 * parentheses.
6936 */
6937 for (start = end; start > 0; start--)
6938 {
6939 if (buf[start] == '"')
6940 inquotes = !inquotes;
6941 if (!inquotes)
6942 {
6943 if (buf[start] == ')')
6944 parentheses++;
6945 else if (buf[start] == '(')
6946 {
6947 if (--parentheses <= 0)
6948 break;
6949 }
6950 else if (parentheses == 0 &&
6951 strchr(WORD_BREAKS, buf[start - 1]))
6952 break;
6953 }
6954 }
6955
6956 /* Return the word located at start to end inclusive */
6957 previous_words[words_found++] = outptr;
6958 i = end - start + 1;
6959 memcpy(outptr, &buf[start], i);
6960 outptr += i;
6961 *outptr++ = '\0';
6962
6963 /* Continue searching */
6964 point = start - 1;
6965 }
6966
6967 /* Release parsing input workspace, if we made one above */
6968 if (buf != rl_line_buffer)
6969 free(buf);
6970
6971 *nwords = words_found;
6972 return previous_words;
6973}
6974
6975/*
6976 * Look up the type for the GUC variable with the passed name.
6977 *
6978 * Returns NULL if the variable is unknown. Otherwise the returned string,
6979 * containing the type, has to be freed.
6980 */
6981static char *
6982get_guctype(const char *varname)
6983{
6984 PQExpBufferData query_buffer;
6985 char *e_varname;
6986 PGresult *result;
6987 char *guctype = NULL;
6988
6989 e_varname = escape_string(varname);
6990
6991 initPQExpBuffer(&query_buffer);
6992 appendPQExpBuffer(&query_buffer,
6993 "SELECT vartype FROM pg_catalog.pg_settings "
6994 "WHERE pg_catalog.lower(name) = pg_catalog.lower('%s')",
6995 e_varname);
6996
6997 result = exec_query(query_buffer.data);
6998 termPQExpBuffer(&query_buffer);
6999 free(e_varname);
7000
7001 if (PQresultStatus(result) == PGRES_TUPLES_OK && PQntuples(result) > 0)
7002 guctype = pg_strdup(PQgetvalue(result, 0, 0));
7003
7004 PQclear(result);
7005
7006 return guctype;
7007}
7008
7009#ifdef USE_FILENAME_QUOTING_FUNCTIONS
7010
7011/*
7012 * Quote a filename according to SQL rules, returning a malloc'd string.
7013 * completion_charp must point to escape character or '\0', and
7014 * completion_force_quote must be set correctly, as per comments for
7015 * complete_from_files().
7016 */
7017static char *
7018quote_file_name(char *fname, int match_type, char *quote_pointer)
7019{
7020 char *s;
7021 struct stat statbuf;
7022
7023 /* Quote if needed. */
7024 s = quote_if_needed(fname, " \t\r\n\"`",
7025 '\'', *completion_charp,
7026 completion_force_quote,
7027 pset.encoding);
7028 if (!s)
7029 s = pg_strdup(fname);
7030
7031 /*
7032 * However, some of the time we have to strip the trailing quote from what
7033 * we send back. Never strip the trailing quote if the user already typed
7034 * one; otherwise, suppress the trailing quote if we have multiple/no
7035 * matches (because we don't want to add a quote if the input is seemingly
7036 * unfinished), or if the input was already quoted (because Readline will
7037 * do arguably-buggy things otherwise), or if the file does not exist, or
7038 * if it's a directory.
7039 */
7040 if (*s == '\'' &&
7041 completion_last_char != '\'' &&
7042 (match_type != SINGLE_MATCH ||
7043 (quote_pointer && *quote_pointer == '\'') ||
7044 stat(fname, &statbuf) != 0 ||
7045 S_ISDIR(statbuf.st_mode)))
7046 {
7047 char *send = s + strlen(s) - 1;
7048
7049 Assert(*send == '\'');
7050 *send = '\0';
7051 }
7052
7053 /*
7054 * And now we can let Readline do its thing with possibly adding a quote
7055 * on its own accord. (This covers some additional cases beyond those
7056 * dealt with above.)
7057 */
7058#ifdef HAVE_RL_COMPLETION_SUPPRESS_QUOTE
7059 rl_completion_suppress_quote = 0;
7060#endif
7061
7062 /*
7063 * If user typed a leading quote character other than single quote (i.e.,
7064 * double quote), zap it, so that we replace it with the correct single
7065 * quote.
7066 */
7067 if (quote_pointer && *quote_pointer != '\'')
7068 *quote_pointer = '\0';
7069
7070 return s;
7071}
7072
7073/*
7074 * Dequote a filename, if it's quoted.
7075 * completion_charp must point to escape character or '\0', as per
7076 * comments for complete_from_files().
7077 */
7078static char *
7079dequote_file_name(char *fname, int quote_char)
7080{
7081 char *unquoted_fname;
7082
7083 /*
7084 * If quote_char is set, it's not included in "fname". We have to add it
7085 * or strtokx will not interpret the string correctly (notably, it won't
7086 * recognize escapes).
7087 */
7088 if (quote_char == '\'')
7089 {
7090 char *workspace = (char *) pg_malloc(strlen(fname) + 2);
7091
7092 workspace[0] = quote_char;
7093 strcpy(workspace + 1, fname);
7094 unquoted_fname = strtokx(workspace, "", NULL, "'", *completion_charp,
7095 false, true, pset.encoding);
7096 free(workspace);
7097 }
7098 else
7099 unquoted_fname = strtokx(fname, "", NULL, "'", *completion_charp,
7100 false, true, pset.encoding);
7101
7102 /* expect a NULL return for the empty string only */
7103 if (!unquoted_fname)
7104 {
7105 Assert(*fname == '\0');
7106 unquoted_fname = fname;
7107 }
7108
7109 /* readline expects a malloc'd result that it is to free */
7110 return pg_strdup(unquoted_fname);
7111}
7112
7113#endif /* USE_FILENAME_QUOTING_FUNCTIONS */
7114
7115#endif /* USE_READLINE */
bool recognized_connection_string(const char *connstr)
Definition: common.c:2704
struct varlena text
Definition: c.h:719
#define IS_HIGHBIT_SET(ch)
Definition: c.h:1153
uint32 bits32
Definition: c.h:561
#define CppAsString2(x)
Definition: c.h:434
#define lengthof(array)
Definition: c.h:801
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[DEFAULT_XLOG_SEG_SIZE]
Definition: pg_test_fsync.c:71
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:706
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:502