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

Generated by: LCOV version 1.13