LCOV - code coverage report
Current view: top level - src/bin/psql - tab-complete.c (source / functions) Hit Total Coverage
Test: PostgreSQL 13devel Lines: 0 1617 0.0 %
Date: 2019-09-22 08:06:49 Functions: 0 26 0.0 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.13