LCOV - code coverage report
Current view: top level - src/bin/psql - tab-complete.c (source / functions) Hit Total Coverage
Test: PostgreSQL 14devel Lines: 888 1746 50.9 %
Date: 2020-11-27 12:05:55 Functions: 16 28 57.1 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.13