LCOV - code coverage report
Current view: top level - src/bin/psql - tab-complete.in.c (source / functions) Hit Total Coverage
Test: PostgreSQL 19devel Lines: 652 2341 27.9 %
Date: 2025-08-31 13:18:20 Functions: 37 38 97.4 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.16