LCOV - differential code coverage report
Current view: top level - src/backend/utils/adt - ruleutils.c (source / functions) Coverage Total Hit UNC UBC GBC GNC CBC DCB
Current: 4b3c9325757dfd8f2312e9f1a8decf4431f344ae vs e87b024bfb8dd55e3049b1b6e6ab4e810cf1abc8 Lines: 90.8 % 5453 4954 10 489 1 43 4910 12
Current Date: 2026-11-28 16:48:44 +0900 Functions: 99.4 % 174 173 1 9 164
Baseline: lcov-20261128-baseline Branches: 73.6 % 3992 2939 18 1035 1 26 2912
Baseline Date: 2026-11-28 16:48:48 +0900 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(7,30] days: 100.0 % 9 9 2 7
(30,360] days: 79.4 % 131 104 10 17 41 63
(360..) days: 91.1 % 5313 4841 472 1 4840
Function coverage date bins:
(30,360] days: 100.0 % 5 5 2 3
(360..) days: 99.4 % 169 168 1 7 161
Branch coverage date bins:
(7,30] days: 83.3 % 6 5 1 1 4
(30,360] days: 61.1 % 90 55 17 18 25 30
(360..) days: 73.9 % 3896 2879 1017 1 2878

 Age         Owner                    Branch data    TLA  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-2026, 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/table.h"
                                 26                 :                : #include "catalog/pg_aggregate.h"
                                 27                 :                : #include "catalog/pg_am.h"
                                 28                 :                : #include "catalog/pg_authid.h"
                                 29                 :                : #include "catalog/pg_collation.h"
                                 30                 :                : #include "catalog/pg_constraint.h"
                                 31                 :                : #include "catalog/pg_depend.h"
                                 32                 :                : #include "catalog/pg_language.h"
                                 33                 :                : #include "catalog/pg_opclass.h"
                                 34                 :                : #include "catalog/pg_operator.h"
                                 35                 :                : #include "catalog/pg_partitioned_table.h"
                                 36                 :                : #include "catalog/pg_proc.h"
                                 37                 :                : #include "catalog/pg_statistic_ext.h"
                                 38                 :                : #include "catalog/pg_trigger.h"
                                 39                 :                : #include "catalog/pg_type.h"
                                 40                 :                : #include "commands/defrem.h"
                                 41                 :                : #include "commands/tablespace.h"
                                 42                 :                : #include "common/keywords.h"
                                 43                 :                : #include "executor/spi.h"
                                 44                 :                : #include "funcapi.h"
                                 45                 :                : #include "mb/pg_wchar.h"
                                 46                 :                : #include "miscadmin.h"
                                 47                 :                : #include "nodes/makefuncs.h"
                                 48                 :                : #include "nodes/nodeFuncs.h"
                                 49                 :                : #include "nodes/pathnodes.h"
                                 50                 :                : #include "optimizer/optimizer.h"
                                 51                 :                : #include "parser/parse_agg.h"
                                 52                 :                : #include "parser/parse_func.h"
                                 53                 :                : #include "parser/parse_oper.h"
                                 54                 :                : #include "parser/parse_relation.h"
                                 55                 :                : #include "parser/parser.h"
                                 56                 :                : #include "parser/parsetree.h"
                                 57                 :                : #include "rewrite/rewriteHandler.h"
                                 58                 :                : #include "rewrite/rewriteManip.h"
                                 59                 :                : #include "rewrite/rewriteSupport.h"
                                 60                 :                : #include "utils/array.h"
                                 61                 :                : #include "utils/builtins.h"
                                 62                 :                : #include "utils/fmgroids.h"
                                 63                 :                : #include "utils/guc.h"
                                 64                 :                : #include "utils/hsearch.h"
                                 65                 :                : #include "utils/lsyscache.h"
                                 66                 :                : #include "utils/partcache.h"
                                 67                 :                : #include "utils/rel.h"
                                 68                 :                : #include "utils/ruleutils.h"
                                 69                 :                : #include "utils/snapmgr.h"
                                 70                 :                : #include "utils/syscache.h"
                                 71                 :                : #include "utils/typcache.h"
                                 72                 :                : #include "utils/varlena.h"
                                 73                 :                : #include "utils/xml.h"
                                 74                 :                : 
                                 75                 :                : /* ----------
                                 76                 :                :  * Pretty formatting constants
                                 77                 :                :  * ----------
                                 78                 :                :  */
                                 79                 :                : 
                                 80                 :                : /* Indent counts */
                                 81                 :                : #define PRETTYINDENT_STD        8
                                 82                 :                : #define PRETTYINDENT_JOIN       4
                                 83                 :                : #define PRETTYINDENT_VAR        4
                                 84                 :                : 
                                 85                 :                : #define PRETTYINDENT_LIMIT      40  /* wrap limit */
                                 86                 :                : 
                                 87                 :                : /* Pretty flags */
                                 88                 :                : #define PRETTYFLAG_PAREN        0x0001
                                 89                 :                : #define PRETTYFLAG_INDENT       0x0002
                                 90                 :                : #define PRETTYFLAG_SCHEMA       0x0004
                                 91                 :                : 
                                 92                 :                : /* Standard conversion of a "bool pretty" option to detailed flags */
                                 93                 :                : #define GET_PRETTY_FLAGS(pretty) \
                                 94                 :                :     ((pretty) ? (PRETTYFLAG_PAREN | PRETTYFLAG_INDENT | PRETTYFLAG_SCHEMA) \
                                 95                 :                :      : PRETTYFLAG_INDENT)
                                 96                 :                : 
                                 97                 :                : /* Default line length for pretty-print wrapping: 0 means wrap always */
                                 98                 :                : #define WRAP_COLUMN_DEFAULT     0
                                 99                 :                : 
                                100                 :                : /* macros to test if pretty action needed */
                                101                 :                : #define PRETTY_PAREN(context)   ((context)->prettyFlags & PRETTYFLAG_PAREN)
                                102                 :                : #define PRETTY_INDENT(context)  ((context)->prettyFlags & PRETTYFLAG_INDENT)
                                103                 :                : #define PRETTY_SCHEMA(context)  ((context)->prettyFlags & PRETTYFLAG_SCHEMA)
                                104                 :                : 
                                105                 :                : 
                                106                 :                : /* ----------
                                107                 :                :  * Local data types
                                108                 :                :  * ----------
                                109                 :                :  */
                                110                 :                : 
                                111                 :                : /* Context info needed for invoking a recursive querytree display routine */
                                112                 :                : typedef struct
                                113                 :                : {
                                114                 :                :     StringInfo  buf;            /* output buffer to append to */
                                115                 :                :     List       *namespaces;     /* List of deparse_namespace nodes */
                                116                 :                :     TupleDesc   resultDesc;     /* if top level of a view, the view's tupdesc */
                                117                 :                :     List       *targetList;     /* Current query level's SELECT targetlist */
                                118                 :                :     List       *windowClause;   /* Current query level's WINDOW clause */
                                119                 :                :     int         prettyFlags;    /* enabling of pretty-print functions */
                                120                 :                :     int         wrapColumn;     /* max line length, or -1 for no limit */
                                121                 :                :     int         indentLevel;    /* current indent level for pretty-print */
                                122                 :                :     bool        varprefix;      /* true to print prefixes on Vars */
                                123                 :                :     bool        colNamesVisible;    /* do we care about output column names? */
                                124                 :                :     bool        inGroupBy;      /* deparsing GROUP BY clause? */
                                125                 :                :     bool        varInOrderBy;   /* deparsing simple Var in ORDER BY? */
                                126                 :                :     Bitmapset  *appendparents;  /* if not null, map child Vars of these relids
                                127                 :                :                                  * back to the parent rel */
                                128                 :                : } deparse_context;
                                129                 :                : 
                                130                 :                : /*
                                131                 :                :  * Each level of query context around a subtree needs a level of Var namespace.
                                132                 :                :  * A Var having varlevelsup=N refers to the N'th item (counting from 0) in
                                133                 :                :  * the current context's namespaces list.
                                134                 :                :  *
                                135                 :                :  * rtable is the list of actual RTEs from the Query or PlannedStmt.
                                136                 :                :  * rtable_names holds the alias name to be used for each RTE (either a C
                                137                 :                :  * string, or NULL for nameless RTEs such as unnamed joins).
                                138                 :                :  * rtable_columns holds the column alias names to be used for each RTE.
                                139                 :                :  *
                                140                 :                :  * subplans is a list of Plan trees for SubPlans and CTEs (it's only used
                                141                 :                :  * in the PlannedStmt case).
                                142                 :                :  * ctes is a list of CommonTableExpr nodes (only used in the Query case).
                                143                 :                :  * appendrels, if not null (it's only used in the PlannedStmt case), is an
                                144                 :                :  * array of AppendRelInfo nodes, indexed by child relid.  We use that to map
                                145                 :                :  * child-table Vars to their inheritance parents.
                                146                 :                :  *
                                147                 :                :  * In some cases we need to make names of merged JOIN USING columns unique
                                148                 :                :  * across the whole query, not only per-RTE.  If so, unique_using is true
                                149                 :                :  * and using_names is a list of C strings representing names already assigned
                                150                 :                :  * to USING columns.
                                151                 :                :  *
                                152                 :                :  * When deparsing plan trees, there is always just a single item in the
                                153                 :                :  * deparse_namespace list (since a plan tree never contains Vars with
                                154                 :                :  * varlevelsup > 0).  We store the Plan node that is the immediate
                                155                 :                :  * parent of the expression to be deparsed, as well as a list of that
                                156                 :                :  * Plan's ancestors.  In addition, we store its outer and inner subplan nodes,
                                157                 :                :  * as well as their targetlists, and the index tlist if the current plan node
                                158                 :                :  * might contain INDEX_VAR Vars.  (These fields could be derived on-the-fly
                                159                 :                :  * from the current Plan node, but it seems notationally clearer to set them
                                160                 :                :  * up as separate fields.)
                                161                 :                :  */
                                162                 :                : typedef struct
                                163                 :                : {
                                164                 :                :     List       *rtable;         /* List of RangeTblEntry nodes */
                                165                 :                :     List       *rtable_names;   /* Parallel list of names for RTEs */
                                166                 :                :     List       *rtable_columns; /* Parallel list of deparse_columns structs */
                                167                 :                :     List       *subplans;       /* List of Plan trees for SubPlans */
                                168                 :                :     List       *ctes;           /* List of CommonTableExpr nodes */
                                169                 :                :     AppendRelInfo **appendrels; /* Array of AppendRelInfo nodes, or NULL */
                                170                 :                :     char       *ret_old_alias;  /* alias for OLD in RETURNING list */
                                171                 :                :     char       *ret_new_alias;  /* alias for NEW in RETURNING list */
                                172                 :                :     /* Workspace for column alias assignment: */
                                173                 :                :     bool        unique_using;   /* Are we making USING names globally unique */
                                174                 :                :     List       *using_names;    /* List of assigned names for USING columns */
                                175                 :                :     /* Remaining fields are used only when deparsing a Plan tree: */
                                176                 :                :     Plan       *plan;           /* immediate parent of current expression */
                                177                 :                :     List       *ancestors;      /* ancestors of plan */
                                178                 :                :     Plan       *outer_plan;     /* outer subnode, or NULL if none */
                                179                 :                :     Plan       *inner_plan;     /* inner subnode, or NULL if none */
                                180                 :                :     List       *outer_tlist;    /* referent for OUTER_VAR Vars */
                                181                 :                :     List       *inner_tlist;    /* referent for INNER_VAR Vars */
                                182                 :                :     List       *index_tlist;    /* referent for INDEX_VAR Vars */
                                183                 :                :     /* Special namespace representing a function signature: */
                                184                 :                :     char       *funcname;
                                185                 :                :     int         numargs;        /* number of input arguments */
                                186                 :                :     char      **argnames;       /* names of input args (NULL if unnamed) */
                                187                 :                : } deparse_namespace;
                                188                 :                : 
                                189                 :                : /*
                                190                 :                :  * Per-relation data about column alias names.
                                191                 :                :  *
                                192                 :                :  * Selecting aliases is unreasonably complicated because of the need to dump
                                193                 :                :  * rules/views whose underlying tables may have had columns added, deleted, or
                                194                 :                :  * renamed since the query was parsed.  We must nonetheless print the rule/view
                                195                 :                :  * in a form that can be reloaded and will produce the same results as before.
                                196                 :                :  *
                                197                 :                :  * For each RTE used in the query, we must assign column aliases that are
                                198                 :                :  * unique within that RTE.  SQL does not require this of the original query,
                                199                 :                :  * but due to factors such as *-expansion we need to be able to uniquely
                                200                 :                :  * reference every column in a decompiled query.  As long as we qualify all
                                201                 :                :  * column references, per-RTE uniqueness is sufficient for that.
                                202                 :                :  *
                                203                 :                :  * However, we can't ensure per-column name uniqueness for unnamed join RTEs,
                                204                 :                :  * since they just inherit column names from their input RTEs, and we can't
                                205                 :                :  * rename the columns at the join level.  Most of the time this isn't an issue
                                206                 :                :  * because we don't need to reference the join's output columns as such; we
                                207                 :                :  * can reference the input columns instead.  That approach can fail for merged
                                208                 :                :  * JOIN USING columns, however, so when we have one of those in an unnamed
                                209                 :                :  * join, we have to make that column's alias globally unique across the whole
                                210                 :                :  * query to ensure it can be referenced unambiguously.
                                211                 :                :  *
                                212                 :                :  * Another problem is that a JOIN USING clause requires the columns to be
                                213                 :                :  * merged to have the same aliases in both input RTEs, and that no other
                                214                 :                :  * columns in those RTEs or their children conflict with the USING names.
                                215                 :                :  * To handle that, we do USING-column alias assignment in a recursive
                                216                 :                :  * traversal of the query's jointree.  When descending through a JOIN with
                                217                 :                :  * USING, we preassign the USING column names to the child columns, overriding
                                218                 :                :  * other rules for column alias assignment.  We also mark each RTE with a list
                                219                 :                :  * of all USING column names selected for joins containing that RTE, so that
                                220                 :                :  * when we assign other columns' aliases later, we can avoid conflicts.
                                221                 :                :  *
                                222                 :                :  * Another problem is that if a JOIN's input tables have had columns added or
                                223                 :                :  * deleted since the query was parsed, we must generate a column alias list
                                224                 :                :  * for the join that matches the current set of input columns --- otherwise, a
                                225                 :                :  * change in the number of columns in the left input would throw off matching
                                226                 :                :  * of aliases to columns of the right input.  Thus, positions in the printable
                                227                 :                :  * column alias list are not necessarily one-for-one with varattnos of the
                                228                 :                :  * JOIN, so we need a separate new_colnames[] array for printing purposes.
                                229                 :                :  *
                                230                 :                :  * Finally, when dealing with wide tables we risk O(N^2) costs in assigning
                                231                 :                :  * non-duplicate column names.  We ameliorate that by using a hash table that
                                232                 :                :  * holds all the strings appearing in colnames, new_colnames, and parentUsing.
                                233                 :                :  */
                                234                 :                : typedef struct
                                235                 :                : {
                                236                 :                :     /*
                                237                 :                :      * colnames is an array containing column aliases to use for columns that
                                238                 :                :      * existed when the query was parsed.  Dropped columns have NULL entries.
                                239                 :                :      * This array can be directly indexed by varattno to get a Var's name.
                                240                 :                :      *
                                241                 :                :      * Non-NULL entries are guaranteed unique within the RTE, *except* when
                                242                 :                :      * this is for an unnamed JOIN RTE.  In that case we merely copy up names
                                243                 :                :      * from the two input RTEs.
                                244                 :                :      *
                                245                 :                :      * During the recursive descent in set_using_names(), forcible assignment
                                246                 :                :      * of a child RTE's column name is represented by pre-setting that element
                                247                 :                :      * of the child's colnames array.  So at that stage, NULL entries in this
                                248                 :                :      * array just mean that no name has been preassigned, not necessarily that
                                249                 :                :      * the column is dropped.
                                250                 :                :      */
                                251                 :                :     int         num_cols;       /* length of colnames[] array */
                                252                 :                :     char      **colnames;       /* array of C strings and NULLs */
                                253                 :                : 
                                254                 :                :     /*
                                255                 :                :      * new_colnames is an array containing column aliases to use for columns
                                256                 :                :      * that would exist if the query was re-parsed against the current
                                257                 :                :      * definitions of its base tables.  This is what to print as the column
                                258                 :                :      * alias list for the RTE.  This array does not include dropped columns,
                                259                 :                :      * but it will include columns added since original parsing.  Indexes in
                                260                 :                :      * it therefore have little to do with current varattno values.  As above,
                                261                 :                :      * entries are unique unless this is for an unnamed JOIN RTE.  (In such an
                                262                 :                :      * RTE, we never actually print this array, but we must compute it anyway
                                263                 :                :      * for possible use in computing column names of upper joins.) The
                                264                 :                :      * parallel array is_new_col marks which of these columns are new since
                                265                 :                :      * original parsing.  Entries with is_new_col false must match the
                                266                 :                :      * non-NULL colnames entries one-for-one.
                                267                 :                :      */
                                268                 :                :     int         num_new_cols;   /* length of new_colnames[] array */
                                269                 :                :     char      **new_colnames;   /* array of C strings */
                                270                 :                :     bool       *is_new_col;     /* array of bool flags */
                                271                 :                : 
                                272                 :                :     /* This flag tells whether we should actually print a column alias list */
                                273                 :                :     bool        printaliases;
                                274                 :                : 
                                275                 :                :     /* This list has all names used as USING names in joins above this RTE */
                                276                 :                :     List       *parentUsing;    /* names assigned to parent merged columns */
                                277                 :                : 
                                278                 :                :     /*
                                279                 :                :      * If this struct is for a JOIN RTE, we fill these fields during the
                                280                 :                :      * set_using_names() pass to describe its relationship to its child RTEs.
                                281                 :                :      *
                                282                 :                :      * leftattnos and rightattnos are arrays with one entry per existing
                                283                 :                :      * output column of the join (hence, indexable by join varattno).  For a
                                284                 :                :      * simple reference to a column of the left child, leftattnos[i] is the
                                285                 :                :      * child RTE's attno and rightattnos[i] is zero; and conversely for a
                                286                 :                :      * column of the right child.  But for merged columns produced by JOIN
                                287                 :                :      * USING/NATURAL JOIN, both leftattnos[i] and rightattnos[i] are nonzero.
                                288                 :                :      * Note that a simple reference might be to a child RTE column that's been
                                289                 :                :      * dropped; but that's OK since the column could not be used in the query.
                                290                 :                :      *
                                291                 :                :      * If it's a JOIN USING, usingNames holds the alias names selected for the
                                292                 :                :      * merged columns (these might be different from the original USING list,
                                293                 :                :      * if we had to modify names to achieve uniqueness).
                                294                 :                :      */
                                295                 :                :     int         leftrti;        /* rangetable index of left child */
                                296                 :                :     int         rightrti;       /* rangetable index of right child */
                                297                 :                :     int        *leftattnos;     /* left-child varattnos of join cols, or 0 */
                                298                 :                :     int        *rightattnos;    /* right-child varattnos of join cols, or 0 */
                                299                 :                :     List       *usingNames;     /* names assigned to merged columns */
                                300                 :                : 
                                301                 :                :     /*
                                302                 :                :      * Hash table holding copies of all the strings appearing in this struct's
                                303                 :                :      * colnames, new_colnames, and parentUsing.  We use a hash table only for
                                304                 :                :      * sufficiently wide relations, and only during the colname-assignment
                                305                 :                :      * functions set_relation_column_names and set_join_column_names;
                                306                 :                :      * otherwise, names_hash is NULL.
                                307                 :                :      */
                                308                 :                :     HTAB       *names_hash;     /* entries are just strings */
                                309                 :                : } deparse_columns;
                                310                 :                : 
                                311                 :                : /* This macro is analogous to rt_fetch(), but for deparse_columns structs */
                                312                 :                : #define deparse_columns_fetch(rangetable_index, dpns) \
                                313                 :                :     ((deparse_columns *) list_nth((dpns)->rtable_columns, (rangetable_index)-1))
                                314                 :                : 
                                315                 :                : /*
                                316                 :                :  * Entry in set_rtable_names' hash table
                                317                 :                :  */
                                318                 :                : typedef struct
                                319                 :                : {
                                320                 :                :     char        name[NAMEDATALEN];  /* Hash key --- must be first */
                                321                 :                :     int         counter;        /* Largest addition used so far for name */
                                322                 :                : } NameHashEntry;
                                323                 :                : 
                                324                 :                : /* Callback signature for resolve_special_varno() */
                                325                 :                : typedef void (*rsv_callback) (Node *node, deparse_context *context,
                                326                 :                :                               void *callback_arg);
                                327                 :                : 
                                328                 :                : 
                                329                 :                : /* ----------
                                330                 :                :  * Global data
                                331                 :                :  * ----------
                                332                 :                :  */
                                333                 :                : static SPIPlanPtr plan_getrulebyoid = NULL;
                                334                 :                : static const char *const query_getrulebyoid = "SELECT * FROM pg_catalog.pg_rewrite WHERE oid = $1";
                                335                 :                : static SPIPlanPtr plan_getviewrule = NULL;
                                336                 :                : static const char *const query_getviewrule = "SELECT * FROM pg_catalog.pg_rewrite WHERE ev_class = $1 AND rulename = $2";
                                337                 :                : 
                                338                 :                : /* GUC parameters */
                                339                 :                : bool        quote_all_identifiers = false;
                                340                 :                : 
                                341                 :                : 
                                342                 :                : /* ----------
                                343                 :                :  * Local functions
                                344                 :                :  *
                                345                 :                :  * Most of these functions used to use fixed-size buffers to build their
                                346                 :                :  * results.  Now, they take an (already initialized) StringInfo object
                                347                 :                :  * as a parameter, and append their text output to its contents.
                                348                 :                :  * ----------
                                349                 :                :  */
                                350                 :                : static char *deparse_expression_pretty(Node *expr, List *dpcontext,
                                351                 :                :                                        bool forceprefix, bool showimplicit,
                                352                 :                :                                        int prettyFlags, int startIndent);
                                353                 :                : static char *pg_get_viewdef_worker(Oid viewoid,
                                354                 :                :                                    int prettyFlags, int wrapColumn);
                                355                 :                : static char *pg_get_triggerdef_worker(Oid trigid, bool pretty);
                                356                 :                : static int  decompile_column_index_array(Datum column_index_array, Oid relId,
                                357                 :                :                                          bool withPeriod, StringInfo buf);
                                358                 :                : static char *pg_get_ruledef_worker(Oid ruleoid, int prettyFlags);
                                359                 :                : static char *pg_get_indexdef_worker(Oid indexrelid, int colno,
                                360                 :                :                                     const Oid *excludeOps,
                                361                 :                :                                     bool attrsOnly, bool keysOnly,
                                362                 :                :                                     bool showTblSpc, bool inherits,
                                363                 :                :                                     int prettyFlags, bool missing_ok);
                                364                 :                : static char *pg_get_statisticsobj_worker(Oid statextid, bool columns_only,
                                365                 :                :                                          bool missing_ok);
                                366                 :                : static char *pg_get_partkeydef_worker(Oid relid, int prettyFlags,
                                367                 :                :                                       bool attrsOnly, bool missing_ok);
                                368                 :                : static char *pg_get_constraintdef_worker(Oid constraintId, bool fullCommand,
                                369                 :                :                                          int prettyFlags, bool missing_ok);
                                370                 :                : static text *pg_get_expr_worker(text *expr, Oid relid, int prettyFlags);
                                371                 :                : static int  print_function_arguments(StringInfo buf, HeapTuple proctup,
                                372                 :                :                                      bool print_table_args, bool print_defaults);
                                373                 :                : static void print_function_rettype(StringInfo buf, HeapTuple proctup);
                                374                 :                : static void print_function_trftypes(StringInfo buf, HeapTuple proctup);
                                375                 :                : static void print_function_sqlbody(StringInfo buf, HeapTuple proctup);
                                376                 :                : static void set_rtable_names(deparse_namespace *dpns, List *parent_namespaces,
                                377                 :                :                              Bitmapset *rels_used);
                                378                 :                : static void set_deparse_for_query(deparse_namespace *dpns, Query *query,
                                379                 :                :                                   List *parent_namespaces);
                                380                 :                : static void set_simple_column_names(deparse_namespace *dpns);
                                381                 :                : static bool has_dangerous_join_using(deparse_namespace *dpns, Node *jtnode);
                                382                 :                : static void set_using_names(deparse_namespace *dpns, Node *jtnode,
                                383                 :                :                             List *parentUsing);
                                384                 :                : static void set_relation_column_names(deparse_namespace *dpns,
                                385                 :                :                                       RangeTblEntry *rte,
                                386                 :                :                                       deparse_columns *colinfo);
                                387                 :                : static void set_join_column_names(deparse_namespace *dpns, RangeTblEntry *rte,
                                388                 :                :                                   deparse_columns *colinfo);
                                389                 :                : static bool colname_is_unique(const char *colname, deparse_namespace *dpns,
                                390                 :                :                               deparse_columns *colinfo);
                                391                 :                : static char *make_colname_unique(char *colname, deparse_namespace *dpns,
                                392                 :                :                                  deparse_columns *colinfo);
                                393                 :                : static void expand_colnames_array_to(deparse_columns *colinfo, int n);
                                394                 :                : static void build_colinfo_names_hash(deparse_columns *colinfo);
                                395                 :                : static void add_to_names_hash(deparse_columns *colinfo, const char *name);
                                396                 :                : static void destroy_colinfo_names_hash(deparse_columns *colinfo);
                                397                 :                : static void identify_join_columns(JoinExpr *j, RangeTblEntry *jrte,
                                398                 :                :                                   deparse_columns *colinfo);
                                399                 :                : static char *get_rtable_name(int rtindex, deparse_context *context);
                                400                 :                : static void set_deparse_plan(deparse_namespace *dpns, Plan *plan);
                                401                 :                : static Plan *find_recursive_union(deparse_namespace *dpns,
                                402                 :                :                                   WorkTableScan *wtscan);
                                403                 :                : static void push_child_plan(deparse_namespace *dpns, Plan *plan,
                                404                 :                :                             deparse_namespace *save_dpns);
                                405                 :                : static void pop_child_plan(deparse_namespace *dpns,
                                406                 :                :                            deparse_namespace *save_dpns);
                                407                 :                : static void push_ancestor_plan(deparse_namespace *dpns, ListCell *ancestor_cell,
                                408                 :                :                                deparse_namespace *save_dpns);
                                409                 :                : static void pop_ancestor_plan(deparse_namespace *dpns,
                                410                 :                :                               deparse_namespace *save_dpns);
                                411                 :                : static void make_ruledef(StringInfo buf, HeapTuple ruletup, TupleDesc rulettc,
                                412                 :                :                          int prettyFlags);
                                413                 :                : static void make_viewdef(StringInfo buf, HeapTuple ruletup, TupleDesc rulettc,
                                414                 :                :                          int prettyFlags, int wrapColumn);
                                415                 :                : static void get_query_def(Query *query, StringInfo buf, List *parentnamespace,
                                416                 :                :                           TupleDesc resultDesc, bool colNamesVisible,
                                417                 :                :                           int prettyFlags, int wrapColumn, int startIndent);
                                418                 :                : static void get_values_def(List *values_lists, deparse_context *context);
                                419                 :                : static void get_with_clause(Query *query, deparse_context *context);
                                420                 :                : static void get_select_query_def(Query *query, deparse_context *context);
                                421                 :                : static void get_insert_query_def(Query *query, deparse_context *context);
                                422                 :                : static void get_update_query_def(Query *query, deparse_context *context);
                                423                 :                : static void get_update_query_targetlist_def(Query *query, List *targetList,
                                424                 :                :                                             deparse_context *context,
                                425                 :                :                                             RangeTblEntry *rte);
                                426                 :                : static void get_delete_query_def(Query *query, deparse_context *context);
                                427                 :                : static void get_merge_query_def(Query *query, deparse_context *context);
                                428                 :                : static void get_utility_query_def(Query *query, deparse_context *context);
                                429                 :                : static char *get_lock_clause_strength(LockClauseStrength strength);
                                430                 :                : static void get_basic_select_query(Query *query, deparse_context *context);
                                431                 :                : static void get_target_list(List *targetList, deparse_context *context);
                                432                 :                : static void get_returning_clause(Query *query, deparse_context *context);
                                433                 :                : static void get_setop_query(Node *setOp, Query *query,
                                434                 :                :                             deparse_context *context);
                                435                 :                : static Node *get_rule_sortgroupclause(Index ref, List *tlist,
                                436                 :                :                                       bool force_colno,
                                437                 :                :                                       deparse_context *context);
                                438                 :                : static void get_rule_groupingset(GroupingSet *gset, List *targetlist,
                                439                 :                :                                  bool omit_parens, deparse_context *context);
                                440                 :                : static void get_rule_orderby(List *orderList, List *targetList,
                                441                 :                :                              bool force_colno, deparse_context *context);
                                442                 :                : static void get_rule_windowclause(Query *query, deparse_context *context);
                                443                 :                : static void get_rule_windowspec(WindowClause *wc, List *targetList,
                                444                 :                :                                 deparse_context *context);
                                445                 :                : static void get_window_frame_options(int frameOptions,
                                446                 :                :                                      Node *startOffset, Node *endOffset,
                                447                 :                :                                      deparse_context *context);
                                448                 :                : static char *get_variable(Var *var, int levelsup, bool istoplevel,
                                449                 :                :                           deparse_context *context);
                                450                 :                : static void get_special_variable(Node *node, deparse_context *context,
                                451                 :                :                                  void *callback_arg);
                                452                 :                : static void resolve_special_varno(Node *node, deparse_context *context,
                                453                 :                :                                   rsv_callback callback, void *callback_arg);
                                454                 :                : static Node *find_param_referent(Param *param, deparse_context *context,
                                455                 :                :                                  deparse_namespace **dpns_p, ListCell **ancestor_cell_p);
                                456                 :                : static SubPlan *find_param_generator(Param *param, deparse_context *context,
                                457                 :                :                                      int *column_p);
                                458                 :                : static SubPlan *find_param_generator_initplan(Param *param, Plan *plan,
                                459                 :                :                                               int *column_p);
                                460                 :                : static void get_parameter(Param *param, deparse_context *context);
                                461                 :                : static const char *get_simple_binary_op_name(OpExpr *expr);
                                462                 :                : static bool isSimpleNode(Node *node, Node *parentNode, int prettyFlags);
                                463                 :                : static void appendContextKeyword(deparse_context *context, const char *str,
                                464                 :                :                                  int indentBefore, int indentAfter, int indentPlus);
                                465                 :                : static void removeStringInfoSpaces(StringInfo str);
                                466                 :                : static void get_rule_expr(Node *node, deparse_context *context,
                                467                 :                :                           bool showimplicit);
                                468                 :                : static void get_rule_expr_toplevel(Node *node, deparse_context *context,
                                469                 :                :                                    bool showimplicit);
                                470                 :                : static void get_rule_list_toplevel(List *lst, deparse_context *context,
                                471                 :                :                                    bool showimplicit);
                                472                 :                : static void get_rule_expr_funccall(Node *node, deparse_context *context,
                                473                 :                :                                    bool showimplicit);
                                474                 :                : static bool looks_like_function(Node *node);
                                475                 :                : static void get_oper_expr(OpExpr *expr, deparse_context *context);
                                476                 :                : static void get_func_expr(FuncExpr *expr, deparse_context *context,
                                477                 :                :                           bool showimplicit);
                                478                 :                : static void get_agg_expr(Aggref *aggref, deparse_context *context,
                                479                 :                :                          Aggref *original_aggref);
                                480                 :                : static void get_agg_expr_helper(Aggref *aggref, deparse_context *context,
                                481                 :                :                                 Aggref *original_aggref, const char *funcname,
                                482                 :                :                                 const char *options, bool is_json_objectagg);
                                483                 :                : static void get_agg_combine_expr(Node *node, deparse_context *context,
                                484                 :                :                                  void *callback_arg);
                                485                 :                : static void get_windowfunc_expr(WindowFunc *wfunc, deparse_context *context);
                                486                 :                : static void get_windowfunc_expr_helper(WindowFunc *wfunc, deparse_context *context,
                                487                 :                :                                        const char *funcname, const char *options,
                                488                 :                :                                        bool is_json_objectagg);
                                489                 :                : static bool get_func_sql_syntax(FuncExpr *expr, deparse_context *context);
                                490                 :                : static void get_coercion_expr(Node *arg, deparse_context *context,
                                491                 :                :                               Oid resulttype, int32 resulttypmod,
                                492                 :                :                               Node *parentNode);
                                493                 :                : static void get_const_expr(Const *constval, deparse_context *context,
                                494                 :                :                            int showtype);
                                495                 :                : static void get_const_collation(Const *constval, deparse_context *context);
                                496                 :                : static void get_json_format(JsonFormat *format, StringInfo buf);
                                497                 :                : static void get_json_returning(JsonReturning *returning, StringInfo buf,
                                498                 :                :                                bool json_format_by_default);
                                499                 :                : static void get_json_constructor(JsonConstructorExpr *ctor,
                                500                 :                :                                  deparse_context *context, bool showimplicit);
                                501                 :                : static void get_json_constructor_options(JsonConstructorExpr *ctor,
                                502                 :                :                                          StringInfo buf);
                                503                 :                : static void get_json_agg_constructor(JsonConstructorExpr *ctor,
                                504                 :                :                                      deparse_context *context,
                                505                 :                :                                      const char *funcname,
                                506                 :                :                                      bool is_json_objectagg);
                                507                 :                : static void get_json_agg_constructor_expr(Node *node, deparse_context *context,
                                508                 :                :                                           void *callback_arg);
                                509                 :                : static void simple_quote_literal(StringInfo buf, const char *val);
                                510                 :                : static void get_sublink_expr(SubLink *sublink, deparse_context *context);
                                511                 :                : static void get_tablefunc(TableFunc *tf, deparse_context *context,
                                512                 :                :                           bool showimplicit);
                                513                 :                : static void get_from_clause(Query *query, const char *prefix,
                                514                 :                :                             deparse_context *context);
                                515                 :                : static void get_from_clause_item(Node *jtnode, Query *query,
                                516                 :                :                                  deparse_context *context);
                                517                 :                : static void get_rte_alias(RangeTblEntry *rte, int varno, bool use_as,
                                518                 :                :                           deparse_context *context);
                                519                 :                : static void get_column_alias_list(deparse_columns *colinfo,
                                520                 :                :                                   deparse_context *context);
                                521                 :                : static void get_from_clause_coldeflist(RangeTblFunction *rtfunc,
                                522                 :                :                                        deparse_columns *colinfo,
                                523                 :                :                                        deparse_context *context);
                                524                 :                : static void get_tablesample_def(TableSampleClause *tablesample,
                                525                 :                :                                 deparse_context *context);
                                526                 :                : static void get_opclass_name(Oid opclass, Oid actual_datatype,
                                527                 :                :                              StringInfo buf);
                                528                 :                : static Node *processIndirection(Node *node, deparse_context *context);
                                529                 :                : static void printSubscripts(SubscriptingRef *sbsref, deparse_context *context);
                                530                 :                : static char *get_relation_name(Oid relid);
                                531                 :                : static char *generate_relation_name(Oid relid, List *namespaces);
                                532                 :                : static char *generate_qualified_relation_name(Oid relid);
                                533                 :                : static char *generate_function_name(Oid funcid, int nargs,
                                534                 :                :                                     List *argnames, Oid *argtypes,
                                535                 :                :                                     bool has_variadic, bool *use_variadic_p,
                                536                 :                :                                     bool inGroupBy);
                                537                 :                : static char *generate_operator_name(Oid operid, Oid arg1, Oid arg2);
                                538                 :                : static void add_cast_to(StringInfo buf, Oid typid);
                                539                 :                : static char *generate_qualified_type_name(Oid typid);
                                540                 :                : static text *string_to_text(char *str);
                                541                 :                : static char *flatten_reloptions(Oid relid);
                                542                 :                : void        get_reloptions(StringInfo buf, Datum reloptions);
                                543                 :                : static void get_json_path_spec(Node *path_spec, deparse_context *context,
                                544                 :                :                                bool showimplicit);
                                545                 :                : static void get_json_table_columns(TableFunc *tf, JsonTablePathScan *scan,
                                546                 :                :                                    deparse_context *context,
                                547                 :                :                                    bool showimplicit);
                                548                 :                : static void get_json_table_nested_columns(TableFunc *tf, JsonTablePlan *plan,
                                549                 :                :                                           deparse_context *context,
                                550                 :                :                                           bool showimplicit,
                                551                 :                :                                           bool needcomma);
                                552                 :                : 
                                553                 :                : #define only_marker(rte)  ((rte)->inh ? "" : "ONLY ")
                                554                 :                : 
                                555                 :                : 
                                556                 :                : /* ----------
                                557                 :                :  * pg_get_ruledef       - Do it all and return a text
                                558                 :                :  *                that could be used as a statement
                                559                 :                :  *                to recreate the rule
                                560                 :                :  * ----------
                                561                 :                :  */
                                562                 :                : Datum
 9641 tgl@sss.pgh.pa.us         563                 :CBC         237 : pg_get_ruledef(PG_FUNCTION_ARGS)
                                564                 :                : {
 8990                           565                 :            237 :     Oid         ruleoid = PG_GETARG_OID(0);
                                566                 :                :     int         prettyFlags;
                                567                 :                :     char       *res;
                                568                 :                : 
 5046                           569                 :            237 :     prettyFlags = PRETTYFLAG_INDENT;
                                570                 :                : 
 3777 rhaas@postgresql.org      571                 :            237 :     res = pg_get_ruledef_worker(ruleoid, prettyFlags);
                                572                 :                : 
                                573         [ +  + ]:            237 :     if (res == NULL)
                                574                 :              4 :         PG_RETURN_NULL();
                                575                 :                : 
                                576                 :            233 :     PG_RETURN_TEXT_P(string_to_text(res));
                                577                 :                : }
                                578                 :                : 
                                579                 :                : 
                                580                 :                : Datum
 8522 tgl@sss.pgh.pa.us         581                 :             80 : pg_get_ruledef_ext(PG_FUNCTION_ARGS)
                                582                 :                : {
                                583                 :             80 :     Oid         ruleoid = PG_GETARG_OID(0);
                                584                 :             80 :     bool        pretty = PG_GETARG_BOOL(1);
                                585                 :                :     int         prettyFlags;
                                586                 :                :     char       *res;
                                587                 :                : 
 1706                           588         [ +  - ]:             80 :     prettyFlags = GET_PRETTY_FLAGS(pretty);
                                589                 :                : 
 3777 rhaas@postgresql.org      590                 :             80 :     res = pg_get_ruledef_worker(ruleoid, prettyFlags);
                                591                 :                : 
                                592         [ -  + ]:             80 :     if (res == NULL)
 3777 rhaas@postgresql.org      593                 :UBC           0 :         PG_RETURN_NULL();
                                594                 :                : 
 3777 rhaas@postgresql.org      595                 :CBC          80 :     PG_RETURN_TEXT_P(string_to_text(res));
                                596                 :                : }
                                597                 :                : 
                                598                 :                : 
                                599                 :                : static char *
 8522 tgl@sss.pgh.pa.us         600                 :            317 : pg_get_ruledef_worker(Oid ruleoid, int prettyFlags)
                                601                 :                : {
                                602                 :                :     Datum       args[1];
                                603                 :                :     char        nulls[1];
                                604                 :                :     int         spirc;
                                605                 :                :     HeapTuple   ruletup;
                                606                 :                :     TupleDesc   rulettc;
                                607                 :                :     StringInfoData buf;
                                608                 :                : 
                                609                 :                :     /*
                                610                 :                :      * Do this first so that string is alloc'd in outer context not SPI's.
                                611                 :                :      */
 8242                           612                 :            317 :     initStringInfo(&buf);
                                613                 :                : 
                                614                 :                :     /*
                                615                 :                :      * Connect to SPI manager
                                616                 :                :      */
  810                           617                 :            317 :     SPI_connect();
                                618                 :                : 
                                619                 :                :     /*
                                620                 :                :      * On the first call prepare the plan to lookup pg_rewrite. We read
                                621                 :                :      * pg_rewrite over the SPI manager instead of using the syscache to be
                                622                 :                :      * checked for read access on pg_rewrite.
                                623                 :                :      */
 8990                           624         [ +  + ]:            317 :     if (plan_getrulebyoid == NULL)
                                625                 :                :     {
                                626                 :                :         Oid         argtypes[1];
                                627                 :                :         SPIPlanPtr  plan;
                                628                 :                : 
                                629                 :             24 :         argtypes[0] = OIDOID;
                                630                 :             24 :         plan = SPI_prepare(query_getrulebyoid, 1, argtypes);
10315 bruce@momjian.us          631         [ -  + ]:             24 :         if (plan == NULL)
 8525 tgl@sss.pgh.pa.us         632         [ #  # ]:UBC           0 :             elog(ERROR, "SPI_prepare failed for \"%s\"", query_getrulebyoid);
 5552 tgl@sss.pgh.pa.us         633                 :CBC          24 :         SPI_keepplan(plan);
                                634                 :             24 :         plan_getrulebyoid = plan;
                                635                 :                :     }
                                636                 :                : 
                                637                 :                :     /*
                                638                 :                :      * Get the pg_rewrite tuple for this rule
                                639                 :                :      */
 8990                           640                 :            317 :     args[0] = ObjectIdGetDatum(ruleoid);
                                641                 :            317 :     nulls[0] = ' ';
 4753 peter_e@gmx.net           642                 :            317 :     spirc = SPI_execute_plan(plan_getrulebyoid, args, nulls, true, 0);
10315 bruce@momjian.us          643         [ -  + ]:            317 :     if (spirc != SPI_OK_SELECT)
 8525 tgl@sss.pgh.pa.us         644         [ #  # ]:UBC           0 :         elog(ERROR, "failed to get pg_rewrite tuple for rule %u", ruleoid);
10315 bruce@momjian.us          645         [ +  + ]:CBC         317 :     if (SPI_processed != 1)
                                646                 :                :     {
                                647                 :                :         /*
                                648                 :                :          * There is no tuple data available here, just keep the output buffer
                                649                 :                :          * empty.
                                650                 :                :          */
                                651                 :                :     }
                                652                 :                :     else
                                653                 :                :     {
                                654                 :                :         /*
                                655                 :                :          * Get the rule's definition and put it into executor's memory
                                656                 :                :          */
 8242 tgl@sss.pgh.pa.us         657                 :            313 :         ruletup = SPI_tuptable->vals[0];
                                658                 :            313 :         rulettc = SPI_tuptable->tupdesc;
                                659                 :            313 :         make_ruledef(&buf, ruletup, rulettc, prettyFlags);
                                660                 :                :     }
                                661                 :                : 
                                662                 :                :     /*
                                663                 :                :      * Disconnect from SPI manager
                                664                 :                :      */
10315 bruce@momjian.us          665         [ -  + ]:            317 :     if (SPI_finish() != SPI_OK_FINISH)
 8525 tgl@sss.pgh.pa.us         666         [ #  # ]:UBC           0 :         elog(ERROR, "SPI_finish failed");
                                667                 :                : 
 3777 rhaas@postgresql.org      668         [ +  + ]:CBC         317 :     if (buf.len == 0)
                                669                 :              4 :         return NULL;
                                670                 :                : 
 8242 tgl@sss.pgh.pa.us         671                 :            313 :     return buf.data;
                                672                 :                : }
                                673                 :                : 
                                674                 :                : 
                                675                 :                : /* ----------
                                676                 :                :  * pg_get_viewdef       - Mainly the same thing, but we
                                677                 :                :  *                only return the SELECT part of a view
                                678                 :                :  * ----------
                                679                 :                :  */
                                680                 :                : Datum
 9641                           681                 :           1442 : pg_get_viewdef(PG_FUNCTION_ARGS)
                                682                 :                : {
                                683                 :                :     /* By OID */
 8990                           684                 :           1442 :     Oid         viewoid = PG_GETARG_OID(0);
                                685                 :                :     int         prettyFlags;
                                686                 :                :     char       *res;
                                687                 :                : 
 5046                           688                 :           1442 :     prettyFlags = PRETTYFLAG_INDENT;
                                689                 :                : 
 3777 rhaas@postgresql.org      690                 :           1442 :     res = pg_get_viewdef_worker(viewoid, prettyFlags, WRAP_COLUMN_DEFAULT);
                                691                 :                : 
                                692         [ +  + ]:           1442 :     if (res == NULL)
                                693                 :              4 :         PG_RETURN_NULL();
                                694                 :                : 
                                695                 :           1438 :     PG_RETURN_TEXT_P(string_to_text(res));
                                696                 :                : }
                                697                 :                : 
                                698                 :                : 
                                699                 :                : Datum
 8522 tgl@sss.pgh.pa.us         700                 :            407 : pg_get_viewdef_ext(PG_FUNCTION_ARGS)
                                701                 :                : {
                                702                 :                :     /* By OID */
                                703                 :            407 :     Oid         viewoid = PG_GETARG_OID(0);
                                704                 :            407 :     bool        pretty = PG_GETARG_BOOL(1);
                                705                 :                :     int         prettyFlags;
                                706                 :                :     char       *res;
                                707                 :                : 
 1706                           708         [ +  - ]:            407 :     prettyFlags = GET_PRETTY_FLAGS(pretty);
                                709                 :                : 
 3777 rhaas@postgresql.org      710                 :            407 :     res = pg_get_viewdef_worker(viewoid, prettyFlags, WRAP_COLUMN_DEFAULT);
                                711                 :                : 
                                712         [ -  + ]:            407 :     if (res == NULL)
 3777 rhaas@postgresql.org      713                 :UBC           0 :         PG_RETURN_NULL();
                                714                 :                : 
 3777 rhaas@postgresql.org      715                 :CBC         407 :     PG_RETURN_TEXT_P(string_to_text(res));
                                716                 :                : }
                                717                 :                : 
                                718                 :                : Datum
 5396 andrew@dunslane.net       719                 :              4 : pg_get_viewdef_wrap(PG_FUNCTION_ARGS)
                                720                 :                : {
                                721                 :                :     /* By OID */
                                722                 :              4 :     Oid         viewoid = PG_GETARG_OID(0);
 5284 bruce@momjian.us          723                 :              4 :     int         wrap = PG_GETARG_INT32(1);
                                724                 :                :     int         prettyFlags;
                                725                 :                :     char       *res;
                                726                 :                : 
                                727                 :                :     /* calling this implies we want pretty printing */
 1706 tgl@sss.pgh.pa.us         728                 :              4 :     prettyFlags = GET_PRETTY_FLAGS(true);
                                729                 :                : 
 3777 rhaas@postgresql.org      730                 :              4 :     res = pg_get_viewdef_worker(viewoid, prettyFlags, wrap);
                                731                 :                : 
                                732         [ -  + ]:              4 :     if (res == NULL)
 3777 rhaas@postgresql.org      733                 :UBC           0 :         PG_RETURN_NULL();
                                734                 :                : 
 3777 rhaas@postgresql.org      735                 :CBC           4 :     PG_RETURN_TEXT_P(string_to_text(res));
                                736                 :                : }
                                737                 :                : 
                                738                 :                : Datum
 8990 tgl@sss.pgh.pa.us         739                 :             52 : pg_get_viewdef_name(PG_FUNCTION_ARGS)
                                740                 :                : {
                                741                 :                :     /* By qualified name */
 3548 noah@leadboat.com         742                 :             52 :     text       *viewname = PG_GETARG_TEXT_PP(0);
                                743                 :                :     int         prettyFlags;
                                744                 :                :     RangeVar   *viewrel;
                                745                 :                :     Oid         viewoid;
                                746                 :                :     char       *res;
                                747                 :                : 
 5046 tgl@sss.pgh.pa.us         748                 :             52 :     prettyFlags = PRETTYFLAG_INDENT;
                                749                 :                : 
                                750                 :                :     /* Look up view name.  Can't lock it - we might not have privileges. */
 7855 neilc@samurai.com         751                 :             52 :     viewrel = makeRangeVarFromNameList(textToQualifiedNameList(viewname));
 5477 rhaas@postgresql.org      752                 :             52 :     viewoid = RangeVarGetRelid(viewrel, NoLock, false);
                                753                 :                : 
 3777                           754                 :             52 :     res = pg_get_viewdef_worker(viewoid, prettyFlags, WRAP_COLUMN_DEFAULT);
                                755                 :                : 
                                756         [ -  + ]:             52 :     if (res == NULL)
 3777 rhaas@postgresql.org      757                 :UBC           0 :         PG_RETURN_NULL();
                                758                 :                : 
 3777 rhaas@postgresql.org      759                 :CBC          52 :     PG_RETURN_TEXT_P(string_to_text(res));
                                760                 :                : }
                                761                 :                : 
                                762                 :                : 
                                763                 :                : Datum
 8522 tgl@sss.pgh.pa.us         764                 :            272 : pg_get_viewdef_name_ext(PG_FUNCTION_ARGS)
                                765                 :                : {
                                766                 :                :     /* By qualified name */
 3548 noah@leadboat.com         767                 :            272 :     text       *viewname = PG_GETARG_TEXT_PP(0);
 8522 tgl@sss.pgh.pa.us         768                 :            272 :     bool        pretty = PG_GETARG_BOOL(1);
                                769                 :                :     int         prettyFlags;
                                770                 :                :     RangeVar   *viewrel;
                                771                 :                :     Oid         viewoid;
                                772                 :                :     char       *res;
                                773                 :                : 
 1706                           774         [ +  - ]:            272 :     prettyFlags = GET_PRETTY_FLAGS(pretty);
                                775                 :                : 
                                776                 :                :     /* Look up view name.  Can't lock it - we might not have privileges. */
 7855 neilc@samurai.com         777                 :            272 :     viewrel = makeRangeVarFromNameList(textToQualifiedNameList(viewname));
 5477 rhaas@postgresql.org      778                 :            272 :     viewoid = RangeVarGetRelid(viewrel, NoLock, false);
                                779                 :                : 
 3765 tgl@sss.pgh.pa.us         780                 :            272 :     res = pg_get_viewdef_worker(viewoid, prettyFlags, WRAP_COLUMN_DEFAULT);
                                781                 :                : 
                                782         [ -  + ]:            272 :     if (res == NULL)
 3765 tgl@sss.pgh.pa.us         783                 :UBC           0 :         PG_RETURN_NULL();
                                784                 :                : 
 3765 tgl@sss.pgh.pa.us         785                 :CBC         272 :     PG_RETURN_TEXT_P(string_to_text(res));
                                786                 :                : }
                                787                 :                : 
                                788                 :                : /*
                                789                 :                :  * Common code for by-OID and by-name variants of pg_get_viewdef
                                790                 :                :  */
                                791                 :                : static char *
 5087                           792                 :           2177 : pg_get_viewdef_worker(Oid viewoid, int prettyFlags, int wrapColumn)
                                793                 :                : {
                                794                 :                :     Datum       args[2];
                                795                 :                :     char        nulls[2];
                                796                 :                :     int         spirc;
                                797                 :                :     HeapTuple   ruletup;
                                798                 :                :     TupleDesc   rulettc;
                                799                 :                :     StringInfoData buf;
                                800                 :                : 
                                801                 :                :     /*
                                802                 :                :      * Do this first so that string is alloc'd in outer context not SPI's.
                                803                 :                :      */
 8242                           804                 :           2177 :     initStringInfo(&buf);
                                805                 :                : 
                                806                 :                :     /*
                                807                 :                :      * Connect to SPI manager
                                808                 :                :      */
  810                           809                 :           2177 :     SPI_connect();
                                810                 :                : 
                                811                 :                :     /*
                                812                 :                :      * On the first call prepare the plan to lookup pg_rewrite. We read
                                813                 :                :      * pg_rewrite over the SPI manager instead of using the syscache to be
                                814                 :                :      * checked for read access on pg_rewrite.
                                815                 :                :      */
 8990                           816         [ +  + ]:           2177 :     if (plan_getviewrule == NULL)
                                817                 :                :     {
                                818                 :                :         Oid         argtypes[2];
                                819                 :                :         SPIPlanPtr  plan;
                                820                 :                : 
                                821                 :            168 :         argtypes[0] = OIDOID;
                                822                 :            168 :         argtypes[1] = NAMEOID;
                                823                 :            168 :         plan = SPI_prepare(query_getviewrule, 2, argtypes);
10315 bruce@momjian.us          824         [ -  + ]:            168 :         if (plan == NULL)
 8525 tgl@sss.pgh.pa.us         825         [ #  # ]:UBC           0 :             elog(ERROR, "SPI_prepare failed for \"%s\"", query_getviewrule);
 5552 tgl@sss.pgh.pa.us         826                 :CBC         168 :         SPI_keepplan(plan);
                                827                 :            168 :         plan_getviewrule = plan;
                                828                 :                :     }
                                829                 :                : 
                                830                 :                :     /*
                                831                 :                :      * Get the pg_rewrite tuple for the view's SELECT rule
                                832                 :                :      */
 8990                           833                 :           2177 :     args[0] = ObjectIdGetDatum(viewoid);
 4753 peter_e@gmx.net           834                 :           2177 :     args[1] = DirectFunctionCall1(namein, CStringGetDatum(ViewSelectRuleName));
10315 bruce@momjian.us          835                 :           2177 :     nulls[0] = ' ';
 8990 tgl@sss.pgh.pa.us         836                 :           2177 :     nulls[1] = ' ';
 4753 peter_e@gmx.net           837                 :           2177 :     spirc = SPI_execute_plan(plan_getviewrule, args, nulls, true, 0);
10315 bruce@momjian.us          838         [ -  + ]:           2177 :     if (spirc != SPI_OK_SELECT)
 8975 tgl@sss.pgh.pa.us         839         [ #  # ]:UBC           0 :         elog(ERROR, "failed to get pg_rewrite tuple for view %u", viewoid);
10315 bruce@momjian.us          840         [ +  + ]:CBC        2177 :     if (SPI_processed != 1)
                                841                 :                :     {
                                842                 :                :         /*
                                843                 :                :          * There is no tuple data available here, just keep the output buffer
                                844                 :                :          * empty.
                                845                 :                :          */
                                846                 :                :     }
                                847                 :                :     else
                                848                 :                :     {
                                849                 :                :         /*
                                850                 :                :          * Get the rule's definition and put it into executor's memory
                                851                 :                :          */
                                852                 :           2173 :         ruletup = SPI_tuptable->vals[0];
                                853                 :           2173 :         rulettc = SPI_tuptable->tupdesc;
 5087 tgl@sss.pgh.pa.us         854                 :           2173 :         make_viewdef(&buf, ruletup, rulettc, prettyFlags, wrapColumn);
                                855                 :                :     }
                                856                 :                : 
                                857                 :                :     /*
                                858                 :                :      * Disconnect from SPI manager
                                859                 :                :      */
10315 bruce@momjian.us          860         [ -  + ]:           2177 :     if (SPI_finish() != SPI_OK_FINISH)
 8525 tgl@sss.pgh.pa.us         861         [ #  # ]:UBC           0 :         elog(ERROR, "SPI_finish failed");
                                862                 :                : 
 3777 rhaas@postgresql.org      863         [ +  + ]:CBC        2177 :     if (buf.len == 0)
                                864                 :              4 :         return NULL;
                                865                 :                : 
 8242 tgl@sss.pgh.pa.us         866                 :           2173 :     return buf.data;
                                867                 :                : }
                                868                 :                : 
                                869                 :                : /* ----------
                                870                 :                :  * pg_get_triggerdef        - Get the definition of a trigger
                                871                 :                :  * ----------
                                872                 :                :  */
                                873                 :                : Datum
 8654 bruce@momjian.us          874                 :             96 : pg_get_triggerdef(PG_FUNCTION_ARGS)
                                875                 :                : {
                                876                 :             96 :     Oid         trigid = PG_GETARG_OID(0);
                                877                 :                :     char       *res;
                                878                 :                : 
 3777 rhaas@postgresql.org      879                 :             96 :     res = pg_get_triggerdef_worker(trigid, false);
                                880                 :                : 
                                881         [ +  + ]:             96 :     if (res == NULL)
                                882                 :              4 :         PG_RETURN_NULL();
                                883                 :                : 
                                884                 :             92 :     PG_RETURN_TEXT_P(string_to_text(res));
                                885                 :                : }
                                886                 :                : 
                                887                 :                : Datum
 6259 peter_e@gmx.net           888                 :            631 : pg_get_triggerdef_ext(PG_FUNCTION_ARGS)
                                889                 :                : {
                                890                 :            631 :     Oid         trigid = PG_GETARG_OID(0);
                                891                 :            631 :     bool        pretty = PG_GETARG_BOOL(1);
                                892                 :                :     char       *res;
                                893                 :                : 
 3777 rhaas@postgresql.org      894                 :            631 :     res = pg_get_triggerdef_worker(trigid, pretty);
                                895                 :                : 
                                896         [ -  + ]:            631 :     if (res == NULL)
 3777 rhaas@postgresql.org      897                 :UBC           0 :         PG_RETURN_NULL();
                                898                 :                : 
 3777 rhaas@postgresql.org      899                 :CBC         631 :     PG_RETURN_TEXT_P(string_to_text(res));
                                900                 :                : }
                                901                 :                : 
                                902                 :                : static char *
 6259 peter_e@gmx.net           903                 :            727 : pg_get_triggerdef_worker(Oid trigid, bool pretty)
                                904                 :                : {
                                905                 :                :     HeapTuple   ht_trig;
                                906                 :                :     Form_pg_trigger trigrec;
                                907                 :                :     StringInfoData buf;
                                908                 :                :     Relation    tgrel;
                                909                 :                :     ScanKeyData skey[1];
                                910                 :                :     SysScanDesc tgscan;
 8593 tgl@sss.pgh.pa.us         911                 :            727 :     int         findx = 0;
                                912                 :                :     char       *tgname;
                                913                 :                :     char       *tgoldtable;
                                914                 :                :     char       *tgnewtable;
                                915                 :                :     Datum       value;
                                916                 :                :     bool        isnull;
                                917                 :                : 
                                918                 :                :     /*
                                919                 :                :      * Fetch the pg_trigger tuple by the Oid of the trigger
                                920                 :                :      */
 2868 andres@anarazel.de        921                 :            727 :     tgrel = table_open(TriggerRelationId, AccessShareLock);
                                922                 :                : 
 8417 tgl@sss.pgh.pa.us         923                 :            727 :     ScanKeyInit(&skey[0],
                                924                 :                :                 Anum_pg_trigger_oid,
                                925                 :                :                 BTEqualStrategyNumber, F_OIDEQ,
                                926                 :                :                 ObjectIdGetDatum(trigid));
                                927                 :                : 
 7898                           928                 :            727 :     tgscan = systable_beginscan(tgrel, TriggerOidIndexId, true,
                                929                 :                :                                 NULL, 1, skey);
                                930                 :                : 
 8593                           931                 :            727 :     ht_trig = systable_getnext(tgscan);
                                932                 :                : 
                                933         [ +  + ]:            727 :     if (!HeapTupleIsValid(ht_trig))
                                934                 :                :     {
 3777 rhaas@postgresql.org      935                 :              4 :         systable_endscan(tgscan);
 2868 andres@anarazel.de        936                 :              4 :         table_close(tgrel, AccessShareLock);
 3777 rhaas@postgresql.org      937                 :              4 :         return NULL;
                                938                 :                :     }
                                939                 :                : 
 8654 bruce@momjian.us          940                 :            723 :     trigrec = (Form_pg_trigger) GETSTRUCT(ht_trig);
                                941                 :                : 
                                942                 :                :     /*
                                943                 :                :      * Start the trigger definition. Note that the trigger's name should never
                                944                 :                :      * be schema-qualified, but the trigger rel's name may be.
                                945                 :                :      */
                                946                 :            723 :     initStringInfo(&buf);
                                947                 :                : 
                                948                 :            723 :     tgname = NameStr(trigrec->tgname);
 6155 itagaki.takahiro@gma      949                 :           1446 :     appendStringInfo(&buf, "CREATE %sTRIGGER %s ",
 6159 tgl@sss.pgh.pa.us         950         [ -  + ]:            723 :                      OidIsValid(trigrec->tgconstraint) ? "CONSTRAINT " : "",
                                951                 :                :                      quote_identifier(tgname));
                                952                 :                : 
 8654 bruce@momjian.us          953         [ +  + ]:            723 :     if (TRIGGER_FOR_BEFORE(trigrec->tgtype))
 4776 rhaas@postgresql.org      954                 :            263 :         appendStringInfoString(&buf, "BEFORE");
 5893 tgl@sss.pgh.pa.us         955         [ +  + ]:            460 :     else if (TRIGGER_FOR_AFTER(trigrec->tgtype))
 4776 rhaas@postgresql.org      956                 :            444 :         appendStringInfoString(&buf, "AFTER");
 5893 tgl@sss.pgh.pa.us         957         [ +  - ]:             16 :     else if (TRIGGER_FOR_INSTEAD(trigrec->tgtype))
 4776 rhaas@postgresql.org      958                 :             16 :         appendStringInfoString(&buf, "INSTEAD OF");
                                959                 :                :     else
 5893 tgl@sss.pgh.pa.us         960         [ #  # ]:UBC           0 :         elog(ERROR, "unexpected tgtype value: %d", trigrec->tgtype);
                                961                 :                : 
 8654 bruce@momjian.us          962         [ +  + ]:CBC         723 :     if (TRIGGER_FOR_INSERT(trigrec->tgtype))
                                963                 :                :     {
 4776 rhaas@postgresql.org      964                 :            488 :         appendStringInfoString(&buf, " INSERT");
 8654 bruce@momjian.us          965                 :            488 :         findx++;
                                966                 :                :     }
                                967         [ +  + ]:            723 :     if (TRIGGER_FOR_DELETE(trigrec->tgtype))
                                968                 :                :     {
                                969         [ +  + ]:            113 :         if (findx > 0)
 4776 rhaas@postgresql.org      970                 :             45 :             appendStringInfoString(&buf, " OR DELETE");
                                971                 :                :         else
                                972                 :             68 :             appendStringInfoString(&buf, " DELETE");
 8654 bruce@momjian.us          973                 :            113 :         findx++;
                                974                 :                :     }
                                975         [ +  + ]:            723 :     if (TRIGGER_FOR_UPDATE(trigrec->tgtype))
                                976                 :                :     {
                                977         [ +  + ]:            332 :         if (findx > 0)
 4776 rhaas@postgresql.org      978                 :            165 :             appendStringInfoString(&buf, " OR UPDATE");
                                979                 :                :         else
                                980                 :            167 :             appendStringInfoString(&buf, " UPDATE");
 6217 tgl@sss.pgh.pa.us         981                 :            332 :         findx++;
                                982                 :                :         /* tgattr is first var-width field, so OK to access directly */
 6254                           983         [ +  + ]:            332 :         if (trigrec->tgattr.dim1 > 0)
                                984                 :                :         {
                                985                 :                :             int         i;
                                986                 :                : 
                                987                 :             44 :             appendStringInfoString(&buf, " OF ");
                                988         [ +  + ]:             97 :             for (i = 0; i < trigrec->tgattr.dim1; i++)
                                989                 :                :             {
                                990                 :                :                 char       *attname;
                                991                 :                : 
                                992         [ +  + ]:             53 :                 if (i > 0)
                                993                 :              9 :                     appendStringInfoString(&buf, ", ");
 3211 alvherre@alvh.no-ip.      994                 :             53 :                 attname = get_attname(trigrec->tgrelid,
                                995                 :             53 :                                       trigrec->tgattr.values[i], false);
 6254 tgl@sss.pgh.pa.us         996                 :             53 :                 appendStringInfoString(&buf, quote_identifier(attname));
                                997                 :                :             }
                                998                 :                :         }
                                999                 :                :     }
 6819                          1000         [ -  + ]:            723 :     if (TRIGGER_FOR_TRUNCATE(trigrec->tgtype))
                               1001                 :                :     {
 6819 tgl@sss.pgh.pa.us        1002         [ #  # ]:UBC           0 :         if (findx > 0)
 4776 rhaas@postgresql.org     1003                 :              0 :             appendStringInfoString(&buf, " OR TRUNCATE");
                               1004                 :                :         else
                               1005                 :              0 :             appendStringInfoString(&buf, " TRUNCATE");
 6217 tgl@sss.pgh.pa.us        1006                 :              0 :         findx++;
                               1007                 :                :     }
                               1008                 :                : 
                               1009                 :                :     /*
                               1010                 :                :      * In non-pretty mode, always schema-qualify the target table name for
                               1011                 :                :      * safety.  In pretty mode, schema-qualify only if not visible.
                               1012                 :                :      */
 6155 itagaki.takahiro@gma     1013         [ +  + ]:CBC        1446 :     appendStringInfo(&buf, " ON %s ",
                               1014                 :                :                      pretty ?
 3197 tgl@sss.pgh.pa.us        1015                 :             92 :                      generate_relation_name(trigrec->tgrelid, NIL) :
                               1016                 :            631 :                      generate_qualified_relation_name(trigrec->tgrelid));
                               1017                 :                : 
 6159                          1018         [ -  + ]:            723 :     if (OidIsValid(trigrec->tgconstraint))
                               1019                 :                :     {
 6217 tgl@sss.pgh.pa.us        1020         [ #  # ]:UBC           0 :         if (OidIsValid(trigrec->tgconstrrelid))
 6155 itagaki.takahiro@gma     1021                 :              0 :             appendStringInfo(&buf, "FROM %s ",
                               1022                 :                :                              generate_relation_name(trigrec->tgconstrrelid, NIL));
 8654 bruce@momjian.us         1023         [ #  # ]:              0 :         if (!trigrec->tgdeferrable)
 4776 rhaas@postgresql.org     1024                 :              0 :             appendStringInfoString(&buf, "NOT ");
                               1025                 :              0 :         appendStringInfoString(&buf, "DEFERRABLE INITIALLY ");
 8654 bruce@momjian.us         1026         [ #  # ]:              0 :         if (trigrec->tginitdeferred)
 4776 rhaas@postgresql.org     1027                 :              0 :             appendStringInfoString(&buf, "DEFERRED ");
                               1028                 :                :         else
                               1029                 :              0 :             appendStringInfoString(&buf, "IMMEDIATE ");
                               1030                 :                :     }
                               1031                 :                : 
 3676 kgrittn@postgresql.o     1032                 :CBC         723 :     value = fastgetattr(ht_trig, Anum_pg_trigger_tgoldtable,
                               1033                 :                :                         tgrel->rd_att, &isnull);
                               1034         [ +  + ]:            723 :     if (!isnull)
 2962 tgl@sss.pgh.pa.us        1035                 :             57 :         tgoldtable = NameStr(*DatumGetName(value));
                               1036                 :                :     else
 3676 kgrittn@postgresql.o     1037                 :            666 :         tgoldtable = NULL;
                               1038                 :            723 :     value = fastgetattr(ht_trig, Anum_pg_trigger_tgnewtable,
                               1039                 :                :                         tgrel->rd_att, &isnull);
                               1040         [ +  + ]:            723 :     if (!isnull)
 2962 tgl@sss.pgh.pa.us        1041                 :             62 :         tgnewtable = NameStr(*DatumGetName(value));
                               1042                 :                :     else
 3676 kgrittn@postgresql.o     1043                 :            661 :         tgnewtable = NULL;
                               1044   [ +  +  +  + ]:            723 :     if (tgoldtable != NULL || tgnewtable != NULL)
                               1045                 :                :     {
                               1046                 :             88 :         appendStringInfoString(&buf, "REFERENCING ");
                               1047         [ +  + ]:             88 :         if (tgoldtable != NULL)
 2962 tgl@sss.pgh.pa.us        1048                 :             57 :             appendStringInfo(&buf, "OLD TABLE AS %s ",
                               1049                 :                :                              quote_identifier(tgoldtable));
 3676 kgrittn@postgresql.o     1050         [ +  + ]:             88 :         if (tgnewtable != NULL)
 2962 tgl@sss.pgh.pa.us        1051                 :             62 :             appendStringInfo(&buf, "NEW TABLE AS %s ",
                               1052                 :                :                              quote_identifier(tgnewtable));
                               1053                 :                :     }
                               1054                 :                : 
 8654 bruce@momjian.us         1055         [ +  + ]:            723 :     if (TRIGGER_FOR_ROW(trigrec->tgtype))
 4776 rhaas@postgresql.org     1056                 :            534 :         appendStringInfoString(&buf, "FOR EACH ROW ");
                               1057                 :                :     else
                               1058                 :            189 :         appendStringInfoString(&buf, "FOR EACH STATEMENT ");
                               1059                 :                : 
                               1060                 :                :     /* If the trigger has a WHEN qualification, add that */
 6217 tgl@sss.pgh.pa.us        1061                 :            723 :     value = fastgetattr(ht_trig, Anum_pg_trigger_tgqual,
                               1062                 :                :                         tgrel->rd_att, &isnull);
                               1063         [ +  + ]:            723 :     if (!isnull)
                               1064                 :                :     {
                               1065                 :                :         Node       *qual;
                               1066                 :                :         char        relkind;
                               1067                 :                :         deparse_context context;
                               1068                 :                :         deparse_namespace dpns;
                               1069                 :                :         RangeTblEntry *oldrte;
                               1070                 :                :         RangeTblEntry *newrte;
                               1071                 :                : 
                               1072                 :             88 :         appendStringInfoString(&buf, "WHEN (");
                               1073                 :                : 
                               1074                 :             88 :         qual = stringToNode(TextDatumGetCString(value));
                               1075                 :                : 
 5758                          1076                 :             88 :         relkind = get_rel_relkind(trigrec->tgrelid);
                               1077                 :                : 
                               1078                 :                :         /* Build minimal OLD and NEW RTEs for the rel */
 6217                          1079                 :             88 :         oldrte = makeNode(RangeTblEntry);
                               1080                 :             88 :         oldrte->rtekind = RTE_RELATION;
                               1081                 :             88 :         oldrte->relid = trigrec->tgrelid;
 5758                          1082                 :             88 :         oldrte->relkind = relkind;
 2981                          1083                 :             88 :         oldrte->rellockmode = AccessShareLock;
 5181                          1084                 :             88 :         oldrte->alias = makeAlias("old", NIL);
                               1085                 :             88 :         oldrte->eref = oldrte->alias;
 5226                          1086                 :             88 :         oldrte->lateral = false;
 6217                          1087                 :             88 :         oldrte->inh = false;
                               1088                 :             88 :         oldrte->inFromCl = true;
                               1089                 :                : 
                               1090                 :             88 :         newrte = makeNode(RangeTblEntry);
                               1091                 :             88 :         newrte->rtekind = RTE_RELATION;
                               1092                 :             88 :         newrte->relid = trigrec->tgrelid;
 5758                          1093                 :             88 :         newrte->relkind = relkind;
 2981                          1094                 :             88 :         newrte->rellockmode = AccessShareLock;
 5181                          1095                 :             88 :         newrte->alias = makeAlias("new", NIL);
                               1096                 :             88 :         newrte->eref = newrte->alias;
 5226                          1097                 :             88 :         newrte->lateral = false;
 6217                          1098                 :             88 :         newrte->inh = false;
                               1099                 :             88 :         newrte->inFromCl = true;
                               1100                 :                : 
                               1101                 :                :         /* Build two-element rtable */
 5982                          1102                 :             88 :         memset(&dpns, 0, sizeof(dpns));
 6217                          1103                 :             88 :         dpns.rtable = list_make2(oldrte, newrte);
 2544                          1104                 :             88 :         dpns.subplans = NIL;
 6217                          1105                 :             88 :         dpns.ctes = NIL;
 2544                          1106                 :             88 :         dpns.appendrels = NULL;
 5181                          1107                 :             88 :         set_rtable_names(&dpns, NIL, NULL);
 5080                          1108                 :             88 :         set_simple_column_names(&dpns);
                               1109                 :                : 
                               1110                 :                :         /* Set up context with one-deep namespace stack */
 6217                          1111                 :             88 :         context.buf = &buf;
                               1112                 :             88 :         context.namespaces = list_make1(&dpns);
  821                          1113                 :             88 :         context.resultDesc = NULL;
                               1114                 :             88 :         context.targetList = NIL;
 6217                          1115                 :             88 :         context.windowClause = NIL;
                               1116                 :             88 :         context.varprefix = true;
 1706                          1117         [ +  + ]:             88 :         context.prettyFlags = GET_PRETTY_FLAGS(pretty);
 5087                          1118                 :             88 :         context.wrapColumn = WRAP_COLUMN_DEFAULT;
 6217                          1119                 :             88 :         context.indentLevel = PRETTYINDENT_STD;
  821                          1120                 :             88 :         context.colNamesVisible = true;
                               1121                 :             88 :         context.inGroupBy = false;
                               1122                 :             88 :         context.varInOrderBy = false;
 2544                          1123                 :             88 :         context.appendparents = NULL;
                               1124                 :                : 
 6217                          1125                 :             88 :         get_rule_expr(qual, &context, false);
                               1126                 :                : 
 4776 rhaas@postgresql.org     1127                 :             88 :         appendStringInfoString(&buf, ") ");
                               1128                 :                :     }
                               1129                 :                : 
 2851 peter@eisentraut.org     1130                 :            723 :     appendStringInfo(&buf, "EXECUTE FUNCTION %s(",
                               1131                 :                :                      generate_function_name(trigrec->tgfoid, 0,
                               1132                 :                :                                             NIL, NULL,
                               1133                 :                :                                             false, NULL, false));
                               1134                 :                : 
 8593 tgl@sss.pgh.pa.us        1135         [ +  + ]:            723 :     if (trigrec->tgnargs > 0)
                               1136                 :                :     {
                               1137                 :                :         char       *p;
                               1138                 :                :         int         i;
                               1139                 :                : 
 6217                          1140                 :            225 :         value = fastgetattr(ht_trig, Anum_pg_trigger_tgargs,
                               1141                 :                :                             tgrel->rd_att, &isnull);
 8593                          1142         [ -  + ]:            225 :         if (isnull)
 8593 tgl@sss.pgh.pa.us        1143         [ #  # ]:UBC           0 :             elog(ERROR, "tgargs is null for trigger %u", trigid);
 3548 noah@leadboat.com        1144                 :CBC         225 :         p = (char *) VARDATA_ANY(DatumGetByteaPP(value));
 8593 tgl@sss.pgh.pa.us        1145         [ +  + ]:            460 :         for (i = 0; i < trigrec->tgnargs; i++)
                               1146                 :                :         {
                               1147         [ +  + ]:            235 :             if (i > 0)
 4776 rhaas@postgresql.org     1148                 :             10 :                 appendStringInfoString(&buf, ", ");
 6657 tgl@sss.pgh.pa.us        1149                 :            235 :             simple_quote_literal(&buf, p);
                               1150                 :                :             /* advance p to next string embedded in tgargs */
                               1151         [ +  + ]:           2825 :             while (*p)
                               1152                 :           2590 :                 p++;
 7489                          1153                 :            235 :             p++;
                               1154                 :                :         }
                               1155                 :                :     }
                               1156                 :                : 
                               1157                 :                :     /* We deliberately do not put semi-colon at end */
 4776 rhaas@postgresql.org     1158                 :            723 :     appendStringInfoChar(&buf, ')');
                               1159                 :                : 
                               1160                 :                :     /* Clean up */
 8593 tgl@sss.pgh.pa.us        1161                 :            723 :     systable_endscan(tgscan);
                               1162                 :                : 
 2868 andres@anarazel.de       1163                 :            723 :     table_close(tgrel, AccessShareLock);
                               1164                 :                : 
 6259 peter_e@gmx.net          1165                 :            723 :     return buf.data;
                               1166                 :                : }
                               1167                 :                : 
                               1168                 :                : /* ----------
                               1169                 :                :  * pg_get_indexdef          - Get the definition of an index
                               1170                 :                :  *
                               1171                 :                :  * In the extended version, there is a colno argument as well as pretty bool.
                               1172                 :                :  *  if colno == 0, we want a complete index definition.
                               1173                 :                :  *  if colno > 0, we only want the Nth index key's variable or expression.
                               1174                 :                :  *
                               1175                 :                :  * Note that the SQL-function versions of this omit any info about the
                               1176                 :                :  * index tablespace; this is intentional because pg_dump wants it that way.
                               1177                 :                :  * However pg_get_indexdef_string() includes the index tablespace.
                               1178                 :                :  * ----------
                               1179                 :                :  */
                               1180                 :                : Datum
 9668 tgl@sss.pgh.pa.us        1181                 :           3108 : pg_get_indexdef(PG_FUNCTION_ARGS)
                               1182                 :                : {
                               1183                 :           3108 :     Oid         indexrelid = PG_GETARG_OID(0);
                               1184                 :                :     int         prettyFlags;
                               1185                 :                :     char       *res;
                               1186                 :                : 
 5046                          1187                 :           3108 :     prettyFlags = PRETTYFLAG_INDENT;
                               1188                 :                : 
 3054                          1189                 :           3108 :     res = pg_get_indexdef_worker(indexrelid, 0, NULL,
                               1190                 :                :                                  false, false,
                               1191                 :                :                                  false, false,
                               1192                 :                :                                  prettyFlags, true);
                               1193                 :                : 
 3777 rhaas@postgresql.org     1194         [ +  + ]:           3108 :     if (res == NULL)
                               1195                 :              4 :         PG_RETURN_NULL();
                               1196                 :                : 
                               1197                 :           3104 :     PG_RETURN_TEXT_P(string_to_text(res));
                               1198                 :                : }
                               1199                 :                : 
                               1200                 :                : Datum
 8522 tgl@sss.pgh.pa.us        1201                 :           1375 : pg_get_indexdef_ext(PG_FUNCTION_ARGS)
                               1202                 :                : {
                               1203                 :           1375 :     Oid         indexrelid = PG_GETARG_OID(0);
 8517 bruce@momjian.us         1204                 :           1375 :     int32       colno = PG_GETARG_INT32(1);
 8522 tgl@sss.pgh.pa.us        1205                 :           1375 :     bool        pretty = PG_GETARG_BOOL(2);
                               1206                 :                :     int         prettyFlags;
                               1207                 :                :     char       *res;
                               1208                 :                : 
 1706                          1209         [ +  - ]:           1375 :     prettyFlags = GET_PRETTY_FLAGS(pretty);
                               1210                 :                : 
 3054                          1211                 :           1375 :     res = pg_get_indexdef_worker(indexrelid, colno, NULL,
                               1212                 :                :                                  colno != 0, false,
                               1213                 :                :                                  false, false,
                               1214                 :                :                                  prettyFlags, true);
                               1215                 :                : 
 3777 rhaas@postgresql.org     1216         [ -  + ]:           1375 :     if (res == NULL)
 3777 rhaas@postgresql.org     1217                 :UBC           0 :         PG_RETURN_NULL();
                               1218                 :                : 
 3777 rhaas@postgresql.org     1219                 :CBC        1375 :     PG_RETURN_TEXT_P(string_to_text(res));
                               1220                 :                : }
                               1221                 :                : 
                               1222                 :                : /*
                               1223                 :                :  * Internal version for use by ALTER TABLE.
                               1224                 :                :  * Includes a tablespace clause in the result.
                               1225                 :                :  * Returns a palloc'd C string; no pretty-printing.
                               1226                 :                :  */
                               1227                 :                : char *
 8242 tgl@sss.pgh.pa.us        1228                 :            187 : pg_get_indexdef_string(Oid indexrelid)
                               1229                 :                : {
 3054                          1230                 :            187 :     return pg_get_indexdef_worker(indexrelid, 0, NULL,
                               1231                 :                :                                   false, false,
                               1232                 :                :                                   true, true,
                               1233                 :                :                                   0, false);
                               1234                 :                : }
                               1235                 :                : 
                               1236                 :                : /* Internal version that just reports the key-column definitions */
                               1237                 :                : char *
 6328                          1238                 :            804 : pg_get_indexdef_columns(Oid indexrelid, bool pretty)
                               1239                 :                : {
                               1240                 :                :     int         prettyFlags;
                               1241                 :                : 
 1706                          1242         [ +  - ]:            804 :     prettyFlags = GET_PRETTY_FLAGS(pretty);
                               1243                 :                : 
 3054                          1244                 :            804 :     return pg_get_indexdef_worker(indexrelid, 0, NULL,
                               1245                 :                :                                   true, true,
                               1246                 :                :                                   false, false,
                               1247                 :                :                                   prettyFlags, false);
                               1248                 :                : }
                               1249                 :                : 
                               1250                 :                : /* Internal version, extensible with flags to control its behavior */
                               1251                 :                : char *
  243 nathan@postgresql.or     1252                 :              4 : pg_get_indexdef_columns_extended(Oid indexrelid, uint16 flags)
                               1253                 :                : {
 1289 michael@paquier.xyz      1254                 :              4 :     bool        pretty = ((flags & RULE_INDEXDEF_PRETTY) != 0);
                               1255                 :              4 :     bool        keys_only = ((flags & RULE_INDEXDEF_KEYS_ONLY) != 0);
                               1256                 :                :     int         prettyFlags;
                               1257                 :                : 
                               1258         [ +  - ]:              4 :     prettyFlags = GET_PRETTY_FLAGS(pretty);
                               1259                 :                : 
                               1260                 :              4 :     return pg_get_indexdef_worker(indexrelid, 0, NULL,
                               1261                 :                :                                   true, keys_only,
                               1262                 :                :                                   false, false,
                               1263                 :                :                                   prettyFlags, false);
                               1264                 :                : }
                               1265                 :                : 
                               1266                 :                : /*
                               1267                 :                :  * Internal workhorse to decompile an index definition.
                               1268                 :                :  *
                               1269                 :                :  * This is now used for exclusion constraints as well: if excludeOps is not
                               1270                 :                :  * NULL then it points to an array of exclusion operator OIDs.
                               1271                 :                :  */
                               1272                 :                : static char *
 6328 tgl@sss.pgh.pa.us        1273                 :           5595 : pg_get_indexdef_worker(Oid indexrelid, int colno,
                               1274                 :                :                        const Oid *excludeOps,
                               1275                 :                :                        bool attrsOnly, bool keysOnly,
                               1276                 :                :                        bool showTblSpc, bool inherits,
                               1277                 :                :                        int prettyFlags, bool missing_ok)
                               1278                 :                : {
                               1279                 :                :     /* might want a separate isConstraint parameter later */
 6200                          1280                 :           5595 :     bool        isConstraint = (excludeOps != NULL);
                               1281                 :                :     HeapTuple   ht_idx;
                               1282                 :                :     HeapTuple   ht_idxrel;
                               1283                 :                :     HeapTuple   ht_am;
                               1284                 :                :     Form_pg_index idxrec;
                               1285                 :                :     Form_pg_class idxrelrec;
                               1286                 :                :     Form_pg_am  amrec;
                               1287                 :                :     const IndexAmRoutine *amroutine;
                               1288                 :                :     List       *indexprs;
                               1289                 :                :     ListCell   *indexpr_item;
                               1290                 :                :     List       *context;
                               1291                 :                :     Oid         indrelid;
                               1292                 :                :     int         keyno;
                               1293                 :                :     Datum       indcollDatum;
                               1294                 :                :     Datum       indclassDatum;
                               1295                 :                :     Datum       indoptionDatum;
                               1296                 :                :     oidvector  *indcollation;
                               1297                 :                :     oidvector  *indclass;
                               1298                 :                :     int2vector *indoption;
                               1299                 :                :     StringInfoData buf;
                               1300                 :                :     char       *str;
                               1301                 :                :     char       *sep;
                               1302                 :                : 
                               1303                 :                :     /*
                               1304                 :                :      * Fetch the pg_index tuple by the Oid of the index
                               1305                 :                :      */
 6131 rhaas@postgresql.org     1306                 :           5595 :     ht_idx = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexrelid));
10284 bruce@momjian.us         1307         [ +  + ]:           5595 :     if (!HeapTupleIsValid(ht_idx))
                               1308                 :                :     {
 3777 rhaas@postgresql.org     1309         [ +  - ]:              4 :         if (missing_ok)
                               1310                 :              4 :             return NULL;
 8525 tgl@sss.pgh.pa.us        1311         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for index %u", indexrelid);
                               1312                 :                :     }
10049 bruce@momjian.us         1313                 :CBC        5591 :     idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
                               1314                 :                : 
 8975 tgl@sss.pgh.pa.us        1315                 :           5591 :     indrelid = idxrec->indrelid;
                               1316         [ -  + ]:           5591 :     Assert(indexrelid == idxrec->indexrelid);
                               1317                 :                : 
                               1318                 :                :     /* Must get indcollation, indclass, and indoption the hard way */
 1344 dgustafsson@postgres     1319                 :           5591 :     indcollDatum = SysCacheGetAttrNotNull(INDEXRELID, ht_idx,
                               1320                 :                :                                           Anum_pg_index_indcollation);
 5772 peter_e@gmx.net          1321                 :           5591 :     indcollation = (oidvector *) DatumGetPointer(indcollDatum);
                               1322                 :                : 
 1344 dgustafsson@postgres     1323                 :           5591 :     indclassDatum = SysCacheGetAttrNotNull(INDEXRELID, ht_idx,
                               1324                 :                :                                            Anum_pg_index_indclass);
 7914 tgl@sss.pgh.pa.us        1325                 :           5591 :     indclass = (oidvector *) DatumGetPointer(indclassDatum);
                               1326                 :                : 
 1344 dgustafsson@postgres     1327                 :           5591 :     indoptionDatum = SysCacheGetAttrNotNull(INDEXRELID, ht_idx,
                               1328                 :                :                                             Anum_pg_index_indoption);
 7263 tgl@sss.pgh.pa.us        1329                 :           5591 :     indoption = (int2vector *) DatumGetPointer(indoptionDatum);
                               1330                 :                : 
                               1331                 :                :     /*
                               1332                 :                :      * Fetch the pg_class tuple of the index relation
                               1333                 :                :      */
 6131 rhaas@postgresql.org     1334                 :           5591 :     ht_idxrel = SearchSysCache1(RELOID, ObjectIdGetDatum(indexrelid));
10284 bruce@momjian.us         1335         [ -  + ]:           5591 :     if (!HeapTupleIsValid(ht_idxrel))
 8525 tgl@sss.pgh.pa.us        1336         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for relation %u", indexrelid);
10049 bruce@momjian.us         1337                 :CBC        5591 :     idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
                               1338                 :                : 
                               1339                 :                :     /*
                               1340                 :                :      * Fetch the pg_am tuple of the index' access method
                               1341                 :                :      */
 6131 rhaas@postgresql.org     1342                 :           5591 :     ht_am = SearchSysCache1(AMOID, ObjectIdGetDatum(idxrelrec->relam));
 9048 tgl@sss.pgh.pa.us        1343         [ -  + ]:           5591 :     if (!HeapTupleIsValid(ht_am))
 8525 tgl@sss.pgh.pa.us        1344         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for access method %u",
                               1345                 :                :              idxrelrec->relam);
 9048 tgl@sss.pgh.pa.us        1346                 :CBC        5591 :     amrec = (Form_pg_am) GETSTRUCT(ht_am);
                               1347                 :                : 
                               1348                 :                :     /* Fetch the index AM's API struct */
 3968                          1349                 :           5591 :     amroutine = GetIndexAmRoutine(amrec->amhandler);
                               1350                 :                : 
                               1351                 :                :     /*
                               1352                 :                :      * Get the index expressions, if any.  (NOTE: we do not use the relcache
                               1353                 :                :      * versions of the expressions and predicate, because we want to display
                               1354                 :                :      * non-const-folded expressions.)
                               1355                 :                :      */
 3167 andrew@dunslane.net      1356         [ +  + ]:           5591 :     if (!heap_attisnull(ht_idx, Anum_pg_index_indexprs, NULL))
                               1357                 :                :     {
                               1358                 :                :         Datum       exprsDatum;
                               1359                 :                :         char       *exprsString;
                               1360                 :                : 
 1344 dgustafsson@postgres     1361                 :            524 :         exprsDatum = SysCacheGetAttrNotNull(INDEXRELID, ht_idx,
                               1362                 :                :                                             Anum_pg_index_indexprs);
 6822 tgl@sss.pgh.pa.us        1363                 :            524 :         exprsString = TextDatumGetCString(exprsDatum);
 8585                          1364                 :            524 :         indexprs = (List *) stringToNode(exprsString);
                               1365                 :            524 :         pfree(exprsString);
                               1366                 :                :     }
                               1367                 :                :     else
                               1368                 :           5067 :         indexprs = NIL;
                               1369                 :                : 
 8221 neilc@samurai.com        1370                 :           5591 :     indexpr_item = list_head(indexprs);
                               1371                 :                : 
 5870 tgl@sss.pgh.pa.us        1372                 :           5591 :     context = deparse_context_for(get_relation_name(indrelid), indrelid);
                               1373                 :                : 
                               1374                 :                :     /*
                               1375                 :                :      * Start the index definition.  Note that the index's name should never be
                               1376                 :                :      * schema-qualified, but the indexed rel's name may be.
                               1377                 :                :      */
 9919                          1378                 :           5591 :     initStringInfo(&buf);
                               1379                 :                : 
 6328                          1380         [ +  + ]:           5591 :     if (!attrsOnly)
                               1381                 :                :     {
 6200                          1382         [ +  + ]:           4473 :         if (!isConstraint)
 3235 alvherre@alvh.no-ip.     1383                 :           8712 :             appendStringInfo(&buf, "CREATE %sINDEX %s ON %s%s USING %s (",
 6200 tgl@sss.pgh.pa.us        1384         [ +  + ]:           4356 :                              idxrec->indisunique ? "UNIQUE " : "",
                               1385                 :           4356 :                              quote_identifier(NameStr(idxrelrec->relname)),
 3235 alvherre@alvh.no-ip.     1386         [ +  + ]:           4356 :                              idxrelrec->relkind == RELKIND_PARTITIONED_INDEX
                               1387         [ +  + ]:            414 :                              && !inherits ? "ONLY " : "",
 3197 tgl@sss.pgh.pa.us        1388         [ +  + ]:           4356 :                              (prettyFlags & PRETTYFLAG_SCHEMA) ?
                               1389                 :           1065 :                              generate_relation_name(indrelid, NIL) :
                               1390                 :           3291 :                              generate_qualified_relation_name(indrelid),
 6200                          1391                 :           4356 :                              quote_identifier(NameStr(amrec->amname)));
                               1392                 :                :         else                    /* currently, must be EXCLUDE constraint */
                               1393                 :            117 :             appendStringInfo(&buf, "EXCLUDE USING %s (",
                               1394                 :            117 :                              quote_identifier(NameStr(amrec->amname)));
                               1395                 :                :     }
                               1396                 :                : 
                               1397                 :                :     /*
                               1398                 :                :      * Report the indexed attributes
                               1399                 :                :      */
10284 bruce@momjian.us         1400                 :           5591 :     sep = "";
 8585 tgl@sss.pgh.pa.us        1401         [ +  + ]:          14040 :     for (keyno = 0; keyno < idxrec->indnatts; keyno++)
                               1402                 :                :     {
 7914                          1403                 :           8514 :         AttrNumber  attnum = idxrec->indkey.values[keyno];
                               1404                 :                :         Oid         keycoltype;
                               1405                 :                :         Oid         keycolcollation;
                               1406                 :                : 
                               1407                 :                :         /*
                               1408                 :                :          * Ignore non-key attributes if told to.
                               1409                 :                :          */
 3054                          1410   [ +  +  +  + ]:           8514 :         if (keysOnly && keyno >= idxrec->indnkeyatts)
 3157 teodor@sigaev.ru         1411                 :             65 :             break;
                               1412                 :                : 
                               1413                 :                :         /* Otherwise, print INCLUDE to divide key and non-key attrs. */
 3054 tgl@sss.pgh.pa.us        1414   [ +  +  +  + ]:           8449 :         if (!colno && keyno == idxrec->indnkeyatts)
                               1415                 :                :         {
 3157 teodor@sigaev.ru         1416                 :            148 :             appendStringInfoString(&buf, ") INCLUDE (");
                               1417                 :            148 :             sep = "";
                               1418                 :                :         }
                               1419                 :                : 
 8522 tgl@sss.pgh.pa.us        1420         [ +  + ]:           8449 :         if (!colno)
 7882 neilc@samurai.com        1421                 :           8023 :             appendStringInfoString(&buf, sep);
10284 bruce@momjian.us         1422                 :           8449 :         sep = ", ";
                               1423                 :                : 
 8585 tgl@sss.pgh.pa.us        1424         [ +  + ]:           8449 :         if (attnum != 0)
                               1425                 :                :         {
                               1426                 :                :             /* Simple index column */
                               1427                 :                :             char       *attname;
                               1428                 :                :             int32       keycoltypmod;
                               1429                 :                : 
 3211 alvherre@alvh.no-ip.     1430                 :           7760 :             attname = get_attname(indrelid, attnum, false);
 8517 bruce@momjian.us         1431   [ +  +  +  + ]:           7760 :             if (!colno || colno == keyno + 1)
 8337 neilc@samurai.com        1432                 :           7652 :                 appendStringInfoString(&buf, quote_identifier(attname));
 5726 tgl@sss.pgh.pa.us        1433                 :           7760 :             get_atttypetypmodcoll(indrelid, attnum,
                               1434                 :                :                                   &keycoltype, &keycoltypmod,
                               1435                 :                :                                   &keycolcollation);
                               1436                 :                :         }
                               1437                 :                :         else
                               1438                 :                :         {
                               1439                 :                :             /* expressional index */
                               1440                 :                :             Node       *indexkey;
                               1441                 :                : 
 8221 neilc@samurai.com        1442         [ -  + ]:            689 :             if (indexpr_item == NULL)
 8585 tgl@sss.pgh.pa.us        1443         [ #  # ]:UBC           0 :                 elog(ERROR, "too few entries in indexprs list");
 8221 neilc@samurai.com        1444                 :CBC         689 :             indexkey = (Node *) lfirst(indexpr_item);
 2693 tgl@sss.pgh.pa.us        1445                 :            689 :             indexpr_item = lnext(indexprs, indexpr_item);
                               1446                 :                :             /* Deparse */
 8522                          1447                 :            689 :             str = deparse_expression_pretty(indexkey, context, false, false,
                               1448                 :                :                                             prettyFlags, 0);
 8517 bruce@momjian.us         1449   [ +  +  +  + ]:            689 :             if (!colno || colno == keyno + 1)
                               1450                 :                :             {
                               1451                 :                :                 /* Need parens if it's not a bare function call */
 3425 tgl@sss.pgh.pa.us        1452         [ +  + ]:            681 :                 if (looks_like_function(indexkey))
 8337 neilc@samurai.com        1453                 :             33 :                     appendStringInfoString(&buf, str);
                               1454                 :                :                 else
 8522 tgl@sss.pgh.pa.us        1455                 :            648 :                     appendStringInfo(&buf, "(%s)", str);
                               1456                 :                :             }
 8585                          1457                 :            689 :             keycoltype = exprType(indexkey);
 5728                          1458                 :            689 :             keycolcollation = exprCollation(indexkey);
                               1459                 :                :         }
                               1460                 :                : 
                               1461                 :                :         /* Print additional decoration for (selected) key columns */
 3054                          1462   [ +  +  +  +  :           8449 :         if (!attrsOnly && keyno < idxrec->indnkeyatts &&
                                              -  + ]
 3054 tgl@sss.pgh.pa.us        1463         [ #  # ]:UBC           0 :             (!colno || colno == keyno + 1))
                               1464                 :                :         {
 2792 tgl@sss.pgh.pa.us        1465                 :CBC        6653 :             int16       opt = indoption->values[keyno];
                               1466                 :           6653 :             Oid         indcoll = indcollation->values[keyno];
 2434 akorotkov@postgresql     1467                 :           6653 :             Datum       attoptions = get_attoptions(indexrelid, keyno + 1);
                               1468                 :           6653 :             bool        has_options = attoptions != (Datum) 0;
                               1469                 :                : 
                               1470                 :                :             /* Add collation, if not default for column */
 5728 tgl@sss.pgh.pa.us        1471   [ +  +  +  + ]:           6653 :             if (OidIsValid(indcoll) && indcoll != keycolcollation)
                               1472                 :             62 :                 appendStringInfo(&buf, " COLLATE %s",
                               1473                 :                :                                  generate_collation_name((indcoll)));
                               1474                 :                : 
                               1475                 :                :             /* Add the operator class name, if not default */
 2434 akorotkov@postgresql     1476         [ +  + ]:           6653 :             get_opclass_name(indclass->values[keyno],
                               1477                 :                :                              has_options ? InvalidOid : keycoltype, &buf);
                               1478                 :                : 
                               1479         [ +  + ]:           6653 :             if (has_options)
                               1480                 :                :             {
                               1481                 :             22 :                 appendStringInfoString(&buf, " (");
                               1482                 :             22 :                 get_reloptions(&buf, attoptions);
                               1483                 :             22 :                 appendStringInfoChar(&buf, ')');
                               1484                 :                :             }
                               1485                 :                : 
                               1486                 :                :             /* Add options if relevant */
 3968 tgl@sss.pgh.pa.us        1487         [ +  + ]:           6653 :             if (amroutine->amcanorder)
                               1488                 :                :             {
                               1489                 :                :                 /* if it supports sort ordering, report DESC and NULLS opts */
 6918                          1490         [ -  + ]:           5468 :                 if (opt & INDOPTION_DESC)
                               1491                 :                :                 {
 4776 rhaas@postgresql.org     1492                 :UBC           0 :                     appendStringInfoString(&buf, " DESC");
                               1493                 :                :                     /* NULLS FIRST is the default in this case */
 6918 tgl@sss.pgh.pa.us        1494         [ #  # ]:              0 :                     if (!(opt & INDOPTION_NULLS_FIRST))
 4776 rhaas@postgresql.org     1495                 :              0 :                         appendStringInfoString(&buf, " NULLS LAST");
                               1496                 :                :                 }
                               1497                 :                :                 else
                               1498                 :                :                 {
 6918 tgl@sss.pgh.pa.us        1499         [ -  + ]:CBC        5468 :                     if (opt & INDOPTION_NULLS_FIRST)
 4776 rhaas@postgresql.org     1500                 :UBC           0 :                         appendStringInfoString(&buf, " NULLS FIRST");
                               1501                 :                :                 }
                               1502                 :                :             }
                               1503                 :                : 
                               1504                 :                :             /* Add the exclusion operator if relevant */
 6200 tgl@sss.pgh.pa.us        1505         [ +  + ]:CBC        6653 :             if (excludeOps != NULL)
                               1506                 :            219 :                 appendStringInfo(&buf, " WITH %s",
                               1507                 :            219 :                                  generate_operator_name(excludeOps[keyno],
                               1508                 :                :                                                         keycoltype,
                               1509                 :                :                                                         keycoltype));
                               1510                 :                :         }
                               1511                 :                :     }
                               1512                 :                : 
 6328                          1513         [ +  + ]:           5591 :     if (!attrsOnly)
                               1514                 :                :     {
 8517 bruce@momjian.us         1515                 :           4473 :         appendStringInfoChar(&buf, ')');
                               1516                 :                : 
 1759 peter@eisentraut.org     1517         [ +  + ]:           4473 :         if (idxrec->indnullsnotdistinct)
 1544 drowley@postgresql.o     1518                 :              8 :             appendStringInfoString(&buf, " NULLS NOT DISTINCT");
                               1519                 :                : 
                               1520                 :                :         /*
                               1521                 :                :          * If it has options, append "WITH (options)"
                               1522                 :                :          */
 7453 tgl@sss.pgh.pa.us        1523                 :           4473 :         str = flatten_reloptions(indexrelid);
                               1524         [ +  + ]:           4473 :         if (str)
                               1525                 :                :         {
                               1526                 :            105 :             appendStringInfo(&buf, " WITH (%s)", str);
                               1527                 :            105 :             pfree(str);
                               1528                 :                :         }
                               1529                 :                : 
                               1530                 :                :         /*
                               1531                 :                :          * Print tablespace, but only if requested
                               1532                 :                :          */
 6986                          1533         [ +  + ]:           4473 :         if (showTblSpc)
                               1534                 :                :         {
                               1535                 :                :             Oid         tblspc;
                               1536                 :                : 
                               1537                 :            187 :             tblspc = get_rel_tablespace(indexrelid);
 2774 alvherre@alvh.no-ip.     1538         [ +  + ]:            187 :             if (OidIsValid(tblspc))
                               1539                 :                :             {
                               1540         [ -  + ]:             36 :                 if (isConstraint)
 2774 alvherre@alvh.no-ip.     1541                 :UBC           0 :                     appendStringInfoString(&buf, " USING INDEX");
 2774 alvherre@alvh.no-ip.     1542                 :CBC          36 :                 appendStringInfo(&buf, " TABLESPACE %s",
                               1543                 :             36 :                                  quote_identifier(get_tablespace_name(tblspc)));
                               1544                 :                :             }
                               1545                 :                :         }
                               1546                 :                : 
                               1547                 :                :         /*
                               1548                 :                :          * If it's a partial index, decompile and append the predicate
                               1549                 :                :          */
 3167 andrew@dunslane.net      1550         [ +  + ]:           4473 :         if (!heap_attisnull(ht_idx, Anum_pg_index_indpred, NULL))
                               1551                 :                :         {
                               1552                 :                :             Node       *node;
                               1553                 :                :             Datum       predDatum;
                               1554                 :                :             char       *predString;
                               1555                 :                : 
                               1556                 :                :             /* Convert text string to node tree */
 1344 dgustafsson@postgres     1557                 :            234 :             predDatum = SysCacheGetAttrNotNull(INDEXRELID, ht_idx,
                               1558                 :                :                                                Anum_pg_index_indpred);
 6822 tgl@sss.pgh.pa.us        1559                 :            234 :             predString = TextDatumGetCString(predDatum);
 8522                          1560                 :            234 :             node = (Node *) stringToNode(predString);
                               1561                 :            234 :             pfree(predString);
                               1562                 :                : 
                               1563                 :                :             /* Deparse */
                               1564                 :            234 :             str = deparse_expression_pretty(node, context, false, false,
                               1565                 :                :                                             prettyFlags, 0);
 6200                          1566         [ +  + ]:            234 :             if (isConstraint)
                               1567                 :             28 :                 appendStringInfo(&buf, " WHERE (%s)", str);
                               1568                 :                :             else
                               1569                 :            206 :                 appendStringInfo(&buf, " WHERE %s", str);
                               1570                 :                :         }
                               1571                 :                :     }
                               1572                 :                : 
                               1573                 :                :     /* Clean up */
 9508                          1574                 :           5591 :     ReleaseSysCache(ht_idx);
                               1575                 :           5591 :     ReleaseSysCache(ht_idxrel);
 9048                          1576                 :           5591 :     ReleaseSysCache(ht_am);
                               1577                 :                : 
 8242                          1578                 :           5591 :     return buf.data;
                               1579                 :                : }
                               1580                 :                : 
                               1581                 :                : /* ----------
                               1582                 :                :  * pg_get_querydef
                               1583                 :                :  *
                               1584                 :                :  * Public entry point to deparse one query parsetree.
                               1585                 :                :  * The pretty flags are determined by GET_PRETTY_FLAGS(pretty).
                               1586                 :                :  *
                               1587                 :                :  * The result is a palloc'd C string.
                               1588                 :                :  * ----------
                               1589                 :                :  */
                               1590                 :                : char *
 1706 tgl@sss.pgh.pa.us        1591                 :UBC           0 : pg_get_querydef(Query *query, bool pretty)
                               1592                 :                : {
                               1593                 :                :     StringInfoData buf;
                               1594                 :                :     int         prettyFlags;
                               1595                 :                : 
                               1596         [ #  # ]:              0 :     prettyFlags = GET_PRETTY_FLAGS(pretty);
                               1597                 :                : 
                               1598                 :              0 :     initStringInfo(&buf);
                               1599                 :                : 
 1652                          1600                 :              0 :     get_query_def(query, &buf, NIL, NULL, true,
                               1601                 :                :                   prettyFlags, WRAP_COLUMN_DEFAULT, 0);
                               1602                 :                : 
 1706                          1603                 :              0 :     return buf.data;
                               1604                 :                : }
                               1605                 :                : 
                               1606                 :                : /*
                               1607                 :                :  * pg_get_statisticsobjdef
                               1608                 :                :  *      Get the definition of an extended statistics object
                               1609                 :                :  */
                               1610                 :                : Datum
 3485 tgl@sss.pgh.pa.us        1611                 :CBC         176 : pg_get_statisticsobjdef(PG_FUNCTION_ARGS)
                               1612                 :                : {
 3536 alvherre@alvh.no-ip.     1613                 :            176 :     Oid         statextid = PG_GETARG_OID(0);
                               1614                 :                :     char       *res;
                               1615                 :                : 
 2073 tomas.vondra@postgre     1616                 :            176 :     res = pg_get_statisticsobj_worker(statextid, false, true);
                               1617                 :                : 
                               1618         [ +  + ]:            176 :     if (res == NULL)
                               1619                 :              4 :         PG_RETURN_NULL();
                               1620                 :                : 
                               1621                 :            172 :     PG_RETURN_TEXT_P(string_to_text(res));
                               1622                 :                : }
                               1623                 :                : 
                               1624                 :                : /*
                               1625                 :                :  * Internal version for use by ALTER TABLE.
                               1626                 :                :  * Returns a palloc'd C string; no pretty-printing.
                               1627                 :                :  */
                               1628                 :                : char *
                               1629                 :             57 : pg_get_statisticsobjdef_string(Oid statextid)
                               1630                 :                : {
                               1631                 :             57 :     return pg_get_statisticsobj_worker(statextid, false, false);
                               1632                 :                : }
                               1633                 :                : 
                               1634                 :                : /*
                               1635                 :                :  * pg_get_statisticsobjdef_columns
                               1636                 :                :  *      Get columns and expressions for an extended statistics object
                               1637                 :                :  */
                               1638                 :                : Datum
                               1639                 :            276 : pg_get_statisticsobjdef_columns(PG_FUNCTION_ARGS)
                               1640                 :                : {
                               1641                 :            276 :     Oid         statextid = PG_GETARG_OID(0);
                               1642                 :                :     char       *res;
                               1643                 :                : 
                               1644                 :            276 :     res = pg_get_statisticsobj_worker(statextid, true, true);
                               1645                 :                : 
 3536 alvherre@alvh.no-ip.     1646         [ -  + ]:            276 :     if (res == NULL)
 3536 alvherre@alvh.no-ip.     1647                 :UBC           0 :         PG_RETURN_NULL();
                               1648                 :                : 
 3536 alvherre@alvh.no-ip.     1649                 :CBC         276 :     PG_RETURN_TEXT_P(string_to_text(res));
                               1650                 :                : }
                               1651                 :                : 
                               1652                 :                : /*
                               1653                 :                :  * Internal workhorse to decompile an extended statistics object.
                               1654                 :                :  */
                               1655                 :                : static char *
 2073 tomas.vondra@postgre     1656                 :            509 : pg_get_statisticsobj_worker(Oid statextid, bool columns_only, bool missing_ok)
                               1657                 :                : {
                               1658                 :                :     Form_pg_statistic_ext statextrec;
                               1659                 :                :     HeapTuple   statexttup;
                               1660                 :                :     StringInfoData buf;
                               1661                 :                :     int         colno;
                               1662                 :                :     char       *nsp;
                               1663                 :                :     ArrayType  *arr;
                               1664                 :                :     char       *enabled;
                               1665                 :                :     Datum       datum;
                               1666                 :                :     bool        ndistinct_enabled;
                               1667                 :                :     bool        dependencies_enabled;
                               1668                 :                :     bool        mcv_enabled;
                               1669                 :                :     int         i;
                               1670                 :                :     List       *context;
                               1671                 :                :     ListCell   *lc;
                               1672                 :            509 :     List       *exprs = NIL;
                               1673                 :                :     bool        has_exprs;
                               1674                 :                :     int         ncolumns;
                               1675                 :                : 
 3536 alvherre@alvh.no-ip.     1676                 :            509 :     statexttup = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(statextid));
                               1677                 :                : 
                               1678         [ +  + ]:            509 :     if (!HeapTupleIsValid(statexttup))
                               1679                 :                :     {
                               1680         [ +  - ]:              4 :         if (missing_ok)
                               1681                 :              4 :             return NULL;
 3485 tgl@sss.pgh.pa.us        1682         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for statistics object %u", statextid);
                               1683                 :                :     }
                               1684                 :                : 
                               1685                 :                :     /* has the statistics expressions? */
 2073 tomas.vondra@postgre     1686                 :CBC         505 :     has_exprs = !heap_attisnull(statexttup, Anum_pg_statistic_ext_stxexprs, NULL);
                               1687                 :                : 
                               1688                 :            505 :     statextrec = (Form_pg_statistic_ext) GETSTRUCT(statexttup);
                               1689                 :                : 
                               1690                 :                :     /*
                               1691                 :                :      * Get the statistics expressions, if any.  (NOTE: we do not use the
                               1692                 :                :      * relcache versions of the expressions, because we want to display
                               1693                 :                :      * non-const-folded expressions.)
                               1694                 :                :      */
                               1695         [ +  + ]:            505 :     if (has_exprs)
                               1696                 :                :     {
                               1697                 :                :         Datum       exprsDatum;
                               1698                 :                :         char       *exprsString;
                               1699                 :                : 
 1344 dgustafsson@postgres     1700                 :            129 :         exprsDatum = SysCacheGetAttrNotNull(STATEXTOID, statexttup,
                               1701                 :                :                                             Anum_pg_statistic_ext_stxexprs);
 2073 tomas.vondra@postgre     1702                 :            129 :         exprsString = TextDatumGetCString(exprsDatum);
                               1703                 :            129 :         exprs = (List *) stringToNode(exprsString);
                               1704                 :            129 :         pfree(exprsString);
                               1705                 :                :     }
                               1706                 :                :     else
                               1707                 :            376 :         exprs = NIL;
                               1708                 :                : 
                               1709                 :                :     /* count the number of columns (attributes and expressions) */
                               1710                 :            505 :     ncolumns = statextrec->stxkeys.dim1 + list_length(exprs);
                               1711                 :                : 
                               1712                 :            505 :     initStringInfo(&buf);
                               1713                 :                : 
                               1714         [ +  + ]:            505 :     if (!columns_only)
                               1715                 :                :     {
 1950 tgl@sss.pgh.pa.us        1716                 :            229 :         nsp = get_namespace_name_or_temp(statextrec->stxnamespace);
 2073 tomas.vondra@postgre     1717                 :            229 :         appendStringInfo(&buf, "CREATE STATISTICS %s",
                               1718                 :                :                          quote_qualified_identifier(nsp,
                               1719                 :            229 :                                                     NameStr(statextrec->stxname)));
                               1720                 :                : 
                               1721                 :                :         /*
                               1722                 :                :          * Decode the stxkind column so that we know which stats types to
                               1723                 :                :          * print.
                               1724                 :                :          */
 1344 dgustafsson@postgres     1725                 :            229 :         datum = SysCacheGetAttrNotNull(STATEXTOID, statexttup,
                               1726                 :                :                                        Anum_pg_statistic_ext_stxkind);
 2073 tomas.vondra@postgre     1727                 :            229 :         arr = DatumGetArrayTypeP(datum);
                               1728         [ +  - ]:            229 :         if (ARR_NDIM(arr) != 1 ||
                               1729         [ +  - ]:            229 :             ARR_HASNULL(arr) ||
                               1730         [ -  + ]:            229 :             ARR_ELEMTYPE(arr) != CHAROID)
 2073 tomas.vondra@postgre     1731         [ #  # ]:UBC           0 :             elog(ERROR, "stxkind is not a 1-D char array");
 2073 tomas.vondra@postgre     1732         [ -  + ]:CBC         229 :         enabled = (char *) ARR_DATA_PTR(arr);
                               1733                 :                : 
                               1734                 :            229 :         ndistinct_enabled = false;
                               1735                 :            229 :         dependencies_enabled = false;
                               1736                 :            229 :         mcv_enabled = false;
                               1737                 :                : 
                               1738         [ +  + ]:            737 :         for (i = 0; i < ARR_DIMS(arr)[0]; i++)
                               1739                 :                :         {
                               1740         [ +  + ]:            508 :             if (enabled[i] == STATS_EXT_NDISTINCT)
                               1741                 :            154 :                 ndistinct_enabled = true;
                               1742         [ +  + ]:            354 :             else if (enabled[i] == STATS_EXT_DEPENDENCIES)
                               1743                 :            130 :                 dependencies_enabled = true;
                               1744         [ +  + ]:            224 :             else if (enabled[i] == STATS_EXT_MCV)
                               1745                 :            139 :                 mcv_enabled = true;
                               1746                 :                : 
                               1747                 :                :             /* ignore STATS_EXT_EXPRESSIONS (it's built automatically) */
                               1748                 :                :         }
                               1749                 :                : 
                               1750                 :                :         /*
                               1751                 :                :          * If any option is disabled, then we'll need to append the types
                               1752                 :                :          * clause to show which options are enabled.  We omit the types clause
                               1753                 :                :          * on purpose when all options are enabled, so a pg_dump/pg_restore
                               1754                 :                :          * will create all statistics types on a newer postgres version, if
                               1755                 :                :          * the statistics had all options enabled on the original version.
                               1756                 :                :          *
                               1757                 :                :          * But if the statistics is defined on just a single column, it has to
                               1758                 :                :          * be an expression statistics. In that case we don't need to specify
                               1759                 :                :          * kinds.
                               1760                 :                :          */
                               1761   [ +  +  +  +  :            229 :         if ((!ndistinct_enabled || !dependencies_enabled || !mcv_enabled) &&
                                        -  +  +  + ]
                               1762                 :                :             (ncolumns > 1))
                               1763                 :                :         {
                               1764                 :             63 :             bool        gotone = false;
                               1765                 :                : 
                               1766                 :             63 :             appendStringInfoString(&buf, " (");
                               1767                 :                : 
                               1768         [ +  + ]:             63 :             if (ndistinct_enabled)
                               1769                 :                :             {
                               1770                 :             34 :                 appendStringInfoString(&buf, "ndistinct");
                               1771                 :             34 :                 gotone = true;
                               1772                 :                :             }
                               1773                 :                : 
                               1774         [ +  + ]:             63 :             if (dependencies_enabled)
                               1775                 :                :             {
                               1776         [ -  + ]:             10 :                 appendStringInfo(&buf, "%sdependencies", gotone ? ", " : "");
                               1777                 :             10 :                 gotone = true;
                               1778                 :                :             }
                               1779                 :                : 
                               1780         [ +  + ]:             63 :             if (mcv_enabled)
                               1781         [ -  + ]:             19 :                 appendStringInfo(&buf, "%smcv", gotone ? ", " : "");
                               1782                 :                : 
                               1783                 :             63 :             appendStringInfoChar(&buf, ')');
                               1784                 :                :         }
                               1785                 :                : 
                               1786                 :            229 :         appendStringInfoString(&buf, " ON ");
                               1787                 :                :     }
                               1788                 :                : 
                               1789                 :                :     /* decode simple column references */
 3512 alvherre@alvh.no-ip.     1790         [ +  + ]:           1438 :     for (colno = 0; colno < statextrec->stxkeys.dim1; colno++)
                               1791                 :                :     {
                               1792                 :            933 :         AttrNumber  attnum = statextrec->stxkeys.values[colno];
                               1793                 :                :         char       *attname;
                               1794                 :                : 
 3536                          1795         [ +  + ]:            933 :         if (colno > 0)
                               1796                 :            515 :             appendStringInfoString(&buf, ", ");
                               1797                 :                : 
 3211                          1798                 :            933 :         attname = get_attname(statextrec->stxrelid, attnum, false);
                               1799                 :                : 
 3536                          1800                 :            933 :         appendStringInfoString(&buf, quote_identifier(attname));
                               1801                 :                :     }
                               1802                 :                : 
 2073 tomas.vondra@postgre     1803                 :            505 :     context = deparse_context_for(get_relation_name(statextrec->stxrelid),
                               1804                 :                :                                   statextrec->stxrelid);
                               1805                 :                : 
                               1806   [ +  +  +  +  :            688 :     foreach(lc, exprs)
                                              +  + ]
                               1807                 :                :     {
                               1808                 :            183 :         Node       *expr = (Node *) lfirst(lc);
                               1809                 :                :         char       *str;
 1914                          1810                 :            183 :         int         prettyFlags = PRETTYFLAG_PAREN;
                               1811                 :                : 
 2073                          1812                 :            183 :         str = deparse_expression_pretty(expr, context, false, false,
                               1813                 :                :                                         prettyFlags, 0);
                               1814                 :                : 
                               1815         [ +  + ]:            183 :         if (colno > 0)
                               1816                 :             96 :             appendStringInfoString(&buf, ", ");
                               1817                 :                : 
                               1818                 :                :         /* Need parens if it's not a bare function call */
                               1819         [ +  + ]:            183 :         if (looks_like_function(expr))
                               1820                 :             21 :             appendStringInfoString(&buf, str);
                               1821                 :                :         else
                               1822                 :            162 :             appendStringInfo(&buf, "(%s)", str);
                               1823                 :                : 
                               1824                 :            183 :         colno++;
                               1825                 :                :     }
                               1826                 :                : 
                               1827         [ +  + ]:            505 :     if (!columns_only)
                               1828                 :            229 :         appendStringInfo(&buf, " FROM %s",
                               1829                 :                :                          generate_relation_name(statextrec->stxrelid, NIL));
                               1830                 :                : 
 3536 alvherre@alvh.no-ip.     1831                 :            505 :     ReleaseSysCache(statexttup);
                               1832                 :                : 
                               1833                 :            505 :     return buf.data;
                               1834                 :                : }
                               1835                 :                : 
                               1836                 :                : /*
                               1837                 :                :  * Generate text array of expressions for statistics object.
                               1838                 :                :  */
                               1839                 :                : Datum
 2073 tomas.vondra@postgre     1840                 :            140 : pg_get_statisticsobjdef_expressions(PG_FUNCTION_ARGS)
                               1841                 :                : {
                               1842                 :            140 :     Oid         statextid = PG_GETARG_OID(0);
                               1843                 :                :     Form_pg_statistic_ext statextrec;
                               1844                 :                :     HeapTuple   statexttup;
                               1845                 :                :     Datum       datum;
                               1846                 :                :     List       *context;
                               1847                 :                :     ListCell   *lc;
                               1848                 :            140 :     List       *exprs = NIL;
                               1849                 :                :     bool        has_exprs;
                               1850                 :                :     char       *tmp;
                               1851                 :            140 :     ArrayBuildState *astate = NULL;
                               1852                 :                : 
                               1853                 :            140 :     statexttup = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(statextid));
                               1854                 :                : 
                               1855         [ -  + ]:            140 :     if (!HeapTupleIsValid(statexttup))
 2031 tomas.vondra@postgre     1856                 :UBC           0 :         PG_RETURN_NULL();
                               1857                 :                : 
                               1858                 :                :     /* Does the stats object have expressions? */
 2073 tomas.vondra@postgre     1859                 :CBC         140 :     has_exprs = !heap_attisnull(statexttup, Anum_pg_statistic_ext_stxexprs, NULL);
                               1860                 :                : 
                               1861                 :                :     /* no expressions? we're done */
                               1862         [ +  + ]:            140 :     if (!has_exprs)
                               1863                 :                :     {
                               1864                 :             11 :         ReleaseSysCache(statexttup);
                               1865                 :             11 :         PG_RETURN_NULL();
                               1866                 :                :     }
                               1867                 :                : 
                               1868                 :            129 :     statextrec = (Form_pg_statistic_ext) GETSTRUCT(statexttup);
                               1869                 :                : 
                               1870                 :                :     /*
                               1871                 :                :      * Get the statistics expressions, and deparse them into text values.
                               1872                 :                :      */
 1344 dgustafsson@postgres     1873                 :            129 :     datum = SysCacheGetAttrNotNull(STATEXTOID, statexttup,
                               1874                 :                :                                    Anum_pg_statistic_ext_stxexprs);
 2073 tomas.vondra@postgre     1875                 :            129 :     tmp = TextDatumGetCString(datum);
                               1876                 :            129 :     exprs = (List *) stringToNode(tmp);
                               1877                 :            129 :     pfree(tmp);
                               1878                 :                : 
                               1879                 :            129 :     context = deparse_context_for(get_relation_name(statextrec->stxrelid),
                               1880                 :                :                                   statextrec->stxrelid);
                               1881                 :                : 
                               1882   [ +  -  +  +  :            308 :     foreach(lc, exprs)
                                              +  + ]
                               1883                 :                :     {
                               1884                 :            179 :         Node       *expr = (Node *) lfirst(lc);
                               1885                 :                :         char       *str;
                               1886                 :            179 :         int         prettyFlags = PRETTYFLAG_INDENT;
                               1887                 :                : 
                               1888                 :            179 :         str = deparse_expression_pretty(expr, context, false, false,
                               1889                 :                :                                         prettyFlags, 0);
                               1890                 :                : 
                               1891                 :            179 :         astate = accumArrayResult(astate,
                               1892                 :            179 :                                   PointerGetDatum(cstring_to_text(str)),
                               1893                 :                :                                   false,
                               1894                 :                :                                   TEXTOID,
                               1895                 :                :                                   CurrentMemoryContext);
                               1896                 :                :     }
                               1897                 :                : 
                               1898                 :            129 :     ReleaseSysCache(statexttup);
                               1899                 :                : 
                               1900                 :            129 :     PG_RETURN_DATUM(makeArrayResult(astate, CurrentMemoryContext));
                               1901                 :                : }
                               1902                 :                : 
                               1903                 :                : /*
                               1904                 :                :  * pg_get_partkeydef
                               1905                 :                :  *
                               1906                 :                :  * Returns the partition key specification, ie, the following:
                               1907                 :                :  *
                               1908                 :                :  * { RANGE | LIST | HASH } (column opt_collation opt_opclass [, ...])
                               1909                 :                :  */
                               1910                 :                : Datum
 3643 rhaas@postgresql.org     1911                 :            831 : pg_get_partkeydef(PG_FUNCTION_ARGS)
                               1912                 :                : {
                               1913                 :            831 :     Oid         relid = PG_GETARG_OID(0);
                               1914                 :                :     char       *res;
                               1915                 :                : 
 3503 sfrost@snowman.net       1916                 :            831 :     res = pg_get_partkeydef_worker(relid, PRETTYFLAG_INDENT, false, true);
                               1917                 :                : 
                               1918         [ +  + ]:            831 :     if (res == NULL)
                               1919                 :              4 :         PG_RETURN_NULL();
                               1920                 :                : 
                               1921                 :            827 :     PG_RETURN_TEXT_P(string_to_text(res));
                               1922                 :                : }
                               1923                 :                : 
                               1924                 :                : /* Internal version that just reports the column definitions */
                               1925                 :                : char *
 3557 rhaas@postgresql.org     1926                 :             94 : pg_get_partkeydef_columns(Oid relid, bool pretty)
                               1927                 :                : {
                               1928                 :                :     int         prettyFlags;
                               1929                 :                : 
 1706 tgl@sss.pgh.pa.us        1930         [ +  - ]:             94 :     prettyFlags = GET_PRETTY_FLAGS(pretty);
                               1931                 :                : 
 3503 sfrost@snowman.net       1932                 :             94 :     return pg_get_partkeydef_worker(relid, prettyFlags, true, false);
                               1933                 :                : }
                               1934                 :                : 
                               1935                 :                : /*
                               1936                 :                :  * Internal workhorse to decompile a partition key definition.
                               1937                 :                :  */
                               1938                 :                : static char *
 3557 rhaas@postgresql.org     1939                 :            925 : pg_get_partkeydef_worker(Oid relid, int prettyFlags,
                               1940                 :                :                          bool attrsOnly, bool missing_ok)
                               1941                 :                : {
                               1942                 :                :     Form_pg_partitioned_table form;
                               1943                 :                :     HeapTuple   tuple;
                               1944                 :                :     oidvector  *partclass;
                               1945                 :                :     oidvector  *partcollation;
                               1946                 :                :     List       *partexprs;
                               1947                 :                :     ListCell   *partexpr_item;
                               1948                 :                :     List       *context;
                               1949                 :                :     Datum       datum;
                               1950                 :                :     StringInfoData buf;
                               1951                 :                :     int         keyno;
                               1952                 :                :     char       *str;
                               1953                 :                :     char       *sep;
                               1954                 :                : 
 3643                          1955                 :            925 :     tuple = SearchSysCache1(PARTRELID, ObjectIdGetDatum(relid));
                               1956         [ +  + ]:            925 :     if (!HeapTupleIsValid(tuple))
                               1957                 :                :     {
 3503 sfrost@snowman.net       1958         [ +  - ]:              4 :         if (missing_ok)
                               1959                 :              4 :             return NULL;
 3643 rhaas@postgresql.org     1960         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for partition key of %u", relid);
                               1961                 :                :     }
                               1962                 :                : 
 3643 rhaas@postgresql.org     1963                 :CBC         921 :     form = (Form_pg_partitioned_table) GETSTRUCT(tuple);
                               1964                 :                : 
                               1965         [ -  + ]:            921 :     Assert(form->partrelid == relid);
                               1966                 :                : 
                               1967                 :                :     /* Must get partclass and partcollation the hard way */
 1344 dgustafsson@postgres     1968                 :            921 :     datum = SysCacheGetAttrNotNull(PARTRELID, tuple,
                               1969                 :                :                                    Anum_pg_partitioned_table_partclass);
 3643 rhaas@postgresql.org     1970                 :            921 :     partclass = (oidvector *) DatumGetPointer(datum);
                               1971                 :                : 
 1344 dgustafsson@postgres     1972                 :            921 :     datum = SysCacheGetAttrNotNull(PARTRELID, tuple,
                               1973                 :                :                                    Anum_pg_partitioned_table_partcollation);
 3643 rhaas@postgresql.org     1974                 :            921 :     partcollation = (oidvector *) DatumGetPointer(datum);
                               1975                 :                : 
                               1976                 :                : 
                               1977                 :                :     /*
                               1978                 :                :      * Get the expressions, if any.  (NOTE: we do not use the relcache
                               1979                 :                :      * versions of the expressions, because we want to display
                               1980                 :                :      * non-const-folded expressions.)
                               1981                 :                :      */
 3167 andrew@dunslane.net      1982         [ +  + ]:            921 :     if (!heap_attisnull(tuple, Anum_pg_partitioned_table_partexprs, NULL))
                               1983                 :                :     {
                               1984                 :                :         Datum       exprsDatum;
                               1985                 :                :         char       *exprsString;
                               1986                 :                : 
 1344 dgustafsson@postgres     1987                 :             86 :         exprsDatum = SysCacheGetAttrNotNull(PARTRELID, tuple,
                               1988                 :                :                                             Anum_pg_partitioned_table_partexprs);
 3643 rhaas@postgresql.org     1989                 :             86 :         exprsString = TextDatumGetCString(exprsDatum);
                               1990                 :             86 :         partexprs = (List *) stringToNode(exprsString);
                               1991                 :                : 
                               1992         [ -  + ]:             86 :         if (!IsA(partexprs, List))
 3643 rhaas@postgresql.org     1993         [ #  # ]:UBC           0 :             elog(ERROR, "unexpected node type found in partexprs: %d",
                               1994                 :                :                  (int) nodeTag(partexprs));
                               1995                 :                : 
 3643 rhaas@postgresql.org     1996                 :CBC          86 :         pfree(exprsString);
                               1997                 :                :     }
                               1998                 :                :     else
                               1999                 :            835 :         partexprs = NIL;
                               2000                 :                : 
                               2001                 :            921 :     partexpr_item = list_head(partexprs);
                               2002                 :            921 :     context = deparse_context_for(get_relation_name(relid), relid);
                               2003                 :                : 
                               2004                 :            921 :     initStringInfo(&buf);
                               2005                 :                : 
                               2006   [ +  +  +  - ]:            921 :     switch (form->partstrat)
                               2007                 :                :     {
 3306                          2008                 :             77 :         case PARTITION_STRATEGY_HASH:
                               2009         [ +  - ]:             77 :             if (!attrsOnly)
 2704 drowley@postgresql.o     2010                 :             77 :                 appendStringInfoString(&buf, "HASH");
 3306 rhaas@postgresql.org     2011                 :             77 :             break;
 3643                          2012                 :            341 :         case PARTITION_STRATEGY_LIST:
 3557                          2013         [ +  + ]:            341 :             if (!attrsOnly)
 3392 peter_e@gmx.net          2014                 :            315 :                 appendStringInfoString(&buf, "LIST");
 3643 rhaas@postgresql.org     2015                 :            341 :             break;
                               2016                 :            503 :         case PARTITION_STRATEGY_RANGE:
 3557                          2017         [ +  + ]:            503 :             if (!attrsOnly)
 3392 peter_e@gmx.net          2018                 :            435 :                 appendStringInfoString(&buf, "RANGE");
 3643 rhaas@postgresql.org     2019                 :            503 :             break;
 3643 rhaas@postgresql.org     2020                 :UBC           0 :         default:
                               2021         [ #  # ]:              0 :             elog(ERROR, "unexpected partition strategy: %d",
                               2022                 :                :                  (int) form->partstrat);
                               2023                 :                :     }
                               2024                 :                : 
 3557 rhaas@postgresql.org     2025         [ +  + ]:CBC         921 :     if (!attrsOnly)
 3392 peter_e@gmx.net          2026                 :            827 :         appendStringInfoString(&buf, " (");
 3643 rhaas@postgresql.org     2027                 :            921 :     sep = "";
                               2028         [ +  + ]:           1935 :     for (keyno = 0; keyno < form->partnatts; keyno++)
                               2029                 :                :     {
                               2030                 :           1014 :         AttrNumber  attnum = form->partattrs.values[keyno];
                               2031                 :                :         Oid         keycoltype;
                               2032                 :                :         Oid         keycolcollation;
                               2033                 :                :         Oid         partcoll;
                               2034                 :                : 
                               2035                 :           1014 :         appendStringInfoString(&buf, sep);
                               2036                 :           1014 :         sep = ", ";
                               2037         [ +  + ]:           1014 :         if (attnum != 0)
                               2038                 :                :         {
                               2039                 :                :             /* Simple attribute reference */
                               2040                 :                :             char       *attname;
                               2041                 :                :             int32       keycoltypmod;
                               2042                 :                : 
 3211 alvherre@alvh.no-ip.     2043                 :            920 :             attname = get_attname(relid, attnum, false);
 3643 rhaas@postgresql.org     2044                 :            920 :             appendStringInfoString(&buf, quote_identifier(attname));
                               2045                 :            920 :             get_atttypetypmodcoll(relid, attnum,
                               2046                 :                :                                   &keycoltype, &keycoltypmod,
                               2047                 :                :                                   &keycolcollation);
                               2048                 :                :         }
                               2049                 :                :         else
                               2050                 :                :         {
                               2051                 :                :             /* Expression */
                               2052                 :                :             Node       *partkey;
                               2053                 :                : 
                               2054         [ -  + ]:             94 :             if (partexpr_item == NULL)
 3643 rhaas@postgresql.org     2055         [ #  # ]:UBC           0 :                 elog(ERROR, "too few entries in partexprs list");
 3643 rhaas@postgresql.org     2056                 :CBC          94 :             partkey = (Node *) lfirst(partexpr_item);
 2693 tgl@sss.pgh.pa.us        2057                 :             94 :             partexpr_item = lnext(partexprs, partexpr_item);
                               2058                 :                : 
                               2059                 :                :             /* Deparse */
 3643 rhaas@postgresql.org     2060                 :             94 :             str = deparse_expression_pretty(partkey, context, false, false,
                               2061                 :                :                                             prettyFlags, 0);
                               2062                 :                :             /* Need parens if it's not a bare function call */
 3425 tgl@sss.pgh.pa.us        2063         [ +  + ]:             94 :             if (looks_like_function(partkey))
                               2064                 :             34 :                 appendStringInfoString(&buf, str);
                               2065                 :                :             else
                               2066                 :             60 :                 appendStringInfo(&buf, "(%s)", str);
                               2067                 :                : 
 3643 rhaas@postgresql.org     2068                 :             94 :             keycoltype = exprType(partkey);
                               2069                 :             94 :             keycolcollation = exprCollation(partkey);
                               2070                 :                :         }
                               2071                 :                : 
                               2072                 :                :         /* Add collation, if not default for column */
                               2073                 :           1014 :         partcoll = partcollation->values[keyno];
 3557                          2074   [ +  +  +  +  :           1014 :         if (!attrsOnly && OidIsValid(partcoll) && partcoll != keycolcollation)
                                              +  + ]
 3643                          2075                 :              4 :             appendStringInfo(&buf, " COLLATE %s",
                               2076                 :                :                              generate_collation_name((partcoll)));
                               2077                 :                : 
                               2078                 :                :         /* Add the operator class name, if not default */
 3557                          2079         [ +  + ]:           1014 :         if (!attrsOnly)
                               2080                 :            884 :             get_opclass_name(partclass->values[keyno], keycoltype, &buf);
                               2081                 :                :     }
                               2082                 :                : 
                               2083         [ +  + ]:            921 :     if (!attrsOnly)
                               2084                 :            827 :         appendStringInfoChar(&buf, ')');
                               2085                 :                : 
                               2086                 :                :     /* Clean up */
 3643                          2087                 :            921 :     ReleaseSysCache(tuple);
                               2088                 :                : 
                               2089                 :            921 :     return buf.data;
                               2090                 :                : }
                               2091                 :                : 
                               2092                 :                : /*
                               2093                 :                :  * pg_get_partition_constraintdef
                               2094                 :                :  *
                               2095                 :                :  * Returns partition constraint expression as a string for the input relation
                               2096                 :                :  */
                               2097                 :                : Datum
 3486                          2098                 :            121 : pg_get_partition_constraintdef(PG_FUNCTION_ARGS)
                               2099                 :                : {
 3482 bruce@momjian.us         2100                 :            121 :     Oid         relationId = PG_GETARG_OID(0);
                               2101                 :                :     Expr       *constr_expr;
                               2102                 :                :     int         prettyFlags;
                               2103                 :                :     List       *context;
                               2104                 :                :     char       *consrc;
                               2105                 :                : 
 3486 rhaas@postgresql.org     2106                 :            121 :     constr_expr = get_partition_qual_relid(relationId);
                               2107                 :                : 
                               2108                 :                :     /* Quick exit if no partition constraint */
                               2109         [ +  + ]:            121 :     if (constr_expr == NULL)
                               2110                 :             12 :         PG_RETURN_NULL();
                               2111                 :                : 
                               2112                 :                :     /*
                               2113                 :                :      * Deparse and return the constraint expression.
                               2114                 :                :      */
                               2115                 :            109 :     prettyFlags = PRETTYFLAG_INDENT;
                               2116                 :            109 :     context = deparse_context_for(get_relation_name(relationId), relationId);
                               2117                 :            109 :     consrc = deparse_expression_pretty((Node *) constr_expr, context, false,
                               2118                 :                :                                        false, prettyFlags, 0);
                               2119                 :                : 
                               2120                 :            109 :     PG_RETURN_TEXT_P(string_to_text(consrc));
                               2121                 :                : }
                               2122                 :                : 
                               2123                 :                : /*
                               2124                 :                :  * pg_get_partconstrdef_string
                               2125                 :                :  *
                               2126                 :                :  * Returns the partition constraint as a C-string for the input relation, with
                               2127                 :                :  * the given alias.  No pretty-printing.
                               2128                 :                :  */
                               2129                 :                : char *
 2796 alvherre@alvh.no-ip.     2130                 :             65 : pg_get_partconstrdef_string(Oid partitionId, char *aliasname)
                               2131                 :                : {
                               2132                 :                :     Expr       *constr_expr;
                               2133                 :                :     List       *context;
                               2134                 :                : 
                               2135                 :             65 :     constr_expr = get_partition_qual_relid(partitionId);
                               2136                 :             65 :     context = deparse_context_for(aliasname, partitionId);
                               2137                 :                : 
                               2138                 :             65 :     return deparse_expression((Node *) constr_expr, context, true, false);
                               2139                 :                : }
                               2140                 :                : 
                               2141                 :                : /*
                               2142                 :                :  * pg_get_constraintdef
                               2143                 :                :  *
                               2144                 :                :  * Returns the definition for the constraint, ie, everything that needs to
                               2145                 :                :  * appear after "ALTER TABLE ... ADD CONSTRAINT <constraintname>".
                               2146                 :                :  */
                               2147                 :                : Datum
 8870 tgl@sss.pgh.pa.us        2148                 :           1130 : pg_get_constraintdef(PG_FUNCTION_ARGS)
                               2149                 :                : {
 8851 bruce@momjian.us         2150                 :           1130 :     Oid         constraintId = PG_GETARG_OID(0);
                               2151                 :                :     int         prettyFlags;
                               2152                 :                :     char       *res;
                               2153                 :                : 
 5046 tgl@sss.pgh.pa.us        2154                 :           1130 :     prettyFlags = PRETTYFLAG_INDENT;
                               2155                 :                : 
 3777 rhaas@postgresql.org     2156                 :           1130 :     res = pg_get_constraintdef_worker(constraintId, false, prettyFlags, true);
                               2157                 :                : 
                               2158         [ +  + ]:           1130 :     if (res == NULL)
                               2159                 :              4 :         PG_RETURN_NULL();
                               2160                 :                : 
                               2161                 :           1126 :     PG_RETURN_TEXT_P(string_to_text(res));
                               2162                 :                : }
                               2163                 :                : 
                               2164                 :                : Datum
 8522 tgl@sss.pgh.pa.us        2165                 :           2797 : pg_get_constraintdef_ext(PG_FUNCTION_ARGS)
                               2166                 :                : {
                               2167                 :           2797 :     Oid         constraintId = PG_GETARG_OID(0);
                               2168                 :           2797 :     bool        pretty = PG_GETARG_BOOL(1);
                               2169                 :                :     int         prettyFlags;
                               2170                 :                :     char       *res;
                               2171                 :                : 
 1706                          2172         [ +  + ]:           2797 :     prettyFlags = GET_PRETTY_FLAGS(pretty);
                               2173                 :                : 
 3777 rhaas@postgresql.org     2174                 :           2797 :     res = pg_get_constraintdef_worker(constraintId, false, prettyFlags, true);
                               2175                 :                : 
                               2176         [ -  + ]:           2797 :     if (res == NULL)
 3777 rhaas@postgresql.org     2177                 :UBC           0 :         PG_RETURN_NULL();
                               2178                 :                : 
 3777 rhaas@postgresql.org     2179                 :CBC        2797 :     PG_RETURN_TEXT_P(string_to_text(res));
                               2180                 :                : }
                               2181                 :                : 
                               2182                 :                : /*
                               2183                 :                :  * Internal version that returns a full ALTER TABLE ... ADD CONSTRAINT command
                               2184                 :                :  */
                               2185                 :                : char *
 4026 tgl@sss.pgh.pa.us        2186                 :            468 : pg_get_constraintdef_command(Oid constraintId)
                               2187                 :                : {
 3777 rhaas@postgresql.org     2188                 :            468 :     return pg_get_constraintdef_worker(constraintId, true, 0, false);
                               2189                 :                : }
                               2190                 :                : 
                               2191                 :                : /*
                               2192                 :                :  * As of 9.4, we now use an MVCC snapshot for this.
                               2193                 :                :  */
                               2194                 :                : static char *
 8242 tgl@sss.pgh.pa.us        2195                 :           4395 : pg_get_constraintdef_worker(Oid constraintId, bool fullCommand,
                               2196                 :                :                             int prettyFlags, bool missing_ok)
                               2197                 :                : {
                               2198                 :                :     HeapTuple   tup;
                               2199                 :                :     Form_pg_constraint conForm;
                               2200                 :                :     StringInfoData buf;
                               2201                 :                :     SysScanDesc scandesc;
                               2202                 :                :     ScanKeyData scankey[1];
 4589 bruce@momjian.us         2203                 :           4395 :     Snapshot    snapshot = RegisterSnapshot(GetTransactionSnapshot());
 2868 andres@anarazel.de       2204                 :           4395 :     Relation    relation = table_open(ConstraintRelationId, AccessShareLock);
                               2205                 :                : 
 4619 simon@2ndQuadrant.co     2206                 :           4395 :     ScanKeyInit(&scankey[0],
                               2207                 :                :                 Anum_pg_constraint_oid,
                               2208                 :                :                 BTEqualStrategyNumber, F_OIDEQ,
                               2209                 :                :                 ObjectIdGetDatum(constraintId));
                               2210                 :                : 
                               2211                 :           4395 :     scandesc = systable_beginscan(relation,
                               2212                 :                :                                   ConstraintOidIndexId,
                               2213                 :                :                                   true,
                               2214                 :                :                                   snapshot,
                               2215                 :                :                                   1,
                               2216                 :                :                                   scankey);
                               2217                 :                : 
                               2218                 :                :     /*
                               2219                 :                :      * We later use the tuple with SysCacheGetAttr() as if we had obtained it
                               2220                 :                :      * via SearchSysCache, which works fine.
                               2221                 :                :      */
                               2222                 :           4395 :     tup = systable_getnext(scandesc);
                               2223                 :                : 
                               2224                 :           4395 :     UnregisterSnapshot(snapshot);
                               2225                 :                : 
 3777 rhaas@postgresql.org     2226         [ +  + ]:           4395 :     if (!HeapTupleIsValid(tup))
                               2227                 :                :     {
                               2228         [ +  - ]:              4 :         if (missing_ok)
                               2229                 :                :         {
                               2230                 :              4 :             systable_endscan(scandesc);
 2868 andres@anarazel.de       2231                 :              4 :             table_close(relation, AccessShareLock);
 3777 rhaas@postgresql.org     2232                 :              4 :             return NULL;
                               2233                 :                :         }
 3464 tgl@sss.pgh.pa.us        2234         [ #  # ]:UBC           0 :         elog(ERROR, "could not find tuple for constraint %u", constraintId);
                               2235                 :                :     }
                               2236                 :                : 
 8870 tgl@sss.pgh.pa.us        2237                 :CBC        4391 :     conForm = (Form_pg_constraint) GETSTRUCT(tup);
                               2238                 :                : 
                               2239                 :           4391 :     initStringInfo(&buf);
                               2240                 :                : 
 4026                          2241         [ +  + ]:           4391 :     if (fullCommand)
                               2242                 :                :     {
 3314                          2243         [ +  + ]:            468 :         if (OidIsValid(conForm->conrelid))
                               2244                 :                :         {
                               2245                 :                :             /*
                               2246                 :                :              * Currently, callers want ALTER TABLE (without ONLY) for CHECK
                               2247                 :                :              * constraints, and other types of constraints don't inherit
                               2248                 :                :              * anyway so it doesn't matter whether we say ONLY or not. Someday
                               2249                 :                :              * we might need to let callers specify whether to put ONLY in the
                               2250                 :                :              * command.
                               2251                 :                :              */
                               2252                 :            455 :             appendStringInfo(&buf, "ALTER TABLE %s ADD CONSTRAINT %s ",
                               2253                 :                :                              generate_qualified_relation_name(conForm->conrelid),
                               2254                 :            455 :                              quote_identifier(NameStr(conForm->conname)));
                               2255                 :                :         }
                               2256                 :                :         else
                               2257                 :                :         {
                               2258                 :                :             /* Must be a domain constraint */
                               2259         [ -  + ]:             13 :             Assert(OidIsValid(conForm->contypid));
                               2260                 :             13 :             appendStringInfo(&buf, "ALTER DOMAIN %s ADD CONSTRAINT %s ",
                               2261                 :                :                              generate_qualified_type_name(conForm->contypid),
                               2262                 :             13 :                              quote_identifier(NameStr(conForm->conname)));
                               2263                 :                :         }
                               2264                 :                :     }
                               2265                 :                : 
 8870                          2266   [ +  +  +  +  :           4391 :     switch (conForm->contype)
                                           -  +  - ]
                               2267                 :                :     {
                               2268                 :            463 :         case CONSTRAINT_FOREIGN:
                               2269                 :                :             {
                               2270                 :                :                 Datum       val;
                               2271                 :                :                 bool        isnull;
                               2272                 :                :                 const char *string;
                               2273                 :                : 
                               2274                 :                :                 /* Start off the constraint definition */
 4776 rhaas@postgresql.org     2275                 :            463 :                 appendStringInfoString(&buf, "FOREIGN KEY (");
                               2276                 :                : 
                               2277                 :                :                 /* Fetch and build referencing-column list */
 1344 dgustafsson@postgres     2278                 :            463 :                 val = SysCacheGetAttrNotNull(CONSTROID, tup,
                               2279                 :                :                                              Anum_pg_constraint_conkey);
                               2280                 :                : 
                               2281                 :                :                 /* If it is a temporal foreign key then it uses PERIOD. */
  802 peter@eisentraut.org     2282                 :            463 :                 decompile_column_index_array(val, conForm->conrelid, conForm->conperiod, &buf);
                               2283                 :                : 
                               2284                 :                :                 /* add foreign relation name */
 8851 bruce@momjian.us         2285                 :            463 :                 appendStringInfo(&buf, ") REFERENCES %s(",
                               2286                 :                :                                  generate_relation_name(conForm->confrelid,
                               2287                 :                :                                                         NIL));
                               2288                 :                : 
                               2289                 :                :                 /* Fetch and build referenced-column list */
 1344 dgustafsson@postgres     2290                 :            463 :                 val = SysCacheGetAttrNotNull(CONSTROID, tup,
                               2291                 :                :                                              Anum_pg_constraint_confkey);
                               2292                 :                : 
  802 peter@eisentraut.org     2293                 :            463 :                 decompile_column_index_array(val, conForm->confrelid, conForm->conperiod, &buf);
                               2294                 :                : 
 4776 rhaas@postgresql.org     2295                 :            463 :                 appendStringInfoChar(&buf, ')');
                               2296                 :                : 
                               2297                 :                :                 /* Add match type */
 8851 bruce@momjian.us         2298   [ +  -  +  - ]:            463 :                 switch (conForm->confmatchtype)
                               2299                 :                :                 {
                               2300                 :             21 :                     case FKCONSTR_MATCH_FULL:
                               2301                 :             21 :                         string = " MATCH FULL";
                               2302                 :             21 :                         break;
 8851 bruce@momjian.us         2303                 :UBC           0 :                     case FKCONSTR_MATCH_PARTIAL:
                               2304                 :              0 :                         string = " MATCH PARTIAL";
                               2305                 :              0 :                         break;
 5277 tgl@sss.pgh.pa.us        2306                 :CBC         442 :                     case FKCONSTR_MATCH_SIMPLE:
 8851 bruce@momjian.us         2307                 :            442 :                         string = "";
                               2308                 :            442 :                         break;
 8851 bruce@momjian.us         2309                 :UBC           0 :                     default:
 8525 tgl@sss.pgh.pa.us        2310         [ #  # ]:              0 :                         elog(ERROR, "unrecognized confmatchtype: %d",
                               2311                 :                :                              conForm->confmatchtype);
                               2312                 :                :                         string = "";  /* keep compiler quiet */
                               2313                 :                :                         break;
                               2314                 :                :                 }
 8337 neilc@samurai.com        2315                 :CBC         463 :                 appendStringInfoString(&buf, string);
                               2316                 :                : 
                               2317                 :                :                 /* Add ON UPDATE and ON DELETE clauses, if needed */
 8851 bruce@momjian.us         2318   [ +  -  +  +  :            463 :                 switch (conForm->confupdtype)
                                              -  - ]
                               2319                 :                :                 {
                               2320                 :            379 :                     case FKCONSTR_ACTION_NOACTION:
 8517                          2321                 :            379 :                         string = NULL;  /* suppress default */
 8851                          2322                 :            379 :                         break;
 8851 bruce@momjian.us         2323                 :UBC           0 :                     case FKCONSTR_ACTION_RESTRICT:
                               2324                 :              0 :                         string = "RESTRICT";
                               2325                 :              0 :                         break;
 8851 bruce@momjian.us         2326                 :CBC          67 :                     case FKCONSTR_ACTION_CASCADE:
                               2327                 :             67 :                         string = "CASCADE";
                               2328                 :             67 :                         break;
                               2329                 :             17 :                     case FKCONSTR_ACTION_SETNULL:
                               2330                 :             17 :                         string = "SET NULL";
                               2331                 :             17 :                         break;
 8851 bruce@momjian.us         2332                 :UBC           0 :                     case FKCONSTR_ACTION_SETDEFAULT:
                               2333                 :              0 :                         string = "SET DEFAULT";
                               2334                 :              0 :                         break;
                               2335                 :              0 :                     default:
 8525 tgl@sss.pgh.pa.us        2336         [ #  # ]:              0 :                         elog(ERROR, "unrecognized confupdtype: %d",
                               2337                 :                :                              conForm->confupdtype);
                               2338                 :                :                         string = NULL;  /* keep compiler quiet */
                               2339                 :                :                         break;
                               2340                 :                :                 }
 8699 tgl@sss.pgh.pa.us        2341         [ +  + ]:CBC         463 :                 if (string)
      bruce@momjian.us         2342                 :             84 :                     appendStringInfo(&buf, " ON UPDATE %s", string);
                               2343                 :                : 
 8851                          2344   [ +  -  +  +  :            463 :                 switch (conForm->confdeltype)
                                              +  - ]
                               2345                 :                :                 {
                               2346                 :            380 :                     case FKCONSTR_ACTION_NOACTION:
 8517                          2347                 :            380 :                         string = NULL;  /* suppress default */
 8851                          2348                 :            380 :                         break;
 8851 bruce@momjian.us         2349                 :UBC           0 :                     case FKCONSTR_ACTION_RESTRICT:
                               2350                 :              0 :                         string = "RESTRICT";
                               2351                 :              0 :                         break;
 8851 bruce@momjian.us         2352                 :CBC          67 :                     case FKCONSTR_ACTION_CASCADE:
                               2353                 :             67 :                         string = "CASCADE";
                               2354                 :             67 :                         break;
                               2355                 :             12 :                     case FKCONSTR_ACTION_SETNULL:
                               2356                 :             12 :                         string = "SET NULL";
                               2357                 :             12 :                         break;
                               2358                 :              4 :                     case FKCONSTR_ACTION_SETDEFAULT:
                               2359                 :              4 :                         string = "SET DEFAULT";
                               2360                 :              4 :                         break;
 8851 bruce@momjian.us         2361                 :UBC           0 :                     default:
 8525 tgl@sss.pgh.pa.us        2362         [ #  # ]:              0 :                         elog(ERROR, "unrecognized confdeltype: %d",
                               2363                 :                :                              conForm->confdeltype);
                               2364                 :                :                         string = NULL;  /* keep compiler quiet */
                               2365                 :                :                         break;
                               2366                 :                :                 }
 8699 tgl@sss.pgh.pa.us        2367         [ +  + ]:CBC         463 :                 if (string)
      bruce@momjian.us         2368                 :             83 :                     appendStringInfo(&buf, " ON DELETE %s", string);
                               2369                 :                : 
                               2370                 :                :                 /*
                               2371                 :                :                  * Add columns specified to SET NULL or SET DEFAULT if
                               2372                 :                :                  * provided.
                               2373                 :                :                  */
 1816 peter@eisentraut.org     2374                 :            463 :                 val = SysCacheGetAttr(CONSTROID, tup,
                               2375                 :                :                                       Anum_pg_constraint_confdelsetcols, &isnull);
                               2376         [ +  + ]:            463 :                 if (!isnull)
                               2377                 :                :                 {
 1544 drowley@postgresql.o     2378                 :              8 :                     appendStringInfoString(&buf, " (");
  802 peter@eisentraut.org     2379                 :              8 :                     decompile_column_index_array(val, conForm->conrelid, false, &buf);
 1544 drowley@postgresql.o     2380                 :              8 :                     appendStringInfoChar(&buf, ')');
                               2381                 :                :                 }
                               2382                 :                : 
 8851 bruce@momjian.us         2383                 :            463 :                 break;
                               2384                 :                :             }
 8689                          2385                 :           2200 :         case CONSTRAINT_PRIMARY:
                               2386                 :                :         case CONSTRAINT_UNIQUE:
                               2387                 :                :             {
                               2388                 :                :                 Datum       val;
                               2389                 :                :                 Oid         indexId;
                               2390                 :                :                 int         keyatts;
                               2391                 :                :                 HeapTuple   indtup;
                               2392                 :                : 
                               2393                 :                :                 /* Start off the constraint definition */
                               2394         [ +  + ]:           2200 :                 if (conForm->contype == CONSTRAINT_PRIMARY)
 1759 peter@eisentraut.org     2395                 :           1778 :                     appendStringInfoString(&buf, "PRIMARY KEY ");
                               2396                 :                :                 else
                               2397                 :            422 :                     appendStringInfoString(&buf, "UNIQUE ");
                               2398                 :                : 
                               2399                 :           2200 :                 indexId = conForm->conindid;
                               2400                 :                : 
                               2401                 :           2200 :                 indtup = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexId));
                               2402         [ -  + ]:           2200 :                 if (!HeapTupleIsValid(indtup))
 1759 peter@eisentraut.org     2403         [ #  # ]:UBC           0 :                     elog(ERROR, "cache lookup failed for index %u", indexId);
 1759 peter@eisentraut.org     2404         [ +  + ]:CBC        2200 :                 if (conForm->contype == CONSTRAINT_UNIQUE &&
                               2405         [ -  + ]:            422 :                     ((Form_pg_index) GETSTRUCT(indtup))->indnullsnotdistinct)
 1759 peter@eisentraut.org     2406                 :UBC           0 :                     appendStringInfoString(&buf, "NULLS NOT DISTINCT ");
                               2407                 :                : 
 1544 drowley@postgresql.o     2408                 :CBC        2200 :                 appendStringInfoChar(&buf, '(');
                               2409                 :                : 
                               2410                 :                :                 /* Fetch and build target column list */
 1344 dgustafsson@postgres     2411                 :           2200 :                 val = SysCacheGetAttrNotNull(CONSTROID, tup,
                               2412                 :                :                                              Anum_pg_constraint_conkey);
                               2413                 :                : 
  802 peter@eisentraut.org     2414                 :           2200 :                 keyatts = decompile_column_index_array(val, conForm->conrelid, false, &buf);
                               2415         [ +  + ]:           2200 :                 if (conForm->conperiod)
                               2416                 :            221 :                     appendStringInfoString(&buf, " WITHOUT OVERLAPS");
                               2417                 :                : 
 4776 rhaas@postgresql.org     2418                 :           2200 :                 appendStringInfoChar(&buf, ')');
                               2419                 :                : 
                               2420                 :                :                 /* Build including column list (from pg_index.indkeys) */
 1344 dgustafsson@postgres     2421                 :           2200 :                 val = SysCacheGetAttrNotNull(INDEXRELID, indtup,
                               2422                 :                :                                              Anum_pg_index_indnatts);
 3008 alvherre@alvh.no-ip.     2423         [ +  + ]:           2200 :                 if (DatumGetInt32(val) > keyatts)
                               2424                 :                :                 {
                               2425                 :                :                     Datum       cols;
                               2426                 :                :                     Datum      *keys;
                               2427                 :                :                     int         nKeys;
                               2428                 :                :                     int         j;
                               2429                 :                : 
 3157 teodor@sigaev.ru         2430                 :             48 :                     appendStringInfoString(&buf, " INCLUDE (");
                               2431                 :                : 
 1344 dgustafsson@postgres     2432                 :             48 :                     cols = SysCacheGetAttrNotNull(INDEXRELID, indtup,
                               2433                 :                :                                                   Anum_pg_index_indkey);
                               2434                 :                : 
 1611 peter@eisentraut.org     2435                 :             48 :                     deconstruct_array_builtin(DatumGetArrayTypeP(cols), INT2OID,
                               2436                 :                :                                               &keys, NULL, &nKeys);
                               2437                 :                : 
 3008 alvherre@alvh.no-ip.     2438         [ +  + ]:            144 :                     for (j = keyatts; j < nKeys; j++)
                               2439                 :                :                     {
                               2440                 :                :                         char       *colName;
                               2441                 :                : 
                               2442                 :             96 :                         colName = get_attname(conForm->conrelid,
                               2443                 :             96 :                                               DatumGetInt16(keys[j]), false);
                               2444         [ +  + ]:             96 :                         if (j > keyatts)
                               2445                 :             48 :                             appendStringInfoString(&buf, ", ");
                               2446                 :             96 :                         appendStringInfoString(&buf, quote_identifier(colName));
                               2447                 :                :                     }
                               2448                 :                : 
 3157 teodor@sigaev.ru         2449                 :             48 :                     appendStringInfoChar(&buf, ')');
                               2450                 :                :                 }
 3008 alvherre@alvh.no-ip.     2451                 :           2200 :                 ReleaseSysCache(indtup);
                               2452                 :                : 
                               2453                 :                :                 /* XXX why do we only print these bits if fullCommand? */
 6986 tgl@sss.pgh.pa.us        2454   [ +  +  +  - ]:           2200 :                 if (fullCommand && OidIsValid(indexId))
                               2455                 :                :                 {
                               2456                 :            136 :                     char       *options = flatten_reloptions(indexId);
                               2457                 :                :                     Oid         tblspc;
                               2458                 :                : 
 7454 bruce@momjian.us         2459         [ -  + ]:            136 :                     if (options)
                               2460                 :                :                     {
 7454 bruce@momjian.us         2461                 :UBC           0 :                         appendStringInfo(&buf, " WITH (%s)", options);
                               2462                 :              0 :                         pfree(options);
                               2463                 :                :                     }
                               2464                 :                : 
                               2465                 :                :                     /*
                               2466                 :                :                      * Print the tablespace, unless it's the database default.
                               2467                 :                :                      * This is to help ALTER TABLE usage of this facility,
                               2468                 :                :                      * which needs this behavior to recreate exact catalog
                               2469                 :                :                      * state.
                               2470                 :                :                      */
 6986 tgl@sss.pgh.pa.us        2471                 :CBC         136 :                     tblspc = get_rel_tablespace(indexId);
                               2472         [ +  + ]:            136 :                     if (OidIsValid(tblspc))
                               2473                 :             16 :                         appendStringInfo(&buf, " USING INDEX TABLESPACE %s",
 3447                          2474                 :             16 :                                          quote_identifier(get_tablespace_name(tblspc)));
                               2475                 :                :                 }
                               2476                 :                : 
 8689 bruce@momjian.us         2477                 :           2200 :                 break;
                               2478                 :                :             }
                               2479                 :           1319 :         case CONSTRAINT_CHECK:
                               2480                 :                :             {
                               2481                 :                :                 Datum       val;
                               2482                 :                :                 char       *conbin;
                               2483                 :                :                 char       *consrc;
                               2484                 :                :                 Node       *expr;
                               2485                 :                :                 List       *context;
                               2486                 :                : 
                               2487                 :                :                 /* Fetch constraint expression in parsetree form */
 1344 dgustafsson@postgres     2488                 :           1319 :                 val = SysCacheGetAttrNotNull(CONSTROID, tup,
                               2489                 :                :                                              Anum_pg_constraint_conbin);
                               2490                 :                : 
 6822 tgl@sss.pgh.pa.us        2491                 :           1319 :                 conbin = TextDatumGetCString(val);
 8557 bruce@momjian.us         2492                 :           1319 :                 expr = stringToNode(conbin);
                               2493                 :                : 
                               2494                 :                :                 /* Set up deparsing context for Var nodes in constraint */
                               2495         [ +  + ]:           1319 :                 if (conForm->conrelid != InvalidOid)
                               2496                 :                :                 {
                               2497                 :                :                     /* relation constraint */
 5870 tgl@sss.pgh.pa.us        2498                 :           1172 :                     context = deparse_context_for(get_relation_name(conForm->conrelid),
                               2499                 :                :                                                   conForm->conrelid);
                               2500                 :                :                 }
                               2501                 :                :                 else
                               2502                 :                :                 {
                               2503                 :                :                     /* domain constraint --- can't have Vars */
 8456                          2504                 :            147 :                     context = NIL;
                               2505                 :                :                 }
                               2506                 :                : 
 8522                          2507                 :           1319 :                 consrc = deparse_expression_pretty(expr, context, false, false,
                               2508                 :                :                                                    prettyFlags, 0);
                               2509                 :                : 
                               2510                 :                :                 /*
                               2511                 :                :                  * Now emit the constraint definition, adding NO INHERIT if
                               2512                 :                :                  * necessary.
                               2513                 :                :                  *
                               2514                 :                :                  * There are cases where the constraint expression will be
                               2515                 :                :                  * fully parenthesized and we don't need the outer parens ...
                               2516                 :                :                  * but there are other cases where we do need 'em.  Be
                               2517                 :                :                  * conservative for now.
                               2518                 :                :                  *
                               2519                 :                :                  * Note that simply checking for leading '(' and trailing ')'
                               2520                 :                :                  * would NOT be good enough, consider "(x > 0) AND (y > 0)".
                               2521                 :                :                  */
 5240 alvherre@alvh.no-ip.     2522                 :           1319 :                 appendStringInfo(&buf, "CHECK (%s)%s",
                               2523                 :                :                                  consrc,
                               2524         [ +  + ]:           1319 :                                  conForm->connoinherit ? " NO INHERIT" : "");
 8689 bruce@momjian.us         2525                 :           1319 :                 break;
                               2526                 :                :             }
  750 alvherre@alvh.no-ip.     2527                 :            292 :         case CONSTRAINT_NOTNULL:
                               2528                 :                :             {
                               2529         [ +  + ]:            292 :                 if (conForm->conrelid)
                               2530                 :                :                 {
                               2531                 :                :                     AttrNumber  attnum;
                               2532                 :                : 
                               2533                 :            232 :                     attnum = extractNotNullColumn(tup);
                               2534                 :                : 
                               2535                 :            232 :                     appendStringInfo(&buf, "NOT NULL %s",
                               2536                 :            232 :                                      quote_identifier(get_attname(conForm->conrelid,
                               2537                 :                :                                                                   attnum, false)));
                               2538         [ -  + ]:            232 :                     if (((Form_pg_constraint) GETSTRUCT(tup))->connoinherit)
  750 alvherre@alvh.no-ip.     2539                 :UBC           0 :                         appendStringInfoString(&buf, " NO INHERIT");
                               2540                 :                :                 }
  750 alvherre@alvh.no-ip.     2541         [ +  - ]:CBC          60 :                 else if (conForm->contypid)
                               2542                 :                :                 {
                               2543                 :                :                     /* conkey is null for domain not-null constraints */
                               2544                 :             60 :                     appendStringInfoString(&buf, "NOT NULL");
                               2545                 :                :                 }
                               2546                 :            292 :                 break;
                               2547                 :                :             }
                               2548                 :                : 
 6159 tgl@sss.pgh.pa.us        2549                 :UBC           0 :         case CONSTRAINT_TRIGGER:
                               2550                 :                : 
                               2551                 :                :             /*
                               2552                 :                :              * There isn't an ALTER TABLE syntax for creating a user-defined
                               2553                 :                :              * constraint trigger, but it seems better to print something than
                               2554                 :                :              * throw an error; if we throw error then this function couldn't
                               2555                 :                :              * safely be applied to all rows of pg_constraint.
                               2556                 :                :              */
 4776 rhaas@postgresql.org     2557                 :              0 :             appendStringInfoString(&buf, "TRIGGER");
 6159 tgl@sss.pgh.pa.us        2558                 :              0 :             break;
 6200 tgl@sss.pgh.pa.us        2559                 :CBC         117 :         case CONSTRAINT_EXCLUSION:
                               2560                 :                :             {
 6119 bruce@momjian.us         2561                 :            117 :                 Oid         indexOid = conForm->conindid;
                               2562                 :                :                 Datum       val;
                               2563                 :                :                 Datum      *elems;
                               2564                 :                :                 int         nElems;
                               2565                 :                :                 int         i;
                               2566                 :                :                 Oid        *operators;
                               2567                 :                : 
                               2568                 :                :                 /* Extract operator OIDs from the pg_constraint tuple */
 1344 dgustafsson@postgres     2569                 :            117 :                 val = SysCacheGetAttrNotNull(CONSTROID, tup,
                               2570                 :                :                                              Anum_pg_constraint_conexclop);
                               2571                 :                : 
 1611 peter@eisentraut.org     2572                 :            117 :                 deconstruct_array_builtin(DatumGetArrayTypeP(val), OIDOID,
                               2573                 :                :                                           &elems, NULL, &nElems);
                               2574                 :                : 
  103 michael@paquier.xyz      2575                 :GNC         117 :                 operators = palloc_array(Oid, nElems);
 6200 tgl@sss.pgh.pa.us        2576         [ +  + ]:CBC         336 :                 for (i = 0; i < nElems; i++)
                               2577                 :            219 :                     operators[i] = DatumGetObjectId(elems[i]);
                               2578                 :                : 
                               2579                 :                :                 /* pg_get_indexdef_worker does the rest */
                               2580                 :                :                 /* suppress tablespace because pg_dump wants it that way */
                               2581                 :            117 :                 appendStringInfoString(&buf,
                               2582                 :            117 :                                        pg_get_indexdef_worker(indexOid,
                               2583                 :                :                                                               0,
                               2584                 :                :                                                               operators,
                               2585                 :                :                                                               false,
                               2586                 :                :                                                               false,
                               2587                 :                :                                                               false,
                               2588                 :                :                                                               false,
                               2589                 :                :                                                               prettyFlags,
                               2590                 :                :                                                               false));
                               2591                 :            117 :                 break;
                               2592                 :                :             }
 8870 tgl@sss.pgh.pa.us        2593                 :UBC           0 :         default:
 8475 peter_e@gmx.net          2594         [ #  # ]:              0 :             elog(ERROR, "invalid constraint type \"%c\"", conForm->contype);
                               2595                 :                :             break;
                               2596                 :                :     }
                               2597                 :                : 
 6331 tgl@sss.pgh.pa.us        2598         [ +  + ]:CBC        4391 :     if (conForm->condeferrable)
 4776 rhaas@postgresql.org     2599                 :             90 :         appendStringInfoString(&buf, " DEFERRABLE");
 6331 tgl@sss.pgh.pa.us        2600         [ +  + ]:           4391 :     if (conForm->condeferred)
 4776 rhaas@postgresql.org     2601                 :             39 :         appendStringInfoString(&buf, " INITIALLY DEFERRED");
                               2602                 :                : 
                               2603                 :                :     /* Validated status is irrelevant when the constraint is NOT ENFORCED. */
  686 peter@eisentraut.org     2604         [ +  + ]:           4391 :     if (!conForm->conenforced)
                               2605                 :             57 :         appendStringInfoString(&buf, " NOT ENFORCED");
                               2606         [ +  + ]:           4334 :     else if (!conForm->convalidated)
 5658 alvherre@alvh.no-ip.     2607                 :            130 :         appendStringInfoString(&buf, " NOT VALID");
                               2608                 :                : 
                               2609                 :                :     /* Cleanup */
 4619 simon@2ndQuadrant.co     2610                 :           4391 :     systable_endscan(scandesc);
 2868 andres@anarazel.de       2611                 :           4391 :     table_close(relation, AccessShareLock);
                               2612                 :                : 
 8242 tgl@sss.pgh.pa.us        2613                 :           4391 :     return buf.data;
                               2614                 :                : }
                               2615                 :                : 
                               2616                 :                : 
                               2617                 :                : /*
                               2618                 :                :  * Convert an int16[] Datum into a comma-separated list of column names
                               2619                 :                :  * for the indicated relation; append the list to buf.  Returns the number
                               2620                 :                :  * of keys.
                               2621                 :                :  */
                               2622                 :                : static int
 8870                          2623                 :           3134 : decompile_column_index_array(Datum column_index_array, Oid relId,
                               2624                 :                :                              bool withPeriod, StringInfo buf)
                               2625                 :                : {
                               2626                 :                :     Datum      *keys;
                               2627                 :                :     int         nKeys;
                               2628                 :                :     int         j;
                               2629                 :                : 
                               2630                 :                :     /* Extract data from array of int16 */
 1611 peter@eisentraut.org     2631                 :           3134 :     deconstruct_array_builtin(DatumGetArrayTypeP(column_index_array), INT2OID,
                               2632                 :                :                               &keys, NULL, &nKeys);
                               2633                 :                : 
 8870 tgl@sss.pgh.pa.us        2634         [ +  + ]:           7557 :     for (j = 0; j < nKeys; j++)
                               2635                 :                :     {
                               2636                 :                :         char       *colName;
                               2637                 :                : 
 3211 alvherre@alvh.no-ip.     2638                 :           4423 :         colName = get_attname(relId, DatumGetInt16(keys[j]), false);
                               2639                 :                : 
 8870 tgl@sss.pgh.pa.us        2640         [ +  + ]:           4423 :         if (j == 0)
 8337 neilc@samurai.com        2641                 :           3134 :             appendStringInfoString(buf, quote_identifier(colName));
                               2642                 :                :         else
  802 peter@eisentraut.org     2643         [ +  + ]:           1423 :             appendStringInfo(buf, ", %s%s",
                               2644         [ +  + ]:            134 :                              (withPeriod && j == nKeys - 1) ? "PERIOD " : "",
                               2645                 :                :                              quote_identifier(colName));
                               2646                 :                :     }
                               2647                 :                : 
 3008 alvherre@alvh.no-ip.     2648                 :           3134 :     return nKeys;
                               2649                 :                : }
                               2650                 :                : 
                               2651                 :                : 
                               2652                 :                : /* ----------
                               2653                 :                :  * pg_get_expr          - Decompile an expression tree
                               2654                 :                :  *
                               2655                 :                :  * Input: an expression tree in nodeToString form, and a relation OID
                               2656                 :                :  *
                               2657                 :                :  * Output: reverse-listed expression
                               2658                 :                :  *
                               2659                 :                :  * Currently, the expression can only refer to a single relation, namely
                               2660                 :                :  * the one specified by the second parameter.  This is sufficient for
                               2661                 :                :  * partial indexes, column default expressions, etc.  We also support
                               2662                 :                :  * Var-free expressions, for which the OID can be InvalidOid.
                               2663                 :                :  *
                               2664                 :                :  * If the OID is nonzero but not actually valid, don't throw an error,
                               2665                 :                :  * just return NULL.  This is a bit questionable, but it's what we've
                               2666                 :                :  * done historically, and it can help avoid unwanted failures when
                               2667                 :                :  * examining catalog entries for just-deleted relations.
                               2668                 :                :  *
                               2669                 :                :  * We expect this function to work, or throw a reasonably clean error,
                               2670                 :                :  * for any node tree that can appear in a catalog pg_node_tree column.
                               2671                 :                :  * Query trees, such as those appearing in pg_rewrite.ev_action, are
                               2672                 :                :  * not supported.  Nor are expressions in more than one relation, which
                               2673                 :                :  * can appear in places like pg_rewrite.ev_qual.
                               2674                 :                :  * ----------
                               2675                 :                :  */
                               2676                 :                : Datum
 9266 tgl@sss.pgh.pa.us        2677                 :           5259 : pg_get_expr(PG_FUNCTION_ARGS)
                               2678                 :                : {
 3548 noah@leadboat.com        2679                 :           5259 :     text       *expr = PG_GETARG_TEXT_PP(0);
 8517 bruce@momjian.us         2680                 :           5259 :     Oid         relid = PG_GETARG_OID(1);
                               2681                 :                :     text       *result;
                               2682                 :                :     int         prettyFlags;
                               2683                 :                : 
 5046 tgl@sss.pgh.pa.us        2684                 :           5259 :     prettyFlags = PRETTYFLAG_INDENT;
                               2685                 :                : 
 1023                          2686                 :           5259 :     result = pg_get_expr_worker(expr, relid, prettyFlags);
                               2687         [ +  + ]:           5259 :     if (result)
                               2688                 :           5257 :         PG_RETURN_TEXT_P(result);
                               2689                 :                :     else
                               2690                 :              2 :         PG_RETURN_NULL();
                               2691                 :                : }
                               2692                 :                : 
                               2693                 :                : Datum
 8522                          2694                 :            496 : pg_get_expr_ext(PG_FUNCTION_ARGS)
                               2695                 :                : {
 3548 noah@leadboat.com        2696                 :            496 :     text       *expr = PG_GETARG_TEXT_PP(0);
 8517 bruce@momjian.us         2697                 :            496 :     Oid         relid = PG_GETARG_OID(1);
 8522 tgl@sss.pgh.pa.us        2698                 :            496 :     bool        pretty = PG_GETARG_BOOL(2);
                               2699                 :                :     text       *result;
                               2700                 :                :     int         prettyFlags;
                               2701                 :                : 
 1706                          2702         [ +  - ]:            496 :     prettyFlags = GET_PRETTY_FLAGS(pretty);
                               2703                 :                : 
 1023                          2704                 :            496 :     result = pg_get_expr_worker(expr, relid, prettyFlags);
                               2705         [ +  - ]:            496 :     if (result)
                               2706                 :            496 :         PG_RETURN_TEXT_P(result);
                               2707                 :                :     else
 1023 tgl@sss.pgh.pa.us        2708                 :UBC           0 :         PG_RETURN_NULL();
                               2709                 :                : }
                               2710                 :                : 
                               2711                 :                : static text *
 1023 tgl@sss.pgh.pa.us        2712                 :CBC        5755 : pg_get_expr_worker(text *expr, Oid relid, int prettyFlags)
                               2713                 :                : {
                               2714                 :                :     Node       *node;
                               2715                 :                :     Node       *tst;
                               2716                 :                :     Relids      relids;
                               2717                 :                :     List       *context;
                               2718                 :                :     char       *exprstr;
                               2719                 :           5755 :     Relation    rel = NULL;
                               2720                 :                :     char       *str;
                               2721                 :                : 
                               2722                 :                :     /* Convert input pg_node_tree (really TEXT) object to C string */
 6822                          2723                 :           5755 :     exprstr = text_to_cstring(expr);
                               2724                 :                : 
                               2725                 :                :     /* Convert expression to node tree */
 9266                          2726                 :           5755 :     node = (Node *) stringToNode(exprstr);
                               2727                 :                : 
 6395                          2728                 :           5755 :     pfree(exprstr);
                               2729                 :                : 
                               2730                 :                :     /*
                               2731                 :                :      * Throw error if the input is a querytree rather than an expression tree.
                               2732                 :                :      * While we could support queries here, there seems no very good reason
                               2733                 :                :      * to.  In most such catalog columns, we'll see a List of Query nodes, or
                               2734                 :                :      * even nested Lists, so drill down to a non-List node before checking.
                               2735                 :                :      */
 1784                          2736                 :           5755 :     tst = node;
                               2737   [ +  -  -  + ]:           5755 :     while (tst && IsA(tst, List))
 1784 tgl@sss.pgh.pa.us        2738                 :UBC           0 :         tst = linitial((List *) tst);
 1784 tgl@sss.pgh.pa.us        2739   [ +  -  -  + ]:CBC        5755 :     if (tst && IsA(tst, Query))
 1784 tgl@sss.pgh.pa.us        2740         [ #  # ]:UBC           0 :         ereport(ERROR,
                               2741                 :                :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                               2742                 :                :                  errmsg("input is a query, not an expression")));
                               2743                 :                : 
                               2744                 :                :     /*
                               2745                 :                :      * Throw error if the expression contains Vars we won't be able to
                               2746                 :                :      * deparse.
                               2747                 :                :      */
 1784 tgl@sss.pgh.pa.us        2748                 :CBC        5755 :     relids = pull_varnos(NULL, node);
                               2749         [ +  + ]:           5755 :     if (OidIsValid(relid))
                               2750                 :                :     {
                               2751         [ -  + ]:           5687 :         if (!bms_is_subset(relids, bms_make_singleton(1)))
 1784 tgl@sss.pgh.pa.us        2752         [ #  # ]:UBC           0 :             ereport(ERROR,
                               2753                 :                :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                               2754                 :                :                      errmsg("expression contains variables of more than one relation")));
                               2755                 :                :     }
                               2756                 :                :     else
                               2757                 :                :     {
 1784 tgl@sss.pgh.pa.us        2758         [ -  + ]:CBC          68 :         if (!bms_is_empty(relids))
 1784 tgl@sss.pgh.pa.us        2759         [ #  # ]:UBC           0 :             ereport(ERROR,
                               2760                 :                :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                               2761                 :                :                      errmsg("expression contains variables")));
                               2762                 :                :     }
                               2763                 :                : 
                               2764                 :                :     /*
                               2765                 :                :      * Prepare deparse context if needed.  If we are deparsing with a relid,
                               2766                 :                :      * we need to transiently open and lock the rel, to make sure it won't go
                               2767                 :                :      * away underneath us.  (set_relation_column_names would lock it anyway,
                               2768                 :                :      * so this isn't really introducing any new behavior.)
                               2769                 :                :      */
 6395 tgl@sss.pgh.pa.us        2770         [ +  + ]:CBC        5755 :     if (OidIsValid(relid))
                               2771                 :                :     {
 1023                          2772                 :           5687 :         rel = try_relation_open(relid, AccessShareLock);
                               2773         [ +  + ]:           5687 :         if (rel == NULL)
                               2774                 :              2 :             return NULL;
                               2775                 :           5685 :         context = deparse_context_for(RelationGetRelationName(rel), relid);
                               2776                 :                :     }
                               2777                 :                :     else
 6395                          2778                 :             68 :         context = NIL;
                               2779                 :                : 
                               2780                 :                :     /* Deparse */
 8522                          2781                 :           5753 :     str = deparse_expression_pretty(node, context, false, false,
                               2782                 :                :                                     prettyFlags, 0);
                               2783                 :                : 
 1023                          2784         [ +  + ]:           5753 :     if (rel != NULL)
                               2785                 :           5685 :         relation_close(rel, AccessShareLock);
                               2786                 :                : 
 6395                          2787                 :           5753 :     return string_to_text(str);
                               2788                 :                : }
                               2789                 :                : 
                               2790                 :                : 
                               2791                 :                : /* ----------
                               2792                 :                :  * pg_get_userbyid      - Get a user name by roleid and
                               2793                 :                :  *                fallback to 'unknown (OID=n)'
                               2794                 :                :  * ----------
                               2795                 :                :  */
                               2796                 :                : Datum
 9664                          2797                 :           1215 : pg_get_userbyid(PG_FUNCTION_ARGS)
                               2798                 :                : {
 7823                          2799                 :           1215 :     Oid         roleid = PG_GETARG_OID(0);
                               2800                 :                :     Name        result;
                               2801                 :                :     HeapTuple   roletup;
                               2802                 :                :     Form_pg_authid role_rec;
                               2803                 :                : 
                               2804                 :                :     /*
                               2805                 :                :      * Allocate space for the result
                               2806                 :                :      */
 9664                          2807                 :           1215 :     result = (Name) palloc(NAMEDATALEN);
 9883 bruce@momjian.us         2808                 :           1215 :     memset(NameStr(*result), 0, NAMEDATALEN);
                               2809                 :                : 
                               2810                 :                :     /*
                               2811                 :                :      * Get the pg_authid entry and print the result
                               2812                 :                :      */
 6131 rhaas@postgresql.org     2813                 :           1215 :     roletup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
 7823 tgl@sss.pgh.pa.us        2814         [ +  - ]:           1215 :     if (HeapTupleIsValid(roletup))
                               2815                 :                :     {
                               2816                 :           1215 :         role_rec = (Form_pg_authid) GETSTRUCT(roletup);
 2301 peter@eisentraut.org     2817                 :           1215 :         *result = role_rec->rolname;
 7823 tgl@sss.pgh.pa.us        2818                 :           1215 :         ReleaseSysCache(roletup);
                               2819                 :                :     }
                               2820                 :                :     else
 7823 tgl@sss.pgh.pa.us        2821                 :UBC           0 :         sprintf(NameStr(*result), "unknown (OID=%u)", roleid);
                               2822                 :                : 
 9664 tgl@sss.pgh.pa.us        2823                 :CBC        1215 :     PG_RETURN_NAME(result);
                               2824                 :                : }
                               2825                 :                : 
                               2826                 :                : 
                               2827                 :                : /*
                               2828                 :                :  * pg_get_serial_sequence
                               2829                 :                :  *      Get the name of the sequence used by an identity or serial column,
                               2830                 :                :  *      formatted suitably for passing to setval, nextval or currval.
                               2831                 :                :  *      First parameter is not treated as double-quoted, second parameter
                               2832                 :                :  *      is --- see documentation for reason.
                               2833                 :                :  */
                               2834                 :                : Datum
 8191                          2835                 :              8 : pg_get_serial_sequence(PG_FUNCTION_ARGS)
                               2836                 :                : {
 3548 noah@leadboat.com        2837                 :              8 :     text       *tablename = PG_GETARG_TEXT_PP(0);
 6822 tgl@sss.pgh.pa.us        2838                 :              8 :     text       *columnname = PG_GETARG_TEXT_PP(1);
                               2839                 :                :     RangeVar   *tablerv;
                               2840                 :                :     Oid         tableOid;
                               2841                 :                :     char       *column;
                               2842                 :                :     AttrNumber  attnum;
 8126 bruce@momjian.us         2843                 :              8 :     Oid         sequenceId = InvalidOid;
                               2844                 :                :     Relation    depRel;
                               2845                 :                :     ScanKeyData key[3];
                               2846                 :                :     SysScanDesc scan;
                               2847                 :                :     HeapTuple   tup;
                               2848                 :                : 
                               2849                 :                :     /* Look up table name.  Can't lock it - we might not have privileges. */
 7855 neilc@samurai.com        2850                 :              8 :     tablerv = makeRangeVarFromNameList(textToQualifiedNameList(tablename));
 5477 rhaas@postgresql.org     2851                 :              8 :     tableOid = RangeVarGetRelid(tablerv, NoLock, false);
                               2852                 :                : 
                               2853                 :                :     /* Get the number of the column */
 6822 tgl@sss.pgh.pa.us        2854                 :              8 :     column = text_to_cstring(columnname);
                               2855                 :                : 
 8191                          2856                 :              8 :     attnum = get_attnum(tableOid, column);
                               2857         [ -  + ]:              8 :     if (attnum == InvalidAttrNumber)
 8191 tgl@sss.pgh.pa.us        2858         [ #  # ]:UBC           0 :         ereport(ERROR,
                               2859                 :                :                 (errcode(ERRCODE_UNDEFINED_COLUMN),
                               2860                 :                :                  errmsg("column \"%s\" of relation \"%s\" does not exist",
                               2861                 :                :                         column, tablerv->relname)));
                               2862                 :                : 
                               2863                 :                :     /* Search the dependency table for the dependent sequence */
 2868 andres@anarazel.de       2864                 :CBC           8 :     depRel = table_open(DependRelationId, AccessShareLock);
                               2865                 :                : 
 8191 tgl@sss.pgh.pa.us        2866                 :              8 :     ScanKeyInit(&key[0],
                               2867                 :                :                 Anum_pg_depend_refclassid,
                               2868                 :                :                 BTEqualStrategyNumber, F_OIDEQ,
                               2869                 :                :                 ObjectIdGetDatum(RelationRelationId));
                               2870                 :              8 :     ScanKeyInit(&key[1],
                               2871                 :                :                 Anum_pg_depend_refobjid,
                               2872                 :                :                 BTEqualStrategyNumber, F_OIDEQ,
                               2873                 :                :                 ObjectIdGetDatum(tableOid));
                               2874                 :              8 :     ScanKeyInit(&key[2],
                               2875                 :                :                 Anum_pg_depend_refobjsubid,
                               2876                 :                :                 BTEqualStrategyNumber, F_INT4EQ,
                               2877                 :                :                 Int32GetDatum(attnum));
                               2878                 :                : 
 7898                          2879                 :              8 :     scan = systable_beginscan(depRel, DependReferenceIndexId, true,
                               2880                 :                :                               NULL, 3, key);
                               2881                 :                : 
 8191                          2882         [ +  - ]:             20 :     while (HeapTupleIsValid(tup = systable_getnext(scan)))
                               2883                 :                :     {
 8126 bruce@momjian.us         2884                 :             20 :         Form_pg_depend deprec = (Form_pg_depend) GETSTRUCT(tup);
                               2885                 :                : 
                               2886                 :                :         /*
                               2887                 :                :          * Look for an auto dependency (serial column) or internal dependency
                               2888                 :                :          * (identity column) of a sequence on a column.  (We need the relkind
                               2889                 :                :          * test because indexes can also have auto dependencies on columns.)
                               2890                 :                :          */
 7898 tgl@sss.pgh.pa.us        2891         [ +  + ]:             20 :         if (deprec->classid == RelationRelationId &&
 8191                          2892         [ +  - ]:              8 :             deprec->objsubid == 0 &&
 3361 peter_e@gmx.net          2893         [ +  + ]:              8 :             (deprec->deptype == DEPENDENCY_AUTO ||
                               2894   [ +  -  +  - ]:             12 :              deprec->deptype == DEPENDENCY_INTERNAL) &&
 7323 tgl@sss.pgh.pa.us        2895                 :              8 :             get_rel_relkind(deprec->objid) == RELKIND_SEQUENCE)
                               2896                 :                :         {
 8191                          2897                 :              8 :             sequenceId = deprec->objid;
                               2898                 :              8 :             break;
                               2899                 :                :         }
                               2900                 :                :     }
                               2901                 :                : 
                               2902                 :              8 :     systable_endscan(scan);
 2868 andres@anarazel.de       2903                 :              8 :     table_close(depRel, AccessShareLock);
                               2904                 :                : 
 8191 tgl@sss.pgh.pa.us        2905         [ +  - ]:              8 :     if (OidIsValid(sequenceId))
                               2906                 :                :     {
                               2907                 :                :         char       *result;
                               2908                 :                : 
 4026                          2909                 :              8 :         result = generate_qualified_relation_name(sequenceId);
                               2910                 :                : 
 8191                          2911                 :              8 :         PG_RETURN_TEXT_P(string_to_text(result));
                               2912                 :                :     }
                               2913                 :                : 
 8191 tgl@sss.pgh.pa.us        2914                 :UBC           0 :     PG_RETURN_NULL();
                               2915                 :                : }
                               2916                 :                : 
                               2917                 :                : 
                               2918                 :                : /*
                               2919                 :                :  * pg_get_functiondef
                               2920                 :                :  *      Returns the complete "CREATE OR REPLACE FUNCTION ..." statement for
                               2921                 :                :  *      the specified function.
                               2922                 :                :  *
                               2923                 :                :  * Note: if you change the output format of this function, be careful not
                               2924                 :                :  * to break psql's rules (in \ef and \sf) for identifying the start of the
                               2925                 :                :  * function body.  To wit: the function body starts on a line that begins with
                               2926                 :                :  * "AS ", "BEGIN ", or "RETURN ", and no preceding line will look like that.
                               2927                 :                :  */
                               2928                 :                : Datum
 6657 tgl@sss.pgh.pa.us        2929                 :CBC         127 : pg_get_functiondef(PG_FUNCTION_ARGS)
                               2930                 :                : {
                               2931                 :            127 :     Oid         funcid = PG_GETARG_OID(0);
                               2932                 :                :     StringInfoData buf;
                               2933                 :                :     StringInfoData dq;
                               2934                 :                :     HeapTuple   proctup;
                               2935                 :                :     Form_pg_proc proc;
                               2936                 :                :     bool        isfunction;
                               2937                 :                :     Datum       tmp;
                               2938                 :                :     bool        isnull;
                               2939                 :                :     const char *prosrc;
                               2940                 :                :     const char *name;
                               2941                 :                :     const char *nsp;
                               2942                 :                :     float4      procost;
                               2943                 :                :     int         oldlen;
                               2944                 :                : 
                               2945                 :            127 :     initStringInfo(&buf);
                               2946                 :                : 
                               2947                 :                :     /* Look up the function */
 6131 rhaas@postgresql.org     2948                 :            127 :     proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
 6657 tgl@sss.pgh.pa.us        2949         [ +  + ]:            127 :     if (!HeapTupleIsValid(proctup))
 3777 rhaas@postgresql.org     2950                 :              4 :         PG_RETURN_NULL();
                               2951                 :                : 
 6657 tgl@sss.pgh.pa.us        2952                 :            123 :     proc = (Form_pg_proc) GETSTRUCT(proctup);
                               2953                 :            123 :     name = NameStr(proc->proname);
                               2954                 :                : 
 3193 peter_e@gmx.net          2955         [ -  + ]:            123 :     if (proc->prokind == PROKIND_AGGREGATE)
 6657 tgl@sss.pgh.pa.us        2956         [ #  # ]:UBC           0 :         ereport(ERROR,
                               2957                 :                :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
                               2958                 :                :                  errmsg("\"%s\" is an aggregate function", name)));
                               2959                 :                : 
 3193 peter_e@gmx.net          2960                 :CBC         123 :     isfunction = (proc->prokind != PROKIND_PROCEDURE);
                               2961                 :                : 
                               2962                 :                :     /*
                               2963                 :                :      * We always qualify the function name, to ensure the right function gets
                               2964                 :                :      * replaced.
                               2965                 :                :      */
 1950 tgl@sss.pgh.pa.us        2966                 :            123 :     nsp = get_namespace_name_or_temp(proc->pronamespace);
 3210 peter_e@gmx.net          2967         [ +  + ]:            123 :     appendStringInfo(&buf, "CREATE OR REPLACE %s %s(",
                               2968                 :                :                      isfunction ? "FUNCTION" : "PROCEDURE",
                               2969                 :                :                      quote_qualified_identifier(nsp, name));
 6568                          2970                 :            123 :     (void) print_function_arguments(&buf, proctup, false, true);
 3210                          2971                 :            123 :     appendStringInfoString(&buf, ")\n");
                               2972         [ +  + ]:            123 :     if (isfunction)
                               2973                 :                :     {
                               2974                 :            110 :         appendStringInfoString(&buf, " RETURNS ");
                               2975                 :            110 :         print_function_rettype(&buf, proctup);
                               2976                 :            110 :         appendStringInfoChar(&buf, '\n');
                               2977                 :                :     }
                               2978                 :                : 
 4234                          2979                 :            123 :     print_function_trftypes(&buf, proctup);
                               2980                 :                : 
 3210                          2981                 :            123 :     appendStringInfo(&buf, " LANGUAGE %s\n",
 3447 tgl@sss.pgh.pa.us        2982                 :            123 :                      quote_identifier(get_language_name(proc->prolang, false)));
                               2983                 :                : 
                               2984                 :                :     /* Emit some miscellaneous options on one line */
 6657                          2985                 :            123 :     oldlen = buf.len;
                               2986                 :                : 
 3193 peter_e@gmx.net          2987         [ -  + ]:            123 :     if (proc->prokind == PROKIND_WINDOW)
 6541 tgl@sss.pgh.pa.us        2988                 :UBC           0 :         appendStringInfoString(&buf, " WINDOW");
 6657 tgl@sss.pgh.pa.us        2989   [ +  +  +  - ]:CBC         123 :     switch (proc->provolatile)
                               2990                 :                :     {
                               2991                 :              8 :         case PROVOLATILE_IMMUTABLE:
                               2992                 :              8 :             appendStringInfoString(&buf, " IMMUTABLE");
                               2993                 :              8 :             break;
                               2994                 :             20 :         case PROVOLATILE_STABLE:
                               2995                 :             20 :             appendStringInfoString(&buf, " STABLE");
                               2996                 :             20 :             break;
                               2997                 :             95 :         case PROVOLATILE_VOLATILE:
                               2998                 :             95 :             break;
                               2999                 :                :     }
                               3000                 :                : 
 3868 rhaas@postgresql.org     3001   [ +  -  +  - ]:            123 :     switch (proc->proparallel)
                               3002                 :                :     {
                               3003                 :             17 :         case PROPARALLEL_SAFE:
                               3004                 :             17 :             appendStringInfoString(&buf, " PARALLEL SAFE");
                               3005                 :             17 :             break;
 3868 rhaas@postgresql.org     3006                 :UBC           0 :         case PROPARALLEL_RESTRICTED:
                               3007                 :              0 :             appendStringInfoString(&buf, " PARALLEL RESTRICTED");
                               3008                 :              0 :             break;
 3868 rhaas@postgresql.org     3009                 :CBC         106 :         case PROPARALLEL_UNSAFE:
                               3010                 :            106 :             break;
                               3011                 :                :     }
                               3012                 :                : 
 6657 tgl@sss.pgh.pa.us        3013         [ +  + ]:            123 :     if (proc->proisstrict)
                               3014                 :             32 :         appendStringInfoString(&buf, " STRICT");
                               3015         [ +  + ]:            123 :     if (proc->prosecdef)
                               3016                 :              4 :         appendStringInfoString(&buf, " SECURITY DEFINER");
 4202                          3017         [ -  + ]:            123 :     if (proc->proleakproof)
 4202 tgl@sss.pgh.pa.us        3018                 :UBC           0 :         appendStringInfoString(&buf, " LEAKPROOF");
                               3019                 :                : 
                               3020                 :                :     /* This code for the default cost and rows should match functioncmds.c */
 6657 tgl@sss.pgh.pa.us        3021         [ +  - ]:CBC         123 :     if (proc->prolang == INTERNALlanguageId ||
                               3022         [ +  + ]:            123 :         proc->prolang == ClanguageId)
                               3023                 :              5 :         procost = 1;
                               3024                 :                :     else
                               3025                 :            118 :         procost = 100;
                               3026         [ +  + ]:            123 :     if (proc->procost != procost)
                               3027                 :              4 :         appendStringInfo(&buf, " COST %g", proc->procost);
                               3028                 :                : 
                               3029   [ +  +  -  + ]:            123 :     if (proc->prorows > 0 && proc->prorows != 1000)
 6657 tgl@sss.pgh.pa.us        3030                 :UBC           0 :         appendStringInfo(&buf, " ROWS %g", proc->prorows);
                               3031                 :                : 
 2849 tgl@sss.pgh.pa.us        3032         [ -  + ]:CBC         123 :     if (proc->prosupport)
                               3033                 :                :     {
                               3034                 :                :         Oid         argtypes[1];
                               3035                 :                : 
                               3036                 :                :         /*
                               3037                 :                :          * We should qualify the support function's name if it wouldn't be
                               3038                 :                :          * resolved by lookup in the current search path.
                               3039                 :                :          */
 2849 tgl@sss.pgh.pa.us        3040                 :UBC           0 :         argtypes[0] = INTERNALOID;
                               3041                 :              0 :         appendStringInfo(&buf, " SUPPORT %s",
                               3042                 :                :                          generate_function_name(proc->prosupport, 1,
                               3043                 :                :                                                 NIL, argtypes,
                               3044                 :                :                                                 false, NULL, false));
                               3045                 :                :     }
                               3046                 :                : 
 6657 tgl@sss.pgh.pa.us        3047         [ +  + ]:CBC         123 :     if (oldlen != buf.len)
                               3048                 :             41 :         appendStringInfoChar(&buf, '\n');
                               3049                 :                : 
                               3050                 :                :     /* Emit any proconfig options, one per line */
                               3051                 :            123 :     tmp = SysCacheGetAttr(PROCOID, proctup, Anum_pg_proc_proconfig, &isnull);
                               3052         [ +  + ]:            123 :     if (!isnull)
                               3053                 :                :     {
 6379 bruce@momjian.us         3054                 :              4 :         ArrayType  *a = DatumGetArrayTypeP(tmp);
                               3055                 :                :         int         i;
                               3056                 :                : 
 6657 tgl@sss.pgh.pa.us        3057         [ -  + ]:              4 :         Assert(ARR_ELEMTYPE(a) == TEXTOID);
                               3058         [ -  + ]:              4 :         Assert(ARR_NDIM(a) == 1);
                               3059         [ -  + ]:              4 :         Assert(ARR_LBOUND(a)[0] == 1);
                               3060                 :                : 
                               3061         [ +  + ]:             28 :         for (i = 1; i <= ARR_DIMS(a)[0]; i++)
                               3062                 :                :         {
                               3063                 :                :             Datum       d;
                               3064                 :                : 
                               3065                 :             24 :             d = array_ref(a, 1, &i,
                               3066                 :                :                           -1 /* varlenarray */ ,
                               3067                 :                :                           -1 /* TEXT's typlen */ ,
                               3068                 :                :                           false /* TEXT's typbyval */ ,
                               3069                 :                :                           TYPALIGN_INT /* TEXT's typalign */ ,
                               3070                 :                :                           &isnull);
                               3071         [ +  - ]:             24 :             if (!isnull)
                               3072                 :                :             {
                               3073                 :             24 :                 char       *configitem = TextDatumGetCString(d);
                               3074                 :                :                 char       *pos;
                               3075                 :                : 
                               3076                 :             24 :                 pos = strchr(configitem, '=');
                               3077         [ -  + ]:             24 :                 if (pos == NULL)
 6657 tgl@sss.pgh.pa.us        3078                 :UBC           0 :                     continue;
 6657 tgl@sss.pgh.pa.us        3079                 :CBC          24 :                 *pos++ = '\0';
                               3080                 :                : 
                               3081                 :             24 :                 appendStringInfo(&buf, " SET %s TO ",
                               3082                 :                :                                  quote_identifier(configitem));
                               3083                 :                : 
                               3084                 :                :                 /*
                               3085                 :                :                  * Variables that are marked GUC_LIST_QUOTE were already fully
                               3086                 :                :                  * quoted by flatten_set_variable_args() before they were put
                               3087                 :                :                  * into the proconfig array.  However, because the quoting
                               3088                 :                :                  * rules used there aren't exactly like SQL's, we have to
                               3089                 :                :                  * break the list value apart and then quote the elements as
                               3090                 :                :                  * string literals.  (The elements may be double-quoted as-is,
                               3091                 :                :                  * but we can't just feed them to the SQL parser; it would do
                               3092                 :                :                  * the wrong thing with elements that are zero-length or
                               3093                 :                :                  * longer than NAMEDATALEN.)  Also, we need a special case for
                               3094                 :                :                  * empty lists.
                               3095                 :                :                  *
                               3096                 :                :                  * Variables that are not so marked should just be emitted as
                               3097                 :                :                  * simple string literals.  If the variable is not known to
                               3098                 :                :                  * guc.c, we'll do that; this makes it unsafe to use
                               3099                 :                :                  * GUC_LIST_QUOTE for extension variables.
                               3100                 :                :                  */
 3174                          3101         [ +  + ]:             24 :                 if (GetConfigOptionFlags(configitem, true) & GUC_LIST_QUOTE)
                               3102                 :                :                 {
                               3103                 :                :                     List       *namelist;
                               3104                 :                :                     ListCell   *lc;
                               3105                 :                : 
                               3106                 :                :                     /* Parse string into list of identifiers */
 3042                          3107         [ -  + ]:             12 :                     if (!SplitGUCList(pos, ',', &namelist))
                               3108                 :                :                     {
                               3109                 :                :                         /* this shouldn't fail really */
 3042 tgl@sss.pgh.pa.us        3110         [ #  # ]:UBC           0 :                         elog(ERROR, "invalid list syntax in proconfig item");
                               3111                 :                :                     }
                               3112                 :                :                     /* Special case: represent an empty list as NULL */
  389 tgl@sss.pgh.pa.us        3113         [ +  + ]:CBC          12 :                     if (namelist == NIL)
                               3114                 :              4 :                         appendStringInfoString(&buf, "NULL");
 3042                          3115   [ +  +  +  +  :             32 :                     foreach(lc, namelist)
                                              +  + ]
                               3116                 :                :                     {
                               3117                 :             20 :                         char       *curname = (char *) lfirst(lc);
                               3118                 :                : 
                               3119                 :             20 :                         simple_quote_literal(&buf, curname);
 2693                          3120         [ +  + ]:             20 :                         if (lnext(namelist, lc))
 3042                          3121                 :             12 :                             appendStringInfoString(&buf, ", ");
                               3122                 :                :                     }
                               3123                 :                :                 }
                               3124                 :                :                 else
 6657                          3125                 :             12 :                     simple_quote_literal(&buf, pos);
                               3126                 :             24 :                 appendStringInfoChar(&buf, '\n');
                               3127                 :                :             }
                               3128                 :                :         }
                               3129                 :                :     }
                               3130                 :                : 
                               3131                 :                :     /* And finally the function definition ... */
 1915                          3132                 :            123 :     (void) SysCacheGetAttr(PROCOID, proctup, Anum_pg_proc_prosqlbody, &isnull);
 2061 peter@eisentraut.org     3133   [ +  +  +  + ]:            123 :     if (proc->prolang == SQLlanguageId && !isnull)
                               3134                 :                :     {
                               3135                 :             91 :         print_function_sqlbody(&buf, proctup);
                               3136                 :                :     }
                               3137                 :                :     else
                               3138                 :                :     {
                               3139                 :                :         const char *dqmatch;
                               3140                 :                : 
 2026 tgl@sss.pgh.pa.us        3141                 :             32 :         appendStringInfoString(&buf, "AS ");
                               3142                 :                : 
                               3143                 :             32 :         tmp = SysCacheGetAttr(PROCOID, proctup, Anum_pg_proc_probin, &isnull);
                               3144         [ +  + ]:             32 :         if (!isnull)
                               3145                 :                :         {
                               3146                 :              5 :             simple_quote_literal(&buf, TextDatumGetCString(tmp));
                               3147                 :              5 :             appendStringInfoString(&buf, ", "); /* assume prosrc isn't null */
                               3148                 :                :         }
                               3149                 :                : 
 1344 dgustafsson@postgres     3150                 :             32 :         tmp = SysCacheGetAttrNotNull(PROCOID, proctup, Anum_pg_proc_prosrc);
 2026 tgl@sss.pgh.pa.us        3151                 :             32 :         prosrc = TextDatumGetCString(tmp);
                               3152                 :                : 
                               3153                 :                :         /*
                               3154                 :                :          * We always use dollar quoting.  Figure out a suitable delimiter.
                               3155                 :                :          *
                               3156                 :                :          * Since the user is likely to be editing the function body string, we
                               3157                 :                :          * shouldn't use a short delimiter that he might easily create a
                               3158                 :                :          * conflict with.  Hence prefer "$function$"/"$procedure$", but extend
                               3159                 :                :          * if needed.  Each candidate extends the previous one, so we can
                               3160                 :                :          * resume searching at the previous match.
                               3161                 :                :          */
                               3162                 :             32 :         initStringInfo(&dq);
                               3163                 :             32 :         appendStringInfoChar(&dq, '$');
                               3164         [ +  + ]:             32 :         appendStringInfoString(&dq, (isfunction ? "function" : "procedure"));
    9 heikki.linnakangas@i     3165                 :GNC          32 :         dqmatch = prosrc;
                               3166         [ -  + ]:             32 :         while ((dqmatch = strstr(dqmatch, dq.data)) != NULL)
 2026 tgl@sss.pgh.pa.us        3167                 :UBC           0 :             appendStringInfoChar(&dq, 'x');
 2026 tgl@sss.pgh.pa.us        3168                 :CBC          32 :         appendStringInfoChar(&dq, '$');
                               3169                 :                : 
                               3170                 :             32 :         appendBinaryStringInfo(&buf, dq.data, dq.len);
                               3171                 :             32 :         appendStringInfoString(&buf, prosrc);
                               3172                 :             32 :         appendBinaryStringInfo(&buf, dq.data, dq.len);
                               3173                 :                :     }
                               3174                 :                : 
 4776 rhaas@postgresql.org     3175                 :            123 :     appendStringInfoChar(&buf, '\n');
                               3176                 :                : 
 6657 tgl@sss.pgh.pa.us        3177                 :            123 :     ReleaseSysCache(proctup);
                               3178                 :                : 
                               3179                 :            123 :     PG_RETURN_TEXT_P(string_to_text(buf.data));
                               3180                 :                : }
                               3181                 :                : 
                               3182                 :                : /*
                               3183                 :                :  * pg_get_function_arguments
                               3184                 :                :  *      Get a nicely-formatted list of arguments for a function.
                               3185                 :                :  *      This is everything that would go between the parentheses in
                               3186                 :                :  *      CREATE FUNCTION.
                               3187                 :                :  */
                               3188                 :                : Datum
 6707                          3189                 :           2467 : pg_get_function_arguments(PG_FUNCTION_ARGS)
                               3190                 :                : {
                               3191                 :           2467 :     Oid         funcid = PG_GETARG_OID(0);
                               3192                 :                :     StringInfoData buf;
                               3193                 :                :     HeapTuple   proctup;
                               3194                 :                : 
 6131 rhaas@postgresql.org     3195                 :           2467 :     proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
 6707 tgl@sss.pgh.pa.us        3196         [ +  + ]:           2467 :     if (!HeapTupleIsValid(proctup))
 3774 rhaas@postgresql.org     3197                 :              4 :         PG_RETURN_NULL();
                               3198                 :                : 
                               3199                 :           2463 :     initStringInfo(&buf);
                               3200                 :                : 
 6568 peter_e@gmx.net          3201                 :           2463 :     (void) print_function_arguments(&buf, proctup, false, true);
                               3202                 :                : 
 6707 tgl@sss.pgh.pa.us        3203                 :           2463 :     ReleaseSysCache(proctup);
                               3204                 :                : 
                               3205                 :           2463 :     PG_RETURN_TEXT_P(string_to_text(buf.data));
                               3206                 :                : }
                               3207                 :                : 
                               3208                 :                : /*
                               3209                 :                :  * pg_get_function_identity_arguments
                               3210                 :                :  *      Get a formatted list of arguments for a function.
                               3211                 :                :  *      This is everything that would go between the parentheses in
                               3212                 :                :  *      ALTER FUNCTION, etc.  In particular, don't print defaults.
                               3213                 :                :  */
                               3214                 :                : Datum
 6568 peter_e@gmx.net          3215                 :           2113 : pg_get_function_identity_arguments(PG_FUNCTION_ARGS)
                               3216                 :                : {
                               3217                 :           2113 :     Oid         funcid = PG_GETARG_OID(0);
                               3218                 :                :     StringInfoData buf;
                               3219                 :                :     HeapTuple   proctup;
                               3220                 :                : 
 6131 rhaas@postgresql.org     3221                 :           2113 :     proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
 6568 peter_e@gmx.net          3222         [ +  + ]:           2113 :     if (!HeapTupleIsValid(proctup))
 3774 rhaas@postgresql.org     3223                 :              4 :         PG_RETURN_NULL();
                               3224                 :                : 
                               3225                 :           2109 :     initStringInfo(&buf);
                               3226                 :                : 
 6568 peter_e@gmx.net          3227                 :           2109 :     (void) print_function_arguments(&buf, proctup, false, false);
                               3228                 :                : 
                               3229                 :           2109 :     ReleaseSysCache(proctup);
                               3230                 :                : 
                               3231                 :           2109 :     PG_RETURN_TEXT_P(string_to_text(buf.data));
                               3232                 :                : }
                               3233                 :                : 
                               3234                 :                : /*
                               3235                 :                :  * pg_get_function_result
                               3236                 :                :  *      Get a nicely-formatted version of the result type of a function.
                               3237                 :                :  *      This is what would appear after RETURNS in CREATE FUNCTION.
                               3238                 :                :  */
                               3239                 :                : Datum
 6707 tgl@sss.pgh.pa.us        3240                 :           2171 : pg_get_function_result(PG_FUNCTION_ARGS)
                               3241                 :                : {
                               3242                 :           2171 :     Oid         funcid = PG_GETARG_OID(0);
                               3243                 :                :     StringInfoData buf;
                               3244                 :                :     HeapTuple   proctup;
                               3245                 :                : 
 6131 rhaas@postgresql.org     3246                 :           2171 :     proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
 6707 tgl@sss.pgh.pa.us        3247         [ +  + ]:           2171 :     if (!HeapTupleIsValid(proctup))
 3774 rhaas@postgresql.org     3248                 :              4 :         PG_RETURN_NULL();
                               3249                 :                : 
 3193 peter_e@gmx.net          3250         [ +  + ]:           2167 :     if (((Form_pg_proc) GETSTRUCT(proctup))->prokind == PROKIND_PROCEDURE)
                               3251                 :                :     {
 3285                          3252                 :            130 :         ReleaseSysCache(proctup);
                               3253                 :            130 :         PG_RETURN_NULL();
                               3254                 :                :     }
                               3255                 :                : 
 3774 rhaas@postgresql.org     3256                 :           2037 :     initStringInfo(&buf);
                               3257                 :                : 
 6657 tgl@sss.pgh.pa.us        3258                 :           2037 :     print_function_rettype(&buf, proctup);
                               3259                 :                : 
                               3260                 :           2037 :     ReleaseSysCache(proctup);
                               3261                 :                : 
                               3262                 :           2037 :     PG_RETURN_TEXT_P(string_to_text(buf.data));
                               3263                 :                : }
                               3264                 :                : 
                               3265                 :                : /*
                               3266                 :                :  * Guts of pg_get_function_result: append the function's return type
                               3267                 :                :  * to the specified buffer.
                               3268                 :                :  */
                               3269                 :                : static void
                               3270                 :           2147 : print_function_rettype(StringInfo buf, HeapTuple proctup)
                               3271                 :                : {
                               3272                 :           2147 :     Form_pg_proc proc = (Form_pg_proc) GETSTRUCT(proctup);
                               3273                 :           2147 :     int         ntabargs = 0;
                               3274                 :                :     StringInfoData rbuf;
                               3275                 :                : 
                               3276                 :           2147 :     initStringInfo(&rbuf);
                               3277                 :                : 
                               3278         [ +  + ]:           2147 :     if (proc->proretset)
                               3279                 :                :     {
                               3280                 :                :         /* It might be a table function; try to print the arguments */
                               3281                 :            209 :         appendStringInfoString(&rbuf, "TABLE(");
 6554                          3282                 :            209 :         ntabargs = print_function_arguments(&rbuf, proctup, true, false);
 6707                          3283         [ +  + ]:            209 :         if (ntabargs > 0)
 4219 peter_e@gmx.net          3284                 :             39 :             appendStringInfoChar(&rbuf, ')');
                               3285                 :                :         else
 6657 tgl@sss.pgh.pa.us        3286                 :            170 :             resetStringInfo(&rbuf);
                               3287                 :                :     }
                               3288                 :                : 
 6707                          3289         [ +  + ]:           2147 :     if (ntabargs == 0)
                               3290                 :                :     {
                               3291                 :                :         /* Not a table function, so do the normal thing */
 6657                          3292         [ +  + ]:           2108 :         if (proc->proretset)
                               3293                 :            170 :             appendStringInfoString(&rbuf, "SETOF ");
                               3294                 :           2108 :         appendStringInfoString(&rbuf, format_type_be(proc->prorettype));
                               3295                 :                :     }
                               3296                 :                : 
 2685 drowley@postgresql.o     3297                 :           2147 :     appendBinaryStringInfo(buf, rbuf.data, rbuf.len);
 6707 tgl@sss.pgh.pa.us        3298                 :           2147 : }
                               3299                 :                : 
                               3300                 :                : /*
                               3301                 :                :  * Common code for pg_get_function_arguments and pg_get_function_result:
                               3302                 :                :  * append the desired subset of arguments to buf.  We print only TABLE
                               3303                 :                :  * arguments when print_table_args is true, and all the others when it's false.
                               3304                 :                :  * We print argument defaults only if print_defaults is true.
                               3305                 :                :  * Function return value is the number of arguments printed.
                               3306                 :                :  */
                               3307                 :                : static int
                               3308                 :           4904 : print_function_arguments(StringInfo buf, HeapTuple proctup,
                               3309                 :                :                          bool print_table_args, bool print_defaults)
                               3310                 :                : {
 6554                          3311                 :           4904 :     Form_pg_proc proc = (Form_pg_proc) GETSTRUCT(proctup);
                               3312                 :                :     int         numargs;
                               3313                 :                :     Oid        *argtypes;
                               3314                 :                :     char      **argnames;
                               3315                 :                :     char       *argmodes;
 4723                          3316                 :           4904 :     int         insertorderbyat = -1;
                               3317                 :                :     int         argsprinted;
                               3318                 :                :     int         inputargno;
                               3319                 :                :     int         nlackdefaults;
 2693                          3320                 :           4904 :     List       *argdefaults = NIL;
 6554                          3321                 :           4904 :     ListCell   *nextargdefault = NULL;
                               3322                 :                :     int         i;
                               3323                 :                : 
 6707                          3324                 :           4904 :     numargs = get_func_arg_info(proctup,
                               3325                 :                :                                 &argtypes, &argnames, &argmodes);
                               3326                 :                : 
 6554                          3327                 :           4904 :     nlackdefaults = numargs;
                               3328   [ +  +  +  + ]:           4904 :     if (print_defaults && proc->pronargdefaults > 0)
                               3329                 :                :     {
                               3330                 :                :         Datum       proargdefaults;
                               3331                 :                :         bool        isnull;
                               3332                 :                : 
                               3333                 :             21 :         proargdefaults = SysCacheGetAttr(PROCOID, proctup,
                               3334                 :                :                                          Anum_pg_proc_proargdefaults,
                               3335                 :                :                                          &isnull);
                               3336         [ +  - ]:             21 :         if (!isnull)
                               3337                 :                :         {
                               3338                 :                :             char       *str;
                               3339                 :                : 
                               3340                 :             21 :             str = TextDatumGetCString(proargdefaults);
 3567 peter_e@gmx.net          3341                 :             21 :             argdefaults = castNode(List, stringToNode(str));
 6554 tgl@sss.pgh.pa.us        3342                 :             21 :             pfree(str);
                               3343                 :             21 :             nextargdefault = list_head(argdefaults);
                               3344                 :                :             /* nlackdefaults counts only *input* arguments lacking defaults */
                               3345                 :             21 :             nlackdefaults = proc->pronargs - list_length(argdefaults);
                               3346                 :                :         }
                               3347                 :                :     }
                               3348                 :                : 
                               3349                 :                :     /* Check for special treatment of ordered-set aggregates */
 3193 peter_e@gmx.net          3350         [ +  + ]:           4904 :     if (proc->prokind == PROKIND_AGGREGATE)
                               3351                 :                :     {
                               3352                 :                :         HeapTuple   aggtup;
                               3353                 :                :         Form_pg_aggregate agg;
                               3354                 :                : 
 1227 michael@paquier.xyz      3355                 :            594 :         aggtup = SearchSysCache1(AGGFNOID, ObjectIdGetDatum(proc->oid));
 4723 tgl@sss.pgh.pa.us        3356         [ -  + ]:            594 :         if (!HeapTupleIsValid(aggtup))
 4723 tgl@sss.pgh.pa.us        3357         [ #  # ]:UBC           0 :             elog(ERROR, "cache lookup failed for aggregate %u",
                               3358                 :                :                  proc->oid);
 4723 tgl@sss.pgh.pa.us        3359                 :CBC         594 :         agg = (Form_pg_aggregate) GETSTRUCT(aggtup);
                               3360         [ +  + ]:            594 :         if (AGGKIND_IS_ORDERED_SET(agg->aggkind))
                               3361                 :             28 :             insertorderbyat = agg->aggnumdirectargs;
                               3362                 :            594 :         ReleaseSysCache(aggtup);
                               3363                 :                :     }
                               3364                 :                : 
 6707                          3365                 :           4904 :     argsprinted = 0;
 6554                          3366                 :           4904 :     inputargno = 0;
 6707                          3367         [ +  + ]:           9966 :     for (i = 0; i < numargs; i++)
                               3368                 :                :     {
 6379 bruce@momjian.us         3369                 :           5062 :         Oid         argtype = argtypes[i];
                               3370         [ +  + ]:           5062 :         char       *argname = argnames ? argnames[i] : NULL;
                               3371         [ +  + ]:           5062 :         char        argmode = argmodes ? argmodes[i] : PROARGMODE_IN;
                               3372                 :                :         const char *modename;
                               3373                 :                :         bool        isinput;
                               3374                 :                : 
 6707 tgl@sss.pgh.pa.us        3375   [ +  +  +  +  :           5062 :         switch (argmode)
                                              +  - ]
                               3376                 :                :         {
                               3377                 :           4149 :             case PROARGMODE_IN:
                               3378                 :                : 
                               3379                 :                :                 /*
                               3380                 :                :                  * For procedures, explicitly mark all argument modes, so as
                               3381                 :                :                  * to avoid ambiguity with the SQL syntax for DROP PROCEDURE.
                               3382                 :                :                  */
 1997                          3383         [ +  + ]:           4149 :                 if (proc->prokind == PROKIND_PROCEDURE)
                               3384                 :            287 :                     modename = "IN ";
                               3385                 :                :                 else
                               3386                 :           3862 :                     modename = "";
 6554                          3387                 :           4149 :                 isinput = true;
 6707                          3388                 :           4149 :                 break;
                               3389                 :             50 :             case PROARGMODE_INOUT:
                               3390                 :             50 :                 modename = "INOUT ";
 6554                          3391                 :             50 :                 isinput = true;
 6707                          3392                 :             50 :                 break;
                               3393                 :            525 :             case PROARGMODE_OUT:
                               3394                 :            525 :                 modename = "OUT ";
 6554                          3395                 :            525 :                 isinput = false;
 6707                          3396                 :            525 :                 break;
                               3397                 :             92 :             case PROARGMODE_VARIADIC:
                               3398                 :             92 :                 modename = "VARIADIC ";
 6554                          3399                 :             92 :                 isinput = true;
 6707                          3400                 :             92 :                 break;
                               3401                 :            246 :             case PROARGMODE_TABLE:
                               3402                 :            246 :                 modename = "";
 6554                          3403                 :            246 :                 isinput = false;
 6707                          3404                 :            246 :                 break;
 6707 tgl@sss.pgh.pa.us        3405                 :UBC           0 :             default:
                               3406         [ #  # ]:              0 :                 elog(ERROR, "invalid parameter mode '%c'", argmode);
                               3407                 :                :                 modename = NULL;    /* keep compiler quiet */
                               3408                 :                :                 isinput = false;
                               3409                 :                :                 break;
                               3410                 :                :         }
 6554 tgl@sss.pgh.pa.us        3411         [ +  + ]:CBC        5062 :         if (isinput)
                               3412                 :           4291 :             inputargno++;       /* this is a 1-based counter */
                               3413                 :                : 
                               3414         [ +  + ]:           5062 :         if (print_table_args != (argmode == PROARGMODE_TABLE))
                               3415                 :            416 :             continue;
                               3416                 :                : 
 4723                          3417         [ +  + ]:           4646 :         if (argsprinted == insertorderbyat)
                               3418                 :                :         {
                               3419         [ +  - ]:             28 :             if (argsprinted)
                               3420                 :             28 :                 appendStringInfoChar(buf, ' ');
                               3421                 :             28 :             appendStringInfoString(buf, "ORDER BY ");
                               3422                 :                :         }
                               3423         [ +  + ]:           4618 :         else if (argsprinted)
 6707                          3424                 :           1503 :             appendStringInfoString(buf, ", ");
                               3425                 :                : 
                               3426                 :           4646 :         appendStringInfoString(buf, modename);
 6554                          3427   [ +  +  +  + ]:           4646 :         if (argname && argname[0])
 6381                          3428                 :           1643 :             appendStringInfo(buf, "%s ", quote_identifier(argname));
 6707                          3429                 :           4646 :         appendStringInfoString(buf, format_type_be(argtype));
 6554                          3430   [ +  +  +  +  :           4646 :         if (print_defaults && isinput && inputargno > nlackdefaults)
                                              +  + ]
                               3431                 :                :         {
                               3432                 :                :             Node       *expr;
                               3433                 :                : 
                               3434         [ -  + ]:             32 :             Assert(nextargdefault != NULL);
                               3435                 :             32 :             expr = (Node *) lfirst(nextargdefault);
 2693                          3436                 :             32 :             nextargdefault = lnext(argdefaults, nextargdefault);
                               3437                 :                : 
 6554                          3438                 :             32 :             appendStringInfo(buf, " DEFAULT %s",
                               3439                 :                :                              deparse_expression(expr, NIL, false, false));
                               3440                 :                :         }
 6707                          3441                 :           4646 :         argsprinted++;
                               3442                 :                : 
                               3443                 :                :         /* nasty hack: print the last arg twice for variadic ordered-set agg */
 4723                          3444   [ +  +  +  + ]:           4646 :         if (argsprinted == insertorderbyat && i == numargs - 1)
                               3445                 :                :         {
                               3446                 :             14 :             i--;
                               3447                 :                :             /* aggs shouldn't have defaults anyway, but just to be sure ... */
                               3448                 :             14 :             print_defaults = false;
                               3449                 :                :         }
                               3450                 :                :     }
                               3451                 :                : 
 6707                          3452                 :           4904 :     return argsprinted;
                               3453                 :                : }
                               3454                 :                : 
                               3455                 :                : static bool
 4750 peter_e@gmx.net          3456                 :             64 : is_input_argument(int nth, const char *argmodes)
                               3457                 :                : {
                               3458                 :                :     return (!argmodes
                               3459         [ +  + ]:             28 :             || argmodes[nth] == PROARGMODE_IN
                               3460         [ +  - ]:             12 :             || argmodes[nth] == PROARGMODE_INOUT
                               3461   [ +  +  -  + ]:             92 :             || argmodes[nth] == PROARGMODE_VARIADIC);
                               3462                 :                : }
                               3463                 :                : 
                               3464                 :                : /*
                               3465                 :                :  * Append used transformed types to specified buffer
                               3466                 :                :  */
                               3467                 :                : static void
 4234                          3468                 :            123 : print_function_trftypes(StringInfo buf, HeapTuple proctup)
                               3469                 :                : {
                               3470                 :                :     Oid        *trftypes;
                               3471                 :                :     int         ntypes;
                               3472                 :                : 
                               3473                 :            123 :     ntypes = get_func_trftypes(proctup, &trftypes);
                               3474         [ +  + ]:            123 :     if (ntypes > 0)
                               3475                 :                :     {
                               3476                 :                :         int         i;
                               3477                 :                : 
 2133 tgl@sss.pgh.pa.us        3478                 :              3 :         appendStringInfoString(buf, " TRANSFORM ");
 4234 peter_e@gmx.net          3479         [ +  + ]:              8 :         for (i = 0; i < ntypes; i++)
                               3480                 :                :         {
                               3481         [ +  + ]:              5 :             if (i != 0)
                               3482                 :              2 :                 appendStringInfoString(buf, ", ");
 4223 magnus@hagander.net      3483                 :              5 :             appendStringInfo(buf, "FOR TYPE %s", format_type_be(trftypes[i]));
                               3484                 :                :         }
 2133 tgl@sss.pgh.pa.us        3485                 :              3 :         appendStringInfoChar(buf, '\n');
                               3486                 :                :     }
 4234 peter_e@gmx.net          3487                 :            123 : }
                               3488                 :                : 
                               3489                 :                : /*
                               3490                 :                :  * Get textual representation of a function argument's default value.  The
                               3491                 :                :  * second argument of this function is the argument number among all arguments
                               3492                 :                :  * (i.e. proallargtypes, *not* proargtypes), starting with 1, because that's
                               3493                 :                :  * how information_schema.sql uses it.
                               3494                 :                :  */
                               3495                 :                : Datum
 4750                          3496                 :             36 : pg_get_function_arg_default(PG_FUNCTION_ARGS)
                               3497                 :                : {
                               3498                 :             36 :     Oid         funcid = PG_GETARG_OID(0);
                               3499                 :             36 :     int32       nth_arg = PG_GETARG_INT32(1);
                               3500                 :                :     HeapTuple   proctup;
                               3501                 :                :     Form_pg_proc proc;
                               3502                 :                :     int         numargs;
                               3503                 :                :     Oid        *argtypes;
                               3504                 :                :     char      **argnames;
                               3505                 :                :     char       *argmodes;
                               3506                 :                :     int         i;
                               3507                 :                :     List       *argdefaults;
                               3508                 :                :     Node       *node;
                               3509                 :                :     char       *str;
                               3510                 :                :     int         nth_inputarg;
                               3511                 :                :     Datum       proargdefaults;
                               3512                 :                :     bool        isnull;
                               3513                 :                :     int         nth_default;
                               3514                 :                : 
                               3515                 :             36 :     proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
                               3516         [ +  + ]:             36 :     if (!HeapTupleIsValid(proctup))
 3774 rhaas@postgresql.org     3517                 :              8 :         PG_RETURN_NULL();
                               3518                 :                : 
 4750 peter_e@gmx.net          3519                 :             28 :     numargs = get_func_arg_info(proctup, &argtypes, &argnames, &argmodes);
                               3520   [ +  -  +  -  :             28 :     if (nth_arg < 1 || nth_arg > numargs || !is_input_argument(nth_arg - 1, argmodes))
                                              +  + ]
                               3521                 :                :     {
                               3522                 :              8 :         ReleaseSysCache(proctup);
                               3523                 :              8 :         PG_RETURN_NULL();
                               3524                 :                :     }
                               3525                 :                : 
                               3526                 :             20 :     nth_inputarg = 0;
                               3527         [ +  + ]:             56 :     for (i = 0; i < nth_arg; i++)
                               3528         [ +  + ]:             36 :         if (is_input_argument(i, argmodes))
                               3529                 :             32 :             nth_inputarg++;
                               3530                 :                : 
                               3531                 :             20 :     proargdefaults = SysCacheGetAttr(PROCOID, proctup,
                               3532                 :                :                                      Anum_pg_proc_proargdefaults,
                               3533                 :                :                                      &isnull);
                               3534         [ -  + ]:             20 :     if (isnull)
                               3535                 :                :     {
 4750 peter_e@gmx.net          3536                 :UBC           0 :         ReleaseSysCache(proctup);
                               3537                 :              0 :         PG_RETURN_NULL();
                               3538                 :                :     }
                               3539                 :                : 
 4750 peter_e@gmx.net          3540                 :CBC          20 :     str = TextDatumGetCString(proargdefaults);
 3567                          3541                 :             20 :     argdefaults = castNode(List, stringToNode(str));
 4750                          3542                 :             20 :     pfree(str);
                               3543                 :                : 
                               3544                 :             20 :     proc = (Form_pg_proc) GETSTRUCT(proctup);
                               3545                 :                : 
                               3546                 :                :     /*
                               3547                 :                :      * Calculate index into proargdefaults: proargdefaults corresponds to the
                               3548                 :                :      * last N input arguments, where N = pronargdefaults.
                               3549                 :                :      */
                               3550                 :             20 :     nth_default = nth_inputarg - 1 - (proc->pronargs - proc->pronargdefaults);
                               3551                 :                : 
                               3552   [ +  +  -  + ]:             20 :     if (nth_default < 0 || nth_default >= list_length(argdefaults))
                               3553                 :                :     {
                               3554                 :              4 :         ReleaseSysCache(proctup);
                               3555                 :              4 :         PG_RETURN_NULL();
                               3556                 :                :     }
                               3557                 :             16 :     node = list_nth(argdefaults, nth_default);
                               3558                 :             16 :     str = deparse_expression(node, NIL, false, false);
                               3559                 :                : 
                               3560                 :             16 :     ReleaseSysCache(proctup);
                               3561                 :                : 
                               3562                 :             16 :     PG_RETURN_TEXT_P(string_to_text(str));
                               3563                 :                : }
                               3564                 :                : 
                               3565                 :                : static void
 2061 peter@eisentraut.org     3566                 :            141 : print_function_sqlbody(StringInfo buf, HeapTuple proctup)
                               3567                 :                : {
                               3568                 :                :     Datum       proargnames;
                               3569                 :                :     Datum       proargmodes;
                               3570                 :                :     bool        isNull;
                               3571                 :            141 :     deparse_namespace dpns = {0};
                               3572                 :                :     Datum       tmp;
                               3573                 :                :     Node       *n;
                               3574                 :                : 
                               3575                 :            141 :     dpns.funcname = pstrdup(NameStr(((Form_pg_proc) GETSTRUCT(proctup))->proname));
                               3576                 :                : 
   16 tgl@sss.pgh.pa.us        3577                 :            141 :     proargnames = SysCacheGetAttr(PROCOID, proctup,
                               3578                 :                :                                   Anum_pg_proc_proargnames,
                               3579                 :                :                                   &isNull);
                               3580         [ +  + ]:            141 :     if (isNull)
                               3581                 :             87 :         proargnames = PointerGetDatum(NULL);    /* just to be sure */
                               3582                 :                : 
                               3583                 :            141 :     proargmodes = SysCacheGetAttr(PROCOID, proctup,
                               3584                 :                :                                   Anum_pg_proc_proargmodes,
                               3585                 :                :                                   &isNull);
                               3586         [ +  + ]:            141 :     if (isNull)
                               3587                 :            121 :         proargmodes = PointerGetDatum(NULL);    /* just to be sure */
                               3588                 :                : 
                               3589                 :            141 :     dpns.numargs = get_func_input_arg_names(proargnames, proargmodes,
                               3590                 :                :                                             &dpns.argnames);
                               3591                 :                : 
 1344 dgustafsson@postgres     3592                 :            141 :     tmp = SysCacheGetAttrNotNull(PROCOID, proctup, Anum_pg_proc_prosqlbody);
 2061 peter@eisentraut.org     3593                 :            141 :     n = stringToNode(TextDatumGetCString(tmp));
                               3594                 :                : 
                               3595         [ +  + ]:            141 :     if (IsA(n, List))
                               3596                 :                :     {
                               3597                 :                :         List       *stmts;
                               3598                 :                :         ListCell   *lc;
                               3599                 :                : 
                               3600                 :            114 :         stmts = linitial(castNode(List, n));
                               3601                 :                : 
                               3602                 :            114 :         appendStringInfoString(buf, "BEGIN ATOMIC\n");
                               3603                 :                : 
                               3604   [ +  +  +  +  :            223 :         foreach(lc, stmts)
                                              +  + ]
                               3605                 :                :         {
                               3606                 :            109 :             Query      *query = lfirst_node(Query, lc);
                               3607                 :                : 
                               3608                 :                :             /* It seems advisable to get at least AccessShareLock on rels */
 1915 tgl@sss.pgh.pa.us        3609                 :            109 :             AcquireRewriteLocks(query, false, false);
 1652                          3610                 :            109 :             get_query_def(query, buf, list_make1(&dpns), NULL, false,
                               3611                 :                :                           PRETTYFLAG_INDENT, WRAP_COLUMN_DEFAULT, 1);
 2061 peter@eisentraut.org     3612                 :            109 :             appendStringInfoChar(buf, ';');
                               3613                 :            109 :             appendStringInfoChar(buf, '\n');
                               3614                 :                :         }
                               3615                 :                : 
                               3616                 :            114 :         appendStringInfoString(buf, "END");
                               3617                 :                :     }
                               3618                 :                :     else
                               3619                 :                :     {
 1915 tgl@sss.pgh.pa.us        3620                 :             27 :         Query      *query = castNode(Query, n);
                               3621                 :                : 
                               3622                 :                :         /* It seems advisable to get at least AccessShareLock on rels */
                               3623                 :             27 :         AcquireRewriteLocks(query, false, false);
 1652                          3624                 :             27 :         get_query_def(query, buf, list_make1(&dpns), NULL, false,
                               3625                 :                :                       0, WRAP_COLUMN_DEFAULT, 0);
                               3626                 :                :     }
 2061 peter@eisentraut.org     3627                 :            141 : }
                               3628                 :                : 
                               3629                 :                : Datum
                               3630                 :           1822 : pg_get_function_sqlbody(PG_FUNCTION_ARGS)
                               3631                 :                : {
                               3632                 :           1822 :     Oid         funcid = PG_GETARG_OID(0);
                               3633                 :                :     StringInfoData buf;
                               3634                 :                :     HeapTuple   proctup;
                               3635                 :                :     bool        isnull;
                               3636                 :                : 
                               3637                 :           1822 :     initStringInfo(&buf);
                               3638                 :                : 
                               3639                 :                :     /* Look up the function */
                               3640                 :           1822 :     proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
                               3641         [ -  + ]:           1822 :     if (!HeapTupleIsValid(proctup))
 2061 peter@eisentraut.org     3642                 :UBC           0 :         PG_RETURN_NULL();
                               3643                 :                : 
 1915 tgl@sss.pgh.pa.us        3644                 :CBC        1822 :     (void) SysCacheGetAttr(PROCOID, proctup, Anum_pg_proc_prosqlbody, &isnull);
 2061 peter@eisentraut.org     3645         [ +  + ]:           1822 :     if (isnull)
                               3646                 :                :     {
                               3647                 :           1772 :         ReleaseSysCache(proctup);
                               3648                 :           1772 :         PG_RETURN_NULL();
                               3649                 :                :     }
                               3650                 :                : 
                               3651                 :             50 :     print_function_sqlbody(&buf, proctup);
                               3652                 :                : 
                               3653                 :             50 :     ReleaseSysCache(proctup);
                               3654                 :                : 
 1544 drowley@postgresql.o     3655                 :             50 :     PG_RETURN_TEXT_P(cstring_to_text_with_len(buf.data, buf.len));
                               3656                 :                : }
                               3657                 :                : 
                               3658                 :                : 
                               3659                 :                : /*
                               3660                 :                :  * deparse_expression           - General utility for deparsing expressions
                               3661                 :                :  *
                               3662                 :                :  * calls deparse_expression_pretty with all prettyPrinting disabled
                               3663                 :                :  */
                               3664                 :                : char *
 8522 tgl@sss.pgh.pa.us        3665                 :          59755 : deparse_expression(Node *expr, List *dpcontext,
                               3666                 :                :                    bool forceprefix, bool showimplicit)
                               3667                 :                : {
 8517 bruce@momjian.us         3668                 :          59755 :     return deparse_expression_pretty(expr, dpcontext, forceprefix,
                               3669                 :                :                                      showimplicit, 0, 0);
                               3670                 :                : }
                               3671                 :                : 
                               3672                 :                : /* ----------
                               3673                 :                :  * deparse_expression_pretty    - General utility for deparsing expressions
                               3674                 :                :  *
                               3675                 :                :  * expr is the node tree to be deparsed.  It must be a transformed expression
                               3676                 :                :  * tree (ie, not the raw output of gram.y).
                               3677                 :                :  *
                               3678                 :                :  * dpcontext is a list of deparse_namespace nodes representing the context
                               3679                 :                :  * for interpreting Vars in the node tree.  It can be NIL if no Vars are
                               3680                 :                :  * expected.
                               3681                 :                :  *
                               3682                 :                :  * forceprefix is true to force all Vars to be prefixed with their table names.
                               3683                 :                :  *
                               3684                 :                :  * showimplicit is true to force all implicit casts to be shown explicitly.
                               3685                 :                :  *
                               3686                 :                :  * Tries to pretty up the output according to prettyFlags and startIndent.
                               3687                 :                :  *
                               3688                 :                :  * The result is a palloc'd string.
                               3689                 :                :  * ----------
                               3690                 :                :  */
                               3691                 :                : static char *
 8522 tgl@sss.pgh.pa.us        3692                 :          68315 : deparse_expression_pretty(Node *expr, List *dpcontext,
                               3693                 :                :                           bool forceprefix, bool showimplicit,
                               3694                 :                :                           int prettyFlags, int startIndent)
                               3695                 :                : {
                               3696                 :                :     StringInfoData buf;
                               3697                 :                :     deparse_context context;
                               3698                 :                : 
 9918                          3699                 :          68315 :     initStringInfo(&buf);
                               3700                 :          68315 :     context.buf = &buf;
 9418                          3701                 :          68315 :     context.namespaces = dpcontext;
  821                          3702                 :          68315 :     context.resultDesc = NULL;
                               3703                 :          68315 :     context.targetList = NIL;
 6544                          3704                 :          68315 :     context.windowClause = NIL;
 9418                          3705                 :          68315 :     context.varprefix = forceprefix;
 8522                          3706                 :          68315 :     context.prettyFlags = prettyFlags;
 5087                          3707                 :          68315 :     context.wrapColumn = WRAP_COLUMN_DEFAULT;
 8522                          3708                 :          68315 :     context.indentLevel = startIndent;
  821                          3709                 :          68315 :     context.colNamesVisible = true;
                               3710                 :          68315 :     context.inGroupBy = false;
                               3711                 :          68315 :     context.varInOrderBy = false;
 2544                          3712                 :          68315 :     context.appendparents = NULL;
                               3713                 :                : 
 8836                          3714                 :          68315 :     get_rule_expr(expr, &context, showimplicit);
                               3715                 :                : 
 9918                          3716                 :          68315 :     return buf.data;
                               3717                 :                : }
                               3718                 :                : 
                               3719                 :                : /* ----------
                               3720                 :                :  * deparse_context_for          - Build deparse context for a single relation
                               3721                 :                :  *
                               3722                 :                :  * Given the reference name (alias) and OID of a relation, build deparsing
                               3723                 :                :  * context for an expression referencing only that relation (as varno 1,
                               3724                 :                :  * varlevelsup 0).  This is sufficient for many uses of deparse_expression.
                               3725                 :                :  * ----------
                               3726                 :                :  */
                               3727                 :                : List *
 9017                          3728                 :          14834 : deparse_context_for(const char *aliasname, Oid relid)
                               3729                 :                : {
                               3730                 :                :     deparse_namespace *dpns;
                               3731                 :                :     RangeTblEntry *rte;
                               3732                 :                : 
  353 michael@paquier.xyz      3733                 :          14834 :     dpns = palloc0_object(deparse_namespace);
                               3734                 :                : 
                               3735                 :                :     /* Build a minimal RTE for the rel */
 9418 tgl@sss.pgh.pa.us        3736                 :          14834 :     rte = makeNode(RangeTblEntry);
 9027                          3737                 :          14834 :     rte->rtekind = RTE_RELATION;
 9418                          3738                 :          14834 :     rte->relid = relid;
 5758                          3739                 :          14834 :     rte->relkind = RELKIND_RELATION; /* no need for exactness here */
 2981                          3740                 :          14834 :     rte->rellockmode = AccessShareLock;
 5181                          3741                 :          14834 :     rte->alias = makeAlias(aliasname, NIL);
                               3742                 :          14834 :     rte->eref = rte->alias;
 5226                          3743                 :          14834 :     rte->lateral = false;
 9418                          3744                 :          14834 :     rte->inh = false;
                               3745                 :          14834 :     rte->inFromCl = true;
                               3746                 :                : 
                               3747                 :                :     /* Build one-element rtable */
 8217 neilc@samurai.com        3748                 :          14834 :     dpns->rtable = list_make1(rte);
 2544 tgl@sss.pgh.pa.us        3749                 :          14834 :     dpns->subplans = NIL;
 6627                          3750                 :          14834 :     dpns->ctes = NIL;
 2544                          3751                 :          14834 :     dpns->appendrels = NULL;
 5181                          3752                 :          14834 :     set_rtable_names(dpns, NIL, NULL);
 5080                          3753                 :          14834 :     set_simple_column_names(dpns);
                               3754                 :                : 
                               3755                 :                :     /* Return a one-deep namespace stack */
 8217 neilc@samurai.com        3756                 :          14834 :     return list_make1(dpns);
                               3757                 :                : }
                               3758                 :                : 
                               3759                 :                : /*
                               3760                 :                :  * deparse_context_for_plan_tree - Build deparse context for a Plan tree
                               3761                 :                :  *
                               3762                 :                :  * When deparsing an expression in a Plan tree, we use the plan's rangetable
                               3763                 :                :  * to resolve names of simple Vars.  The initialization of column names for
                               3764                 :                :  * this is rather expensive if the rangetable is large, and it'll be the same
                               3765                 :                :  * for every expression in the Plan tree; so we do it just once and re-use
                               3766                 :                :  * the result of this function for each expression.  (Note that the result
                               3767                 :                :  * is not usable until set_deparse_context_plan() is applied to it.)
                               3768                 :                :  *
                               3769                 :                :  * In addition to the PlannedStmt, pass the per-RTE alias names
                               3770                 :                :  * assigned by a previous call to select_rtable_names_for_explain.
                               3771                 :                :  */
                               3772                 :                : List *
 2544 tgl@sss.pgh.pa.us        3773                 :          17428 : deparse_context_for_plan_tree(PlannedStmt *pstmt, List *rtable_names)
                               3774                 :                : {
                               3775                 :                :     deparse_namespace *dpns;
                               3776                 :                : 
  353 michael@paquier.xyz      3777                 :          17428 :     dpns = palloc0_object(deparse_namespace);
                               3778                 :                : 
                               3779                 :                :     /* Initialize fields that stay the same across the whole plan tree */
 2544 tgl@sss.pgh.pa.us        3780                 :          17428 :     dpns->rtable = pstmt->rtable;
 4335                          3781                 :          17428 :     dpns->rtable_names = rtable_names;
 2544                          3782                 :          17428 :     dpns->subplans = pstmt->subplans;
 4335                          3783                 :          17428 :     dpns->ctes = NIL;
 2544                          3784         [ +  + ]:          17428 :     if (pstmt->appendRelations)
                               3785                 :                :     {
                               3786                 :                :         /* Set up the array, indexed by child relid */
                               3787                 :           2831 :         int         ntables = list_length(dpns->rtable);
                               3788                 :                :         ListCell   *lc;
                               3789                 :                : 
  103 michael@paquier.xyz      3790                 :GNC        2831 :         dpns->appendrels = palloc0_array(AppendRelInfo *, ntables + 1);
 2544 tgl@sss.pgh.pa.us        3791   [ +  -  +  +  :CBC       15297 :         foreach(lc, pstmt->appendRelations)
                                              +  + ]
                               3792                 :                :         {
                               3793                 :          12466 :             AppendRelInfo *appinfo = lfirst_node(AppendRelInfo, lc);
                               3794                 :          12466 :             Index       crelid = appinfo->child_relid;
                               3795                 :                : 
                               3796   [ +  -  -  + ]:          12466 :             Assert(crelid > 0 && crelid <= ntables);
                               3797         [ -  + ]:          12466 :             Assert(dpns->appendrels[crelid] == NULL);
                               3798                 :          12466 :             dpns->appendrels[crelid] = appinfo;
                               3799                 :                :         }
                               3800                 :                :     }
                               3801                 :                :     else
                               3802                 :          14597 :         dpns->appendrels = NULL; /* don't need it */
                               3803                 :                : 
                               3804                 :                :     /*
                               3805                 :                :      * Set up column name aliases, ignoring any join RTEs; they don't matter
                               3806                 :                :      * because plan trees don't contain any join alias Vars.
                               3807                 :                :      */
 4335                          3808                 :          17428 :     set_simple_column_names(dpns);
                               3809                 :                : 
                               3810                 :                :     /* Return a one-deep namespace stack */
                               3811                 :          17428 :     return list_make1(dpns);
                               3812                 :                : }
                               3813                 :                : 
                               3814                 :                : /*
                               3815                 :                :  * set_deparse_context_plan - Specify Plan node containing expression
                               3816                 :                :  *
                               3817                 :                :  * When deparsing an expression in a Plan tree, we might have to resolve
                               3818                 :                :  * OUTER_VAR, INNER_VAR, or INDEX_VAR references.  To do this, the caller must
                               3819                 :                :  * provide the parent Plan node.  Then OUTER_VAR and INNER_VAR references
                               3820                 :                :  * can be resolved by drilling down into the left and right child plans.
                               3821                 :                :  * Similarly, INDEX_VAR references can be resolved by reference to the
                               3822                 :                :  * indextlist given in a parent IndexOnlyScan node, or to the scan tlist in
                               3823                 :                :  * ForeignScan and CustomScan nodes.  (Note that we don't currently support
                               3824                 :                :  * deparsing of indexquals in regular IndexScan or BitmapIndexScan nodes;
                               3825                 :                :  * for those, we can only deparse the indexqualorig fields, which won't
                               3826                 :                :  * contain INDEX_VAR Vars.)
                               3827                 :                :  *
                               3828                 :                :  * The ancestors list is a list of the Plan's parent Plan and SubPlan nodes,
                               3829                 :                :  * the most-closely-nested first.  This is needed to resolve PARAM_EXEC
                               3830                 :                :  * Params.  Note we assume that all the Plan nodes share the same rtable.
                               3831                 :                :  *
                               3832                 :                :  * For a ModifyTable plan, we might also need to resolve references to OLD/NEW
                               3833                 :                :  * variables in the RETURNING list, so we copy the alias names of the OLD and
                               3834                 :                :  * NEW rows from the ModifyTable plan node.
                               3835                 :                :  *
                               3836                 :                :  * Once this function has been called, deparse_expression() can be called on
                               3837                 :                :  * subsidiary expression(s) of the specified Plan node.  To deparse
                               3838                 :                :  * expressions of a different Plan node in the same Plan tree, re-call this
                               3839                 :                :  * function to identify the new parent Plan node.
                               3840                 :                :  *
                               3841                 :                :  * The result is the same List passed in; this is a notational convenience.
                               3842                 :                :  */
                               3843                 :                : List *
 2544                          3844                 :          43560 : set_deparse_context_plan(List *dpcontext, Plan *plan, List *ancestors)
                               3845                 :                : {
                               3846                 :                :     deparse_namespace *dpns;
                               3847                 :                : 
                               3848                 :                :     /* Should always have one-entry namespace list for Plan deparsing */
 4335                          3849         [ -  + ]:          43560 :     Assert(list_length(dpcontext) == 1);
                               3850                 :          43560 :     dpns = (deparse_namespace *) linitial(dpcontext);
                               3851                 :                : 
                               3852                 :                :     /* Set our attention on the specific plan node passed in */
 5982                          3853                 :          43560 :     dpns->ancestors = ancestors;
 1874                          3854                 :          43560 :     set_deparse_plan(dpns, plan);
                               3855                 :                : 
 4335                          3856                 :          43560 :     return dpcontext;
                               3857                 :                : }
                               3858                 :                : 
                               3859                 :                : /*
                               3860                 :                :  * select_rtable_names_for_explain  - Select RTE aliases for EXPLAIN
                               3861                 :                :  *
                               3862                 :                :  * Determine the relation aliases we'll use during an EXPLAIN operation.
                               3863                 :                :  * This is just a frontend to set_rtable_names.  We have to expose the aliases
                               3864                 :                :  * to EXPLAIN because EXPLAIN needs to know the right alias names to print.
                               3865                 :                :  */
                               3866                 :                : List *
 5181                          3867                 :          17428 : select_rtable_names_for_explain(List *rtable, Bitmapset *rels_used)
                               3868                 :                : {
                               3869                 :                :     deparse_namespace dpns;
                               3870                 :                : 
                               3871                 :          17428 :     memset(&dpns, 0, sizeof(dpns));
                               3872                 :          17428 :     dpns.rtable = rtable;
 2544                          3873                 :          17428 :     dpns.subplans = NIL;
 5181                          3874                 :          17428 :     dpns.ctes = NIL;
 2544                          3875                 :          17428 :     dpns.appendrels = NULL;
 5181                          3876                 :          17428 :     set_rtable_names(&dpns, NIL, rels_used);
                               3877                 :                :     /* We needn't bother computing column aliases yet */
                               3878                 :                : 
                               3879                 :          17428 :     return dpns.rtable_names;
                               3880                 :                : }
                               3881                 :                : 
                               3882                 :                : /*
                               3883                 :                :  * set_rtable_names: select RTE aliases to be used in printing a query
                               3884                 :                :  *
                               3885                 :                :  * We fill in dpns->rtable_names with a list of names that is one-for-one with
                               3886                 :                :  * the already-filled dpns->rtable list.  Each RTE name is unique among those
                               3887                 :                :  * in the new namespace plus any ancestor namespaces listed in
                               3888                 :                :  * parent_namespaces.
                               3889                 :                :  *
                               3890                 :                :  * If rels_used isn't NULL, only RTE indexes listed in it are given aliases.
                               3891                 :                :  *
                               3892                 :                :  * Note that this function is only concerned with relation names, not column
                               3893                 :                :  * names.
                               3894                 :                :  */
                               3895                 :                : static void
                               3896                 :          36008 : set_rtable_names(deparse_namespace *dpns, List *parent_namespaces,
                               3897                 :                :                  Bitmapset *rels_used)
                               3898                 :                : {
                               3899                 :                :     HASHCTL     hash_ctl;
                               3900                 :                :     HTAB       *names_hash;
                               3901                 :                :     NameHashEntry *hentry;
                               3902                 :                :     bool        found;
                               3903                 :                :     int         rtindex;
                               3904                 :                :     ListCell   *lc;
                               3905                 :                : 
                               3906                 :          36008 :     dpns->rtable_names = NIL;
                               3907                 :                :     /* nothing more to do if empty rtable */
 4030                          3908         [ +  + ]:          36008 :     if (dpns->rtable == NIL)
                               3909                 :            387 :         return;
                               3910                 :                : 
                               3911                 :                :     /*
                               3912                 :                :      * We use a hash table to hold known names, so that this process is O(N)
                               3913                 :                :      * not O(N^2) for N names.
                               3914                 :                :      */
                               3915                 :          35621 :     hash_ctl.keysize = NAMEDATALEN;
                               3916                 :          35621 :     hash_ctl.entrysize = sizeof(NameHashEntry);
                               3917                 :          35621 :     hash_ctl.hcxt = CurrentMemoryContext;
                               3918                 :          35621 :     names_hash = hash_create("set_rtable_names names",
                               3919                 :          35621 :                              list_length(dpns->rtable),
                               3920                 :                :                              &hash_ctl,
                               3921                 :                :                              HASH_ELEM | HASH_STRINGS | HASH_CONTEXT);
                               3922                 :                : 
                               3923                 :                :     /* Preload the hash table with names appearing in parent_namespaces */
                               3924   [ +  +  +  +  :          36752 :     foreach(lc, parent_namespaces)
                                              +  + ]
                               3925                 :                :     {
                               3926                 :           1131 :         deparse_namespace *olddpns = (deparse_namespace *) lfirst(lc);
                               3927                 :                :         ListCell   *lc2;
                               3928                 :                : 
                               3929   [ +  +  +  +  :           3919 :         foreach(lc2, olddpns->rtable_names)
                                              +  + ]
                               3930                 :                :         {
                               3931                 :           2788 :             char       *oldname = (char *) lfirst(lc2);
                               3932                 :                : 
                               3933         [ +  + ]:           2788 :             if (oldname == NULL)
                               3934                 :            201 :                 continue;
                               3935                 :           2587 :             hentry = (NameHashEntry *) hash_search(names_hash,
                               3936                 :                :                                                    oldname,
                               3937                 :                :                                                    HASH_ENTER,
                               3938                 :                :                                                    &found);
                               3939                 :                :             /* we do not complain about duplicate names in parent namespaces */
                               3940                 :           2587 :             hentry->counter = 0;
                               3941                 :                :         }
                               3942                 :                :     }
                               3943                 :                : 
                               3944                 :                :     /* Now we can scan the rtable */
                               3945                 :          35621 :     rtindex = 1;
 5181                          3946   [ +  -  +  +  :         107923 :     foreach(lc, dpns->rtable)
                                              +  + ]
                               3947                 :                :     {
                               3948                 :          72302 :         RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
                               3949                 :                :         char       *refname;
                               3950                 :                : 
                               3951                 :                :         /* Just in case this takes an unreasonable amount of time ... */
 4030                          3952         [ +  + ]:          72302 :         CHECK_FOR_INTERRUPTS();
                               3953                 :                : 
 5181                          3954   [ +  +  +  + ]:          72302 :         if (rels_used && !bms_is_member(rtindex, rels_used))
                               3955                 :                :         {
                               3956                 :                :             /* Ignore unreferenced RTE */
                               3957                 :          14438 :             refname = NULL;
                               3958                 :                :         }
                               3959         [ +  + ]:          57864 :         else if (rte->alias)
                               3960                 :                :         {
                               3961                 :                :             /* If RTE has a user-defined alias, prefer that */
                               3962                 :          37365 :             refname = rte->alias->aliasname;
                               3963                 :                :         }
                               3964         [ +  + ]:          20499 :         else if (rte->rtekind == RTE_RELATION)
                               3965                 :                :         {
                               3966                 :                :             /* Use the current actual name of the relation */
                               3967                 :          15416 :             refname = get_rel_name(rte->relid);
                               3968                 :                :         }
                               3969         [ +  + ]:           5083 :         else if (rte->rtekind == RTE_JOIN)
                               3970                 :                :         {
                               3971                 :                :             /* Unnamed join has no refname */
                               3972                 :           1182 :             refname = NULL;
                               3973                 :                :         }
                               3974                 :                :         else
                               3975                 :                :         {
                               3976                 :                :             /* Otherwise use whatever the parser assigned */
                               3977                 :           3901 :             refname = rte->eref->aliasname;
                               3978                 :                :         }
                               3979                 :                : 
                               3980                 :                :         /*
                               3981                 :                :          * If the selected name isn't unique, append digits to make it so, and
                               3982                 :                :          * make a new hash entry for it once we've got a unique name.  For a
                               3983                 :                :          * very long input name, we might have to truncate to stay within
                               3984                 :                :          * NAMEDATALEN.
                               3985                 :                :          */
 4030                          3986         [ +  + ]:          72302 :         if (refname)
                               3987                 :                :         {
                               3988                 :          56682 :             hentry = (NameHashEntry *) hash_search(names_hash,
                               3989                 :                :                                                    refname,
                               3990                 :                :                                                    HASH_ENTER,
                               3991                 :                :                                                    &found);
                               3992         [ +  + ]:          56682 :             if (found)
                               3993                 :                :             {
                               3994                 :                :                 /* Name already in use, must choose a new one */
                               3995                 :          10738 :                 int         refnamelen = strlen(refname);
                               3996                 :          10738 :                 char       *modname = (char *) palloc(refnamelen + 16);
                               3997                 :                :                 NameHashEntry *hentry2;
                               3998                 :                : 
                               3999                 :                :                 do
                               4000                 :                :                 {
                               4001                 :          10742 :                     hentry->counter++;
                               4002                 :                :                     for (;;)
                               4003                 :                :                     {
                               4004                 :          10750 :                         memcpy(modname, refname, refnamelen);
                               4005                 :          10750 :                         sprintf(modname + refnamelen, "_%d", hentry->counter);
                               4006         [ +  + ]:          10750 :                         if (strlen(modname) < NAMEDATALEN)
                               4007                 :          10742 :                             break;
                               4008                 :                :                         /* drop chars from refname to keep all the digits */
                               4009                 :              8 :                         refnamelen = pg_mbcliplen(refname, refnamelen,
                               4010                 :                :                                                   refnamelen - 1);
                               4011                 :                :                     }
                               4012                 :          10742 :                     hentry2 = (NameHashEntry *) hash_search(names_hash,
                               4013                 :                :                                                             modname,
                               4014                 :                :                                                             HASH_ENTER,
                               4015                 :                :                                                             &found);
                               4016         [ +  + ]:          10742 :                 } while (found);
                               4017                 :          10738 :                 hentry2->counter = 0;    /* init new hash entry */
                               4018                 :          10738 :                 refname = modname;
                               4019                 :                :             }
                               4020                 :                :             else
                               4021                 :                :             {
                               4022                 :                :                 /* Name not previously used, need only initialize hentry */
                               4023                 :          45944 :                 hentry->counter = 0;
                               4024                 :                :             }
                               4025                 :                :         }
                               4026                 :                : 
 5181                          4027                 :          72302 :         dpns->rtable_names = lappend(dpns->rtable_names, refname);
                               4028                 :          72302 :         rtindex++;
                               4029                 :                :     }
                               4030                 :                : 
 4030                          4031                 :          35621 :     hash_destroy(names_hash);
                               4032                 :                : }
                               4033                 :                : 
                               4034                 :                : /*
                               4035                 :                :  * set_deparse_for_query: set up deparse_namespace for deparsing a Query tree
                               4036                 :                :  *
                               4037                 :                :  * For convenience, this is defined to initialize the deparse_namespace struct
                               4038                 :                :  * from scratch.
                               4039                 :                :  */
                               4040                 :                : static void
 5080                          4041                 :           3658 : set_deparse_for_query(deparse_namespace *dpns, Query *query,
                               4042                 :                :                       List *parent_namespaces)
                               4043                 :                : {
                               4044                 :                :     ListCell   *lc;
                               4045                 :                :     ListCell   *lc2;
                               4046                 :                : 
                               4047                 :                :     /* Initialize *dpns and fill rtable/ctes links */
                               4048                 :           3658 :     memset(dpns, 0, sizeof(deparse_namespace));
                               4049                 :           3658 :     dpns->rtable = query->rtable;
 2544                          4050                 :           3658 :     dpns->subplans = NIL;
 5080                          4051                 :           3658 :     dpns->ctes = query->cteList;
 2544                          4052                 :           3658 :     dpns->appendrels = NULL;
  681 dean.a.rasheed@gmail     4053                 :           3658 :     dpns->ret_old_alias = query->returningOldAlias;
                               4054                 :           3658 :     dpns->ret_new_alias = query->returningNewAlias;
                               4055                 :                : 
                               4056                 :                :     /* Assign a unique relation alias to each RTE */
 5080 tgl@sss.pgh.pa.us        4057                 :           3658 :     set_rtable_names(dpns, parent_namespaces, NULL);
                               4058                 :                : 
                               4059                 :                :     /* Initialize dpns->rtable_columns to contain zeroed structs */
                               4060                 :           3658 :     dpns->rtable_columns = NIL;
                               4061         [ +  + ]:          10114 :     while (list_length(dpns->rtable_columns) < list_length(dpns->rtable))
                               4062                 :           6456 :         dpns->rtable_columns = lappend(dpns->rtable_columns,
                               4063                 :                :                                        palloc0_object(deparse_columns));
                               4064                 :                : 
                               4065                 :                :     /* If it's a utility query, it won't have a jointree */
 4944                          4066         [ +  + ]:           3658 :     if (query->jointree)
                               4067                 :                :     {
                               4068                 :                :         /* Detect whether global uniqueness of USING names is needed */
                               4069                 :           3649 :         dpns->unique_using =
 4876                          4070                 :           3649 :             has_dangerous_join_using(dpns, (Node *) query->jointree);
                               4071                 :                : 
                               4072                 :                :         /*
                               4073                 :                :          * Select names for columns merged by USING, via a recursive pass over
                               4074                 :                :          * the query jointree.
                               4075                 :                :          */
 4594                          4076                 :           3649 :         set_using_names(dpns, (Node *) query->jointree, NIL);
                               4077                 :                :     }
                               4078                 :                : 
                               4079                 :                :     /*
                               4080                 :                :      * Now assign remaining column aliases for each RTE.  We do this in a
                               4081                 :                :      * linear scan of the rtable, so as to process RTEs whether or not they
                               4082                 :                :      * are in the jointree (we mustn't miss NEW.*, INSERT target relations,
                               4083                 :                :      * etc).  JOIN RTEs must be processed after their children, but this is
                               4084                 :                :      * okay because they appear later in the rtable list than their children
                               4085                 :                :      * (cf Asserts in identify_join_columns()).
                               4086                 :                :      */
 5080                          4087   [ +  +  +  +  :          10114 :     forboth(lc, dpns->rtable, lc2, dpns->rtable_columns)
                                     +  +  +  +  +  
                                        +  +  -  +  
                                                 + ]
                               4088                 :                :     {
                               4089                 :           6456 :         RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
                               4090                 :           6456 :         deparse_columns *colinfo = (deparse_columns *) lfirst(lc2);
                               4091                 :                : 
                               4092         [ +  + ]:           6456 :         if (rte->rtekind == RTE_JOIN)
                               4093                 :            940 :             set_join_column_names(dpns, rte, colinfo);
                               4094                 :                :         else
                               4095                 :           5516 :             set_relation_column_names(dpns, rte, colinfo);
                               4096                 :                :     }
                               4097                 :           3658 : }
                               4098                 :                : 
                               4099                 :                : /*
                               4100                 :                :  * set_simple_column_names: fill in column aliases for non-query situations
                               4101                 :                :  *
                               4102                 :                :  * This handles EXPLAIN and cases where we only have relation RTEs.  Without
                               4103                 :                :  * a join tree, we can't do anything smart about join RTEs, but we don't
                               4104                 :                :  * need to, because EXPLAIN should never see join alias Vars anyway.
                               4105                 :                :  * If we find a join RTE we'll just skip it, leaving its deparse_columns
                               4106                 :                :  * struct all-zero.  If somehow we try to deparse a join alias Var, we'll
                               4107                 :                :  * error out cleanly because the struct's num_cols will be zero.
                               4108                 :                :  */
                               4109                 :                : static void
                               4110                 :          32350 : set_simple_column_names(deparse_namespace *dpns)
                               4111                 :                : {
                               4112                 :                :     ListCell   *lc;
                               4113                 :                :     ListCell   *lc2;
                               4114                 :                : 
                               4115                 :                :     /* Initialize dpns->rtable_columns to contain zeroed structs */
                               4116                 :          32350 :     dpns->rtable_columns = NIL;
                               4117         [ +  + ]:          98196 :     while (list_length(dpns->rtable_columns) < list_length(dpns->rtable))
                               4118                 :          65846 :         dpns->rtable_columns = lappend(dpns->rtable_columns,
                               4119                 :                :                                        palloc0_object(deparse_columns));
                               4120                 :                : 
                               4121                 :                :     /* Assign unique column aliases within each non-join RTE */
                               4122   [ +  -  +  +  :          98196 :     forboth(lc, dpns->rtable, lc2, dpns->rtable_columns)
                                     +  -  +  +  +  
                                        +  +  -  +  
                                                 + ]
                               4123                 :                :     {
                               4124                 :          65846 :         RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
                               4125                 :          65846 :         deparse_columns *colinfo = (deparse_columns *) lfirst(lc2);
                               4126                 :                : 
  711                          4127         [ +  + ]:          65846 :         if (rte->rtekind != RTE_JOIN)
                               4128                 :          60726 :             set_relation_column_names(dpns, rte, colinfo);
                               4129                 :                :     }
 5080                          4130                 :          32350 : }
                               4131                 :                : 
                               4132                 :                : /*
                               4133                 :                :  * has_dangerous_join_using: search jointree for unnamed JOIN USING
                               4134                 :                :  *
                               4135                 :                :  * Merged columns of a JOIN USING may act differently from either of the input
                               4136                 :                :  * columns, either because they are merged with COALESCE (in a FULL JOIN) or
                               4137                 :                :  * because an implicit coercion of the underlying input column is required.
                               4138                 :                :  * In such a case the column must be referenced as a column of the JOIN not as
                               4139                 :                :  * a column of either input.  And this is problematic if the join is unnamed
                               4140                 :                :  * (alias-less): we cannot qualify the column's name with an RTE name, since
                               4141                 :                :  * there is none.  (Forcibly assigning an alias to the join is not a solution,
                               4142                 :                :  * since that will prevent legal references to tables below the join.)
                               4143                 :                :  * To ensure that every column in the query is unambiguously referenceable,
                               4144                 :                :  * we must assign such merged columns names that are globally unique across
                               4145                 :                :  * the whole query, aliasing other columns out of the way as necessary.
                               4146                 :                :  *
                               4147                 :                :  * Because the ensuing re-aliasing is fairly damaging to the readability of
                               4148                 :                :  * the query, we don't do this unless we have to.  So, we must pre-scan
                               4149                 :                :  * the join tree to see if we have to, before starting set_using_names().
                               4150                 :                :  */
                               4151                 :                : static bool
 4876                          4152                 :           8607 : has_dangerous_join_using(deparse_namespace *dpns, Node *jtnode)
                               4153                 :                : {
 5080                          4154         [ +  + ]:           8607 :     if (IsA(jtnode, RangeTblRef))
                               4155                 :                :     {
                               4156                 :                :         /* nothing to do here */
                               4157                 :                :     }
                               4158         [ +  + ]:           4545 :     else if (IsA(jtnode, FromExpr))
                               4159                 :                :     {
                               4160                 :           3649 :         FromExpr   *f = (FromExpr *) jtnode;
                               4161                 :                :         ListCell   *lc;
                               4162                 :                : 
                               4163   [ +  +  +  +  :           6867 :         foreach(lc, f->fromlist)
                                              +  + ]
                               4164                 :                :         {
 4876                          4165         [ +  + ]:           3270 :             if (has_dangerous_join_using(dpns, (Node *) lfirst(lc)))
 5080                          4166                 :             52 :                 return true;
                               4167                 :                :         }
                               4168                 :                :     }
                               4169         [ +  - ]:            896 :     else if (IsA(jtnode, JoinExpr))
                               4170                 :                :     {
                               4171                 :            896 :         JoinExpr   *j = (JoinExpr *) jtnode;
                               4172                 :                : 
                               4173                 :                :         /* Is it an unnamed JOIN with USING? */
 4876                          4174   [ +  +  +  + ]:            896 :         if (j->alias == NULL && j->usingClause)
                               4175                 :                :         {
                               4176                 :                :             /*
                               4177                 :                :              * Yes, so check each join alias var to see if any of them are not
                               4178                 :                :              * simple references to underlying columns.  If so, we have a
                               4179                 :                :              * dangerous situation and must pick unique aliases.
                               4180                 :                :              */
                               4181                 :            188 :             RangeTblEntry *jrte = rt_fetch(j->rtindex, dpns->rtable);
                               4182                 :                : 
                               4183                 :                :             /* We need only examine the merged columns */
 2515                          4184         [ +  + ]:            388 :             for (int i = 0; i < jrte->joinmergedcols; i++)
                               4185                 :                :             {
                               4186                 :            252 :                 Node       *aliasvar = list_nth(jrte->joinaliasvars, i);
                               4187                 :                : 
                               4188         [ +  + ]:            252 :                 if (!IsA(aliasvar, Var))
 4876                          4189                 :             52 :                     return true;
                               4190                 :                :             }
                               4191                 :                :         }
                               4192                 :                : 
                               4193                 :                :         /* Nope, but inspect children */
                               4194         [ -  + ]:            844 :         if (has_dangerous_join_using(dpns, j->larg))
 5080 tgl@sss.pgh.pa.us        4195                 :UBC           0 :             return true;
 4876 tgl@sss.pgh.pa.us        4196         [ -  + ]:CBC         844 :         if (has_dangerous_join_using(dpns, j->rarg))
 5080 tgl@sss.pgh.pa.us        4197                 :UBC           0 :             return true;
                               4198                 :                :     }
                               4199                 :                :     else
                               4200         [ #  # ]:              0 :         elog(ERROR, "unrecognized node type: %d",
                               4201                 :                :              (int) nodeTag(jtnode));
 5080 tgl@sss.pgh.pa.us        4202                 :CBC        8503 :     return false;
                               4203                 :                : }
                               4204                 :                : 
                               4205                 :                : /*
                               4206                 :                :  * set_using_names: select column aliases to be used for merged USING columns
                               4207                 :                :  *
                               4208                 :                :  * We do this during a recursive descent of the query jointree.
                               4209                 :                :  * dpns->unique_using must already be set to determine the global strategy.
                               4210                 :                :  *
                               4211                 :                :  * Column alias info is saved in the dpns->rtable_columns list, which is
                               4212                 :                :  * assumed to be filled with pre-zeroed deparse_columns structs.
                               4213                 :                :  *
                               4214                 :                :  * parentUsing is a list of all USING aliases assigned in parent joins of
                               4215                 :                :  * the current jointree node.  (The passed-in list must not be modified.)
                               4216                 :                :  *
                               4217                 :                :  * Note that we do not use per-deparse_columns hash tables in this function.
                               4218                 :                :  * The number of names that need to be assigned should be small enough that
                               4219                 :                :  * we don't need to trouble with that.
                               4220                 :                :  */
                               4221                 :                : static void
 4594                          4222                 :           8827 : set_using_names(deparse_namespace *dpns, Node *jtnode, List *parentUsing)
                               4223                 :                : {
 5080                          4224         [ +  + ]:           8827 :     if (IsA(jtnode, RangeTblRef))
                               4225                 :                :     {
                               4226                 :                :         /* nothing to do now */
                               4227                 :                :     }
                               4228         [ +  + ]:           4589 :     else if (IsA(jtnode, FromExpr))
                               4229                 :                :     {
                               4230                 :           3649 :         FromExpr   *f = (FromExpr *) jtnode;
                               4231                 :                :         ListCell   *lc;
                               4232                 :                : 
                               4233   [ +  +  +  +  :           6947 :         foreach(lc, f->fromlist)
                                              +  + ]
 4594                          4234                 :           3298 :             set_using_names(dpns, (Node *) lfirst(lc), parentUsing);
                               4235                 :                :     }
 5080                          4236         [ +  - ]:            940 :     else if (IsA(jtnode, JoinExpr))
                               4237                 :                :     {
                               4238                 :            940 :         JoinExpr   *j = (JoinExpr *) jtnode;
                               4239                 :            940 :         RangeTblEntry *rte = rt_fetch(j->rtindex, dpns->rtable);
                               4240                 :            940 :         deparse_columns *colinfo = deparse_columns_fetch(j->rtindex, dpns);
                               4241                 :                :         int        *leftattnos;
                               4242                 :                :         int        *rightattnos;
                               4243                 :                :         deparse_columns *leftcolinfo;
                               4244                 :                :         deparse_columns *rightcolinfo;
                               4245                 :                :         int         i;
                               4246                 :                :         ListCell   *lc;
                               4247                 :                : 
                               4248                 :                :         /* Get info about the shape of the join */
                               4249                 :            940 :         identify_join_columns(j, rte, colinfo);
                               4250                 :            940 :         leftattnos = colinfo->leftattnos;
                               4251                 :            940 :         rightattnos = colinfo->rightattnos;
                               4252                 :                : 
                               4253                 :                :         /* Look up the not-yet-filled-in child deparse_columns structs */
                               4254                 :            940 :         leftcolinfo = deparse_columns_fetch(colinfo->leftrti, dpns);
                               4255                 :            940 :         rightcolinfo = deparse_columns_fetch(colinfo->rightrti, dpns);
                               4256                 :                : 
                               4257                 :                :         /*
                               4258                 :                :          * If this join is unnamed, then we cannot substitute new aliases at
                               4259                 :                :          * this level, so any name requirements pushed down to here must be
                               4260                 :                :          * pushed down again to the children.
                               4261                 :                :          */
                               4262         [ +  + ]:            940 :         if (rte->alias == NULL)
                               4263                 :                :         {
                               4264         [ +  + ]:            960 :             for (i = 0; i < colinfo->num_cols; i++)
                               4265                 :                :             {
                               4266                 :             92 :                 char       *colname = colinfo->colnames[i];
                               4267                 :                : 
                               4268         [ +  + ]:             92 :                 if (colname == NULL)
                               4269                 :             16 :                     continue;
                               4270                 :                : 
                               4271                 :                :                 /* Push down to left column, unless it's a system column */
                               4272         [ +  + ]:             76 :                 if (leftattnos[i] > 0)
                               4273                 :                :                 {
                               4274                 :             68 :                     expand_colnames_array_to(leftcolinfo, leftattnos[i]);
                               4275                 :             68 :                     leftcolinfo->colnames[leftattnos[i] - 1] = colname;
                               4276                 :                :                 }
                               4277                 :                : 
                               4278                 :                :                 /* Same on the righthand side */
                               4279         [ +  - ]:             76 :                 if (rightattnos[i] > 0)
                               4280                 :                :                 {
                               4281                 :             76 :                     expand_colnames_array_to(rightcolinfo, rightattnos[i]);
                               4282                 :             76 :                     rightcolinfo->colnames[rightattnos[i] - 1] = colname;
                               4283                 :                :                 }
                               4284                 :                :             }
                               4285                 :                :         }
                               4286                 :                : 
                               4287                 :                :         /*
                               4288                 :                :          * If there's a USING clause, select the USING column names and push
                               4289                 :                :          * those names down to the children.  We have two strategies:
                               4290                 :                :          *
                               4291                 :                :          * If dpns->unique_using is true, we force all USING names to be
                               4292                 :                :          * unique across the whole query level.  In principle we'd only need
                               4293                 :                :          * the names of dangerous USING columns to be globally unique, but to
                               4294                 :                :          * safely assign all USING names in a single pass, we have to enforce
                               4295                 :                :          * the same uniqueness rule for all of them.  However, if a USING
                               4296                 :                :          * column's name has been pushed down from the parent, we should use
                               4297                 :                :          * it as-is rather than making a uniqueness adjustment.  This is
                               4298                 :                :          * necessary when we're at an unnamed join, and it creates no risk of
                               4299                 :                :          * ambiguity.  Also, if there's a user-written output alias for a
                               4300                 :                :          * merged column, we prefer to use that rather than the input name;
                               4301                 :                :          * this simplifies the logic and seems likely to lead to less aliasing
                               4302                 :                :          * overall.
                               4303                 :                :          *
                               4304                 :                :          * If dpns->unique_using is false, we only need USING names to be
                               4305                 :                :          * unique within their own join RTE.  We still need to honor
                               4306                 :                :          * pushed-down names, though.
                               4307                 :                :          *
                               4308                 :                :          * Though significantly different in results, these two strategies are
                               4309                 :                :          * implemented by the same code, with only the difference of whether
                               4310                 :                :          * to put assigned names into dpns->using_names.
                               4311                 :                :          */
                               4312         [ +  + ]:            940 :         if (j->usingClause)
                               4313                 :                :         {
                               4314                 :                :             /* Copy the input parentUsing list so we don't modify it */
 4594                          4315                 :            280 :             parentUsing = list_copy(parentUsing);
                               4316                 :                : 
                               4317                 :                :             /* USING names must correspond to the first join output columns */
 5080                          4318                 :            280 :             expand_colnames_array_to(colinfo, list_length(j->usingClause));
                               4319                 :            280 :             i = 0;
                               4320   [ +  -  +  +  :            664 :             foreach(lc, j->usingClause)
                                              +  + ]
                               4321                 :                :             {
                               4322                 :            384 :                 char       *colname = strVal(lfirst(lc));
                               4323                 :                : 
                               4324                 :                :                 /* Assert it's a merged column */
                               4325   [ +  -  -  + ]:            384 :                 Assert(leftattnos[i] != 0 && rightattnos[i] != 0);
                               4326                 :                : 
                               4327                 :                :                 /* Adopt passed-down name if any, else select unique name */
                               4328         [ +  + ]:            384 :                 if (colinfo->colnames[i] != NULL)
                               4329                 :             68 :                     colname = colinfo->colnames[i];
                               4330                 :                :                 else
                               4331                 :                :                 {
                               4332                 :                :                     /* Prefer user-written output alias if any */
                               4333   [ +  +  -  + ]:            316 :                     if (rte->alias && i < list_length(rte->alias->colnames))
 5080 tgl@sss.pgh.pa.us        4334                 :UBC           0 :                         colname = strVal(list_nth(rte->alias->colnames, i));
                               4335                 :                :                     /* Make it appropriately unique */
 5080 tgl@sss.pgh.pa.us        4336                 :CBC         316 :                     colname = make_colname_unique(colname, dpns, colinfo);
                               4337         [ +  + ]:            316 :                     if (dpns->unique_using)
                               4338                 :             88 :                         dpns->using_names = lappend(dpns->using_names,
                               4339                 :                :                                                     colname);
                               4340                 :                :                     /* Save it as output column name, too */
                               4341                 :            316 :                     colinfo->colnames[i] = colname;
                               4342                 :                :                 }
                               4343                 :                : 
                               4344                 :                :                 /* Remember selected names for use later */
                               4345                 :            384 :                 colinfo->usingNames = lappend(colinfo->usingNames, colname);
 4594                          4346                 :            384 :                 parentUsing = lappend(parentUsing, colname);
                               4347                 :                : 
                               4348                 :                :                 /* Push down to left column, unless it's a system column */
 5080                          4349         [ +  - ]:            384 :                 if (leftattnos[i] > 0)
                               4350                 :                :                 {
                               4351                 :            384 :                     expand_colnames_array_to(leftcolinfo, leftattnos[i]);
                               4352                 :            384 :                     leftcolinfo->colnames[leftattnos[i] - 1] = colname;
                               4353                 :                :                 }
                               4354                 :                : 
                               4355                 :                :                 /* Same on the righthand side */
                               4356         [ +  - ]:            384 :                 if (rightattnos[i] > 0)
                               4357                 :                :                 {
                               4358                 :            384 :                     expand_colnames_array_to(rightcolinfo, rightattnos[i]);
                               4359                 :            384 :                     rightcolinfo->colnames[rightattnos[i] - 1] = colname;
                               4360                 :                :                 }
                               4361                 :                : 
                               4362                 :            384 :                 i++;
                               4363                 :                :             }
                               4364                 :                :         }
                               4365                 :                : 
                               4366                 :                :         /* Mark child deparse_columns structs with correct parentUsing info */
 4594                          4367                 :            940 :         leftcolinfo->parentUsing = parentUsing;
                               4368                 :            940 :         rightcolinfo->parentUsing = parentUsing;
                               4369                 :                : 
                               4370                 :                :         /* Now recursively assign USING column names in children */
                               4371                 :            940 :         set_using_names(dpns, j->larg, parentUsing);
                               4372                 :            940 :         set_using_names(dpns, j->rarg, parentUsing);
                               4373                 :                :     }
                               4374                 :                :     else
 5080 tgl@sss.pgh.pa.us        4375         [ #  # ]:UBC           0 :         elog(ERROR, "unrecognized node type: %d",
                               4376                 :                :              (int) nodeTag(jtnode));
 5080 tgl@sss.pgh.pa.us        4377                 :CBC        8827 : }
                               4378                 :                : 
                               4379                 :                : /*
                               4380                 :                :  * set_relation_column_names: select column aliases for a non-join RTE
                               4381                 :                :  *
                               4382                 :                :  * Column alias info is saved in *colinfo, which is assumed to be pre-zeroed.
                               4383                 :                :  * If any colnames entries are already filled in, those override local
                               4384                 :                :  * choices.
                               4385                 :                :  */
                               4386                 :                : static void
                               4387                 :          66242 : set_relation_column_names(deparse_namespace *dpns, RangeTblEntry *rte,
                               4388                 :                :                           deparse_columns *colinfo)
                               4389                 :                : {
                               4390                 :                :     int         ncolumns;
                               4391                 :                :     char      **real_colnames;
                               4392                 :                :     bool        changed_any;
                               4393                 :                :     int         noldcolumns;
                               4394                 :                :     int         i;
                               4395                 :                :     int         j;
                               4396                 :                : 
                               4397                 :                :     /*
                               4398                 :                :      * Construct an array of the current "real" column names of the RTE.
                               4399                 :                :      * real_colnames[] will be indexed by physical column number, with NULL
                               4400                 :                :      * entries for dropped columns.
                               4401                 :                :      */
                               4402         [ +  + ]:          66242 :     if (rte->rtekind == RTE_RELATION)
                               4403                 :                :     {
                               4404                 :                :         /* Relation --- look to the system catalogs for up-to-date info */
                               4405                 :                :         Relation    rel;
                               4406                 :                :         TupleDesc   tupdesc;
                               4407                 :                : 
                               4408                 :          54756 :         rel = relation_open(rte->relid, AccessShareLock);
                               4409                 :          54756 :         tupdesc = RelationGetDescr(rel);
                               4410                 :                : 
                               4411                 :          54756 :         ncolumns = tupdesc->natts;
  103 michael@paquier.xyz      4412                 :GNC       54756 :         real_colnames = palloc_array(char *, ncolumns);
                               4413                 :                : 
 5080 tgl@sss.pgh.pa.us        4414         [ +  + ]:CBC      340900 :         for (i = 0; i < ncolumns; i++)
                               4415                 :                :         {
 3387 andres@anarazel.de       4416                 :         286144 :             Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
                               4417                 :                : 
                               4418         [ +  + ]:         286144 :             if (attr->attisdropped)
 5080 tgl@sss.pgh.pa.us        4419                 :           1908 :                 real_colnames[i] = NULL;
                               4420                 :                :             else
 3387 andres@anarazel.de       4421                 :         284236 :                 real_colnames[i] = pstrdup(NameStr(attr->attname));
                               4422                 :                :         }
 5080 tgl@sss.pgh.pa.us        4423                 :          54756 :         relation_close(rel, AccessShareLock);
                               4424                 :                :     }
                               4425                 :                :     else
                               4426                 :                :     {
                               4427                 :                :         /* Otherwise get the column names from eref or expandRTE() */
                               4428                 :                :         List       *colnames;
                               4429                 :                :         ListCell   *lc;
                               4430                 :                : 
                               4431                 :                :         /*
                               4432                 :                :          * Functions returning composites have the annoying property that some
                               4433                 :                :          * of the composite type's columns might have been dropped since the
                               4434                 :                :          * query was parsed.  If possible, use expandRTE() to handle that
                               4435                 :                :          * case, since it has the tedious logic needed to find out about
                               4436                 :                :          * dropped columns.  However, if we're explaining a plan, then we
                               4437                 :                :          * don't have rte->functions because the planner thinks that won't be
                               4438                 :                :          * needed later, and that breaks expandRTE().  So in that case we have
                               4439                 :                :          * to rely on rte->eref, which may lead us to report a dropped
                               4440                 :                :          * column's old name; that seems close enough for EXPLAIN's purposes.
                               4441                 :                :          *
                               4442                 :                :          * For non-RELATION, non-FUNCTION RTEs, we can just look at rte->eref,
                               4443                 :                :          * which should be sufficiently up-to-date: no other RTE types can
                               4444                 :                :          * have columns get dropped from under them after parsing.
                               4445                 :                :          */
 1591                          4446   [ +  +  +  + ]:          11486 :         if (rte->rtekind == RTE_FUNCTION && rte->functions != NIL)
                               4447                 :                :         {
                               4448                 :                :             /* Since we're not creating Vars, rtindex etc. don't matter */
  681 dean.a.rasheed@gmail     4449                 :            564 :             expandRTE(rte, 1, 0, VAR_RETURNING_DEFAULT, -1,
                               4450                 :                :                       true /* include dropped */ , &colnames, NULL);
                               4451                 :                :         }
                               4452                 :                :         else
 1591 tgl@sss.pgh.pa.us        4453                 :          10922 :             colnames = rte->eref->colnames;
                               4454                 :                : 
                               4455                 :          11486 :         ncolumns = list_length(colnames);
  103 michael@paquier.xyz      4456                 :GNC       11486 :         real_colnames = palloc_array(char *, ncolumns);
                               4457                 :                : 
 5080 tgl@sss.pgh.pa.us        4458                 :CBC       11486 :         i = 0;
 1591                          4459   [ +  +  +  +  :          35357 :         foreach(lc, colnames)
                                              +  + ]
                               4460                 :                :         {
                               4461                 :                :             /*
                               4462                 :                :              * If the column name we find here is an empty string, then it's a
                               4463                 :                :              * dropped column, so change to NULL.
                               4464                 :                :              */
 4515                          4465                 :          23871 :             char       *cname = strVal(lfirst(lc));
                               4466                 :                : 
                               4467         [ +  + ]:          23871 :             if (cname[0] == '\0')
                               4468                 :             39 :                 cname = NULL;
                               4469                 :          23871 :             real_colnames[i] = cname;
 5080                          4470                 :          23871 :             i++;
                               4471                 :                :         }
                               4472                 :                :     }
                               4473                 :                : 
                               4474                 :                :     /*
                               4475                 :                :      * Ensure colinfo->colnames has a slot for each column.  (It could be long
                               4476                 :                :      * enough already, if we pushed down a name for the last column.)  Note:
                               4477                 :                :      * it's possible that there are now more columns than there were when the
                               4478                 :                :      * query was parsed, ie colnames could be longer than rte->eref->colnames.
                               4479                 :                :      * We must assign unique aliases to the new columns too, else there could
                               4480                 :                :      * be unresolved conflicts when the view/rule is reloaded.
                               4481                 :                :      */
                               4482                 :          66242 :     expand_colnames_array_to(colinfo, ncolumns);
                               4483         [ -  + ]:          66242 :     Assert(colinfo->num_cols == ncolumns);
                               4484                 :                : 
                               4485                 :                :     /*
                               4486                 :                :      * Make sufficiently large new_colnames and is_new_col arrays, too.
                               4487                 :                :      *
                               4488                 :                :      * Note: because we leave colinfo->num_new_cols zero until after the loop,
                               4489                 :                :      * colname_is_unique will not consult that array, which is fine because it
                               4490                 :                :      * would only be duplicate effort.
                               4491                 :                :      */
  103 michael@paquier.xyz      4492                 :GNC       66242 :     colinfo->new_colnames = palloc_array(char *, ncolumns);
                               4493                 :          66242 :     colinfo->is_new_col = palloc_array(bool, ncolumns);
                               4494                 :                : 
                               4495                 :                :     /* If the RTE is wide enough, use a hash table to avoid O(N^2) costs */
  809 tgl@sss.pgh.pa.us        4496                 :CBC       66242 :     build_colinfo_names_hash(colinfo);
                               4497                 :                : 
                               4498                 :                :     /*
                               4499                 :                :      * Scan the columns, select a unique alias for each one, and store it in
                               4500                 :                :      * colinfo->colnames and colinfo->new_colnames.  The former array has NULL
                               4501                 :                :      * entries for dropped columns, the latter omits them.  Also mark
                               4502                 :                :      * new_colnames entries as to whether they are new since parse time; this
                               4503                 :                :      * is the case for entries beyond the length of rte->eref->colnames.
                               4504                 :                :      */
 5080                          4505                 :          66242 :     noldcolumns = list_length(rte->eref->colnames);
                               4506                 :          66242 :     changed_any = false;
                               4507                 :          66242 :     j = 0;
                               4508         [ +  + ]:         376257 :     for (i = 0; i < ncolumns; i++)
                               4509                 :                :     {
                               4510                 :         310015 :         char       *real_colname = real_colnames[i];
                               4511                 :         310015 :         char       *colname = colinfo->colnames[i];
                               4512                 :                : 
                               4513                 :                :         /* Skip dropped columns */
                               4514         [ +  + ]:         310015 :         if (real_colname == NULL)
                               4515                 :                :         {
                               4516         [ -  + ]:           1947 :             Assert(colname == NULL);    /* colnames[i] is already NULL */
                               4517                 :           1947 :             continue;
                               4518                 :                :         }
                               4519                 :                : 
                               4520                 :                :         /* If alias already assigned, that's what to use */
                               4521         [ +  + ]:         308068 :         if (colname == NULL)
                               4522                 :                :         {
                               4523                 :                :             /* If user wrote an alias, prefer that over real column name */
                               4524   [ +  +  +  + ]:         307368 :             if (rte->alias && i < list_length(rte->alias->colnames))
                               4525                 :          31105 :                 colname = strVal(list_nth(rte->alias->colnames, i));
                               4526                 :                :             else
                               4527                 :         276263 :                 colname = real_colname;
                               4528                 :                : 
                               4529                 :                :             /* Unique-ify and insert into colinfo */
                               4530                 :         307368 :             colname = make_colname_unique(colname, dpns, colinfo);
                               4531                 :                : 
                               4532                 :         307368 :             colinfo->colnames[i] = colname;
  809                          4533                 :         307368 :             add_to_names_hash(colinfo, colname);
                               4534                 :                :         }
                               4535                 :                : 
                               4536                 :                :         /* Put names of non-dropped columns in new_colnames[] too */
 5080                          4537                 :         308068 :         colinfo->new_colnames[j] = colname;
                               4538                 :                :         /* And mark them as new or not */
                               4539                 :         308068 :         colinfo->is_new_col[j] = (i >= noldcolumns);
                               4540                 :         308068 :         j++;
                               4541                 :                : 
                               4542                 :                :         /* Remember if any assigned aliases differ from "real" name */
                               4543   [ +  +  +  + ]:         308068 :         if (!changed_any && strcmp(colname, real_colname) != 0)
                               4544                 :            817 :             changed_any = true;
                               4545                 :                :     }
                               4546                 :                : 
                               4547                 :                :     /* We're now done needing the colinfo's names_hash */
  809                          4548                 :          66242 :     destroy_colinfo_names_hash(colinfo);
                               4549                 :                : 
                               4550                 :                :     /*
                               4551                 :                :      * Set correct length for new_colnames[] array.  (Note: if columns have
                               4552                 :                :      * been added, colinfo->num_cols includes them, which is not really quite
                               4553                 :                :      * right but is harmless, since any new columns must be at the end where
                               4554                 :                :      * they won't affect varattnos of pre-existing columns.)
                               4555                 :                :      */
 5080                          4556                 :          66242 :     colinfo->num_new_cols = j;
                               4557                 :                : 
                               4558                 :                :     /*
                               4559                 :                :      * For a relation RTE, we need only print the alias column names if any
                               4560                 :                :      * are different from the underlying "real" names.  For a function RTE,
                               4561                 :                :      * always emit a complete column alias list; this is to protect against
                               4562                 :                :      * possible instability of the default column names (eg, from altering
                               4563                 :                :      * parameter names).  For tablefunc RTEs, we never print aliases, because
                               4564                 :                :      * the column names are part of the clause itself.  For other RTE types,
                               4565                 :                :      * print if we changed anything OR if there were user-written column
                               4566                 :                :      * aliases (since the latter would be part of the underlying "reality").
                               4567                 :                :      */
                               4568         [ +  + ]:          66242 :     if (rte->rtekind == RTE_RELATION)
                               4569                 :          54756 :         colinfo->printaliases = changed_any;
                               4570         [ +  + ]:          11486 :     else if (rte->rtekind == RTE_FUNCTION)
                               4571                 :           1055 :         colinfo->printaliases = true;
 3552 alvherre@alvh.no-ip.     4572         [ +  + ]:          10431 :     else if (rte->rtekind == RTE_TABLEFUNC)
                               4573                 :            130 :         colinfo->printaliases = false;
 5080 tgl@sss.pgh.pa.us        4574   [ +  +  +  + ]:          10301 :     else if (rte->alias && rte->alias->colnames != NIL)
                               4575                 :            687 :         colinfo->printaliases = true;
                               4576                 :                :     else
                               4577                 :           9614 :         colinfo->printaliases = changed_any;
                               4578                 :          66242 : }
                               4579                 :                : 
                               4580                 :                : /*
                               4581                 :                :  * set_join_column_names: select column aliases for a join RTE
                               4582                 :                :  *
                               4583                 :                :  * Column alias info is saved in *colinfo, which is assumed to be pre-zeroed.
                               4584                 :                :  * If any colnames entries are already filled in, those override local
                               4585                 :                :  * choices.  Also, names for USING columns were already chosen by
                               4586                 :                :  * set_using_names().  We further expect that column alias selection has been
                               4587                 :                :  * completed for both input RTEs.
                               4588                 :                :  */
                               4589                 :                : static void
                               4590                 :            940 : set_join_column_names(deparse_namespace *dpns, RangeTblEntry *rte,
                               4591                 :                :                       deparse_columns *colinfo)
                               4592                 :                : {
                               4593                 :                :     deparse_columns *leftcolinfo;
                               4594                 :                :     deparse_columns *rightcolinfo;
                               4595                 :                :     bool        changed_any;
                               4596                 :                :     int         noldcolumns;
                               4597                 :                :     int         nnewcolumns;
                               4598                 :            940 :     Bitmapset  *leftmerged = NULL;
                               4599                 :            940 :     Bitmapset  *rightmerged = NULL;
                               4600                 :                :     int         i;
                               4601                 :                :     int         j;
                               4602                 :                :     int         ic;
                               4603                 :                :     int         jc;
                               4604                 :                : 
                               4605                 :                :     /* Look up the previously-filled-in child deparse_columns structs */
                               4606                 :            940 :     leftcolinfo = deparse_columns_fetch(colinfo->leftrti, dpns);
                               4607                 :            940 :     rightcolinfo = deparse_columns_fetch(colinfo->rightrti, dpns);
                               4608                 :                : 
                               4609                 :                :     /*
                               4610                 :                :      * Ensure colinfo->colnames has a slot for each column.  (It could be long
                               4611                 :                :      * enough already, if we pushed down a name for the last column.)  Note:
                               4612                 :                :      * it's possible that one or both inputs now have more columns than there
                               4613                 :                :      * were when the query was parsed, but we'll deal with that below.  We
                               4614                 :                :      * only need entries in colnames for pre-existing columns.
                               4615                 :                :      */
                               4616                 :            940 :     noldcolumns = list_length(rte->eref->colnames);
                               4617                 :            940 :     expand_colnames_array_to(colinfo, noldcolumns);
                               4618         [ -  + ]:            940 :     Assert(colinfo->num_cols == noldcolumns);
                               4619                 :                : 
                               4620                 :                :     /* If the RTE is wide enough, use a hash table to avoid O(N^2) costs */
  809                          4621                 :            940 :     build_colinfo_names_hash(colinfo);
                               4622                 :                : 
                               4623                 :                :     /*
                               4624                 :                :      * Scan the join output columns, select an alias for each one, and store
                               4625                 :                :      * it in colinfo->colnames.  If there are USING columns, set_using_names()
                               4626                 :                :      * already selected their names, so we can start the loop at the first
                               4627                 :                :      * non-merged column.
                               4628                 :                :      */
 5080                          4629                 :            940 :     changed_any = false;
                               4630         [ +  + ]:          30556 :     for (i = list_length(colinfo->usingNames); i < noldcolumns; i++)
                               4631                 :                :     {
                               4632                 :          29616 :         char       *colname = colinfo->colnames[i];
                               4633                 :                :         char       *real_colname;
                               4634                 :                : 
                               4635                 :                :         /* Join column must refer to at least one input column */
 2515                          4636   [ +  +  -  + ]:          29616 :         Assert(colinfo->leftattnos[i] != 0 || colinfo->rightattnos[i] != 0);
                               4637                 :                : 
                               4638                 :                :         /* Get the child column name */
 5080                          4639         [ +  + ]:          29616 :         if (colinfo->leftattnos[i] > 0)
                               4640                 :          20749 :             real_colname = leftcolinfo->colnames[colinfo->leftattnos[i] - 1];
                               4641         [ +  - ]:           8867 :         else if (colinfo->rightattnos[i] > 0)
                               4642                 :           8867 :             real_colname = rightcolinfo->colnames[colinfo->rightattnos[i] - 1];
                               4643                 :                :         else
                               4644                 :                :         {
                               4645                 :                :             /* We're joining system columns --- use eref name */
 4876 tgl@sss.pgh.pa.us        4646                 :UBC           0 :             real_colname = strVal(list_nth(rte->eref->colnames, i));
                               4647                 :                :         }
                               4648                 :                : 
                               4649                 :                :         /* If child col has been dropped, no need to assign a join colname */
 2515 tgl@sss.pgh.pa.us        4650         [ +  + ]:CBC       29616 :         if (real_colname == NULL)
                               4651                 :                :         {
                               4652                 :              4 :             colinfo->colnames[i] = NULL;
                               4653                 :              4 :             continue;
                               4654                 :                :         }
                               4655                 :                : 
                               4656                 :                :         /* In an unnamed join, just report child column names as-is */
 5080                          4657         [ +  + ]:          29612 :         if (rte->alias == NULL)
                               4658                 :                :         {
                               4659                 :          29360 :             colinfo->colnames[i] = real_colname;
  809                          4660                 :          29360 :             add_to_names_hash(colinfo, real_colname);
 5080                          4661                 :          29360 :             continue;
                               4662                 :                :         }
                               4663                 :                : 
                               4664                 :                :         /* If alias already assigned, that's what to use */
                               4665         [ +  - ]:            252 :         if (colname == NULL)
                               4666                 :                :         {
                               4667                 :                :             /* If user wrote an alias, prefer that over real column name */
                               4668   [ +  -  +  + ]:            252 :             if (rte->alias && i < list_length(rte->alias->colnames))
                               4669                 :             64 :                 colname = strVal(list_nth(rte->alias->colnames, i));
                               4670                 :                :             else
                               4671                 :            188 :                 colname = real_colname;
                               4672                 :                : 
                               4673                 :                :             /* Unique-ify and insert into colinfo */
                               4674                 :            252 :             colname = make_colname_unique(colname, dpns, colinfo);
                               4675                 :                : 
                               4676                 :            252 :             colinfo->colnames[i] = colname;
  809                          4677                 :            252 :             add_to_names_hash(colinfo, colname);
                               4678                 :                :         }
                               4679                 :                : 
                               4680                 :                :         /* Remember if any assigned aliases differ from "real" name */
 5080                          4681   [ +  +  +  + ]:            252 :         if (!changed_any && strcmp(colname, real_colname) != 0)
                               4682                 :             16 :             changed_any = true;
                               4683                 :                :     }
                               4684                 :                : 
                               4685                 :                :     /*
                               4686                 :                :      * Calculate number of columns the join would have if it were re-parsed
                               4687                 :                :      * now, and create storage for the new_colnames and is_new_col arrays.
                               4688                 :                :      *
                               4689                 :                :      * Note: colname_is_unique will be consulting new_colnames[] during the
                               4690                 :                :      * loops below, so its not-yet-filled entries must be zeroes.
                               4691                 :                :      */
                               4692                 :           1880 :     nnewcolumns = leftcolinfo->num_new_cols + rightcolinfo->num_new_cols -
                               4693                 :            940 :         list_length(colinfo->usingNames);
                               4694                 :            940 :     colinfo->num_new_cols = nnewcolumns;
  103 michael@paquier.xyz      4695                 :GNC         940 :     colinfo->new_colnames = palloc0_array(char *, nnewcolumns);
                               4696                 :            940 :     colinfo->is_new_col = palloc0_array(bool, nnewcolumns);
                               4697                 :                : 
                               4698                 :                :     /*
                               4699                 :                :      * Generating the new_colnames array is a bit tricky since any new columns
                               4700                 :                :      * added since parse time must be inserted in the right places.  This code
                               4701                 :                :      * must match the parser, which will order a join's columns as merged
                               4702                 :                :      * columns first (in USING-clause order), then non-merged columns from the
                               4703                 :                :      * left input (in attnum order), then non-merged columns from the right
                               4704                 :                :      * input (ditto).  If one of the inputs is itself a join, its columns will
                               4705                 :                :      * be ordered according to the same rule, which means newly-added columns
                               4706                 :                :      * might not be at the end.  We can figure out what's what by consulting
                               4707                 :                :      * the leftattnos and rightattnos arrays plus the input is_new_col arrays.
                               4708                 :                :      *
                               4709                 :                :      * In these loops, i indexes leftattnos/rightattnos (so it's join varattno
                               4710                 :                :      * less one), j indexes new_colnames/is_new_col, and ic/jc have similar
                               4711                 :                :      * meanings for the current child RTE.
                               4712                 :                :      */
                               4713                 :                : 
                               4714                 :                :     /* Handle merged columns; they are first and can't be new */
 5080 tgl@sss.pgh.pa.us        4715                 :CBC         940 :     i = j = 0;
                               4716                 :            940 :     while (i < noldcolumns &&
                               4717   [ +  -  +  - ]:           1324 :            colinfo->leftattnos[i] != 0 &&
                               4718         [ +  + ]:           1324 :            colinfo->rightattnos[i] != 0)
                               4719                 :                :     {
                               4720                 :                :         /* column name is already determined and known unique */
                               4721                 :            384 :         colinfo->new_colnames[j] = colinfo->colnames[i];
                               4722                 :            384 :         colinfo->is_new_col[j] = false;
                               4723                 :                : 
                               4724                 :                :         /* build bitmapsets of child attnums of merged columns */
                               4725         [ +  - ]:            384 :         if (colinfo->leftattnos[i] > 0)
                               4726                 :            384 :             leftmerged = bms_add_member(leftmerged, colinfo->leftattnos[i]);
                               4727         [ +  - ]:            384 :         if (colinfo->rightattnos[i] > 0)
                               4728                 :            384 :             rightmerged = bms_add_member(rightmerged, colinfo->rightattnos[i]);
                               4729                 :                : 
                               4730                 :            384 :         i++, j++;
                               4731                 :                :     }
                               4732                 :                : 
                               4733                 :                :     /* Handle non-merged left-child columns */
                               4734                 :            940 :     ic = 0;
                               4735         [ +  + ]:          22397 :     for (jc = 0; jc < leftcolinfo->num_new_cols; jc++)
                               4736                 :                :     {
                               4737                 :          21457 :         char       *child_colname = leftcolinfo->new_colnames[jc];
                               4738                 :                : 
                               4739         [ +  + ]:          21457 :         if (!leftcolinfo->is_new_col[jc])
                               4740                 :                :         {
                               4741                 :                :             /* Advance ic to next non-dropped old column of left child */
                               4742         [ +  - ]:          21185 :             while (ic < leftcolinfo->num_cols &&
                               4743         [ +  + ]:          21185 :                    leftcolinfo->colnames[ic] == NULL)
                               4744                 :             56 :                 ic++;
                               4745         [ -  + ]:          21129 :             Assert(ic < leftcolinfo->num_cols);
                               4746                 :          21129 :             ic++;
                               4747                 :                :             /* If it is a merged column, we already processed it */
                               4748         [ +  + ]:          21129 :             if (bms_is_member(ic, leftmerged))
                               4749                 :            384 :                 continue;
                               4750                 :                :             /* Else, advance i to the corresponding existing join column */
                               4751         [ +  - ]:          20749 :             while (i < colinfo->num_cols &&
                               4752         [ +  + ]:          20749 :                    colinfo->colnames[i] == NULL)
                               4753                 :              4 :                 i++;
                               4754         [ -  + ]:          20745 :             Assert(i < colinfo->num_cols);
                               4755         [ -  + ]:          20745 :             Assert(ic == colinfo->leftattnos[i]);
                               4756                 :                :             /* Use the already-assigned name of this column */
                               4757                 :          20745 :             colinfo->new_colnames[j] = colinfo->colnames[i];
                               4758                 :          20745 :             i++;
                               4759                 :                :         }
                               4760                 :                :         else
                               4761                 :                :         {
                               4762                 :                :             /*
                               4763                 :                :              * Unique-ify the new child column name and assign, unless we're
                               4764                 :                :              * in an unnamed join, in which case just copy
                               4765                 :                :              */
                               4766         [ +  + ]:            328 :             if (rte->alias != NULL)
                               4767                 :                :             {
                               4768                 :            176 :                 colinfo->new_colnames[j] =
                               4769                 :             88 :                     make_colname_unique(child_colname, dpns, colinfo);
                               4770         [ +  + ]:             88 :                 if (!changed_any &&
                               4771         [ +  + ]:             72 :                     strcmp(colinfo->new_colnames[j], child_colname) != 0)
                               4772                 :              8 :                     changed_any = true;
                               4773                 :                :             }
                               4774                 :                :             else
                               4775                 :            240 :                 colinfo->new_colnames[j] = child_colname;
  809                          4776                 :            328 :             add_to_names_hash(colinfo, colinfo->new_colnames[j]);
                               4777                 :                :         }
                               4778                 :                : 
 5080                          4779                 :          21073 :         colinfo->is_new_col[j] = leftcolinfo->is_new_col[jc];
                               4780                 :          21073 :         j++;
                               4781                 :                :     }
                               4782                 :                : 
                               4783                 :                :     /* Handle non-merged right-child columns in exactly the same way */
                               4784                 :            940 :     ic = 0;
                               4785         [ +  + ]:          10303 :     for (jc = 0; jc < rightcolinfo->num_new_cols; jc++)
                               4786                 :                :     {
                               4787                 :           9363 :         char       *child_colname = rightcolinfo->new_colnames[jc];
                               4788                 :                : 
                               4789         [ +  + ]:           9363 :         if (!rightcolinfo->is_new_col[jc])
                               4790                 :                :         {
                               4791                 :                :             /* Advance ic to next non-dropped old column of right child */
                               4792         [ +  - ]:           9251 :             while (ic < rightcolinfo->num_cols &&
                               4793         [ -  + ]:           9251 :                    rightcolinfo->colnames[ic] == NULL)
 5080 tgl@sss.pgh.pa.us        4794                 :UBC           0 :                 ic++;
 5080 tgl@sss.pgh.pa.us        4795         [ -  + ]:CBC        9251 :             Assert(ic < rightcolinfo->num_cols);
                               4796                 :           9251 :             ic++;
                               4797                 :                :             /* If it is a merged column, we already processed it */
                               4798         [ +  + ]:           9251 :             if (bms_is_member(ic, rightmerged))
                               4799                 :            384 :                 continue;
                               4800                 :                :             /* Else, advance i to the corresponding existing join column */
                               4801         [ +  - ]:           8867 :             while (i < colinfo->num_cols &&
                               4802         [ -  + ]:           8867 :                    colinfo->colnames[i] == NULL)
 5080 tgl@sss.pgh.pa.us        4803                 :UBC           0 :                 i++;
 5080 tgl@sss.pgh.pa.us        4804         [ -  + ]:CBC        8867 :             Assert(i < colinfo->num_cols);
                               4805         [ -  + ]:           8867 :             Assert(ic == colinfo->rightattnos[i]);
                               4806                 :                :             /* Use the already-assigned name of this column */
                               4807                 :           8867 :             colinfo->new_colnames[j] = colinfo->colnames[i];
                               4808                 :           8867 :             i++;
                               4809                 :                :         }
                               4810                 :                :         else
                               4811                 :                :         {
                               4812                 :                :             /*
                               4813                 :                :              * Unique-ify the new child column name and assign, unless we're
                               4814                 :                :              * in an unnamed join, in which case just copy
                               4815                 :                :              */
                               4816         [ +  + ]:            112 :             if (rte->alias != NULL)
                               4817                 :                :             {
                               4818                 :             32 :                 colinfo->new_colnames[j] =
                               4819                 :             16 :                     make_colname_unique(child_colname, dpns, colinfo);
                               4820         [ +  - ]:             16 :                 if (!changed_any &&
                               4821         [ +  + ]:             16 :                     strcmp(colinfo->new_colnames[j], child_colname) != 0)
                               4822                 :              8 :                     changed_any = true;
                               4823                 :                :             }
                               4824                 :                :             else
                               4825                 :             96 :                 colinfo->new_colnames[j] = child_colname;
  809                          4826                 :            112 :             add_to_names_hash(colinfo, colinfo->new_colnames[j]);
                               4827                 :                :         }
                               4828                 :                : 
 5080                          4829                 :           8979 :         colinfo->is_new_col[j] = rightcolinfo->is_new_col[jc];
                               4830                 :           8979 :         j++;
                               4831                 :                :     }
                               4832                 :                : 
                               4833                 :                :     /* Assert we processed the right number of columns */
                               4834                 :                : #ifdef USE_ASSERT_CHECKING
                               4835   [ -  +  -  - ]:            940 :     while (i < colinfo->num_cols && colinfo->colnames[i] == NULL)
 5080 tgl@sss.pgh.pa.us        4836                 :UBC           0 :         i++;
 5080 tgl@sss.pgh.pa.us        4837         [ -  + ]:CBC         940 :     Assert(i == colinfo->num_cols);
                               4838         [ -  + ]:            940 :     Assert(j == nnewcolumns);
                               4839                 :                : #endif
                               4840                 :                : 
                               4841                 :                :     /* We're now done needing the colinfo's names_hash */
  809                          4842                 :            940 :     destroy_colinfo_names_hash(colinfo);
                               4843                 :                : 
                               4844                 :                :     /*
                               4845                 :                :      * For a named join, print column aliases if we changed any from the child
                               4846                 :                :      * names.  Unnamed joins cannot print aliases.
                               4847                 :                :      */
 5080                          4848         [ +  + ]:            940 :     if (rte->alias != NULL)
                               4849                 :             72 :         colinfo->printaliases = changed_any;
                               4850                 :                :     else
                               4851                 :            868 :         colinfo->printaliases = false;
                               4852                 :            940 : }
                               4853                 :                : 
                               4854                 :                : /*
                               4855                 :                :  * colname_is_unique: is colname distinct from already-chosen column names?
                               4856                 :                :  *
                               4857                 :                :  * dpns is query-wide info, colinfo is for the column's RTE
                               4858                 :                :  */
                               4859                 :                : static bool
 3315 peter_e@gmx.net          4860                 :         309675 : colname_is_unique(const char *colname, deparse_namespace *dpns,
                               4861                 :                :                   deparse_columns *colinfo)
                               4862                 :                : {
                               4863                 :                :     int         i;
                               4864                 :                :     ListCell   *lc;
                               4865                 :                : 
                               4866                 :                :     /*
                               4867                 :                :      * If we have a hash table, consult that instead of linearly scanning the
                               4868                 :                :      * colinfo's strings.
                               4869                 :                :      */
  809 tgl@sss.pgh.pa.us        4870         [ +  + ]:         309675 :     if (colinfo->names_hash)
                               4871                 :                :     {
                               4872         [ +  + ]:          10922 :         if (hash_search(colinfo->names_hash,
                               4873                 :                :                         colname,
                               4874                 :                :                         HASH_FIND,
                               4875                 :                :                         NULL) != NULL)
 5080                          4876                 :             64 :             return false;
                               4877                 :                :     }
                               4878                 :                :     else
                               4879                 :                :     {
                               4880                 :                :         /* Check against already-assigned column aliases within RTE */
  809                          4881         [ +  + ]:        4111340 :         for (i = 0; i < colinfo->num_cols; i++)
                               4882                 :                :         {
                               4883                 :        3814110 :             char       *oldname = colinfo->colnames[i];
                               4884                 :                : 
                               4885   [ +  +  +  + ]:        3814110 :             if (oldname && strcmp(oldname, colname) == 0)
                               4886                 :           1523 :                 return false;
                               4887                 :                :         }
                               4888                 :                : 
                               4889                 :                :         /*
                               4890                 :                :          * If we're building a new_colnames array, check that too (this will
                               4891                 :                :          * be partially but not completely redundant with the previous checks)
                               4892                 :                :          */
                               4893         [ +  + ]:         298078 :         for (i = 0; i < colinfo->num_new_cols; i++)
                               4894                 :                :         {
                               4895                 :            864 :             char       *oldname = colinfo->new_colnames[i];
                               4896                 :                : 
                               4897   [ +  +  +  + ]:            864 :             if (oldname && strcmp(oldname, colname) == 0)
                               4898                 :             16 :                 return false;
                               4899                 :                :         }
                               4900                 :                : 
                               4901                 :                :         /*
                               4902                 :                :          * Also check against names already assigned for parent-join USING
                               4903                 :                :          * cols
                               4904                 :                :          */
                               4905   [ +  +  +  +  :         298910 :         foreach(lc, colinfo->parentUsing)
                                              +  + ]
                               4906                 :                :         {
                               4907                 :           1700 :             char       *oldname = (char *) lfirst(lc);
                               4908                 :                : 
                               4909         [ +  + ]:           1700 :             if (strcmp(oldname, colname) == 0)
                               4910                 :              4 :                 return false;
                               4911                 :                :         }
                               4912                 :                :     }
                               4913                 :                : 
                               4914                 :                :     /*
                               4915                 :                :      * Also check against USING-column names that must be globally unique.
                               4916                 :                :      * These are not hashed, but there should be few of them.
                               4917                 :                :      */
                               4918   [ +  +  +  +  :         308640 :     foreach(lc, dpns->using_names)
                                              +  + ]
                               4919                 :                :     {
 4594                          4920                 :            600 :         char       *oldname = (char *) lfirst(lc);
                               4921                 :                : 
                               4922         [ +  + ]:            600 :         if (strcmp(oldname, colname) == 0)
                               4923                 :             28 :             return false;
                               4924                 :                :     }
                               4925                 :                : 
 5080                          4926                 :         308040 :     return true;
                               4927                 :                : }
                               4928                 :                : 
                               4929                 :                : /*
                               4930                 :                :  * make_colname_unique: modify colname if necessary to make it unique
                               4931                 :                :  *
                               4932                 :                :  * dpns is query-wide info, colinfo is for the column's RTE
                               4933                 :                :  */
                               4934                 :                : static char *
                               4935                 :         308040 : make_colname_unique(char *colname, deparse_namespace *dpns,
                               4936                 :                :                     deparse_columns *colinfo)
                               4937                 :                : {
                               4938                 :                :     /*
                               4939                 :                :      * If the selected name isn't unique, append digits to make it so.  For a
                               4940                 :                :      * very long input name, we might have to truncate to stay within
                               4941                 :                :      * NAMEDATALEN.
                               4942                 :                :      */
                               4943         [ +  + ]:         308040 :     if (!colname_is_unique(colname, dpns, colinfo))
                               4944                 :                :     {
 4030                          4945                 :           1154 :         int         colnamelen = strlen(colname);
                               4946                 :           1154 :         char       *modname = (char *) palloc(colnamelen + 16);
 5080                          4947                 :           1154 :         int         i = 0;
                               4948                 :                : 
                               4949                 :                :         do
                               4950                 :                :         {
 4030                          4951                 :           1635 :             i++;
                               4952                 :                :             for (;;)
                               4953                 :                :             {
                               4954                 :           1635 :                 memcpy(modname, colname, colnamelen);
                               4955                 :           1635 :                 sprintf(modname + colnamelen, "_%d", i);
                               4956         [ +  - ]:           1635 :                 if (strlen(modname) < NAMEDATALEN)
                               4957                 :           1635 :                     break;
                               4958                 :                :                 /* drop chars from colname to keep all the digits */
 4030 tgl@sss.pgh.pa.us        4959                 :UBC           0 :                 colnamelen = pg_mbcliplen(colname, colnamelen,
                               4960                 :                :                                           colnamelen - 1);
                               4961                 :                :             }
 5080 tgl@sss.pgh.pa.us        4962         [ +  + ]:CBC        1635 :         } while (!colname_is_unique(modname, dpns, colinfo));
                               4963                 :           1154 :         colname = modname;
                               4964                 :                :     }
                               4965                 :         308040 :     return colname;
                               4966                 :                : }
                               4967                 :                : 
                               4968                 :                : /*
                               4969                 :                :  * expand_colnames_array_to: make colinfo->colnames at least n items long
                               4970                 :                :  *
                               4971                 :                :  * Any added array entries are initialized to zero.
                               4972                 :                :  */
                               4973                 :                : static void
                               4974                 :          68374 : expand_colnames_array_to(deparse_columns *colinfo, int n)
                               4975                 :                : {
                               4976         [ +  + ]:          68374 :     if (n > colinfo->num_cols)
                               4977                 :                :     {
                               4978         [ +  + ]:          66224 :         if (colinfo->colnames == NULL)
 1477 peter@eisentraut.org     4979                 :          65288 :             colinfo->colnames = palloc0_array(char *, n);
                               4980                 :                :         else
                               4981                 :            936 :             colinfo->colnames = repalloc0_array(colinfo->colnames, char *, colinfo->num_cols, n);
 5080 tgl@sss.pgh.pa.us        4982                 :          66224 :         colinfo->num_cols = n;
                               4983                 :                :     }
                               4984                 :          68374 : }
                               4985                 :                : 
                               4986                 :                : /*
                               4987                 :                :  * build_colinfo_names_hash: optionally construct a hash table for colinfo
                               4988                 :                :  */
                               4989                 :                : static void
  809                          4990                 :          67182 : build_colinfo_names_hash(deparse_columns *colinfo)
                               4991                 :                : {
                               4992                 :                :     HASHCTL     hash_ctl;
                               4993                 :                :     int         i;
                               4994                 :                :     ListCell   *lc;
                               4995                 :                : 
                               4996                 :                :     /*
                               4997                 :                :      * Use a hash table only for RTEs with at least 32 columns.  (The cutoff
                               4998                 :                :      * is somewhat arbitrary, but let's choose it so that this code does get
                               4999                 :                :      * exercised in the regression tests.)
                               5000                 :                :      */
                               5001         [ +  + ]:          67182 :     if (colinfo->num_cols < 32)
                               5002                 :          66362 :         return;
                               5003                 :                : 
                               5004                 :                :     /*
                               5005                 :                :      * Set up the hash table.  The entries are just strings with no other
                               5006                 :                :      * payload.
                               5007                 :                :      */
                               5008                 :            820 :     hash_ctl.keysize = NAMEDATALEN;
                               5009                 :            820 :     hash_ctl.entrysize = NAMEDATALEN;
                               5010                 :            820 :     hash_ctl.hcxt = CurrentMemoryContext;
                               5011                 :           1640 :     colinfo->names_hash = hash_create("deparse_columns names",
                               5012                 :            820 :                                       colinfo->num_cols + colinfo->num_new_cols,
                               5013                 :                :                                       &hash_ctl,
                               5014                 :                :                                       HASH_ELEM | HASH_STRINGS | HASH_CONTEXT);
                               5015                 :                : 
                               5016                 :                :     /*
                               5017                 :                :      * Preload the hash table with any names already present (these would have
                               5018                 :                :      * come from set_using_names).
                               5019                 :                :      */
                               5020         [ +  + ]:          38348 :     for (i = 0; i < colinfo->num_cols; i++)
                               5021                 :                :     {
                               5022                 :          37528 :         char       *oldname = colinfo->colnames[i];
                               5023                 :                : 
                               5024         [ -  + ]:          37528 :         if (oldname)
  809 tgl@sss.pgh.pa.us        5025                 :UBC           0 :             add_to_names_hash(colinfo, oldname);
                               5026                 :                :     }
                               5027                 :                : 
  809 tgl@sss.pgh.pa.us        5028         [ -  + ]:CBC         820 :     for (i = 0; i < colinfo->num_new_cols; i++)
                               5029                 :                :     {
  809 tgl@sss.pgh.pa.us        5030                 :UBC           0 :         char       *oldname = colinfo->new_colnames[i];
                               5031                 :                : 
                               5032         [ #  # ]:              0 :         if (oldname)
                               5033                 :              0 :             add_to_names_hash(colinfo, oldname);
                               5034                 :                :     }
                               5035                 :                : 
  809 tgl@sss.pgh.pa.us        5036   [ -  +  -  -  :CBC         820 :     foreach(lc, colinfo->parentUsing)
                                              -  + ]
                               5037                 :                :     {
  809 tgl@sss.pgh.pa.us        5038                 :UBC           0 :         char       *oldname = (char *) lfirst(lc);
                               5039                 :                : 
                               5040                 :              0 :         add_to_names_hash(colinfo, oldname);
                               5041                 :                :     }
                               5042                 :                : }
                               5043                 :                : 
                               5044                 :                : /*
                               5045                 :                :  * add_to_names_hash: add a string to the names_hash, if we're using one
                               5046                 :                :  */
                               5047                 :                : static void
  809 tgl@sss.pgh.pa.us        5048                 :CBC      337420 : add_to_names_hash(deparse_columns *colinfo, const char *name)
                               5049                 :                : {
                               5050         [ +  + ]:         337420 :     if (colinfo->names_hash)
                               5051                 :          37528 :         (void) hash_search(colinfo->names_hash,
                               5052                 :                :                            name,
                               5053                 :                :                            HASH_ENTER,
                               5054                 :                :                            NULL);
                               5055                 :         337420 : }
                               5056                 :                : 
                               5057                 :                : /*
                               5058                 :                :  * destroy_colinfo_names_hash: destroy hash table when done with it
                               5059                 :                :  */
                               5060                 :                : static void
                               5061                 :          67182 : destroy_colinfo_names_hash(deparse_columns *colinfo)
                               5062                 :                : {
                               5063         [ +  + ]:          67182 :     if (colinfo->names_hash)
                               5064                 :                :     {
                               5065                 :            820 :         hash_destroy(colinfo->names_hash);
                               5066                 :            820 :         colinfo->names_hash = NULL;
                               5067                 :                :     }
                               5068                 :          67182 : }
                               5069                 :                : 
                               5070                 :                : /*
                               5071                 :                :  * identify_join_columns: figure out where columns of a join come from
                               5072                 :                :  *
                               5073                 :                :  * Fills the join-specific fields of the colinfo struct, except for
                               5074                 :                :  * usingNames which is filled later.
                               5075                 :                :  */
                               5076                 :                : static void
 5080                          5077                 :            940 : identify_join_columns(JoinExpr *j, RangeTblEntry *jrte,
                               5078                 :                :                       deparse_columns *colinfo)
                               5079                 :                : {
                               5080                 :                :     int         numjoincols;
                               5081                 :                :     int         jcolno;
                               5082                 :                :     int         rcolno;
                               5083                 :                :     ListCell   *lc;
                               5084                 :                : 
                               5085                 :                :     /* Extract left/right child RT indexes */
                               5086         [ +  + ]:            940 :     if (IsA(j->larg, RangeTblRef))
                               5087                 :            605 :         colinfo->leftrti = ((RangeTblRef *) j->larg)->rtindex;
                               5088         [ +  - ]:            335 :     else if (IsA(j->larg, JoinExpr))
                               5089                 :            335 :         colinfo->leftrti = ((JoinExpr *) j->larg)->rtindex;
                               5090                 :                :     else
 5080 tgl@sss.pgh.pa.us        5091         [ #  # ]:UBC           0 :         elog(ERROR, "unrecognized node type in jointree: %d",
                               5092                 :                :              (int) nodeTag(j->larg));
 5080 tgl@sss.pgh.pa.us        5093         [ +  - ]:CBC         940 :     if (IsA(j->rarg, RangeTblRef))
                               5094                 :            940 :         colinfo->rightrti = ((RangeTblRef *) j->rarg)->rtindex;
 5080 tgl@sss.pgh.pa.us        5095         [ #  # ]:UBC           0 :     else if (IsA(j->rarg, JoinExpr))
                               5096                 :              0 :         colinfo->rightrti = ((JoinExpr *) j->rarg)->rtindex;
                               5097                 :                :     else
                               5098         [ #  # ]:              0 :         elog(ERROR, "unrecognized node type in jointree: %d",
                               5099                 :                :              (int) nodeTag(j->rarg));
                               5100                 :                : 
                               5101                 :                :     /* Assert children will be processed earlier than join in second pass */
 5080 tgl@sss.pgh.pa.us        5102         [ -  + ]:CBC         940 :     Assert(colinfo->leftrti < j->rtindex);
                               5103         [ -  + ]:            940 :     Assert(colinfo->rightrti < j->rtindex);
                               5104                 :                : 
                               5105                 :                :     /* Initialize result arrays with zeroes */
                               5106                 :            940 :     numjoincols = list_length(jrte->joinaliasvars);
                               5107         [ -  + ]:            940 :     Assert(numjoincols == list_length(jrte->eref->colnames));
  103 michael@paquier.xyz      5108                 :GNC         940 :     colinfo->leftattnos = palloc0_array(int, numjoincols);
                               5109                 :            940 :     colinfo->rightattnos = palloc0_array(int, numjoincols);
                               5110                 :                : 
                               5111                 :                :     /*
                               5112                 :                :      * Deconstruct RTE's joinleftcols/joinrightcols into desired format.
                               5113                 :                :      * Recall that the column(s) merged due to USING are the first column(s)
                               5114                 :                :      * of the join output.  We need not do anything special while scanning
                               5115                 :                :      * joinleftcols, but while scanning joinrightcols we must distinguish
                               5116                 :                :      * merged from unmerged columns.
                               5117                 :                :      */
 2515 tgl@sss.pgh.pa.us        5118                 :CBC         940 :     jcolno = 0;
                               5119   [ +  -  +  +  :          22073 :     foreach(lc, jrte->joinleftcols)
                                              +  + ]
                               5120                 :                :     {
                               5121                 :          21133 :         int         leftattno = lfirst_int(lc);
                               5122                 :                : 
                               5123                 :          21133 :         colinfo->leftattnos[jcolno++] = leftattno;
                               5124                 :                :     }
                               5125                 :            940 :     rcolno = 0;
                               5126   [ +  -  +  +  :          10191 :     foreach(lc, jrte->joinrightcols)
                                              +  + ]
                               5127                 :                :     {
                               5128                 :           9251 :         int         rightattno = lfirst_int(lc);
                               5129                 :                : 
                               5130         [ +  + ]:           9251 :         if (rcolno < jrte->joinmergedcols)    /* merged column? */
                               5131                 :            384 :             colinfo->rightattnos[rcolno] = rightattno;
                               5132                 :                :         else
                               5133                 :           8867 :             colinfo->rightattnos[jcolno++] = rightattno;
                               5134                 :           9251 :         rcolno++;
                               5135                 :                :     }
                               5136         [ -  + ]:            940 :     Assert(jcolno == numjoincols);
 5080                          5137                 :            940 : }
                               5138                 :                : 
                               5139                 :                : /*
                               5140                 :                :  * get_rtable_name: convenience function to get a previously assigned RTE alias
                               5141                 :                :  *
                               5142                 :                :  * The RTE must belong to the topmost namespace level in "context".
                               5143                 :                :  */
                               5144                 :                : static char *
 5181                          5145                 :           4137 : get_rtable_name(int rtindex, deparse_context *context)
                               5146                 :                : {
                               5147                 :           4137 :     deparse_namespace *dpns = (deparse_namespace *) linitial(context->namespaces);
                               5148                 :                : 
                               5149   [ +  -  -  + ]:           4137 :     Assert(rtindex > 0 && rtindex <= list_length(dpns->rtable_names));
                               5150                 :           4137 :     return (char *) list_nth(dpns->rtable_names, rtindex - 1);
                               5151                 :                : }
                               5152                 :                : 
                               5153                 :                : /*
                               5154                 :                :  * set_deparse_plan: set up deparse_namespace to parse subexpressions
                               5155                 :                :  * of a given Plan node
                               5156                 :                :  *
                               5157                 :                :  * This sets the plan, outer_plan, inner_plan, outer_tlist, inner_tlist,
                               5158                 :                :  * index_tlist, ret_old_alias, and ret_new_alias fields as appropriate.
                               5159                 :                :  * Caller must already have adjusted the ancestors list if necessary.
                               5160                 :                :  * Note that the rtable, subplans, and ctes fields do not need to change
                               5161                 :                :  * when shifting attention to different plan nodes in a single plan tree.
                               5162                 :                :  */
                               5163                 :                : static void
 2544                          5164                 :         114958 : set_deparse_plan(deparse_namespace *dpns, Plan *plan)
                               5165                 :                : {
                               5166                 :         114958 :     dpns->plan = plan;
                               5167                 :                : 
                               5168                 :                :     /*
                               5169                 :                :      * We special-case Append and MergeAppend to pretend that the first child
                               5170                 :                :      * plan is the OUTER referent; we have to interpret OUTER Vars in their
                               5171                 :                :      * tlists according to one of the children, and the first one is the most
                               5172                 :                :      * natural choice.
                               5173                 :                :      */
                               5174         [ +  + ]:         114958 :     if (IsA(plan, Append))
                               5175                 :           3140 :         dpns->outer_plan = linitial(((Append *) plan)->appendplans);
                               5176         [ +  + ]:         111818 :     else if (IsA(plan, MergeAppend))
                               5177                 :            403 :         dpns->outer_plan = linitial(((MergeAppend *) plan)->mergeplans);
                               5178                 :                :     else
                               5179                 :         111415 :         dpns->outer_plan = outerPlan(plan);
                               5180                 :                : 
                               5181         [ +  + ]:         114958 :     if (dpns->outer_plan)
                               5182                 :          56402 :         dpns->outer_tlist = dpns->outer_plan->targetlist;
                               5183                 :                :     else
 5527                          5184                 :          58556 :         dpns->outer_tlist = NIL;
                               5185                 :                : 
                               5186                 :                :     /*
                               5187                 :                :      * For a SubqueryScan, pretend the subplan is INNER referent.  (We don't
                               5188                 :                :      * use OUTER because that could someday conflict with the normal meaning.)
                               5189                 :                :      * Likewise, for a CteScan, pretend the subquery's plan is INNER referent.
                               5190                 :                :      * For a WorkTableScan, locate the parent RecursiveUnion plan node and use
                               5191                 :                :      * that as INNER referent.
                               5192                 :                :      *
                               5193                 :                :      * For MERGE, pretend the ModifyTable's source plan (its outer plan) is
                               5194                 :                :      * INNER referent.  This is the join from the target relation to the data
                               5195                 :                :      * source, and all INNER_VAR Vars in other parts of the query refer to its
                               5196                 :                :      * targetlist.
                               5197                 :                :      *
                               5198                 :                :      * For ON CONFLICT DO SELECT/UPDATE we just need the inner tlist to point
                               5199                 :                :      * to the excluded expression's tlist. (Similar to the SubqueryScan we
                               5200                 :                :      * don't want to reuse OUTER, it's used for RETURNING in some modify table
                               5201                 :                :      * cases, although not INSERT .. CONFLICT).
                               5202                 :                :      */
 2544                          5203         [ +  + ]:         114958 :     if (IsA(plan, SubqueryScan))
                               5204                 :            600 :         dpns->inner_plan = ((SubqueryScan *) plan)->subplan;
                               5205         [ +  + ]:         114358 :     else if (IsA(plan, CteScan))
                               5206                 :            413 :         dpns->inner_plan = list_nth(dpns->subplans,
                               5207                 :            413 :                                     ((CteScan *) plan)->ctePlanId - 1);
 1899                          5208         [ +  + ]:         113945 :     else if (IsA(plan, WorkTableScan))
                               5209                 :            116 :         dpns->inner_plan = find_recursive_union(dpns,
                               5210                 :                :                                                 (WorkTableScan *) plan);
 2544                          5211         [ +  + ]:         113829 :     else if (IsA(plan, ModifyTable))
                               5212                 :                :     {
 1706 alvherre@alvh.no-ip.     5213         [ +  + ]:            317 :         if (((ModifyTable *) plan)->operation == CMD_MERGE)
  986 dean.a.rasheed@gmail     5214                 :             40 :             dpns->inner_plan = outerPlan(plan);
                               5215                 :                :         else
                               5216                 :            277 :             dpns->inner_plan = plan;
                               5217                 :                :     }
                               5218                 :                :     else
                               5219                 :         113512 :         dpns->inner_plan = innerPlan(plan);
                               5220                 :                : 
                               5221   [ +  +  +  + ]:         114958 :     if (IsA(plan, ModifyTable) && ((ModifyTable *) plan)->operation == CMD_INSERT)
                               5222                 :            141 :         dpns->inner_tlist = ((ModifyTable *) plan)->exclRelTlist;
 2544 tgl@sss.pgh.pa.us        5223         [ +  + ]:         114817 :     else if (dpns->inner_plan)
                               5224                 :          21301 :         dpns->inner_tlist = dpns->inner_plan->targetlist;
                               5225                 :                :     else
 5527                          5226                 :          93516 :         dpns->inner_tlist = NIL;
                               5227                 :                : 
                               5228                 :                :     /* Set up referent for INDEX_VAR Vars, if needed */
 2544                          5229         [ +  + ]:         114958 :     if (IsA(plan, IndexOnlyScan))
                               5230                 :           2583 :         dpns->index_tlist = ((IndexOnlyScan *) plan)->indextlist;
                               5231         [ +  + ]:         112375 :     else if (IsA(plan, ForeignScan))
                               5232                 :           1735 :         dpns->index_tlist = ((ForeignScan *) plan)->fdw_scan_tlist;
                               5233         [ +  + ]:         110640 :     else if (IsA(plan, CustomScan))
 2544 tgl@sss.pgh.pa.us        5234                 :GBC           4 :         dpns->index_tlist = ((CustomScan *) plan)->custom_scan_tlist;
                               5235                 :                :     else
 5527 tgl@sss.pgh.pa.us        5236                 :CBC      110636 :         dpns->index_tlist = NIL;
                               5237                 :                : 
                               5238                 :                :     /* Set up table aliases for OLD and NEW in RETURNING */
   39                          5239         [ +  + ]:         114958 :     if (IsA(plan, ModifyTable))
                               5240                 :                :     {
                               5241                 :            317 :         dpns->ret_old_alias = ((ModifyTable *) plan)->returningOldAlias;
                               5242                 :            317 :         dpns->ret_new_alias = ((ModifyTable *) plan)->returningNewAlias;
                               5243                 :                :     }
                               5244                 :                :     else
                               5245                 :         114641 :         dpns->ret_old_alias = dpns->ret_new_alias = NULL;
 5982                          5246                 :         114958 : }
                               5247                 :                : 
                               5248                 :                : /*
                               5249                 :                :  * Locate the ancestor plan node that is the RecursiveUnion generating
                               5250                 :                :  * the WorkTableScan's work table.  We can match on wtParam, since that
                               5251                 :                :  * should be unique within the plan tree.
                               5252                 :                :  */
                               5253                 :                : static Plan *
 1899                          5254                 :            116 : find_recursive_union(deparse_namespace *dpns, WorkTableScan *wtscan)
                               5255                 :                : {
                               5256                 :                :     ListCell   *lc;
                               5257                 :                : 
                               5258   [ +  -  +  -  :            292 :     foreach(lc, dpns->ancestors)
                                              +  - ]
                               5259                 :                :     {
                               5260                 :            292 :         Plan       *ancestor = (Plan *) lfirst(lc);
                               5261                 :                : 
                               5262         [ +  + ]:            292 :         if (IsA(ancestor, RecursiveUnion) &&
                               5263         [ +  - ]:            116 :             ((RecursiveUnion *) ancestor)->wtParam == wtscan->wtParam)
                               5264                 :            116 :             return ancestor;
                               5265                 :                :     }
 1899 tgl@sss.pgh.pa.us        5266         [ #  # ]:UBC           0 :     elog(ERROR, "could not find RecursiveUnion for WorkTableScan with wtParam %d",
                               5267                 :                :          wtscan->wtParam);
                               5268                 :                :     return NULL;
                               5269                 :                : }
                               5270                 :                : 
                               5271                 :                : /*
                               5272                 :                :  * push_child_plan: temporarily transfer deparsing attention to a child plan
                               5273                 :                :  *
                               5274                 :                :  * When expanding an OUTER_VAR or INNER_VAR reference, we must adjust the
                               5275                 :                :  * deparse context in case the referenced expression itself uses
                               5276                 :                :  * OUTER_VAR/INNER_VAR.  We modify the top stack entry in-place to avoid
                               5277                 :                :  * affecting levelsup issues (although in a Plan tree there really shouldn't
                               5278                 :                :  * be any).
                               5279                 :                :  *
                               5280                 :                :  * Caller must provide a local deparse_namespace variable to save the
                               5281                 :                :  * previous state for pop_child_plan.
                               5282                 :                :  */
                               5283                 :                : static void
 2544 tgl@sss.pgh.pa.us        5284                 :CBC       67449 : push_child_plan(deparse_namespace *dpns, Plan *plan,
                               5285                 :                :                 deparse_namespace *save_dpns)
                               5286                 :                : {
                               5287                 :                :     /* Save state for restoration later */
 5982                          5288                 :          67449 :     *save_dpns = *dpns;
                               5289                 :                : 
                               5290                 :                :     /* Link current plan node into ancestors list */
 2544                          5291                 :          67449 :     dpns->ancestors = lcons(dpns->plan, dpns->ancestors);
                               5292                 :                : 
                               5293                 :                :     /* Set attention on selected child */
                               5294                 :          67449 :     set_deparse_plan(dpns, plan);
 9418                          5295                 :          67449 : }
                               5296                 :                : 
                               5297                 :                : /*
                               5298                 :                :  * pop_child_plan: undo the effects of push_child_plan
                               5299                 :                :  */
                               5300                 :                : static void
 5982                          5301                 :          67449 : pop_child_plan(deparse_namespace *dpns, deparse_namespace *save_dpns)
                               5302                 :                : {
                               5303                 :                :     List       *ancestors;
                               5304                 :                : 
                               5305                 :                :     /* Get rid of ancestors list cell added by push_child_plan */
 5203                          5306                 :          67449 :     ancestors = list_delete_first(dpns->ancestors);
                               5307                 :                : 
                               5308                 :                :     /* Restore fields changed by push_child_plan */
 5982                          5309                 :          67449 :     *dpns = *save_dpns;
                               5310                 :                : 
                               5311                 :                :     /* Make sure dpns->ancestors is right (may be unnecessary) */
 5203                          5312                 :          67449 :     dpns->ancestors = ancestors;
 5982                          5313                 :          67449 : }
                               5314                 :                : 
                               5315                 :                : /*
                               5316                 :                :  * push_ancestor_plan: temporarily transfer deparsing attention to an
                               5317                 :                :  * ancestor plan
                               5318                 :                :  *
                               5319                 :                :  * When expanding a Param reference, we must adjust the deparse context
                               5320                 :                :  * to match the plan node that contains the expression being printed;
                               5321                 :                :  * otherwise we'd fail if that expression itself contains a Param or
                               5322                 :                :  * OUTER_VAR/INNER_VAR/INDEX_VAR variable.
                               5323                 :                :  *
                               5324                 :                :  * The target ancestor is conveniently identified by the ListCell holding it
                               5325                 :                :  * in dpns->ancestors.
                               5326                 :                :  *
                               5327                 :                :  * Caller must provide a local deparse_namespace variable to save the
                               5328                 :                :  * previous state for pop_ancestor_plan.
                               5329                 :                :  */
                               5330                 :                : static void
                               5331                 :           3949 : push_ancestor_plan(deparse_namespace *dpns, ListCell *ancestor_cell,
                               5332                 :                :                    deparse_namespace *save_dpns)
                               5333                 :                : {
 2544                          5334                 :           3949 :     Plan       *plan = (Plan *) lfirst(ancestor_cell);
                               5335                 :                : 
                               5336                 :                :     /* Save state for restoration later */
 5982                          5337                 :           3949 :     *save_dpns = *dpns;
                               5338                 :                : 
                               5339                 :                :     /* Build a new ancestor list with just this node's ancestors */
 2693                          5340                 :           3949 :     dpns->ancestors =
                               5341                 :           3949 :         list_copy_tail(dpns->ancestors,
                               5342                 :           3949 :                        list_cell_number(dpns->ancestors, ancestor_cell) + 1);
                               5343                 :                : 
                               5344                 :                :     /* Set attention on selected ancestor */
 2544                          5345                 :           3949 :     set_deparse_plan(dpns, plan);
 5982                          5346                 :           3949 : }
                               5347                 :                : 
                               5348                 :                : /*
                               5349                 :                :  * pop_ancestor_plan: undo the effects of push_ancestor_plan
                               5350                 :                :  */
                               5351                 :                : static void
                               5352                 :           3949 : pop_ancestor_plan(deparse_namespace *dpns, deparse_namespace *save_dpns)
                               5353                 :                : {
                               5354                 :                :     /* Free the ancestor list made in push_ancestor_plan */
                               5355                 :           3949 :     list_free(dpns->ancestors);
                               5356                 :                : 
                               5357                 :                :     /* Restore fields changed by push_ancestor_plan */
                               5358                 :           3949 :     *dpns = *save_dpns;
                               5359                 :           3949 : }
                               5360                 :                : 
                               5361                 :                : 
                               5362                 :                : /* ----------
                               5363                 :                :  * make_ruledef         - reconstruct the CREATE RULE command
                               5364                 :                :  *                for a given pg_rewrite tuple
                               5365                 :                :  * ----------
                               5366                 :                :  */
                               5367                 :                : static void
 8522                          5368                 :            313 : make_ruledef(StringInfo buf, HeapTuple ruletup, TupleDesc rulettc,
                               5369                 :                :              int prettyFlags)
                               5370                 :                : {
                               5371                 :                :     char       *rulename;
                               5372                 :                :     char        ev_type;
                               5373                 :                :     Oid         ev_class;
                               5374                 :                :     bool        is_instead;
                               5375                 :                :     char       *ev_qual;
                               5376                 :                :     char       *ev_action;
                               5377                 :                :     List       *actions;
                               5378                 :                :     Relation    ev_relation;
 3414                          5379                 :            313 :     TupleDesc   viewResultDesc = NULL;
                               5380                 :                :     int         fno;
                               5381                 :                :     Datum       dat;
                               5382                 :                :     bool        isnull;
                               5383                 :                : 
                               5384                 :                :     /*
                               5385                 :                :      * Get the attribute values from the rules tuple
                               5386                 :                :      */
 8990                          5387                 :            313 :     fno = SPI_fnumber(rulettc, "rulename");
                               5388                 :            313 :     dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
                               5389         [ -  + ]:            313 :     Assert(!isnull);
                               5390                 :            313 :     rulename = NameStr(*(DatumGetName(dat)));
                               5391                 :                : 
10315 bruce@momjian.us         5392                 :            313 :     fno = SPI_fnumber(rulettc, "ev_type");
 8990 tgl@sss.pgh.pa.us        5393                 :            313 :     dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
                               5394         [ -  + ]:            313 :     Assert(!isnull);
                               5395                 :            313 :     ev_type = DatumGetChar(dat);
                               5396                 :                : 
10315 bruce@momjian.us         5397                 :            313 :     fno = SPI_fnumber(rulettc, "ev_class");
 8990 tgl@sss.pgh.pa.us        5398                 :            313 :     dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
                               5399         [ -  + ]:            313 :     Assert(!isnull);
                               5400                 :            313 :     ev_class = DatumGetObjectId(dat);
                               5401                 :                : 
10315 bruce@momjian.us         5402                 :            313 :     fno = SPI_fnumber(rulettc, "is_instead");
 8990 tgl@sss.pgh.pa.us        5403                 :            313 :     dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
                               5404         [ -  + ]:            313 :     Assert(!isnull);
                               5405                 :            313 :     is_instead = DatumGetBool(dat);
                               5406                 :                : 
10315 bruce@momjian.us         5407                 :            313 :     fno = SPI_fnumber(rulettc, "ev_qual");
                               5408                 :            313 :     ev_qual = SPI_getvalue(ruletup, rulettc, fno);
 2217 tgl@sss.pgh.pa.us        5409         [ -  + ]:            313 :     Assert(ev_qual != NULL);
                               5410                 :                : 
10315 bruce@momjian.us         5411                 :            313 :     fno = SPI_fnumber(rulettc, "ev_action");
                               5412                 :            313 :     ev_action = SPI_getvalue(ruletup, rulettc, fno);
 2217 tgl@sss.pgh.pa.us        5413         [ -  + ]:            313 :     Assert(ev_action != NULL);
                               5414                 :            313 :     actions = (List *) stringToNode(ev_action);
                               5415         [ -  + ]:            313 :     if (actions == NIL)
 2217 tgl@sss.pgh.pa.us        5416         [ #  # ]:UBC           0 :         elog(ERROR, "invalid empty ev_action list");
                               5417                 :                : 
 2868 andres@anarazel.de       5418                 :CBC         313 :     ev_relation = table_open(ev_class, AccessShareLock);
                               5419                 :                : 
                               5420                 :                :     /*
                               5421                 :                :      * Build the rules definition text
                               5422                 :                :      */
 8522 tgl@sss.pgh.pa.us        5423                 :            313 :     appendStringInfo(buf, "CREATE RULE %s AS",
                               5424                 :                :                      quote_identifier(rulename));
                               5425                 :                : 
                               5426         [ +  - ]:            313 :     if (prettyFlags & PRETTYFLAG_INDENT)
 8517 bruce@momjian.us         5427                 :            313 :         appendStringInfoString(buf, "\n    ON ");
                               5428                 :                :     else
 8517 bruce@momjian.us         5429                 :UBC           0 :         appendStringInfoString(buf, " ON ");
                               5430                 :                : 
                               5431                 :                :     /* The event the rule is fired for */
10315 bruce@momjian.us         5432   [ +  +  +  +  :CBC         313 :     switch (ev_type)
                                                 - ]
                               5433                 :                :     {
                               5434                 :              4 :         case '1':
 4776 rhaas@postgresql.org     5435                 :              4 :             appendStringInfoString(buf, "SELECT");
 3414 tgl@sss.pgh.pa.us        5436                 :              4 :             viewResultDesc = RelationGetDescr(ev_relation);
10323 bruce@momjian.us         5437                 :              4 :             break;
                               5438                 :                : 
10315                          5439                 :             84 :         case '2':
 4776 rhaas@postgresql.org     5440                 :             84 :             appendStringInfoString(buf, "UPDATE");
10323 bruce@momjian.us         5441                 :             84 :             break;
                               5442                 :                : 
10315                          5443                 :            169 :         case '3':
 4776 rhaas@postgresql.org     5444                 :            169 :             appendStringInfoString(buf, "INSERT");
10323 bruce@momjian.us         5445                 :            169 :             break;
                               5446                 :                : 
10315                          5447                 :             56 :         case '4':
 4776 rhaas@postgresql.org     5448                 :             56 :             appendStringInfoString(buf, "DELETE");
10323 bruce@momjian.us         5449                 :             56 :             break;
                               5450                 :                : 
10315 bruce@momjian.us         5451                 :UBC           0 :         default:
 8525 tgl@sss.pgh.pa.us        5452         [ #  # ]:              0 :             ereport(ERROR,
                               5453                 :                :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                               5454                 :                :                      errmsg("rule \"%s\" has unsupported event type %d",
                               5455                 :                :                             rulename, ev_type)));
                               5456                 :                :             break;
                               5457                 :                :     }
                               5458                 :                : 
                               5459                 :                :     /* The relation the rule is fired on */
 3197 tgl@sss.pgh.pa.us        5460                 :CBC         313 :     appendStringInfo(buf, " TO %s",
                               5461         [ +  + ]:            313 :                      (prettyFlags & PRETTYFLAG_SCHEMA) ?
                               5462                 :             80 :                      generate_relation_name(ev_class, NIL) :
                               5463                 :            233 :                      generate_qualified_relation_name(ev_class));
                               5464                 :                : 
                               5465                 :                :     /* If the rule has an event qualification, add it */
 2217                          5466         [ +  + ]:            313 :     if (strcmp(ev_qual, "<>") != 0)
                               5467                 :                :     {
                               5468                 :                :         Node       *qual;
                               5469                 :                :         Query      *query;
                               5470                 :                :         deparse_context context;
                               5471                 :                :         deparse_namespace dpns;
                               5472                 :                : 
 8522                          5473         [ +  - ]:             62 :         if (prettyFlags & PRETTYFLAG_INDENT)
 8517 bruce@momjian.us         5474                 :             62 :             appendStringInfoString(buf, "\n  ");
 4776 rhaas@postgresql.org     5475                 :             62 :         appendStringInfoString(buf, " WHERE ");
                               5476                 :                : 
10315 bruce@momjian.us         5477                 :             62 :         qual = stringToNode(ev_qual);
                               5478                 :                : 
                               5479                 :                :         /*
                               5480                 :                :          * We need to make a context for recognizing any Vars in the qual
                               5481                 :                :          * (which can only be references to OLD and NEW).  Use the rtable of
                               5482                 :                :          * the first query in the action list for this purpose.
                               5483                 :                :          */
 8221 neilc@samurai.com        5484                 :             62 :         query = (Query *) linitial(actions);
                               5485                 :                : 
                               5486                 :                :         /*
                               5487                 :                :          * If the action is INSERT...SELECT, OLD/NEW have been pushed down
                               5488                 :                :          * into the SELECT, and that's what we need to look at. (Ugly kluge
                               5489                 :                :          * ... try to fix this when we redesign querytrees.)
                               5490                 :                :          */
 9133 tgl@sss.pgh.pa.us        5491                 :             62 :         query = getInsertSelectQuery(query, NULL);
                               5492                 :                : 
                               5493                 :                :         /* Must acquire locks right away; see notes in get_query_def() */
 4650                          5494                 :             62 :         AcquireRewriteLocks(query, false, false);
                               5495                 :                : 
 9918                          5496                 :             62 :         context.buf = buf;
 8217 neilc@samurai.com        5497                 :             62 :         context.namespaces = list_make1(&dpns);
  821 tgl@sss.pgh.pa.us        5498                 :             62 :         context.resultDesc = NULL;
                               5499                 :             62 :         context.targetList = NIL;
 6544                          5500                 :             62 :         context.windowClause = NIL;
 8217 neilc@samurai.com        5501                 :             62 :         context.varprefix = (list_length(query->rtable) != 1);
 8522 tgl@sss.pgh.pa.us        5502                 :             62 :         context.prettyFlags = prettyFlags;
 5087                          5503                 :             62 :         context.wrapColumn = WRAP_COLUMN_DEFAULT;
 8522                          5504                 :             62 :         context.indentLevel = PRETTYINDENT_STD;
  821                          5505                 :             62 :         context.colNamesVisible = true;
                               5506                 :             62 :         context.inGroupBy = false;
                               5507                 :             62 :         context.varInOrderBy = false;
 2544                          5508                 :             62 :         context.appendparents = NULL;
                               5509                 :                : 
 5080                          5510                 :             62 :         set_deparse_for_query(&dpns, query, NIL);
                               5511                 :                : 
 8836                          5512                 :             62 :         get_rule_expr(qual, &context, false);
                               5513                 :                :     }
                               5514                 :                : 
 4776 rhaas@postgresql.org     5515                 :            313 :     appendStringInfoString(buf, " DO ");
                               5516                 :                : 
                               5517                 :                :     /* The INSTEAD keyword (if so) */
10315 bruce@momjian.us         5518         [ +  + ]:            313 :     if (is_instead)
 4776 rhaas@postgresql.org     5519                 :            183 :         appendStringInfoString(buf, "INSTEAD ");
                               5520                 :                : 
                               5521                 :                :     /* Finally the rules actions */
 8217 neilc@samurai.com        5522         [ +  + ]:            313 :     if (list_length(actions) > 1)
                               5523                 :                :     {
                               5524                 :                :         ListCell   *action;
                               5525                 :                :         Query      *query;
                               5526                 :                : 
 4776 rhaas@postgresql.org     5527                 :             10 :         appendStringInfoChar(buf, '(');
10315 bruce@momjian.us         5528   [ +  -  +  +  :             30 :         foreach(action, actions)
                                              +  + ]
                               5529                 :                :         {
                               5530                 :             20 :             query = (Query *) lfirst(action);
 1652 tgl@sss.pgh.pa.us        5531                 :             20 :             get_query_def(query, buf, NIL, viewResultDesc, true,
                               5532                 :                :                           prettyFlags, WRAP_COLUMN_DEFAULT, 0);
 8522                          5533         [ +  - ]:             20 :             if (prettyFlags)
 4776 rhaas@postgresql.org     5534                 :             20 :                 appendStringInfoString(buf, ";\n");
                               5535                 :                :             else
 4776 rhaas@postgresql.org     5536                 :UBC           0 :                 appendStringInfoString(buf, "; ");
                               5537                 :                :         }
 4776 rhaas@postgresql.org     5538                 :CBC          10 :         appendStringInfoString(buf, ");");
                               5539                 :                :     }
                               5540                 :                :     else
                               5541                 :                :     {
                               5542                 :                :         Query      *query;
                               5543                 :                : 
 8221 neilc@samurai.com        5544                 :            303 :         query = (Query *) linitial(actions);
 1652 tgl@sss.pgh.pa.us        5545                 :            303 :         get_query_def(query, buf, NIL, viewResultDesc, true,
                               5546                 :                :                       prettyFlags, WRAP_COLUMN_DEFAULT, 0);
 4776 rhaas@postgresql.org     5547                 :            303 :         appendStringInfoChar(buf, ';');
                               5548                 :                :     }
                               5549                 :                : 
 2868 andres@anarazel.de       5550                 :            313 :     table_close(ev_relation, AccessShareLock);
10323 bruce@momjian.us         5551                 :            313 : }
                               5552                 :                : 
                               5553                 :                : 
                               5554                 :                : /* ----------
                               5555                 :                :  * make_viewdef         - reconstruct the SELECT part of a
                               5556                 :                :  *                view rewrite rule
                               5557                 :                :  * ----------
                               5558                 :                :  */
                               5559                 :                : static void
 8522 tgl@sss.pgh.pa.us        5560                 :           2173 : make_viewdef(StringInfo buf, HeapTuple ruletup, TupleDesc rulettc,
                               5561                 :                :              int prettyFlags, int wrapColumn)
                               5562                 :                : {
                               5563                 :                :     Query      *query;
                               5564                 :                :     char        ev_type;
                               5565                 :                :     Oid         ev_class;
                               5566                 :                :     bool        is_instead;
                               5567                 :                :     char       *ev_qual;
                               5568                 :                :     char       *ev_action;
                               5569                 :                :     List       *actions;
                               5570                 :                :     Relation    ev_relation;
                               5571                 :                :     int         fno;
                               5572                 :                :     Datum       dat;
                               5573                 :                :     bool        isnull;
                               5574                 :                : 
                               5575                 :                :     /*
                               5576                 :                :      * Get the attribute values from the rules tuple
                               5577                 :                :      */
10315 bruce@momjian.us         5578                 :           2173 :     fno = SPI_fnumber(rulettc, "ev_type");
 3414 tgl@sss.pgh.pa.us        5579                 :           2173 :     dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
                               5580         [ -  + ]:           2173 :     Assert(!isnull);
                               5581                 :           2173 :     ev_type = DatumGetChar(dat);
                               5582                 :                : 
10315 bruce@momjian.us         5583                 :           2173 :     fno = SPI_fnumber(rulettc, "ev_class");
 3414 tgl@sss.pgh.pa.us        5584                 :           2173 :     dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
                               5585         [ -  + ]:           2173 :     Assert(!isnull);
                               5586                 :           2173 :     ev_class = DatumGetObjectId(dat);
                               5587                 :                : 
10315 bruce@momjian.us         5588                 :           2173 :     fno = SPI_fnumber(rulettc, "is_instead");
 3414 tgl@sss.pgh.pa.us        5589                 :           2173 :     dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
                               5590         [ -  + ]:           2173 :     Assert(!isnull);
                               5591                 :           2173 :     is_instead = DatumGetBool(dat);
                               5592                 :                : 
10315 bruce@momjian.us         5593                 :           2173 :     fno = SPI_fnumber(rulettc, "ev_qual");
                               5594                 :           2173 :     ev_qual = SPI_getvalue(ruletup, rulettc, fno);
 2217 tgl@sss.pgh.pa.us        5595         [ -  + ]:           2173 :     Assert(ev_qual != NULL);
                               5596                 :                : 
10315 bruce@momjian.us         5597                 :           2173 :     fno = SPI_fnumber(rulettc, "ev_action");
                               5598                 :           2173 :     ev_action = SPI_getvalue(ruletup, rulettc, fno);
 2217 tgl@sss.pgh.pa.us        5599         [ -  + ]:           2173 :     Assert(ev_action != NULL);
                               5600                 :           2173 :     actions = (List *) stringToNode(ev_action);
                               5601                 :                : 
 8217 neilc@samurai.com        5602         [ -  + ]:           2173 :     if (list_length(actions) != 1)
                               5603                 :                :     {
                               5604                 :                :         /* keep output buffer empty and leave */
 9919 tgl@sss.pgh.pa.us        5605                 :UBC           0 :         return;
                               5606                 :                :     }
                               5607                 :                : 
 8221 neilc@samurai.com        5608                 :CBC        2173 :     query = (Query *) linitial(actions);
                               5609                 :                : 
 4832 kgrittn@postgresql.o     5610   [ +  -  +  - ]:           2173 :     if (ev_type != '1' || !is_instead ||
 8878 tgl@sss.pgh.pa.us        5611   [ +  -  -  + ]:           2173 :         strcmp(ev_qual, "<>") != 0 || query->commandType != CMD_SELECT)
                               5612                 :                :     {
                               5613                 :                :         /* keep output buffer empty and leave */
 9919 tgl@sss.pgh.pa.us        5614                 :UBC           0 :         return;
                               5615                 :                :     }
                               5616                 :                : 
 2868 andres@anarazel.de       5617                 :CBC        2173 :     ev_relation = table_open(ev_class, AccessShareLock);
                               5618                 :                : 
 1652 tgl@sss.pgh.pa.us        5619                 :           2173 :     get_query_def(query, buf, NIL, RelationGetDescr(ev_relation), true,
                               5620                 :                :                   prettyFlags, wrapColumn, 0);
 4776 rhaas@postgresql.org     5621                 :           2173 :     appendStringInfoChar(buf, ';');
                               5622                 :                : 
 2868 andres@anarazel.de       5623                 :           2173 :     table_close(ev_relation, AccessShareLock);
                               5624                 :                : }
                               5625                 :                : 
                               5626                 :                : 
                               5627                 :                : /* ----------
                               5628                 :                :  * get_query_def            - Parse back one query parsetree
                               5629                 :                :  *
                               5630                 :                :  * query: parsetree to be displayed
                               5631                 :                :  * buf: output text is appended to buf
                               5632                 :                :  * parentnamespace: list (initially empty) of outer-level deparse_namespace's
                               5633                 :                :  * resultDesc: if not NULL, the output tuple descriptor for the view
                               5634                 :                :  *      represented by a SELECT query.  We use the column names from it
                               5635                 :                :  *      to label SELECT output columns, in preference to names in the query
                               5636                 :                :  * colNamesVisible: true if the surrounding context cares about the output
                               5637                 :                :  *      column names at all (as, for example, an EXISTS() context does not);
                               5638                 :                :  *      when false, we can suppress dummy column labels such as "?column?"
                               5639                 :                :  * prettyFlags: bitmask of PRETTYFLAG_XXX options
                               5640                 :                :  * wrapColumn: maximum line length, or -1 to disable wrapping
                               5641                 :                :  * startIndent: initial indentation amount
                               5642                 :                :  * ----------
                               5643                 :                :  */
                               5644                 :                : static void
 8878 tgl@sss.pgh.pa.us        5645                 :           3572 : get_query_def(Query *query, StringInfo buf, List *parentnamespace,
                               5646                 :                :               TupleDesc resultDesc, bool colNamesVisible,
                               5647                 :                :               int prettyFlags, int wrapColumn, int startIndent)
                               5648                 :                : {
                               5649                 :                :     deparse_context context;
                               5650                 :                :     deparse_namespace dpns;
                               5651                 :                :     int         rtable_size;
                               5652                 :                : 
                               5653                 :                :     /* Guard against excessively long or deeply-nested queries */
 4595                          5654         [ -  + ]:           3572 :     CHECK_FOR_INTERRUPTS();
                               5655                 :           3572 :     check_stack_depth();
                               5656                 :                : 
  809 rguo@postgresql.org      5657                 :           7144 :     rtable_size = query->hasGroupRTE ?
                               5658         [ +  + ]:           3572 :         list_length(query->rtable) - 1 :
                               5659                 :           3440 :         list_length(query->rtable);
                               5660                 :                : 
                               5661                 :                :     /*
                               5662                 :                :      * Replace any Vars in the query's targetlist and havingQual that
                               5663                 :                :      * reference GROUP outputs with the underlying grouping expressions.
                               5664                 :                :      *
                               5665                 :                :      * We can safely pass NULL for the root here.  Preserving varnullingrels
                               5666                 :                :      * makes no difference to the deparsed source text.
                               5667                 :                :      */
                               5668         [ +  + ]:           3572 :     if (query->hasGroupRTE)
                               5669                 :                :     {
                               5670                 :            132 :         query->targetList = (List *)
                               5671                 :            132 :             flatten_group_exprs(NULL, query, (Node *) query->targetList);
                               5672                 :            132 :         query->havingQual =
                               5673                 :            132 :             flatten_group_exprs(NULL, query, query->havingQual);
                               5674                 :                :     }
                               5675                 :                : 
                               5676                 :                :     /*
                               5677                 :                :      * Before we begin to examine the query, acquire locks on referenced
                               5678                 :                :      * relations, and fix up deleted columns in JOIN RTEs.  This ensures
                               5679                 :                :      * consistent results.  Note we assume it's OK to scribble on the passed
                               5680                 :                :      * querytree!
                               5681                 :                :      *
                               5682                 :                :      * We are only deparsing the query (we are not about to execute it), so we
                               5683                 :                :      * only need AccessShareLock on the relations it mentions.
                               5684                 :                :      */
 4650 tgl@sss.pgh.pa.us        5685                 :           3572 :     AcquireRewriteLocks(query, false, false);
                               5686                 :                : 
 9918                          5687                 :           3572 :     context.buf = buf;
 8221 neilc@samurai.com        5688                 :           3572 :     context.namespaces = lcons(&dpns, list_copy(parentnamespace));
  821 tgl@sss.pgh.pa.us        5689                 :           3572 :     context.resultDesc = NULL;
                               5690                 :           3572 :     context.targetList = NIL;
 6544                          5691                 :           3572 :     context.windowClause = NIL;
 9418                          5692   [ +  +  +  + ]:           3572 :     context.varprefix = (parentnamespace != NIL ||
  809 rguo@postgresql.org      5693                 :           3572 :                          rtable_size != 1);
 8522 tgl@sss.pgh.pa.us        5694                 :           3572 :     context.prettyFlags = prettyFlags;
 5087                          5695                 :           3572 :     context.wrapColumn = wrapColumn;
 8522                          5696                 :           3572 :     context.indentLevel = startIndent;
  821                          5697                 :           3572 :     context.colNamesVisible = colNamesVisible;
                               5698                 :           3572 :     context.inGroupBy = false;
                               5699                 :           3572 :     context.varInOrderBy = false;
 2544                          5700                 :           3572 :     context.appendparents = NULL;
                               5701                 :                : 
 5080                          5702                 :           3572 :     set_deparse_for_query(&dpns, query, parentnamespace);
                               5703                 :                : 
10315 bruce@momjian.us         5704   [ +  +  +  +  :           3572 :     switch (query->commandType)
                                        +  +  +  - ]
                               5705                 :                :     {
10049                          5706                 :           3206 :         case CMD_SELECT:
                               5707                 :                :             /* We set context.resultDesc only if it's a SELECT */
  821 tgl@sss.pgh.pa.us        5708                 :           3206 :             context.resultDesc = resultDesc;
                               5709                 :           3206 :             get_select_query_def(query, &context);
10315 bruce@momjian.us         5710                 :           3206 :             break;
                               5711                 :                : 
                               5712                 :             86 :         case CMD_UPDATE:
  821 tgl@sss.pgh.pa.us        5713                 :             86 :             get_update_query_def(query, &context);
10315 bruce@momjian.us         5714                 :             86 :             break;
                               5715                 :                : 
                               5716                 :            194 :         case CMD_INSERT:
  821 tgl@sss.pgh.pa.us        5717                 :            194 :             get_insert_query_def(query, &context);
10315 bruce@momjian.us         5718                 :            194 :             break;
                               5719                 :                : 
                               5720                 :             39 :         case CMD_DELETE:
  821 tgl@sss.pgh.pa.us        5721                 :             39 :             get_delete_query_def(query, &context);
10315 bruce@momjian.us         5722                 :             39 :             break;
                               5723                 :                : 
 1301 tgl@sss.pgh.pa.us        5724                 :             16 :         case CMD_MERGE:
  821                          5725                 :             16 :             get_merge_query_def(query, &context);
 1301                          5726                 :             16 :             break;
                               5727                 :                : 
10315 bruce@momjian.us         5728                 :             22 :         case CMD_NOTHING:
 4776 rhaas@postgresql.org     5729                 :             22 :             appendStringInfoString(buf, "NOTHING");
10315 bruce@momjian.us         5730                 :             22 :             break;
                               5731                 :                : 
 9460 tgl@sss.pgh.pa.us        5732                 :              9 :         case CMD_UTILITY:
                               5733                 :              9 :             get_utility_query_def(query, &context);
                               5734                 :              9 :             break;
                               5735                 :                : 
10315 bruce@momjian.us         5736                 :UBC           0 :         default:
 8525 tgl@sss.pgh.pa.us        5737         [ #  # ]:              0 :             elog(ERROR, "unrecognized query command type: %d",
                               5738                 :                :                  query->commandType);
                               5739                 :                :             break;
                               5740                 :                :     }
10323 bruce@momjian.us         5741                 :CBC        3572 : }
                               5742                 :                : 
                               5743                 :                : /* ----------
                               5744                 :                :  * get_values_def           - Parse back a VALUES list
                               5745                 :                :  * ----------
                               5746                 :                :  */
                               5747                 :                : static void
 7423 mail@joeconway.com       5748                 :            197 : get_values_def(List *values_lists, deparse_context *context)
                               5749                 :                : {
                               5750                 :            197 :     StringInfo  buf = context->buf;
                               5751                 :            197 :     bool        first_list = true;
                               5752                 :                :     ListCell   *vtl;
                               5753                 :                : 
                               5754                 :            197 :     appendStringInfoString(buf, "VALUES ");
                               5755                 :                : 
                               5756   [ +  -  +  +  :            589 :     foreach(vtl, values_lists)
                                              +  + ]
                               5757                 :                :     {
                               5758                 :            392 :         List       *sublist = (List *) lfirst(vtl);
                               5759                 :            392 :         bool        first_col = true;
                               5760                 :                :         ListCell   *lc;
                               5761                 :                : 
                               5762         [ +  + ]:            392 :         if (first_list)
                               5763                 :            197 :             first_list = false;
                               5764                 :                :         else
                               5765                 :            195 :             appendStringInfoString(buf, ", ");
                               5766                 :                : 
                               5767                 :            392 :         appendStringInfoChar(buf, '(');
                               5768   [ +  -  +  +  :           1392 :         foreach(lc, sublist)
                                              +  + ]
                               5769                 :                :         {
 7360 bruce@momjian.us         5770                 :           1000 :             Node       *col = (Node *) lfirst(lc);
                               5771                 :                : 
 7423 mail@joeconway.com       5772         [ +  + ]:           1000 :             if (first_col)
                               5773                 :            392 :                 first_col = false;
                               5774                 :                :             else
                               5775                 :            608 :                 appendStringInfoChar(buf, ',');
                               5776                 :                : 
                               5777                 :                :             /*
                               5778                 :                :              * Print the value.  Whole-row Vars need special treatment.
                               5779                 :                :              */
 3769 tgl@sss.pgh.pa.us        5780                 :           1000 :             get_rule_expr_toplevel(col, context, false);
                               5781                 :                :         }
 7423 mail@joeconway.com       5782                 :            392 :         appendStringInfoChar(buf, ')');
                               5783                 :                :     }
                               5784                 :            197 : }
                               5785                 :                : 
                               5786                 :                : /* ----------
                               5787                 :                :  * get_with_clause          - Parse back a WITH clause
                               5788                 :                :  * ----------
                               5789                 :                :  */
                               5790                 :                : static void
 6629 tgl@sss.pgh.pa.us        5791                 :           3541 : get_with_clause(Query *query, deparse_context *context)
                               5792                 :                : {
                               5793                 :           3541 :     StringInfo  buf = context->buf;
                               5794                 :                :     const char *sep;
                               5795                 :                :     ListCell   *l;
                               5796                 :                : 
                               5797         [ +  + ]:           3541 :     if (query->cteList == NIL)
                               5798                 :           3474 :         return;
                               5799                 :                : 
                               5800         [ +  - ]:             67 :     if (PRETTY_INDENT(context))
                               5801                 :                :     {
                               5802                 :             67 :         context->indentLevel += PRETTYINDENT_STD;
                               5803                 :             67 :         appendStringInfoChar(buf, ' ');
                               5804                 :                :     }
                               5805                 :                : 
                               5806         [ +  + ]:             67 :     if (query->hasRecursive)
                               5807                 :             34 :         sep = "WITH RECURSIVE ";
                               5808                 :                :     else
                               5809                 :             33 :         sep = "WITH ";
                               5810   [ +  -  +  +  :            164 :     foreach(l, query->cteList)
                                              +  + ]
                               5811                 :                :     {
                               5812                 :             97 :         CommonTableExpr *cte = (CommonTableExpr *) lfirst(l);
                               5813                 :                : 
                               5814                 :             97 :         appendStringInfoString(buf, sep);
                               5815                 :             97 :         appendStringInfoString(buf, quote_identifier(cte->ctename));
                               5816         [ +  + ]:             97 :         if (cte->aliascolnames)
                               5817                 :                :         {
                               5818                 :             38 :             bool        first = true;
                               5819                 :                :             ListCell   *col;
                               5820                 :                : 
                               5821                 :             38 :             appendStringInfoChar(buf, '(');
                               5822   [ +  -  +  +  :            100 :             foreach(col, cte->aliascolnames)
                                              +  + ]
                               5823                 :                :             {
                               5824         [ +  + ]:             62 :                 if (first)
                               5825                 :             38 :                     first = false;
                               5826                 :                :                 else
                               5827                 :             24 :                     appendStringInfoString(buf, ", ");
                               5828                 :             62 :                 appendStringInfoString(buf,
                               5829                 :             62 :                                        quote_identifier(strVal(lfirst(col))));
                               5830                 :                :             }
                               5831                 :             38 :             appendStringInfoChar(buf, ')');
                               5832                 :                :         }
 2842                          5833                 :             97 :         appendStringInfoString(buf, " AS ");
                               5834   [ +  +  -  - ]:             97 :         switch (cte->ctematerialized)
                               5835                 :                :         {
                               5836                 :             85 :             case CTEMaterializeDefault:
                               5837                 :             85 :                 break;
                               5838                 :             12 :             case CTEMaterializeAlways:
                               5839                 :             12 :                 appendStringInfoString(buf, "MATERIALIZED ");
                               5840                 :             12 :                 break;
 2842 tgl@sss.pgh.pa.us        5841                 :UBC           0 :             case CTEMaterializeNever:
                               5842                 :              0 :                 appendStringInfoString(buf, "NOT MATERIALIZED ");
                               5843                 :              0 :                 break;
                               5844                 :                :         }
 2842 tgl@sss.pgh.pa.us        5845                 :CBC          97 :         appendStringInfoChar(buf, '(');
 6629                          5846         [ +  - ]:             97 :         if (PRETTY_INDENT(context))
                               5847                 :             97 :             appendContextKeyword(context, "", 0, 0, 0);
                               5848                 :             97 :         get_query_def((Query *) cte->ctequery, buf, context->namespaces, NULL,
                               5849                 :                :                       true,
                               5850                 :                :                       context->prettyFlags, context->wrapColumn,
                               5851                 :                :                       context->indentLevel);
                               5852         [ +  - ]:             97 :         if (PRETTY_INDENT(context))
                               5853                 :             97 :             appendContextKeyword(context, "", 0, 0, 0);
                               5854                 :             97 :         appendStringInfoChar(buf, ')');
                               5855                 :                : 
 2126 peter@eisentraut.org     5856         [ +  + ]:             97 :         if (cte->search_clause)
                               5857                 :                :         {
                               5858                 :              4 :             bool        first = true;
                               5859                 :                :             ListCell   *lc;
                               5860                 :                : 
                               5861                 :              4 :             appendStringInfo(buf, " SEARCH %s FIRST BY ",
                               5862         [ -  + ]:              4 :                              cte->search_clause->search_breadth_first ? "BREADTH" : "DEPTH");
                               5863                 :                : 
                               5864   [ +  -  +  +  :             12 :             foreach(lc, cte->search_clause->search_col_list)
                                              +  + ]
                               5865                 :                :             {
                               5866         [ +  + ]:              8 :                 if (first)
                               5867                 :              4 :                     first = false;
                               5868                 :                :                 else
                               5869                 :              4 :                     appendStringInfoString(buf, ", ");
                               5870                 :              8 :                 appendStringInfoString(buf,
                               5871                 :              8 :                                        quote_identifier(strVal(lfirst(lc))));
                               5872                 :                :             }
                               5873                 :                : 
                               5874                 :              4 :             appendStringInfo(buf, " SET %s", quote_identifier(cte->search_clause->search_seq_column));
                               5875                 :                :         }
                               5876                 :                : 
                               5877         [ +  + ]:             97 :         if (cte->cycle_clause)
                               5878                 :                :         {
                               5879                 :              8 :             bool        first = true;
                               5880                 :                :             ListCell   *lc;
                               5881                 :                : 
                               5882                 :              8 :             appendStringInfoString(buf, " CYCLE ");
                               5883                 :                : 
                               5884   [ +  -  +  +  :             24 :             foreach(lc, cte->cycle_clause->cycle_col_list)
                                              +  + ]
                               5885                 :                :             {
                               5886         [ +  + ]:             16 :                 if (first)
                               5887                 :              8 :                     first = false;
                               5888                 :                :                 else
                               5889                 :              8 :                     appendStringInfoString(buf, ", ");
                               5890                 :             16 :                 appendStringInfoString(buf,
                               5891                 :             16 :                                        quote_identifier(strVal(lfirst(lc))));
                               5892                 :                :             }
                               5893                 :                : 
                               5894                 :              8 :             appendStringInfo(buf, " SET %s", quote_identifier(cte->cycle_clause->cycle_mark_column));
                               5895                 :                : 
                               5896                 :                :             {
 2100                          5897                 :              8 :                 Const      *cmv = castNode(Const, cte->cycle_clause->cycle_mark_value);
                               5898                 :              8 :                 Const      *cmd = castNode(Const, cte->cycle_clause->cycle_mark_default);
                               5899                 :                : 
                               5900   [ +  +  +  -  :             12 :                 if (!(cmv->consttype == BOOLOID && !cmv->constisnull && DatumGetBool(cmv->constvalue) == true &&
                                        +  -  -  + ]
                               5901   [ +  -  +  - ]:              4 :                       cmd->consttype == BOOLOID && !cmd->constisnull && DatumGetBool(cmd->constvalue) == false))
                               5902                 :                :                 {
                               5903                 :              4 :                     appendStringInfoString(buf, " TO ");
                               5904                 :              4 :                     get_rule_expr(cte->cycle_clause->cycle_mark_value, context, false);
                               5905                 :              4 :                     appendStringInfoString(buf, " DEFAULT ");
                               5906                 :              4 :                     get_rule_expr(cte->cycle_clause->cycle_mark_default, context, false);
                               5907                 :                :                 }
                               5908                 :                :             }
                               5909                 :                : 
 2126                          5910                 :              8 :             appendStringInfo(buf, " USING %s", quote_identifier(cte->cycle_clause->cycle_path_column));
                               5911                 :                :         }
                               5912                 :                : 
 6629 tgl@sss.pgh.pa.us        5913                 :             97 :         sep = ", ";
                               5914                 :                :     }
                               5915                 :                : 
                               5916         [ +  - ]:             67 :     if (PRETTY_INDENT(context))
                               5917                 :                :     {
                               5918                 :             67 :         context->indentLevel -= PRETTYINDENT_STD;
                               5919                 :             67 :         appendContextKeyword(context, "", 0, 0, 0);
                               5920                 :                :     }
                               5921                 :                :     else
 6629 tgl@sss.pgh.pa.us        5922                 :UBC           0 :         appendStringInfoChar(buf, ' ');
                               5923                 :                : }
                               5924                 :                : 
                               5925                 :                : /* ----------
                               5926                 :                :  * get_select_query_def         - Parse back a SELECT parsetree
                               5927                 :                :  * ----------
                               5928                 :                :  */
                               5929                 :                : static void
  821 tgl@sss.pgh.pa.us        5930                 :CBC        3206 : get_select_query_def(Query *query, deparse_context *context)
                               5931                 :                : {
 9550                          5932                 :           3206 :     StringInfo  buf = context->buf;
                               5933                 :                :     bool        force_colno;
                               5934                 :                :     ListCell   *l;
                               5935                 :                : 
                               5936                 :                :     /* Insert the WITH clause if given */
 6629                          5937                 :           3206 :     get_with_clause(query, context);
                               5938                 :                : 
                               5939                 :                :     /* Subroutines may need to consult the SELECT targetlist and windowClause */
  821                          5940                 :           3206 :     context->targetList = query->targetList;
 6544                          5941                 :           3206 :     context->windowClause = query->windowClause;
                               5942                 :                : 
                               5943                 :                :     /*
                               5944                 :                :      * If the Query node has a setOperations tree, then it's the top level of
                               5945                 :                :      * a UNION/INTERSECT/EXCEPT query; only the WITH, ORDER BY and LIMIT
                               5946                 :                :      * fields are interesting in the top query itself.
                               5947                 :                :      */
 9550                          5948         [ +  + ]:           3206 :     if (query->setOperations)
                               5949                 :                :     {
  821                          5950                 :            103 :         get_setop_query(query->setOperations, query, context);
                               5951                 :                :         /* ORDER BY clauses must be simple in this case */
 9358                          5952                 :            103 :         force_colno = true;
                               5953                 :                :     }
                               5954                 :                :     else
                               5955                 :                :     {
  821                          5956                 :           3103 :         get_basic_select_query(query, context);
 9358                          5957                 :           3103 :         force_colno = false;
                               5958                 :                :     }
                               5959                 :                : 
                               5960                 :                :     /* Add the ORDER BY clause if given */
 9550                          5961         [ +  + ]:           3206 :     if (query->sortClause != NIL)
                               5962                 :                :     {
 8517 bruce@momjian.us         5963                 :            119 :         appendContextKeyword(context, " ORDER BY ",
                               5964                 :                :                              -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
 6544 tgl@sss.pgh.pa.us        5965                 :            119 :         get_rule_orderby(query->sortClause, query->targetList,
                               5966                 :                :                          force_colno, context);
                               5967                 :                :     }
                               5968                 :                : 
                               5969                 :                :     /*
                               5970                 :                :      * Add the LIMIT/OFFSET clauses if given. If non-default options, use the
                               5971                 :                :      * standard spelling of LIMIT.
                               5972                 :                :      */
 9529                          5973         [ +  + ]:           3206 :     if (query->limitOffset != NULL)
                               5974                 :                :     {
 8522                          5975                 :             18 :         appendContextKeyword(context, " OFFSET ",
                               5976                 :                :                              -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
 8836                          5977                 :             18 :         get_rule_expr(query->limitOffset, context, false);
                               5978                 :                :     }
 9529                          5979         [ +  + ]:           3206 :     if (query->limitCount != NULL)
                               5980                 :                :     {
 2426 alvherre@alvh.no-ip.     5981         [ +  + ]:             53 :         if (query->limitOption == LIMIT_OPTION_WITH_TIES)
                               5982                 :                :         {
                               5983                 :                :             /*
                               5984                 :                :              * The limitCount arg is a c_expr, so it needs parens. Simple
                               5985                 :                :              * literals and function expressions would not need parens, but
                               5986                 :                :              * unfortunately it's hard to tell if the expression will be
                               5987                 :                :              * printed as a simple literal like 123 or as a typecast
                               5988                 :                :              * expression, like '-123'::int4. The grammar accepts the former
                               5989                 :                :              * without quoting, but not the latter.
                               5990                 :                :              */
                               5991                 :             27 :             appendContextKeyword(context, " FETCH FIRST ",
                               5992                 :                :                                  -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
  558 heikki.linnakangas@i     5993                 :             27 :             appendStringInfoChar(buf, '(');
 8836 tgl@sss.pgh.pa.us        5994                 :             27 :             get_rule_expr(query->limitCount, context, false);
  558 heikki.linnakangas@i     5995                 :             27 :             appendStringInfoChar(buf, ')');
 2235 drowley@postgresql.o     5996                 :             27 :             appendStringInfoString(buf, " ROWS WITH TIES");
                               5997                 :                :         }
                               5998                 :                :         else
                               5999                 :                :         {
 2426 alvherre@alvh.no-ip.     6000                 :             26 :             appendContextKeyword(context, " LIMIT ",
                               6001                 :                :                                  -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
                               6002         [ +  + ]:             26 :             if (IsA(query->limitCount, Const) &&
                               6003         [ +  - ]:              9 :                 ((Const *) query->limitCount)->constisnull)
                               6004                 :              9 :                 appendStringInfoString(buf, "ALL");
                               6005                 :                :             else
                               6006                 :             17 :                 get_rule_expr(query->limitCount, context, false);
                               6007                 :                :         }
                               6008                 :                :     }
                               6009                 :                : 
                               6010                 :                :     /* Add FOR [KEY] UPDATE/SHARE clauses if present */
 6240 tgl@sss.pgh.pa.us        6011         [ +  + ]:           3206 :     if (query->hasForUpdate)
                               6012                 :                :     {
                               6013   [ +  -  +  +  :              8 :         foreach(l, query->rowMarks)
                                              +  + ]
                               6014                 :                :         {
                               6015                 :              4 :             RowMarkClause *rc = (RowMarkClause *) lfirst(l);
                               6016                 :                : 
                               6017                 :                :             /* don't print implicit clauses */
                               6018         [ -  + ]:              4 :             if (rc->pushedDown)
 6240 tgl@sss.pgh.pa.us        6019                 :UBC           0 :                 continue;
                               6020                 :                : 
  289 dean.a.rasheed@gmail     6021                 :CBC           4 :             appendContextKeyword(context,
                               6022                 :              4 :                                  get_lock_clause_strength(rc->strength),
                               6023                 :                :                                  -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
                               6024                 :                : 
 6240 tgl@sss.pgh.pa.us        6025                 :              4 :             appendStringInfo(buf, " OF %s",
 5181                          6026                 :              4 :                              quote_identifier(get_rtable_name(rc->rti,
                               6027                 :                :                                                               context)));
 4435 alvherre@alvh.no-ip.     6028         [ -  + ]:              4 :             if (rc->waitPolicy == LockWaitError)
 4776 rhaas@postgresql.org     6029                 :UBC           0 :                 appendStringInfoString(buf, " NOWAIT");
 4435 alvherre@alvh.no-ip.     6030         [ -  + ]:CBC           4 :             else if (rc->waitPolicy == LockWaitSkip)
 4435 alvherre@alvh.no-ip.     6031                 :UBC           0 :                 appendStringInfoString(buf, " SKIP LOCKED");
                               6032                 :                :         }
                               6033                 :                :     }
 9550 tgl@sss.pgh.pa.us        6034                 :CBC        3206 : }
                               6035                 :                : 
                               6036                 :                : static char *
  289 dean.a.rasheed@gmail     6037                 :              8 : get_lock_clause_strength(LockClauseStrength strength)
                               6038                 :                : {
                               6039   [ -  -  -  -  :              8 :     switch (strength)
                                              +  - ]
                               6040                 :                :     {
  289 dean.a.rasheed@gmail     6041                 :UBC           0 :         case LCS_NONE:
                               6042                 :                :             /* we intentionally throw an error for LCS_NONE */
                               6043         [ #  # ]:              0 :             elog(ERROR, "unrecognized LockClauseStrength %d",
                               6044                 :                :                  (int) strength);
                               6045                 :                :             break;
                               6046                 :              0 :         case LCS_FORKEYSHARE:
                               6047                 :              0 :             return " FOR KEY SHARE";
                               6048                 :              0 :         case LCS_FORSHARE:
                               6049                 :              0 :             return " FOR SHARE";
                               6050                 :              0 :         case LCS_FORNOKEYUPDATE:
                               6051                 :              0 :             return " FOR NO KEY UPDATE";
  289 dean.a.rasheed@gmail     6052                 :CBC           8 :         case LCS_FORUPDATE:
                               6053                 :              8 :             return " FOR UPDATE";
                               6054                 :                :     }
  289 dean.a.rasheed@gmail     6055                 :UBC           0 :     return NULL;                /* keep compiler quiet */
                               6056                 :                : }
                               6057                 :                : 
                               6058                 :                : /*
                               6059                 :                :  * Detect whether query looks like SELECT ... FROM VALUES(),
                               6060                 :                :  * with no need to rename the output columns of the VALUES RTE.
                               6061                 :                :  * If so, return the VALUES RTE.  Otherwise return NULL.
                               6062                 :                :  */
                               6063                 :                : static RangeTblEntry *
 2569 tgl@sss.pgh.pa.us        6064                 :CBC        3103 : get_simple_values_rte(Query *query, TupleDesc resultDesc)
                               6065                 :                : {
 5214                          6066                 :           3103 :     RangeTblEntry *result = NULL;
                               6067                 :                :     ListCell   *lc;
                               6068                 :                : 
                               6069                 :                :     /*
                               6070                 :                :      * We want to detect a match even if the Query also contains OLD or NEW
                               6071                 :                :      * rule RTEs.  So the idea is to scan the rtable and see if there is only
                               6072                 :                :      * one inFromCl RTE that is a VALUES RTE.
                               6073                 :                :      */
                               6074   [ +  +  +  +  :           3366 :     foreach(lc, query->rtable)
                                              +  + ]
                               6075                 :                :     {
                               6076                 :           2797 :         RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
                               6077                 :                : 
                               6078   [ +  +  +  - ]:           2797 :         if (rte->rtekind == RTE_VALUES && rte->inFromCl)
                               6079                 :                :         {
                               6080         [ -  + ]:            171 :             if (result)
                               6081                 :           2534 :                 return NULL;    /* multiple VALUES (probably not possible) */
                               6082                 :            171 :             result = rte;
                               6083                 :                :         }
                               6084   [ +  +  +  + ]:           2626 :         else if (rte->rtekind == RTE_RELATION && !rte->inFromCl)
                               6085                 :             92 :             continue;           /* ignore rule entries */
                               6086                 :                :         else
                               6087                 :           2534 :             return NULL;        /* something else -> not simple VALUES */
                               6088                 :                :     }
                               6089                 :                : 
                               6090                 :                :     /*
                               6091                 :                :      * We don't need to check the targetlist in any great detail, because
                               6092                 :                :      * parser/analyze.c will never generate a "bare" VALUES RTE --- they only
                               6093                 :                :      * appear inside auto-generated sub-queries with very restricted
                               6094                 :                :      * structure.  However, DefineView might have modified the tlist by
                               6095                 :                :      * injecting new column aliases, or we might have some other column
                               6096                 :                :      * aliases forced by a resultDesc.  We can only simplify if the RTE's
                               6097                 :                :      * column names match the names that get_target_list() would select.
                               6098                 :                :      */
 4294                          6099         [ +  + ]:            569 :     if (result)
                               6100                 :                :     {
                               6101                 :                :         ListCell   *lcn;
                               6102                 :                :         int         colno;
                               6103                 :                : 
                               6104         [ -  + ]:            171 :         if (list_length(query->targetList) != list_length(result->eref->colnames))
 4294 tgl@sss.pgh.pa.us        6105                 :UBC           0 :             return NULL;        /* this probably cannot happen */
 2569 tgl@sss.pgh.pa.us        6106                 :CBC         171 :         colno = 0;
 4294                          6107   [ +  -  +  +  :            600 :         forboth(lc, query->targetList, lcn, result->eref->colnames)
                                     +  -  +  +  +  
                                        +  +  -  +  
                                                 + ]
                               6108                 :                :         {
                               6109                 :            437 :             TargetEntry *tle = (TargetEntry *) lfirst(lc);
                               6110                 :            437 :             char       *cname = strVal(lfirst(lcn));
                               6111                 :                :             char       *colname;
                               6112                 :                : 
                               6113         [ -  + ]:            437 :             if (tle->resjunk)
                               6114                 :              8 :                 return NULL;    /* this probably cannot happen */
                               6115                 :                : 
                               6116                 :                :             /* compute name that get_target_list would use for column */
 2569                          6117                 :            437 :             colno++;
                               6118   [ +  +  +  - ]:            437 :             if (resultDesc && colno <= resultDesc->natts)
                               6119                 :             20 :                 colname = NameStr(TupleDescAttr(resultDesc, colno - 1)->attname);
                               6120                 :                :             else
                               6121                 :            417 :                 colname = tle->resname;
                               6122                 :                : 
                               6123                 :                :             /* does it match the VALUES RTE? */
                               6124   [ +  -  +  + ]:            437 :             if (colname == NULL || strcmp(colname, cname) != 0)
 4294                          6125                 :              8 :                 return NULL;    /* column name has been changed */
                               6126                 :                :         }
                               6127                 :                :     }
                               6128                 :                : 
 5214                          6129                 :            561 :     return result;
                               6130                 :                : }
                               6131                 :                : 
                               6132                 :                : static void
  821                          6133                 :           3103 : get_basic_select_query(Query *query, deparse_context *context)
                               6134                 :                : {
 9918                          6135                 :           3103 :     StringInfo  buf = context->buf;
                               6136                 :                :     RangeTblEntry *values_rte;
                               6137                 :                :     char       *sep;
                               6138                 :                :     ListCell   *l;
                               6139                 :                : 
 8522                          6140         [ +  + ]:           3103 :     if (PRETTY_INDENT(context))
                               6141                 :                :     {
 8517 bruce@momjian.us         6142                 :           3076 :         context->indentLevel += PRETTYINDENT_STD;
                               6143                 :           3076 :         appendStringInfoChar(buf, ' ');
                               6144                 :                :     }
                               6145                 :                : 
                               6146                 :                :     /*
                               6147                 :                :      * If the query looks like SELECT * FROM (VALUES ...), then print just the
                               6148                 :                :      * VALUES part.  This reverses what transformValuesClause() did at parse
                               6149                 :                :      * time.
                               6150                 :                :      */
  821 tgl@sss.pgh.pa.us        6151                 :           3103 :     values_rte = get_simple_values_rte(query, context->resultDesc);
 5214                          6152         [ +  + ]:           3103 :     if (values_rte)
                               6153                 :                :     {
                               6154                 :            163 :         get_values_def(values_rte->values_lists, context);
                               6155                 :            163 :         return;
                               6156                 :                :     }
                               6157                 :                : 
                               6158                 :                :     /*
                               6159                 :                :      * Build up the query string - first we say SELECT
                               6160                 :                :      */
 2061 peter@eisentraut.org     6161         [ +  + ]:           2940 :     if (query->isReturn)
                               6162                 :             31 :         appendStringInfoString(buf, "RETURN");
                               6163                 :                :     else
                               6164                 :           2909 :         appendStringInfoString(buf, "SELECT");
                               6165                 :                : 
                               6166                 :                :     /* Add the DISTINCT clause if given */
 9550 tgl@sss.pgh.pa.us        6167         [ -  + ]:           2940 :     if (query->distinctClause != NIL)
                               6168                 :                :     {
 6692 tgl@sss.pgh.pa.us        6169         [ #  # ]:UBC           0 :         if (query->hasDistinctOn)
                               6170                 :                :         {
 4776 rhaas@postgresql.org     6171                 :              0 :             appendStringInfoString(buf, " DISTINCT ON (");
 9550 tgl@sss.pgh.pa.us        6172                 :              0 :             sep = "";
                               6173   [ #  #  #  #  :              0 :             foreach(l, query->distinctClause)
                                              #  # ]
                               6174                 :                :             {
 6692                          6175                 :              0 :                 SortGroupClause *srt = (SortGroupClause *) lfirst(l);
                               6176                 :                : 
 7882 neilc@samurai.com        6177                 :              0 :                 appendStringInfoString(buf, sep);
 4214 andres@anarazel.de       6178                 :              0 :                 get_rule_sortgroupclause(srt->tleSortGroupRef, query->targetList,
                               6179                 :                :                                          false, context);
 9550 tgl@sss.pgh.pa.us        6180                 :              0 :                 sep = ", ";
                               6181                 :                :             }
 4776 rhaas@postgresql.org     6182                 :              0 :             appendStringInfoChar(buf, ')');
                               6183                 :                :         }
                               6184                 :                :         else
                               6185                 :              0 :             appendStringInfoString(buf, " DISTINCT");
                               6186                 :                :     }
                               6187                 :                : 
                               6188                 :                :     /* Then we tell what to select (the targetlist) */
  821 tgl@sss.pgh.pa.us        6189                 :CBC        2940 :     get_target_list(query->targetList, context);
                               6190                 :                : 
                               6191                 :                :     /* Add the FROM clause if needed */
 7413                          6192                 :           2940 :     get_from_clause(query, " FROM ", context);
                               6193                 :                : 
                               6194                 :                :     /* Add the WHERE clause if given */
                               6195         [ +  + ]:           2940 :     if (query->jointree->quals != NULL)
                               6196                 :                :     {
                               6197                 :            903 :         appendContextKeyword(context, " WHERE ",
                               6198                 :                :                              -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
                               6199                 :            903 :         get_rule_expr(query->jointree->quals, context, false);
                               6200                 :                :     }
                               6201                 :                : 
                               6202                 :                :     /* Add the GROUP BY clause if given */
 4214 andres@anarazel.de       6203   [ +  +  -  + ]:           2940 :     if (query->groupClause != NULL || query->groupingSets != NULL)
                               6204                 :                :     {
                               6205                 :                :         bool        save_ingroupby;
                               6206                 :                : 
 7413 tgl@sss.pgh.pa.us        6207                 :            132 :         appendContextKeyword(context, " GROUP BY ",
                               6208                 :                :                              -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
 2081 tomas.vondra@postgre     6209         [ -  + ]:            132 :         if (query->groupDistinct)
 2081 tomas.vondra@postgre     6210                 :UBC           0 :             appendStringInfoString(buf, "DISTINCT ");
                               6211                 :                : 
  821 tgl@sss.pgh.pa.us        6212                 :CBC         132 :         save_ingroupby = context->inGroupBy;
                               6213                 :            132 :         context->inGroupBy = true;
                               6214                 :                : 
  134                          6215         [ +  + ]:            132 :         if (query->groupingSets == NIL)
                               6216                 :                :         {
 4214 andres@anarazel.de       6217                 :            128 :             sep = "";
                               6218   [ +  -  +  +  :            289 :             foreach(l, query->groupClause)
                                              +  + ]
                               6219                 :                :             {
                               6220                 :            161 :                 SortGroupClause *grp = (SortGroupClause *) lfirst(l);
                               6221                 :                : 
                               6222                 :            161 :                 appendStringInfoString(buf, sep);
                               6223                 :            161 :                 get_rule_sortgroupclause(grp->tleSortGroupRef, query->targetList,
                               6224                 :                :                                          false, context);
                               6225                 :            161 :                 sep = ", ";
                               6226                 :                :             }
                               6227                 :                :         }
                               6228                 :                :         else
                               6229                 :                :         {
                               6230                 :              4 :             sep = "";
                               6231   [ +  -  +  +  :              8 :             foreach(l, query->groupingSets)
                                              +  + ]
                               6232                 :                :             {
                               6233                 :              4 :                 GroupingSet *grp = lfirst(l);
                               6234                 :                : 
                               6235                 :              4 :                 appendStringInfoString(buf, sep);
                               6236                 :              4 :                 get_rule_groupingset(grp, query->targetList, true, context);
                               6237                 :              4 :                 sep = ", ";
                               6238                 :                :             }
                               6239                 :                :         }
                               6240                 :                : 
  821 tgl@sss.pgh.pa.us        6241                 :            132 :         context->inGroupBy = save_ingroupby;
                               6242                 :                :     }
                               6243                 :                : 
                               6244                 :                :     /* Add the HAVING clause if given */
 7413                          6245         [ +  + ]:           2940 :     if (query->havingQual != NULL)
                               6246                 :                :     {
                               6247                 :              5 :         appendContextKeyword(context, " HAVING ",
                               6248                 :                :                              -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
                               6249                 :              5 :         get_rule_expr(query->havingQual, context, false);
                               6250                 :                :     }
                               6251                 :                : 
                               6252                 :                :     /* Add the WINDOW clause if needed */
 6544                          6253         [ +  + ]:           2940 :     if (query->windowClause != NIL)
                               6254                 :             32 :         get_rule_windowclause(query, context);
                               6255                 :                : }
                               6256                 :                : 
                               6257                 :                : /* ----------
                               6258                 :                :  * get_target_list          - Parse back a SELECT target list
                               6259                 :                :  *
                               6260                 :                :  * This is also used for RETURNING lists in INSERT/UPDATE/DELETE/MERGE.
                               6261                 :                :  * ----------
                               6262                 :                :  */
                               6263                 :                : static void
  821                          6264                 :           3037 : get_target_list(List *targetList, deparse_context *context)
                               6265                 :                : {
 7413                          6266                 :           3037 :     StringInfo  buf = context->buf;
                               6267                 :                :     StringInfoData targetbuf;
 5087                          6268                 :           3037 :     bool        last_was_multiline = false;
                               6269                 :                :     char       *sep;
                               6270                 :                :     int         colno;
                               6271                 :                :     ListCell   *l;
                               6272                 :                : 
                               6273                 :                :     /* we use targetbuf to hold each TLE's text temporarily */
                               6274                 :           3037 :     initStringInfo(&targetbuf);
                               6275                 :                : 
10323 bruce@momjian.us         6276                 :           3037 :     sep = " ";
 8878 tgl@sss.pgh.pa.us        6277                 :           3037 :     colno = 0;
 7413                          6278   [ +  -  +  +  :          15923 :     foreach(l, targetList)
                                              +  + ]
                               6279                 :                :     {
 9573                          6280                 :          12886 :         TargetEntry *tle = (TargetEntry *) lfirst(l);
                               6281                 :                :         char       *colname;
                               6282                 :                :         char       *attname;
                               6283                 :                : 
 7906                          6284         [ +  + ]:          12886 :         if (tle->resjunk)
 9556                          6285                 :             25 :             continue;           /* ignore junk entries */
                               6286                 :                : 
 7882 neilc@samurai.com        6287                 :          12861 :         appendStringInfoString(buf, sep);
10315 bruce@momjian.us         6288                 :          12861 :         sep = ", ";
 8878 tgl@sss.pgh.pa.us        6289                 :          12861 :         colno++;
                               6290                 :                : 
                               6291                 :                :         /*
                               6292                 :                :          * Put the new field text into targetbuf so we can decide after we've
                               6293                 :                :          * got it whether or not it needs to go on a new line.
                               6294                 :                :          */
 5087                          6295                 :          12861 :         resetStringInfo(&targetbuf);
 5396 andrew@dunslane.net      6296                 :          12861 :         context->buf = &targetbuf;
                               6297                 :                : 
                               6298                 :                :         /*
                               6299                 :                :          * We special-case Var nodes rather than using get_rule_expr. This is
                               6300                 :                :          * needed because get_rule_expr will display a whole-row Var as
                               6301                 :                :          * "foo.*", which is the preferred notation in most contexts, but at
                               6302                 :                :          * the top level of a SELECT list it's not right (the parser will
                               6303                 :                :          * expand that notation into multiple columns, yielding behavior
                               6304                 :                :          * different from a whole-row Var).  We need to call get_variable
                               6305                 :                :          * directly so that we can tell it to do the right thing, and so that
                               6306                 :                :          * we can get the attribute name which is the default AS label.
                               6307                 :                :          */
 4214 andres@anarazel.de       6308   [ +  -  +  + ]:          12861 :         if (tle->expr && (IsA(tle->expr, Var)))
                               6309                 :                :         {
 5328 tgl@sss.pgh.pa.us        6310                 :           9849 :             attname = get_variable((Var *) tle->expr, 0, true, context);
                               6311                 :                :         }
                               6312                 :                :         else
                               6313                 :                :         {
 7611                          6314                 :           3012 :             get_rule_expr((Node *) tle->expr, context, true);
                               6315                 :                : 
                               6316                 :                :             /*
                               6317                 :                :              * When colNamesVisible is true, we should always show the
                               6318                 :                :              * assigned column name explicitly.  Otherwise, show it only if
                               6319                 :                :              * it's not FigureColname's fallback.
                               6320                 :                :              */
  821                          6321         [ +  + ]:           3012 :             attname = context->colNamesVisible ? NULL : "?column?";
                               6322                 :                :         }
                               6323                 :                : 
                               6324                 :                :         /*
                               6325                 :                :          * Figure out what the result column should be called.  In the context
                               6326                 :                :          * of a view, use the view's tuple descriptor (so as to pick up the
                               6327                 :                :          * effects of any column RENAME that's been done on the view).
                               6328                 :                :          * Otherwise, just use what we can find in the TLE.
                               6329                 :                :          */
                               6330   [ +  +  +  - ]:          12861 :         if (context->resultDesc && colno <= context->resultDesc->natts)
                               6331                 :          11670 :             colname = NameStr(TupleDescAttr(context->resultDesc,
                               6332                 :                :                                             colno - 1)->attname);
                               6333                 :                :         else
 7906                          6334                 :           1191 :             colname = tle->resname;
                               6335                 :                : 
                               6336                 :                :         /* Show AS unless the column's name is correct as-is */
 8510                          6337         [ +  + ]:          12861 :         if (colname)            /* resname could be NULL */
                               6338                 :                :         {
 7611                          6339   [ +  +  +  + ]:          12830 :             if (attname == NULL || strcmp(attname, colname) != 0)
 5396 andrew@dunslane.net      6340                 :           4229 :                 appendStringInfo(&targetbuf, " AS %s", quote_identifier(colname));
                               6341                 :                :         }
                               6342                 :                : 
                               6343                 :                :         /* Restore context's output buffer */
                               6344                 :          12861 :         context->buf = buf;
                               6345                 :                : 
                               6346                 :                :         /* Consider line-wrapping if enabled */
 5087 tgl@sss.pgh.pa.us        6347   [ +  +  +  - ]:          12861 :         if (PRETTY_INDENT(context) && context->wrapColumn >= 0)
                               6348                 :                :         {
                               6349                 :                :             int         leading_nl_pos;
                               6350                 :                : 
                               6351                 :                :             /* Does the new field start with a new line? */
 4765                          6352   [ +  -  +  + ]:          12834 :             if (targetbuf.len > 0 && targetbuf.data[0] == '\n')
                               6353                 :            375 :                 leading_nl_pos = 0;
                               6354                 :                :             else
                               6355                 :          12459 :                 leading_nl_pos = -1;
                               6356                 :                : 
                               6357                 :                :             /* If so, we shouldn't add anything */
                               6358         [ +  + ]:          12834 :             if (leading_nl_pos >= 0)
                               6359                 :                :             {
                               6360                 :                :                 /* instead, remove any trailing spaces currently in buf */
                               6361                 :            375 :                 removeStringInfoSpaces(buf);
                               6362                 :                :             }
                               6363                 :                :             else
                               6364                 :                :             {
                               6365                 :                :                 char       *trailing_nl;
                               6366                 :                : 
                               6367                 :                :                 /* Locate the start of the current line in the output buffer */
                               6368                 :          12459 :                 trailing_nl = strrchr(buf->data, '\n');
                               6369         [ +  + ]:          12459 :                 if (trailing_nl == NULL)
                               6370                 :           3726 :                     trailing_nl = buf->data;
                               6371                 :                :                 else
                               6372                 :           8733 :                     trailing_nl++;
                               6373                 :                : 
                               6374                 :                :                 /*
                               6375                 :                :                  * Add a newline, plus some indentation, if the new field is
                               6376                 :                :                  * not the first and either the new field would cause an
                               6377                 :                :                  * overflow or the last field used more than one line.
                               6378                 :                :                  */
                               6379         [ +  + ]:          12459 :                 if (colno > 1 &&
                               6380   [ -  +  -  - ]:           9458 :                     ((strlen(trailing_nl) + targetbuf.len > context->wrapColumn) ||
                               6381                 :                :                      last_was_multiline))
                               6382                 :           9458 :                     appendContextKeyword(context, "", -PRETTYINDENT_STD,
                               6383                 :                :                                          PRETTYINDENT_STD, PRETTYINDENT_VAR);
                               6384                 :                :             }
                               6385                 :                : 
                               6386                 :                :             /* Remember this field's multiline status for next iteration */
 5087                          6387                 :          12834 :             last_was_multiline =
                               6388                 :          12834 :                 (strchr(targetbuf.data + leading_nl_pos + 1, '\n') != NULL);
                               6389                 :                :         }
                               6390                 :                : 
                               6391                 :                :         /* Add the new field */
 2685 drowley@postgresql.o     6392                 :          12861 :         appendBinaryStringInfo(buf, targetbuf.data, targetbuf.len);
                               6393                 :                :     }
                               6394                 :                : 
                               6395                 :                :     /* clean up */
 5087 tgl@sss.pgh.pa.us        6396                 :           3037 :     pfree(targetbuf.data);
 9550                          6397                 :           3037 : }
                               6398                 :                : 
                               6399                 :                : static void
  681 dean.a.rasheed@gmail     6400                 :             97 : get_returning_clause(Query *query, deparse_context *context)
                               6401                 :                : {
                               6402                 :             97 :     StringInfo  buf = context->buf;
                               6403                 :                : 
                               6404         [ +  - ]:             97 :     if (query->returningList)
                               6405                 :                :     {
                               6406                 :             97 :         bool        have_with = false;
                               6407                 :                : 
                               6408                 :             97 :         appendContextKeyword(context, " RETURNING",
                               6409                 :                :                              -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
                               6410                 :                : 
                               6411                 :                :         /* Add WITH (OLD/NEW) options, if they're not the defaults */
                               6412   [ +  +  +  + ]:             97 :         if (query->returningOldAlias && strcmp(query->returningOldAlias, "old") != 0)
                               6413                 :                :         {
                               6414                 :             12 :             appendStringInfo(buf, " WITH (OLD AS %s",
                               6415                 :             12 :                              quote_identifier(query->returningOldAlias));
                               6416                 :             12 :             have_with = true;
                               6417                 :                :         }
                               6418   [ +  +  +  + ]:             97 :         if (query->returningNewAlias && strcmp(query->returningNewAlias, "new") != 0)
                               6419                 :                :         {
                               6420         [ +  + ]:             12 :             if (have_with)
                               6421                 :              8 :                 appendStringInfo(buf, ", NEW AS %s",
                               6422                 :              8 :                                  quote_identifier(query->returningNewAlias));
                               6423                 :                :             else
                               6424                 :                :             {
                               6425                 :              4 :                 appendStringInfo(buf, " WITH (NEW AS %s",
                               6426                 :              4 :                                  quote_identifier(query->returningNewAlias));
                               6427                 :              4 :                 have_with = true;
                               6428                 :                :             }
                               6429                 :                :         }
                               6430         [ +  + ]:             97 :         if (have_with)
                               6431                 :             16 :             appendStringInfoChar(buf, ')');
                               6432                 :                : 
                               6433                 :                :         /* Add the returning expressions themselves */
                               6434                 :             97 :         get_target_list(query->returningList, context);
                               6435                 :                :     }
                               6436                 :             97 : }
                               6437                 :                : 
                               6438                 :                : static void
  821 tgl@sss.pgh.pa.us        6439                 :            463 : get_setop_query(Node *setOp, Query *query, deparse_context *context)
                               6440                 :                : {
 9550                          6441                 :            463 :     StringInfo  buf = context->buf;
                               6442                 :                :     bool        need_paren;
                               6443                 :                : 
                               6444                 :                :     /* Guard against excessively long or deeply-nested queries */
 4595                          6445         [ -  + ]:            463 :     CHECK_FOR_INTERRUPTS();
                               6446                 :            463 :     check_stack_depth();
                               6447                 :                : 
 9550                          6448         [ +  + ]:            463 :     if (IsA(setOp, RangeTblRef))
                               6449                 :                :     {
                               6450                 :            283 :         RangeTblRef *rtr = (RangeTblRef *) setOp;
                               6451                 :            283 :         RangeTblEntry *rte = rt_fetch(rtr->rtindex, query->rtable);
 9382 bruce@momjian.us         6452                 :            283 :         Query      *subquery = rte->subquery;
                               6453                 :                : 
 9550 tgl@sss.pgh.pa.us        6454         [ -  + ]:            283 :         Assert(subquery != NULL);
                               6455                 :                : 
                               6456                 :                :         /*
                               6457                 :                :          * We need parens if WITH, ORDER BY, FOR UPDATE, or LIMIT; see gram.y.
                               6458                 :                :          * Also add parens if the leaf query contains its own set operations.
                               6459                 :                :          * (That shouldn't happen unless one of the other clauses is also
                               6460                 :                :          * present, see transformSetOperationTree; but let's be safe.)
                               6461                 :                :          */
 6629                          6462                 :            849 :         need_paren = (subquery->cteList ||
                               6463         [ +  - ]:            283 :                       subquery->sortClause ||
 8180                          6464         [ +  - ]:            283 :                       subquery->rowMarks ||
                               6465         [ +  - ]:            283 :                       subquery->limitOffset ||
  738                          6466   [ +  -  +  - ]:            849 :                       subquery->limitCount ||
                               6467         [ -  + ]:            283 :                       subquery->setOperations);
 8180                          6468         [ -  + ]:            283 :         if (need_paren)
 8180 tgl@sss.pgh.pa.us        6469                 :UBC           0 :             appendStringInfoChar(buf, '(');
  821 tgl@sss.pgh.pa.us        6470                 :CBC         283 :         get_query_def(subquery, buf, context->namespaces,
                               6471                 :            283 :                       context->resultDesc, context->colNamesVisible,
                               6472                 :                :                       context->prettyFlags, context->wrapColumn,
                               6473                 :                :                       context->indentLevel);
 8180                          6474         [ -  + ]:            283 :         if (need_paren)
 8180 tgl@sss.pgh.pa.us        6475                 :UBC           0 :             appendStringInfoChar(buf, ')');
                               6476                 :                :     }
 9550 tgl@sss.pgh.pa.us        6477         [ +  - ]:CBC         180 :     else if (IsA(setOp, SetOperationStmt))
                               6478                 :                :     {
                               6479                 :            180 :         SetOperationStmt *op = (SetOperationStmt *) setOp;
                               6480                 :                :         int         subindent;
                               6481                 :                :         bool        save_colnamesvisible;
                               6482                 :                : 
                               6483                 :                :         /*
                               6484                 :                :          * We force parens when nesting two SetOperationStmts, except when the
                               6485                 :                :          * lefthand input is another setop of the same kind.  Syntactically,
                               6486                 :                :          * we could omit parens in rather more cases, but it seems best to use
                               6487                 :                :          * parens to flag cases where the setop operator changes.  If we use
                               6488                 :                :          * parens, we also increase the indentation level for the child query.
                               6489                 :                :          *
                               6490                 :                :          * There are some cases in which parens are needed around a leaf query
                               6491                 :                :          * too, but those are more easily handled at the next level down (see
                               6492                 :                :          * code above).
                               6493                 :                :          */
 4595                          6494         [ +  + ]:            180 :         if (IsA(op->larg, SetOperationStmt))
                               6495                 :                :         {
                               6496                 :             77 :             SetOperationStmt *lop = (SetOperationStmt *) op->larg;
                               6497                 :                : 
                               6498   [ +  -  +  - ]:             77 :             if (op->op == lop->op && op->all == lop->all)
                               6499                 :             77 :                 need_paren = false;
                               6500                 :                :             else
 4595 tgl@sss.pgh.pa.us        6501                 :UBC           0 :                 need_paren = true;
                               6502                 :                :         }
                               6503                 :                :         else
 4595 tgl@sss.pgh.pa.us        6504                 :CBC         103 :             need_paren = false;
                               6505                 :                : 
 8180                          6506         [ -  + ]:            180 :         if (need_paren)
                               6507                 :                :         {
 8180 tgl@sss.pgh.pa.us        6508                 :UBC           0 :             appendStringInfoChar(buf, '(');
 4595                          6509                 :              0 :             subindent = PRETTYINDENT_STD;
                               6510                 :              0 :             appendContextKeyword(context, "", subindent, 0, 0);
                               6511                 :                :         }
                               6512                 :                :         else
 4595 tgl@sss.pgh.pa.us        6513                 :CBC         180 :             subindent = 0;
                               6514                 :                : 
  821                          6515                 :            180 :         get_setop_query(op->larg, query, context);
                               6516                 :                : 
 4595                          6517         [ -  + ]:            180 :         if (need_paren)
 4595 tgl@sss.pgh.pa.us        6518                 :UBC           0 :             appendContextKeyword(context, ") ", -subindent, 0, 0);
 4595 tgl@sss.pgh.pa.us        6519         [ +  - ]:CBC         180 :         else if (PRETTY_INDENT(context))
                               6520                 :            180 :             appendContextKeyword(context, "", -subindent, 0, 0);
                               6521                 :                :         else
 8517 bruce@momjian.us         6522                 :UBC           0 :             appendStringInfoChar(buf, ' ');
                               6523                 :                : 
 9550 tgl@sss.pgh.pa.us        6524   [ +  -  -  - ]:CBC         180 :         switch (op->op)
                               6525                 :                :         {
                               6526                 :            180 :             case SETOP_UNION:
 4595                          6527                 :            180 :                 appendStringInfoString(buf, "UNION ");
 9550                          6528                 :            180 :                 break;
 9550 tgl@sss.pgh.pa.us        6529                 :UBC           0 :             case SETOP_INTERSECT:
 4595                          6530                 :              0 :                 appendStringInfoString(buf, "INTERSECT ");
 9550                          6531                 :              0 :                 break;
                               6532                 :              0 :             case SETOP_EXCEPT:
 4595                          6533                 :              0 :                 appendStringInfoString(buf, "EXCEPT ");
 9550                          6534                 :              0 :                 break;
                               6535                 :              0 :             default:
 8525                          6536         [ #  # ]:              0 :                 elog(ERROR, "unrecognized set op: %d",
                               6537                 :                :                      (int) op->op);
                               6538                 :                :         }
 9550 tgl@sss.pgh.pa.us        6539         [ +  + ]:CBC         180 :         if (op->all)
 4776 rhaas@postgresql.org     6540                 :            172 :             appendStringInfoString(buf, "ALL ");
                               6541                 :                : 
                               6542                 :                :         /* Always parenthesize if RHS is another setop */
 4595 tgl@sss.pgh.pa.us        6543                 :            180 :         need_paren = IsA(op->rarg, SetOperationStmt);
                               6544                 :                : 
                               6545                 :                :         /*
                               6546                 :                :          * The indentation code here is deliberately a bit different from that
                               6547                 :                :          * for the lefthand input, because we want the line breaks in
                               6548                 :                :          * different places.
                               6549                 :                :          */
 8180                          6550         [ -  + ]:            180 :         if (need_paren)
                               6551                 :                :         {
 8180 tgl@sss.pgh.pa.us        6552                 :UBC           0 :             appendStringInfoChar(buf, '(');
 4595                          6553                 :              0 :             subindent = PRETTYINDENT_STD;
                               6554                 :                :         }
                               6555                 :                :         else
 4595 tgl@sss.pgh.pa.us        6556                 :CBC         180 :             subindent = 0;
                               6557                 :            180 :         appendContextKeyword(context, "", subindent, 0, 0);
                               6558                 :                : 
                               6559                 :                :         /*
                               6560                 :                :          * The output column names of the RHS sub-select don't matter.
                               6561                 :                :          */
  821                          6562                 :            180 :         save_colnamesvisible = context->colNamesVisible;
                               6563                 :            180 :         context->colNamesVisible = false;
                               6564                 :                : 
                               6565                 :            180 :         get_setop_query(op->rarg, query, context);
                               6566                 :                : 
                               6567                 :            180 :         context->colNamesVisible = save_colnamesvisible;
                               6568                 :                : 
 6629                          6569         [ +  - ]:            180 :         if (PRETTY_INDENT(context))
 4595                          6570                 :            180 :             context->indentLevel -= subindent;
                               6571         [ -  + ]:            180 :         if (need_paren)
 4595 tgl@sss.pgh.pa.us        6572                 :UBC           0 :             appendContextKeyword(context, ")", 0, 0, 0);
                               6573                 :                :     }
                               6574                 :                :     else
                               6575                 :                :     {
 8525                          6576         [ #  # ]:              0 :         elog(ERROR, "unrecognized node type: %d",
                               6577                 :                :              (int) nodeTag(setOp));
                               6578                 :                :     }
 9550 tgl@sss.pgh.pa.us        6579                 :CBC         463 : }
                               6580                 :                : 
                               6581                 :                : /*
                               6582                 :                :  * Display a sort/group clause.
                               6583                 :                :  *
                               6584                 :                :  * Also returns the expression tree, so caller need not find it again.
                               6585                 :                :  */
                               6586                 :                : static Node *
 4214 andres@anarazel.de       6587                 :            448 : get_rule_sortgroupclause(Index ref, List *tlist, bool force_colno,
                               6588                 :                :                          deparse_context *context)
                               6589                 :                : {
 9358 tgl@sss.pgh.pa.us        6590                 :            448 :     StringInfo  buf = context->buf;
                               6591                 :                :     TargetEntry *tle;
                               6592                 :                :     Node       *expr;
                               6593                 :                : 
 4214 andres@anarazel.de       6594                 :            448 :     tle = get_sortgroupref_tle(ref, tlist);
 8752 tgl@sss.pgh.pa.us        6595                 :            448 :     expr = (Node *) tle->expr;
                               6596                 :                : 
                               6597                 :                :     /*
                               6598                 :                :      * Use column-number form if requested by caller.  Otherwise, if
                               6599                 :                :      * expression is a constant, force it to be dumped with an explicit cast
                               6600                 :                :      * as decoration --- this is because a simple integer constant is
                               6601                 :                :      * ambiguous (and will be misinterpreted by findTargetlistEntrySQL92()) if
                               6602                 :                :      * we dump it without any decoration.  Similarly, if it's just a Var,
                               6603                 :                :      * there is risk of misinterpretation if the column name is reassigned in
                               6604                 :                :      * the SELECT list, so we may need to force table qualification.  And, if
                               6605                 :                :      * it's anything more complex than a simple Var, then force extra parens
                               6606                 :                :      * around it, to ensure it can't be misinterpreted as a cube() or rollup()
                               6607                 :                :      * construct.
                               6608                 :                :      */
 6901                          6609         [ +  + ]:            448 :     if (force_colno)
                               6610                 :                :     {
 7906                          6611         [ -  + ]:              7 :         Assert(!tle->resjunk);
                               6612                 :              7 :         appendStringInfo(buf, "%d", tle->resno);
                               6613                 :                :     }
  821                          6614         [ +  - ]:            441 :     else if (!expr)
                               6615                 :                :          /* do nothing, probably can't happen */ ;
                               6616         [ -  + ]:            441 :     else if (IsA(expr, Const))
 6901 tgl@sss.pgh.pa.us        6617                 :UBC           0 :         get_const_expr((Const *) expr, context, 1);
  821 tgl@sss.pgh.pa.us        6618         [ +  + ]:CBC         441 :     else if (IsA(expr, Var))
                               6619                 :                :     {
                               6620                 :                :         /* Tell get_variable to check for name conflict */
                               6621                 :            424 :         bool        save_varinorderby = context->varInOrderBy;
                               6622                 :                : 
                               6623                 :            424 :         context->varInOrderBy = true;
                               6624                 :            424 :         (void) get_variable((Var *) expr, 0, false, context);
                               6625                 :            424 :         context->varInOrderBy = save_varinorderby;
                               6626                 :                :     }
                               6627                 :                :     else
                               6628                 :                :     {
                               6629                 :                :         /*
                               6630                 :                :          * We must force parens for function-like expressions even if
                               6631                 :                :          * PRETTY_PAREN is off, since those are the ones in danger of
                               6632                 :                :          * misparsing. For other expressions we need to force them only if
                               6633                 :                :          * PRETTY_PAREN is on, since otherwise the expression will output them
                               6634                 :                :          * itself. (We can't skip the parens.)
                               6635                 :                :          */
 4207 bruce@momjian.us         6636                 :             34 :         bool        need_paren = (PRETTY_PAREN(context)
                               6637         [ +  + ]:             17 :                                   || IsA(expr, FuncExpr)
 2387 tgl@sss.pgh.pa.us        6638         [ +  - ]:             15 :                                   || IsA(expr, Aggref)
 1340 alvherre@alvh.no-ip.     6639         [ +  - ]:             15 :                                   || IsA(expr, WindowFunc)
                               6640   [ +  -  -  + ]:             34 :                                   || IsA(expr, JsonConstructorExpr));
                               6641                 :                : 
 4214 andres@anarazel.de       6642         [ +  + ]:             17 :         if (need_paren)
 3392 peter_e@gmx.net          6643                 :              2 :             appendStringInfoChar(context->buf, '(');
 8836 tgl@sss.pgh.pa.us        6644                 :             17 :         get_rule_expr(expr, context, true);
 4214 andres@anarazel.de       6645         [ +  + ]:             17 :         if (need_paren)
 3392 peter_e@gmx.net          6646                 :              2 :             appendStringInfoChar(context->buf, ')');
                               6647                 :                :     }
                               6648                 :                : 
 8975 tgl@sss.pgh.pa.us        6649                 :            448 :     return expr;
                               6650                 :                : }
                               6651                 :                : 
                               6652                 :                : /*
                               6653                 :                :  * Display a GroupingSet
                               6654                 :                :  */
                               6655                 :                : static void
 4214 andres@anarazel.de       6656                 :             12 : get_rule_groupingset(GroupingSet *gset, List *targetlist,
                               6657                 :                :                      bool omit_parens, deparse_context *context)
                               6658                 :                : {
                               6659                 :                :     ListCell   *l;
                               6660                 :             12 :     StringInfo  buf = context->buf;
                               6661                 :             12 :     bool        omit_child_parens = true;
                               6662                 :             12 :     char       *sep = "";
                               6663                 :                : 
                               6664   [ -  +  +  -  :             12 :     switch (gset->kind)
                                              -  - ]
                               6665                 :                :     {
 4214 andres@anarazel.de       6666                 :UBC           0 :         case GROUPING_SET_EMPTY:
                               6667                 :              0 :             appendStringInfoString(buf, "()");
                               6668                 :              0 :             return;
                               6669                 :                : 
 4214 andres@anarazel.de       6670                 :CBC           8 :         case GROUPING_SET_SIMPLE:
                               6671                 :                :             {
                               6672   [ +  -  +  - ]:              8 :                 if (!omit_parens || list_length(gset->content) != 1)
 3392 peter_e@gmx.net          6673                 :              8 :                     appendStringInfoChar(buf, '(');
                               6674                 :                : 
 4214 andres@anarazel.de       6675   [ +  -  +  +  :             28 :                 foreach(l, gset->content)
                                              +  + ]
                               6676                 :                :                 {
 4207 bruce@momjian.us         6677                 :             20 :                     Index       ref = lfirst_int(l);
                               6678                 :                : 
 4214 andres@anarazel.de       6679                 :             20 :                     appendStringInfoString(buf, sep);
                               6680                 :             20 :                     get_rule_sortgroupclause(ref, targetlist,
                               6681                 :                :                                              false, context);
                               6682                 :             20 :                     sep = ", ";
                               6683                 :                :                 }
                               6684                 :                : 
                               6685   [ +  -  +  - ]:              8 :                 if (!omit_parens || list_length(gset->content) != 1)
 3392 peter_e@gmx.net          6686                 :              8 :                     appendStringInfoChar(buf, ')');
                               6687                 :                :             }
 4214 andres@anarazel.de       6688                 :              8 :             return;
                               6689                 :                : 
                               6690                 :              4 :         case GROUPING_SET_ROLLUP:
                               6691                 :              4 :             appendStringInfoString(buf, "ROLLUP(");
                               6692                 :              4 :             break;
 4214 andres@anarazel.de       6693                 :UBC           0 :         case GROUPING_SET_CUBE:
                               6694                 :              0 :             appendStringInfoString(buf, "CUBE(");
                               6695                 :              0 :             break;
                               6696                 :              0 :         case GROUPING_SET_SETS:
                               6697                 :              0 :             appendStringInfoString(buf, "GROUPING SETS (");
                               6698                 :              0 :             omit_child_parens = false;
                               6699                 :              0 :             break;
                               6700                 :                :     }
                               6701                 :                : 
 4214 andres@anarazel.de       6702   [ +  -  +  +  :CBC          12 :     foreach(l, gset->content)
                                              +  + ]
                               6703                 :                :     {
                               6704                 :              8 :         appendStringInfoString(buf, sep);
                               6705                 :              8 :         get_rule_groupingset(lfirst(l), targetlist, omit_child_parens, context);
                               6706                 :              8 :         sep = ", ";
                               6707                 :                :     }
                               6708                 :                : 
 3392 peter_e@gmx.net          6709                 :              4 :     appendStringInfoChar(buf, ')');
                               6710                 :                : }
                               6711                 :                : 
                               6712                 :                : /*
                               6713                 :                :  * Display an ORDER BY list.
                               6714                 :                :  */
                               6715                 :                : static void
 6544 tgl@sss.pgh.pa.us        6716                 :            246 : get_rule_orderby(List *orderList, List *targetList,
                               6717                 :                :                  bool force_colno, deparse_context *context)
                               6718                 :                : {
                               6719                 :            246 :     StringInfo  buf = context->buf;
                               6720                 :                :     const char *sep;
                               6721                 :                :     ListCell   *l;
                               6722                 :                : 
                               6723                 :            246 :     sep = "";
                               6724   [ +  -  +  +  :            513 :     foreach(l, orderList)
                                              +  + ]
                               6725                 :                :     {
                               6726                 :            267 :         SortGroupClause *srt = (SortGroupClause *) lfirst(l);
                               6727                 :                :         Node       *sortexpr;
                               6728                 :                :         Oid         sortcoltype;
                               6729                 :                :         TypeCacheEntry *typentry;
                               6730                 :                : 
                               6731                 :            267 :         appendStringInfoString(buf, sep);
 4214 andres@anarazel.de       6732                 :            267 :         sortexpr = get_rule_sortgroupclause(srt->tleSortGroupRef, targetList,
                               6733                 :                :                                             force_colno, context);
 6544 tgl@sss.pgh.pa.us        6734                 :            267 :         sortcoltype = exprType(sortexpr);
                               6735                 :                :         /* See whether operator is default < or > for datatype */
                               6736                 :            267 :         typentry = lookup_type_cache(sortcoltype,
                               6737                 :                :                                      TYPECACHE_LT_OPR | TYPECACHE_GT_OPR);
                               6738         [ +  + ]:            267 :         if (srt->sortop == typentry->lt_opr)
                               6739                 :                :         {
                               6740                 :                :             /* ASC is default, so emit nothing for it */
                               6741         [ -  + ]:            250 :             if (srt->nulls_first)
 4776 rhaas@postgresql.org     6742                 :UBC           0 :                 appendStringInfoString(buf, " NULLS FIRST");
                               6743                 :                :         }
 6544 tgl@sss.pgh.pa.us        6744         [ +  + ]:CBC          17 :         else if (srt->sortop == typentry->gt_opr)
                               6745                 :                :         {
 4776 rhaas@postgresql.org     6746                 :              6 :             appendStringInfoString(buf, " DESC");
                               6747                 :                :             /* DESC defaults to NULLS FIRST */
 6544 tgl@sss.pgh.pa.us        6748         [ +  + ]:              6 :             if (!srt->nulls_first)
 4776 rhaas@postgresql.org     6749                 :              1 :                 appendStringInfoString(buf, " NULLS LAST");
                               6750                 :                :         }
                               6751                 :                :         else
                               6752                 :                :         {
 6544 tgl@sss.pgh.pa.us        6753                 :             11 :             appendStringInfo(buf, " USING %s",
                               6754                 :                :                              generate_operator_name(srt->sortop,
                               6755                 :                :                                                     sortcoltype,
                               6756                 :                :                                                     sortcoltype));
                               6757                 :                :             /* be specific to eliminate ambiguity */
                               6758         [ -  + ]:             11 :             if (srt->nulls_first)
 4776 rhaas@postgresql.org     6759                 :UBC           0 :                 appendStringInfoString(buf, " NULLS FIRST");
                               6760                 :                :             else
 4776 rhaas@postgresql.org     6761                 :CBC          11 :                 appendStringInfoString(buf, " NULLS LAST");
                               6762                 :                :         }
 6544 tgl@sss.pgh.pa.us        6763                 :            267 :         sep = ", ";
                               6764                 :                :     }
                               6765                 :            246 : }
                               6766                 :                : 
                               6767                 :                : /*
                               6768                 :                :  * Display a WINDOW clause.
                               6769                 :                :  *
                               6770                 :                :  * Note that the windowClause list might contain only anonymous window
                               6771                 :                :  * specifications, in which case we should print nothing here.
                               6772                 :                :  */
                               6773                 :                : static void
                               6774                 :             32 : get_rule_windowclause(Query *query, deparse_context *context)
                               6775                 :                : {
                               6776                 :             32 :     StringInfo  buf = context->buf;
                               6777                 :                :     const char *sep;
                               6778                 :                :     ListCell   *l;
                               6779                 :                : 
                               6780                 :             32 :     sep = NULL;
                               6781   [ +  -  +  +  :             64 :     foreach(l, query->windowClause)
                                              +  + ]
                               6782                 :                :     {
                               6783                 :             32 :         WindowClause *wc = (WindowClause *) lfirst(l);
                               6784                 :                : 
                               6785         [ +  + ]:             32 :         if (wc->name == NULL)
                               6786                 :             28 :             continue;           /* ignore anonymous windows */
                               6787                 :                : 
                               6788         [ +  - ]:              4 :         if (sep == NULL)
                               6789                 :              4 :             appendContextKeyword(context, " WINDOW ",
                               6790                 :                :                                  -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
                               6791                 :                :         else
 6544 tgl@sss.pgh.pa.us        6792                 :UBC           0 :             appendStringInfoString(buf, sep);
                               6793                 :                : 
 6544 tgl@sss.pgh.pa.us        6794                 :CBC           4 :         appendStringInfo(buf, "%s AS ", quote_identifier(wc->name));
                               6795                 :                : 
                               6796                 :              4 :         get_rule_windowspec(wc, query->targetList, context);
                               6797                 :                : 
                               6798                 :              4 :         sep = ", ";
                               6799                 :                :     }
                               6800                 :             32 : }
                               6801                 :                : 
                               6802                 :                : /*
                               6803                 :                :  * Display a window definition
                               6804                 :                :  */
                               6805                 :                : static void
                               6806                 :             32 : get_rule_windowspec(WindowClause *wc, List *targetList,
                               6807                 :                :                     deparse_context *context)
                               6808                 :                : {
                               6809                 :             32 :     StringInfo  buf = context->buf;
                               6810                 :             32 :     bool        needspace = false;
                               6811                 :                :     const char *sep;
                               6812                 :                :     ListCell   *l;
                               6813                 :                : 
                               6814                 :             32 :     appendStringInfoChar(buf, '(');
                               6815         [ -  + ]:             32 :     if (wc->refname)
                               6816                 :                :     {
 6544 tgl@sss.pgh.pa.us        6817                 :UBC           0 :         appendStringInfoString(buf, quote_identifier(wc->refname));
                               6818                 :              0 :         needspace = true;
                               6819                 :                :     }
                               6820                 :                :     /* partition clauses are always inherited, so only print if no refname */
 6544 tgl@sss.pgh.pa.us        6821   [ -  +  -  - ]:CBC          32 :     if (wc->partitionClause && !wc->refname)
                               6822                 :                :     {
 6544 tgl@sss.pgh.pa.us        6823         [ #  # ]:UBC           0 :         if (needspace)
                               6824                 :              0 :             appendStringInfoChar(buf, ' ');
                               6825                 :              0 :         appendStringInfoString(buf, "PARTITION BY ");
                               6826                 :              0 :         sep = "";
                               6827   [ #  #  #  #  :              0 :         foreach(l, wc->partitionClause)
                                              #  # ]
                               6828                 :                :         {
                               6829                 :              0 :             SortGroupClause *grp = (SortGroupClause *) lfirst(l);
                               6830                 :                : 
                               6831                 :              0 :             appendStringInfoString(buf, sep);
 4214 andres@anarazel.de       6832                 :              0 :             get_rule_sortgroupclause(grp->tleSortGroupRef, targetList,
                               6833                 :                :                                      false, context);
 6544 tgl@sss.pgh.pa.us        6834                 :              0 :             sep = ", ";
                               6835                 :                :         }
                               6836                 :              0 :         needspace = true;
                               6837                 :                :     }
                               6838                 :                :     /* print ordering clause only if not inherited */
 6544 tgl@sss.pgh.pa.us        6839   [ +  -  +  - ]:CBC          32 :     if (wc->orderClause && !wc->copiedOrder)
                               6840                 :                :     {
                               6841         [ -  + ]:             32 :         if (needspace)
 6544 tgl@sss.pgh.pa.us        6842                 :UBC           0 :             appendStringInfoChar(buf, ' ');
 6544 tgl@sss.pgh.pa.us        6843                 :CBC          32 :         appendStringInfoString(buf, "ORDER BY ");
                               6844                 :             32 :         get_rule_orderby(wc->orderClause, targetList, false, context);
                               6845                 :             32 :         needspace = true;
                               6846                 :                :     }
                               6847                 :                :     /* framing clause is never inherited, so print unless it's default */
 6541                          6848         [ +  + ]:             32 :     if (wc->frameOptions & FRAMEOPTION_NONDEFAULT)
                               6849                 :                :     {
                               6850         [ +  - ]:             28 :         if (needspace)
                               6851                 :             28 :             appendStringInfoChar(buf, ' ');
  627                          6852                 :             28 :         get_window_frame_options(wc->frameOptions,
                               6853                 :                :                                  wc->startOffset, wc->endOffset,
                               6854                 :                :                                  context);
                               6855                 :                :     }
                               6856                 :             32 :     appendStringInfoChar(buf, ')');
                               6857                 :             32 : }
                               6858                 :                : 
                               6859                 :                : /*
                               6860                 :                :  * Append the description of a window's framing options to context->buf
                               6861                 :                :  */
                               6862                 :                : static void
                               6863                 :            218 : get_window_frame_options(int frameOptions,
                               6864                 :                :                          Node *startOffset, Node *endOffset,
                               6865                 :                :                          deparse_context *context)
                               6866                 :                : {
                               6867                 :            218 :     StringInfo  buf = context->buf;
                               6868                 :                : 
                               6869         [ +  - ]:            218 :     if (frameOptions & FRAMEOPTION_NONDEFAULT)
                               6870                 :                :     {
                               6871         [ +  + ]:            218 :         if (frameOptions & FRAMEOPTION_RANGE)
 6541                          6872                 :             29 :             appendStringInfoString(buf, "RANGE ");
  627                          6873         [ +  + ]:            189 :         else if (frameOptions & FRAMEOPTION_ROWS)
 6541                          6874                 :            169 :             appendStringInfoString(buf, "ROWS ");
  627                          6875         [ +  - ]:             20 :         else if (frameOptions & FRAMEOPTION_GROUPS)
 3216                          6876                 :             20 :             appendStringInfoString(buf, "GROUPS ");
                               6877                 :                :         else
 6541 tgl@sss.pgh.pa.us        6878                 :UBC           0 :             Assert(false);
  627 tgl@sss.pgh.pa.us        6879         [ +  + ]:CBC         218 :         if (frameOptions & FRAMEOPTION_BETWEEN)
 6541                          6880                 :            113 :             appendStringInfoString(buf, "BETWEEN ");
  627                          6881         [ +  + ]:            218 :         if (frameOptions & FRAMEOPTION_START_UNBOUNDED_PRECEDING)
 6541                          6882                 :            145 :             appendStringInfoString(buf, "UNBOUNDED PRECEDING ");
  627                          6883         [ +  + ]:             73 :         else if (frameOptions & FRAMEOPTION_START_CURRENT_ROW)
 6541                          6884                 :             33 :             appendStringInfoString(buf, "CURRENT ROW ");
  627                          6885         [ +  - ]:             40 :         else if (frameOptions & FRAMEOPTION_START_OFFSET)
                               6886                 :                :         {
                               6887                 :             40 :             get_rule_expr(startOffset, context, false);
                               6888         [ +  - ]:             40 :             if (frameOptions & FRAMEOPTION_START_OFFSET_PRECEDING)
 6133                          6889                 :             40 :                 appendStringInfoString(buf, " PRECEDING ");
  627 tgl@sss.pgh.pa.us        6890         [ #  # ]:UBC           0 :             else if (frameOptions & FRAMEOPTION_START_OFFSET_FOLLOWING)
 6133                          6891                 :              0 :                 appendStringInfoString(buf, " FOLLOWING ");
                               6892                 :                :             else
                               6893                 :              0 :                 Assert(false);
                               6894                 :                :         }
                               6895                 :                :         else
 6541                          6896                 :              0 :             Assert(false);
  627 tgl@sss.pgh.pa.us        6897         [ +  + ]:CBC         218 :         if (frameOptions & FRAMEOPTION_BETWEEN)
                               6898                 :                :         {
 6541                          6899                 :            113 :             appendStringInfoString(buf, "AND ");
  627                          6900         [ +  + ]:            113 :             if (frameOptions & FRAMEOPTION_END_UNBOUNDED_FOLLOWING)
 6541                          6901                 :             13 :                 appendStringInfoString(buf, "UNBOUNDED FOLLOWING ");
  627                          6902         [ +  + ]:            100 :             else if (frameOptions & FRAMEOPTION_END_CURRENT_ROW)
 6541                          6903                 :             28 :                 appendStringInfoString(buf, "CURRENT ROW ");
  627                          6904         [ +  - ]:             72 :             else if (frameOptions & FRAMEOPTION_END_OFFSET)
                               6905                 :                :             {
                               6906                 :             72 :                 get_rule_expr(endOffset, context, false);
                               6907         [ +  + ]:             72 :                 if (frameOptions & FRAMEOPTION_END_OFFSET_PRECEDING)
 6133                          6908                 :             28 :                     appendStringInfoString(buf, " PRECEDING ");
  627                          6909         [ +  - ]:             44 :                 else if (frameOptions & FRAMEOPTION_END_OFFSET_FOLLOWING)
 6133                          6910                 :             44 :                     appendStringInfoString(buf, " FOLLOWING ");
                               6911                 :                :                 else
 6133 tgl@sss.pgh.pa.us        6912                 :UBC           0 :                     Assert(false);
                               6913                 :                :             }
                               6914                 :                :             else
 6541                          6915                 :              0 :                 Assert(false);
                               6916                 :                :         }
  627 tgl@sss.pgh.pa.us        6917         [ +  + ]:CBC         218 :         if (frameOptions & FRAMEOPTION_EXCLUDE_CURRENT_ROW)
 3216                          6918                 :             24 :             appendStringInfoString(buf, "EXCLUDE CURRENT ROW ");
  627                          6919         [ +  + ]:            194 :         else if (frameOptions & FRAMEOPTION_EXCLUDE_GROUP)
 3216                          6920                 :             12 :             appendStringInfoString(buf, "EXCLUDE GROUP ");
  627                          6921         [ +  + ]:            182 :         else if (frameOptions & FRAMEOPTION_EXCLUDE_TIES)
 3216                          6922                 :             12 :             appendStringInfoString(buf, "EXCLUDE TIES ");
                               6923                 :                :         /* we will now have a trailing space; remove it */
  627                          6924                 :            218 :         buf->data[--(buf->len)] = '\0';
                               6925                 :                :     }
                               6926                 :            218 : }
                               6927                 :                : 
                               6928                 :                : /*
                               6929                 :                :  * Return the description of a window's framing options as a palloc'd string
                               6930                 :                :  */
                               6931                 :                : char *
                               6932                 :            190 : get_window_frame_options_for_explain(int frameOptions,
                               6933                 :                :                                      Node *startOffset, Node *endOffset,
                               6934                 :                :                                      List *dpcontext, bool forceprefix)
                               6935                 :                : {
                               6936                 :                :     StringInfoData buf;
                               6937                 :                :     deparse_context context;
                               6938                 :                : 
                               6939                 :            190 :     initStringInfo(&buf);
                               6940                 :            190 :     context.buf = &buf;
                               6941                 :            190 :     context.namespaces = dpcontext;
                               6942                 :            190 :     context.resultDesc = NULL;
                               6943                 :            190 :     context.targetList = NIL;
                               6944                 :            190 :     context.windowClause = NIL;
                               6945                 :            190 :     context.varprefix = forceprefix;
                               6946                 :            190 :     context.prettyFlags = 0;
                               6947                 :            190 :     context.wrapColumn = WRAP_COLUMN_DEFAULT;
                               6948                 :            190 :     context.indentLevel = 0;
                               6949                 :            190 :     context.colNamesVisible = true;
                               6950                 :            190 :     context.inGroupBy = false;
                               6951                 :            190 :     context.varInOrderBy = false;
                               6952                 :            190 :     context.appendparents = NULL;
                               6953                 :                : 
                               6954                 :            190 :     get_window_frame_options(frameOptions, startOffset, endOffset, &context);
                               6955                 :                : 
                               6956                 :            190 :     return buf.data;
                               6957                 :                : }
                               6958                 :                : 
                               6959                 :                : /* ----------
                               6960                 :                :  * get_insert_query_def         - Parse back an INSERT parsetree
                               6961                 :                :  * ----------
                               6962                 :                :  */
                               6963                 :                : static void
  821                          6964                 :            194 : get_insert_query_def(Query *query, deparse_context *context)
                               6965                 :                : {
 9918                          6966                 :            194 :     StringInfo  buf = context->buf;
 9550                          6967                 :            194 :     RangeTblEntry *select_rte = NULL;
 7423 mail@joeconway.com       6968                 :            194 :     RangeTblEntry *values_rte = NULL;
                               6969                 :                :     RangeTblEntry *rte;
                               6970                 :                :     char       *sep;
                               6971                 :                :     ListCell   *l;
                               6972                 :                :     List       *strippedexprs;
                               6973                 :                : 
                               6974                 :                :     /* Insert the WITH clause if given */
 5888 tgl@sss.pgh.pa.us        6975                 :            194 :     get_with_clause(query, context);
                               6976                 :                : 
                               6977                 :                :     /*
                               6978                 :                :      * If it's an INSERT ... SELECT or multi-row VALUES, there will be a
                               6979                 :                :      * single RTE for the SELECT or VALUES.  Plain VALUES has neither.
                               6980                 :                :      */
10315 bruce@momjian.us         6981   [ +  -  +  +  :            758 :     foreach(l, query->rtable)
                                              +  + ]
                               6982                 :                :     {
                               6983                 :            564 :         rte = (RangeTblEntry *) lfirst(l);
                               6984                 :                : 
 7423 mail@joeconway.com       6985         [ +  + ]:            564 :         if (rte->rtekind == RTE_SUBQUERY)
                               6986                 :                :         {
                               6987         [ -  + ]:             30 :             if (select_rte)
 7423 mail@joeconway.com       6988         [ #  # ]:UBC           0 :                 elog(ERROR, "too many subquery RTEs in INSERT");
 7423 mail@joeconway.com       6989                 :CBC          30 :             select_rte = rte;
                               6990                 :                :         }
                               6991                 :                : 
                               6992         [ +  + ]:            564 :         if (rte->rtekind == RTE_VALUES)
                               6993                 :                :         {
                               6994         [ -  + ]:             26 :             if (values_rte)
 7423 mail@joeconway.com       6995         [ #  # ]:UBC           0 :                 elog(ERROR, "too many values RTEs in INSERT");
 7423 mail@joeconway.com       6996                 :CBC          26 :             values_rte = rte;
                               6997                 :                :         }
                               6998                 :                :     }
                               6999   [ +  +  -  + ]:            194 :     if (select_rte && values_rte)
 7423 mail@joeconway.com       7000         [ #  # ]:UBC           0 :         elog(ERROR, "both subquery and values RTEs in INSERT");
                               7001                 :                : 
                               7002                 :                :     /*
                               7003                 :                :      * Start the query with INSERT INTO relname
                               7004                 :                :      */
 9890 tgl@sss.pgh.pa.us        7005                 :CBC         194 :     rte = rt_fetch(query->resultRelation, query->rtable);
 8975                          7006         [ -  + ]:            194 :     Assert(rte->rtekind == RTE_RELATION);
                               7007                 :                : 
 8522                          7008         [ +  - ]:            194 :     if (PRETTY_INDENT(context))
                               7009                 :                :     {
 8517 bruce@momjian.us         7010                 :            194 :         context->indentLevel += PRETTYINDENT_STD;
                               7011                 :            194 :         appendStringInfoChar(buf, ' ');
                               7012                 :                :     }
 1380 tgl@sss.pgh.pa.us        7013                 :            194 :     appendStringInfo(buf, "INSERT INTO %s",
                               7014                 :                :                      generate_relation_name(rte->relid, NIL));
                               7015                 :                : 
                               7016                 :                :     /* Print the relation alias, if needed; INSERT requires explicit AS */
                               7017                 :            194 :     get_rte_alias(rte, query->resultRelation, true, context);
                               7018                 :                : 
                               7019                 :                :     /* always want a space here */
                               7020                 :            194 :     appendStringInfoChar(buf, ' ');
                               7021                 :                : 
                               7022                 :                :     /*
                               7023                 :                :      * Add the insert-column-names list.  Any indirection decoration needed on
                               7024                 :                :      * the column names can be inferred from the top targetlist.
                               7025                 :                :      */
 8207                          7026                 :            194 :     strippedexprs = NIL;
                               7027                 :            194 :     sep = "";
 5153                          7028         [ +  - ]:            194 :     if (query->targetList)
                               7029                 :            194 :         appendStringInfoChar(buf, '(');
10315 bruce@momjian.us         7030   [ +  -  +  +  :            695 :     foreach(l, query->targetList)
                                              +  + ]
                               7031                 :                :     {
 9573 tgl@sss.pgh.pa.us        7032                 :            501 :         TargetEntry *tle = (TargetEntry *) lfirst(l);
                               7033                 :                : 
 7906                          7034         [ -  + ]:            501 :         if (tle->resjunk)
 9556 tgl@sss.pgh.pa.us        7035                 :UBC           0 :             continue;           /* ignore junk entries */
                               7036                 :                : 
 7882 neilc@samurai.com        7037                 :CBC         501 :         appendStringInfoString(buf, sep);
10315 bruce@momjian.us         7038                 :            501 :         sep = ", ";
                               7039                 :                : 
                               7040                 :                :         /*
                               7041                 :                :          * Put out name of target column; look in the catalogs, not at
                               7042                 :                :          * tle->resname, since resname will fail to track RENAME.
                               7043                 :                :          */
 8337 neilc@samurai.com        7044                 :            501 :         appendStringInfoString(buf,
 3211 alvherre@alvh.no-ip.     7045                 :            501 :                                quote_identifier(get_attname(rte->relid,
                               7046                 :            501 :                                                             tle->resno,
                               7047                 :                :                                                             false)));
                               7048                 :                : 
                               7049                 :                :         /*
                               7050                 :                :          * Print any indirection needed (subfields or subscripts), and strip
                               7051                 :                :          * off the top-level nodes representing the indirection assignments.
                               7052                 :                :          * Add the stripped expressions to strippedexprs.  (If it's a
                               7053                 :                :          * single-VALUES statement, the stripped expressions are the VALUES to
                               7054                 :                :          * print below.  Otherwise they're just Vars and not really
                               7055                 :                :          * interesting.)
                               7056                 :                :          */
 3769 tgl@sss.pgh.pa.us        7057                 :            501 :         strippedexprs = lappend(strippedexprs,
                               7058                 :            501 :                                 processIndirection((Node *) tle->expr,
                               7059                 :                :                                                    context));
                               7060                 :                :     }
 5153                          7061         [ +  - ]:            194 :     if (query->targetList)
 4776 rhaas@postgresql.org     7062                 :            194 :         appendStringInfoString(buf, ") ");
                               7063                 :                : 
 3523 peter_e@gmx.net          7064         [ -  + ]:            194 :     if (query->override)
                               7065                 :                :     {
 3523 peter_e@gmx.net          7066         [ #  # ]:UBC           0 :         if (query->override == OVERRIDING_SYSTEM_VALUE)
                               7067                 :              0 :             appendStringInfoString(buf, "OVERRIDING SYSTEM VALUE ");
                               7068         [ #  # ]:              0 :         else if (query->override == OVERRIDING_USER_VALUE)
                               7069                 :              0 :             appendStringInfoString(buf, "OVERRIDING USER VALUE ");
                               7070                 :                :     }
                               7071                 :                : 
 7423 mail@joeconway.com       7072         [ +  + ]:CBC         194 :     if (select_rte)
                               7073                 :                :     {
                               7074                 :                :         /* Add the SELECT */
 1837 tgl@sss.pgh.pa.us        7075                 :             30 :         get_query_def(select_rte->subquery, buf, context->namespaces, NULL,
                               7076                 :                :                       false,
                               7077                 :                :                       context->prettyFlags, context->wrapColumn,
                               7078                 :                :                       context->indentLevel);
                               7079                 :                :     }
 7423 mail@joeconway.com       7080         [ +  + ]:            164 :     else if (values_rte)
                               7081                 :                :     {
                               7082                 :                :         /* Add the multi-VALUES expression lists */
                               7083                 :             26 :         get_values_def(values_rte->values_lists, context);
                               7084                 :                :     }
 5153 tgl@sss.pgh.pa.us        7085         [ +  - ]:            138 :     else if (strippedexprs)
                               7086                 :                :     {
                               7087                 :                :         /* Add the single-VALUES expression list */
 8522                          7088                 :            138 :         appendContextKeyword(context, "VALUES (",
                               7089                 :                :                              -PRETTYINDENT_STD, PRETTYINDENT_STD, 2);
 1780                          7090                 :            138 :         get_rule_list_toplevel(strippedexprs, context, false);
 9778                          7091                 :            138 :         appendStringInfoChar(buf, ')');
                               7092                 :                :     }
                               7093                 :                :     else
                               7094                 :                :     {
                               7095                 :                :         /* No expressions, so it must be DEFAULT VALUES */
 4776 rhaas@postgresql.org     7096                 :UBC           0 :         appendStringInfoString(buf, "DEFAULT VALUES");
                               7097                 :                :     }
                               7098                 :                : 
                               7099                 :                :     /* Add ON CONFLICT if present */
 4222 andres@anarazel.de       7100         [ +  + ]:CBC         194 :     if (query->onConflict)
                               7101                 :                :     {
                               7102                 :             24 :         OnConflictExpr *confl = query->onConflict;
                               7103                 :                : 
 4167 heikki.linnakangas@i     7104                 :             24 :         appendStringInfoString(buf, " ON CONFLICT");
                               7105                 :                : 
 4211 andres@anarazel.de       7106         [ +  + ]:             24 :         if (confl->arbiterElems)
                               7107                 :                :         {
                               7108                 :                :             /* Add the single-VALUES expression list */
                               7109                 :             20 :             appendStringInfoChar(buf, '(');
                               7110                 :             20 :             get_rule_expr((Node *) confl->arbiterElems, context, false);
                               7111                 :             20 :             appendStringInfoChar(buf, ')');
                               7112                 :                : 
                               7113                 :                :             /* Add a WHERE clause (for partial indexes) if given */
                               7114         [ +  + ]:             20 :             if (confl->arbiterWhere != NULL)
                               7115                 :                :             {
                               7116                 :                :                 bool        save_varprefix;
                               7117                 :                : 
                               7118                 :                :                 /*
                               7119                 :                :                  * Force non-prefixing of Vars, since parser assumes that they
                               7120                 :                :                  * belong to target relation.  WHERE clause does not use
                               7121                 :                :                  * InferenceElem, so this is separately required.
                               7122                 :                :                  */
 3947 tgl@sss.pgh.pa.us        7123                 :              8 :                 save_varprefix = context->varprefix;
                               7124                 :              8 :                 context->varprefix = false;
                               7125                 :                : 
 4211 andres@anarazel.de       7126                 :              8 :                 appendContextKeyword(context, " WHERE ",
                               7127                 :                :                                      -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
                               7128                 :              8 :                 get_rule_expr(confl->arbiterWhere, context, false);
                               7129                 :                : 
 3947 tgl@sss.pgh.pa.us        7130                 :              8 :                 context->varprefix = save_varprefix;
                               7131                 :                :             }
                               7132                 :                :         }
 3853                          7133         [ -  + ]:              4 :         else if (OidIsValid(confl->constraint))
                               7134                 :                :         {
 4207 bruce@momjian.us         7135                 :UBC           0 :             char       *constraint = get_constraint_name(confl->constraint);
                               7136                 :                : 
 3853 tgl@sss.pgh.pa.us        7137         [ #  # ]:              0 :             if (!constraint)
                               7138         [ #  # ]:              0 :                 elog(ERROR, "cache lookup failed for constraint %u",
                               7139                 :                :                      confl->constraint);
 4211 andres@anarazel.de       7140                 :              0 :             appendStringInfo(buf, " ON CONSTRAINT %s",
                               7141                 :                :                              quote_identifier(constraint));
                               7142                 :                :         }
                               7143                 :                : 
 4222 andres@anarazel.de       7144         [ +  + ]:CBC          24 :         if (confl->action == ONCONFLICT_NOTHING)
                               7145                 :                :         {
 4211                          7146                 :             12 :             appendStringInfoString(buf, " DO NOTHING");
                               7147                 :                :         }
  289 dean.a.rasheed@gmail     7148         [ +  + ]:             12 :         else if (confl->action == ONCONFLICT_UPDATE)
                               7149                 :                :         {
 4211 andres@anarazel.de       7150                 :              8 :             appendStringInfoString(buf, " DO UPDATE SET ");
                               7151                 :                :             /* Deparse targetlist */
 4222                          7152                 :              8 :             get_update_query_targetlist_def(query, confl->onConflictSet,
                               7153                 :                :                                             context, rte);
                               7154                 :                : 
                               7155                 :                :             /* Add a WHERE clause if given */
                               7156         [ +  - ]:              8 :             if (confl->onConflictWhere != NULL)
                               7157                 :                :             {
                               7158                 :              8 :                 appendContextKeyword(context, " WHERE ",
                               7159                 :                :                                      -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
                               7160                 :              8 :                 get_rule_expr(confl->onConflictWhere, context, false);
                               7161                 :                :             }
                               7162                 :                :         }
                               7163                 :                :         else
                               7164                 :                :         {
  289 dean.a.rasheed@gmail     7165         [ -  + ]:              4 :             Assert(confl->action == ONCONFLICT_SELECT);
                               7166                 :              4 :             appendStringInfoString(buf, " DO SELECT");
                               7167                 :                : 
                               7168                 :                :             /* Add FOR [KEY] UPDATE/SHARE clause if present */
                               7169         [ +  - ]:              4 :             if (confl->lockStrength != LCS_NONE)
                               7170                 :              4 :                 appendStringInfoString(buf, get_lock_clause_strength(confl->lockStrength));
                               7171                 :                : 
                               7172                 :                :             /* Add a WHERE clause if given */
                               7173         [ +  - ]:              4 :             if (confl->onConflictWhere != NULL)
                               7174                 :                :             {
                               7175                 :              4 :                 appendContextKeyword(context, " WHERE ",
                               7176                 :                :                                      -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
                               7177                 :              4 :                 get_rule_expr(confl->onConflictWhere, context, false);
                               7178                 :                :             }
                               7179                 :                :         }
                               7180                 :                :     }
                               7181                 :                : 
                               7182                 :                :     /* Add RETURNING if present */
 7413 tgl@sss.pgh.pa.us        7183         [ +  + ]:            194 :     if (query->returningList)
  681 dean.a.rasheed@gmail     7184                 :             51 :         get_returning_clause(query, context);
10323 bruce@momjian.us         7185                 :            194 : }
                               7186                 :                : 
                               7187                 :                : 
                               7188                 :                : /* ----------
                               7189                 :                :  * get_update_query_def         - Parse back an UPDATE parsetree
                               7190                 :                :  * ----------
                               7191                 :                :  */
                               7192                 :                : static void
  821 tgl@sss.pgh.pa.us        7193                 :             86 : get_update_query_def(Query *query, deparse_context *context)
                               7194                 :                : {
 8126 bruce@momjian.us         7195                 :             86 :     StringInfo  buf = context->buf;
                               7196                 :                :     RangeTblEntry *rte;
                               7197                 :                : 
                               7198                 :                :     /* Insert the WITH clause if given */
 5888 tgl@sss.pgh.pa.us        7199                 :             86 :     get_with_clause(query, context);
                               7200                 :                : 
                               7201                 :                :     /*
                               7202                 :                :      * Start the query with UPDATE relname SET
                               7203                 :                :      */
 9890                          7204                 :             86 :     rte = rt_fetch(query->resultRelation, query->rtable);
 8975                          7205         [ -  + ]:             86 :     Assert(rte->rtekind == RTE_RELATION);
 8522                          7206         [ +  - ]:             86 :     if (PRETTY_INDENT(context))
                               7207                 :                :     {
 8517 bruce@momjian.us         7208                 :             86 :         appendStringInfoChar(buf, ' ');
                               7209                 :             86 :         context->indentLevel += PRETTYINDENT_STD;
                               7210                 :                :     }
 6783 tgl@sss.pgh.pa.us        7211                 :            172 :     appendStringInfo(buf, "UPDATE %s%s",
 9667                          7212         [ +  - ]:             86 :                      only_marker(rte),
                               7213                 :                :                      generate_relation_name(rte->relid, NIL));
                               7214                 :                : 
                               7215                 :                :     /*
                               7216                 :                :      * Print the relation alias, if needed.  Always write AS, since a bare
                               7217                 :                :      * alias named "set" would be read as the SET keyword.
                               7218                 :                :      */
   40                          7219                 :             86 :     get_rte_alias(rte, query->resultRelation, true, context);
                               7220                 :                : 
 6783                          7221                 :             86 :     appendStringInfoString(buf, " SET ");
                               7222                 :                : 
                               7223                 :                :     /* Deparse targetlist */
 4222 andres@anarazel.de       7224                 :             86 :     get_update_query_targetlist_def(query, query->targetList, context, rte);
                               7225                 :                : 
                               7226                 :                :     /* Add the FROM clause if needed */
                               7227                 :             86 :     get_from_clause(query, " FROM ", context);
                               7228                 :                : 
                               7229                 :                :     /* Add a WHERE clause if given */
                               7230         [ +  + ]:             86 :     if (query->jointree->quals != NULL)
                               7231                 :                :     {
                               7232                 :             61 :         appendContextKeyword(context, " WHERE ",
                               7233                 :                :                              -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
                               7234                 :             61 :         get_rule_expr(query->jointree->quals, context, false);
                               7235                 :                :     }
                               7236                 :                : 
                               7237                 :                :     /* Add RETURNING if present */
                               7238         [ +  + ]:             86 :     if (query->returningList)
  681 dean.a.rasheed@gmail     7239                 :             29 :         get_returning_clause(query, context);
 4222 andres@anarazel.de       7240                 :             86 : }
                               7241                 :                : 
                               7242                 :                : 
                               7243                 :                : /* ----------
                               7244                 :                :  * get_update_query_targetlist_def          - Parse back an UPDATE targetlist
                               7245                 :                :  * ----------
                               7246                 :                :  */
                               7247                 :                : static void
                               7248                 :            118 : get_update_query_targetlist_def(Query *query, List *targetList,
                               7249                 :                :                                 deparse_context *context, RangeTblEntry *rte)
                               7250                 :                : {
                               7251                 :            118 :     StringInfo  buf = context->buf;
                               7252                 :                :     ListCell   *l;
                               7253                 :                :     ListCell   *next_ma_cell;
                               7254                 :                :     int         remaining_ma_columns;
                               7255                 :                :     const char *sep;
                               7256                 :                :     SubLink    *cur_ma_sublink;
                               7257                 :                :     List       *ma_sublinks;
                               7258                 :                : 
                               7259                 :                :     /*
                               7260                 :                :      * Prepare to deal with MULTIEXPR assignments: collect the source SubLinks
                               7261                 :                :      * into a list.  We expect them to appear, in ID order, in resjunk tlist
                               7262                 :                :      * entries.
                               7263                 :                :      */
 4546 tgl@sss.pgh.pa.us        7264                 :            118 :     ma_sublinks = NIL;
                               7265         [ +  + ]:            118 :     if (query->hasSubLinks)      /* else there can't be any */
                               7266                 :                :     {
 4222 andres@anarazel.de       7267   [ +  -  +  +  :             28 :         foreach(l, targetList)
                                              +  + ]
                               7268                 :                :         {
 4546 tgl@sss.pgh.pa.us        7269                 :             20 :             TargetEntry *tle = (TargetEntry *) lfirst(l);
                               7270                 :                : 
                               7271   [ +  +  +  - ]:             20 :             if (tle->resjunk && IsA(tle->expr, SubLink))
                               7272                 :                :             {
                               7273                 :              4 :                 SubLink    *sl = (SubLink *) tle->expr;
                               7274                 :                : 
                               7275         [ +  - ]:              4 :                 if (sl->subLinkType == MULTIEXPR_SUBLINK)
                               7276                 :                :                 {
                               7277                 :              4 :                     ma_sublinks = lappend(ma_sublinks, sl);
                               7278         [ -  + ]:              4 :                     Assert(sl->subLinkId == list_length(ma_sublinks));
                               7279                 :                :                 }
                               7280                 :                :             }
                               7281                 :                :         }
                               7282                 :                :     }
                               7283                 :            118 :     next_ma_cell = list_head(ma_sublinks);
                               7284                 :            118 :     cur_ma_sublink = NULL;
                               7285                 :            118 :     remaining_ma_columns = 0;
                               7286                 :                : 
                               7287                 :                :     /* Add the comma separated list of 'attname = value' */
10315 bruce@momjian.us         7288                 :            118 :     sep = "";
 4222 andres@anarazel.de       7289   [ +  -  +  +  :            298 :     foreach(l, targetList)
                                              +  + ]
                               7290                 :                :     {
 9556 tgl@sss.pgh.pa.us        7291                 :            180 :         TargetEntry *tle = (TargetEntry *) lfirst(l);
                               7292                 :                :         Node       *expr;
                               7293                 :                : 
 7906                          7294         [ +  + ]:            180 :         if (tle->resjunk)
 9556                          7295                 :              4 :             continue;           /* ignore junk entries */
                               7296                 :                : 
                               7297                 :                :         /* Emit separator (OK whether we're in multiassignment or not) */
 7882 neilc@samurai.com        7298                 :            176 :         appendStringInfoString(buf, sep);
10315 bruce@momjian.us         7299                 :            176 :         sep = ", ";
                               7300                 :                : 
                               7301                 :                :         /*
                               7302                 :                :          * Check to see if we're starting a multiassignment group: if so,
                               7303                 :                :          * output a left paren.
                               7304                 :                :          */
 4546 tgl@sss.pgh.pa.us        7305   [ +  +  +  - ]:            176 :         if (next_ma_cell != NULL && cur_ma_sublink == NULL)
                               7306                 :                :         {
                               7307                 :                :             /*
                               7308                 :                :              * We must dig down into the expr to see if it's a PARAM_MULTIEXPR
                               7309                 :                :              * Param.  That could be buried under FieldStores and
                               7310                 :                :              * SubscriptingRefs and CoerceToDomains (cf processIndirection()),
                               7311                 :                :              * and underneath those there could be an implicit type coercion.
                               7312                 :                :              * Because we would ignore implicit type coercions anyway, we
                               7313                 :                :              * don't need to be as careful as processIndirection() is about
                               7314                 :                :              * descending past implicit CoerceToDomains.
                               7315                 :                :              */
                               7316                 :              4 :             expr = (Node *) tle->expr;
                               7317         [ +  - ]:              8 :             while (expr)
                               7318                 :                :             {
                               7319         [ -  + ]:              8 :                 if (IsA(expr, FieldStore))
                               7320                 :                :                 {
 4546 tgl@sss.pgh.pa.us        7321                 :UBC           0 :                     FieldStore *fstore = (FieldStore *) expr;
                               7322                 :                : 
                               7323                 :              0 :                     expr = (Node *) linitial(fstore->newvals);
                               7324                 :                :                 }
 2857 alvherre@alvh.no-ip.     7325         [ +  + ]:CBC           8 :                 else if (IsA(expr, SubscriptingRef))
                               7326                 :                :                 {
                               7327                 :              4 :                     SubscriptingRef *sbsref = (SubscriptingRef *) expr;
                               7328                 :                : 
                               7329         [ -  + ]:              4 :                     if (sbsref->refassgnexpr == NULL)
 4546 tgl@sss.pgh.pa.us        7330                 :UBC           0 :                         break;
                               7331                 :                : 
 2857 alvherre@alvh.no-ip.     7332                 :CBC           4 :                     expr = (Node *) sbsref->refassgnexpr;
                               7333                 :                :                 }
 3426 tgl@sss.pgh.pa.us        7334         [ -  + ]:              4 :                 else if (IsA(expr, CoerceToDomain))
                               7335                 :                :                 {
 3426 tgl@sss.pgh.pa.us        7336                 :UBC           0 :                     CoerceToDomain *cdomain = (CoerceToDomain *) expr;
                               7337                 :                : 
                               7338         [ #  # ]:              0 :                     if (cdomain->coercionformat != COERCE_IMPLICIT_CAST)
                               7339                 :              0 :                         break;
                               7340                 :              0 :                     expr = (Node *) cdomain->arg;
                               7341                 :                :                 }
                               7342                 :                :                 else
 4546 tgl@sss.pgh.pa.us        7343                 :CBC           4 :                     break;
                               7344                 :                :             }
                               7345                 :              4 :             expr = strip_implicit_coercions(expr);
                               7346                 :                : 
                               7347   [ +  -  +  - ]:              4 :             if (expr && IsA(expr, Param) &&
                               7348         [ +  - ]:              4 :                 ((Param *) expr)->paramkind == PARAM_MULTIEXPR)
                               7349                 :                :             {
                               7350                 :              4 :                 cur_ma_sublink = (SubLink *) lfirst(next_ma_cell);
 2693                          7351                 :              4 :                 next_ma_cell = lnext(ma_sublinks, next_ma_cell);
 2494 alvherre@alvh.no-ip.     7352                 :              4 :                 remaining_ma_columns = count_nonjunk_tlist_entries(((Query *) cur_ma_sublink->subselect)->targetList);
 4546 tgl@sss.pgh.pa.us        7353         [ -  + ]:              4 :                 Assert(((Param *) expr)->paramid ==
                               7354                 :                :                        ((cur_ma_sublink->subLinkId << 16) | 1));
                               7355                 :              4 :                 appendStringInfoChar(buf, '(');
                               7356                 :                :             }
                               7357                 :                :         }
                               7358                 :                : 
                               7359                 :                :         /*
                               7360                 :                :          * Put out name of target column; look in the catalogs, not at
                               7361                 :                :          * tle->resname, since resname will fail to track RENAME.
                               7362                 :                :          */
 8207                          7363                 :            176 :         appendStringInfoString(buf,
 3211 alvherre@alvh.no-ip.     7364                 :            176 :                                quote_identifier(get_attname(rte->relid,
                               7365                 :            176 :                                                             tle->resno,
                               7366                 :                :                                                             false)));
                               7367                 :                : 
                               7368                 :                :         /*
                               7369                 :                :          * Print any indirection needed (subfields or subscripts), and strip
                               7370                 :                :          * off the top-level nodes representing the indirection assignments.
                               7371                 :                :          */
 3769 tgl@sss.pgh.pa.us        7372                 :            176 :         expr = processIndirection((Node *) tle->expr, context);
                               7373                 :                : 
                               7374                 :                :         /*
                               7375                 :                :          * If we're in a multiassignment, skip printing anything more, unless
                               7376                 :                :          * this is the last column; in which case, what we print should be the
                               7377                 :                :          * sublink, not the Param.
                               7378                 :                :          */
 4546                          7379         [ +  + ]:            176 :         if (cur_ma_sublink != NULL)
                               7380                 :                :         {
                               7381         [ +  + ]:             12 :             if (--remaining_ma_columns > 0)
                               7382                 :              8 :                 continue;       /* not the last column of multiassignment */
                               7383                 :              4 :             appendStringInfoChar(buf, ')');
                               7384                 :              4 :             expr = (Node *) cur_ma_sublink;
                               7385                 :              4 :             cur_ma_sublink = NULL;
                               7386                 :                :         }
                               7387                 :                : 
 4776 rhaas@postgresql.org     7388                 :            168 :         appendStringInfoString(buf, " = ");
                               7389                 :                : 
 8207 tgl@sss.pgh.pa.us        7390                 :            168 :         get_rule_expr(expr, context, false);
                               7391                 :                :     }
10323 bruce@momjian.us         7392                 :            118 : }
                               7393                 :                : 
                               7394                 :                : 
                               7395                 :                : /* ----------
                               7396                 :                :  * get_delete_query_def         - Parse back a DELETE parsetree
                               7397                 :                :  * ----------
                               7398                 :                :  */
                               7399                 :                : static void
  821 tgl@sss.pgh.pa.us        7400                 :             39 : get_delete_query_def(Query *query, deparse_context *context)
                               7401                 :                : {
 9918                          7402                 :             39 :     StringInfo  buf = context->buf;
                               7403                 :                :     RangeTblEntry *rte;
                               7404                 :                : 
                               7405                 :                :     /* Insert the WITH clause if given */
 5888                          7406                 :             39 :     get_with_clause(query, context);
                               7407                 :                : 
                               7408                 :                :     /*
                               7409                 :                :      * Start the query with DELETE FROM relname
                               7410                 :                :      */
 9890                          7411                 :             39 :     rte = rt_fetch(query->resultRelation, query->rtable);
 8975                          7412         [ -  + ]:             39 :     Assert(rte->rtekind == RTE_RELATION);
 8522                          7413         [ +  - ]:             39 :     if (PRETTY_INDENT(context))
                               7414                 :                :     {
 8517 bruce@momjian.us         7415                 :             39 :         appendStringInfoChar(buf, ' ');
 6783 tgl@sss.pgh.pa.us        7416                 :             39 :         context->indentLevel += PRETTYINDENT_STD;
                               7417                 :                :     }
 9890                          7418                 :             78 :     appendStringInfo(buf, "DELETE FROM %s%s",
 9667                          7419         [ +  - ]:             39 :                      only_marker(rte),
                               7420                 :                :                      generate_relation_name(rte->relid, NIL));
                               7421                 :                : 
                               7422                 :                :     /*
                               7423                 :                :      * Print the relation alias, if needed.  Always write AS, since a bare
                               7424                 :                :      * alias named "set" would be read as the SET keyword.
                               7425                 :                :      */
   40                          7426                 :             39 :     get_rte_alias(rte, query->resultRelation, true, context);
                               7427                 :                : 
                               7428                 :                :     /* Add the USING clause if given */
 7789                          7429                 :             39 :     get_from_clause(query, " USING ", context);
                               7430                 :                : 
                               7431                 :                :     /* Add a WHERE clause if given */
 9556                          7432         [ +  - ]:             39 :     if (query->jointree->quals != NULL)
                               7433                 :                :     {
 8522                          7434                 :             39 :         appendContextKeyword(context, " WHERE ",
                               7435                 :                :                              -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
 8836                          7436                 :             39 :         get_rule_expr(query->jointree->quals, context, false);
                               7437                 :                :     }
                               7438                 :                : 
                               7439                 :                :     /* Add RETURNING if present */
 7413                          7440         [ +  + ]:             39 :     if (query->returningList)
  681 dean.a.rasheed@gmail     7441                 :              9 :         get_returning_clause(query, context);
10323 bruce@momjian.us         7442                 :             39 : }
                               7443                 :                : 
                               7444                 :                : 
                               7445                 :                : /* ----------
                               7446                 :                :  * get_merge_query_def              - Parse back a MERGE parsetree
                               7447                 :                :  * ----------
                               7448                 :                :  */
                               7449                 :                : static void
  821 tgl@sss.pgh.pa.us        7450                 :             16 : get_merge_query_def(Query *query, deparse_context *context)
                               7451                 :                : {
 1301                          7452                 :             16 :     StringInfo  buf = context->buf;
                               7453                 :                :     RangeTblEntry *rte;
                               7454                 :                :     ListCell   *lc;
                               7455                 :                :     bool        haveNotMatchedBySource;
                               7456                 :                : 
                               7457                 :                :     /* Insert the WITH clause if given */
                               7458                 :             16 :     get_with_clause(query, context);
                               7459                 :                : 
                               7460                 :                :     /*
                               7461                 :                :      * Start the query with MERGE INTO relname
                               7462                 :                :      */
                               7463                 :             16 :     rte = rt_fetch(query->resultRelation, query->rtable);
                               7464         [ -  + ]:             16 :     Assert(rte->rtekind == RTE_RELATION);
                               7465         [ +  - ]:             16 :     if (PRETTY_INDENT(context))
                               7466                 :                :     {
                               7467                 :             16 :         appendStringInfoChar(buf, ' ');
                               7468                 :             16 :         context->indentLevel += PRETTYINDENT_STD;
                               7469                 :                :     }
                               7470                 :             32 :     appendStringInfo(buf, "MERGE INTO %s%s",
                               7471         [ +  - ]:             16 :                      only_marker(rte),
                               7472                 :                :                      generate_relation_name(rte->relid, NIL));
                               7473                 :                : 
                               7474                 :                :     /*
                               7475                 :                :      * Print the relation alias, if needed.  Always write AS, since a bare
                               7476                 :                :      * alias named "set" would be read as the SET keyword.
                               7477                 :                :      */
   40                          7478                 :             16 :     get_rte_alias(rte, query->resultRelation, true, context);
                               7479                 :                : 
                               7480                 :                :     /* Print the source relation and join clause */
 1301                          7481                 :             16 :     get_from_clause(query, " USING ", context);
                               7482                 :             16 :     appendContextKeyword(context, " ON ",
                               7483                 :                :                          -PRETTYINDENT_STD, PRETTYINDENT_STD, 2);
  973 dean.a.rasheed@gmail     7484                 :             16 :     get_rule_expr(query->mergeJoinCondition, context, false);
                               7485                 :                : 
                               7486                 :                :     /*
                               7487                 :                :      * Test for any NOT MATCHED BY SOURCE actions.  If there are none, then
                               7488                 :                :      * any NOT MATCHED BY TARGET actions are output as "WHEN NOT MATCHED", per
                               7489                 :                :      * SQL standard.  Otherwise, we have a non-SQL-standard query, so output
                               7490                 :                :      * "BY SOURCE" / "BY TARGET" qualifiers for all NOT MATCHED actions, to be
                               7491                 :                :      * more explicit.
                               7492                 :                :      */
                               7493                 :             16 :     haveNotMatchedBySource = false;
                               7494   [ +  -  +  +  :             80 :     foreach(lc, query->mergeActionList)
                                              +  + ]
                               7495                 :                :     {
                               7496                 :             68 :         MergeAction *action = lfirst_node(MergeAction, lc);
                               7497                 :                : 
                               7498         [ +  + ]:             68 :         if (action->matchKind == MERGE_WHEN_NOT_MATCHED_BY_SOURCE)
                               7499                 :                :         {
                               7500                 :              4 :             haveNotMatchedBySource = true;
                               7501                 :              4 :             break;
                               7502                 :                :         }
                               7503                 :                :     }
                               7504                 :                : 
                               7505                 :                :     /* Print each merge action */
 1301 tgl@sss.pgh.pa.us        7506   [ +  -  +  +  :             84 :     foreach(lc, query->mergeActionList)
                                              +  + ]
                               7507                 :                :     {
                               7508                 :             68 :         MergeAction *action = lfirst_node(MergeAction, lc);
                               7509                 :                : 
                               7510                 :             68 :         appendContextKeyword(context, " WHEN ",
                               7511                 :                :                              -PRETTYINDENT_STD, PRETTYINDENT_STD, 2);
  973 dean.a.rasheed@gmail     7512   [ +  +  +  - ]:             68 :         switch (action->matchKind)
                               7513                 :                :         {
                               7514                 :             32 :             case MERGE_WHEN_MATCHED:
  962 drowley@postgresql.o     7515                 :             32 :                 appendStringInfoString(buf, "MATCHED");
  973 dean.a.rasheed@gmail     7516                 :             32 :                 break;
                               7517                 :              4 :             case MERGE_WHEN_NOT_MATCHED_BY_SOURCE:
  962 drowley@postgresql.o     7518                 :              4 :                 appendStringInfoString(buf, "NOT MATCHED BY SOURCE");
  973 dean.a.rasheed@gmail     7519                 :              4 :                 break;
                               7520                 :             32 :             case MERGE_WHEN_NOT_MATCHED_BY_TARGET:
                               7521         [ +  + ]:             32 :                 if (haveNotMatchedBySource)
  962 drowley@postgresql.o     7522                 :              4 :                     appendStringInfoString(buf, "NOT MATCHED BY TARGET");
                               7523                 :                :                 else
                               7524                 :             28 :                     appendStringInfoString(buf, "NOT MATCHED");
  973 dean.a.rasheed@gmail     7525                 :             32 :                 break;
  973 dean.a.rasheed@gmail     7526                 :UBC           0 :             default:
                               7527         [ #  # ]:              0 :                 elog(ERROR, "unrecognized matchKind: %d",
                               7528                 :                :                      (int) action->matchKind);
                               7529                 :                :         }
                               7530                 :                : 
 1301 tgl@sss.pgh.pa.us        7531         [ +  + ]:CBC          68 :         if (action->qual)
                               7532                 :                :         {
                               7533                 :             32 :             appendContextKeyword(context, " AND ",
                               7534                 :                :                                  -PRETTYINDENT_STD, PRETTYINDENT_STD, 3);
                               7535                 :             32 :             get_rule_expr(action->qual, context, false);
                               7536                 :                :         }
                               7537                 :             68 :         appendContextKeyword(context, " THEN ",
                               7538                 :                :                              -PRETTYINDENT_STD, PRETTYINDENT_STD, 3);
                               7539                 :                : 
                               7540         [ +  + ]:             68 :         if (action->commandType == CMD_INSERT)
                               7541                 :                :         {
                               7542                 :                :             /* This generally matches get_insert_query_def() */
                               7543                 :             32 :             List       *strippedexprs = NIL;
                               7544                 :             32 :             const char *sep = "";
                               7545                 :                :             ListCell   *lc2;
                               7546                 :                : 
                               7547                 :             32 :             appendStringInfoString(buf, "INSERT");
                               7548                 :                : 
                               7549         [ +  + ]:             32 :             if (action->targetList)
                               7550                 :             28 :                 appendStringInfoString(buf, " (");
                               7551   [ +  +  +  +  :             92 :             foreach(lc2, action->targetList)
                                              +  + ]
                               7552                 :                :             {
                               7553                 :             60 :                 TargetEntry *tle = (TargetEntry *) lfirst(lc2);
                               7554                 :                : 
                               7555         [ -  + ]:             60 :                 Assert(!tle->resjunk);
                               7556                 :                : 
                               7557                 :             60 :                 appendStringInfoString(buf, sep);
                               7558                 :             60 :                 sep = ", ";
                               7559                 :                : 
                               7560                 :             60 :                 appendStringInfoString(buf,
                               7561                 :             60 :                                        quote_identifier(get_attname(rte->relid,
                               7562                 :             60 :                                                                     tle->resno,
                               7563                 :                :                                                                     false)));
                               7564                 :             60 :                 strippedexprs = lappend(strippedexprs,
                               7565                 :             60 :                                         processIndirection((Node *) tle->expr,
                               7566                 :                :                                                            context));
                               7567                 :                :             }
                               7568         [ +  + ]:             32 :             if (action->targetList)
                               7569                 :             28 :                 appendStringInfoChar(buf, ')');
                               7570                 :                : 
                               7571         [ +  + ]:             32 :             if (action->override)
                               7572                 :                :             {
                               7573         [ -  + ]:              4 :                 if (action->override == OVERRIDING_SYSTEM_VALUE)
 1301 tgl@sss.pgh.pa.us        7574                 :UBC           0 :                     appendStringInfoString(buf, " OVERRIDING SYSTEM VALUE");
 1301 tgl@sss.pgh.pa.us        7575         [ +  - ]:CBC           4 :                 else if (action->override == OVERRIDING_USER_VALUE)
                               7576                 :              4 :                     appendStringInfoString(buf, " OVERRIDING USER VALUE");
                               7577                 :                :             }
                               7578                 :                : 
                               7579         [ +  + ]:             32 :             if (strippedexprs)
                               7580                 :                :             {
                               7581                 :             28 :                 appendContextKeyword(context, " VALUES (",
                               7582                 :                :                                      -PRETTYINDENT_STD, PRETTYINDENT_STD, 4);
                               7583                 :             28 :                 get_rule_list_toplevel(strippedexprs, context, false);
                               7584                 :             28 :                 appendStringInfoChar(buf, ')');
                               7585                 :                :             }
                               7586                 :                :             else
                               7587                 :              4 :                 appendStringInfoString(buf, " DEFAULT VALUES");
                               7588                 :                :         }
                               7589         [ +  + ]:             36 :         else if (action->commandType == CMD_UPDATE)
                               7590                 :                :         {
                               7591                 :             24 :             appendStringInfoString(buf, "UPDATE SET ");
                               7592                 :             24 :             get_update_query_targetlist_def(query, action->targetList,
                               7593                 :                :                                             context, rte);
                               7594                 :                :         }
                               7595         [ +  + ]:             12 :         else if (action->commandType == CMD_DELETE)
                               7596                 :              8 :             appendStringInfoString(buf, "DELETE");
                               7597         [ +  - ]:              4 :         else if (action->commandType == CMD_NOTHING)
                               7598                 :              4 :             appendStringInfoString(buf, "DO NOTHING");
                               7599                 :                :     }
                               7600                 :                : 
                               7601                 :                :     /* Add RETURNING if present */
  986 dean.a.rasheed@gmail     7602         [ +  + ]:             16 :     if (query->returningList)
  681                          7603                 :              8 :         get_returning_clause(query, context);
 1301 tgl@sss.pgh.pa.us        7604                 :             16 : }
                               7605                 :                : 
                               7606                 :                : 
                               7607                 :                : /* ----------
                               7608                 :                :  * get_utility_query_def            - Parse back a UTILITY parsetree
                               7609                 :                :  * ----------
                               7610                 :                :  */
                               7611                 :                : static void
 9460                          7612                 :              9 : get_utility_query_def(Query *query, deparse_context *context)
                               7613                 :                : {
                               7614                 :              9 :     StringInfo  buf = context->buf;
                               7615                 :                : 
                               7616   [ +  -  +  - ]:              9 :     if (query->utilityStmt && IsA(query->utilityStmt, NotifyStmt))
                               7617                 :              9 :     {
                               7618                 :              9 :         NotifyStmt *stmt = (NotifyStmt *) query->utilityStmt;
                               7619                 :                : 
 8522                          7620                 :              9 :         appendContextKeyword(context, "",
                               7621                 :                :                              0, PRETTYINDENT_STD, 1);
 9017                          7622                 :              9 :         appendStringInfo(buf, "NOTIFY %s",
 6662                          7623                 :              9 :                          quote_identifier(stmt->conditionname));
 6129                          7624         [ -  + ]:              9 :         if (stmt->payload)
                               7625                 :                :         {
 6129 tgl@sss.pgh.pa.us        7626                 :UBC           0 :             appendStringInfoString(buf, ", ");
                               7627                 :              0 :             simple_quote_literal(buf, stmt->payload);
                               7628                 :                :         }
                               7629                 :                :     }
                               7630                 :                :     else
                               7631                 :                :     {
                               7632                 :                :         /* Currently only NOTIFY utility commands can appear in rules */
 8525                          7633         [ #  # ]:              0 :         elog(ERROR, "unexpected utility statement type");
                               7634                 :                :     }
 9460 tgl@sss.pgh.pa.us        7635                 :CBC           9 : }
                               7636                 :                : 
                               7637                 :                : /*
                               7638                 :                :  * Display a Var appropriately.
                               7639                 :                :  *
                               7640                 :                :  * In some cases (currently only when recursing into an unnamed join)
                               7641                 :                :  * the Var's varlevelsup has to be interpreted with respect to a context
                               7642                 :                :  * above the current one; levelsup indicates the offset.
                               7643                 :                :  *
                               7644                 :                :  * If istoplevel is true, the Var is at the top level of a SELECT's
                               7645                 :                :  * targetlist, which means we need special treatment of whole-row Vars.
                               7646                 :                :  * Instead of the normal "tab.*", we'll print "tab.*::typename", which is a
                               7647                 :                :  * dirty hack to prevent "tab.*" from being expanded into multiple columns.
                               7648                 :                :  * (The parser will strip the useless coercion, so no inefficiency is added in
                               7649                 :                :  * dump and reload.)  We used to print just "tab" in such cases, but that is
                               7650                 :                :  * ambiguous and will yield the wrong result if "tab" is also a plain column
                               7651                 :                :  * name in the query.
                               7652                 :                :  *
                               7653                 :                :  * Returns the attname of the Var, or NULL if the Var has no attname (because
                               7654                 :                :  * it is a whole-row Var or a subplan output reference).
                               7655                 :                :  */
                               7656                 :                : static char *
 5328                          7657                 :         136893 : get_variable(Var *var, int levelsup, bool istoplevel, deparse_context *context)
                               7658                 :                : {
 7218                          7659                 :         136893 :     StringInfo  buf = context->buf;
                               7660                 :                :     RangeTblEntry *rte;
                               7661                 :                :     AttrNumber  attnum;
                               7662                 :                :     int         netlevelsup;
                               7663                 :                :     deparse_namespace *dpns;
                               7664                 :                :     int         varno;
                               7665                 :                :     AttrNumber  varattno;
                               7666                 :                :     deparse_columns *colinfo;
                               7667                 :                :     char       *refname;
                               7668                 :                :     char       *attname;
                               7669                 :                :     bool        need_prefix;
                               7670                 :                : 
                               7671                 :                :     /* Find appropriate nesting depth */
 7989                          7672                 :         136893 :     netlevelsup = var->varlevelsup + levelsup;
                               7673         [ -  + ]:         136893 :     if (netlevelsup >= list_length(context->namespaces))
 7989 tgl@sss.pgh.pa.us        7674         [ #  # ]:UBC           0 :         elog(ERROR, "bogus varlevelsup: %d offset %d",
                               7675                 :                :              var->varlevelsup, levelsup);
 8221 tgl@sss.pgh.pa.us        7676                 :CBC      136893 :     dpns = (deparse_namespace *) list_nth(context->namespaces,
                               7677                 :                :                                           netlevelsup);
                               7678                 :                : 
                               7679                 :                :     /*
                               7680                 :                :      * If we have a syntactic referent for the Var, and we're working from a
                               7681                 :                :      * parse tree, prefer to use the syntactic referent.  Otherwise, fall back
                               7682                 :                :      * on the semantic referent.  (Forcing use of the semantic referent when
                               7683                 :                :      * printing plan trees is a design choice that's perhaps more motivated by
                               7684                 :                :      * backwards compatibility than anything else.  But it does have the
                               7685                 :                :      * advantage of making plans more explicit.)
                               7686                 :                :      */
 2515                          7687   [ +  +  +  + ]:         136893 :     if (var->varnosyn > 0 && dpns->plan == NULL)
                               7688                 :                :     {
                               7689                 :          24639 :         varno = var->varnosyn;
                               7690                 :          24639 :         varattno = var->varattnosyn;
                               7691                 :                :     }
                               7692                 :                :     else
                               7693                 :                :     {
                               7694                 :         112254 :         varno = var->varno;
                               7695                 :         112254 :         varattno = var->varattno;
                               7696                 :                :     }
                               7697                 :                : 
                               7698                 :                :     /*
                               7699                 :                :      * Try to find the relevant RTE in this rtable.  In a plan tree, it's
                               7700                 :                :      * likely that varno is OUTER_VAR or INNER_VAR, in which case we must dig
                               7701                 :                :      * down into the subplans, or INDEX_VAR, which is resolved similarly. Also
                               7702                 :                :      * find the aliases previously assigned for this RTE.
                               7703                 :                :      */
                               7704   [ +  +  +  - ]:         136893 :     if (varno >= 1 && varno <= list_length(dpns->rtable))
                               7705                 :                :     {
                               7706                 :                :         /*
                               7707                 :                :          * We might have been asked to map child Vars to some parent relation.
                               7708                 :                :          */
 2544                          7709   [ +  +  +  + ]:          97467 :         if (context->appendparents && dpns->appendrels)
                               7710                 :                :         {
 1900                          7711                 :           2664 :             int         pvarno = varno;
 2544                          7712                 :           2664 :             AttrNumber  pvarattno = varattno;
                               7713                 :           2664 :             AppendRelInfo *appinfo = dpns->appendrels[pvarno];
                               7714                 :           2664 :             bool        found = false;
                               7715                 :                : 
                               7716                 :                :             /* Only map up to inheritance parents, not UNION ALL appendrels */
                               7717         [ +  + ]:           5322 :             while (appinfo &&
                               7718                 :           2889 :                    rt_fetch(appinfo->parent_relid,
                               7719         [ +  + ]:           2889 :                             dpns->rtable)->rtekind == RTE_RELATION)
                               7720                 :                :             {
                               7721                 :           2658 :                 found = false;
                               7722         [ +  + ]:           2658 :                 if (pvarattno > 0)   /* system columns stay as-is */
                               7723                 :                :                 {
                               7724         [ -  + ]:           2506 :                     if (pvarattno > appinfo->num_child_cols)
 2544 tgl@sss.pgh.pa.us        7725                 :UBC           0 :                         break;  /* safety check */
 2544 tgl@sss.pgh.pa.us        7726                 :CBC        2506 :                     pvarattno = appinfo->parent_colnos[pvarattno - 1];
                               7727         [ -  + ]:           2506 :                     if (pvarattno == 0)
 2544 tgl@sss.pgh.pa.us        7728                 :UBC           0 :                         break;  /* Var is local to child */
                               7729                 :                :                 }
                               7730                 :                : 
 2544 tgl@sss.pgh.pa.us        7731                 :CBC        2658 :                 pvarno = appinfo->parent_relid;
                               7732                 :           2658 :                 found = true;
                               7733                 :                : 
                               7734                 :                :                 /* If the parent is itself a child, continue up. */
                               7735   [ +  -  -  + ]:           2658 :                 Assert(pvarno > 0 && pvarno <= list_length(dpns->rtable));
                               7736                 :           2658 :                 appinfo = dpns->appendrels[pvarno];
                               7737                 :                :             }
                               7738                 :                : 
                               7739                 :                :             /*
                               7740                 :                :              * If we found an ancestral rel, and that rel is included in
                               7741                 :                :              * appendparents, print that column not the original one.
                               7742                 :                :              */
                               7743   [ +  +  +  + ]:           2664 :             if (found && bms_is_member(pvarno, context->appendparents))
                               7744                 :                :             {
                               7745                 :           2133 :                 varno = pvarno;
                               7746                 :           2133 :                 varattno = pvarattno;
                               7747                 :                :             }
                               7748                 :                :         }
                               7749                 :                : 
                               7750                 :          97467 :         rte = rt_fetch(varno, dpns->rtable);
                               7751                 :                : 
                               7752                 :                :         /* might be returning old/new column value */
  681 dean.a.rasheed@gmail     7753         [ +  + ]:          97467 :         if (var->varreturningtype == VAR_RETURNING_OLD)
                               7754                 :            298 :             refname = dpns->ret_old_alias;
                               7755         [ +  + ]:          97169 :         else if (var->varreturningtype == VAR_RETURNING_NEW)
                               7756                 :            281 :             refname = dpns->ret_new_alias;
                               7757                 :                :         else
                               7758                 :          96888 :             refname = (char *) list_nth(dpns->rtable_names, varno - 1);
                               7759                 :                : 
 2544 tgl@sss.pgh.pa.us        7760                 :          97467 :         colinfo = deparse_columns_fetch(varno, dpns);
                               7761                 :          97467 :         attnum = varattno;
                               7762                 :                :     }
                               7763                 :                :     else
                               7764                 :                :     {
                               7765                 :          39426 :         resolve_special_varno((Node *) var, context,
                               7766                 :                :                               get_special_variable, NULL);
 3867 rhaas@postgresql.org     7767                 :          39426 :         return NULL;
                               7768                 :                :     }
                               7769                 :                : 
                               7770                 :                :     /*
                               7771                 :                :      * The planner will sometimes emit Vars referencing resjunk elements of a
                               7772                 :                :      * subquery's target list (this is currently only possible if it chooses
                               7773                 :                :      * to generate a "physical tlist" for a SubqueryScan or CteScan node).
                               7774                 :                :      * Although we prefer to print subquery-referencing Vars using the
                               7775                 :                :      * subquery's alias, that's not possible for resjunk items since they have
                               7776                 :                :      * no alias.  So in that case, drill down to the subplan and print the
                               7777                 :                :      * contents of the referenced tlist item.  This works because in a plan
                               7778                 :                :      * tree, such Vars can only occur in a SubqueryScan or CteScan node, and
                               7779                 :                :      * we'll have set dpns->inner_plan to reference the child plan node.
                               7780                 :                :      */
 5986 tgl@sss.pgh.pa.us        7781   [ +  +  +  +  :         100725 :     if ((rte->rtekind == RTE_SUBQUERY || rte->rtekind == RTE_CTE) &&
                                              +  + ]
                               7782                 :           3258 :         attnum > list_length(rte->eref->colnames) &&
 2544                          7783         [ +  - ]:              1 :         dpns->inner_plan)
                               7784                 :                :     {
                               7785                 :                :         TargetEntry *tle;
                               7786                 :                :         deparse_namespace save_dpns;
                               7787                 :                : 
                               7788                 :              1 :         tle = get_tle_by_resno(dpns->inner_tlist, attnum);
 5986                          7789         [ -  + ]:              1 :         if (!tle)
 3802 tgl@sss.pgh.pa.us        7790         [ #  # ]:UBC           0 :             elog(ERROR, "invalid attnum %d for relation \"%s\"",
                               7791                 :                :                  attnum, rte->eref->aliasname);
                               7792                 :                : 
 5986 tgl@sss.pgh.pa.us        7793         [ -  + ]:CBC           1 :         Assert(netlevelsup == 0);
 2544                          7794                 :              1 :         push_child_plan(dpns, dpns->inner_plan, &save_dpns);
                               7795                 :                : 
                               7796                 :                :         /*
                               7797                 :                :          * Force parentheses because our caller probably assumed a Var is a
                               7798                 :                :          * simple expression.
                               7799                 :                :          */
 5986                          7800         [ -  + ]:              1 :         if (!IsA(tle->expr, Var))
 5986 tgl@sss.pgh.pa.us        7801                 :UBC           0 :             appendStringInfoChar(buf, '(');
 5986 tgl@sss.pgh.pa.us        7802                 :CBC           1 :         get_rule_expr((Node *) tle->expr, context, true);
                               7803         [ -  + ]:              1 :         if (!IsA(tle->expr, Var))
 5986 tgl@sss.pgh.pa.us        7804                 :UBC           0 :             appendStringInfoChar(buf, ')');
                               7805                 :                : 
 5982 tgl@sss.pgh.pa.us        7806                 :CBC           1 :         pop_child_plan(dpns, &save_dpns);
 5986                          7807                 :              1 :         return NULL;
                               7808                 :                :     }
                               7809                 :                : 
                               7810                 :                :     /*
                               7811                 :                :      * If it's an unnamed join, look at the expansion of the alias variable.
                               7812                 :                :      * If it's a simple reference to one of the input vars, then recursively
                               7813                 :                :      * print the name of that var instead.  When it's not a simple reference,
                               7814                 :                :      * we have to just print the unqualified join column name.  (This can only
                               7815                 :                :      * happen with "dangerous" merged columns in a JOIN USING; we took pains
                               7816                 :                :      * previously to make the unqualified column name unique in such cases.)
                               7817                 :                :      *
                               7818                 :                :      * This wouldn't work in decompiling plan trees, because we don't store
                               7819                 :                :      * joinaliasvars lists after planning; but a plan tree should never
                               7820                 :                :      * contain a join alias variable.
                               7821                 :                :      */
 5181                          7822   [ +  +  +  + ]:          97466 :     if (rte->rtekind == RTE_JOIN && rte->alias == NULL)
                               7823                 :                :     {
                               7824         [ -  + ]:             72 :         if (rte->joinaliasvars == NIL)
 5181 tgl@sss.pgh.pa.us        7825         [ #  # ]:UBC           0 :             elog(ERROR, "cannot decompile join alias var in plan tree");
 5181 tgl@sss.pgh.pa.us        7826         [ +  - ]:CBC          72 :         if (attnum > 0)
                               7827                 :                :         {
                               7828                 :                :             Var        *aliasvar;
                               7829                 :                : 
                               7830                 :             72 :             aliasvar = (Var *) list_nth(rte->joinaliasvars, attnum - 1);
                               7831                 :                :             /* we intentionally don't strip implicit coercions here */
 4876                          7832   [ +  -  -  + ]:             72 :             if (aliasvar && IsA(aliasvar, Var))
                               7833                 :                :             {
 5181 tgl@sss.pgh.pa.us        7834                 :UBC           0 :                 return get_variable(aliasvar, var->varlevelsup + levelsup,
                               7835                 :                :                                     istoplevel, context);
                               7836                 :                :             }
                               7837                 :                :         }
                               7838                 :                : 
                               7839                 :                :         /*
                               7840                 :                :          * Unnamed join has no refname.  (Note: since it's unnamed, there is
                               7841                 :                :          * no way the user could have referenced it to create a whole-row Var
                               7842                 :                :          * for it.  So we don't have to cover that case below.)
                               7843                 :                :          */
 5181 tgl@sss.pgh.pa.us        7844         [ -  + ]:CBC          72 :         Assert(refname == NULL);
                               7845                 :                :     }
                               7846                 :                : 
 7539                          7847         [ +  + ]:          97466 :     if (attnum == InvalidAttrNumber)
 7218                          7848                 :            760 :         attname = NULL;
 5080                          7849         [ +  + ]:          96706 :     else if (attnum > 0)
                               7850                 :                :     {
                               7851                 :                :         /* Get column name to use from the colinfo struct */
 3802                          7852         [ -  + ]:          95478 :         if (attnum > colinfo->num_cols)
 3802 tgl@sss.pgh.pa.us        7853         [ #  # ]:UBC           0 :             elog(ERROR, "invalid attnum %d for relation \"%s\"",
                               7854                 :                :                  attnum, rte->eref->aliasname);
 5080 tgl@sss.pgh.pa.us        7855                 :CBC       95478 :         attname = colinfo->colnames[attnum - 1];
                               7856                 :                : 
                               7857                 :                :         /*
                               7858                 :                :          * If we find a Var referencing a dropped column, it seems better to
                               7859                 :                :          * print something (anything) than to fail.  In general this should
                               7860                 :                :          * not happen, but it used to be possible for some cases involving
                               7861                 :                :          * functions returning named composite types, and perhaps there are
                               7862                 :                :          * still bugs out there.
                               7863                 :                :          */
 1591                          7864         [ +  + ]:          95478 :         if (attname == NULL)
                               7865                 :              4 :             attname = "?dropped?column?";
                               7866                 :                :     }
                               7867                 :                :     else
                               7868                 :                :     {
                               7869                 :                :         /* System column - name is fixed, get it from the catalog */
 7218                          7870                 :           1228 :         attname = get_rte_attribute_name(rte, attnum);
                               7871                 :                :     }
                               7872                 :                : 
  681 dean.a.rasheed@gmail     7873   [ +  +  +  + ]:         141496 :     need_prefix = (context->varprefix || attname == NULL ||
                               7874         [ +  + ]:          44030 :                    var->varreturningtype != VAR_RETURNING_DEFAULT);
                               7875                 :                : 
                               7876                 :                :     /*
                               7877                 :                :      * If we're considering a plain Var in an ORDER BY (but not GROUP BY)
                               7878                 :                :      * clause, we may need to add a table-name prefix to prevent
                               7879                 :                :      * findTargetlistEntrySQL92 from misinterpreting the name as an
                               7880                 :                :      * output-column name.  To avoid cluttering the output with unnecessary
                               7881                 :                :      * prefixes, do so only if there is a name match to a SELECT tlist item
                               7882                 :                :      * that is different from the Var.
                               7883                 :                :      */
  821 tgl@sss.pgh.pa.us        7884   [ +  +  +  +  :          97466 :     if (context->varInOrderBy && !context->inGroupBy && !need_prefix)
                                              +  + ]
                               7885                 :                :     {
                               7886                 :            179 :         int         colno = 0;
                               7887                 :                : 
                               7888   [ +  +  +  +  :            661 :         foreach_node(TargetEntry, tle, context->targetList)
                                              +  + ]
                               7889                 :                :         {
                               7890                 :                :             char       *colname;
                               7891                 :                : 
                               7892         [ -  + ]:            311 :             if (tle->resjunk)
  821 tgl@sss.pgh.pa.us        7893                 :UBC           0 :                 continue;       /* ignore junk entries */
  821 tgl@sss.pgh.pa.us        7894                 :CBC         311 :             colno++;
                               7895                 :                : 
                               7896                 :                :             /* This must match colname-choosing logic in get_target_list() */
                               7897   [ +  -  +  - ]:            311 :             if (context->resultDesc && colno <= context->resultDesc->natts)
                               7898                 :            311 :                 colname = NameStr(TupleDescAttr(context->resultDesc,
                               7899                 :                :                                                 colno - 1)->attname);
                               7900                 :                :             else
  821 tgl@sss.pgh.pa.us        7901                 :UBC           0 :                 colname = tle->resname;
                               7902                 :                : 
  821 tgl@sss.pgh.pa.us        7903   [ +  -  +  + ]:CBC         311 :             if (colname && strcmp(colname, attname) == 0 &&
                               7904         [ +  + ]:            106 :                 !equal(var, tle->expr))
                               7905                 :                :             {
                               7906                 :              8 :                 need_prefix = true;
                               7907                 :              8 :                 break;
                               7908                 :                :             }
                               7909                 :                :         }
                               7910                 :                :     }
                               7911                 :                : 
                               7912   [ +  +  +  + ]:          97466 :     if (refname && need_prefix)
                               7913                 :                :     {
 6232                          7914                 :          53385 :         appendStringInfoString(buf, quote_identifier(refname));
 5328                          7915                 :          53385 :         appendStringInfoChar(buf, '.');
                               7916                 :                :     }
 7218                          7917         [ +  + ]:          97466 :     if (attname)
                               7918                 :          96706 :         appendStringInfoString(buf, quote_identifier(attname));
                               7919                 :                :     else
                               7920                 :                :     {
                               7921                 :            760 :         appendStringInfoChar(buf, '*');
 5328                          7922         [ +  + ]:            760 :         if (istoplevel)
                               7923                 :             56 :             appendStringInfo(buf, "::%s",
                               7924                 :                :                              format_type_with_typemod(var->vartype,
                               7925                 :                :                                                       var->vartypmod));
                               7926                 :                :     }
                               7927                 :                : 
 7218                          7928                 :          97466 :     return attname;
                               7929                 :                : }
                               7930                 :                : 
                               7931                 :                : /*
                               7932                 :                :  * Deparse a Var which references OUTER_VAR, INNER_VAR, or INDEX_VAR.  This
                               7933                 :                :  * routine is actually a callback for resolve_special_varno, which handles
                               7934                 :                :  * finding the correct TargetEntry.  We get the expression contained in that
                               7935                 :                :  * TargetEntry and just need to deparse it, a job we can throw back on
                               7936                 :                :  * get_rule_expr.
                               7937                 :                :  */
                               7938                 :                : static void
 2544                          7939                 :          39426 : get_special_variable(Node *node, deparse_context *context, void *callback_arg)
                               7940                 :                : {
 3867 rhaas@postgresql.org     7941                 :          39426 :     StringInfo  buf = context->buf;
                               7942                 :                : 
                               7943                 :                :     /*
                               7944                 :                :      * For a non-Var referent, force parentheses because our caller probably
                               7945                 :                :      * assumed a Var is a simple expression.
                               7946                 :                :      */
                               7947         [ +  + ]:          39426 :     if (!IsA(node, Var))
                               7948                 :           4508 :         appendStringInfoChar(buf, '(');
                               7949                 :          39426 :     get_rule_expr(node, context, true);
                               7950         [ +  + ]:          39426 :     if (!IsA(node, Var))
                               7951                 :           4508 :         appendStringInfoChar(buf, ')');
                               7952                 :          39426 : }
                               7953                 :                : 
                               7954                 :                : /*
                               7955                 :                :  * Chase through plan references to special varnos (OUTER_VAR, INNER_VAR,
                               7956                 :                :  * INDEX_VAR) until we find a real Var or some kind of non-Var node; then,
                               7957                 :                :  * invoke the callback provided.
                               7958                 :                :  */
                               7959                 :                : static void
 2544 tgl@sss.pgh.pa.us        7960                 :         111210 : resolve_special_varno(Node *node, deparse_context *context,
                               7961                 :                :                       rsv_callback callback, void *callback_arg)
                               7962                 :                : {
                               7963                 :                :     Var        *var;
                               7964                 :                :     deparse_namespace *dpns;
                               7965                 :                : 
                               7966                 :                :     /* This function is recursive, so let's be paranoid. */
                               7967                 :         111210 :     check_stack_depth();
                               7968                 :                : 
                               7969                 :                :     /* If it's not a Var, invoke the callback. */
 3867 rhaas@postgresql.org     7970         [ +  + ]:         111210 :     if (!IsA(node, Var))
                               7971                 :                :     {
 2544 tgl@sss.pgh.pa.us        7972                 :           5096 :         (*callback) (node, context, callback_arg);
 3867 rhaas@postgresql.org     7973                 :           5096 :         return;
                               7974                 :                :     }
                               7975                 :                : 
                               7976                 :                :     /* Find appropriate nesting depth */
                               7977                 :         106114 :     var = (Var *) node;
                               7978                 :         106114 :     dpns = (deparse_namespace *) list_nth(context->namespaces,
                               7979                 :         106114 :                                           var->varlevelsup);
                               7980                 :                : 
                               7981                 :                :     /*
                               7982                 :                :      * If varno is special, recurse.  (Don't worry about varnosyn; if we're
                               7983                 :                :      * here, we already decided not to use that.)
                               7984                 :                :      */
                               7985   [ +  +  +  - ]:         106114 :     if (var->varno == OUTER_VAR && dpns->outer_tlist)
                               7986                 :                :     {
                               7987                 :                :         TargetEntry *tle;
                               7988                 :                :         deparse_namespace save_dpns;
                               7989                 :                :         Bitmapset  *save_appendparents;
                               7990                 :                : 
                               7991                 :          53989 :         tle = get_tle_by_resno(dpns->outer_tlist, var->varattno);
                               7992         [ -  + ]:          53989 :         if (!tle)
 3867 rhaas@postgresql.org     7993         [ #  # ]:UBC           0 :             elog(ERROR, "bogus varattno for OUTER_VAR var: %d", var->varattno);
                               7994                 :                : 
                               7995                 :                :         /*
                               7996                 :                :          * If we're descending to the first child of an Append or MergeAppend,
                               7997                 :                :          * update appendparents.  This will affect deparsing of all Vars
                               7998                 :                :          * appearing within the eventually-resolved subexpression.
                               7999                 :                :          */
 2544 tgl@sss.pgh.pa.us        8000                 :CBC       53989 :         save_appendparents = context->appendparents;
                               8001                 :                : 
                               8002         [ +  + ]:          53989 :         if (IsA(dpns->plan, Append))
                               8003                 :           3159 :             context->appendparents = bms_union(context->appendparents,
                               8004                 :           3159 :                                                ((Append *) dpns->plan)->apprelids);
                               8005         [ +  + ]:          50830 :         else if (IsA(dpns->plan, MergeAppend))
                               8006                 :            464 :             context->appendparents = bms_union(context->appendparents,
                               8007                 :            464 :                                                ((MergeAppend *) dpns->plan)->apprelids);
                               8008                 :                : 
                               8009                 :          53989 :         push_child_plan(dpns, dpns->outer_plan, &save_dpns);
                               8010                 :          53989 :         resolve_special_varno((Node *) tle->expr, context,
                               8011                 :                :                               callback, callback_arg);
 3867 rhaas@postgresql.org     8012                 :          53989 :         pop_child_plan(dpns, &save_dpns);
 2544 tgl@sss.pgh.pa.us        8013                 :          53989 :         context->appendparents = save_appendparents;
 3867 rhaas@postgresql.org     8014                 :          53989 :         return;
                               8015                 :                :     }
                               8016   [ +  +  +  - ]:          52125 :     else if (var->varno == INNER_VAR && dpns->inner_tlist)
                               8017                 :                :     {
                               8018                 :                :         TargetEntry *tle;
                               8019                 :                :         deparse_namespace save_dpns;
                               8020                 :                : 
                               8021                 :          13371 :         tle = get_tle_by_resno(dpns->inner_tlist, var->varattno);
                               8022         [ -  + ]:          13371 :         if (!tle)
 3867 rhaas@postgresql.org     8023         [ #  # ]:UBC           0 :             elog(ERROR, "bogus varattno for INNER_VAR var: %d", var->varattno);
                               8024                 :                : 
 2544 tgl@sss.pgh.pa.us        8025                 :CBC       13371 :         push_child_plan(dpns, dpns->inner_plan, &save_dpns);
                               8026                 :          13371 :         resolve_special_varno((Node *) tle->expr, context,
                               8027                 :                :                               callback, callback_arg);
 3867 rhaas@postgresql.org     8028                 :          13371 :         pop_child_plan(dpns, &save_dpns);
                               8029                 :          13371 :         return;
                               8030                 :                :     }
                               8031   [ +  +  +  - ]:          38754 :     else if (var->varno == INDEX_VAR && dpns->index_tlist)
                               8032                 :                :     {
                               8033                 :                :         TargetEntry *tle;
                               8034                 :                : 
                               8035                 :           3836 :         tle = get_tle_by_resno(dpns->index_tlist, var->varattno);
                               8036         [ -  + ]:           3836 :         if (!tle)
 3867 rhaas@postgresql.org     8037         [ #  # ]:UBC           0 :             elog(ERROR, "bogus varattno for INDEX_VAR var: %d", var->varattno);
                               8038                 :                : 
 2544 tgl@sss.pgh.pa.us        8039                 :CBC        3836 :         resolve_special_varno((Node *) tle->expr, context,
                               8040                 :                :                               callback, callback_arg);
 3867 rhaas@postgresql.org     8041                 :           3836 :         return;
                               8042                 :                :     }
                               8043   [ +  -  -  + ]:          34918 :     else if (var->varno < 1 || var->varno > list_length(dpns->rtable))
 3867 rhaas@postgresql.org     8044         [ #  # ]:UBC           0 :         elog(ERROR, "bogus varno: %d", var->varno);
                               8045                 :                : 
                               8046                 :                :     /* Not special.  Just invoke the callback. */
 2544 tgl@sss.pgh.pa.us        8047                 :CBC       34918 :     (*callback) (node, context, callback_arg);
                               8048                 :                : }
                               8049                 :                : 
                               8050                 :                : /*
                               8051                 :                :  * Get the name of a field of an expression of composite type.  The
                               8052                 :                :  * expression is usually a Var, but we handle other cases too.
                               8053                 :                :  *
                               8054                 :                :  * levelsup is an extra offset to interpret the Var's varlevelsup correctly.
                               8055                 :                :  *
                               8056                 :                :  * This is fairly straightforward when the expression has a named composite
                               8057                 :                :  * type; we need only look up the type in the catalogs.  However, the type
                               8058                 :                :  * could also be RECORD.  Since no actual table or view column is allowed to
                               8059                 :                :  * have type RECORD, a Var of type RECORD must refer to a JOIN or FUNCTION RTE
                               8060                 :                :  * or to a subquery output.  We drill down to find the ultimate defining
                               8061                 :                :  * expression and attempt to infer the field name from it.  We ereport if we
                               8062                 :                :  * can't determine the name.
                               8063                 :                :  *
                               8064                 :                :  * Similarly, a PARAM of type RECORD has to refer to some expression of
                               8065                 :                :  * a determinable composite type.
                               8066                 :                :  */
                               8067                 :                : static const char *
 7851                          8068                 :           1071 : get_name_for_var_field(Var *var, int fieldno,
                               8069                 :                :                        int levelsup, deparse_context *context)
                               8070                 :                : {
                               8071                 :                :     RangeTblEntry *rte;
                               8072                 :                :     AttrNumber  attnum;
                               8073                 :                :     int         netlevelsup;
                               8074                 :                :     deparse_namespace *dpns;
                               8075                 :                :     int         varno;
                               8076                 :                :     AttrNumber  varattno;
                               8077                 :                :     TupleDesc   tupleDesc;
                               8078                 :                :     Node       *expr;
                               8079                 :                : 
                               8080                 :                :     /*
                               8081                 :                :      * If it's a RowExpr that was expanded from a whole-row Var, use the
                               8082                 :                :      * column names attached to it.  (We could let get_expr_result_tupdesc()
                               8083                 :                :      * handle this, but it's much cheaper to just pull out the name we need.)
                               8084                 :                :      */
 6627                          8085         [ +  + ]:           1071 :     if (IsA(var, RowExpr))
                               8086                 :                :     {
 6379 bruce@momjian.us         8087                 :             24 :         RowExpr    *r = (RowExpr *) var;
                               8088                 :                : 
 6627 tgl@sss.pgh.pa.us        8089   [ +  -  +  - ]:             24 :         if (fieldno > 0 && fieldno <= list_length(r->colnames))
                               8090                 :             24 :             return strVal(list_nth(r->colnames, fieldno - 1));
                               8091                 :                :     }
                               8092                 :                : 
                               8093                 :                :     /*
                               8094                 :                :      * If it's a Param of type RECORD, try to find what the Param refers to.
                               8095                 :                :      */
 5561                          8096         [ +  + ]:           1047 :     if (IsA(var, Param))
                               8097                 :                :     {
                               8098                 :             12 :         Param      *param = (Param *) var;
                               8099                 :                :         ListCell   *ancestor_cell;
                               8100                 :                : 
                               8101                 :             12 :         expr = find_param_referent(param, context, &dpns, &ancestor_cell);
                               8102         [ +  - ]:             12 :         if (expr)
                               8103                 :                :         {
                               8104                 :                :             /* Found a match, so recurse to decipher the field name */
                               8105                 :                :             deparse_namespace save_dpns;
                               8106                 :                :             const char *result;
                               8107                 :                : 
                               8108                 :             12 :             push_ancestor_plan(dpns, ancestor_cell, &save_dpns);
                               8109                 :             12 :             result = get_name_for_var_field((Var *) expr, fieldno,
                               8110                 :                :                                             0, context);
                               8111                 :             12 :             pop_ancestor_plan(dpns, &save_dpns);
                               8112                 :             12 :             return result;
                               8113                 :                :         }
                               8114                 :                :     }
                               8115                 :                : 
                               8116                 :                :     /*
                               8117                 :                :      * If it's a Var of type RECORD, we have to find what the Var refers to;
                               8118                 :                :      * if not, we can use get_expr_result_tupdesc().
                               8119                 :                :      */
 7218                          8120         [ +  + ]:           1035 :     if (!IsA(var, Var) ||
                               8121         [ +  + ]:            961 :         var->vartype != RECORDOID)
                               8122                 :                :     {
 3320                          8123                 :            871 :         tupleDesc = get_expr_result_tupdesc((Node *) var, false);
                               8124                 :                :         /* Got the tupdesc, so we can extract the field name */
 7218                          8125   [ +  -  -  + ]:            871 :         Assert(fieldno >= 1 && fieldno <= tupleDesc->natts);
 3387 andres@anarazel.de       8126                 :            871 :         return NameStr(TupleDescAttr(tupleDesc, fieldno - 1)->attname);
                               8127                 :                :     }
                               8128                 :                : 
                               8129                 :                :     /* Find appropriate nesting depth */
 7218 tgl@sss.pgh.pa.us        8130                 :            164 :     netlevelsup = var->varlevelsup + levelsup;
                               8131         [ -  + ]:            164 :     if (netlevelsup >= list_length(context->namespaces))
 7218 tgl@sss.pgh.pa.us        8132         [ #  # ]:UBC           0 :         elog(ERROR, "bogus varlevelsup: %d offset %d",
                               8133                 :                :              var->varlevelsup, levelsup);
 7218 tgl@sss.pgh.pa.us        8134                 :CBC         164 :     dpns = (deparse_namespace *) list_nth(context->namespaces,
                               8135                 :                :                                           netlevelsup);
                               8136                 :                : 
                               8137                 :                :     /*
                               8138                 :                :      * If we have a syntactic referent for the Var, and we're working from a
                               8139                 :                :      * parse tree, prefer to use the syntactic referent.  Otherwise, fall back
                               8140                 :                :      * on the semantic referent.  (See comments in get_variable().)
                               8141                 :                :      */
 2515                          8142   [ +  +  +  + ]:            164 :     if (var->varnosyn > 0 && dpns->plan == NULL)
                               8143                 :                :     {
                               8144                 :             64 :         varno = var->varnosyn;
                               8145                 :             64 :         varattno = var->varattnosyn;
                               8146                 :                :     }
                               8147                 :                :     else
                               8148                 :                :     {
                               8149                 :            100 :         varno = var->varno;
                               8150                 :            100 :         varattno = var->varattno;
                               8151                 :                :     }
                               8152                 :                : 
                               8153                 :                :     /*
                               8154                 :                :      * Try to find the relevant RTE in this rtable.  In a plan tree, it's
                               8155                 :                :      * likely that varno is OUTER_VAR or INNER_VAR, in which case we must dig
                               8156                 :                :      * down into the subplans, or INDEX_VAR, which is resolved similarly.
                               8157                 :                :      *
                               8158                 :                :      * Note: unlike get_variable and resolve_special_varno, we need not worry
                               8159                 :                :      * about inheritance mapping: a child Var should have the same datatype as
                               8160                 :                :      * its parent, and here we're really only interested in the Var's type.
                               8161                 :                :      */
                               8162   [ +  +  +  - ]:            164 :     if (varno >= 1 && varno <= list_length(dpns->rtable))
                               8163                 :                :     {
                               8164                 :            112 :         rte = rt_fetch(varno, dpns->rtable);
                               8165                 :            112 :         attnum = varattno;
                               8166                 :                :     }
                               8167   [ +  +  +  - ]:             52 :     else if (varno == OUTER_VAR && dpns->outer_tlist)
                               8168                 :                :     {
                               8169                 :                :         TargetEntry *tle;
                               8170                 :                :         deparse_namespace save_dpns;
                               8171                 :                :         const char *result;
                               8172                 :                : 
                               8173                 :             40 :         tle = get_tle_by_resno(dpns->outer_tlist, varattno);
 7218                          8174         [ -  + ]:             40 :         if (!tle)
 2515 tgl@sss.pgh.pa.us        8175         [ #  # ]:UBC           0 :             elog(ERROR, "bogus varattno for OUTER_VAR var: %d", varattno);
                               8176                 :                : 
 7218 tgl@sss.pgh.pa.us        8177         [ -  + ]:CBC          40 :         Assert(netlevelsup == 0);
 2544                          8178                 :             40 :         push_child_plan(dpns, dpns->outer_plan, &save_dpns);
                               8179                 :                : 
 7218                          8180                 :             40 :         result = get_name_for_var_field((Var *) tle->expr, fieldno,
                               8181                 :                :                                         levelsup, context);
                               8182                 :                : 
 5982                          8183                 :             40 :         pop_child_plan(dpns, &save_dpns);
 7218                          8184                 :             40 :         return result;
                               8185                 :                :     }
 2515                          8186   [ +  -  +  - ]:             12 :     else if (varno == INNER_VAR && dpns->inner_tlist)
                               8187                 :                :     {
                               8188                 :                :         TargetEntry *tle;
                               8189                 :                :         deparse_namespace save_dpns;
                               8190                 :                :         const char *result;
                               8191                 :                : 
                               8192                 :             12 :         tle = get_tle_by_resno(dpns->inner_tlist, varattno);
 7218                          8193         [ -  + ]:             12 :         if (!tle)
 2515 tgl@sss.pgh.pa.us        8194         [ #  # ]:UBC           0 :             elog(ERROR, "bogus varattno for INNER_VAR var: %d", varattno);
                               8195                 :                : 
 7218 tgl@sss.pgh.pa.us        8196         [ -  + ]:CBC          12 :         Assert(netlevelsup == 0);
 2544                          8197                 :             12 :         push_child_plan(dpns, dpns->inner_plan, &save_dpns);
                               8198                 :                : 
 7218                          8199                 :             12 :         result = get_name_for_var_field((Var *) tle->expr, fieldno,
                               8200                 :                :                                         levelsup, context);
                               8201                 :                : 
 5982                          8202                 :             12 :         pop_child_plan(dpns, &save_dpns);
 7218                          8203                 :             12 :         return result;
                               8204                 :                :     }
 2515 tgl@sss.pgh.pa.us        8205   [ #  #  #  # ]:UBC           0 :     else if (varno == INDEX_VAR && dpns->index_tlist)
                               8206                 :                :     {
                               8207                 :                :         TargetEntry *tle;
                               8208                 :                :         const char *result;
                               8209                 :                : 
                               8210                 :              0 :         tle = get_tle_by_resno(dpns->index_tlist, varattno);
 5527                          8211         [ #  # ]:              0 :         if (!tle)
 2515                          8212         [ #  # ]:              0 :             elog(ERROR, "bogus varattno for INDEX_VAR var: %d", varattno);
                               8213                 :                : 
 5527                          8214         [ #  # ]:              0 :         Assert(netlevelsup == 0);
                               8215                 :                : 
                               8216                 :              0 :         result = get_name_for_var_field((Var *) tle->expr, fieldno,
                               8217                 :                :                                         levelsup, context);
                               8218                 :                : 
                               8219                 :              0 :         return result;
                               8220                 :                :     }
                               8221                 :                :     else
                               8222                 :                :     {
 2515                          8223         [ #  # ]:              0 :         elog(ERROR, "bogus varno: %d", varno);
                               8224                 :                :         return NULL;            /* keep compiler quiet */
                               8225                 :                :     }
                               8226                 :                : 
 7851 tgl@sss.pgh.pa.us        8227         [ +  + ]:CBC         112 :     if (attnum == InvalidAttrNumber)
                               8228                 :                :     {
                               8229                 :                :         /* Var is whole-row reference to RTE, so select the right field */
                               8230                 :             16 :         return get_rte_attribute_name(rte, fieldno);
                               8231                 :                :     }
                               8232                 :                : 
                               8233                 :                :     /*
                               8234                 :                :      * This part has essentially the same logic as the parser's
                               8235                 :                :      * expandRecordVariable() function, but we are dealing with a different
                               8236                 :                :      * representation of the input context, and we only need one field name
                               8237                 :                :      * not a TupleDesc.  Also, we need special cases for finding subquery and
                               8238                 :                :      * CTE subplans when deparsing Plan trees.
                               8239                 :                :      */
                               8240                 :             96 :     expr = (Node *) var;        /* default if we can't drill down */
                               8241                 :                : 
                               8242   [ -  +  -  -  :             96 :     switch (rte->rtekind)
                                           +  -  - ]
                               8243                 :                :     {
 7851 tgl@sss.pgh.pa.us        8244                 :UBC           0 :         case RTE_RELATION:
                               8245                 :                :         case RTE_VALUES:
                               8246                 :                :         case RTE_NAMEDTUPLESTORE:
                               8247                 :                :         case RTE_RESULT:
                               8248                 :                : 
                               8249                 :                :             /*
                               8250                 :                :              * This case should not occur: a column of a table, values list,
                               8251                 :                :              * or ENR shouldn't have type RECORD.  Fall through and fail (most
                               8252                 :                :              * likely) at the bottom.
                               8253                 :                :              */
                               8254                 :              0 :             break;
 7851 tgl@sss.pgh.pa.us        8255                 :CBC          48 :         case RTE_SUBQUERY:
                               8256                 :                :             /* Subselect-in-FROM: examine sub-select's output expr */
                               8257                 :                :             {
 7218                          8258         [ +  + ]:             48 :                 if (rte->subquery)
                               8259                 :                :                 {
                               8260                 :             28 :                     TargetEntry *ste = get_tle_by_resno(rte->subquery->targetList,
                               8261                 :                :                                                         attnum);
                               8262                 :                : 
                               8263   [ +  -  -  + ]:             28 :                     if (ste == NULL || ste->resjunk)
 7218 tgl@sss.pgh.pa.us        8264         [ #  # ]:UBC           0 :                         elog(ERROR, "subquery %s does not have attribute %d",
                               8265                 :                :                              rte->eref->aliasname, attnum);
 7218 tgl@sss.pgh.pa.us        8266                 :CBC          28 :                     expr = (Node *) ste->expr;
                               8267         [ +  + ]:             28 :                     if (IsA(expr, Var))
                               8268                 :                :                     {
                               8269                 :                :                         /*
                               8270                 :                :                          * Recurse into the sub-select to see what its Var
                               8271                 :                :                          * refers to. We have to build an additional level of
                               8272                 :                :                          * namespace to keep in step with varlevelsup in the
                               8273                 :                :                          * subselect; furthermore, the subquery RTE might be
                               8274                 :                :                          * from an outer query level, in which case the
                               8275                 :                :                          * namespace for the subselect must have that outer
                               8276                 :                :                          * level as parent namespace.
                               8277                 :                :                          */
 1170                          8278                 :             12 :                         List       *save_nslist = context->namespaces;
                               8279                 :                :                         List       *parent_namespaces;
                               8280                 :                :                         deparse_namespace mydpns;
                               8281                 :                :                         const char *result;
                               8282                 :                : 
                               8283                 :             12 :                         parent_namespaces = list_copy_tail(context->namespaces,
                               8284                 :                :                                                            netlevelsup);
                               8285                 :                : 
 5080                          8286                 :             12 :                         set_deparse_for_query(&mydpns, rte->subquery,
                               8287                 :                :                                               parent_namespaces);
                               8288                 :                : 
 1170                          8289                 :             12 :                         context->namespaces = lcons(&mydpns, parent_namespaces);
                               8290                 :                : 
 7218                          8291                 :             12 :                         result = get_name_for_var_field((Var *) expr, fieldno,
                               8292                 :                :                                                         0, context);
                               8293                 :                : 
 1170                          8294                 :             12 :                         context->namespaces = save_nslist;
                               8295                 :                : 
 7218                          8296                 :             12 :                         return result;
                               8297                 :                :                     }
                               8298                 :                :                     /* else fall through to inspect the expression */
                               8299                 :                :                 }
                               8300                 :                :                 else
                               8301                 :                :                 {
                               8302                 :                :                     /*
                               8303                 :                :                      * We're deparsing a Plan tree so we don't have complete
                               8304                 :                :                      * RTE entries (in particular, rte->subquery is NULL). But
                               8305                 :                :                      * the only place we'd normally see a Var directly
                               8306                 :                :                      * referencing a SUBQUERY RTE is in a SubqueryScan plan
                               8307                 :                :                      * node, and we can look into the child plan's tlist
                               8308                 :                :                      * instead.  An exception occurs if the subquery was
                               8309                 :                :                      * proven empty and optimized away: then we'd find such a
                               8310                 :                :                      * Var in a childless Result node, and there's nothing in
                               8311                 :                :                      * the plan tree that would let us figure out what it had
                               8312                 :                :                      * originally referenced.  In that case, fall back on
                               8313                 :                :                      * printing "fN", analogously to the default column names
                               8314                 :                :                      * for RowExprs.
                               8315                 :                :                      */
                               8316                 :                :                     TargetEntry *tle;
                               8317                 :                :                     deparse_namespace save_dpns;
                               8318                 :                :                     const char *result;
                               8319                 :                : 
 2544                          8320         [ +  + ]:             20 :                     if (!dpns->inner_plan)
                               8321                 :                :                     {
  841                          8322                 :              8 :                         char       *dummy_name = palloc(32);
                               8323                 :                : 
  839                          8324   [ +  -  -  + ]:              8 :                         Assert(dpns->plan && IsA(dpns->plan, Result));
  841                          8325                 :              8 :                         snprintf(dummy_name, 32, "f%d", fieldno);
                               8326                 :              8 :                         return dummy_name;
                               8327                 :                :                     }
  839                          8328   [ +  -  -  + ]:             12 :                     Assert(dpns->plan && IsA(dpns->plan, SubqueryScan));
                               8329                 :                : 
 5527                          8330                 :             12 :                     tle = get_tle_by_resno(dpns->inner_tlist, attnum);
 7218                          8331         [ -  + ]:             12 :                     if (!tle)
 7218 tgl@sss.pgh.pa.us        8332         [ #  # ]:UBC           0 :                         elog(ERROR, "bogus varattno for subquery var: %d",
                               8333                 :                :                              attnum);
 7218 tgl@sss.pgh.pa.us        8334         [ -  + ]:CBC          12 :                     Assert(netlevelsup == 0);
 2544                          8335                 :             12 :                     push_child_plan(dpns, dpns->inner_plan, &save_dpns);
                               8336                 :                : 
 7218                          8337                 :             12 :                     result = get_name_for_var_field((Var *) tle->expr, fieldno,
                               8338                 :                :                                                     levelsup, context);
                               8339                 :                : 
 5982                          8340                 :             12 :                     pop_child_plan(dpns, &save_dpns);
 7851                          8341                 :             12 :                     return result;
                               8342                 :                :                 }
                               8343                 :                :             }
                               8344                 :             16 :             break;
 7851 tgl@sss.pgh.pa.us        8345                 :UBC           0 :         case RTE_JOIN:
                               8346                 :                :             /* Join RTE --- recursively inspect the alias variable */
 7128                          8347         [ #  # ]:              0 :             if (rte->joinaliasvars == NIL)
                               8348         [ #  # ]:              0 :                 elog(ERROR, "cannot decompile join alias var in plan tree");
 7851                          8349   [ #  #  #  # ]:              0 :             Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
                               8350                 :              0 :             expr = (Node *) list_nth(rte->joinaliasvars, attnum - 1);
 4876                          8351         [ #  # ]:              0 :             Assert(expr != NULL);
                               8352                 :                :             /* we intentionally don't strip implicit coercions here */
 7851                          8353         [ #  # ]:              0 :             if (IsA(expr, Var))
                               8354                 :              0 :                 return get_name_for_var_field((Var *) expr, fieldno,
                               8355                 :              0 :                                               var->varlevelsup + levelsup,
                               8356                 :                :                                               context);
                               8357                 :                :             /* else fall through to inspect the expression */
                               8358                 :              0 :             break;
                               8359                 :              0 :         case RTE_FUNCTION:
                               8360                 :                :         case RTE_TABLEFUNC:
                               8361                 :                : 
                               8362                 :                :             /*
                               8363                 :                :              * We couldn't get here unless a function is declared with one of
                               8364                 :                :              * its result columns as RECORD, which is not allowed.
                               8365                 :                :              */
                               8366                 :              0 :             break;
 6629 tgl@sss.pgh.pa.us        8367                 :CBC          48 :         case RTE_CTE:
                               8368                 :                :             /* CTE reference: examine subquery's output expr */
                               8369                 :                :             {
 6627                          8370                 :             48 :                 CommonTableExpr *cte = NULL;
                               8371                 :                :                 Index       ctelevelsup;
                               8372                 :                :                 ListCell   *lc;
                               8373                 :                : 
                               8374                 :                :                 /*
                               8375                 :                :                  * Try to find the referenced CTE using the namespace stack.
                               8376                 :                :                  */
                               8377                 :             48 :                 ctelevelsup = rte->ctelevelsup + netlevelsup;
                               8378         [ +  + ]:             48 :                 if (ctelevelsup >= list_length(context->namespaces))
                               8379                 :              8 :                     lc = NULL;
                               8380                 :                :                 else
                               8381                 :                :                 {
                               8382                 :                :                     deparse_namespace *ctedpns;
                               8383                 :                : 
                               8384                 :                :                     ctedpns = (deparse_namespace *)
                               8385                 :             40 :                         list_nth(context->namespaces, ctelevelsup);
                               8386   [ +  +  +  -  :             44 :                     foreach(lc, ctedpns->ctes)
                                              +  + ]
                               8387                 :                :                     {
                               8388                 :             24 :                         cte = (CommonTableExpr *) lfirst(lc);
                               8389         [ +  + ]:             24 :                         if (strcmp(cte->ctename, rte->ctename) == 0)
                               8390                 :             20 :                             break;
                               8391                 :                :                     }
                               8392                 :                :                 }
                               8393         [ +  + ]:             48 :                 if (lc != NULL)
                               8394                 :                :                 {
                               8395                 :             20 :                     Query      *ctequery = (Query *) cte->ctequery;
 5711 bruce@momjian.us         8396   [ -  +  +  - ]:             20 :                     TargetEntry *ste = get_tle_by_resno(GetCTETargetList(cte),
                               8397                 :                :                                                         attnum);
                               8398                 :                : 
 6627 tgl@sss.pgh.pa.us        8399   [ +  -  -  + ]:             20 :                     if (ste == NULL || ste->resjunk)
 1170 tgl@sss.pgh.pa.us        8400         [ #  # ]:UBC           0 :                         elog(ERROR, "CTE %s does not have attribute %d",
                               8401                 :                :                              rte->eref->aliasname, attnum);
 6627 tgl@sss.pgh.pa.us        8402                 :CBC          20 :                     expr = (Node *) ste->expr;
                               8403         [ +  + ]:             20 :                     if (IsA(expr, Var))
                               8404                 :                :                     {
                               8405                 :                :                         /*
                               8406                 :                :                          * Recurse into the CTE to see what its Var refers to.
                               8407                 :                :                          * We have to build an additional level of namespace
                               8408                 :                :                          * to keep in step with varlevelsup in the CTE;
                               8409                 :                :                          * furthermore it could be an outer CTE (compare
                               8410                 :                :                          * SUBQUERY case above).
                               8411                 :                :                          */
                               8412                 :             12 :                         List       *save_nslist = context->namespaces;
                               8413                 :                :                         List       *parent_namespaces;
                               8414                 :                :                         deparse_namespace mydpns;
                               8415                 :                :                         const char *result;
                               8416                 :                : 
 1170                          8417                 :             12 :                         parent_namespaces = list_copy_tail(context->namespaces,
                               8418                 :                :                                                            ctelevelsup);
                               8419                 :                : 
 5080                          8420                 :             12 :                         set_deparse_for_query(&mydpns, ctequery,
                               8421                 :                :                                               parent_namespaces);
                               8422                 :                : 
 1170                          8423                 :             12 :                         context->namespaces = lcons(&mydpns, parent_namespaces);
                               8424                 :                : 
 6627                          8425                 :             12 :                         result = get_name_for_var_field((Var *) expr, fieldno,
                               8426                 :                :                                                         0, context);
                               8427                 :                : 
                               8428                 :             12 :                         context->namespaces = save_nslist;
                               8429                 :                : 
                               8430                 :             12 :                         return result;
                               8431                 :                :                     }
                               8432                 :                :                     /* else fall through to inspect the expression */
                               8433                 :                :                 }
                               8434                 :                :                 else
                               8435                 :                :                 {
                               8436                 :                :                     /*
                               8437                 :                :                      * We're deparsing a Plan tree so we don't have a CTE
                               8438                 :                :                      * list.  But the only places we'd normally see a Var
                               8439                 :                :                      * directly referencing a CTE RTE are in CteScan or
                               8440                 :                :                      * WorkTableScan plan nodes.  For those cases,
                               8441                 :                :                      * set_deparse_plan arranged for dpns->inner_plan to be
                               8442                 :                :                      * the plan node that emits the CTE or RecursiveUnion
                               8443                 :                :                      * result, and we can look at its tlist instead.  As
                               8444                 :                :                      * above, this can fail if the CTE has been proven empty,
                               8445                 :                :                      * in which case fall back to "fN".
                               8446                 :                :                      */
                               8447                 :                :                     TargetEntry *tle;
                               8448                 :                :                     deparse_namespace save_dpns;
                               8449                 :                :                     const char *result;
                               8450                 :                : 
 2544                          8451         [ +  + ]:             28 :                     if (!dpns->inner_plan)
                               8452                 :                :                     {
  841                          8453                 :              4 :                         char       *dummy_name = palloc(32);
                               8454                 :                : 
  839                          8455   [ +  -  -  + ]:              4 :                         Assert(dpns->plan && IsA(dpns->plan, Result));
  841                          8456                 :              4 :                         snprintf(dummy_name, 32, "f%d", fieldno);
                               8457                 :              4 :                         return dummy_name;
                               8458                 :                :                     }
  839                          8459   [ +  -  +  +  :             24 :                     Assert(dpns->plan && (IsA(dpns->plan, CteScan) ||
                                              -  + ]
                               8460                 :                :                                           IsA(dpns->plan, WorkTableScan)));
                               8461                 :                : 
 5527                          8462                 :             24 :                     tle = get_tle_by_resno(dpns->inner_tlist, attnum);
 6627                          8463         [ -  + ]:             24 :                     if (!tle)
 6627 tgl@sss.pgh.pa.us        8464         [ #  # ]:UBC           0 :                         elog(ERROR, "bogus varattno for subquery var: %d",
                               8465                 :                :                              attnum);
 6627 tgl@sss.pgh.pa.us        8466         [ -  + ]:CBC          24 :                     Assert(netlevelsup == 0);
 2544                          8467                 :             24 :                     push_child_plan(dpns, dpns->inner_plan, &save_dpns);
                               8468                 :                : 
 6627                          8469                 :             24 :                     result = get_name_for_var_field((Var *) tle->expr, fieldno,
                               8470                 :                :                                                     levelsup, context);
                               8471                 :                : 
 5982                          8472                 :             24 :                     pop_child_plan(dpns, &save_dpns);
 6627                          8473                 :             24 :                     return result;
                               8474                 :                :                 }
                               8475                 :                :             }
 6629                          8476                 :              8 :             break;
  809 rguo@postgresql.org      8477                 :UBC           0 :         case RTE_GROUP:
                               8478                 :                : 
                               8479                 :                :             /*
                               8480                 :                :              * We couldn't get here: any Vars that reference the RTE_GROUP RTE
                               8481                 :                :              * should have been replaced with the underlying grouping
                               8482                 :                :              * expressions.
                               8483                 :                :              */
                               8484                 :              0 :             break;
                               8485                 :                :     }
                               8486                 :                : 
                               8487                 :                :     /*
                               8488                 :                :      * We now have an expression we can't expand any more, so see if
                               8489                 :                :      * get_expr_result_tupdesc() can do anything with it.
                               8490                 :                :      */
 3320 tgl@sss.pgh.pa.us        8491                 :CBC          24 :     tupleDesc = get_expr_result_tupdesc(expr, false);
                               8492                 :                :     /* Got the tupdesc, so we can extract the field name */
 7851                          8493   [ +  -  -  + ]:             24 :     Assert(fieldno >= 1 && fieldno <= tupleDesc->natts);
 3387 andres@anarazel.de       8494                 :             24 :     return NameStr(TupleDescAttr(tupleDesc, fieldno - 1)->attname);
                               8495                 :                : }
                               8496                 :                : 
                               8497                 :                : /*
                               8498                 :                :  * Try to find the referenced expression for a PARAM_EXEC Param that might
                               8499                 :                :  * reference a parameter supplied by an upper NestLoop or SubPlan plan node.
                               8500                 :                :  *
                               8501                 :                :  * If successful, return the expression and set *dpns_p and *ancestor_cell_p
                               8502                 :                :  * appropriately for calling push_ancestor_plan().  If no referent can be
                               8503                 :                :  * found, return NULL.
                               8504                 :                :  */
                               8505                 :                : static Node *
 5561 tgl@sss.pgh.pa.us        8506                 :           5760 : find_param_referent(Param *param, deparse_context *context,
                               8507                 :                :                     deparse_namespace **dpns_p, ListCell **ancestor_cell_p)
                               8508                 :                : {
                               8509                 :                :     /* Initialize output parameters to prevent compiler warnings */
                               8510                 :           5760 :     *dpns_p = NULL;
                               8511                 :           5760 :     *ancestor_cell_p = NULL;
                               8512                 :                : 
                               8513                 :                :     /*
                               8514                 :                :      * If it's a PARAM_EXEC parameter, look for a matching NestLoopParam or
                               8515                 :                :      * SubPlan argument.  This will necessarily be in some ancestor of the
                               8516                 :                :      * current expression's Plan node.
                               8517                 :                :      */
 5982                          8518         [ +  + ]:           5760 :     if (param->paramkind == PARAM_EXEC)
                               8519                 :                :     {
                               8520                 :                :         deparse_namespace *dpns;
                               8521                 :                :         Plan       *child_plan;
                               8522                 :                :         ListCell   *lc;
                               8523                 :                : 
                               8524                 :           5140 :         dpns = (deparse_namespace *) linitial(context->namespaces);
 2544                          8525                 :           5140 :         child_plan = dpns->plan;
                               8526                 :                : 
 5982                          8527   [ +  +  +  +  :           9162 :         foreach(lc, dpns->ancestors)
                                              +  + ]
                               8528                 :                :         {
 2544                          8529                 :           7971 :             Node       *ancestor = (Node *) lfirst(lc);
                               8530                 :                :             ListCell   *lc2;
                               8531                 :                : 
                               8532                 :                :             /*
                               8533                 :                :              * NestLoops transmit params to their inner child only.
                               8534                 :                :              */
                               8535         [ +  + ]:           7971 :             if (IsA(ancestor, NestLoop) &&
 1473                          8536         [ +  + ]:           3734 :                 child_plan == innerPlan(ancestor))
                               8537                 :                :             {
 2544                          8538                 :           3588 :                 NestLoop   *nl = (NestLoop *) ancestor;
                               8539                 :                : 
 5982                          8540   [ +  +  +  +  :           4439 :                 foreach(lc2, nl->nestParams)
                                              +  + ]
                               8541                 :                :                 {
 5711 bruce@momjian.us         8542                 :           4238 :                     NestLoopParam *nlp = (NestLoopParam *) lfirst(lc2);
                               8543                 :                : 
 5982 tgl@sss.pgh.pa.us        8544         [ +  + ]:           4238 :                     if (nlp->paramno == param->paramid)
                               8545                 :                :                     {
                               8546                 :                :                         /* Found a match, so return it */
 5561                          8547                 :           3387 :                         *dpns_p = dpns;
                               8548                 :           3387 :                         *ancestor_cell_p = lc;
                               8549                 :           3387 :                         return (Node *) nlp->paramval;
                               8550                 :                :                     }
                               8551                 :                :                 }
                               8552                 :                :             }
                               8553                 :                : 
                               8554                 :                :             /*
                               8555                 :                :              * If ancestor is a SubPlan, check the arguments it provides.
                               8556                 :                :              */
 2544                          8557         [ +  + ]:           4584 :             if (IsA(ancestor, SubPlan))
 5982                          8558                 :            345 :             {
 2544                          8559                 :            907 :                 SubPlan    *subplan = (SubPlan *) ancestor;
                               8560                 :                :                 ListCell   *lc3;
                               8561                 :                :                 ListCell   *lc4;
                               8562                 :                : 
 5982                          8563   [ +  +  +  +  :           1154 :                 forboth(lc3, subplan->parParam, lc4, subplan->args)
                                     +  +  +  +  +  
                                        +  +  -  +  
                                                 + ]
                               8564                 :                :                 {
 5711 bruce@momjian.us         8565                 :            809 :                     int         paramid = lfirst_int(lc3);
                               8566                 :            809 :                     Node       *arg = (Node *) lfirst(lc4);
                               8567                 :                : 
 5982 tgl@sss.pgh.pa.us        8568         [ +  + ]:            809 :                     if (paramid == param->paramid)
                               8569                 :                :                     {
                               8570                 :                :                         /*
                               8571                 :                :                          * Found a match, so return it.  But, since Vars in
                               8572                 :                :                          * the arg are to be evaluated in the surrounding
                               8573                 :                :                          * context, we have to point to the next ancestor item
                               8574                 :                :                          * that is *not* a SubPlan.
                               8575                 :                :                          */
                               8576                 :                :                         ListCell   *rest;
                               8577                 :                : 
 2544                          8578   [ +  -  +  -  :            562 :                         for_each_cell(rest, dpns->ancestors,
                                              +  - ]
                               8579                 :                :                                       lnext(dpns->ancestors, lc))
                               8580                 :                :                         {
                               8581                 :            562 :                             Node       *ancestor2 = (Node *) lfirst(rest);
                               8582                 :                : 
                               8583         [ +  - ]:            562 :                             if (!IsA(ancestor2, SubPlan))
                               8584                 :                :                             {
                               8585                 :            562 :                                 *dpns_p = dpns;
                               8586                 :            562 :                                 *ancestor_cell_p = rest;
                               8587                 :            562 :                                 return arg;
                               8588                 :                :                             }
                               8589                 :                :                         }
 2544 tgl@sss.pgh.pa.us        8590         [ #  # ]:UBC           0 :                         elog(ERROR, "SubPlan cannot be outermost ancestor");
                               8591                 :                :                     }
                               8592                 :                :                 }
                               8593                 :                : 
                               8594                 :                :                 /* SubPlan isn't a kind of Plan, so skip the rest */
 2544 tgl@sss.pgh.pa.us        8595                 :CBC         345 :                 continue;
                               8596                 :                :             }
                               8597                 :                : 
                               8598                 :                :             /*
                               8599                 :                :              * We need not consider the ancestor's initPlan list, since
                               8600                 :                :              * initplans never have any parParams.
                               8601                 :                :              */
                               8602                 :                : 
                               8603                 :                :             /* No luck, crawl up to next ancestor */
                               8604                 :           3677 :             child_plan = (Plan *) ancestor;
                               8605                 :                :         }
                               8606                 :                :     }
                               8607                 :                : 
                               8608                 :                :     /* No referent found */
 5561                          8609                 :           1811 :     return NULL;
                               8610                 :                : }
                               8611                 :                : 
                               8612                 :                : /*
                               8613                 :                :  * Try to find a subplan/initplan that emits the value for a PARAM_EXEC Param.
                               8614                 :                :  *
                               8615                 :                :  * If successful, return the generating subplan/initplan and set *column_p
                               8616                 :                :  * to the subplan's 0-based output column number.
                               8617                 :                :  * Otherwise, return NULL.
                               8618                 :                :  */
                               8619                 :                : static SubPlan *
  984                          8620                 :           1811 : find_param_generator(Param *param, deparse_context *context, int *column_p)
                               8621                 :                : {
                               8622                 :                :     /* Initialize output parameter to prevent compiler warnings */
                               8623                 :           1811 :     *column_p = 0;
                               8624                 :                : 
                               8625                 :                :     /*
                               8626                 :                :      * If it's a PARAM_EXEC parameter, search the current plan node as well as
                               8627                 :                :      * ancestor nodes looking for a subplan or initplan that emits the value
                               8628                 :                :      * for the Param.  It could appear in the setParams of an initplan or
                               8629                 :                :      * MULTIEXPR_SUBLINK subplan, or in the paramIds of an ancestral SubPlan.
                               8630                 :                :      */
                               8631         [ +  + ]:           1811 :     if (param->paramkind == PARAM_EXEC)
                               8632                 :                :     {
                               8633                 :                :         SubPlan    *result;
                               8634                 :                :         deparse_namespace *dpns;
                               8635                 :                :         ListCell   *lc;
                               8636                 :                : 
                               8637                 :           1191 :         dpns = (deparse_namespace *) linitial(context->namespaces);
                               8638                 :                : 
                               8639                 :                :         /* First check the innermost plan node's initplans */
                               8640                 :           1191 :         result = find_param_generator_initplan(param, dpns->plan, column_p);
                               8641         [ +  + ]:           1191 :         if (result)
                               8642                 :            308 :             return result;
                               8643                 :                : 
                               8644                 :                :         /*
                               8645                 :                :          * The plan's targetlist might contain MULTIEXPR_SUBLINK SubPlans,
                               8646                 :                :          * which can be referenced by Params elsewhere in the targetlist.
                               8647                 :                :          * (Such Params should always be in the same targetlist, so there's no
                               8648                 :                :          * need to do this work at upper plan nodes.)
                               8649                 :                :          */
                               8650   [ +  +  +  +  :           4447 :         foreach_node(TargetEntry, tle, dpns->plan->targetlist)
                                              +  + ]
                               8651                 :                :         {
                               8652   [ +  -  +  + ]:           2749 :             if (tle->expr && IsA(tle->expr, SubPlan))
                               8653                 :                :             {
                               8654                 :             66 :                 SubPlan    *subplan = (SubPlan *) tle->expr;
                               8655                 :                : 
                               8656         [ +  + ]:             66 :                 if (subplan->subLinkType == MULTIEXPR_SUBLINK)
                               8657                 :                :                 {
                               8658   [ +  -  +  -  :             51 :                     foreach_int(paramid, subplan->setParam)
                                              +  - ]
                               8659                 :                :                     {
                               8660         [ +  + ]:             51 :                         if (paramid == param->paramid)
                               8661                 :                :                         {
                               8662                 :                :                             /* Found a match, so return it. */
                               8663                 :             34 :                             *column_p = foreach_current_index(paramid);
                               8664                 :             34 :                             return subplan;
                               8665                 :                :                         }
                               8666                 :                :                     }
                               8667                 :                :                 }
                               8668                 :                :             }
                               8669                 :                :         }
                               8670                 :                : 
                               8671                 :                :         /* No luck, so check the ancestor nodes */
                               8672   [ +  -  +  -  :           1120 :         foreach(lc, dpns->ancestors)
                                              +  - ]
                               8673                 :                :         {
                               8674                 :           1120 :             Node       *ancestor = (Node *) lfirst(lc);
                               8675                 :                : 
                               8676                 :                :             /*
                               8677                 :                :              * If ancestor is a SubPlan, check the paramIds it provides.
                               8678                 :                :              */
                               8679         [ +  + ]:           1120 :             if (IsA(ancestor, SubPlan))
  984 tgl@sss.pgh.pa.us        8680                 :UBC           0 :             {
  984 tgl@sss.pgh.pa.us        8681                 :CBC         225 :                 SubPlan    *subplan = (SubPlan *) ancestor;
                               8682                 :                : 
                               8683   [ +  -  +  -  :            250 :                 foreach_int(paramid, subplan->paramIds)
                                              +  - ]
                               8684                 :                :                 {
                               8685         [ +  + ]:            250 :                     if (paramid == param->paramid)
                               8686                 :                :                     {
                               8687                 :                :                         /* Found a match, so return it. */
                               8688                 :            225 :                         *column_p = foreach_current_index(paramid);
                               8689                 :            225 :                         return subplan;
                               8690                 :                :                     }
                               8691                 :                :                 }
                               8692                 :                : 
                               8693                 :                :                 /* SubPlan isn't a kind of Plan, so skip the rest */
  984 tgl@sss.pgh.pa.us        8694                 :UBC           0 :                 continue;
                               8695                 :                :             }
                               8696                 :                : 
                               8697                 :                :             /*
                               8698                 :                :              * Otherwise, it's some kind of Plan node, so check its initplans.
                               8699                 :                :              */
  984 tgl@sss.pgh.pa.us        8700                 :CBC         895 :             result = find_param_generator_initplan(param, (Plan *) ancestor,
                               8701                 :                :                                                    column_p);
                               8702         [ +  + ]:            895 :             if (result)
                               8703                 :            624 :                 return result;
                               8704                 :                : 
                               8705                 :                :             /* No luck, crawl up to next ancestor */
                               8706                 :                :         }
                               8707                 :                :     }
                               8708                 :                : 
                               8709                 :                :     /* No generator found */
                               8710                 :            620 :     return NULL;
                               8711                 :                : }
                               8712                 :                : 
                               8713                 :                : /*
                               8714                 :                :  * Subroutine for find_param_generator: search one Plan node's initplans
                               8715                 :                :  */
                               8716                 :                : static SubPlan *
                               8717                 :           2086 : find_param_generator_initplan(Param *param, Plan *plan, int *column_p)
                               8718                 :                : {
                               8719   [ +  +  +  -  :           3340 :     foreach_node(SubPlan, subplan, plan->initPlan)
                                              +  + ]
                               8720                 :                :     {
                               8721   [ +  -  +  +  :           1236 :         foreach_int(paramid, subplan->setParam)
                                              +  + ]
                               8722                 :                :         {
                               8723         [ +  + ]:           1036 :             if (paramid == param->paramid)
                               8724                 :                :             {
                               8725                 :                :                 /* Found a match, so return it. */
                               8726                 :            932 :                 *column_p = foreach_current_index(paramid);
                               8727                 :            932 :                 return subplan;
                               8728                 :                :             }
                               8729                 :                :         }
                               8730                 :                :     }
                               8731                 :           1154 :     return NULL;
                               8732                 :                : }
                               8733                 :                : 
                               8734                 :                : /*
                               8735                 :                :  * Display a Param appropriately.
                               8736                 :                :  */
                               8737                 :                : static void
 5561                          8738                 :           5748 : get_parameter(Param *param, deparse_context *context)
                               8739                 :                : {
                               8740                 :                :     Node       *expr;
                               8741                 :                :     deparse_namespace *dpns;
                               8742                 :                :     ListCell   *ancestor_cell;
                               8743                 :                :     SubPlan    *subplan;
                               8744                 :                :     int         column;
                               8745                 :                : 
                               8746                 :                :     /*
                               8747                 :                :      * If it's a PARAM_EXEC parameter, try to locate the expression from which
                               8748                 :                :      * the parameter was computed.  This stanza handles only cases in which
                               8749                 :                :      * the Param represents an input to the subplan we are currently in.
                               8750                 :                :      */
                               8751                 :           5748 :     expr = find_param_referent(param, context, &dpns, &ancestor_cell);
                               8752         [ +  + ]:           5748 :     if (expr)
                               8753                 :                :     {
                               8754                 :                :         /* Found a match, so print it */
                               8755                 :                :         deparse_namespace save_dpns;
                               8756                 :                :         bool        save_varprefix;
                               8757                 :                :         bool        need_paren;
                               8758                 :                : 
                               8759                 :                :         /* Switch attention to the ancestor plan node */
                               8760                 :           3937 :         push_ancestor_plan(dpns, ancestor_cell, &save_dpns);
                               8761                 :                : 
                               8762                 :                :         /*
                               8763                 :                :          * Force prefixing of Vars, since they won't belong to the relation
                               8764                 :                :          * being scanned in the original plan node.
                               8765                 :                :          */
                               8766                 :           3937 :         save_varprefix = context->varprefix;
                               8767                 :           3937 :         context->varprefix = true;
                               8768                 :                : 
                               8769                 :                :         /*
                               8770                 :                :          * A Param's expansion is typically a Var, Aggref, GroupingFunc, or
                               8771                 :                :          * upper-level Param, which wouldn't need extra parentheses.
                               8772                 :                :          * Otherwise, insert parens to ensure the expression looks atomic.
                               8773                 :                :          */
                               8774         [ +  + ]:           3965 :         need_paren = !(IsA(expr, Var) ||
                               8775         [ +  + ]:             28 :                        IsA(expr, Aggref) ||
 1713                          8776         [ +  + ]:             20 :                        IsA(expr, GroupingFunc) ||
 5561                          8777         [ -  + ]:             16 :                        IsA(expr, Param));
                               8778         [ -  + ]:           3937 :         if (need_paren)
 5561 tgl@sss.pgh.pa.us        8779                 :UBC           0 :             appendStringInfoChar(context->buf, '(');
                               8780                 :                : 
 5561 tgl@sss.pgh.pa.us        8781                 :CBC        3937 :         get_rule_expr(expr, context, false);
                               8782                 :                : 
                               8783         [ -  + ]:           3937 :         if (need_paren)
 5561 tgl@sss.pgh.pa.us        8784                 :UBC           0 :             appendStringInfoChar(context->buf, ')');
                               8785                 :                : 
 5561 tgl@sss.pgh.pa.us        8786                 :CBC        3937 :         context->varprefix = save_varprefix;
                               8787                 :                : 
                               8788                 :           3937 :         pop_ancestor_plan(dpns, &save_dpns);
                               8789                 :                : 
                               8790                 :           3937 :         return;
                               8791                 :                :     }
                               8792                 :                : 
                               8793                 :                :     /*
                               8794                 :                :      * Alternatively, maybe it's a subplan output, which we print as a
                               8795                 :                :      * reference to the subplan.  (We could drill down into the subplan and
                               8796                 :                :      * print the relevant targetlist expression, but that has been deemed too
                               8797                 :                :      * confusing since it would violate normal SQL scope rules.  Also, we're
                               8798                 :                :      * relying on this reference to show that the testexpr containing the
                               8799                 :                :      * Param has anything to do with that subplan at all.)
                               8800                 :                :      */
  984                          8801                 :           1811 :     subplan = find_param_generator(param, context, &column);
                               8802         [ +  + ]:           1811 :     if (subplan)
                               8803                 :                :     {
                               8804                 :                :         const char *nameprefix;
                               8805                 :                : 
  417 rhaas@postgresql.org     8806         [ +  + ]:           1191 :         if (subplan->isInitPlan)
                               8807                 :            932 :             nameprefix = "InitPlan ";
                               8808                 :                :         else
                               8809                 :            259 :             nameprefix = "SubPlan ";
                               8810                 :                : 
                               8811                 :           1191 :         appendStringInfo(context->buf, "(%s%s%s).col%d",
  984 tgl@sss.pgh.pa.us        8812         [ +  + ]:           1191 :                          subplan->useHashTable ? "hashed " : "",
                               8813                 :                :                          nameprefix,
                               8814                 :                :                          subplan->plan_name, column + 1);
                               8815                 :                : 
                               8816                 :           1191 :         return;
                               8817                 :                :     }
                               8818                 :                : 
                               8819                 :                :     /*
                               8820                 :                :      * If it's an external parameter, see if the outermost namespace provides
                               8821                 :                :      * function argument names.
                               8822                 :                :      */
 1837                          8823   [ +  -  +  - ]:            620 :     if (param->paramkind == PARAM_EXTERN && context->namespaces != NIL)
                               8824                 :                :     {
                               8825                 :            620 :         dpns = llast(context->namespaces);
                               8826         [ +  + ]:            620 :         if (dpns->argnames &&
                               8827         [ +  - ]:             61 :             param->paramid > 0 &&
                               8828         [ +  - ]:             61 :             param->paramid <= dpns->numargs)
                               8829                 :                :         {
 2061 peter@eisentraut.org     8830                 :             61 :             char       *argname = dpns->argnames[param->paramid - 1];
                               8831                 :                : 
                               8832         [ +  + ]:             61 :             if (argname)
                               8833                 :                :             {
                               8834                 :             57 :                 bool        should_qualify = false;
                               8835                 :                :                 ListCell   *lc;
                               8836                 :                : 
                               8837                 :                :                 /*
                               8838                 :                :                  * Qualify the parameter name if there are any other deparse
                               8839                 :                :                  * namespaces with range tables.  This avoids qualifying in
                               8840                 :                :                  * trivial cases like "RETURN a + b", but makes it safe in all
                               8841                 :                :                  * other cases.
                               8842                 :                :                  */
                               8843   [ +  -  +  +  :            139 :                 foreach(lc, context->namespaces)
                                              +  + ]
                               8844                 :                :                 {
 1515 drowley@postgresql.o     8845                 :            102 :                     deparse_namespace *depns = lfirst(lc);
                               8846                 :                : 
                               8847         [ +  + ]:            102 :                     if (depns->rtable_names != NIL)
                               8848                 :                :                     {
 2061 peter@eisentraut.org     8849                 :             20 :                         should_qualify = true;
                               8850                 :             20 :                         break;
                               8851                 :                :                     }
                               8852                 :                :                 }
                               8853         [ +  + ]:             57 :                 if (should_qualify)
                               8854                 :                :                 {
                               8855                 :             20 :                     appendStringInfoString(context->buf, quote_identifier(dpns->funcname));
                               8856                 :             20 :                     appendStringInfoChar(context->buf, '.');
                               8857                 :                :                 }
                               8858                 :                : 
                               8859                 :             57 :                 appendStringInfoString(context->buf, quote_identifier(argname));
                               8860                 :             57 :                 return;
                               8861                 :                :             }
                               8862                 :                :         }
                               8863                 :                :     }
                               8864                 :                : 
                               8865                 :                :     /*
                               8866                 :                :      * Not PARAM_EXEC, or couldn't find referent: just print $N.
                               8867                 :                :      *
                               8868                 :                :      * It's a bug if we get here for anything except PARAM_EXTERN Params, but
                               8869                 :                :      * in production builds printing $N seems more useful than failing.
                               8870                 :                :      */
  984 tgl@sss.pgh.pa.us        8871         [ -  + ]:            563 :     Assert(param->paramkind == PARAM_EXTERN);
                               8872                 :                : 
 5561                          8873                 :            563 :     appendStringInfo(context->buf, "$%d", param->paramid);
                               8874                 :                : }
                               8875                 :                : 
                               8876                 :                : /*
                               8877                 :                :  * get_simple_binary_op_name
                               8878                 :                :  *
                               8879                 :                :  * helper function for isSimpleNode
                               8880                 :                :  * will return single char binary operator name, or NULL if it's not
                               8881                 :                :  */
                               8882                 :                : static const char *
 8513 bruce@momjian.us         8883                 :            100 : get_simple_binary_op_name(OpExpr *expr)
                               8884                 :                : {
 8522 tgl@sss.pgh.pa.us        8885                 :            100 :     List       *args = expr->args;
                               8886                 :                : 
 8217 neilc@samurai.com        8887         [ +  - ]:            100 :     if (list_length(args) == 2)
                               8888                 :                :     {
                               8889                 :                :         /* binary operator */
 8221                          8890                 :            100 :         Node       *arg1 = (Node *) linitial(args);
 8522 tgl@sss.pgh.pa.us        8891                 :            100 :         Node       *arg2 = (Node *) lsecond(args);
                               8892                 :                :         const char *op;
                               8893                 :                : 
                               8894                 :            100 :         op = generate_operator_name(expr->opno, exprType(arg1), exprType(arg2));
                               8895         [ +  - ]:            100 :         if (strlen(op) == 1)
 8517 bruce@momjian.us         8896                 :            100 :             return op;
                               8897                 :                :     }
 8522 tgl@sss.pgh.pa.us        8898                 :UBC           0 :     return NULL;
                               8899                 :                : }
                               8900                 :                : 
                               8901                 :                : 
                               8902                 :                : /*
                               8903                 :                :  * isSimpleNode - check if given node is simple (doesn't need parenthesizing)
                               8904                 :                :  *
                               8905                 :                :  *  true   : simple in the context of parent node's type
                               8906                 :                :  *  false  : not simple
                               8907                 :                :  */
                               8908                 :                : static bool
 8522 tgl@sss.pgh.pa.us        8909                 :CBC        3905 : isSimpleNode(Node *node, Node *parentNode, int prettyFlags)
                               8910                 :                : {
 8517 bruce@momjian.us         8911         [ -  + ]:           3905 :     if (!node)
 8522 tgl@sss.pgh.pa.us        8912                 :UBC           0 :         return false;
                               8913                 :                : 
 8517 bruce@momjian.us         8914   [ +  +  -  +  :CBC        3905 :     switch (nodeTag(node))
                                     -  +  +  +  -  
                                     -  -  +  +  +  
                                           +  +  + ]
                               8915                 :                :     {
 8522 tgl@sss.pgh.pa.us        8916                 :           3254 :         case T_Var:
                               8917                 :                :         case T_Const:
                               8918                 :                :         case T_Param:
                               8919                 :                :         case T_CoerceToDomainValue:
                               8920                 :                :         case T_SetToDefault:
                               8921                 :                :         case T_CurrentOfExpr:
                               8922                 :                :             /* single words: always simple */
                               8923                 :           3254 :             return true;
                               8924                 :                : 
 2857 alvherre@alvh.no-ip.     8925                 :            335 :         case T_SubscriptingRef:
                               8926                 :                :         case T_ArrayExpr:
                               8927                 :                :         case T_RowExpr:
                               8928                 :                :         case T_CoalesceExpr:
                               8929                 :                :         case T_MinMaxExpr:
                               8930                 :                :         case T_SQLValueFunction:
                               8931                 :                :         case T_NextValueExpr:
                               8932                 :                :         case T_NullIfExpr:
                               8933                 :                :         case T_Aggref:
                               8934                 :                :         case T_GroupingFunc:
                               8935                 :                :         case T_WindowFunc:
                               8936                 :                :         case T_MergeSupportFunc:
                               8937                 :                :         case T_FuncExpr:
                               8938                 :                :         case T_JsonConstructorExpr:
                               8939                 :                :         case T_JsonExpr:
                               8940                 :                :             /* function-like: name(..) or name[..] */
 8522 tgl@sss.pgh.pa.us        8941                 :            335 :             return true;
                               8942                 :                : 
                               8943                 :                :             /* CASE keywords act as parentheses */
 8522 tgl@sss.pgh.pa.us        8944                 :UBC           0 :         case T_CaseExpr:
                               8945                 :              0 :             return true;
                               8946                 :                : 
 8522 tgl@sss.pgh.pa.us        8947                 :CBC          48 :         case T_FieldSelect:
                               8948                 :                : 
                               8949                 :                :             /*
                               8950                 :                :              * appears simple since . has top precedence, unless parent is
                               8951                 :                :              * T_FieldSelect itself!
                               8952                 :                :              */
 1907 michael@paquier.xyz      8953                 :             48 :             return !IsA(parentNode, FieldSelect);
                               8954                 :                : 
 8207 tgl@sss.pgh.pa.us        8955                 :UBC           0 :         case T_FieldStore:
                               8956                 :                : 
                               8957                 :                :             /*
                               8958                 :                :              * treat like FieldSelect (probably doesn't matter)
                               8959                 :                :              */
 1907 michael@paquier.xyz      8960                 :              0 :             return !IsA(parentNode, FieldStore);
                               8961                 :                : 
 8522 tgl@sss.pgh.pa.us        8962                 :CBC          12 :         case T_CoerceToDomain:
                               8963                 :                :             /* maybe simple, check args */
 8517 bruce@momjian.us         8964                 :             12 :             return isSimpleNode((Node *) ((CoerceToDomain *) node)->arg,
                               8965                 :                :                                 node, prettyFlags);
 8522 tgl@sss.pgh.pa.us        8966                 :             12 :         case T_RelabelType:
 8517 bruce@momjian.us         8967                 :             12 :             return isSimpleNode((Node *) ((RelabelType *) node)->arg,
                               8968                 :                :                                 node, prettyFlags);
 7116 tgl@sss.pgh.pa.us        8969                 :             16 :         case T_CoerceViaIO:
                               8970                 :             16 :             return isSimpleNode((Node *) ((CoerceViaIO *) node)->arg,
                               8971                 :                :                                 node, prettyFlags);
 7186 tgl@sss.pgh.pa.us        8972                 :UBC           0 :         case T_ArrayCoerceExpr:
                               8973                 :              0 :             return isSimpleNode((Node *) ((ArrayCoerceExpr *) node)->arg,
                               8974                 :                :                                 node, prettyFlags);
 8022                          8975                 :              0 :         case T_ConvertRowtypeExpr:
                               8976                 :              0 :             return isSimpleNode((Node *) ((ConvertRowtypeExpr *) node)->arg,
                               8977                 :                :                                 node, prettyFlags);
  681 dean.a.rasheed@gmail     8978                 :              0 :         case T_ReturningExpr:
                               8979                 :              0 :             return isSimpleNode((Node *) ((ReturningExpr *) node)->retexpr,
                               8980                 :                :                                 node, prettyFlags);
                               8981                 :                : 
 8522 tgl@sss.pgh.pa.us        8982                 :CBC         184 :         case T_OpExpr:
                               8983                 :                :             {
                               8984                 :                :                 /* depends on parent node type; needs further checking */
 8517 bruce@momjian.us         8985   [ +  -  +  + ]:            184 :                 if (prettyFlags & PRETTYFLAG_PAREN && IsA(parentNode, OpExpr))
                               8986                 :                :                 {
                               8987                 :                :                     const char *op;
                               8988                 :                :                     const char *parentOp;
                               8989                 :                :                     bool        is_lopriop;
                               8990                 :                :                     bool        is_hipriop;
                               8991                 :                :                     bool        is_lopriparent;
                               8992                 :                :                     bool        is_hipriparent;
                               8993                 :                : 
                               8994                 :             52 :                     op = get_simple_binary_op_name((OpExpr *) node);
                               8995         [ -  + ]:             52 :                     if (!op)
 8517 bruce@momjian.us         8996                 :UBC           0 :                         return false;
                               8997                 :                : 
                               8998                 :                :                     /* We know only the basic operators + - and * / % */
 8517 bruce@momjian.us         8999                 :CBC          52 :                     is_lopriop = (strchr("+-", *op) != NULL);
                               9000                 :             52 :                     is_hipriop = (strchr("*/%", *op) != NULL);
                               9001   [ +  +  +  + ]:             52 :                     if (!(is_lopriop || is_hipriop))
                               9002                 :              4 :                         return false;
                               9003                 :                : 
                               9004                 :             48 :                     parentOp = get_simple_binary_op_name((OpExpr *) parentNode);
                               9005         [ -  + ]:             48 :                     if (!parentOp)
 8517 bruce@momjian.us         9006                 :UBC           0 :                         return false;
                               9007                 :                : 
 8517 bruce@momjian.us         9008                 :CBC          48 :                     is_lopriparent = (strchr("+-", *parentOp) != NULL);
                               9009                 :             48 :                     is_hipriparent = (strchr("*/%", *parentOp) != NULL);
                               9010   [ +  +  -  + ]:             48 :                     if (!(is_lopriparent || is_hipriparent))
 8517 bruce@momjian.us         9011                 :UBC           0 :                         return false;
                               9012                 :                : 
 8517 bruce@momjian.us         9013   [ +  +  +  - ]:CBC          48 :                     if (is_hipriop && is_lopriparent)
                               9014                 :              8 :                         return true;    /* op binds tighter than parent */
                               9015                 :                : 
                               9016   [ +  -  +  + ]:             40 :                     if (is_lopriop && is_hipriparent)
                               9017                 :             32 :                         return false;
                               9018                 :                : 
                               9019                 :                :                     /*
                               9020                 :                :                      * Operators are same priority --- can skip parens only if
                               9021                 :                :                      * we have (a - b) - c, not a - (b - c).
                               9022                 :                :                      */
 8221 neilc@samurai.com        9023         [ +  + ]:              8 :                     if (node == (Node *) linitial(((OpExpr *) parentNode)->args))
 8517 bruce@momjian.us         9024                 :              4 :                         return true;
                               9025                 :                : 
                               9026                 :              4 :                     return false;
                               9027                 :                :                 }
                               9028                 :                :                 /* else do the same stuff as for T_SubLink et al. */
                               9029                 :                :             }
                               9030                 :                :             pg_fallthrough;
                               9031                 :                : 
                               9032                 :                :         case T_XmlExpr:
                               9033                 :                : 
                               9034                 :                :             /*
                               9035                 :                :              * Function-like (name(..)), except "x IS DOCUMENT", which is a
                               9036                 :                :              * postfix test like IS NULL.  (The IsA check is needed because
                               9037                 :                :              * T_OpExpr falls through to here.)
                               9038                 :                :              */
   39 tgl@sss.pgh.pa.us        9039   [ +  +  -  + ]:            136 :             if (IsA(node, XmlExpr) && ((XmlExpr *) node)->op != IS_DOCUMENT)
   39 tgl@sss.pgh.pa.us        9040                 :UBC           0 :                 return true;
                               9041                 :                :             pg_fallthrough;
                               9042                 :                : 
                               9043                 :                :         case T_SubLink:
                               9044                 :                :         case T_NullTest:
                               9045                 :                :         case T_BooleanTest:
                               9046                 :                :         case T_DistinctExpr:
                               9047                 :                :         case T_JsonIsPredicate:
 8522 tgl@sss.pgh.pa.us        9048   [ +  +  +  + ]:CBC         152 :             switch (nodeTag(parentNode))
                               9049                 :                :             {
                               9050                 :             24 :                 case T_FuncExpr:
                               9051                 :                :                     {
                               9052                 :                :                         /* special handling for casts and COERCE_SQL_SYNTAX */
 8517 bruce@momjian.us         9053                 :             24 :                         CoercionForm type = ((FuncExpr *) parentNode)->funcformat;
                               9054                 :                : 
                               9055   [ +  +  +  + ]:             24 :                         if (type == COERCE_EXPLICIT_CAST ||
 1458 tgl@sss.pgh.pa.us        9056         [ +  - ]:              4 :                             type == COERCE_IMPLICIT_CAST ||
                               9057                 :                :                             type == COERCE_SQL_SYNTAX)
 8517 bruce@momjian.us         9058                 :             24 :                             return false;
 8517 bruce@momjian.us         9059                 :UBC           0 :                         return true;    /* own parentheses */
                               9060                 :                :                     }
 3447 tgl@sss.pgh.pa.us        9061                 :CBC          92 :                 case T_BoolExpr:    /* lower precedence */
                               9062                 :                :                 case T_SubscriptingRef: /* other separators */
                               9063                 :                :                 case T_ArrayExpr:   /* other separators */
                               9064                 :                :                 case T_RowExpr: /* other separators */
                               9065                 :                :                 case T_CoalesceExpr:    /* own parentheses */
                               9066                 :                :                 case T_MinMaxExpr:  /* own parentheses */
                               9067                 :                :                 case T_NullIfExpr:  /* other separators */
                               9068                 :                :                 case T_Aggref:  /* own parentheses */
                               9069                 :                :                 case T_GroupingFunc:    /* own parentheses */
                               9070                 :                :                 case T_WindowFunc:  /* own parentheses */
                               9071                 :                :                 case T_CaseExpr:    /* other separators */
 8522                          9072                 :             92 :                     return true;
   39                          9073                 :              4 :                 case T_XmlExpr: /* own parentheses, except IS DOCUMENT */
                               9074                 :              4 :                     return ((XmlExpr *) parentNode)->op != IS_DOCUMENT;
 8522                          9075                 :             32 :                 default:
                               9076                 :             32 :                     return false;
                               9077                 :                :             }
                               9078                 :                : 
                               9079                 :             16 :         case T_BoolExpr:
                               9080   [ +  -  -  -  :             16 :             switch (nodeTag(parentNode))
                                                 + ]
                               9081                 :                :             {
                               9082                 :             12 :                 case T_BoolExpr:
                               9083         [ +  - ]:             12 :                     if (prettyFlags & PRETTYFLAG_PAREN)
                               9084                 :                :                     {
                               9085                 :                :                         BoolExprType type;
                               9086                 :                :                         BoolExprType parentType;
                               9087                 :                : 
 8517 bruce@momjian.us         9088                 :             12 :                         type = ((BoolExpr *) node)->boolop;
                               9089                 :             12 :                         parentType = ((BoolExpr *) parentNode)->boolop;
 8522 tgl@sss.pgh.pa.us        9090      [ +  +  - ]:             12 :                         switch (type)
                               9091                 :                :                         {
                               9092                 :              8 :                             case NOT_EXPR:
                               9093                 :                :                             case AND_EXPR:
                               9094   [ +  +  +  - ]:              8 :                                 if (parentType == AND_EXPR || parentType == OR_EXPR)
                               9095                 :              8 :                                     return true;
 8522 tgl@sss.pgh.pa.us        9096                 :UBC           0 :                                 break;
 8522 tgl@sss.pgh.pa.us        9097                 :CBC           4 :                             case OR_EXPR:
                               9098         [ -  + ]:              4 :                                 if (parentType == OR_EXPR)
 8522 tgl@sss.pgh.pa.us        9099                 :UBC           0 :                                     return true;
 8522 tgl@sss.pgh.pa.us        9100                 :CBC           4 :                                 break;
                               9101                 :                :                         }
                               9102                 :                :                     }
                               9103                 :              4 :                     return false;
 8522 tgl@sss.pgh.pa.us        9104                 :UBC           0 :                 case T_FuncExpr:
                               9105                 :                :                     {
                               9106                 :                :                         /* special handling for casts and COERCE_SQL_SYNTAX */
 8517 bruce@momjian.us         9107                 :              0 :                         CoercionForm type = ((FuncExpr *) parentNode)->funcformat;
                               9108                 :                : 
                               9109   [ #  #  #  # ]:              0 :                         if (type == COERCE_EXPLICIT_CAST ||
 1458 tgl@sss.pgh.pa.us        9110         [ #  # ]:              0 :                             type == COERCE_IMPLICIT_CAST ||
                               9111                 :                :                             type == COERCE_SQL_SYNTAX)
 8517 bruce@momjian.us         9112                 :              0 :                             return false;
                               9113                 :              0 :                         return true;    /* own parentheses */
                               9114                 :                :                     }
 2857 alvherre@alvh.no-ip.     9115                 :              0 :                 case T_SubscriptingRef: /* other separators */
                               9116                 :                :                 case T_ArrayExpr:   /* other separators */
                               9117                 :                :                 case T_RowExpr: /* other separators */
                               9118                 :                :                 case T_CoalesceExpr:    /* own parentheses */
                               9119                 :                :                 case T_MinMaxExpr:  /* own parentheses */
                               9120                 :                :                 case T_NullIfExpr:  /* other separators */
                               9121                 :                :                 case T_Aggref:  /* own parentheses */
                               9122                 :                :                 case T_GroupingFunc:    /* own parentheses */
                               9123                 :                :                 case T_WindowFunc:  /* own parentheses */
                               9124                 :                :                 case T_CaseExpr:    /* other separators */
                               9125                 :                :                 case T_JsonExpr:    /* own parentheses */
 8522 tgl@sss.pgh.pa.us        9126                 :              0 :                     return true;
   39                          9127                 :              0 :                 case T_XmlExpr: /* own parentheses, except IS DOCUMENT */
                               9128                 :              0 :                     return ((XmlExpr *) parentNode)->op != IS_DOCUMENT;
 8522 tgl@sss.pgh.pa.us        9129                 :CBC           4 :                 default:
                               9130                 :              4 :                     return false;
                               9131                 :                :             }
                               9132                 :                : 
 1340 alvherre@alvh.no-ip.     9133                 :              4 :         case T_JsonValueExpr:
                               9134                 :                :             /* maybe simple, check args */
                               9135                 :              4 :             return isSimpleNode((Node *) ((JsonValueExpr *) node)->raw_expr,
                               9136                 :                :                                 node, prettyFlags);
                               9137                 :                : 
 8522 tgl@sss.pgh.pa.us        9138                 :              4 :         default:
                               9139                 :              4 :             break;
                               9140                 :                :     }
                               9141                 :                :     /* those we don't know: in dubio complexo */
 8517 bruce@momjian.us         9142                 :              4 :     return false;
                               9143                 :                : }
                               9144                 :                : 
                               9145                 :                : 
                               9146                 :                : /*
                               9147                 :                :  * appendContextKeyword - append a keyword to buffer
                               9148                 :                :  *
                               9149                 :                :  * If prettyPrint is enabled, perform a line break, and adjust indentation.
                               9150                 :                :  * Otherwise, just append the keyword.
                               9151                 :                :  */
                               9152                 :                : static void
 8522 tgl@sss.pgh.pa.us        9153                 :          19941 : appendContextKeyword(deparse_context *context, const char *str,
                               9154                 :                :                      int indentBefore, int indentAfter, int indentPlus)
                               9155                 :                : {
 4765                          9156                 :          19941 :     StringInfo  buf = context->buf;
                               9157                 :                : 
 8517 bruce@momjian.us         9158         [ +  + ]:          19941 :     if (PRETTY_INDENT(context))
                               9159                 :                :     {
                               9160                 :                :         int         indentAmount;
                               9161                 :                : 
 8522 tgl@sss.pgh.pa.us        9162                 :          18872 :         context->indentLevel += indentBefore;
                               9163                 :                : 
                               9164                 :                :         /* remove any trailing spaces currently in the buffer ... */
 4765                          9165                 :          18872 :         removeStringInfoSpaces(buf);
                               9166                 :                :         /* ... then add a newline and some spaces */
                               9167                 :          18872 :         appendStringInfoChar(buf, '\n');
                               9168                 :                : 
 4595                          9169         [ +  - ]:          18872 :         if (context->indentLevel < PRETTYINDENT_LIMIT)
                               9170                 :          18872 :             indentAmount = Max(context->indentLevel, 0) + indentPlus;
                               9171                 :                :         else
                               9172                 :                :         {
                               9173                 :                :             /*
                               9174                 :                :              * If we're indented more than PRETTYINDENT_LIMIT characters, try
                               9175                 :                :              * to conserve horizontal space by reducing the per-level
                               9176                 :                :              * indentation.  For best results the scale factor here should
                               9177                 :                :              * divide all the indent amounts that get added to indentLevel
                               9178                 :                :              * (PRETTYINDENT_STD, etc).  It's important that the indentation
                               9179                 :                :              * not grow unboundedly, else deeply-nested trees use O(N^2)
                               9180                 :                :              * whitespace; so we also wrap modulo PRETTYINDENT_LIMIT.
                               9181                 :                :              */
 4595 tgl@sss.pgh.pa.us        9182                 :UBC           0 :             indentAmount = PRETTYINDENT_LIMIT +
                               9183                 :              0 :                 (context->indentLevel - PRETTYINDENT_LIMIT) /
                               9184                 :                :                 (PRETTYINDENT_STD / 2);
                               9185                 :              0 :             indentAmount %= PRETTYINDENT_LIMIT;
                               9186                 :                :             /* scale/wrap logic affects indentLevel, but not indentPlus */
                               9187                 :              0 :             indentAmount += indentPlus;
                               9188                 :                :         }
 4595 tgl@sss.pgh.pa.us        9189                 :CBC       18872 :         appendStringInfoSpaces(buf, indentAmount);
                               9190                 :                : 
 4765                          9191                 :          18872 :         appendStringInfoString(buf, str);
                               9192                 :                : 
 8522                          9193                 :          18872 :         context->indentLevel += indentAfter;
                               9194         [ -  + ]:          18872 :         if (context->indentLevel < 0)
 8522 tgl@sss.pgh.pa.us        9195                 :UBC           0 :             context->indentLevel = 0;
                               9196                 :                :     }
                               9197                 :                :     else
 4765 tgl@sss.pgh.pa.us        9198                 :CBC        1069 :         appendStringInfoString(buf, str);
 8522                          9199                 :          19941 : }
                               9200                 :                : 
                               9201                 :                : /*
                               9202                 :                :  * removeStringInfoSpaces - delete trailing spaces from a buffer.
                               9203                 :                :  *
                               9204                 :                :  * Possibly this should move to stringinfo.c at some point.
                               9205                 :                :  */
                               9206                 :                : static void
 4765                          9207                 :          19247 : removeStringInfoSpaces(StringInfo str)
                               9208                 :                : {
                               9209   [ +  +  +  + ]:          29983 :     while (str->len > 0 && str->data[str->len - 1] == ' ')
                               9210                 :          10736 :         str->data[--(str->len)] = '\0';
                               9211                 :          19247 : }
                               9212                 :                : 
                               9213                 :                : 
                               9214                 :                : /*
                               9215                 :                :  * get_rule_expr_paren  - deparse expr using get_rule_expr,
                               9216                 :                :  * embracing the string with parentheses if necessary for prettyPrint.
                               9217                 :                :  *
                               9218                 :                :  * Never embrace if prettyFlags=0, because it's done in the calling node.
                               9219                 :                :  *
                               9220                 :                :  * Any node that does *not* embrace its argument node by sql syntax (with
                               9221                 :                :  * parentheses, non-operator keywords like CASE/WHEN/ON, or comma etc) should
                               9222                 :                :  * use get_rule_expr_paren instead of get_rule_expr so parentheses can be
                               9223                 :                :  * added.
                               9224                 :                :  */
                               9225                 :                : static void
 8517 bruce@momjian.us         9226                 :         114144 : get_rule_expr_paren(Node *node, deparse_context *context,
                               9227                 :                :                     bool showimplicit, Node *parentNode)
                               9228                 :                : {
                               9229                 :                :     bool        need_paren;
                               9230                 :                : 
 8522 tgl@sss.pgh.pa.us        9231         [ +  + ]:         118005 :     need_paren = PRETTY_PAREN(context) &&
                               9232         [ +  + ]:           3861 :         !isSimpleNode(node, parentNode, context->prettyFlags);
                               9233                 :                : 
                               9234         [ +  + ]:         114144 :     if (need_paren)
 8517 bruce@momjian.us         9235                 :            112 :         appendStringInfoChar(context->buf, '(');
                               9236                 :                : 
 8522 tgl@sss.pgh.pa.us        9237                 :         114144 :     get_rule_expr(node, context, showimplicit);
                               9238                 :                : 
                               9239         [ +  + ]:         114144 :     if (need_paren)
 8517 bruce@momjian.us         9240                 :            112 :         appendStringInfoChar(context->buf, ')');
 8522 tgl@sss.pgh.pa.us        9241                 :         114144 : }
                               9242                 :                : 
                               9243                 :                : static void
  982 amitlan@postgresql.o     9244                 :             72 : get_json_behavior(JsonBehavior *behavior, deparse_context *context,
                               9245                 :                :                   const char *on)
                               9246                 :                : {
                               9247                 :                :     /*
                               9248                 :                :      * The order of array elements must correspond to the order of
                               9249                 :                :      * JsonBehaviorType members.
                               9250                 :                :      */
                               9251                 :             72 :     const char *behavior_names[] =
                               9252                 :                :     {
                               9253                 :                :         " NULL",
                               9254                 :                :         " ERROR",
                               9255                 :                :         " EMPTY",
                               9256                 :                :         " TRUE",
                               9257                 :                :         " FALSE",
                               9258                 :                :         " UNKNOWN",
                               9259                 :                :         " EMPTY ARRAY",
                               9260                 :                :         " EMPTY OBJECT",
                               9261                 :                :         " DEFAULT "
                               9262                 :                :     };
                               9263                 :                : 
                               9264   [ +  -  -  + ]:             72 :     if ((int) behavior->btype < 0 || behavior->btype >= lengthof(behavior_names))
  982 amitlan@postgresql.o     9265         [ #  # ]:UBC           0 :         elog(ERROR, "invalid json behavior type: %d", behavior->btype);
                               9266                 :                : 
  982 amitlan@postgresql.o     9267                 :CBC          72 :     appendStringInfoString(context->buf, behavior_names[behavior->btype]);
                               9268                 :                : 
                               9269         [ +  + ]:             72 :     if (behavior->btype == JSON_BEHAVIOR_DEFAULT)
                               9270                 :             12 :         get_rule_expr(behavior->expr, context, false);
                               9271                 :                : 
                               9272                 :             72 :     appendStringInfo(context->buf, " ON %s", on);
                               9273                 :             72 : }
                               9274                 :                : 
                               9275                 :                : /*
                               9276                 :                :  * get_json_expr_options
                               9277                 :                :  *
                               9278                 :                :  * Parse back common options for JSON_QUERY, JSON_VALUE, JSON_EXISTS and
                               9279                 :                :  * JSON_TABLE columns.
                               9280                 :                :  */
                               9281                 :                : static void
                               9282                 :            436 : get_json_expr_options(JsonExpr *jsexpr, deparse_context *context,
                               9283                 :                :                       JsonBehaviorType default_behavior)
                               9284                 :                : {
                               9285         [ +  + ]:            436 :     if (jsexpr->op == JSON_QUERY_OP)
                               9286                 :                :     {
                               9287         [ +  + ]:            192 :         if (jsexpr->wrapper == JSW_CONDITIONAL)
  962 drowley@postgresql.o     9288                 :              8 :             appendStringInfoString(context->buf, " WITH CONDITIONAL WRAPPER");
  982 amitlan@postgresql.o     9289         [ +  + ]:            184 :         else if (jsexpr->wrapper == JSW_UNCONDITIONAL)
  962 drowley@postgresql.o     9290                 :             24 :             appendStringInfoString(context->buf, " WITH UNCONDITIONAL WRAPPER");
                               9291                 :                :         /* The default */
  964 amitlan@postgresql.o     9292   [ +  +  +  - ]:            160 :         else if (jsexpr->wrapper == JSW_NONE || jsexpr->wrapper == JSW_UNSPEC)
  962 drowley@postgresql.o     9293                 :            160 :             appendStringInfoString(context->buf, " WITHOUT WRAPPER");
                               9294                 :                : 
  982 amitlan@postgresql.o     9295         [ +  + ]:            192 :         if (jsexpr->omit_quotes)
  962 drowley@postgresql.o     9296                 :             36 :             appendStringInfoString(context->buf, " OMIT QUOTES");
                               9297                 :                :         /* The default */
                               9298                 :                :         else
                               9299                 :            156 :             appendStringInfoString(context->buf, " KEEP QUOTES");
                               9300                 :                :     }
                               9301                 :                : 
  982 amitlan@postgresql.o     9302   [ +  +  +  + ]:            436 :     if (jsexpr->on_empty && jsexpr->on_empty->btype != default_behavior)
                               9303                 :             24 :         get_json_behavior(jsexpr->on_empty, context, "EMPTY");
                               9304                 :                : 
                               9305   [ +  -  +  + ]:            436 :     if (jsexpr->on_error && jsexpr->on_error->btype != default_behavior)
                               9306                 :             40 :         get_json_behavior(jsexpr->on_error, context, "ERROR");
                               9307                 :            436 : }
                               9308                 :                : 
                               9309                 :                : /* ----------
                               9310                 :                :  * get_rule_expr            - Parse back an expression
                               9311                 :                :  *
                               9312                 :                :  * Note: showimplicit determines whether we display any implicit cast that
                               9313                 :                :  * is present at the top of the expression tree.  It is a passed argument,
                               9314                 :                :  * not a field of the context struct, because we change the value as we
                               9315                 :                :  * recurse down into the expression.  In general we suppress implicit casts
                               9316                 :                :  * when the result type is known with certainty (eg, the arguments of an
                               9317                 :                :  * OR must be boolean).  We display implicit casts for arguments of functions
                               9318                 :                :  * and operators, since this is needed to be certain that the same function
                               9319                 :                :  * or operator will be chosen when the expression is re-parsed.
                               9320                 :                :  * ----------
                               9321                 :                :  */
                               9322                 :                : static void
 8836 tgl@sss.pgh.pa.us        9323                 :         254729 : get_rule_expr(Node *node, deparse_context *context,
                               9324                 :                :               bool showimplicit)
                               9325                 :                : {
 9918                          9326                 :         254729 :     StringInfo  buf = context->buf;
                               9327                 :                : 
10315 bruce@momjian.us         9328         [ +  + ]:         254729 :     if (node == NULL)
 9919 tgl@sss.pgh.pa.us        9329                 :             72 :         return;
                               9330                 :                : 
                               9331                 :                :     /* Guard against excessively long or deeply-nested queries */
 4595                          9332         [ -  + ]:         254657 :     CHECK_FOR_INTERRUPTS();
                               9333                 :         254657 :     check_stack_depth();
                               9334                 :                : 
                               9335                 :                :     /*
                               9336                 :                :      * Each level of get_rule_expr must emit an indivisible term
                               9337                 :                :      * (parenthesized if necessary) to ensure result is reparsed into the same
                               9338                 :                :      * expression tree.  The only exception is that when the input is a List,
                               9339                 :                :      * we emit the component items comma-separated with no surrounding
                               9340                 :                :      * decoration; this is convenient for most callers.
                               9341                 :                :      */
10315 bruce@momjian.us         9342   [ +  +  +  +  :         254657 :     switch (nodeTag(node))
                                     +  +  +  +  +  
                                     +  +  +  +  +  
                                     +  +  +  -  +  
                                     +  +  +  +  +  
                                     +  +  -  +  +  
                                     +  +  +  +  +  
                                     +  +  +  +  +  
                                     +  -  +  +  +  
                                     +  +  +  +  +  
                                              +  - ]
                               9343                 :                :     {
 9954 tgl@sss.pgh.pa.us        9344                 :         125474 :         case T_Var:
 5328                          9345                 :         125474 :             (void) get_variable((Var *) node, 0, false, context);
10315 bruce@momjian.us         9346                 :         125474 :             break;
                               9347                 :                : 
 8752 tgl@sss.pgh.pa.us        9348                 :          43530 :         case T_Const:
 6901                          9349                 :          43530 :             get_const_expr((Const *) node, context, 0);
 8752                          9350                 :          43530 :             break;
                               9351                 :                : 
                               9352                 :           5748 :         case T_Param:
 5982                          9353                 :           5748 :             get_parameter((Param *) node, context);
10315 bruce@momjian.us         9354                 :           5748 :             break;
                               9355                 :                : 
 9954 tgl@sss.pgh.pa.us        9356                 :           2770 :         case T_Aggref:
 3867 rhaas@postgresql.org     9357                 :           2770 :             get_agg_expr((Aggref *) node, context, (Aggref *) node);
 9954 tgl@sss.pgh.pa.us        9358                 :           2770 :             break;
                               9359                 :                : 
 4214 andres@anarazel.de       9360                 :             74 :         case T_GroupingFunc:
                               9361                 :                :             {
                               9362                 :             74 :                 GroupingFunc *gexpr = (GroupingFunc *) node;
                               9363                 :                : 
                               9364                 :             74 :                 appendStringInfoString(buf, "GROUPING(");
                               9365                 :             74 :                 get_rule_expr((Node *) gexpr->args, context, true);
                               9366                 :             74 :                 appendStringInfoChar(buf, ')');
                               9367                 :                :             }
                               9368                 :             74 :             break;
                               9369                 :                : 
 6544 tgl@sss.pgh.pa.us        9370                 :            254 :         case T_WindowFunc:
                               9371                 :            254 :             get_windowfunc_expr((WindowFunc *) node, context);
                               9372                 :            254 :             break;
                               9373                 :                : 
  986 dean.a.rasheed@gmail     9374                 :              4 :         case T_MergeSupportFunc:
                               9375                 :              4 :             appendStringInfoString(buf, "MERGE_ACTION()");
                               9376                 :              4 :             break;
                               9377                 :                : 
 2857 alvherre@alvh.no-ip.     9378                 :            240 :         case T_SubscriptingRef:
                               9379                 :                :             {
                               9380                 :            240 :                 SubscriptingRef *sbsref = (SubscriptingRef *) node;
                               9381                 :                :                 bool        need_parens;
                               9382                 :                : 
                               9383                 :                :                 /*
                               9384                 :                :                  * If the argument is a CaseTestExpr, we must be inside a
                               9385                 :                :                  * FieldStore, ie, we are assigning to an element of an array
                               9386                 :                :                  * within a composite column.  Since we already punted on
                               9387                 :                :                  * displaying the FieldStore's target information, just punt
                               9388                 :                :                  * here too, and display only the assignment source
                               9389                 :                :                  * expression.
                               9390                 :                :                  */
                               9391         [ -  + ]:            240 :                 if (IsA(sbsref->refexpr, CaseTestExpr))
                               9392                 :                :                 {
 2857 alvherre@alvh.no-ip.     9393         [ #  # ]:UBC           0 :                     Assert(sbsref->refassgnexpr);
                               9394                 :              0 :                     get_rule_expr((Node *) sbsref->refassgnexpr,
                               9395                 :                :                                   context, showimplicit);
 6127 tgl@sss.pgh.pa.us        9396                 :              0 :                     break;
                               9397                 :                :                 }
                               9398                 :                : 
                               9399                 :                :                 /*
                               9400                 :                :                  * Parenthesize the argument unless it's a simple Var or a
                               9401                 :                :                  * FieldSelect.  (In particular, if it's another
                               9402                 :                :                  * SubscriptingRef, we *must* parenthesize to avoid
                               9403                 :                :                  * confusion.)
                               9404                 :                :                  */
 2857 alvherre@alvh.no-ip.     9405         [ +  + ]:CBC         374 :                 need_parens = !IsA(sbsref->refexpr, Var) &&
                               9406         [ +  + ]:            134 :                     !IsA(sbsref->refexpr, FieldSelect);
 8635 tgl@sss.pgh.pa.us        9407         [ +  + ]:            240 :                 if (need_parens)
                               9408                 :             64 :                     appendStringInfoChar(buf, '(');
 2857 alvherre@alvh.no-ip.     9409                 :            240 :                 get_rule_expr((Node *) sbsref->refexpr, context, showimplicit);
 8635 tgl@sss.pgh.pa.us        9410         [ +  + ]:            240 :                 if (need_parens)
                               9411                 :             64 :                     appendStringInfoChar(buf, ')');
                               9412                 :                : 
                               9413                 :                :                 /*
                               9414                 :                :                  * If there's a refassgnexpr, we want to print the node in the
                               9415                 :                :                  * format "container[subscripts] := refassgnexpr".  This is
                               9416                 :                :                  * not legal SQL, so decompilation of INSERT or UPDATE
                               9417                 :                :                  * statements should always use processIndirection as part of
                               9418                 :                :                  * the statement-level syntax.  We should only see this when
                               9419                 :                :                  * EXPLAIN tries to print the targetlist of a plan resulting
                               9420                 :                :                  * from such a statement.
                               9421                 :                :                  */
 2857 alvherre@alvh.no-ip.     9422         [ +  + ]:            240 :                 if (sbsref->refassgnexpr)
                               9423                 :                :                 {
                               9424                 :                :                     Node       *refassgnexpr;
                               9425                 :                : 
                               9426                 :                :                     /*
                               9427                 :                :                      * Use processIndirection to print this node's subscripts
                               9428                 :                :                      * as well as any additional field selections or
                               9429                 :                :                      * subscripting in immediate descendants.  It returns the
                               9430                 :                :                      * RHS expr that is actually being "assigned".
                               9431                 :                :                      */
 3769 tgl@sss.pgh.pa.us        9432                 :              8 :                     refassgnexpr = processIndirection(node, context);
 6127                          9433                 :              8 :                     appendStringInfoString(buf, " := ");
                               9434                 :              8 :                     get_rule_expr(refassgnexpr, context, showimplicit);
                               9435                 :                :                 }
                               9436                 :                :                 else
                               9437                 :                :                 {
                               9438                 :                :                     /* Just an ordinary container fetch, so print subscripts */
 2857 alvherre@alvh.no-ip.     9439                 :            232 :                     printSubscripts(sbsref, context);
                               9440                 :                :                 }
                               9441                 :                :             }
 8752 tgl@sss.pgh.pa.us        9442                 :            240 :             break;
                               9443                 :                : 
                               9444                 :           8258 :         case T_FuncExpr:
                               9445                 :           8258 :             get_func_expr((FuncExpr *) node, context, showimplicit);
                               9446                 :           8258 :             break;
                               9447                 :                : 
 6260                          9448                 :             20 :         case T_NamedArgExpr:
                               9449                 :                :             {
                               9450                 :             20 :                 NamedArgExpr *na = (NamedArgExpr *) node;
                               9451                 :                : 
 4229 rhaas@postgresql.org     9452                 :             20 :                 appendStringInfo(buf, "%s => ", quote_identifier(na->name));
 6260 tgl@sss.pgh.pa.us        9453                 :             20 :                 get_rule_expr((Node *) na->arg, context, showimplicit);
                               9454                 :                :             }
                               9455                 :             20 :             break;
                               9456                 :                : 
 8752                          9457                 :          42904 :         case T_OpExpr:
                               9458                 :          42904 :             get_oper_expr((OpExpr *) node, context);
                               9459                 :          42904 :             break;
                               9460                 :                : 
                               9461                 :             16 :         case T_DistinctExpr:
                               9462                 :                :             {
                               9463                 :             16 :                 DistinctExpr *expr = (DistinctExpr *) node;
                               9464                 :             16 :                 List       *args = expr->args;
 8221 neilc@samurai.com        9465                 :             16 :                 Node       *arg1 = (Node *) linitial(args);
 8553 tgl@sss.pgh.pa.us        9466                 :             16 :                 Node       *arg2 = (Node *) lsecond(args);
                               9467                 :                : 
 8522                          9468         [ +  + ]:             16 :                 if (!PRETTY_PAREN(context))
 8517 bruce@momjian.us         9469                 :             12 :                     appendStringInfoChar(buf, '(');
 8522 tgl@sss.pgh.pa.us        9470                 :             16 :                 get_rule_expr_paren(arg1, context, true, node);
 4776 rhaas@postgresql.org     9471                 :             16 :                 appendStringInfoString(buf, " IS DISTINCT FROM ");
 8522 tgl@sss.pgh.pa.us        9472                 :             16 :                 get_rule_expr_paren(arg2, context, true, node);
                               9473         [ +  + ]:             16 :                 if (!PRETTY_PAREN(context))
 8517 bruce@momjian.us         9474                 :             12 :                     appendStringInfoChar(buf, ')');
                               9475                 :                :             }
 8553 tgl@sss.pgh.pa.us        9476                 :             16 :             break;
                               9477                 :                : 
 5733                          9478                 :            140 :         case T_NullIfExpr:
                               9479                 :                :             {
                               9480                 :            140 :                 NullIfExpr *nullifexpr = (NullIfExpr *) node;
                               9481                 :                : 
 4776 rhaas@postgresql.org     9482                 :            140 :                 appendStringInfoString(buf, "NULLIF(");
 5733 tgl@sss.pgh.pa.us        9483                 :            140 :                 get_rule_expr((Node *) nullifexpr->args, context, true);
                               9484                 :            140 :                 appendStringInfoChar(buf, ')');
                               9485                 :                :             }
                               9486                 :            140 :             break;
                               9487                 :                : 
 8553                          9488                 :           2058 :         case T_ScalarArrayOpExpr:
                               9489                 :                :             {
                               9490                 :           2058 :                 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
                               9491                 :           2058 :                 List       *args = expr->args;
 8221 neilc@samurai.com        9492                 :           2058 :                 Node       *arg1 = (Node *) linitial(args);
 8553 tgl@sss.pgh.pa.us        9493                 :           2058 :                 Node       *arg2 = (Node *) lsecond(args);
                               9494                 :                : 
 8522                          9495         [ +  + ]:           2058 :                 if (!PRETTY_PAREN(context))
 8517 bruce@momjian.us         9496                 :           2050 :                     appendStringInfoChar(buf, '(');
 8522 tgl@sss.pgh.pa.us        9497                 :           2058 :                 get_rule_expr_paren(arg1, context, true, node);
 8553                          9498                 :           2058 :                 appendStringInfo(buf, " %s %s (",
                               9499                 :                :                                  generate_operator_name(expr->opno,
                               9500                 :                :                                                         exprType(arg1),
                               9501                 :                :                                                         get_base_element_type(exprType(arg2))),
                               9502         [ +  + ]:           2058 :                                  expr->useOr ? "ANY" : "ALL");
 8522                          9503                 :           2058 :                 get_rule_expr_paren(arg2, context, true, node);
                               9504                 :                : 
                               9505                 :                :                 /*
                               9506                 :                :                  * There's inherent ambiguity in "x op ANY/ALL (y)" when y is
                               9507                 :                :                  * a bare sub-SELECT.  Since we're here, the sub-SELECT must
                               9508                 :                :                  * be meant as a scalar sub-SELECT yielding an array value to
                               9509                 :                :                  * be used in ScalarArrayOpExpr; but the grammar will
                               9510                 :                :                  * preferentially interpret such a construct as an ANY/ALL
                               9511                 :                :                  * SubLink.  To prevent misparsing the output that way, insert
                               9512                 :                :                  * a dummy coercion (which will be stripped by parse analysis,
                               9513                 :                :                  * so no inefficiency is added in dump and reload).  This is
                               9514                 :                :                  * indeed most likely what the user wrote to get the construct
                               9515                 :                :                  * accepted in the first place.
                               9516                 :                :                  */
 3873                          9517         [ +  + ]:           2058 :                 if (IsA(arg2, SubLink) &&
                               9518         [ +  - ]:              4 :                     ((SubLink *) arg2)->subLinkType == EXPR_SUBLINK)
                               9519                 :              4 :                     appendStringInfo(buf, "::%s",
                               9520                 :                :                                      format_type_with_typemod(exprType(arg2),
                               9521                 :                :                                                               exprTypmod(arg2)));
 8522                          9522                 :           2058 :                 appendStringInfoChar(buf, ')');
                               9523         [ +  + ]:           2058 :                 if (!PRETTY_PAREN(context))
 8517 bruce@momjian.us         9524                 :           2050 :                     appendStringInfoChar(buf, ')');
                               9525                 :                :             }
10315                          9526                 :           2058 :             break;
                               9527                 :                : 
 8752 tgl@sss.pgh.pa.us        9528                 :           7653 :         case T_BoolExpr:
                               9529                 :                :             {
                               9530                 :           7653 :                 BoolExpr   *expr = (BoolExpr *) node;
 8221 neilc@samurai.com        9531                 :           7653 :                 Node       *first_arg = linitial(expr->args);
                               9532                 :                :                 ListCell   *arg;
                               9533                 :                : 
 8752 tgl@sss.pgh.pa.us        9534   [ +  +  +  - ]:           7653 :                 switch (expr->boolop)
                               9535                 :                :                 {
                               9536                 :           6096 :                     case AND_EXPR:
 8522                          9537         [ +  + ]:           6096 :                         if (!PRETTY_PAREN(context))
 8517 bruce@momjian.us         9538                 :           6060 :                             appendStringInfoChar(buf, '(');
 8221 neilc@samurai.com        9539                 :           6096 :                         get_rule_expr_paren(first_arg, context,
                               9540                 :                :                                             false, node);
 2252 tgl@sss.pgh.pa.us        9541   [ +  -  +  +  :          13845 :                         for_each_from(arg, expr->args, 1)
                                              +  + ]
                               9542                 :                :                         {
 4776 rhaas@postgresql.org     9543                 :           7749 :                             appendStringInfoString(buf, " AND ");
 8221 neilc@samurai.com        9544                 :           7749 :                             get_rule_expr_paren((Node *) lfirst(arg), context,
                               9545                 :                :                                                 false, node);
                               9546                 :                :                         }
 8522 tgl@sss.pgh.pa.us        9547         [ +  + ]:           6096 :                         if (!PRETTY_PAREN(context))
 8517 bruce@momjian.us         9548                 :           6060 :                             appendStringInfoChar(buf, ')');
 8752 tgl@sss.pgh.pa.us        9549                 :           6096 :                         break;
                               9550                 :                : 
                               9551                 :           1258 :                     case OR_EXPR:
 8522                          9552         [ +  + ]:           1258 :                         if (!PRETTY_PAREN(context))
 8517 bruce@momjian.us         9553                 :           1246 :                             appendStringInfoChar(buf, '(');
 8221 neilc@samurai.com        9554                 :           1258 :                         get_rule_expr_paren(first_arg, context,
                               9555                 :                :                                             false, node);
 2252 tgl@sss.pgh.pa.us        9556   [ +  -  +  +  :           2991 :                         for_each_from(arg, expr->args, 1)
                                              +  + ]
                               9557                 :                :                         {
 4776 rhaas@postgresql.org     9558                 :           1733 :                             appendStringInfoString(buf, " OR ");
 8221 neilc@samurai.com        9559                 :           1733 :                             get_rule_expr_paren((Node *) lfirst(arg), context,
                               9560                 :                :                                                 false, node);
                               9561                 :                :                         }
 8522 tgl@sss.pgh.pa.us        9562         [ +  + ]:           1258 :                         if (!PRETTY_PAREN(context))
 8517 bruce@momjian.us         9563                 :           1246 :                             appendStringInfoChar(buf, ')');
 8752 tgl@sss.pgh.pa.us        9564                 :           1258 :                         break;
                               9565                 :                : 
                               9566                 :            299 :                     case NOT_EXPR:
 8522                          9567         [ +  + ]:            299 :                         if (!PRETTY_PAREN(context))
 8517 bruce@momjian.us         9568                 :            291 :                             appendStringInfoChar(buf, '(');
 4776 rhaas@postgresql.org     9569                 :            299 :                         appendStringInfoString(buf, "NOT ");
 8221 neilc@samurai.com        9570                 :            299 :                         get_rule_expr_paren(first_arg, context,
                               9571                 :                :                                             false, node);
 8522 tgl@sss.pgh.pa.us        9572         [ +  + ]:            299 :                         if (!PRETTY_PAREN(context))
 8517 bruce@momjian.us         9573                 :            291 :                             appendStringInfoChar(buf, ')');
 8752 tgl@sss.pgh.pa.us        9574                 :            299 :                         break;
                               9575                 :                : 
 8752 tgl@sss.pgh.pa.us        9576                 :UBC           0 :                     default:
 8525                          9577         [ #  # ]:              0 :                         elog(ERROR, "unrecognized boolop: %d",
                               9578                 :                :                              (int) expr->boolop);
                               9579                 :                :                 }
                               9580                 :                :             }
 8752 tgl@sss.pgh.pa.us        9581                 :CBC        7653 :             break;
                               9582                 :                : 
                               9583                 :            306 :         case T_SubLink:
                               9584                 :            306 :             get_sublink_expr((SubLink *) node, context);
                               9585                 :            306 :             break;
                               9586                 :                : 
 8750                          9587                 :            762 :         case T_SubPlan:
                               9588                 :                :             {
 6379 bruce@momjian.us         9589                 :            762 :                 SubPlan    *subplan = (SubPlan *) node;
                               9590                 :                : 
                               9591                 :                :                 /*
                               9592                 :                :                  * We cannot see an already-planned subplan in rule deparsing,
                               9593                 :                :                  * only while EXPLAINing a query plan.  We don't try to
                               9594                 :                :                  * reconstruct the original SQL, just reference the subplan
                               9595                 :                :                  * that appears elsewhere in EXPLAIN's result.  It does seem
                               9596                 :                :                  * useful to show the subLinkType and testexpr (if any), and
                               9597                 :                :                  * we also note whether the subplan will be hashed.
                               9598                 :                :                  */
  984 tgl@sss.pgh.pa.us        9599   [ +  +  +  +  :            762 :                 switch (subplan->subLinkType)
                                        +  +  +  -  
                                                 - ]
                               9600                 :                :                 {
                               9601                 :             70 :                     case EXISTS_SUBLINK:
                               9602                 :             70 :                         appendStringInfoString(buf, "EXISTS(");
                               9603         [ -  + ]:             70 :                         Assert(subplan->testexpr == NULL);
                               9604                 :             70 :                         break;
                               9605                 :             12 :                     case ALL_SUBLINK:
                               9606                 :             12 :                         appendStringInfoString(buf, "(ALL ");
                               9607         [ -  + ]:             12 :                         Assert(subplan->testexpr != NULL);
                               9608                 :             12 :                         break;
                               9609                 :            188 :                     case ANY_SUBLINK:
                               9610                 :            188 :                         appendStringInfoString(buf, "(ANY ");
                               9611         [ -  + ]:            188 :                         Assert(subplan->testexpr != NULL);
                               9612                 :            188 :                         break;
                               9613                 :              4 :                     case ROWCOMPARE_SUBLINK:
                               9614                 :                :                         /* Parenthesizing the testexpr seems sufficient */
                               9615                 :              4 :                         appendStringInfoChar(buf, '(');
                               9616         [ -  + ]:              4 :                         Assert(subplan->testexpr != NULL);
                               9617                 :              4 :                         break;
                               9618                 :            462 :                     case EXPR_SUBLINK:
                               9619                 :                :                         /* No need to decorate these subplan references */
                               9620                 :            462 :                         appendStringInfoChar(buf, '(');
                               9621         [ -  + ]:            462 :                         Assert(subplan->testexpr == NULL);
                               9622                 :            462 :                         break;
                               9623                 :             17 :                     case MULTIEXPR_SUBLINK:
                               9624                 :                :                         /* MULTIEXPR isn't executed in the normal way */
                               9625                 :             17 :                         appendStringInfoString(buf, "(rescan ");
                               9626         [ -  + ]:             17 :                         Assert(subplan->testexpr == NULL);
                               9627                 :             17 :                         break;
                               9628                 :              9 :                     case ARRAY_SUBLINK:
                               9629                 :              9 :                         appendStringInfoString(buf, "ARRAY(");
                               9630         [ -  + ]:              9 :                         Assert(subplan->testexpr == NULL);
                               9631                 :              9 :                         break;
  984 tgl@sss.pgh.pa.us        9632                 :UBC           0 :                     case CTE_SUBLINK:
                               9633                 :                :                         /* This case is unreachable within expressions */
                               9634                 :              0 :                         appendStringInfoString(buf, "CTE(");
                               9635         [ #  # ]:              0 :                         Assert(subplan->testexpr == NULL);
                               9636                 :              0 :                         break;
                               9637                 :                :                 }
                               9638                 :                : 
  984 tgl@sss.pgh.pa.us        9639         [ +  + ]:CBC         762 :                 if (subplan->testexpr != NULL)
                               9640                 :                :                 {
                               9641                 :                :                     deparse_namespace *dpns;
                               9642                 :                : 
                               9643                 :                :                     /*
                               9644                 :                :                      * Push SubPlan into ancestors list while deparsing
                               9645                 :                :                      * testexpr, so that we can handle PARAM_EXEC references
                               9646                 :                :                      * to the SubPlan's paramIds.  (This makes it look like
                               9647                 :                :                      * the SubPlan is an "ancestor" of the current plan node,
                               9648                 :                :                      * which is a little weird, but it does no harm.)  In this
                               9649                 :                :                      * path, we don't need to mention the SubPlan explicitly,
                               9650                 :                :                      * because the referencing Params will show its existence.
                               9651                 :                :                      */
                               9652                 :            204 :                     dpns = (deparse_namespace *) linitial(context->namespaces);
                               9653                 :            204 :                     dpns->ancestors = lcons(subplan, dpns->ancestors);
                               9654                 :                : 
                               9655                 :            204 :                     get_rule_expr(subplan->testexpr, context, showimplicit);
                               9656                 :            204 :                     appendStringInfoChar(buf, ')');
                               9657                 :                : 
                               9658                 :            204 :                     dpns->ancestors = list_delete_first(dpns->ancestors);
                               9659                 :                :                 }
                               9660                 :                :                 else
                               9661                 :                :                 {
                               9662                 :                :                     const char *nameprefix;
                               9663                 :                : 
                               9664                 :                :                     /* No referencing Params, so show the SubPlan's name */
  417 rhaas@postgresql.org     9665         [ -  + ]:            558 :                     if (subplan->isInitPlan)
  417 rhaas@postgresql.org     9666                 :UBC           0 :                         nameprefix = "InitPlan ";
                               9667                 :                :                     else
  417 rhaas@postgresql.org     9668                 :CBC         558 :                         nameprefix = "SubPlan ";
  984 tgl@sss.pgh.pa.us        9669         [ -  + ]:            558 :                     if (subplan->useHashTable)
  417 rhaas@postgresql.org     9670                 :UBC           0 :                         appendStringInfo(buf, "hashed %s%s)",
                               9671                 :                :                                          nameprefix, subplan->plan_name);
                               9672                 :                :                     else
  417 rhaas@postgresql.org     9673                 :CBC         558 :                         appendStringInfo(buf, "%s%s)",
                               9674                 :                :                                          nameprefix, subplan->plan_name);
                               9675                 :                :                 }
                               9676                 :                :             }
 8752 tgl@sss.pgh.pa.us        9677                 :            762 :             break;
                               9678                 :                : 
 6672 tgl@sss.pgh.pa.us        9679                 :UBC           0 :         case T_AlternativeSubPlan:
                               9680                 :                :             {
 6446                          9681                 :              0 :                 AlternativeSubPlan *asplan = (AlternativeSubPlan *) node;
                               9682                 :                :                 ListCell   *lc;
                               9683                 :                : 
                               9684                 :                :                 /*
                               9685                 :                :                  * This case cannot be reached in normal usage, since no
                               9686                 :                :                  * AlternativeSubPlan can appear either in parsetrees or
                               9687                 :                :                  * finished plan trees.  We keep it just in case somebody
                               9688                 :                :                  * wants to use this code to print planner data structures.
                               9689                 :                :                  */
 4776 rhaas@postgresql.org     9690                 :              0 :                 appendStringInfoString(buf, "(alternatives: ");
 6446 tgl@sss.pgh.pa.us        9691   [ #  #  #  #  :              0 :                 foreach(lc, asplan->subplans)
                                              #  # ]
                               9692                 :                :                 {
 3519                          9693                 :              0 :                     SubPlan    *splan = lfirst_node(SubPlan, lc);
                               9694                 :                :                     const char *nameprefix;
                               9695                 :                : 
  417 rhaas@postgresql.org     9696         [ #  # ]:              0 :                     if (splan->isInitPlan)
                               9697                 :              0 :                         nameprefix = "InitPlan ";
                               9698                 :                :                     else
                               9699                 :              0 :                         nameprefix = "SubPlan ";
 6446 tgl@sss.pgh.pa.us        9700         [ #  # ]:              0 :                     if (splan->useHashTable)
  417 rhaas@postgresql.org     9701                 :              0 :                         appendStringInfo(buf, "hashed %s%s", nameprefix,
                               9702                 :                :                                          splan->plan_name);
                               9703                 :                :                     else
                               9704                 :              0 :                         appendStringInfo(buf, "%s%s", nameprefix,
                               9705                 :                :                                          splan->plan_name);
 2693 tgl@sss.pgh.pa.us        9706         [ #  # ]:              0 :                     if (lnext(asplan->subplans, lc))
 4776 rhaas@postgresql.org     9707                 :              0 :                         appendStringInfoString(buf, " or ");
                               9708                 :                :                 }
                               9709                 :              0 :                 appendStringInfoChar(buf, ')');
                               9710                 :                :             }
 6672 tgl@sss.pgh.pa.us        9711                 :              0 :             break;
                               9712                 :                : 
 9608 tgl@sss.pgh.pa.us        9713                 :CBC         947 :         case T_FieldSelect:
                               9714                 :                :             {
                               9715                 :            947 :                 FieldSelect *fselect = (FieldSelect *) node;
 7851                          9716                 :            947 :                 Node       *arg = (Node *) fselect->arg;
                               9717                 :            947 :                 int         fno = fselect->fieldnum;
                               9718                 :                :                 const char *fieldname;
                               9719                 :                :                 bool        need_parens;
                               9720                 :                : 
                               9721                 :                :                 /*
                               9722                 :                :                  * Parenthesize the argument unless it's a SubscriptingRef or
                               9723                 :                :                  * another FieldSelect.  Note in particular that it would be
                               9724                 :                :                  * WRONG to not parenthesize a Var argument; simplicity is not
                               9725                 :                :                  * the issue here, having the right number of names is.
                               9726                 :                :                  */
 2857 alvherre@alvh.no-ip.     9727         [ +  + ]:           1870 :                 need_parens = !IsA(arg, SubscriptingRef) &&
                               9728         [ +  - ]:            923 :                     !IsA(arg, FieldSelect);
 8207 tgl@sss.pgh.pa.us        9729         [ +  + ]:            947 :                 if (need_parens)
                               9730                 :            923 :                     appendStringInfoChar(buf, '(');
 7851                          9731                 :            947 :                 get_rule_expr(arg, context, true);
 8207                          9732         [ +  + ]:            947 :                 if (need_parens)
                               9733                 :            923 :                     appendStringInfoChar(buf, ')');
                               9734                 :                : 
                               9735                 :                :                 /*
                               9736                 :                :                  * Get and print the field name.
                               9737                 :                :                  */
 7218                          9738                 :            947 :                 fieldname = get_name_for_var_field((Var *) arg, fno,
                               9739                 :                :                                                    0, context);
 8522                          9740                 :            947 :                 appendStringInfo(buf, ".%s", quote_identifier(fieldname));
                               9741                 :                :             }
 9608                          9742                 :            947 :             break;
                               9743                 :                : 
 8207                          9744                 :              4 :         case T_FieldStore:
                               9745                 :                :             {
 6127                          9746                 :              4 :                 FieldStore *fstore = (FieldStore *) node;
                               9747                 :                :                 bool        need_parens;
                               9748                 :                : 
                               9749                 :                :                 /*
                               9750                 :                :                  * There is no good way to represent a FieldStore as real SQL,
                               9751                 :                :                  * so decompilation of INSERT or UPDATE statements should
                               9752                 :                :                  * always use processIndirection as part of the
                               9753                 :                :                  * statement-level syntax.  We should only get here when
                               9754                 :                :                  * EXPLAIN tries to print the targetlist of a plan resulting
                               9755                 :                :                  * from such a statement.  The plan case is even harder than
                               9756                 :                :                  * ordinary rules would be, because the planner tries to
                               9757                 :                :                  * collapse multiple assignments to the same field or subfield
                               9758                 :                :                  * into one FieldStore; so we can see a list of target fields
                               9759                 :                :                  * not just one, and the arguments could be FieldStores
                               9760                 :                :                  * themselves.  We don't bother to try to print the target
                               9761                 :                :                  * field names; we just print the source arguments, with a
                               9762                 :                :                  * ROW() around them if there's more than one.  This isn't
                               9763                 :                :                  * terribly complete, but it's probably good enough for
                               9764                 :                :                  * EXPLAIN's purposes; especially since anything more would be
                               9765                 :                :                  * either hopelessly confusing or an even poorer
                               9766                 :                :                  * representation of what the plan is actually doing.
                               9767                 :                :                  */
                               9768                 :              4 :                 need_parens = (list_length(fstore->newvals) != 1);
                               9769         [ +  - ]:              4 :                 if (need_parens)
                               9770                 :              4 :                     appendStringInfoString(buf, "ROW(");
                               9771                 :              4 :                 get_rule_expr((Node *) fstore->newvals, context, showimplicit);
                               9772         [ +  - ]:              4 :                 if (need_parens)
                               9773                 :              4 :                     appendStringInfoChar(buf, ')');
                               9774                 :                :             }
 8207                          9775                 :              4 :             break;
                               9776                 :                : 
 9778                          9777                 :           1969 :         case T_RelabelType:
                               9778                 :                :             {
                               9779                 :           1969 :                 RelabelType *relabel = (RelabelType *) node;
 8517 bruce@momjian.us         9780                 :           1969 :                 Node       *arg = (Node *) relabel->arg;
                               9781                 :                : 
 8836 tgl@sss.pgh.pa.us        9782         [ +  + ]:           1969 :                 if (relabel->relabelformat == COERCE_IMPLICIT_CAST &&
                               9783         [ +  + ]:           1802 :                     !showimplicit)
                               9784                 :                :                 {
                               9785                 :                :                     /* don't show the implicit cast */
 8200                          9786                 :             48 :                     get_rule_expr_paren(arg, context, false, node);
                               9787                 :                :                 }
                               9788                 :                :                 else
                               9789                 :                :                 {
 7196                          9790                 :           1921 :                     get_coercion_expr(arg, context,
                               9791                 :                :                                       relabel->resulttype,
                               9792                 :                :                                       relabel->resulttypmod,
                               9793                 :                :                                       node);
                               9794                 :                :                 }
                               9795                 :                :             }
 9778                          9796                 :           1969 :             break;
                               9797                 :                : 
 7116                          9798                 :            539 :         case T_CoerceViaIO:
                               9799                 :                :             {
                               9800                 :            539 :                 CoerceViaIO *iocoerce = (CoerceViaIO *) node;
                               9801                 :            539 :                 Node       *arg = (Node *) iocoerce->arg;
                               9802                 :                : 
                               9803         [ +  + ]:            539 :                 if (iocoerce->coerceformat == COERCE_IMPLICIT_CAST &&
                               9804         [ +  - ]:             24 :                     !showimplicit)
                               9805                 :                :                 {
                               9806                 :                :                     /* don't show the implicit cast */
                               9807                 :             24 :                     get_rule_expr_paren(arg, context, false, node);
                               9808                 :                :                 }
                               9809                 :                :                 else
                               9810                 :                :                 {
                               9811                 :            515 :                     get_coercion_expr(arg, context,
                               9812                 :                :                                       iocoerce->resulttype,
                               9813                 :                :                                       -1,
                               9814                 :                :                                       node);
                               9815                 :                :                 }
                               9816                 :                :             }
                               9817                 :            539 :             break;
                               9818                 :                : 
 7186                          9819                 :             43 :         case T_ArrayCoerceExpr:
                               9820                 :                :             {
                               9821                 :             43 :                 ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
                               9822                 :             43 :                 Node       *arg = (Node *) acoerce->arg;
                               9823                 :                : 
                               9824         [ +  + ]:             43 :                 if (acoerce->coerceformat == COERCE_IMPLICIT_CAST &&
                               9825         [ +  + ]:             37 :                     !showimplicit)
                               9826                 :                :                 {
                               9827                 :                :                     /* don't show the implicit cast */
                               9828                 :              4 :                     get_rule_expr_paren(arg, context, false, node);
                               9829                 :                :                 }
                               9830                 :                :                 else
                               9831                 :                :                 {
                               9832                 :             39 :                     get_coercion_expr(arg, context,
                               9833                 :                :                                       acoerce->resulttype,
                               9834                 :                :                                       acoerce->resulttypmod,
                               9835                 :                :                                       node);
                               9836                 :                :                 }
                               9837                 :                :             }
                               9838                 :             43 :             break;
                               9839                 :                : 
 8022                          9840                 :             53 :         case T_ConvertRowtypeExpr:
                               9841                 :                :             {
                               9842                 :             53 :                 ConvertRowtypeExpr *convert = (ConvertRowtypeExpr *) node;
                               9843                 :             53 :                 Node       *arg = (Node *) convert->arg;
                               9844                 :                : 
                               9845         [ +  + ]:             53 :                 if (convert->convertformat == COERCE_IMPLICIT_CAST &&
                               9846         [ +  + ]:             49 :                     !showimplicit)
                               9847                 :                :                 {
                               9848                 :                :                     /* don't show the implicit cast */
                               9849                 :             12 :                     get_rule_expr_paren(arg, context, false, node);
                               9850                 :                :                 }
                               9851                 :                :                 else
                               9852                 :                :                 {
 7196                          9853                 :             41 :                     get_coercion_expr(arg, context,
                               9854                 :                :                                       convert->resulttype, -1,
                               9855                 :                :                                       node);
                               9856                 :                :                 }
                               9857                 :                :             }
 8022                          9858                 :             53 :             break;
                               9859                 :                : 
 5741                          9860                 :             60 :         case T_CollateExpr:
                               9861                 :                :             {
                               9862                 :             60 :                 CollateExpr *collate = (CollateExpr *) node;
                               9863                 :             60 :                 Node       *arg = (Node *) collate->arg;
                               9864                 :                : 
                               9865         [ +  + ]:             60 :                 if (!PRETTY_PAREN(context))
                               9866                 :             56 :                     appendStringInfoChar(buf, '(');
                               9867                 :             60 :                 get_rule_expr_paren(arg, context, showimplicit, node);
                               9868                 :             60 :                 appendStringInfo(buf, " COLLATE %s",
                               9869                 :                :                                  generate_collation_name(collate->collOid));
                               9870         [ +  + ]:             60 :                 if (!PRETTY_PAREN(context))
                               9871                 :             56 :                     appendStringInfoChar(buf, ')');
                               9872                 :                :             }
                               9873                 :             60 :             break;
                               9874                 :                : 
 9954                          9875                 :            526 :         case T_CaseExpr:
                               9876                 :                :             {
                               9877                 :            526 :                 CaseExpr   *caseexpr = (CaseExpr *) node;
                               9878                 :                :                 ListCell   *temp;
                               9879                 :                : 
 8522                          9880                 :            526 :                 appendContextKeyword(context, "CASE",
                               9881                 :                :                                      0, PRETTYINDENT_VAR, 0);
 8291                          9882         [ +  + ]:            526 :                 if (caseexpr->arg)
                               9883                 :                :                 {
                               9884                 :            207 :                     appendStringInfoChar(buf, ' ');
                               9885                 :            207 :                     get_rule_expr((Node *) caseexpr->arg, context, true);
                               9886                 :                :                 }
 9954                          9887   [ +  -  +  +  :           2086 :                 foreach(temp, caseexpr->args)
                                              +  + ]
                               9888                 :                :                 {
                               9889                 :           1560 :                     CaseWhen   *when = (CaseWhen *) lfirst(temp);
 7658                          9890                 :           1560 :                     Node       *w = (Node *) when->expr;
                               9891                 :                : 
 8291                          9892         [ +  + ]:           1560 :                     if (caseexpr->arg)
                               9893                 :                :                     {
                               9894                 :                :                         /*
                               9895                 :                :                          * The parser should have produced WHEN clauses of the
                               9896                 :                :                          * form "CaseTestExpr = RHS", possibly with an
                               9897                 :                :                          * implicit coercion inserted above the CaseTestExpr.
                               9898                 :                :                          * For accurate decompilation of rules it's essential
                               9899                 :                :                          * that we show just the RHS.  However in an
                               9900                 :                :                          * expression that's been through the optimizer, the
                               9901                 :                :                          * WHEN clause could be almost anything (since the
                               9902                 :                :                          * equality operator could have been expanded into an
                               9903                 :                :                          * inline function).  If we don't recognize the form
                               9904                 :                :                          * of the WHEN clause, just punt and display it as-is.
                               9905                 :                :                          */
 7658                          9906         [ +  - ]:            639 :                         if (IsA(w, OpExpr))
                               9907                 :                :                         {
 6485                          9908                 :            639 :                             List       *args = ((OpExpr *) w)->args;
                               9909                 :                : 
 5665                          9910         [ +  - ]:            639 :                             if (list_length(args) == 2 &&
                               9911         [ +  - ]:            639 :                                 IsA(strip_implicit_coercions(linitial(args)),
                               9912                 :                :                                     CaseTestExpr))
                               9913                 :            639 :                                 w = (Node *) lsecond(args);
                               9914                 :                :                         }
                               9915                 :                :                     }
                               9916                 :                : 
                               9917         [ +  + ]:           1560 :                     if (!PRETTY_INDENT(context))
                               9918                 :            140 :                         appendStringInfoChar(buf, ' ');
                               9919                 :           1560 :                     appendContextKeyword(context, "WHEN ",
                               9920                 :                :                                          0, 0, 0);
                               9921                 :           1560 :                     get_rule_expr(w, context, false);
 4776 rhaas@postgresql.org     9922                 :           1560 :                     appendStringInfoString(buf, " THEN ");
 8752 tgl@sss.pgh.pa.us        9923                 :           1560 :                     get_rule_expr((Node *) when->result, context, true);
                               9924                 :                :                 }
 8522                          9925         [ +  + ]:            526 :                 if (!PRETTY_INDENT(context))
 8517 bruce@momjian.us         9926                 :            135 :                     appendStringInfoChar(buf, ' ');
 8522 tgl@sss.pgh.pa.us        9927                 :            526 :                 appendContextKeyword(context, "ELSE ",
                               9928                 :                :                                      0, 0, 0);
 8752                          9929                 :            526 :                 get_rule_expr((Node *) caseexpr->defresult, context, true);
 8522                          9930         [ +  + ]:            526 :                 if (!PRETTY_INDENT(context))
 8517 bruce@momjian.us         9931                 :            135 :                     appendStringInfoChar(buf, ' ');
 8522 tgl@sss.pgh.pa.us        9932                 :            526 :                 appendContextKeyword(context, "END",
                               9933                 :                :                                      -PRETTYINDENT_VAR, 0, 0);
                               9934                 :                :             }
10315 bruce@momjian.us         9935                 :            526 :             break;
                               9936                 :                : 
 5665 tgl@sss.pgh.pa.us        9937                 :UBC           0 :         case T_CaseTestExpr:
                               9938                 :                :             {
                               9939                 :                :                 /*
                               9940                 :                :                  * Normally we should never get here, since for expressions
                               9941                 :                :                  * that can contain this node type we attempt to avoid
                               9942                 :                :                  * recursing to it.  But in an optimized expression we might
                               9943                 :                :                  * be unable to avoid that (see comments for CaseExpr).  If we
                               9944                 :                :                  * do see one, print it as CASE_TEST_EXPR.
                               9945                 :                :                  */
 4776 rhaas@postgresql.org     9946                 :              0 :                 appendStringInfoString(buf, "CASE_TEST_EXPR");
                               9947                 :                :             }
 5665 tgl@sss.pgh.pa.us        9948                 :              0 :             break;
                               9949                 :                : 
 8635 tgl@sss.pgh.pa.us        9950                 :CBC         372 :         case T_ArrayExpr:
                               9951                 :                :             {
 8517 bruce@momjian.us         9952                 :            372 :                 ArrayExpr  *arrayexpr = (ArrayExpr *) node;
                               9953                 :                : 
 4776 rhaas@postgresql.org     9954                 :            372 :                 appendStringInfoString(buf, "ARRAY[");
 8087 tgl@sss.pgh.pa.us        9955                 :            372 :                 get_rule_expr((Node *) arrayexpr->elements, context, true);
                               9956                 :            372 :                 appendStringInfoChar(buf, ']');
                               9957                 :                : 
                               9958                 :                :                 /*
                               9959                 :                :                  * If the array isn't empty, we assume its elements are
                               9960                 :                :                  * coerced to the desired type.  If it's empty, though, we
                               9961                 :                :                  * need an explicit coercion to the array type.
                               9962                 :                :                  */
 6553                          9963         [ +  + ]:            372 :                 if (arrayexpr->elements == NIL)
                               9964                 :              4 :                     appendStringInfo(buf, "::%s",
                               9965                 :                :                                      format_type_with_typemod(arrayexpr->array_typeid, -1));
                               9966                 :                :             }
 8635                          9967                 :            372 :             break;
                               9968                 :                : 
 8237                          9969                 :            376 :         case T_RowExpr:
                               9970                 :                :             {
 8126 bruce@momjian.us         9971                 :            376 :                 RowExpr    *rowexpr = (RowExpr *) node;
 8138 tgl@sss.pgh.pa.us        9972                 :            376 :                 TupleDesc   tupdesc = NULL;
                               9973                 :                :                 ListCell   *arg;
                               9974                 :                :                 int         i;
                               9975                 :                :                 char       *sep;
                               9976                 :                : 
                               9977                 :                :                 /*
                               9978                 :                :                  * If it's a named type and not RECORD, we may have to skip
                               9979                 :                :                  * dropped columns and/or claim there are NULLs for added
                               9980                 :                :                  * columns.
                               9981                 :                :                  */
                               9982         [ +  + ]:            376 :                 if (rowexpr->row_typeid != RECORDOID)
                               9983                 :                :                 {
                               9984                 :             54 :                     tupdesc = lookup_rowtype_tupdesc(rowexpr->row_typeid, -1);
                               9985         [ -  + ]:             54 :                     Assert(list_length(rowexpr->args) <= tupdesc->natts);
                               9986                 :                :                 }
                               9987                 :                : 
                               9988                 :                :                 /*
                               9989                 :                :                  * SQL99 allows "ROW" to be omitted when there is more than
                               9990                 :                :                  * one column, but for simplicity we always print it.
                               9991                 :                :                  */
 4776 rhaas@postgresql.org     9992                 :            376 :                 appendStringInfoString(buf, "ROW(");
 8237 tgl@sss.pgh.pa.us        9993                 :            376 :                 sep = "";
 8138                          9994                 :            376 :                 i = 0;
 8237                          9995   [ +  -  +  +  :           1158 :                 foreach(arg, rowexpr->args)
                                              +  + ]
                               9996                 :                :                 {
                               9997                 :            782 :                     Node       *e = (Node *) lfirst(arg);
                               9998                 :                : 
 8138                          9999         [ +  + ]:            782 :                     if (tupdesc == NULL ||
  402 drowley@postgresql.o    10000         [ +  - ]:            116 :                         !TupleDescCompactAttr(tupdesc, i)->attisdropped)
                              10001                 :                :                     {
 7882 neilc@samurai.com       10002                 :            782 :                         appendStringInfoString(buf, sep);
                              10003                 :                :                         /* Whole-row Vars need special treatment here */
 4031 tgl@sss.pgh.pa.us       10004                 :            782 :                         get_rule_expr_toplevel(e, context, true);
 8138                         10005                 :            782 :                         sep = ", ";
                              10006                 :                :                     }
                              10007                 :            782 :                     i++;
                              10008                 :                :                 }
                              10009         [ +  + ]:            376 :                 if (tupdesc != NULL)
                              10010                 :                :                 {
                              10011         [ -  + ]:             54 :                     while (i < tupdesc->natts)
                              10012                 :                :                     {
  402 drowley@postgresql.o    10013         [ #  # ]:UBC           0 :                         if (!TupleDescCompactAttr(tupdesc, i)->attisdropped)
                              10014                 :                :                         {
 7882 neilc@samurai.com       10015                 :              0 :                             appendStringInfoString(buf, sep);
 4776 rhaas@postgresql.org    10016                 :              0 :                             appendStringInfoString(buf, "NULL");
 8138 tgl@sss.pgh.pa.us       10017                 :              0 :                             sep = ", ";
                              10018                 :                :                         }
                              10019                 :              0 :                         i++;
                              10020                 :                :                     }
                              10021                 :                : 
 7470 tgl@sss.pgh.pa.us       10022         [ +  - ]:CBC          54 :                     ReleaseTupleDesc(tupdesc);
                              10023                 :                :                 }
 4776 rhaas@postgresql.org    10024                 :            376 :                 appendStringInfoChar(buf, ')');
 8237 tgl@sss.pgh.pa.us       10025         [ +  + ]:            376 :                 if (rowexpr->row_format == COERCE_EXPLICIT_CAST)
                              10026                 :             34 :                     appendStringInfo(buf, "::%s",
                              10027                 :                :                                      format_type_with_typemod(rowexpr->row_typeid, -1));
                              10028                 :                :             }
                              10029                 :            376 :             break;
                              10030                 :                : 
 7640                         10031                 :            100 :         case T_RowCompareExpr:
                              10032                 :                :             {
                              10033                 :            100 :                 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
                              10034                 :                : 
                              10035                 :                :                 /*
                              10036                 :                :                  * SQL99 allows "ROW" to be omitted when there is more than
                              10037                 :                :                  * one column, but for simplicity we always print it.  Within
                              10038                 :                :                  * a ROW expression, whole-row Vars need special treatment, so
                              10039                 :                :                  * use get_rule_list_toplevel.
                              10040                 :                :                  */
 4776 rhaas@postgresql.org    10041                 :            100 :                 appendStringInfoString(buf, "(ROW(");
 1780 tgl@sss.pgh.pa.us       10042                 :            100 :                 get_rule_list_toplevel(rcexpr->largs, context, true);
                              10043                 :                : 
                              10044                 :                :                 /*
                              10045                 :                :                  * We assume that the name of the first-column operator will
                              10046                 :                :                  * do for all the rest too.  This is definitely open to
                              10047                 :                :                  * failure, eg if some but not all operators were renamed
                              10048                 :                :                  * since the construct was parsed, but there seems no way to
                              10049                 :                :                  * be perfect.
                              10050                 :                :                  */
 7640                         10051                 :            100 :                 appendStringInfo(buf, ") %s ROW(",
 3447                         10052                 :            100 :                                  generate_operator_name(linitial_oid(rcexpr->opnos),
                              10053                 :            100 :                                                         exprType(linitial(rcexpr->largs)),
                              10054                 :            100 :                                                         exprType(linitial(rcexpr->rargs))));
 1780                         10055                 :            100 :                 get_rule_list_toplevel(rcexpr->rargs, context, true);
 4776 rhaas@postgresql.org    10056                 :            100 :                 appendStringInfoString(buf, "))");
                              10057                 :                :             }
 7640 tgl@sss.pgh.pa.us       10058                 :            100 :             break;
                              10059                 :                : 
 8686                         10060                 :           1105 :         case T_CoalesceExpr:
                              10061                 :                :             {
                              10062                 :           1105 :                 CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
                              10063                 :                : 
 4776 rhaas@postgresql.org    10064                 :           1105 :                 appendStringInfoString(buf, "COALESCE(");
 8087 tgl@sss.pgh.pa.us       10065                 :           1105 :                 get_rule_expr((Node *) coalesceexpr->args, context, true);
                              10066                 :           1105 :                 appendStringInfoChar(buf, ')');
                              10067                 :                :             }
 8686                         10068                 :           1105 :             break;
                              10069                 :                : 
 7825                         10070                 :             28 :         case T_MinMaxExpr:
                              10071                 :                :             {
                              10072                 :             28 :                 MinMaxExpr *minmaxexpr = (MinMaxExpr *) node;
                              10073                 :                : 
                              10074      [ +  +  - ]:             28 :                 switch (minmaxexpr->op)
                              10075                 :                :                 {
                              10076                 :              8 :                     case IS_GREATEST:
 4776 rhaas@postgresql.org    10077                 :              8 :                         appendStringInfoString(buf, "GREATEST(");
 7825 tgl@sss.pgh.pa.us       10078                 :              8 :                         break;
                              10079                 :             20 :                     case IS_LEAST:
 4776 rhaas@postgresql.org    10080                 :             20 :                         appendStringInfoString(buf, "LEAST(");
 7825 tgl@sss.pgh.pa.us       10081                 :             20 :                         break;
                              10082                 :                :                 }
                              10083                 :             28 :                 get_rule_expr((Node *) minmaxexpr->args, context, true);
                              10084                 :             28 :                 appendStringInfoChar(buf, ')');
                              10085                 :                :             }
                              10086                 :             28 :             break;
                              10087                 :                : 
 1291 michael@paquier.xyz     10088                 :            456 :         case T_SQLValueFunction:
                              10089                 :                :             {
                              10090                 :            456 :                 SQLValueFunction *svf = (SQLValueFunction *) node;
                              10091                 :                : 
                              10092                 :                :                 /*
                              10093                 :                :                  * Note: this code knows that typmod for time, timestamp, and
                              10094                 :                :                  * timestamptz just prints as integer.
                              10095                 :                :                  */
                              10096   [ +  +  +  +  :            456 :                 switch (svf->op)
                                     +  +  +  +  +  
                                     +  +  +  +  +  
                                              +  - ]
                              10097                 :                :                 {
                              10098                 :             69 :                     case SVFOP_CURRENT_DATE:
                              10099                 :             69 :                         appendStringInfoString(buf, "CURRENT_DATE");
                              10100                 :             69 :                         break;
                              10101                 :              8 :                     case SVFOP_CURRENT_TIME:
                              10102                 :              8 :                         appendStringInfoString(buf, "CURRENT_TIME");
                              10103                 :              8 :                         break;
                              10104                 :              8 :                     case SVFOP_CURRENT_TIME_N:
                              10105                 :              8 :                         appendStringInfo(buf, "CURRENT_TIME(%d)", svf->typmod);
                              10106                 :              8 :                         break;
                              10107                 :              8 :                     case SVFOP_CURRENT_TIMESTAMP:
                              10108                 :              8 :                         appendStringInfoString(buf, "CURRENT_TIMESTAMP");
                              10109                 :              8 :                         break;
                              10110                 :             78 :                     case SVFOP_CURRENT_TIMESTAMP_N:
                              10111                 :             78 :                         appendStringInfo(buf, "CURRENT_TIMESTAMP(%d)",
                              10112                 :                :                                          svf->typmod);
                              10113                 :             78 :                         break;
                              10114                 :              8 :                     case SVFOP_LOCALTIME:
                              10115                 :              8 :                         appendStringInfoString(buf, "LOCALTIME");
                              10116                 :              8 :                         break;
                              10117                 :              8 :                     case SVFOP_LOCALTIME_N:
                              10118                 :              8 :                         appendStringInfo(buf, "LOCALTIME(%d)", svf->typmod);
                              10119                 :              8 :                         break;
                              10120                 :             20 :                     case SVFOP_LOCALTIMESTAMP:
                              10121                 :             20 :                         appendStringInfoString(buf, "LOCALTIMESTAMP");
                              10122                 :             20 :                         break;
                              10123                 :             12 :                     case SVFOP_LOCALTIMESTAMP_N:
                              10124                 :             12 :                         appendStringInfo(buf, "LOCALTIMESTAMP(%d)",
                              10125                 :                :                                          svf->typmod);
                              10126                 :             12 :                         break;
                              10127                 :              8 :                     case SVFOP_CURRENT_ROLE:
                              10128                 :              8 :                         appendStringInfoString(buf, "CURRENT_ROLE");
                              10129                 :              8 :                         break;
                              10130                 :            185 :                     case SVFOP_CURRENT_USER:
                              10131                 :            185 :                         appendStringInfoString(buf, "CURRENT_USER");
                              10132                 :            185 :                         break;
                              10133                 :              8 :                     case SVFOP_USER:
                              10134                 :              8 :                         appendStringInfoString(buf, "USER");
                              10135                 :              8 :                         break;
                              10136                 :             20 :                     case SVFOP_SESSION_USER:
                              10137                 :             20 :                         appendStringInfoString(buf, "SESSION_USER");
                              10138                 :             20 :                         break;
                              10139                 :              8 :                     case SVFOP_CURRENT_CATALOG:
                              10140                 :              8 :                         appendStringInfoString(buf, "CURRENT_CATALOG");
                              10141                 :              8 :                         break;
                              10142                 :              8 :                     case SVFOP_CURRENT_SCHEMA:
                              10143                 :              8 :                         appendStringInfoString(buf, "CURRENT_SCHEMA");
                              10144                 :              8 :                         break;
                              10145                 :                :                 }
                              10146                 :                :             }
                              10147                 :            456 :             break;
                              10148                 :                : 
 7279 tgl@sss.pgh.pa.us       10149                 :            111 :         case T_XmlExpr:
                              10150                 :                :             {
 6953 bruce@momjian.us        10151                 :            111 :                 XmlExpr    *xexpr = (XmlExpr *) node;
                              10152                 :            111 :                 bool        needcomma = false;
                              10153                 :                :                 ListCell   *arg;
                              10154                 :                :                 ListCell   *narg;
                              10155                 :                :                 Const      *con;
                              10156                 :                : 
 7279 tgl@sss.pgh.pa.us       10157   [ +  +  +  +  :            111 :                 switch (xexpr->op)
                                        +  +  +  +  
                                                 - ]
                              10158                 :                :                 {
                              10159                 :              9 :                     case IS_XMLCONCAT:
                              10160                 :              9 :                         appendStringInfoString(buf, "XMLCONCAT(");
                              10161                 :              9 :                         break;
                              10162                 :             18 :                     case IS_XMLELEMENT:
                              10163                 :             18 :                         appendStringInfoString(buf, "XMLELEMENT(");
                              10164                 :             18 :                         break;
                              10165                 :              9 :                     case IS_XMLFOREST:
                              10166                 :              9 :                         appendStringInfoString(buf, "XMLFOREST(");
                              10167                 :              9 :                         break;
                              10168                 :              9 :                     case IS_XMLPARSE:
                              10169                 :              9 :                         appendStringInfoString(buf, "XMLPARSE(");
                              10170                 :              9 :                         break;
                              10171                 :              9 :                     case IS_XMLPI:
                              10172                 :              9 :                         appendStringInfoString(buf, "XMLPI(");
                              10173                 :              9 :                         break;
                              10174                 :              9 :                     case IS_XMLROOT:
                              10175                 :              9 :                         appendStringInfoString(buf, "XMLROOT(");
                              10176                 :              9 :                         break;
 7238 peter_e@gmx.net         10177                 :             36 :                     case IS_XMLSERIALIZE:
                              10178                 :             36 :                         appendStringInfoString(buf, "XMLSERIALIZE(");
                              10179                 :             36 :                         break;
 7258                         10180                 :             12 :                     case IS_DOCUMENT:
                              10181                 :                :                         /* postfix test, like IS NULL: not self-delimiting */
   39 tgl@sss.pgh.pa.us       10182         [ -  + ]:             12 :                         if (!PRETTY_PAREN(context))
   39 tgl@sss.pgh.pa.us       10183                 :UBC           0 :                             appendStringInfoChar(buf, '(');
 7258 peter_e@gmx.net         10184                 :CBC          12 :                         break;
                              10185                 :                :                 }
 7238                         10186   [ +  +  +  + ]:            111 :                 if (xexpr->op == IS_XMLPARSE || xexpr->op == IS_XMLSERIALIZE)
                              10187                 :                :                 {
                              10188         [ +  + ]:             45 :                     if (xexpr->xmloption == XMLOPTION_DOCUMENT)
                              10189                 :             18 :                         appendStringInfoString(buf, "DOCUMENT ");
                              10190                 :                :                     else
                              10191                 :             27 :                         appendStringInfoString(buf, "CONTENT ");
                              10192                 :                :                 }
 7279 tgl@sss.pgh.pa.us       10193         [ +  + ]:            111 :                 if (xexpr->name)
                              10194                 :                :                 {
                              10195                 :             27 :                     appendStringInfo(buf, "NAME %s",
 7274 peter_e@gmx.net         10196                 :             27 :                                      quote_identifier(map_xml_name_to_sql_identifier(xexpr->name)));
 7279 tgl@sss.pgh.pa.us       10197                 :             27 :                     needcomma = true;
                              10198                 :                :                 }
                              10199         [ +  + ]:            111 :                 if (xexpr->named_args)
                              10200                 :                :                 {
                              10201         [ +  + ]:             18 :                     if (xexpr->op != IS_XMLFOREST)
                              10202                 :                :                     {
                              10203         [ +  - ]:              9 :                         if (needcomma)
                              10204                 :              9 :                             appendStringInfoString(buf, ", ");
                              10205                 :              9 :                         appendStringInfoString(buf, "XMLATTRIBUTES(");
                              10206                 :              9 :                         needcomma = false;
                              10207                 :                :                     }
                              10208   [ +  -  +  +  :             63 :                     forboth(arg, xexpr->named_args, narg, xexpr->arg_names)
                                     +  -  +  +  +  
                                        +  +  -  +  
                                                 + ]
                              10209                 :                :                     {
 6953 bruce@momjian.us        10210                 :             45 :                         Node       *e = (Node *) lfirst(arg);
                              10211                 :             45 :                         char       *argname = strVal(lfirst(narg));
                              10212                 :                : 
 7279 tgl@sss.pgh.pa.us       10213         [ +  + ]:             45 :                         if (needcomma)
                              10214                 :             27 :                             appendStringInfoString(buf, ", ");
  361 peter@eisentraut.org    10215                 :             45 :                         get_rule_expr(e, context, true);
 7279 tgl@sss.pgh.pa.us       10216                 :             45 :                         appendStringInfo(buf, " AS %s",
 7274 peter_e@gmx.net         10217                 :             45 :                                          quote_identifier(map_xml_name_to_sql_identifier(argname)));
 7279 tgl@sss.pgh.pa.us       10218                 :             45 :                         needcomma = true;
                              10219                 :                :                     }
                              10220         [ +  + ]:             18 :                     if (xexpr->op != IS_XMLFOREST)
                              10221                 :              9 :                         appendStringInfoChar(buf, ')');
                              10222                 :                :                 }
                              10223         [ +  + ]:            111 :                 if (xexpr->args)
                              10224                 :                :                 {
                              10225         [ +  + ]:            102 :                     if (needcomma)
                              10226                 :             27 :                         appendStringInfoString(buf, ", ");
                              10227   [ +  +  +  +  :            102 :                     switch (xexpr->op)
                                                 - ]
                              10228                 :                :                     {
                              10229                 :             72 :                         case IS_XMLCONCAT:
                              10230                 :                :                         case IS_XMLELEMENT:
                              10231                 :                :                         case IS_XMLFOREST:
                              10232                 :                :                         case IS_XMLPI:
                              10233                 :                :                         case IS_XMLSERIALIZE:
                              10234                 :                :                             /* no extra decoration needed */
                              10235                 :             72 :                             get_rule_expr((Node *) xexpr->args, context, true);
                              10236                 :             72 :                             break;
                              10237                 :              9 :                         case IS_XMLPARSE:
 7238 peter_e@gmx.net         10238         [ -  + ]:              9 :                             Assert(list_length(xexpr->args) == 2);
                              10239                 :                : 
 7279 tgl@sss.pgh.pa.us       10240                 :              9 :                             get_rule_expr((Node *) linitial(xexpr->args),
                              10241                 :                :                                           context, true);
                              10242                 :                : 
 3519                         10243                 :              9 :                             con = lsecond_node(Const, xexpr->args);
 7279                         10244         [ -  + ]:              9 :                             Assert(!con->constisnull);
                              10245         [ -  + ]:              9 :                             if (DatumGetBool(con->constvalue))
 7279 tgl@sss.pgh.pa.us       10246                 :UBC           0 :                                 appendStringInfoString(buf,
                              10247                 :                :                                                        " PRESERVE WHITESPACE");
                              10248                 :                :                             else
 7279 tgl@sss.pgh.pa.us       10249                 :CBC           9 :                                 appendStringInfoString(buf,
                              10250                 :                :                                                        " STRIP WHITESPACE");
                              10251                 :              9 :                             break;
                              10252                 :              9 :                         case IS_XMLROOT:
                              10253         [ -  + ]:              9 :                             Assert(list_length(xexpr->args) == 3);
                              10254                 :                : 
                              10255                 :              9 :                             get_rule_expr((Node *) linitial(xexpr->args),
                              10256                 :                :                                           context, true);
                              10257                 :                : 
                              10258                 :              9 :                             appendStringInfoString(buf, ", VERSION ");
                              10259                 :              9 :                             con = (Const *) lsecond(xexpr->args);
                              10260         [ +  - ]:              9 :                             if (IsA(con, Const) &&
                              10261         [ +  - ]:              9 :                                 con->constisnull)
                              10262                 :              9 :                                 appendStringInfoString(buf, "NO VALUE");
                              10263                 :                :                             else
 7279 tgl@sss.pgh.pa.us       10264                 :UBC           0 :                                 get_rule_expr((Node *) con, context, false);
                              10265                 :                : 
 3519 tgl@sss.pgh.pa.us       10266                 :CBC           9 :                             con = lthird_node(Const, xexpr->args);
 7279                         10267         [ +  - ]:              9 :                             if (con->constisnull)
                              10268                 :                :                                  /* suppress STANDALONE NO VALUE */ ;
                              10269                 :                :                             else
                              10270                 :                :                             {
 7238 peter_e@gmx.net         10271   [ +  -  -  - ]:              9 :                                 switch (DatumGetInt32(con->constvalue))
                              10272                 :                :                                 {
                              10273                 :              9 :                                     case XML_STANDALONE_YES:
                              10274                 :              9 :                                         appendStringInfoString(buf,
                              10275                 :                :                                                                ", STANDALONE YES");
                              10276                 :              9 :                                         break;
 7238 peter_e@gmx.net         10277                 :UBC           0 :                                     case XML_STANDALONE_NO:
                              10278                 :              0 :                                         appendStringInfoString(buf,
                              10279                 :                :                                                                ", STANDALONE NO");
                              10280                 :              0 :                                         break;
                              10281                 :              0 :                                     case XML_STANDALONE_NO_VALUE:
                              10282                 :              0 :                                         appendStringInfoString(buf,
                              10283                 :                :                                                                ", STANDALONE NO VALUE");
                              10284                 :              0 :                                         break;
                              10285                 :              0 :                                     default:
                              10286                 :              0 :                                         break;
                              10287                 :                :                                 }
                              10288                 :                :                             }
 7279 tgl@sss.pgh.pa.us       10289                 :CBC           9 :                             break;
 7258 peter_e@gmx.net         10290                 :             12 :                         case IS_DOCUMENT:
   39 tgl@sss.pgh.pa.us       10291         [ -  + ]:             12 :                             Assert(list_length(xexpr->args) == 1);
                              10292                 :             12 :                             get_rule_expr_paren((Node *) linitial(xexpr->args),
                              10293                 :                :                                                 context, false, node);
 7258 peter_e@gmx.net         10294                 :             12 :                             break;
                              10295                 :                :                     }
                              10296                 :                :                 }
 7238                         10297         [ +  + ]:            111 :                 if (xexpr->op == IS_XMLSERIALIZE)
                              10298                 :                :                 {
 5733 tgl@sss.pgh.pa.us       10299                 :             36 :                     appendStringInfo(buf, " AS %s",
                              10300                 :                :                                      format_type_with_typemod(xexpr->type,
                              10301                 :                :                                                               xexpr->typmod));
  645 michael@paquier.xyz     10302         [ +  + ]:             36 :                     if (xexpr->indent)
                              10303                 :              9 :                         appendStringInfoString(buf, " INDENT");
                              10304                 :                :                     else
                              10305                 :             27 :                         appendStringInfoString(buf, " NO INDENT");
                              10306                 :                :                 }
                              10307                 :                : 
 7258 peter_e@gmx.net         10308         [ +  + ]:            111 :                 if (xexpr->op == IS_DOCUMENT)
                              10309                 :                :                 {
                              10310                 :             12 :                     appendStringInfoString(buf, " IS DOCUMENT");
   39 tgl@sss.pgh.pa.us       10311         [ -  + ]:             12 :                     if (!PRETTY_PAREN(context))
   39 tgl@sss.pgh.pa.us       10312                 :UBC           0 :                         appendStringInfoChar(buf, ')');
                              10313                 :                :                 }
                              10314                 :                :                 else
 7258 peter_e@gmx.net         10315                 :CBC          99 :                     appendStringInfoChar(buf, ')');
                              10316                 :                :             }
 7279 tgl@sss.pgh.pa.us       10317                 :            111 :             break;
                              10318                 :                : 
 9293                         10319                 :           2046 :         case T_NullTest:
                              10320                 :                :             {
 9165 bruce@momjian.us        10321                 :           2046 :                 NullTest   *ntest = (NullTest *) node;
                              10322                 :                : 
 8522 tgl@sss.pgh.pa.us       10323         [ +  + ]:           2046 :                 if (!PRETTY_PAREN(context))
 8517 bruce@momjian.us        10324                 :           2006 :                     appendStringInfoChar(buf, '(');
 8522 tgl@sss.pgh.pa.us       10325                 :           2046 :                 get_rule_expr_paren((Node *) ntest->arg, context, true, node);
                              10326                 :                : 
                              10327                 :                :                 /*
                              10328                 :                :                  * For scalar inputs, we prefer to print as IS [NOT] NULL,
                              10329                 :                :                  * which is shorter and traditional.  If it's a rowtype input
                              10330                 :                :                  * but we're applying a scalar test, must print IS [NOT]
                              10331                 :                :                  * DISTINCT FROM NULL to be semantically correct.
                              10332                 :                :                  */
 3775                         10333         [ +  + ]:           2046 :                 if (ntest->argisrow ||
                              10334         [ +  + ]:           1948 :                     !type_is_rowtype(exprType((Node *) ntest->arg)))
                              10335                 :                :                 {
                              10336      [ +  +  - ]:           2026 :                     switch (ntest->nulltesttype)
                              10337                 :                :                     {
                              10338                 :            692 :                         case IS_NULL:
                              10339                 :            692 :                             appendStringInfoString(buf, " IS NULL");
                              10340                 :            692 :                             break;
                              10341                 :           1334 :                         case IS_NOT_NULL:
                              10342                 :           1334 :                             appendStringInfoString(buf, " IS NOT NULL");
                              10343                 :           1334 :                             break;
 3775 tgl@sss.pgh.pa.us       10344                 :UBC           0 :                         default:
                              10345         [ #  # ]:              0 :                             elog(ERROR, "unrecognized nulltesttype: %d",
                              10346                 :                :                                  (int) ntest->nulltesttype);
                              10347                 :                :                     }
                              10348                 :                :                 }
                              10349                 :                :                 else
                              10350                 :                :                 {
 3775 tgl@sss.pgh.pa.us       10351      [ +  +  - ]:CBC          20 :                     switch (ntest->nulltesttype)
                              10352                 :                :                     {
                              10353                 :              8 :                         case IS_NULL:
                              10354                 :              8 :                             appendStringInfoString(buf, " IS NOT DISTINCT FROM NULL");
                              10355                 :              8 :                             break;
                              10356                 :             12 :                         case IS_NOT_NULL:
                              10357                 :             12 :                             appendStringInfoString(buf, " IS DISTINCT FROM NULL");
                              10358                 :             12 :                             break;
 3775 tgl@sss.pgh.pa.us       10359                 :UBC           0 :                         default:
                              10360         [ #  # ]:              0 :                             elog(ERROR, "unrecognized nulltesttype: %d",
                              10361                 :                :                                  (int) ntest->nulltesttype);
                              10362                 :                :                     }
                              10363                 :                :                 }
 8522 tgl@sss.pgh.pa.us       10364         [ +  + ]:CBC        2046 :                 if (!PRETTY_PAREN(context))
 8517 bruce@momjian.us        10365                 :           2006 :                     appendStringInfoChar(buf, ')');
                              10366                 :                :             }
 9293 tgl@sss.pgh.pa.us       10367                 :           2046 :             break;
                              10368                 :                : 
                              10369                 :            212 :         case T_BooleanTest:
                              10370                 :                :             {
 9165 bruce@momjian.us        10371                 :            212 :                 BooleanTest *btest = (BooleanTest *) node;
                              10372                 :                : 
 8522 tgl@sss.pgh.pa.us       10373         [ +  - ]:            212 :                 if (!PRETTY_PAREN(context))
 8517 bruce@momjian.us        10374                 :            212 :                     appendStringInfoChar(buf, '(');
 8522 tgl@sss.pgh.pa.us       10375                 :            212 :                 get_rule_expr_paren((Node *) btest->arg, context, false, node);
 9165 bruce@momjian.us        10376   [ +  +  -  +  :            212 :                 switch (btest->booltesttype)
                                           +  +  - ]
                              10377                 :                :                 {
                              10378                 :             28 :                     case IS_TRUE:
 4776 rhaas@postgresql.org    10379                 :             28 :                         appendStringInfoString(buf, " IS TRUE");
 9293 tgl@sss.pgh.pa.us       10380                 :             28 :                         break;
 9165 bruce@momjian.us        10381                 :             92 :                     case IS_NOT_TRUE:
 4776 rhaas@postgresql.org    10382                 :             92 :                         appendStringInfoString(buf, " IS NOT TRUE");
 9293 tgl@sss.pgh.pa.us       10383                 :             92 :                         break;
 9165 bruce@momjian.us        10384                 :UBC           0 :                     case IS_FALSE:
 4776 rhaas@postgresql.org    10385                 :              0 :                         appendStringInfoString(buf, " IS FALSE");
 9293 tgl@sss.pgh.pa.us       10386                 :              0 :                         break;
 9165 bruce@momjian.us        10387                 :CBC          36 :                     case IS_NOT_FALSE:
 4776 rhaas@postgresql.org    10388                 :             36 :                         appendStringInfoString(buf, " IS NOT FALSE");
 9293 tgl@sss.pgh.pa.us       10389                 :             36 :                         break;
 9165 bruce@momjian.us        10390                 :             20 :                     case IS_UNKNOWN:
 4776 rhaas@postgresql.org    10391                 :             20 :                         appendStringInfoString(buf, " IS UNKNOWN");
 9293 tgl@sss.pgh.pa.us       10392                 :             20 :                         break;
 9165 bruce@momjian.us        10393                 :             36 :                     case IS_NOT_UNKNOWN:
 4776 rhaas@postgresql.org    10394                 :             36 :                         appendStringInfoString(buf, " IS NOT UNKNOWN");
 9293 tgl@sss.pgh.pa.us       10395                 :             36 :                         break;
 9165 bruce@momjian.us        10396                 :UBC           0 :                     default:
 8525 tgl@sss.pgh.pa.us       10397         [ #  # ]:              0 :                         elog(ERROR, "unrecognized booltesttype: %d",
                              10398                 :                :                              (int) btest->booltesttype);
                              10399                 :                :                 }
 8522 tgl@sss.pgh.pa.us       10400         [ +  - ]:CBC         212 :                 if (!PRETTY_PAREN(context))
 8517 bruce@momjian.us        10401                 :            212 :                     appendStringInfoChar(buf, ')');
                              10402                 :                :             }
 9293 tgl@sss.pgh.pa.us       10403                 :            212 :             break;
                              10404                 :                : 
 8699                         10405                 :             91 :         case T_CoerceToDomain:
                              10406                 :                :             {
                              10407                 :             91 :                 CoerceToDomain *ctest = (CoerceToDomain *) node;
 8517 bruce@momjian.us        10408                 :             91 :                 Node       *arg = (Node *) ctest->arg;
                              10409                 :                : 
 8699 tgl@sss.pgh.pa.us       10410         [ +  + ]:             91 :                 if (ctest->coercionformat == COERCE_IMPLICIT_CAST &&
                              10411         [ +  + ]:             36 :                     !showimplicit)
                              10412                 :                :                 {
                              10413                 :                :                     /* don't show the implicit cast */
                              10414                 :             28 :                     get_rule_expr(arg, context, false);
                              10415                 :                :                 }
                              10416                 :                :                 else
                              10417                 :                :                 {
 7196                         10418                 :             63 :                     get_coercion_expr(arg, context,
                              10419                 :                :                                       ctest->resulttype,
                              10420                 :                :                                       ctest->resulttypmod,
                              10421                 :                :                                       node);
                              10422                 :                :                 }
                              10423                 :                :             }
 8855                         10424                 :             91 :             break;
                              10425                 :                : 
 8699                         10426                 :            266 :         case T_CoerceToDomainValue:
 4776 rhaas@postgresql.org    10427                 :            266 :             appendStringInfoString(buf, "VALUE");
 9027 tgl@sss.pgh.pa.us       10428                 :            266 :             break;
                              10429                 :                : 
 8549                         10430                 :             44 :         case T_SetToDefault:
 4776 rhaas@postgresql.org    10431                 :             44 :             appendStringInfoString(buf, "DEFAULT");
 8549 tgl@sss.pgh.pa.us       10432                 :             44 :             break;
                              10433                 :                : 
 7110                         10434                 :             16 :         case T_CurrentOfExpr:
                              10435                 :                :             {
                              10436                 :             16 :                 CurrentOfExpr *cexpr = (CurrentOfExpr *) node;
                              10437                 :                : 
                              10438         [ +  - ]:             16 :                 if (cexpr->cursor_name)
                              10439                 :             16 :                     appendStringInfo(buf, "CURRENT OF %s",
                              10440                 :             16 :                                      quote_identifier(cexpr->cursor_name));
                              10441                 :                :                 else
 7110 tgl@sss.pgh.pa.us       10442                 :UBC           0 :                     appendStringInfo(buf, "CURRENT OF $%d",
                              10443                 :                :                                      cexpr->cursor_param);
                              10444                 :                :             }
 7110 tgl@sss.pgh.pa.us       10445                 :CBC          16 :             break;
                              10446                 :                : 
 3424 tgl@sss.pgh.pa.us       10447                 :UBC           0 :         case T_NextValueExpr:
                              10448                 :                :             {
                              10449                 :              0 :                 NextValueExpr *nvexpr = (NextValueExpr *) node;
                              10450                 :                : 
                              10451                 :                :                 /*
                              10452                 :                :                  * This isn't exactly nextval(), but that seems close enough
                              10453                 :                :                  * for EXPLAIN's purposes.
                              10454                 :                :                  */
                              10455                 :              0 :                 appendStringInfoString(buf, "nextval(");
                              10456                 :              0 :                 simple_quote_literal(buf,
                              10457                 :              0 :                                      generate_relation_name(nvexpr->seqid,
                              10458                 :                :                                                             NIL));
                              10459                 :              0 :                 appendStringInfoChar(buf, ')');
                              10460                 :                :             }
                              10461                 :              0 :             break;
                              10462                 :                : 
 4211 andres@anarazel.de      10463                 :CBC          20 :         case T_InferenceElem:
                              10464                 :                :             {
 4207 bruce@momjian.us        10465                 :             20 :                 InferenceElem *iexpr = (InferenceElem *) node;
                              10466                 :                :                 bool        save_varprefix;
                              10467                 :                :                 bool        need_parens;
                              10468                 :                : 
                              10469                 :                :                 /*
                              10470                 :                :                  * InferenceElem can only refer to target relation, so a
                              10471                 :                :                  * prefix is not useful, and indeed would cause parse errors.
                              10472                 :                :                  */
 3947 tgl@sss.pgh.pa.us       10473                 :             20 :                 save_varprefix = context->varprefix;
 4211 andres@anarazel.de      10474                 :             20 :                 context->varprefix = false;
                              10475                 :                : 
                              10476                 :                :                 /*
                              10477                 :                :                  * Parenthesize the element unless it's a simple Var or a bare
                              10478                 :                :                  * function call.  Follows pg_get_indexdef_worker().
                              10479                 :                :                  */
                              10480                 :             20 :                 need_parens = !IsA(iexpr->expr, Var);
                              10481         [ -  + ]:             20 :                 if (IsA(iexpr->expr, FuncExpr) &&
 4211 andres@anarazel.de      10482         [ #  # ]:UBC           0 :                     ((FuncExpr *) iexpr->expr)->funcformat ==
                              10483                 :                :                     COERCE_EXPLICIT_CALL)
                              10484                 :              0 :                     need_parens = false;
                              10485                 :                : 
 4211 andres@anarazel.de      10486         [ -  + ]:CBC          20 :                 if (need_parens)
 4211 andres@anarazel.de      10487                 :UBC           0 :                     appendStringInfoChar(buf, '(');
 4211 andres@anarazel.de      10488                 :CBC          20 :                 get_rule_expr((Node *) iexpr->expr,
                              10489                 :                :                               context, false);
                              10490         [ -  + ]:             20 :                 if (need_parens)
 4211 andres@anarazel.de      10491                 :UBC           0 :                     appendStringInfoChar(buf, ')');
                              10492                 :                : 
 3947 tgl@sss.pgh.pa.us       10493                 :CBC          20 :                 context->varprefix = save_varprefix;
                              10494                 :                : 
 4211 andres@anarazel.de      10495         [ +  + ]:             20 :                 if (iexpr->infercollid)
                              10496                 :              8 :                     appendStringInfo(buf, " COLLATE %s",
                              10497                 :                :                                      generate_collation_name(iexpr->infercollid));
                              10498                 :                : 
                              10499                 :                :                 /* Add the operator class name, if not default */
                              10500         [ +  + ]:             20 :                 if (iexpr->inferopclass)
                              10501                 :                :                 {
 4207 bruce@momjian.us        10502                 :              8 :                     Oid         inferopclass = iexpr->inferopclass;
                              10503                 :              8 :                     Oid         inferopcinputtype = get_opclass_input_type(iexpr->inferopclass);
                              10504                 :                : 
 4211 andres@anarazel.de      10505                 :              8 :                     get_opclass_name(inferopclass, inferopcinputtype, buf);
                              10506                 :                :                 }
                              10507                 :                :             }
                              10508                 :             20 :             break;
                              10509                 :                : 
  681 dean.a.rasheed@gmail    10510                 :              8 :         case T_ReturningExpr:
                              10511                 :                :             {
                              10512                 :              8 :                 ReturningExpr *retExpr = (ReturningExpr *) node;
                              10513                 :                : 
                              10514                 :                :                 /*
                              10515                 :                :                  * We cannot see a ReturningExpr in rule deparsing, only while
                              10516                 :                :                  * EXPLAINing a query plan (ReturningExpr nodes are only ever
                              10517                 :                :                  * adding during query rewriting). Just display the expression
                              10518                 :                :                  * returned (an expanded view column).
                              10519                 :                :                  */
                              10520                 :              8 :                 get_rule_expr((Node *) retExpr->retexpr, context, showimplicit);
                              10521                 :                :             }
                              10522                 :              8 :             break;
                              10523                 :                : 
 3643 rhaas@postgresql.org    10524                 :           2436 :         case T_PartitionBoundSpec:
                              10525                 :                :             {
                              10526                 :           2436 :                 PartitionBoundSpec *spec = (PartitionBoundSpec *) node;
                              10527                 :                :                 ListCell   *cell;
                              10528                 :                :                 char       *sep;
                              10529                 :                : 
 3368                         10530         [ +  + ]:           2436 :                 if (spec->is_default)
                              10531                 :                :                 {
                              10532                 :             89 :                     appendStringInfoString(buf, "DEFAULT");
                              10533                 :             89 :                     break;
                              10534                 :                :                 }
                              10535                 :                : 
 3643                         10536   [ +  +  +  - ]:           2347 :                 switch (spec->strategy)
                              10537                 :                :                 {
 3306                         10538                 :            181 :                     case PARTITION_STRATEGY_HASH:
                              10539   [ +  -  -  + ]:            181 :                         Assert(spec->modulus > 0 && spec->remainder >= 0);
                              10540         [ -  + ]:            181 :                         Assert(spec->modulus > spec->remainder);
                              10541                 :                : 
                              10542                 :            181 :                         appendStringInfoString(buf, "FOR VALUES");
                              10543                 :            181 :                         appendStringInfo(buf, " WITH (modulus %d, remainder %d)",
                              10544                 :                :                                          spec->modulus, spec->remainder);
                              10545                 :            181 :                         break;
                              10546                 :                : 
 3643                         10547                 :            823 :                     case PARTITION_STRATEGY_LIST:
                              10548         [ -  + ]:            823 :                         Assert(spec->listdatums != NIL);
                              10549                 :                : 
 3471 tgl@sss.pgh.pa.us       10550                 :            823 :                         appendStringInfoString(buf, "FOR VALUES IN (");
 3643 rhaas@postgresql.org    10551                 :            823 :                         sep = "";
 3595                         10552   [ +  -  +  +  :           2120 :                         foreach(cell, spec->listdatums)
                                              +  + ]
                              10553                 :                :                         {
 1958 peter@eisentraut.org    10554                 :           1297 :                             Const      *val = lfirst_node(Const, cell);
                              10555                 :                : 
 3643 rhaas@postgresql.org    10556                 :           1297 :                             appendStringInfoString(buf, sep);
                              10557                 :           1297 :                             get_const_expr(val, context, -1);
                              10558                 :           1297 :                             sep = ", ";
                              10559                 :                :                         }
                              10560                 :                : 
 3392 peter_e@gmx.net         10561                 :            823 :                         appendStringInfoChar(buf, ')');
 3643 rhaas@postgresql.org    10562                 :            823 :                         break;
                              10563                 :                : 
                              10564                 :           1343 :                     case PARTITION_STRATEGY_RANGE:
                              10565   [ +  -  +  -  :           1343 :                         Assert(spec->lowerdatums != NIL &&
                                              -  + ]
                              10566                 :                :                                spec->upperdatums != NIL &&
                              10567                 :                :                                list_length(spec->lowerdatums) ==
                              10568                 :                :                                list_length(spec->upperdatums));
                              10569                 :                : 
 3397                         10570                 :           1343 :                         appendStringInfo(buf, "FOR VALUES FROM %s TO %s",
                              10571                 :                :                                          get_range_partbound_string(spec->lowerdatums),
                              10572                 :                :                                          get_range_partbound_string(spec->upperdatums));
 3643                         10573                 :           1343 :                         break;
                              10574                 :                : 
 3643 rhaas@postgresql.org    10575                 :UBC           0 :                     default:
                              10576         [ #  # ]:              0 :                         elog(ERROR, "unrecognized partition strategy: %d",
                              10577                 :                :                              (int) spec->strategy);
                              10578                 :                :                         break;
                              10579                 :                :                 }
                              10580                 :                :             }
 3643 rhaas@postgresql.org    10581                 :CBC        2347 :             break;
                              10582                 :                : 
 1340 alvherre@alvh.no-ip.    10583                 :            104 :         case T_JsonValueExpr:
                              10584                 :                :             {
                              10585                 :            104 :                 JsonValueExpr *jve = (JsonValueExpr *) node;
                              10586                 :                : 
                              10587                 :            104 :                 get_rule_expr((Node *) jve->raw_expr, context, false);
                              10588                 :            104 :                 get_json_format(jve->format, context->buf);
                              10589                 :                :             }
                              10590                 :            104 :             break;
                              10591                 :                : 
                              10592                 :            188 :         case T_JsonConstructorExpr:
                              10593                 :            188 :             get_json_constructor((JsonConstructorExpr *) node, context, false);
                              10594                 :            188 :             break;
                              10595                 :                : 
 1338                         10596                 :             52 :         case T_JsonIsPredicate:
                              10597                 :                :             {
                              10598                 :             52 :                 JsonIsPredicate *pred = (JsonIsPredicate *) node;
                              10599                 :                : 
                              10600         [ +  + ]:             52 :                 if (!PRETTY_PAREN(context))
                              10601                 :             20 :                     appendStringInfoChar(context->buf, '(');
                              10602                 :                : 
                              10603                 :             52 :                 get_rule_expr_paren(pred->expr, context, true, node);
                              10604                 :                : 
                              10605                 :             52 :                 appendStringInfoString(context->buf, " IS JSON");
                              10606                 :                : 
                              10607                 :                :                 /* TODO: handle FORMAT clause */
                              10608                 :                : 
                              10609   [ +  +  +  + ]:             52 :                 switch (pred->item_type)
                              10610                 :                :                 {
                              10611                 :              8 :                     case JS_TYPE_SCALAR:
                              10612                 :              8 :                         appendStringInfoString(context->buf, " SCALAR");
                              10613                 :              8 :                         break;
                              10614                 :              8 :                     case JS_TYPE_ARRAY:
                              10615                 :              8 :                         appendStringInfoString(context->buf, " ARRAY");
                              10616                 :              8 :                         break;
                              10617                 :              8 :                     case JS_TYPE_OBJECT:
                              10618                 :              8 :                         appendStringInfoString(context->buf, " OBJECT");
                              10619                 :              8 :                         break;
                              10620                 :             28 :                     default:
                              10621                 :             28 :                         break;
                              10622                 :                :                 }
                              10623                 :                : 
                              10624         [ +  + ]:             52 :                 if (pred->unique_keys)
                              10625                 :             20 :                     appendStringInfoString(context->buf, " WITH UNIQUE KEYS");
                              10626                 :                : 
                              10627         [ +  + ]:             52 :                 if (!PRETTY_PAREN(context))
                              10628                 :             20 :                     appendStringInfoChar(context->buf, ')');
                              10629                 :                :             }
                              10630                 :             52 :             break;
                              10631                 :                : 
  982 amitlan@postgresql.o    10632                 :             40 :         case T_JsonExpr:
                              10633                 :                :             {
                              10634                 :             40 :                 JsonExpr   *jexpr = (JsonExpr *) node;
                              10635                 :                : 
                              10636   [ +  +  +  - ]:             40 :                 switch (jexpr->op)
                              10637                 :                :                 {
                              10638                 :              8 :                     case JSON_EXISTS_OP:
                              10639                 :              8 :                         appendStringInfoString(buf, "JSON_EXISTS(");
                              10640                 :              8 :                         break;
                              10641                 :             24 :                     case JSON_QUERY_OP:
                              10642                 :             24 :                         appendStringInfoString(buf, "JSON_QUERY(");
                              10643                 :             24 :                         break;
                              10644                 :              8 :                     case JSON_VALUE_OP:
                              10645                 :              8 :                         appendStringInfoString(buf, "JSON_VALUE(");
                              10646                 :              8 :                         break;
  982 amitlan@postgresql.o    10647                 :UBC           0 :                     default:
                              10648         [ #  # ]:              0 :                         elog(ERROR, "unrecognized JsonExpr op: %d",
                              10649                 :                :                              (int) jexpr->op);
                              10650                 :                :                 }
                              10651                 :                : 
  982 amitlan@postgresql.o    10652                 :CBC          40 :                 get_rule_expr(jexpr->formatted_expr, context, showimplicit);
                              10653                 :                : 
                              10654                 :             40 :                 appendStringInfoString(buf, ", ");
                              10655                 :                : 
                              10656                 :             40 :                 get_json_path_spec(jexpr->path_spec, context, showimplicit);
                              10657                 :                : 
                              10658         [ +  + ]:             40 :                 if (jexpr->passing_values)
                              10659                 :                :                 {
                              10660                 :                :                     ListCell   *lc1,
                              10661                 :                :                                *lc2;
                              10662                 :              8 :                     bool        needcomma = false;
                              10663                 :                : 
                              10664                 :              8 :                     appendStringInfoString(buf, " PASSING ");
                              10665                 :                : 
                              10666   [ +  -  +  +  :             32 :                     forboth(lc1, jexpr->passing_names,
                                     +  -  +  +  +  
                                        +  +  -  +  
                                                 + ]
                              10667                 :                :                             lc2, jexpr->passing_values)
                              10668                 :                :                     {
                              10669         [ +  + ]:             24 :                         if (needcomma)
                              10670                 :             16 :                             appendStringInfoString(buf, ", ");
                              10671                 :             24 :                         needcomma = true;
                              10672                 :                : 
                              10673                 :             24 :                         get_rule_expr((Node *) lfirst(lc2), context, showimplicit);
                              10674                 :             24 :                         appendStringInfo(buf, " AS %s",
  685 dean.a.rasheed@gmail    10675                 :             24 :                                          quote_identifier(lfirst_node(String, lc1)->sval));
                              10676                 :                :                     }
                              10677                 :                :                 }
                              10678                 :                : 
  982 amitlan@postgresql.o    10679         [ +  + ]:             40 :                 if (jexpr->op != JSON_EXISTS_OP ||
                              10680         [ -  + ]:              8 :                     jexpr->returning->typid != BOOLOID)
                              10681                 :             32 :                     get_json_returning(jexpr->returning, context->buf,
                              10682                 :             32 :                                        jexpr->op == JSON_QUERY_OP);
                              10683                 :                : 
                              10684                 :             40 :                 get_json_expr_options(jexpr, context,
                              10685         [ +  + ]:             40 :                                       jexpr->op != JSON_EXISTS_OP ?
                              10686                 :                :                                       JSON_BEHAVIOR_NULL :
                              10687                 :                :                                       JSON_BEHAVIOR_FALSE);
                              10688                 :                : 
  962 drowley@postgresql.o    10689                 :             40 :                 appendStringInfoChar(buf, ')');
                              10690                 :                :             }
  982 amitlan@postgresql.o    10691                 :             40 :             break;
                              10692                 :                : 
 8087 tgl@sss.pgh.pa.us       10693                 :           2182 :         case T_List:
                              10694                 :                :             {
                              10695                 :                :                 char       *sep;
                              10696                 :                :                 ListCell   *l;
                              10697                 :                : 
                              10698                 :           2182 :                 sep = "";
                              10699   [ +  -  +  +  :           6185 :                 foreach(l, (List *) node)
                                              +  + ]
                              10700                 :                :                 {
 7882 neilc@samurai.com       10701                 :           4003 :                     appendStringInfoString(buf, sep);
 8087 tgl@sss.pgh.pa.us       10702                 :           4003 :                     get_rule_expr((Node *) lfirst(l), context, showimplicit);
                              10703                 :           4003 :                     sep = ", ";
                              10704                 :                :                 }
                              10705                 :                :             }
                              10706                 :           2182 :             break;
                              10707                 :                : 
 3552 alvherre@alvh.no-ip.    10708                 :             52 :         case T_TableFunc:
                              10709                 :             52 :             get_tablefunc((TableFunc *) node, context, showimplicit);
                              10710                 :             52 :             break;
                              10711                 :                : 
10315 bruce@momjian.us        10712                 :UBC           0 :         default:
 8525 tgl@sss.pgh.pa.us       10713         [ #  # ]:              0 :             elog(ERROR, "unrecognized node type: %d", (int) nodeTag(node));
                              10714                 :                :             break;
                              10715                 :                :     }
                              10716                 :                : }
                              10717                 :                : 
                              10718                 :                : /*
                              10719                 :                :  * get_rule_expr_toplevel       - Parse back a toplevel expression
                              10720                 :                :  *
                              10721                 :                :  * Same as get_rule_expr(), except that if the expr is just a Var, we pass
                              10722                 :                :  * istoplevel = true not false to get_variable().  This causes whole-row Vars
                              10723                 :                :  * to get printed with decoration that will prevent expansion of "*".
                              10724                 :                :  * We need to use this in contexts such as ROW() and VALUES(), where the
                              10725                 :                :  * parser would expand "foo.*" appearing at top level.  (In principle we'd
                              10726                 :                :  * use this in get_target_list() too, but that has additional worries about
                              10727                 :                :  * whether to print AS, so it needs to invoke get_variable() directly anyway.)
                              10728                 :                :  */
                              10729                 :                : static void
 4031 tgl@sss.pgh.pa.us       10730                 :CBC        2623 : get_rule_expr_toplevel(Node *node, deparse_context *context,
                              10731                 :                :                        bool showimplicit)
                              10732                 :                : {
                              10733   [ +  -  +  + ]:           2623 :     if (node && IsA(node, Var))
                              10734                 :           1146 :         (void) get_variable((Var *) node, 0, true, context);
                              10735                 :                :     else
                              10736                 :           1477 :         get_rule_expr(node, context, showimplicit);
                              10737                 :           2623 : }
                              10738                 :                : 
                              10739                 :                : /*
                              10740                 :                :  * get_rule_list_toplevel       - Parse back a list of toplevel expressions
                              10741                 :                :  *
                              10742                 :                :  * Apply get_rule_expr_toplevel() to each element of a List.
                              10743                 :                :  *
                              10744                 :                :  * This adds commas between the expressions, but caller is responsible
                              10745                 :                :  * for printing surrounding decoration.
                              10746                 :                :  */
                              10747                 :                : static void
 1780                         10748                 :            366 : get_rule_list_toplevel(List *lst, deparse_context *context,
                              10749                 :                :                        bool showimplicit)
                              10750                 :                : {
                              10751                 :                :     const char *sep;
                              10752                 :                :     ListCell   *lc;
                              10753                 :                : 
                              10754                 :            366 :     sep = "";
                              10755   [ +  -  +  +  :           1207 :     foreach(lc, lst)
                                              +  + ]
                              10756                 :                :     {
                              10757                 :            841 :         Node       *e = (Node *) lfirst(lc);
                              10758                 :                : 
                              10759                 :            841 :         appendStringInfoString(context->buf, sep);
                              10760                 :            841 :         get_rule_expr_toplevel(e, context, showimplicit);
                              10761                 :            841 :         sep = ", ";
                              10762                 :                :     }
                              10763                 :            366 : }
                              10764                 :                : 
                              10765                 :                : /*
                              10766                 :                :  * get_rule_expr_funccall       - Parse back a function-call expression
                              10767                 :                :  *
                              10768                 :                :  * Same as get_rule_expr(), except that we guarantee that the output will
                              10769                 :                :  * look like a function call, or like one of the things the grammar treats as
                              10770                 :                :  * equivalent to a function call (see the func_expr_windowless production).
                              10771                 :                :  * This is needed in places where the grammar uses func_expr_windowless and
                              10772                 :                :  * you can't substitute a parenthesized a_expr.  If what we have isn't going
                              10773                 :                :  * to look like a function call, wrap it in a dummy CAST() expression, which
                              10774                 :                :  * will satisfy the grammar --- and, indeed, is likely what the user wrote to
                              10775                 :                :  * produce such a thing.
                              10776                 :                :  */
                              10777                 :                : static void
 3425                         10778                 :            576 : get_rule_expr_funccall(Node *node, deparse_context *context,
                              10779                 :                :                        bool showimplicit)
                              10780                 :                : {
                              10781         [ +  + ]:            576 :     if (looks_like_function(node))
                              10782                 :            564 :         get_rule_expr(node, context, showimplicit);
                              10783                 :                :     else
                              10784                 :                :     {
                              10785                 :             12 :         StringInfo  buf = context->buf;
                              10786                 :                : 
                              10787                 :             12 :         appendStringInfoString(buf, "CAST(");
                              10788                 :                :         /* no point in showing any top-level implicit cast */
                              10789                 :             12 :         get_rule_expr(node, context, false);
                              10790                 :             12 :         appendStringInfo(buf, " AS %s)",
                              10791                 :                :                          format_type_with_typemod(exprType(node),
                              10792                 :                :                                                   exprTypmod(node)));
                              10793                 :                :     }
                              10794                 :            576 : }
                              10795                 :                : 
                              10796                 :                : /*
                              10797                 :                :  * Helper function to identify node types that satisfy func_expr_windowless.
                              10798                 :                :  * If in doubt, "false" is always a safe answer.
                              10799                 :                :  */
                              10800                 :                : static bool
                              10801                 :           1534 : looks_like_function(Node *node)
                              10802                 :                : {
                              10803         [ -  + ]:           1534 :     if (node == NULL)
 3425 tgl@sss.pgh.pa.us       10804                 :UBC           0 :         return false;           /* probably shouldn't happen */
 3425 tgl@sss.pgh.pa.us       10805   [ +  +  -  + ]:CBC        1534 :     switch (nodeTag(node))
                              10806                 :                :     {
                              10807                 :            588 :         case T_FuncExpr:
                              10808                 :                :             /* OK if it will print as a normal function call */
   32                         10809         [ +  + ]:            588 :             if (((FuncExpr *) node)->funcformat == COERCE_EXPLICIT_CALL)
                              10810                 :            572 :                 return true;
                              10811                 :                :             /* SQL_SYNTAX needs case-by-case analysis; all else is unsafe */
                              10812         [ +  + ]:             16 :             if (((FuncExpr *) node)->funcformat != COERCE_SQL_SYNTAX)
                              10813                 :              4 :                 return false;
                              10814                 :                : 
                              10815                 :                :             /*
                              10816                 :                :              * Most SQL-syntax functions are accepted by func_expr_windowless,
                              10817                 :                :              * but get_func_sql_syntax() prints AT TIME ZONE, AT LOCAL,
                              10818                 :                :              * OVERLAPS and IS xxx NORMALIZED in forms that aren't accepted.
                              10819                 :                :              * All of the associated functions must be listed here.
                              10820                 :                :              */
                              10821         [ +  + ]:             12 :             switch (((FuncExpr *) node)->funcid)
                              10822                 :                :             {
                              10823                 :                :                     /* AT TIME ZONE: */
                              10824                 :              4 :                 case F_TIMEZONE_INTERVAL_TIMESTAMP:
                              10825                 :                :                 case F_TIMEZONE_INTERVAL_TIMESTAMPTZ:
                              10826                 :                :                 case F_TIMEZONE_INTERVAL_TIMETZ:
                              10827                 :                :                 case F_TIMEZONE_TEXT_TIMESTAMP:
                              10828                 :                :                 case F_TIMEZONE_TEXT_TIMESTAMPTZ:
                              10829                 :                :                 case F_TIMEZONE_TEXT_TIMETZ:
                              10830                 :                :                     /* AT LOCAL: */
                              10831                 :                :                 case F_TIMEZONE_TIMESTAMP:
                              10832                 :                :                 case F_TIMEZONE_TIMESTAMPTZ:
                              10833                 :                :                 case F_TIMEZONE_TIMETZ:
                              10834                 :                :                     /* OVERLAPS: */
                              10835                 :                :                 case F_OVERLAPS_TIMESTAMPTZ_INTERVAL_TIMESTAMPTZ_INTERVAL:
                              10836                 :                :                 case F_OVERLAPS_TIMESTAMPTZ_INTERVAL_TIMESTAMPTZ_TIMESTAMPTZ:
                              10837                 :                :                 case F_OVERLAPS_TIMESTAMPTZ_TIMESTAMPTZ_TIMESTAMPTZ_INTERVAL:
                              10838                 :                :                 case F_OVERLAPS_TIMESTAMPTZ_TIMESTAMPTZ_TIMESTAMPTZ_TIMESTAMPTZ:
                              10839                 :                :                 case F_OVERLAPS_TIMESTAMP_INTERVAL_TIMESTAMP_INTERVAL:
                              10840                 :                :                 case F_OVERLAPS_TIMESTAMP_INTERVAL_TIMESTAMP_TIMESTAMP:
                              10841                 :                :                 case F_OVERLAPS_TIMESTAMP_TIMESTAMP_TIMESTAMP_INTERVAL:
                              10842                 :                :                 case F_OVERLAPS_TIMESTAMP_TIMESTAMP_TIMESTAMP_TIMESTAMP:
                              10843                 :                :                 case F_OVERLAPS_TIMETZ_TIMETZ_TIMETZ_TIMETZ:
                              10844                 :                :                 case F_OVERLAPS_TIME_INTERVAL_TIME_INTERVAL:
                              10845                 :                :                 case F_OVERLAPS_TIME_INTERVAL_TIME_TIME:
                              10846                 :                :                 case F_OVERLAPS_TIME_TIME_TIME_INTERVAL:
                              10847                 :                :                 case F_OVERLAPS_TIME_TIME_TIME_TIME:
                              10848                 :                :                     /* IS xxx NORMALIZED: */
                              10849                 :                :                 case F_IS_NORMALIZED:
                              10850                 :              4 :                     return false;
                              10851                 :              8 :                 default:
                              10852                 :              8 :                     break;
                              10853                 :                :             }
                              10854                 :              8 :             return true;
 3425                         10855                 :             72 :         case T_NullIfExpr:
                              10856                 :                :         case T_CoalesceExpr:
                              10857                 :                :         case T_MinMaxExpr:
                              10858                 :                :         case T_SQLValueFunction:
                              10859                 :                :         case T_JsonExpr:
                              10860                 :                :             /* these are all accepted by func_expr_common_subexpr */
                              10861                 :             72 :             return true;
   39 tgl@sss.pgh.pa.us       10862                 :UBC           0 :         case T_XmlExpr:
                              10863                 :                :             /* all but IS DOCUMENT, which is a postfix test */
                              10864                 :              0 :             return ((XmlExpr *) node)->op != IS_DOCUMENT;
 3425 tgl@sss.pgh.pa.us       10865                 :CBC         874 :         default:
                              10866                 :            874 :             break;
                              10867                 :                :     }
                              10868                 :            874 :     return false;
                              10869                 :                : }
                              10870                 :                : 
                              10871                 :                : 
                              10872                 :                : /*
                              10873                 :                :  * get_oper_expr            - Parse back an OpExpr node
                              10874                 :                :  */
                              10875                 :                : static void
 8513 bruce@momjian.us        10876                 :          42904 : get_oper_expr(OpExpr *expr, deparse_context *context)
                              10877                 :                : {
 8975 tgl@sss.pgh.pa.us       10878                 :          42904 :     StringInfo  buf = context->buf;
 8752                         10879                 :          42904 :     Oid         opno = expr->opno;
 8975                         10880                 :          42904 :     List       *args = expr->args;
                              10881                 :                : 
 8522                         10882         [ +  + ]:          42904 :     if (!PRETTY_PAREN(context))
 8517 bruce@momjian.us        10883                 :          41328 :         appendStringInfoChar(buf, '(');
 8217 neilc@samurai.com       10884         [ +  + ]:          42904 :     if (list_length(args) == 2)
                              10885                 :                :     {
                              10886                 :                :         /* binary operator */
 8221                         10887                 :          42868 :         Node       *arg1 = (Node *) linitial(args);
 8851 bruce@momjian.us        10888                 :          42868 :         Node       *arg2 = (Node *) lsecond(args);
                              10889                 :                : 
 8517                         10890                 :          42868 :         get_rule_expr_paren(arg1, context, true, (Node *) expr);
 8975 tgl@sss.pgh.pa.us       10891                 :          42868 :         appendStringInfo(buf, " %s ",
                              10892                 :                :                          generate_operator_name(opno,
                              10893                 :                :                                                 exprType(arg1),
                              10894                 :                :                                                 exprType(arg2)));
 8517 bruce@momjian.us        10895                 :          42868 :         get_rule_expr_paren(arg2, context, true, (Node *) expr);
                              10896                 :                :     }
                              10897                 :                :     else
                              10898                 :                :     {
                              10899                 :                :         /* prefix operator */
 8221 neilc@samurai.com       10900                 :             36 :         Node       *arg = (Node *) linitial(args);
                              10901                 :                : 
 2263 tgl@sss.pgh.pa.us       10902                 :             36 :         appendStringInfo(buf, "%s ",
                              10903                 :                :                          generate_operator_name(opno,
                              10904                 :                :                                                 InvalidOid,
                              10905                 :                :                                                 exprType(arg)));
                              10906                 :             36 :         get_rule_expr_paren(arg, context, true, (Node *) expr);
                              10907                 :                :     }
 8522                         10908         [ +  + ]:          42904 :     if (!PRETTY_PAREN(context))
 8517 bruce@momjian.us        10909                 :          41328 :         appendStringInfoChar(buf, ')');
 8975 tgl@sss.pgh.pa.us       10910                 :          42904 : }
                              10911                 :                : 
                              10912                 :                : /*
                              10913                 :                :  * get_func_expr            - Parse back a FuncExpr node
                              10914                 :                :  */
                              10915                 :                : static void
 8513 bruce@momjian.us        10916                 :           8258 : get_func_expr(FuncExpr *expr, deparse_context *context,
                              10917                 :                :               bool showimplicit)
                              10918                 :                : {
 9918 tgl@sss.pgh.pa.us       10919                 :           8258 :     StringInfo  buf = context->buf;
 8752                         10920                 :           8258 :     Oid         funcoid = expr->funcid;
                              10921                 :                :     Oid         argtypes[FUNC_MAX_ARGS];
                              10922                 :                :     int         nargs;
                              10923                 :                :     List       *argnames;
                              10924                 :                :     bool        use_variadic;
                              10925                 :                :     ListCell   *l;
                              10926                 :                : 
                              10927                 :                :     /*
                              10928                 :                :      * If the function call came from an implicit coercion, then just show the
                              10929                 :                :      * first argument --- unless caller wants to see implicit coercions.
                              10930                 :                :      */
                              10931   [ +  +  +  + ]:           8258 :     if (expr->funcformat == COERCE_IMPLICIT_CAST && !showimplicit)
                              10932                 :                :     {
 8221 neilc@samurai.com       10933                 :            777 :         get_rule_expr_paren((Node *) linitial(expr->args), context,
                              10934                 :                :                             false, (Node *) expr);
 8837 tgl@sss.pgh.pa.us       10935                 :           2107 :         return;
                              10936                 :                :     }
                              10937                 :                : 
                              10938                 :                :     /*
                              10939                 :                :      * If the function call came from a cast, then show the first argument
                              10940                 :                :      * plus an explicit cast operation.
                              10941                 :                :      */
 8752                         10942         [ +  + ]:           7481 :     if (expr->funcformat == COERCE_EXPLICIT_CAST ||
                              10943         [ +  + ]:           6978 :         expr->funcformat == COERCE_IMPLICIT_CAST)
                              10944                 :                :     {
 8221 neilc@samurai.com       10945                 :           1210 :         Node       *arg = linitial(expr->args);
 8752 tgl@sss.pgh.pa.us       10946                 :           1210 :         Oid         rettype = expr->funcresulttype;
                              10947                 :                :         int32       coercedTypmod;
                              10948                 :                : 
                              10949                 :                :         /* Get the typmod if this is a length-coercion function */
 8837                         10950                 :           1210 :         (void) exprIsLengthCoercion((Node *) expr, &coercedTypmod);
                              10951                 :                : 
 7196                         10952                 :           1210 :         get_coercion_expr(arg, context,
                              10953                 :                :                           rettype, coercedTypmod,
                              10954                 :                :                           (Node *) expr);
                              10955                 :                : 
 9772                         10956                 :           1210 :         return;
                              10957                 :                :     }
                              10958                 :                : 
                              10959                 :                :     /*
                              10960                 :                :      * If the function was called using one of the SQL spec's random special
                              10961                 :                :      * syntaxes, try to reproduce that.  If we don't recognize the function,
                              10962                 :                :      * fall through.
                              10963                 :                :      */
 2215                         10964         [ +  + ]:           6271 :     if (expr->funcformat == COERCE_SQL_SYNTAX)
                              10965                 :                :     {
                              10966         [ +  + ]:            124 :         if (get_func_sql_syntax(expr, context))
                              10967                 :            120 :             return;
                              10968                 :                :     }
                              10969                 :                : 
                              10970                 :                :     /*
                              10971                 :                :      * Normal function: display as proname(args).  First we need to extract
                              10972                 :                :      * the argument datatypes.
                              10973                 :                :      */
 6544                         10974         [ -  + ]:           6151 :     if (list_length(expr->args) > FUNC_MAX_ARGS)
 6544 tgl@sss.pgh.pa.us       10975         [ #  # ]:UBC           0 :         ereport(ERROR,
                              10976                 :                :                 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
                              10977                 :                :                  errmsg("too many arguments")));
 8975 tgl@sss.pgh.pa.us       10978                 :CBC        6151 :     nargs = 0;
 6260                         10979                 :           6151 :     argnames = NIL;
 8975                         10980   [ +  +  +  +  :          12871 :     foreach(l, expr->args)
                                              +  + ]
                              10981                 :                :     {
 6119 bruce@momjian.us        10982                 :           6720 :         Node       *arg = (Node *) lfirst(l);
                              10983                 :                : 
 6260 tgl@sss.pgh.pa.us       10984         [ +  + ]:           6720 :         if (IsA(arg, NamedArgExpr))
                              10985                 :             20 :             argnames = lappend(argnames, ((NamedArgExpr *) arg)->name);
                              10986                 :           6720 :         argtypes[nargs] = exprType(arg);
 8975                         10987                 :           6720 :         nargs++;
                              10988                 :                :     }
                              10989                 :                : 
                              10990                 :           6151 :     appendStringInfo(buf, "%s(",
                              10991                 :                :                      generate_function_name(funcoid, nargs,
                              10992                 :                :                                             argnames, argtypes,
 5059                         10993                 :           6151 :                                             expr->funcvariadic,
                              10994                 :                :                                             &use_variadic,
  821                         10995                 :           6151 :                                             context->inGroupBy));
 6709                         10996                 :           6151 :     nargs = 0;
                              10997   [ +  +  +  +  :          12871 :     foreach(l, expr->args)
                                              +  + ]
                              10998                 :                :     {
                              10999         [ +  + ]:           6720 :         if (nargs++ > 0)
                              11000                 :           1342 :             appendStringInfoString(buf, ", ");
 2693                         11001   [ +  +  +  - ]:           6720 :         if (use_variadic && lnext(expr->args, l) == NULL)
 6709                         11002                 :              7 :             appendStringInfoString(buf, "VARIADIC ");
                              11003                 :           6720 :         get_rule_expr((Node *) lfirst(l), context, true);
                              11004                 :                :     }
 9778                         11005                 :           6151 :     appendStringInfoChar(buf, ')');
                              11006                 :                : }
                              11007                 :                : 
                              11008                 :                : /*
                              11009                 :                :  * get_agg_expr         - Parse back an Aggref node
                              11010                 :                :  */
                              11011                 :                : static void
 1549 andrew@dunslane.net     11012                 :           3330 : get_agg_expr(Aggref *aggref, deparse_context *context,
                              11013                 :                :              Aggref *original_aggref)
                              11014                 :                : {
 1340 alvherre@alvh.no-ip.    11015                 :           3330 :     get_agg_expr_helper(aggref, context, original_aggref, NULL, NULL,
                              11016                 :                :                         false);
                              11017                 :           3330 : }
                              11018                 :                : 
                              11019                 :                : /*
                              11020                 :                :  * get_agg_expr_helper      - subroutine for get_agg_expr and
                              11021                 :                :  *                          get_json_agg_constructor
                              11022                 :                :  */
                              11023                 :                : static void
                              11024                 :           3398 : get_agg_expr_helper(Aggref *aggref, deparse_context *context,
                              11025                 :                :                     Aggref *original_aggref, const char *funcname,
                              11026                 :                :                     const char *options, bool is_json_objectagg)
                              11027                 :                : {
 8997 tgl@sss.pgh.pa.us       11028                 :           3398 :     StringInfo  buf = context->buf;
                              11029                 :                :     Oid         argtypes[FUNC_MAX_ARGS];
                              11030                 :                :     int         nargs;
 1340 alvherre@alvh.no-ip.    11031                 :           3398 :     bool        use_variadic = false;
                              11032                 :                : 
                              11033                 :                :     /*
                              11034                 :                :      * For a combining aggregate, we look up and deparse the corresponding
                              11035                 :                :      * partial aggregate instead.  This is necessary because our input
                              11036                 :                :      * argument list has been replaced; the new argument list always has just
                              11037                 :                :      * one element, which will point to a partial Aggref that supplies us with
                              11038                 :                :      * transition states to combine.
                              11039                 :                :      */
 3807 tgl@sss.pgh.pa.us       11040         [ +  + ]:           3398 :     if (DO_AGGSPLIT_COMBINE(aggref->aggsplit))
                              11041                 :                :     {
                              11042                 :                :         TargetEntry *tle;
                              11043                 :                : 
 3867 rhaas@postgresql.org    11044         [ -  + ]:            560 :         Assert(list_length(aggref->args) == 1);
 2544 tgl@sss.pgh.pa.us       11045                 :            560 :         tle = linitial_node(TargetEntry, aggref->args);
                              11046                 :            560 :         resolve_special_varno((Node *) tle->expr, context,
                              11047                 :                :                               get_agg_combine_expr, original_aggref);
 3867 rhaas@postgresql.org    11048                 :            560 :         return;
                              11049                 :                :     }
                              11050                 :                : 
                              11051                 :                :     /*
                              11052                 :                :      * Mark as PARTIAL, if appropriate.  We look to the original aggref so as
                              11053                 :                :      * to avoid printing this when recursing from the code just above.
                              11054                 :                :      */
 3807 tgl@sss.pgh.pa.us       11055         [ +  + ]:           2838 :     if (DO_AGGSPLIT_SKIPFINAL(original_aggref->aggsplit))
 3867 rhaas@postgresql.org    11056                 :           1224 :         appendStringInfoString(buf, "PARTIAL ");
                              11057                 :                : 
                              11058                 :                :     /* Extract the argument types as seen by the parser */
 4723 tgl@sss.pgh.pa.us       11059                 :           2838 :     nargs = get_aggregate_argtypes(aggref, argtypes);
                              11060                 :                : 
 1340 alvherre@alvh.no-ip.    11061         [ +  + ]:           2838 :     if (!funcname)
                              11062                 :           2770 :         funcname = generate_function_name(aggref->aggfnoid, nargs, NIL,
                              11063                 :           2770 :                                           argtypes, aggref->aggvariadic,
                              11064                 :                :                                           &use_variadic,
  821 tgl@sss.pgh.pa.us       11065                 :           2770 :                                           context->inGroupBy);
                              11066                 :                : 
                              11067                 :                :     /* Print the aggregate name, schema-qualified if needed */
 1340 alvherre@alvh.no-ip.    11068                 :           2838 :     appendStringInfo(buf, "%s(%s", funcname,
 6192 tgl@sss.pgh.pa.us       11069         [ +  + ]:           2838 :                      (aggref->aggdistinct != NIL) ? "DISTINCT " : "");
                              11070                 :                : 
 4723                         11071         [ +  + ]:           2838 :     if (AGGKIND_IS_ORDERED_SET(aggref->aggkind))
                              11072                 :                :     {
                              11073                 :                :         /*
                              11074                 :                :          * Ordered-set aggregates do not use "*" syntax.  Also, we needn't
                              11075                 :                :          * worry about inserting VARIADIC.  So we can just dump the direct
                              11076                 :                :          * args as-is.
                              11077                 :                :          */
                              11078         [ -  + ]:             17 :         Assert(!aggref->aggvariadic);
                              11079                 :             17 :         get_rule_expr((Node *) aggref->aggdirectargs, context, true);
                              11080         [ -  + ]:             17 :         Assert(aggref->aggorder != NIL);
                              11081                 :             17 :         appendStringInfoString(buf, ") WITHIN GROUP (ORDER BY ");
                              11082                 :             17 :         get_rule_orderby(aggref->aggorder, aggref->args, false, context);
                              11083                 :                :     }
                              11084                 :                :     else
                              11085                 :                :     {
                              11086                 :                :         /* aggstar can be set only in zero-argument aggregates */
                              11087         [ +  + ]:           2821 :         if (aggref->aggstar)
                              11088                 :            842 :             appendStringInfoChar(buf, '*');
                              11089                 :                :         else
                              11090                 :                :         {
                              11091                 :                :             ListCell   *l;
                              11092                 :                :             int         i;
                              11093                 :                : 
                              11094                 :           1979 :             i = 0;
                              11095   [ +  -  +  +  :           4097 :             foreach(l, aggref->args)
                                              +  + ]
                              11096                 :                :             {
                              11097                 :           2118 :                 TargetEntry *tle = (TargetEntry *) lfirst(l);
                              11098                 :           2118 :                 Node       *arg = (Node *) tle->expr;
                              11099                 :                : 
                              11100         [ -  + ]:           2118 :                 Assert(!IsA(arg, NamedArgExpr));
                              11101         [ +  + ]:           2118 :                 if (tle->resjunk)
                              11102                 :             31 :                     continue;
                              11103         [ +  + ]:           2087 :                 if (i++ > 0)
                              11104                 :                :                 {
 1340 alvherre@alvh.no-ip.    11105         [ +  + ]:            108 :                     if (is_json_objectagg)
                              11106                 :                :                     {
                              11107                 :                :                         /*
                              11108                 :                :                          * the ABSENT ON NULL and WITH UNIQUE args are printed
                              11109                 :                :                          * separately, so ignore them here
                              11110                 :                :                          */
                              11111         [ -  + ]:             28 :                         if (i > 2)
 1340 alvherre@alvh.no-ip.    11112                 :UBC           0 :                             break;
                              11113                 :                : 
 1340 alvherre@alvh.no-ip.    11114                 :CBC          28 :                         appendStringInfoString(buf, " : ");
                              11115                 :                :                     }
                              11116                 :                :                     else
                              11117                 :             80 :                         appendStringInfoString(buf, ", ");
                              11118                 :                :                 }
 4723 tgl@sss.pgh.pa.us       11119   [ +  +  +  - ]:           2087 :                 if (use_variadic && i == nargs)
                              11120                 :              4 :                     appendStringInfoString(buf, "VARIADIC ");
                              11121                 :           2087 :                 get_rule_expr(arg, context, true);
                              11122                 :                :             }
                              11123                 :                :         }
                              11124                 :                : 
                              11125         [ +  + ]:           2821 :         if (aggref->aggorder != NIL)
                              11126                 :                :         {
                              11127                 :             78 :             appendStringInfoString(buf, " ORDER BY ");
                              11128                 :             78 :             get_rule_orderby(aggref->aggorder, aggref->args, false, context);
                              11129                 :                :         }
                              11130                 :                :     }
                              11131                 :                : 
 1340 alvherre@alvh.no-ip.    11132         [ +  + ]:           2838 :     if (options)
                              11133                 :             68 :         appendStringInfoString(buf, options);
                              11134                 :                : 
 4883 noah@leadboat.com       11135         [ +  + ]:           2838 :     if (aggref->aggfilter != NULL)
                              11136                 :                :     {
                              11137                 :             28 :         appendStringInfoString(buf, ") FILTER (WHERE ");
                              11138                 :             28 :         get_rule_expr((Node *) aggref->aggfilter, context, false);
                              11139                 :                :     }
                              11140                 :                : 
 8997 tgl@sss.pgh.pa.us       11141                 :           2838 :     appendStringInfoChar(buf, ')');
                              11142                 :                : }
                              11143                 :                : 
                              11144                 :                : /*
                              11145                 :                :  * This is a helper function for get_agg_expr().  It's used when we deparse
                              11146                 :                :  * a combining Aggref; resolve_special_varno locates the corresponding partial
                              11147                 :                :  * Aggref and then calls this.
                              11148                 :                :  */
                              11149                 :                : static void
 2544                         11150                 :            560 : get_agg_combine_expr(Node *node, deparse_context *context, void *callback_arg)
                              11151                 :                : {
                              11152                 :                :     Aggref     *aggref;
                              11153                 :            560 :     Aggref     *original_aggref = callback_arg;
                              11154                 :                : 
 3867 rhaas@postgresql.org    11155         [ -  + ]:            560 :     if (!IsA(node, Aggref))
 3867 rhaas@postgresql.org    11156         [ #  # ]:UBC           0 :         elog(ERROR, "combining Aggref does not point to an Aggref");
                              11157                 :                : 
 3867 rhaas@postgresql.org    11158                 :CBC         560 :     aggref = (Aggref *) node;
                              11159                 :            560 :     get_agg_expr(aggref, context, original_aggref);
                              11160                 :            560 : }
                              11161                 :                : 
                              11162                 :                : /*
                              11163                 :                :  * get_windowfunc_expr  - Parse back a WindowFunc node
                              11164                 :                :  */
                              11165                 :                : static void
 1549 andrew@dunslane.net     11166                 :            254 : get_windowfunc_expr(WindowFunc *wfunc, deparse_context *context)
                              11167                 :                : {
 1340 alvherre@alvh.no-ip.    11168                 :            254 :     get_windowfunc_expr_helper(wfunc, context, NULL, NULL, false);
                              11169                 :            254 : }
                              11170                 :                : 
                              11171                 :                : 
                              11172                 :                : /*
                              11173                 :                :  * get_windowfunc_expr_helper   - subroutine for get_windowfunc_expr and
                              11174                 :                :  *                              get_json_agg_constructor
                              11175                 :                :  */
                              11176                 :                : static void
                              11177                 :            266 : get_windowfunc_expr_helper(WindowFunc *wfunc, deparse_context *context,
                              11178                 :                :                            const char *funcname, const char *options,
                              11179                 :                :                            bool is_json_objectagg)
                              11180                 :                : {
 6544 tgl@sss.pgh.pa.us       11181                 :            266 :     StringInfo  buf = context->buf;
                              11182                 :                :     Oid         argtypes[FUNC_MAX_ARGS];
                              11183                 :                :     int         nargs;
                              11184                 :                :     List       *argnames;
                              11185                 :                :     ListCell   *l;
                              11186                 :                : 
                              11187         [ -  + ]:            266 :     if (list_length(wfunc->args) > FUNC_MAX_ARGS)
 6544 tgl@sss.pgh.pa.us       11188         [ #  # ]:UBC           0 :         ereport(ERROR,
                              11189                 :                :                 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
                              11190                 :                :                  errmsg("too many arguments")));
 6544 tgl@sss.pgh.pa.us       11191                 :CBC         266 :     nargs = 0;
 4770                         11192                 :            266 :     argnames = NIL;
 6544                         11193   [ +  +  +  +  :            440 :     foreach(l, wfunc->args)
                                              +  + ]
                              11194                 :                :     {
 6119 bruce@momjian.us        11195                 :            174 :         Node       *arg = (Node *) lfirst(l);
                              11196                 :                : 
 4770 tgl@sss.pgh.pa.us       11197         [ -  + ]:            174 :         if (IsA(arg, NamedArgExpr))
 4770 tgl@sss.pgh.pa.us       11198                 :UBC           0 :             argnames = lappend(argnames, ((NamedArgExpr *) arg)->name);
 6260 tgl@sss.pgh.pa.us       11199                 :CBC         174 :         argtypes[nargs] = exprType(arg);
 6544                         11200                 :            174 :         nargs++;
                              11201                 :                :     }
                              11202                 :                : 
 1340 alvherre@alvh.no-ip.    11203         [ +  + ]:            266 :     if (!funcname)
                              11204                 :            254 :         funcname = generate_function_name(wfunc->winfnoid, nargs, argnames,
                              11205                 :                :                                           argtypes, false, NULL,
  821 tgl@sss.pgh.pa.us       11206                 :            254 :                                           context->inGroupBy);
                              11207                 :                : 
 1340 alvherre@alvh.no-ip.    11208                 :            266 :     appendStringInfo(buf, "%s(", funcname);
                              11209                 :                : 
                              11210                 :                :     /* winstar can be set only in zero-argument aggregates */
 6544 tgl@sss.pgh.pa.us       11211         [ +  + ]:            266 :     if (wfunc->winstar)
                              11212                 :             28 :         appendStringInfoChar(buf, '*');
                              11213                 :                :     else
                              11214                 :                :     {
 1340 alvherre@alvh.no-ip.    11215         [ +  + ]:            238 :         if (is_json_objectagg)
                              11216                 :                :         {
                              11217                 :              4 :             get_rule_expr((Node *) linitial(wfunc->args), context, false);
                              11218                 :              4 :             appendStringInfoString(buf, " : ");
                              11219                 :              4 :             get_rule_expr((Node *) lsecond(wfunc->args), context, false);
                              11220                 :                :         }
                              11221                 :                :         else
                              11222                 :            234 :             get_rule_expr((Node *) wfunc->args, context, true);
                              11223                 :                :     }
                              11224                 :                : 
                              11225         [ +  + ]:            266 :     if (options)
                              11226                 :             12 :         appendStringInfoString(buf, options);
                              11227                 :                : 
 4883 noah@leadboat.com       11228         [ -  + ]:            266 :     if (wfunc->aggfilter != NULL)
                              11229                 :                :     {
 4883 noah@leadboat.com       11230                 :UBC           0 :         appendStringInfoString(buf, ") FILTER (WHERE ");
                              11231                 :              0 :         get_rule_expr((Node *) wfunc->aggfilter, context, false);
                              11232                 :                :     }
                              11233                 :                : 
  421 ishii@postgresql.org    11234                 :CBC         266 :     appendStringInfoString(buf, ") ");
                              11235                 :                : 
                              11236         [ +  + ]:            266 :     if (wfunc->ignore_nulls == PARSER_IGNORE_NULLS)
                              11237                 :              4 :         appendStringInfoString(buf, "IGNORE NULLS ");
                              11238                 :                : 
                              11239                 :            266 :     appendStringInfoString(buf, "OVER ");
                              11240                 :                : 
  627 tgl@sss.pgh.pa.us       11241         [ +  + ]:            266 :     if (context->windowClause)
                              11242                 :                :     {
                              11243                 :                :         /* Query-decompilation case: search the windowClause list */
                              11244   [ +  -  +  -  :             40 :         foreach(l, context->windowClause)
                                              +  - ]
                              11245                 :                :         {
                              11246                 :             40 :             WindowClause *wc = (WindowClause *) lfirst(l);
                              11247                 :                : 
                              11248         [ +  - ]:             40 :             if (wc->winref == wfunc->winref)
                              11249                 :                :             {
                              11250         [ +  + ]:             40 :                 if (wc->name)
                              11251                 :             12 :                     appendStringInfoString(buf, quote_identifier(wc->name));
                              11252                 :                :                 else
                              11253                 :             28 :                     get_rule_windowspec(wc, context->targetList, context);
                              11254                 :             40 :                 break;
                              11255                 :                :             }
                              11256                 :                :         }
                              11257         [ -  + ]:             40 :         if (l == NULL)
 6544 tgl@sss.pgh.pa.us       11258         [ #  # ]:UBC           0 :             elog(ERROR, "could not find window clause for winref %u",
                              11259                 :                :                  wfunc->winref);
                              11260                 :                :     }
                              11261                 :                :     else
                              11262                 :                :     {
                              11263                 :                :         /*
                              11264                 :                :          * In EXPLAIN, search the namespace stack for a matching WindowAgg
                              11265                 :                :          * node (probably it's always the first entry), and print winname.
                              11266                 :                :          */
  627 tgl@sss.pgh.pa.us       11267   [ +  -  +  -  :CBC         226 :         foreach(l, context->namespaces)
                                              +  - ]
                              11268                 :                :         {
                              11269                 :            226 :             deparse_namespace *dpns = (deparse_namespace *) lfirst(l);
                              11270                 :                : 
                              11271   [ +  -  +  - ]:            226 :             if (dpns->plan && IsA(dpns->plan, WindowAgg))
                              11272                 :                :             {
                              11273                 :            226 :                 WindowAgg  *wagg = (WindowAgg *) dpns->plan;
                              11274                 :                : 
                              11275         [ +  - ]:            226 :                 if (wagg->winref == wfunc->winref)
                              11276                 :                :                 {
                              11277                 :            226 :                     appendStringInfoString(buf, quote_identifier(wagg->winname));
                              11278                 :            226 :                     break;
                              11279                 :                :                 }
                              11280                 :                :             }
                              11281                 :                :         }
                              11282         [ -  + ]:            226 :         if (l == NULL)
  627 tgl@sss.pgh.pa.us       11283         [ #  # ]:UBC           0 :             elog(ERROR, "could not find window clause for winref %u",
                              11284                 :                :                  wfunc->winref);
                              11285                 :                :     }
 6544 tgl@sss.pgh.pa.us       11286                 :CBC         266 : }
                              11287                 :                : 
                              11288                 :                : /*
                              11289                 :                :  * get_func_sql_syntax      - Parse back a SQL-syntax function call
                              11290                 :                :  *
                              11291                 :                :  * Returns true if we successfully deparsed, false if we did not
                              11292                 :                :  * recognize the function.
                              11293                 :                :  *
                              11294                 :                :  * Most of these print as constructs that func_expr_windowless accepts.
                              11295                 :                :  * But AT TIME ZONE, AT LOCAL, OVERLAPS and IS xxx NORMALIZED print as a
                              11296                 :                :  * parenthesized a_expr instead, so a function added to them, or another
                              11297                 :                :  * one printed that way, must also be listed in looks_like_function().
                              11298                 :                :  */
                              11299                 :                : static bool
 2215                         11300                 :            124 : get_func_sql_syntax(FuncExpr *expr, deparse_context *context)
                              11301                 :                : {
                              11302                 :            124 :     StringInfo  buf = context->buf;
                              11303                 :            124 :     Oid         funcoid = expr->funcid;
                              11304                 :                : 
                              11305   [ +  +  +  +  :            124 :     switch (funcoid)
                                     +  +  +  +  +  
                                     +  +  +  +  +  
                                           +  -  + ]
                              11306                 :                :     {
                              11307                 :             16 :         case F_TIMEZONE_INTERVAL_TIMESTAMP:
                              11308                 :                :         case F_TIMEZONE_INTERVAL_TIMESTAMPTZ:
                              11309                 :                :         case F_TIMEZONE_INTERVAL_TIMETZ:
                              11310                 :                :         case F_TIMEZONE_TEXT_TIMESTAMP:
                              11311                 :                :         case F_TIMEZONE_TEXT_TIMESTAMPTZ:
                              11312                 :                :         case F_TIMEZONE_TEXT_TIMETZ:
                              11313                 :                :             /* AT TIME ZONE ... note reversed argument order */
                              11314                 :             16 :             appendStringInfoChar(buf, '(');
 1458                         11315                 :             16 :             get_rule_expr_paren((Node *) lsecond(expr->args), context, false,
                              11316                 :                :                                 (Node *) expr);
 2215                         11317                 :             16 :             appendStringInfoString(buf, " AT TIME ZONE ");
 1458                         11318                 :             16 :             get_rule_expr_paren((Node *) linitial(expr->args), context, false,
                              11319                 :                :                                 (Node *) expr);
 2215                         11320                 :             16 :             appendStringInfoChar(buf, ')');
                              11321                 :             16 :             return true;
                              11322                 :                : 
 1142 michael@paquier.xyz     11323                 :             12 :         case F_TIMEZONE_TIMESTAMP:
                              11324                 :                :         case F_TIMEZONE_TIMESTAMPTZ:
                              11325                 :                :         case F_TIMEZONE_TIMETZ:
                              11326                 :                :             /* AT LOCAL */
                              11327                 :             12 :             appendStringInfoChar(buf, '(');
                              11328                 :             12 :             get_rule_expr_paren((Node *) linitial(expr->args), context, false,
                              11329                 :                :                                 (Node *) expr);
                              11330                 :             12 :             appendStringInfoString(buf, " AT LOCAL)");
                              11331                 :             12 :             return true;
                              11332                 :                : 
 2215 tgl@sss.pgh.pa.us       11333                 :              4 :         case F_OVERLAPS_TIMESTAMPTZ_INTERVAL_TIMESTAMPTZ_INTERVAL:
                              11334                 :                :         case F_OVERLAPS_TIMESTAMPTZ_INTERVAL_TIMESTAMPTZ_TIMESTAMPTZ:
                              11335                 :                :         case F_OVERLAPS_TIMESTAMPTZ_TIMESTAMPTZ_TIMESTAMPTZ_INTERVAL:
                              11336                 :                :         case F_OVERLAPS_TIMESTAMPTZ_TIMESTAMPTZ_TIMESTAMPTZ_TIMESTAMPTZ:
                              11337                 :                :         case F_OVERLAPS_TIMESTAMP_INTERVAL_TIMESTAMP_INTERVAL:
                              11338                 :                :         case F_OVERLAPS_TIMESTAMP_INTERVAL_TIMESTAMP_TIMESTAMP:
                              11339                 :                :         case F_OVERLAPS_TIMESTAMP_TIMESTAMP_TIMESTAMP_INTERVAL:
                              11340                 :                :         case F_OVERLAPS_TIMESTAMP_TIMESTAMP_TIMESTAMP_TIMESTAMP:
                              11341                 :                :         case F_OVERLAPS_TIMETZ_TIMETZ_TIMETZ_TIMETZ:
                              11342                 :                :         case F_OVERLAPS_TIME_INTERVAL_TIME_INTERVAL:
                              11343                 :                :         case F_OVERLAPS_TIME_INTERVAL_TIME_TIME:
                              11344                 :                :         case F_OVERLAPS_TIME_TIME_TIME_INTERVAL:
                              11345                 :                :         case F_OVERLAPS_TIME_TIME_TIME_TIME:
                              11346                 :                :             /* (x1, x2) OVERLAPS (y1, y2) */
                              11347                 :              4 :             appendStringInfoString(buf, "((");
                              11348                 :              4 :             get_rule_expr((Node *) linitial(expr->args), context, false);
                              11349                 :              4 :             appendStringInfoString(buf, ", ");
                              11350                 :              4 :             get_rule_expr((Node *) lsecond(expr->args), context, false);
                              11351                 :              4 :             appendStringInfoString(buf, ") OVERLAPS (");
                              11352                 :              4 :             get_rule_expr((Node *) lthird(expr->args), context, false);
                              11353                 :              4 :             appendStringInfoString(buf, ", ");
                              11354                 :              4 :             get_rule_expr((Node *) lfourth(expr->args), context, false);
                              11355                 :              4 :             appendStringInfoString(buf, "))");
                              11356                 :              4 :             return true;
                              11357                 :                : 
 2062 peter@eisentraut.org    11358                 :             12 :         case F_EXTRACT_TEXT_DATE:
                              11359                 :                :         case F_EXTRACT_TEXT_TIME:
                              11360                 :                :         case F_EXTRACT_TEXT_TIMETZ:
                              11361                 :                :         case F_EXTRACT_TEXT_TIMESTAMP:
                              11362                 :                :         case F_EXTRACT_TEXT_TIMESTAMPTZ:
                              11363                 :                :         case F_EXTRACT_TEXT_INTERVAL:
                              11364                 :                :             /* EXTRACT (x FROM y) */
                              11365                 :             12 :             appendStringInfoString(buf, "EXTRACT(");
                              11366                 :                :             {
                              11367                 :             12 :                 Const      *con = (Const *) linitial(expr->args);
                              11368                 :                : 
                              11369   [ +  -  +  -  :             12 :                 Assert(IsA(con, Const) &&
                                              -  + ]
                              11370                 :                :                        con->consttype == TEXTOID &&
                              11371                 :                :                        !con->constisnull);
  110 nathan@postgresql.or    11372                 :             12 :                 appendStringInfoString(buf, quote_identifier(TextDatumGetCString(con->constvalue)));
                              11373                 :                :             }
 2062 peter@eisentraut.org    11374                 :             12 :             appendStringInfoString(buf, " FROM ");
                              11375                 :             12 :             get_rule_expr((Node *) lsecond(expr->args), context, false);
                              11376                 :             12 :             appendStringInfoChar(buf, ')');
                              11377                 :             12 :             return true;
                              11378                 :                : 
 2215 tgl@sss.pgh.pa.us       11379                 :             12 :         case F_IS_NORMALIZED:
                              11380                 :                :             /* IS xxx NORMALIZED */
 1152 drowley@postgresql.o    11381                 :             12 :             appendStringInfoChar(buf, '(');
 1458 tgl@sss.pgh.pa.us       11382                 :             12 :             get_rule_expr_paren((Node *) linitial(expr->args), context, false,
                              11383                 :                :                                 (Node *) expr);
                              11384                 :             12 :             appendStringInfoString(buf, " IS");
 2215                         11385         [ +  + ]:             12 :             if (list_length(expr->args) == 2)
                              11386                 :                :             {
                              11387                 :              4 :                 Const      *con = (Const *) lsecond(expr->args);
                              11388                 :                : 
                              11389   [ +  -  +  -  :              4 :                 Assert(IsA(con, Const) &&
                                              -  + ]
                              11390                 :                :                        con->consttype == TEXTOID &&
                              11391                 :                :                        !con->constisnull);
                              11392                 :                :                 /* NB: safe because no allowed words need quoted/escaped */
                              11393                 :              4 :                 appendStringInfo(buf, " %s",
                              11394                 :              4 :                                  TextDatumGetCString(con->constvalue));
                              11395                 :                :             }
                              11396                 :             12 :             appendStringInfoString(buf, " NORMALIZED)");
                              11397                 :             12 :             return true;
                              11398                 :                : 
                              11399                 :              4 :         case F_PG_COLLATION_FOR:
                              11400                 :                :             /* COLLATION FOR */
                              11401                 :              4 :             appendStringInfoString(buf, "COLLATION FOR (");
                              11402                 :              4 :             get_rule_expr((Node *) linitial(expr->args), context, false);
                              11403                 :              4 :             appendStringInfoChar(buf, ')');
                              11404                 :              4 :             return true;
                              11405                 :                : 
                              11406                 :              8 :         case F_NORMALIZE:
                              11407                 :                :             /* NORMALIZE() */
                              11408                 :              8 :             appendStringInfoString(buf, "NORMALIZE(");
                              11409                 :              8 :             get_rule_expr((Node *) linitial(expr->args), context, false);
                              11410         [ +  + ]:              8 :             if (list_length(expr->args) == 2)
                              11411                 :                :             {
                              11412                 :              4 :                 Const      *con = (Const *) lsecond(expr->args);
                              11413                 :                : 
                              11414   [ +  -  +  -  :              4 :                 Assert(IsA(con, Const) &&
                                              -  + ]
                              11415                 :                :                        con->consttype == TEXTOID &&
                              11416                 :                :                        !con->constisnull);
                              11417                 :              4 :                 appendStringInfo(buf, ", %s",
                              11418                 :              4 :                                  TextDatumGetCString(con->constvalue));
                              11419                 :                :             }
                              11420                 :              8 :             appendStringInfoChar(buf, ')');
                              11421                 :              8 :             return true;
                              11422                 :                : 
                              11423                 :              8 :         case F_OVERLAY_BIT_BIT_INT4:
                              11424                 :                :         case F_OVERLAY_BIT_BIT_INT4_INT4:
                              11425                 :                :         case F_OVERLAY_BYTEA_BYTEA_INT4:
                              11426                 :                :         case F_OVERLAY_BYTEA_BYTEA_INT4_INT4:
                              11427                 :                :         case F_OVERLAY_TEXT_TEXT_INT4:
                              11428                 :                :         case F_OVERLAY_TEXT_TEXT_INT4_INT4:
                              11429                 :                :             /* OVERLAY() */
                              11430                 :              8 :             appendStringInfoString(buf, "OVERLAY(");
                              11431                 :              8 :             get_rule_expr((Node *) linitial(expr->args), context, false);
                              11432                 :              8 :             appendStringInfoString(buf, " PLACING ");
                              11433                 :              8 :             get_rule_expr((Node *) lsecond(expr->args), context, false);
                              11434                 :              8 :             appendStringInfoString(buf, " FROM ");
                              11435                 :              8 :             get_rule_expr((Node *) lthird(expr->args), context, false);
                              11436         [ +  + ]:              8 :             if (list_length(expr->args) == 4)
                              11437                 :                :             {
                              11438                 :              4 :                 appendStringInfoString(buf, " FOR ");
                              11439                 :              4 :                 get_rule_expr((Node *) lfourth(expr->args), context, false);
                              11440                 :                :             }
                              11441                 :              8 :             appendStringInfoChar(buf, ')');
                              11442                 :              8 :             return true;
                              11443                 :                : 
                              11444                 :              4 :         case F_POSITION_BIT_BIT:
                              11445                 :                :         case F_POSITION_BYTEA_BYTEA:
                              11446                 :                :         case F_POSITION_TEXT_TEXT:
                              11447                 :                :             /* POSITION() ... extra parens since args are b_expr not a_expr */
                              11448                 :              4 :             appendStringInfoString(buf, "POSITION((");
                              11449                 :              4 :             get_rule_expr((Node *) lsecond(expr->args), context, false);
                              11450                 :              4 :             appendStringInfoString(buf, ") IN (");
                              11451                 :              4 :             get_rule_expr((Node *) linitial(expr->args), context, false);
                              11452                 :              4 :             appendStringInfoString(buf, "))");
                              11453                 :              4 :             return true;
                              11454                 :                : 
                              11455                 :              4 :         case F_SUBSTRING_BIT_INT4:
                              11456                 :                :         case F_SUBSTRING_BIT_INT4_INT4:
                              11457                 :                :         case F_SUBSTRING_BYTEA_INT4:
                              11458                 :                :         case F_SUBSTRING_BYTEA_INT4_INT4:
                              11459                 :                :         case F_SUBSTRING_TEXT_INT4:
                              11460                 :                :         case F_SUBSTRING_TEXT_INT4_INT4:
                              11461                 :                :             /* SUBSTRING FROM/FOR (i.e., integer-position variants) */
                              11462                 :              4 :             appendStringInfoString(buf, "SUBSTRING(");
                              11463                 :              4 :             get_rule_expr((Node *) linitial(expr->args), context, false);
                              11464                 :              4 :             appendStringInfoString(buf, " FROM ");
                              11465                 :              4 :             get_rule_expr((Node *) lsecond(expr->args), context, false);
                              11466         [ +  - ]:              4 :             if (list_length(expr->args) == 3)
                              11467                 :                :             {
                              11468                 :              4 :                 appendStringInfoString(buf, " FOR ");
                              11469                 :              4 :                 get_rule_expr((Node *) lthird(expr->args), context, false);
                              11470                 :                :             }
                              11471                 :              4 :             appendStringInfoChar(buf, ')');
                              11472                 :              4 :             return true;
                              11473                 :                : 
                              11474                 :              4 :         case F_SUBSTRING_TEXT_TEXT_TEXT:
                              11475                 :                :             /* SUBSTRING SIMILAR/ESCAPE */
                              11476                 :              4 :             appendStringInfoString(buf, "SUBSTRING(");
                              11477                 :              4 :             get_rule_expr((Node *) linitial(expr->args), context, false);
                              11478                 :              4 :             appendStringInfoString(buf, " SIMILAR ");
                              11479                 :              4 :             get_rule_expr((Node *) lsecond(expr->args), context, false);
                              11480                 :              4 :             appendStringInfoString(buf, " ESCAPE ");
                              11481                 :              4 :             get_rule_expr((Node *) lthird(expr->args), context, false);
                              11482                 :              4 :             appendStringInfoChar(buf, ')');
                              11483                 :              4 :             return true;
                              11484                 :                : 
                              11485                 :              8 :         case F_BTRIM_BYTEA_BYTEA:
                              11486                 :                :         case F_BTRIM_TEXT:
                              11487                 :                :         case F_BTRIM_TEXT_TEXT:
                              11488                 :                :             /* TRIM() */
                              11489                 :              8 :             appendStringInfoString(buf, "TRIM(BOTH");
                              11490         [ +  - ]:              8 :             if (list_length(expr->args) == 2)
                              11491                 :                :             {
                              11492                 :              8 :                 appendStringInfoChar(buf, ' ');
                              11493                 :              8 :                 get_rule_expr((Node *) lsecond(expr->args), context, false);
                              11494                 :                :             }
                              11495                 :              8 :             appendStringInfoString(buf, " FROM ");
                              11496                 :              8 :             get_rule_expr((Node *) linitial(expr->args), context, false);
                              11497                 :              8 :             appendStringInfoChar(buf, ')');
                              11498                 :              8 :             return true;
                              11499                 :                : 
 2140                         11500                 :              8 :         case F_LTRIM_BYTEA_BYTEA:
                              11501                 :                :         case F_LTRIM_TEXT:
                              11502                 :                :         case F_LTRIM_TEXT_TEXT:
                              11503                 :                :             /* TRIM() */
 2215                         11504                 :              8 :             appendStringInfoString(buf, "TRIM(LEADING");
                              11505         [ +  - ]:              8 :             if (list_length(expr->args) == 2)
                              11506                 :                :             {
                              11507                 :              8 :                 appendStringInfoChar(buf, ' ');
                              11508                 :              8 :                 get_rule_expr((Node *) lsecond(expr->args), context, false);
                              11509                 :                :             }
                              11510                 :              8 :             appendStringInfoString(buf, " FROM ");
                              11511                 :              8 :             get_rule_expr((Node *) linitial(expr->args), context, false);
                              11512                 :              8 :             appendStringInfoChar(buf, ')');
                              11513                 :              8 :             return true;
                              11514                 :                : 
 2140                         11515                 :              8 :         case F_RTRIM_BYTEA_BYTEA:
                              11516                 :                :         case F_RTRIM_TEXT:
                              11517                 :                :         case F_RTRIM_TEXT_TEXT:
                              11518                 :                :             /* TRIM() */
 2215                         11519                 :              8 :             appendStringInfoString(buf, "TRIM(TRAILING");
                              11520         [ +  + ]:              8 :             if (list_length(expr->args) == 2)
                              11521                 :                :             {
                              11522                 :              4 :                 appendStringInfoChar(buf, ' ');
                              11523                 :              4 :                 get_rule_expr((Node *) lsecond(expr->args), context, false);
                              11524                 :                :             }
                              11525                 :              8 :             appendStringInfoString(buf, " FROM ");
                              11526                 :              8 :             get_rule_expr((Node *) linitial(expr->args), context, false);
                              11527                 :              8 :             appendStringInfoChar(buf, ')');
                              11528                 :              8 :             return true;
                              11529                 :                : 
 1521 michael@paquier.xyz     11530                 :              8 :         case F_SYSTEM_USER:
                              11531                 :              8 :             appendStringInfoString(buf, "SYSTEM_USER");
                              11532                 :              8 :             return true;
                              11533                 :                : 
 2215 tgl@sss.pgh.pa.us       11534                 :UBC           0 :         case F_XMLEXISTS:
                              11535                 :                :             /* XMLEXISTS ... extra parens because args are c_expr */
                              11536                 :              0 :             appendStringInfoString(buf, "XMLEXISTS((");
                              11537                 :              0 :             get_rule_expr((Node *) linitial(expr->args), context, false);
                              11538                 :              0 :             appendStringInfoString(buf, ") PASSING (");
                              11539                 :              0 :             get_rule_expr((Node *) lsecond(expr->args), context, false);
                              11540                 :              0 :             appendStringInfoString(buf, "))");
                              11541                 :              0 :             return true;
                              11542                 :                :     }
 2215 tgl@sss.pgh.pa.us       11543                 :CBC           4 :     return false;
                              11544                 :                : }
                              11545                 :                : 
                              11546                 :                : /* ----------
                              11547                 :                :  * get_coercion_expr
                              11548                 :                :  *
                              11549                 :                :  *  Make a string representation of a value coerced to a specific type
                              11550                 :                :  * ----------
                              11551                 :                :  */
                              11552                 :                : static void
 7196                         11553                 :           3789 : get_coercion_expr(Node *arg, deparse_context *context,
                              11554                 :                :                   Oid resulttype, int32 resulttypmod,
                              11555                 :                :                   Node *parentNode)
                              11556                 :                : {
                              11557                 :           3789 :     StringInfo  buf = context->buf;
                              11558                 :                : 
                              11559                 :                :     /*
                              11560                 :                :      * Since parse_coerce.c doesn't immediately collapse application of
                              11561                 :                :      * length-coercion functions to constants, what we'll typically see in
                              11562                 :                :      * such cases is a Const with typmod -1 and a length-coercion function
                              11563                 :                :      * right above it.  Avoid generating redundant output. However, beware of
                              11564                 :                :      * suppressing casts when the user actually wrote something like
                              11565                 :                :      * 'foo'::text::char(3).
                              11566                 :                :      *
                              11567                 :                :      * Note: it might seem that we are missing the possibility of needing to
                              11568                 :                :      * print a COLLATE clause for such a Const.  However, a Const could only
                              11569                 :                :      * have nondefault collation in a post-constant-folding tree, in which the
                              11570                 :                :      * length coercion would have been folded too.  See also the special
                              11571                 :                :      * handling of CollateExpr in coerce_to_target_type(): any collation
                              11572                 :                :      * marking will be above the coercion node, not below it.
                              11573                 :                :      */
                              11574   [ +  -  +  + ]:           3789 :     if (arg && IsA(arg, Const) &&
                              11575         [ +  + ]:            387 :         ((Const *) arg)->consttype == resulttype &&
                              11576         [ +  - ]:             19 :         ((Const *) arg)->consttypmod == -1)
                              11577                 :                :     {
                              11578                 :                :         /* Show the constant without normal ::typename decoration */
 6901                         11579                 :             19 :         get_const_expr((Const *) arg, context, -1);
                              11580                 :                :     }
                              11581                 :                :     else
                              11582                 :                :     {
 7196                         11583         [ +  + ]:           3770 :         if (!PRETTY_PAREN(context))
                              11584                 :           3505 :             appendStringInfoChar(buf, '(');
                              11585                 :           3770 :         get_rule_expr_paren(arg, context, false, parentNode);
                              11586         [ +  + ]:           3770 :         if (!PRETTY_PAREN(context))
                              11587                 :           3505 :             appendStringInfoChar(buf, ')');
                              11588                 :                :     }
                              11589                 :                : 
                              11590                 :                :     /*
                              11591                 :                :      * Never emit resulttype(arg) functional notation. A pg_proc entry could
                              11592                 :                :      * take precedence, and a resulttype in pg_temp would require schema
                              11593                 :                :      * qualification that format_type_with_typemod() would usually omit. We've
                              11594                 :                :      * standardized on arg::resulttype, but CAST(arg AS resulttype) notation
                              11595                 :                :      * would work fine.
                              11596                 :                :      */
                              11597                 :           3789 :     appendStringInfo(buf, "::%s",
                              11598                 :                :                      format_type_with_typemod(resulttype, resulttypmod));
                              11599                 :           3789 : }
                              11600                 :                : 
                              11601                 :                : /* ----------
                              11602                 :                :  * get_const_expr
                              11603                 :                :  *
                              11604                 :                :  *  Make a string representation of a Const
                              11605                 :                :  *
                              11606                 :                :  * showtype can be -1 to never show "::typename" decoration, or +1 to always
                              11607                 :                :  * show it, or 0 to show it only if the constant wouldn't be assumed to be
                              11608                 :                :  * the right type by default.
                              11609                 :                :  *
                              11610                 :                :  * If the Const's collation isn't default for its type, show that too.
                              11611                 :                :  * We mustn't do this when showtype is -1 (since that means the caller will
                              11612                 :                :  * print "::typename", and we can't put a COLLATE clause in between).  It's
                              11613                 :                :  * caller's responsibility that collation isn't missed in such cases.
                              11614                 :                :  * ----------
                              11615                 :                :  */
                              11616                 :                : static void
 6901                         11617                 :          48398 : get_const_expr(Const *constval, deparse_context *context, int showtype)
                              11618                 :                : {
 9918                         11619                 :          48398 :     StringInfo  buf = context->buf;
                              11620                 :                :     Oid         typoutput;
                              11621                 :                :     bool        typIsVarlena;
                              11622                 :                :     char       *extval;
 4261                         11623                 :          48398 :     bool        needlabel = false;
                              11624                 :                : 
 9836                         11625         [ +  + ]:          48398 :     if (constval->constisnull)
                              11626                 :                :     {
                              11627                 :                :         /*
                              11628                 :                :          * Always label the type of a NULL constant to prevent misdecisions
                              11629                 :                :          * about type when reparsing.
                              11630                 :                :          */
 4776 rhaas@postgresql.org    11631                 :           1000 :         appendStringInfoString(buf, "NULL");
 6901 tgl@sss.pgh.pa.us       11632         [ +  + ]:           1000 :         if (showtype >= 0)
                              11633                 :                :         {
 7196                         11634                 :            966 :             appendStringInfo(buf, "::%s",
                              11635                 :                :                              format_type_with_typemod(constval->consttype,
                              11636                 :                :                                                       constval->consttypmod));
 5741                         11637                 :            966 :             get_const_collation(constval, context);
                              11638                 :                :         }
 9836                         11639                 :           5834 :         return;
                              11640                 :                :     }
                              11641                 :                : 
 8210                         11642                 :          47398 :     getTypeOutputInfo(constval->consttype,
                              11643                 :                :                       &typoutput, &typIsVarlena);
                              11644                 :                : 
 7543                         11645                 :          47398 :     extval = OidOutputFunctionCall(typoutput, constval->constvalue);
                              11646                 :                : 
 9917                         11647   [ +  +  +  + ]:          47398 :     switch (constval->consttype)
                              11648                 :                :     {
                              11649                 :          27860 :         case INT4OID:
                              11650                 :                : 
                              11651                 :                :             /*
                              11652                 :                :              * INT4 can be printed without any decoration, unless it is
                              11653                 :                :              * negative; in that case print it as '-nnn'::integer to ensure
                              11654                 :                :              * that the output will re-parse as a constant, not as a constant
                              11655                 :                :              * plus operator.  In most cases we could get away with printing
                              11656                 :                :              * (-nnn) instead, because of the way that gram.y handles negative
                              11657                 :                :              * literals; but that doesn't work for INT_MIN, and it doesn't
                              11658                 :                :              * seem that much prettier anyway.
                              11659                 :                :              */
 4261                         11660         [ +  + ]:          27860 :             if (extval[0] != '-')
                              11661                 :          27510 :                 appendStringInfoString(buf, extval);
                              11662                 :                :             else
                              11663                 :                :             {
                              11664                 :            350 :                 appendStringInfo(buf, "'%s'", extval);
 3447                         11665                 :            350 :                 needlabel = true;   /* we must attach a cast */
                              11666                 :                :             }
 4261                         11667                 :          27860 :             break;
                              11668                 :                : 
 8868 peter_e@gmx.net         11669                 :            736 :         case NUMERICOID:
                              11670                 :                : 
                              11671                 :                :             /*
                              11672                 :                :              * NUMERIC can be printed without quotes if it looks like a float
                              11673                 :                :              * constant (not an integer, and not Infinity or NaN) and doesn't
                              11674                 :                :              * have a leading sign (for the same reason as for INT4).
                              11675                 :                :              */
 4261 tgl@sss.pgh.pa.us       11676         [ +  - ]:            736 :             if (isdigit((unsigned char) extval[0]) &&
                              11677         [ +  + ]:            736 :                 strcspn(extval, "eE.") != strlen(extval))
                              11678                 :                :             {
                              11679                 :            251 :                 appendStringInfoString(buf, extval);
                              11680                 :                :             }
                              11681                 :                :             else
                              11682                 :                :             {
                              11683                 :            485 :                 appendStringInfo(buf, "'%s'", extval);
 3447                         11684                 :            485 :                 needlabel = true;   /* we must attach a cast */
                              11685                 :                :             }
 8851 bruce@momjian.us        11686                 :            736 :             break;
                              11687                 :                : 
 8868 peter_e@gmx.net         11688                 :           1187 :         case BOOLOID:
 8851 bruce@momjian.us        11689         [ +  + ]:           1187 :             if (strcmp(extval, "t") == 0)
 4776 rhaas@postgresql.org    11690                 :            452 :                 appendStringInfoString(buf, "true");
                              11691                 :                :             else
                              11692                 :            735 :                 appendStringInfoString(buf, "false");
 8868 peter_e@gmx.net         11693                 :           1187 :             break;
                              11694                 :                : 
                              11695                 :          17615 :         default:
 6657 tgl@sss.pgh.pa.us       11696                 :          17615 :             simple_quote_literal(buf, extval);
 9917                         11697                 :          17615 :             break;
                              11698                 :                :     }
                              11699                 :                : 
 9919                         11700                 :          47398 :     pfree(extval);
                              11701                 :                : 
 6901                         11702         [ +  + ]:          47398 :     if (showtype < 0)
 7196                         11703                 :           4834 :         return;
                              11704                 :                : 
                              11705                 :                :     /*
                              11706                 :                :      * For showtype == 0, append ::typename unless the constant will be
                              11707                 :                :      * implicitly typed as the right type when it is read in.
                              11708                 :                :      *
                              11709                 :                :      * XXX this code has to be kept in sync with the behavior of the parser,
                              11710                 :                :      * especially make_const.
                              11711                 :                :      */
 9917                         11712   [ +  +  +  + ]:          42564 :     switch (constval->consttype)
                              11713                 :                :     {
 8868 peter_e@gmx.net         11714                 :           1237 :         case BOOLOID:
                              11715                 :                :         case UNKNOWNOID:
                              11716                 :                :             /* These types can be left unlabeled */
 8837 tgl@sss.pgh.pa.us       11717                 :           1237 :             needlabel = false;
                              11718                 :           1237 :             break;
 4261                         11719                 :          25239 :         case INT4OID:
                              11720                 :                :             /* We determined above whether a label is needed */
                              11721                 :          25239 :             break;
 8837                         11722                 :            736 :         case NUMERICOID:
                              11723                 :                : 
                              11724                 :                :             /*
                              11725                 :                :              * Float-looking constants will be typed as numeric, which we
                              11726                 :                :              * checked above; but if there's a nondefault typmod we need to
                              11727                 :                :              * show it.
                              11728                 :                :              */
 4261                         11729                 :            736 :             needlabel |= (constval->consttypmod >= 0);
 9917                         11730                 :            736 :             break;
                              11731                 :          15352 :         default:
 8837                         11732                 :          15352 :             needlabel = true;
 9917                         11733                 :          15352 :             break;
                              11734                 :                :     }
 6901                         11735   [ +  +  -  + ]:          42564 :     if (needlabel || showtype > 0)
 8837                         11736                 :          16181 :         appendStringInfo(buf, "::%s",
                              11737                 :                :                          format_type_with_typemod(constval->consttype,
                              11738                 :                :                                                   constval->consttypmod));
                              11739                 :                : 
 5741                         11740                 :          42564 :     get_const_collation(constval, context);
                              11741                 :                : }
                              11742                 :                : 
                              11743                 :                : /*
                              11744                 :                :  * helper for get_const_expr: append COLLATE if needed
                              11745                 :                :  */
                              11746                 :                : static void
                              11747                 :          43530 : get_const_collation(Const *constval, deparse_context *context)
                              11748                 :                : {
                              11749                 :          43530 :     StringInfo  buf = context->buf;
                              11750                 :                : 
                              11751         [ +  + ]:          43530 :     if (OidIsValid(constval->constcollid))
                              11752                 :                :     {
 5711 bruce@momjian.us        11753                 :           5987 :         Oid         typcollation = get_typcollation(constval->consttype);
                              11754                 :                : 
 5741 tgl@sss.pgh.pa.us       11755         [ +  + ]:           5987 :         if (constval->constcollid != typcollation)
                              11756                 :                :         {
                              11757                 :            160 :             appendStringInfo(buf, " COLLATE %s",
                              11758                 :                :                              generate_collation_name(constval->constcollid));
                              11759                 :                :         }
                              11760                 :                :     }
10284 bruce@momjian.us        11761                 :          43530 : }
                              11762                 :                : 
                              11763                 :                : /*
                              11764                 :                :  * get_json_path_spec       - Parse back a JSON path specification
                              11765                 :                :  */
                              11766                 :                : static void
  982 amitlan@postgresql.o    11767                 :            436 : get_json_path_spec(Node *path_spec, deparse_context *context, bool showimplicit)
                              11768                 :                : {
                              11769         [ +  - ]:            436 :     if (IsA(path_spec, Const))
                              11770                 :            436 :         get_const_expr((Const *) path_spec, context, -1);
                              11771                 :                :     else
  982 amitlan@postgresql.o    11772                 :UBC           0 :         get_rule_expr(path_spec, context, showimplicit);
  982 amitlan@postgresql.o    11773                 :CBC         436 : }
                              11774                 :                : 
                              11775                 :                : /*
                              11776                 :                :  * get_json_format          - Parse back a JsonFormat node
                              11777                 :                :  */
                              11778                 :                : static void
 1340 alvherre@alvh.no-ip.    11779                 :            148 : get_json_format(JsonFormat *format, StringInfo buf)
                              11780                 :                : {
                              11781         [ +  + ]:            148 :     if (format->format_type == JS_FORMAT_DEFAULT)
                              11782                 :             92 :         return;
                              11783                 :                : 
                              11784                 :             56 :     appendStringInfoString(buf,
                              11785         [ -  + ]:             56 :                            format->format_type == JS_FORMAT_JSONB ?
                              11786                 :                :                            " FORMAT JSONB" : " FORMAT JSON");
                              11787                 :                : 
                              11788         [ +  + ]:             56 :     if (format->encoding != JS_ENC_DEFAULT)
                              11789                 :                :     {
                              11790                 :                :         const char *encoding;
                              11791                 :                : 
                              11792                 :              4 :         encoding =
                              11793         [ +  - ]:              8 :             format->encoding == JS_ENC_UTF16 ? "UTF16" :
                              11794         [ -  + ]:              4 :             format->encoding == JS_ENC_UTF32 ? "UTF32" : "UTF8";
                              11795                 :                : 
                              11796                 :              4 :         appendStringInfo(buf, " ENCODING %s", encoding);
                              11797                 :                :     }
                              11798                 :                : }
                              11799                 :                : 
                              11800                 :                : /*
                              11801                 :                :  * get_json_returning       - Parse back a JsonReturning structure
                              11802                 :                :  */
                              11803                 :                : static void
                              11804                 :            212 : get_json_returning(JsonReturning *returning, StringInfo buf,
                              11805                 :                :                    bool json_format_by_default)
                              11806                 :                : {
                              11807         [ -  + ]:            212 :     if (!OidIsValid(returning->typid))
 1340 alvherre@alvh.no-ip.    11808                 :UBC           0 :         return;
                              11809                 :                : 
 1340 alvherre@alvh.no-ip.    11810                 :CBC         212 :     appendStringInfo(buf, " RETURNING %s",
                              11811                 :                :                      format_type_with_typemod(returning->typid,
                              11812                 :                :                                               returning->typmod));
                              11813                 :                : 
                              11814   [ +  +  +  + ]:            416 :     if (!json_format_by_default ||
                              11815                 :            204 :         returning->format->format_type !=
                              11816         [ +  + ]:            204 :         (returning->typid == JSONBOID ? JS_FORMAT_JSONB : JS_FORMAT_JSON))
                              11817                 :             24 :         get_json_format(returning->format, buf);
                              11818                 :                : }
                              11819                 :                : 
                              11820                 :                : /*
                              11821                 :                :  * get_json_constructor     - Parse back a JsonConstructorExpr node
                              11822                 :                :  */
                              11823                 :                : static void
                              11824                 :            216 : get_json_constructor(JsonConstructorExpr *ctor, deparse_context *context,
                              11825                 :                :                      bool showimplicit)
                              11826                 :                : {
                              11827                 :            216 :     StringInfo  buf = context->buf;
                              11828                 :                :     const char *funcname;
                              11829                 :                :     bool        is_json_object;
                              11830                 :                :     int         curridx;
                              11831                 :                :     ListCell   *lc;
                              11832                 :                : 
                              11833         [ +  + ]:            216 :     if (ctor->type == JSCTOR_JSON_OBJECTAGG)
                              11834                 :                :     {
                              11835                 :             40 :         get_json_agg_constructor(ctor, context, "JSON_OBJECTAGG", true);
                              11836                 :             40 :         return;
                              11837                 :                :     }
                              11838         [ +  + ]:            176 :     else if (ctor->type == JSCTOR_JSON_ARRAYAGG)
                              11839                 :                :     {
                              11840                 :             68 :         get_json_agg_constructor(ctor, context, "JSON_ARRAYAGG", false);
                              11841                 :             68 :         return;
                              11842                 :                :     }
  211 rguo@postgresql.org     11843         [ +  + ]:            108 :     else if (ctor->type == JSCTOR_JSON_ARRAY_QUERY)
                              11844                 :                :     {
                              11845                 :             20 :         Query      *query = castNode(Query, ctor->orig_query);
                              11846                 :                : 
                              11847                 :             20 :         appendStringInfo(buf, "JSON_ARRAY(");
                              11848                 :                : 
                              11849                 :             20 :         get_query_def(query, buf, context->namespaces, NULL, false,
                              11850                 :                :                       context->prettyFlags, context->wrapColumn,
                              11851                 :                :                       context->indentLevel);
                              11852                 :                : 
  124                         11853                 :             20 :         get_json_format(ctor->format, buf);
  211                         11854                 :             20 :         get_json_constructor_options(ctor, buf);
                              11855                 :             20 :         appendStringInfoChar(buf, ')');
                              11856                 :                : 
                              11857                 :             20 :         return;
                              11858                 :                :     }
                              11859                 :                : 
 1340 alvherre@alvh.no-ip.    11860   [ +  +  +  +  :             88 :     switch (ctor->type)
                                              +  - ]
                              11861                 :                :     {
                              11862                 :             28 :         case JSCTOR_JSON_OBJECT:
                              11863                 :             28 :             funcname = "JSON_OBJECT";
                              11864                 :             28 :             break;
                              11865                 :             16 :         case JSCTOR_JSON_ARRAY:
                              11866                 :             16 :             funcname = "JSON_ARRAY";
                              11867                 :             16 :             break;
 1227 amitlan@postgresql.o    11868                 :             28 :         case JSCTOR_JSON_PARSE:
                              11869                 :             28 :             funcname = "JSON";
                              11870                 :             28 :             break;
                              11871                 :              8 :         case JSCTOR_JSON_SCALAR:
                              11872                 :              8 :             funcname = "JSON_SCALAR";
                              11873                 :              8 :             break;
                              11874                 :              8 :         case JSCTOR_JSON_SERIALIZE:
                              11875                 :              8 :             funcname = "JSON_SERIALIZE";
                              11876                 :              8 :             break;
 1340 alvherre@alvh.no-ip.    11877                 :UBC           0 :         default:
 1339                         11878         [ #  # ]:              0 :             elog(ERROR, "invalid JsonConstructorType %d", ctor->type);
                              11879                 :                :     }
                              11880                 :                : 
 1340 alvherre@alvh.no-ip.    11881                 :CBC          88 :     appendStringInfo(buf, "%s(", funcname);
                              11882                 :                : 
                              11883                 :             88 :     is_json_object = ctor->type == JSCTOR_JSON_OBJECT;
                              11884   [ +  -  +  +  :            236 :     foreach(lc, ctor->args)
                                              +  + ]
                              11885                 :                :     {
                              11886                 :            148 :         curridx = foreach_current_index(lc);
                              11887         [ +  + ]:            148 :         if (curridx > 0)
                              11888                 :                :         {
                              11889                 :                :             const char *sep;
                              11890                 :                : 
                              11891   [ +  +  +  + ]:             60 :             sep = (is_json_object && (curridx % 2) != 0) ? " : " : ", ";
                              11892                 :             60 :             appendStringInfoString(buf, sep);
                              11893                 :                :         }
                              11894                 :                : 
                              11895                 :            148 :         get_rule_expr((Node *) lfirst(lc), context, true);
                              11896                 :                :     }
                              11897                 :                : 
                              11898                 :             88 :     get_json_constructor_options(ctor, buf);
 1152 drowley@postgresql.o    11899                 :             88 :     appendStringInfoChar(buf, ')');
                              11900                 :                : }
                              11901                 :                : 
                              11902                 :                : /*
                              11903                 :                :  * Append options, if any, to the JSON constructor being deparsed
                              11904                 :                :  */
                              11905                 :                : static void
 1340 alvherre@alvh.no-ip.    11906                 :            216 : get_json_constructor_options(JsonConstructorExpr *ctor, StringInfo buf)
                              11907                 :                : {
                              11908         [ +  + ]:            216 :     if (ctor->absent_on_null)
                              11909                 :                :     {
                              11910         [ +  - ]:             84 :         if (ctor->type == JSCTOR_JSON_OBJECT ||
                              11911         [ +  + ]:             84 :             ctor->type == JSCTOR_JSON_OBJECTAGG)
                              11912                 :              8 :             appendStringInfoString(buf, " ABSENT ON NULL");
                              11913                 :                :     }
                              11914                 :                :     else
                              11915                 :                :     {
                              11916         [ +  - ]:            132 :         if (ctor->type == JSCTOR_JSON_ARRAY ||
                              11917         [ +  + ]:            132 :             ctor->type == JSCTOR_JSON_ARRAYAGG)
                              11918                 :             28 :             appendStringInfoString(buf, " NULL ON NULL");
                              11919                 :                :     }
                              11920                 :                : 
                              11921         [ +  + ]:            216 :     if (ctor->unique)
                              11922                 :             24 :         appendStringInfoString(buf, " WITH UNIQUE KEYS");
                              11923                 :                : 
                              11924                 :                :     /*
                              11925                 :                :      * Append RETURNING clause if needed; JSON() and JSON_SCALAR() don't
                              11926                 :                :      * support one.
                              11927                 :                :      */
 1227 amitlan@postgresql.o    11928   [ +  +  +  + ]:            216 :     if (ctor->type != JSCTOR_JSON_PARSE && ctor->type != JSCTOR_JSON_SCALAR)
                              11929                 :            180 :         get_json_returning(ctor->returning, buf, true);
 1340 alvherre@alvh.no-ip.    11930                 :            216 : }
                              11931                 :                : 
                              11932                 :                : /*
                              11933                 :                :  * get_json_agg_constructor - Parse back an aggregate JsonConstructorExpr node
                              11934                 :                :  */
                              11935                 :                : static void
                              11936                 :            108 : get_json_agg_constructor(JsonConstructorExpr *ctor, deparse_context *context,
                              11937                 :                :                          const char *funcname, bool is_json_objectagg)
                              11938                 :                : {
                              11939                 :                :     StringInfoData options;
                              11940                 :                : 
                              11941                 :            108 :     initStringInfo(&options);
                              11942                 :            108 :     get_json_constructor_options(ctor, &options);
                              11943                 :                : 
                              11944         [ +  + ]:            108 :     if (IsA(ctor->func, Aggref))
                              11945                 :             68 :         get_agg_expr_helper((Aggref *) ctor->func, context,
                              11946                 :             68 :                             (Aggref *) ctor->func,
                              11947                 :             68 :                             funcname, options.data, is_json_objectagg);
                              11948         [ +  + ]:             40 :     else if (IsA(ctor->func, WindowFunc))
                              11949                 :             12 :         get_windowfunc_expr_helper((WindowFunc *) ctor->func, context,
                              11950                 :             12 :                                    funcname, options.data,
                              11951                 :                :                                    is_json_objectagg);
  143 rguo@postgresql.org     11952         [ +  - ]:             28 :     else if (IsA(ctor->func, Var))
                              11953                 :                :     {
                              11954                 :                :         /*
                              11955                 :                :          * If the aggregate is computed by a lower plan node, setrefs.c will
                              11956                 :                :          * have replaced the Aggref or WindowFunc with a Var referencing that
                              11957                 :                :          * node's output.  Chase the Var back to it so we can still print the
                              11958                 :                :          * original JSON aggregate syntax.  This only happens in EXPLAIN.
                              11959                 :                :          */
                              11960                 :             28 :         resolve_special_varno((Node *) ctor->func, context,
                              11961                 :                :                               get_json_agg_constructor_expr, ctor);
                              11962                 :                :     }
                              11963                 :                :     else
 1340 alvherre@alvh.no-ip.    11964         [ #  # ]:UBC           0 :         elog(ERROR, "invalid JsonConstructorExpr underlying node type: %d",
                              11965                 :                :              nodeTag(ctor->func));
 1340 alvherre@alvh.no-ip.    11966                 :CBC         108 : }
                              11967                 :                : 
                              11968                 :                : /*
                              11969                 :                :  * Deparse a JsonConstructorExpr whose aggregate is computed by a lower plan
                              11970                 :                :  * node; resolve_special_varno has located the underlying Aggref/WindowFunc.
                              11971                 :                :  */
                              11972                 :                : static void
  143 rguo@postgresql.org     11973                 :             28 : get_json_agg_constructor_expr(Node *node, deparse_context *context,
                              11974                 :                :                               void *callback_arg)
                              11975                 :                : {
                              11976                 :                :     JsonConstructorExpr ctor;
                              11977                 :                : 
                              11978   [ +  +  -  + ]:             28 :     if (!IsA(node, Aggref) && !IsA(node, WindowFunc))
  143 rguo@postgresql.org     11979         [ #  # ]:UBC           0 :         elog(ERROR, "JSON aggregate constructor does not point to an Aggref or WindowFunc");
                              11980                 :                : 
                              11981                 :                :     /* Flat copy suffices; we only replace func. */
  143 rguo@postgresql.org     11982                 :CBC          28 :     ctor = *(JsonConstructorExpr *) callback_arg;
                              11983                 :             28 :     ctor.func = (Expr *) node;
                              11984                 :             28 :     get_json_constructor(&ctor, context, false);
                              11985                 :             28 : }
                              11986                 :                : 
                              11987                 :                : /*
                              11988                 :                :  * simple_quote_literal - Format a string as a SQL literal, append to buf
                              11989                 :                :  */
                              11990                 :                : static void
 6657 tgl@sss.pgh.pa.us       11991                 :          18036 : simple_quote_literal(StringInfo buf, const char *val)
                              11992                 :                : {
                              11993                 :                :     const char *valptr;
                              11994                 :                : 
                              11995                 :                :     /*
                              11996                 :                :      * We always form the string literal according to standard SQL rules.
                              11997                 :                :      */
                              11998                 :          18036 :     appendStringInfoChar(buf, '\'');
                              11999         [ +  + ]:         181573 :     for (valptr = val; *valptr; valptr++)
                              12000                 :                :     {
                              12001                 :         163537 :         char        ch = *valptr;
                              12002                 :                : 
  311                         12003         [ +  + ]:         163537 :         if (SQL_STR_DOUBLE(ch, false))
 6657                         12004                 :            204 :             appendStringInfoChar(buf, ch);
                              12005                 :         163537 :         appendStringInfoChar(buf, ch);
                              12006                 :                :     }
                              12007                 :          18036 :     appendStringInfoChar(buf, '\'');
                              12008                 :          18036 : }
                              12009                 :                : 
                              12010                 :                : 
                              12011                 :                : /* ----------
                              12012                 :                :  * get_sublink_expr         - Parse back a sublink
                              12013                 :                :  * ----------
                              12014                 :                :  */
                              12015                 :                : static void
 8752                         12016                 :            306 : get_sublink_expr(SubLink *sublink, deparse_context *context)
                              12017                 :                : {
 9918                         12018                 :            306 :     StringInfo  buf = context->buf;
10284 bruce@momjian.us        12019                 :            306 :     Query      *query = (Query *) (sublink->subselect);
 7640 tgl@sss.pgh.pa.us       12020                 :            306 :     char       *opname = NULL;
                              12021                 :                :     bool        need_paren;
                              12022                 :                : 
 8635                         12023         [ +  + ]:            306 :     if (sublink->subLinkType == ARRAY_SUBLINK)
 4776 rhaas@postgresql.org    12024                 :             14 :         appendStringInfoString(buf, "ARRAY(");
                              12025                 :                :     else
 8635 tgl@sss.pgh.pa.us       12026                 :            292 :         appendStringInfoChar(buf, '(');
                              12027                 :                : 
                              12028                 :                :     /*
                              12029                 :                :      * Note that we print the name of only the first operator, when there are
                              12030                 :                :      * multiple combining operators.  This is an approximation that could go
                              12031                 :                :      * wrong in various scenarios (operators in different schemas, renamed
                              12032                 :                :      * operators, etc) but there is not a whole lot we can do about it, since
                              12033                 :                :      * the syntax allows only one operator to be shown.
                              12034                 :                :      */
 7640                         12035         [ +  + ]:            306 :     if (sublink->testexpr)
                              12036                 :                :     {
                              12037         [ +  + ]:             24 :         if (IsA(sublink->testexpr, OpExpr))
                              12038                 :                :         {
                              12039                 :                :             /* single combining operator */
 7360 bruce@momjian.us        12040                 :             16 :             OpExpr     *opexpr = (OpExpr *) sublink->testexpr;
                              12041                 :                : 
                              12042                 :                :             /* Use get_rule_expr_paren to add parens if needed */
   40 tgl@sss.pgh.pa.us       12043                 :             16 :             get_rule_expr_paren(linitial(opexpr->args), context, true,
                              12044                 :                :                                 (Node *) sublink);
 7640                         12045                 :             16 :             opname = generate_operator_name(opexpr->opno,
                              12046                 :             16 :                                             exprType(linitial(opexpr->args)),
                              12047                 :             16 :                                             exprType(lsecond(opexpr->args)));
                              12048                 :                :         }
                              12049         [ +  + ]:              8 :         else if (IsA(sublink->testexpr, BoolExpr))
                              12050                 :                :         {
                              12051                 :                :             /* multiple combining operators, = or <> cases */
                              12052                 :                :             char       *sep;
                              12053                 :                :             ListCell   *l;
                              12054                 :                : 
 9778                         12055                 :              4 :             appendStringInfoChar(buf, '(');
 7640                         12056                 :              4 :             sep = "";
                              12057   [ +  -  +  +  :             12 :             foreach(l, ((BoolExpr *) sublink->testexpr)->args)
                                              +  + ]
                              12058                 :                :             {
 3519                         12059                 :              8 :                 OpExpr     *opexpr = lfirst_node(OpExpr, l);
                              12060                 :                : 
 7640                         12061                 :              8 :                 appendStringInfoString(buf, sep);
                              12062                 :              8 :                 get_rule_expr(linitial(opexpr->args), context, true);
                              12063         [ +  + ]:              8 :                 if (!opname)
                              12064                 :              4 :                     opname = generate_operator_name(opexpr->opno,
 3447                         12065                 :              4 :                                                     exprType(linitial(opexpr->args)),
                              12066                 :              4 :                                                     exprType(lsecond(opexpr->args)));
 7640                         12067                 :              8 :                 sep = ", ";
                              12068                 :                :             }
 8087                         12069                 :              4 :             appendStringInfoChar(buf, ')');
                              12070                 :                :         }
 7640                         12071         [ +  - ]:              4 :         else if (IsA(sublink->testexpr, RowCompareExpr))
                              12072                 :                :         {
                              12073                 :                :             /* multiple combining operators, < <= > >= cases */
                              12074                 :              4 :             RowCompareExpr *rcexpr = (RowCompareExpr *) sublink->testexpr;
                              12075                 :                : 
                              12076                 :              4 :             appendStringInfoChar(buf, '(');
                              12077                 :              4 :             get_rule_expr((Node *) rcexpr->largs, context, true);
                              12078                 :              4 :             opname = generate_operator_name(linitial_oid(rcexpr->opnos),
                              12079                 :              4 :                                             exprType(linitial(rcexpr->largs)),
 3447                         12080                 :              4 :                                             exprType(linitial(rcexpr->rargs)));
 7640                         12081                 :              4 :             appendStringInfoChar(buf, ')');
                              12082                 :                :         }
                              12083                 :                :         else
 7640 tgl@sss.pgh.pa.us       12084         [ #  # ]:UBC           0 :             elog(ERROR, "unrecognized testexpr type: %d",
                              12085                 :                :                  (int) nodeTag(sublink->testexpr));
                              12086                 :                :     }
                              12087                 :                : 
 9875 tgl@sss.pgh.pa.us       12088                 :CBC         306 :     need_paren = true;
                              12089                 :                : 
10049 bruce@momjian.us        12090   [ +  +  +  -  :            306 :     switch (sublink->subLinkType)
                                              +  - ]
                              12091                 :                :     {
10284                         12092                 :            113 :         case EXISTS_SUBLINK:
 4776 rhaas@postgresql.org    12093                 :            113 :             appendStringInfoString(buf, "EXISTS ");
10284 bruce@momjian.us        12094                 :            113 :             break;
                              12095                 :                : 
                              12096                 :             16 :         case ANY_SUBLINK:
 3447 tgl@sss.pgh.pa.us       12097         [ +  + ]:             16 :             if (strcmp(opname, "=") == 0) /* Represent = ANY as IN */
 4776 rhaas@postgresql.org    12098                 :             12 :                 appendStringInfoString(buf, " IN ");
                              12099                 :                :             else
 7640 tgl@sss.pgh.pa.us       12100                 :              4 :                 appendStringInfo(buf, " %s ANY ", opname);
10284 bruce@momjian.us        12101                 :             16 :             break;
                              12102                 :                : 
                              12103                 :              8 :         case ALL_SUBLINK:
 7640 tgl@sss.pgh.pa.us       12104                 :              8 :             appendStringInfo(buf, " %s ALL ", opname);
10284 bruce@momjian.us        12105                 :              8 :             break;
                              12106                 :                : 
 7640 tgl@sss.pgh.pa.us       12107                 :UBC           0 :         case ROWCOMPARE_SUBLINK:
                              12108                 :              0 :             appendStringInfo(buf, " %s ", opname);
10284 bruce@momjian.us        12109                 :              0 :             break;
                              12110                 :                : 
 9875 tgl@sss.pgh.pa.us       12111                 :CBC         169 :         case EXPR_SUBLINK:
                              12112                 :                :         case MULTIEXPR_SUBLINK:
                              12113                 :                :         case ARRAY_SUBLINK:
                              12114                 :            169 :             need_paren = false;
                              12115                 :            169 :             break;
                              12116                 :                : 
 6629 tgl@sss.pgh.pa.us       12117                 :UBC           0 :         case CTE_SUBLINK:       /* shouldn't occur in a SubLink */
                              12118                 :                :         default:
 8525                         12119         [ #  # ]:              0 :             elog(ERROR, "unrecognized sublink type: %d",
                              12120                 :                :                  (int) sublink->subLinkType);
                              12121                 :                :             break;
                              12122                 :                :     }
                              12123                 :                : 
 9875 tgl@sss.pgh.pa.us       12124         [ +  + ]:CBC         306 :     if (need_paren)
 9778                         12125                 :            137 :         appendStringInfoChar(buf, '(');
                              12126                 :                : 
 1652                         12127                 :            306 :     get_query_def(query, buf, context->namespaces, NULL, false,
                              12128                 :                :                   context->prettyFlags, context->wrapColumn,
                              12129                 :                :                   context->indentLevel);
                              12130                 :                : 
 9875                         12131         [ +  + ]:            306 :     if (need_paren)
 4776 rhaas@postgresql.org    12132                 :            137 :         appendStringInfoString(buf, "))");
                              12133                 :                :     else
 9778 tgl@sss.pgh.pa.us       12134                 :            169 :         appendStringInfoChar(buf, ')');
10323 bruce@momjian.us        12135                 :            306 : }
                              12136                 :                : 
                              12137                 :                : 
                              12138                 :                : /* ----------
                              12139                 :                :  * get_xmltable         - Parse back a XMLTABLE function
                              12140                 :                :  * ----------
                              12141                 :                :  */
                              12142                 :                : static void
  968 amitlan@postgresql.o    12143                 :             38 : get_xmltable(TableFunc *tf, deparse_context *context, bool showimplicit)
                              12144                 :                : {
 3552 alvherre@alvh.no-ip.    12145                 :             38 :     StringInfo  buf = context->buf;
                              12146                 :                : 
                              12147                 :             38 :     appendStringInfoString(buf, "XMLTABLE(");
                              12148                 :                : 
                              12149         [ +  + ]:             38 :     if (tf->ns_uris != NIL)
                              12150                 :                :     {
                              12151                 :                :         ListCell   *lc1,
                              12152                 :                :                    *lc2;
                              12153                 :              9 :         bool        first = true;
                              12154                 :                : 
                              12155                 :              9 :         appendStringInfoString(buf, "XMLNAMESPACES (");
                              12156   [ +  -  +  +  :             18 :         forboth(lc1, tf->ns_uris, lc2, tf->ns_names)
                                     +  -  +  +  +  
                                        +  +  -  +  
                                                 + ]
                              12157                 :                :         {
                              12158                 :              9 :             Node       *expr = (Node *) lfirst(lc1);
 1906 peter@eisentraut.org    12159                 :              9 :             String     *ns_node = lfirst_node(String, lc2);
                              12160                 :                : 
 3552 alvherre@alvh.no-ip.    12161         [ -  + ]:              9 :             if (!first)
 3552 alvherre@alvh.no-ip.    12162                 :UBC           0 :                 appendStringInfoString(buf, ", ");
                              12163                 :                :             else
 3552 alvherre@alvh.no-ip.    12164                 :CBC           9 :                 first = false;
                              12165                 :                : 
 2994 tgl@sss.pgh.pa.us       12166         [ +  - ]:              9 :             if (ns_node != NULL)
                              12167                 :                :             {
 3552 alvherre@alvh.no-ip.    12168                 :              9 :                 get_rule_expr(expr, context, showimplicit);
  685 dean.a.rasheed@gmail    12169                 :              9 :                 appendStringInfo(buf, " AS %s",
                              12170                 :              9 :                                  quote_identifier(strVal(ns_node)));
                              12171                 :                :             }
                              12172                 :                :             else
                              12173                 :                :             {
 3552 alvherre@alvh.no-ip.    12174                 :UBC           0 :                 appendStringInfoString(buf, "DEFAULT ");
                              12175                 :              0 :                 get_rule_expr(expr, context, showimplicit);
                              12176                 :                :             }
                              12177                 :                :         }
 3552 alvherre@alvh.no-ip.    12178                 :CBC           9 :         appendStringInfoString(buf, "), ");
                              12179                 :                :     }
                              12180                 :                : 
                              12181                 :             38 :     appendStringInfoChar(buf, '(');
                              12182                 :             38 :     get_rule_expr((Node *) tf->rowexpr, context, showimplicit);
                              12183                 :             38 :     appendStringInfoString(buf, ") PASSING (");
                              12184                 :             38 :     get_rule_expr((Node *) tf->docexpr, context, showimplicit);
                              12185                 :             38 :     appendStringInfoChar(buf, ')');
                              12186                 :                : 
                              12187         [ +  - ]:             38 :     if (tf->colexprs != NIL)
                              12188                 :                :     {
                              12189                 :                :         ListCell   *l1;
                              12190                 :                :         ListCell   *l2;
                              12191                 :                :         ListCell   *l3;
                              12192                 :                :         ListCell   *l4;
                              12193                 :                :         ListCell   *l5;
                              12194                 :             38 :         int         colnum = 0;
                              12195                 :                : 
                              12196                 :             38 :         appendStringInfoString(buf, " COLUMNS ");
 2830 tgl@sss.pgh.pa.us       12197   [ +  -  +  +  :            231 :         forfive(l1, tf->colnames, l2, tf->coltypes, l3, tf->coltypmods,
                                     +  -  +  +  +  
                                     -  +  +  +  -  
                                     +  +  +  -  +  
                                     +  +  +  +  -  
                                     +  -  +  -  +  
                                           -  +  + ]
                              12198                 :                :                 l4, tf->colexprs, l5, tf->coldefexprs)
                              12199                 :                :         {
 3552 alvherre@alvh.no-ip.    12200                 :            193 :             char       *colname = strVal(lfirst(l1));
 2830 tgl@sss.pgh.pa.us       12201                 :            193 :             Oid         typid = lfirst_oid(l2);
                              12202                 :            193 :             int32       typmod = lfirst_int(l3);
                              12203                 :            193 :             Node       *colexpr = (Node *) lfirst(l4);
                              12204                 :            193 :             Node       *coldefexpr = (Node *) lfirst(l5);
                              12205                 :            193 :             bool        ordinality = (tf->ordinalitycol == colnum);
 3552 alvherre@alvh.no-ip.    12206                 :            193 :             bool        notnull = bms_is_member(colnum, tf->notnulls);
                              12207                 :                : 
                              12208         [ +  + ]:            193 :             if (colnum > 0)
                              12209                 :            155 :                 appendStringInfoString(buf, ", ");
                              12210                 :            193 :             colnum++;
                              12211                 :                : 
                              12212         [ +  + ]:            365 :             appendStringInfo(buf, "%s %s", quote_identifier(colname),
                              12213                 :                :                              ordinality ? "FOR ORDINALITY" :
                              12214                 :            172 :                              format_type_with_typemod(typid, typmod));
                              12215         [ +  + ]:            193 :             if (ordinality)
                              12216                 :             21 :                 continue;
                              12217                 :                : 
                              12218         [ +  + ]:            172 :             if (coldefexpr != NULL)
                              12219                 :                :             {
                              12220                 :             21 :                 appendStringInfoString(buf, " DEFAULT (");
                              12221                 :             21 :                 get_rule_expr((Node *) coldefexpr, context, showimplicit);
                              12222                 :             21 :                 appendStringInfoChar(buf, ')');
                              12223                 :                :             }
                              12224         [ +  + ]:            172 :             if (colexpr != NULL)
                              12225                 :                :             {
                              12226                 :            156 :                 appendStringInfoString(buf, " PATH (");
                              12227                 :            156 :                 get_rule_expr((Node *) colexpr, context, showimplicit);
                              12228                 :            156 :                 appendStringInfoChar(buf, ')');
                              12229                 :                :             }
                              12230         [ +  + ]:            172 :             if (notnull)
                              12231                 :             21 :                 appendStringInfoString(buf, " NOT NULL");
                              12232                 :                :         }
                              12233                 :                :     }
                              12234                 :                : 
                              12235                 :             38 :     appendStringInfoChar(buf, ')');
                              12236                 :             38 : }
                              12237                 :                : 
                              12238                 :                : /*
                              12239                 :                :  * get_json_table_nested_columns - Parse back nested JSON_TABLE columns
                              12240                 :                :  */
                              12241                 :                : static void
  964 amitlan@postgresql.o    12242                 :            104 : get_json_table_nested_columns(TableFunc *tf, JsonTablePlan *plan,
                              12243                 :                :                               deparse_context *context, bool showimplicit,
                              12244                 :                :                               bool needcomma)
                              12245                 :                : {
                              12246         [ +  + ]:            104 :     if (IsA(plan, JsonTablePathScan))
                              12247                 :                :     {
                              12248                 :             76 :         JsonTablePathScan *scan = castNode(JsonTablePathScan, plan);
                              12249                 :                : 
                              12250         [ +  + ]:             76 :         if (needcomma)
                              12251                 :             48 :             appendStringInfoChar(context->buf, ',');
                              12252                 :                : 
                              12253                 :             76 :         appendStringInfoChar(context->buf, ' ');
                              12254                 :             76 :         appendContextKeyword(context, "NESTED PATH ", 0, 0, 0);
                              12255                 :             76 :         get_const_expr(scan->path->value, context, -1);
                              12256                 :             76 :         appendStringInfo(context->buf, " AS %s", quote_identifier(scan->path->name));
                              12257                 :             76 :         get_json_table_columns(tf, scan, context, showimplicit);
                              12258                 :                :     }
                              12259         [ +  - ]:             28 :     else if (IsA(plan, JsonTableSiblingJoin))
                              12260                 :                :     {
                              12261                 :             28 :         JsonTableSiblingJoin *join = (JsonTableSiblingJoin *) plan;
                              12262                 :                : 
                              12263                 :             28 :         get_json_table_nested_columns(tf, join->lplan, context, showimplicit,
                              12264                 :                :                                       needcomma);
                              12265                 :             28 :         get_json_table_nested_columns(tf, join->rplan, context, showimplicit,
                              12266                 :                :                                       true);
                              12267                 :                :     }
                              12268                 :            104 : }
                              12269                 :                : 
                              12270                 :                : /*
                              12271                 :                :  * json_table_plan_is_default - does this plan match the implicit default?
                              12272                 :                :  *
                              12273                 :                :  * When no PLAN clause is given, JSON_TABLE builds a default plan that joins
                              12274                 :                :  * every nested path to its parent with OUTER and every set of sibling paths
                              12275                 :                :  * with UNION (see transformJsonTableColumns()).  Such a plan is fully implied
                              12276                 :                :  * by the NESTED COLUMNS structure, so we need not (and, to match the input,
                              12277                 :                :  * should not) print a PLAN clause for it; we only deparse a PLAN clause when
                              12278                 :                :  * the plan deviates from the default, i.e. uses an INNER or CROSS join
                              12279                 :                :  * somewhere.  This follows the usual ruleutils convention of omitting a clause
                              12280                 :                :  * that merely restates the default (cf. get_json_expr_options() for ON
                              12281                 :                :  * EMPTY/ON ERROR, or the NULLS FIRST/LAST handling in get_rule_orderby()).
                              12282                 :                :  */
                              12283                 :                : static bool
  142 akorotkov@postgresql    12284                 :GNC         116 : json_table_plan_is_default(JsonTablePlan *plan)
                              12285                 :                : {
                              12286         [ +  + ]:            116 :     if (IsA(plan, JsonTablePathScan))
                              12287                 :                :     {
                              12288                 :             88 :         JsonTablePathScan *scan = castNode(JsonTablePathScan, plan);
                              12289                 :                : 
                              12290         [ +  + ]:             88 :         if (scan->child)
                              12291                 :                :         {
                              12292         [ +  + ]:             48 :             if (!scan->outerJoin)
                              12293                 :              4 :                 return false;   /* INNER is not the default */
                              12294                 :             44 :             return json_table_plan_is_default(scan->child);
                              12295                 :                :         }
                              12296                 :                : 
                              12297                 :             40 :         return true;
                              12298                 :                :     }
                              12299                 :                :     else
                              12300                 :                :     {
                              12301                 :             28 :         JsonTableSiblingJoin *join = castNode(JsonTableSiblingJoin, plan);
                              12302                 :                : 
                              12303         [ -  + ]:             28 :         if (join->cross)
  142 akorotkov@postgresql    12304                 :UNC           0 :             return false;       /* CROSS is not the default */
  142 akorotkov@postgresql    12305   [ +  -  +  - ]:GNC          56 :         return json_table_plan_is_default(join->lplan) &&
                              12306                 :             28 :             json_table_plan_is_default(join->rplan);
                              12307                 :                :     }
                              12308                 :                : }
                              12309                 :                : 
                              12310                 :                : /*
                              12311                 :                :  * get_json_table_plan - Parse back a JSON_TABLE plan
                              12312                 :                :  */
                              12313                 :                : static void
                              12314                 :             12 : get_json_table_plan(TableFunc *tf, JsonTablePlan *plan, deparse_context *context,
                              12315                 :                :                     bool parenthesize)
                              12316                 :                : {
                              12317         [ +  + ]:             12 :     if (parenthesize)
                              12318                 :              8 :         appendStringInfoChar(context->buf, '(');
                              12319                 :                : 
                              12320         [ +  - ]:             12 :     if (IsA(plan, JsonTablePathScan))
                              12321                 :                :     {
                              12322                 :             12 :         JsonTablePathScan *s = castNode(JsonTablePathScan, plan);
                              12323                 :                : 
                              12324                 :             12 :         appendStringInfoString(context->buf, quote_identifier(s->path->name));
                              12325                 :                : 
                              12326         [ +  + ]:             12 :         if (s->child)
                              12327                 :                :         {
                              12328                 :              8 :             appendStringInfoString(context->buf,
                              12329         [ +  + ]:              8 :                                    s->outerJoin ? " OUTER " : " INNER ");
                              12330                 :              8 :             get_json_table_plan(tf, s->child, context,
  136                         12331         [ +  - ]:             16 :                                 IsA(s->child, JsonTableSiblingJoin) ||
                              12332         [ +  + ]:             16 :                                 castNode(JsonTablePathScan, s->child)->child);
                              12333                 :                :         }
                              12334                 :                :     }
  142 akorotkov@postgresql    12335         [ #  # ]:UNC           0 :     else if (IsA(plan, JsonTableSiblingJoin))
                              12336                 :                :     {
                              12337                 :              0 :         JsonTableSiblingJoin *j = (JsonTableSiblingJoin *) plan;
                              12338                 :                : 
                              12339                 :              0 :         get_json_table_plan(tf, j->lplan, context,
                              12340         [ #  # ]:              0 :                             IsA(j->lplan, JsonTableSiblingJoin) ||
                              12341         [ #  # ]:              0 :                             castNode(JsonTablePathScan, j->lplan)->child);
                              12342                 :                : 
                              12343         [ #  # ]:              0 :         appendStringInfoString(context->buf, j->cross ? " CROSS " : " UNION ");
                              12344                 :                : 
                              12345                 :              0 :         get_json_table_plan(tf, j->rplan, context,
                              12346         [ #  # ]:              0 :                             IsA(j->rplan, JsonTableSiblingJoin) ||
                              12347         [ #  # ]:              0 :                             castNode(JsonTablePathScan, j->rplan)->child);
                              12348                 :                :     }
                              12349                 :                : 
  142 akorotkov@postgresql    12350         [ +  + ]:GNC          12 :     if (parenthesize)
                              12351                 :              8 :         appendStringInfoChar(context->buf, ')');
                              12352                 :             12 : }
                              12353                 :                : 
                              12354                 :                : /*
                              12355                 :                :  * get_json_table_columns - Parse back JSON_TABLE columns
                              12356                 :                :  */
                              12357                 :                : static void
  964 amitlan@postgresql.o    12358                 :CBC         164 : get_json_table_columns(TableFunc *tf, JsonTablePathScan *scan,
                              12359                 :                :                        deparse_context *context,
                              12360                 :                :                        bool showimplicit)
                              12361                 :                : {
  968                         12362                 :            164 :     StringInfo  buf = context->buf;
                              12363                 :                :     ListCell   *lc_colname;
                              12364                 :                :     ListCell   *lc_coltype;
                              12365                 :                :     ListCell   *lc_coltypmod;
                              12366                 :                :     ListCell   *lc_colvalexpr;
                              12367                 :            164 :     int         colnum = 0;
                              12368                 :                : 
                              12369                 :            164 :     appendStringInfoChar(buf, ' ');
                              12370                 :            164 :     appendContextKeyword(context, "COLUMNS (", 0, 0, 0);
                              12371                 :                : 
                              12372         [ +  + ]:            164 :     if (PRETTY_INDENT(context))
                              12373                 :            112 :         context->indentLevel += PRETTYINDENT_VAR;
                              12374                 :                : 
                              12375   [ +  -  +  +  :           1316 :     forfour(lc_colname, tf->colnames,
                                     +  -  +  +  +  
                                     -  +  +  +  -  
                                     +  +  +  +  +  
                                     -  +  -  +  -  
                                              +  + ]
                              12376                 :                :             lc_coltype, tf->coltypes,
                              12377                 :                :             lc_coltypmod, tf->coltypmods,
                              12378                 :                :             lc_colvalexpr, tf->colvalexprs)
                              12379                 :                :     {
                              12380                 :           1200 :         char       *colname = strVal(lfirst(lc_colname));
                              12381                 :                :         JsonExpr   *colexpr;
                              12382                 :                :         Oid         typid;
                              12383                 :                :         int32       typmod;
                              12384                 :                :         bool        ordinality;
                              12385                 :                :         JsonBehaviorType default_behavior;
                              12386                 :                : 
                              12387                 :           1200 :         typid = lfirst_oid(lc_coltype);
                              12388                 :           1200 :         typmod = lfirst_int(lc_coltypmod);
                              12389                 :           1200 :         colexpr = castNode(JsonExpr, lfirst(lc_colvalexpr));
                              12390                 :                : 
                              12391                 :                :         /* Skip columns that don't belong to this scan. */
  964                         12392   [ +  +  +  + ]:           1200 :         if (scan->colMin < 0 || colnum < scan->colMin)
                              12393                 :                :         {
                              12394                 :            740 :             colnum++;
                              12395                 :            740 :             continue;
                              12396                 :                :         }
                              12397         [ +  + ]:            460 :         if (colnum > scan->colMax)
                              12398                 :             48 :             break;
                              12399                 :                : 
                              12400         [ +  + ]:            412 :         if (colnum > scan->colMin)
  968                         12401                 :            276 :             appendStringInfoString(buf, ", ");
                              12402                 :                : 
                              12403                 :            412 :         colnum++;
                              12404                 :                : 
                              12405                 :            412 :         ordinality = !colexpr;
                              12406                 :                : 
                              12407                 :            412 :         appendContextKeyword(context, "", 0, 0, 0);
                              12408                 :                : 
                              12409         [ +  + ]:            808 :         appendStringInfo(buf, "%s %s", quote_identifier(colname),
                              12410                 :                :                          ordinality ? "FOR ORDINALITY" :
                              12411                 :            396 :                          format_type_with_typemod(typid, typmod));
                              12412         [ +  + ]:            412 :         if (ordinality)
                              12413                 :             16 :             continue;
                              12414                 :                : 
                              12415                 :                :         /*
                              12416                 :                :          * Set default_behavior to guide get_json_expr_options() on whether to
                              12417                 :                :          * emit the ON ERROR / EMPTY clauses.
                              12418                 :                :          */
                              12419         [ +  + ]:            396 :         if (colexpr->op == JSON_EXISTS_OP)
                              12420                 :                :         {
                              12421                 :             40 :             appendStringInfoString(buf, " EXISTS");
                              12422                 :             40 :             default_behavior = JSON_BEHAVIOR_FALSE;
                              12423                 :                :         }
                              12424                 :                :         else
                              12425                 :                :         {
                              12426         [ +  + ]:            356 :             if (colexpr->op == JSON_QUERY_OP)
                              12427                 :                :             {
                              12428                 :                :                 char        typcategory;
                              12429                 :                :                 bool        typispreferred;
                              12430                 :                : 
                              12431                 :            168 :                 get_type_category_preferred(typid, &typcategory, &typispreferred);
                              12432                 :                : 
                              12433         [ +  + ]:            168 :                 if (typcategory == TYPCATEGORY_STRING)
                              12434                 :             36 :                     appendStringInfoString(buf,
                              12435         [ -  + ]:             36 :                                            colexpr->format->format_type == JS_FORMAT_JSONB ?
                              12436                 :                :                                            " FORMAT JSONB" : " FORMAT JSON");
                              12437                 :                :             }
                              12438                 :                : 
                              12439                 :            356 :             default_behavior = JSON_BEHAVIOR_NULL;
                              12440                 :                :         }
                              12441                 :                : 
                              12442                 :            396 :         appendStringInfoString(buf, " PATH ");
                              12443                 :                : 
                              12444                 :            396 :         get_json_path_spec(colexpr->path_spec, context, showimplicit);
                              12445                 :                : 
                              12446                 :            396 :         get_json_expr_options(colexpr, context, default_behavior);
                              12447                 :                :     }
                              12448                 :                : 
  964                         12449         [ +  + ]:            164 :     if (scan->child)
                              12450                 :             48 :         get_json_table_nested_columns(tf, scan->child, context, showimplicit,
                              12451                 :             48 :                                       scan->colMin >= 0);
                              12452                 :                : 
  968                         12453         [ +  + ]:            164 :     if (PRETTY_INDENT(context))
                              12454                 :            112 :         context->indentLevel -= PRETTYINDENT_VAR;
                              12455                 :                : 
                              12456                 :            164 :     appendContextKeyword(context, ")", 0, 0, 0);
                              12457                 :            164 : }
                              12458                 :                : 
                              12459                 :                : /* ----------
                              12460                 :                :  * get_json_table           - Parse back a JSON_TABLE function
                              12461                 :                :  * ----------
                              12462                 :                :  */
                              12463                 :                : static void
                              12464                 :             88 : get_json_table(TableFunc *tf, deparse_context *context, bool showimplicit)
                              12465                 :                : {
                              12466                 :             88 :     StringInfo  buf = context->buf;
                              12467                 :             88 :     JsonExpr   *jexpr = castNode(JsonExpr, tf->docexpr);
                              12468                 :             88 :     JsonTablePathScan *root = castNode(JsonTablePathScan, tf->plan);
                              12469                 :                : 
                              12470                 :             88 :     appendStringInfoString(buf, "JSON_TABLE(");
                              12471                 :                : 
                              12472         [ +  + ]:             88 :     if (PRETTY_INDENT(context))
                              12473                 :             56 :         context->indentLevel += PRETTYINDENT_VAR;
                              12474                 :                : 
                              12475                 :             88 :     appendContextKeyword(context, "", 0, 0, 0);
                              12476                 :                : 
                              12477                 :             88 :     get_rule_expr(jexpr->formatted_expr, context, showimplicit);
                              12478                 :                : 
                              12479                 :             88 :     appendStringInfoString(buf, ", ");
                              12480                 :                : 
                              12481                 :             88 :     get_const_expr(root->path->value, context, -1);
                              12482                 :                : 
                              12483                 :             88 :     appendStringInfo(buf, " AS %s", quote_identifier(root->path->name));
                              12484                 :                : 
                              12485         [ +  + ]:             88 :     if (jexpr->passing_values)
                              12486                 :                :     {
                              12487                 :                :         ListCell   *lc1,
                              12488                 :                :                    *lc2;
                              12489                 :             64 :         bool        needcomma = false;
                              12490                 :                : 
                              12491                 :             64 :         appendStringInfoChar(buf, ' ');
                              12492                 :             64 :         appendContextKeyword(context, "PASSING ", 0, 0, 0);
                              12493                 :                : 
                              12494         [ +  + ]:             64 :         if (PRETTY_INDENT(context))
                              12495                 :             32 :             context->indentLevel += PRETTYINDENT_VAR;
                              12496                 :                : 
                              12497   [ +  -  +  +  :            188 :         forboth(lc1, jexpr->passing_names,
                                     +  -  +  +  +  
                                        +  +  -  +  
                                                 + ]
                              12498                 :                :                 lc2, jexpr->passing_values)
                              12499                 :                :         {
                              12500         [ +  + ]:            124 :             if (needcomma)
                              12501                 :             60 :                 appendStringInfoString(buf, ", ");
                              12502                 :            124 :             needcomma = true;
                              12503                 :                : 
                              12504                 :            124 :             appendContextKeyword(context, "", 0, 0, 0);
                              12505                 :                : 
                              12506                 :            124 :             get_rule_expr((Node *) lfirst(lc2), context, false);
                              12507                 :            124 :             appendStringInfo(buf, " AS %s",
                              12508                 :            124 :                              quote_identifier((lfirst_node(String, lc1))->sval)
                              12509                 :                :                 );
                              12510                 :                :         }
                              12511                 :                : 
                              12512         [ +  + ]:             64 :         if (PRETTY_INDENT(context))
                              12513                 :             32 :             context->indentLevel -= PRETTYINDENT_VAR;
                              12514                 :                :     }
                              12515                 :                : 
  964                         12516                 :             88 :     get_json_table_columns(tf, castNode(JsonTablePathScan, tf->plan), context,
                              12517                 :                :                            showimplicit);
                              12518                 :                : 
                              12519                 :                :     /*
                              12520                 :                :      * Deparse a PLAN clause only for a non-default plan; the default plan is
                              12521                 :                :      * implied by the NESTED COLUMNS structure (see
                              12522                 :                :      * json_table_plan_is_default).
                              12523                 :                :      */
  142 akorotkov@postgresql    12524   [ +  +  +  + ]:GNC          88 :     if (root->child && !json_table_plan_is_default((JsonTablePlan *) root))
                              12525                 :                :     {
                              12526                 :              4 :         appendStringInfoChar(buf, ' ');
                              12527                 :              4 :         appendContextKeyword(context, "PLAN ", 0, 0, 0);
                              12528                 :              4 :         get_json_table_plan(tf, (JsonTablePlan *) root, context, true);
                              12529                 :                :     }
                              12530                 :                : 
  813 amitlan@postgresql.o    12531         [ +  + ]:CBC          88 :     if (jexpr->on_error->btype != JSON_BEHAVIOR_EMPTY_ARRAY)
  968                         12532                 :              8 :         get_json_behavior(jexpr->on_error, context, "ERROR");
                              12533                 :                : 
                              12534         [ +  + ]:             88 :     if (PRETTY_INDENT(context))
                              12535                 :             56 :         context->indentLevel -= PRETTYINDENT_VAR;
                              12536                 :                : 
                              12537                 :             88 :     appendContextKeyword(context, ")", 0, 0, 0);
                              12538                 :             88 : }
                              12539                 :                : 
                              12540                 :                : /* ----------
                              12541                 :                :  * get_tablefunc            - Parse back a table function
                              12542                 :                :  * ----------
                              12543                 :                :  */
                              12544                 :                : static void
                              12545                 :            126 : get_tablefunc(TableFunc *tf, deparse_context *context, bool showimplicit)
                              12546                 :                : {
                              12547                 :                :     /* XMLTABLE and JSON_TABLE are the only existing implementations.  */
                              12548                 :                : 
                              12549         [ +  + ]:            126 :     if (tf->functype == TFT_XMLTABLE)
                              12550                 :             38 :         get_xmltable(tf, context, showimplicit);
                              12551         [ +  - ]:             88 :     else if (tf->functype == TFT_JSON_TABLE)
                              12552                 :             88 :         get_json_table(tf, context, showimplicit);
                              12553                 :            126 : }
                              12554                 :                : 
                              12555                 :                : /* ----------
                              12556                 :                :  * get_from_clause          - Parse back a FROM clause
                              12557                 :                :  *
                              12558                 :                :  * "prefix" is the keyword that denotes the start of the list of FROM
                              12559                 :                :  * elements. It is FROM when used to parse back SELECT and UPDATE, but
                              12560                 :                :  * is USING when parsing back DELETE.
                              12561                 :                :  * ----------
                              12562                 :                :  */
                              12563                 :                : static void
 7905 neilc@samurai.com       12564                 :           3081 : get_from_clause(Query *query, const char *prefix, deparse_context *context)
                              12565                 :                : {
 9573 tgl@sss.pgh.pa.us       12566                 :           3081 :     StringInfo  buf = context->buf;
 8522                         12567                 :           3081 :     bool        first = true;
                              12568                 :                :     ListCell   *l;
                              12569                 :                : 
                              12570                 :                :     /*
                              12571                 :                :      * We use the query's jointree as a guide to what to print.  However, we
                              12572                 :                :      * must ignore auto-added RTEs that are marked not inFromCl. (These can
                              12573                 :                :      * only appear at the top level of the jointree, so it's sufficient to
                              12574                 :                :      * check here.)  This check also ensures we ignore the rule pseudo-RTEs
                              12575                 :                :      * for NEW and OLD.
                              12576                 :                :      */
 9556                         12577   [ +  +  +  +  :           6081 :     foreach(l, query->jointree->fromlist)
                                              +  + ]
                              12578                 :                :     {
 9382 bruce@momjian.us        12579                 :           3000 :         Node       *jtnode = (Node *) lfirst(l);
                              12580                 :                : 
 9573 tgl@sss.pgh.pa.us       12581         [ +  + ]:           3000 :         if (IsA(jtnode, RangeTblRef))
                              12582                 :                :         {
                              12583                 :           2395 :             int         varno = ((RangeTblRef *) jtnode)->rtindex;
                              12584                 :           2395 :             RangeTblEntry *rte = rt_fetch(varno, query->rtable);
                              12585                 :                : 
                              12586         [ +  + ]:           2395 :             if (!rte->inFromCl)
                              12587                 :            214 :                 continue;
                              12588                 :                :         }
                              12589                 :                : 
 8522                         12590         [ +  + ]:           2786 :         if (first)
                              12591                 :                :         {
 7905 neilc@samurai.com       12592                 :           2558 :             appendContextKeyword(context, prefix,
                              12593                 :                :                                  -PRETTYINDENT_STD, PRETTYINDENT_STD, 2);
 8522 tgl@sss.pgh.pa.us       12594                 :           2558 :             first = false;
                              12595                 :                : 
 5396 andrew@dunslane.net     12596                 :           2558 :             get_from_clause_item(jtnode, query, context);
                              12597                 :                :         }
                              12598                 :                :         else
                              12599                 :                :         {
                              12600                 :                :             StringInfoData itembuf;
                              12601                 :                : 
 8517 bruce@momjian.us        12602                 :            228 :             appendStringInfoString(buf, ", ");
                              12603                 :                : 
                              12604                 :                :             /*
                              12605                 :                :              * Put the new FROM item's text into itembuf so we can decide
                              12606                 :                :              * after we've got it whether or not it needs to go on a new line.
                              12607                 :                :              */
 5087 tgl@sss.pgh.pa.us       12608                 :            228 :             initStringInfo(&itembuf);
                              12609                 :            228 :             context->buf = &itembuf;
                              12610                 :                : 
 5396 andrew@dunslane.net     12611                 :            228 :             get_from_clause_item(jtnode, query, context);
                              12612                 :                : 
                              12613                 :                :             /* Restore context's output buffer */
                              12614                 :            228 :             context->buf = buf;
                              12615                 :                : 
                              12616                 :                :             /* Consider line-wrapping if enabled */
 5087 tgl@sss.pgh.pa.us       12617   [ +  -  +  - ]:            228 :             if (PRETTY_INDENT(context) && context->wrapColumn >= 0)
                              12618                 :                :             {
                              12619                 :                :                 /* Does the new item start with a new line? */
 4765                         12620   [ +  -  -  + ]:            228 :                 if (itembuf.len > 0 && itembuf.data[0] == '\n')
                              12621                 :                :                 {
                              12622                 :                :                     /* If so, we shouldn't add anything */
                              12623                 :                :                     /* instead, remove any trailing spaces currently in buf */
 4765 tgl@sss.pgh.pa.us       12624                 :UBC           0 :                     removeStringInfoSpaces(buf);
                              12625                 :                :                 }
                              12626                 :                :                 else
                              12627                 :                :                 {
                              12628                 :                :                     char       *trailing_nl;
                              12629                 :                : 
                              12630                 :                :                     /* Locate the start of the current line in the buffer */
 4765 tgl@sss.pgh.pa.us       12631                 :CBC         228 :                     trailing_nl = strrchr(buf->data, '\n');
                              12632         [ -  + ]:            228 :                     if (trailing_nl == NULL)
 4765 tgl@sss.pgh.pa.us       12633                 :UBC           0 :                         trailing_nl = buf->data;
                              12634                 :                :                     else
 4765 tgl@sss.pgh.pa.us       12635                 :CBC         228 :                         trailing_nl++;
                              12636                 :                : 
                              12637                 :                :                     /*
                              12638                 :                :                      * Add a newline, plus some indentation, if the new item
                              12639                 :                :                      * would cause an overflow.
                              12640                 :                :                      */
                              12641         [ +  - ]:            228 :                     if (strlen(trailing_nl) + itembuf.len > context->wrapColumn)
                              12642                 :            228 :                         appendContextKeyword(context, "", -PRETTYINDENT_STD,
                              12643                 :                :                                              PRETTYINDENT_STD,
                              12644                 :                :                                              PRETTYINDENT_VAR);
                              12645                 :                :                 }
                              12646                 :                :             }
                              12647                 :                : 
                              12648                 :                :             /* Add the new item */
 2685 drowley@postgresql.o    12649                 :            228 :             appendBinaryStringInfo(buf, itembuf.data, itembuf.len);
                              12650                 :                : 
                              12651                 :                :             /* clean up */
 5087 tgl@sss.pgh.pa.us       12652                 :            228 :             pfree(itembuf.data);
                              12653                 :                :         }
                              12654                 :                :     }
 9573                         12655                 :           3081 : }
                              12656                 :                : 
                              12657                 :                : static void
                              12658                 :           4666 : get_from_clause_item(Node *jtnode, Query *query, deparse_context *context)
                              12659                 :                : {
                              12660                 :           4666 :     StringInfo  buf = context->buf;
 5080                         12661                 :           4666 :     deparse_namespace *dpns = (deparse_namespace *) linitial(context->namespaces);
                              12662                 :                : 
 9573                         12663         [ +  + ]:           4666 :     if (IsA(jtnode, RangeTblRef))
                              12664                 :                :     {
                              12665                 :           3726 :         int         varno = ((RangeTblRef *) jtnode)->rtindex;
                              12666                 :           3726 :         RangeTblEntry *rte = rt_fetch(varno, query->rtable);
 5080                         12667                 :           3726 :         deparse_columns *colinfo = deparse_columns_fetch(varno, dpns);
 4755                         12668                 :           3726 :         RangeTblFunction *rtfunc1 = NULL;
                              12669                 :                : 
 5226                         12670         [ +  + ]:           3726 :         if (rte->lateral)
                              12671                 :             73 :             appendStringInfoString(buf, "LATERAL ");
                              12672                 :                : 
                              12673                 :                :         /* Print the FROM item proper */
 9017                         12674   [ +  +  +  +  :           3726 :         switch (rte->rtekind)
                                           +  +  - ]
                              12675                 :                :         {
                              12676                 :           2757 :             case RTE_RELATION:
                              12677                 :                :                 /* Normal relation RTE */
                              12678                 :           5514 :                 appendStringInfo(buf, "%s%s",
                              12679         [ +  + ]:           2757 :                                  only_marker(rte),
                              12680                 :                :                                  generate_relation_name(rte->relid,
                              12681                 :                :                                                         context->namespaces));
                              12682                 :           2757 :                 break;
                              12683                 :            204 :             case RTE_SUBQUERY:
                              12684                 :                :                 /* Subquery RTE */
                              12685                 :            204 :                 appendStringInfoChar(buf, '(');
 8517 bruce@momjian.us        12686                 :            204 :                 get_query_def(rte->subquery, buf, context->namespaces, NULL,
                              12687                 :                :                               true,
                              12688                 :                :                               context->prettyFlags, context->wrapColumn,
                              12689                 :                :                               context->indentLevel);
 9017 tgl@sss.pgh.pa.us       12690                 :            204 :                 appendStringInfoChar(buf, ')');
                              12691                 :            204 :                 break;
 8966                         12692                 :            564 :             case RTE_FUNCTION:
                              12693                 :                :                 /* Function RTE */
 4755                         12694                 :            564 :                 rtfunc1 = (RangeTblFunction *) linitial(rte->functions);
                              12695                 :                : 
                              12696                 :                :                 /*
                              12697                 :                :                  * Omit ROWS FROM() syntax for just one function, unless it
                              12698                 :                :                  * has both a coldeflist and WITH ORDINALITY. If it has both,
                              12699                 :                :                  * we must use ROWS FROM() syntax to avoid ambiguity about
                              12700                 :                :                  * whether the coldeflist includes the ordinality column.
                              12701                 :                :                  */
                              12702         [ +  + ]:            564 :                 if (list_length(rte->functions) == 1 &&
                              12703   [ -  +  -  - ]:            544 :                     (rtfunc1->funccolnames == NIL || !rte->funcordinality))
                              12704                 :                :                 {
 3425                         12705                 :            544 :                     get_rule_expr_funccall(rtfunc1->funcexpr, context, true);
                              12706                 :                :                     /* we'll print the coldeflist below, if it has one */
                              12707                 :                :                 }
                              12708                 :                :                 else
                              12709                 :                :                 {
                              12710                 :                :                     bool        all_unnest;
                              12711                 :                :                     ListCell   *lc;
                              12712                 :                : 
                              12713                 :                :                     /*
                              12714                 :                :                      * If all the function calls in the list are to unnest,
                              12715                 :                :                      * and none need a coldeflist, then collapse the list back
                              12716                 :                :                      * down to UNNEST(args).  (If we had more than one
                              12717                 :                :                      * built-in unnest function, this would get more
                              12718                 :                :                      * difficult.)
                              12719                 :                :                      *
                              12720                 :                :                      * XXX This is pretty ugly, since it makes not-terribly-
                              12721                 :                :                      * future-proof assumptions about what the parser would do
                              12722                 :                :                      * with the output; but the alternative is to emit our
                              12723                 :                :                      * nonstandard ROWS FROM() notation for what might have
                              12724                 :                :                      * been a perfectly spec-compliant multi-argument
                              12725                 :                :                      * UNNEST().
                              12726                 :                :                      */
 4755                         12727                 :             20 :                     all_unnest = true;
                              12728   [ +  -  +  +  :             52 :                     foreach(lc, rte->functions)
                                              +  + ]
                              12729                 :                :                     {
                              12730                 :             44 :                         RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
                              12731                 :                : 
                              12732         [ +  - ]:             44 :                         if (!IsA(rtfunc->funcexpr, FuncExpr) ||
 2217                         12733         [ +  + ]:             44 :                             ((FuncExpr *) rtfunc->funcexpr)->funcid != F_UNNEST_ANYARRAY ||
 4755                         12734         [ -  + ]:             32 :                             rtfunc->funccolnames != NIL)
                              12735                 :                :                         {
                              12736                 :             12 :                             all_unnest = false;
                              12737                 :             12 :                             break;
                              12738                 :                :                         }
                              12739                 :                :                     }
                              12740                 :                : 
                              12741         [ +  + ]:             20 :                     if (all_unnest)
                              12742                 :                :                     {
                              12743                 :              8 :                         List       *allargs = NIL;
                              12744                 :                : 
                              12745   [ +  -  +  +  :             32 :                         foreach(lc, rte->functions)
                                              +  + ]
                              12746                 :                :                         {
                              12747                 :             24 :                             RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
                              12748                 :             24 :                             List       *args = ((FuncExpr *) rtfunc->funcexpr)->args;
                              12749                 :                : 
 2665                         12750                 :             24 :                             allargs = list_concat(allargs, args);
                              12751                 :                :                         }
                              12752                 :                : 
 4755                         12753                 :              8 :                         appendStringInfoString(buf, "UNNEST(");
                              12754                 :              8 :                         get_rule_expr((Node *) allargs, context, true);
                              12755                 :              8 :                         appendStringInfoChar(buf, ')');
                              12756                 :                :                     }
                              12757                 :                :                     else
                              12758                 :                :                     {
                              12759                 :             12 :                         int         funcno = 0;
                              12760                 :                : 
 4736 noah@leadboat.com       12761                 :             12 :                         appendStringInfoString(buf, "ROWS FROM(");
 4755 tgl@sss.pgh.pa.us       12762   [ +  -  +  +  :             44 :                         foreach(lc, rte->functions)
                                              +  + ]
                              12763                 :                :                         {
                              12764                 :             32 :                             RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
                              12765                 :                : 
                              12766         [ +  + ]:             32 :                             if (funcno > 0)
                              12767                 :             20 :                                 appendStringInfoString(buf, ", ");
 3425                         12768                 :             32 :                             get_rule_expr_funccall(rtfunc->funcexpr, context, true);
 4755                         12769         [ +  + ]:             32 :                             if (rtfunc->funccolnames != NIL)
                              12770                 :                :                             {
                              12771                 :                :                                 /* Reconstruct the column definition list */
                              12772                 :              4 :                                 appendStringInfoString(buf, " AS ");
                              12773                 :              4 :                                 get_from_clause_coldeflist(rtfunc,
                              12774                 :                :                                                            NULL,
                              12775                 :                :                                                            context);
                              12776                 :                :                             }
                              12777                 :             32 :                             funcno++;
                              12778                 :                :                         }
                              12779                 :             12 :                         appendStringInfoChar(buf, ')');
                              12780                 :                :                     }
                              12781                 :                :                     /* prevent printing duplicate coldeflist below */
                              12782                 :             20 :                     rtfunc1 = NULL;
                              12783                 :                :                 }
 4870 stark@mit.edu           12784         [ +  + ]:            564 :                 if (rte->funcordinality)
                              12785                 :             12 :                     appendStringInfoString(buf, " WITH ORDINALITY");
 8966 tgl@sss.pgh.pa.us       12786                 :            564 :                 break;
 3552 alvherre@alvh.no-ip.    12787                 :             74 :             case RTE_TABLEFUNC:
                              12788                 :             74 :                 get_tablefunc(rte->tablefunc, context, true);
                              12789                 :             74 :                 break;
 7423 mail@joeconway.com      12790                 :              8 :             case RTE_VALUES:
                              12791                 :                :                 /* Values list RTE */
 4294 tgl@sss.pgh.pa.us       12792                 :              8 :                 appendStringInfoChar(buf, '(');
 7423 mail@joeconway.com      12793                 :              8 :                 get_values_def(rte->values_lists, context);
 4294 tgl@sss.pgh.pa.us       12794                 :              8 :                 appendStringInfoChar(buf, ')');
 7423 mail@joeconway.com      12795                 :              8 :                 break;
 6629 tgl@sss.pgh.pa.us       12796                 :            119 :             case RTE_CTE:
                              12797                 :            119 :                 appendStringInfoString(buf, quote_identifier(rte->ctename));
                              12798                 :            119 :                 break;
 9017 tgl@sss.pgh.pa.us       12799                 :UBC           0 :             default:
 8525                         12800         [ #  # ]:              0 :                 elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
                              12801                 :                :                 break;
                              12802                 :                :         }
                              12803                 :                : 
                              12804                 :                :         /* Print the relation alias, if needed */
 1380 tgl@sss.pgh.pa.us       12805                 :CBC        3726 :         get_rte_alias(rte, varno, false, context);
                              12806                 :                : 
                              12807                 :                :         /* Print the column definitions or aliases, if needed */
 4755                         12808   [ +  +  -  + ]:           3726 :         if (rtfunc1 && rtfunc1->funccolnames != NIL)
                              12809                 :                :         {
                              12810                 :                :             /* Reconstruct the columndef list, which is also the aliases */
 4755 tgl@sss.pgh.pa.us       12811                 :UBC           0 :             get_from_clause_coldeflist(rtfunc1, colinfo, context);
                              12812                 :                :         }
                              12813                 :                :         else
                              12814                 :                :         {
                              12815                 :                :             /* Else print column aliases as needed */
 5080 tgl@sss.pgh.pa.us       12816                 :CBC        3726 :             get_column_alias_list(colinfo, context);
                              12817                 :                :         }
                              12818                 :                : 
                              12819                 :                :         /* Tablesample clause must go after any alias */
 4144                         12820   [ +  +  +  + ]:           3726 :         if (rte->rtekind == RTE_RELATION && rte->tablesample)
                              12821                 :             18 :             get_tablesample_def(rte->tablesample, context);
                              12822                 :                :     }
 9573                         12823         [ +  - ]:            940 :     else if (IsA(jtnode, JoinExpr))
                              12824                 :                :     {
                              12825                 :            940 :         JoinExpr   *j = (JoinExpr *) jtnode;
 5080                         12826                 :            940 :         deparse_columns *colinfo = deparse_columns_fetch(j->rtindex, dpns);
                              12827                 :                :         bool        need_paren_on_right;
                              12828                 :                : 
 8522                         12829                 :           2172 :         need_paren_on_right = PRETTY_PAREN(context) &&
 7825                         12830   [ +  +  -  + ]:            940 :             !IsA(j->rarg, RangeTblRef) &&
 2387 tgl@sss.pgh.pa.us       12831   [ #  #  #  # ]:UBC           0 :             !(IsA(j->rarg, JoinExpr) && ((JoinExpr *) j->rarg)->alias != NULL);
                              12832                 :                : 
 8522 tgl@sss.pgh.pa.us       12833   [ +  +  +  + ]:CBC         940 :         if (!PRETTY_PAREN(context) || j->alias != NULL)
 8517 bruce@momjian.us        12834                 :            720 :             appendStringInfoChar(buf, '(');
                              12835                 :                : 
 9573 tgl@sss.pgh.pa.us       12836                 :            940 :         get_from_clause_item(j->larg, query, context);
                              12837                 :                : 
 5080                         12838   [ +  +  +  -  :            940 :         switch (j->jointype)
                                                 - ]
                              12839                 :                :         {
                              12840                 :            517 :             case JOIN_INNER:
                              12841         [ +  + ]:            517 :                 if (j->quals)
                              12842                 :            489 :                     appendContextKeyword(context, " JOIN ",
                              12843                 :                :                                          -PRETTYINDENT_STD,
                              12844                 :                :                                          PRETTYINDENT_STD,
                              12845                 :                :                                          PRETTYINDENT_JOIN);
                              12846                 :                :                 else
                              12847                 :             28 :                     appendContextKeyword(context, " CROSS JOIN ",
                              12848                 :                :                                          -PRETTYINDENT_STD,
                              12849                 :                :                                          PRETTYINDENT_STD,
                              12850                 :                :                                          PRETTYINDENT_JOIN);
                              12851                 :            517 :                 break;
                              12852                 :            355 :             case JOIN_LEFT:
                              12853                 :            355 :                 appendContextKeyword(context, " LEFT JOIN ",
                              12854                 :                :                                      -PRETTYINDENT_STD,
                              12855                 :                :                                      PRETTYINDENT_STD,
                              12856                 :                :                                      PRETTYINDENT_JOIN);
                              12857                 :            355 :                 break;
                              12858                 :             68 :             case JOIN_FULL:
                              12859                 :             68 :                 appendContextKeyword(context, " FULL JOIN ",
                              12860                 :                :                                      -PRETTYINDENT_STD,
                              12861                 :                :                                      PRETTYINDENT_STD,
                              12862                 :                :                                      PRETTYINDENT_JOIN);
                              12863                 :             68 :                 break;
 5080 tgl@sss.pgh.pa.us       12864                 :UBC           0 :             case JOIN_RIGHT:
                              12865                 :              0 :                 appendContextKeyword(context, " RIGHT JOIN ",
                              12866                 :                :                                      -PRETTYINDENT_STD,
                              12867                 :                :                                      PRETTYINDENT_STD,
                              12868                 :                :                                      PRETTYINDENT_JOIN);
                              12869                 :              0 :                 break;
                              12870                 :              0 :             default:
                              12871         [ #  # ]:              0 :                 elog(ERROR, "unrecognized join type: %d",
                              12872                 :                :                      (int) j->jointype);
                              12873                 :                :         }
                              12874                 :                : 
 8522 tgl@sss.pgh.pa.us       12875         [ -  + ]:CBC         940 :         if (need_paren_on_right)
 8517 bruce@momjian.us        12876                 :UBC           0 :             appendStringInfoChar(buf, '(');
 9573 tgl@sss.pgh.pa.us       12877                 :CBC         940 :         get_from_clause_item(j->rarg, query, context);
 8522                         12878         [ -  + ]:            940 :         if (need_paren_on_right)
 8517 bruce@momjian.us        12879                 :UBC           0 :             appendStringInfoChar(buf, ')');
                              12880                 :                : 
 5080 tgl@sss.pgh.pa.us       12881         [ +  + ]:CBC         940 :         if (j->usingClause)
                              12882                 :                :         {
                              12883                 :                :             ListCell   *lc;
                              12884                 :            280 :             bool        first = true;
                              12885                 :                : 
 4776 rhaas@postgresql.org    12886                 :            280 :             appendStringInfoString(buf, " USING (");
                              12887                 :                :             /* Use the assigned names, not what's in usingClause */
 5080 tgl@sss.pgh.pa.us       12888   [ +  -  +  +  :            664 :             foreach(lc, colinfo->usingNames)
                                              +  + ]
                              12889                 :                :             {
                              12890                 :            384 :                 char       *colname = (char *) lfirst(lc);
                              12891                 :                : 
                              12892         [ +  + ]:            384 :                 if (first)
                              12893                 :            280 :                     first = false;
                              12894                 :                :                 else
 4776 rhaas@postgresql.org    12895                 :            104 :                     appendStringInfoString(buf, ", ");
 5080 tgl@sss.pgh.pa.us       12896                 :            384 :                 appendStringInfoString(buf, quote_identifier(colname));
                              12897                 :                :             }
                              12898                 :            280 :             appendStringInfoChar(buf, ')');
                              12899                 :                : 
 2068 peter@eisentraut.org    12900         [ +  + ]:            280 :             if (j->join_using_alias)
                              12901                 :              8 :                 appendStringInfo(buf, " AS %s",
                              12902                 :              8 :                                  quote_identifier(j->join_using_alias->aliasname));
                              12903                 :                :         }
 5080 tgl@sss.pgh.pa.us       12904         [ +  + ]:            660 :         else if (j->quals)
                              12905                 :                :         {
 4776 rhaas@postgresql.org    12906                 :            628 :             appendStringInfoString(buf, " ON ");
 5080 tgl@sss.pgh.pa.us       12907         [ +  + ]:            628 :             if (!PRETTY_PAREN(context))
                              12908                 :            624 :                 appendStringInfoChar(buf, '(');
                              12909                 :            628 :             get_rule_expr(j->quals, context, false);
                              12910         [ +  + ]:            628 :             if (!PRETTY_PAREN(context))
                              12911                 :            624 :                 appendStringInfoChar(buf, ')');
                              12912                 :                :         }
 3418                         12913         [ +  + ]:             32 :         else if (j->jointype != JOIN_INNER)
                              12914                 :                :         {
                              12915                 :                :             /* If we didn't say CROSS JOIN above, we must provide an ON */
                              12916                 :              4 :             appendStringInfoString(buf, " ON TRUE");
                              12917                 :                :         }
                              12918                 :                : 
 8522                         12919   [ +  +  +  + ]:            940 :         if (!PRETTY_PAREN(context) || j->alias != NULL)
 8517 bruce@momjian.us        12920                 :            720 :             appendStringInfoChar(buf, ')');
                              12921                 :                : 
                              12922                 :                :         /* Yes, it's correct to put alias after the right paren ... */
 9573 tgl@sss.pgh.pa.us       12923         [ +  + ]:            940 :         if (j->alias != NULL)
                              12924                 :                :         {
                              12925                 :                :             /*
                              12926                 :                :              * Note that it's correct to emit an alias clause if and only if
                              12927                 :                :              * there was one originally.  Otherwise we'd be converting a named
                              12928                 :                :              * join to unnamed or vice versa, which creates semantic
                              12929                 :                :              * subtleties we don't want.  However, we might print a different
                              12930                 :                :              * alias name than was there originally.
                              12931                 :                :              */
                              12932                 :             72 :             appendStringInfo(buf, " %s",
 2726                         12933                 :             72 :                              quote_identifier(get_rtable_name(j->rtindex,
                              12934                 :                :                                                               context)));
 5080                         12935                 :             72 :             get_column_alias_list(colinfo, context);
                              12936                 :                :         }
                              12937                 :                :     }
                              12938                 :                :     else
 8525 tgl@sss.pgh.pa.us       12939         [ #  # ]:UBC           0 :         elog(ERROR, "unrecognized node type: %d",
                              12940                 :                :              (int) nodeTag(jtnode));
 9573 tgl@sss.pgh.pa.us       12941                 :CBC        4666 : }
                              12942                 :                : 
                              12943                 :                : /*
                              12944                 :                :  * get_rte_alias - print the relation's alias, if needed
                              12945                 :                :  *
                              12946                 :                :  * If printed, the alias is preceded by a space, or by " AS " if use_as is true.
                              12947                 :                :  */
                              12948                 :                : static void
 1380                         12949                 :           4061 : get_rte_alias(RangeTblEntry *rte, int varno, bool use_as,
                              12950                 :                :               deparse_context *context)
                              12951                 :                : {
                              12952                 :           4061 :     deparse_namespace *dpns = (deparse_namespace *) linitial(context->namespaces);
                              12953                 :           4061 :     char       *refname = get_rtable_name(varno, context);
                              12954                 :           4061 :     deparse_columns *colinfo = deparse_columns_fetch(varno, dpns);
                              12955                 :           4061 :     bool        printalias = false;
                              12956                 :                : 
                              12957         [ +  + ]:           4061 :     if (rte->alias != NULL)
                              12958                 :                :     {
                              12959                 :                :         /* Always print alias if user provided one */
                              12960                 :           1931 :         printalias = true;
                              12961                 :                :     }
                              12962         [ +  + ]:           2130 :     else if (colinfo->printaliases)
                              12963                 :                :     {
                              12964                 :                :         /* Always print alias if we need to print column aliases */
                              12965                 :            210 :         printalias = true;
                              12966                 :                :     }
                              12967         [ +  + ]:           1920 :     else if (rte->rtekind == RTE_RELATION)
                              12968                 :                :     {
                              12969                 :                :         /*
                              12970                 :                :          * No need to print alias if it's same as relation name (this would
                              12971                 :                :          * normally be the case, but not if set_rtable_names had to resolve a
                              12972                 :                :          * conflict).
                              12973                 :                :          */
                              12974         [ +  + ]:           1737 :         if (strcmp(refname, get_relation_name(rte->relid)) != 0)
                              12975                 :             52 :             printalias = true;
                              12976                 :                :     }
                              12977         [ -  + ]:            183 :     else if (rte->rtekind == RTE_FUNCTION)
                              12978                 :                :     {
                              12979                 :                :         /*
                              12980                 :                :          * For a function RTE, always print alias.  This covers possible
                              12981                 :                :          * renaming of the function and/or instability of the FigureColname
                              12982                 :                :          * rules for things that aren't simple functions.  Note we'd need to
                              12983                 :                :          * force it anyway for the columndef list case.
                              12984                 :                :          */
 1380 tgl@sss.pgh.pa.us       12985                 :UBC           0 :         printalias = true;
                              12986                 :                :     }
 1380 tgl@sss.pgh.pa.us       12987         [ +  + ]:CBC         183 :     else if (rte->rtekind == RTE_SUBQUERY ||
                              12988         [ +  + ]:            167 :              rte->rtekind == RTE_VALUES)
                              12989                 :                :     {
                              12990                 :                :         /*
                              12991                 :                :          * For a subquery, always print alias.  This makes the output
                              12992                 :                :          * SQL-spec-compliant, even though we allow such aliases to be omitted
                              12993                 :                :          * on input.
                              12994                 :                :          */
                              12995                 :             24 :         printalias = true;
                              12996                 :                :     }
                              12997         [ +  + ]:            159 :     else if (rte->rtekind == RTE_CTE)
                              12998                 :                :     {
                              12999                 :                :         /*
                              13000                 :                :          * No need to print alias if it's same as CTE name (this would
                              13001                 :                :          * normally be the case, but not if set_rtable_names had to resolve a
                              13002                 :                :          * conflict).
                              13003                 :                :          */
                              13004         [ +  + ]:             93 :         if (strcmp(refname, rte->ctename) != 0)
                              13005                 :             12 :             printalias = true;
                              13006                 :                :     }
                              13007                 :                : 
                              13008         [ +  + ]:           4061 :     if (printalias)
                              13009         [ +  + ]:           2229 :         appendStringInfo(context->buf, "%s%s",
                              13010                 :                :                          use_as ? " AS " : " ",
                              13011                 :                :                          quote_identifier(refname));
                              13012                 :           4061 : }
                              13013                 :                : 
                              13014                 :                : /*
                              13015                 :                :  * get_column_alias_list - print column alias list for an RTE
                              13016                 :                :  *
                              13017                 :                :  * Caller must already have printed the relation's alias name.
                              13018                 :                :  */
                              13019                 :                : static void
 5080                         13020                 :           3798 : get_column_alias_list(deparse_columns *colinfo, deparse_context *context)
                              13021                 :                : {
 8136                         13022                 :           3798 :     StringInfo  buf = context->buf;
                              13023                 :                :     int         i;
                              13024                 :           3798 :     bool        first = true;
                              13025                 :                : 
                              13026                 :                :     /* Don't print aliases if not needed */
 5080                         13027         [ +  + ]:           3798 :     if (!colinfo->printaliases)
                              13028                 :           2978 :         return;
                              13029                 :                : 
                              13030         [ +  + ]:           6405 :     for (i = 0; i < colinfo->num_new_cols; i++)
                              13031                 :                :     {
                              13032                 :           5585 :         char       *colname = colinfo->new_colnames[i];
                              13033                 :                : 
 8136                         13034         [ +  + ]:           5585 :         if (first)
                              13035                 :                :         {
                              13036                 :            820 :             appendStringInfoChar(buf, '(');
                              13037                 :            820 :             first = false;
                              13038                 :                :         }
                              13039                 :                :         else
 4776 rhaas@postgresql.org    13040                 :           4765 :             appendStringInfoString(buf, ", ");
 5080 tgl@sss.pgh.pa.us       13041                 :           5585 :         appendStringInfoString(buf, quote_identifier(colname));
                              13042                 :                :     }
 8136                         13043         [ +  - ]:            820 :     if (!first)
                              13044                 :            820 :         appendStringInfoChar(buf, ')');
                              13045                 :                : }
                              13046                 :                : 
                              13047                 :                : /*
                              13048                 :                :  * get_from_clause_coldeflist - reproduce FROM clause coldeflist
                              13049                 :                :  *
                              13050                 :                :  * When printing a top-level coldeflist (which is syntactically also the
                              13051                 :                :  * relation's column alias list), use column names from colinfo.  But when
                              13052                 :                :  * printing a coldeflist embedded inside ROWS FROM(), we prefer to use the
                              13053                 :                :  * original coldeflist's names, which are available in rtfunc->funccolnames.
                              13054                 :                :  * Pass NULL for colinfo to select the latter behavior.
                              13055                 :                :  *
                              13056                 :                :  * The coldeflist is appended immediately (no space) to buf.  Caller is
                              13057                 :                :  * responsible for ensuring that an alias or AS is present before it.
                              13058                 :                :  */
                              13059                 :                : static void
 4755                         13060                 :              4 : get_from_clause_coldeflist(RangeTblFunction *rtfunc,
                              13061                 :                :                            deparse_columns *colinfo,
                              13062                 :                :                            deparse_context *context)
                              13063                 :                : {
 8857                         13064                 :              4 :     StringInfo  buf = context->buf;
                              13065                 :                :     ListCell   *l1;
                              13066                 :                :     ListCell   *l2;
                              13067                 :                :     ListCell   *l3;
                              13068                 :                :     ListCell   *l4;
                              13069                 :                :     int         i;
                              13070                 :                : 
                              13071                 :              4 :     appendStringInfoChar(buf, '(');
                              13072                 :                : 
 5080                         13073                 :              4 :     i = 0;
 2830                         13074   [ +  -  +  +  :             16 :     forfour(l1, rtfunc->funccoltypes,
                                     +  -  +  +  +  
                                     -  +  +  +  -  
                                     +  +  +  +  +  
                                     -  +  -  +  -  
                                              +  + ]
                              13075                 :                :             l2, rtfunc->funccoltypmods,
                              13076                 :                :             l3, rtfunc->funccolcollations,
                              13077                 :                :             l4, rtfunc->funccolnames)
                              13078                 :                :     {
 5080                         13079                 :             12 :         Oid         atttypid = lfirst_oid(l1);
                              13080                 :             12 :         int32       atttypmod = lfirst_int(l2);
                              13081                 :             12 :         Oid         attcollation = lfirst_oid(l3);
                              13082                 :                :         char       *attname;
                              13083                 :                : 
 4755                         13084         [ -  + ]:             12 :         if (colinfo)
 4755 tgl@sss.pgh.pa.us       13085                 :UBC           0 :             attname = colinfo->colnames[i];
                              13086                 :                :         else
 4755 tgl@sss.pgh.pa.us       13087                 :CBC          12 :             attname = strVal(lfirst(l4));
                              13088                 :                : 
 5080                         13089         [ -  + ]:             12 :         Assert(attname);        /* shouldn't be any dropped columns here */
                              13090                 :                : 
 8857                         13091         [ +  + ]:             12 :         if (i > 0)
 4776 rhaas@postgresql.org    13092                 :              8 :             appendStringInfoString(buf, ", ");
 8857 tgl@sss.pgh.pa.us       13093                 :             12 :         appendStringInfo(buf, "%s %s",
                              13094                 :                :                          quote_identifier(attname),
                              13095                 :                :                          format_type_with_typemod(atttypid, atttypmod));
 5699                         13096   [ +  +  -  + ]:             16 :         if (OidIsValid(attcollation) &&
                              13097                 :              4 :             attcollation != get_typcollation(atttypid))
 5728 tgl@sss.pgh.pa.us       13098                 :UBC           0 :             appendStringInfo(buf, " COLLATE %s",
                              13099                 :                :                              generate_collation_name(attcollation));
                              13100                 :                : 
 8857 tgl@sss.pgh.pa.us       13101                 :CBC          12 :         i++;
                              13102                 :                :     }
                              13103                 :                : 
                              13104                 :              4 :     appendStringInfoChar(buf, ')');
                              13105                 :              4 : }
                              13106                 :                : 
                              13107                 :                : /*
                              13108                 :                :  * get_tablesample_def          - print a TableSampleClause
                              13109                 :                :  */
                              13110                 :                : static void
 4144                         13111                 :             18 : get_tablesample_def(TableSampleClause *tablesample, deparse_context *context)
                              13112                 :                : {
                              13113                 :             18 :     StringInfo  buf = context->buf;
                              13114                 :                :     Oid         argtypes[1];
                              13115                 :                :     int         nargs;
                              13116                 :                :     ListCell   *l;
                              13117                 :                : 
                              13118                 :                :     /*
                              13119                 :                :      * We should qualify the handler's function name if it wouldn't be
                              13120                 :                :      * resolved by lookup in the current search path.
                              13121                 :                :      */
                              13122                 :             18 :     argtypes[0] = INTERNALOID;
                              13123                 :             18 :     appendStringInfo(buf, " TABLESAMPLE %s (",
                              13124                 :                :                      generate_function_name(tablesample->tsmhandler, 1,
                              13125                 :                :                                             NIL, argtypes,
                              13126                 :                :                                             false, NULL, false));
                              13127                 :                : 
                              13128                 :             18 :     nargs = 0;
                              13129   [ +  -  +  +  :             36 :     foreach(l, tablesample->args)
                                              +  + ]
                              13130                 :                :     {
                              13131         [ -  + ]:             18 :         if (nargs++ > 0)
 4144 tgl@sss.pgh.pa.us       13132                 :UBC           0 :             appendStringInfoString(buf, ", ");
 4144 tgl@sss.pgh.pa.us       13133                 :CBC          18 :         get_rule_expr((Node *) lfirst(l), context, false);
                              13134                 :                :     }
                              13135                 :             18 :     appendStringInfoChar(buf, ')');
                              13136                 :                : 
                              13137         [ +  + ]:             18 :     if (tablesample->repeatable != NULL)
                              13138                 :                :     {
                              13139                 :              9 :         appendStringInfoString(buf, " REPEATABLE (");
                              13140                 :              9 :         get_rule_expr((Node *) tablesample->repeatable, context, false);
                              13141                 :              9 :         appendStringInfoChar(buf, ')');
                              13142                 :                :     }
                              13143                 :             18 : }
                              13144                 :                : 
                              13145                 :                : /*
                              13146                 :                :  * get_opclass_name         - fetch name of an index operator class
                              13147                 :                :  *
                              13148                 :                :  * The opclass name is appended (after a space) to buf.
                              13149                 :                :  *
                              13150                 :                :  * Output is suppressed if the opclass is the default for the given
                              13151                 :                :  * actual_datatype.  (If you don't want this behavior, just pass
                              13152                 :                :  * InvalidOid for actual_datatype.)
                              13153                 :                :  */
                              13154                 :                : static void
 9186                         13155                 :           7549 : get_opclass_name(Oid opclass, Oid actual_datatype,
                              13156                 :                :                  StringInfo buf)
                              13157                 :                : {
                              13158                 :                :     HeapTuple   ht_opc;
                              13159                 :                :     Form_pg_opclass opcrec;
                              13160                 :                :     char       *opcname;
                              13161                 :                :     char       *nspname;
                              13162                 :                : 
 6131 rhaas@postgresql.org    13163                 :           7549 :     ht_opc = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
 9189 tgl@sss.pgh.pa.us       13164         [ -  + ]:           7549 :     if (!HeapTupleIsValid(ht_opc))
 9189 tgl@sss.pgh.pa.us       13165         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for opclass %u", opclass);
 9189 tgl@sss.pgh.pa.us       13166                 :CBC        7549 :     opcrec = (Form_pg_opclass) GETSTRUCT(ht_opc);
                              13167                 :                : 
 7280                         13168   [ +  +  +  + ]:          15072 :     if (!OidIsValid(actual_datatype) ||
                              13169                 :           7523 :         GetDefaultOpClass(actual_datatype, opcrec->opcmethod) != opclass)
                              13170                 :                :     {
                              13171                 :                :         /* Okay, we need the opclass name.  Do we need to qualify it? */
 8975                         13172                 :            293 :         opcname = NameStr(opcrec->opcname);
 7280                         13173         [ +  - ]:            293 :         if (OpclassIsVisible(opclass))
 8975                         13174                 :            293 :             appendStringInfo(buf, " %s", quote_identifier(opcname));
                              13175                 :                :         else
                              13176                 :                :         {
 1950 tgl@sss.pgh.pa.us       13177                 :UBC           0 :             nspname = get_namespace_name_or_temp(opcrec->opcnamespace);
 8975                         13178                 :              0 :             appendStringInfo(buf, " %s.%s",
                              13179                 :                :                              quote_identifier(nspname),
                              13180                 :                :                              quote_identifier(opcname));
                              13181                 :                :         }
                              13182                 :                :     }
 9189 tgl@sss.pgh.pa.us       13183                 :CBC        7549 :     ReleaseSysCache(ht_opc);
                              13184                 :           7549 : }
                              13185                 :                : 
                              13186                 :                : /*
                              13187                 :                :  * generate_opclass_name
                              13188                 :                :  *      Compute the name to display for an opclass specified by OID
                              13189                 :                :  *
                              13190                 :                :  * The result includes all necessary quoting and schema-prefixing.
                              13191                 :                :  */
                              13192                 :                : char *
 2434 akorotkov@postgresql    13193                 :              4 : generate_opclass_name(Oid opclass)
                              13194                 :                : {
                              13195                 :                :     StringInfoData buf;
                              13196                 :                : 
                              13197                 :              4 :     initStringInfo(&buf);
                              13198                 :              4 :     get_opclass_name(opclass, InvalidOid, &buf);
                              13199                 :                : 
 2389 tgl@sss.pgh.pa.us       13200                 :              4 :     return &buf.data[1];        /* get_opclass_name() prepends space */
                              13201                 :                : }
                              13202                 :                : 
                              13203                 :                : /*
                              13204                 :                :  * processIndirection - take care of array and subfield assignment
                              13205                 :                :  *
                              13206                 :                :  * We strip any top-level FieldStore or assignment SubscriptingRef nodes that
                              13207                 :                :  * appear in the input, printing them as decoration for the base column
                              13208                 :                :  * name (which we assume the caller just printed).  We might also need to
                              13209                 :                :  * strip CoerceToDomain nodes, but only ones that appear above assignment
                              13210                 :                :  * nodes.
                              13211                 :                :  *
                              13212                 :                :  * Returns the subexpression that's to be assigned.
                              13213                 :                :  */
                              13214                 :                : static Node *
 3769                         13215                 :            745 : processIndirection(Node *node, deparse_context *context)
                              13216                 :                : {
 8207                         13217                 :            745 :     StringInfo  buf = context->buf;
 3426                         13218                 :            745 :     CoerceToDomain *cdomain = NULL;
                              13219                 :                : 
                              13220                 :                :     for (;;)
                              13221                 :                :     {
 8207                         13222         [ -  + ]:            949 :         if (node == NULL)
 8207 tgl@sss.pgh.pa.us       13223                 :UBC           0 :             break;
 8207 tgl@sss.pgh.pa.us       13224         [ +  + ]:CBC         949 :         if (IsA(node, FieldStore))
                              13225                 :                :         {
                              13226                 :             72 :             FieldStore *fstore = (FieldStore *) node;
                              13227                 :                :             Oid         typrelid;
                              13228                 :                :             char       *fieldname;
                              13229                 :                : 
                              13230                 :                :             /* lookup tuple type */
                              13231                 :             72 :             typrelid = get_typ_typrelid(fstore->resulttype);
                              13232         [ -  + ]:             72 :             if (!OidIsValid(typrelid))
 8207 tgl@sss.pgh.pa.us       13233         [ #  # ]:UBC           0 :                 elog(ERROR, "argument type %s of FieldStore is not a tuple type",
                              13234                 :                :                      format_type_be(fstore->resulttype));
                              13235                 :                : 
                              13236                 :                :             /*
                              13237                 :                :              * Print the field name.  There should only be one target field in
                              13238                 :                :              * stored rules.  There could be more than that in executable
                              13239                 :                :              * target lists, but this function cannot be used for that case.
                              13240                 :                :              */
 6127 tgl@sss.pgh.pa.us       13241         [ -  + ]:CBC          72 :             Assert(list_length(fstore->fieldnums) == 1);
 3211 alvherre@alvh.no-ip.    13242                 :             72 :             fieldname = get_attname(typrelid,
                              13243                 :             72 :                                     linitial_int(fstore->fieldnums), false);
 3769 tgl@sss.pgh.pa.us       13244                 :             72 :             appendStringInfo(buf, ".%s", quote_identifier(fieldname));
                              13245                 :                : 
                              13246                 :                :             /*
                              13247                 :                :              * We ignore arg since it should be an uninteresting reference to
                              13248                 :                :              * the target column or subcolumn.
                              13249                 :                :              */
 8207                         13250                 :             72 :             node = (Node *) linitial(fstore->newvals);
                              13251                 :                :         }
 2857 alvherre@alvh.no-ip.    13252         [ +  + ]:            877 :         else if (IsA(node, SubscriptingRef))
                              13253                 :                :         {
                              13254                 :             92 :             SubscriptingRef *sbsref = (SubscriptingRef *) node;
                              13255                 :                : 
                              13256         [ -  + ]:             92 :             if (sbsref->refassgnexpr == NULL)
 8207 tgl@sss.pgh.pa.us       13257                 :UBC           0 :                 break;
                              13258                 :                : 
 2857 alvherre@alvh.no-ip.    13259                 :CBC          92 :             printSubscripts(sbsref, context);
                              13260                 :                : 
                              13261                 :                :             /*
                              13262                 :                :              * We ignore refexpr since it should be an uninteresting reference
                              13263                 :                :              * to the target column or subcolumn.
                              13264                 :                :              */
                              13265                 :             92 :             node = (Node *) sbsref->refassgnexpr;
                              13266                 :                :         }
 3426 tgl@sss.pgh.pa.us       13267         [ +  + ]:            785 :         else if (IsA(node, CoerceToDomain))
                              13268                 :                :         {
                              13269                 :             40 :             cdomain = (CoerceToDomain *) node;
                              13270                 :                :             /* If it's an explicit domain coercion, we're done */
                              13271         [ -  + ]:             40 :             if (cdomain->coercionformat != COERCE_IMPLICIT_CAST)
 3426 tgl@sss.pgh.pa.us       13272                 :UBC           0 :                 break;
                              13273                 :                :             /* Tentatively descend past the CoerceToDomain */
 3426 tgl@sss.pgh.pa.us       13274                 :CBC          40 :             node = (Node *) cdomain->arg;
                              13275                 :                :         }
                              13276                 :                :         else
 8207                         13277                 :            745 :             break;
                              13278                 :                :     }
                              13279                 :                : 
                              13280                 :                :     /*
                              13281                 :                :      * If we descended past a CoerceToDomain whose argument turned out not to
                              13282                 :                :      * be a FieldStore or array assignment, back up to the CoerceToDomain.
                              13283                 :                :      * (This is not enough to be fully correct if there are nested implicit
                              13284                 :                :      * CoerceToDomains, but such cases shouldn't ever occur.)
                              13285                 :                :      */
 3426                         13286   [ +  +  -  + ]:            745 :     if (cdomain && node == (Node *) cdomain->arg)
 3426 tgl@sss.pgh.pa.us       13287                 :UBC           0 :         node = (Node *) cdomain;
                              13288                 :                : 
 8207 tgl@sss.pgh.pa.us       13289                 :CBC         745 :     return node;
                              13290                 :                : }
                              13291                 :                : 
                              13292                 :                : static void
 2857 alvherre@alvh.no-ip.    13293                 :            324 : printSubscripts(SubscriptingRef *sbsref, deparse_context *context)
                              13294                 :                : {
 8207 tgl@sss.pgh.pa.us       13295                 :            324 :     StringInfo  buf = context->buf;
                              13296                 :                :     ListCell   *lowlist_item;
                              13297                 :                :     ListCell   *uplist_item;
                              13298                 :                : 
 2857 alvherre@alvh.no-ip.    13299                 :            324 :     lowlist_item = list_head(sbsref->reflowerindexpr);   /* could be NULL */
                              13300   [ +  -  +  +  :            648 :     foreach(uplist_item, sbsref->refupperindexpr)
                                              +  + ]
                              13301                 :                :     {
 8207 tgl@sss.pgh.pa.us       13302                 :            324 :         appendStringInfoChar(buf, '[');
                              13303         [ -  + ]:            324 :         if (lowlist_item)
                              13304                 :                :         {
                              13305                 :                :             /* If subexpression is NULL, get_rule_expr prints nothing */
 8207 tgl@sss.pgh.pa.us       13306                 :UBC           0 :             get_rule_expr((Node *) lfirst(lowlist_item), context, false);
                              13307                 :              0 :             appendStringInfoChar(buf, ':');
 2693                         13308                 :              0 :             lowlist_item = lnext(sbsref->reflowerindexpr, lowlist_item);
                              13309                 :                :         }
                              13310                 :                :         /* If subexpression is NULL, get_rule_expr prints nothing */
 8207 tgl@sss.pgh.pa.us       13311                 :CBC         324 :         get_rule_expr((Node *) lfirst(uplist_item), context, false);
                              13312                 :            324 :         appendStringInfoChar(buf, ']');
                              13313                 :                :     }
 9604                         13314                 :            324 : }
                              13315                 :                : 
                              13316                 :                : /*
                              13317                 :                :  * quote_identifier         - Quote an identifier only if needed
                              13318                 :                :  *
                              13319                 :                :  * When quotes are needed, we palloc the required space; slightly
                              13320                 :                :  * space-wasteful but well worth it for notational simplicity.
                              13321                 :                :  */
                              13322                 :                : const char *
 8983                         13323                 :        1893038 : quote_identifier(const char *ident)
                              13324                 :                : {
                              13325                 :                :     /*
                              13326                 :                :      * Can avoid quoting if ident starts with a lowercase letter or underscore
                              13327                 :                :      * and contains only lowercase letters, digits, and underscores, *and* is
                              13328                 :                :      * not any SQL keyword.  Otherwise, supply quotes.
                              13329                 :                :      */
 8961                         13330                 :        1893038 :     int         nquotes = 0;
                              13331                 :                :     bool        safe;
                              13332                 :                :     const char *ptr;
                              13333                 :                :     char       *result;
                              13334                 :                :     char       *optr;
                              13335                 :                : 
                              13336                 :                :     /*
                              13337                 :                :      * would like to use <ctype.h> macros here, but they might yield unwanted
                              13338                 :                :      * locale-specific results...
                              13339                 :                :      */
 8980                         13340   [ +  +  -  +  :        1893038 :     safe = ((ident[0] >= 'a' && ident[0] <= 'z') || ident[0] == '_');
                                              +  + ]
                              13341                 :                : 
 8961                         13342         [ +  + ]:       16576335 :     for (ptr = ident; *ptr; ptr++)
                              13343                 :                :     {
                              13344                 :       14683297 :         char        ch = *ptr;
                              13345                 :                : 
                              13346   [ +  +  +  -  :       14683297 :         if ((ch >= 'a' && ch <= 'z') ||
                                              +  + ]
                              13347   [ +  +  +  + ]:        2259429 :             (ch >= '0' && ch <= '9') ||
                              13348                 :                :             (ch == '_'))
                              13349                 :                :         {
                              13350                 :                :             /* okay */
                              13351                 :                :         }
                              13352                 :                :         else
                              13353                 :                :         {
                              13354                 :         375338 :             safe = false;
                              13355         [ +  + ]:         375338 :             if (ch == '"')
                              13356                 :             89 :                 nquotes++;
                              13357                 :                :         }
                              13358                 :                :     }
                              13359                 :                : 
 5973 rhaas@postgresql.org    13360         [ +  + ]:        1893038 :     if (quote_all_identifiers)
                              13361                 :           6934 :         safe = false;
                              13362                 :                : 
 9854 tgl@sss.pgh.pa.us       13363         [ +  + ]:        1893038 :     if (safe)
                              13364                 :                :     {
                              13365                 :                :         /*
                              13366                 :                :          * Check for keyword.  We quote keywords except for unreserved ones.
                              13367                 :                :          * (In some cases we could avoid quoting a col_name or type_func_name
                              13368                 :                :          * keyword, but it seems much harder than it's worth to tell that.)
                              13369                 :                :          *
                              13370                 :                :          * Note: ScanKeywordLookup() does case-insensitive comparison, but
                              13371                 :                :          * that's fine, since we already know we have all-lower-case.
                              13372                 :                :          */
 2883                         13373                 :        1829574 :         int         kwnum = ScanKeywordLookup(ident, &ScanKeywords);
                              13374                 :                : 
                              13375   [ +  +  +  + ]:        1829574 :         if (kwnum >= 0 && ScanKeywordCategories[kwnum] != UNRESERVED_KEYWORD)
 9854                         13376                 :           2462 :             safe = false;
                              13377                 :                :     }
                              13378                 :                : 
 9917                         13379         [ +  + ]:        1893038 :     if (safe)
                              13380                 :        1827112 :         return ident;           /* no change needed */
                              13381                 :                : 
 8961                         13382                 :          65926 :     result = (char *) palloc(strlen(ident) + nquotes + 2 + 1);
                              13383                 :                : 
                              13384                 :          65926 :     optr = result;
                              13385                 :          65926 :     *optr++ = '"';
                              13386         [ +  + ]:         528286 :     for (ptr = ident; *ptr; ptr++)
                              13387                 :                :     {
                              13388                 :         462360 :         char        ch = *ptr;
                              13389                 :                : 
                              13390         [ +  + ]:         462360 :         if (ch == '"')
                              13391                 :             89 :             *optr++ = '"';
                              13392                 :         462360 :         *optr++ = ch;
                              13393                 :                :     }
                              13394                 :          65926 :     *optr++ = '"';
                              13395                 :          65926 :     *optr = '\0';
                              13396                 :                : 
 9917                         13397                 :          65926 :     return result;
                              13398                 :                : }
                              13399                 :                : 
                              13400                 :                : /*
                              13401                 :                :  * quote_qualified_identifier   - Quote a possibly-qualified identifier
                              13402                 :                :  *
                              13403                 :                :  * Return a name of the form qualifier.ident, or just ident if qualifier
                              13404                 :                :  * is NULL, quoting each component if necessary.  The result is palloc'd.
                              13405                 :                :  */
                              13406                 :                : char *
 6344 peter_e@gmx.net         13407                 :         729213 : quote_qualified_identifier(const char *qualifier,
                              13408                 :                :                            const char *ident)
                              13409                 :                : {
                              13410                 :                :     StringInfoData buf;
                              13411                 :                : 
 8983 tgl@sss.pgh.pa.us       13412                 :         729213 :     initStringInfo(&buf);
 6344 peter_e@gmx.net         13413         [ +  + ]:         729213 :     if (qualifier)
                              13414                 :         251078 :         appendStringInfo(&buf, "%s.", quote_identifier(qualifier));
 8337 neilc@samurai.com       13415                 :         729213 :     appendStringInfoString(&buf, quote_identifier(ident));
 8983 tgl@sss.pgh.pa.us       13416                 :         729213 :     return buf.data;
                              13417                 :                : }
                              13418                 :                : 
                              13419                 :                : /*
                              13420                 :                :  * get_relation_name
                              13421                 :                :  *      Get the unqualified name of a relation specified by OID
                              13422                 :                :  *
                              13423                 :                :  * This differs from the underlying get_rel_name() function in that it will
                              13424                 :                :  * throw error instead of silently returning NULL if the OID is bad.
                              13425                 :                :  */
                              13426                 :                : static char *
 5870                         13427                 :          10164 : get_relation_name(Oid relid)
                              13428                 :                : {
                              13429                 :          10164 :     char       *relname = get_rel_name(relid);
                              13430                 :                : 
                              13431         [ -  + ]:          10164 :     if (!relname)
 5870 tgl@sss.pgh.pa.us       13432         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for relation %u", relid);
 5870 tgl@sss.pgh.pa.us       13433                 :CBC       10164 :     return relname;
                              13434                 :                : }
                              13435                 :                : 
                              13436                 :                : /*
                              13437                 :                :  * generate_relation_name
                              13438                 :                :  *      Compute the name to display for a relation specified by OID
                              13439                 :                :  *
                              13440                 :                :  * The result includes all necessary quoting and schema-prefixing.
                              13441                 :                :  *
                              13442                 :                :  * If namespaces isn't NIL, it must be a list of deparse_namespace nodes.
                              13443                 :                :  * We will forcibly qualify the relation name if it equals any CTE name
                              13444                 :                :  * visible in the namespace list.
                              13445                 :                :  */
                              13446                 :                : static char *
 6627                         13447                 :           5021 : generate_relation_name(Oid relid, List *namespaces)
                              13448                 :                : {
                              13449                 :                :     HeapTuple   tp;
                              13450                 :                :     Form_pg_class reltup;
                              13451                 :                :     bool        need_qual;
                              13452                 :                :     ListCell   *nslist;
                              13453                 :                :     char       *relname;
                              13454                 :                :     char       *nspname;
                              13455                 :                :     char       *result;
                              13456                 :                : 
 6131 rhaas@postgresql.org    13457                 :           5021 :     tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
 8975 tgl@sss.pgh.pa.us       13458         [ -  + ]:           5021 :     if (!HeapTupleIsValid(tp))
 8525 tgl@sss.pgh.pa.us       13459         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for relation %u", relid);
 8975 tgl@sss.pgh.pa.us       13460                 :CBC        5021 :     reltup = (Form_pg_class) GETSTRUCT(tp);
 6627                         13461                 :           5021 :     relname = NameStr(reltup->relname);
                              13462                 :                : 
                              13463                 :                :     /* Check for conflicting CTE name */
                              13464                 :           5021 :     need_qual = false;
                              13465   [ +  +  +  +  :           8546 :     foreach(nslist, namespaces)
                                              +  + ]
                              13466                 :                :     {
                              13467                 :           3525 :         deparse_namespace *dpns = (deparse_namespace *) lfirst(nslist);
                              13468                 :                :         ListCell   *ctlist;
                              13469                 :                : 
                              13470   [ +  +  +  +  :           3617 :         foreach(ctlist, dpns->ctes)
                                              +  + ]
                              13471                 :                :         {
                              13472                 :             92 :             CommonTableExpr *cte = (CommonTableExpr *) lfirst(ctlist);
                              13473                 :                : 
                              13474         [ -  + ]:             92 :             if (strcmp(cte->ctename, relname) == 0)
                              13475                 :                :             {
 6627 tgl@sss.pgh.pa.us       13476                 :UBC           0 :                 need_qual = true;
                              13477                 :              0 :                 break;
                              13478                 :                :             }
                              13479                 :                :         }
 6627 tgl@sss.pgh.pa.us       13480         [ -  + ]:CBC        3525 :         if (need_qual)
 6627 tgl@sss.pgh.pa.us       13481                 :UBC           0 :             break;
                              13482                 :                :     }
                              13483                 :                : 
                              13484                 :                :     /* Otherwise, qualify the name if not visible in search path */
 6627 tgl@sss.pgh.pa.us       13485         [ +  - ]:CBC        5021 :     if (!need_qual)
                              13486                 :           5021 :         need_qual = !RelationIsVisible(relid);
                              13487                 :                : 
                              13488         [ +  + ]:           5021 :     if (need_qual)
 1950                         13489                 :           1298 :         nspname = get_namespace_name_or_temp(reltup->relnamespace);
                              13490                 :                :     else
 6627                         13491                 :           3723 :         nspname = NULL;
                              13492                 :                : 
                              13493                 :           5021 :     result = quote_qualified_identifier(nspname, relname);
                              13494                 :                : 
 8975                         13495                 :           5021 :     ReleaseSysCache(tp);
                              13496                 :                : 
                              13497                 :           5021 :     return result;
                              13498                 :                : }
                              13499                 :                : 
                              13500                 :                : /*
                              13501                 :                :  * generate_qualified_relation_name
                              13502                 :                :  *      Compute the name to display for a relation specified by OID
                              13503                 :                :  *
                              13504                 :                :  * As above, but unconditionally schema-qualify the name.
                              13505                 :                :  */
                              13506                 :                : static char *
 4026                         13507                 :           4618 : generate_qualified_relation_name(Oid relid)
                              13508                 :                : {
                              13509                 :                :     HeapTuple   tp;
                              13510                 :                :     Form_pg_class reltup;
                              13511                 :                :     char       *result;
                              13512                 :                : 
                              13513                 :           4618 :     tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
                              13514         [ -  + ]:           4618 :     if (!HeapTupleIsValid(tp))
 4026 tgl@sss.pgh.pa.us       13515         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for relation %u", relid);
 4026 tgl@sss.pgh.pa.us       13516                 :CBC        4618 :     reltup = (Form_pg_class) GETSTRUCT(tp);
                              13517                 :                : 
  204 akapila@postgresql.o    13518                 :           4618 :     result = get_qualified_objname(reltup->relnamespace,
                              13519                 :           4618 :                                    NameStr(reltup->relname));
 4026 tgl@sss.pgh.pa.us       13520                 :           4618 :     ReleaseSysCache(tp);
                              13521                 :                : 
                              13522                 :           4618 :     return result;
                              13523                 :                : }
                              13524                 :                : 
                              13525                 :                : /*
                              13526                 :                :  * generate_function_name
                              13527                 :                :  *      Compute the name to display for a function specified by OID,
                              13528                 :                :  *      given that it is being called with the specified actual arg names and
                              13529                 :                :  *      types.  (Those matter because of ambiguous-function resolution rules.)
                              13530                 :                :  *
                              13531                 :                :  * If we're dealing with a potentially variadic function (in practice, this
                              13532                 :                :  * means a FuncExpr or Aggref, not some other way of calling a function), then
                              13533                 :                :  * has_variadic must specify whether variadic arguments have been merged,
                              13534                 :                :  * and *use_variadic_p will be set to indicate whether to print VARIADIC in
                              13535                 :                :  * the output.  For non-FuncExpr cases, has_variadic should be false and
                              13536                 :                :  * use_variadic_p can be NULL.
                              13537                 :                :  *
                              13538                 :                :  * inGroupBy must be true if we're deparsing a GROUP BY clause.
                              13539                 :                :  *
                              13540                 :                :  * The result includes all necessary quoting and schema-prefixing.
                              13541                 :                :  */
                              13542                 :                : static char *
 5059                         13543                 :           9916 : generate_function_name(Oid funcid, int nargs, List *argnames, Oid *argtypes,
                              13544                 :                :                        bool has_variadic, bool *use_variadic_p,
                              13545                 :                :                        bool inGroupBy)
                              13546                 :                : {
                              13547                 :                :     char       *result;
                              13548                 :                :     HeapTuple   proctup;
                              13549                 :                :     Form_pg_proc procform;
                              13550                 :                :     char       *proname;
                              13551                 :                :     bool        use_variadic;
                              13552                 :                :     char       *nspname;
                              13553                 :                :     FuncDetailCode p_result;
                              13554                 :                :     int         fgc_flags;
                              13555                 :                :     Oid         p_funcid;
                              13556                 :                :     Oid         p_rettype;
                              13557                 :                :     bool        p_retset;
                              13558                 :                :     int         p_nvargs;
                              13559                 :                :     Oid         p_vatype;
                              13560                 :                :     Oid        *p_true_typeids;
 4214 andres@anarazel.de      13561                 :           9916 :     bool        force_qualify = false;
                              13562                 :                : 
 6131 rhaas@postgresql.org    13563                 :           9916 :     proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
 8975 tgl@sss.pgh.pa.us       13564         [ -  + ]:           9916 :     if (!HeapTupleIsValid(proctup))
 8525 tgl@sss.pgh.pa.us       13565         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for function %u", funcid);
 8975 tgl@sss.pgh.pa.us       13566                 :CBC        9916 :     procform = (Form_pg_proc) GETSTRUCT(proctup);
                              13567                 :           9916 :     proname = NameStr(procform->proname);
                              13568                 :                : 
                              13569                 :                :     /*
                              13570                 :                :      * Due to parser hacks to avoid needing to reserve CUBE, we need to force
                              13571                 :                :      * qualification of some function names within GROUP BY.
                              13572                 :                :      */
  821                         13573         [ -  + ]:           9916 :     if (inGroupBy)
                              13574                 :                :     {
 4214 andres@anarazel.de      13575   [ #  #  #  # ]:UBC           0 :         if (strcmp(proname, "cube") == 0 || strcmp(proname, "rollup") == 0)
                              13576                 :              0 :             force_qualify = true;
                              13577                 :                :     }
                              13578                 :                : 
                              13579                 :                :     /*
                              13580                 :                :      * Determine whether VARIADIC should be printed.  We must do this first
                              13581                 :                :      * since it affects the lookup rules in func_get_detail().
                              13582                 :                :      *
                              13583                 :                :      * We always print VARIADIC if the function has a merged variadic-array
                              13584                 :                :      * argument.  Note that this is always the case for functions taking a
                              13585                 :                :      * VARIADIC argument type other than VARIADIC ANY.  If we omitted VARIADIC
                              13586                 :                :      * and printed the array elements as separate arguments, the call could
                              13587                 :                :      * match a newer non-VARIADIC function.
                              13588                 :                :      */
 5059 tgl@sss.pgh.pa.us       13589         [ +  + ]:CBC        9916 :     if (use_variadic_p)
                              13590                 :                :     {
                              13591                 :                :         /* Parser should not have set funcvariadic unless fn is variadic */
 4622                         13592   [ +  +  -  + ]:           8921 :         Assert(!has_variadic || OidIsValid(procform->provariadic));
                              13593                 :           8921 :         use_variadic = has_variadic;
 5059                         13594                 :           8921 :         *use_variadic_p = use_variadic;
                              13595                 :                :     }
                              13596                 :                :     else
                              13597                 :                :     {
 4622                         13598         [ -  + ]:            995 :         Assert(!has_variadic);
 5059                         13599                 :            995 :         use_variadic = false;
                              13600                 :                :     }
                              13601                 :                : 
                              13602                 :                :     /*
                              13603                 :                :      * The idea here is to schema-qualify only if the parser would fail to
                              13604                 :                :      * resolve the correct function given the unqualified func name with the
                              13605                 :                :      * specified argtypes and VARIADIC flag.  But if we already decided to
                              13606                 :                :      * force qualification, then we can skip the lookup and pretend we didn't
                              13607                 :                :      * find it.
                              13608                 :                :      */
 4214 andres@anarazel.de      13609         [ +  - ]:           9916 :     if (!force_qualify)
                              13610                 :           9916 :         p_result = func_get_detail(list_make1(makeString(proname)),
                              13611                 :                :                                    NIL, argnames, nargs, argtypes,
                              13612                 :                :                                    !use_variadic, true, false,
                              13613                 :                :                                    &fgc_flags,
                              13614                 :                :                                    &p_funcid, &p_rettype,
                              13615                 :                :                                    &p_retset, &p_nvargs, &p_vatype,
                              13616                 :           9916 :                                    &p_true_typeids, NULL);
                              13617                 :                :     else
                              13618                 :                :     {
 4214 andres@anarazel.de      13619                 :UBC           0 :         p_result = FUNCDETAIL_NOTFOUND;
                              13620                 :              0 :         p_funcid = InvalidOid;
                              13621                 :                :     }
                              13622                 :                : 
 6544 tgl@sss.pgh.pa.us       13623   [ +  +  +  + ]:CBC        9916 :     if ((p_result == FUNCDETAIL_NORMAL ||
                              13624         [ +  + ]:            683 :          p_result == FUNCDETAIL_AGGREGATE ||
                              13625                 :           9329 :          p_result == FUNCDETAIL_WINDOWFUNC) &&
 8548                         13626         [ +  - ]:           9329 :         p_funcid == funcid)
 8975                         13627                 :           9329 :         nspname = NULL;
                              13628                 :                :     else
 1950                         13629                 :            587 :         nspname = get_namespace_name_or_temp(procform->pronamespace);
                              13630                 :                : 
 8975                         13631                 :           9916 :     result = quote_qualified_identifier(nspname, proname);
                              13632                 :                : 
                              13633                 :           9916 :     ReleaseSysCache(proctup);
                              13634                 :                : 
                              13635                 :           9916 :     return result;
                              13636                 :                : }
                              13637                 :                : 
                              13638                 :                : /*
                              13639                 :                :  * generate_operator_name
                              13640                 :                :  *      Compute the name to display for an operator specified by OID,
                              13641                 :                :  *      given that it is being called with the specified actual arg types.
                              13642                 :                :  *      (Arg types matter because of ambiguous-operator resolution rules.
                              13643                 :                :  *      Pass InvalidOid for unused arg of a unary operator.)
                              13644                 :                :  *
                              13645                 :                :  * The result includes all necessary quoting and schema-prefixing,
                              13646                 :                :  * plus the OPERATOR() decoration needed to use a qualified operator name
                              13647                 :                :  * in an expression.
                              13648                 :                :  */
                              13649                 :                : static char *
                              13650                 :          45416 : generate_operator_name(Oid operid, Oid arg1, Oid arg2)
                              13651                 :                : {
                              13652                 :                :     StringInfoData buf;
                              13653                 :                :     HeapTuple   opertup;
                              13654                 :                :     Form_pg_operator operform;
                              13655                 :                :     char       *oprname;
                              13656                 :                :     char       *nspname;
                              13657                 :                :     Operator    p_result;
                              13658                 :                : 
                              13659                 :          45416 :     initStringInfo(&buf);
                              13660                 :                : 
 6131 rhaas@postgresql.org    13661                 :          45416 :     opertup = SearchSysCache1(OPEROID, ObjectIdGetDatum(operid));
 8975 tgl@sss.pgh.pa.us       13662         [ -  + ]:          45416 :     if (!HeapTupleIsValid(opertup))
 8525 tgl@sss.pgh.pa.us       13663         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for operator %u", operid);
 8975 tgl@sss.pgh.pa.us       13664                 :CBC       45416 :     operform = (Form_pg_operator) GETSTRUCT(opertup);
                              13665                 :          45416 :     oprname = NameStr(operform->oprname);
                              13666                 :                : 
                              13667                 :                :     /*
                              13668                 :                :      * The idea here is to schema-qualify only if the parser would fail to
                              13669                 :                :      * resolve the correct operator given the unqualified op name with the
                              13670                 :                :      * specified argtypes.
                              13671                 :                :      */
                              13672      [ +  +  - ]:          45416 :     switch (operform->oprkind)
                              13673                 :                :     {
                              13674                 :          45380 :         case 'b':
 7564                         13675                 :          45380 :             p_result = oper(NULL, list_make1(makeString(oprname)), arg1, arg2,
                              13676                 :                :                             true, -1);
 8975                         13677                 :          45380 :             break;
                              13678                 :             36 :         case 'l':
 7564                         13679                 :             36 :             p_result = left_oper(NULL, list_make1(makeString(oprname)), arg2,
                              13680                 :                :                                  true, -1);
 8975                         13681                 :             36 :             break;
 8975 tgl@sss.pgh.pa.us       13682                 :UBC           0 :         default:
 8525                         13683         [ #  # ]:              0 :             elog(ERROR, "unrecognized oprkind: %d", operform->oprkind);
                              13684                 :                :             p_result = NULL;    /* keep compiler quiet */
                              13685                 :                :             break;
                              13686                 :                :     }
                              13687                 :                : 
 8975 tgl@sss.pgh.pa.us       13688   [ +  +  +  - ]:CBC       45416 :     if (p_result != NULL && oprid(p_result) == operid)
                              13689                 :          45411 :         nspname = NULL;
                              13690                 :                :     else
                              13691                 :                :     {
 1950                         13692                 :              5 :         nspname = get_namespace_name_or_temp(operform->oprnamespace);
 8975                         13693                 :              5 :         appendStringInfo(&buf, "OPERATOR(%s.", quote_identifier(nspname));
                              13694                 :                :     }
                              13695                 :                : 
 8337 neilc@samurai.com       13696                 :          45416 :     appendStringInfoString(&buf, oprname);
                              13697                 :                : 
 8975 tgl@sss.pgh.pa.us       13698         [ +  + ]:          45416 :     if (nspname)
                              13699                 :              5 :         appendStringInfoChar(&buf, ')');
                              13700                 :                : 
                              13701         [ +  + ]:          45416 :     if (p_result != NULL)
                              13702                 :          45411 :         ReleaseSysCache(p_result);
                              13703                 :                : 
                              13704                 :          45416 :     ReleaseSysCache(opertup);
                              13705                 :                : 
                              13706                 :          45416 :     return buf.data;
                              13707                 :                : }
                              13708                 :                : 
                              13709                 :                : /*
                              13710                 :                :  * generate_operator_clause --- generate a binary-operator WHERE clause
                              13711                 :                :  *
                              13712                 :                :  * This is used for internally-generated-and-executed SQL queries, where
                              13713                 :                :  * precision is essential and readability is secondary.  The basic
                              13714                 :                :  * requirement is to append "leftop op rightop" to buf, where leftop and
                              13715                 :                :  * rightop are given as strings and are assumed to yield types leftoptype
                              13716                 :                :  * and rightoptype; the operator is identified by OID.  The complexity
                              13717                 :                :  * comes from needing to be sure that the parser will select the desired
                              13718                 :                :  * operator when the query is parsed.  We always name the operator using
                              13719                 :                :  * OPERATOR(schema.op) syntax, so as to avoid search-path uncertainties.
                              13720                 :                :  * We have to emit casts too, if either input isn't already the input type
                              13721                 :                :  * of the operator; else we are at the mercy of the parser's heuristics for
                              13722                 :                :  * ambiguous-operator resolution.  The caller must ensure that leftop and
                              13723                 :                :  * rightop are suitable arguments for a cast operation; it's best to insert
                              13724                 :                :  * parentheses if they aren't just variables or parameters.
                              13725                 :                :  */
                              13726                 :                : void
 3176                         13727                 :           3332 : generate_operator_clause(StringInfo buf,
                              13728                 :                :                          const char *leftop, Oid leftoptype,
                              13729                 :                :                          Oid opoid,
                              13730                 :                :                          const char *rightop, Oid rightoptype)
                              13731                 :                : {
                              13732                 :                :     HeapTuple   opertup;
                              13733                 :                :     Form_pg_operator operform;
                              13734                 :                :     char       *oprname;
                              13735                 :                :     char       *nspname;
                              13736                 :                : 
                              13737                 :           3332 :     opertup = SearchSysCache1(OPEROID, ObjectIdGetDatum(opoid));
                              13738         [ -  + ]:           3332 :     if (!HeapTupleIsValid(opertup))
 3176 tgl@sss.pgh.pa.us       13739         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for operator %u", opoid);
 3176 tgl@sss.pgh.pa.us       13740                 :CBC        3332 :     operform = (Form_pg_operator) GETSTRUCT(opertup);
                              13741         [ -  + ]:           3332 :     Assert(operform->oprkind == 'b');
                              13742                 :           3332 :     oprname = NameStr(operform->oprname);
                              13743                 :                : 
                              13744                 :           3332 :     nspname = get_namespace_name(operform->oprnamespace);
                              13745                 :                : 
                              13746                 :           3332 :     appendStringInfoString(buf, leftop);
                              13747         [ +  + ]:           3332 :     if (leftoptype != operform->oprleft)
                              13748                 :            749 :         add_cast_to(buf, operform->oprleft);
                              13749                 :           3332 :     appendStringInfo(buf, " OPERATOR(%s.", quote_identifier(nspname));
                              13750                 :           3332 :     appendStringInfoString(buf, oprname);
                              13751                 :           3332 :     appendStringInfo(buf, ") %s", rightop);
                              13752         [ +  + ]:           3332 :     if (rightoptype != operform->oprright)
                              13753                 :            694 :         add_cast_to(buf, operform->oprright);
                              13754                 :                : 
                              13755                 :           3332 :     ReleaseSysCache(opertup);
                              13756                 :           3332 : }
                              13757                 :                : 
                              13758                 :                : /*
                              13759                 :                :  * Add a cast specification to buf.  We spell out the type name the hard way,
                              13760                 :                :  * intentionally not using format_type_be().  This is to avoid corner cases
                              13761                 :                :  * for CHARACTER, BIT, and perhaps other types, where specifying the type
                              13762                 :                :  * using SQL-standard syntax results in undesirable data truncation.  By
                              13763                 :                :  * doing it this way we can be certain that the cast will have default (-1)
                              13764                 :                :  * target typmod.
                              13765                 :                :  */
                              13766                 :                : static void
                              13767                 :           1443 : add_cast_to(StringInfo buf, Oid typid)
                              13768                 :                : {
                              13769                 :                :     HeapTuple   typetup;
                              13770                 :                :     Form_pg_type typform;
                              13771                 :                :     char       *typname;
                              13772                 :                :     char       *nspname;
                              13773                 :                : 
                              13774                 :           1443 :     typetup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
                              13775         [ -  + ]:           1443 :     if (!HeapTupleIsValid(typetup))
 3176 tgl@sss.pgh.pa.us       13776         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for type %u", typid);
 3176 tgl@sss.pgh.pa.us       13777                 :CBC        1443 :     typform = (Form_pg_type) GETSTRUCT(typetup);
                              13778                 :                : 
                              13779                 :           1443 :     typname = NameStr(typform->typname);
 1950                         13780                 :           1443 :     nspname = get_namespace_name_or_temp(typform->typnamespace);
                              13781                 :                : 
 3176                         13782                 :           1443 :     appendStringInfo(buf, "::%s.%s",
                              13783                 :                :                      quote_identifier(nspname), quote_identifier(typname));
                              13784                 :                : 
                              13785                 :           1443 :     ReleaseSysCache(typetup);
                              13786                 :           1443 : }
                              13787                 :                : 
                              13788                 :                : /*
                              13789                 :                :  * generate_qualified_type_name
                              13790                 :                :  *      Compute the name to display for a type specified by OID
                              13791                 :                :  *
                              13792                 :                :  * This is different from format_type_be() in that we unconditionally
                              13793                 :                :  * schema-qualify the name.  That also means no special syntax for
                              13794                 :                :  * SQL-standard type names ... although in current usage, this should
                              13795                 :                :  * only get used for domains, so such cases wouldn't occur anyway.
                              13796                 :                :  */
                              13797                 :                : static char *
 3314                         13798                 :             13 : generate_qualified_type_name(Oid typid)
                              13799                 :                : {
                              13800                 :                :     HeapTuple   tp;
                              13801                 :                :     Form_pg_type typtup;
                              13802                 :                :     char       *typname;
                              13803                 :                :     char       *nspname;
                              13804                 :                :     char       *result;
                              13805                 :                : 
                              13806                 :             13 :     tp = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
                              13807         [ -  + ]:             13 :     if (!HeapTupleIsValid(tp))
 3314 tgl@sss.pgh.pa.us       13808         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for type %u", typid);
 3314 tgl@sss.pgh.pa.us       13809                 :CBC          13 :     typtup = (Form_pg_type) GETSTRUCT(tp);
                              13810                 :             13 :     typname = NameStr(typtup->typname);
                              13811                 :                : 
 1950                         13812                 :             13 :     nspname = get_namespace_name_or_temp(typtup->typnamespace);
 3314                         13813         [ -  + ]:             13 :     if (!nspname)
 3314 tgl@sss.pgh.pa.us       13814         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for namespace %u",
                              13815                 :                :              typtup->typnamespace);
                              13816                 :                : 
 3314 tgl@sss.pgh.pa.us       13817                 :CBC          13 :     result = quote_qualified_identifier(nspname, typname);
                              13818                 :                : 
                              13819                 :             13 :     ReleaseSysCache(tp);
                              13820                 :                : 
                              13821                 :             13 :     return result;
                              13822                 :                : }
                              13823                 :                : 
                              13824                 :                : /*
                              13825                 :                :  * generate_collation_name
                              13826                 :                :  *      Compute the name to display for a collation specified by OID
                              13827                 :                :  *
                              13828                 :                :  * The result includes all necessary quoting and schema-prefixing.
                              13829                 :                :  */
                              13830                 :                : char *
 5772 peter_e@gmx.net         13831                 :            306 : generate_collation_name(Oid collid)
                              13832                 :                : {
                              13833                 :                :     HeapTuple   tp;
                              13834                 :                :     Form_pg_collation colltup;
                              13835                 :                :     char       *collname;
                              13836                 :                :     char       *nspname;
                              13837                 :                :     char       *result;
                              13838                 :                : 
                              13839                 :            306 :     tp = SearchSysCache1(COLLOID, ObjectIdGetDatum(collid));
                              13840         [ -  + ]:            306 :     if (!HeapTupleIsValid(tp))
 5772 peter_e@gmx.net         13841         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for collation %u", collid);
 5772 peter_e@gmx.net         13842                 :CBC         306 :     colltup = (Form_pg_collation) GETSTRUCT(tp);
                              13843                 :            306 :     collname = NameStr(colltup->collname);
                              13844                 :                : 
                              13845         [ -  + ]:            306 :     if (!CollationIsVisible(collid))
 1950 tgl@sss.pgh.pa.us       13846                 :UBC           0 :         nspname = get_namespace_name_or_temp(colltup->collnamespace);
                              13847                 :                :     else
 5772 peter_e@gmx.net         13848                 :CBC         306 :         nspname = NULL;
                              13849                 :                : 
                              13850                 :            306 :     result = quote_qualified_identifier(nspname, collname);
                              13851                 :                : 
                              13852                 :            306 :     ReleaseSysCache(tp);
                              13853                 :                : 
                              13854                 :            306 :     return result;
                              13855                 :                : }
                              13856                 :                : 
                              13857                 :                : /*
                              13858                 :                :  * Given a C string, produce a TEXT datum.
                              13859                 :                :  *
                              13860                 :                :  * We assume that the input was palloc'd and may be freed.
                              13861                 :                :  */
                              13862                 :                : static text *
 8242 tgl@sss.pgh.pa.us       13863                 :          25504 : string_to_text(char *str)
                              13864                 :                : {
                              13865                 :                :     text       *result;
                              13866                 :                : 
 6822                         13867                 :          25504 :     result = cstring_to_text(str);
 8242                         13868                 :          25504 :     pfree(str);
                              13869                 :          25504 :     return result;
                              13870                 :                : }
                              13871                 :                : 
                              13872                 :                : /*
                              13873                 :                :  * Generate a C string representing a relation options from text[] datum.
                              13874                 :                :  */
                              13875                 :                : void
 2434 akorotkov@postgresql    13876                 :            131 : get_reloptions(StringInfo buf, Datum reloptions)
                              13877                 :                : {
                              13878                 :                :     Datum      *options;
                              13879                 :                :     int         noptions;
                              13880                 :                :     int         i;
                              13881                 :                : 
 1611 peter@eisentraut.org    13882                 :            131 :     deconstruct_array_builtin(DatumGetArrayTypeP(reloptions), TEXTOID,
                              13883                 :                :                               &options, NULL, &noptions);
                              13884                 :                : 
 2434 akorotkov@postgresql    13885         [ +  + ]:            284 :     for (i = 0; i < noptions; i++)
                              13886                 :                :     {
                              13887                 :            153 :         char       *option = TextDatumGetCString(options[i]);
                              13888                 :                :         char       *name;
                              13889                 :                :         char       *separator;
                              13890                 :                :         char       *value;
                              13891                 :                : 
                              13892                 :                :         /*
                              13893                 :                :          * Each array element should have the form name=value.  If the "=" is
                              13894                 :                :          * missing for some reason, treat it like an empty value.
                              13895                 :                :          */
                              13896                 :            153 :         name = option;
                              13897                 :            153 :         separator = strchr(option, '=');
                              13898         [ +  - ]:            153 :         if (separator)
                              13899                 :                :         {
                              13900                 :            153 :             *separator = '\0';
                              13901                 :            153 :             value = separator + 1;
                              13902                 :                :         }
                              13903                 :                :         else
 2434 akorotkov@postgresql    13904                 :UBC           0 :             value = "";
                              13905                 :                : 
 2434 akorotkov@postgresql    13906         [ +  + ]:CBC         153 :         if (i > 0)
                              13907                 :             22 :             appendStringInfoString(buf, ", ");
                              13908                 :            153 :         appendStringInfo(buf, "%s=", quote_identifier(name));
                              13909                 :                : 
                              13910                 :                :         /*
                              13911                 :                :          * In general we need to quote the value; but to avoid unnecessary
                              13912                 :                :          * clutter, do not quote if it is an identifier that would not need
                              13913                 :                :          * quoting.  (We could also allow numbers, but that is a bit trickier
                              13914                 :                :          * than it looks --- for example, are leading zeroes significant?  We
                              13915                 :                :          * don't want to assume very much here about what custom reloptions
                              13916                 :                :          * might mean.)
                              13917                 :                :          */
                              13918         [ +  + ]:            153 :         if (quote_identifier(value) == value)
                              13919                 :              4 :             appendStringInfoString(buf, value);
                              13920                 :                :         else
                              13921                 :            149 :             simple_quote_literal(buf, value);
                              13922                 :                : 
                              13923                 :            153 :         pfree(option);
                              13924                 :                :     }
                              13925                 :            131 : }
                              13926                 :                : 
                              13927                 :                : /*
                              13928                 :                :  * Generate a C string representing a relation's reloptions, or NULL if none.
                              13929                 :                :  */
                              13930                 :                : static char *
 7454 bruce@momjian.us        13931                 :           4609 : flatten_reloptions(Oid relid)
                              13932                 :                : {
                              13933                 :           4609 :     char       *result = NULL;
                              13934                 :                :     HeapTuple   tuple;
                              13935                 :                :     Datum       reloptions;
                              13936                 :                :     bool        isnull;
                              13937                 :                : 
 6131 rhaas@postgresql.org    13938                 :           4609 :     tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
 7453 tgl@sss.pgh.pa.us       13939         [ -  + ]:           4609 :     if (!HeapTupleIsValid(tuple))
 7453 tgl@sss.pgh.pa.us       13940         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for relation %u", relid);
                              13941                 :                : 
 7453 tgl@sss.pgh.pa.us       13942                 :CBC        4609 :     reloptions = SysCacheGetAttr(RELOID, tuple,
                              13943                 :                :                                  Anum_pg_class_reloptions, &isnull);
                              13944         [ +  + ]:           4609 :     if (!isnull)
                              13945                 :                :     {
                              13946                 :                :         StringInfoData buf;
                              13947                 :                : 
 3984                         13948                 :            105 :         initStringInfo(&buf);
 2434 akorotkov@postgresql    13949                 :            105 :         get_reloptions(&buf, reloptions);
                              13950                 :                : 
 3984 tgl@sss.pgh.pa.us       13951                 :            105 :         result = buf.data;
                              13952                 :                :     }
                              13953                 :                : 
 7453                         13954                 :           4609 :     ReleaseSysCache(tuple);
                              13955                 :                : 
 7454 bruce@momjian.us        13956                 :           4609 :     return result;
                              13957                 :                : }
                              13958                 :                : 
                              13959                 :                : /*
                              13960                 :                :  * get_range_partbound_string
                              13961                 :                :  *      A C string representation of one range partition bound
                              13962                 :                :  */
                              13963                 :                : char *
 3397 rhaas@postgresql.org    13964                 :           2702 : get_range_partbound_string(List *bound_datums)
                              13965                 :                : {
                              13966                 :                :     deparse_context context;
                              13967                 :                :     StringInfoData buf;
                              13968                 :                :     ListCell   *cell;
                              13969                 :                :     char       *sep;
                              13970                 :                : 
  387 drowley@postgresql.o    13971                 :           2702 :     initStringInfo(&buf);
 3397 rhaas@postgresql.org    13972                 :           2702 :     memset(&context, 0, sizeof(deparse_context));
  387 drowley@postgresql.o    13973                 :           2702 :     context.buf = &buf;
                              13974                 :                : 
                              13975                 :           2702 :     appendStringInfoChar(&buf, '(');
 3397 rhaas@postgresql.org    13976                 :           2702 :     sep = "";
                              13977   [ +  -  +  +  :           5882 :     foreach(cell, bound_datums)
                                              +  + ]
                              13978                 :                :     {
                              13979                 :                :         PartitionRangeDatum *datum =
 1289 tgl@sss.pgh.pa.us       13980                 :           3180 :             lfirst_node(PartitionRangeDatum, cell);
                              13981                 :                : 
  387 drowley@postgresql.o    13982                 :           3180 :         appendStringInfoString(&buf, sep);
 3397 rhaas@postgresql.org    13983         [ +  + ]:           3180 :         if (datum->kind == PARTITION_RANGE_DATUM_MINVALUE)
  387 drowley@postgresql.o    13984                 :            148 :             appendStringInfoString(&buf, "MINVALUE");
 3397 rhaas@postgresql.org    13985         [ +  + ]:           3032 :         else if (datum->kind == PARTITION_RANGE_DATUM_MAXVALUE)
  387 drowley@postgresql.o    13986                 :             80 :             appendStringInfoString(&buf, "MAXVALUE");
                              13987                 :                :         else
                              13988                 :                :         {
 3397 rhaas@postgresql.org    13989                 :           2952 :             Const      *val = castNode(Const, datum->value);
                              13990                 :                : 
                              13991                 :           2952 :             get_const_expr(val, &context, -1);
                              13992                 :                :         }
                              13993                 :           3180 :         sep = ", ";
                              13994                 :                :     }
  387 drowley@postgresql.o    13995                 :           2702 :     appendStringInfoChar(&buf, ')');
                              13996                 :                : 
                              13997                 :           2702 :     return buf.data;
                              13998                 :                : }
        

Generated by: LCOV version 2.0-1