LCOV - code coverage report
Current view: top level - src/backend/utils/adt - ruleutils.c (source / functions) Hit Total Coverage
Test: PostgreSQL 13beta1 Lines: 3816 4347 87.8 %
Date: 2020-06-01 08:06:25 Functions: 136 136 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * ruleutils.c
       4             :  *    Functions to convert stored expressions/querytrees back to
       5             :  *    source text
       6             :  *
       7             :  * Portions Copyright (c) 1996-2020, PostgreSQL Global Development Group
       8             :  * Portions Copyright (c) 1994, Regents of the University of California
       9             :  *
      10             :  *
      11             :  * IDENTIFICATION
      12             :  *    src/backend/utils/adt/ruleutils.c
      13             :  *
      14             :  *-------------------------------------------------------------------------
      15             :  */
      16             : #include "postgres.h"
      17             : 
      18             : #include <ctype.h>
      19             : #include <unistd.h>
      20             : #include <fcntl.h>
      21             : 
      22             : #include "access/amapi.h"
      23             : #include "access/htup_details.h"
      24             : #include "access/relation.h"
      25             : #include "access/sysattr.h"
      26             : #include "access/table.h"
      27             : #include "catalog/dependency.h"
      28             : #include "catalog/indexing.h"
      29             : #include "catalog/pg_aggregate.h"
      30             : #include "catalog/pg_am.h"
      31             : #include "catalog/pg_authid.h"
      32             : #include "catalog/pg_collation.h"
      33             : #include "catalog/pg_constraint.h"
      34             : #include "catalog/pg_depend.h"
      35             : #include "catalog/pg_language.h"
      36             : #include "catalog/pg_opclass.h"
      37             : #include "catalog/pg_operator.h"
      38             : #include "catalog/pg_partitioned_table.h"
      39             : #include "catalog/pg_proc.h"
      40             : #include "catalog/pg_statistic_ext.h"
      41             : #include "catalog/pg_trigger.h"
      42             : #include "catalog/pg_type.h"
      43             : #include "commands/defrem.h"
      44             : #include "commands/tablespace.h"
      45             : #include "common/keywords.h"
      46             : #include "executor/spi.h"
      47             : #include "funcapi.h"
      48             : #include "mb/pg_wchar.h"
      49             : #include "miscadmin.h"
      50             : #include "nodes/makefuncs.h"
      51             : #include "nodes/nodeFuncs.h"
      52             : #include "nodes/pathnodes.h"
      53             : #include "optimizer/optimizer.h"
      54             : #include "parser/parse_agg.h"
      55             : #include "parser/parse_func.h"
      56             : #include "parser/parse_node.h"
      57             : #include "parser/parse_oper.h"
      58             : #include "parser/parser.h"
      59             : #include "parser/parsetree.h"
      60             : #include "rewrite/rewriteHandler.h"
      61             : #include "rewrite/rewriteManip.h"
      62             : #include "rewrite/rewriteSupport.h"
      63             : #include "utils/array.h"
      64             : #include "utils/builtins.h"
      65             : #include "utils/fmgroids.h"
      66             : #include "utils/guc.h"
      67             : #include "utils/hsearch.h"
      68             : #include "utils/lsyscache.h"
      69             : #include "utils/partcache.h"
      70             : #include "utils/rel.h"
      71             : #include "utils/ruleutils.h"
      72             : #include "utils/snapmgr.h"
      73             : #include "utils/syscache.h"
      74             : #include "utils/typcache.h"
      75             : #include "utils/varlena.h"
      76             : #include "utils/xml.h"
      77             : 
      78             : /* ----------
      79             :  * Pretty formatting constants
      80             :  * ----------
      81             :  */
      82             : 
      83             : /* Indent counts */
      84             : #define PRETTYINDENT_STD        8
      85             : #define PRETTYINDENT_JOIN       4
      86             : #define PRETTYINDENT_VAR        4
      87             : 
      88             : #define PRETTYINDENT_LIMIT      40  /* wrap limit */
      89             : 
      90             : /* Pretty flags */
      91             : #define PRETTYFLAG_PAREN        0x0001
      92             : #define PRETTYFLAG_INDENT       0x0002
      93             : #define PRETTYFLAG_SCHEMA       0x0004
      94             : 
      95             : /* Default line length for pretty-print wrapping: 0 means wrap always */
      96             : #define WRAP_COLUMN_DEFAULT     0
      97             : 
      98             : /* macros to test if pretty action needed */
      99             : #define PRETTY_PAREN(context)   ((context)->prettyFlags & PRETTYFLAG_PAREN)
     100             : #define PRETTY_INDENT(context)  ((context)->prettyFlags & PRETTYFLAG_INDENT)
     101             : #define PRETTY_SCHEMA(context)  ((context)->prettyFlags & PRETTYFLAG_SCHEMA)
     102             : 
     103             : 
     104             : /* ----------
     105             :  * Local data types
     106             :  * ----------
     107             :  */
     108             : 
     109             : /* Context info needed for invoking a recursive querytree display routine */
     110             : typedef struct
     111             : {
     112             :     StringInfo  buf;            /* output buffer to append to */
     113             :     List       *namespaces;     /* List of deparse_namespace nodes */
     114             :     List       *windowClause;   /* Current query level's WINDOW clause */
     115             :     List       *windowTList;    /* targetlist for resolving WINDOW clause */
     116             :     int         prettyFlags;    /* enabling of pretty-print functions */
     117             :     int         wrapColumn;     /* max line length, or -1 for no limit */
     118             :     int         indentLevel;    /* current indent level for pretty-print */
     119             :     bool        varprefix;      /* true to print prefixes on Vars */
     120             :     ParseExprKind special_exprkind; /* set only for exprkinds needing special
     121             :                                      * handling */
     122             :     Bitmapset  *appendparents;  /* if not null, map child Vars of these relids
     123             :                                  * back to the parent rel */
     124             : } deparse_context;
     125             : 
     126             : /*
     127             :  * Each level of query context around a subtree needs a level of Var namespace.
     128             :  * A Var having varlevelsup=N refers to the N'th item (counting from 0) in
     129             :  * the current context's namespaces list.
     130             :  *
     131             :  * rtable is the list of actual RTEs from the Query or PlannedStmt.
     132             :  * rtable_names holds the alias name to be used for each RTE (either a C
     133             :  * string, or NULL for nameless RTEs such as unnamed joins).
     134             :  * rtable_columns holds the column alias names to be used for each RTE.
     135             :  *
     136             :  * subplans is a list of Plan trees for SubPlans and CTEs (it's only used
     137             :  * in the PlannedStmt case).
     138             :  * ctes is a list of CommonTableExpr nodes (only used in the Query case).
     139             :  * appendrels, if not null (it's only used in the PlannedStmt case), is an
     140             :  * array of AppendRelInfo nodes, indexed by child relid.  We use that to map
     141             :  * child-table Vars to their inheritance parents.
     142             :  *
     143             :  * In some cases we need to make names of merged JOIN USING columns unique
     144             :  * across the whole query, not only per-RTE.  If so, unique_using is true
     145             :  * and using_names is a list of C strings representing names already assigned
     146             :  * to USING columns.
     147             :  *
     148             :  * When deparsing plan trees, there is always just a single item in the
     149             :  * deparse_namespace list (since a plan tree never contains Vars with
     150             :  * varlevelsup > 0).  We store the Plan node that is the immediate
     151             :  * parent of the expression to be deparsed, as well as a list of that
     152             :  * Plan's ancestors.  In addition, we store its outer and inner subplan nodes,
     153             :  * as well as their targetlists, and the index tlist if the current plan node
     154             :  * might contain INDEX_VAR Vars.  (These fields could be derived on-the-fly
     155             :  * from the current Plan node, but it seems notationally clearer to set them
     156             :  * up as separate fields.)
     157             :  */
     158             : typedef struct
     159             : {
     160             :     List       *rtable;         /* List of RangeTblEntry nodes */
     161             :     List       *rtable_names;   /* Parallel list of names for RTEs */
     162             :     List       *rtable_columns; /* Parallel list of deparse_columns structs */
     163             :     List       *subplans;       /* List of Plan trees for SubPlans */
     164             :     List       *ctes;           /* List of CommonTableExpr nodes */
     165             :     AppendRelInfo **appendrels; /* Array of AppendRelInfo nodes, or NULL */
     166             :     /* Workspace for column alias assignment: */
     167             :     bool        unique_using;   /* Are we making USING names globally unique */
     168             :     List       *using_names;    /* List of assigned names for USING columns */
     169             :     /* Remaining fields are used only when deparsing a Plan tree: */
     170             :     Plan       *plan;           /* immediate parent of current expression */
     171             :     List       *ancestors;      /* ancestors of plan */
     172             :     Plan       *outer_plan;     /* outer subnode, or NULL if none */
     173             :     Plan       *inner_plan;     /* inner subnode, or NULL if none */
     174             :     List       *outer_tlist;    /* referent for OUTER_VAR Vars */
     175             :     List       *inner_tlist;    /* referent for INNER_VAR Vars */
     176             :     List       *index_tlist;    /* referent for INDEX_VAR Vars */
     177             : } deparse_namespace;
     178             : 
     179             : /*
     180             :  * Per-relation data about column alias names.
     181             :  *
     182             :  * Selecting aliases is unreasonably complicated because of the need to dump
     183             :  * rules/views whose underlying tables may have had columns added, deleted, or
     184             :  * renamed since the query was parsed.  We must nonetheless print the rule/view
     185             :  * in a form that can be reloaded and will produce the same results as before.
     186             :  *
     187             :  * For each RTE used in the query, we must assign column aliases that are
     188             :  * unique within that RTE.  SQL does not require this of the original query,
     189             :  * but due to factors such as *-expansion we need to be able to uniquely
     190             :  * reference every column in a decompiled query.  As long as we qualify all
     191             :  * column references, per-RTE uniqueness is sufficient for that.
     192             :  *
     193             :  * However, we can't ensure per-column name uniqueness for unnamed join RTEs,
     194             :  * since they just inherit column names from their input RTEs, and we can't
     195             :  * rename the columns at the join level.  Most of the time this isn't an issue
     196             :  * because we don't need to reference the join's output columns as such; we
     197             :  * can reference the input columns instead.  That approach can fail for merged
     198             :  * JOIN USING columns, however, so when we have one of those in an unnamed
     199             :  * join, we have to make that column's alias globally unique across the whole
     200             :  * query to ensure it can be referenced unambiguously.
     201             :  *
     202             :  * Another problem is that a JOIN USING clause requires the columns to be
     203             :  * merged to have the same aliases in both input RTEs, and that no other
     204             :  * columns in those RTEs or their children conflict with the USING names.
     205             :  * To handle that, we do USING-column alias assignment in a recursive
     206             :  * traversal of the query's jointree.  When descending through a JOIN with
     207             :  * USING, we preassign the USING column names to the child columns, overriding
     208             :  * other rules for column alias assignment.  We also mark each RTE with a list
     209             :  * of all USING column names selected for joins containing that RTE, so that
     210             :  * when we assign other columns' aliases later, we can avoid conflicts.
     211             :  *
     212             :  * Another problem is that if a JOIN's input tables have had columns added or
     213             :  * deleted since the query was parsed, we must generate a column alias list
     214             :  * for the join that matches the current set of input columns --- otherwise, a
     215             :  * change in the number of columns in the left input would throw off matching
     216             :  * of aliases to columns of the right input.  Thus, positions in the printable
     217             :  * column alias list are not necessarily one-for-one with varattnos of the
     218             :  * JOIN, so we need a separate new_colnames[] array for printing purposes.
     219             :  */
     220             : typedef struct
     221             : {
     222             :     /*
     223             :      * colnames is an array containing column aliases to use for columns that
     224             :      * existed when the query was parsed.  Dropped columns have NULL entries.
     225             :      * This array can be directly indexed by varattno to get a Var's name.
     226             :      *
     227             :      * Non-NULL entries are guaranteed unique within the RTE, *except* when
     228             :      * this is for an unnamed JOIN RTE.  In that case we merely copy up names
     229             :      * from the two input RTEs.
     230             :      *
     231             :      * During the recursive descent in set_using_names(), forcible assignment
     232             :      * of a child RTE's column name is represented by pre-setting that element
     233             :      * of the child's colnames array.  So at that stage, NULL entries in this
     234             :      * array just mean that no name has been preassigned, not necessarily that
     235             :      * the column is dropped.
     236             :      */
     237             :     int         num_cols;       /* length of colnames[] array */
     238             :     char      **colnames;       /* array of C strings and NULLs */
     239             : 
     240             :     /*
     241             :      * new_colnames is an array containing column aliases to use for columns
     242             :      * that would exist if the query was re-parsed against the current
     243             :      * definitions of its base tables.  This is what to print as the column
     244             :      * alias list for the RTE.  This array does not include dropped columns,
     245             :      * but it will include columns added since original parsing.  Indexes in
     246             :      * it therefore have little to do with current varattno values.  As above,
     247             :      * entries are unique unless this is for an unnamed JOIN RTE.  (In such an
     248             :      * RTE, we never actually print this array, but we must compute it anyway
     249             :      * for possible use in computing column names of upper joins.) The
     250             :      * parallel array is_new_col marks which of these columns are new since
     251             :      * original parsing.  Entries with is_new_col false must match the
     252             :      * non-NULL colnames entries one-for-one.
     253             :      */
     254             :     int         num_new_cols;   /* length of new_colnames[] array */
     255             :     char      **new_colnames;   /* array of C strings */
     256             :     bool       *is_new_col;     /* array of bool flags */
     257             : 
     258             :     /* This flag tells whether we should actually print a column alias list */
     259             :     bool        printaliases;
     260             : 
     261             :     /* This list has all names used as USING names in joins above this RTE */
     262             :     List       *parentUsing;    /* names assigned to parent merged columns */
     263             : 
     264             :     /*
     265             :      * If this struct is for a JOIN RTE, we fill these fields during the
     266             :      * set_using_names() pass to describe its relationship to its child RTEs.
     267             :      *
     268             :      * leftattnos and rightattnos are arrays with one entry per existing
     269             :      * output column of the join (hence, indexable by join varattno).  For a
     270             :      * simple reference to a column of the left child, leftattnos[i] is the
     271             :      * child RTE's attno and rightattnos[i] is zero; and conversely for a
     272             :      * column of the right child.  But for merged columns produced by JOIN
     273             :      * USING/NATURAL JOIN, both leftattnos[i] and rightattnos[i] are nonzero.
     274             :      * Note that a simple reference might be to a child RTE column that's been
     275             :      * dropped; but that's OK since the column could not be used in the query.
     276             :      *
     277             :      * If it's a JOIN USING, usingNames holds the alias names selected for the
     278             :      * merged columns (these might be different from the original USING list,
     279             :      * if we had to modify names to achieve uniqueness).
     280             :      */
     281             :     int         leftrti;        /* rangetable index of left child */
     282             :     int         rightrti;       /* rangetable index of right child */
     283             :     int        *leftattnos;     /* left-child varattnos of join cols, or 0 */
     284             :     int        *rightattnos;    /* right-child varattnos of join cols, or 0 */
     285             :     List       *usingNames;     /* names assigned to merged columns */
     286             : } deparse_columns;
     287             : 
     288             : /* This macro is analogous to rt_fetch(), but for deparse_columns structs */
     289             : #define deparse_columns_fetch(rangetable_index, dpns) \
     290             :     ((deparse_columns *) list_nth((dpns)->rtable_columns, (rangetable_index)-1))
     291             : 
     292             : /*
     293             :  * Entry in set_rtable_names' hash table
     294             :  */
     295             : typedef struct
     296             : {
     297             :     char        name[NAMEDATALEN];  /* Hash key --- must be first */
     298             :     int         counter;        /* Largest addition used so far for name */
     299             : } NameHashEntry;
     300             : 
     301             : /* Callback signature for resolve_special_varno() */
     302             : typedef void (*rsv_callback) (Node *node, deparse_context *context,
     303             :                               void *callback_arg);
     304             : 
     305             : 
     306             : /* ----------
     307             :  * Global data
     308             :  * ----------
     309             :  */
     310             : static SPIPlanPtr plan_getrulebyoid = NULL;
     311             : static const char *query_getrulebyoid = "SELECT * FROM pg_catalog.pg_rewrite WHERE oid = $1";
     312             : static SPIPlanPtr plan_getviewrule = NULL;
     313             : static const char *query_getviewrule = "SELECT * FROM pg_catalog.pg_rewrite WHERE ev_class = $1 AND rulename = $2";
     314             : 
     315             : /* GUC parameters */
     316             : bool        quote_all_identifiers = false;
     317             : 
     318             : 
     319             : /* ----------
     320             :  * Local functions
     321             :  *
     322             :  * Most of these functions used to use fixed-size buffers to build their
     323             :  * results.  Now, they take an (already initialized) StringInfo object
     324             :  * as a parameter, and append their text output to its contents.
     325             :  * ----------
     326             :  */
     327             : static char *deparse_expression_pretty(Node *expr, List *dpcontext,
     328             :                                        bool forceprefix, bool showimplicit,
     329             :                                        int prettyFlags, int startIndent);
     330             : static char *pg_get_viewdef_worker(Oid viewoid,
     331             :                                    int prettyFlags, int wrapColumn);
     332             : static char *pg_get_triggerdef_worker(Oid trigid, bool pretty);
     333             : static int  decompile_column_index_array(Datum column_index_array, Oid relId,
     334             :                                          StringInfo buf);
     335             : static char *pg_get_ruledef_worker(Oid ruleoid, int prettyFlags);
     336             : static char *pg_get_indexdef_worker(Oid indexrelid, int colno,
     337             :                                     const Oid *excludeOps,
     338             :                                     bool attrsOnly, bool keysOnly,
     339             :                                     bool showTblSpc, bool inherits,
     340             :                                     int prettyFlags, bool missing_ok);
     341             : static char *pg_get_statisticsobj_worker(Oid statextid, bool missing_ok);
     342             : static char *pg_get_partkeydef_worker(Oid relid, int prettyFlags,
     343             :                                       bool attrsOnly, bool missing_ok);
     344             : static char *pg_get_constraintdef_worker(Oid constraintId, bool fullCommand,
     345             :                                          int prettyFlags, bool missing_ok);
     346             : static text *pg_get_expr_worker(text *expr, Oid relid, const char *relname,
     347             :                                 int prettyFlags);
     348             : static int  print_function_arguments(StringInfo buf, HeapTuple proctup,
     349             :                                      bool print_table_args, bool print_defaults);
     350             : static void print_function_rettype(StringInfo buf, HeapTuple proctup);
     351             : static void print_function_trftypes(StringInfo buf, HeapTuple proctup);
     352             : static void set_rtable_names(deparse_namespace *dpns, List *parent_namespaces,
     353             :                              Bitmapset *rels_used);
     354             : static void set_deparse_for_query(deparse_namespace *dpns, Query *query,
     355             :                                   List *parent_namespaces);
     356             : static void set_simple_column_names(deparse_namespace *dpns);
     357             : static bool has_dangerous_join_using(deparse_namespace *dpns, Node *jtnode);
     358             : static void set_using_names(deparse_namespace *dpns, Node *jtnode,
     359             :                             List *parentUsing);
     360             : static void set_relation_column_names(deparse_namespace *dpns,
     361             :                                       RangeTblEntry *rte,
     362             :                                       deparse_columns *colinfo);
     363             : static void set_join_column_names(deparse_namespace *dpns, RangeTblEntry *rte,
     364             :                                   deparse_columns *colinfo);
     365             : static bool colname_is_unique(const char *colname, deparse_namespace *dpns,
     366             :                               deparse_columns *colinfo);
     367             : static char *make_colname_unique(char *colname, deparse_namespace *dpns,
     368             :                                  deparse_columns *colinfo);
     369             : static void expand_colnames_array_to(deparse_columns *colinfo, int n);
     370             : static void identify_join_columns(JoinExpr *j, RangeTblEntry *jrte,
     371             :                                   deparse_columns *colinfo);
     372             : static char *get_rtable_name(int rtindex, deparse_context *context);
     373             : static void set_deparse_plan(deparse_namespace *dpns, Plan *plan);
     374             : static void push_child_plan(deparse_namespace *dpns, Plan *plan,
     375             :                             deparse_namespace *save_dpns);
     376             : static void pop_child_plan(deparse_namespace *dpns,
     377             :                            deparse_namespace *save_dpns);
     378             : static void push_ancestor_plan(deparse_namespace *dpns, ListCell *ancestor_cell,
     379             :                                deparse_namespace *save_dpns);
     380             : static void pop_ancestor_plan(deparse_namespace *dpns,
     381             :                               deparse_namespace *save_dpns);
     382             : static void make_ruledef(StringInfo buf, HeapTuple ruletup, TupleDesc rulettc,
     383             :                          int prettyFlags);
     384             : static void make_viewdef(StringInfo buf, HeapTuple ruletup, TupleDesc rulettc,
     385             :                          int prettyFlags, int wrapColumn);
     386             : static void get_query_def(Query *query, StringInfo buf, List *parentnamespace,
     387             :                           TupleDesc resultDesc,
     388             :                           int prettyFlags, int wrapColumn, int startIndent);
     389             : static void get_values_def(List *values_lists, deparse_context *context);
     390             : static void get_with_clause(Query *query, deparse_context *context);
     391             : static void get_select_query_def(Query *query, deparse_context *context,
     392             :                                  TupleDesc resultDesc);
     393             : static void get_insert_query_def(Query *query, deparse_context *context);
     394             : static void get_update_query_def(Query *query, deparse_context *context);
     395             : static void get_update_query_targetlist_def(Query *query, List *targetList,
     396             :                                             deparse_context *context,
     397             :                                             RangeTblEntry *rte);
     398             : static void get_delete_query_def(Query *query, deparse_context *context);
     399             : static void get_utility_query_def(Query *query, deparse_context *context);
     400             : static void get_basic_select_query(Query *query, deparse_context *context,
     401             :                                    TupleDesc resultDesc);
     402             : static void get_target_list(List *targetList, deparse_context *context,
     403             :                             TupleDesc resultDesc);
     404             : static void get_setop_query(Node *setOp, Query *query,
     405             :                             deparse_context *context,
     406             :                             TupleDesc resultDesc);
     407             : static Node *get_rule_sortgroupclause(Index ref, List *tlist,
     408             :                                       bool force_colno,
     409             :                                       deparse_context *context);
     410             : static void get_rule_groupingset(GroupingSet *gset, List *targetlist,
     411             :                                  bool omit_parens, deparse_context *context);
     412             : static void get_rule_orderby(List *orderList, List *targetList,
     413             :                              bool force_colno, deparse_context *context);
     414             : static void get_rule_windowclause(Query *query, deparse_context *context);
     415             : static void get_rule_windowspec(WindowClause *wc, List *targetList,
     416             :                                 deparse_context *context);
     417             : static char *get_variable(Var *var, int levelsup, bool istoplevel,
     418             :                           deparse_context *context);
     419             : static void get_special_variable(Node *node, deparse_context *context,
     420             :                                  void *callback_arg);
     421             : static void resolve_special_varno(Node *node, deparse_context *context,
     422             :                                   rsv_callback callback, void *callback_arg);
     423             : static Node *find_param_referent(Param *param, deparse_context *context,
     424             :                                  deparse_namespace **dpns_p, ListCell **ancestor_cell_p);
     425             : static void get_parameter(Param *param, deparse_context *context);
     426             : static const char *get_simple_binary_op_name(OpExpr *expr);
     427             : static bool isSimpleNode(Node *node, Node *parentNode, int prettyFlags);
     428             : static void appendContextKeyword(deparse_context *context, const char *str,
     429             :                                  int indentBefore, int indentAfter, int indentPlus);
     430             : static void removeStringInfoSpaces(StringInfo str);
     431             : static void get_rule_expr(Node *node, deparse_context *context,
     432             :                           bool showimplicit);
     433             : static void get_rule_expr_toplevel(Node *node, deparse_context *context,
     434             :                                    bool showimplicit);
     435             : static void get_rule_expr_funccall(Node *node, deparse_context *context,
     436             :                                    bool showimplicit);
     437             : static bool looks_like_function(Node *node);
     438             : static void get_oper_expr(OpExpr *expr, deparse_context *context);
     439             : static void get_func_expr(FuncExpr *expr, deparse_context *context,
     440             :                           bool showimplicit);
     441             : static void get_agg_expr(Aggref *aggref, deparse_context *context,
     442             :                          Aggref *original_aggref);
     443             : static void get_agg_combine_expr(Node *node, deparse_context *context,
     444             :                                  void *callback_arg);
     445             : static void get_windowfunc_expr(WindowFunc *wfunc, deparse_context *context);
     446             : static void get_coercion_expr(Node *arg, deparse_context *context,
     447             :                               Oid resulttype, int32 resulttypmod,
     448             :                               Node *parentNode);
     449             : static void get_const_expr(Const *constval, deparse_context *context,
     450             :                            int showtype);
     451             : static void get_const_collation(Const *constval, deparse_context *context);
     452             : static void simple_quote_literal(StringInfo buf, const char *val);
     453             : static void get_sublink_expr(SubLink *sublink, deparse_context *context);
     454             : static void get_tablefunc(TableFunc *tf, deparse_context *context,
     455             :                           bool showimplicit);
     456             : static void get_from_clause(Query *query, const char *prefix,
     457             :                             deparse_context *context);
     458             : static void get_from_clause_item(Node *jtnode, Query *query,
     459             :                                  deparse_context *context);
     460             : static void get_column_alias_list(deparse_columns *colinfo,
     461             :                                   deparse_context *context);
     462             : static void get_from_clause_coldeflist(RangeTblFunction *rtfunc,
     463             :                                        deparse_columns *colinfo,
     464             :                                        deparse_context *context);
     465             : static void get_tablesample_def(TableSampleClause *tablesample,
     466             :                                 deparse_context *context);
     467             : static void get_opclass_name(Oid opclass, Oid actual_datatype,
     468             :                              StringInfo buf);
     469             : static Node *processIndirection(Node *node, deparse_context *context);
     470             : static void printSubscripts(SubscriptingRef *sbsref, deparse_context *context);
     471             : static char *get_relation_name(Oid relid);
     472             : static char *generate_relation_name(Oid relid, List *namespaces);
     473             : static char *generate_qualified_relation_name(Oid relid);
     474             : static char *generate_function_name(Oid funcid, int nargs,
     475             :                                     List *argnames, Oid *argtypes,
     476             :                                     bool has_variadic, bool *use_variadic_p,
     477             :                                     ParseExprKind special_exprkind);
     478             : static char *generate_operator_name(Oid operid, Oid arg1, Oid arg2);
     479             : static void add_cast_to(StringInfo buf, Oid typid);
     480             : static char *generate_qualified_type_name(Oid typid);
     481             : static text *string_to_text(char *str);
     482             : static char *flatten_reloptions(Oid relid);
     483             : static void get_reloptions(StringInfo buf, Datum reloptions);
     484             : 
     485             : #define only_marker(rte)  ((rte)->inh ? "" : "ONLY ")
     486             : 
     487             : 
     488             : /* ----------
     489             :  * pg_get_ruledef       - Do it all and return a text
     490             :  *                that could be used as a statement
     491             :  *                to recreate the rule
     492             :  * ----------
     493             :  */
     494             : Datum
     495         344 : pg_get_ruledef(PG_FUNCTION_ARGS)
     496             : {
     497         344 :     Oid         ruleoid = PG_GETARG_OID(0);
     498             :     int         prettyFlags;
     499             :     char       *res;
     500             : 
     501         344 :     prettyFlags = PRETTYFLAG_INDENT;
     502             : 
     503         344 :     res = pg_get_ruledef_worker(ruleoid, prettyFlags);
     504             : 
     505         344 :     if (res == NULL)
     506           4 :         PG_RETURN_NULL();
     507             : 
     508         340 :     PG_RETURN_TEXT_P(string_to_text(res));
     509             : }
     510             : 
     511             : 
     512             : Datum
     513          64 : pg_get_ruledef_ext(PG_FUNCTION_ARGS)
     514             : {
     515          64 :     Oid         ruleoid = PG_GETARG_OID(0);
     516          64 :     bool        pretty = PG_GETARG_BOOL(1);
     517             :     int         prettyFlags;
     518             :     char       *res;
     519             : 
     520          64 :     prettyFlags = pretty ? (PRETTYFLAG_PAREN | PRETTYFLAG_INDENT | PRETTYFLAG_SCHEMA) : PRETTYFLAG_INDENT;
     521             : 
     522          64 :     res = pg_get_ruledef_worker(ruleoid, prettyFlags);
     523             : 
     524          64 :     if (res == NULL)
     525           0 :         PG_RETURN_NULL();
     526             : 
     527          64 :     PG_RETURN_TEXT_P(string_to_text(res));
     528             : }
     529             : 
     530             : 
     531             : static char *
     532         408 : pg_get_ruledef_worker(Oid ruleoid, int prettyFlags)
     533             : {
     534             :     Datum       args[1];
     535             :     char        nulls[1];
     536             :     int         spirc;
     537             :     HeapTuple   ruletup;
     538             :     TupleDesc   rulettc;
     539             :     StringInfoData buf;
     540             : 
     541             :     /*
     542             :      * Do this first so that string is alloc'd in outer context not SPI's.
     543             :      */
     544         408 :     initStringInfo(&buf);
     545             : 
     546             :     /*
     547             :      * Connect to SPI manager
     548             :      */
     549         408 :     if (SPI_connect() != SPI_OK_CONNECT)
     550           0 :         elog(ERROR, "SPI_connect failed");
     551             : 
     552             :     /*
     553             :      * On the first call prepare the plan to lookup pg_rewrite. We read
     554             :      * pg_rewrite over the SPI manager instead of using the syscache to be
     555             :      * checked for read access on pg_rewrite.
     556             :      */
     557         408 :     if (plan_getrulebyoid == NULL)
     558             :     {
     559             :         Oid         argtypes[1];
     560             :         SPIPlanPtr  plan;
     561             : 
     562          22 :         argtypes[0] = OIDOID;
     563          22 :         plan = SPI_prepare(query_getrulebyoid, 1, argtypes);
     564          22 :         if (plan == NULL)
     565           0 :             elog(ERROR, "SPI_prepare failed for \"%s\"", query_getrulebyoid);
     566          22 :         SPI_keepplan(plan);
     567          22 :         plan_getrulebyoid = plan;
     568             :     }
     569             : 
     570             :     /*
     571             :      * Get the pg_rewrite tuple for this rule
     572             :      */
     573         408 :     args[0] = ObjectIdGetDatum(ruleoid);
     574         408 :     nulls[0] = ' ';
     575         408 :     spirc = SPI_execute_plan(plan_getrulebyoid, args, nulls, true, 0);
     576         408 :     if (spirc != SPI_OK_SELECT)
     577           0 :         elog(ERROR, "failed to get pg_rewrite tuple for rule %u", ruleoid);
     578         408 :     if (SPI_processed != 1)
     579             :     {
     580             :         /*
     581             :          * There is no tuple data available here, just keep the output buffer
     582             :          * empty.
     583             :          */
     584             :     }
     585             :     else
     586             :     {
     587             :         /*
     588             :          * Get the rule's definition and put it into executor's memory
     589             :          */
     590         404 :         ruletup = SPI_tuptable->vals[0];
     591         404 :         rulettc = SPI_tuptable->tupdesc;
     592         404 :         make_ruledef(&buf, ruletup, rulettc, prettyFlags);
     593             :     }
     594             : 
     595             :     /*
     596             :      * Disconnect from SPI manager
     597             :      */
     598         408 :     if (SPI_finish() != SPI_OK_FINISH)
     599           0 :         elog(ERROR, "SPI_finish failed");
     600             : 
     601         408 :     if (buf.len == 0)
     602           4 :         return NULL;
     603             : 
     604         404 :     return buf.data;
     605             : }
     606             : 
     607             : 
     608             : /* ----------
     609             :  * pg_get_viewdef       - Mainly the same thing, but we
     610             :  *                only return the SELECT part of a view
     611             :  * ----------
     612             :  */
     613             : Datum
     614        1168 : pg_get_viewdef(PG_FUNCTION_ARGS)
     615             : {
     616             :     /* By OID */
     617        1168 :     Oid         viewoid = PG_GETARG_OID(0);
     618             :     int         prettyFlags;
     619             :     char       *res;
     620             : 
     621        1168 :     prettyFlags = PRETTYFLAG_INDENT;
     622             : 
     623        1168 :     res = pg_get_viewdef_worker(viewoid, prettyFlags, WRAP_COLUMN_DEFAULT);
     624             : 
     625        1168 :     if (res == NULL)
     626           4 :         PG_RETURN_NULL();
     627             : 
     628        1164 :     PG_RETURN_TEXT_P(string_to_text(res));
     629             : }
     630             : 
     631             : 
     632             : Datum
     633         256 : pg_get_viewdef_ext(PG_FUNCTION_ARGS)
     634             : {
     635             :     /* By OID */
     636         256 :     Oid         viewoid = PG_GETARG_OID(0);
     637         256 :     bool        pretty = PG_GETARG_BOOL(1);
     638             :     int         prettyFlags;
     639             :     char       *res;
     640             : 
     641         256 :     prettyFlags = pretty ? (PRETTYFLAG_PAREN | PRETTYFLAG_INDENT | PRETTYFLAG_SCHEMA) : PRETTYFLAG_INDENT;
     642             : 
     643         256 :     res = pg_get_viewdef_worker(viewoid, prettyFlags, WRAP_COLUMN_DEFAULT);
     644             : 
     645         256 :     if (res == NULL)
     646           0 :         PG_RETURN_NULL();
     647             : 
     648         256 :     PG_RETURN_TEXT_P(string_to_text(res));
     649             : }
     650             : 
     651             : Datum
     652           4 : pg_get_viewdef_wrap(PG_FUNCTION_ARGS)
     653             : {
     654             :     /* By OID */
     655           4 :     Oid         viewoid = PG_GETARG_OID(0);
     656           4 :     int         wrap = PG_GETARG_INT32(1);
     657             :     int         prettyFlags;
     658             :     char       *res;
     659             : 
     660             :     /* calling this implies we want pretty printing */
     661           4 :     prettyFlags = PRETTYFLAG_PAREN | PRETTYFLAG_INDENT | PRETTYFLAG_SCHEMA;
     662             : 
     663           4 :     res = pg_get_viewdef_worker(viewoid, prettyFlags, wrap);
     664             : 
     665           4 :     if (res == NULL)
     666           0 :         PG_RETURN_NULL();
     667             : 
     668           4 :     PG_RETURN_TEXT_P(string_to_text(res));
     669             : }
     670             : 
     671             : Datum
     672          36 : pg_get_viewdef_name(PG_FUNCTION_ARGS)
     673             : {
     674             :     /* By qualified name */
     675          36 :     text       *viewname = PG_GETARG_TEXT_PP(0);
     676             :     int         prettyFlags;
     677             :     RangeVar   *viewrel;
     678             :     Oid         viewoid;
     679             :     char       *res;
     680             : 
     681          36 :     prettyFlags = PRETTYFLAG_INDENT;
     682             : 
     683             :     /* Look up view name.  Can't lock it - we might not have privileges. */
     684          36 :     viewrel = makeRangeVarFromNameList(textToQualifiedNameList(viewname));
     685          36 :     viewoid = RangeVarGetRelid(viewrel, NoLock, false);
     686             : 
     687          36 :     res = pg_get_viewdef_worker(viewoid, prettyFlags, WRAP_COLUMN_DEFAULT);
     688             : 
     689          36 :     if (res == NULL)
     690           0 :         PG_RETURN_NULL();
     691             : 
     692          36 :     PG_RETURN_TEXT_P(string_to_text(res));
     693             : }
     694             : 
     695             : 
     696             : Datum
     697         228 : pg_get_viewdef_name_ext(PG_FUNCTION_ARGS)
     698             : {
     699             :     /* By qualified name */
     700         228 :     text       *viewname = PG_GETARG_TEXT_PP(0);
     701         228 :     bool        pretty = PG_GETARG_BOOL(1);
     702             :     int         prettyFlags;
     703             :     RangeVar   *viewrel;
     704             :     Oid         viewoid;
     705             :     char       *res;
     706             : 
     707         228 :     prettyFlags = pretty ? (PRETTYFLAG_PAREN | PRETTYFLAG_INDENT | PRETTYFLAG_SCHEMA) : PRETTYFLAG_INDENT;
     708             : 
     709             :     /* Look up view name.  Can't lock it - we might not have privileges. */
     710         228 :     viewrel = makeRangeVarFromNameList(textToQualifiedNameList(viewname));
     711         228 :     viewoid = RangeVarGetRelid(viewrel, NoLock, false);
     712             : 
     713         228 :     res = pg_get_viewdef_worker(viewoid, prettyFlags, WRAP_COLUMN_DEFAULT);
     714             : 
     715         228 :     if (res == NULL)
     716           0 :         PG_RETURN_NULL();
     717             : 
     718         228 :     PG_RETURN_TEXT_P(string_to_text(res));
     719             : }
     720             : 
     721             : /*
     722             :  * Common code for by-OID and by-name variants of pg_get_viewdef
     723             :  */
     724             : static char *
     725        1692 : pg_get_viewdef_worker(Oid viewoid, int prettyFlags, int wrapColumn)
     726             : {
     727             :     Datum       args[2];
     728             :     char        nulls[2];
     729             :     int         spirc;
     730             :     HeapTuple   ruletup;
     731             :     TupleDesc   rulettc;
     732             :     StringInfoData buf;
     733             : 
     734             :     /*
     735             :      * Do this first so that string is alloc'd in outer context not SPI's.
     736             :      */
     737        1692 :     initStringInfo(&buf);
     738             : 
     739             :     /*
     740             :      * Connect to SPI manager
     741             :      */
     742        1692 :     if (SPI_connect() != SPI_OK_CONNECT)
     743           0 :         elog(ERROR, "SPI_connect failed");
     744             : 
     745             :     /*
     746             :      * On the first call prepare the plan to lookup pg_rewrite. We read
     747             :      * pg_rewrite over the SPI manager instead of using the syscache to be
     748             :      * checked for read access on pg_rewrite.
     749             :      */
     750        1692 :     if (plan_getviewrule == NULL)
     751             :     {
     752             :         Oid         argtypes[2];
     753             :         SPIPlanPtr  plan;
     754             : 
     755         116 :         argtypes[0] = OIDOID;
     756         116 :         argtypes[1] = NAMEOID;
     757         116 :         plan = SPI_prepare(query_getviewrule, 2, argtypes);
     758         116 :         if (plan == NULL)
     759           0 :             elog(ERROR, "SPI_prepare failed for \"%s\"", query_getviewrule);
     760         116 :         SPI_keepplan(plan);
     761         116 :         plan_getviewrule = plan;
     762             :     }
     763             : 
     764             :     /*
     765             :      * Get the pg_rewrite tuple for the view's SELECT rule
     766             :      */
     767        1692 :     args[0] = ObjectIdGetDatum(viewoid);
     768        1692 :     args[1] = DirectFunctionCall1(namein, CStringGetDatum(ViewSelectRuleName));
     769        1692 :     nulls[0] = ' ';
     770        1692 :     nulls[1] = ' ';
     771        1692 :     spirc = SPI_execute_plan(plan_getviewrule, args, nulls, true, 0);
     772        1692 :     if (spirc != SPI_OK_SELECT)
     773           0 :         elog(ERROR, "failed to get pg_rewrite tuple for view %u", viewoid);
     774        1692 :     if (SPI_processed != 1)
     775             :     {
     776             :         /*
     777             :          * There is no tuple data available here, just keep the output buffer
     778             :          * empty.
     779             :          */
     780             :     }
     781             :     else
     782             :     {
     783             :         /*
     784             :          * Get the rule's definition and put it into executor's memory
     785             :          */
     786        1688 :         ruletup = SPI_tuptable->vals[0];
     787        1688 :         rulettc = SPI_tuptable->tupdesc;
     788        1688 :         make_viewdef(&buf, ruletup, rulettc, prettyFlags, wrapColumn);
     789             :     }
     790             : 
     791             :     /*
     792             :      * Disconnect from SPI manager
     793             :      */
     794        1692 :     if (SPI_finish() != SPI_OK_FINISH)
     795           0 :         elog(ERROR, "SPI_finish failed");
     796             : 
     797        1692 :     if (buf.len == 0)
     798           4 :         return NULL;
     799             : 
     800        1688 :     return buf.data;
     801             : }
     802             : 
     803             : /* ----------
     804             :  * pg_get_triggerdef        - Get the definition of a trigger
     805             :  * ----------
     806             :  */
     807             : Datum
     808         136 : pg_get_triggerdef(PG_FUNCTION_ARGS)
     809             : {
     810         136 :     Oid         trigid = PG_GETARG_OID(0);
     811             :     char       *res;
     812             : 
     813         136 :     res = pg_get_triggerdef_worker(trigid, false);
     814             : 
     815         136 :     if (res == NULL)
     816           4 :         PG_RETURN_NULL();
     817             : 
     818         132 :     PG_RETURN_TEXT_P(string_to_text(res));
     819             : }
     820             : 
     821             : Datum
     822         536 : pg_get_triggerdef_ext(PG_FUNCTION_ARGS)
     823             : {
     824         536 :     Oid         trigid = PG_GETARG_OID(0);
     825         536 :     bool        pretty = PG_GETARG_BOOL(1);
     826             :     char       *res;
     827             : 
     828         536 :     res = pg_get_triggerdef_worker(trigid, pretty);
     829             : 
     830         536 :     if (res == NULL)
     831           0 :         PG_RETURN_NULL();
     832             : 
     833         536 :     PG_RETURN_TEXT_P(string_to_text(res));
     834             : }
     835             : 
     836             : static char *
     837         672 : pg_get_triggerdef_worker(Oid trigid, bool pretty)
     838             : {
     839             :     HeapTuple   ht_trig;
     840             :     Form_pg_trigger trigrec;
     841             :     StringInfoData buf;
     842             :     Relation    tgrel;
     843             :     ScanKeyData skey[1];
     844             :     SysScanDesc tgscan;
     845         672 :     int         findx = 0;
     846             :     char       *tgname;
     847             :     char       *tgoldtable;
     848             :     char       *tgnewtable;
     849             :     Datum       value;
     850             :     bool        isnull;
     851             : 
     852             :     /*
     853             :      * Fetch the pg_trigger tuple by the Oid of the trigger
     854             :      */
     855         672 :     tgrel = table_open(TriggerRelationId, AccessShareLock);
     856             : 
     857         672 :     ScanKeyInit(&skey[0],
     858             :                 Anum_pg_trigger_oid,
     859             :                 BTEqualStrategyNumber, F_OIDEQ,
     860             :                 ObjectIdGetDatum(trigid));
     861             : 
     862         672 :     tgscan = systable_beginscan(tgrel, TriggerOidIndexId, true,
     863             :                                 NULL, 1, skey);
     864             : 
     865         672 :     ht_trig = systable_getnext(tgscan);
     866             : 
     867         672 :     if (!HeapTupleIsValid(ht_trig))
     868             :     {
     869           4 :         systable_endscan(tgscan);
     870           4 :         table_close(tgrel, AccessShareLock);
     871           4 :         return NULL;
     872             :     }
     873             : 
     874         668 :     trigrec = (Form_pg_trigger) GETSTRUCT(ht_trig);
     875             : 
     876             :     /*
     877             :      * Start the trigger definition. Note that the trigger's name should never
     878             :      * be schema-qualified, but the trigger rel's name may be.
     879             :      */
     880         668 :     initStringInfo(&buf);
     881             : 
     882         668 :     tgname = NameStr(trigrec->tgname);
     883        1336 :     appendStringInfo(&buf, "CREATE %sTRIGGER %s ",
     884         668 :                      OidIsValid(trigrec->tgconstraint) ? "CONSTRAINT " : "",
     885             :                      quote_identifier(tgname));
     886             : 
     887         668 :     if (TRIGGER_FOR_BEFORE(trigrec->tgtype))
     888         322 :         appendStringInfoString(&buf, "BEFORE");
     889         346 :     else if (TRIGGER_FOR_AFTER(trigrec->tgtype))
     890         330 :         appendStringInfoString(&buf, "AFTER");
     891          16 :     else if (TRIGGER_FOR_INSTEAD(trigrec->tgtype))
     892          16 :         appendStringInfoString(&buf, "INSTEAD OF");
     893             :     else
     894           0 :         elog(ERROR, "unexpected tgtype value: %d", trigrec->tgtype);
     895             : 
     896         668 :     if (TRIGGER_FOR_INSERT(trigrec->tgtype))
     897             :     {
     898         380 :         appendStringInfoString(&buf, " INSERT");
     899         380 :         findx++;
     900             :     }
     901         668 :     if (TRIGGER_FOR_DELETE(trigrec->tgtype))
     902             :     {
     903         138 :         if (findx > 0)
     904          54 :             appendStringInfoString(&buf, " OR DELETE");
     905             :         else
     906          84 :             appendStringInfoString(&buf, " DELETE");
     907         138 :         findx++;
     908             :     }
     909         668 :     if (TRIGGER_FOR_UPDATE(trigrec->tgtype))
     910             :     {
     911         388 :         if (findx > 0)
     912         184 :             appendStringInfoString(&buf, " OR UPDATE");
     913             :         else
     914         204 :             appendStringInfoString(&buf, " UPDATE");
     915         388 :         findx++;
     916             :         /* tgattr is first var-width field, so OK to access directly */
     917         388 :         if (trigrec->tgattr.dim1 > 0)
     918             :         {
     919             :             int         i;
     920             : 
     921          48 :             appendStringInfoString(&buf, " OF ");
     922         106 :             for (i = 0; i < trigrec->tgattr.dim1; i++)
     923             :             {
     924             :                 char       *attname;
     925             : 
     926          58 :                 if (i > 0)
     927          10 :                     appendStringInfoString(&buf, ", ");
     928          58 :                 attname = get_attname(trigrec->tgrelid,
     929          58 :                                       trigrec->tgattr.values[i], false);
     930          58 :                 appendStringInfoString(&buf, quote_identifier(attname));
     931             :             }
     932             :         }
     933             :     }
     934         668 :     if (TRIGGER_FOR_TRUNCATE(trigrec->tgtype))
     935             :     {
     936           0 :         if (findx > 0)
     937           0 :             appendStringInfoString(&buf, " OR TRUNCATE");
     938             :         else
     939           0 :             appendStringInfoString(&buf, " TRUNCATE");
     940           0 :         findx++;
     941             :     }
     942             : 
     943             :     /*
     944             :      * In non-pretty mode, always schema-qualify the target table name for
     945             :      * safety.  In pretty mode, schema-qualify only if not visible.
     946             :      */
     947        1336 :     appendStringInfo(&buf, " ON %s ",
     948             :                      pretty ?
     949          80 :                      generate_relation_name(trigrec->tgrelid, NIL) :
     950         588 :                      generate_qualified_relation_name(trigrec->tgrelid));
     951             : 
     952         668 :     if (OidIsValid(trigrec->tgconstraint))
     953             :     {
     954           0 :         if (OidIsValid(trigrec->tgconstrrelid))
     955           0 :             appendStringInfo(&buf, "FROM %s ",
     956             :                              generate_relation_name(trigrec->tgconstrrelid, NIL));
     957           0 :         if (!trigrec->tgdeferrable)
     958           0 :             appendStringInfoString(&buf, "NOT ");
     959           0 :         appendStringInfoString(&buf, "DEFERRABLE INITIALLY ");
     960           0 :         if (trigrec->tginitdeferred)
     961           0 :             appendStringInfoString(&buf, "DEFERRED ");
     962             :         else
     963           0 :             appendStringInfoString(&buf, "IMMEDIATE ");
     964             :     }
     965             : 
     966         668 :     value = fastgetattr(ht_trig, Anum_pg_trigger_tgoldtable,
     967             :                         tgrel->rd_att, &isnull);
     968         668 :     if (!isnull)
     969          62 :         tgoldtable = NameStr(*DatumGetName(value));
     970             :     else
     971         606 :         tgoldtable = NULL;
     972         668 :     value = fastgetattr(ht_trig, Anum_pg_trigger_tgnewtable,
     973             :                         tgrel->rd_att, &isnull);
     974         668 :     if (!isnull)
     975          68 :         tgnewtable = NameStr(*DatumGetName(value));
     976             :     else
     977         600 :         tgnewtable = NULL;
     978         668 :     if (tgoldtable != NULL || tgnewtable != NULL)
     979             :     {
     980          96 :         appendStringInfoString(&buf, "REFERENCING ");
     981          96 :         if (tgoldtable != NULL)
     982          62 :             appendStringInfo(&buf, "OLD TABLE AS %s ",
     983             :                              quote_identifier(tgoldtable));
     984          96 :         if (tgnewtable != NULL)
     985          68 :             appendStringInfo(&buf, "NEW TABLE AS %s ",
     986             :                              quote_identifier(tgnewtable));
     987             :     }
     988             : 
     989         668 :     if (TRIGGER_FOR_ROW(trigrec->tgtype))
     990         474 :         appendStringInfoString(&buf, "FOR EACH ROW ");
     991             :     else
     992         194 :         appendStringInfoString(&buf, "FOR EACH STATEMENT ");
     993             : 
     994             :     /* If the trigger has a WHEN qualification, add that */
     995         668 :     value = fastgetattr(ht_trig, Anum_pg_trigger_tgqual,
     996             :                         tgrel->rd_att, &isnull);
     997         668 :     if (!isnull)
     998             :     {
     999             :         Node       *qual;
    1000             :         char        relkind;
    1001             :         deparse_context context;
    1002             :         deparse_namespace dpns;
    1003             :         RangeTblEntry *oldrte;
    1004             :         RangeTblEntry *newrte;
    1005             : 
    1006          92 :         appendStringInfoString(&buf, "WHEN (");
    1007             : 
    1008          92 :         qual = stringToNode(TextDatumGetCString(value));
    1009             : 
    1010          92 :         relkind = get_rel_relkind(trigrec->tgrelid);
    1011             : 
    1012             :         /* Build minimal OLD and NEW RTEs for the rel */
    1013          92 :         oldrte = makeNode(RangeTblEntry);
    1014          92 :         oldrte->rtekind = RTE_RELATION;
    1015          92 :         oldrte->relid = trigrec->tgrelid;
    1016          92 :         oldrte->relkind = relkind;
    1017          92 :         oldrte->rellockmode = AccessShareLock;
    1018          92 :         oldrte->alias = makeAlias("old", NIL);
    1019          92 :         oldrte->eref = oldrte->alias;
    1020          92 :         oldrte->lateral = false;
    1021          92 :         oldrte->inh = false;
    1022          92 :         oldrte->inFromCl = true;
    1023             : 
    1024          92 :         newrte = makeNode(RangeTblEntry);
    1025          92 :         newrte->rtekind = RTE_RELATION;
    1026          92 :         newrte->relid = trigrec->tgrelid;
    1027          92 :         newrte->relkind = relkind;
    1028          92 :         newrte->rellockmode = AccessShareLock;
    1029          92 :         newrte->alias = makeAlias("new", NIL);
    1030          92 :         newrte->eref = newrte->alias;
    1031          92 :         newrte->lateral = false;
    1032          92 :         newrte->inh = false;
    1033          92 :         newrte->inFromCl = true;
    1034             : 
    1035             :         /* Build two-element rtable */
    1036          92 :         memset(&dpns, 0, sizeof(dpns));
    1037          92 :         dpns.rtable = list_make2(oldrte, newrte);
    1038          92 :         dpns.subplans = NIL;
    1039          92 :         dpns.ctes = NIL;
    1040          92 :         dpns.appendrels = NULL;
    1041          92 :         set_rtable_names(&dpns, NIL, NULL);
    1042          92 :         set_simple_column_names(&dpns);
    1043             : 
    1044             :         /* Set up context with one-deep namespace stack */
    1045          92 :         context.buf = &buf;
    1046          92 :         context.namespaces = list_make1(&dpns);
    1047          92 :         context.windowClause = NIL;
    1048          92 :         context.windowTList = NIL;
    1049          92 :         context.varprefix = true;
    1050          92 :         context.prettyFlags = pretty ? (PRETTYFLAG_PAREN | PRETTYFLAG_INDENT | PRETTYFLAG_SCHEMA) : PRETTYFLAG_INDENT;
    1051          92 :         context.wrapColumn = WRAP_COLUMN_DEFAULT;
    1052          92 :         context.indentLevel = PRETTYINDENT_STD;
    1053          92 :         context.special_exprkind = EXPR_KIND_NONE;
    1054          92 :         context.appendparents = NULL;
    1055             : 
    1056          92 :         get_rule_expr(qual, &context, false);
    1057             : 
    1058          92 :         appendStringInfoString(&buf, ") ");
    1059             :     }
    1060             : 
    1061         668 :     appendStringInfo(&buf, "EXECUTE FUNCTION %s(",
    1062             :                      generate_function_name(trigrec->tgfoid, 0,
    1063             :                                             NIL, NULL,
    1064             :                                             false, NULL, EXPR_KIND_NONE));
    1065             : 
    1066         668 :     if (trigrec->tgnargs > 0)
    1067             :     {
    1068             :         char       *p;
    1069             :         int         i;
    1070             : 
    1071         286 :         value = fastgetattr(ht_trig, Anum_pg_trigger_tgargs,
    1072             :                             tgrel->rd_att, &isnull);
    1073         286 :         if (isnull)
    1074           0 :             elog(ERROR, "tgargs is null for trigger %u", trigid);
    1075         286 :         p = (char *) VARDATA_ANY(DatumGetByteaPP(value));
    1076         768 :         for (i = 0; i < trigrec->tgnargs; i++)
    1077             :         {
    1078         482 :             if (i > 0)
    1079         196 :                 appendStringInfoString(&buf, ", ");
    1080         482 :             simple_quote_literal(&buf, p);
    1081             :             /* advance p to next string embedded in tgargs */
    1082        4386 :             while (*p)
    1083        3904 :                 p++;
    1084         482 :             p++;
    1085             :         }
    1086             :     }
    1087             : 
    1088             :     /* We deliberately do not put semi-colon at end */
    1089         668 :     appendStringInfoChar(&buf, ')');
    1090             : 
    1091             :     /* Clean up */
    1092         668 :     systable_endscan(tgscan);
    1093             : 
    1094         668 :     table_close(tgrel, AccessShareLock);
    1095             : 
    1096         668 :     return buf.data;
    1097             : }
    1098             : 
    1099             : /* ----------
    1100             :  * pg_get_indexdef          - Get the definition of an index
    1101             :  *
    1102             :  * In the extended version, there is a colno argument as well as pretty bool.
    1103             :  *  if colno == 0, we want a complete index definition.
    1104             :  *  if colno > 0, we only want the Nth index key's variable or expression.
    1105             :  *
    1106             :  * Note that the SQL-function versions of this omit any info about the
    1107             :  * index tablespace; this is intentional because pg_dump wants it that way.
    1108             :  * However pg_get_indexdef_string() includes the index tablespace.
    1109             :  * ----------
    1110             :  */
    1111             : Datum
    1112        2182 : pg_get_indexdef(PG_FUNCTION_ARGS)
    1113             : {
    1114        2182 :     Oid         indexrelid = PG_GETARG_OID(0);
    1115             :     int         prettyFlags;
    1116             :     char       *res;
    1117             : 
    1118        2182 :     prettyFlags = PRETTYFLAG_INDENT;
    1119             : 
    1120        2182 :     res = pg_get_indexdef_worker(indexrelid, 0, NULL,
    1121             :                                  false, false,
    1122             :                                  false, false,
    1123             :                                  prettyFlags, true);
    1124             : 
    1125        2182 :     if (res == NULL)
    1126           4 :         PG_RETURN_NULL();
    1127             : 
    1128        2178 :     PG_RETURN_TEXT_P(string_to_text(res));
    1129             : }
    1130             : 
    1131             : Datum
    1132         996 : pg_get_indexdef_ext(PG_FUNCTION_ARGS)
    1133             : {
    1134         996 :     Oid         indexrelid = PG_GETARG_OID(0);
    1135         996 :     int32       colno = PG_GETARG_INT32(1);
    1136         996 :     bool        pretty = PG_GETARG_BOOL(2);
    1137             :     int         prettyFlags;
    1138             :     char       *res;
    1139             : 
    1140         996 :     prettyFlags = pretty ? (PRETTYFLAG_PAREN | PRETTYFLAG_INDENT | PRETTYFLAG_SCHEMA) : PRETTYFLAG_INDENT;
    1141             : 
    1142         996 :     res = pg_get_indexdef_worker(indexrelid, colno, NULL,
    1143             :                                  colno != 0, false,
    1144             :                                  false, false,
    1145             :                                  prettyFlags, true);
    1146             : 
    1147         996 :     if (res == NULL)
    1148           0 :         PG_RETURN_NULL();
    1149             : 
    1150         996 :     PG_RETURN_TEXT_P(string_to_text(res));
    1151             : }
    1152             : 
    1153             : /*
    1154             :  * Internal version for use by ALTER TABLE.
    1155             :  * Includes a tablespace clause in the result.
    1156             :  * Returns a palloc'd C string; no pretty-printing.
    1157             :  */
    1158             : char *
    1159         128 : pg_get_indexdef_string(Oid indexrelid)
    1160             : {
    1161         128 :     return pg_get_indexdef_worker(indexrelid, 0, NULL,
    1162             :                                   false, false,
    1163             :                                   true, true,
    1164             :                                   0, false);
    1165             : }
    1166             : 
    1167             : /* Internal version that just reports the key-column definitions */
    1168             : char *
    1169         470 : pg_get_indexdef_columns(Oid indexrelid, bool pretty)
    1170             : {
    1171             :     int         prettyFlags;
    1172             : 
    1173         470 :     prettyFlags = pretty ? (PRETTYFLAG_PAREN | PRETTYFLAG_INDENT | PRETTYFLAG_SCHEMA) : PRETTYFLAG_INDENT;
    1174             : 
    1175         470 :     return pg_get_indexdef_worker(indexrelid, 0, NULL,
    1176             :                                   true, true,
    1177             :                                   false, false,
    1178             :                                   prettyFlags, false);
    1179             : }
    1180             : 
    1181             : /*
    1182             :  * Internal workhorse to decompile an index definition.
    1183             :  *
    1184             :  * This is now used for exclusion constraints as well: if excludeOps is not
    1185             :  * NULL then it points to an array of exclusion operator OIDs.
    1186             :  */
    1187             : static char *
    1188        3844 : pg_get_indexdef_worker(Oid indexrelid, int colno,
    1189             :                        const Oid *excludeOps,
    1190             :                        bool attrsOnly, bool keysOnly,
    1191             :                        bool showTblSpc, bool inherits,
    1192             :                        int prettyFlags, bool missing_ok)
    1193             : {
    1194             :     /* might want a separate isConstraint parameter later */
    1195        3844 :     bool        isConstraint = (excludeOps != NULL);
    1196             :     HeapTuple   ht_idx;
    1197             :     HeapTuple   ht_idxrel;
    1198             :     HeapTuple   ht_am;
    1199             :     Form_pg_index idxrec;
    1200             :     Form_pg_class idxrelrec;
    1201             :     Form_pg_am  amrec;
    1202             :     IndexAmRoutine *amroutine;
    1203             :     List       *indexprs;
    1204             :     ListCell   *indexpr_item;
    1205             :     List       *context;
    1206             :     Oid         indrelid;
    1207             :     int         keyno;
    1208             :     Datum       indcollDatum;
    1209             :     Datum       indclassDatum;
    1210             :     Datum       indoptionDatum;
    1211             :     bool        isnull;
    1212             :     oidvector  *indcollation;
    1213             :     oidvector  *indclass;
    1214             :     int2vector *indoption;
    1215             :     StringInfoData buf;
    1216             :     char       *str;
    1217             :     char       *sep;
    1218             : 
    1219             :     /*
    1220             :      * Fetch the pg_index tuple by the Oid of the index
    1221             :      */
    1222        3844 :     ht_idx = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexrelid));
    1223        3844 :     if (!HeapTupleIsValid(ht_idx))
    1224             :     {
    1225           4 :         if (missing_ok)
    1226           4 :             return NULL;
    1227           0 :         elog(ERROR, "cache lookup failed for index %u", indexrelid);
    1228             :     }
    1229        3840 :     idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
    1230             : 
    1231        3840 :     indrelid = idxrec->indrelid;
    1232             :     Assert(indexrelid == idxrec->indexrelid);
    1233             : 
    1234             :     /* Must get indcollation, indclass, and indoption the hard way */
    1235        3840 :     indcollDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
    1236             :                                    Anum_pg_index_indcollation, &isnull);
    1237             :     Assert(!isnull);
    1238        3840 :     indcollation = (oidvector *) DatumGetPointer(indcollDatum);
    1239             : 
    1240        3840 :     indclassDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
    1241             :                                     Anum_pg_index_indclass, &isnull);
    1242             :     Assert(!isnull);
    1243        3840 :     indclass = (oidvector *) DatumGetPointer(indclassDatum);
    1244             : 
    1245        3840 :     indoptionDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
    1246             :                                      Anum_pg_index_indoption, &isnull);
    1247             :     Assert(!isnull);
    1248        3840 :     indoption = (int2vector *) DatumGetPointer(indoptionDatum);
    1249             : 
    1250             :     /*
    1251             :      * Fetch the pg_class tuple of the index relation
    1252             :      */
    1253        3840 :     ht_idxrel = SearchSysCache1(RELOID, ObjectIdGetDatum(indexrelid));
    1254        3840 :     if (!HeapTupleIsValid(ht_idxrel))
    1255           0 :         elog(ERROR, "cache lookup failed for relation %u", indexrelid);
    1256        3840 :     idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
    1257             : 
    1258             :     /*
    1259             :      * Fetch the pg_am tuple of the index' access method
    1260             :      */
    1261        3840 :     ht_am = SearchSysCache1(AMOID, ObjectIdGetDatum(idxrelrec->relam));
    1262        3840 :     if (!HeapTupleIsValid(ht_am))
    1263           0 :         elog(ERROR, "cache lookup failed for access method %u",
    1264             :              idxrelrec->relam);
    1265        3840 :     amrec = (Form_pg_am) GETSTRUCT(ht_am);
    1266             : 
    1267             :     /* Fetch the index AM's API struct */
    1268        3840 :     amroutine = GetIndexAmRoutine(amrec->amhandler);
    1269             : 
    1270             :     /*
    1271             :      * Get the index expressions, if any.  (NOTE: we do not use the relcache
    1272             :      * versions of the expressions and predicate, because we want to display
    1273             :      * non-const-folded expressions.)
    1274             :      */
    1275        3840 :     if (!heap_attisnull(ht_idx, Anum_pg_index_indexprs, NULL))
    1276             :     {
    1277             :         Datum       exprsDatum;
    1278             :         bool        isnull;
    1279             :         char       *exprsString;
    1280             : 
    1281         314 :         exprsDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
    1282             :                                      Anum_pg_index_indexprs, &isnull);
    1283             :         Assert(!isnull);
    1284         314 :         exprsString = TextDatumGetCString(exprsDatum);
    1285         314 :         indexprs = (List *) stringToNode(exprsString);
    1286         314 :         pfree(exprsString);
    1287             :     }
    1288             :     else
    1289        3526 :         indexprs = NIL;
    1290             : 
    1291        3840 :     indexpr_item = list_head(indexprs);
    1292             : 
    1293        3840 :     context = deparse_context_for(get_relation_name(indrelid), indrelid);
    1294             : 
    1295             :     /*
    1296             :      * Start the index definition.  Note that the index's name should never be
    1297             :      * schema-qualified, but the indexed rel's name may be.
    1298             :      */
    1299        3840 :     initStringInfo(&buf);
    1300             : 
    1301        3840 :     if (!attrsOnly)
    1302             :     {
    1303        3086 :         if (!isConstraint)
    1304        6036 :             appendStringInfo(&buf, "CREATE %sINDEX %s ON %s%s USING %s (",
    1305        3018 :                              idxrec->indisunique ? "UNIQUE " : "",
    1306        3018 :                              quote_identifier(NameStr(idxrelrec->relname)),
    1307        3018 :                              idxrelrec->relkind == RELKIND_PARTITIONED_INDEX
    1308         364 :                              && !inherits ? "ONLY " : "",
    1309        3018 :                              (prettyFlags & PRETTYFLAG_SCHEMA) ?
    1310         712 :                              generate_relation_name(indrelid, NIL) :
    1311        2306 :                              generate_qualified_relation_name(indrelid),
    1312        3018 :                              quote_identifier(NameStr(amrec->amname)));
    1313             :         else                    /* currently, must be EXCLUDE constraint */
    1314          68 :             appendStringInfo(&buf, "EXCLUDE USING %s (",
    1315          68 :                              quote_identifier(NameStr(amrec->amname)));
    1316             :     }
    1317             : 
    1318             :     /*
    1319             :      * Report the indexed attributes
    1320             :      */
    1321        3840 :     sep = "";
    1322        9324 :     for (keyno = 0; keyno < idxrec->indnatts; keyno++)
    1323             :     {
    1324        5548 :         AttrNumber  attnum = idxrec->indkey.values[keyno];
    1325             :         Oid         keycoltype;
    1326             :         Oid         keycolcollation;
    1327             : 
    1328             :         /*
    1329             :          * Ignore non-key attributes if told to.
    1330             :          */
    1331        5548 :         if (keysOnly && keyno >= idxrec->indnkeyatts)
    1332          64 :             break;
    1333             : 
    1334             :         /* Otherwise, print INCLUDE to divide key and non-key attrs. */
    1335        5484 :         if (!colno && keyno == idxrec->indnkeyatts)
    1336             :         {
    1337         158 :             appendStringInfoString(&buf, ") INCLUDE (");
    1338         158 :             sep = "";
    1339             :         }
    1340             : 
    1341        5484 :         if (!colno)
    1342        5096 :             appendStringInfoString(&buf, sep);
    1343        5484 :         sep = ", ";
    1344             : 
    1345        5484 :         if (attnum != 0)
    1346             :         {
    1347             :             /* Simple index column */
    1348             :             char       *attname;
    1349             :             int32       keycoltypmod;
    1350             : 
    1351        5074 :             attname = get_attname(indrelid, attnum, false);
    1352        5074 :             if (!colno || colno == keyno + 1)
    1353        4978 :                 appendStringInfoString(&buf, quote_identifier(attname));
    1354        5074 :             get_atttypetypmodcoll(indrelid, attnum,
    1355             :                                   &keycoltype, &keycoltypmod,
    1356             :                                   &keycolcollation);
    1357             :         }
    1358             :         else
    1359             :         {
    1360             :             /* expressional index */
    1361             :             Node       *indexkey;
    1362             : 
    1363         410 :             if (indexpr_item == NULL)
    1364           0 :                 elog(ERROR, "too few entries in indexprs list");
    1365         410 :             indexkey = (Node *) lfirst(indexpr_item);
    1366         410 :             indexpr_item = lnext(indexprs, indexpr_item);
    1367             :             /* Deparse */
    1368         410 :             str = deparse_expression_pretty(indexkey, context, false, false,
    1369             :                                             prettyFlags, 0);
    1370         410 :             if (!colno || colno == keyno + 1)
    1371             :             {
    1372             :                 /* Need parens if it's not a bare function call */
    1373         402 :                 if (looks_like_function(indexkey))
    1374          34 :                     appendStringInfoString(&buf, str);
    1375             :                 else
    1376         368 :                     appendStringInfo(&buf, "(%s)", str);
    1377             :             }
    1378         410 :             keycoltype = exprType(indexkey);
    1379         410 :             keycolcollation = exprCollation(indexkey);
    1380             :         }
    1381             : 
    1382             :         /* Print additional decoration for (selected) key columns */
    1383        5484 :         if (!attrsOnly && keyno < idxrec->indnkeyatts &&
    1384           0 :             (!colno || colno == keyno + 1))
    1385             :         {
    1386        4228 :             int16       opt = indoption->values[keyno];
    1387        4228 :             Oid         indcoll = indcollation->values[keyno];
    1388        4228 :             Datum       attoptions = get_attoptions(indexrelid, keyno + 1);
    1389        4228 :             bool        has_options = attoptions != (Datum) 0;
    1390             : 
    1391             :             /* Add collation, if not default for column */
    1392        4228 :             if (OidIsValid(indcoll) && indcoll != keycolcollation)
    1393          48 :                 appendStringInfo(&buf, " COLLATE %s",
    1394             :                                  generate_collation_name((indcoll)));
    1395             : 
    1396             :             /* Add the operator class name, if not default */
    1397        4228 :             get_opclass_name(indclass->values[keyno],
    1398             :                              has_options ? InvalidOid : keycoltype, &buf);
    1399             : 
    1400        4228 :             if (has_options)
    1401             :             {
    1402           8 :                 appendStringInfoString(&buf, " (");
    1403           8 :                 get_reloptions(&buf, attoptions);
    1404           8 :                 appendStringInfoChar(&buf, ')');
    1405             :             }
    1406             : 
    1407             :             /* Add options if relevant */
    1408        4228 :             if (amroutine->amcanorder)
    1409             :             {
    1410             :                 /* if it supports sort ordering, report DESC and NULLS opts */
    1411        3756 :                 if (opt & INDOPTION_DESC)
    1412             :                 {
    1413           0 :                     appendStringInfoString(&buf, " DESC");
    1414             :                     /* NULLS FIRST is the default in this case */
    1415           0 :                     if (!(opt & INDOPTION_NULLS_FIRST))
    1416           0 :                         appendStringInfoString(&buf, " NULLS LAST");
    1417             :                 }
    1418             :                 else
    1419             :                 {
    1420        3756 :                     if (opt & INDOPTION_NULLS_FIRST)
    1421           0 :                         appendStringInfoString(&buf, " NULLS FIRST");
    1422             :                 }
    1423             :             }
    1424             : 
    1425             :             /* Add the exclusion operator if relevant */
    1426        4228 :             if (excludeOps != NULL)
    1427          80 :                 appendStringInfo(&buf, " WITH %s",
    1428          80 :                                  generate_operator_name(excludeOps[keyno],
    1429             :                                                         keycoltype,
    1430             :                                                         keycoltype));
    1431             :         }
    1432             :     }
    1433             : 
    1434        3840 :     if (!attrsOnly)
    1435             :     {
    1436        3086 :         appendStringInfoChar(&buf, ')');
    1437             : 
    1438             :         /*
    1439             :          * If it has options, append "WITH (options)"
    1440             :          */
    1441        3086 :         str = flatten_reloptions(indexrelid);
    1442        3086 :         if (str)
    1443             :         {
    1444          90 :             appendStringInfo(&buf, " WITH (%s)", str);
    1445          90 :             pfree(str);
    1446             :         }
    1447             : 
    1448             :         /*
    1449             :          * Print tablespace, but only if requested
    1450             :          */
    1451        3086 :         if (showTblSpc)
    1452             :         {
    1453             :             Oid         tblspc;
    1454             : 
    1455         128 :             tblspc = get_rel_tablespace(indexrelid);
    1456         128 :             if (OidIsValid(tblspc))
    1457             :             {
    1458          36 :                 if (isConstraint)
    1459           0 :                     appendStringInfoString(&buf, " USING INDEX");
    1460          36 :                 appendStringInfo(&buf, " TABLESPACE %s",
    1461          36 :                                  quote_identifier(get_tablespace_name(tblspc)));
    1462             :             }
    1463             :         }
    1464             : 
    1465             :         /*
    1466             :          * If it's a partial index, decompile and append the predicate
    1467             :          */
    1468        3086 :         if (!heap_attisnull(ht_idx, Anum_pg_index_indpred, NULL))
    1469             :         {
    1470             :             Node       *node;
    1471             :             Datum       predDatum;
    1472             :             bool        isnull;
    1473             :             char       *predString;
    1474             : 
    1475             :             /* Convert text string to node tree */
    1476         192 :             predDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
    1477             :                                         Anum_pg_index_indpred, &isnull);
    1478             :             Assert(!isnull);
    1479         192 :             predString = TextDatumGetCString(predDatum);
    1480         192 :             node = (Node *) stringToNode(predString);
    1481         192 :             pfree(predString);
    1482             : 
    1483             :             /* Deparse */
    1484         192 :             str = deparse_expression_pretty(node, context, false, false,
    1485             :                                             prettyFlags, 0);
    1486         192 :             if (isConstraint)
    1487          28 :                 appendStringInfo(&buf, " WHERE (%s)", str);
    1488             :             else
    1489         164 :                 appendStringInfo(&buf, " WHERE %s", str);
    1490             :         }
    1491             :     }
    1492             : 
    1493             :     /* Clean up */
    1494        3840 :     ReleaseSysCache(ht_idx);
    1495        3840 :     ReleaseSysCache(ht_idxrel);
    1496        3840 :     ReleaseSysCache(ht_am);
    1497             : 
    1498        3840 :     return buf.data;
    1499             : }
    1500             : 
    1501             : /*
    1502             :  * pg_get_statisticsobjdef
    1503             :  *      Get the definition of an extended statistics object
    1504             :  */
    1505             : Datum
    1506         120 : pg_get_statisticsobjdef(PG_FUNCTION_ARGS)
    1507             : {
    1508         120 :     Oid         statextid = PG_GETARG_OID(0);
    1509             :     char       *res;
    1510             : 
    1511         120 :     res = pg_get_statisticsobj_worker(statextid, true);
    1512             : 
    1513         120 :     if (res == NULL)
    1514           4 :         PG_RETURN_NULL();
    1515             : 
    1516         116 :     PG_RETURN_TEXT_P(string_to_text(res));
    1517             : }
    1518             : 
    1519             : /*
    1520             :  * Internal workhorse to decompile an extended statistics object.
    1521             :  */
    1522             : static char *
    1523         120 : pg_get_statisticsobj_worker(Oid statextid, bool missing_ok)
    1524             : {
    1525             :     Form_pg_statistic_ext statextrec;
    1526             :     HeapTuple   statexttup;
    1527             :     StringInfoData buf;
    1528             :     int         colno;
    1529             :     char       *nsp;
    1530             :     ArrayType  *arr;
    1531             :     char       *enabled;
    1532             :     Datum       datum;
    1533             :     bool        isnull;
    1534             :     bool        ndistinct_enabled;
    1535             :     bool        dependencies_enabled;
    1536             :     bool        mcv_enabled;
    1537             :     int         i;
    1538             : 
    1539         120 :     statexttup = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(statextid));
    1540             : 
    1541         120 :     if (!HeapTupleIsValid(statexttup))
    1542             :     {
    1543           4 :         if (missing_ok)
    1544           4 :             return NULL;
    1545           0 :         elog(ERROR, "cache lookup failed for statistics object %u", statextid);
    1546             :     }
    1547             : 
    1548         116 :     statextrec = (Form_pg_statistic_ext) GETSTRUCT(statexttup);
    1549             : 
    1550         116 :     initStringInfo(&buf);
    1551             : 
    1552         116 :     nsp = get_namespace_name(statextrec->stxnamespace);
    1553         116 :     appendStringInfo(&buf, "CREATE STATISTICS %s",
    1554             :                      quote_qualified_identifier(nsp,
    1555         116 :                                                 NameStr(statextrec->stxname)));
    1556             : 
    1557             :     /*
    1558             :      * Decode the stxkind column so that we know which stats types to print.
    1559             :      */
    1560         116 :     datum = SysCacheGetAttr(STATEXTOID, statexttup,
    1561             :                             Anum_pg_statistic_ext_stxkind, &isnull);
    1562             :     Assert(!isnull);
    1563         116 :     arr = DatumGetArrayTypeP(datum);
    1564         116 :     if (ARR_NDIM(arr) != 1 ||
    1565         116 :         ARR_HASNULL(arr) ||
    1566         116 :         ARR_ELEMTYPE(arr) != CHAROID)
    1567           0 :         elog(ERROR, "stxkind is not a 1-D char array");
    1568         116 :     enabled = (char *) ARR_DATA_PTR(arr);
    1569             : 
    1570         116 :     ndistinct_enabled = false;
    1571         116 :     dependencies_enabled = false;
    1572         116 :     mcv_enabled = false;
    1573             : 
    1574         328 :     for (i = 0; i < ARR_DIMS(arr)[0]; i++)
    1575             :     {
    1576         212 :         if (enabled[i] == STATS_EXT_NDISTINCT)
    1577          92 :             ndistinct_enabled = true;
    1578         212 :         if (enabled[i] == STATS_EXT_DEPENDENCIES)
    1579          54 :             dependencies_enabled = true;
    1580         212 :         if (enabled[i] == STATS_EXT_MCV)
    1581          66 :             mcv_enabled = true;
    1582             :     }
    1583             : 
    1584             :     /*
    1585             :      * If any option is disabled, then we'll need to append the types clause
    1586             :      * to show which options are enabled.  We omit the types clause on purpose
    1587             :      * when all options are enabled, so a pg_dump/pg_restore will create all
    1588             :      * statistics types on a newer postgres version, if the statistics had all
    1589             :      * options enabled on the original version.
    1590             :      */
    1591         116 :     if (!ndistinct_enabled || !dependencies_enabled || !mcv_enabled)
    1592             :     {
    1593          68 :         bool        gotone = false;
    1594             : 
    1595          68 :         appendStringInfoString(&buf, " (");
    1596             : 
    1597          68 :         if (ndistinct_enabled)
    1598             :         {
    1599          44 :             appendStringInfoString(&buf, "ndistinct");
    1600          44 :             gotone = true;
    1601             :         }
    1602             : 
    1603          68 :         if (dependencies_enabled)
    1604             :         {
    1605           6 :             appendStringInfo(&buf, "%sdependencies", gotone ? ", " : "");
    1606           6 :             gotone = true;
    1607             :         }
    1608             : 
    1609          68 :         if (mcv_enabled)
    1610          18 :             appendStringInfo(&buf, "%smcv", gotone ? ", " : "");
    1611             : 
    1612          68 :         appendStringInfoChar(&buf, ')');
    1613             :     }
    1614             : 
    1615         116 :     appendStringInfoString(&buf, " ON ");
    1616             : 
    1617         372 :     for (colno = 0; colno < statextrec->stxkeys.dim1; colno++)
    1618             :     {
    1619         256 :         AttrNumber  attnum = statextrec->stxkeys.values[colno];
    1620             :         char       *attname;
    1621             : 
    1622         256 :         if (colno > 0)
    1623         140 :             appendStringInfoString(&buf, ", ");
    1624             : 
    1625         256 :         attname = get_attname(statextrec->stxrelid, attnum, false);
    1626             : 
    1627         256 :         appendStringInfoString(&buf, quote_identifier(attname));
    1628             :     }
    1629             : 
    1630         116 :     appendStringInfo(&buf, " FROM %s",
    1631             :                      generate_relation_name(statextrec->stxrelid, NIL));
    1632             : 
    1633         116 :     ReleaseSysCache(statexttup);
    1634             : 
    1635         116 :     return buf.data;
    1636             : }
    1637             : 
    1638             : /*
    1639             :  * pg_get_partkeydef
    1640             :  *
    1641             :  * Returns the partition key specification, ie, the following:
    1642             :  *
    1643             :  * PARTITION BY { RANGE | LIST | HASH } (column opt_collation opt_opclass [, ...])
    1644             :  */
    1645             : Datum
    1646       37678 : pg_get_partkeydef(PG_FUNCTION_ARGS)
    1647             : {
    1648       37678 :     Oid         relid = PG_GETARG_OID(0);
    1649             :     char       *res;
    1650             : 
    1651       37678 :     res = pg_get_partkeydef_worker(relid, PRETTYFLAG_INDENT, false, true);
    1652             : 
    1653       37678 :     if (res == NULL)
    1654       36992 :         PG_RETURN_NULL();
    1655             : 
    1656         686 :     PG_RETURN_TEXT_P(string_to_text(res));
    1657             : }
    1658             : 
    1659             : /* Internal version that just reports the column definitions */
    1660             : char *
    1661          76 : pg_get_partkeydef_columns(Oid relid, bool pretty)
    1662             : {
    1663             :     int         prettyFlags;
    1664             : 
    1665          76 :     prettyFlags = pretty ? (PRETTYFLAG_PAREN | PRETTYFLAG_INDENT | PRETTYFLAG_SCHEMA) : PRETTYFLAG_INDENT;
    1666             : 
    1667          76 :     return pg_get_partkeydef_worker(relid, prettyFlags, true, false);
    1668             : }
    1669             : 
    1670             : /*
    1671             :  * Internal workhorse to decompile a partition key definition.
    1672             :  */
    1673             : static char *
    1674       37754 : pg_get_partkeydef_worker(Oid relid, int prettyFlags,
    1675             :                          bool attrsOnly, bool missing_ok)
    1676             : {
    1677             :     Form_pg_partitioned_table form;
    1678             :     HeapTuple   tuple;
    1679             :     oidvector  *partclass;
    1680             :     oidvector  *partcollation;
    1681             :     List       *partexprs;
    1682             :     ListCell   *partexpr_item;
    1683             :     List       *context;
    1684             :     Datum       datum;
    1685             :     bool        isnull;
    1686             :     StringInfoData buf;
    1687             :     int         keyno;
    1688             :     char       *str;
    1689             :     char       *sep;
    1690             : 
    1691       37754 :     tuple = SearchSysCache1(PARTRELID, ObjectIdGetDatum(relid));
    1692       37754 :     if (!HeapTupleIsValid(tuple))
    1693             :     {
    1694       36992 :         if (missing_ok)
    1695       36992 :             return NULL;
    1696           0 :         elog(ERROR, "cache lookup failed for partition key of %u", relid);
    1697             :     }
    1698             : 
    1699         762 :     form = (Form_pg_partitioned_table) GETSTRUCT(tuple);
    1700             : 
    1701             :     Assert(form->partrelid == relid);
    1702             : 
    1703             :     /* Must get partclass and partcollation the hard way */
    1704         762 :     datum = SysCacheGetAttr(PARTRELID, tuple,
    1705             :                             Anum_pg_partitioned_table_partclass, &isnull);
    1706             :     Assert(!isnull);
    1707         762 :     partclass = (oidvector *) DatumGetPointer(datum);
    1708             : 
    1709         762 :     datum = SysCacheGetAttr(PARTRELID, tuple,
    1710             :                             Anum_pg_partitioned_table_partcollation, &isnull);
    1711             :     Assert(!isnull);
    1712         762 :     partcollation = (oidvector *) DatumGetPointer(datum);
    1713             : 
    1714             : 
    1715             :     /*
    1716             :      * Get the expressions, if any.  (NOTE: we do not use the relcache
    1717             :      * versions of the expressions, because we want to display
    1718             :      * non-const-folded expressions.)
    1719             :      */
    1720         762 :     if (!heap_attisnull(tuple, Anum_pg_partitioned_table_partexprs, NULL))
    1721             :     {
    1722             :         Datum       exprsDatum;
    1723             :         bool        isnull;
    1724             :         char       *exprsString;
    1725             : 
    1726          92 :         exprsDatum = SysCacheGetAttr(PARTRELID, tuple,
    1727             :                                      Anum_pg_partitioned_table_partexprs, &isnull);
    1728             :         Assert(!isnull);
    1729          92 :         exprsString = TextDatumGetCString(exprsDatum);
    1730          92 :         partexprs = (List *) stringToNode(exprsString);
    1731             : 
    1732          92 :         if (!IsA(partexprs, List))
    1733           0 :             elog(ERROR, "unexpected node type found in partexprs: %d",
    1734             :                  (int) nodeTag(partexprs));
    1735             : 
    1736          92 :         pfree(exprsString);
    1737             :     }
    1738             :     else
    1739         670 :         partexprs = NIL;
    1740             : 
    1741         762 :     partexpr_item = list_head(partexprs);
    1742         762 :     context = deparse_context_for(get_relation_name(relid), relid);
    1743             : 
    1744         762 :     initStringInfo(&buf);
    1745             : 
    1746         762 :     switch (form->partstrat)
    1747             :     {
    1748          22 :         case PARTITION_STRATEGY_HASH:
    1749          22 :             if (!attrsOnly)
    1750          22 :                 appendStringInfoString(&buf, "HASH");
    1751          22 :             break;
    1752         234 :         case PARTITION_STRATEGY_LIST:
    1753         234 :             if (!attrsOnly)
    1754         222 :                 appendStringInfoString(&buf, "LIST");
    1755         234 :             break;
    1756         506 :         case PARTITION_STRATEGY_RANGE:
    1757         506 :             if (!attrsOnly)
    1758         442 :                 appendStringInfoString(&buf, "RANGE");
    1759         506 :             break;
    1760           0 :         default:
    1761           0 :             elog(ERROR, "unexpected partition strategy: %d",
    1762             :                  (int) form->partstrat);
    1763             :     }
    1764             : 
    1765         762 :     if (!attrsOnly)
    1766         686 :         appendStringInfoString(&buf, " (");
    1767         762 :     sep = "";
    1768        1622 :     for (keyno = 0; keyno < form->partnatts; keyno++)
    1769             :     {
    1770         860 :         AttrNumber  attnum = form->partattrs.values[keyno];
    1771             :         Oid         keycoltype;
    1772             :         Oid         keycolcollation;
    1773             :         Oid         partcoll;
    1774             : 
    1775         860 :         appendStringInfoString(&buf, sep);
    1776         860 :         sep = ", ";
    1777         860 :         if (attnum != 0)
    1778             :         {
    1779             :             /* Simple attribute reference */
    1780             :             char       *attname;
    1781             :             int32       keycoltypmod;
    1782             : 
    1783         760 :             attname = get_attname(relid, attnum, false);
    1784         760 :             appendStringInfoString(&buf, quote_identifier(attname));
    1785         760 :             get_atttypetypmodcoll(relid, attnum,
    1786             :                                   &keycoltype, &keycoltypmod,
    1787             :                                   &keycolcollation);
    1788             :         }
    1789             :         else
    1790             :         {
    1791             :             /* Expression */
    1792             :             Node       *partkey;
    1793             : 
    1794         100 :             if (partexpr_item == NULL)
    1795           0 :                 elog(ERROR, "too few entries in partexprs list");
    1796         100 :             partkey = (Node *) lfirst(partexpr_item);
    1797         100 :             partexpr_item = lnext(partexprs, partexpr_item);
    1798             : 
    1799             :             /* Deparse */
    1800         100 :             str = deparse_expression_pretty(partkey, context, false, false,
    1801             :                                             prettyFlags, 0);
    1802             :             /* Need parens if it's not a bare function call */
    1803         100 :             if (looks_like_function(partkey))
    1804          36 :                 appendStringInfoString(&buf, str);
    1805             :             else
    1806          64 :                 appendStringInfo(&buf, "(%s)", str);
    1807             : 
    1808         100 :             keycoltype = exprType(partkey);
    1809         100 :             keycolcollation = exprCollation(partkey);
    1810             :         }
    1811             : 
    1812             :         /* Add collation, if not default for column */
    1813         860 :         partcoll = partcollation->values[keyno];
    1814         860 :         if (!attrsOnly && OidIsValid(partcoll) && partcoll != keycolcollation)
    1815           4 :             appendStringInfo(&buf, " COLLATE %s",
    1816             :                              generate_collation_name((partcoll)));
    1817             : 
    1818             :         /* Add the operator class name, if not default */
    1819         860 :         if (!attrsOnly)
    1820         748 :             get_opclass_name(partclass->values[keyno], keycoltype, &buf);
    1821             :     }
    1822             : 
    1823         762 :     if (!attrsOnly)
    1824         686 :         appendStringInfoChar(&buf, ')');
    1825             : 
    1826             :     /* Clean up */
    1827         762 :     ReleaseSysCache(tuple);
    1828             : 
    1829         762 :     return buf.data;
    1830             : }
    1831             : 
    1832             : /*
    1833             :  * pg_get_partition_constraintdef
    1834             :  *
    1835             :  * Returns partition constraint expression as a string for the input relation
    1836             :  */
    1837             : Datum
    1838         104 : pg_get_partition_constraintdef(PG_FUNCTION_ARGS)
    1839             : {
    1840         104 :     Oid         relationId = PG_GETARG_OID(0);
    1841             :     Expr       *constr_expr;
    1842             :     int         prettyFlags;
    1843             :     List       *context;
    1844             :     char       *consrc;
    1845             : 
    1846         104 :     constr_expr = get_partition_qual_relid(relationId);
    1847             : 
    1848             :     /* Quick exit if no partition constraint */
    1849         104 :     if (constr_expr == NULL)
    1850          12 :         PG_RETURN_NULL();
    1851             : 
    1852             :     /*
    1853             :      * Deparse and return the constraint expression.
    1854             :      */
    1855          92 :     prettyFlags = PRETTYFLAG_INDENT;
    1856          92 :     context = deparse_context_for(get_relation_name(relationId), relationId);
    1857          92 :     consrc = deparse_expression_pretty((Node *) constr_expr, context, false,
    1858             :                                        false, prettyFlags, 0);
    1859             : 
    1860          92 :     PG_RETURN_TEXT_P(string_to_text(consrc));
    1861             : }
    1862             : 
    1863             : /*
    1864             :  * pg_get_partconstrdef_string
    1865             :  *
    1866             :  * Returns the partition constraint as a C-string for the input relation, with
    1867             :  * the given alias.  No pretty-printing.
    1868             :  */
    1869             : char *
    1870          24 : pg_get_partconstrdef_string(Oid partitionId, char *aliasname)
    1871             : {
    1872             :     Expr       *constr_expr;
    1873             :     List       *context;
    1874             : 
    1875          24 :     constr_expr = get_partition_qual_relid(partitionId);
    1876          24 :     context = deparse_context_for(aliasname, partitionId);
    1877             : 
    1878          24 :     return deparse_expression((Node *) constr_expr, context, true, false);
    1879             : }
    1880             : 
    1881             : /*
    1882             :  * pg_get_constraintdef
    1883             :  *
    1884             :  * Returns the definition for the constraint, ie, everything that needs to
    1885             :  * appear after "ALTER TABLE ... ADD CONSTRAINT <constraintname>".
    1886             :  */
    1887             : Datum
    1888         846 : pg_get_constraintdef(PG_FUNCTION_ARGS)
    1889             : {
    1890         846 :     Oid         constraintId = PG_GETARG_OID(0);
    1891             :     int         prettyFlags;
    1892             :     char       *res;
    1893             : 
    1894         846 :     prettyFlags = PRETTYFLAG_INDENT;
    1895             : 
    1896         846 :     res = pg_get_constraintdef_worker(constraintId, false, prettyFlags, true);
    1897             : 
    1898         846 :     if (res == NULL)
    1899           4 :         PG_RETURN_NULL();
    1900             : 
    1901         842 :     PG_RETURN_TEXT_P(string_to_text(res));
    1902             : }
    1903             : 
    1904             : Datum
    1905        1580 : pg_get_constraintdef_ext(PG_FUNCTION_ARGS)
    1906             : {
    1907        1580 :     Oid         constraintId = PG_GETARG_OID(0);
    1908        1580 :     bool        pretty = PG_GETARG_BOOL(1);
    1909             :     int         prettyFlags;
    1910             :     char       *res;
    1911             : 
    1912        1580 :     prettyFlags = pretty ? (PRETTYFLAG_PAREN | PRETTYFLAG_INDENT | PRETTYFLAG_SCHEMA) : PRETTYFLAG_INDENT;
    1913             : 
    1914        1580 :     res = pg_get_constraintdef_worker(constraintId, false, prettyFlags, true);
    1915             : 
    1916        1580 :     if (res == NULL)
    1917           0 :         PG_RETURN_NULL();
    1918             : 
    1919        1580 :     PG_RETURN_TEXT_P(string_to_text(res));
    1920             : }
    1921             : 
    1922             : /*
    1923             :  * Internal version that returns a full ALTER TABLE ... ADD CONSTRAINT command
    1924             :  */
    1925             : char *
    1926         200 : pg_get_constraintdef_command(Oid constraintId)
    1927             : {
    1928         200 :     return pg_get_constraintdef_worker(constraintId, true, 0, false);
    1929             : }
    1930             : 
    1931             : /*
    1932             :  * As of 9.4, we now use an MVCC snapshot for this.
    1933             :  */
    1934             : static char *
    1935        2626 : pg_get_constraintdef_worker(Oid constraintId, bool fullCommand,
    1936             :                             int prettyFlags, bool missing_ok)
    1937             : {
    1938             :     HeapTuple   tup;
    1939             :     Form_pg_constraint conForm;
    1940             :     StringInfoData buf;
    1941             :     SysScanDesc scandesc;
    1942             :     ScanKeyData scankey[1];
    1943        2626 :     Snapshot    snapshot = RegisterSnapshot(GetTransactionSnapshot());
    1944        2626 :     Relation    relation = table_open(ConstraintRelationId, AccessShareLock);
    1945             : 
    1946        2626 :     ScanKeyInit(&scankey[0],
    1947             :                 Anum_pg_constraint_oid,
    1948             :                 BTEqualStrategyNumber, F_OIDEQ,
    1949             :                 ObjectIdGetDatum(constraintId));
    1950             : 
    1951        2626 :     scandesc = systable_beginscan(relation,
    1952             :                                   ConstraintOidIndexId,
    1953             :                                   true,
    1954             :                                   snapshot,
    1955             :                                   1,
    1956             :                                   scankey);
    1957             : 
    1958             :     /*
    1959             :      * We later use the tuple with SysCacheGetAttr() as if we had obtained it
    1960             :      * via SearchSysCache, which works fine.
    1961             :      */
    1962        2626 :     tup = systable_getnext(scandesc);
    1963             : 
    1964        2626 :     UnregisterSnapshot(snapshot);
    1965             : 
    1966        2626 :     if (!HeapTupleIsValid(tup))
    1967             :     {
    1968           4 :         if (missing_ok)
    1969             :         {
    1970           4 :             systable_endscan(scandesc);
    1971           4 :             table_close(relation, AccessShareLock);
    1972           4 :             return NULL;
    1973             :         }
    1974           0 :         elog(ERROR, "could not find tuple for constraint %u", constraintId);
    1975             :     }
    1976             : 
    1977        2622 :     conForm = (Form_pg_constraint) GETSTRUCT(tup);
    1978             : 
    1979        2622 :     initStringInfo(&buf);
    1980             : 
    1981        2622 :     if (fullCommand)
    1982             :     {
    1983         200 :         if (OidIsValid(conForm->conrelid))
    1984             :         {
    1985             :             /*
    1986             :              * Currently, callers want ALTER TABLE (without ONLY) for CHECK
    1987             :              * constraints, and other types of constraints don't inherit
    1988             :              * anyway so it doesn't matter whether we say ONLY or not. Someday
    1989             :              * we might need to let callers specify whether to put ONLY in the
    1990             :              * command.
    1991             :              */
    1992         192 :             appendStringInfo(&buf, "ALTER TABLE %s ADD CONSTRAINT %s ",
    1993             :                              generate_qualified_relation_name(conForm->conrelid),
    1994         192 :                              quote_identifier(NameStr(conForm->conname)));
    1995             :         }
    1996             :         else
    1997             :         {
    1998             :             /* Must be a domain constraint */
    1999             :             Assert(OidIsValid(conForm->contypid));
    2000           8 :             appendStringInfo(&buf, "ALTER DOMAIN %s ADD CONSTRAINT %s ",
    2001             :                              generate_qualified_type_name(conForm->contypid),
    2002           8 :                              quote_identifier(NameStr(conForm->conname)));
    2003             :         }
    2004             :     }
    2005             : 
    2006        2622 :     switch (conForm->contype)
    2007             :     {
    2008         342 :         case CONSTRAINT_FOREIGN:
    2009             :             {
    2010             :                 Datum       val;
    2011             :                 bool        isnull;
    2012             :                 const char *string;
    2013             : 
    2014             :                 /* Start off the constraint definition */
    2015         342 :                 appendStringInfoString(&buf, "FOREIGN KEY (");
    2016             : 
    2017             :                 /* Fetch and build referencing-column list */
    2018         342 :                 val = SysCacheGetAttr(CONSTROID, tup,
    2019             :                                       Anum_pg_constraint_conkey, &isnull);
    2020         342 :                 if (isnull)
    2021           0 :                     elog(ERROR, "null conkey for constraint %u",
    2022             :                          constraintId);
    2023             : 
    2024         342 :                 decompile_column_index_array(val, conForm->conrelid, &buf);
    2025             : 
    2026             :                 /* add foreign relation name */
    2027         342 :                 appendStringInfo(&buf, ") REFERENCES %s(",
    2028             :                                  generate_relation_name(conForm->confrelid,
    2029             :                                                         NIL));
    2030             : 
    2031             :                 /* Fetch and build referenced-column list */
    2032         342 :                 val = SysCacheGetAttr(CONSTROID, tup,
    2033             :                                       Anum_pg_constraint_confkey, &isnull);
    2034         342 :                 if (isnull)
    2035           0 :                     elog(ERROR, "null confkey for constraint %u",
    2036             :                          constraintId);
    2037             : 
    2038         342 :                 decompile_column_index_array(val, conForm->confrelid, &buf);
    2039             : 
    2040         342 :                 appendStringInfoChar(&buf, ')');
    2041             : 
    2042             :                 /* Add match type */
    2043         342 :                 switch (conForm->confmatchtype)
    2044             :                 {
    2045          22 :                     case FKCONSTR_MATCH_FULL:
    2046          22 :                         string = " MATCH FULL";
    2047          22 :                         break;
    2048           0 :                     case FKCONSTR_MATCH_PARTIAL:
    2049           0 :                         string = " MATCH PARTIAL";
    2050           0 :                         break;
    2051         320 :                     case FKCONSTR_MATCH_SIMPLE:
    2052         320 :                         string = "";
    2053         320 :                         break;
    2054           0 :                     default:
    2055           0 :                         elog(ERROR, "unrecognized confmatchtype: %d",
    2056             :                              conForm->confmatchtype);
    2057             :                         string = "";  /* keep compiler quiet */
    2058             :                         break;
    2059             :                 }
    2060         342 :                 appendStringInfoString(&buf, string);
    2061             : 
    2062             :                 /* Add ON UPDATE and ON DELETE clauses, if needed */
    2063         342 :                 switch (conForm->confupdtype)
    2064             :                 {
    2065         262 :                     case FKCONSTR_ACTION_NOACTION:
    2066         262 :                         string = NULL;  /* suppress default */
    2067         262 :                         break;
    2068           0 :                     case FKCONSTR_ACTION_RESTRICT:
    2069           0 :                         string = "RESTRICT";
    2070           0 :                         break;
    2071          62 :                     case FKCONSTR_ACTION_CASCADE:
    2072          62 :                         string = "CASCADE";
    2073          62 :                         break;
    2074          18 :                     case FKCONSTR_ACTION_SETNULL:
    2075          18 :                         string = "SET NULL";
    2076          18 :                         break;
    2077           0 :                     case FKCONSTR_ACTION_SETDEFAULT:
    2078           0 :                         string = "SET DEFAULT";
    2079           0 :                         break;
    2080           0 :                     default:
    2081           0 :                         elog(ERROR, "unrecognized confupdtype: %d",
    2082             :                              conForm->confupdtype);
    2083             :                         string = NULL;  /* keep compiler quiet */
    2084             :                         break;
    2085             :                 }
    2086         342 :                 if (string)
    2087          80 :                     appendStringInfo(&buf, " ON UPDATE %s", string);
    2088             : 
    2089         342 :                 switch (conForm->confdeltype)
    2090             :                 {
    2091         272 :                     case FKCONSTR_ACTION_NOACTION:
    2092         272 :                         string = NULL;  /* suppress default */
    2093         272 :                         break;
    2094           0 :                     case FKCONSTR_ACTION_RESTRICT:
    2095           0 :                         string = "RESTRICT";
    2096           0 :                         break;
    2097          62 :                     case FKCONSTR_ACTION_CASCADE:
    2098          62 :                         string = "CASCADE";
    2099          62 :                         break;
    2100           8 :                     case FKCONSTR_ACTION_SETNULL:
    2101           8 :                         string = "SET NULL";
    2102           8 :                         break;
    2103           0 :                     case FKCONSTR_ACTION_SETDEFAULT:
    2104           0 :                         string = "SET DEFAULT";
    2105           0 :                         break;
    2106           0 :                     default:
    2107           0 :                         elog(ERROR, "unrecognized confdeltype: %d",
    2108             :                              conForm->confdeltype);
    2109             :                         string = NULL;  /* keep compiler quiet */
    2110             :                         break;
    2111             :                 }
    2112         342 :                 if (string)
    2113          70 :                     appendStringInfo(&buf, " ON DELETE %s", string);
    2114             : 
    2115         342 :                 break;
    2116             :             }
    2117        1208 :         case CONSTRAINT_PRIMARY:
    2118             :         case CONSTRAINT_UNIQUE:
    2119             :             {
    2120             :                 Datum       val;
    2121             :                 bool        isnull;
    2122             :                 Oid         indexId;
    2123             :                 int         keyatts;
    2124             :                 HeapTuple   indtup;
    2125             : 
    2126             :                 /* Start off the constraint definition */
    2127        1208 :                 if (conForm->contype == CONSTRAINT_PRIMARY)
    2128        1040 :                     appendStringInfoString(&buf, "PRIMARY KEY (");
    2129             :                 else
    2130         168 :                     appendStringInfoString(&buf, "UNIQUE (");
    2131             : 
    2132             :                 /* Fetch and build target column list */
    2133        1208 :                 val = SysCacheGetAttr(CONSTROID, tup,
    2134             :                                       Anum_pg_constraint_conkey, &isnull);
    2135        1208 :                 if (isnull)
    2136           0 :                     elog(ERROR, "null conkey for constraint %u",
    2137             :                          constraintId);
    2138             : 
    2139        1208 :                 keyatts = decompile_column_index_array(val, conForm->conrelid, &buf);
    2140             : 
    2141        1208 :                 appendStringInfoChar(&buf, ')');
    2142             : 
    2143        1208 :                 indexId = get_constraint_index(constraintId);
    2144             : 
    2145             :                 /* Build including column list (from pg_index.indkeys) */
    2146        1208 :                 indtup = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexId));
    2147        1208 :                 if (!HeapTupleIsValid(indtup))
    2148           0 :                     elog(ERROR, "cache lookup failed for index %u", indexId);
    2149        1208 :                 val = SysCacheGetAttr(INDEXRELID, indtup,
    2150             :                                       Anum_pg_index_indnatts, &isnull);
    2151        1208 :                 if (isnull)
    2152           0 :                     elog(ERROR, "null indnatts for index %u", indexId);
    2153        1208 :                 if (DatumGetInt32(val) > keyatts)
    2154             :                 {
    2155             :                     Datum       cols;
    2156             :                     Datum      *keys;
    2157             :                     int         nKeys;
    2158             :                     int         j;
    2159             : 
    2160          52 :                     appendStringInfoString(&buf, " INCLUDE (");
    2161             : 
    2162          52 :                     cols = SysCacheGetAttr(INDEXRELID, indtup,
    2163             :                                            Anum_pg_index_indkey, &isnull);
    2164          52 :                     if (isnull)
    2165           0 :                         elog(ERROR, "null indkey for index %u", indexId);
    2166             : 
    2167          52 :                     deconstruct_array(DatumGetArrayTypeP(cols),
    2168             :                                       INT2OID, 2, true, TYPALIGN_SHORT,
    2169             :                                       &keys, NULL, &nKeys);
    2170             : 
    2171         156 :                     for (j = keyatts; j < nKeys; j++)
    2172             :                     {
    2173             :                         char       *colName;
    2174             : 
    2175         104 :                         colName = get_attname(conForm->conrelid,
    2176         104 :                                               DatumGetInt16(keys[j]), false);
    2177         104 :                         if (j > keyatts)
    2178          52 :                             appendStringInfoString(&buf, ", ");
    2179         104 :                         appendStringInfoString(&buf, quote_identifier(colName));
    2180             :                     }
    2181             : 
    2182          52 :                     appendStringInfoChar(&buf, ')');
    2183             :                 }
    2184        1208 :                 ReleaseSysCache(indtup);
    2185             : 
    2186             :                 /* XXX why do we only print these bits if fullCommand? */
    2187        1208 :                 if (fullCommand && OidIsValid(indexId))
    2188             :                 {
    2189         108 :                     char       *options = flatten_reloptions(indexId);
    2190             :                     Oid         tblspc;
    2191             : 
    2192         108 :                     if (options)
    2193             :                     {
    2194           0 :                         appendStringInfo(&buf, " WITH (%s)", options);
    2195           0 :                         pfree(options);
    2196             :                     }
    2197             : 
    2198             :                     /*
    2199             :                      * Print the tablespace, unless it's the database default.
    2200             :                      * This is to help ALTER TABLE usage of this facility,
    2201             :                      * which needs this behavior to recreate exact catalog
    2202             :                      * state.
    2203             :                      */
    2204         108 :                     tblspc = get_rel_tablespace(indexId);
    2205         108 :                     if (OidIsValid(tblspc))
    2206          16 :                         appendStringInfo(&buf, " USING INDEX TABLESPACE %s",
    2207          16 :                                          quote_identifier(get_tablespace_name(tblspc)));
    2208             :                 }
    2209             : 
    2210        1208 :                 break;
    2211             :             }
    2212        1004 :         case CONSTRAINT_CHECK:
    2213             :             {
    2214             :                 Datum       val;
    2215             :                 bool        isnull;
    2216             :                 char       *conbin;
    2217             :                 char       *consrc;
    2218             :                 Node       *expr;
    2219             :                 List       *context;
    2220             : 
    2221             :                 /* Fetch constraint expression in parsetree form */
    2222        1004 :                 val = SysCacheGetAttr(CONSTROID, tup,
    2223             :                                       Anum_pg_constraint_conbin, &isnull);
    2224        1004 :                 if (isnull)
    2225           0 :                     elog(ERROR, "null conbin for constraint %u",
    2226             :                          constraintId);
    2227             : 
    2228        1004 :                 conbin = TextDatumGetCString(val);
    2229        1004 :                 expr = stringToNode(conbin);
    2230             : 
    2231             :                 /* Set up deparsing context for Var nodes in constraint */
    2232        1004 :                 if (conForm->conrelid != InvalidOid)
    2233             :                 {
    2234             :                     /* relation constraint */
    2235         894 :                     context = deparse_context_for(get_relation_name(conForm->conrelid),
    2236             :                                                   conForm->conrelid);
    2237             :                 }
    2238             :                 else
    2239             :                 {
    2240             :                     /* domain constraint --- can't have Vars */
    2241         110 :                     context = NIL;
    2242             :                 }
    2243             : 
    2244        1004 :                 consrc = deparse_expression_pretty(expr, context, false, false,
    2245             :                                                    prettyFlags, 0);
    2246             : 
    2247             :                 /*
    2248             :                  * Now emit the constraint definition, adding NO INHERIT if
    2249             :                  * necessary.
    2250             :                  *
    2251             :                  * There are cases where the constraint expression will be
    2252             :                  * fully parenthesized and we don't need the outer parens ...
    2253             :                  * but there are other cases where we do need 'em.  Be
    2254             :                  * conservative for now.
    2255             :                  *
    2256             :                  * Note that simply checking for leading '(' and trailing ')'
    2257             :                  * would NOT be good enough, consider "(x > 0) AND (y > 0)".
    2258             :                  */
    2259        1004 :                 appendStringInfo(&buf, "CHECK (%s)%s",
    2260             :                                  consrc,
    2261        1004 :                                  conForm->connoinherit ? " NO INHERIT" : "");
    2262        1004 :                 break;
    2263             :             }
    2264           0 :         case CONSTRAINT_TRIGGER:
    2265             : 
    2266             :             /*
    2267             :              * There isn't an ALTER TABLE syntax for creating a user-defined
    2268             :              * constraint trigger, but it seems better to print something than
    2269             :              * throw an error; if we throw error then this function couldn't
    2270             :              * safely be applied to all rows of pg_constraint.
    2271             :              */
    2272           0 :             appendStringInfoString(&buf, "TRIGGER");
    2273           0 :             break;
    2274          68 :         case CONSTRAINT_EXCLUSION:
    2275             :             {
    2276          68 :                 Oid         indexOid = conForm->conindid;
    2277             :                 Datum       val;
    2278             :                 bool        isnull;
    2279             :                 Datum      *elems;
    2280             :                 int         nElems;
    2281             :                 int         i;
    2282             :                 Oid        *operators;
    2283             : 
    2284             :                 /* Extract operator OIDs from the pg_constraint tuple */
    2285          68 :                 val = SysCacheGetAttr(CONSTROID, tup,
    2286             :                                       Anum_pg_constraint_conexclop,
    2287             :                                       &isnull);
    2288          68 :                 if (isnull)
    2289           0 :                     elog(ERROR, "null conexclop for constraint %u",
    2290             :                          constraintId);
    2291             : 
    2292          68 :                 deconstruct_array(DatumGetArrayTypeP(val),
    2293             :                                   OIDOID, sizeof(Oid), true, TYPALIGN_INT,
    2294             :                                   &elems, NULL, &nElems);
    2295             : 
    2296          68 :                 operators = (Oid *) palloc(nElems * sizeof(Oid));
    2297         148 :                 for (i = 0; i < nElems; i++)
    2298          80 :                     operators[i] = DatumGetObjectId(elems[i]);
    2299             : 
    2300             :                 /* pg_get_indexdef_worker does the rest */
    2301             :                 /* suppress tablespace because pg_dump wants it that way */
    2302          68 :                 appendStringInfoString(&buf,
    2303          68 :                                        pg_get_indexdef_worker(indexOid,
    2304             :                                                               0,
    2305             :                                                               operators,
    2306             :                                                               false,
    2307             :                                                               false,
    2308             :                                                               false,
    2309             :                                                               false,
    2310             :                                                               prettyFlags,
    2311             :                                                               false));
    2312          68 :                 break;
    2313             :             }
    2314           0 :         default:
    2315           0 :             elog(ERROR, "invalid constraint type \"%c\"", conForm->contype);
    2316             :             break;
    2317             :     }
    2318             : 
    2319        2622 :     if (conForm->condeferrable)
    2320          26 :         appendStringInfoString(&buf, " DEFERRABLE");
    2321        2622 :     if (conForm->condeferred)
    2322           0 :         appendStringInfoString(&buf, " INITIALLY DEFERRED");
    2323        2622 :     if (!conForm->convalidated)
    2324          54 :         appendStringInfoString(&buf, " NOT VALID");
    2325             : 
    2326             :     /* Cleanup */
    2327        2622 :     systable_endscan(scandesc);
    2328        2622 :     table_close(relation, AccessShareLock);
    2329             : 
    2330        2622 :     return buf.data;
    2331             : }
    2332             : 
    2333             : 
    2334             : /*
    2335             :  * Convert an int16[] Datum into a comma-separated list of column names
    2336             :  * for the indicated relation; append the list to buf.  Returns the number
    2337             :  * of keys.
    2338             :  */
    2339             : static int
    2340        1892 : decompile_column_index_array(Datum column_index_array, Oid relId,
    2341             :                              StringInfo buf)
    2342             : {
    2343             :     Datum      *keys;
    2344             :     int         nKeys;
    2345             :     int         j;
    2346             : 
    2347             :     /* Extract data from array of int16 */
    2348        1892 :     deconstruct_array(DatumGetArrayTypeP(column_index_array),
    2349             :                       INT2OID, 2, true, TYPALIGN_SHORT,
    2350             :                       &keys, NULL, &nKeys);
    2351             : 
    2352        4304 :     for (j = 0; j < nKeys; j++)
    2353             :     {
    2354             :         char       *colName;
    2355             : 
    2356        2412 :         colName = get_attname(relId, DatumGetInt16(keys[j]), false);
    2357             : 
    2358        2412 :         if (j == 0)
    2359        1892 :             appendStringInfoString(buf, quote_identifier(colName));
    2360             :         else
    2361         520 :             appendStringInfo(buf, ", %s", quote_identifier(colName));
    2362             :     }
    2363             : 
    2364        1892 :     return nKeys;
    2365             : }
    2366             : 
    2367             : 
    2368             : /* ----------
    2369             :  * pg_get_expr          - Decompile an expression tree
    2370             :  *
    2371             :  * Input: an expression tree in nodeToString form, and a relation OID
    2372             :  *
    2373             :  * Output: reverse-listed expression
    2374             :  *
    2375             :  * Currently, the expression can only refer to a single relation, namely
    2376             :  * the one specified by the second parameter.  This is sufficient for
    2377             :  * partial indexes, column default expressions, etc.  We also support
    2378             :  * Var-free expressions, for which the OID can be InvalidOid.
    2379             :  * ----------
    2380             :  */
    2381             : Datum
    2382        3336 : pg_get_expr(PG_FUNCTION_ARGS)
    2383             : {
    2384        3336 :     text       *expr = PG_GETARG_TEXT_PP(0);
    2385        3336 :     Oid         relid = PG_GETARG_OID(1);
    2386             :     int         prettyFlags;
    2387             :     char       *relname;
    2388             : 
    2389        3336 :     prettyFlags = PRETTYFLAG_INDENT;
    2390             : 
    2391        3336 :     if (OidIsValid(relid))
    2392             :     {
    2393             :         /* Get the name for the relation */
    2394        3336 :         relname = get_rel_name(relid);
    2395             : 
    2396             :         /*
    2397             :          * If the OID isn't actually valid, don't throw an error, just return
    2398             :          * NULL.  This is a bit questionable, but it's what we've done
    2399             :          * historically, and it can help avoid unwanted failures when
    2400             :          * examining catalog entries for just-deleted relations.
    2401             :          */
    2402        3336 :         if (relname == NULL)
    2403           0 :             PG_RETURN_NULL();
    2404             :     }
    2405             :     else
    2406           0 :         relname = NULL;
    2407             : 
    2408        3336 :     PG_RETURN_TEXT_P(pg_get_expr_worker(expr, relid, relname, prettyFlags));
    2409             : }
    2410             : 
    2411             : Datum
    2412         236 : pg_get_expr_ext(PG_FUNCTION_ARGS)
    2413             : {
    2414         236 :     text       *expr = PG_GETARG_TEXT_PP(0);
    2415         236 :     Oid         relid = PG_GETARG_OID(1);
    2416         236 :     bool        pretty = PG_GETARG_BOOL(2);
    2417             :     int         prettyFlags;
    2418             :     char       *relname;
    2419             : 
    2420         236 :     prettyFlags = pretty ? (PRETTYFLAG_PAREN | PRETTYFLAG_INDENT | PRETTYFLAG_SCHEMA) : PRETTYFLAG_INDENT;
    2421             : 
    2422         236 :     if (OidIsValid(relid))
    2423             :     {
    2424             :         /* Get the name for the relation */
    2425         236 :         relname = get_rel_name(relid);
    2426             :         /* See notes above */
    2427         236 :         if (relname == NULL)
    2428           0 :             PG_RETURN_NULL();
    2429             :     }
    2430             :     else
    2431           0 :         relname = NULL;
    2432             : 
    2433         236 :     PG_RETURN_TEXT_P(pg_get_expr_worker(expr, relid, relname, prettyFlags));
    2434             : }
    2435             : 
    2436             : static text *
    2437        3572 : pg_get_expr_worker(text *expr, Oid relid, const char *relname, int prettyFlags)
    2438             : {
    2439             :     Node       *node;
    2440             :     List       *context;
    2441             :     char       *exprstr;
    2442             :     char       *str;
    2443             : 
    2444             :     /* Convert input TEXT object to C string */
    2445        3572 :     exprstr = text_to_cstring(expr);
    2446             : 
    2447             :     /* Convert expression to node tree */
    2448        3572 :     node = (Node *) stringToNode(exprstr);
    2449             : 
    2450        3572 :     pfree(exprstr);
    2451             : 
    2452             :     /* Prepare deparse context if needed */
    2453        3572 :     if (OidIsValid(relid))
    2454        3572 :         context = deparse_context_for(relname, relid);
    2455             :     else
    2456           0 :         context = NIL;
    2457             : 
    2458             :     /* Deparse */
    2459        3572 :     str = deparse_expression_pretty(node, context, false, false,
    2460             :                                     prettyFlags, 0);
    2461             : 
    2462        3572 :     return string_to_text(str);
    2463             : }
    2464             : 
    2465             : 
    2466             : /* ----------
    2467             :  * pg_get_userbyid      - Get a user name by roleid and
    2468             :  *                fallback to 'unknown (OID=n)'
    2469             :  * ----------
    2470             :  */
    2471             : Datum
    2472         740 : pg_get_userbyid(PG_FUNCTION_ARGS)
    2473             : {
    2474         740 :     Oid         roleid = PG_GETARG_OID(0);
    2475             :     Name        result;
    2476             :     HeapTuple   roletup;
    2477             :     Form_pg_authid role_rec;
    2478             : 
    2479             :     /*
    2480             :      * Allocate space for the result
    2481             :      */
    2482         740 :     result = (Name) palloc(NAMEDATALEN);
    2483         740 :     memset(NameStr(*result), 0, NAMEDATALEN);
    2484             : 
    2485             :     /*
    2486             :      * Get the pg_authid entry and print the result
    2487             :      */
    2488         740 :     roletup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
    2489         740 :     if (HeapTupleIsValid(roletup))
    2490             :     {
    2491         740 :         role_rec = (Form_pg_authid) GETSTRUCT(roletup);
    2492         740 :         StrNCpy(NameStr(*result), NameStr(role_rec->rolname), NAMEDATALEN);
    2493         740 :         ReleaseSysCache(roletup);
    2494             :     }
    2495             :     else
    2496           0 :         sprintf(NameStr(*result), "unknown (OID=%u)", roleid);
    2497             : 
    2498         740 :     PG_RETURN_NAME(result);
    2499             : }
    2500             : 
    2501             : 
    2502             : /*
    2503             :  * pg_get_serial_sequence
    2504             :  *      Get the name of the sequence used by an identity or serial column,
    2505             :  *      formatted suitably for passing to setval, nextval or currval.
    2506             :  *      First parameter is not treated as double-quoted, second parameter
    2507             :  *      is --- see documentation for reason.
    2508             :  */
    2509             : Datum
    2510           8 : pg_get_serial_sequence(PG_FUNCTION_ARGS)
    2511             : {
    2512           8 :     text       *tablename = PG_GETARG_TEXT_PP(0);
    2513           8 :     text       *columnname = PG_GETARG_TEXT_PP(1);
    2514             :     RangeVar   *tablerv;
    2515             :     Oid         tableOid;
    2516             :     char       *column;
    2517             :     AttrNumber  attnum;
    2518           8 :     Oid         sequenceId = InvalidOid;
    2519             :     Relation    depRel;
    2520             :     ScanKeyData key[3];
    2521             :     SysScanDesc scan;
    2522             :     HeapTuple   tup;
    2523             : 
    2524             :     /* Look up table name.  Can't lock it - we might not have privileges. */
    2525           8 :     tablerv = makeRangeVarFromNameList(textToQualifiedNameList(tablename));
    2526           8 :     tableOid = RangeVarGetRelid(tablerv, NoLock, false);
    2527             : 
    2528             :     /* Get the number of the column */
    2529           8 :     column = text_to_cstring(columnname);
    2530             : 
    2531           8 :     attnum = get_attnum(tableOid, column);
    2532           8 :     if (attnum == InvalidAttrNumber)
    2533           0 :         ereport(ERROR,
    2534             :                 (errcode(ERRCODE_UNDEFINED_COLUMN),
    2535             :                  errmsg("column \"%s\" of relation \"%s\" does not exist",
    2536             :                         column, tablerv->relname)));
    2537             : 
    2538             :     /* Search the dependency table for the dependent sequence */
    2539           8 :     depRel = table_open(DependRelationId, AccessShareLock);
    2540             : 
    2541           8 :     ScanKeyInit(&key[0],
    2542             :                 Anum_pg_depend_refclassid,
    2543             :                 BTEqualStrategyNumber, F_OIDEQ,
    2544             :                 ObjectIdGetDatum(RelationRelationId));
    2545           8 :     ScanKeyInit(&key[1],
    2546             :                 Anum_pg_depend_refobjid,
    2547             :                 BTEqualStrategyNumber, F_OIDEQ,
    2548             :                 ObjectIdGetDatum(tableOid));
    2549           8 :     ScanKeyInit(&key[2],
    2550             :                 Anum_pg_depend_refobjsubid,
    2551             :                 BTEqualStrategyNumber, F_INT4EQ,
    2552             :                 Int32GetDatum(attnum));
    2553             : 
    2554           8 :     scan = systable_beginscan(depRel, DependReferenceIndexId, true,
    2555             :                               NULL, 3, key);
    2556             : 
    2557          12 :     while (HeapTupleIsValid(tup = systable_getnext(scan)))
    2558             :     {
    2559          12 :         Form_pg_depend deprec = (Form_pg_depend) GETSTRUCT(tup);
    2560             : 
    2561             :         /*
    2562             :          * Look for an auto dependency (serial column) or internal dependency
    2563             :          * (identity column) of a sequence on a column.  (We need the relkind
    2564             :          * test because indexes can also have auto dependencies on columns.)
    2565             :          */
    2566          12 :         if (deprec->classid == RelationRelationId &&
    2567           8 :             deprec->objsubid == 0 &&
    2568           8 :             (deprec->deptype == DEPENDENCY_AUTO ||
    2569          12 :              deprec->deptype == DEPENDENCY_INTERNAL) &&
    2570           8 :             get_rel_relkind(deprec->objid) == RELKIND_SEQUENCE)
    2571             :         {
    2572           8 :             sequenceId = deprec->objid;
    2573           8 :             break;
    2574             :         }
    2575             :     }
    2576             : 
    2577           8 :     systable_endscan(scan);
    2578           8 :     table_close(depRel, AccessShareLock);
    2579             : 
    2580           8 :     if (OidIsValid(sequenceId))
    2581             :     {
    2582             :         char       *result;
    2583             : 
    2584           8 :         result = generate_qualified_relation_name(sequenceId);
    2585             : 
    2586           8 :         PG_RETURN_TEXT_P(string_to_text(result));
    2587             :     }
    2588             : 
    2589           0 :     PG_RETURN_NULL();
    2590             : }
    2591             : 
    2592             : 
    2593             : /*
    2594             :  * pg_get_functiondef
    2595             :  *      Returns the complete "CREATE OR REPLACE FUNCTION ..." statement for
    2596             :  *      the specified function.
    2597             :  *
    2598             :  * Note: if you change the output format of this function, be careful not
    2599             :  * to break psql's rules (in \ef and \sf) for identifying the start of the
    2600             :  * function body.  To wit: the function body starts on a line that begins
    2601             :  * with "AS ", and no preceding line will look like that.
    2602             :  */
    2603             : Datum
    2604          28 : pg_get_functiondef(PG_FUNCTION_ARGS)
    2605             : {
    2606          28 :     Oid         funcid = PG_GETARG_OID(0);
    2607             :     StringInfoData buf;
    2608             :     StringInfoData dq;
    2609             :     HeapTuple   proctup;
    2610             :     Form_pg_proc proc;
    2611             :     bool        isfunction;
    2612             :     Datum       tmp;
    2613             :     bool        isnull;
    2614             :     const char *prosrc;
    2615             :     const char *name;
    2616             :     const char *nsp;
    2617             :     float4      procost;
    2618             :     int         oldlen;
    2619             : 
    2620          28 :     initStringInfo(&buf);
    2621             : 
    2622             :     /* Look up the function */
    2623          28 :     proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
    2624          28 :     if (!HeapTupleIsValid(proctup))
    2625           4 :         PG_RETURN_NULL();
    2626             : 
    2627          24 :     proc = (Form_pg_proc) GETSTRUCT(proctup);
    2628          24 :     name = NameStr(proc->proname);
    2629             : 
    2630          24 :     if (proc->prokind == PROKIND_AGGREGATE)
    2631           0 :         ereport(ERROR,
    2632             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    2633             :                  errmsg("\"%s\" is an aggregate function", name)));
    2634             : 
    2635          24 :     isfunction = (proc->prokind != PROKIND_PROCEDURE);
    2636             : 
    2637             :     /*
    2638             :      * We always qualify the function name, to ensure the right function gets
    2639             :      * replaced.
    2640             :      */
    2641          24 :     nsp = get_namespace_name(proc->pronamespace);
    2642          24 :     appendStringInfo(&buf, "CREATE OR REPLACE %s %s(",
    2643             :                      isfunction ? "FUNCTION" : "PROCEDURE",
    2644             :                      quote_qualified_identifier(nsp, name));
    2645          24 :     (void) print_function_arguments(&buf, proctup, false, true);
    2646          24 :     appendStringInfoString(&buf, ")\n");
    2647          24 :     if (isfunction)
    2648             :     {
    2649          20 :         appendStringInfoString(&buf, " RETURNS ");
    2650          20 :         print_function_rettype(&buf, proctup);
    2651          20 :         appendStringInfoChar(&buf, '\n');
    2652             :     }
    2653             : 
    2654          24 :     print_function_trftypes(&buf, proctup);
    2655             : 
    2656          24 :     appendStringInfo(&buf, " LANGUAGE %s\n",
    2657          24 :                      quote_identifier(get_language_name(proc->prolang, false)));
    2658             : 
    2659             :     /* Emit some miscellaneous options on one line */
    2660          24 :     oldlen = buf.len;
    2661             : 
    2662          24 :     if (proc->prokind == PROKIND_WINDOW)
    2663           0 :         appendStringInfoString(&buf, " WINDOW");
    2664          24 :     switch (proc->provolatile)
    2665             :     {
    2666           4 :         case PROVOLATILE_IMMUTABLE:
    2667           4 :             appendStringInfoString(&buf, " IMMUTABLE");
    2668           4 :             break;
    2669           4 :         case PROVOLATILE_STABLE:
    2670           4 :             appendStringInfoString(&buf, " STABLE");
    2671           4 :             break;
    2672          16 :         case PROVOLATILE_VOLATILE:
    2673          16 :             break;
    2674             :     }
    2675             : 
    2676          24 :     switch (proc->proparallel)
    2677             :     {
    2678           0 :         case PROPARALLEL_SAFE:
    2679           0 :             appendStringInfoString(&buf, " PARALLEL SAFE");
    2680           0 :             break;
    2681           0 :         case PROPARALLEL_RESTRICTED:
    2682           0 :             appendStringInfoString(&buf, " PARALLEL RESTRICTED");
    2683           0 :             break;
    2684          24 :         case PROPARALLEL_UNSAFE:
    2685          24 :             break;
    2686             :     }
    2687             : 
    2688          24 :     if (proc->proisstrict)
    2689           8 :         appendStringInfoString(&buf, " STRICT");
    2690          24 :     if (proc->prosecdef)
    2691           4 :         appendStringInfoString(&buf, " SECURITY DEFINER");
    2692          24 :     if (proc->proleakproof)
    2693           0 :         appendStringInfoString(&buf, " LEAKPROOF");
    2694             : 
    2695             :     /* This code for the default cost and rows should match functioncmds.c */
    2696          24 :     if (proc->prolang == INTERNALlanguageId ||
    2697          24 :         proc->prolang == ClanguageId)
    2698           0 :         procost = 1;
    2699             :     else
    2700          24 :         procost = 100;
    2701          24 :     if (proc->procost != procost)
    2702           0 :         appendStringInfo(&buf, " COST %g", proc->procost);
    2703             : 
    2704          24 :     if (proc->prorows > 0 && proc->prorows != 1000)
    2705           0 :         appendStringInfo(&buf, " ROWS %g", proc->prorows);
    2706             : 
    2707          24 :     if (proc->prosupport)
    2708             :     {
    2709             :         Oid         argtypes[1];
    2710             : 
    2711             :         /*
    2712             :          * We should qualify the support function's name if it wouldn't be
    2713             :          * resolved by lookup in the current search path.
    2714             :          */
    2715           0 :         argtypes[0] = INTERNALOID;
    2716           0 :         appendStringInfo(&buf, " SUPPORT %s",
    2717             :                          generate_function_name(proc->prosupport, 1,
    2718             :                                                 NIL, argtypes,
    2719             :                                                 false, NULL, EXPR_KIND_NONE));
    2720             :     }
    2721             : 
    2722          24 :     if (oldlen != buf.len)
    2723          16 :         appendStringInfoChar(&buf, '\n');
    2724             : 
    2725             :     /* Emit any proconfig options, one per line */
    2726          24 :     tmp = SysCacheGetAttr(PROCOID, proctup, Anum_pg_proc_proconfig, &isnull);
    2727          24 :     if (!isnull)
    2728             :     {
    2729           4 :         ArrayType  *a = DatumGetArrayTypeP(tmp);
    2730             :         int         i;
    2731             : 
    2732             :         Assert(ARR_ELEMTYPE(a) == TEXTOID);
    2733             :         Assert(ARR_NDIM(a) == 1);
    2734             :         Assert(ARR_LBOUND(a)[0] == 1);
    2735             : 
    2736          24 :         for (i = 1; i <= ARR_DIMS(a)[0]; i++)
    2737             :         {
    2738             :             Datum       d;
    2739             : 
    2740          20 :             d = array_ref(a, 1, &i,
    2741             :                           -1 /* varlenarray */ ,
    2742             :                           -1 /* TEXT's typlen */ ,
    2743             :                           false /* TEXT's typbyval */ ,
    2744             :                           TYPALIGN_INT /* TEXT's typalign */ ,
    2745             :                           &isnull);
    2746          20 :             if (!isnull)
    2747             :             {
    2748          20 :                 char       *configitem = TextDatumGetCString(d);
    2749             :                 char       *pos;
    2750             : 
    2751          20 :                 pos = strchr(configitem, '=');
    2752          20 :                 if (pos == NULL)
    2753           0 :                     continue;
    2754          20 :                 *pos++ = '\0';
    2755             : 
    2756          20 :                 appendStringInfo(&buf, " SET %s TO ",
    2757             :                                  quote_identifier(configitem));
    2758             : 
    2759             :                 /*
    2760             :                  * Variables that are marked GUC_LIST_QUOTE were already fully
    2761             :                  * quoted by flatten_set_variable_args() before they were put
    2762             :                  * into the proconfig array.  However, because the quoting
    2763             :                  * rules used there aren't exactly like SQL's, we have to
    2764             :                  * break the list value apart and then quote the elements as
    2765             :                  * string literals.  (The elements may be double-quoted as-is,
    2766             :                  * but we can't just feed them to the SQL parser; it would do
    2767             :                  * the wrong thing with elements that are zero-length or
    2768             :                  * longer than NAMEDATALEN.)
    2769             :                  *
    2770             :                  * Variables that are not so marked should just be emitted as
    2771             :                  * simple string literals.  If the variable is not known to
    2772             :                  * guc.c, we'll do that; this makes it unsafe to use
    2773             :                  * GUC_LIST_QUOTE for extension variables.
    2774             :                  */
    2775          20 :                 if (GetConfigOptionFlags(configitem, true) & GUC_LIST_QUOTE)
    2776             :                 {
    2777             :                     List       *namelist;
    2778             :                     ListCell   *lc;
    2779             : 
    2780             :                     /* Parse string into list of identifiers */
    2781           8 :                     if (!SplitGUCList(pos, ',', &namelist))
    2782             :                     {
    2783             :                         /* this shouldn't fail really */
    2784           0 :                         elog(ERROR, "invalid list syntax in proconfig item");
    2785             :                     }
    2786          28 :                     foreach(lc, namelist)
    2787             :                     {
    2788          20 :                         char       *curname = (char *) lfirst(lc);
    2789             : 
    2790          20 :                         simple_quote_literal(&buf, curname);
    2791          20 :                         if (lnext(namelist, lc))
    2792          12 :                             appendStringInfoString(&buf, ", ");
    2793             :                     }
    2794             :                 }
    2795             :                 else
    2796          12 :                     simple_quote_literal(&buf, pos);
    2797          20 :                 appendStringInfoChar(&buf, '\n');
    2798             :             }
    2799             :         }
    2800             :     }
    2801             : 
    2802             :     /* And finally the function definition ... */
    2803          24 :     appendStringInfoString(&buf, "AS ");
    2804             : 
    2805          24 :     tmp = SysCacheGetAttr(PROCOID, proctup, Anum_pg_proc_probin, &isnull);
    2806          24 :     if (!isnull)
    2807             :     {
    2808           0 :         simple_quote_literal(&buf, TextDatumGetCString(tmp));
    2809           0 :         appendStringInfoString(&buf, ", "); /* assume prosrc isn't null */
    2810             :     }
    2811             : 
    2812          24 :     tmp = SysCacheGetAttr(PROCOID, proctup, Anum_pg_proc_prosrc, &isnull);
    2813          24 :     if (isnull)
    2814           0 :         elog(ERROR, "null prosrc");
    2815          24 :     prosrc = TextDatumGetCString(tmp);
    2816             : 
    2817             :     /*
    2818             :      * We always use dollar quoting.  Figure out a suitable delimiter.
    2819             :      *
    2820             :      * Since the user is likely to be editing the function body string, we
    2821             :      * shouldn't use a short delimiter that he might easily create a conflict
    2822             :      * with.  Hence prefer "$function$"/"$procedure$", but extend if needed.
    2823             :      */
    2824          24 :     initStringInfo(&dq);
    2825          24 :     appendStringInfoChar(&dq, '$');
    2826          24 :     appendStringInfoString(&dq, (isfunction ? "function" : "procedure"));
    2827          24 :     while (strstr(prosrc, dq.data) != NULL)
    2828           0 :         appendStringInfoChar(&dq, 'x');
    2829          24 :     appendStringInfoChar(&dq, '$');
    2830             : 
    2831          24 :     appendBinaryStringInfo(&buf, dq.data, dq.len);
    2832          24 :     appendStringInfoString(&buf, prosrc);
    2833          24 :     appendBinaryStringInfo(&buf, dq.data, dq.len);
    2834             : 
    2835          24 :     appendStringInfoChar(&buf, '\n');
    2836             : 
    2837          24 :     ReleaseSysCache(proctup);
    2838             : 
    2839          24 :     PG_RETURN_TEXT_P(string_to_text(buf.data));
    2840             : }
    2841             : 
    2842             : /*
    2843             :  * pg_get_function_arguments
    2844             :  *      Get a nicely-formatted list of arguments for a function.
    2845             :  *      This is everything that would go between the parentheses in
    2846             :  *      CREATE FUNCTION.
    2847             :  */
    2848             : Datum
    2849        2324 : pg_get_function_arguments(PG_FUNCTION_ARGS)
    2850             : {
    2851        2324 :     Oid         funcid = PG_GETARG_OID(0);
    2852             :     StringInfoData buf;
    2853             :     HeapTuple   proctup;
    2854             : 
    2855        2324 :     proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
    2856        2324 :     if (!HeapTupleIsValid(proctup))
    2857           4 :         PG_RETURN_NULL();
    2858             : 
    2859        2320 :     initStringInfo(&buf);
    2860             : 
    2861        2320 :     (void) print_function_arguments(&buf, proctup, false, true);
    2862             : 
    2863        2320 :     ReleaseSysCache(proctup);
    2864             : 
    2865        2320 :     PG_RETURN_TEXT_P(string_to_text(buf.data));
    2866             : }
    2867             : 
    2868             : /*
    2869             :  * pg_get_function_identity_arguments
    2870             :  *      Get a formatted list of arguments for a function.
    2871             :  *      This is everything that would go between the parentheses in
    2872             :  *      ALTER FUNCTION, etc.  In particular, don't print defaults.
    2873             :  */
    2874             : Datum
    2875        2150 : pg_get_function_identity_arguments(PG_FUNCTION_ARGS)
    2876             : {
    2877        2150 :     Oid         funcid = PG_GETARG_OID(0);
    2878             :     StringInfoData buf;
    2879             :     HeapTuple   proctup;
    2880             : 
    2881        2150 :     proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
    2882        2150 :     if (!HeapTupleIsValid(proctup))
    2883           4 :         PG_RETURN_NULL();
    2884             : 
    2885        2146 :     initStringInfo(&buf);
    2886             : 
    2887        2146 :     (void) print_function_arguments(&buf, proctup, false, false);
    2888             : 
    2889        2146 :     ReleaseSysCache(proctup);
    2890             : 
    2891        2146 :     PG_RETURN_TEXT_P(string_to_text(buf.data));
    2892             : }
    2893             : 
    2894             : /*
    2895             :  * pg_get_function_result
    2896             :  *      Get a nicely-formatted version of the result type of a function.
    2897             :  *      This is what would appear after RETURNS in CREATE FUNCTION.
    2898             :  */
    2899             : Datum
    2900        1958 : pg_get_function_result(PG_FUNCTION_ARGS)
    2901             : {
    2902        1958 :     Oid         funcid = PG_GETARG_OID(0);
    2903             :     StringInfoData buf;
    2904             :     HeapTuple   proctup;
    2905             : 
    2906        1958 :     proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
    2907        1958 :     if (!HeapTupleIsValid(proctup))
    2908           4 :         PG_RETURN_NULL();
    2909             : 
    2910        1954 :     if (((Form_pg_proc) GETSTRUCT(proctup))->prokind == PROKIND_PROCEDURE)
    2911             :     {
    2912          76 :         ReleaseSysCache(proctup);
    2913          76 :         PG_RETURN_NULL();
    2914             :     }
    2915             : 
    2916        1878 :     initStringInfo(&buf);
    2917             : 
    2918        1878 :     print_function_rettype(&buf, proctup);
    2919             : 
    2920        1878 :     ReleaseSysCache(proctup);
    2921             : 
    2922        1878 :     PG_RETURN_TEXT_P(string_to_text(buf.data));
    2923             : }
    2924             : 
    2925             : /*
    2926             :  * Guts of pg_get_function_result: append the function's return type
    2927             :  * to the specified buffer.
    2928             :  */
    2929             : static void
    2930        1898 : print_function_rettype(StringInfo buf, HeapTuple proctup)
    2931             : {
    2932        1898 :     Form_pg_proc proc = (Form_pg_proc) GETSTRUCT(proctup);
    2933        1898 :     int         ntabargs = 0;
    2934             :     StringInfoData rbuf;
    2935             : 
    2936        1898 :     initStringInfo(&rbuf);
    2937             : 
    2938        1898 :     if (proc->proretset)
    2939             :     {
    2940             :         /* It might be a table function; try to print the arguments */
    2941         174 :         appendStringInfoString(&rbuf, "TABLE(");
    2942         174 :         ntabargs = print_function_arguments(&rbuf, proctup, true, false);
    2943         174 :         if (ntabargs > 0)
    2944          36 :             appendStringInfoChar(&rbuf, ')');
    2945             :         else
    2946         138 :             resetStringInfo(&rbuf);
    2947             :     }
    2948             : 
    2949        1898 :     if (ntabargs == 0)
    2950             :     {
    2951             :         /* Not a table function, so do the normal thing */
    2952        1862 :         if (proc->proretset)
    2953         138 :             appendStringInfoString(&rbuf, "SETOF ");
    2954        1862 :         appendStringInfoString(&rbuf, format_type_be(proc->prorettype));
    2955             :     }
    2956             : 
    2957        1898 :     appendBinaryStringInfo(buf, rbuf.data, rbuf.len);
    2958        1898 : }
    2959             : 
    2960             : /*
    2961             :  * Common code for pg_get_function_arguments and pg_get_function_result:
    2962             :  * append the desired subset of arguments to buf.  We print only TABLE
    2963             :  * arguments when print_table_args is true, and all the others when it's false.
    2964             :  * We print argument defaults only if print_defaults is true.
    2965             :  * Function return value is the number of arguments printed.
    2966             :  */
    2967             : static int
    2968        4664 : print_function_arguments(StringInfo buf, HeapTuple proctup,
    2969             :                          bool print_table_args, bool print_defaults)
    2970             : {
    2971        4664 :     Form_pg_proc proc = (Form_pg_proc) GETSTRUCT(proctup);
    2972             :     int         numargs;
    2973             :     Oid        *argtypes;
    2974             :     char      **argnames;
    2975             :     char       *argmodes;
    2976        4664 :     int         insertorderbyat = -1;
    2977             :     int         argsprinted;
    2978             :     int         inputargno;
    2979             :     int         nlackdefaults;
    2980        4664 :     List       *argdefaults = NIL;
    2981        4664 :     ListCell   *nextargdefault = NULL;
    2982             :     int         i;
    2983             : 
    2984        4664 :     numargs = get_func_arg_info(proctup,
    2985             :                                 &argtypes, &argnames, &argmodes);
    2986             : 
    2987        4664 :     nlackdefaults = numargs;
    2988        4664 :     if (print_defaults && proc->pronargdefaults > 0)
    2989             :     {
    2990             :         Datum       proargdefaults;
    2991             :         bool        isnull;
    2992             : 
    2993          20 :         proargdefaults = SysCacheGetAttr(PROCOID, proctup,
    2994             :                                          Anum_pg_proc_proargdefaults,
    2995             :                                          &isnull);
    2996          20 :         if (!isnull)
    2997             :         {
    2998             :             char       *str;
    2999             : 
    3000          20 :             str = TextDatumGetCString(proargdefaults);
    3001          20 :             argdefaults = castNode(List, stringToNode(str));
    3002          20 :             pfree(str);
    3003          20 :             nextargdefault = list_head(argdefaults);
    3004             :             /* nlackdefaults counts only *input* arguments lacking defaults */
    3005          20 :             nlackdefaults = proc->pronargs - list_length(argdefaults);
    3006             :         }
    3007             :     }
    3008             : 
    3009             :     /* Check for special treatment of ordered-set aggregates */
    3010        4664 :     if (proc->prokind == PROKIND_AGGREGATE)
    3011             :     {
    3012             :         HeapTuple   aggtup;
    3013             :         Form_pg_aggregate agg;
    3014             : 
    3015         720 :         aggtup = SearchSysCache1(AGGFNOID, proc->oid);
    3016         720 :         if (!HeapTupleIsValid(aggtup))
    3017           0 :             elog(ERROR, "cache lookup failed for aggregate %u",
    3018             :                  proc->oid);
    3019         720 :         agg = (Form_pg_aggregate) GETSTRUCT(aggtup);
    3020         720 :         if (AGGKIND_IS_ORDERED_SET(agg->aggkind))
    3021          32 :             insertorderbyat = agg->aggnumdirectargs;
    3022         720 :         ReleaseSysCache(aggtup);
    3023             :     }
    3024             : 
    3025        4664 :     argsprinted = 0;
    3026        4664 :     inputargno = 0;
    3027        8972 :     for (i = 0; i < numargs; i++)
    3028             :     {
    3029        4308 :         Oid         argtype = argtypes[i];
    3030        4308 :         char       *argname = argnames ? argnames[i] : NULL;
    3031        4308 :         char        argmode = argmodes ? argmodes[i] : PROARGMODE_IN;
    3032             :         const char *modename;
    3033             :         bool        isinput;
    3034             : 
    3035        4308 :         switch (argmode)
    3036             :         {
    3037        3908 :             case PROARGMODE_IN:
    3038        3908 :                 modename = "";
    3039        3908 :                 isinput = true;
    3040        3908 :                 break;
    3041          12 :             case PROARGMODE_INOUT:
    3042          12 :                 modename = "INOUT ";
    3043          12 :                 isinput = true;
    3044          12 :                 break;
    3045         148 :             case PROARGMODE_OUT:
    3046         148 :                 modename = "OUT ";
    3047         148 :                 isinput = false;
    3048         148 :                 break;
    3049          96 :             case PROARGMODE_VARIADIC:
    3050          96 :                 modename = "VARIADIC ";
    3051          96 :                 isinput = true;
    3052          96 :                 break;
    3053         144 :             case PROARGMODE_TABLE:
    3054         144 :                 modename = "";
    3055         144 :                 isinput = false;
    3056         144 :                 break;
    3057           0 :             default:
    3058           0 :                 elog(ERROR, "invalid parameter mode '%c'", argmode);
    3059             :                 modename = NULL;    /* keep compiler quiet */
    3060             :                 isinput = false;
    3061             :                 break;
    3062             :         }
    3063        4308 :         if (isinput)
    3064        4016 :             inputargno++;       /* this is a 1-based counter */
    3065             : 
    3066        4308 :         if (print_table_args != (argmode == PROARGMODE_TABLE))
    3067         288 :             continue;
    3068             : 
    3069        4020 :         if (argsprinted == insertorderbyat)
    3070             :         {
    3071          32 :             if (argsprinted)
    3072          32 :                 appendStringInfoChar(buf, ' ');
    3073          32 :             appendStringInfoString(buf, "ORDER BY ");
    3074             :         }
    3075        3988 :         else if (argsprinted)
    3076         984 :             appendStringInfoString(buf, ", ");
    3077             : 
    3078        4020 :         appendStringInfoString(buf, modename);
    3079        4020 :         if (argname && argname[0])
    3080         984 :             appendStringInfo(buf, "%s ", quote_identifier(argname));
    3081        4020 :         appendStringInfoString(buf, format_type_be(argtype));
    3082        4020 :         if (print_defaults && isinput && inputargno > nlackdefaults)
    3083             :         {
    3084             :             Node       *expr;
    3085             : 
    3086             :             Assert(nextargdefault != NULL);
    3087          24 :             expr = (Node *) lfirst(nextargdefault);
    3088          24 :             nextargdefault = lnext(argdefaults, nextargdefault);
    3089             : 
    3090          24 :             appendStringInfo(buf, " DEFAULT %s",
    3091             :                              deparse_expression(expr, NIL, false, false));
    3092             :         }
    3093        4020 :         argsprinted++;
    3094             : 
    3095             :         /* nasty hack: print the last arg twice for variadic ordered-set agg */
    3096        4020 :         if (argsprinted == insertorderbyat && i == numargs - 1)
    3097             :         {
    3098          16 :             i--;
    3099             :             /* aggs shouldn't have defaults anyway, but just to be sure ... */
    3100          16 :             print_defaults = false;
    3101             :         }
    3102             :     }
    3103             : 
    3104        4664 :     return argsprinted;
    3105             : }
    3106             : 
    3107             : static bool
    3108          64 : is_input_argument(int nth, const char *argmodes)
    3109             : {
    3110             :     return (!argmodes
    3111          28 :             || argmodes[nth] == PROARGMODE_IN
    3112          12 :             || argmodes[nth] == PROARGMODE_INOUT
    3113          92 :             || argmodes[nth] == PROARGMODE_VARIADIC);
    3114             : }
    3115             : 
    3116             : /*
    3117             :  * Append used transformed types to specified buffer
    3118             :  */
    3119             : static void
    3120          24 : print_function_trftypes(StringInfo buf, HeapTuple proctup)
    3121             : {
    3122             :     Oid        *trftypes;
    3123             :     int         ntypes;
    3124             : 
    3125          24 :     ntypes = get_func_trftypes(proctup, &trftypes);
    3126          24 :     if (ntypes > 0)
    3127             :     {
    3128             :         int         i;
    3129             : 
    3130           0 :         appendStringInfoString(buf, "\n TRANSFORM ");
    3131           0 :         for (i = 0; i < ntypes; i++)
    3132             :         {
    3133           0 :             if (i != 0)
    3134           0 :                 appendStringInfoString(buf, ", ");
    3135           0 :             appendStringInfo(buf, "FOR TYPE %s", format_type_be(trftypes[i]));
    3136             :         }
    3137             :     }
    3138          24 : }
    3139             : 
    3140             : /*
    3141             :  * Get textual representation of a function argument's default value.  The
    3142             :  * second argument of this function is the argument number among all arguments
    3143             :  * (i.e. proallargtypes, *not* proargtypes), starting with 1, because that's
    3144             :  * how information_schema.sql uses it.
    3145             :  */
    3146             : Datum
    3147          36 : pg_get_function_arg_default(PG_FUNCTION_ARGS)
    3148             : {
    3149          36 :     Oid         funcid = PG_GETARG_OID(0);
    3150          36 :     int32       nth_arg = PG_GETARG_INT32(1);
    3151             :     HeapTuple   proctup;
    3152             :     Form_pg_proc proc;
    3153             :     int         numargs;
    3154             :     Oid        *argtypes;
    3155             :     char      **argnames;
    3156             :     char       *argmodes;
    3157             :     int         i;
    3158             :     List       *argdefaults;
    3159             :     Node       *node;
    3160             :     char       *str;
    3161             :     int         nth_inputarg;
    3162             :     Datum       proargdefaults;
    3163             :     bool        isnull;
    3164             :     int         nth_default;
    3165             : 
    3166          36 :     proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
    3167          36 :     if (!HeapTupleIsValid(proctup))
    3168           8 :         PG_RETURN_NULL();
    3169             : 
    3170          28 :     numargs = get_func_arg_info(proctup, &argtypes, &argnames, &argmodes);
    3171          28 :     if (nth_arg < 1 || nth_arg > numargs || !is_input_argument(nth_arg - 1, argmodes))
    3172             :     {
    3173           8 :         ReleaseSysCache(proctup);
    3174           8 :         PG_RETURN_NULL();
    3175             :     }
    3176             : 
    3177          20 :     nth_inputarg = 0;
    3178          56 :     for (i = 0; i < nth_arg; i++)
    3179          36 :         if (is_input_argument(i, argmodes))
    3180          32 :             nth_inputarg++;
    3181             : 
    3182          20 :     proargdefaults = SysCacheGetAttr(PROCOID, proctup,
    3183             :                                      Anum_pg_proc_proargdefaults,
    3184             :                                      &isnull);
    3185          20 :     if (isnull)
    3186             :     {
    3187           0 :         ReleaseSysCache(proctup);
    3188           0 :         PG_RETURN_NULL();
    3189             :     }
    3190             : 
    3191          20 :     str = TextDatumGetCString(proargdefaults);
    3192          20 :     argdefaults = castNode(List, stringToNode(str));
    3193          20 :     pfree(str);
    3194             : 
    3195          20 :     proc = (Form_pg_proc) GETSTRUCT(proctup);
    3196             : 
    3197             :     /*
    3198             :      * Calculate index into proargdefaults: proargdefaults corresponds to the
    3199             :      * last N input arguments, where N = pronargdefaults.
    3200             :      */
    3201          20 :     nth_default = nth_inputarg - 1 - (proc->pronargs - proc->pronargdefaults);
    3202             : 
    3203          20 :     if (nth_default < 0 || nth_default >= list_length(argdefaults))
    3204             :     {
    3205           4 :         ReleaseSysCache(proctup);
    3206           4 :         PG_RETURN_NULL();
    3207             :     }
    3208          16 :     node = list_nth(argdefaults, nth_default);
    3209          16 :     str = deparse_expression(node, NIL, false, false);
    3210             : 
    3211          16 :     ReleaseSysCache(proctup);
    3212             : 
    3213          16 :     PG_RETURN_TEXT_P(string_to_text(str));
    3214             : }
    3215             : 
    3216             : 
    3217             : /*
    3218             :  * deparse_expression           - General utility for deparsing expressions
    3219             :  *
    3220             :  * calls deparse_expression_pretty with all prettyPrinting disabled
    3221             :  */
    3222             : char *
    3223       32598 : deparse_expression(Node *expr, List *dpcontext,
    3224             :                    bool forceprefix, bool showimplicit)
    3225             : {
    3226       32598 :     return deparse_expression_pretty(expr, dpcontext, forceprefix,
    3227             :                                      showimplicit, 0, 0);
    3228             : }
    3229             : 
    3230             : /* ----------
    3231             :  * deparse_expression_pretty    - General utility for deparsing expressions
    3232             :  *
    3233             :  * expr is the node tree to be deparsed.  It must be a transformed expression
    3234             :  * tree (ie, not the raw output of gram.y).
    3235             :  *
    3236             :  * dpcontext is a list of deparse_namespace nodes representing the context
    3237             :  * for interpreting Vars in the node tree.  It can be NIL if no Vars are
    3238             :  * expected.
    3239             :  *
    3240             :  * forceprefix is true to force all Vars to be prefixed with their table names.
    3241             :  *
    3242             :  * showimplicit is true to force all implicit casts to be shown explicitly.
    3243             :  *
    3244             :  * Tries to pretty up the output according to prettyFlags and startIndent.
    3245             :  *
    3246             :  * The result is a palloc'd string.
    3247             :  * ----------
    3248             :  */
    3249             : static char *
    3250       37968 : deparse_expression_pretty(Node *expr, List *dpcontext,
    3251             :                           bool forceprefix, bool showimplicit,
    3252             :                           int prettyFlags, int startIndent)
    3253             : {
    3254             :     StringInfoData buf;
    3255             :     deparse_context context;
    3256             : 
    3257       37968 :     initStringInfo(&buf);
    3258       37968 :     context.buf = &buf;
    3259       37968 :     context.namespaces = dpcontext;
    3260       37968 :     context.windowClause = NIL;
    3261       37968 :     context.windowTList = NIL;
    3262       37968 :     context.varprefix = forceprefix;
    3263       37968 :     context.prettyFlags = prettyFlags;
    3264       37968 :     context.wrapColumn = WRAP_COLUMN_DEFAULT;
    3265       37968 :     context.indentLevel = startIndent;
    3266       37968 :     context.special_exprkind = EXPR_KIND_NONE;
    3267       37968 :     context.appendparents = NULL;
    3268             : 
    3269       37968 :     get_rule_expr(expr, &context, showimplicit);
    3270             : 
    3271       37968 :     return buf.data;
    3272             : }
    3273             : 
    3274             : /* ----------
    3275             :  * deparse_context_for          - Build deparse context for a single relation
    3276             :  *
    3277             :  * Given the reference name (alias) and OID of a relation, build deparsing
    3278             :  * context for an expression referencing only that relation (as varno 1,
    3279             :  * varlevelsup 0).  This is sufficient for many uses of deparse_expression.
    3280             :  * ----------
    3281             :  */
    3282             : List *
    3283        9822 : deparse_context_for(const char *aliasname, Oid relid)
    3284             : {
    3285             :     deparse_namespace *dpns;
    3286             :     RangeTblEntry *rte;
    3287             : 
    3288        9822 :     dpns = (deparse_namespace *) palloc0(sizeof(deparse_namespace));
    3289             : 
    3290             :     /* Build a minimal RTE for the rel */
    3291        9822 :     rte = makeNode(RangeTblEntry);
    3292        9822 :     rte->rtekind = RTE_RELATION;
    3293        9822 :     rte->relid = relid;
    3294        9822 :     rte->relkind = RELKIND_RELATION; /* no need for exactness here */
    3295        9822 :     rte->rellockmode = AccessShareLock;
    3296        9822 :     rte->alias = makeAlias(aliasname, NIL);
    3297        9822 :     rte->eref = rte->alias;
    3298        9822 :     rte->lateral = false;
    3299        9822 :     rte->inh = false;
    3300        9822 :     rte->inFromCl = true;
    3301             : 
    3302             :     /* Build one-element rtable */
    3303        9822 :     dpns->rtable = list_make1(rte);
    3304        9822 :     dpns->subplans = NIL;
    3305        9822 :     dpns->ctes = NIL;
    3306        9822 :     dpns->appendrels = NULL;
    3307        9822 :     set_rtable_names(dpns, NIL, NULL);
    3308        9822 :     set_simple_column_names(dpns);
    3309             : 
    3310             :     /* Return a one-deep namespace stack */
    3311        9822 :     return list_make1(dpns);
    3312             : }
    3313             : 
    3314             : /*
    3315             :  * deparse_context_for_plan_tree - Build deparse context for a Plan tree
    3316             :  *
    3317             :  * When deparsing an expression in a Plan tree, we use the plan's rangetable
    3318             :  * to resolve names of simple Vars.  The initialization of column names for
    3319             :  * this is rather expensive if the rangetable is large, and it'll be the same
    3320             :  * for every expression in the Plan tree; so we do it just once and re-use
    3321             :  * the result of this function for each expression.  (Note that the result
    3322             :  * is not usable until set_deparse_context_plan() is applied to it.)
    3323             :  *
    3324             :  * In addition to the PlannedStmt, pass the per-RTE alias names
    3325             :  * assigned by a previous call to select_rtable_names_for_explain.
    3326             :  */
    3327             : List *
    3328       10378 : deparse_context_for_plan_tree(PlannedStmt *pstmt, List *rtable_names)
    3329             : {
    3330             :     deparse_namespace *dpns;
    3331             : 
    3332       10378 :     dpns = (deparse_namespace *) palloc0(sizeof(deparse_namespace));
    3333             : 
    3334             :     /* Initialize fields that stay the same across the whole plan tree */
    3335       10378 :     dpns->rtable = pstmt->rtable;
    3336       10378 :     dpns->rtable_names = rtable_names;
    3337       10378 :     dpns->subplans = pstmt->subplans;
    3338       10378 :     dpns->ctes = NIL;
    3339       10378 :     if (pstmt->appendRelations)
    3340             :     {
    3341             :         /* Set up the array, indexed by child relid */
    3342        1908 :         int         ntables = list_length(dpns->rtable);
    3343             :         ListCell   *lc;
    3344             : 
    3345        1908 :         dpns->appendrels = (AppendRelInfo **)
    3346        1908 :             palloc0((ntables + 1) * sizeof(AppendRelInfo *));
    3347       11226 :         foreach(lc, pstmt->appendRelations)
    3348             :         {
    3349        9318 :             AppendRelInfo *appinfo = lfirst_node(AppendRelInfo, lc);
    3350        9318 :             Index       crelid = appinfo->child_relid;
    3351             : 
    3352             :             Assert(crelid > 0 && crelid <= ntables);
    3353             :             Assert(dpns->appendrels[crelid] == NULL);
    3354        9318 :             dpns->appendrels[crelid] = appinfo;
    3355             :         }
    3356             :     }
    3357             :     else
    3358        8470 :         dpns->appendrels = NULL; /* don't need it */
    3359             : 
    3360             :     /*
    3361             :      * Set up column name aliases.  We will get rather bogus results for join
    3362             :      * RTEs, but that doesn't matter because plan trees don't contain any join
    3363             :      * alias Vars.
    3364             :      */
    3365       10378 :     set_simple_column_names(dpns);
    3366             : 
    3367             :     /* Return a one-deep namespace stack */
    3368       10378 :     return list_make1(dpns);
    3369             : }
    3370             : 
    3371             : /*
    3372             :  * set_deparse_context_plan - Specify Plan node containing expression
    3373             :  *
    3374             :  * When deparsing an expression in a Plan tree, we might have to resolve
    3375             :  * OUTER_VAR, INNER_VAR, or INDEX_VAR references.  To do this, the caller must
    3376             :  * provide the parent Plan node.  Then OUTER_VAR and INNER_VAR references
    3377             :  * can be resolved by drilling down into the left and right child plans.
    3378             :  * Similarly, INDEX_VAR references can be resolved by reference to the
    3379             :  * indextlist given in a parent IndexOnlyScan node, or to the scan tlist in
    3380             :  * ForeignScan and CustomScan nodes.  (Note that we don't currently support
    3381             :  * deparsing of indexquals in regular IndexScan or BitmapIndexScan nodes;
    3382             :  * for those, we can only deparse the indexqualorig fields, which won't
    3383             :  * contain INDEX_VAR Vars.)
    3384             :  *
    3385             :  * The ancestors list is a list of the Plan's parent Plan and SubPlan nodes,
    3386             :  * the most-closely-nested first.  This is needed to resolve PARAM_EXEC
    3387             :  * Params.  Note we assume that all the Plan nodes share the same rtable.
    3388             :  *
    3389             :  * Once this function has been called, deparse_expression() can be called on
    3390             :  * subsidiary expression(s) of the specified Plan node.  To deparse
    3391             :  * expressions of a different Plan node in the same Plan tree, re-call this
    3392             :  * function to identify the new parent Plan node.
    3393             :  *
    3394             :  * The result is the same List passed in; this is a notational convenience.
    3395             :  */
    3396             : List *
    3397       23988 : set_deparse_context_plan(List *dpcontext, Plan *plan, List *ancestors)
    3398             : {
    3399             :     deparse_namespace *dpns;
    3400             : 
    3401             :     /* Should always have one-entry namespace list for Plan deparsing */
    3402             :     Assert(list_length(dpcontext) == 1);
    3403       23988 :     dpns = (deparse_namespace *) linitial(dpcontext);
    3404             : 
    3405             :     /* Set our attention on the specific plan node passed in */
    3406       23988 :     set_deparse_plan(dpns, plan);
    3407       23988 :     dpns->ancestors = ancestors;
    3408             : 
    3409       23988 :     return dpcontext;
    3410             : }
    3411             : 
    3412             : /*
    3413             :  * select_rtable_names_for_explain  - Select RTE aliases for EXPLAIN
    3414             :  *
    3415             :  * Determine the relation aliases we'll use during an EXPLAIN operation.
    3416             :  * This is just a frontend to set_rtable_names.  We have to expose the aliases
    3417             :  * to EXPLAIN because EXPLAIN needs to know the right alias names to print.
    3418             :  */
    3419             : List *
    3420       10378 : select_rtable_names_for_explain(List *rtable, Bitmapset *rels_used)
    3421             : {
    3422             :     deparse_namespace dpns;
    3423             : 
    3424       10378 :     memset(&dpns, 0, sizeof(dpns));
    3425       10378 :     dpns.rtable = rtable;
    3426       10378 :     dpns.subplans = NIL;
    3427       10378 :     dpns.ctes = NIL;
    3428       10378 :     dpns.appendrels = NULL;
    3429       10378 :     set_rtable_names(&dpns, NIL, rels_used);
    3430             :     /* We needn't bother computing column aliases yet */
    3431             : 
    3432       10378 :     return dpns.rtable_names;
    3433             : }
    3434             : 
    3435             : /*
    3436             :  * set_rtable_names: select RTE aliases to be used in printing a query
    3437             :  *
    3438             :  * We fill in dpns->rtable_names with a list of names that is one-for-one with
    3439             :  * the already-filled dpns->rtable list.  Each RTE name is unique among those
    3440             :  * in the new namespace plus any ancestor namespaces listed in
    3441             :  * parent_namespaces.
    3442             :  *
    3443             :  * If rels_used isn't NULL, only RTE indexes listed in it are given aliases.
    3444             :  *
    3445             :  * Note that this function is only concerned with relation names, not column
    3446             :  * names.
    3447             :  */
    3448             : static void
    3449       23090 : set_rtable_names(deparse_namespace *dpns, List *parent_namespaces,
    3450             :                  Bitmapset *rels_used)
    3451             : {
    3452             :     HASHCTL     hash_ctl;
    3453             :     HTAB       *names_hash;
    3454             :     NameHashEntry *hentry;
    3455             :     bool        found;
    3456             :     int         rtindex;
    3457             :     ListCell   *lc;
    3458             : 
    3459       23090 :     dpns->rtable_names = NIL;
    3460             :     /* nothing more to do if empty rtable */
    3461       23090 :     if (dpns->rtable == NIL)
    3462          38 :         return;
    3463             : 
    3464             :     /*
    3465             :      * We use a hash table to hold known names, so that this process is O(N)
    3466             :      * not O(N^2) for N names.
    3467             :      */
    3468      322728 :     MemSet(&hash_ctl, 0, sizeof(hash_ctl));
    3469       23052 :     hash_ctl.keysize = NAMEDATALEN;
    3470       23052 :     hash_ctl.entrysize = sizeof(NameHashEntry);
    3471       23052 :     hash_ctl.hcxt = CurrentMemoryContext;
    3472       23052 :     names_hash = hash_create("set_rtable_names names",
    3473       23052 :                              list_length(dpns->rtable),
    3474             :                              &hash_ctl,
    3475             :                              HASH_ELEM | HASH_CONTEXT);
    3476             :     /* Preload the hash table with names appearing in parent_namespaces */
    3477       23678 :     foreach(lc, parent_namespaces)
    3478             :     {
    3479         626 :         deparse_namespace *olddpns = (deparse_namespace *) lfirst(lc);
    3480             :         ListCell   *lc2;
    3481             : 
    3482        3350 :         foreach(lc2, olddpns->rtable_names)
    3483             :         {
    3484        2724 :             char       *oldname = (char *) lfirst(lc2);
    3485             : 
    3486        2724 :             if (oldname == NULL)
    3487         116 :                 continue;
    3488        2608 :             hentry = (NameHashEntry *) hash_search(names_hash,
    3489             :                                                    oldname,
    3490             :                                                    HASH_ENTER,
    3491             :                                                    &found);
    3492             :             /* we do not complain about duplicate names in parent namespaces */
    3493        2608 :             hentry->counter = 0;
    3494             :         }
    3495             :     }
    3496             : 
    3497             :     /* Now we can scan the rtable */
    3498       23052 :     rtindex = 1;
    3499       70658 :     foreach(lc, dpns->rtable)
    3500             :     {
    3501       47606 :         RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
    3502             :         char       *refname;
    3503             : 
    3504             :         /* Just in case this takes an unreasonable amount of time ... */
    3505       47606 :         CHECK_FOR_INTERRUPTS();
    3506             : 
    3507       47606 :         if (rels_used && !bms_is_member(rtindex, rels_used))
    3508             :         {
    3509             :             /* Ignore unreferenced RTE */
    3510        7504 :             refname = NULL;
    3511             :         }
    3512       40102 :         else if (rte->alias)
    3513             :         {
    3514             :             /* If RTE has a user-defined alias, prefer that */
    3515       28352 :             refname = rte->alias->aliasname;
    3516             :         }
    3517       11750 :         else if (rte->rtekind == RTE_RELATION)
    3518             :         {
    3519             :             /* Use the current actual name of the relation */
    3520       10378 :             refname = get_rel_name(rte->relid);
    3521             :         }
    3522        1372 :         else if (rte->rtekind == RTE_JOIN)
    3523             :         {
    3524             :             /* Unnamed join has no refname */
    3525         592 :             refname = NULL;
    3526             :         }
    3527             :         else
    3528             :         {
    3529             :             /* Otherwise use whatever the parser assigned */
    3530         780 :             refname = rte->eref->aliasname;
    3531             :         }
    3532             : 
    3533             :         /*
    3534             :          * If the selected name isn't unique, append digits to make it so, and
    3535             :          * make a new hash entry for it once we've got a unique name.  For a
    3536             :          * very long input name, we might have to truncate to stay within
    3537             :          * NAMEDATALEN.
    3538             :          */
    3539       47606 :         if (refname)
    3540             :         {
    3541       39510 :             hentry = (NameHashEntry *) hash_search(names_hash,
    3542             :                                                    refname,
    3543             :                                                    HASH_ENTER,
    3544             :                                                    &found);
    3545       39510 :             if (found)
    3546             :             {
    3547             :                 /* Name already in use, must choose a new one */
    3548        7720 :                 int         refnamelen = strlen(refname);
    3549        7720 :                 char       *modname = (char *) palloc(refnamelen + 16);
    3550             :                 NameHashEntry *hentry2;
    3551             : 
    3552             :                 do
    3553             :                 {
    3554        7720 :                     hentry->counter++;
    3555             :                     for (;;)
    3556             :                     {
    3557             :                         /*
    3558             :                          * We avoid using %.*s here because it can misbehave
    3559             :                          * if the data is not valid in what libc thinks is the
    3560             :                          * prevailing encoding.
    3561             :                          */
    3562           8 :                         memcpy(modname, refname, refnamelen);
    3563        7728 :                         sprintf(modname + refnamelen, "_%d", hentry->counter);
    3564        7728 :                         if (strlen(modname) < NAMEDATALEN)
    3565        7720 :                             break;
    3566             :                         /* drop chars from refname to keep all the digits */
    3567           8 :                         refnamelen = pg_mbcliplen(refname, refnamelen,
    3568             :                                                   refnamelen - 1);
    3569             :                     }
    3570        7720 :                     hentry2 = (NameHashEntry *) hash_search(names_hash,
    3571             :                                                             modname,
    3572             :                                                             HASH_ENTER,
    3573             :                                                             &found);
    3574        7720 :                 } while (found);
    3575        7720 :                 hentry2->counter = 0;    /* init new hash entry */
    3576        7720 :                 refname = modname;
    3577             :             }
    3578             :             else
    3579             :             {
    3580             :                 /* Name not previously used, need only initialize hentry */
    3581       31790 :                 hentry->counter = 0;
    3582             :             }
    3583             :         }
    3584             : 
    3585       47606 :         dpns->rtable_names = lappend(dpns->rtable_names, refname);
    3586       47606 :         rtindex++;
    3587             :     }
    3588             : 
    3589       23052 :     hash_destroy(names_hash);
    3590             : }
    3591             : 
    3592             : /*
    3593             :  * set_deparse_for_query: set up deparse_namespace for deparsing a Query tree
    3594             :  *
    3595             :  * For convenience, this is defined to initialize the deparse_namespace struct
    3596             :  * from scratch.
    3597             :  */
    3598             : static void
    3599        2798 : set_deparse_for_query(deparse_namespace *dpns, Query *query,
    3600             :                       List *parent_namespaces)
    3601             : {
    3602             :     ListCell   *lc;
    3603             :     ListCell   *lc2;
    3604             : 
    3605             :     /* Initialize *dpns and fill rtable/ctes links */
    3606        2798 :     memset(dpns, 0, sizeof(deparse_namespace));
    3607        2798 :     dpns->rtable = query->rtable;
    3608        2798 :     dpns->subplans = NIL;
    3609        2798 :     dpns->ctes = query->cteList;
    3610        2798 :     dpns->appendrels = NULL;
    3611             : 
    3612             :     /* Assign a unique relation alias to each RTE */
    3613        2798 :     set_rtable_names(dpns, parent_namespaces, NULL);
    3614             : 
    3615             :     /* Initialize dpns->rtable_columns to contain zeroed structs */
    3616        2798 :     dpns->rtable_columns = NIL;
    3617       11302 :     while (list_length(dpns->rtable_columns) < list_length(dpns->rtable))
    3618        8504 :         dpns->rtable_columns = lappend(dpns->rtable_columns,
    3619             :                                        palloc0(sizeof(deparse_columns)));
    3620             : 
    3621             :     /* If it's a utility query, it won't have a jointree */
    3622        2798 :     if (query->jointree)
    3623             :     {
    3624             :         /* Detect whether global uniqueness of USING names is needed */
    3625        2784 :         dpns->unique_using =
    3626        2784 :             has_dangerous_join_using(dpns, (Node *) query->jointree);
    3627             : 
    3628             :         /*
    3629             :          * Select names for columns merged by USING, via a recursive pass over
    3630             :          * the query jointree.
    3631             :          */
    3632        2784 :         set_using_names(dpns, (Node *) query->jointree, NIL);
    3633             :     }
    3634             : 
    3635             :     /*
    3636             :      * Now assign remaining column aliases for each RTE.  We do this in a
    3637             :      * linear scan of the rtable, so as to process RTEs whether or not they
    3638             :      * are in the jointree (we mustn't miss NEW.*, INSERT target relations,
    3639             :      * etc).  JOIN RTEs must be processed after their children, but this is
    3640             :      * okay because they appear later in the rtable list than their children
    3641             :      * (cf Asserts in identify_join_columns()).
    3642             :      */
    3643       11302 :     forboth(lc, dpns->rtable, lc2, dpns->rtable_columns)
    3644             :     {
    3645        8504 :         RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
    3646        8504 :         deparse_columns *colinfo = (deparse_columns *) lfirst(lc2);
    3647             : 
    3648        8504 :         if (rte->rtekind == RTE_JOIN)
    3649         624 :             set_join_column_names(dpns, rte, colinfo);
    3650             :         else
    3651        7880 :             set_relation_column_names(dpns, rte, colinfo);
    3652             :     }
    3653        2798 : }
    3654             : 
    3655             : /*
    3656             :  * set_simple_column_names: fill in column aliases for non-query situations
    3657             :  *
    3658             :  * This handles EXPLAIN and cases where we only have relation RTEs.  Without
    3659             :  * a join tree, we can't do anything smart about join RTEs, but we don't
    3660             :  * need to (note that EXPLAIN should never see join alias Vars anyway).
    3661             :  * If we do hit a join RTE we'll just process it like a non-table base RTE.
    3662             :  */
    3663             : static void
    3664       20292 : set_simple_column_names(deparse_namespace *dpns)
    3665             : {
    3666             :     ListCell   *lc;
    3667             :     ListCell   *lc2;
    3668             : 
    3669             :     /* Initialize dpns->rtable_columns to contain zeroed structs */
    3670       20292 :     dpns->rtable_columns = NIL;
    3671       59394 :     while (list_length(dpns->rtable_columns) < list_length(dpns->rtable))
    3672       39102 :         dpns->rtable_columns = lappend(dpns->rtable_columns,
    3673             :                                        palloc0(sizeof(deparse_columns)));
    3674             : 
    3675             :     /* Assign unique column aliases within each RTE */
    3676       59394 :     forboth(lc, dpns->rtable, lc2, dpns->rtable_columns)
    3677             :     {
    3678       39102 :         RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
    3679       39102 :         deparse_columns *colinfo = (deparse_columns *) lfirst(lc2);
    3680             : 
    3681       39102 :         set_relation_column_names(dpns, rte, colinfo);
    3682             :     }
    3683       20292 : }
    3684             : 
    3685             : /*
    3686             :  * has_dangerous_join_using: search jointree for unnamed JOIN USING
    3687             :  *
    3688             :  * Merged columns of a JOIN USING may act differently from either of the input
    3689             :  * columns, either because they are merged with COALESCE (in a FULL JOIN) or
    3690             :  * because an implicit coercion of the underlying input column is required.
    3691             :  * In such a case the column must be referenced as a column of the JOIN not as
    3692             :  * a column of either input.  And this is problematic if the join is unnamed
    3693             :  * (alias-less): we cannot qualify the column's name with an RTE name, since
    3694             :  * there is none.  (Forcibly assigning an alias to the join is not a solution,
    3695             :  * since that will prevent legal references to tables below the join.)
    3696             :  * To ensure that every column in the query is unambiguously referenceable,
    3697             :  * we must assign such merged columns names that are globally unique across
    3698             :  * the whole query, aliasing other columns out of the way as necessary.
    3699             :  *
    3700             :  * Because the ensuing re-aliasing is fairly damaging to the readability of
    3701             :  * the query, we don't do this unless we have to.  So, we must pre-scan
    3702             :  * the join tree to see if we have to, before starting set_using_names().
    3703             :  */
    3704             : static bool
    3705        6352 : has_dangerous_join_using(deparse_namespace *dpns, Node *jtnode)
    3706             : {
    3707        6352 :     if (IsA(jtnode, RangeTblRef))
    3708             :     {
    3709             :         /* nothing to do here */
    3710             :     }
    3711        3364 :     else if (IsA(jtnode, FromExpr))
    3712             :     {
    3713        2784 :         FromExpr   *f = (FromExpr *) jtnode;
    3714             :         ListCell   *lc;
    3715             : 
    3716        5240 :         foreach(lc, f->fromlist)
    3717             :         {
    3718        2504 :             if (has_dangerous_join_using(dpns, (Node *) lfirst(lc)))
    3719          48 :                 return true;
    3720             :         }
    3721             :     }
    3722         580 :     else if (IsA(jtnode, JoinExpr))
    3723             :     {
    3724         580 :         JoinExpr   *j = (JoinExpr *) jtnode;
    3725             : 
    3726             :         /* Is it an unnamed JOIN with USING? */
    3727         580 :         if (j->alias == NULL && j->usingClause)
    3728             :         {
    3729             :             /*
    3730             :              * Yes, so check each join alias var to see if any of them are not
    3731             :              * simple references to underlying columns.  If so, we have a
    3732             :              * dangerous situation and must pick unique aliases.
    3733             :              */
    3734         180 :             RangeTblEntry *jrte = rt_fetch(j->rtindex, dpns->rtable);
    3735             : 
    3736             :             /* We need only examine the merged columns */
    3737         376 :             for (int i = 0; i < jrte->joinmergedcols; i++)
    3738             :             {
    3739         244 :                 Node       *aliasvar = list_nth(jrte->joinaliasvars, i);
    3740             : 
    3741         244 :                 if (!IsA(aliasvar, Var))
    3742          48 :                     return true;
    3743             :             }
    3744             :         }
    3745             : 
    3746             :         /* Nope, but inspect children */
    3747         532 :         if (has_dangerous_join_using(dpns, j->larg))
    3748           0 :             return true;
    3749         532 :         if (has_dangerous_join_using(dpns, j->rarg))
    3750           0 :             return true;
    3751             :     }
    3752             :     else
    3753           0 :         elog(ERROR, "unrecognized node type: %d",
    3754             :              (int) nodeTag(jtnode));
    3755        6256 :     return false;
    3756             : }
    3757             : 
    3758             : /*
    3759             :  * set_using_names: select column aliases to be used for merged USING columns
    3760             :  *
    3761             :  * We do this during a recursive descent of the query jointree.
    3762             :  * dpns->unique_using must already be set to determine the global strategy.
    3763             :  *
    3764             :  * Column alias info is saved in the dpns->rtable_columns list, which is
    3765             :  * assumed to be filled with pre-zeroed deparse_columns structs.
    3766             :  *
    3767             :  * parentUsing is a list of all USING aliases assigned in parent joins of
    3768             :  * the current jointree node.  (The passed-in list must not be modified.)
    3769             :  */
    3770             : static void
    3771        6564 : set_using_names(deparse_namespace *dpns, Node *jtnode, List *parentUsing)
    3772             : {
    3773        6564 :     if (IsA(jtnode, RangeTblRef))
    3774             :     {
    3775             :         /* nothing to do now */
    3776             :     }
    3777        3408 :     else if (IsA(jtnode, FromExpr))
    3778             :     {
    3779        2784 :         FromExpr   *f = (FromExpr *) jtnode;
    3780             :         ListCell   *lc;
    3781             : 
    3782        5316 :         foreach(lc, f->fromlist)
    3783        2532 :             set_using_names(dpns, (Node *) lfirst(lc), parentUsing);
    3784             :     }
    3785         624 :     else if (IsA(jtnode, JoinExpr))
    3786             :     {
    3787         624 :         JoinExpr   *j = (JoinExpr *) jtnode;
    3788         624 :         RangeTblEntry *rte = rt_fetch(j->rtindex, dpns->rtable);
    3789         624 :         deparse_columns *colinfo = deparse_columns_fetch(j->rtindex, dpns);
    3790             :         int        *leftattnos;
    3791             :         int        *rightattnos;
    3792             :         deparse_columns *leftcolinfo;
    3793             :         deparse_columns *rightcolinfo;
    3794             :         int         i;
    3795             :         ListCell   *lc;
    3796             : 
    3797             :         /* Get info about the shape of the join */
    3798         624 :         identify_join_columns(j, rte, colinfo);
    3799         624 :         leftattnos = colinfo->leftattnos;
    3800         624 :         rightattnos = colinfo->rightattnos;
    3801             : 
    3802             :         /* Look up the not-yet-filled-in child deparse_columns structs */
    3803         624 :         leftcolinfo = deparse_columns_fetch(colinfo->leftrti, dpns);
    3804         624 :         rightcolinfo = deparse_columns_fetch(colinfo->rightrti, dpns);
    3805             : 
    3806             :         /*
    3807             :          * If this join is unnamed, then we cannot substitute new aliases at
    3808             :          * this level, so any name requirements pushed down to here must be
    3809             :          * pushed down again to the children.
    3810             :          */
    3811         624 :         if (rte->alias == NULL)
    3812             :         {
    3813         652 :             for (i = 0; i < colinfo->num_cols; i++)
    3814             :             {
    3815          92 :                 char       *colname = colinfo->colnames[i];
    3816             : 
    3817          92 :                 if (colname == NULL)
    3818          16 :                     continue;
    3819             : 
    3820             :                 /* Push down to left column, unless it's a system column */
    3821          76 :                 if (leftattnos[i] > 0)
    3822             :                 {
    3823          68 :                     expand_colnames_array_to(leftcolinfo, leftattnos[i]);
    3824          68 :                     leftcolinfo->colnames[leftattnos[i] - 1] = colname;
    3825             :                 }
    3826             : 
    3827             :                 /* Same on the righthand side */
    3828          76 :                 if (rightattnos[i] > 0)
    3829             :                 {
    3830          76 :                     expand_colnames_array_to(rightcolinfo, rightattnos[i]);
    3831          76 :                     rightcolinfo->colnames[rightattnos[i] - 1] = colname;
    3832             :                 }
    3833             :             }
    3834             :         }
    3835             : 
    3836             :         /*
    3837             :          * If there's a USING clause, select the USING column names and push
    3838             :          * those names down to the children.  We have two strategies:
    3839             :          *
    3840             :          * If dpns->unique_using is true, we force all USING names to be
    3841             :          * unique across the whole query level.  In principle we'd only need
    3842             :          * the names of dangerous USING columns to be globally unique, but to
    3843             :          * safely assign all USING names in a single pass, we have to enforce
    3844             :          * the same uniqueness rule for all of them.  However, if a USING
    3845             :          * column's name has been pushed down from the parent, we should use
    3846             :          * it as-is rather than making a uniqueness adjustment.  This is
    3847             :          * necessary when we're at an unnamed join, and it creates no risk of
    3848             :          * ambiguity.  Also, if there's a user-written output alias for a
    3849             :          * merged column, we prefer to use that rather than the input name;
    3850             :          * this simplifies the logic and seems likely to lead to less aliasing
    3851             :          * overall.
    3852             :          *
    3853             :          * If dpns->unique_using is false, we only need USING names to be
    3854             :          * unique within their own join RTE.  We still need to honor
    3855             :          * pushed-down names, though.
    3856             :          *
    3857             :          * Though significantly different in results, these two strategies are
    3858             :          * implemented by the same code, with only the difference of whether
    3859             :          * to put assigned names into dpns->using_names.
    3860             :          */
    3861         624 :         if (j->usingClause)
    3862             :         {
    3863             :             /* Copy the input parentUsing list so we don't modify it */
    3864         264 :             parentUsing = list_copy(parentUsing);
    3865             : 
    3866             :             /* USING names must correspond to the first join output columns */
    3867         264 :             expand_colnames_array_to(colinfo, list_length(j->usingClause));
    3868         264 :             i = 0;
    3869         632 :             foreach(lc, j->usingClause)
    3870             :             {
    3871         368 :                 char       *colname = strVal(lfirst(lc));
    3872             : 
    3873             :                 /* Assert it's a merged column */
    3874             :                 Assert(leftattnos[i] != 0 && rightattnos[i] != 0);
    3875             : 
    3876             :                 /* Adopt passed-down name if any, else select unique name */
    3877         368 :                 if (colinfo->colnames[i] != NULL)
    3878          68 :                     colname = colinfo->colnames[i];
    3879             :                 else
    3880             :                 {
    3881             :                     /* Prefer user-written output alias if any */
    3882         300 :                     if (rte->alias && i < list_length(rte->alias->colnames))
    3883           0 :                         colname = strVal(list_nth(rte->alias->colnames, i));
    3884             :                     /* Make it appropriately unique */
    3885         300 :                     colname = make_colname_unique(colname, dpns, colinfo);
    3886         300 :                     if (dpns->unique_using)
    3887          84 :                         dpns->using_names = lappend(dpns->using_names,
    3888             :                                                     colname);
    3889             :                     /* Save it as output column name, too */
    3890         300 :                     colinfo->colnames[i] = colname;
    3891             :                 }
    3892             : 
    3893             :                 /* Remember selected names for use later */
    3894         368 :                 colinfo->usingNames = lappend(colinfo->usingNames, colname);
    3895         368 :                 parentUsing = lappend(parentUsing, colname);
    3896             : 
    3897             :                 /* Push down to left column, unless it's a system column */
    3898         368 :                 if (leftattnos[i] > 0)
    3899             :                 {
    3900         368 :                     expand_colnames_array_to(leftcolinfo, leftattnos[i]);
    3901         368 :                     leftcolinfo->colnames[leftattnos[i] - 1] = colname;
    3902             :                 }
    3903             : 
    3904             :                 /* Same on the righthand side */
    3905         368 :                 if (rightattnos[i] > 0)
    3906             :                 {
    3907         368 :                     expand_colnames_array_to(rightcolinfo, rightattnos[i]);
    3908         368 :                     rightcolinfo->colnames[rightattnos[i] - 1] = colname;
    3909             :                 }
    3910             : 
    3911         368 :                 i++;
    3912             :             }
    3913             :         }
    3914             : 
    3915             :         /* Mark child deparse_columns structs with correct parentUsing info */
    3916         624 :         leftcolinfo->parentUsing = parentUsing;
    3917         624 :         rightcolinfo->parentUsing = parentUsing;
    3918             : 
    3919             :         /* Now recursively assign USING column names in children */
    3920         624 :         set_using_names(dpns, j->larg, parentUsing);
    3921         624 :         set_using_names(dpns, j->rarg, parentUsing);
    3922             :     }
    3923             :     else
    3924           0 :         elog(ERROR, "unrecognized node type: %d",
    3925             :              (int) nodeTag(jtnode));
    3926        6564 : }
    3927             : 
    3928             : /*
    3929             :  * set_relation_column_names: select column aliases for a non-join RTE
    3930             :  *
    3931             :  * Column alias info is saved in *colinfo, which is assumed to be pre-zeroed.
    3932             :  * If any colnames entries are already filled in, those override local
    3933             :  * choices.
    3934             :  */
    3935             : static void
    3936       46982 : set_relation_column_names(deparse_namespace *dpns, RangeTblEntry *rte,
    3937             :                           deparse_columns *colinfo)
    3938             : {
    3939             :     int         ncolumns;
    3940             :     char      **real_colnames;
    3941             :     bool        changed_any;
    3942             :     int         noldcolumns;
    3943             :     int         i;
    3944             :     int         j;
    3945             : 
    3946             :     /*
    3947             :      * Extract the RTE's "real" column names.  This is comparable to
    3948             :      * get_rte_attribute_name, except that it's important to disregard dropped
    3949             :      * columns.  We put NULL into the array for a dropped column.
    3950             :      */
    3951       46982 :     if (rte->rtekind == RTE_RELATION)
    3952             :     {
    3953             :         /* Relation --- look to the system catalogs for up-to-date info */
    3954             :         Relation    rel;
    3955             :         TupleDesc   tupdesc;
    3956             : 
    3957       40434 :         rel = relation_open(rte->relid, AccessShareLock);
    3958       40434 :         tupdesc = RelationGetDescr(rel);
    3959             : 
    3960       40434 :         ncolumns = tupdesc->natts;
    3961       40434 :         real_colnames = (char **) palloc(ncolumns * sizeof(char *));
    3962             : 
    3963      240432 :         for (i = 0; i < ncolumns; i++)
    3964             :         {
    3965      199998 :             Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
    3966             : 
    3967      199998 :             if (attr->attisdropped)
    3968        1966 :                 real_colnames[i] = NULL;
    3969             :             else
    3970      198032 :                 real_colnames[i] = pstrdup(NameStr(attr->attname));
    3971             :         }
    3972       40434 :         relation_close(rel, AccessShareLock);
    3973             :     }
    3974             :     else
    3975             :     {
    3976             :         /* Otherwise use the column names from eref */
    3977             :         ListCell   *lc;
    3978             : 
    3979        6548 :         ncolumns = list_length(rte->eref->colnames);
    3980        6548 :         real_colnames = (char **) palloc(ncolumns * sizeof(char *));
    3981             : 
    3982        6548 :         i = 0;
    3983       38324 :         foreach(lc, rte->eref->colnames)
    3984             :         {
    3985             :             /*
    3986             :              * If the column name shown in eref is an empty string, then it's
    3987             :              * a column that was dropped at the time of parsing the query, so
    3988             :              * treat it as dropped.
    3989             :              */
    3990       31776 :             char       *cname = strVal(lfirst(lc));
    3991             : 
    3992       31776 :             if (cname[0] == '\0')
    3993          12 :                 cname = NULL;
    3994       31776 :             real_colnames[i] = cname;
    3995       31776 :             i++;
    3996             :         }
    3997             :     }
    3998             : 
    3999             :     /*
    4000             :      * Ensure colinfo->colnames has a slot for each column.  (It could be long
    4001             :      * enough already, if we pushed down a name for the last column.)  Note:
    4002             :      * it's possible that there are now more columns than there were when the
    4003             :      * query was parsed, ie colnames could be longer than rte->eref->colnames.
    4004             :      * We must assign unique aliases to the new columns too, else there could
    4005             :      * be unresolved conflicts when the view/rule is reloaded.
    4006             :      */
    4007       46982 :     expand_colnames_array_to(colinfo, ncolumns);
    4008             :     Assert(colinfo->num_cols == ncolumns);
    4009             : 
    4010             :     /*
    4011             :      * Make sufficiently large new_colnames and is_new_col arrays, too.
    4012             :      *
    4013             :      * Note: because we leave colinfo->num_new_cols zero until after the loop,
    4014             :      * colname_is_unique will not consult that array, which is fine because it
    4015             :      * would only be duplicate effort.
    4016             :      */
    4017       46982 :     colinfo->new_colnames = (char **) palloc(ncolumns * sizeof(char *));
    4018       46982 :     colinfo->is_new_col = (bool *) palloc(ncolumns * sizeof(bool));
    4019             : 
    4020             :     /*
    4021             :      * Scan the columns, select a unique alias for each one, and store it in
    4022             :      * colinfo->colnames and colinfo->new_colnames.  The former array has NULL
    4023             :      * entries for dropped columns, the latter omits them.  Also mark
    4024             :      * new_colnames entries as to whether they are new since parse time; this
    4025             :      * is the case for entries beyond the length of rte->eref->colnames.
    4026             :      */
    4027       46982 :     noldcolumns = list_length(rte->eref->colnames);
    4028       46982 :     changed_any = false;
    4029       46982 :     j = 0;
    4030      278756 :     for (i = 0; i < ncolumns; i++)
    4031             :     {
    4032      231774 :         char       *real_colname = real_colnames[i];
    4033      231774 :         char       *colname = colinfo->colnames[i];
    4034             : 
    4035             :         /* Skip dropped columns */
    4036      231774 :         if (real_colname == NULL)
    4037             :         {
    4038             :             Assert(colname == NULL);    /* colnames[i] is already NULL */
    4039        1978 :             continue;
    4040             :         }
    4041             : 
    4042             :         /* If alias already assigned, that's what to use */
    4043      229796 :         if (colname == NULL)
    4044             :         {
    4045             :             /* If user wrote an alias, prefer that over real column name */
    4046      229128 :             if (rte->alias && i < list_length(rte->alias->colnames))
    4047       24168 :                 colname = strVal(list_nth(rte->alias->colnames, i));
    4048             :             else
    4049      204960 :                 colname = real_colname;
    4050             : 
    4051             :             /* Unique-ify and insert into colinfo */
    4052      229128 :             colname = make_colname_unique(colname, dpns, colinfo);
    4053             : 
    4054      229128 :             colinfo->colnames[i] = colname;
    4055             :         }
    4056             : 
    4057             :         /* Put names of non-dropped columns in new_colnames[] too */
    4058      229796 :         colinfo->new_colnames[j] = colname;
    4059             :         /* And mark them as new or not */
    4060      229796 :         colinfo->is_new_col[j] = (i >= noldcolumns);
    4061      229796 :         j++;
    4062             : 
    4063             :         /* Remember if any assigned aliases differ from "real" name */
    4064      229796 :         if (!changed_any && strcmp(colname, real_colname) != 0)
    4065        2188 :             changed_any = true;
    4066             :     }
    4067             : 
    4068             :     /*
    4069             :      * Set correct length for new_colnames[] array.  (Note: if columns have
    4070             :      * been added, colinfo->num_cols includes them, which is not really quite
    4071             :      * right but is harmless, since any new columns must be at the end where
    4072             :      * they won't affect varattnos of pre-existing columns.)
    4073             :      */
    4074       46982 :     colinfo->num_new_cols = j;
    4075             : 
    4076             :     /*
    4077             :      * For a relation RTE, we need only print the alias column names if any
    4078             :      * are different from the underlying "real" names.  For a function RTE,
    4079             :      * always emit a complete column alias list; this is to protect against
    4080             :      * possible instability of the default column names (eg, from altering
    4081             :      * parameter names).  For tablefunc RTEs, we never print aliases, because
    4082             :      * the column names are part of the clause itself.  For other RTE types,
    4083             :      * print if we changed anything OR if there were user-written column
    4084             :      * aliases (since the latter would be part of the underlying "reality").
    4085             :      */
    4086       46982 :     if (rte->rtekind == RTE_RELATION)
    4087       40434 :         colinfo->printaliases = changed_any;
    4088        6548 :     else if (rte->rtekind == RTE_FUNCTION)
    4089         420 :         colinfo->printaliases = true;
    4090        6128 :     else if (rte->rtekind == RTE_TABLEFUNC)
    4091          36 :         colinfo->printaliases = false;
    4092        6092 :     else if (rte->alias && rte->alias->colnames != NIL)
    4093         236 :         colinfo->printaliases = true;
    4094             :     else
    4095        5856 :         colinfo->printaliases = changed_any;
    4096       46982 : }
    4097             : 
    4098             : /*
    4099             :  * set_join_column_names: select column aliases for a join RTE
    4100             :  *
    4101             :  * Column alias info is saved in *colinfo, which is assumed to be pre-zeroed.
    4102             :  * If any colnames entries are already filled in, those override local
    4103             :  * choices.  Also, names for USING columns were already chosen by
    4104             :  * set_using_names().  We further expect that column alias selection has been
    4105             :  * completed for both input RTEs.
    4106             :  */
    4107             : static void
    4108         624 : set_join_column_names(deparse_namespace *dpns, RangeTblEntry *rte,
    4109             :                       deparse_columns *colinfo)
    4110             : {
    4111             :     deparse_columns *leftcolinfo;
    4112             :     deparse_columns *rightcolinfo;
    4113             :     bool        changed_any;
    4114             :     int         noldcolumns;
    4115             :     int         nnewcolumns;
    4116         624 :     Bitmapset  *leftmerged = NULL;
    4117         624 :     Bitmapset  *rightmerged = NULL;
    4118             :     int         i;
    4119             :     int         j;
    4120             :     int         ic;
    4121             :     int         jc;
    4122             : 
    4123             :     /* Look up the previously-filled-in child deparse_columns structs */
    4124         624 :     leftcolinfo = deparse_columns_fetch(colinfo->leftrti, dpns);
    4125         624 :     rightcolinfo = deparse_columns_fetch(colinfo->rightrti, dpns);
    4126             : 
    4127             :     /*
    4128             :      * Ensure colinfo->colnames has a slot for each column.  (It could be long
    4129             :      * enough already, if we pushed down a name for the last column.)  Note:
    4130             :      * it's possible that one or both inputs now have more columns than there
    4131             :      * were when the query was parsed, but we'll deal with that below.  We
    4132             :      * only need entries in colnames for pre-existing columns.
    4133             :      */
    4134         624 :     noldcolumns = list_length(rte->eref->colnames);
    4135         624 :     expand_colnames_array_to(colinfo, noldcolumns);
    4136             :     Assert(colinfo->num_cols == noldcolumns);
    4137             : 
    4138             :     /*
    4139             :      * Scan the join output columns, select an alias for each one, and store
    4140             :      * it in colinfo->colnames.  If there are USING columns, set_using_names()
    4141             :      * already selected their names, so we can start the loop at the first
    4142             :      * non-merged column.
    4143             :      */
    4144         624 :     changed_any = false;
    4145       15784 :     for (i = list_length(colinfo->usingNames); i < noldcolumns; i++)
    4146             :     {
    4147       15160 :         char       *colname = colinfo->colnames[i];
    4148             :         char       *real_colname;
    4149             : 
    4150             :         /* Join column must refer to at least one input column */
    4151             :         Assert(colinfo->leftattnos[i] != 0 || colinfo->rightattnos[i] != 0);
    4152             : 
    4153             :         /* Get the child column name */
    4154       15160 :         if (colinfo->leftattnos[i] > 0)
    4155       10464 :             real_colname = leftcolinfo->colnames[colinfo->leftattnos[i] - 1];
    4156        4696 :         else if (colinfo->rightattnos[i] > 0)
    4157        4696 :             real_colname = rightcolinfo->colnames[colinfo->rightattnos[i] - 1];
    4158             :         else
    4159             :         {
    4160             :             /* We're joining system columns --- use eref name */
    4161           0 :             real_colname = strVal(list_nth(rte->eref->colnames, i));
    4162             :         }
    4163             : 
    4164             :         /* If child col has been dropped, no need to assign a join colname */
    4165       15160 :         if (real_colname == NULL)
    4166             :         {
    4167           4 :             colinfo->colnames[i] = NULL;
    4168           4 :             continue;
    4169             :         }
    4170             : 
    4171             :         /* In an unnamed join, just report child column names as-is */
    4172       15156 :         if (rte->alias == NULL)
    4173             :         {
    4174       14920 :             colinfo->colnames[i] = real_colname;
    4175       14920 :             continue;
    4176             :         }
    4177             : 
    4178             :         /* If alias already assigned, that's what to use */
    4179         236 :         if (colname == NULL)
    4180             :         {
    4181             :             /* If user wrote an alias, prefer that over real column name */
    4182         236 :             if (rte->alias && i < list_length(rte->alias->colnames))
    4183          64 :                 colname = strVal(list_nth(rte->alias->colnames, i));
    4184             :             else
    4185         172 :                 colname = real_colname;
    4186             : 
    4187             :             /* Unique-ify and insert into colinfo */
    4188         236 :             colname = make_colname_unique(colname, dpns, colinfo);
    4189             : 
    4190         236 :             colinfo->colnames[i] = colname;
    4191             :         }
    4192             : 
    4193             :         /* Remember if any assigned aliases differ from "real" name */
    4194         236 :         if (!changed_any && strcmp(colname, real_colname) != 0)
    4195          16 :             changed_any = true;
    4196             :     }
    4197             : 
    4198             :     /*
    4199             :      * Calculate number of columns the join would have if it were re-parsed
    4200             :      * now, and create storage for the new_colnames and is_new_col arrays.
    4201             :      *
    4202             :      * Note: colname_is_unique will be consulting new_colnames[] during the
    4203             :      * loops below, so its not-yet-filled entries must be zeroes.
    4204             :      */
    4205        1248 :     nnewcolumns = leftcolinfo->num_new_cols + rightcolinfo->num_new_cols -
    4206         624 :         list_length(colinfo->usingNames);
    4207         624 :     colinfo->num_new_cols = nnewcolumns;
    4208         624 :     colinfo->new_colnames = (char **) palloc0(nnewcolumns * sizeof(char *));
    4209         624 :     colinfo->is_new_col = (bool *) palloc0(nnewcolumns * sizeof(bool));
    4210             : 
    4211             :     /*
    4212             :      * Generating the new_colnames array is a bit tricky since any new columns
    4213             :      * added since parse time must be inserted in the right places.  This code
    4214             :      * must match the parser, which will order a join's columns as merged
    4215             :      * columns first (in USING-clause order), then non-merged columns from the
    4216             :      * left input (in attnum order), then non-merged columns from the right
    4217             :      * input (ditto).  If one of the inputs is itself a join, its columns will
    4218             :      * be ordered according to the same rule, which means newly-added columns
    4219             :      * might not be at the end.  We can figure out what's what by consulting
    4220             :      * the leftattnos and rightattnos arrays plus the input is_new_col arrays.
    4221             :      *
    4222             :      * In these loops, i indexes leftattnos/rightattnos (so it's join varattno
    4223             :      * less one), j indexes new_colnames/is_new_col, and ic/jc have similar
    4224             :      * meanings for the current child RTE.
    4225             :      */
    4226             : 
    4227             :     /* Handle merged columns; they are first and can't be new */
    4228         624 :     i = j = 0;
    4229         992 :     while (i < noldcolumns &&
    4230         992 :            colinfo->leftattnos[i] != 0 &&
    4231         992 :            colinfo->rightattnos[i] != 0)
    4232             :     {
    4233             :         /* column name is already determined and known unique */
    4234         368 :         colinfo->new_colnames[j] = colinfo->colnames[i];
    4235         368 :         colinfo->is_new_col[j] = false;
    4236             : 
    4237             :         /* build bitmapsets of child attnums of merged columns */
    4238         368 :         if (colinfo->leftattnos[i] > 0)
    4239         368 :             leftmerged = bms_add_member(leftmerged, colinfo->leftattnos[i]);
    4240         368 :         if (colinfo->rightattnos[i] > 0)
    4241         368 :             rightmerged = bms_add_member(rightmerged, colinfo->rightattnos[i]);
    4242             : 
    4243         368 :         i++, j++;
    4244             :     }
    4245             : 
    4246             :     /* Handle non-merged left-child columns */
    4247         624 :     ic = 0;
    4248       11780 :     for (jc = 0; jc < leftcolinfo->num_new_cols; jc++)
    4249             :     {
    4250       11156 :         char       *child_colname = leftcolinfo->new_colnames[jc];
    4251             : 
    4252       11156 :         if (!leftcolinfo->is_new_col[jc])
    4253             :         {
    4254             :             /* Advance ic to next non-dropped old column of left child */
    4255       10884 :             while (ic < leftcolinfo->num_cols &&
    4256       10884 :                    leftcolinfo->colnames[ic] == NULL)
    4257          56 :                 ic++;
    4258             :             Assert(ic < leftcolinfo->num_cols);
    4259       10828 :             ic++;
    4260             :             /* If it is a merged column, we already processed it */
    4261       10828 :             if (bms_is_member(ic, leftmerged))
    4262         368 :                 continue;
    4263             :             /* Else, advance i to the corresponding existing join column */
    4264       10464 :             while (i < colinfo->num_cols &&
    4265       10464 :                    colinfo->colnames[i] == NULL)
    4266           4 :                 i++;
    4267             :             Assert(i < colinfo->num_cols);
    4268             :             Assert(ic == colinfo->leftattnos[i]);
    4269             :             /* Use the already-assigned name of this column */
    4270       10460 :             colinfo->new_colnames[j] = colinfo->colnames[i];
    4271       10460 :             i++;
    4272             :         }
    4273             :         else
    4274             :         {
    4275             :             /*
    4276             :              * Unique-ify the new child column name and assign, unless we're
    4277             :              * in an unnamed join, in which case just copy
    4278             :              */
    4279         328 :             if (rte->alias != NULL)
    4280             :             {
    4281         176 :                 colinfo->new_colnames[j] =
    4282          88 :                     make_colname_unique(child_colname, dpns, colinfo);
    4283          88 :                 if (!changed_any &&
    4284          72 :                     strcmp(colinfo->new_colnames[j], child_colname) != 0)
    4285           8 :                     changed_any = true;
    4286             :             }
    4287             :             else
    4288         240 :                 colinfo->new_colnames[j] = child_colname;
    4289             :         }
    4290             : 
    4291       10788 :         colinfo->is_new_col[j] = leftcolinfo->is_new_col[jc];
    4292       10788 :         j++;
    4293             :     }
    4294             : 
    4295             :     /* Handle non-merged right-child columns in exactly the same way */
    4296         624 :     ic = 0;
    4297        5800 :     for (jc = 0; jc < rightcolinfo->num_new_cols; jc++)
    4298             :     {
    4299        5176 :         char       *child_colname = rightcolinfo->new_colnames[jc];
    4300             : 
    4301        5176 :         if (!rightcolinfo->is_new_col[jc])
    4302             :         {
    4303             :             /* Advance ic to next non-dropped old column of right child */
    4304        5064 :             while (ic < rightcolinfo->num_cols &&
    4305        5064 :                    rightcolinfo->colnames[ic] == NULL)
    4306           0 :                 ic++;
    4307             :             Assert(ic < rightcolinfo->num_cols);
    4308        5064 :             ic++;
    4309             :             /* If it is a merged column, we already processed it */
    4310        5064 :             if (bms_is_member(ic, rightmerged))
    4311         368 :                 continue;
    4312             :             /* Else, advance i to the corresponding existing join column */
    4313        4696 :             while (i < colinfo->num_cols &&
    4314        4696 :                    colinfo->colnames[i] == NULL)
    4315           0 :                 i++;
    4316             :             Assert(i < colinfo->num_cols);
    4317             :             Assert(ic == colinfo->rightattnos[i]);
    4318             :             /* Use the already-assigned name of this column */
    4319        4696 :             colinfo->new_colnames[j] = colinfo->colnames[i];
    4320        4696 :             i++;
    4321             :         }
    4322             :         else
    4323             :         {
    4324             :             /*
    4325             :              * Unique-ify the new child column name and assign, unless we're
    4326             :              * in an unnamed join, in which case just copy
    4327             :              */
    4328         112 :             if (rte->alias != NULL)
    4329             :             {
    4330          32 :                 colinfo->new_colnames[j] =
    4331          16 :                     make_colname_unique(child_colname, dpns, colinfo);
    4332          16 :                 if (!changed_any &&
    4333          16 :                     strcmp(colinfo->new_colnames[j], child_colname) != 0)
    4334           8 :                     changed_any = true;
    4335             :             }
    4336             :             else
    4337          96 :                 colinfo->new_colnames[j] = child_colname;
    4338             :         }
    4339             : 
    4340        4808 :         colinfo->is_new_col[j] = rightcolinfo->is_new_col[jc];
    4341        4808 :         j++;
    4342             :     }
    4343             : 
    4344             :     /* Assert we processed the right number of columns */
    4345             : #ifdef USE_ASSERT_CHECKING
    4346             :     while (i < colinfo->num_cols && colinfo->colnames[i] == NULL)
    4347             :         i++;
    4348             :     Assert(i == colinfo->num_cols);
    4349             :     Assert(j == nnewcolumns);
    4350             : #endif
    4351             : 
    4352             :     /*
    4353             :      * For a named join, print column aliases if we changed any from the child
    4354             :      * names.  Unnamed joins cannot print aliases.
    4355             :      */
    4356         624 :     if (rte->alias != NULL)
    4357          64 :         colinfo->printaliases = changed_any;
    4358             :     else
    4359         560 :         colinfo->printaliases = false;
    4360         624 : }
    4361             : 
    4362             : /*
    4363             :  * colname_is_unique: is colname distinct from already-chosen column names?
    4364             :  *
    4365             :  * dpns is query-wide info, colinfo is for the column's RTE
    4366             :  */
    4367             : static bool
    4368      240886 : colname_is_unique(const char *colname, deparse_namespace *dpns,
    4369             :                   deparse_columns *colinfo)
    4370             : {
    4371             :     int         i;
    4372             :     ListCell   *lc;
    4373             : 
    4374             :     /* Check against already-assigned column aliases within RTE */
    4375     3479736 :     for (i = 0; i < colinfo->num_cols; i++)
    4376             :     {
    4377     3249840 :         char       *oldname = colinfo->colnames[i];
    4378             : 
    4379     3249840 :         if (oldname && strcmp(oldname, colname) == 0)
    4380       10990 :             return false;
    4381             :     }
    4382             : 
    4383             :     /*
    4384             :      * If we're building a new_colnames array, check that too (this will be
    4385             :      * partially but not completely redundant with the previous checks)
    4386             :      */
    4387      230744 :     for (i = 0; i < colinfo->num_new_cols; i++)
    4388             :     {
    4389         864 :         char       *oldname = colinfo->new_colnames[i];
    4390             : 
    4391         864 :         if (oldname && strcmp(oldname, colname) == 0)
    4392          16 :             return false;
    4393             :     }
    4394             : 
    4395             :     /* Also check against USING-column names that must be globally unique */
    4396      230960 :     foreach(lc, dpns->using_names)
    4397             :     {
    4398        1188 :         char       *oldname = (char *) lfirst(lc);
    4399             : 
    4400        1188 :         if (strcmp(oldname, colname) == 0)
    4401         108 :             return false;
    4402             :     }
    4403             : 
    4404             :     /* Also check against names already assigned for parent-join USING cols */
    4405      231452 :     foreach(lc, colinfo->parentUsing)
    4406             :     {
    4407        1684 :         char       *oldname = (char *) lfirst(lc);
    4408             : 
    4409        1684 :         if (strcmp(oldname, colname) == 0)
    4410           4 :             return false;
    4411             :     }
    4412             : 
    4413      229768 :     return true;
    4414             : }
    4415             : 
    4416             : /*
    4417             :  * make_colname_unique: modify colname if necessary to make it unique
    4418             :  *
    4419             :  * dpns is query-wide info, colinfo is for the column's RTE
    4420             :  */
    4421             : static char *
    4422      229768 : make_colname_unique(char *colname, deparse_namespace *dpns,
    4423             :                     deparse_columns *colinfo)
    4424             : {
    4425             :     /*
    4426             :      * If the selected name isn't unique, append digits to make it so.  For a
    4427             :      * very long input name, we might have to truncate to stay within
    4428             :      * NAMEDATALEN.
    4429             :      */
    4430      229768 :     if (!colname_is_unique(colname, dpns, colinfo))
    4431             :     {
    4432        9886 :         int         colnamelen = strlen(colname);
    4433        9886 :         char       *modname = (char *) palloc(colnamelen + 16);
    4434        9886 :         int         i = 0;
    4435             : 
    4436             :         do
    4437             :         {
    4438       11118 :             i++;
    4439             :             for (;;)
    4440             :             {
    4441             :                 /*
    4442             :                  * We avoid using %.*s here because it can misbehave if the
    4443             :                  * data is not valid in what libc thinks is the prevailing
    4444             :                  * encoding.
    4445             :                  */
    4446           0 :                 memcpy(modname, colname, colnamelen);
    4447       11118 :                 sprintf(modname + colnamelen, "_%d", i);
    4448       11118 :                 if (strlen(modname) < NAMEDATALEN)
    4449       11118 :                     break;
    4450             :                 /* drop chars from colname to keep all the digits */
    4451           0 :                 colnamelen = pg_mbcliplen(colname, colnamelen,
    4452             :                                           colnamelen - 1);
    4453             :             }
    4454       11118 :         } while (!colname_is_unique(modname, dpns, colinfo));
    4455        9886 :         colname = modname;
    4456             :     }
    4457      229768 :     return colname;
    4458             : }
    4459             : 
    4460             : /*
    4461             :  * expand_colnames_array_to: make colinfo->colnames at least n items long
    4462             :  *
    4463             :  * Any added array entries are initialized to zero.
    4464             :  */
    4465             : static void
    4466       48750 : expand_colnames_array_to(deparse_columns *colinfo, int n)
    4467             : {
    4468       48750 :     if (n > colinfo->num_cols)
    4469             :     {
    4470       47652 :         if (colinfo->colnames == NULL)
    4471       46764 :             colinfo->colnames = (char **) palloc0(n * sizeof(char *));
    4472             :         else
    4473             :         {
    4474         888 :             colinfo->colnames = (char **) repalloc(colinfo->colnames,
    4475             :                                                    n * sizeof(char *));
    4476         888 :             memset(colinfo->colnames + colinfo->num_cols, 0,
    4477         888 :                    (n - colinfo->num_cols) * sizeof(char *));
    4478             :         }
    4479       47652 :         colinfo->num_cols = n;
    4480             :     }
    4481       48750 : }
    4482             : 
    4483             : /*
    4484             :  * identify_join_columns: figure out where columns of a join come from
    4485             :  *
    4486             :  * Fills the join-specific fields of the colinfo struct, except for
    4487             :  * usingNames which is filled later.
    4488             :  */
    4489             : static void
    4490         624 : identify_join_columns(JoinExpr *j, RangeTblEntry *jrte,
    4491             :                       deparse_columns *colinfo)
    4492             : {
    4493             :     int         numjoincols;
    4494             :     int         jcolno;
    4495             :     int         rcolno;
    4496             :     ListCell   *lc;
    4497             : 
    4498             :     /* Extract left/right child RT indexes */
    4499         624 :     if (IsA(j->larg, RangeTblRef))
    4500         420 :         colinfo->leftrti = ((RangeTblRef *) j->larg)->rtindex;
    4501         204 :     else if (IsA(j->larg, JoinExpr))
    4502         204 :         colinfo->leftrti = ((JoinExpr *) j->larg)->rtindex;
    4503             :     else
    4504           0 :         elog(ERROR, "unrecognized node type in jointree: %d",
    4505             :              (int) nodeTag(j->larg));
    4506         624 :     if (IsA(j->rarg, RangeTblRef))
    4507         624 :         colinfo->rightrti = ((RangeTblRef *) j->rarg)->rtindex;
    4508           0 :     else if (IsA(j->rarg, JoinExpr))
    4509           0 :         colinfo->rightrti = ((JoinExpr *) j->rarg)->rtindex;
    4510             :     else
    4511           0 :         elog(ERROR, "unrecognized node type in jointree: %d",
    4512             :              (int) nodeTag(j->rarg));
    4513             : 
    4514             :     /* Assert children will be processed earlier than join in second pass */
    4515             :     Assert(colinfo->leftrti < j->rtindex);
    4516             :     Assert(colinfo->rightrti < j->rtindex);
    4517             : 
    4518             :     /* Initialize result arrays with zeroes */
    4519         624 :     numjoincols = list_length(jrte->joinaliasvars);
    4520             :     Assert(numjoincols == list_length(jrte->eref->colnames));
    4521         624 :     colinfo->leftattnos = (int *) palloc0(numjoincols * sizeof(int));
    4522         624 :     colinfo->rightattnos = (int *) palloc0(numjoincols * sizeof(int));
    4523             : 
    4524             :     /*
    4525             :      * Deconstruct RTE's joinleftcols/joinrightcols into desired format.
    4526             :      * Recall that the column(s) merged due to USING are the first column(s)
    4527             :      * of the join output.  We need not do anything special while scanning
    4528             :      * joinleftcols, but while scanning joinrightcols we must distinguish
    4529             :      * merged from unmerged columns.
    4530             :      */
    4531         624 :     jcolno = 0;
    4532       11456 :     foreach(lc, jrte->joinleftcols)
    4533             :     {
    4534       10832 :         int         leftattno = lfirst_int(lc);
    4535             : 
    4536       10832 :         colinfo->leftattnos[jcolno++] = leftattno;
    4537             :     }
    4538         624 :     rcolno = 0;
    4539        5688 :     foreach(lc, jrte->joinrightcols)
    4540             :     {
    4541        5064 :         int         rightattno = lfirst_int(lc);
    4542             : 
    4543        5064 :         if (rcolno < jrte->joinmergedcols)    /* merged column? */
    4544         368 :             colinfo->rightattnos[rcolno] = rightattno;
    4545             :         else
    4546        4696 :             colinfo->rightattnos[jcolno++] = rightattno;
    4547        5064 :         rcolno++;
    4548             :     }
    4549             :     Assert(jcolno == numjoincols);
    4550         624 : }
    4551             : 
    4552             : /*
    4553             :  * get_rtable_name: convenience function to get a previously assigned RTE alias
    4554             :  *
    4555             :  * The RTE must belong to the topmost namespace level in "context".
    4556             :  */
    4557             : static char *
    4558        2690 : get_rtable_name(int rtindex, deparse_context *context)
    4559             : {
    4560        2690 :     deparse_namespace *dpns = (deparse_namespace *) linitial(context->namespaces);
    4561             : 
    4562             :     Assert(rtindex > 0 && rtindex <= list_length(dpns->rtable_names));
    4563        2690 :     return (char *) list_nth(dpns->rtable_names, rtindex - 1);
    4564             : }
    4565             : 
    4566             : /*
    4567             :  * set_deparse_plan: set up deparse_namespace to parse subexpressions
    4568             :  * of a given Plan node
    4569             :  *
    4570             :  * This sets the plan, outer_plan, inner_plan, outer_tlist, inner_tlist,
    4571             :  * and index_tlist fields.  Caller is responsible for adjusting the ancestors
    4572             :  * list if necessary.  Note that the rtable, subplans, and ctes fields do
    4573             :  * not need to change when shifting attention to different plan nodes in a
    4574             :  * single plan tree.
    4575             :  */
    4576             : static void
    4577       57852 : set_deparse_plan(deparse_namespace *dpns, Plan *plan)
    4578             : {
    4579       57852 :     dpns->plan = plan;
    4580             : 
    4581             :     /*
    4582             :      * We special-case Append and MergeAppend to pretend that the first child
    4583             :      * plan is the OUTER referent; we have to interpret OUTER Vars in their
    4584             :      * tlists according to one of the children, and the first one is the most
    4585             :      * natural choice.  Likewise special-case ModifyTable to pretend that the
    4586             :      * first child plan is the OUTER referent; this is to support RETURNING
    4587             :      * lists containing references to non-target relations.
    4588             :      */
    4589       57852 :     if (IsA(plan, Append))
    4590        2252 :         dpns->outer_plan = linitial(((Append *) plan)->appendplans);
    4591       55600 :     else if (IsA(plan, MergeAppend))
    4592         268 :         dpns->outer_plan = linitial(((MergeAppend *) plan)->mergeplans);
    4593       55332 :     else if (IsA(plan, ModifyTable))
    4594         148 :         dpns->outer_plan = linitial(((ModifyTable *) plan)->plans);
    4595             :     else
    4596       55184 :         dpns->outer_plan = outerPlan(plan);
    4597             : 
    4598       57852 :     if (dpns->outer_plan)
    4599       26070 :         dpns->outer_tlist = dpns->outer_plan->targetlist;
    4600             :     else
    4601       31782 :         dpns->outer_tlist = NIL;
    4602             : 
    4603             :     /*
    4604             :      * For a SubqueryScan, pretend the subplan is INNER referent.  (We don't
    4605             :      * use OUTER because that could someday conflict with the normal meaning.)
    4606             :      * Likewise, for a CteScan, pretend the subquery's plan is INNER referent.
    4607             :      * For ON CONFLICT .. UPDATE we just need the inner tlist to point to the
    4608             :      * excluded expression's tlist. (Similar to the SubqueryScan we don't want
    4609             :      * to reuse OUTER, it's used for RETURNING in some modify table cases,
    4610             :      * although not INSERT .. CONFLICT).
    4611             :      */
    4612       57852 :     if (IsA(plan, SubqueryScan))
    4613         240 :         dpns->inner_plan = ((SubqueryScan *) plan)->subplan;
    4614       57612 :     else if (IsA(plan, CteScan))
    4615         210 :         dpns->inner_plan = list_nth(dpns->subplans,
    4616         210 :                                     ((CteScan *) plan)->ctePlanId - 1);
    4617       57402 :     else if (IsA(plan, ModifyTable))
    4618         148 :         dpns->inner_plan = plan;
    4619             :     else
    4620       57254 :         dpns->inner_plan = innerPlan(plan);
    4621             : 
    4622       57852 :     if (IsA(plan, ModifyTable))
    4623         148 :         dpns->inner_tlist = ((ModifyTable *) plan)->exclRelTlist;
    4624       57704 :     else if (dpns->inner_plan)
    4625        9452 :         dpns->inner_tlist = dpns->inner_plan->targetlist;
    4626             :     else
    4627       48252 :         dpns->inner_tlist = NIL;
    4628             : 
    4629             :     /* Set up referent for INDEX_VAR Vars, if needed */
    4630       57852 :     if (IsA(plan, IndexOnlyScan))
    4631        1324 :         dpns->index_tlist = ((IndexOnlyScan *) plan)->indextlist;
    4632       56528 :     else if (IsA(plan, ForeignScan))
    4633        2052 :         dpns->index_tlist = ((ForeignScan *) plan)->fdw_scan_tlist;
    4634       54476 :     else if (IsA(plan, CustomScan))
    4635           0 :         dpns->index_tlist = ((CustomScan *) plan)->custom_scan_tlist;
    4636             :     else
    4637       54476 :         dpns->index_tlist = NIL;
    4638       57852 : }
    4639             : 
    4640             : /*
    4641             :  * push_child_plan: temporarily transfer deparsing attention to a child plan
    4642             :  *
    4643             :  * When expanding an OUTER_VAR or INNER_VAR reference, we must adjust the
    4644             :  * deparse context in case the referenced expression itself uses
    4645             :  * OUTER_VAR/INNER_VAR.  We modify the top stack entry in-place to avoid
    4646             :  * affecting levelsup issues (although in a Plan tree there really shouldn't
    4647             :  * be any).
    4648             :  *
    4649             :  * Caller must provide a local deparse_namespace variable to save the
    4650             :  * previous state for pop_child_plan.
    4651             :  */
    4652             : static void
    4653       32370 : push_child_plan(deparse_namespace *dpns, Plan *plan,
    4654             :                 deparse_namespace *save_dpns)
    4655             : {
    4656             :     /* Save state for restoration later */
    4657       32370 :     *save_dpns = *dpns;
    4658             : 
    4659             :     /* Link current plan node into ancestors list */
    4660       32370 :     dpns->ancestors = lcons(dpns->plan, dpns->ancestors);
    4661             : 
    4662             :     /* Set attention on selected child */
    4663       32370 :     set_deparse_plan(dpns, plan);
    4664       32370 : }
    4665             : 
    4666             : /*
    4667             :  * pop_child_plan: undo the effects of push_child_plan
    4668             :  */
    4669             : static void
    4670       32370 : pop_child_plan(deparse_namespace *dpns, deparse_namespace *save_dpns)
    4671             : {
    4672             :     List       *ancestors;
    4673             : 
    4674             :     /* Get rid of ancestors list cell added by push_child_plan */
    4675       32370 :     ancestors = list_delete_first(dpns->ancestors);
    4676             : 
    4677             :     /* Restore fields changed by push_child_plan */
    4678       32370 :     *dpns = *save_dpns;
    4679             : 
    4680             :     /* Make sure dpns->ancestors is right (may be unnecessary) */
    4681       32370 :     dpns->ancestors = ancestors;
    4682       32370 : }
    4683             : 
    4684             : /*
    4685             :  * push_ancestor_plan: temporarily transfer deparsing attention to an
    4686             :  * ancestor plan
    4687             :  *
    4688             :  * When expanding a Param reference, we must adjust the deparse context
    4689             :  * to match the plan node that contains the expression being printed;
    4690             :  * otherwise we'd fail if that expression itself contains a Param or
    4691             :  * OUTER_VAR/INNER_VAR/INDEX_VAR variable.
    4692             :  *
    4693             :  * The target ancestor is conveniently identified by the ListCell holding it
    4694             :  * in dpns->ancestors.
    4695             :  *
    4696             :  * Caller must provide a local deparse_namespace variable to save the
    4697             :  * previous state for pop_ancestor_plan.
    4698             :  */
    4699             : static void
    4700        1494 : push_ancestor_plan(deparse_namespace *dpns, ListCell *ancestor_cell,
    4701             :                    deparse_namespace *save_dpns)
    4702             : {
    4703        1494 :     Plan       *plan = (Plan *) lfirst(ancestor_cell);
    4704             : 
    4705             :     /* Save state for restoration later */
    4706        1494 :     *save_dpns = *dpns;
    4707             : 
    4708             :     /* Build a new ancestor list with just this node's ancestors */
    4709        1494 :     dpns->ancestors =
    4710        1494 :         list_copy_tail(dpns->ancestors,
    4711        1494 :                        list_cell_number(dpns->ancestors, ancestor_cell) + 1);
    4712             : 
    4713             :     /* Set attention on selected ancestor */
    4714        1494 :     set_deparse_plan(dpns, plan);
    4715        1494 : }
    4716             : 
    4717             : /*
    4718             :  * pop_ancestor_plan: undo the effects of push_ancestor_plan
    4719             :  */
    4720             : static void
    4721        1494 : pop_ancestor_plan(deparse_namespace *dpns, deparse_namespace *save_dpns)
    4722             : {
    4723             :     /* Free the ancestor list made in push_ancestor_plan */
    4724        1494 :     list_free(dpns->ancestors);
    4725             : 
    4726             :     /* Restore fields changed by push_ancestor_plan */
    4727        1494 :     *dpns = *save_dpns;
    4728        1494 : }
    4729             : 
    4730             : 
    4731             : /* ----------
    4732             :  * make_ruledef         - reconstruct the CREATE RULE command
    4733             :  *                for a given pg_rewrite tuple
    4734             :  * ----------
    4735             :  */
    4736             : static void
    4737         404 : make_ruledef(StringInfo buf, HeapTuple ruletup, TupleDesc rulettc,
    4738             :              int prettyFlags)
    4739             : {
    4740             :     char       *rulename;
    4741             :     char        ev_type;
    4742             :     Oid         ev_class;
    4743             :     bool        is_instead;
    4744             :     char       *ev_qual;
    4745             :     char       *ev_action;
    4746         404 :     List       *actions = NIL;
    4747             :     Relation    ev_relation;
    4748         404 :     TupleDesc   viewResultDesc = NULL;
    4749             :     int         fno;
    4750             :     Datum       dat;
    4751             :     bool        isnull;
    4752             : 
    4753             :     /*
    4754             :      * Get the attribute values from the rules tuple
    4755             :      */
    4756         404 :     fno = SPI_fnumber(rulettc, "rulename");
    4757         404 :     dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
    4758             :     Assert(!isnull);
    4759         404 :     rulename = NameStr(*(DatumGetName(dat)));
    4760             : 
    4761         404 :     fno = SPI_fnumber(rulettc, "ev_type");
    4762         404 :     dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
    4763             :     Assert(!isnull);
    4764         404 :     ev_type = DatumGetChar(dat);
    4765             : 
    4766         404 :     fno = SPI_fnumber(rulettc, "ev_class");
    4767         404 :     dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
    4768             :     Assert(!isnull);
    4769         404 :     ev_class = DatumGetObjectId(dat);
    4770             : 
    4771         404 :     fno = SPI_fnumber(rulettc, "is_instead");
    4772         404 :     dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
    4773             :     Assert(!isnull);
    4774         404 :     is_instead = DatumGetBool(dat);
    4775             : 
    4776             :     /* these could be nulls */
    4777         404 :     fno = SPI_fnumber(rulettc, "ev_qual");
    4778         404 :     ev_qual = SPI_getvalue(ruletup, rulettc, fno);
    4779             : 
    4780         404 :     fno = SPI_fnumber(rulettc, "ev_action");
    4781         404 :     ev_action = SPI_getvalue(ruletup, rulettc, fno);
    4782         404 :     if (ev_action != NULL)
    4783         404 :         actions = (List *) stringToNode(ev_action);
    4784             : 
    4785         404 :     ev_relation = table_open(ev_class, AccessShareLock);
    4786             : 
    4787             :     /*
    4788             :      * Build the rules definition text
    4789             :      */
    4790         404 :     appendStringInfo(buf, "CREATE RULE %s AS",
    4791             :                      quote_identifier(rulename));
    4792             : 
    4793         404 :     if (prettyFlags & PRETTYFLAG_INDENT)
    4794         404 :         appendStringInfoString(buf, "\n    ON ");
    4795             :     else
    4796           0 :         appendStringInfoString(buf, " ON ");
    4797             : 
    4798             :     /* The event the rule is fired for */
    4799         404 :     switch (ev_type)
    4800             :     {
    4801           4 :         case '1':
    4802           4 :             appendStringInfoString(buf, "SELECT");
    4803           4 :             viewResultDesc = RelationGetDescr(ev_relation);
    4804           4 :             break;
    4805             : 
    4806         110 :         case '2':
    4807         110 :             appendStringInfoString(buf, "UPDATE");
    4808         110 :             break;
    4809             : 
    4810         218 :         case '3':
    4811         218 :             appendStringInfoString(buf, "INSERT");
    4812         218 :             break;
    4813             : 
    4814          72 :         case '4':
    4815          72 :             appendStringInfoString(buf, "DELETE");
    4816          72 :             break;
    4817             : 
    4818           0 :         default:
    4819           0 :             ereport(ERROR,
    4820             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    4821             :                      errmsg("rule \"%s\" has unsupported event type %d",
    4822             :                             rulename, ev_type)));
    4823             :             break;
    4824             :     }
    4825             : 
    4826             :     /* The relation the rule is fired on */
    4827         404 :     appendStringInfo(buf, " TO %s",
    4828         404 :                      (prettyFlags & PRETTYFLAG_SCHEMA) ?
    4829          64 :                      generate_relation_name(ev_class, NIL) :
    4830         340 :                      generate_qualified_relation_name(ev_class));
    4831             : 
    4832             :     /* If the rule has an event qualification, add it */
    4833         404 :     if (ev_qual == NULL)
    4834           0 :         ev_qual = "";
    4835         404 :     if (strlen(ev_qual) > 0 && strcmp(ev_qual, "<>") != 0)
    4836             :     {
    4837             :         Node       *qual;
    4838             :         Query      *query;
    4839             :         deparse_context context;
    4840             :         deparse_namespace dpns;
    4841             : 
    4842         110 :         if (prettyFlags & PRETTYFLAG_INDENT)
    4843         110 :             appendStringInfoString(buf, "\n  ");
    4844         110 :         appendStringInfoString(buf, " WHERE ");
    4845             : 
    4846         110 :         qual = stringToNode(ev_qual);
    4847             : 
    4848             :         /*
    4849             :          * We need to make a context for recognizing any Vars in the qual
    4850             :          * (which can only be references to OLD and NEW).  Use the rtable of
    4851             :          * the first query in the action list for this purpose.
    4852             :          */
    4853         110 :         query = (Query *) linitial(actions);
    4854             : 
    4855             :         /*
    4856             :          * If the action is INSERT...SELECT, OLD/NEW have been pushed down
    4857             :          * into the SELECT, and that's what we need to look at. (Ugly kluge
    4858             :          * ... try to fix this when we redesign querytrees.)
    4859             :          */
    4860         110 :         query = getInsertSelectQuery(query, NULL);
    4861             : 
    4862             :         /* Must acquire locks right away; see notes in get_query_def() */
    4863         110 :         AcquireRewriteLocks(query, false, false);
    4864             : 
    4865         110 :         context.buf = buf;
    4866         110 :         context.namespaces = list_make1(&dpns);
    4867         110 :         context.windowClause = NIL;
    4868         110 :         context.windowTList = NIL;
    4869         110 :         context.varprefix = (list_length(query->rtable) != 1);
    4870         110 :         context.prettyFlags = prettyFlags;
    4871         110 :         context.wrapColumn = WRAP_COLUMN_DEFAULT;
    4872         110 :         context.indentLevel = PRETTYINDENT_STD;
    4873         110 :         context.special_exprkind = EXPR_KIND_NONE;
    4874         110 :         context.appendparents = NULL;
    4875             : 
    4876         110 :         set_deparse_for_query(&dpns, query, NIL);
    4877             : 
    4878         110 :         get_rule_expr(qual, &context, false);
    4879             :     }
    4880             : 
    4881         404 :     appendStringInfoString(buf, " DO ");
    4882             : 
    4883             :     /* The INSTEAD keyword (if so) */
    4884         404 :     if (is_instead)
    4885         236 :         appendStringInfoString(buf, "INSTEAD ");
    4886             : 
    4887             :     /* Finally the rules actions */
    4888         404 :     if (list_length(actions) > 1)
    4889             :     {
    4890             :         ListCell   *action;
    4891             :         Query      *query;
    4892             : 
    4893          20 :         appendStringInfoChar(buf, '(');
    4894          60 :         foreach(action, actions)
    4895             :         {
    4896          40 :             query = (Query *) lfirst(action);
    4897          40 :             get_query_def(query, buf, NIL, viewResultDesc,
    4898             :                           prettyFlags, WRAP_COLUMN_DEFAULT, 0);
    4899          40 :             if (prettyFlags)
    4900          40 :                 appendStringInfoString(buf, ";\n");
    4901             :             else
    4902           0 :                 appendStringInfoString(buf, "; ");
    4903             :         }
    4904          20 :         appendStringInfoString(buf, ");");
    4905             :     }
    4906         384 :     else if (list_length(actions) == 0)
    4907             :     {
    4908           0 :         appendStringInfoString(buf, "NOTHING;");
    4909             :     }
    4910             :     else
    4911             :     {
    4912             :         Query      *query;
    4913             : 
    4914         384 :         query = (Query *) linitial(actions);
    4915         384 :         get_query_def(query, buf, NIL, viewResultDesc,
    4916             :                       prettyFlags, WRAP_COLUMN_DEFAULT, 0);
    4917         384 :         appendStringInfoChar(buf, ';');
    4918             :     }
    4919             : 
    4920         404 :     table_close(ev_relation, AccessShareLock);
    4921         404 : }
    4922             : 
    4923             : 
    4924             : /* ----------
    4925             :  * make_viewdef         - reconstruct the SELECT part of a
    4926             :  *                view rewrite rule
    4927             :  * ----------
    4928             :  */
    4929             : static void
    4930        1688 : make_viewdef(StringInfo buf, HeapTuple ruletup, TupleDesc rulettc,
    4931             :              int prettyFlags, int wrapColumn)
    4932             : {
    4933             :     Query      *query;
    4934             :     char        ev_type;
    4935             :     Oid         ev_class;
    4936             :     bool        is_instead;
    4937             :     char       *ev_qual;
    4938             :     char       *ev_action;
    4939        1688 :     List       *actions = NIL;
    4940             :     Relation    ev_relation;
    4941             :     int         fno;
    4942             :     Datum       dat;
    4943             :     bool        isnull;
    4944             : 
    4945             :     /*
    4946             :      * Get the attribute values from the rules tuple
    4947             :      */
    4948        1688 :     fno = SPI_fnumber(rulettc, "ev_type");
    4949        1688 :     dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
    4950             :     Assert(!isnull);
    4951        1688 :     ev_type = DatumGetChar(dat);
    4952             : 
    4953        1688 :     fno = SPI_fnumber(rulettc, "ev_class");
    4954        1688 :     dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
    4955             :     Assert(!isnull);
    4956        1688 :     ev_class = DatumGetObjectId(dat);
    4957             : 
    4958        1688 :     fno = SPI_fnumber(rulettc, "is_instead");
    4959        1688 :     dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
    4960             :     Assert(!isnull);
    4961        1688 :     is_instead = DatumGetBool(dat);
    4962             : 
    4963             :     /* these could be nulls */
    4964        1688 :     fno = SPI_fnumber(rulettc, "ev_qual");
    4965        1688 :     ev_qual = SPI_getvalue(ruletup, rulettc, fno);
    4966             : 
    4967        1688 :     fno = SPI_fnumber(rulettc, "ev_action");
    4968        1688 :     ev_action = SPI_getvalue(ruletup, rulettc, fno);
    4969        1688 :     if (ev_action != NULL)
    4970        1688 :         actions = (List *) stringToNode(ev_action);
    4971             : 
    4972        1688 :     if (list_length(actions) != 1)
    4973             :     {
    4974             :         /* keep output buffer empty and leave */
    4975           0 :         return;
    4976             :     }
    4977             : 
    4978        1688 :     query = (Query *) linitial(actions);
    4979             : 
    4980        1688 :     if (ev_type != '1' || !is_instead ||
    4981        1688 :         strcmp(ev_qual, "<>") != 0 || query->commandType != CMD_SELECT)
    4982             :     {
    4983             :         /* keep output buffer empty and leave */
    4984           0 :         return;
    4985             :     }
    4986             : 
    4987        1688 :     ev_relation = table_open(ev_class, AccessShareLock);
    4988             : 
    4989        1688 :     get_query_def(query, buf, NIL, RelationGetDescr(ev_relation),
    4990             :                   prettyFlags, wrapColumn, 0);
    4991        1688 :     appendStringInfoChar(buf, ';');
    4992             : 
    4993        1688 :     table_close(ev_relation, AccessShareLock);
    4994             : }
    4995             : 
    4996             : 
    4997             : /* ----------
    4998             :  * get_query_def            - Parse back one query parsetree
    4999             :  *
    5000             :  * If resultDesc is not NULL, then it is the output tuple descriptor for
    5001             :  * the view represented by a SELECT query.
    5002             :  * ----------
    5003             :  */
    5004             : static void
    5005        2672 : get_query_def(Query *query, StringInfo buf, List *parentnamespace,
    5006             :               TupleDesc resultDesc,
    5007             :               int prettyFlags, int wrapColumn, int startIndent)
    5008             : {
    5009             :     deparse_context context;
    5010             :     deparse_namespace dpns;
    5011             : 
    5012             :     /* Guard against excessively long or deeply-nested queries */
    5013        2672 :     CHECK_FOR_INTERRUPTS();
    5014        2672 :     check_stack_depth();
    5015             : 
    5016             :     /*
    5017             :      * Before we begin to examine the query, acquire locks on referenced
    5018             :      * relations, and fix up deleted columns in JOIN RTEs.  This ensures
    5019             :      * consistent results.  Note we assume it's OK to scribble on the passed
    5020             :      * querytree!
    5021             :      *
    5022             :      * We are only deparsing the query (we are not about to execute it), so we
    5023             :      * only need AccessShareLock on the relations it mentions.
    5024             :      */
    5025        2672 :     AcquireRewriteLocks(query, false, false);
    5026             : 
    5027        2672 :     context.buf = buf;
    5028        2672 :     context.namespaces = lcons(&dpns, list_copy(parentnamespace));
    5029        2672 :     context.windowClause = NIL;
    5030        2672 :     context.windowTList = NIL;
    5031        4798 :     context.varprefix = (parentnamespace != NIL ||
    5032        2126 :                          list_length(query->rtable) != 1);
    5033        2672 :     context.prettyFlags = prettyFlags;
    5034        2672 :     context.wrapColumn = wrapColumn;
    5035        2672 :     context.indentLevel = startIndent;
    5036        2672 :     context.special_exprkind = EXPR_KIND_NONE;
    5037        2672 :     context.appendparents = NULL;
    5038             : 
    5039        2672 :     set_deparse_for_query(&dpns, query, parentnamespace);
    5040             : 
    5041        2672 :     switch (query->commandType)
    5042             :     {
    5043        2270 :         case CMD_SELECT:
    5044        2270 :             get_select_query_def(query, &context, resultDesc);
    5045        2270 :             break;
    5046             : 
    5047          88 :         case CMD_UPDATE:
    5048          88 :             get_update_query_def(query, &context);
    5049          88 :             break;
    5050             : 
    5051         216 :         case CMD_INSERT:
    5052         216 :             get_insert_query_def(query, &context);
    5053         216 :             break;
    5054             : 
    5055          50 :         case CMD_DELETE:
    5056          50 :             get_delete_query_def(query, &context);
    5057          50 :             break;
    5058             : 
    5059          34 :         case CMD_NOTHING:
    5060          34 :             appendStringInfoString(buf, "NOTHING");
    5061          34 :             break;
    5062             : 
    5063          14 :         case CMD_UTILITY:
    5064          14 :             get_utility_query_def(query, &context);
    5065          14 :             break;
    5066             : 
    5067           0 :         default:
    5068           0 :             elog(ERROR, "unrecognized query command type: %d",
    5069             :                  query->commandType);
    5070             :             break;
    5071             :     }
    5072        2672 : }
    5073             : 
    5074             : /* ----------
    5075             :  * get_values_def           - Parse back a VALUES list
    5076             :  * ----------
    5077             :  */
    5078             : static void
    5079         164 : get_values_def(List *values_lists, deparse_context *context)
    5080             : {
    5081         164 :     StringInfo  buf = context->buf;
    5082         164 :     bool        first_list = true;
    5083             :     ListCell   *vtl;
    5084             : 
    5085         164 :     appendStringInfoString(buf, "VALUES ");
    5086             : 
    5087         464 :     foreach(vtl, values_lists)
    5088             :     {
    5089         300 :         List       *sublist = (List *) lfirst(vtl);
    5090         300 :         bool        first_col = true;
    5091             :         ListCell   *lc;
    5092             : 
    5093         300 :         if (first_list)
    5094         164 :             first_list = false;
    5095             :         else
    5096         136 :             appendStringInfoString(buf, ", ");
    5097             : 
    5098         300 :         appendStringInfoChar(buf, '(');
    5099        1164 :         foreach(lc, sublist)
    5100             :         {
    5101         864 :             Node       *col = (Node *) lfirst(lc);
    5102             : 
    5103         864 :             if (first_col)
    5104         300 :                 first_col = false;
    5105             :             else
    5106         564 :                 appendStringInfoChar(buf, ',');
    5107             : 
    5108             :             /*
    5109             :              * Print the value.  Whole-row Vars need special treatment.
    5110             :              */
    5111         864 :             get_rule_expr_toplevel(col, context, false);
    5112             :         }
    5113         300 :         appendStringInfoChar(buf, ')');
    5114             :     }
    5115         164 : }
    5116             : 
    5117             : /* ----------
    5118             :  * get_with_clause          - Parse back a WITH clause
    5119             :  * ----------
    5120             :  */
    5121             : static void
    5122        2624 : get_with_clause(Query *query, deparse_context *context)
    5123             : {
    5124        2624 :     StringInfo  buf = context->buf;
    5125             :     const char *sep;
    5126             :     ListCell   *l;
    5127             : 
    5128        2624 :     if (query->cteList == NIL)
    5129        2592 :         return;
    5130             : 
    5131          32 :     if (PRETTY_INDENT(context))
    5132             :     {
    5133          32 :         context->indentLevel += PRETTYINDENT_STD;
    5134          32 :         appendStringInfoChar(buf, ' ');
    5135             :     }
    5136             : 
    5137          32 :     if (query->hasRecursive)
    5138          24 :         sep = "WITH RECURSIVE ";
    5139             :     else
    5140           8 :         sep = "WITH ";
    5141          64 :     foreach(l, query->cteList)
    5142             :     {
    5143          32 :         CommonTableExpr *cte = (CommonTableExpr *) lfirst(l);
    5144             : 
    5145          32 :         appendStringInfoString(buf, sep);
    5146          32 :         appendStringInfoString(buf, quote_identifier(cte->ctename));
    5147          32 :         if (cte->aliascolnames)
    5148             :         {
    5149          16 :             bool        first = true;
    5150             :             ListCell   *col;
    5151             : 
    5152          16 :             appendStringInfoChar(buf, '(');
    5153          32 :             foreach(col, cte->aliascolnames)
    5154             :             {
    5155          16 :                 if (first)
    5156          16 :                     first = false;
    5157             :                 else
    5158           0 :                     appendStringInfoString(buf, ", ");
    5159          16 :                 appendStringInfoString(buf,
    5160          16 :                                        quote_identifier(strVal(lfirst(col))));
    5161             :             }
    5162          16 :             appendStringInfoChar(buf, ')');
    5163             :         }
    5164          32 :         appendStringInfoString(buf, " AS ");
    5165          32 :         switch (cte->ctematerialized)
    5166             :         {
    5167          24 :             case CTEMaterializeDefault:
    5168          24 :                 break;
    5169           8 :             case CTEMaterializeAlways:
    5170           8 :                 appendStringInfoString(buf, "MATERIALIZED ");
    5171           8 :                 break;
    5172           0 :             case CTEMaterializeNever:
    5173           0 :                 appendStringInfoString(buf, "NOT MATERIALIZED ");
    5174           0 :                 break;
    5175             :         }
    5176          32 :         appendStringInfoChar(buf, '(');
    5177          32 :         if (PRETTY_INDENT(context))
    5178          32 :             appendContextKeyword(context, "", 0, 0, 0);
    5179          32 :         get_query_def((Query *) cte->ctequery, buf, context->namespaces, NULL,
    5180             :                       context->prettyFlags, context->wrapColumn,
    5181             :                       context->indentLevel);
    5182          32 :         if (PRETTY_INDENT(context))
    5183          32 :             appendContextKeyword(context, "", 0, 0, 0);
    5184          32 :         appendStringInfoChar(buf, ')');
    5185          32 :         sep = ", ";
    5186             :     }
    5187             : 
    5188          32 :     if (PRETTY_INDENT(context))
    5189             :     {
    5190          32 :         context->indentLevel -= PRETTYINDENT_STD;
    5191          32 :         appendContextKeyword(context, "", 0, 0, 0);
    5192             :     }
    5193             :     else
    5194           0 :         appendStringInfoChar(buf, ' ');
    5195             : }
    5196             : 
    5197             : /* ----------
    5198             :  * get_select_query_def         - Parse back a SELECT parsetree
    5199             :  * ----------
    5200             :  */
    5201             : static void
    5202        2270 : get_select_query_def(Query *query, deparse_context *context,
    5203             :                      TupleDesc resultDesc)
    5204             : {
    5205        2270 :     StringInfo  buf = context->buf;
    5206             :     List       *save_windowclause;
    5207             :     List       *save_windowtlist;
    5208             :     bool        force_colno;
    5209             :     ListCell   *l;
    5210             : 
    5211             :     /* Insert the WITH clause if given */
    5212        2270 :     get_with_clause(query, context);
    5213             : 
    5214             :     /* Set up context for possible window functions */
    5215        2270 :     save_windowclause = context->windowClause;
    5216        2270 :     context->windowClause = query->windowClause;
    5217        2270 :     save_windowtlist = context->windowTList;
    5218        2270 :     context->windowTList = query->targetList;
    5219             : 
    5220             :     /*
    5221             :      * If the Query node has a setOperations tree, then it's the top level of
    5222             :      * a UNION/INTERSECT/EXCEPT query; only the WITH, ORDER BY and LIMIT
    5223             :      * fields are interesting in the top query itself.
    5224             :      */
    5225        2270 :     if (query->setOperations)
    5226             :     {
    5227          80 :         get_setop_query(query->setOperations, query, context, resultDesc);
    5228             :         /* ORDER BY clauses must be simple in this case */
    5229          80 :         force_colno = true;
    5230             :     }
    5231             :     else
    5232             :     {
    5233        2190 :         get_basic_select_query(query, context, resultDesc);
    5234        2190 :         force_colno = false;
    5235             :     }
    5236             : 
    5237             :     /* Add the ORDER BY clause if given */
    5238        2270 :     if (query->sortClause != NIL)
    5239             :     {
    5240          70 :         appendContextKeyword(context, " ORDER BY ",
    5241             :                              -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
    5242          70 :         get_rule_orderby(query->sortClause, query->targetList,
    5243             :                          force_colno, context);
    5244             :     }
    5245             : 
    5246             :     /*
    5247             :      * Add the LIMIT/OFFSET clauses if given. If non-default options, use the
    5248             :      * standard spelling of LIMIT.
    5249             :      */
    5250        2270 :     if (query->limitOffset != NULL)
    5251             :     {
    5252          20 :         appendContextKeyword(context, " OFFSET ",
    5253             :                              -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
    5254          20 :         get_rule_expr(query->limitOffset, context, false);
    5255             :     }
    5256        2270 :     if (query->limitCount != NULL)
    5257             :     {
    5258          44 :         if (query->limitOption == LIMIT_OPTION_WITH_TIES)
    5259             :         {
    5260          20 :             appendContextKeyword(context, " FETCH FIRST ",
    5261             :                                  -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
    5262          20 :             get_rule_expr(query->limitCount, context, false);
    5263          20 :             appendStringInfo(buf, " ROWS WITH TIES");
    5264             :         }
    5265             :         else
    5266             :         {
    5267          24 :             appendContextKeyword(context, " LIMIT ",
    5268             :                                  -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
    5269          24 :             if (IsA(query->limitCount, Const) &&
    5270          10 :                 ((Const *) query->limitCount)->constisnull)
    5271          10 :                 appendStringInfoString(buf, "ALL");
    5272             :             else
    5273          14 :                 get_rule_expr(query->limitCount, context, false);
    5274             :         }
    5275             :     }
    5276             : 
    5277             :     /* Add FOR [KEY] UPDATE/SHARE clauses if present */
    5278        2270 :     if (query->hasForUpdate)
    5279             :     {
    5280           0 :         foreach(l, query->rowMarks)
    5281             :         {
    5282           0 :             RowMarkClause *rc = (RowMarkClause *) lfirst(l);
    5283             : 
    5284             :             /* don't print implicit clauses */
    5285           0 :             if (rc->pushedDown)
    5286           0 :                 continue;
    5287             : 
    5288           0 :             switch (rc->strength)
    5289             :             {
    5290           0 :                 case LCS_NONE:
    5291             :                     /* we intentionally throw an error for LCS_NONE */
    5292           0 :                     elog(ERROR, "unrecognized LockClauseStrength %d",
    5293             :                          (int) rc->strength);
    5294             :                     break;
    5295           0 :                 case LCS_FORKEYSHARE:
    5296           0 :                     appendContextKeyword(context, " FOR KEY SHARE",
    5297             :                                          -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
    5298           0 :                     break;
    5299           0 :                 case LCS_FORSHARE:
    5300           0 :                     appendContextKeyword(context, " FOR SHARE",
    5301             :                                          -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
    5302           0 :                     break;
    5303           0 :                 case LCS_FORNOKEYUPDATE:
    5304           0 :                     appendContextKeyword(context, " FOR NO KEY UPDATE",
    5305             :                                          -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
    5306           0 :                     break;
    5307           0 :                 case LCS_FORUPDATE:
    5308           0 :                     appendContextKeyword(context, " FOR UPDATE",
    5309             :                                          -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
    5310           0 :                     break;
    5311             :             }
    5312             : 
    5313           0 :             appendStringInfo(buf, " OF %s",
    5314           0 :                              quote_identifier(get_rtable_name(rc->rti,
    5315             :                                                               context)));
    5316           0 :             if (rc->waitPolicy == LockWaitError)
    5317           0 :                 appendStringInfoString(buf, " NOWAIT");
    5318           0 :             else if (rc->waitPolicy == LockWaitSkip)
    5319           0 :                 appendStringInfoString(buf, " SKIP LOCKED");
    5320             :         }
    5321             :     }
    5322             : 
    5323        2270 :     context->windowClause = save_windowclause;
    5324        2270 :     context->windowTList = save_windowtlist;
    5325        2270 : }
    5326             : 
    5327             : /*
    5328             :  * Detect whether query looks like SELECT ... FROM VALUES(),
    5329             :  * with no need to rename the output columns of the VALUES RTE.
    5330             :  * If so, return the VALUES RTE.  Otherwise return NULL.
    5331             :  */
    5332             : static RangeTblEntry *
    5333        2190 : get_simple_values_rte(Query *query, TupleDesc resultDesc)
    5334             : {
    5335        2190 :     RangeTblEntry *result = NULL;
    5336             :     ListCell   *lc;
    5337             : 
    5338             :     /*
    5339             :      * We want to detect a match even if the Query also contains OLD or NEW
    5340             :      * rule RTEs.  So the idea is to scan the rtable and see if there is only
    5341             :      * one inFromCl RTE that is a VALUES RTE.
    5342             :      */
    5343        5680 :     foreach(lc, query->rtable)
    5344             :     {
    5345        5308 :         RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
    5346             : 
    5347        5308 :         if (rte->rtekind == RTE_VALUES && rte->inFromCl)
    5348             :         {
    5349         146 :             if (result)
    5350        1818 :                 return NULL;    /* multiple VALUES (probably not possible) */
    5351         146 :             result = rte;
    5352             :         }
    5353        5162 :         else if (rte->rtekind == RTE_RELATION && !rte->inFromCl)
    5354        3344 :             continue;           /* ignore rule entries */
    5355             :         else
    5356        1818 :             return NULL;        /* something else -> not simple VALUES */
    5357             :     }
    5358             : 
    5359             :     /*
    5360             :      * We don't need to check the targetlist in any great detail, because
    5361             :      * parser/analyze.c will never generate a "bare" VALUES RTE --- they only
    5362             :      * appear inside auto-generated sub-queries with very restricted
    5363             :      * structure.  However, DefineView might have modified the tlist by
    5364             :      * injecting new column aliases, or we might have some other column
    5365             :      * aliases forced by a resultDesc.  We can only simplify if the RTE's
    5366             :      * column names match the names that get_target_list() would select.
    5367             :      */
    5368         372 :     if (result)
    5369             :     {
    5370             :         ListCell   *lcn;
    5371             :         int         colno;
    5372             : 
    5373         146 :         if (list_length(query->targetList) != list_length(result->eref->colnames))
    5374           0 :             return NULL;        /* this probably cannot happen */
    5375         146 :         colno = 0;
    5376         556 :         forboth(lc, query->targetList, lcn, result->eref->colnames)
    5377             :         {
    5378         418 :             TargetEntry *tle = (TargetEntry *) lfirst(lc);
    5379         418 :             char       *cname = strVal(lfirst(lcn));
    5380             :             char       *colname;
    5381             : 
    5382         418 :             if (tle->resjunk)
    5383           8 :                 return NULL;    /* this probably cannot happen */
    5384             : 
    5385             :             /* compute name that get_target_list would use for column */
    5386         418 :             colno++;
    5387         418 :             if (resultDesc && colno <= resultDesc->natts)
    5388          20 :                 colname = NameStr(TupleDescAttr(resultDesc, colno - 1)->attname);
    5389             :             else
    5390         398 :                 colname = tle->resname;
    5391             : 
    5392             :             /* does it match the VALUES RTE? */
    5393         418 :             if (colname == NULL || strcmp(colname, cname) != 0)
    5394           8 :                 return NULL;    /* column name has been changed */
    5395             :         }
    5396             :     }
    5397             : 
    5398         364 :     return result;
    5399             : }
    5400             : 
    5401             : static void
    5402        2190 : get_basic_select_query(Query *query, deparse_context *context,
    5403             :                        TupleDesc resultDesc)
    5404             : {
    5405        2190 :     StringInfo  buf = context->buf;
    5406             :     RangeTblEntry *values_rte;
    5407             :     char       *sep;
    5408             :     ListCell   *l;
    5409             : 
    5410        2190 :     if (PRETTY_INDENT(context))
    5411             :     {
    5412        2190 :         context->indentLevel += PRETTYINDENT_STD;
    5413        2190 :         appendStringInfoChar(buf, ' ');
    5414             :     }
    5415             : 
    5416             :     /*
    5417             :      * If the query looks like SELECT * FROM (VALUES ...), then print just the
    5418             :      * VALUES part.  This reverses what transformValuesClause() did at parse
    5419             :      * time.
    5420             :      */
    5421        2190 :     values_rte = get_simple_values_rte(query, resultDesc);
    5422        2190 :     if (values_rte)
    5423             :     {
    5424         138 :         get_values_def(values_rte->values_lists, context);
    5425         138 :         return;
    5426             :     }
    5427             : 
    5428             :     /*
    5429             :      * Build up the query string - first we say SELECT
    5430             :      */
    5431        2052 :     appendStringInfoString(buf, "SELECT");
    5432             : 
    5433             :     /* Add the DISTINCT clause if given */
    5434        2052 :     if (query->distinctClause != NIL)
    5435             :     {
    5436           0 :         if (query->hasDistinctOn)
    5437             :         {
    5438           0 :             appendStringInfoString(buf, " DISTINCT ON (");
    5439           0 :             sep = "";
    5440           0 :             foreach(l, query->distinctClause)
    5441             :             {
    5442           0 :                 SortGroupClause *srt = (SortGroupClause *) lfirst(l);
    5443             : 
    5444           0 :                 appendStringInfoString(buf, sep);
    5445           0 :                 get_rule_sortgroupclause(srt->tleSortGroupRef, query->targetList,
    5446             :                                          false, context);
    5447           0 :                 sep = ", ";
    5448             :             }
    5449           0 :             appendStringInfoChar(buf, ')');
    5450             :         }
    5451             :         else
    5452           0 :             appendStringInfoString(buf, " DISTINCT");
    5453             :     }
    5454             : 
    5455             :     /* Then we tell what to select (the targetlist) */
    5456        2052 :     get_target_list(query->targetList, context, resultDesc);
    5457             : 
    5458             :     /* Add the FROM clause if needed */
    5459        2052 :     get_from_clause(query, " FROM ", context);
    5460             : 
    5461             :     /* Add the WHERE clause if given */
    5462        2052 :     if (query->jointree->quals != NULL)
    5463             :     {
    5464         712 :         appendContextKeyword(context, " WHERE ",
    5465             :                              -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
    5466         712 :         get_rule_expr(query->jointree->quals, context, false);
    5467             :     }
    5468             : 
    5469             :     /* Add the GROUP BY clause if given */
    5470        2052 :     if (query->groupClause != NULL || query->groupingSets != NULL)
    5471             :     {
    5472             :         ParseExprKind save_exprkind;
    5473             : 
    5474          66 :         appendContextKeyword(context, " GROUP BY ",
    5475             :                              -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
    5476             : 
    5477          66 :         save_exprkind = context->special_exprkind;
    5478          66 :         context->special_exprkind = EXPR_KIND_GROUP_BY;
    5479             : 
    5480          66 :         if (query->groupingSets == NIL)
    5481             :         {
    5482          62 :             sep = "";
    5483         166 :             foreach(l, query->groupClause)
    5484             :             {
    5485         104 :                 SortGroupClause *grp = (SortGroupClause *) lfirst(l);
    5486             : 
    5487         104 :                 appendStringInfoString(buf, sep);
    5488         104 :                 get_rule_sortgroupclause(grp->tleSortGroupRef, query->targetList,
    5489             :                                          false, context);
    5490         104 :                 sep = ", ";
    5491             :             }
    5492             :         }
    5493             :         else
    5494             :         {
    5495           4 :             sep = "";
    5496           8 :             foreach(l, query->groupingSets)
    5497             :             {
    5498           4 :                 GroupingSet *grp = lfirst(l);
    5499             : 
    5500           4 :                 appendStringInfoString(buf, sep);
    5501           4 :                 get_rule_groupingset(grp, query->targetList, true, context);
    5502           4 :                 sep = ", ";
    5503             :             }
    5504             :         }
    5505             : 
    5506          66 :         context->special_exprkind = save_exprkind;
    5507             :     }
    5508             : 
    5509             :     /* Add the HAVING clause if given */
    5510        2052 :     if (query->havingQual != NULL)
    5511             :     {
    5512          10 :         appendContextKeyword(context, " HAVING ",
    5513             :                              -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
    5514          10 :         get_rule_expr(query->havingQual, context, false);
    5515             :     }
    5516             : 
    5517             :     /* Add the WINDOW clause if needed */
    5518        2052 :     if (query->windowClause != NIL)
    5519          28 :         get_rule_windowclause(query, context);
    5520             : }
    5521             : 
    5522             : /* ----------
    5523             :  * get_target_list          - Parse back a SELECT target list
    5524             :  *
    5525             :  * This is also used for RETURNING lists in INSERT/UPDATE/DELETE.
    5526             :  * ----------
    5527             :  */
    5528             : static void
    5529        2086 : get_target_list(List *targetList, deparse_context *context,
    5530             :                 TupleDesc resultDesc)
    5531             : {
    5532        2086 :     StringInfo  buf = context->buf;
    5533             :     StringInfoData targetbuf;
    5534        2086 :     bool        last_was_multiline = false;
    5535             :     char       *sep;
    5536             :     int         colno;
    5537             :     ListCell   *l;
    5538             : 
    5539             :     /* we use targetbuf to hold each TLE's text temporarily */
    5540        2086 :     initStringInfo(&targetbuf);
    5541             : 
    5542        2086 :     sep = " ";
    5543        2086 :     colno = 0;
    5544        9216 :     foreach(l, targetList)
    5545             :     {
    5546        7130 :         TargetEntry *tle = (TargetEntry *) lfirst(l);
    5547             :         char       *colname;
    5548             :         char       *attname;
    5549             : 
    5550        7130 :         if (tle->resjunk)
    5551          30 :             continue;           /* ignore junk entries */
    5552             : 
    5553        7100 :         appendStringInfoString(buf, sep);
    5554        7100 :         sep = ", ";
    5555        7100 :         colno++;
    5556             : 
    5557             :         /*
    5558             :          * Put the new field text into targetbuf so we can decide after we've
    5559             :          * got it whether or not it needs to go on a new line.
    5560             :          */
    5561        7100 :         resetStringInfo(&targetbuf);
    5562        7100 :         context->buf = &targetbuf;
    5563             : 
    5564             :         /*
    5565             :          * We special-case Var nodes rather than using get_rule_expr. This is
    5566             :          * needed because get_rule_expr will display a whole-row Var as
    5567             :          * "foo.*", which is the preferred notation in most contexts, but at
    5568             :          * the top level of a SELECT list it's not right (the parser will
    5569             :          * expand that notation into multiple columns, yielding behavior
    5570             :          * different from a whole-row Var).  We need to call get_variable
    5571             :          * directly so that we can tell it to do the right thing, and so that
    5572             :          * we can get the attribute name which is the default AS label.
    5573             :          */
    5574        7100 :         if (tle->expr && (IsA(tle->expr, Var)))
    5575             :         {
    5576        5608 :             attname = get_variable((Var *) tle->expr, 0, true, context);
    5577             :         }
    5578             :         else
    5579             :         {
    5580        1492 :             get_rule_expr((Node *) tle->expr, context, true);
    5581             :             /* We'll show the AS name unless it's this: */
    5582        1492 :             attname = "?column?";
    5583             :         }
    5584             : 
    5585             :         /*
    5586             :          * Figure out what the result column should be called.  In the context
    5587             :          * of a view, use the view's tuple descriptor (so as to pick up the
    5588             :          * effects of any column RENAME that's been done on the view).
    5589             :          * Otherwise, just use what we can find in the TLE.
    5590             :          */
    5591        7100 :         if (resultDesc && colno <= resultDesc->natts)
    5592        6678 :             colname = NameStr(TupleDescAttr(resultDesc, colno - 1)->attname);
    5593             :         else
    5594         422 :             colname = tle->resname;
    5595             : 
    5596             :         /* Show AS unless the column's name is correct as-is */
    5597        7100 :         if (colname)            /* resname could be NULL */
    5598             :         {
    5599        7100 :             if (attname == NULL || strcmp(attname, colname) != 0)
    5600        2018 :                 appendStringInfo(&targetbuf, " AS %s", quote_identifier(colname));
    5601             :         }
    5602             : 
    5603             :         /* Restore context's output buffer */
    5604        7100 :         context->buf = buf;
    5605             : 
    5606             :         /* Consider line-wrapping if enabled */
    5607        7100 :         if (PRETTY_INDENT(context) && context->wrapColumn >= 0)
    5608             :         {
    5609             :             int         leading_nl_pos;
    5610             : 
    5611             :             /* Does the new field start with a new line? */
    5612        7100 :             if (targetbuf.len > 0 && targetbuf.data[0] == '\n')
    5613         108 :                 leading_nl_pos = 0;
    5614             :             else
    5615        6992 :                 leading_nl_pos = -1;
    5616             : 
    5617             :             /* If so, we shouldn't add anything */
    5618        7100 :             if (leading_nl_pos >= 0)
    5619             :             {
    5620             :                 /* instead, remove any trailing spaces currently in buf */
    5621         108 :                 removeStringInfoSpaces(buf);
    5622             :             }
    5623             :             else
    5624             :             {
    5625             :                 char       *trailing_nl;
    5626             : 
    5627             :                 /* Locate the start of the current line in the output buffer */
    5628        6992 :                 trailing_nl = strrchr(buf->data, '\n');
    5629        6992 :                 if (trailing_nl == NULL)
    5630        2656 :                     trailing_nl = buf->data;
    5631             :                 else
    5632        4336 :                     trailing_nl++;
    5633             : 
    5634             :                 /*
    5635             :                  * Add a newline, plus some indentation, if the new field is
    5636             :                  * not the first and either the new field would cause an
    5637             :                  * overflow or the last field used more than one line.
    5638             :                  */
    5639        6992 :                 if (colno > 1 &&
    5640        4916 :                     ((strlen(trailing_nl) + targetbuf.len > context->wrapColumn) ||
    5641             :                      last_was_multiline))
    5642        4916 :                     appendContextKeyword(context, "", -PRETTYINDENT_STD,
    5643             :                                          PRETTYINDENT_STD, PRETTYINDENT_VAR);
    5644             :             }
    5645             : 
    5646             :             /* Remember this field's multiline status for next iteration */
    5647        7100 :             last_was_multiline =
    5648        7100 :                 (strchr(targetbuf.data + leading_nl_pos + 1, '\n') != NULL);
    5649             :         }
    5650             : 
    5651             :         /* Add the new field */
    5652        7100 :         appendBinaryStringInfo(buf, targetbuf.data, targetbuf.len);
    5653             :     }
    5654             : 
    5655             :     /* clean up */
    5656        2086 :     pfree(targetbuf.data);
    5657        2086 : }
    5658             : 
    5659             : static void
    5660         328 : get_setop_query(Node *setOp, Query *query, deparse_context *context,
    5661             :                 TupleDesc resultDesc)
    5662             : {
    5663         328 :     StringInfo  buf = context->buf;
    5664             :     bool        need_paren;
    5665             : 
    5666             :     /* Guard against excessively long or deeply-nested queries */
    5667         328 :     CHECK_FOR_INTERRUPTS();
    5668         328 :     check_stack_depth();
    5669             : 
    5670         328 :     if (IsA(setOp, RangeTblRef))
    5671             :     {
    5672         204 :         RangeTblRef *rtr = (RangeTblRef *) setOp;
    5673         204 :         RangeTblEntry *rte = rt_fetch(rtr->rtindex, query->rtable);
    5674         204 :         Query      *subquery = rte->subquery;
    5675             : 
    5676             :         Assert(subquery != NULL);
    5677             :         Assert(subquery->setOperations == NULL);
    5678             :         /* Need parens if WITH, ORDER BY, FOR UPDATE, or LIMIT; see gram.y */
    5679         612 :         need_paren = (subquery->cteList ||
    5680         204 :                       subquery->sortClause ||
    5681         204 :                       subquery->rowMarks ||
    5682         612 :                       subquery->limitOffset ||
    5683         204 :                       subquery->limitCount);
    5684         204 :         if (need_paren)
    5685           0 :             appendStringInfoChar(buf, '(');
    5686         204 :         get_query_def(subquery, buf, context->namespaces, resultDesc,
    5687             :                       context->prettyFlags, context->wrapColumn,
    5688             :                       context->indentLevel);
    5689         204 :         if (need_paren)
    5690           0 :             appendStringInfoChar(buf, ')');
    5691             :     }
    5692         124 :     else if (IsA(setOp, SetOperationStmt))
    5693             :     {
    5694         124 :         SetOperationStmt *op = (SetOperationStmt *) setOp;
    5695             :         int         subindent;
    5696             : 
    5697             :         /*
    5698             :          * We force parens when nesting two SetOperationStmts, except when the
    5699             :          * lefthand input is another setop of the same kind.  Syntactically,
    5700             :          * we could omit parens in rather more cases, but it seems best to use
    5701             :          * parens to flag cases where the setop operator changes.  If we use
    5702             :          * parens, we also increase the indentation level for the child query.
    5703             :          *
    5704             :          * There are some cases in which parens are needed around a leaf query
    5705             :          * too, but those are more easily handled at the next level down (see
    5706             :          * code above).
    5707             :          */
    5708         124 :         if (IsA(op->larg, SetOperationStmt))
    5709             :         {
    5710          44 :             SetOperationStmt *lop = (SetOperationStmt *) op->larg;
    5711             : 
    5712          44 :             if (op->op == lop->op && op->all == lop->all)
    5713          44 :                 need_paren = false;
    5714             :             else
    5715           0 :                 need_paren = true;
    5716             :         }
    5717             :         else
    5718          80 :             need_paren = false;
    5719             : 
    5720         124 :         if (need_paren)
    5721             :         {
    5722           0 :             appendStringInfoChar(buf, '(');
    5723           0 :             subindent = PRETTYINDENT_STD;
    5724           0 :             appendContextKeyword(context, "", subindent, 0, 0);
    5725             :         }
    5726             :         else
    5727         124 :             subindent = 0;
    5728             : 
    5729         124 :         get_setop_query(op->larg, query, context, resultDesc);
    5730             : 
    5731         124 :         if (need_paren)
    5732           0 :             appendContextKeyword(context, ") ", -subindent, 0, 0);
    5733         124 :         else if (PRETTY_INDENT(context))
    5734         124 :             appendContextKeyword(context, "", -subindent, 0, 0);
    5735             :         else
    5736           0 :             appendStringInfoChar(buf, ' ');
    5737             : 
    5738         124 :         switch (op->op)
    5739             :         {
    5740         124 :             case SETOP_UNION:
    5741         124 :                 appendStringInfoString(buf, "UNION ");
    5742         124 :                 break;
    5743           0 :             case SETOP_INTERSECT:
    5744           0 :                 appendStringInfoString(buf, "INTERSECT ");
    5745           0 :                 break;
    5746           0 :             case SETOP_EXCEPT:
    5747           0 :                 appendStringInfoString(buf, "EXCEPT ");
    5748           0 :                 break;
    5749           0 :             default:
    5750           0 :                 elog(ERROR, "unrecognized set op: %d",
    5751             :                      (int) op->op);
    5752             :         }
    5753         124 :         if (op->all)
    5754         116 :             appendStringInfoString(buf, "ALL ");
    5755             : 
    5756             :         /* Always parenthesize if RHS is another setop */
    5757         124 :         need_paren = IsA(op->rarg, SetOperationStmt);
    5758             : 
    5759             :         /*
    5760             :          * The indentation code here is deliberately a bit different from that
    5761             :          * for the lefthand input, because we want the line breaks in
    5762             :          * different places.
    5763             :          */
    5764         124 :         if (need_paren)
    5765             :         {
    5766           0 :             appendStringInfoChar(buf, '(');
    5767           0 :             subindent = PRETTYINDENT_STD;
    5768             :         }
    5769             :         else
    5770         124 :             subindent = 0;
    5771         124 :         appendContextKeyword(context, "", subindent, 0, 0);
    5772             : 
    5773         124 :         get_setop_query(op->rarg, query, context, resultDesc);
    5774             : 
    5775         124 :         if (PRETTY_INDENT(context))
    5776         124 :             context->indentLevel -= subindent;
    5777         124 :         if (need_paren)
    5778           0 :             appendContextKeyword(context, ")", 0, 0, 0);
    5779             :     }
    5780             :     else
    5781             :     {
    5782           0 :         elog(ERROR, "unrecognized node type: %d",
    5783             :              (int) nodeTag(setOp));
    5784             :     }
    5785         328 : }
    5786             : 
    5787             : /*
    5788             :  * Display a sort/group clause.
    5789             :  *
    5790             :  * Also returns the expression tree, so caller need not find it again.
    5791             :  */
    5792             : static Node *
    5793         310 : get_rule_sortgroupclause(Index ref, List *tlist, bool force_colno,
    5794             :                          deparse_context *context)
    5795             : {
    5796         310 :     StringInfo  buf = context->buf;
    5797             :     TargetEntry *tle;
    5798             :     Node       *expr;
    5799             : 
    5800         310 :     tle = get_sortgroupref_tle(ref, tlist);
    5801         310 :     expr = (Node *) tle->expr;
    5802             : 
    5803             :     /*
    5804             :      * Use column-number form if requested by caller.  Otherwise, if
    5805             :      * expression is a constant, force it to be dumped with an explicit cast
    5806             :      * as decoration --- this is because a simple integer constant is
    5807             :      * ambiguous (and will be misinterpreted by findTargetlistEntry()) if we
    5808             :      * dump it without any decoration.  If it's anything more complex than a
    5809             :      * simple Var, then force extra parens around it, to ensure it can't be
    5810             :      * misinterpreted as a cube() or rollup() construct.
    5811             :      */
    5812         310 :     if (force_colno)
    5813             :     {
    5814             :         Assert(!tle->resjunk);
    5815           0 :         appendStringInfo(buf, "%d", tle->resno);
    5816             :     }
    5817         310 :     else if (expr && IsA(expr, Const))
    5818           0 :         get_const_expr((Const *) expr, context, 1);
    5819         310 :     else if (!expr || IsA(expr, Var))
    5820         292 :         get_rule_expr(expr, context, true);
    5821             :     else
    5822             :     {
    5823             :         /*
    5824             :          * We must force parens for function-like expressions even if
    5825             :          * PRETTY_PAREN is off, since those are the ones in danger of
    5826             :          * misparsing. For other expressions we need to force them only if
    5827             :          * PRETTY_PAREN is on, since otherwise the expression will output them
    5828             :          * itself. (We can't skip the parens.)
    5829             :          */
    5830          36 :         bool        need_paren = (PRETTY_PAREN(context)
    5831          18 :                                   || IsA(expr, FuncExpr)
    5832          14 :                                   || IsA(expr, Aggref)
    5833          36 :                                   || IsA(expr, WindowFunc));
    5834             : 
    5835          18 :         if (need_paren)
    5836           4 :             appendStringInfoChar(context->buf, '(');
    5837          18 :         get_rule_expr(expr, context, true);
    5838          18 :         if (need_paren)
    5839           4 :             appendStringInfoChar(context->buf, ')');
    5840             :     }
    5841             : 
    5842         310 :     return expr;
    5843             : }
    5844             : 
    5845             : /*
    5846             :  * Display a GroupingSet
    5847             :  */
    5848             : static void
    5849          12 : get_rule_groupingset(GroupingSet *gset, List *targetlist,
    5850             :                      bool omit_parens, deparse_context *context)
    5851             : {
    5852             :     ListCell   *l;
    5853          12 :     StringInfo  buf = context->buf;
    5854          12 :     bool        omit_child_parens = true;
    5855          12 :     char       *sep = "";
    5856             : 
    5857          12 :     switch (gset->kind)
    5858             :     {
    5859           0 :         case GROUPING_SET_EMPTY:
    5860           0 :             appendStringInfoString(buf, "()");
    5861           0 :             return;
    5862             : 
    5863           8 :         case GROUPING_SET_SIMPLE:
    5864             :             {
    5865           8 :                 if (!omit_parens || list_length(gset->content) != 1)
    5866           8 :                     appendStringInfoChar(buf, '(');
    5867             : 
    5868          28 :                 foreach(l, gset->content)
    5869             :                 {
    5870          20 :                     Index       ref = lfirst_int(l);
    5871             : 
    5872          20 :                     appendStringInfoString(buf, sep);
    5873          20 :                     get_rule_sortgroupclause(ref, targetlist,
    5874             :                                              false, context);
    5875          20 :                     sep = ", ";
    5876             :                 }
    5877             : 
    5878           8 :                 if (!omit_parens || list_length(gset->content) != 1)
    5879           8 :                     appendStringInfoChar(buf, ')');
    5880             :             }
    5881           8 :             return;
    5882             : 
    5883           4 :         case GROUPING_SET_ROLLUP:
    5884           4 :             appendStringInfoString(buf, "ROLLUP(");
    5885           4 :             break;
    5886           0 :         case GROUPING_SET_CUBE:
    5887           0 :             appendStringInfoString(buf, "CUBE(");
    5888           0 :             break;
    5889           0 :         case GROUPING_SET_SETS:
    5890           0 :             appendStringInfoString(buf, "GROUPING SETS (");
    5891           0 :             omit_child_parens = false;
    5892           0 :             break;
    5893             :     }
    5894             : 
    5895          12 :     foreach(l, gset->content)
    5896             :     {
    5897           8 :         appendStringInfoString(buf, sep);
    5898           8 :         get_rule_groupingset(lfirst(l), targetlist, omit_child_parens, context);
    5899           8 :         sep = ", ";
    5900             :     }
    5901             : 
    5902           4 :     appendStringInfoChar(buf, ')');
    5903             : }
    5904             : 
    5905             : /*
    5906             :  * Display an ORDER BY list.
    5907             :  */
    5908             : static void
    5909         168 : get_rule_orderby(List *orderList, List *targetList,
    5910             :                  bool force_colno, deparse_context *context)
    5911             : {
    5912         168 :     StringInfo  buf = context->buf;
    5913             :     const char *sep;
    5914             :     ListCell   *l;
    5915             : 
    5916         168 :     sep = "";
    5917         354 :     foreach(l, orderList)
    5918             :     {
    5919         186 :         SortGroupClause *srt = (SortGroupClause *) lfirst(l);
    5920             :         Node       *sortexpr;
    5921             :         Oid         sortcoltype;
    5922             :         TypeCacheEntry *typentry;
    5923             : 
    5924         186 :         appendStringInfoString(buf, sep);
    5925         186 :         sortexpr = get_rule_sortgroupclause(srt->tleSortGroupRef, targetList,
    5926             :                                             force_colno, context);
    5927         186 :         sortcoltype = exprType(sortexpr);
    5928             :         /* See whether operator is default < or > for datatype */
    5929         186 :         typentry = lookup_type_cache(sortcoltype,
    5930             :                                      TYPECACHE_LT_OPR | TYPECACHE_GT_OPR);
    5931         186 :         if (srt->sortop == typentry->lt_opr)
    5932             :         {
    5933             :             /* ASC is default, so emit nothing for it */
    5934         164 :             if (srt->nulls_first)
    5935           0 :                 appendStringInfoString(buf, " NULLS FIRST");
    5936             :         }
    5937          22 :         else if (srt->sortop == typentry->gt_opr)
    5938             :         {
    5939           8 :             appendStringInfoString(buf, " DESC");
    5940             :             /* DESC defaults to NULLS FIRST */
    5941           8 :             if (!srt->nulls_first)
    5942           2 :                 appendStringInfoString(buf, " NULLS LAST");
    5943             :         }
    5944             :         else
    5945             :         {
    5946          14 :             appendStringInfo(buf, " USING %s",
    5947             :                              generate_operator_name(srt->sortop,
    5948             :                                                     sortcoltype,
    5949             :                                                     sortcoltype));
    5950             :             /* be specific to eliminate ambiguity */
    5951          14 :             if (srt->nulls_first)
    5952           0 :                 appendStringInfoString(buf, " NULLS FIRST");
    5953             :             else
    5954          14 :                 appendStringInfoString(buf, " NULLS LAST");
    5955             :         }
    5956         186 :         sep = ", ";
    5957             :     }
    5958         168 : }
    5959             : 
    5960             : /*
    5961             :  * Display a WINDOW clause.
    5962             :  *
    5963             :  * Note that the windowClause list might contain only anonymous window
    5964             :  * specifications, in which case we should print nothing here.
    5965             :  */
    5966             : static void
    5967          28 : get_rule_windowclause(Query *query, deparse_context *context)
    5968             : {
    5969          28 :     StringInfo  buf = context->buf;
    5970             :     const char *sep;
    5971             :     ListCell   *l;
    5972             : 
    5973          28 :     sep = NULL;
    5974          56 :     foreach(l, query->windowClause)
    5975             :     {
    5976          28 :         WindowClause *wc = (WindowClause *) lfirst(l);
    5977             : 
    5978          28 :         if (wc->name == NULL)
    5979          28 :             continue;           /* ignore anonymous windows */
    5980             : 
    5981           0 :         if (sep == NULL)
    5982           0 :             appendContextKeyword(context, " WINDOW ",
    5983             :                                  -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
    5984             :         else
    5985           0 :             appendStringInfoString(buf, sep);
    5986             : 
    5987           0 :         appendStringInfo(buf, "%s AS ", quote_identifier(wc->name));
    5988             : 
    5989           0 :         get_rule_windowspec(wc, query->targetList, context);
    5990             : 
    5991           0 :         sep = ", ";
    5992             :     }
    5993          28 : }
    5994             : 
    5995             : /*
    5996             :  * Display a window definition
    5997             :  */
    5998             : static void
    5999          28 : get_rule_windowspec(WindowClause *wc, List *targetList,
    6000             :                     deparse_context *context)
    6001             : {
    6002          28 :     StringInfo  buf = context->buf;
    6003          28 :     bool        needspace = false;
    6004             :     const char *sep;
    6005             :     ListCell   *l;
    6006             : 
    6007          28 :     appendStringInfoChar(buf, '(');
    6008          28 :     if (wc->refname)
    6009             :     {
    6010           0 :         appendStringInfoString(buf, quote_identifier(wc->refname));
    6011           0 :         needspace = true;
    6012             :     }
    6013             :     /* partition clauses are always inherited, so only print if no refname */
    6014          28 :     if (wc->partitionClause && !wc->refname)
    6015             :     {
    6016           0 :         if (needspace)
    6017           0 :             appendStringInfoChar(buf, ' ');
    6018           0 :         appendStringInfoString(buf, "PARTITION BY ");
    6019           0 :         sep = "";
    6020           0 :         foreach(l, wc->partitionClause)
    6021             :         {
    6022           0 :             SortGroupClause *grp = (SortGroupClause *) lfirst(l);
    6023             : 
    6024           0 :             appendStringInfoString(buf, sep);
    6025           0 :             get_rule_sortgroupclause(grp->tleSortGroupRef, targetList,
    6026             :                                      false, context);
    6027           0 :             sep = ", ";
    6028             :         }
    6029           0 :         needspace = true;
    6030             :     }
    6031             :     /* print ordering clause only if not inherited */
    6032          28 :     if (wc->orderClause && !wc->copiedOrder)
    6033             :     {
    6034          28 :         if (needspace)
    6035           0 :             appendStringInfoChar(buf, ' ');
    6036          28 :         appendStringInfoString(buf, "ORDER BY ");
    6037          28 :         get_rule_orderby(wc->orderClause, targetList, false, context);
    6038          28 :         needspace = true;
    6039             :     }
    6040             :     /* framing clause is never inherited, so print unless it's default */
    6041          28 :     if (wc->frameOptions & FRAMEOPTION_NONDEFAULT)
    6042             :     {
    6043          28 :         if (needspace)
    6044          28 :             appendStringInfoChar(buf, ' ');
    6045          28 :         if (wc->frameOptions & FRAMEOPTION_RANGE)
    6046           4 :             appendStringInfoString(buf, "RANGE ");
    6047          24 :         else if (wc->frameOptions & FRAMEOPTION_ROWS)
    6048          20 :             appendStringInfoString(buf, "ROWS ");
    6049           4 :         else if (wc->frameOptions & FRAMEOPTION_GROUPS)
    6050           4 :             appendStringInfoString(buf, "GROUPS ");
    6051             :         else
    6052             :             Assert(false);
    6053          28 :         if (wc->frameOptions & FRAMEOPTION_BETWEEN)
    6054          28 :             appendStringInfoString(buf, "BETWEEN ");
    6055          28 :         if (wc->frameOptions & FRAMEOPTION_START_UNBOUNDED_PRECEDING)
    6056           0 :             appendStringInfoString(buf, "UNBOUNDED PRECEDING ");
    6057          28 :         else if (wc->frameOptions & FRAMEOPTION_START_CURRENT_ROW)
    6058           0 :             appendStringInfoString(buf, "CURRENT ROW ");
    6059          28 :         else if (wc->frameOptions & FRAMEOPTION_START_OFFSET)
    6060             :         {
    6061          28 :             get_rule_expr(wc->startOffset, context, false);
    6062          28 :             if (wc->frameOptions & FRAMEOPTION_START_OFFSET_PRECEDING)
    6063          28 :                 appendStringInfoString(buf, " PRECEDING ");
    6064           0 :             else if (wc->frameOptions & FRAMEOPTION_START_OFFSET_FOLLOWING)
    6065           0 :                 appendStringInfoString(buf, " FOLLOWING ");
    6066             :             else
    6067             :                 Assert(false);
    6068             :         }
    6069             :         else
    6070             :             Assert(false);
    6071          28 :         if (wc->frameOptions & FRAMEOPTION_BETWEEN)
    6072             :         {
    6073          28 :             appendStringInfoString(buf, "AND ");
    6074          28 :             if (wc->frameOptions & FRAMEOPTION_END_UNBOUNDED_FOLLOWING)
    6075           0 :                 appendStringInfoString(buf, "UNBOUNDED FOLLOWING ");
    6076          28 :             else if (wc->frameOptions & FRAMEOPTION_END_CURRENT_ROW)
    6077           0 :                 appendStringInfoString(buf, "CURRENT ROW ");
    6078          28 :             else if (wc->frameOptions & FRAMEOPTION_END_OFFSET)
    6079             :             {
    6080          28 :                 get_rule_expr(wc->endOffset, context, false);
    6081          28 :                 if (wc->frameOptions & FRAMEOPTION_END_OFFSET_PRECEDING)
    6082           0 :                     appendStringInfoString(buf, " PRECEDING ");
    6083          28 :                 else if (wc->frameOptions & FRAMEOPTION_END_OFFSET_FOLLOWING)
    6084          28 :                     appendStringInfoString(buf, " FOLLOWING ");
    6085             :                 else
    6086             :                     Assert(false);
    6087             :             }
    6088             :             else
    6089             :                 Assert(false);
    6090             :         }
    6091          28 :         if (wc->frameOptions & FRAMEOPTION_EXCLUDE_CURRENT_ROW)
    6092           4 :             appendStringInfoString(buf, "EXCLUDE CURRENT ROW ");
    6093          24 :         else if (wc->frameOptions & FRAMEOPTION_EXCLUDE_GROUP)
    6094           4 :             appendStringInfoString(buf, "EXCLUDE GROUP ");
    6095          20 :         else if (wc->frameOptions & FRAMEOPTION_EXCLUDE_TIES)
    6096           4 :             appendStringInfoString(buf, "EXCLUDE TIES ");
    6097             :         /* we will now have a trailing space; remove it */
    6098          28 :         buf->len--;
    6099             :     }
    6100          28 :     appendStringInfoChar(buf, ')');
    6101          28 : }
    6102             : 
    6103             : /* ----------
    6104             :  * get_insert_query_def         - Parse back an INSERT parsetree
    6105             :  * ----------
    6106             :  */
    6107             : static void
    6108         216 : get_insert_query_def(Query *query, deparse_context *context)
    6109             : {
    6110         216 :     StringInfo  buf = context->buf;
    6111         216 :     RangeTblEntry *select_rte = NULL;
    6112         216 :     RangeTblEntry *values_rte = NULL;
    6113             :     RangeTblEntry *rte;
    6114             :     char       *sep;
    6115             :     ListCell   *l;
    6116             :     List       *strippedexprs;
    6117             : 
    6118             :     /* Insert the WITH clause if given */
    6119         216 :     get_with_clause(query, context);
    6120             : 
    6121             :     /*
    6122             :      * If it's an INSERT ... SELECT or multi-row VALUES, there will be a
    6123             :      * single RTE for the SELECT or VALUES.  Plain VALUES has neither.
    6124             :      */
    6125         876 :     foreach(l, query->rtable)
    6126             :     {
    6127         660 :         rte = (RangeTblEntry *) lfirst(l);
    6128             : 
    6129         660 :         if (rte->rtekind == RTE_SUBQUERY)
    6130             :         {
    6131          14 :             if (select_rte)
    6132           0 :                 elog(ERROR, "too many subquery RTEs in INSERT");
    6133          14 :             select_rte = rte;
    6134             :         }
    6135             : 
    6136         660 :         if (rte->rtekind == RTE_VALUES)
    6137             :         {
    6138          18 :             if (values_rte)
    6139           0 :                 elog(ERROR, "too many values RTEs in INSERT");
    6140          18 :             values_rte = rte;
    6141             :         }
    6142             :     }
    6143         216 :     if (select_rte && values_rte)
    6144           0 :         elog(ERROR, "both subquery and values RTEs in INSERT");
    6145             : 
    6146             :     /*
    6147             :      * Start the query with INSERT INTO relname
    6148             :      */
    6149         216 :     rte = rt_fetch(query->resultRelation, query->rtable);
    6150             :     Assert(rte->rtekind == RTE_RELATION);
    6151             : 
    6152         216 :     if (PRETTY_INDENT(context))
    6153             :     {
    6154         216 :         context->indentLevel += PRETTYINDENT_STD;
    6155         216 :         appendStringInfoChar(buf, ' ');
    6156             :     }
    6157         216 :     appendStringInfo(buf, "INSERT INTO %s ",
    6158             :                      generate_relation_name(rte->relid, NIL));
    6159             :     /* INSERT requires AS keyword for target alias */
    6160         216 :     if (rte->alias != NULL)
    6161          10 :         appendStringInfo(buf, "AS %s ",
    6162          10 :                          quote_identifier(rte->alias->aliasname));
    6163             : 
    6164             :     /*
    6165             :      * Add the insert-column-names list.  Any indirection decoration needed on
    6166             :      * the column names can be inferred from the top targetlist.
    6167             :      */
    6168         216 :     strippedexprs = NIL;
    6169         216 :     sep = "";
    6170         216 :     if (query->targetList)
    6171         216 :         appendStringInfoChar(buf, '(');
    6172         838 :     foreach(l, query->targetList)
    6173             :     {
    6174         622 :         TargetEntry *tle = (TargetEntry *) lfirst(l);
    6175             : 
    6176         622 :         if (tle->resjunk)
    6177           0 :             continue;           /* ignore junk entries */
    6178             : 
    6179         622 :         appendStringInfoString(buf, sep);
    6180         622 :         sep = ", ";
    6181             : 
    6182             :         /*
    6183             :          * Put out name of target column; look in the catalogs, not at
    6184             :          * tle->resname, since resname will fail to track RENAME.
    6185             :          */
    6186         622 :         appendStringInfoString(buf,
    6187         622 :                                quote_identifier(get_attname(rte->relid,
    6188         622 :                                                             tle->resno,
    6189             :                                                             false)));
    6190             : 
    6191             :         /*
    6192             :          * Print any indirection needed (subfields or subscripts), and strip
    6193             :          * off the top-level nodes representing the indirection assignments.
    6194             :          * Add the stripped expressions to strippedexprs.  (If it's a
    6195             :          * single-VALUES statement, the stripped expressions are the VALUES to
    6196             :          * print below.  Otherwise they're just Vars and not really
    6197             :          * interesting.)
    6198             :          */
    6199         622 :         strippedexprs = lappend(strippedexprs,
    6200         622 :                                 processIndirection((Node *) tle->expr,
    6201             :                                                    context));
    6202             :     }
    6203         216 :     if (query->targetList)
    6204         216 :         appendStringInfoString(buf, ") ");
    6205             : 
    6206         216 :     if (query->override)
    6207             :     {
    6208           0 :         if (query->override == OVERRIDING_SYSTEM_VALUE)
    6209           0 :             appendStringInfoString(buf, "OVERRIDING SYSTEM VALUE ");
    6210           0 :         else if (query->override == OVERRIDING_USER_VALUE)
    6211           0 :             appendStringInfoString(buf, "OVERRIDING USER VALUE ");
    6212             :     }
    6213             : 
    6214         216 :     if (select_rte)
    6215             :     {
    6216             :         /* Add the SELECT */
    6217          14 :         get_query_def(select_rte->subquery, buf, NIL, NULL,
    6218             :                       context->prettyFlags, context->wrapColumn,
    6219             :                       context->indentLevel);
    6220             :     }
    6221         202 :     else if (values_rte)
    6222             :     {
    6223             :         /* Add the multi-VALUES expression lists */
    6224          18 :         get_values_def(values_rte->values_lists, context);
    6225             :     }
    6226         184 :     else if (strippedexprs)
    6227             :     {
    6228             :         /* Add the single-VALUES expression list */
    6229         184 :         appendContextKeyword(context, "VALUES (",
    6230             :                              -PRETTYINDENT_STD, PRETTYINDENT_STD, 2);
    6231         184 :         get_rule_expr((Node *) strippedexprs, context, false);
    6232         184 :         appendStringInfoChar(buf, ')');
    6233             :     }
    6234             :     else
    6235             :     {
    6236             :         /* No expressions, so it must be DEFAULT VALUES */
    6237           0 :         appendStringInfoString(buf, "DEFAULT VALUES");
    6238             :     }
    6239             : 
    6240             :     /* Add ON CONFLICT if present */
    6241         216 :     if (query->onConflict)
    6242             :     {
    6243          20 :         OnConflictExpr *confl = query->onConflict;
    6244             : 
    6245          20 :         appendStringInfoString(buf, " ON CONFLICT");
    6246             : 
    6247          20 :         if (confl->arbiterElems)
    6248             :         {
    6249             :             /* Add the single-VALUES expression list */
    6250          16 :             appendStringInfoChar(buf, '(');
    6251          16 :             get_rule_expr((Node *) confl->arbiterElems, context, false);
    6252          16 :             appendStringInfoChar(buf, ')');
    6253             : 
    6254             :             /* Add a WHERE clause (for partial indexes) if given */
    6255          16 :             if (confl->arbiterWhere != NULL)
    6256             :             {
    6257             :                 bool        save_varprefix;
    6258             : 
    6259             :                 /*
    6260             :                  * Force non-prefixing of Vars, since parser assumes that they
    6261             :                  * belong to target relation.  WHERE clause does not use
    6262             :                  * InferenceElem, so this is separately required.
    6263             :                  */
    6264           8 :                 save_varprefix = context->varprefix;
    6265           8 :                 context->varprefix = false;
    6266             : 
    6267           8 :                 appendContextKeyword(context, " WHERE ",
    6268             :                                      -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
    6269           8 :                 get_rule_expr(confl->arbiterWhere, context, false);
    6270             : 
    6271           8 :                 context->varprefix = save_varprefix;
    6272             :             }
    6273             :         }
    6274           4 :         else if (OidIsValid(confl->constraint))
    6275             :         {
    6276           0 :             char       *constraint = get_constraint_name(confl->constraint);
    6277             : 
    6278           0 :             if (!constraint)
    6279           0 :                 elog(ERROR, "cache lookup failed for constraint %u",
    6280             :                      confl->constraint);
    6281           0 :             appendStringInfo(buf, " ON CONSTRAINT %s",
    6282             :                              quote_identifier(constraint));
    6283             :         }
    6284             : 
    6285          20 :         if (confl->action == ONCONFLICT_NOTHING)
    6286             :         {
    6287          12 :             appendStringInfoString(buf, " DO NOTHING");
    6288             :         }
    6289             :         else
    6290             :         {
    6291           8 :             appendStringInfoString(buf, " DO UPDATE SET ");
    6292             :             /* Deparse targetlist */
    6293           8 :             get_update_query_targetlist_def(query, confl->onConflictSet,
    6294             :                                             context, rte);
    6295             : 
    6296             :             /* Add a WHERE clause if given */
    6297           8 :             if (confl->onConflictWhere != NULL)
    6298             :             {
    6299           8 :                 appendContextKeyword(context, " WHERE ",
    6300             :                                      -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
    6301           8 :                 get_rule_expr(confl->onConflictWhere, context, false);
    6302             :             }
    6303             :         }
    6304             :     }
    6305             : 
    6306             :     /* Add RETURNING if present */
    6307         216 :     if (query->returningList)
    6308             :     {
    6309          30 :         appendContextKeyword(context, " RETURNING",
    6310             :                              -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
    6311          30 :         get_target_list(query->returningList, context, NULL);
    6312             :     }
    6313         216 : }
    6314             : 
    6315             : 
    6316             : /* ----------
    6317             :  * get_update_query_def         - Parse back an UPDATE parsetree
    6318             :  * ----------
    6319             :  */
    6320             : static void
    6321          88 : get_update_query_def(Query *query, deparse_context *context)
    6322             : {
    6323          88 :     StringInfo  buf = context->buf;
    6324             :     RangeTblEntry *rte;
    6325             : 
    6326             :     /* Insert the WITH clause if given */
    6327          88 :     get_with_clause(query, context);
    6328             : 
    6329             :     /*
    6330             :      * Start the query with UPDATE relname SET
    6331             :      */
    6332          88 :     rte = rt_fetch(query->resultRelation, query->rtable);
    6333             :     Assert(rte->rtekind == RTE_RELATION);
    6334          88 :     if (PRETTY_INDENT(context))
    6335             :     {
    6336          88 :         appendStringInfoChar(buf, ' ');
    6337          88 :         context->indentLevel += PRETTYINDENT_STD;
    6338             :     }
    6339         176 :     appendStringInfo(buf, "UPDATE %s%s",
    6340          88 :                      only_marker(rte),
    6341             :                      generate_relation_name(rte->relid, NIL));
    6342          88 :     if (rte->alias != NULL)
    6343          14 :         appendStringInfo(buf, " %s",
    6344          14 :                          quote_identifier(rte->alias->aliasname));
    6345          88 :     appendStringInfoString(buf, " SET ");
    6346             : 
    6347             :     /* Deparse targetlist */
    6348          88 :     get_update_query_targetlist_def(query, query->targetList, context, rte);
    6349             : 
    6350             :     /* Add the FROM clause if needed */
    6351          88 :     get_from_clause(query, " FROM ", context);
    6352             : 
    6353             :     /* Add a WHERE clause if given */
    6354          88 :     if (query->jointree->quals != NULL)
    6355             :     {
    6356          88 :         appendContextKeyword(context, " WHERE ",
    6357             :                              -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
    6358          88 :         get_rule_expr(query->jointree->quals, context, false);
    6359             :     }
    6360             : 
    6361             :     /* Add RETURNING if present */
    6362          88 :     if (query->returningList)
    6363             :     {
    6364           4 :         appendContextKeyword(context, " RETURNING",
    6365             :                              -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
    6366           4 :         get_target_list(query->returningList, context, NULL);
    6367             :     }
    6368          88 : }
    6369             : 
    6370             : 
    6371             : /* ----------
    6372             :  * get_update_query_targetlist_def          - Parse back an UPDATE targetlist
    6373             :  * ----------
    6374             :  */
    6375             : static void
    6376          96 : get_update_query_targetlist_def(Query *query, List *targetList,
    6377             :                                 deparse_context *context, RangeTblEntry *rte)
    6378             : {
    6379          96 :     StringInfo  buf = context->buf;
    6380             :     ListCell   *l;
    6381             :     ListCell   *next_ma_cell;
    6382             :     int         remaining_ma_columns;
    6383             :     const char *sep;
    6384             :     SubLink    *cur_ma_sublink;
    6385             :     List       *ma_sublinks;
    6386             : 
    6387             :     /*
    6388             :      * Prepare to deal with MULTIEXPR assignments: collect the source SubLinks
    6389             :      * into a list.  We expect them to appear, in ID order, in resjunk tlist
    6390             :      * entries.
    6391             :      */
    6392          96 :     ma_sublinks = NIL;
    6393          96 :     if (query->hasSubLinks)      /* else there can't be any */
    6394             :     {
    6395          20 :         foreach(l, targetList)
    6396             :         {
    6397          16 :             TargetEntry *tle = (TargetEntry *) lfirst(l);
    6398             : 
    6399          16 :             if (tle->resjunk && IsA(tle->expr, SubLink))
    6400             :             {
    6401           4 :                 SubLink    *sl = (SubLink *) tle->expr;
    6402             : 
    6403           4 :                 if (sl->subLinkType == MULTIEXPR_SUBLINK)
    6404             :                 {
    6405           4 :                     ma_sublinks = lappend(ma_sublinks, sl);
    6406             :                     Assert(sl->subLinkId == list_length(ma_sublinks));
    6407             :                 }
    6408             :             }
    6409             :         }
    6410             :     }
    6411          96 :     next_ma_cell = list_head(ma_sublinks);
    6412          96 :     cur_ma_sublink = NULL;
    6413          96 :     remaining_ma_columns = 0;
    6414             : 
    6415             :     /* Add the comma separated list of 'attname = value' */
    6416          96 :     sep = "";
    6417         270 :     foreach(l, targetList)
    6418             :     {
    6419         174 :         TargetEntry *tle = (TargetEntry *) lfirst(l);
    6420             :         Node       *expr;
    6421             : 
    6422         174 :         if (tle->resjunk)
    6423           4 :             continue;           /* ignore junk entries */
    6424             : 
    6425             :         /* Emit separator (OK whether we're in multiassignment or not) */
    6426         170 :         appendStringInfoString(buf, sep);
    6427         170 :         sep = ", ";
    6428             : 
    6429             :         /*
    6430             :          * Check to see if we're starting a multiassignment group: if so,
    6431             :          * output a left paren.
    6432             :          */
    6433         170 :         if (next_ma_cell != NULL && cur_ma_sublink == NULL)
    6434             :         {
    6435             :             /*
    6436             :              * We must dig down into the expr to see if it's a PARAM_MULTIEXPR
    6437             :              * Param.  That could be buried under FieldStores and
    6438             :              * SubscriptingRefs and CoerceToDomains (cf processIndirection()),
    6439             :              * and underneath those there could be an implicit type coercion.
    6440             :              * Because we would ignore implicit type coercions anyway, we
    6441             :              * don't need to be as careful as processIndirection() is about
    6442             :              * descending past implicit CoerceToDomains.
    6443             :              */
    6444           4 :             expr = (Node *) tle->expr;
    6445           8 :             while (expr)
    6446             :             {
    6447           8 :                 if (IsA(expr, FieldStore))
    6448             :                 {
    6449           0 :                     FieldStore *fstore = (FieldStore *) expr;
    6450             : 
    6451           0 :                     expr = (Node *) linitial(fstore->newvals);
    6452             :                 }
    6453           8 :                 else if (IsA(expr, SubscriptingRef))
    6454             :                 {
    6455           4 :                     SubscriptingRef *sbsref = (SubscriptingRef *) expr;
    6456             : 
    6457           4 :                     if (sbsref->refassgnexpr == NULL)
    6458           0 :                         break;
    6459             : 
    6460           4 :                     expr = (Node *) sbsref->refassgnexpr;
    6461             :                 }
    6462           4 :                 else if (IsA(expr, CoerceToDomain))
    6463             :                 {
    6464           0 :                     CoerceToDomain *cdomain = (CoerceToDomain *) expr;
    6465             : 
    6466           0 :                     if (cdomain->coercionformat != COERCE_IMPLICIT_CAST)
    6467           0 :                         break;
    6468           0 :                     expr = (Node *) cdomain->arg;
    6469             :                 }
    6470             :                 else
    6471           4 :                     break;
    6472             :             }
    6473           4 :             expr = strip_implicit_coercions(expr);
    6474             : 
    6475           4 :             if (expr && IsA(expr, Param) &&
    6476           4 :                 ((Param *) expr)->paramkind == PARAM_MULTIEXPR)
    6477             :             {
    6478           4 :                 cur_ma_sublink = (SubLink *) lfirst(next_ma_cell);
    6479           4 :                 next_ma_cell = lnext(ma_sublinks, next_ma_cell);
    6480           4 :                 remaining_ma_columns = count_nonjunk_tlist_entries(((Query *) cur_ma_sublink->subselect)->targetList);
    6481             :                 Assert(((Param *) expr)->paramid ==
    6482             :                        ((cur_ma_sublink->subLinkId << 16) | 1));
    6483           4 :                 appendStringInfoChar(buf, '(');
    6484             :             }
    6485             :         }
    6486             : 
    6487             :         /*
    6488             :          * Put out name of target column; look in the catalogs, not at
    6489             :          * tle->resname, since resname will fail to track RENAME.
    6490             :          */
    6491         170 :         appendStringInfoString(buf,
    6492         170 :                                quote_identifier(get_attname(rte->relid,
    6493         170 :                                                             tle->resno,
    6494             :                                                             false)));
    6495             : 
    6496             :         /*
    6497             :          * Print any indirection needed (subfields or subscripts), and strip
    6498             :          * off the top-level nodes representing the indirection assignments.
    6499             :          */
    6500         170 :         expr = processIndirection((Node *) tle->expr, context);
    6501             : 
    6502             :         /*
    6503             :          * If we're in a multiassignment, skip printing anything more, unless
    6504             :          * this is the last column; in which case, what we print should be the
    6505             :          * sublink, not the Param.
    6506             :          */
    6507         170 :         if (cur_ma_sublink != NULL)
    6508             :         {
    6509          12 :             if (--remaining_ma_columns > 0)
    6510           8 :                 continue;       /* not the last column of multiassignment */
    6511           4 :             appendStringInfoChar(buf, ')');
    6512           4 :             expr = (Node *) cur_ma_sublink;
    6513           4 :             cur_ma_sublink = NULL;
    6514             :         }
    6515             : 
    6516         162 :         appendStringInfoString(buf, " = ");
    6517             : 
    6518         162 :         get_rule_expr(expr, context, false);
    6519             :     }
    6520          96 : }
    6521             : 
    6522             : 
    6523             : /* ----------
    6524             :  * get_delete_query_def         - Parse back a DELETE parsetree
    6525             :  * ----------
    6526             :  */
    6527             : static void
    6528          50 : get_delete_query_def(Query *query, deparse_context *context)
    6529             : {
    6530          50 :     StringInfo  buf = context->buf;
    6531             :     RangeTblEntry *rte;
    6532             : 
    6533             :     /* Insert the WITH clause if given */
    6534          50 :     get_with_clause(query, context);
    6535             : 
    6536             :     /*
    6537             :      * Start the query with DELETE FROM relname
    6538             :      */
    6539          50 :     rte = rt_fetch(query->resultRelation, query->rtable);
    6540             :     Assert(rte->rtekind == RTE_RELATION);
    6541          50 :     if (PRETTY_INDENT(context))
    6542             :     {
    6543          50 :         appendStringInfoChar(buf, ' ');
    6544          50 :         context->indentLevel += PRETTYINDENT_STD;
    6545             :     }
    6546         100 :     appendStringInfo(buf, "DELETE FROM %s%s",
    6547          50 :                      only_marker(rte),
    6548             :                      generate_relation_name(rte->relid, NIL));
    6549          50 :     if (rte->alias != NULL)
    6550           0 :         appendStringInfo(buf, " %s",
    6551           0 :                          quote_identifier(rte->alias->aliasname));
    6552             : 
    6553             :     /* Add the USING clause if given */
    6554          50 :     get_from_clause(query, " USING ", context);
    6555             : 
    6556             :     /* Add a WHERE clause if given */
    6557          50 :     if (query->jointree->quals != NULL)
    6558             :     {
    6559          50 :         appendContextKeyword(context, " WHERE ",
    6560             :                              -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
    6561          50 :         get_rule_expr(query->jointree->quals, context, false);
    6562             :     }
    6563             : 
    6564             :     /* Add RETURNING if present */
    6565          50 :     if (query->returningList)
    6566             :     {
    6567           0 :         appendContextKeyword(context, " RETURNING",
    6568             :                              -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
    6569           0 :         get_target_list(query->returningList, context, NULL);
    6570             :     }
    6571          50 : }
    6572             : 
    6573             : 
    6574             : /* ----------
    6575             :  * get_utility_query_def            - Parse back a UTILITY parsetree
    6576             :  * ----------
    6577             :  */
    6578             : static void
    6579          14 : get_utility_query_def(Query *query, deparse_context *context)
    6580             : {
    6581          14 :     StringInfo  buf = context->buf;
    6582             : 
    6583          14 :     if (query->utilityStmt && IsA(query->utilityStmt, NotifyStmt))
    6584          14 :     {
    6585          14 :         NotifyStmt *stmt = (NotifyStmt *) query->utilityStmt;
    6586             : 
    6587          14 :         appendContextKeyword(context, "",
    6588             :                              0, PRETTYINDENT_STD, 1);
    6589          14 :         appendStringInfo(buf, "NOTIFY %s",
    6590          14 :                          quote_identifier(stmt->conditionname));
    6591          14 :         if (stmt->payload)
    6592             :         {
    6593           0 :             appendStringInfoString(buf, ", ");
    6594           0 :             simple_quote_literal(buf, stmt->payload);
    6595             :         }
    6596             :     }
    6597             :     else
    6598             :     {
    6599             :         /* Currently only NOTIFY utility commands can appear in rules */
    6600           0 :         elog(ERROR, "unexpected utility statement type");
    6601             :     }
    6602          14 : }
    6603             : 
    6604             : /*
    6605             :  * Display a Var appropriately.
    6606             :  *
    6607             :  * In some cases (currently only when recursing into an unnamed join)
    6608             :  * the Var's varlevelsup has to be interpreted with respect to a context
    6609             :  * above the current one; levelsup indicates the offset.
    6610             :  *
    6611             :  * If istoplevel is true, the Var is at the top level of a SELECT's
    6612             :  * targetlist, which means we need special treatment of whole-row Vars.
    6613             :  * Instead of the normal "tab.*", we'll print "tab.*::typename", which is a
    6614             :  * dirty hack to prevent "tab.*" from being expanded into multiple columns.
    6615             :  * (The parser will strip the useless coercion, so no inefficiency is added in
    6616             :  * dump and reload.)  We used to print just "tab" in such cases, but that is
    6617             :  * ambiguous and will yield the wrong result if "tab" is also a plain column
    6618             :  * name in the query.
    6619             :  *
    6620             :  * Returns the attname of the Var, or NULL if the Var has no attname (because
    6621             :  * it is a whole-row Var or a subplan output reference).
    6622             :  */
    6623             : static char *
    6624       75572 : get_variable(Var *var, int levelsup, bool istoplevel, deparse_context *context)
    6625             : {
    6626       75572 :     StringInfo  buf = context->buf;
    6627             :     RangeTblEntry *rte;
    6628             :     AttrNumber  attnum;
    6629             :     int         netlevelsup;
    6630             :     deparse_namespace *dpns;
    6631             :     Index       varno;
    6632             :     AttrNumber  varattno;
    6633             :     deparse_columns *colinfo;
    6634             :     char       *refname;
    6635             :     char       *attname;
    6636             : 
    6637             :     /* Find appropriate nesting depth */
    6638       75572 :     netlevelsup = var->varlevelsup + levelsup;
    6639       75572 :     if (netlevelsup >= list_length(context->namespaces))
    6640           0 :         elog(ERROR, "bogus varlevelsup: %d offset %d",
    6641             :              var->varlevelsup, levelsup);
    6642       75572 :     dpns = (deparse_namespace *) list_nth(context->namespaces,
    6643             :                                           netlevelsup);
    6644             : 
    6645             :     /*
    6646             :      * If we have a syntactic referent for the Var, and we're working from a
    6647             :      * parse tree, prefer to use the syntactic referent.  Otherwise, fall back
    6648             :      * on the semantic referent.  (Forcing use of the semantic referent when
    6649             :      * printing plan trees is a design choice that's perhaps more motivated by
    6650             :      * backwards compatibility than anything else.  But it does have the
    6651             :      * advantage of making plans more explicit.)
    6652             :      */
    6653       75572 :     if (var->varnosyn > 0 && dpns->plan == NULL)
    6654             :     {
    6655       14404 :         varno = var->varnosyn;
    6656       14404 :         varattno = var->varattnosyn;
    6657             :     }
    6658             :     else
    6659             :     {
    6660       61168 :         varno = var->varno;
    6661       61168 :         varattno = var->varattno;
    6662             :     }
    6663             : 
    6664             :     /*
    6665             :      * Try to find the relevant RTE in this rtable.  In a plan tree, it's
    6666             :      * likely that varno is OUTER_VAR or INNER_VAR, in which case we must dig
    6667             :      * down into the subplans, or INDEX_VAR, which is resolved similarly. Also
    6668             :      * find the aliases previously assigned for this RTE.
    6669             :      */
    6670       75572 :     if (varno >= 1 && varno <= list_length(dpns->rtable))
    6671             :     {
    6672             :         /*
    6673             :          * We might have been asked to map child Vars to some parent relation.
    6674             :          */
    6675       55662 :         if (context->appendparents && dpns->appendrels)
    6676             :         {
    6677        2098 :             Index       pvarno = varno;
    6678        2098 :             AttrNumber  pvarattno = varattno;
    6679        2098 :             AppendRelInfo *appinfo = dpns->appendrels[pvarno];
    6680        2098 :             bool        found = false;
    6681             : 
    6682             :             /* Only map up to inheritance parents, not UNION ALL appendrels */
    6683        4328 :             while (appinfo &&
    6684        2348 :                    rt_fetch(appinfo->parent_relid,
    6685        2348 :                             dpns->rtable)->rtekind == RTE_RELATION)
    6686             :             {
    6687        2230 :                 found = false;
    6688        2230 :                 if (pvarattno > 0)   /* system columns stay as-is */
    6689             :                 {
    6690        2098 :                     if (pvarattno > appinfo->num_child_cols)
    6691           0 :                         break;  /* safety check */
    6692        2098 :                     pvarattno = appinfo->parent_colnos[pvarattno - 1];
    6693        2098 :                     if (pvarattno == 0)
    6694           0 :                         break;  /* Var is local to child */
    6695             :                 }
    6696             : 
    6697        2230 :                 pvarno = appinfo->parent_relid;
    6698        2230 :                 found = true;
    6699             : 
    6700             :                 /* If the parent is itself a child, continue up. */
    6701             :                 Assert(pvarno > 0 && pvarno <= list_length(dpns->rtable));
    6702        2230 :                 appinfo = dpns->appendrels[pvarno];
    6703             :             }
    6704             : 
    6705             :             /*
    6706             :              * If we found an ancestral rel, and that rel is included in
    6707             :              * appendparents, print that column not the original one.
    6708             :              */
    6709        2098 :             if (found && bms_is_member(pvarno, context->appendparents))
    6710             :             {
    6711        1784 :                 varno = pvarno;
    6712        1784 :                 varattno = pvarattno;
    6713             :             }
    6714             :         }
    6715             : 
    6716       55662 :         rte = rt_fetch(varno, dpns->rtable);
    6717       55662 :         refname = (char *) list_nth(dpns->rtable_names, varno - 1);
    6718       55662 :         colinfo = deparse_columns_fetch(varno, dpns);
    6719       55662 :         attnum = varattno;
    6720             :     }
    6721             :     else
    6722             :     {
    6723       19910 :         resolve_special_varno((Node *) var, context,
    6724             :                               get_special_variable, NULL);
    6725       19910 :         return NULL;
    6726             :     }
    6727             : 
    6728             :     /*
    6729             :      * The planner will sometimes emit Vars referencing resjunk elements of a
    6730             :      * subquery's target list (this is currently only possible if it chooses
    6731             :      * to generate a "physical tlist" for a SubqueryScan or CteScan node).
    6732             :      * Although we prefer to print subquery-referencing Vars using the
    6733             :      * subquery's alias, that's not possible for resjunk items since they have
    6734             :      * no alias.  So in that case, drill down to the subplan and print the
    6735             :      * contents of the referenced tlist item.  This works because in a plan
    6736             :      * tree, such Vars can only occur in a SubqueryScan or CteScan node, and
    6737             :      * we'll have set dpns->inner_plan to reference the child plan node.
    6738             :      */
    6739       56948 :     if ((rte->rtekind == RTE_SUBQUERY || rte->rtekind == RTE_CTE) &&
    6740        1286 :         attnum > list_length(rte->eref->colnames) &&
    6741           2 :         dpns->inner_plan)
    6742             :     {
    6743             :         TargetEntry *tle;
    6744             :         deparse_namespace save_dpns;
    6745             : 
    6746           2 :         tle = get_tle_by_resno(dpns->inner_tlist, attnum);
    6747           2 :         if (!tle)
    6748           0 :             elog(ERROR, "invalid attnum %d for relation \"%s\"",
    6749             :                  attnum, rte->eref->aliasname);
    6750             : 
    6751             :         Assert(netlevelsup == 0);
    6752           2 :         push_child_plan(dpns, dpns->inner_plan, &save_dpns);
    6753             : 
    6754             :         /*
    6755             :          * Force parentheses because our caller probably assumed a Var is a
    6756             :          * simple expression.
    6757             :          */
    6758           2 :         if (!IsA(tle->expr, Var))
    6759           0 :             appendStringInfoChar(buf, '(');
    6760           2 :         get_rule_expr((Node *) tle->expr, context, true);
    6761           2 :         if (!IsA(tle->expr, Var))
    6762           0 :             appendStringInfoChar(buf, ')');
    6763             : 
    6764           2 :         pop_child_plan(dpns, &save_dpns);
    6765           2 :         return NULL;
    6766             :     }
    6767             : 
    6768             :     /*
    6769             :      * If it's an unnamed join, look at the expansion of the alias variable.
    6770             :      * If it's a simple reference to one of the input vars, then recursively
    6771             :      * print the name of that var instead.  When it's not a simple reference,
    6772             :      * we have to just print the unqualified join column name.  (This can only
    6773             :      * happen with "dangerous" merged columns in a JOIN USING; we took pains
    6774             :      * previously to make the unqualified column name unique in such cases.)
    6775             :      *
    6776             :      * This wouldn't work in decompiling plan trees, because we don't store
    6777             :      * joinaliasvars lists after planning; but a plan tree should never
    6778             :      * contain a join alias variable.
    6779             :      */
    6780       55660 :     if (rte->rtekind == RTE_JOIN && rte->alias == NULL)
    6781             :     {
    6782          64 :         if (rte->joinaliasvars == NIL)
    6783           0 :             elog(ERROR, "cannot decompile join alias var in plan tree");
    6784          64 :         if (attnum > 0)
    6785             :         {
    6786             :             Var        *aliasvar;
    6787             : 
    6788          64 :             aliasvar = (Var *) list_nth(rte->joinaliasvars, attnum - 1);
    6789             :             /* we intentionally don't strip implicit coercions here */
    6790          64 :             if (aliasvar && IsA(aliasvar, Var))
    6791             :             {
    6792           0 :                 return get_variable(aliasvar, var->varlevelsup + levelsup,
    6793             :                                     istoplevel, context);
    6794             :             }
    6795             :         }
    6796             : 
    6797             :         /*
    6798             :          * Unnamed join has no refname.  (Note: since it's unnamed, there is
    6799             :          * no way the user could have referenced it to create a whole-row Var
    6800             :          * for it.  So we don't have to cover that case below.)
    6801             :          */
    6802             :         Assert(refname == NULL);
    6803             :     }
    6804             : 
    6805       55660 :     if (attnum == InvalidAttrNumber)
    6806         492 :         attname = NULL;
    6807       55168 :     else if (attnum > 0)
    6808             :     {
    6809             :         /* Get column name to use from the colinfo struct */
    6810       54614 :         if (attnum > colinfo->num_cols)
    6811           0 :             elog(ERROR, "invalid attnum %d for relation \"%s\"",
    6812             :                  attnum, rte->eref->aliasname);
    6813       54614 :         attname = colinfo->colnames[attnum - 1];
    6814       54614 :         if (attname == NULL)    /* dropped column? */
    6815           0 :             elog(ERROR, "invalid attnum %d for relation \"%s\"",
    6816             :                  attnum, rte->eref->aliasname);
    6817             :     }
    6818             :     else
    6819             :     {
    6820             :         /* System column - name is fixed, get it from the catalog */
    6821         554 :         attname = get_rte_attribute_name(rte, attnum);
    6822             :     }
    6823             : 
    6824       55660 :     if (refname && (context->varprefix || attname == NULL))
    6825             :     {
    6826       30792 :         appendStringInfoString(buf, quote_identifier(refname));
    6827       30792 :         appendStringInfoChar(buf, '.');
    6828             :     }
    6829       55660 :     if (attname)
    6830       55168 :         appendStringInfoString(buf, quote_identifier(attname));
    6831             :     else
    6832             :     {
    6833         492 :         appendStringInfoChar(buf, '*');
    6834         492 :         if (istoplevel)
    6835          20 :             appendStringInfo(buf, "::%s",
    6836             :                              format_type_with_typemod(var->vartype,
    6837             :                                                       var->vartypmod));
    6838             :     }
    6839             : 
    6840       55660 :     return attname;
    6841             : }
    6842             : 
    6843             : /*
    6844             :  * Deparse a Var which references OUTER_VAR, INNER_VAR, or INDEX_VAR.  This
    6845             :  * routine is actually a callback for resolve_special_varno, which handles
    6846             :  * finding the correct TargetEntry.  We get the expression contained in that
    6847             :  * TargetEntry and just need to deparse it, a job we can throw back on
    6848             :  * get_rule_expr.
    6849             :  */
    6850             : static void
    6851       19910 : get_special_variable(Node *node, deparse_context *context, void *callback_arg)
    6852             : {
    6853       19910 :     StringInfo  buf = context->buf;
    6854             : 
    6855             :     /*
    6856             :      * For a non-Var referent, force parentheses because our caller probably
    6857             :      * assumed a Var is a simple expression.
    6858             :      */
    6859       19910 :     if (!IsA(node, Var))
    6860        1790 :         appendStringInfoChar(buf, '(');
    6861       19910 :     get_rule_expr(node, context, true);
    6862       19910 :     if (!IsA(node, Var))
    6863        1790 :         appendStringInfoChar(buf, ')');
    6864       19910 : }
    6865             : 
    6866             : /*
    6867             :  * Chase through plan references to special varnos (OUTER_VAR, INNER_VAR,
    6868             :  * INDEX_VAR) until we find a real Var or some kind of non-Var node; then,
    6869             :  * invoke the callback provided.
    6870             :  */
    6871             : static void
    6872       54774 : resolve_special_varno(Node *node, deparse_context *context,
    6873             :                       rsv_callback callback, void *callback_arg)
    6874             : {
    6875             :     Var        *var;
    6876             :     deparse_namespace *dpns;
    6877             : 
    6878             :     /* This function is recursive, so let's be paranoid. */
    6879       54774 :     check_stack_depth();
    6880             : 
    6881             :     /* If it's not a Var, invoke the callback. */
    6882       54774 :     if (!IsA(node, Var))
    6883             :     {
    6884        1948 :         (*callback) (node, context, callback_arg);
    6885        1948 :         return;
    6886             :     }
    6887             : 
    6888             :     /* Find appropriate nesting depth */
    6889       52826 :     var = (Var *) node;
    6890       52826 :     dpns = (deparse_namespace *) list_nth(context->namespaces,
    6891       52826 :                                           var->varlevelsup);
    6892             : 
    6893             :     /*
    6894             :      * If varno is special, recurse.  (Don't worry about varnosyn; if we're
    6895             :      * here, we already decided not to use that.)
    6896             :      */
    6897       52826 :     if (var->varno == OUTER_VAR && dpns->outer_tlist)
    6898             :     {
    6899             :         TargetEntry *tle;
    6900             :         deparse_namespace save_dpns;
    6901             :         Bitmapset  *save_appendparents;
    6902             : 
    6903       25708 :         tle = get_tle_by_resno(dpns->outer_tlist, var->varattno);
    6904       25708 :         if (!tle)
    6905           0 :             elog(ERROR, "bogus varattno for OUTER_VAR var: %d", var->varattno);
    6906             : 
    6907             :         /*
    6908             :          * If we're descending to the first child of an Append or MergeAppend,
    6909             :          * update appendparents.  This will affect deparsing of all Vars
    6910             :          * appearing within the eventually-resolved subexpression.
    6911             :          */
    6912       25708 :         save_appendparents = context->appendparents;
    6913             : 
    6914       25708 :         if (IsA(dpns->plan, Append))
    6915        2278 :             context->appendparents = bms_union(context->appendparents,
    6916        2278 :                                                ((Append *) dpns->plan)->apprelids);
    6917       23430 :         else if (IsA(dpns->plan, MergeAppend))
    6918         308 :             context->appendparents = bms_union(context->appendparents,
    6919         308 :                                                ((MergeAppend *) dpns->plan)->apprelids);
    6920             : 
    6921       25708 :         push_child_plan(dpns, dpns->outer_plan, &save_dpns);
    6922       25708 :         resolve_special_varno((Node *) tle->expr, context,
    6923             :                               callback, callback_arg);
    6924       25708 :         pop_child_plan(dpns, &save_dpns);
    6925       25708 :         context->appendparents = save_appendparents;
    6926       25708 :         return;
    6927             :     }
    6928       27118 :     else if (var->varno == INNER_VAR && dpns->inner_tlist)
    6929             :     {
    6930             :         TargetEntry *tle;
    6931             :         deparse_namespace save_dpns;
    6932             : 
    6933        6612 :         tle = get_tle_by_resno(dpns->inner_tlist, var->varattno);
    6934        6612 :         if (!tle)
    6935           0 :             elog(ERROR, "bogus varattno for INNER_VAR var: %d", var->varattno);
    6936             : 
    6937        6612 :         push_child_plan(dpns, dpns->inner_plan, &save_dpns);
    6938        6612 :         resolve_special_varno((Node *) tle->expr, context,
    6939             :                               callback, callback_arg);
    6940        6612 :         pop_child_plan(dpns, &save_dpns);
    6941        6612 :         return;
    6942             :     }
    6943       20506 :     else if (var->varno == INDEX_VAR && dpns->index_tlist)
    6944             :     {
    6945             :         TargetEntry *tle;
    6946             : 
    6947        2386 :         tle = get_tle_by_resno(dpns->index_tlist, var->varattno);
    6948        2386 :         if (!tle)
    6949           0 :             elog(ERROR, "bogus varattno for INDEX_VAR var: %d", var->varattno);
    6950             : 
    6951        2386 :         resolve_special_varno((Node *) tle->expr, context,
    6952             :                               callback, callback_arg);
    6953        2386 :         return;
    6954             :     }
    6955       18120 :     else if (var->varno < 1 || var->varno > list_length(dpns->rtable))
    6956           0 :         elog(ERROR, "bogus varno: %d", var->varno);
    6957             : 
    6958             :     /* Not special.  Just invoke the callback. */
    6959       18120 :     (*callback) (node, context, callback_arg);
    6960             : }
    6961             : 
    6962             : /*
    6963             :  * Get the name of a field of an expression of composite type.  The
    6964             :  * expression is usually a Var, but we handle other cases too.
    6965             :  *
    6966             :  * levelsup is an extra offset to interpret the Var's varlevelsup correctly.
    6967             :  *
    6968             :  * This is fairly straightforward when the expression has a named composite
    6969             :  * type; we need only look up the type in the catalogs.  However, the type
    6970             :  * could also be RECORD.  Since no actual table or view column is allowed to
    6971             :  * have type RECORD, a Var of type RECORD must refer to a JOIN or FUNCTION RTE
    6972             :  * or to a subquery output.  We drill down to find the ultimate defining
    6973             :  * expression and attempt to infer the field name from it.  We ereport if we
    6974             :  * can't determine the name.
    6975             :  *
    6976             :  * Similarly, a PARAM of type RECORD has to refer to some expression of
    6977             :  * a determinable composite type.
    6978             :  */
    6979             : static const char *
    6980         176 : get_name_for_var_field(Var *var, int fieldno,
    6981             :                        int levelsup, deparse_context *context)
    6982             : {
    6983             :     RangeTblEntry *rte;
    6984             :     AttrNumber  attnum;
    6985             :     int         netlevelsup;
    6986             :     deparse_namespace *dpns;
    6987             :     Index       varno;
    6988             :     AttrNumber  varattno;
    6989             :     TupleDesc   tupleDesc;
    6990             :     Node       *expr;
    6991             : 
    6992             :     /*
    6993             :      * If it's a RowExpr that was expanded from a whole-row Var, use the
    6994             :      * column names attached to it.
    6995             :      */
    6996         176 :     if (IsA(var, RowExpr))
    6997             :     {
    6998          20 :         RowExpr    *r = (RowExpr *) var;
    6999             : 
    7000          20 :         if (fieldno > 0 && fieldno <= list_length(r->colnames))
    7001          20 :             return strVal(list_nth(r->colnames, fieldno - 1));
    7002             :     }
    7003             : 
    7004             :     /*
    7005             :      * If it's a Param of type RECORD, try to find what the Param refers to.
    7006             :      */
    7007         156 :     if (IsA(var, Param))
    7008             :     {
    7009           8 :         Param      *param = (Param *) var;
    7010             :         ListCell   *ancestor_cell;
    7011             : 
    7012           8 :         expr = find_param_referent(param, context, &dpns, &ancestor_cell);
    7013           8 :         if (expr)
    7014             :         {
    7015             :             /* Found a match, so recurse to decipher the field name */
    7016             :             deparse_namespace save_dpns;
    7017             :             const char *result;
    7018             : 
    7019           8 :             push_ancestor_plan(dpns, ancestor_cell, &save_dpns);
    7020           8 :             result = get_name_for_var_field((Var *) expr, fieldno,
    7021             :                                             0, context);
    7022           8 :             pop_ancestor_plan(dpns, &save_dpns);
    7023           8 :             return result;
    7024             :         }
    7025             :     }
    7026             : 
    7027             :     /*
    7028             :      * If it's a Var of type RECORD, we have to find what the Var refers to;
    7029             :      * if not, we can use get_expr_result_tupdesc().
    7030             :      */
    7031         148 :     if (!IsA(var, Var) ||
    7032         116 :         var->vartype != RECORDOID)
    7033             :     {
    7034          64 :         tupleDesc = get_expr_result_tupdesc((Node *) var, false);
    7035             :         /* Got the tupdesc, so we can extract the field name */
    7036             :         Assert(fieldno >= 1 && fieldno <= tupleDesc->natts);
    7037          64 :         return NameStr(TupleDescAttr(tupleDesc, fieldno - 1)->attname);
    7038             :     }
    7039             : 
    7040             :     /* Find appropriate nesting depth */
    7041          84 :     netlevelsup = var->varlevelsup + levelsup;
    7042          84 :     if (netlevelsup >= list_length(context->namespaces))
    7043           0 :         elog(ERROR, "bogus varlevelsup: %d offset %d",
    7044             :              var->varlevelsup, levelsup);
    7045          84 :     dpns = (deparse_namespace *) list_nth(context->namespaces,
    7046             :                                           netlevelsup);
    7047             : 
    7048             :     /*
    7049             :      * If we have a syntactic referent for the Var, and we're working from a
    7050             :      * parse tree, prefer to use the syntactic referent.  Otherwise, fall back
    7051             :      * on the semantic referent.  (See comments in get_variable().)
    7052             :      */
    7053          84 :     if (var->varnosyn > 0 && dpns->plan == NULL)
    7054             :     {
    7055          36 :         varno = var->varnosyn;
    7056          36 :         varattno = var->varattnosyn;
    7057             :     }
    7058             :     else
    7059             :     {
    7060          48 :         varno = var->varno;
    7061          48 :         varattno = var->varattno;
    7062             :     }
    7063             : 
    7064             :     /*
    7065             :      * Try to find the relevant RTE in this rtable.  In a plan tree, it's
    7066             :      * likely that varno is OUTER_VAR or INNER_VAR, in which case we must dig
    7067             :      * down into the subplans, or INDEX_VAR, which is resolved similarly.
    7068             :      *
    7069             :      * Note: unlike get_variable and resolve_special_varno, we need not worry
    7070             :      * about inheritance mapping: a child Var should have the same datatype as
    7071             :      * its parent, and here we're really only interested in the Var's type.
    7072             :      */
    7073          84 :     if (varno >= 1 && varno <= list_length(dpns->rtable))
    7074             :     {
    7075          48 :         rte = rt_fetch(varno, dpns->rtable);
    7076          48 :         attnum = varattno;
    7077             :     }
    7078          36 :     else if (varno == OUTER_VAR && dpns->outer_tlist)
    7079             :     {
    7080             :         TargetEntry *tle;
    7081             :         deparse_namespace save_dpns;
    7082             :         const char *result;
    7083             : 
    7084          28 :         tle = get_tle_by_resno(dpns->outer_tlist, varattno);
    7085          28 :         if (!tle)
    7086           0 :             elog(ERROR, "bogus varattno for OUTER_VAR var: %d", varattno);
    7087             : 
    7088             :         Assert(netlevelsup == 0);
    7089          28 :         push_child_plan(dpns, dpns->outer_plan, &save_dpns);
    7090             : 
    7091          28 :         result = get_name_for_var_field((Var *) tle->expr, fieldno,
    7092             :                                         levelsup, context);
    7093             : 
    7094          28 :         pop_child_plan(dpns, &save_dpns);
    7095          28 :         return result;
    7096             :     }
    7097           8 :     else if (varno == INNER_VAR && dpns->inner_tlist)
    7098             :     {
    7099             :         TargetEntry *tle;
    7100             :         deparse_namespace save_dpns;
    7101             :         const char *result;
    7102             : 
    7103           8 :         tle = get_tle_by_resno(dpns->inner_tlist, varattno);
    7104           8 :         if (!tle)
    7105           0 :             elog(ERROR, "bogus varattno for INNER_VAR var: %d", varattno);
    7106             : 
    7107             :         Assert(netlevelsup == 0);
    7108           8 :         push_child_plan(dpns, dpns->inner_plan, &save_dpns);
    7109             : 
    7110           8 :         result = get_name_for_var_field((Var *) tle->expr, fieldno,
    7111             :                                         levelsup, context);
    7112             : 
    7113           8 :         pop_child_plan(dpns, &save_dpns);
    7114           8 :         return result;
    7115             :     }
    7116           0 :     else if (varno == INDEX_VAR && dpns->index_tlist)
    7117             :     {
    7118             :         TargetEntry *tle;
    7119             :         const char *result;
    7120             : 
    7121           0 :         tle = get_tle_by_resno(dpns->index_tlist, varattno);
    7122           0 :         if (!tle)
    7123           0 :             elog(ERROR, "bogus varattno for INDEX_VAR var: %d", varattno);
    7124             : 
    7125             :         Assert(netlevelsup == 0);
    7126             : 
    7127           0 :         result = get_name_for_var_field((Var *) tle->expr, fieldno,
    7128             :                                         levelsup, context);
    7129             : 
    7130           0 :         return result;
    7131             :     }
    7132             :     else
    7133             :     {
    7134           0 :         elog(ERROR, "bogus varno: %d", varno);
    7135             :         return NULL;            /* keep compiler quiet */
    7136             :     }
    7137             : 
    7138          48 :     if (attnum == InvalidAttrNumber)
    7139             :     {
    7140             :         /* Var is whole-row reference to RTE, so select the right field */
    7141          16 :         return get_rte_attribute_name(rte, fieldno);
    7142             :     }
    7143             : 
    7144             :     /*
    7145             :      * This part has essentially the same logic as the parser's
    7146             :      * expandRecordVariable() function, but we are dealing with a different
    7147             :      * representation of the input context, and we only need one field name
    7148             :      * not a TupleDesc.  Also, we need special cases for finding subquery and
    7149             :      * CTE subplans when deparsing Plan trees.
    7150             :      */
    7151          32 :     expr = (Node *) var;        /* default if we can't drill down */
    7152             : 
    7153          32 :     switch (rte->rtekind)
    7154             :     {
    7155           0 :         case RTE_RELATION:
    7156             :         case RTE_VALUES:
    7157             :         case RTE_NAMEDTUPLESTORE:
    7158             :         case RTE_RESULT:
    7159             : 
    7160             :             /*
    7161             :              * This case should not occur: a column of a table, values list,
    7162             :              * or ENR shouldn't have type RECORD.  Fall through and fail (most
    7163             :              * likely) at the bottom.
    7164             :              */
    7165           0 :             break;
    7166          12 :         case RTE_SUBQUERY:
    7167             :             /* Subselect-in-FROM: examine sub-select's output expr */
    7168             :             {
    7169          12 :                 if (rte->subquery)
    7170             :                 {
    7171           8 :                     TargetEntry *ste = get_tle_by_resno(rte->subquery->targetList,
    7172             :                                                         attnum);
    7173             : 
    7174           8 :                     if (ste == NULL || ste->resjunk)
    7175           0 :                         elog(ERROR, "subquery %s does not have attribute %d",
    7176             :                              rte->eref->aliasname, attnum);
    7177           8 :                     expr = (Node *) ste->expr;
    7178           8 :                     if (IsA(expr, Var))
    7179             :                     {
    7180             :                         /*
    7181             :                          * Recurse into the sub-select to see what its Var
    7182             :                          * refers to. We have to build an additional level of
    7183             :                          * namespace to keep in step with varlevelsup in the
    7184             :                          * subselect.
    7185             :                          */
    7186             :                         deparse_namespace mydpns;
    7187             :                         const char *result;
    7188             : 
    7189           8 :                         set_deparse_for_query(&mydpns, rte->subquery,
    7190             :                                               context->namespaces);
    7191             : 
    7192           8 :                         context->namespaces = lcons(&mydpns,
    7193             :                                                     context->namespaces);
    7194             : 
    7195           8 :                         result = get_name_for_var_field((Var *) expr, fieldno,
    7196             :                                                         0, context);
    7197             : 
    7198           8 :                         context->namespaces =
    7199           8 :                             list_delete_first(context->namespaces);
    7200             : 
    7201           8 :                         return result;
    7202             :                     }
    7203             :                     /* else fall through to inspect the expression */
    7204             :                 }
    7205             :                 else
    7206             :                 {
    7207             :                     /*
    7208             :                      * We're deparsing a Plan tree so we don't have complete
    7209             :                      * RTE entries (in particular, rte->subquery is NULL). But
    7210             :                      * the only place we'd see a Var directly referencing a
    7211             :                      * SUBQUERY RTE is in a SubqueryScan plan node, and we can
    7212             :                      * look into the child plan's tlist instead.
    7213             :                      */
    7214             :                     TargetEntry *tle;
    7215             :                     deparse_namespace save_dpns;
    7216             :                     const char *result;
    7217             : 
    7218           4 :                     if (!dpns->inner_plan)
    7219           0 :                         elog(ERROR, "failed to find plan for subquery %s",
    7220             :                              rte->eref->aliasname);
    7221           4 :                     tle = get_tle_by_resno(dpns->inner_tlist, attnum);
    7222           4 :                     if (!tle)
    7223           0 :                         elog(ERROR, "bogus varattno for subquery var: %d",
    7224             :                              attnum);
    7225             :                     Assert(netlevelsup == 0);
    7226           4 :                     push_child_plan(dpns, dpns->inner_plan, &save_dpns);
    7227             : 
    7228           4 :                     result = get_name_for_var_field((Var *) tle->expr, fieldno,
    7229             :                                                     levelsup, context);
    7230             : 
    7231           4 :                     pop_child_plan(dpns, &save_dpns);
    7232           4 :                     return result;
    7233             :                 }
    7234             :             }
    7235           0 :             break;
    7236           0 :         case RTE_JOIN:
    7237             :             /* Join RTE --- recursively inspect the alias variable */
    7238           0 :             if (rte->joinaliasvars == NIL)
    7239           0 :                 elog(ERROR, "cannot decompile join alias var in plan tree");
    7240             :             Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
    7241           0 :             expr = (Node *) list_nth(rte->joinaliasvars, attnum - 1);
    7242             :             Assert(expr != NULL);
    7243             :             /* we intentionally don't strip implicit coercions here */
    7244           0 :             if (IsA(expr, Var))
    7245           0 :                 return get_name_for_var_field((Var *) expr, fieldno,
    7246           0 :                                               var->varlevelsup + levelsup,
    7247             :                                               context);
    7248             :             /* else fall through to inspect the expression */
    7249           0 :             break;
    7250           0 :         case RTE_FUNCTION:
    7251             :         case RTE_TABLEFUNC:
    7252             : 
    7253             :             /*
    7254             :              * We couldn't get here unless a function is declared with one of
    7255             :              * its result columns as RECORD, which is not allowed.
    7256             :              */
    7257           0 :             break;
    7258          20 :         case RTE_CTE:
    7259             :             /* CTE reference: examine subquery's output expr */
    7260             :             {
    7261          20 :                 CommonTableExpr *cte = NULL;
    7262             :                 Index       ctelevelsup;
    7263             :                 ListCell   *lc;
    7264             : 
    7265             :                 /*
    7266             :                  * Try to find the referenced CTE using the namespace stack.
    7267             :                  */
    7268          20 :                 ctelevelsup = rte->ctelevelsup + netlevelsup;
    7269          20 :                 if (ctelevelsup >= list_length(context->namespaces))
    7270           0 :                     lc = NULL;
    7271             :                 else
    7272             :                 {
    7273             :                     deparse_namespace *ctedpns;
    7274             : 
    7275             :                     ctedpns = (deparse_namespace *)
    7276          20 :                         list_nth(context->namespaces, ctelevelsup);
    7277          20 :                     foreach(lc, ctedpns->ctes)
    7278             :                     {
    7279          12 :                         cte = (CommonTableExpr *) lfirst(lc);
    7280          12 :                         if (strcmp(cte->ctename, rte->ctename) == 0)
    7281          12 :                             break;
    7282             :                     }
    7283             :                 }
    7284          20 :                 if (lc != NULL)
    7285             :                 {
    7286          12 :                     Query      *ctequery = (Query *) cte->ctequery;
    7287          12 :                     TargetEntry *ste = get_tle_by_resno(GetCTETargetList(cte),
    7288             :                                                         attnum);
    7289             : 
    7290          12 :                     if (ste == NULL || ste->resjunk)
    7291           0 :                         elog(ERROR, "subquery %s does not have attribute %d",
    7292             :                              rte->eref->aliasname, attnum);
    7293          12 :                     expr = (Node *) ste->expr;
    7294          12 :                     if (IsA(expr, Var))
    7295             :                     {
    7296             :                         /*
    7297             :                          * Recurse into the CTE to see what its Var refers to.
    7298             :                          * We have to build an additional level of namespace
    7299             :                          * to keep in step with varlevelsup in the CTE.
    7300             :                          * Furthermore it could be an outer CTE, so we may
    7301             :                          * have to delete some levels of namespace.
    7302             :                          */
    7303           8 :                         List       *save_nslist = context->namespaces;
    7304             :                         List       *new_nslist;
    7305             :                         deparse_namespace mydpns;
    7306             :                         const char *result;
    7307             : 
    7308           8 :                         set_deparse_for_query(&mydpns, ctequery,
    7309             :                                               context->namespaces);
    7310             : 
    7311           8 :                         new_nslist = list_copy_tail(context->namespaces,
    7312             :                                                     ctelevelsup);
    7313           8 :                         context->namespaces = lcons(&mydpns, new_nslist);
    7314             : 
    7315           8 :                         result = get_name_for_var_field((Var *) expr, fieldno,
    7316             :                                                         0, context);
    7317             : 
    7318           8 :                         context->namespaces = save_nslist;
    7319             : 
    7320           8 :                         return result;
    7321             :                     }
    7322             :                     /* else fall through to inspect the expression */
    7323             :                 }
    7324             :                 else
    7325             :                 {
    7326             :                     /*
    7327             :                      * We're deparsing a Plan tree so we don't have a CTE
    7328             :                      * list.  But the only place we'd see a Var directly
    7329             :                      * referencing a CTE RTE is in a CteScan plan node, and we
    7330             :                      * can look into the subplan's tlist instead.
    7331             :                      */
    7332             :                     TargetEntry *tle;
    7333             :                     deparse_namespace save_dpns;
    7334             :                     const char *result;
    7335             : 
    7336           8 :                     if (!dpns->inner_plan)
    7337           0 :                         elog(ERROR, "failed to find plan for CTE %s",
    7338             :                              rte->eref->aliasname);
    7339           8 :                     tle = get_tle_by_resno(dpns->inner_tlist, attnum);
    7340           8 :                     if (!tle)
    7341           0 :                         elog(ERROR, "bogus varattno for subquery var: %d",
    7342             :                              attnum);
    7343             :                     Assert(netlevelsup == 0);
    7344           8 :                     push_child_plan(dpns, dpns->inner_plan, &save_dpns);
    7345             : 
    7346           8 :                     result = get_name_for_var_field((Var *) tle->expr, fieldno,
    7347             :                                                     levelsup, context);
    7348             : 
    7349           8 :                     pop_child_plan(dpns, &save_dpns);
    7350           8 :                     return result;
    7351             :                 }
    7352             :             }
    7353           4 :             break;
    7354             :     }
    7355             : 
    7356             :     /*
    7357             :      * We now have an expression we can't expand any more, so see if
    7358             :      * get_expr_result_tupdesc() can do anything with it.
    7359             :      */
    7360           4 :     tupleDesc = get_expr_result_tupdesc(expr, false);
    7361             :     /* Got the tupdesc, so we can extract the field name */
    7362             :     Assert(fieldno >= 1 && fieldno <= tupleDesc->natts);
    7363           4 :     return NameStr(TupleDescAttr(tupleDesc, fieldno - 1)->attname);
    7364             : }
    7365             : 
    7366             : /*
    7367             :  * Try to find the referenced expression for a PARAM_EXEC Param that might
    7368             :  * reference a parameter supplied by an upper NestLoop or SubPlan plan node.
    7369             :  *
    7370             :  * If successful, return the expression and set *dpns_p and *ancestor_cell_p
    7371             :  * appropriately for calling push_ancestor_plan().  If no referent can be
    7372             :  * found, return NULL.
    7373             :  */
    7374             : static Node *
    7375        2812 : find_param_referent(Param *param, deparse_context *context,
    7376             :                     deparse_namespace **dpns_p, ListCell **ancestor_cell_p)
    7377             : {
    7378             :     /* Initialize output parameters to prevent compiler warnings */
    7379        2812 :     *dpns_p = NULL;
    7380        2812 :     *ancestor_cell_p = NULL;
    7381             : 
    7382             :     /*
    7383             :      * If it's a PARAM_EXEC parameter, look for a matching NestLoopParam or
    7384             :      * SubPlan argument.  This will necessarily be in some ancestor of the
    7385             :      * current expression's Plan node.
    7386             :      */
    7387        2812 :     if (param->paramkind == PARAM_EXEC)
    7388             :     {
    7389             :         deparse_namespace *dpns;
    7390             :         Plan       *child_plan;
    7391             :         bool        in_same_plan_level;
    7392             :         ListCell   *lc;
    7393             : 
    7394        2346 :         dpns = (deparse_namespace *) linitial(context->namespaces);
    7395        2346 :         child_plan = dpns->plan;
    7396        2346 :         in_same_plan_level = true;
    7397             : 
    7398        4392 :         foreach(lc, dpns->ancestors)
    7399             :         {
    7400        3540 :             Node       *ancestor = (Node *) lfirst(lc);
    7401             :             ListCell   *lc2;
    7402             : 
    7403             :             /*
    7404             :              * NestLoops transmit params to their inner child only; also, once
    7405             :              * we've crawled up out of a subplan, this couldn't possibly be
    7406             :              * the right match.
    7407             :              */
    7408        3540 :             if (IsA(ancestor, NestLoop) &&
    7409        1472 :                 child_plan == innerPlan(ancestor) &&
    7410             :                 in_same_plan_level)
    7411             :             {
    7412        1392 :                 NestLoop   *nl = (NestLoop *) ancestor;
    7413             : 
    7414        1714 :                 foreach(lc2, nl->nestParams)
    7415             :                 {
    7416        1654 :                     NestLoopParam *nlp = (NestLoopParam *) lfirst(lc2);
    7417             : 
    7418        1654 :                     if (nlp->paramno == param->paramid)
    7419             :                     {
    7420             :                         /* Found a match, so return it */
    7421        1332 :                         *dpns_p = dpns;
    7422        1332 :                         *ancestor_cell_p = lc;
    7423        1332 :                         return (Node *) nlp->paramval;
    7424             :                     }
    7425             :                 }
    7426             :             }
    7427             : 
    7428             :             /*
    7429             :              * If ancestor is a SubPlan, check the arguments it provides.
    7430             :              */
    7431        2208 :             if (IsA(ancestor, SubPlan))
    7432             :             {
    7433         206 :                 SubPlan    *subplan = (SubPlan *) ancestor;
    7434             :                 ListCell   *lc3;
    7435             :                 ListCell   *lc4;
    7436             : 
    7437         224 :                 forboth(lc3, subplan->parParam, lc4, subplan->args)
    7438             :                 {
    7439         180 :                     int         paramid = lfirst_int(lc3);
    7440         180 :                     Node       *arg = (Node *) lfirst(lc4);
    7441             : 
    7442         180 :                     if (paramid == param->paramid)
    7443             :                     {
    7444             :                         /*
    7445             :                          * Found a match, so return it.  But, since Vars in
    7446             :                          * the arg are to be evaluated in the surrounding
    7447             :                          * context, we have to point to the next ancestor item
    7448             :                          * that is *not* a SubPlan.
    7449             :                          */
    7450             :                         ListCell   *rest;
    7451             : 
    7452         162 :                         for_each_cell(rest, dpns->ancestors,
    7453             :                                       lnext(dpns->ancestors, lc))
    7454             :                         {
    7455         162 :                             Node       *ancestor2 = (Node *) lfirst(rest);
    7456             : 
    7457         162 :                             if (!IsA(ancestor2, SubPlan))
    7458             :                             {
    7459         162 :                                 *dpns_p = dpns;
    7460         162 :                                 *ancestor_cell_p = rest;
    7461         162 :                                 return arg;
    7462             :                             }
    7463             :                         }
    7464           0 :                         elog(ERROR, "SubPlan cannot be outermost ancestor");
    7465             :                     }
    7466             :                 }
    7467             : 
    7468             :                 /* We have emerged from a subplan. */
    7469          44 :                 in_same_plan_level = false;
    7470             : 
    7471             :                 /* SubPlan isn't a kind of Plan, so skip the rest */
    7472          44 :                 continue;
    7473             :             }
    7474             : 
    7475             :             /*
    7476             :              * Check to see if we're emerging from an initplan of the current
    7477             :              * ancestor plan.  Initplans never have any parParams, so no need
    7478             :              * to search that list, but we need to know if we should reset
    7479             :              * in_same_plan_level.
    7480             :              */
    7481        2696 :             foreach(lc2, ((Plan *) ancestor)->initPlan)
    7482             :             {
    7483         710 :                 SubPlan    *subplan = castNode(SubPlan, lfirst(lc2));
    7484             : 
    7485         710 :                 if (child_plan != (Plan *) list_nth(dpns->subplans,
    7486         710 :                                                     subplan->plan_id - 1))
    7487         694 :                     continue;
    7488             : 
    7489             :                 /* No parameters to be had here. */
    7490             :                 Assert(subplan->parParam == NIL);
    7491             : 
    7492             :                 /* We have emerged from an initplan. */
    7493          16 :                 in_same_plan_level = false;
    7494          16 :                 break;
    7495             :             }
    7496             : 
    7497             :             /* No luck, crawl up to next ancestor */
    7498        2002 :             child_plan = (Plan *) ancestor;
    7499             :         }
    7500             :     }
    7501             : 
    7502             :     /* No referent found */
    7503        1318 :     return NULL;
    7504             : }
    7505             : 
    7506             : /*
    7507             :  * Display a Param appropriately.
    7508             :  */
    7509             : static void
    7510        2804 : get_parameter(Param *param, deparse_context *context)
    7511             : {
    7512             :     Node       *expr;
    7513             :     deparse_namespace *dpns;
    7514             :     ListCell   *ancestor_cell;
    7515             : 
    7516             :     /*
    7517             :      * If it's a PARAM_EXEC parameter, try to locate the expression from which
    7518             :      * the parameter was computed.  Note that failing to find a referent isn't
    7519             :      * an error, since the Param might well be a subplan output rather than an
    7520             :      * input.
    7521             :      */
    7522        2804 :     expr = find_param_referent(param, context, &dpns, &ancestor_cell);
    7523        2804 :     if (expr)
    7524             :     {
    7525             :         /* Found a match, so print it */
    7526             :         deparse_namespace save_dpns;
    7527             :         bool        save_varprefix;
    7528             :         bool        need_paren;
    7529             : 
    7530             :         /* Switch attention to the ancestor plan node */
    7531        1486 :         push_ancestor_plan(dpns, ancestor_cell, &save_dpns);
    7532             : 
    7533             :         /*
    7534             :          * Force prefixing of Vars, since they won't belong to the relation
    7535             :          * being scanned in the original plan node.
    7536             :          */
    7537        1486 :         save_varprefix = context->varprefix;
    7538        1486 :         context->varprefix = true;
    7539             : 
    7540             :         /*
    7541             :          * A Param's expansion is typically a Var, Aggref, or upper-level
    7542             :          * Param, which wouldn't need extra parentheses.  Otherwise, insert
    7543             :          * parens to ensure the expression looks atomic.
    7544             :          */
    7545        1486 :         need_paren = !(IsA(expr, Var) ||
    7546           0 :                        IsA(expr, Aggref) ||
    7547           0 :                        IsA(expr, Param));
    7548        1486 :         if (need_paren)
    7549           0 :             appendStringInfoChar(context->buf, '(');
    7550             : 
    7551        1486 :         get_rule_expr(expr, context, false);
    7552             : 
    7553        1486 :         if (need_paren)
    7554           0 :             appendStringInfoChar(context->buf, ')');
    7555             : 
    7556        1486 :         context->varprefix = save_varprefix;
    7557             : 
    7558        1486 :         pop_ancestor_plan(dpns, &save_dpns);
    7559             : 
    7560        1486 :         return;
    7561             :     }
    7562             : 
    7563             :     /*
    7564             :      * Not PARAM_EXEC, or couldn't find referent: just print $N.
    7565             :      */
    7566        1318 :     appendStringInfo(context->buf, "$%d", param->paramid);
    7567             : }
    7568             : 
    7569             : /*
    7570             :  * get_simple_binary_op_name
    7571             :  *
    7572             :  * helper function for isSimpleNode
    7573             :  * will return single char binary operator name, or NULL if it's not
    7574             :  */
    7575             : static const char *
    7576          76 : get_simple_binary_op_name(OpExpr *expr)
    7577             : {
    7578          76 :     List       *args = expr->args;
    7579             : 
    7580          76 :     if (list_length(args) == 2)
    7581             :     {
    7582             :         /* binary operator */
    7583          76 :         Node       *arg1 = (Node *) linitial(args);
    7584          76 :         Node       *arg2 = (Node *) lsecond(args);
    7585             :         const char *op;
    7586             : 
    7587          76 :         op = generate_operator_name(expr->opno, exprType(arg1), exprType(arg2));
    7588          76 :         if (strlen(op) == 1)
    7589          76 :             return op;
    7590             :     }
    7591           0 :     return NULL;
    7592             : }
    7593             : 
    7594             : 
    7595             : /*
    7596             :  * isSimpleNode - check if given node is simple (doesn't need parenthesizing)
    7597             :  *
    7598             :  *  true   : simple in the context of parent node's type
    7599             :  *  false  : not simple
    7600             :  */
    7601             : static bool
    7602        2252 : isSimpleNode(Node *node, Node *parentNode, int prettyFlags)
    7603             : {
    7604        2252 :     if (!node)
    7605           0 :         return false;
    7606             : 
    7607        2252 :     switch (nodeTag(node))
    7608             :     {
    7609        1864 :         case T_Var:
    7610             :         case T_Const:
    7611             :         case T_Param:
    7612             :         case T_CoerceToDomainValue:
    7613             :         case T_SetToDefault:
    7614             :         case T_CurrentOfExpr:
    7615             :             /* single words: always simple */
    7616        1864 :             return true;
    7617             : 
    7618         208 :         case T_SubscriptingRef:
    7619             :         case T_ArrayExpr:
    7620             :         case T_RowExpr:
    7621             :         case T_CoalesceExpr:
    7622             :         case T_MinMaxExpr:
    7623             :         case T_SQLValueFunction:
    7624             :         case T_XmlExpr:
    7625             :         case T_NextValueExpr:
    7626             :         case T_NullIfExpr:
    7627             :         case T_Aggref:
    7628             :         case T_WindowFunc:
    7629             :         case T_FuncExpr:
    7630             :             /* function-like: name(..) or name[..] */
    7631         208 :             return true;
    7632             : 
    7633             :             /* CASE keywords act as parentheses */
    7634           0 :         case T_CaseExpr:
    7635           0 :             return true;
    7636             : 
    7637          32 :         case T_FieldSelect:
    7638             : 
    7639             :             /*
    7640             :              * appears simple since . has top precedence, unless parent is
    7641             :              * T_FieldSelect itself!
    7642             :              */
    7643          32 :             return (IsA(parentNode, FieldSelect) ? false : true);
    7644             : 
    7645           0 :         case T_FieldStore:
    7646             : 
    7647             :             /*
    7648             :              * treat like FieldSelect (probably doesn't matter)
    7649             :              */
    7650           0 :             return (IsA(parentNode, FieldStore) ? false : true);
    7651             : 
    7652           0 :         case T_CoerceToDomain:
    7653             :             /* maybe simple, check args */
    7654           0 :             return isSimpleNode((Node *) ((CoerceToDomain *) node)->arg,
    7655             :                                 node, prettyFlags);
    7656           4 :         case T_RelabelType:
    7657           4 :             return isSimpleNode((Node *) ((RelabelType *) node)->arg,
    7658             :                                 node, prettyFlags);
    7659           0 :         case T_CoerceViaIO:
    7660           0 :             return isSimpleNode((Node *) ((CoerceViaIO *) node)->arg,
    7661             :                                 node, prettyFlags);
    7662           0 :         case T_ArrayCoerceExpr:
    7663           0 :             return isSimpleNode((Node *) ((ArrayCoerceExpr *) node)->arg,
    7664             :                                 node, prettyFlags);
    7665           0 :         case T_ConvertRowtypeExpr:
    7666           0 :             return isSimpleNode((Node *) ((ConvertRowtypeExpr *) node)->arg,
    7667             :                                 node, prettyFlags);
    7668             : 
    7669         128 :         case T_OpExpr:
    7670             :             {
    7671             :                 /* depends on parent node type; needs further checking */
    7672         128 :                 if (prettyFlags & PRETTYFLAG_PAREN && IsA(parentNode, OpExpr))
    7673             :                 {
    7674             :                     const char *op;
    7675             :                     const char *parentOp;
    7676             :                     bool        is_lopriop;
    7677             :                     bool        is_hipriop;
    7678             :                     bool        is_lopriparent;
    7679             :                     bool        is_hipriparent;
    7680             : 
    7681          40 :                     op = get_simple_binary_op_name((OpExpr *) node);
    7682          40 :                     if (!op)
    7683           0 :                         return false;
    7684             : 
    7685             :                     /* We know only the basic operators + - and * / % */
    7686          40 :                     is_lopriop = (strchr("+-", *op) != NULL);
    7687          40 :                     is_hipriop = (strchr("*/%", *op) != NULL);
    7688          40 :                     if (!(is_lopriop || is_hipriop))
    7689           4 :                         return false;
    7690             : 
    7691          36 :                     parentOp = get_simple_binary_op_name((OpExpr *) parentNode);
    7692          36 :                     if (!parentOp)
    7693           0 :                         return false;
    7694             : 
    7695          36 :                     is_lopriparent = (strchr("+-", *parentOp) != NULL);
    7696          36 :                     is_hipriparent = (strchr("*/%", *parentOp) != NULL);
    7697          36 :                     if (!(is_lopriparent || is_hipriparent))
    7698           0 :                         return false;
    7699             : 
    7700          36 :                     if (is_hipriop && is_lopriparent)
    7701           8 :                         return true;    /* op binds tighter than parent */
    7702             : 
    7703          28 :                     if (is_lopriop && is_hipriparent)
    7704          20 :                         return false;
    7705             : 
    7706             :                     /*
    7707             :                      * Operators are same priority --- can skip parens only if
    7708             :                      * we have (a - b) - c, not a - (b - c).
    7709             :                      */
    7710           8 :                     if (node == (Node *) linitial(((OpExpr *) parentNode)->args))
    7711           4 :                         return true;
    7712             : 
    7713           4 :                     return false;
    7714             :                 }
    7715             :                 /* else do the same stuff as for T_SubLink et al. */
    7716             :             }
    7717             :             /* FALLTHROUGH */
    7718             : 
    7719             :         case T_SubLink:
    7720             :         case T_NullTest:
    7721             :         case T_BooleanTest:
    7722             :         case T_DistinctExpr:
    7723          92 :             switch (nodeTag(parentNode))
    7724             :             {
    7725          16 :                 case T_FuncExpr:
    7726             :                     {
    7727             :                         /* special handling for casts */
    7728          16 :                         CoercionForm type = ((FuncExpr *) parentNode)->funcformat;
    7729             : 
    7730          16 :                         if (type == COERCE_EXPLICIT_CAST ||
    7731             :                             type == COERCE_IMPLICIT_CAST)
    7732          16 :                             return false;
    7733           0 :                         return true;    /* own parentheses */
    7734             :                     }
    7735          72 :                 case T_BoolExpr:    /* lower precedence */
    7736             :                 case T_SubscriptingRef: /* other separators */
    7737             :                 case T_ArrayExpr:   /* other separators */
    7738             :                 case T_RowExpr: /* other separators */
    7739             :                 case T_CoalesceExpr:    /* own parentheses */
    7740             :                 case T_MinMaxExpr:  /* own parentheses */
    7741             :                 case T_XmlExpr: /* own parentheses */
    7742             :                 case T_NullIfExpr:  /* other separators */
    7743             :                 case T_Aggref:  /* own parentheses */
    7744             :                 case T_WindowFunc:  /* own parentheses */
    7745             :                 case T_CaseExpr:    /* other separators */
    7746          72 :                     return true;
    7747           4 :                 default:
    7748           4 :                     return false;
    7749             :             }
    7750             : 
    7751          12 :         case T_BoolExpr:
    7752          12 :             switch (nodeTag(parentNode))
    7753             :             {
    7754          12 :                 case T_BoolExpr:
    7755          12 :                     if (prettyFlags & PRETTYFLAG_PAREN)
    7756             :                     {
    7757             :                         BoolExprType type;
    7758             :                         BoolExprType parentType;
    7759             : 
    7760          12 :                         type = ((BoolExpr *) node)->boolop;
    7761          12 :                         parentType = ((BoolExpr *) parentNode)->boolop;
    7762             :                         switch (type)
    7763             :                         {
    7764           8 :                             case NOT_EXPR:
    7765             :                             case AND_EXPR:
    7766           8 :                                 if (parentType == AND_EXPR || parentType == OR_EXPR)
    7767           8 :                                     return true;
    7768           0 :                                 break;
    7769           4 :                             case OR_EXPR:
    7770           4 :                                 if (parentType == OR_EXPR)
    7771           0 :                                     return true;
    7772           4 :                                 break;
    7773             :                         }
    7774           0 :                     }
    7775           4 :                     return false;
    7776           0 :                 case T_FuncExpr:
    7777             :                     {
    7778             :                         /* special handling for casts */
    7779           0 :                         CoercionForm type = ((FuncExpr *) parentNode)->funcformat;
    7780             : 
    7781           0 :                         if (type == COERCE_EXPLICIT_CAST ||
    7782             :                             type == COERCE_IMPLICIT_CAST)
    7783           0 :                             return false;
    7784           0 :                         return true;    /* own parentheses */
    7785             :                     }
    7786           0 :                 case T_SubscriptingRef: /* other separators */
    7787             :                 case T_ArrayExpr:   /* other separators */
    7788             :                 case T_RowExpr: /* other separators */
    7789             :                 case T_CoalesceExpr:    /* own parentheses */
    7790             :                 case T_MinMaxExpr:  /* own parentheses */
    7791             :                 case T_XmlExpr: /* own parentheses */
    7792             :                 case T_NullIfExpr:  /* other separators */
    7793             :                 case T_Aggref:  /* own parentheses */
    7794             :                 case T_WindowFunc:  /* own parentheses */
    7795             :                 case T_CaseExpr:    /* other separators */
    7796           0 :                     return true;
    7797           0 :                 default:
    7798           0 :                     return false;
    7799             :             }
    7800             : 
    7801           0 :         default:
    7802           0 :             break;
    7803             :     }
    7804             :     /* those we don't know: in dubio complexo */
    7805           0 :     return false;
    7806             : }
    7807             : 
    7808             : 
    7809             : /*
    7810             :  * appendContextKeyword - append a keyword to buffer
    7811             :  *
    7812             :  * If prettyPrint is enabled, perform a line break, and adjust indentation.
    7813             :  * Otherwise, just append the keyword.
    7814             :  */
    7815             : static void
    7816       10022 : appendContextKeyword(deparse_context *context, const char *str,
    7817             :                      int indentBefore, int indentAfter, int indentPlus)
    7818             : {
    7819       10022 :     StringInfo  buf = context->buf;
    7820             : 
    7821       10022 :     if (PRETTY_INDENT(context))
    7822             :     {
    7823             :         int         indentAmount;
    7824             : 
    7825        9958 :         context->indentLevel += indentBefore;
    7826             : 
    7827             :         /* remove any trailing spaces currently in the buffer ... */
    7828        9958 :         removeStringInfoSpaces(buf);
    7829             :         /* ... then add a newline and some spaces */
    7830        9958 :         appendStringInfoChar(buf, '\n');
    7831             : 
    7832        9958 :         if (context->indentLevel < PRETTYINDENT_LIMIT)
    7833        9958 :             indentAmount = Max(context->indentLevel, 0) + indentPlus;
    7834             :         else
    7835             :         {
    7836             :             /*
    7837             :              * If we're indented more than PRETTYINDENT_LIMIT characters, try
    7838             :              * to conserve horizontal space by reducing the per-level
    7839             :              * indentation.  For best results the scale factor here should
    7840             :              * divide all the indent amounts that get added to indentLevel
    7841             :              * (PRETTYINDENT_STD, etc).  It's important that the indentation
    7842             :              * not grow unboundedly, else deeply-nested trees use O(N^2)
    7843             :              * whitespace; so we also wrap modulo PRETTYINDENT_LIMIT.
    7844             :              */
    7845           0 :             indentAmount = PRETTYINDENT_LIMIT +
    7846           0 :                 (context->indentLevel - PRETTYINDENT_LIMIT) /
    7847             :                 (PRETTYINDENT_STD / 2);
    7848           0 :             indentAmount %= PRETTYINDENT_LIMIT;
    7849             :             /* scale/wrap logic affects indentLevel, but not indentPlus */
    7850           0 :             indentAmount += indentPlus;
    7851             :         }
    7852        9958 :         appendStringInfoSpaces(buf, indentAmount);
    7853             : 
    7854        9958 :         appendStringInfoString(buf, str);
    7855             : 
    7856        9958 :         context->indentLevel += indentAfter;
    7857        9958 :         if (context->indentLevel < 0)
    7858           0 :             context->indentLevel = 0;
    7859             :     }
    7860             :     else
    7861          64 :         appendStringInfoString(buf, str);
    7862       10022 : }
    7863             : 
    7864             : /*
    7865             :  * removeStringInfoSpaces - delete trailing spaces from a buffer.
    7866             :  *
    7867             :  * Possibly this should move to stringinfo.c at some point.
    7868             :  */
    7869             : static void
    7870       10066 : removeStringInfoSpaces(StringInfo str)
    7871             : {
    7872       15588 :     while (str->len > 0 && str->data[str->len - 1] == ' ')
    7873        5522 :         str->data[--(str->len)] = '\0';
    7874       10066 : }
    7875             : 
    7876             : 
    7877             : /*
    7878             :  * get_rule_expr_paren  - deparse expr using get_rule_expr,
    7879             :  * embracing the string with parentheses if necessary for prettyPrint.
    7880             :  *
    7881             :  * Never embrace if prettyFlags=0, because it's done in the calling node.
    7882             :  *
    7883             :  * Any node that does *not* embrace its argument node by sql syntax (with
    7884             :  * parentheses, non-operator keywords like CASE/WHEN/ON, or comma etc) should
    7885             :  * use get_rule_expr_paren instead of get_rule_expr so parentheses can be
    7886             :  * added.
    7887             :  */
    7888             : static void
    7889       72210 : get_rule_expr_paren(Node *node, deparse_context *context,
    7890             :                     bool showimplicit, Node *parentNode)
    7891             : {
    7892             :     bool        need_paren;
    7893             : 
    7894       74458 :     need_paren = PRETTY_PAREN(context) &&
    7895        2248 :         !isSimpleNode(node, parentNode, context->prettyFlags);
    7896             : 
    7897       72210 :     if (need_paren)
    7898          52 :         appendStringInfoChar(context->buf, '(');
    7899             : 
    7900       72210 :     get_rule_expr(node, context, showimplicit);
    7901             : 
    7902       72210 :     if (need_paren)
    7903          52 :         appendStringInfoChar(context->buf, ')');
    7904       72210 : }
    7905             : 
    7906             : 
    7907             : /* ----------
    7908             :  * get_rule_expr            - Parse back an expression
    7909             :  *
    7910             :  * Note: showimplicit determines whether we display any implicit cast that
    7911             :  * is present at the top of the expression tree.  It is a passed argument,
    7912             :  * not a field of the context struct, because we change the value as we
    7913             :  * recurse down into the expression.  In general we suppress implicit casts
    7914             :  * when the result type is known with certainty (eg, the arguments of an
    7915             :  * OR must be boolean).  We display implicit casts for arguments of functions
    7916             :  * and operators, since this is needed to be certain that the same function
    7917             :  * or operator will be chosen when the expression is re-parsed.
    7918             :  * ----------
    7919             :  */
    7920             : static void
    7921      146650 : get_rule_expr(Node *node, deparse_context *context,
    7922             :               bool showimplicit)
    7923             : {
    7924      146650 :     StringInfo  buf = context->buf;
    7925             : 
    7926      146650 :     if (node == NULL)
    7927          16 :         return;
    7928             : 
    7929             :     /* Guard against excessively long or deeply-nested queries */
    7930      146634 :     CHECK_FOR_INTERRUPTS();
    7931      146634 :     check_stack_depth();
    7932             : 
    7933             :     /*
    7934             :      * Each level of get_rule_expr must emit an indivisible term
    7935             :      * (parenthesized if necessary) to ensure result is reparsed into the same
    7936             :      * expression tree.  The only exception is that when the input is a List,
    7937             :      * we emit the component items comma-separated with no surrounding
    7938             :      * decoration; this is convenient for most callers.
    7939             :      */
    7940      146634 :     switch (nodeTag(node))
    7941             :     {
    7942       69710 :         case T_Var:
    7943       69710 :             (void) get_variable((Var *) node, 0, false, context);
    7944       69710 :             break;
    7945             : 
    7946       26300 :         case T_Const:
    7947       26300 :             get_const_expr((Const *) node, context, 0);
    7948       26300 :             break;
    7949             : 
    7950        2804 :         case T_Param:
    7951        2804 :             get_parameter((Param *) node, context);
    7952        2804 :             break;
    7953             : 
    7954        1058 :         case T_Aggref:
    7955        1058 :             get_agg_expr((Aggref *) node, context, (Aggref *) node);
    7956        1058 :             break;
    7957             : 
    7958          28 :         case T_GroupingFunc:
    7959             :             {
    7960          28 :                 GroupingFunc *gexpr = (GroupingFunc *) node;
    7961             : 
    7962          28 :                 appendStringInfoString(buf, "GROUPING(");
    7963          28 :                 get_rule_expr((Node *) gexpr->args, context, true);
    7964          28 :                 appendStringInfoChar(buf, ')');
    7965             :             }
    7966          28 :             break;
    7967             : 
    7968          56 :         case T_WindowFunc:
    7969          56 :             get_windowfunc_expr((WindowFunc *) node, context);
    7970          56 :             break;
    7971             : 
    7972         104 :         case T_SubscriptingRef:
    7973             :             {
    7974         104 :                 SubscriptingRef *sbsref = (SubscriptingRef *) node;
    7975             :                 bool        need_parens;
    7976             : 
    7977             :                 /*
    7978             :                  * If the argument is a CaseTestExpr, we must be inside a
    7979             :                  * FieldStore, ie, we are assigning to an element of an array
    7980             :                  * within a composite column.  Since we already punted on
    7981             :                  * displaying the FieldStore's target information, just punt
    7982             :                  * here too, and display only the assignment source
    7983             :                  * expression.
    7984             :                  */
    7985         104 :                 if (IsA(sbsref->refexpr, CaseTestExpr))
    7986             :                 {
    7987             :                     Assert(sbsref->refassgnexpr);
    7988           0 :                     get_rule_expr((Node *) sbsref->refassgnexpr,
    7989             :                                   context, showimplicit);
    7990           0 :                     break;
    7991             :                 }
    7992             : 
    7993             :                 /*
    7994             :                  * Parenthesize the argument unless it's a simple Var or a
    7995             :                  * FieldSelect.  (In particular, if it's another
    7996             :                  * SubscriptingRef, we *must* parenthesize to avoid
    7997             :                  * confusion.)
    7998             :                  */
    7999         152 :                 need_parens = !IsA(sbsref->refexpr, Var) &&
    8000          48 :                     !IsA(sbsref->refexpr, FieldSelect);
    8001         104 :                 if (need_parens)
    8002          48 :                     appendStringInfoChar(buf, '(');
    8003         104 :                 get_rule_expr((Node *) sbsref->refexpr, context, showimplicit);
    8004         104 :                 if (need_parens)
    8005          48 :                     appendStringInfoChar(buf, ')');
    8006             : 
    8007             :                 /*
    8008             :                  * If there's a refassgnexpr, we want to print the node in the
    8009             :                  * format "container[subscripts] := refassgnexpr".  This is
    8010             :                  * not legal SQL, so decompilation of INSERT or UPDATE
    8011             :                  * statements should always use processIndirection as part of
    8012             :                  * the statement-level syntax.  We should only see this when
    8013             :                  * EXPLAIN tries to print the targetlist of a plan resulting
    8014             :                  * from such a statement.
    8015             :                  */
    8016         104 :                 if (sbsref->refassgnexpr)
    8017             :                 {
    8018             :                     Node       *refassgnexpr;
    8019             : 
    8020             :                     /*
    8021             :                      * Use processIndirection to print this node's subscripts
    8022             :                      * as well as any additional field selections or
    8023             :                      * subscripting in immediate descendants.  It returns the
    8024             :                      * RHS expr that is actually being "assigned".
    8025             :                      */
    8026           8 :                     refassgnexpr = processIndirection(node, context);
    8027           8 :                     appendStringInfoString(buf, " := ");
    8028           8 :                     get_rule_expr(refassgnexpr, context, showimplicit);
    8029             :                 }
    8030             :                 else
    8031             :                 {
    8032             :                     /* Just an ordinary container fetch, so print subscripts */
    8033          96 :                     printSubscripts(sbsref, context);
    8034             :                 }
    8035             :             }
    8036         104 :             break;
    8037             : 
    8038        4852 :         case T_FuncExpr:
    8039        4852 :             get_func_expr((FuncExpr *) node, context, showimplicit);
    8040        4852 :             break;
    8041             : 
    8042          12 :         case T_NamedArgExpr:
    8043             :             {
    8044          12 :                 NamedArgExpr *na = (NamedArgExpr *) node;
    8045             : 
    8046          12 :                 appendStringInfo(buf, "%s => ", quote_identifier(na->name));
    8047          12 :                 get_rule_expr((Node *) na->arg, context, showimplicit);
    8048             :             }
    8049          12 :             break;
    8050             : 
    8051       27288 :         case T_OpExpr:
    8052       27288 :             get_oper_expr((OpExpr *) node, context);
    8053       27288 :             break;
    8054             : 
    8055          12 :         case T_DistinctExpr:
    8056           4 :             {
    8057          12 :                 DistinctExpr *expr = (DistinctExpr *) node;
    8058          12 :                 List       *args = expr->args;
    8059          12 :                 Node       *arg1 = (Node *) linitial(args);
    8060          12 :                 Node       *arg2 = (Node *) lsecond(args);
    8061             : 
    8062          12 :                 if (!PRETTY_PAREN(context))
    8063           8 :                     appendStringInfoChar(buf, '(');
    8064          12 :                 get_rule_expr_paren(arg1, context, true, node);
    8065          12 :                 appendStringInfoString(buf, " IS DISTINCT FROM ");
    8066          12 :                 get_rule_expr_paren(arg2, context, true, node);
    8067          12 :                 if (!PRETTY_PAREN(context))
    8068           8 :                     appendStringInfoChar(buf, ')');
    8069             :             }
    8070          12 :             break;
    8071             : 
    8072          12 :         case T_NullIfExpr:
    8073             :             {
    8074          12 :                 NullIfExpr *nullifexpr = (NullIfExpr *) node;
    8075             : 
    8076          12 :                 appendStringInfoString(buf, "NULLIF(");
    8077          12 :                 get_rule_expr((Node *) nullifexpr->args, context, true);
    8078          12 :                 appendStringInfoChar(buf, ')');
    8079             :             }
    8080          12 :             break;
    8081             : 
    8082        1030 :         case T_ScalarArrayOpExpr:
    8083           8 :             {
    8084        1030 :                 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
    8085        1030 :                 List       *args = expr->args;
    8086        1030 :                 Node       *arg1 = (Node *) linitial(args);
    8087        1030 :                 Node       *arg2 = (Node *) lsecond(args);
    8088             : 
    8089        1030 :                 if (!PRETTY_PAREN(context))
    8090        1022 :                     appendStringInfoChar(buf, '(');
    8091        1030 :                 get_rule_expr_paren(arg1, context, true, node);
    8092        1030 :                 appendStringInfo(buf, " %s %s (",
    8093             :                                  generate_operator_name(expr->opno,
    8094             :                                                         exprType(arg1),
    8095             :                                                         get_base_element_type(exprType(arg2))),
    8096        1030 :                                  expr->useOr ? "ANY" : "ALL");
    8097        1030 :                 get_rule_expr_paren(arg2, context, true, node);
    8098             : 
    8099             :                 /*
    8100             :                  * There's inherent ambiguity in "x op ANY/ALL (y)" when y is
    8101             :                  * a bare sub-SELECT.  Since we're here, the sub-SELECT must
    8102             :                  * be meant as a scalar sub-SELECT yielding an array value to
    8103             :                  * be used in ScalarArrayOpExpr; but the grammar will
    8104             :                  * preferentially interpret such a construct as an ANY/ALL
    8105             :                  * SubLink.  To prevent misparsing the output that way, insert
    8106             :                  * a dummy coercion (which will be stripped by parse analysis,
    8107             :                  * so no inefficiency is added in dump and reload).  This is
    8108             :                  * indeed most likely what the user wrote to get the construct
    8109             :                  * accepted in the first place.
    8110             :                  */
    8111        1030 :                 if (IsA(arg2, SubLink) &&
    8112           4 :                     ((SubLink *) arg2)->subLinkType == EXPR_SUBLINK)
    8113           4 :                     appendStringInfo(buf, "::%s",
    8114             :                                      format_type_with_typemod(exprType(arg2),
    8115             :                                                               exprTypmod(arg2)));
    8116        1030 :                 appendStringInfoChar(buf, ')');
    8117        1030 :                 if (!PRETTY_PAREN(context))
    8118        1022 :                     appendStringInfoChar(buf, ')');
    8119             :             }
    8120        1030 :             break;
    8121             : 
    8122        5260 :         case T_BoolExpr:
    8123             :             {
    8124        5260 :                 BoolExpr   *expr = (BoolExpr *) node;
    8125        5260 :                 Node       *first_arg = linitial(expr->args);
    8126        5260 :                 ListCell   *arg = list_second_cell(expr->args);
    8127             : 
    8128        5260 :                 switch (expr->boolop)
    8129             :                 {
    8130        4354 :                     case AND_EXPR:
    8131        4354 :                         if (!PRETTY_PAREN(context))
    8132        4322 :                             appendStringInfoChar(buf, '(');
    8133        4354 :                         get_rule_expr_paren(first_arg, context,
    8134             :                                             false, node);
    8135        9834 :                         while (arg)
    8136             :                         {
    8137        5480 :                             appendStringInfoString(buf, " AND ");
    8138        5480 :                             get_rule_expr_paren((Node *) lfirst(arg), context,
    8139             :                                                 false, node);
    8140        5480 :                             arg = lnext(expr->args, arg);
    8141             :                         }
    8142        4354 :                         if (!PRETTY_PAREN(context))
    8143        4322 :                             appendStringInfoChar(buf, ')');
    8144        4354 :                         break;
    8145             : 
    8146         776 :                     case OR_EXPR:
    8147         776 :                         if (!PRETTY_PAREN(context))
    8148         768 :                             appendStringInfoChar(buf, '(');
    8149         776 :                         get_rule_expr_paren(first_arg, context,
    8150             :                                             false, node);
    8151        1820 :                         while (arg)
    8152             :                         {
    8153        1044 :                             appendStringInfoString(buf, " OR ");
    8154        1044 :                             get_rule_expr_paren((Node *) lfirst(arg), context,
    8155             :                                                 false, node);
    8156        1044 :                             arg = lnext(expr->args, arg);
    8157             :                         }
    8158         776 :                         if (!PRETTY_PAREN(context))
    8159         768 :                             appendStringInfoChar(buf, ')');
    8160         776 :                         break;
    8161             : 
    8162         130 :                     case NOT_EXPR:
    8163         130 :                         if (!PRETTY_PAREN(context))
    8164         126 :                             appendStringInfoChar(buf, '(');
    8165         130 :                         appendStringInfoString(buf, "NOT ");
    8166         130 :                         get_rule_expr_paren(first_arg, context,
    8167             :                                             false, node);
    8168         130 :                         if (!PRETTY_PAREN(context))
    8169         126 :                             appendStringInfoChar(buf, ')');
    8170         130 :                         break;
    8171             : 
    8172           0 :                     default:
    8173           0 :                         elog(ERROR, "unrecognized boolop: %d",
    8174             :                              (int) expr->boolop);
    8175             :                 }
    8176             :             }
    8177        5260 :             break;
    8178             : 
    8179         192 :         case T_SubLink:
    8180         192 :             get_sublink_expr((SubLink *) node, context);
    8181         192 :             break;
    8182             : 
    8183         140 :         case T_SubPlan:
    8184             :             {
    8185         140 :                 SubPlan    *subplan = (SubPlan *) node;
    8186             : 
    8187             :                 /*
    8188             :                  * We cannot see an already-planned subplan in rule deparsing,
    8189             :                  * only while EXPLAINing a query plan.  We don't try to
    8190             :                  * reconstruct the original SQL, just reference the subplan
    8191             :                  * that appears elsewhere in EXPLAIN's result.
    8192             :                  */
    8193         140 :                 if (subplan->useHashTable)
    8194          42 :                     appendStringInfo(buf, "(hashed %s)", subplan->plan_name);
    8195             :                 else
    8196          98 :                     appendStringInfo(buf, "(%s)", subplan->plan_name);
    8197             :             }
    8198         140 :             break;
    8199             : 
    8200          36 :         case T_AlternativeSubPlan:
    8201             :             {
    8202          36 :                 AlternativeSubPlan *asplan = (AlternativeSubPlan *) node;
    8203             :                 ListCell   *lc;
    8204             : 
    8205             :                 /* As above, this can only happen during EXPLAIN */
    8206          36 :                 appendStringInfoString(buf, "(alternatives: ");
    8207         108 :                 foreach(lc, asplan->subplans)
    8208             :                 {
    8209          72 :                     SubPlan    *splan = lfirst_node(SubPlan, lc);
    8210             : 
    8211          72 :                     if (splan->useHashTable)
    8212          36 :                         appendStringInfo(buf, "hashed %s", splan->plan_name);
    8213             :                     else
    8214          36 :                         appendStringInfoString(buf, splan->plan_name);
    8215          72 :                     if (lnext(asplan->subplans, lc))
    8216          36 :                         appendStringInfoString(buf, " or ");
    8217             :                 }
    8218          36 :                 appendStringInfoChar(buf, ')');
    8219             :             }
    8220          36 :             break;
    8221             : 
    8222         104 :         case T_FieldSelect:
    8223             :             {
    8224         104 :                 FieldSelect *fselect = (FieldSelect *) node;
    8225         104 :                 Node       *arg = (Node *) fselect->arg;
    8226         104 :                 int         fno = fselect->fieldnum;
    8227             :                 const char *fieldname;
    8228             :                 bool        need_parens;
    8229             : 
    8230             :                 /*
    8231             :                  * Parenthesize the argument unless it's an SubscriptingRef or
    8232             :                  * another FieldSelect.  Note in particular that it would be
    8233             :                  * WRONG to not parenthesize a Var argument; simplicity is not
    8234             :                  * the issue here, having the right number of names is.
    8235             :                  */
    8236         184 :                 need_parens = !IsA(arg, SubscriptingRef) &&
    8237          80 :                     !IsA(arg, FieldSelect);
    8238         104 :                 if (need_parens)
    8239          80 :                     appendStringInfoChar(buf, '(');
    8240         104 :                 get_rule_expr(arg, context, true);
    8241         104 :                 if (need_parens)
    8242          80 :                     appendStringInfoChar(buf, ')');
    8243             : 
    8244             :                 /*
    8245             :                  * Get and print the field name.
    8246             :                  */
    8247         104 :                 fieldname = get_name_for_var_field((Var *) arg, fno,
    8248             :                                                    0, context);
    8249         104 :                 appendStringInfo(buf, ".%s", quote_identifier(fieldname));
    8250             :             }
    8251         104 :             break;
    8252             : 
    8253           4 :         case T_FieldStore:
    8254           0 :             {
    8255           4 :                 FieldStore *fstore = (FieldStore *) node;
    8256             :                 bool        need_parens;
    8257             : 
    8258             :                 /*
    8259             :                  * There is no good way to represent a FieldStore as real SQL,
    8260             :                  * so decompilation of INSERT or UPDATE statements should
    8261             :                  * always use processIndirection as part of the
    8262             :                  * statement-level syntax.  We should only get here when
    8263             :                  * EXPLAIN tries to print the targetlist of a plan resulting
    8264             :                  * from such a statement.  The plan case is even harder than
    8265             :                  * ordinary rules would be, because the planner tries to
    8266             :                  * collapse multiple assignments to the same field or subfield
    8267             :                  * into one FieldStore; so we can see a list of target fields
    8268             :                  * not just one, and the arguments could be FieldStores
    8269             :                  * themselves.  We don't bother to try to print the target
    8270             :                  * field names; we just print the source arguments, with a
    8271             :                  * ROW() around them if there's more than one.  This isn't
    8272             :                  * terribly complete, but it's probably good enough for
    8273             :                  * EXPLAIN's purposes; especially since anything more would be
    8274             :                  * either hopelessly confusing or an even poorer
    8275             :                  * representation of what the plan is actually doing.
    8276             :                  */
    8277           4 :                 need_parens = (list_length(fstore->newvals) != 1);
    8278           4 :                 if (need_parens)
    8279           4 :                     appendStringInfoString(buf, "ROW(");
    8280           4 :                 get_rule_expr((Node *) fstore->newvals, context, showimplicit);
    8281           4 :                 if (need_parens)
    8282           4 :                     appendStringInfoChar(buf, ')');
    8283             :             }
    8284           4 :             break;
    8285             : 
    8286        1194 :         case T_RelabelType:
    8287             :             {
    8288        1194 :                 RelabelType *relabel = (RelabelType *) node;
    8289        1194 :                 Node       *arg = (Node *) relabel->arg;
    8290             : 
    8291        1194 :                 if (relabel->relabelformat == COERCE_IMPLICIT_CAST &&
    8292        1134 :                     !showimplicit)
    8293             :                 {
    8294             :                     /* don't show the implicit cast */
    8295          26 :                     get_rule_expr_paren(arg, context, false, node);
    8296             :                 }
    8297             :                 else
    8298             :                 {
    8299        1168 :                     get_coercion_expr(arg, context,
    8300             :                                       relabel->resulttype,
    8301             :                                       relabel->resulttypmod,
    8302             :                                       node);
    8303             :                 }
    8304             :             }
    8305        1194 :             break;
    8306             : 
    8307         116 :         case T_CoerceViaIO:
    8308             :             {
    8309         116 :                 CoerceViaIO *iocoerce = (CoerceViaIO *) node;
    8310         116 :                 Node       *arg = (Node *) iocoerce->arg;
    8311             : 
    8312         116 :                 if (iocoerce->coerceformat == COERCE_IMPLICIT_CAST &&
    8313           8 :                     !showimplicit)
    8314             :                 {
    8315             :                     /* don't show the implicit cast */
    8316           8 :                     get_rule_expr_paren(arg, context, false, node);
    8317             :                 }
    8318             :                 else
    8319             :                 {
    8320         108 :                     get_coercion_expr(arg, context,
    8321             :                                       iocoerce->resulttype,
    8322             :                                       -1,
    8323             :                                       node);
    8324             :                 }
    8325             :             }
    8326         116 :             break;
    8327             : 
    8328          16 :         case T_ArrayCoerceExpr:
    8329             :             {
    8330          16 :                 ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
    8331          16 :                 Node       *arg = (Node *) acoerce->arg;
    8332             : 
    8333          16 :                 if (acoerce->coerceformat == COERCE_IMPLICIT_CAST &&
    8334          16 :                     !showimplicit)
    8335             :                 {
    8336             :                     /* don't show the implicit cast */
    8337           0 :                     get_rule_expr_paren(arg, context, false, node);
    8338             :                 }
    8339             :                 else
    8340             :                 {
    8341          16 :                     get_coercion_expr(arg, context,
    8342             :                                       acoerce->resulttype,
    8343             :                                       acoerce->resulttypmod,
    8344             :                                       node);
    8345             :                 }
    8346             :             }
    8347          16 :             break;
    8348             : 
    8349          66 :         case T_ConvertRowtypeExpr:
    8350             :             {
    8351          66 :                 ConvertRowtypeExpr *convert = (ConvertRowtypeExpr *) node;
    8352          66 :                 Node       *arg = (Node *) convert->arg;
    8353             : 
    8354          66 :                 if (convert->convertformat == COERCE_IMPLICIT_CAST &&
    8355          62 :                     !showimplicit)
    8356             :                 {
    8357             :                     /* don't show the implicit cast */
    8358          18 :                     get_rule_expr_paren(arg, context, false, node);
    8359             :                 }
    8360             :                 else
    8361             :                 {
    8362          48 :                     get_coercion_expr(arg, context,
    8363             :                                       convert->resulttype, -1,
    8364             :                                       node);
    8365             :                 }
    8366             :             }
    8367          66 :             break;
    8368             : 
    8369          40 :         case T_CollateExpr:
    8370           0 :             {
    8371          40 :                 CollateExpr *collate = (CollateExpr *) node;
    8372          40 :                 Node       *arg = (Node *) collate->arg;
    8373             : 
    8374          40 :                 if (!PRETTY_PAREN(context))
    8375          40 :                     appendStringInfoChar(buf, '(');
    8376          40 :                 get_rule_expr_paren(arg, context, showimplicit, node);
    8377          40 :                 appendStringInfo(buf, " COLLATE %s",
    8378             :                                  generate_collation_name(collate->collOid));
    8379          40 :                 if (!PRETTY_PAREN(context))
    8380          40 :                     appendStringInfoChar(buf, ')');
    8381             :             }
    8382          40 :             break;
    8383             : 
    8384         132 :         case T_CaseExpr:
    8385             :             {
    8386         132 :                 CaseExpr   *caseexpr = (CaseExpr *) node;
    8387             :                 ListCell   *temp;
    8388             : 
    8389         132 :                 appendContextKeyword(context, "CASE",
    8390             :                                      0, PRETTYINDENT_VAR, 0);
    8391         132 :                 if (caseexpr->arg)
    8392             :                 {
    8393          48 :                     appendStringInfoChar(buf, ' ');
    8394          48 :                     get_rule_expr((Node *) caseexpr->arg, context, true);
    8395             :                 }
    8396         564 :                 foreach(temp, caseexpr->args)
    8397             :                 {
    8398         432 :                     CaseWhen   *when = (CaseWhen *) lfirst(temp);
    8399         432 :                     Node       *w = (Node *) when->expr;
    8400             : 
    8401         432 :                     if (caseexpr->arg)
    8402             :                     {
    8403             :                         /*
    8404             :                          * The parser should have produced WHEN clauses of the
    8405             :                          * form "CaseTestExpr = RHS", possibly with an
    8406             :                          * implicit coercion inserted above the CaseTestExpr.
    8407             :                          * For accurate decompilation of rules it's essential
    8408             :                          * that we show just the RHS.  However in an
    8409             :                          * expression that's been through the optimizer, the
    8410             :                          * WHEN clause could be almost anything (since the
    8411             :                          * equality operator could have been expanded into an
    8412             :                          * inline function).  If we don't recognize the form
    8413             :                          * of the WHEN clause, just punt and display it as-is.
    8414             :                          */
    8415         220 :                         if (IsA(w, OpExpr))
    8416             :                         {
    8417         220 :                             List       *args = ((OpExpr *) w)->args;
    8418             : 
    8419         220 :                             if (list_length(args) == 2 &&
    8420         220 :                                 IsA(strip_implicit_coercions(linitial(args)),
    8421             :                                     CaseTestExpr))
    8422         220 :                                 w = (Node *) lsecond(args);
    8423             :                         }
    8424             :                     }
    8425             : 
    8426         432 :                     if (!PRETTY_INDENT(context))
    8427          16 :                         appendStringInfoChar(buf, ' ');
    8428         432 :                     appendContextKeyword(context, "WHEN ",
    8429             :                                          0, 0, 0);
    8430         432 :                     get_rule_expr(w, context, false);
    8431         432 :                     appendStringInfoString(buf, " THEN ");
    8432         432 :                     get_rule_expr((Node *) when->result, context, true);
    8433             :                 }
    8434         132 :                 if (!PRETTY_INDENT(context))
    8435          16 :                     appendStringInfoChar(buf, ' ');
    8436         132 :                 appendContextKeyword(context, "ELSE ",
    8437             :                                      0, 0, 0);
    8438         132 :                 get_rule_expr((Node *) caseexpr->defresult, context, true);
    8439         132 :                 if (!PRETTY_INDENT(context))
    8440          16 :                     appendStringInfoChar(buf, ' ');
    8441         132 :                 appendContextKeyword(context, "END",
    8442             :                                      -PRETTYINDENT_VAR, 0, 0);
    8443             :             }
    8444         132 :             break;
    8445             : 
    8446           0 :         case T_CaseTestExpr:
    8447             :             {
    8448             :                 /*
    8449             :                  * Normally we should never get here, since for expressions
    8450             :                  * that can contain this node type we attempt to avoid
    8451             :                  * recursing to it.  But in an optimized expression we might
    8452             :                  * be unable to avoid that (see comments for CaseExpr).  If we
    8453             :                  * do see one, print it as CASE_TEST_EXPR.
    8454             :                  */
    8455           0 :                 appendStringInfoString(buf, "CASE_TEST_EXPR");
    8456             :             }
    8457           0 :             break;
    8458             : 
    8459         200 :         case T_ArrayExpr:
    8460         196 :             {
    8461         200 :                 ArrayExpr  *arrayexpr = (ArrayExpr *) node;
    8462             : 
    8463         200 :                 appendStringInfoString(buf, "ARRAY[");
    8464         200 :                 get_rule_expr((Node *) arrayexpr->elements, context, true);
    8465         200 :                 appendStringInfoChar(buf, ']');
    8466             : 
    8467             :                 /*
    8468             :                  * If the array isn't empty, we assume its elements are
    8469             :                  * coerced to the desired type.  If it's empty, though, we
    8470             :                  * need an explicit coercion to the array type.
    8471             :                  */
    8472         200 :                 if (arrayexpr->elements == NIL)
    8473           4 :                     appendStringInfo(buf, "::%s",
    8474             :                                      format_type_with_typemod(arrayexpr->array_typeid, -1));
    8475             :             }
    8476         200 :             break;
    8477             : 
    8478          82 :         case T_RowExpr:
    8479          62 :             {
    8480          82 :                 RowExpr    *rowexpr = (RowExpr *) node;
    8481          82 :                 TupleDesc   tupdesc = NULL;
    8482             :                 ListCell   *arg;
    8483             :                 int         i;
    8484             :                 char       *sep;
    8485             : 
    8486             :                 /*
    8487             :                  * If it's a named type and not RECORD, we may have to skip
    8488             :                  * dropped columns and/or claim there are NULLs for added
    8489             :                  * columns.
    8490             :                  */
    8491          82 :                 if (rowexpr->row_typeid != RECORDOID)
    8492             :                 {
    8493          28 :                     tupdesc = lookup_rowtype_tupdesc(rowexpr->row_typeid, -1);
    8494             :                     Assert(list_length(rowexpr->args) <= tupdesc->natts);
    8495             :                 }
    8496             : 
    8497             :                 /*
    8498             :                  * SQL99 allows "ROW" to be omitted when there is more than
    8499             :                  * one column, but for simplicity we always print it.
    8500             :                  */
    8501          82 :                 appendStringInfoString(buf, "ROW(");
    8502          82 :                 sep = "";
    8503          82 :                 i = 0;
    8504         220 :                 foreach(arg, rowexpr->args)
    8505             :                 {
    8506         138 :                     Node       *e = (Node *) lfirst(arg);
    8507             : 
    8508         138 :                     if (tupdesc == NULL ||
    8509          52 :                         !TupleDescAttr(tupdesc, i)->attisdropped)
    8510             :                     {
    8511         138 :                         appendStringInfoString(buf, sep);
    8512             :                         /* Whole-row Vars need special treatment here */
    8513         138 :                         get_rule_expr_toplevel(e, context, true);
    8514         138 :                         sep = ", ";
    8515             :                     }
    8516         138 :                     i++;
    8517             :                 }
    8518          82 :                 if (tupdesc != NULL)
    8519             :                 {
    8520          32 :                     while (i < tupdesc->natts)
    8521             :                     {
    8522           4 :                         if (!TupleDescAttr(tupdesc, i)->attisdropped)
    8523             :                         {
    8524           4 :                             appendStringInfoString(buf, sep);
    8525           4 :                             appendStringInfoString(buf, "NULL");
    8526           4 :                             sep = ", ";
    8527             :                         }
    8528           4 :                         i++;
    8529             :                     }
    8530             : 
    8531          28 :                     ReleaseTupleDesc(tupdesc);
    8532             :                 }
    8533          82 :                 appendStringInfoChar(buf, ')');
    8534          82 :                 if (rowexpr->row_format == COERCE_EXPLICIT_CAST)
    8535          20 :                     appendStringInfo(buf, "::%s",
    8536             :                                      format_type_with_typemod(rowexpr->row_typeid, -1));
    8537             :             }
    8538          82 :             break;
    8539             : 
    8540          40 :         case T_RowCompareExpr:
    8541             :             {
    8542          40 :                 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
    8543             :                 ListCell   *arg;
    8544             :                 char       *sep;
    8545             : 
    8546             :                 /*
    8547             :                  * SQL99 allows "ROW" to be omitted when there is more than
    8548             :                  * one column, but for simplicity we always print it.
    8549             :                  */
    8550          40 :                 appendStringInfoString(buf, "(ROW(");
    8551          40 :                 sep = "";
    8552         132 :                 foreach(arg, rcexpr->largs)
    8553             :                 {
    8554          92 :                     Node       *e = (Node *) lfirst(arg);
    8555             : 
    8556          92 :                     appendStringInfoString(buf, sep);
    8557          92 :                     get_rule_expr(e, context, true);
    8558          92 :                     sep = ", ";
    8559             :                 }
    8560             : 
    8561             :                 /*
    8562             :                  * We assume that the name of the first-column operator will
    8563             :                  * do for all the rest too.  This is definitely open to
    8564             :                  * failure, eg if some but not all operators were renamed
    8565             :                  * since the construct was parsed, but there seems no way to
    8566             :                  * be perfect.
    8567             :                  */
    8568          40 :                 appendStringInfo(buf, ") %s ROW(",
    8569          40 :                                  generate_operator_name(linitial_oid(rcexpr->opnos),
    8570          40 :                                                         exprType(linitial(rcexpr->largs)),
    8571          40 :                                                         exprType(linitial(rcexpr->rargs))));
    8572          40 :                 sep = "";
    8573         132 :                 foreach(arg, rcexpr->rargs)
    8574             :                 {
    8575          92 :                     Node       *e = (Node *) lfirst(arg);
    8576             : 
    8577          92 :                     appendStringInfoString(buf, sep);
    8578          92 :                     get_rule_expr(e, context, true);
    8579          92 :                     sep = ", ";
    8580             :                 }
    8581          40 :                 appendStringInfoString(buf, "))");
    8582             :             }
    8583          40 :             break;
    8584             : 
    8585         632 :         case T_CoalesceExpr:
    8586             :             {
    8587         632 :                 CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
    8588             : 
    8589         632 :                 appendStringInfoString(buf, "COALESCE(");
    8590         632 :                 get_rule_expr((Node *) coalesceexpr->args, context, true);
    8591         632 :                 appendStringInfoChar(buf, ')');
    8592             :             }
    8593         632 :             break;
    8594             : 
    8595          24 :         case T_MinMaxExpr:
    8596             :             {
    8597          24 :                 MinMaxExpr *minmaxexpr = (MinMaxExpr *) node;
    8598             : 
    8599          24 :                 switch (minmaxexpr->op)
    8600             :                 {
    8601           4 :                     case IS_GREATEST:
    8602           4 :                         appendStringInfoString(buf, "GREATEST(");
    8603           4 :                         break;
    8604          20 :                     case IS_LEAST:
    8605          20 :                         appendStringInfoString(buf, "LEAST(");
    8606          20 :                         break;
    8607             :                 }
    8608          24 :                 get_rule_expr((Node *) minmaxexpr->args, context, true);
    8609          24 :                 appendStringInfoChar(buf, ')');
    8610             :             }
    8611          24 :             break;
    8612             : 
    8613         556 :         case T_SQLValueFunction:
    8614             :             {
    8615         556 :                 SQLValueFunction *svf = (SQLValueFunction *) node;
    8616             : 
    8617             :                 /*
    8618             :                  * Note: this code knows that typmod for time, timestamp, and
    8619             :                  * timestamptz just prints as integer.
    8620             :                  */
    8621         556 :                 switch (svf->op)
    8622             :                 {
    8623           4 :                     case SVFOP_CURRENT_DATE:
    8624           4 :                         appendStringInfoString(buf, "CURRENT_DATE");
    8625           4 :                         break;
    8626           0 :                     case SVFOP_CURRENT_TIME:
    8627           0 :                         appendStringInfoString(buf, "CURRENT_TIME");
    8628           0 :                         break;
    8629           0 :                     case SVFOP_CURRENT_TIME_N:
    8630           0 :                         appendStringInfo(buf, "CURRENT_TIME(%d)", svf->typmod);
    8631           0 :                         break;
    8632           0 :                     case SVFOP_CURRENT_TIMESTAMP:
    8633           0 :                         appendStringInfoString(buf, "CURRENT_TIMESTAMP");
    8634           0 :                         break;
    8635         358 :                     case SVFOP_CURRENT_TIMESTAMP_N:
    8636         358 :                         appendStringInfo(buf, "CURRENT_TIMESTAMP(%d)",
    8637             :                                          svf->typmod);
    8638         358 :                         break;
    8639           0 :                     case SVFOP_LOCALTIME:
    8640           0 :                         appendStringInfoString(buf, "LOCALTIME");
    8641           0 :                         break;
    8642           0 :                     case SVFOP_LOCALTIME_N:
    8643           0 :                         appendStringInfo(buf, "LOCALTIME(%d)", svf->typmod);
    8644           0 :                         break;
    8645          12 :                     case SVFOP_LOCALTIMESTAMP:
    8646          12 :                         appendStringInfoString(buf, "LOCALTIMESTAMP");
    8647          12 :                         break;
    8648           4 :                     case SVFOP_LOCALTIMESTAMP_N:
    8649           4 :                         appendStringInfo(buf, "LOCALTIMESTAMP(%d)",
    8650             :                                          svf->typmod);
    8651           4 :                         break;
    8652           0 :                     case SVFOP_CURRENT_ROLE:
    8653           0 :                         appendStringInfoString(buf, "CURRENT_ROLE");
    8654           0 :                         break;
    8655         174 :                     case SVFOP_CURRENT_USER:
    8656         174 :                         appendStringInfoString(buf, "CURRENT_USER");
    8657         174 :                         break;
    8658           0 :                     case SVFOP_USER:
    8659           0 :                         appendStringInfoString(buf, "USER");
    8660           0 :                         break;
    8661           4 :                     case SVFOP_SESSION_USER:
    8662           4 :                         appendStringInfoString(buf, "SESSION_USER");
    8663           4 :                         break;
    8664           0 :                     case SVFOP_CURRENT_CATALOG:
    8665           0 :                         appendStringInfoString(buf, "CURRENT_CATALOG");
    8666           0 :                         break;
    8667           0 :                     case SVFOP_CURRENT_SCHEMA:
    8668           0 :                         appendStringInfoString(buf, "CURRENT_SCHEMA");
    8669           0 :                         break;
    8670             :                 }
    8671         556 :             }
    8672         556 :             break;
    8673             : 
    8674          90 :         case T_XmlExpr:
    8675             :             {
    8676          90 :                 XmlExpr    *xexpr = (XmlExpr *) node;
    8677          90 :                 bool        needcomma = false;
    8678             :                 ListCell   *arg;
    8679             :                 ListCell   *narg;
    8680             :                 Const      *con;
    8681             : 
    8682          90 :                 switch (xexpr->op)
    8683             :                 {
    8684          10 :                     case IS_XMLCONCAT:
    8685          10 :                         appendStringInfoString(buf, "XMLCONCAT(");
    8686          10 :                         break;
    8687          20 :                     case IS_XMLELEMENT:
    8688          20 :                         appendStringInfoString(buf, "XMLELEMENT(");
    8689          20 :                         break;
    8690          10 :                     case IS_XMLFOREST:
    8691          10 :                         appendStringInfoString(buf, "XMLFOREST(");
    8692          10 :                         break;
    8693          10 :                     case IS_XMLPARSE:
    8694          10 :                         appendStringInfoString(buf, "XMLPARSE(");
    8695          10 :                         break;
    8696          10 :                     case IS_XMLPI:
    8697          10 :                         appendStringInfoString(buf, "XMLPI(");
    8698          10 :                         break;
    8699          10 :                     case IS_XMLROOT:
    8700          10 :                         appendStringInfoString(buf, "XMLROOT(");
    8701          10 :                         break;
    8702          20 :                     case IS_XMLSERIALIZE:
    8703          20 :                         appendStringInfoString(buf, "XMLSERIALIZE(");
    8704          20 :                         break;
    8705           0 :                     case IS_DOCUMENT:
    8706           0 :                         break;
    8707             :                 }
    8708          90 :                 if (xexpr->op == IS_XMLPARSE || xexpr->op == IS_XMLSERIALIZE)
    8709             :                 {
    8710          30 :                     if (xexpr->xmloption == XMLOPTION_DOCUMENT)
    8711           0 :                         appendStringInfoString(buf, "DOCUMENT ");
    8712             :                     else
    8713          30 :                         appendStringInfoString(buf, "CONTENT ");
    8714             :                 }
    8715          90 :                 if (xexpr->name)
    8716             :                 {
    8717          30 :                     appendStringInfo(buf, "NAME %s",
    8718          30 :                                      quote_identifier(map_xml_name_to_sql_identifier(xexpr->name)));
    8719          30 :                     needcomma = true;
    8720             :                 }
    8721          90 :                 if (xexpr->named_args)
    8722             :                 {
    8723          20 :                     if (xexpr->op != IS_XMLFOREST)
    8724             :                     {
    8725          10 :                         if (needcomma)
    8726          10 :                             appendStringInfoString(buf, ", ");
    8727          10 :                         appendStringInfoString(buf, "XMLATTRIBUTES(");
    8728          10 :                         needcomma = false;
    8729             :                     }
    8730          70 :                     forboth(arg, xexpr->named_args, narg, xexpr->arg_names)
    8731             :                     {
    8732          50 :                         Node       *e = (Node *) lfirst(arg);
    8733          50 :                         char       *argname = strVal(lfirst(narg));
    8734             : 
    8735          50 :                         if (needcomma)
    8736          30 :                             appendStringInfoString(buf, ", ");
    8737          50 :                         get_rule_expr((Node *) e, context, true);
    8738          50 :                         appendStringInfo(buf, " AS %s",
    8739          50 :                                          quote_identifier(map_xml_name_to_sql_identifier(argname)));
    8740          50 :                         needcomma = true;
    8741             :                     }
    8742          20 :                     if (xexpr->op != IS_XMLFOREST)
    8743          10 :                         appendStringInfoChar(buf, ')');
    8744             :                 }
    8745          90 :                 if (xexpr->args)
    8746             :                 {
    8747          80 :                     if (needcomma)
    8748          30 :                         appendStringInfoString(buf, ", ");
    8749          80 :                     switch (xexpr->op)
    8750             :                     {
    8751          60 :                         case IS_XMLCONCAT:
    8752             :                         case IS_XMLELEMENT:
    8753             :                         case IS_XMLFOREST:
    8754             :                         case IS_XMLPI:
    8755             :                         case IS_XMLSERIALIZE:
    8756             :                             /* no extra decoration needed */
    8757          60 :                             get_rule_expr((Node *) xexpr->args, context, true);
    8758          60 :                             break;
    8759          10 :                         case IS_XMLPARSE:
    8760             :                             Assert(list_length(xexpr->args) == 2);
    8761             : 
    8762          10 :                             get_rule_expr((Node *) linitial(xexpr->args),
    8763             :                                           context, true);
    8764             : 
    8765          10 :                             con = lsecond_node(Const, xexpr->args);
    8766             :                             Assert(!con->constisnull);
    8767          10 :                             if (DatumGetBool(con->constvalue))
    8768           0 :                                 appendStringInfoString(buf,
    8769             :                                                        " PRESERVE WHITESPACE");
    8770             :                             else
    8771          10 :                                 appendStringInfoString(buf,
    8772             :                                                        " STRIP WHITESPACE");
    8773          10 :                             break;
    8774          10 :                         case IS_XMLROOT:
    8775             :                             Assert(list_length(xexpr->args) == 3);
    8776             : 
    8777          10 :                             get_rule_expr((Node *) linitial(xexpr->args),
    8778             :                                           context, true);
    8779             : 
    8780          10 :                             appendStringInfoString(buf, ", VERSION ");
    8781          10 :                             con = (Const *) lsecond(xexpr->args);
    8782          10 :                             if (IsA(con, Const) &&
    8783          10 :                                 con->constisnull)
    8784          10 :                                 appendStringInfoString(buf, "NO VALUE");
    8785             :                             else
    8786           0 :                                 get_rule_expr((Node *) con, context, false);
    8787             : 
    8788          10 :                             con = lthird_node(Const, xexpr->args);
    8789          10 :                             if (con->constisnull)
    8790             :                                  /* suppress STANDALONE NO VALUE */ ;
    8791             :                             else
    8792             :                             {
    8793          10 :                                 switch (DatumGetInt32(con->constvalue))
    8794             :                                 {
    8795          10 :                                     case XML_STANDALONE_YES:
    8796          10 :                                         appendStringInfoString(buf,
    8797             :                                                                ", STANDALONE YES");
    8798          10 :                                         break;
    8799           0 :                                     case XML_STANDALONE_NO:
    8800           0 :                                         appendStringInfoString(buf,
    8801             :                                                                ", STANDALONE NO");
    8802           0 :                                         break;
    8803           0 :                                     case XML_STANDALONE_NO_VALUE:
    8804           0 :                                         appendStringInfoString(buf,
    8805             :                                                                ", STANDALONE NO VALUE");
    8806           0 :                                         break;
    8807           0 :                                     default:
    8808           0 :                                         break;
    8809             :                                 }
    8810             :                             }
    8811          10 :                             break;
    8812           0 :                         case IS_DOCUMENT:
    8813           0 :                             get_rule_expr_paren((Node *) xexpr->args, context, false, node);
    8814           0 :                             break;
    8815             :                     }
    8816             : 
    8817          10 :                 }
    8818          90 :                 if (xexpr->op == IS_XMLSERIALIZE)
    8819          20 :                     appendStringInfo(buf, " AS %s",
    8820             :                                      format_type_with_typemod(xexpr->type,
    8821             :                                                               xexpr->typmod));
    8822          90 :                 if (xexpr->op == IS_DOCUMENT)
    8823           0 :                     appendStringInfoString(buf, " IS DOCUMENT");
    8824             :                 else
    8825          90 :                     appendStringInfoChar(buf, ')');
    8826             :             }
    8827          90 :             break;
    8828             : 
    8829        1002 :         case T_NullTest:
    8830          16 :             {
    8831        1002 :                 NullTest   *ntest = (NullTest *) node;
    8832             : 
    8833        1002 :                 if (!PRETTY_PAREN(context))
    8834         986 :                     appendStringInfoChar(buf, '(');
    8835        1002 :                 get_rule_expr_paren((Node *) ntest->arg, context, true, node);
    8836             : 
    8837             :                 /*
    8838             :                  * For scalar inputs, we prefer to print as IS [NOT] NULL,
    8839             :                  * which is shorter and traditional.  If it's a rowtype input
    8840             :                  * but we're applying a scalar test, must print IS [NOT]
    8841             :                  * DISTINCT FROM NULL to be semantically correct.
    8842             :                  */
    8843        1002 :                 if (ntest->argisrow ||
    8844         990 :                     !type_is_rowtype(exprType((Node *) ntest->arg)))
    8845             :                 {
    8846        1980 :                     switch (ntest->nulltesttype)
    8847             :                     {
    8848         284 :                         case IS_NULL:
    8849         284 :                             appendStringInfoString(buf, " IS NULL");
    8850         284 :                             break;
    8851         706 :                         case IS_NOT_NULL:
    8852         706 :                             appendStringInfoString(buf, " IS NOT NULL");
    8853         706 :                             break;
    8854           0 :                         default:
    8855           0 :                             elog(ERROR, "unrecognized nulltesttype: %d",
    8856             :                                  (int) ntest->nulltesttype);
    8857             :                     }
    8858             :                 }
    8859             :                 else
    8860             :                 {
    8861          12 :                     switch (ntest->nulltesttype)
    8862             :                     {
    8863           4 :                         case IS_NULL:
    8864           4 :                             appendStringInfoString(buf, " IS NOT DISTINCT FROM NULL");
    8865           4 :                             break;
    8866           8 :                         case IS_NOT_NULL:
    8867           8 :                             appendStringInfoString(buf, " IS DISTINCT FROM NULL");
    8868           8 :                             break;
    8869           0 :                         default:
    8870           0 :                             elog(ERROR, "unrecognized nulltesttype: %d",
    8871             :                                  (int) ntest->nulltesttype);
    8872             :                     }
    8873             :                 }
    8874        1002 :                 if (!PRETTY_PAREN(context))
    8875         986 :                     appendStringInfoChar(buf, ')');
    8876             :             }
    8877        1002 :             break;
    8878             : 
    8879          48 :         case T_BooleanTest:
    8880           0 :             {
    8881          48 :                 BooleanTest *btest = (BooleanTest *) node;
    8882             : 
    8883          48 :                 if (!PRETTY_PAREN(context))
    8884          48 :                     appendStringInfoChar(buf, '(');
    8885          48 :                 get_rule_expr_paren((Node *) btest->arg, context, false, node);
    8886          48 :                 switch (btest->booltesttype)
    8887             :                 {
    8888           8 :                     case IS_TRUE:
    8889           8 :                         appendStringInfoString(buf, " IS TRUE");
    8890           8 :                         break;
    8891          16 :                     case IS_NOT_TRUE:
    8892          16 :                         appendStringInfoString(buf, " IS NOT TRUE");
    8893          16 :                         break;
    8894           0 :                     case IS_FALSE:
    8895           0 :                         appendStringInfoString(buf, " IS FALSE");
    8896           0 :                         break;
    8897           0 :                     case IS_NOT_FALSE:
    8898           0 :                         appendStringInfoString(buf, " IS NOT FALSE");
    8899           0 :                         break;
    8900          12 :                     case IS_UNKNOWN:
    8901          12 :                         appendStringInfoString(buf, " IS UNKNOWN");
    8902          12 :                         break;
    8903          12 :                     case IS_NOT_UNKNOWN:
    8904          12 :                         appendStringInfoString(buf, " IS NOT UNKNOWN");
    8905          12 :                         break;
    8906           0 :                     default:
    8907           0 :                         elog(ERROR, "unrecognized booltesttype: %d",
    8908             :                              (int) btest->booltesttype);
    8909             :                 }
    8910          48 :                 if (!PRETTY_PAREN(context))
    8911          48 :                     appendStringInfoChar(buf, ')');
    8912             :             }
    8913          48 :             break;
    8914             : 
    8915          20 :         case T_CoerceToDomain:
    8916             :             {
    8917          20 :                 CoerceToDomain *ctest = (CoerceToDomain *) node;
    8918          20 :                 Node       *arg = (Node *) ctest->arg;
    8919             : 
    8920          20 :                 if (ctest->coercionformat == COERCE_IMPLICIT_CAST &&
    8921          14 :                     !showimplicit)
    8922             :                 {
    8923             :                     /* don't show the implicit cast */
    8924          14 :                     get_rule_expr(arg, context, false);
    8925             :                 }
    8926             :                 else
    8927             :                 {
    8928           6 :                     get_coercion_expr(arg, context,
    8929             :                                       ctest->resulttype,
    8930             :                                       ctest->resulttypmod,
    8931             :                                       node);
    8932             :                 }
    8933             :             }
    8934          20 :             break;
    8935             : 
    8936         170 :         case T_CoerceToDomainValue:
    8937         170 :             appendStringInfoString(buf, "VALUE");
    8938         170 :             break;
    8939             : 
    8940           0 :         case T_SetToDefault:
    8941           0 :             appendStringInfoString(buf, "DEFAULT");
    8942           0 :             break;
    8943             : 
    8944          12 :         case T_CurrentOfExpr:
    8945             :             {
    8946          12 :                 CurrentOfExpr *cexpr = (CurrentOfExpr *) node;
    8947             : 
    8948          12 :                 if (cexpr->cursor_name)
    8949          12 :                     appendStringInfo(buf, "CURRENT OF %s",
    8950          12 :                                      quote_identifier(cexpr->cursor_name));
    8951             :                 else
    8952           0 :                     appendStringInfo(buf, "CURRENT OF $%d",
    8953             :                                      cexpr->cursor_param);
    8954             :             }
    8955          12 :             break;
    8956             : 
    8957           0 :         case T_NextValueExpr:
    8958             :             {
    8959           0 :                 NextValueExpr *nvexpr = (NextValueExpr *) node;
    8960             : 
    8961             :                 /*
    8962             :                  * This isn't exactly nextval(), but that seems close enough
    8963             :                  * for EXPLAIN's purposes.
    8964             :                  */
    8965           0 :                 appendStringInfoString(buf, "nextval(");
    8966           0 :                 simple_quote_literal(buf,
    8967           0 :                                      generate_relation_name(nvexpr->seqid,
    8968             :                                                             NIL));
    8969           0 :                 appendStringInfoChar(buf, ')');
    8970             :             }
    8971           0 :             break;
    8972             : 
    8973          16 :         case T_InferenceElem:
    8974           8 :             {
    8975          16 :                 InferenceElem *iexpr = (InferenceElem *) node;
    8976             :                 bool        save_varprefix;
    8977             :                 bool        need_parens;
    8978             : 
    8979             :                 /*
    8980             :                  * InferenceElem can only refer to target relation, so a
    8981             :                  * prefix is not useful, and indeed would cause parse errors.
    8982             :                  */
    8983          16 :                 save_varprefix = context->varprefix;
    8984          16 :                 context->varprefix = false;
    8985             : 
    8986             :                 /*
    8987             :                  * Parenthesize the element unless it's a simple Var or a bare
    8988             :                  * function call.  Follows pg_get_indexdef_worker().
    8989             :                  */
    8990          16 :                 need_parens = !IsA(iexpr->expr, Var);
    8991          16 :                 if (IsA(iexpr->expr, FuncExpr) &&
    8992           0 :                     ((FuncExpr *) iexpr->expr)->funcformat ==
    8993             :                     COERCE_EXPLICIT_CALL)
    8994           0 :                     need_parens = false;
    8995             : 
    8996          16 :                 if (need_parens)
    8997           0 :                     appendStringInfoChar(buf, '(');
    8998          16 :                 get_rule_expr((Node *) iexpr->expr,
    8999             :                               context, false);
    9000          16 :                 if (need_parens)
    9001           0 :                     appendStringInfoChar(buf, ')');
    9002             : 
    9003          16 :                 context->varprefix = save_varprefix;
    9004             : 
    9005          16 :                 if (iexpr->infercollid)
    9006           8 :                     appendStringInfo(buf, " COLLATE %s",
    9007             :                                      generate_collation_name(iexpr->infercollid));
    9008             : 
    9009             :                 /* Add the operator class name, if not default */
    9010          16 :                 if (iexpr->inferopclass)
    9011             :                 {
    9012           8 :                     Oid         inferopclass = iexpr->inferopclass;
    9013           8 :                     Oid         inferopcinputtype = get_opclass_input_type(iexpr->inferopclass);
    9014             : 
    9015           8 :                     get_opclass_name(inferopclass, inferopcinputtype, buf);
    9016             :                 }
    9017             :             }
    9018          16 :             break;
    9019             : 
    9020        1870 :         case T_PartitionBoundSpec:
    9021             :             {
    9022        1870 :                 PartitionBoundSpec *spec = (PartitionBoundSpec *) node;
    9023             :                 ListCell   *cell;
    9024             :                 char       *sep;
    9025             : 
    9026        1870 :                 if (spec->is_default)
    9027             :                 {
    9028          82 :                     appendStringInfoString(buf, "DEFAULT");
    9029          82 :                     break;
    9030             :                 }
    9031             : 
    9032        1788 :                 switch (spec->strategy)
    9033             :                 {
    9034          78 :                     case PARTITION_STRATEGY_HASH:
    9035             :                         Assert(spec->modulus > 0 && spec->remainder >= 0);
    9036             :                         Assert(spec->modulus > spec->remainder);
    9037             : 
    9038          78 :                         appendStringInfoString(buf, "FOR VALUES");
    9039          78 :                         appendStringInfo(buf, " WITH (modulus %d, remainder %d)",
    9040             :                                          spec->modulus, spec->remainder);
    9041          78 :                         break;
    9042             : 
    9043         648 :                     case PARTITION_STRATEGY_LIST:
    9044             :                         Assert(spec->listdatums != NIL);
    9045             : 
    9046         648 :                         appendStringInfoString(buf, "FOR VALUES IN (");
    9047         648 :                         sep = "";
    9048        1792 :                         foreach(cell, spec->listdatums)
    9049             :                         {
    9050        1144 :                             Const      *val = castNode(Const, lfirst(cell));
    9051             : 
    9052        1144 :                             appendStringInfoString(buf, sep);
    9053        1144 :                             get_const_expr(val, context, -1);
    9054        1144 :                             sep = ", ";
    9055             :                         }
    9056             : 
    9057         648 :                         appendStringInfoChar(buf, ')');
    9058         648 :                         break;
    9059             : 
    9060        1062 :                     case PARTITION_STRATEGY_RANGE:
    9061             :                         Assert(spec->lowerdatums != NIL &&
    9062             :                                spec->upperdatums != NIL &&
    9063             :                                list_length(spec->lowerdatums) ==
    9064             :                                list_length(spec->upperdatums));
    9065             : 
    9066        1062 :                         appendStringInfo(buf, "FOR VALUES FROM %s TO %s",
    9067             :                                          get_range_partbound_string(spec->lowerdatums),
    9068             :                                          get_range_partbound_string(spec->upperdatums));
    9069        1062 :                         break;
    9070             : 
    9071           0 :                     default:
    9072           0 :                         elog(ERROR, "unrecognized partition strategy: %d",
    9073             :                              (int) spec->strategy);
    9074             :                         break;
    9075             :                 }
    9076             :             }
    9077        1788 :             break;
    9078             : 
    9079        1290 :         case T_List:
    9080        1290 :             {
    9081             :                 char       *sep;
    9082             :                 ListCell   *l;
    9083             : 
    9084        1290 :                 sep = "";
    9085        3932 :                 foreach(l, (List *) node)
    9086             :                 {
    9087        2642 :                     appendStringInfoString(buf, sep);
    9088        2642 :                     get_rule_expr((Node *) lfirst(l), context, showimplicit);
    9089        2642 :                     sep = ", ";
    9090             :                 }
    9091             :             }
    9092        1290 :             break;
    9093             : 
    9094          16 :         case T_TableFunc:
    9095          16 :             get_tablefunc((TableFunc *) node, context, showimplicit);
    9096          16 :             break;
    9097             : 
    9098           0 :         default:
    9099           0 :             elog(ERROR, "unrecognized node type: %d", (int) nodeTag(node));
    9100             :             break;
    9101             :     }
    9102             : }
    9103             : 
    9104             : /*
    9105             :  * get_rule_expr_toplevel       - Parse back a toplevel expression
    9106             :  *
    9107             :  * Same as get_rule_expr(), except that if the expr is just a Var, we pass
    9108             :  * istoplevel = true not false to get_variable().  This causes whole-row Vars
    9109             :  * to get printed with decoration that will prevent expansion of "*".
    9110             :  * We need to use this in contexts such as ROW() and VALUES(), where the
    9111             :  * parser would expand "foo.*" appearing at top level.  (In principle we'd
    9112             :  * use this in get_target_list() too, but that has additional worries about
    9113             :  * whether to print AS, so it needs to invoke get_variable() directly anyway.)
    9114             :  */
    9115             : static void
    9116        1002 : get_rule_expr_toplevel(Node *node, deparse_context *context,
    9117             :                        bool showimplicit)
    9118             : {
    9119        1002 :     if (node && IsA(node, Var))
    9120         254 :         (void) get_variable((Var *) node, 0, true, context);
    9121             :     else
    9122         748 :         get_rule_expr(node, context, showimplicit);
    9123        1002 : }
    9124             : 
    9125             : /*
    9126             :  * get_rule_expr_funccall       - Parse back a function-call expression
    9127             :  *
    9128             :  * Same as get_rule_expr(), except that we guarantee that the output will
    9129             :  * look like a function call, or like one of the things the grammar treats as
    9130             :  * equivalent to a function call (see the func_expr_windowless production).
    9131             :  * This is needed in places where the grammar uses func_expr_windowless and
    9132             :  * you can't substitute a parenthesized a_expr.  If what we have isn't going
    9133             :  * to look like a function call, wrap it in a dummy CAST() expression, which
    9134             :  * will satisfy the grammar --- and, indeed, is likely what the user wrote to
    9135             :  * produce such a thing.
    9136             :  */
    9137             : static void
    9138         244 : get_rule_expr_funccall(Node *node, deparse_context *context,
    9139             :                        bool showimplicit)
    9140             : {
    9141         244 :     if (looks_like_function(node))
    9142         236 :         get_rule_expr(node, context, showimplicit);
    9143             :     else
    9144             :     {
    9145           8 :         StringInfo  buf = context->buf;
    9146             : 
    9147           8 :         appendStringInfoString(buf, "CAST(");
    9148             :         /* no point in showing any top-level implicit cast */
    9149           8 :         get_rule_expr(node, context, false);
    9150           8 :         appendStringInfo(buf, " AS %s)",
    9151             :                          format_type_with_typemod(exprType(node),
    9152             :                                                   exprTypmod(node)));
    9153             :     }
    9154         244 : }
    9155             : 
    9156             : /*
    9157             :  * Helper function to identify node types that satisfy func_expr_windowless.
    9158             :  * If in doubt, "false" is always a safe answer.
    9159             :  */
    9160             : static bool
    9161         746 : looks_like_function(Node *node)
    9162             : {
    9163         746 :     if (node == NULL)
    9164           0 :         return false;           /* probably shouldn't happen */
    9165         746 :     switch (nodeTag(node))
    9166             :     {
    9167         298 :         case T_FuncExpr:
    9168             :             /* OK, unless it's going to deparse as a cast */
    9169         298 :             return (((FuncExpr *) node)->funcformat == COERCE_EXPLICIT_CALL);
    9170          12 :         case T_NullIfExpr:
    9171             :         case T_CoalesceExpr:
    9172             :         case T_MinMaxExpr:
    9173             :         case T_SQLValueFunction:
    9174             :         case T_XmlExpr:
    9175             :             /* these are all accepted by func_expr_common_subexpr */
    9176          12 :             return true;
    9177         436 :         default:
    9178         436 :             break;
    9179             :     }
    9180         436 :     return false;
    9181             : }
    9182             : 
    9183             : 
    9184             : /*
    9185             :  * get_oper_expr            - Parse back an OpExpr node
    9186             :  */
    9187             : static void
    9188       27288 : get_oper_expr(OpExpr *expr, deparse_context *context)
    9189             : {
    9190       27288 :     StringInfo  buf = context->buf;
    9191       27288 :     Oid         opno = expr->opno;
    9192       27288 :     List       *args = expr->args;
    9193             : 
    9194       27288 :     if (!PRETTY_PAREN(context))
    9195       26364 :         appendStringInfoChar(buf, '(');
    9196       27288 :     if (list_length(args) == 2)
    9197             :     {
    9198             :         /* binary operator */
    9199       27268 :         Node       *arg1 = (Node *) linitial(args);
    9200       27268 :         Node       *arg2 = (Node *) lsecond(args);
    9201             : 
    9202       27268 :         get_rule_expr_paren(arg1, context, true, (Node *) expr);
    9203       27268 :         appendStringInfo(buf, " %s ",
    9204             :                          generate_operator_name(opno,
    9205             :                                                 exprType(arg1),
    9206             :                                                 exprType(arg2)));
    9207       27268 :         get_rule_expr_paren(arg2, context, true, (Node *) expr);
    9208             :     }
    9209             :     else
    9210             :     {
    9211             :         /* unary operator --- but which side? */
    9212          20 :         Node       *arg = (Node *) linitial(args);
    9213             :         HeapTuple   tp;
    9214             :         Form_pg_operator optup;
    9215             : 
    9216          20 :         tp = SearchSysCache1(OPEROID, ObjectIdGetDatum(opno));
    9217          20 :         if (!HeapTupleIsValid(tp))
    9218           0 :             elog(ERROR, "cache lookup failed for operator %u", opno);
    9219          20 :         optup = (Form_pg_operator) GETSTRUCT(tp);
    9220          20 :         switch (optup->oprkind)
    9221             :         {
    9222          20 :             case 'l':
    9223          20 :                 appendStringInfo(buf, "%s ",
    9224             :                                  generate_operator_name(opno,
    9225             :                                                         InvalidOid,
    9226             :                                                         exprType(arg)));
    9227          20 :                 get_rule_expr_paren(arg, context, true, (Node *) expr);
    9228          20 :                 break;
    9229           0 :             case 'r':
    9230           0 :                 get_rule_expr_paren(arg, context, true, (Node *) expr);
    9231           0 :                 appendStringInfo(buf, " %s",
    9232             :                                  generate_operator_name(opno,
    9233             :                                                         exprType(arg),
    9234             :                                                         InvalidOid));
    9235           0 :                 break;
    9236           0 :             default:
    9237           0 :                 elog(ERROR, "bogus oprkind: %d", optup->oprkind);
    9238             :         }
    9239          20 :         ReleaseSysCache(tp);
    9240             :     }
    9241       27288 :     if (!PRETTY_PAREN(context))
    9242       26364 :         appendStringInfoChar(buf, ')');
    9243       27288 : }
    9244             : 
    9245             : /*
    9246             :  * get_func_expr            - Parse back a FuncExpr node
    9247             :  */
    9248             : static void
    9249        4852 : get_func_expr(FuncExpr *expr, deparse_context *context,
    9250             :               bool showimplicit)
    9251             : {
    9252        4852 :     StringInfo  buf = context->buf;
    9253        4852 :     Oid         funcoid = expr->funcid;
    9254             :     Oid         argtypes[FUNC_MAX_ARGS];
    9255             :     int         nargs;
    9256             :     List       *argnames;
    9257             :     bool        use_variadic;
    9258             :     ListCell   *l;
    9259             : 
    9260             :     /*
    9261             :      * If the function call came from an implicit coercion, then just show the
    9262             :      * first argument --- unless caller wants to see implicit coercions.
    9263             :      */
    9264        4852 :     if (expr->funcformat == COERCE_IMPLICIT_CAST && !showimplicit)
    9265             :     {
    9266         592 :         get_rule_expr_paren((Node *) linitial(expr->args), context,
    9267             :                             false, (Node *) expr);
    9268        1314 :         return;
    9269             :     }
    9270             : 
    9271             :     /*
    9272             :      * If the function call came from a cast, then show the first argument
    9273             :      * plus an explicit cast operation.
    9274             :      */
    9275        4260 :     if (expr->funcformat == COERCE_EXPLICIT_CAST ||
    9276        3984 :         expr->funcformat == COERCE_IMPLICIT_CAST)
    9277             :     {
    9278         722 :         Node       *arg = linitial(expr->args);
    9279         722 :         Oid         rettype = expr->funcresulttype;
    9280             :         int32       coercedTypmod;
    9281             : 
    9282             :         /* Get the typmod if this is a length-coercion function */
    9283         722 :         (void) exprIsLengthCoercion((Node *) expr, &coercedTypmod);
    9284             : 
    9285         722 :         get_coercion_expr(arg, context,
    9286             :                           rettype, coercedTypmod,
    9287             :                           (Node *) expr);
    9288             : 
    9289         722 :         return;
    9290             :     }
    9291             : 
    9292             :     /*
    9293             :      * Normal function: display as proname(args).  First we need to extract
    9294             :      * the argument datatypes.
    9295             :      */
    9296        3538 :     if (list_length(expr->args) > FUNC_MAX_ARGS)
    9297           0 :         ereport(ERROR,
    9298             :                 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
    9299             :                  errmsg("too many arguments")));
    9300        3538 :     nargs = 0;
    9301        3538 :     argnames = NIL;
    9302        7264 :     foreach(l, expr->args)
    9303             :     {
    9304        3726 :         Node       *arg = (Node *) lfirst(l);
    9305             : 
    9306        3726 :         if (IsA(arg, NamedArgExpr))
    9307          12 :             argnames = lappend(argnames, ((NamedArgExpr *) arg)->name);
    9308        3726 :         argtypes[nargs] = exprType(arg);
    9309        3726 :         nargs++;
    9310             :     }
    9311             : 
    9312        3538 :     appendStringInfo(buf, "%s(",
    9313             :                      generate_function_name(funcoid, nargs,
    9314             :                                             argnames, argtypes,
    9315        3538 :                                             expr->funcvariadic,
    9316             :                                             &use_variadic,
    9317             :                                             context->special_exprkind));
    9318        3538 :     nargs = 0;
    9319        7264 :     foreach(l, expr->args)
    9320             :     {
    9321        3726 :         if (nargs++ > 0)
    9322         540 :             appendStringInfoString(buf, ", ");
    9323        3726 :         if (use_variadic && lnext(expr->args, l) == NULL)
    9324           0 :             appendStringInfoString(buf, "VARIADIC ");
    9325        3726 :         get_rule_expr((Node *) lfirst(l), context, true);
    9326             :     }
    9327        3538 :     appendStringInfoChar(buf, ')');
    9328             : }
    9329             : 
    9330             : /*
    9331             :  * get_agg_expr         - Parse back an Aggref node
    9332             :  */
    9333             : static void
    9334        1216 : get_agg_expr(Aggref *aggref, deparse_context *context,
    9335             :              Aggref *original_aggref)
    9336             : {
    9337        1216 :     StringInfo  buf = context->buf;
    9338             :     Oid         argtypes[FUNC_MAX_ARGS];
    9339             :     int         nargs;
    9340             :     bool        use_variadic;
    9341             : 
    9342             :     /*
    9343             :      * For a combining aggregate, we look up and deparse the corresponding
    9344             :      * partial aggregate instead.  This is necessary because our input
    9345             :      * argument list has been replaced; the new argument list always has just
    9346             :      * one element, which will point to a partial Aggref that supplies us with
    9347             :      * transition states to combine.
    9348             :      */
    9349        1216 :     if (DO_AGGSPLIT_COMBINE(aggref->aggsplit))
    9350             :     {
    9351             :         TargetEntry *tle;
    9352             : 
    9353             :         Assert(list_length(aggref->args) == 1);
    9354         158 :         tle = linitial_node(TargetEntry, aggref->args);
    9355         158 :         resolve_special_varno((Node *) tle->expr, context,
    9356             :                               get_agg_combine_expr, original_aggref);
    9357         158 :         return;
    9358             :     }
    9359             : 
    9360             :     /*
    9361             :      * Mark as PARTIAL, if appropriate.  We look to the original aggref so as
    9362             :      * to avoid printing this when recursing from the code just above.
    9363             :      */
    9364        1058 :     if (DO_AGGSPLIT_SKIPFINAL(original_aggref->aggsplit))
    9365          24 :         appendStringInfoString(buf, "PARTIAL ");
    9366             : 
    9367             :     /* Extract the argument types as seen by the parser */
    9368        1058 :     nargs = get_aggregate_argtypes(aggref, argtypes);
    9369             : 
    9370             :     /* Print the aggregate name, schema-qualified if needed */
    9371        2116 :     appendStringInfo(buf, "%s(%s",
    9372             :                      generate_function_name(aggref->aggfnoid, nargs,
    9373             :                                             NIL, argtypes,
    9374        1058 :                                             aggref->aggvariadic,
    9375             :                                             &use_variadic,
    9376             :                                             context->special_exprkind),
    9377        1058 :                      (aggref->aggdistinct != NIL) ? "DISTINCT " : "");
    9378             : 
    9379        1058 :     if (AGGKIND_IS_ORDERED_SET(aggref->aggkind))
    9380             :     {
    9381             :         /*
    9382             :          * Ordered-set aggregates do not use "*" syntax.  Also, we needn't
    9383             :          * worry about inserting VARIADIC.  So we can just dump the direct
    9384             :          * args as-is.
    9385             :          */
    9386             :         Assert(!aggref->aggvariadic);
    9387          22 :         get_rule_expr((Node *) aggref->aggdirectargs, context, true);
    9388             :         Assert(aggref->aggorder != NIL);
    9389          22 :         appendStringInfoString(buf, ") WITHIN GROUP (ORDER BY ");
    9390          22 :         get_rule_orderby(aggref->aggorder, aggref->args, false, context);
    9391             :     }
    9392             :     else
    9393             :     {
    9394             :         /* aggstar can be set only in zero-argument aggregates */
    9395        1036 :         if (aggref->aggstar)
    9396         150 :             appendStringInfoChar(buf, '*');
    9397             :         else
    9398             :         {
    9399             :             ListCell   *l;
    9400             :             int         i;
    9401             : 
    9402         886 :             i = 0;
    9403        1862 :             foreach(l, aggref->args)
    9404             :             {
    9405         976 :                 TargetEntry *tle = (TargetEntry *) lfirst(l);
    9406         976 :                 Node       *arg = (Node *) tle->expr;
    9407             : 
    9408             :                 Assert(!IsA(arg, NamedArgExpr));
    9409         976 :                 if (tle->resjunk)
    9410          22 :                     continue;
    9411         954 :                 if (i++ > 0)
    9412          68 :                     appendStringInfoString(buf, ", ");
    9413         954 :                 if (use_variadic && i == nargs)
    9414           8 :                     appendStringInfoString(buf, "VARIADIC ");
    9415         954 :                 get_rule_expr(arg, context, true);
    9416             :             }
    9417             :         }
    9418             : 
    9419        1036 :         if (aggref->aggorder != NIL)
    9420             :         {
    9421          48 :             appendStringInfoString(buf, " ORDER BY ");
    9422          48 :             get_rule_orderby(aggref->aggorder, aggref->args, false, context);
    9423             :         }
    9424             :     }
    9425             : 
    9426        1058 :     if (aggref->aggfilter != NULL)
    9427             :     {
    9428          20 :         appendStringInfoString(buf, ") FILTER (WHERE ");
    9429          20 :         get_rule_expr((Node *) aggref->aggfilter, context, false);
    9430             :     }
    9431             : 
    9432        1058 :     appendStringInfoChar(buf, ')');
    9433             : }
    9434             : 
    9435             : /*
    9436             :  * This is a helper function for get_agg_expr().  It's used when we deparse
    9437             :  * a combining Aggref; resolve_special_varno locates the corresponding partial
    9438             :  * Aggref and then calls this.
    9439             :  */
    9440             : static void
    9441         158 : get_agg_combine_expr(Node *node, deparse_context *context, void *callback_arg)
    9442             : {
    9443             :     Aggref     *aggref;
    9444         158 :     Aggref     *original_aggref = callback_arg;
    9445             : 
    9446         158 :     if (!IsA(node, Aggref))
    9447           0 :         elog(ERROR, "combining Aggref does not point to an Aggref");
    9448             : 
    9449         158 :     aggref = (Aggref *) node;
    9450         158 :     get_agg_expr(aggref, context, original_aggref);
    9451         158 : }
    9452             : 
    9453             : /*
    9454             :  * get_windowfunc_expr  - Parse back a WindowFunc node
    9455             :  */
    9456             : static void
    9457          56 : get_windowfunc_expr(WindowFunc *wfunc, deparse_context *context)
    9458             : {
    9459          56 :     StringInfo  buf = context->buf;
    9460             :     Oid         argtypes[FUNC_MAX_ARGS];
    9461             :     int         nargs;
    9462             :     List       *argnames;
    9463             :     ListCell   *l;
    9464             : 
    9465          56 :     if (list_length(wfunc->args) > FUNC_MAX_ARGS)
    9466           0 :         ereport(ERROR,
    9467             :                 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
    9468             :                  errmsg("too many arguments")));
    9469          56 :     nargs = 0;
    9470          56 :     argnames = NIL;
    9471         100 :     foreach(l, wfunc->args)
    9472             :     {
    9473          44 :         Node       *arg = (Node *) lfirst(l);
    9474             : 
    9475          44 :         if (IsA(arg, NamedArgExpr))
    9476           0 :             argnames = lappend(argnames, ((NamedArgExpr *) arg)->name);
    9477          44 :         argtypes[nargs] = exprType(arg);
    9478          44 :         nargs++;
    9479             :     }
    9480             : 
    9481          56 :     appendStringInfo(buf, "%s(",
    9482             :                      generate_function_name(wfunc->winfnoid, nargs,
    9483             :                                             argnames, argtypes,
    9484             :                                             false, NULL,
    9485             :                                             context->special_exprkind));
    9486             :     /* winstar can be set only in zero-argument aggregates */
    9487          56 :     if (wfunc->winstar)
    9488           0 :         appendStringInfoChar(buf, '*');
    9489             :     else
    9490          56 :         get_rule_expr((Node *) wfunc->args, context, true);
    9491             : 
    9492          56 :     if (wfunc->aggfilter != NULL)
    9493             :     {
    9494           0 :         appendStringInfoString(buf, ") FILTER (WHERE ");
    9495           0 :         get_rule_expr((Node *) wfunc->aggfilter, context, false);
    9496             :     }
    9497             : 
    9498          56 :     appendStringInfoString(buf, ") OVER ");
    9499             : 
    9500          56 :     foreach(l, context->windowClause)
    9501             :     {
    9502          28 :         WindowClause *wc = (WindowClause *) lfirst(l);
    9503             : 
    9504          28 :         if (wc->winref == wfunc->winref)
    9505             :         {
    9506          28 :             if (wc->name)
    9507           0 :                 appendStringInfoString(buf, quote_identifier(wc->name));
    9508             :             else
    9509          28 :                 get_rule_windowspec(wc, context->windowTList, context);
    9510          28 :             break;
    9511             :         }
    9512             :     }
    9513          56 :     if (l == NULL)
    9514             :     {
    9515          28 :         if (context->windowClause)
    9516           0 :             elog(ERROR, "could not find window clause for winref %u",
    9517             :                  wfunc->winref);
    9518             : 
    9519             :         /*
    9520             :          * In EXPLAIN, we don't have window context information available, so
    9521             :          * we have to settle for this:
    9522             :          */
    9523          28 :         appendStringInfoString(buf, "(?)");
    9524             :     }
    9525          56 : }
    9526             : 
    9527             : /* ----------
    9528             :  * get_coercion_expr
    9529             :  *
    9530             :  *  Make a string representation of a value coerced to a specific type
    9531             :  * ----------
    9532             :  */
    9533             : static void
    9534        2068 : get_coercion_expr(Node *arg, deparse_context *context,
    9535             :                   Oid resulttype, int32 resulttypmod,
    9536             :                   Node *parentNode)
    9537             : {
    9538        2068 :     StringInfo  buf = context->buf;
    9539             : 
    9540             :     /*
    9541             :      * Since parse_coerce.c doesn't immediately collapse application of
    9542             :      * length-coercion functions to constants, what we'll typically see in
    9543             :      * such cases is a Const with typmod -1 and a length-coercion function
    9544             :      * right above it.  Avoid generating redundant output. However, beware of
    9545             :      * suppressing casts when the user actually wrote something like
    9546             :      * 'foo'::text::char(3).
    9547             :      *
    9548             :      * Note: it might seem that we are missing the possibility of needing to
    9549             :      * print a COLLATE clause for such a Const.  However, a Const could only
    9550             :      * have nondefault collation in a post-constant-folding tree, in which the
    9551             :      * length coercion would have been folded too.  See also the special
    9552             :      * handling of CollateExpr in coerce_to_target_type(): any collation
    9553             :      * marking will be above the coercion node, not below it.
    9554             :      */
    9555        2068 :     if (arg && IsA(arg, Const) &&
    9556         272 :         ((Const *) arg)->consttype == resulttype &&
    9557          16 :         ((Const *) arg)->consttypmod == -1)
    9558             :     {
    9559             :         /* Show the constant without normal ::typename decoration */
    9560          16 :         get_const_expr((Const *) arg, context, -1);
    9561             :     }
    9562             :     else
    9563             :     {
    9564        2052 :         if (!PRETTY_PAREN(context))
    9565        1892 :             appendStringInfoChar(buf, '(');
    9566        2052 :         get_rule_expr_paren(arg, context, false, parentNode);
    9567        2052 :         if (!PRETTY_PAREN(context))
    9568        1892 :             appendStringInfoChar(buf, ')');
    9569             :     }
    9570             : 
    9571             :     /*
    9572             :      * Never emit resulttype(arg) functional notation. A pg_proc entry could
    9573             :      * take precedence, and a resulttype in pg_temp would require schema
    9574             :      * qualification that format_type_with_typemod() would usually omit. We've
    9575             :      * standardized on arg::resulttype, but CAST(arg AS resulttype) notation
    9576             :      * would work fine.
    9577             :      */
    9578        2068 :     appendStringInfo(buf, "::%s",
    9579             :                      format_type_with_typemod(resulttype, resulttypmod));
    9580        2068 : }
    9581             : 
    9582             : /* ----------
    9583             :  * get_const_expr
    9584             :  *
    9585             :  *  Make a string representation of a Const
    9586             :  *
    9587             :  * showtype can be -1 to never show "::typename" decoration, or +1 to always
    9588             :  * show it, or 0 to show it only if the constant wouldn't be assumed to be
    9589             :  * the right type by default.
    9590             :  *
    9591             :  * If the Const's collation isn't default for its type, show that too.
    9592             :  * We mustn't do this when showtype is -1 (since that means the caller will
    9593             :  * print "::typename", and we can't put a COLLATE clause in between).  It's
    9594             :  * caller's responsibility that collation isn't missed in such cases.
    9595             :  * ----------
    9596             :  */
    9597             : static void
    9598       29880 : get_const_expr(Const *constval, deparse_context *context, int showtype)
    9599             : {
    9600       29880 :     StringInfo  buf = context->buf;
    9601             :     Oid         typoutput;
    9602             :     bool        typIsVarlena;
    9603             :     char       *extval;
    9604       29880 :     bool        needlabel = false;
    9605             : 
    9606       29880 :     if (constval->constisnull)
    9607             :     {
    9608             :         /*
    9609             :          * Always label the type of a NULL constant to prevent misdecisions
    9610             :          * about type when reparsing.
    9611             :          */
    9612         362 :         appendStringInfoString(buf, "NULL");
    9613         362 :         if (showtype >= 0)
    9614             :         {
    9615         334 :             appendStringInfo(buf, "::%s",
    9616             :                              format_type_with_typemod(constval->consttype,
    9617             :                                                       constval->consttypmod));
    9618         334 :             get_const_collation(constval, context);
    9619             :         }
    9620        3914 :         return;
    9621             :     }
    9622             : 
    9623       29518 :     getTypeOutputInfo(constval->consttype,
    9624             :                       &typoutput, &typIsVarlena);
    9625             : 
    9626       29518 :     extval = OidOutputFunctionCall(typoutput, constval->constvalue);
    9627             : 
    9628       29518 :     switch (constval->consttype)
    9629             :     {
    9630       17670 :         case INT4OID:
    9631             : 
    9632             :             /*
    9633             :              * INT4 can be printed without any decoration, unless it is
    9634             :              * negative; in that case print it as '-nnn'::integer to ensure
    9635             :              * that the output will re-parse as a constant, not as a constant
    9636             :              * plus operator.  In most cases we could get away with printing
    9637             :              * (-nnn) instead, because of the way that gram.y handles negative
    9638             :              * literals; but that doesn't work for INT_MIN, and it doesn't
    9639             :              * seem that much prettier anyway.
    9640             :              */
    9641       17670 :             if (extval[0] != '-')
    9642       17480 :                 appendStringInfoString(buf, extval);
    9643             :             else
    9644             :             {
    9645         190 :                 appendStringInfo(buf, "'%s'", extval);
    9646         190 :                 needlabel = true;   /* we must attach a cast */
    9647             :             }
    9648       17670 :             break;
    9649             : 
    9650         464 :         case NUMERICOID:
    9651             : 
    9652             :             /*
    9653             :              * NUMERIC can be printed without quotes if it looks like a float
    9654             :              * constant (not an integer, and not Infinity or NaN) and doesn't
    9655             :              * have a leading sign (for the same reason as for INT4).
    9656             :              */
    9657         464 :             if (isdigit((unsigned char) extval[0]) &&
    9658         464 :                 strcspn(extval, "eE.") != strlen(extval))
    9659             :             {
    9660         170 :                 appendStringInfoString(buf, extval);
    9661             :             }
    9662             :             else
    9663             :             {
    9664         294 :                 appendStringInfo(buf, "'%s'", extval);
    9665         294 :                 needlabel = true;   /* we must attach a cast */
    9666             :             }
    9667         464 :             break;
    9668             : 
    9669         684 :         case BOOLOID:
    9670         684 :             if (strcmp(extval, "t") == 0)
    9671         410 :                 appendStringInfoString(buf, "true");
    9672             :             else
    9673         274 :                 appendStringInfoString(buf, "false");
    9674         684 :             break;
    9675             : 
    9676       10700 :         default:
    9677       10700 :             simple_quote_literal(buf, extval);
    9678       10700 :             break;
    9679             :     }
    9680             : 
    9681       29518 :     pfree(extval);
    9682             : 
    9683       29518 :     if (showtype < 0)
    9684        3552 :         return;
    9685             : 
    9686             :     /*
    9687             :      * For showtype == 0, append ::typename unless the constant will be
    9688             :      * implicitly typed as the right type when it is read in.
    9689             :      *
    9690             :      * XXX this code has to be kept in sync with the behavior of the parser,
    9691             :      * especially make_const.
    9692             :      */
    9693       25966 :     switch (constval->consttype)
    9694             :     {
    9695         688 :         case BOOLOID:
    9696             :         case UNKNOWNOID:
    9697             :             /* These types can be left unlabeled */
    9698         688 :             needlabel = false;
    9699         688 :             break;
    9700       15192 :         case INT4OID:
    9701             :             /* We determined above whether a label is needed */
    9702       15192 :             break;
    9703         464 :         case NUMERICOID:
    9704             : 
    9705             :             /*
    9706             :              * Float-looking constants will be typed as numeric, which we
    9707             :              * checked above; but if there's a nondefault typmod we need to
    9708             :              * show it.
    9709             :              */
    9710         464 :             needlabel |= (constval->consttypmod >= 0);
    9711         464 :             break;
    9712        9622 :         default:
    9713        9622 :             needlabel = true;
    9714        9622 :             break;
    9715             :     }
    9716       25966 :     if (needlabel || showtype > 0)
    9717       10098 :         appendStringInfo(buf, "::%s",
    9718             :                          format_type_with_typemod(constval->consttype,
    9719             :                                                   constval->consttypmod));
    9720             : 
    9721       25966 :     get_const_collation(constval, context);
    9722             : }
    9723             : 
    9724             : /*
    9725             :  * helper for get_const_expr: append COLLATE if needed
    9726             :  */
    9727             : static void
    9728       26300 : get_const_collation(Const *constval, deparse_context *context)
    9729             : {
    9730       26300 :     StringInfo  buf = context->buf;
    9731             : 
    9732       26300 :     if (OidIsValid(constval->constcollid))
    9733             :     {
    9734        4110 :         Oid         typcollation = get_typcollation(constval->consttype);
    9735             : 
    9736        4110 :         if (constval->constcollid != typcollation)
    9737             :         {
    9738          48 :             appendStringInfo(buf, " COLLATE %s",
    9739             :                              generate_collation_name(constval->constcollid));
    9740             :         }
    9741             :     }
    9742       26300 : }
    9743             : 
    9744             : /*
    9745             :  * simple_quote_literal - Format a string as a SQL literal, append to buf
    9746             :  */
    9747             : static void
    9748       11320 : simple_quote_literal(StringInfo buf, const char *val)
    9749             : {
    9750             :     const char *valptr;
    9751             : 
    9752             :     /*
    9753             :      * We form the string literal according to the prevailing setting of
    9754             :      * standard_conforming_strings; we never use E''. User is responsible for
    9755             :      * making sure result is used correctly.
    9756             :      */
    9757       11320 :     appendStringInfoChar(buf, '\'');
    9758      114190 :     for (valptr = val; *valptr; valptr++)
    9759             :     {
    9760      102870 :         char        ch = *valptr;
    9761             : 
    9762      102870 :         if (SQL_STR_DOUBLE(ch, !standard_conforming_strings))
    9763         204 :             appendStringInfoChar(buf, ch);
    9764      102870 :         appendStringInfoChar(buf, ch);
    9765             :     }
    9766       11320 :     appendStringInfoChar(buf, '\'');
    9767       11320 : }
    9768             : 
    9769             : 
    9770             : /* ----------
    9771             :  * get_sublink_expr         - Parse back a sublink
    9772             :  * ----------
    9773             :  */
    9774             : static void
    9775         192 : get_sublink_expr(SubLink *sublink, deparse_context *context)
    9776             : {
    9777         192 :     StringInfo  buf = context->buf;
    9778         192 :     Query      *query = (Query *) (sublink->subselect);
    9779         192 :     char       *opname = NULL;
    9780             :     bool        need_paren;
    9781             : 
    9782         192 :     if (sublink->subLinkType == ARRAY_SUBLINK)
    9783           8 :         appendStringInfoString(buf, "ARRAY(");
    9784             :     else
    9785         184 :         appendStringInfoChar(buf, '(');
    9786             : 
    9787             :     /*
    9788             :      * Note that we print the name of only the first operator, when there are
    9789             :      * multiple combining operators.  This is an approximation that could go
    9790             :      * wrong in various scenarios (operators in different schemas, renamed
    9791             :      * operators, etc) but there is not a whole lot we can do about it, since
    9792             :      * the syntax allows only one operator to be shown.
    9793             :      */
    9794         192 :     if (sublink->testexpr)
    9795             :     {
    9796          12 :         if (IsA(sublink->testexpr, OpExpr))
    9797             :         {
    9798             :             /* single combining operator */
    9799           4 :             OpExpr     *opexpr = (OpExpr *) sublink->testexpr;
    9800             : 
    9801           4 :             get_rule_expr(linitial(opexpr->args), context, true);
    9802           4 :             opname = generate_operator_name(opexpr->opno,
    9803           4 :                                             exprType(linitial(opexpr->args)),
    9804           4 :                                             exprType(lsecond(opexpr->args)));
    9805             :         }
    9806           8 :         else if (IsA(sublink->testexpr, BoolExpr))
    9807             :         {
    9808             :             /* multiple combining operators, = or <> cases */
    9809             :             char       *sep;
    9810             :             ListCell   *l;
    9811             : 
    9812           4 :             appendStringInfoChar(buf, '(');
    9813           4 :             sep = "";
    9814          12 :             foreach(l, ((BoolExpr *) sublink->testexpr)->args)
    9815             :             {
    9816           8 :                 OpExpr     *opexpr = lfirst_node(OpExpr, l);
    9817             : 
    9818           8 :                 appendStringInfoString(buf, sep);
    9819           8 :                 get_rule_expr(linitial(opexpr->args), context, true);
    9820           8 :                 if (!opname)
    9821           4 :                     opname = generate_operator_name(opexpr->opno,
    9822           4 :                                                     exprType(linitial(opexpr->args)),
    9823           4 :                                                     exprType(lsecond(opexpr->args)));
    9824           8 :                 sep = ", ";
    9825             :             }
    9826           4 :             appendStringInfoChar(buf, ')');
    9827             :         }
    9828           4 :         else if (IsA(sublink->testexpr, RowCompareExpr))
    9829             :         {
    9830             :             /* multiple combining operators, < <= > >= cases */
    9831           4 :             RowCompareExpr *rcexpr = (RowCompareExpr *) sublink->testexpr;
    9832             : 
    9833           4 :             appendStringInfoChar(buf, '(');
    9834           4 :             get_rule_expr((Node *) rcexpr->largs, context, true);
    9835           4 :             opname = generate_operator_name(linitial_oid(rcexpr->opnos),
    9836           4 :                                             exprType(linitial(rcexpr->largs)),
    9837           4 :                                             exprType(linitial(rcexpr->rargs)));
    9838           4 :             appendStringInfoChar(buf, ')');
    9839             :         }
    9840             :         else
    9841           0 :             elog(ERROR, "unrecognized testexpr type: %d",
    9842             :                  (int) nodeTag(sublink->testexpr));
    9843             :     }
    9844             : 
    9845         192 :     need_paren = true;
    9846             : 
    9847         192 :     switch (sublink->subLinkType)
    9848             :     {
    9849         116 :         case EXISTS_SUBLINK:
    9850         116 :             appendStringInfoString(buf, "EXISTS ");
    9851         116 :             break;
    9852             : 
    9853           8 :         case ANY_SUBLINK:
    9854           8 :             if (strcmp(opname, "=") == 0) /* Represent = ANY as IN */
    9855           4 :                 appendStringInfoString(buf, " IN ");
    9856             :             else
    9857           4 :                 appendStringInfo(buf, " %s ANY ", opname);
    9858           8 :             break;
    9859             : 
    9860           4 :         case ALL_SUBLINK:
    9861           4 :             appendStringInfo(buf, " %s ALL ", opname);
    9862           4 :             break;
    9863             : 
    9864           0 :         case ROWCOMPARE_SUBLINK:
    9865           0 :             appendStringInfo(buf, " %s ", opname);
    9866           0 :             break;
    9867             : 
    9868          64 :         case EXPR_SUBLINK:
    9869             :         case MULTIEXPR_SUBLINK:
    9870             :         case ARRAY_SUBLINK:
    9871          64 :             need_paren = false;
    9872          64 :             break;
    9873             : 
    9874           0 :         case CTE_SUBLINK:       /* shouldn't occur in a SubLink */
    9875             :         default:
    9876           0 :             elog(ERROR, "unrecognized sublink type: %d",
    9877             :                  (int) sublink->subLinkType);
    9878             :             break;
    9879             :     }
    9880             : 
    9881         192 :     if (need_paren)
    9882         128 :         appendStringInfoChar(buf, '(');
    9883             : 
    9884         192 :     get_query_def(query, buf, context->namespaces, NULL,
    9885             :                   context->prettyFlags, context->wrapColumn,
    9886             :                   context->indentLevel);
    9887             : 
    9888         192 :     if (need_paren)
    9889         128 :         appendStringInfoString(buf, "))");
    9890             :     else
    9891          64 :         appendStringInfoChar(buf, ')');
    9892         192 : }
    9893             : 
    9894             : 
    9895             : /* ----------
    9896             :  * get_tablefunc            - Parse back a table function
    9897             :  * ----------
    9898             :  */
    9899             : static void
    9900          32 : get_tablefunc(TableFunc *tf, deparse_context *context, bool showimplicit)
    9901             : {
    9902          32 :     StringInfo  buf = context->buf;
    9903             : 
    9904             :     /* XMLTABLE is the only existing implementation.  */
    9905             : 
    9906          32 :     appendStringInfoString(buf, "XMLTABLE(");
    9907             : 
    9908          32 :     if (tf->ns_uris != NIL)
    9909             :     {
    9910             :         ListCell   *lc1,
    9911             :                    *lc2;
    9912           6 :         bool        first = true;
    9913             : 
    9914           6 :         appendStringInfoString(buf, "XMLNAMESPACES (");
    9915          12 :         forboth(lc1, tf->ns_uris, lc2, tf->ns_names)
    9916             :         {
    9917           6 :             Node       *expr = (Node *) lfirst(lc1);
    9918           6 :             Value      *ns_node = (Value *) lfirst(lc2);
    9919             : 
    9920           6 :             if (!first)
    9921           0 :                 appendStringInfoString(buf, ", ");
    9922             :             else
    9923           6 :                 first = false;
    9924             : 
    9925           6 :             if (ns_node != NULL)
    9926             :             {
    9927           6 :                 get_rule_expr(expr, context, showimplicit);
    9928           6 :                 appendStringInfo(buf, " AS %s", strVal(ns_node));
    9929             :             }
    9930             :             else
    9931             :             {
    9932           0 :                 appendStringInfoString(buf, "DEFAULT ");
    9933           0 :                 get_rule_expr(expr, context, showimplicit);
    9934             :             }
    9935             :         }
    9936           6 :         appendStringInfoString(buf, "), ");
    9937             :     }
    9938             : 
    9939          32 :     appendStringInfoChar(buf, '(');
    9940          32 :     get_rule_expr((Node *) tf->rowexpr, context, showimplicit);
    9941          32 :     appendStringInfoString(buf, ") PASSING (");
    9942          32 :     get_rule_expr((Node *) tf->docexpr, context, showimplicit);
    9943          32 :     appendStringInfoChar(buf, ')');
    9944             : 
    9945          32 :     if (tf->colexprs != NIL)
    9946             :     {
    9947             :         ListCell   *l1;
    9948             :         ListCell   *l2;
    9949             :         ListCell   *l3;
    9950             :         ListCell   *l4;
    9951             :         ListCell   *l5;
    9952          32 :         int         colnum = 0;
    9953             : 
    9954          32 :         appendStringInfoString(buf, " COLUMNS ");
    9955         222 :         forfive(l1, tf->colnames, l2, tf->coltypes, l3, tf->coltypmods,
    9956             :                 l4, tf->colexprs, l5, tf->coldefexprs)
    9957             :         {
    9958         190 :             char       *colname = strVal(lfirst(l1));
    9959         190 :             Oid         typid = lfirst_oid(l2);
    9960         190 :             int32       typmod = lfirst_int(l3);
    9961         190 :             Node       *colexpr = (Node *) lfirst(l4);
    9962         190 :             Node       *coldefexpr = (Node *) lfirst(l5);
    9963         190 :             bool        ordinality = (tf->ordinalitycol == colnum);
    9964         190 :             bool        notnull = bms_is_member(colnum, tf->notnulls);
    9965             : 
    9966         190 :             if (colnum > 0)
    9967         158 :                 appendStringInfoString(buf, ", ");
    9968         190 :             colnum++;
    9969             : 
    9970         358 :             appendStringInfo(buf, "%s %s", quote_identifier(colname),
    9971             :                              ordinality ? "FOR ORDINALITY" :
    9972         168 :                              format_type_with_typemod(typid, typmod));
    9973         190 :             if (ordinality)
    9974          22 :                 continue;
    9975             : 
    9976         168 :             if (coldefexpr != NULL)
    9977             :             {
    9978          22 :                 appendStringInfoString(buf, " DEFAULT (");
    9979          22 :                 get_rule_expr((Node *) coldefexpr, context, showimplicit);
    9980          22 :                 appendStringInfoChar(buf, ')');
    9981             :             }
    9982         168 :             if (colexpr != NULL)
    9983             :             {
    9984         160 :                 appendStringInfoString(buf, " PATH (");
    9985         160 :                 get_rule_expr((Node *) colexpr, context, showimplicit);
    9986         160 :                 appendStringInfoChar(buf, ')');
    9987             :             }
    9988         168 :             if (notnull)
    9989          22 :                 appendStringInfoString(buf, " NOT NULL");
    9990             :         }
    9991             :     }
    9992             : 
    9993          32 :     appendStringInfoChar(buf, ')');
    9994          32 : }
    9995             : 
    9996             : /* ----------
    9997             :  * get_from_clause          - Parse back a FROM clause
    9998             :  *
    9999             :  * "prefix" is the keyword that denotes the start of the list of FROM
   10000             :  * elements. It is FROM when used to parse back SELECT and UPDATE, but
   10001             :  * is USING when parsing back DELETE.
   10002             :  * ----------
   10003             :  */
   10004             : static void
   10005        2190 : get_from_clause(Query *query, const char *prefix, deparse_context *context)
   10006             : {
   10007        2190 :     StringInfo  buf = context->buf;
   10008        2190 :     bool        first = true;
   10009             :     ListCell   *l;
   10010             : 
   10011             :     /*
   10012             :      * We use the query's jointree as a guide to what to print.  However, we
   10013             :      * must ignore auto-added RTEs that are marked not inFromCl. (These can
   10014             :      * only appear at the top level of the jointree, so it's sufficient to
   10015             :      * check here.)  This check also ensures we ignore the rule pseudo-RTEs
   10016             :      * for NEW and OLD.
   10017             :      */
   10018        4448 :     foreach(l, query->jointree->fromlist)
   10019             :     {
   10020        2258 :         Node       *jtnode = (Node *) lfirst(l);
   10021             : 
   10022        2258 :         if (IsA(jtnode, RangeTblRef))
   10023             :         {
   10024        1838 :             int         varno = ((RangeTblRef *) jtnode)->rtindex;
   10025        1838 :             RangeTblEntry *rte = rt_fetch(varno, query->rtable);
   10026             : 
   10027        1838 :             if (!rte->inFromCl)
   10028         256 :                 continue;
   10029             :         }
   10030             : 
   10031        2002 :         if (first)
   10032             :         {
   10033        1826 :             appendContextKeyword(context, prefix,
   10034             :                                  -PRETTYINDENT_STD, PRETTYINDENT_STD, 2);
   10035        1826 :             first = false;
   10036             : 
   10037        1826 :             get_from_clause_item(jtnode, query, context);
   10038             :         }
   10039             :         else
   10040             :         {
   10041             :             StringInfoData itembuf;
   10042             : 
   10043         176 :             appendStringInfoString(buf, ", ");
   10044             : 
   10045             :             /*
   10046             :              * Put the new FROM item's text into itembuf so we can decide
   10047             :              * after we've got it whether or not it needs to go on a new line.
   10048             :              */
   10049         176 :             initStringInfo(&itembuf);
   10050         176 :             context->buf = &itembuf;
   10051             : 
   10052         176 :             get_from_clause_item(jtnode, query, context);
   10053             : 
   10054             :             /* Restore context's output buffer */
   10055         176 :             context->buf = buf;
   10056             : 
   10057             :             /* Consider line-wrapping if enabled */
   10058         176 :             if (PRETTY_INDENT(context) && context->wrapColumn >= 0)
   10059             :             {
   10060             :                 /* Does the new item start with a new line? */
   10061         176 :                 if (itembuf.len > 0 && itembuf.data[0] == '\n')
   10062             :                 {
   10063             :                     /* If so, we shouldn't add anything */
   10064             :                     /* instead, remove any trailing spaces currently in buf */
   10065           0 :                     removeStringInfoSpaces(buf);
   10066             :                 }
   10067             :                 else
   10068             :                 {
   10069             :                     char       *trailing_nl;
   10070             : 
   10071             :                     /* Locate the start of the current line in the buffer */
   10072         176 :                     trailing_nl = strrchr(buf->data, '\n');
   10073         176 :                     if (trailing_nl == NULL)
   10074           0 :                         trailing_nl = buf->data;
   10075             :                     else
   10076         176 :                         trailing_nl++;
   10077             : 
   10078             :                     /*
   10079             :                      * Add a newline, plus some indentation, if the new item
   10080             :                      * would cause an overflow.
   10081             :                      */
   10082         176 :                     if (strlen(trailing_nl) + itembuf.len > context->wrapColumn)
   10083         176 :                         appendContextKeyword(context, "", -PRETTYINDENT_STD,
   10084             :                                              PRETTYINDENT_STD,
   10085             :                                              PRETTYINDENT_VAR);
   10086             :                 }
   10087             :             }
   10088             : 
   10089             :             /* Add the new item */
   10090         176 :             appendBinaryStringInfo(buf, itembuf.data, itembuf.len);
   10091             : 
   10092             :             /* clean up */
   10093         176 :             pfree(itembuf.data);
   10094             :         }
   10095             :     }
   10096        2190 : }
   10097             : 
   10098             : static void
   10099        3250 : get_from_clause_item(Node *jtnode, Query *query, deparse_context *context)
   10100             : {
   10101        3250 :     StringInfo  buf = context->buf;
   10102        3250 :     deparse_namespace *dpns = (deparse_namespace *) linitial(context->namespaces);
   10103             : 
   10104        3250 :     if (IsA(jtnode, RangeTblRef))
   10105             :     {
   10106        2626 :         int         varno = ((RangeTblRef *) jtnode)->rtindex;
   10107        2626 :         RangeTblEntry *rte = rt_fetch(varno, query->rtable);
   10108        2626 :         char       *refname = get_rtable_name(varno, context);
   10109        2626 :         deparse_columns *colinfo = deparse_columns_fetch(varno, dpns);
   10110        2626 :         RangeTblFunction *rtfunc1 = NULL;
   10111             :         bool        printalias;
   10112             : 
   10113        2626 :         if (rte->lateral)
   10114          22 :             appendStringInfoString(buf, "LATERAL ");
   10115             : 
   10116             :         /* Print the FROM item proper */
   10117        2626 :         switch (rte->rtekind)
   10118             :         {
   10119        2196 :             case RTE_RELATION:
   10120             :                 /* Normal relation RTE */
   10121        4392 :                 appendStringInfo(buf, "%s%s",
   10122        2196 :                                  only_marker(rte),
   10123             :                                  generate_relation_name(rte->relid,
   10124             :                                                         context->namespaces));
   10125        2196 :                 break;
   10126         118 :             case RTE_SUBQUERY:
   10127             :                 /* Subquery RTE */
   10128         118 :                 appendStringInfoChar(buf, '(');
   10129         118 :                 get_query_def(rte->subquery, buf, context->namespaces, NULL,
   10130             :                               context->prettyFlags, context->wrapColumn,
   10131             :                               context->indentLevel);
   10132         118 :                 appendStringInfoChar(buf, ')');
   10133         118 :                 break;
   10134         232 :             case RTE_FUNCTION:
   10135             :                 /* Function RTE */
   10136         232 :                 rtfunc1 = (RangeTblFunction *) linitial(rte->functions);
   10137             : 
   10138             :                 /*
   10139             :                  * Omit ROWS FROM() syntax for just one function, unless it
   10140             :                  * has both a coldeflist and WITH ORDINALITY. If it has both,
   10141             :                  * we must use ROWS FROM() syntax to avoid ambiguity about
   10142             :                  * whether the coldeflist includes the ordinality column.
   10143             :                  */
   10144         232 :                 if (list_length(rte->functions) == 1 &&
   10145         212 :                     (rtfunc1->funccolnames == NIL || !rte->funcordinality))
   10146             :                 {
   10147         212 :                     get_rule_expr_funccall(rtfunc1->funcexpr, context, true);
   10148             :                     /* we'll print the coldeflist below, if it has one */
   10149             :                 }
   10150             :                 else
   10151             :                 {
   10152             :                     bool        all_unnest;
   10153             :                     ListCell   *lc;
   10154             : 
   10155             :                     /*
   10156             :                      * If all the function calls in the list are to unnest,
   10157             :                      * and none need a coldeflist, then collapse the list back
   10158             :                      * down to UNNEST(args).  (If we had more than one
   10159             :                      * built-in unnest function, this would get more
   10160             :                      * difficult.)
   10161             :                      *
   10162             :                      * XXX This is pretty ugly, since it makes not-terribly-
   10163             :                      * future-proof assumptions about what the parser would do
   10164             :                      * with the output; but the alternative is to emit our
   10165             :                      * nonstandard ROWS FROM() notation for what might have
   10166             :                      * been a perfectly spec-compliant multi-argument
   10167             :                      * UNNEST().
   10168             :                      */
   10169          20 :                     all_unnest = true;
   10170          52 :                     foreach(lc, rte->functions)
   10171             :                     {
   10172          44 :                         RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
   10173             : 
   10174          44 :                         if (!IsA(rtfunc->funcexpr, FuncExpr) ||
   10175          44 :                             ((FuncExpr *) rtfunc->funcexpr)->funcid != F_ARRAY_UNNEST ||
   10176          32 :                             rtfunc->funccolnames != NIL)
   10177             :                         {
   10178          12 :                             all_unnest = false;
   10179          12 :                             break;
   10180             :                         }
   10181             :                     }
   10182             : 
   10183          20 :                     if (all_unnest)
   10184             :                     {
   10185           8 :                         List       *allargs = NIL;
   10186             : 
   10187          32 :                         foreach(lc, rte->functions)
   10188             :                         {
   10189          24 :                             RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
   10190          24 :                             List       *args = ((FuncExpr *) rtfunc->funcexpr)->args;
   10191             : 
   10192          24 :                             allargs = list_concat(allargs, args);
   10193             :                         }
   10194             : 
   10195           8 :                         appendStringInfoString(buf, "UNNEST(");
   10196           8 :                         get_rule_expr((Node *) allargs, context, true);
   10197           8 :                         appendStringInfoChar(buf, ')');
   10198             :                     }
   10199             :                     else
   10200             :                     {
   10201          12 :                         int         funcno = 0;
   10202             : 
   10203          12 :                         appendStringInfoString(buf, "ROWS FROM(");
   10204          44 :                         foreach(lc, rte->functions)
   10205             :                         {
   10206          32 :                             RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
   10207             : 
   10208          32 :                             if (funcno > 0)
   10209          20 :                                 appendStringInfoString(buf, ", ");
   10210          32 :                             get_rule_expr_funccall(rtfunc->funcexpr, context, true);
   10211          32 :                             if (rtfunc->funccolnames != NIL)
   10212             :                             {
   10213             :                                 /* Reconstruct the column definition list */
   10214           4 :                                 appendStringInfoString(buf, " AS ");
   10215           4 :                                 get_from_clause_coldeflist(rtfunc,
   10216             :                                                            NULL,
   10217             :                                                            context);
   10218             :                             }
   10219          32 :                             funcno++;
   10220             :                         }
   10221          12 :                         appendStringInfoChar(buf, ')');
   10222             :                     }
   10223             :                     /* prevent printing duplicate coldeflist below */
   10224          20 :                     rtfunc1 = NULL;
   10225             :                 }
   10226         232 :                 if (rte->funcordinality)
   10227          12 :                     appendStringInfoString(buf, " WITH ORDINALITY");
   10228         232 :                 break;
   10229          16 :             case RTE_TABLEFUNC:
   10230          16 :                 get_tablefunc(rte->tablefunc, context, true);
   10231          16 :                 break;
   10232           8 :             case RTE_VALUES:
   10233             :                 /* Values list RTE */
   10234           8 :                 appendStringInfoChar(buf, '(');
   10235           8 :                 get_values_def(rte->values_lists, context);
   10236           8 :                 appendStringInfoChar(buf, ')');
   10237           8 :                 break;
   10238          56 :             case RTE_CTE:
   10239          56 :                 appendStringInfoString(buf, quote_identifier(rte->ctename));
   10240          56 :                 break;
   10241           0 :             default:
   10242           0 :                 elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
   10243             :                 break;
   10244             :         }
   10245             : 
   10246             :         /* Print the relation alias, if needed */
   10247        2626 :         printalias = false;
   10248        2626 :         if (rte->alias != NULL)
   10249             :         {
   10250             :             /* Always print alias if user provided one */
   10251        1186 :             printalias = true;
   10252             :         }
   10253        1440 :         else if (colinfo->printaliases)
   10254             :         {
   10255             :             /* Always print alias if we need to print column aliases */
   10256          92 :             printalias = true;
   10257             :         }
   10258        1348 :         else if (rte->rtekind == RTE_RELATION)
   10259             :         {
   10260             :             /*
   10261             :              * No need to print alias if it's same as relation name (this
   10262             :              * would normally be the case, but not if set_rtable_names had to
   10263             :              * resolve a conflict).
   10264             :              */
   10265        1280 :             if (strcmp(refname, get_relation_name(rte->relid)) != 0)
   10266          24 :                 printalias = true;
   10267             :         }
   10268          68 :         else if (rte->rtekind == RTE_FUNCTION)
   10269             :         {
   10270             :             /*
   10271             :              * For a function RTE, always print alias.  This covers possible
   10272             :              * renaming of the function and/or instability of the
   10273             :              * FigureColname rules for things that aren't simple functions.
   10274             :              * Note we'd need to force it anyway for the columndef list case.
   10275             :              */
   10276           0 :             printalias = true;
   10277             :         }
   10278          68 :         else if (rte->rtekind == RTE_VALUES)
   10279             :         {
   10280             :             /* Alias is syntactically required for VALUES */
   10281           8 :             printalias = true;
   10282             :         }
   10283          60 :         else if (rte->rtekind == RTE_CTE)
   10284             :         {
   10285             :             /*
   10286             :              * No need to print alias if it's same as CTE name (this would
   10287             :              * normally be the case, but not if set_rtable_names had to
   10288             :              * resolve a conflict).
   10289             :              */
   10290          44 :             if (strcmp(refname, rte->ctename) != 0)
   10291          12 :                 printalias = true;
   10292             :         }
   10293        2626 :         if (printalias)
   10294        1322 :             appendStringInfo(buf, " %s", quote_identifier(refname));
   10295             : 
   10296             :         /* Print the column definitions or aliases, if needed */
   10297        2626 :         if (rtfunc1 && rtfunc1->funccolnames != NIL)
   10298             :         {
   10299             :             /* Reconstruct the columndef list, which is also the aliases */
   10300           0 :             get_from_clause_coldeflist(rtfunc1, colinfo, context);
   10301             :         }
   10302             :         else
   10303             :         {
   10304             :             /* Else print column aliases as needed */
   10305        2626 :             get_column_alias_list(colinfo, context);
   10306             :         }
   10307             : 
   10308             :         /* Tablesample clause must go after any alias */
   10309        2626 :         if (rte->rtekind == RTE_RELATION && rte->tablesample)
   10310          28 :             get_tablesample_def(rte->tablesample, context);
   10311             :     }
   10312         624 :     else if (IsA(jtnode, JoinExpr))
   10313             :     {
   10314         624 :         JoinExpr   *j = (JoinExpr *) jtnode;
   10315         624 :         deparse_columns *colinfo = deparse_columns_fetch(j->rtindex, dpns);
   10316             :         bool        need_paren_on_right;
   10317             : 
   10318        1524 :         need_paren_on_right = PRETTY_PAREN(context) &&
   10319         624 :             !IsA(j->rarg, RangeTblRef) &&
   10320           0 :             !(IsA(j->rarg, JoinExpr) && ((JoinExpr *) j->rarg)->alias != NULL);
   10321             : 
   10322         624 :         if (!PRETTY_PAREN(context) || j->alias != NULL)
   10323         412 :             appendStringInfoChar(buf, '(');
   10324             : 
   10325         624 :         get_from_clause_item(j->larg, query, context);
   10326             : 
   10327         624 :         switch (j->jointype)
   10328             :         {
   10329         376 :             case JOIN_INNER:
   10330         376 :                 if (j->quals)
   10331         348 :                     appendContextKeyword(context, " JOIN ",
   10332             :                                          -PRETTYINDENT_STD,
   10333             :                                          PRETTYINDENT_STD,
   10334             :                                          PRETTYINDENT_JOIN);
   10335             :                 else
   10336          28 :                     appendContextKeyword(context, " CROSS JOIN ",
   10337             :                                          -PRETTYINDENT_STD,
   10338             :                                          PRETTYINDENT_STD,
   10339             :                                          PRETTYINDENT_JOIN);
   10340         376 :                 break;
   10341         180 :             case JOIN_LEFT:
   10342         180 :                 appendContextKeyword(context, " LEFT JOIN ",
   10343             :                                      -PRETTYINDENT_STD,
   10344             :                                      PRETTYINDENT_STD,
   10345             :                                      PRETTYINDENT_JOIN);
   10346         180 :                 break;
   10347          68 :             case JOIN_FULL:
   10348          68 :                 appendContextKeyword(context, " FULL JOIN ",
   10349             :                                      -PRETTYINDENT_STD,
   10350             :                                      PRETTYINDENT_STD,
   10351             :                                      PRETTYINDENT_JOIN);
   10352          68 :                 break;
   10353           0 :             case JOIN_RIGHT:
   10354           0 :                 appendContextKeyword(context, " RIGHT JOIN ",
   10355             :                                      -PRETTYINDENT_STD,
   10356             :                                      PRETTYINDENT_STD,
   10357             :                                      PRETTYINDENT_JOIN);
   10358           0 :                 break;
   10359           0 :             default:
   10360           0 :                 elog(ERROR, "unrecognized join type: %d",
   10361             :                      (int) j->jointype);
   10362             :         }
   10363             : 
   10364         624 :         if (need_paren_on_right)
   10365           0 :             appendStringInfoChar(buf, '(');
   10366         624 :         get_from_clause_item(j->rarg, query, context);
   10367         624 :         if (need_paren_on_right)
   10368           0 :             appendStringInfoChar(buf, ')');
   10369             : 
   10370         624 :         if (j->usingClause)
   10371             :         {
   10372             :             ListCell   *lc;
   10373         264 :             bool        first = true;
   10374             : 
   10375         264 :             appendStringInfoString(buf, " USING (");
   10376             :             /* Use the assigned names, not what's in usingClause */
   10377         632 :             foreach(lc, colinfo->usingNames)
   10378             :             {
   10379         368 :                 char       *colname = (char *) lfirst(lc);
   10380             : 
   10381         368 :                 if (first)
   10382         264 :                     first = false;
   10383             :                 else
   10384         104 :                     appendStringInfoString(buf, ", ");
   10385         368 :                 appendStringInfoString(buf, quote_identifier(colname));
   10386             :             }
   10387         264 :             appendStringInfoChar(buf, ')');
   10388             :         }
   10389         360 :         else if (j->quals)
   10390             :         {
   10391         328 :             appendStringInfoString(buf, " ON ");
   10392         328 :             if (!PRETTY_PAREN(context))
   10393         324 :                 appendStringInfoChar(buf, '(');
   10394         328 :             get_rule_expr(j->quals, context, false);
   10395         328 :             if (!PRETTY_PAREN(context))
   10396         324 :                 appendStringInfoChar(buf, ')');
   10397             :         }
   10398          32 :         else if (j->jointype != JOIN_INNER)
   10399             :         {
   10400             :             /* If we didn't say CROSS JOIN above, we must provide an ON */
   10401           4 :             appendStringInfoString(buf, " ON TRUE");
   10402             :         }
   10403             : 
   10404         624 :         if (!PRETTY_PAREN(context) || j->alias != NULL)
   10405         412 :             appendStringInfoChar(buf, ')');
   10406             : 
   10407             :         /* Yes, it's correct to put alias after the right paren ... */
   10408         624 :         if (j->alias != NULL)
   10409             :         {
   10410             :             /*
   10411             :              * Note that it's correct to emit an alias clause if and only if
   10412             :              * there was one originally.  Otherwise we'd be converting a named
   10413             :              * join to unnamed or vice versa, which creates semantic
   10414             :              * subtleties we don't want.  However, we might print a different
   10415             :              * alias name than was there originally.
   10416             :              */
   10417          64 :             appendStringInfo(buf, " %s",
   10418          64 :                              quote_identifier(get_rtable_name(j->rtindex,
   10419             :                                                               context)));
   10420          64 :             get_column_alias_list(colinfo, context);
   10421             :         }
   10422             :     }
   10423             :     else
   10424           0 :         elog(ERROR, "unrecognized node type: %d",
   10425             :              (int) nodeTag(jtnode));
   10426        3250 : }
   10427             : 
   10428             : /*
   10429             :  * get_column_alias_list - print column alias list for an RTE
   10430             :  *
   10431             :  * Caller must already have printed the relation's alias name.
   10432             :  */
   10433             : static void
   10434        2690 : get_column_alias_list(deparse_columns *colinfo, deparse_context *context)
   10435             : {
   10436        2690 :     StringInfo  buf = context->buf;
   10437             :     int         i;
   10438        2690 :     bool        first = true;
   10439             : 
   10440             :     /* Don't print aliases if not needed */
   10441        2690 :     if (!colinfo->printaliases)
   10442        2230 :         return;
   10443             : 
   10444        3196 :     for (i = 0; i < colinfo->num_new_cols; i++)
   10445             :     {