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 EUB ECB DUB DCB
Current: b45a8d7d8b306b43f31a002f1b3f1dddc8defeaf vs 8767b449a3a1e75626dfb08f24da54933171d4c5 Lines: 90.6 % 5364 4861 8 495 8 15 4838 4 5
Current Date: 2025-10-28 08:26:42 +0900 Functions: 99.4 % 170 169 1 4 165
Baseline: lcov-20251028-005825-baseline Branches: 73.3 % 3920 2875 6 1039 5 10 2860 1 1
Baseline Date: 2025-10-27 06:37:35 +0000 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(1,7] days: 50.0 % 2 1 1 1
(7,30] days: 66.7 % 21 14 7 14
(30,360] days: 96.2 % 131 126 5 1 125
(360..) days: 90.6 % 5210 4720 490 7 4713
Function coverage date bins:
(30,360] days: 100.0 % 3 3 3
(360..) days: 99.4 % 167 166 1 4 162
Branch coverage date bins:
(1,7] days: 25.0 % 4 1 3 1
(7,30] days: 75.0 % 12 9 3 9
(30,360] days: 74.6 % 114 85 29 1 84
(360..) days: 73.3 % 3792 2780 1010 4 2776 1 1

 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-2025, 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;
                                186                 :                :     char      **argnames;
                                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 void get_basic_select_query(Query *query, deparse_context *context);
                                430                 :                : static void get_target_list(List *targetList, deparse_context *context);
                                431                 :                : static void get_returning_clause(Query *query, deparse_context *context);
                                432                 :                : static void get_setop_query(Node *setOp, Query *query,
                                433                 :                :                             deparse_context *context);
                                434                 :                : static Node *get_rule_sortgroupclause(Index ref, List *tlist,
                                435                 :                :                                       bool force_colno,
                                436                 :                :                                       deparse_context *context);
                                437                 :                : static void get_rule_groupingset(GroupingSet *gset, List *targetlist,
                                438                 :                :                                  bool omit_parens, deparse_context *context);
                                439                 :                : static void get_rule_orderby(List *orderList, List *targetList,
                                440                 :                :                              bool force_colno, deparse_context *context);
                                441                 :                : static void get_rule_windowclause(Query *query, deparse_context *context);
                                442                 :                : static void get_rule_windowspec(WindowClause *wc, List *targetList,
                                443                 :                :                                 deparse_context *context);
                                444                 :                : static void get_window_frame_options(int frameOptions,
                                445                 :                :                                      Node *startOffset, Node *endOffset,
                                446                 :                :                                      deparse_context *context);
                                447                 :                : static char *get_variable(Var *var, int levelsup, bool istoplevel,
                                448                 :                :                           deparse_context *context);
                                449                 :                : static void get_special_variable(Node *node, deparse_context *context,
                                450                 :                :                                  void *callback_arg);
                                451                 :                : static void resolve_special_varno(Node *node, deparse_context *context,
                                452                 :                :                                   rsv_callback callback, void *callback_arg);
                                453                 :                : static Node *find_param_referent(Param *param, deparse_context *context,
                                454                 :                :                                  deparse_namespace **dpns_p, ListCell **ancestor_cell_p);
                                455                 :                : static SubPlan *find_param_generator(Param *param, deparse_context *context,
                                456                 :                :                                      int *column_p);
                                457                 :                : static SubPlan *find_param_generator_initplan(Param *param, Plan *plan,
                                458                 :                :                                               int *column_p);
                                459                 :                : static void get_parameter(Param *param, deparse_context *context);
                                460                 :                : static const char *get_simple_binary_op_name(OpExpr *expr);
                                461                 :                : static bool isSimpleNode(Node *node, Node *parentNode, int prettyFlags);
                                462                 :                : static void appendContextKeyword(deparse_context *context, const char *str,
                                463                 :                :                                  int indentBefore, int indentAfter, int indentPlus);
                                464                 :                : static void removeStringInfoSpaces(StringInfo str);
                                465                 :                : static void get_rule_expr(Node *node, deparse_context *context,
                                466                 :                :                           bool showimplicit);
                                467                 :                : static void get_rule_expr_toplevel(Node *node, deparse_context *context,
                                468                 :                :                                    bool showimplicit);
                                469                 :                : static void get_rule_list_toplevel(List *lst, deparse_context *context,
                                470                 :                :                                    bool showimplicit);
                                471                 :                : static void get_rule_expr_funccall(Node *node, deparse_context *context,
                                472                 :                :                                    bool showimplicit);
                                473                 :                : static bool looks_like_function(Node *node);
                                474                 :                : static void get_oper_expr(OpExpr *expr, deparse_context *context);
                                475                 :                : static void get_func_expr(FuncExpr *expr, deparse_context *context,
                                476                 :                :                           bool showimplicit);
                                477                 :                : static void get_agg_expr(Aggref *aggref, deparse_context *context,
                                478                 :                :                          Aggref *original_aggref);
                                479                 :                : static void get_agg_expr_helper(Aggref *aggref, deparse_context *context,
                                480                 :                :                                 Aggref *original_aggref, const char *funcname,
                                481                 :                :                                 const char *options, bool is_json_objectagg);
                                482                 :                : static void get_agg_combine_expr(Node *node, deparse_context *context,
                                483                 :                :                                  void *callback_arg);
                                484                 :                : static void get_windowfunc_expr(WindowFunc *wfunc, deparse_context *context);
                                485                 :                : static void get_windowfunc_expr_helper(WindowFunc *wfunc, deparse_context *context,
                                486                 :                :                                        const char *funcname, const char *options,
                                487                 :                :                                        bool is_json_objectagg);
                                488                 :                : static bool get_func_sql_syntax(FuncExpr *expr, deparse_context *context);
                                489                 :                : static void get_coercion_expr(Node *arg, deparse_context *context,
                                490                 :                :                               Oid resulttype, int32 resulttypmod,
                                491                 :                :                               Node *parentNode);
                                492                 :                : static void get_const_expr(Const *constval, deparse_context *context,
                                493                 :                :                            int showtype);
                                494                 :                : static void get_const_collation(Const *constval, deparse_context *context);
                                495                 :                : static void get_json_format(JsonFormat *format, StringInfo buf);
                                496                 :                : static void get_json_returning(JsonReturning *returning, StringInfo buf,
                                497                 :                :                                bool json_format_by_default);
                                498                 :                : static void get_json_constructor(JsonConstructorExpr *ctor,
                                499                 :                :                                  deparse_context *context, bool showimplicit);
                                500                 :                : static void get_json_constructor_options(JsonConstructorExpr *ctor,
                                501                 :                :                                          StringInfo buf);
                                502                 :                : static void get_json_agg_constructor(JsonConstructorExpr *ctor,
                                503                 :                :                                      deparse_context *context,
                                504                 :                :                                      const char *funcname,
                                505                 :                :                                      bool is_json_objectagg);
                                506                 :                : static void simple_quote_literal(StringInfo buf, const char *val);
                                507                 :                : static void get_sublink_expr(SubLink *sublink, deparse_context *context);
                                508                 :                : static void get_tablefunc(TableFunc *tf, deparse_context *context,
                                509                 :                :                           bool showimplicit);
                                510                 :                : static void get_from_clause(Query *query, const char *prefix,
                                511                 :                :                             deparse_context *context);
                                512                 :                : static void get_from_clause_item(Node *jtnode, Query *query,
                                513                 :                :                                  deparse_context *context);
                                514                 :                : static void get_rte_alias(RangeTblEntry *rte, int varno, bool use_as,
                                515                 :                :                           deparse_context *context);
                                516                 :                : static void get_column_alias_list(deparse_columns *colinfo,
                                517                 :                :                                   deparse_context *context);
                                518                 :                : static void get_from_clause_coldeflist(RangeTblFunction *rtfunc,
                                519                 :                :                                        deparse_columns *colinfo,
                                520                 :                :                                        deparse_context *context);
                                521                 :                : static void get_tablesample_def(TableSampleClause *tablesample,
                                522                 :                :                                 deparse_context *context);
                                523                 :                : static void get_opclass_name(Oid opclass, Oid actual_datatype,
                                524                 :                :                              StringInfo buf);
                                525                 :                : static Node *processIndirection(Node *node, deparse_context *context);
                                526                 :                : static void printSubscripts(SubscriptingRef *sbsref, deparse_context *context);
                                527                 :                : static char *get_relation_name(Oid relid);
                                528                 :                : static char *generate_relation_name(Oid relid, List *namespaces);
                                529                 :                : static char *generate_qualified_relation_name(Oid relid);
                                530                 :                : static char *generate_function_name(Oid funcid, int nargs,
                                531                 :                :                                     List *argnames, Oid *argtypes,
                                532                 :                :                                     bool has_variadic, bool *use_variadic_p,
                                533                 :                :                                     bool inGroupBy);
                                534                 :                : static char *generate_operator_name(Oid operid, Oid arg1, Oid arg2);
                                535                 :                : static void add_cast_to(StringInfo buf, Oid typid);
                                536                 :                : static char *generate_qualified_type_name(Oid typid);
                                537                 :                : static text *string_to_text(char *str);
                                538                 :                : static char *flatten_reloptions(Oid relid);
                                539                 :                : static void get_reloptions(StringInfo buf, Datum reloptions);
                                540                 :                : static void get_json_path_spec(Node *path_spec, deparse_context *context,
                                541                 :                :                                bool showimplicit);
                                542                 :                : static void get_json_table_columns(TableFunc *tf, JsonTablePathScan *scan,
                                543                 :                :                                    deparse_context *context,
                                544                 :                :                                    bool showimplicit);
                                545                 :                : static void get_json_table_nested_columns(TableFunc *tf, JsonTablePlan *plan,
                                546                 :                :                                           deparse_context *context,
                                547                 :                :                                           bool showimplicit,
                                548                 :                :                                           bool needcomma);
                                549                 :                : 
                                550                 :                : #define only_marker(rte)  ((rte)->inh ? "" : "ONLY ")
                                551                 :                : 
                                552                 :                : 
                                553                 :                : /* ----------
                                554                 :                :  * pg_get_ruledef       - Do it all and return a text
                                555                 :                :  *                that could be used as a statement
                                556                 :                :  *                to recreate the rule
                                557                 :                :  * ----------
                                558                 :                :  */
                                559                 :                : Datum
 9245 tgl@sss.pgh.pa.us         560                 :CBC         225 : pg_get_ruledef(PG_FUNCTION_ARGS)
                                561                 :                : {
 8594                           562                 :            225 :     Oid         ruleoid = PG_GETARG_OID(0);
                                563                 :                :     int         prettyFlags;
                                564                 :                :     char       *res;
                                565                 :                : 
 4650                           566                 :            225 :     prettyFlags = PRETTYFLAG_INDENT;
                                567                 :                : 
 3381 rhaas@postgresql.org      568                 :            225 :     res = pg_get_ruledef_worker(ruleoid, prettyFlags);
                                569                 :                : 
                                570         [ +  + ]:            225 :     if (res == NULL)
                                571                 :              3 :         PG_RETURN_NULL();
                                572                 :                : 
                                573                 :            222 :     PG_RETURN_TEXT_P(string_to_text(res));
                                574                 :                : }
                                575                 :                : 
                                576                 :                : 
                                577                 :                : Datum
 8126 tgl@sss.pgh.pa.us         578                 :             57 : pg_get_ruledef_ext(PG_FUNCTION_ARGS)
                                579                 :                : {
                                580                 :             57 :     Oid         ruleoid = PG_GETARG_OID(0);
                                581                 :             57 :     bool        pretty = PG_GETARG_BOOL(1);
                                582                 :                :     int         prettyFlags;
                                583                 :                :     char       *res;
                                584                 :                : 
 1310                           585         [ +  - ]:             57 :     prettyFlags = GET_PRETTY_FLAGS(pretty);
                                586                 :                : 
 3381 rhaas@postgresql.org      587                 :             57 :     res = pg_get_ruledef_worker(ruleoid, prettyFlags);
                                588                 :                : 
                                589         [ -  + ]:             57 :     if (res == NULL)
 3381 rhaas@postgresql.org      590                 :UBC           0 :         PG_RETURN_NULL();
                                591                 :                : 
 3381 rhaas@postgresql.org      592                 :CBC          57 :     PG_RETURN_TEXT_P(string_to_text(res));
                                593                 :                : }
                                594                 :                : 
                                595                 :                : 
                                596                 :                : static char *
 8126 tgl@sss.pgh.pa.us         597                 :            282 : pg_get_ruledef_worker(Oid ruleoid, int prettyFlags)
                                598                 :                : {
                                599                 :                :     Datum       args[1];
                                600                 :                :     char        nulls[1];
                                601                 :                :     int         spirc;
                                602                 :                :     HeapTuple   ruletup;
                                603                 :                :     TupleDesc   rulettc;
                                604                 :                :     StringInfoData buf;
                                605                 :                : 
                                606                 :                :     /*
                                607                 :                :      * Do this first so that string is alloc'd in outer context not SPI's.
                                608                 :                :      */
 7846                           609                 :            282 :     initStringInfo(&buf);
                                610                 :                : 
                                611                 :                :     /*
                                612                 :                :      * Connect to SPI manager
                                613                 :                :      */
  414                           614                 :            282 :     SPI_connect();
                                615                 :                : 
                                616                 :                :     /*
                                617                 :                :      * On the first call prepare the plan to lookup pg_rewrite. We read
                                618                 :                :      * pg_rewrite over the SPI manager instead of using the syscache to be
                                619                 :                :      * checked for read access on pg_rewrite.
                                620                 :                :      */
 8594                           621         [ +  + ]:            282 :     if (plan_getrulebyoid == NULL)
                                622                 :                :     {
                                623                 :                :         Oid         argtypes[1];
                                624                 :                :         SPIPlanPtr  plan;
                                625                 :                : 
                                626                 :             20 :         argtypes[0] = OIDOID;
                                627                 :             20 :         plan = SPI_prepare(query_getrulebyoid, 1, argtypes);
 9919 bruce@momjian.us          628         [ -  + ]:             20 :         if (plan == NULL)
 8129 tgl@sss.pgh.pa.us         629         [ #  # ]:UBC           0 :             elog(ERROR, "SPI_prepare failed for \"%s\"", query_getrulebyoid);
 5156 tgl@sss.pgh.pa.us         630                 :CBC          20 :         SPI_keepplan(plan);
                                631                 :             20 :         plan_getrulebyoid = plan;
                                632                 :                :     }
                                633                 :                : 
                                634                 :                :     /*
                                635                 :                :      * Get the pg_rewrite tuple for this rule
                                636                 :                :      */
 8594                           637                 :            282 :     args[0] = ObjectIdGetDatum(ruleoid);
                                638                 :            282 :     nulls[0] = ' ';
 4357 peter_e@gmx.net           639                 :            282 :     spirc = SPI_execute_plan(plan_getrulebyoid, args, nulls, true, 0);
 9919 bruce@momjian.us          640         [ -  + ]:            282 :     if (spirc != SPI_OK_SELECT)
 8129 tgl@sss.pgh.pa.us         641         [ #  # ]:UBC           0 :         elog(ERROR, "failed to get pg_rewrite tuple for rule %u", ruleoid);
 9919 bruce@momjian.us          642         [ +  + ]:CBC         282 :     if (SPI_processed != 1)
                                643                 :                :     {
                                644                 :                :         /*
                                645                 :                :          * There is no tuple data available here, just keep the output buffer
                                646                 :                :          * empty.
                                647                 :                :          */
                                648                 :                :     }
                                649                 :                :     else
                                650                 :                :     {
                                651                 :                :         /*
                                652                 :                :          * Get the rule's definition and put it into executor's memory
                                653                 :                :          */
 7846 tgl@sss.pgh.pa.us         654                 :            279 :         ruletup = SPI_tuptable->vals[0];
                                655                 :            279 :         rulettc = SPI_tuptable->tupdesc;
                                656                 :            279 :         make_ruledef(&buf, ruletup, rulettc, prettyFlags);
                                657                 :                :     }
                                658                 :                : 
                                659                 :                :     /*
                                660                 :                :      * Disconnect from SPI manager
                                661                 :                :      */
 9919 bruce@momjian.us          662         [ -  + ]:            282 :     if (SPI_finish() != SPI_OK_FINISH)
 8129 tgl@sss.pgh.pa.us         663         [ #  # ]:UBC           0 :         elog(ERROR, "SPI_finish failed");
                                664                 :                : 
 3381 rhaas@postgresql.org      665         [ +  + ]:CBC         282 :     if (buf.len == 0)
                                666                 :              3 :         return NULL;
                                667                 :                : 
 7846 tgl@sss.pgh.pa.us         668                 :            279 :     return buf.data;
                                669                 :                : }
                                670                 :                : 
                                671                 :                : 
                                672                 :                : /* ----------
                                673                 :                :  * pg_get_viewdef       - Mainly the same thing, but we
                                674                 :                :  *                only return the SELECT part of a view
                                675                 :                :  * ----------
                                676                 :                :  */
                                677                 :                : Datum
 9245                           678                 :           1237 : pg_get_viewdef(PG_FUNCTION_ARGS)
                                679                 :                : {
                                680                 :                :     /* By OID */
 8594                           681                 :           1237 :     Oid         viewoid = PG_GETARG_OID(0);
                                682                 :                :     int         prettyFlags;
                                683                 :                :     char       *res;
                                684                 :                : 
 4650                           685                 :           1237 :     prettyFlags = PRETTYFLAG_INDENT;
                                686                 :                : 
 3381 rhaas@postgresql.org      687                 :           1237 :     res = pg_get_viewdef_worker(viewoid, prettyFlags, WRAP_COLUMN_DEFAULT);
                                688                 :                : 
                                689         [ +  + ]:           1237 :     if (res == NULL)
                                690                 :              3 :         PG_RETURN_NULL();
                                691                 :                : 
                                692                 :           1234 :     PG_RETURN_TEXT_P(string_to_text(res));
                                693                 :                : }
                                694                 :                : 
                                695                 :                : 
                                696                 :                : Datum
 8126 tgl@sss.pgh.pa.us         697                 :            282 : pg_get_viewdef_ext(PG_FUNCTION_ARGS)
                                698                 :                : {
                                699                 :                :     /* By OID */
                                700                 :            282 :     Oid         viewoid = PG_GETARG_OID(0);
                                701                 :            282 :     bool        pretty = PG_GETARG_BOOL(1);
                                702                 :                :     int         prettyFlags;
                                703                 :                :     char       *res;
                                704                 :                : 
 1310                           705         [ +  - ]:            282 :     prettyFlags = GET_PRETTY_FLAGS(pretty);
                                706                 :                : 
 3381 rhaas@postgresql.org      707                 :            282 :     res = pg_get_viewdef_worker(viewoid, prettyFlags, WRAP_COLUMN_DEFAULT);
                                708                 :                : 
                                709         [ -  + ]:            282 :     if (res == NULL)
 3381 rhaas@postgresql.org      710                 :UBC           0 :         PG_RETURN_NULL();
                                711                 :                : 
 3381 rhaas@postgresql.org      712                 :CBC         282 :     PG_RETURN_TEXT_P(string_to_text(res));
                                713                 :                : }
                                714                 :                : 
                                715                 :                : Datum
 5000 andrew@dunslane.net       716                 :              3 : pg_get_viewdef_wrap(PG_FUNCTION_ARGS)
                                717                 :                : {
                                718                 :                :     /* By OID */
                                719                 :              3 :     Oid         viewoid = PG_GETARG_OID(0);
 4888 bruce@momjian.us          720                 :              3 :     int         wrap = PG_GETARG_INT32(1);
                                721                 :                :     int         prettyFlags;
                                722                 :                :     char       *res;
                                723                 :                : 
                                724                 :                :     /* calling this implies we want pretty printing */
 1310 tgl@sss.pgh.pa.us         725                 :              3 :     prettyFlags = GET_PRETTY_FLAGS(true);
                                726                 :                : 
 3381 rhaas@postgresql.org      727                 :              3 :     res = pg_get_viewdef_worker(viewoid, prettyFlags, wrap);
                                728                 :                : 
                                729         [ -  + ]:              3 :     if (res == NULL)
 3381 rhaas@postgresql.org      730                 :UBC           0 :         PG_RETURN_NULL();
                                731                 :                : 
 3381 rhaas@postgresql.org      732                 :CBC           3 :     PG_RETURN_TEXT_P(string_to_text(res));
                                733                 :                : }
                                734                 :                : 
                                735                 :                : Datum
 8594 tgl@sss.pgh.pa.us         736                 :             39 : pg_get_viewdef_name(PG_FUNCTION_ARGS)
                                737                 :                : {
                                738                 :                :     /* By qualified name */
 3152 noah@leadboat.com         739                 :             39 :     text       *viewname = PG_GETARG_TEXT_PP(0);
                                740                 :                :     int         prettyFlags;
                                741                 :                :     RangeVar   *viewrel;
                                742                 :                :     Oid         viewoid;
                                743                 :                :     char       *res;
                                744                 :                : 
 4650 tgl@sss.pgh.pa.us         745                 :             39 :     prettyFlags = PRETTYFLAG_INDENT;
                                746                 :                : 
                                747                 :                :     /* Look up view name.  Can't lock it - we might not have privileges. */
 7459 neilc@samurai.com         748                 :             39 :     viewrel = makeRangeVarFromNameList(textToQualifiedNameList(viewname));
 5081 rhaas@postgresql.org      749                 :             39 :     viewoid = RangeVarGetRelid(viewrel, NoLock, false);
                                750                 :                : 
 3381                           751                 :             39 :     res = pg_get_viewdef_worker(viewoid, prettyFlags, WRAP_COLUMN_DEFAULT);
                                752                 :                : 
                                753         [ -  + ]:             39 :     if (res == NULL)
 3381 rhaas@postgresql.org      754                 :UBC           0 :         PG_RETURN_NULL();
                                755                 :                : 
 3381 rhaas@postgresql.org      756                 :CBC          39 :     PG_RETURN_TEXT_P(string_to_text(res));
                                757                 :                : }
                                758                 :                : 
                                759                 :                : 
                                760                 :                : Datum
 8126 tgl@sss.pgh.pa.us         761                 :            201 : pg_get_viewdef_name_ext(PG_FUNCTION_ARGS)
                                762                 :                : {
                                763                 :                :     /* By qualified name */
 3152 noah@leadboat.com         764                 :            201 :     text       *viewname = PG_GETARG_TEXT_PP(0);
 8126 tgl@sss.pgh.pa.us         765                 :            201 :     bool        pretty = PG_GETARG_BOOL(1);
                                766                 :                :     int         prettyFlags;
                                767                 :                :     RangeVar   *viewrel;
                                768                 :                :     Oid         viewoid;
                                769                 :                :     char       *res;
                                770                 :                : 
 1310                           771         [ +  - ]:            201 :     prettyFlags = GET_PRETTY_FLAGS(pretty);
                                772                 :                : 
                                773                 :                :     /* Look up view name.  Can't lock it - we might not have privileges. */
 7459 neilc@samurai.com         774                 :            201 :     viewrel = makeRangeVarFromNameList(textToQualifiedNameList(viewname));
 5081 rhaas@postgresql.org      775                 :            201 :     viewoid = RangeVarGetRelid(viewrel, NoLock, false);
                                776                 :                : 
 3369 tgl@sss.pgh.pa.us         777                 :            201 :     res = pg_get_viewdef_worker(viewoid, prettyFlags, WRAP_COLUMN_DEFAULT);
                                778                 :                : 
                                779         [ -  + ]:            201 :     if (res == NULL)
 3369 tgl@sss.pgh.pa.us         780                 :UBC           0 :         PG_RETURN_NULL();
                                781                 :                : 
 3369 tgl@sss.pgh.pa.us         782                 :CBC         201 :     PG_RETURN_TEXT_P(string_to_text(res));
                                783                 :                : }
                                784                 :                : 
                                785                 :                : /*
                                786                 :                :  * Common code for by-OID and by-name variants of pg_get_viewdef
                                787                 :                :  */
                                788                 :                : static char *
 4691                           789                 :           1762 : pg_get_viewdef_worker(Oid viewoid, int prettyFlags, int wrapColumn)
                                790                 :                : {
                                791                 :                :     Datum       args[2];
                                792                 :                :     char        nulls[2];
                                793                 :                :     int         spirc;
                                794                 :                :     HeapTuple   ruletup;
                                795                 :                :     TupleDesc   rulettc;
                                796                 :                :     StringInfoData buf;
                                797                 :                : 
                                798                 :                :     /*
                                799                 :                :      * Do this first so that string is alloc'd in outer context not SPI's.
                                800                 :                :      */
 7846                           801                 :           1762 :     initStringInfo(&buf);
                                802                 :                : 
                                803                 :                :     /*
                                804                 :                :      * Connect to SPI manager
                                805                 :                :      */
  414                           806                 :           1762 :     SPI_connect();
                                807                 :                : 
                                808                 :                :     /*
                                809                 :                :      * On the first call prepare the plan to lookup pg_rewrite. We read
                                810                 :                :      * pg_rewrite over the SPI manager instead of using the syscache to be
                                811                 :                :      * checked for read access on pg_rewrite.
                                812                 :                :      */
 8594                           813         [ +  + ]:           1762 :     if (plan_getviewrule == NULL)
                                814                 :                :     {
                                815                 :                :         Oid         argtypes[2];
                                816                 :                :         SPIPlanPtr  plan;
                                817                 :                : 
                                818                 :            127 :         argtypes[0] = OIDOID;
                                819                 :            127 :         argtypes[1] = NAMEOID;
                                820                 :            127 :         plan = SPI_prepare(query_getviewrule, 2, argtypes);
 9919 bruce@momjian.us          821         [ -  + ]:            127 :         if (plan == NULL)
 8129 tgl@sss.pgh.pa.us         822         [ #  # ]:UBC           0 :             elog(ERROR, "SPI_prepare failed for \"%s\"", query_getviewrule);
 5156 tgl@sss.pgh.pa.us         823                 :CBC         127 :         SPI_keepplan(plan);
                                824                 :            127 :         plan_getviewrule = plan;
                                825                 :                :     }
                                826                 :                : 
                                827                 :                :     /*
                                828                 :                :      * Get the pg_rewrite tuple for the view's SELECT rule
                                829                 :                :      */
 8594                           830                 :           1762 :     args[0] = ObjectIdGetDatum(viewoid);
 4357 peter_e@gmx.net           831                 :           1762 :     args[1] = DirectFunctionCall1(namein, CStringGetDatum(ViewSelectRuleName));
 9919 bruce@momjian.us          832                 :           1762 :     nulls[0] = ' ';
 8594 tgl@sss.pgh.pa.us         833                 :           1762 :     nulls[1] = ' ';
 4357 peter_e@gmx.net           834                 :           1762 :     spirc = SPI_execute_plan(plan_getviewrule, args, nulls, true, 0);
 9919 bruce@momjian.us          835         [ -  + ]:           1762 :     if (spirc != SPI_OK_SELECT)
 8579 tgl@sss.pgh.pa.us         836         [ #  # ]:UBC           0 :         elog(ERROR, "failed to get pg_rewrite tuple for view %u", viewoid);
 9919 bruce@momjian.us          837         [ +  + ]:CBC        1762 :     if (SPI_processed != 1)
                                838                 :                :     {
                                839                 :                :         /*
                                840                 :                :          * There is no tuple data available here, just keep the output buffer
                                841                 :                :          * empty.
                                842                 :                :          */
                                843                 :                :     }
                                844                 :                :     else
                                845                 :                :     {
                                846                 :                :         /*
                                847                 :                :          * Get the rule's definition and put it into executor's memory
                                848                 :                :          */
                                849                 :           1759 :         ruletup = SPI_tuptable->vals[0];
                                850                 :           1759 :         rulettc = SPI_tuptable->tupdesc;
 4691 tgl@sss.pgh.pa.us         851                 :           1759 :         make_viewdef(&buf, ruletup, rulettc, prettyFlags, wrapColumn);
                                852                 :                :     }
                                853                 :                : 
                                854                 :                :     /*
                                855                 :                :      * Disconnect from SPI manager
                                856                 :                :      */
 9919 bruce@momjian.us          857         [ -  + ]:           1762 :     if (SPI_finish() != SPI_OK_FINISH)
 8129 tgl@sss.pgh.pa.us         858         [ #  # ]:UBC           0 :         elog(ERROR, "SPI_finish failed");
                                859                 :                : 
 3381 rhaas@postgresql.org      860         [ +  + ]:CBC        1762 :     if (buf.len == 0)
                                861                 :              3 :         return NULL;
                                862                 :                : 
 7846 tgl@sss.pgh.pa.us         863                 :           1759 :     return buf.data;
                                864                 :                : }
                                865                 :                : 
                                866                 :                : /* ----------
                                867                 :                :  * pg_get_triggerdef        - Get the definition of a trigger
                                868                 :                :  * ----------
                                869                 :                :  */
                                870                 :                : Datum
 8258 bruce@momjian.us          871                 :             82 : pg_get_triggerdef(PG_FUNCTION_ARGS)
                                872                 :                : {
                                873                 :             82 :     Oid         trigid = PG_GETARG_OID(0);
                                874                 :                :     char       *res;
                                875                 :                : 
 3381 rhaas@postgresql.org      876                 :             82 :     res = pg_get_triggerdef_worker(trigid, false);
                                877                 :                : 
                                878         [ +  + ]:             82 :     if (res == NULL)
                                879                 :              3 :         PG_RETURN_NULL();
                                880                 :                : 
                                881                 :             79 :     PG_RETURN_TEXT_P(string_to_text(res));
                                882                 :                : }
                                883                 :                : 
                                884                 :                : Datum
 5863 peter_e@gmx.net           885                 :            595 : pg_get_triggerdef_ext(PG_FUNCTION_ARGS)
                                886                 :                : {
                                887                 :            595 :     Oid         trigid = PG_GETARG_OID(0);
                                888                 :            595 :     bool        pretty = PG_GETARG_BOOL(1);
                                889                 :                :     char       *res;
                                890                 :                : 
 3381 rhaas@postgresql.org      891                 :            595 :     res = pg_get_triggerdef_worker(trigid, pretty);
                                892                 :                : 
                                893         [ -  + ]:            595 :     if (res == NULL)
 3381 rhaas@postgresql.org      894                 :UBC           0 :         PG_RETURN_NULL();
                                895                 :                : 
 3381 rhaas@postgresql.org      896                 :CBC         595 :     PG_RETURN_TEXT_P(string_to_text(res));
                                897                 :                : }
                                898                 :                : 
                                899                 :                : static char *
 5863 peter_e@gmx.net           900                 :            677 : pg_get_triggerdef_worker(Oid trigid, bool pretty)
                                901                 :                : {
                                902                 :                :     HeapTuple   ht_trig;
                                903                 :                :     Form_pg_trigger trigrec;
                                904                 :                :     StringInfoData buf;
                                905                 :                :     Relation    tgrel;
                                906                 :                :     ScanKeyData skey[1];
                                907                 :                :     SysScanDesc tgscan;
 8197 tgl@sss.pgh.pa.us         908                 :            677 :     int         findx = 0;
                                909                 :                :     char       *tgname;
                                910                 :                :     char       *tgoldtable;
                                911                 :                :     char       *tgnewtable;
                                912                 :                :     Datum       value;
                                913                 :                :     bool        isnull;
                                914                 :                : 
                                915                 :                :     /*
                                916                 :                :      * Fetch the pg_trigger tuple by the Oid of the trigger
                                917                 :                :      */
 2472 andres@anarazel.de        918                 :            677 :     tgrel = table_open(TriggerRelationId, AccessShareLock);
                                919                 :                : 
 8021 tgl@sss.pgh.pa.us         920                 :            677 :     ScanKeyInit(&skey[0],
                                921                 :                :                 Anum_pg_trigger_oid,
                                922                 :                :                 BTEqualStrategyNumber, F_OIDEQ,
                                923                 :                :                 ObjectIdGetDatum(trigid));
                                924                 :                : 
 7502                           925                 :            677 :     tgscan = systable_beginscan(tgrel, TriggerOidIndexId, true,
                                926                 :                :                                 NULL, 1, skey);
                                927                 :                : 
 8197                           928                 :            677 :     ht_trig = systable_getnext(tgscan);
                                929                 :                : 
                                930         [ +  + ]:            677 :     if (!HeapTupleIsValid(ht_trig))
                                931                 :                :     {
 3381 rhaas@postgresql.org      932                 :              3 :         systable_endscan(tgscan);
 2472 andres@anarazel.de        933                 :              3 :         table_close(tgrel, AccessShareLock);
 3381 rhaas@postgresql.org      934                 :              3 :         return NULL;
                                935                 :                :     }
                                936                 :                : 
 8258 bruce@momjian.us          937                 :            674 :     trigrec = (Form_pg_trigger) GETSTRUCT(ht_trig);
                                938                 :                : 
                                939                 :                :     /*
                                940                 :                :      * Start the trigger definition. Note that the trigger's name should never
                                941                 :                :      * be schema-qualified, but the trigger rel's name may be.
                                942                 :                :      */
                                943                 :            674 :     initStringInfo(&buf);
                                944                 :                : 
                                945                 :            674 :     tgname = NameStr(trigrec->tgname);
 5759 itagaki.takahiro@gma      946                 :           1348 :     appendStringInfo(&buf, "CREATE %sTRIGGER %s ",
 5763 tgl@sss.pgh.pa.us         947         [ -  + ]:            674 :                      OidIsValid(trigrec->tgconstraint) ? "CONSTRAINT " : "",
                                948                 :                :                      quote_identifier(tgname));
                                949                 :                : 
 8258 bruce@momjian.us          950         [ +  + ]:            674 :     if (TRIGGER_FOR_BEFORE(trigrec->tgtype))
 4380 rhaas@postgresql.org      951                 :            247 :         appendStringInfoString(&buf, "BEFORE");
 5497 tgl@sss.pgh.pa.us         952         [ +  + ]:            427 :     else if (TRIGGER_FOR_AFTER(trigrec->tgtype))
 4380 rhaas@postgresql.org      953                 :            415 :         appendStringInfoString(&buf, "AFTER");
 5497 tgl@sss.pgh.pa.us         954         [ +  - ]:             12 :     else if (TRIGGER_FOR_INSTEAD(trigrec->tgtype))
 4380 rhaas@postgresql.org      955                 :             12 :         appendStringInfoString(&buf, "INSTEAD OF");
                                956                 :                :     else
 5497 tgl@sss.pgh.pa.us         957         [ #  # ]:UBC           0 :         elog(ERROR, "unexpected tgtype value: %d", trigrec->tgtype);
                                958                 :                : 
 8258 bruce@momjian.us          959         [ +  + ]:CBC         674 :     if (TRIGGER_FOR_INSERT(trigrec->tgtype))
                                960                 :                :     {
 4380 rhaas@postgresql.org      961                 :            465 :         appendStringInfoString(&buf, " INSERT");
 8258 bruce@momjian.us          962                 :            465 :         findx++;
                                963                 :                :     }
                                964         [ +  + ]:            674 :     if (TRIGGER_FOR_DELETE(trigrec->tgtype))
                                965                 :                :     {
                                966         [ +  + ]:            105 :         if (findx > 0)
 4380 rhaas@postgresql.org      967                 :             45 :             appendStringInfoString(&buf, " OR DELETE");
                                968                 :                :         else
                                969                 :             60 :             appendStringInfoString(&buf, " DELETE");
 8258 bruce@momjian.us          970                 :            105 :         findx++;
                                971                 :                :     }
                                972         [ +  + ]:            674 :     if (TRIGGER_FOR_UPDATE(trigrec->tgtype))
                                973                 :                :     {
                                974         [ +  + ]:            324 :         if (findx > 0)
 4380 rhaas@postgresql.org      975                 :            175 :             appendStringInfoString(&buf, " OR UPDATE");
                                976                 :                :         else
                                977                 :            149 :             appendStringInfoString(&buf, " UPDATE");
 5821 tgl@sss.pgh.pa.us         978                 :            324 :         findx++;
                                979                 :                :         /* tgattr is first var-width field, so OK to access directly */
 5858                           980         [ +  + ]:            324 :         if (trigrec->tgattr.dim1 > 0)
                                981                 :                :         {
                                982                 :                :             int         i;
                                983                 :                : 
                                984                 :             38 :             appendStringInfoString(&buf, " OF ");
                                985         [ +  + ]:             84 :             for (i = 0; i < trigrec->tgattr.dim1; i++)
                                986                 :                :             {
                                987                 :                :                 char       *attname;
                                988                 :                : 
                                989         [ +  + ]:             46 :                 if (i > 0)
                                990                 :              8 :                     appendStringInfoString(&buf, ", ");
 2815 alvherre@alvh.no-ip.      991                 :             46 :                 attname = get_attname(trigrec->tgrelid,
                                992                 :             46 :                                       trigrec->tgattr.values[i], false);
 5858 tgl@sss.pgh.pa.us         993                 :             46 :                 appendStringInfoString(&buf, quote_identifier(attname));
                                994                 :                :             }
                                995                 :                :         }
                                996                 :                :     }
 6423                           997         [ -  + ]:            674 :     if (TRIGGER_FOR_TRUNCATE(trigrec->tgtype))
                                998                 :                :     {
 6423 tgl@sss.pgh.pa.us         999         [ #  # ]:UBC           0 :         if (findx > 0)
 4380 rhaas@postgresql.org     1000                 :              0 :             appendStringInfoString(&buf, " OR TRUNCATE");
                               1001                 :                :         else
                               1002                 :              0 :             appendStringInfoString(&buf, " TRUNCATE");
 5821 tgl@sss.pgh.pa.us        1003                 :              0 :         findx++;
                               1004                 :                :     }
                               1005                 :                : 
                               1006                 :                :     /*
                               1007                 :                :      * In non-pretty mode, always schema-qualify the target table name for
                               1008                 :                :      * safety.  In pretty mode, schema-qualify only if not visible.
                               1009                 :                :      */
 5759 itagaki.takahiro@gma     1010         [ +  + ]:CBC        1348 :     appendStringInfo(&buf, " ON %s ",
                               1011                 :                :                      pretty ?
 2801 tgl@sss.pgh.pa.us        1012                 :             69 :                      generate_relation_name(trigrec->tgrelid, NIL) :
                               1013                 :            605 :                      generate_qualified_relation_name(trigrec->tgrelid));
                               1014                 :                : 
 5763                          1015         [ -  + ]:            674 :     if (OidIsValid(trigrec->tgconstraint))
                               1016                 :                :     {
 5821 tgl@sss.pgh.pa.us        1017         [ #  # ]:UBC           0 :         if (OidIsValid(trigrec->tgconstrrelid))
 5759 itagaki.takahiro@gma     1018                 :              0 :             appendStringInfo(&buf, "FROM %s ",
                               1019                 :                :                              generate_relation_name(trigrec->tgconstrrelid, NIL));
 8258 bruce@momjian.us         1020         [ #  # ]:              0 :         if (!trigrec->tgdeferrable)
 4380 rhaas@postgresql.org     1021                 :              0 :             appendStringInfoString(&buf, "NOT ");
                               1022                 :              0 :         appendStringInfoString(&buf, "DEFERRABLE INITIALLY ");
 8258 bruce@momjian.us         1023         [ #  # ]:              0 :         if (trigrec->tginitdeferred)
 4380 rhaas@postgresql.org     1024                 :              0 :             appendStringInfoString(&buf, "DEFERRED ");
                               1025                 :                :         else
                               1026                 :              0 :             appendStringInfoString(&buf, "IMMEDIATE ");
                               1027                 :                :     }
                               1028                 :                : 
 3280 kgrittn@postgresql.o     1029                 :CBC         674 :     value = fastgetattr(ht_trig, Anum_pg_trigger_tgoldtable,
                               1030                 :                :                         tgrel->rd_att, &isnull);
                               1031         [ +  + ]:            674 :     if (!isnull)
 2566 tgl@sss.pgh.pa.us        1032                 :             49 :         tgoldtable = NameStr(*DatumGetName(value));
                               1033                 :                :     else
 3280 kgrittn@postgresql.o     1034                 :            625 :         tgoldtable = NULL;
                               1035                 :            674 :     value = fastgetattr(ht_trig, Anum_pg_trigger_tgnewtable,
                               1036                 :                :                         tgrel->rd_att, &isnull);
                               1037         [ +  + ]:            674 :     if (!isnull)
 2566 tgl@sss.pgh.pa.us        1038                 :             54 :         tgnewtable = NameStr(*DatumGetName(value));
                               1039                 :                :     else
 3280 kgrittn@postgresql.o     1040                 :            620 :         tgnewtable = NULL;
                               1041   [ +  +  +  + ]:            674 :     if (tgoldtable != NULL || tgnewtable != NULL)
                               1042                 :                :     {
                               1043                 :             76 :         appendStringInfoString(&buf, "REFERENCING ");
                               1044         [ +  + ]:             76 :         if (tgoldtable != NULL)
 2566 tgl@sss.pgh.pa.us        1045                 :             49 :             appendStringInfo(&buf, "OLD TABLE AS %s ",
                               1046                 :                :                              quote_identifier(tgoldtable));
 3280 kgrittn@postgresql.o     1047         [ +  + ]:             76 :         if (tgnewtable != NULL)
 2566 tgl@sss.pgh.pa.us        1048                 :             54 :             appendStringInfo(&buf, "NEW TABLE AS %s ",
                               1049                 :                :                              quote_identifier(tgnewtable));
                               1050                 :                :     }
                               1051                 :                : 
 8258 bruce@momjian.us         1052         [ +  + ]:            674 :     if (TRIGGER_FOR_ROW(trigrec->tgtype))
 4380 rhaas@postgresql.org     1053                 :            515 :         appendStringInfoString(&buf, "FOR EACH ROW ");
                               1054                 :                :     else
                               1055                 :            159 :         appendStringInfoString(&buf, "FOR EACH STATEMENT ");
                               1056                 :                : 
                               1057                 :                :     /* If the trigger has a WHEN qualification, add that */
 5821 tgl@sss.pgh.pa.us        1058                 :            674 :     value = fastgetattr(ht_trig, Anum_pg_trigger_tgqual,
                               1059                 :                :                         tgrel->rd_att, &isnull);
                               1060         [ +  + ]:            674 :     if (!isnull)
                               1061                 :                :     {
                               1062                 :                :         Node       *qual;
                               1063                 :                :         char        relkind;
                               1064                 :                :         deparse_context context;
                               1065                 :                :         deparse_namespace dpns;
                               1066                 :                :         RangeTblEntry *oldrte;
                               1067                 :                :         RangeTblEntry *newrte;
                               1068                 :                : 
                               1069                 :             76 :         appendStringInfoString(&buf, "WHEN (");
                               1070                 :                : 
                               1071                 :             76 :         qual = stringToNode(TextDatumGetCString(value));
                               1072                 :                : 
 5362                          1073                 :             76 :         relkind = get_rel_relkind(trigrec->tgrelid);
                               1074                 :                : 
                               1075                 :                :         /* Build minimal OLD and NEW RTEs for the rel */
 5821                          1076                 :             76 :         oldrte = makeNode(RangeTblEntry);
                               1077                 :             76 :         oldrte->rtekind = RTE_RELATION;
                               1078                 :             76 :         oldrte->relid = trigrec->tgrelid;
 5362                          1079                 :             76 :         oldrte->relkind = relkind;
 2585                          1080                 :             76 :         oldrte->rellockmode = AccessShareLock;
 4785                          1081                 :             76 :         oldrte->alias = makeAlias("old", NIL);
                               1082                 :             76 :         oldrte->eref = oldrte->alias;
 4830                          1083                 :             76 :         oldrte->lateral = false;
 5821                          1084                 :             76 :         oldrte->inh = false;
                               1085                 :             76 :         oldrte->inFromCl = true;
                               1086                 :                : 
                               1087                 :             76 :         newrte = makeNode(RangeTblEntry);
                               1088                 :             76 :         newrte->rtekind = RTE_RELATION;
                               1089                 :             76 :         newrte->relid = trigrec->tgrelid;
 5362                          1090                 :             76 :         newrte->relkind = relkind;
 2585                          1091                 :             76 :         newrte->rellockmode = AccessShareLock;
 4785                          1092                 :             76 :         newrte->alias = makeAlias("new", NIL);
                               1093                 :             76 :         newrte->eref = newrte->alias;
 4830                          1094                 :             76 :         newrte->lateral = false;
 5821                          1095                 :             76 :         newrte->inh = false;
                               1096                 :             76 :         newrte->inFromCl = true;
                               1097                 :                : 
                               1098                 :                :         /* Build two-element rtable */
 5586                          1099                 :             76 :         memset(&dpns, 0, sizeof(dpns));
 5821                          1100                 :             76 :         dpns.rtable = list_make2(oldrte, newrte);
 2148                          1101                 :             76 :         dpns.subplans = NIL;
 5821                          1102                 :             76 :         dpns.ctes = NIL;
 2148                          1103                 :             76 :         dpns.appendrels = NULL;
 4785                          1104                 :             76 :         set_rtable_names(&dpns, NIL, NULL);
 4684                          1105                 :             76 :         set_simple_column_names(&dpns);
                               1106                 :                : 
                               1107                 :                :         /* Set up context with one-deep namespace stack */
 5821                          1108                 :             76 :         context.buf = &buf;
                               1109                 :             76 :         context.namespaces = list_make1(&dpns);
  425                          1110                 :             76 :         context.resultDesc = NULL;
                               1111                 :             76 :         context.targetList = NIL;
 5821                          1112                 :             76 :         context.windowClause = NIL;
                               1113                 :             76 :         context.varprefix = true;
 1310                          1114         [ +  + ]:             76 :         context.prettyFlags = GET_PRETTY_FLAGS(pretty);
 4691                          1115                 :             76 :         context.wrapColumn = WRAP_COLUMN_DEFAULT;
 5821                          1116                 :             76 :         context.indentLevel = PRETTYINDENT_STD;
  425                          1117                 :             76 :         context.colNamesVisible = true;
                               1118                 :             76 :         context.inGroupBy = false;
                               1119                 :             76 :         context.varInOrderBy = false;
 2148                          1120                 :             76 :         context.appendparents = NULL;
                               1121                 :                : 
 5821                          1122                 :             76 :         get_rule_expr(qual, &context, false);
                               1123                 :                : 
 4380 rhaas@postgresql.org     1124                 :             76 :         appendStringInfoString(&buf, ") ");
                               1125                 :                :     }
                               1126                 :                : 
 2455 peter@eisentraut.org     1127                 :            674 :     appendStringInfo(&buf, "EXECUTE FUNCTION %s(",
                               1128                 :                :                      generate_function_name(trigrec->tgfoid, 0,
                               1129                 :                :                                             NIL, NULL,
                               1130                 :                :                                             false, NULL, false));
                               1131                 :                : 
 8197 tgl@sss.pgh.pa.us        1132         [ +  + ]:            674 :     if (trigrec->tgnargs > 0)
                               1133                 :                :     {
                               1134                 :                :         char       *p;
                               1135                 :                :         int         i;
                               1136                 :                : 
 5821                          1137                 :            205 :         value = fastgetattr(ht_trig, Anum_pg_trigger_tgargs,
                               1138                 :                :                             tgrel->rd_att, &isnull);
 8197                          1139         [ -  + ]:            205 :         if (isnull)
 8197 tgl@sss.pgh.pa.us        1140         [ #  # ]:UBC           0 :             elog(ERROR, "tgargs is null for trigger %u", trigid);
 3152 noah@leadboat.com        1141         [ +  - ]:CBC         205 :         p = (char *) VARDATA_ANY(DatumGetByteaPP(value));
 8197 tgl@sss.pgh.pa.us        1142         [ +  + ]:            466 :         for (i = 0; i < trigrec->tgnargs; i++)
                               1143                 :                :         {
                               1144         [ +  + ]:            261 :             if (i > 0)
 4380 rhaas@postgresql.org     1145                 :             56 :                 appendStringInfoString(&buf, ", ");
 6261 tgl@sss.pgh.pa.us        1146                 :            261 :             simple_quote_literal(&buf, p);
                               1147                 :                :             /* advance p to next string embedded in tgargs */
                               1148         [ +  + ]:           2686 :             while (*p)
                               1149                 :           2425 :                 p++;
 7093                          1150                 :            261 :             p++;
                               1151                 :                :         }
                               1152                 :                :     }
                               1153                 :                : 
                               1154                 :                :     /* We deliberately do not put semi-colon at end */
 4380 rhaas@postgresql.org     1155                 :            674 :     appendStringInfoChar(&buf, ')');
                               1156                 :                : 
                               1157                 :                :     /* Clean up */
 8197 tgl@sss.pgh.pa.us        1158                 :            674 :     systable_endscan(tgscan);
                               1159                 :                : 
 2472 andres@anarazel.de       1160                 :            674 :     table_close(tgrel, AccessShareLock);
                               1161                 :                : 
 5863 peter_e@gmx.net          1162                 :            674 :     return buf.data;
                               1163                 :                : }
                               1164                 :                : 
                               1165                 :                : /* ----------
                               1166                 :                :  * pg_get_indexdef          - Get the definition of an index
                               1167                 :                :  *
                               1168                 :                :  * In the extended version, there is a colno argument as well as pretty bool.
                               1169                 :                :  *  if colno == 0, we want a complete index definition.
                               1170                 :                :  *  if colno > 0, we only want the Nth index key's variable or expression.
                               1171                 :                :  *
                               1172                 :                :  * Note that the SQL-function versions of this omit any info about the
                               1173                 :                :  * index tablespace; this is intentional because pg_dump wants it that way.
                               1174                 :                :  * However pg_get_indexdef_string() includes the index tablespace.
                               1175                 :                :  * ----------
                               1176                 :                :  */
                               1177                 :                : Datum
 9272 tgl@sss.pgh.pa.us        1178                 :           2811 : pg_get_indexdef(PG_FUNCTION_ARGS)
                               1179                 :                : {
                               1180                 :           2811 :     Oid         indexrelid = PG_GETARG_OID(0);
                               1181                 :                :     int         prettyFlags;
                               1182                 :                :     char       *res;
                               1183                 :                : 
 4650                          1184                 :           2811 :     prettyFlags = PRETTYFLAG_INDENT;
                               1185                 :                : 
 2658                          1186                 :           2811 :     res = pg_get_indexdef_worker(indexrelid, 0, NULL,
                               1187                 :                :                                  false, false,
                               1188                 :                :                                  false, false,
                               1189                 :                :                                  prettyFlags, true);
                               1190                 :                : 
 3381 rhaas@postgresql.org     1191         [ +  + ]:           2811 :     if (res == NULL)
                               1192                 :              3 :         PG_RETURN_NULL();
                               1193                 :                : 
                               1194                 :           2808 :     PG_RETURN_TEXT_P(string_to_text(res));
                               1195                 :                : }
                               1196                 :                : 
                               1197                 :                : Datum
 8126 tgl@sss.pgh.pa.us        1198                 :            997 : pg_get_indexdef_ext(PG_FUNCTION_ARGS)
                               1199                 :                : {
                               1200                 :            997 :     Oid         indexrelid = PG_GETARG_OID(0);
 8121 bruce@momjian.us         1201                 :            997 :     int32       colno = PG_GETARG_INT32(1);
 8126 tgl@sss.pgh.pa.us        1202                 :            997 :     bool        pretty = PG_GETARG_BOOL(2);
                               1203                 :                :     int         prettyFlags;
                               1204                 :                :     char       *res;
                               1205                 :                : 
 1310                          1206         [ +  - ]:            997 :     prettyFlags = GET_PRETTY_FLAGS(pretty);
                               1207                 :                : 
 2658                          1208                 :            997 :     res = pg_get_indexdef_worker(indexrelid, colno, NULL,
                               1209                 :                :                                  colno != 0, false,
                               1210                 :                :                                  false, false,
                               1211                 :                :                                  prettyFlags, true);
                               1212                 :                : 
 3381 rhaas@postgresql.org     1213         [ -  + ]:            997 :     if (res == NULL)
 3381 rhaas@postgresql.org     1214                 :UBC           0 :         PG_RETURN_NULL();
                               1215                 :                : 
 3381 rhaas@postgresql.org     1216                 :CBC         997 :     PG_RETURN_TEXT_P(string_to_text(res));
                               1217                 :                : }
                               1218                 :                : 
                               1219                 :                : /*
                               1220                 :                :  * Internal version for use by ALTER TABLE.
                               1221                 :                :  * Includes a tablespace clause in the result.
                               1222                 :                :  * Returns a palloc'd C string; no pretty-printing.
                               1223                 :                :  */
                               1224                 :                : char *
 7846 tgl@sss.pgh.pa.us        1225                 :            114 : pg_get_indexdef_string(Oid indexrelid)
                               1226                 :                : {
 2658                          1227                 :            114 :     return pg_get_indexdef_worker(indexrelid, 0, NULL,
                               1228                 :                :                                   false, false,
                               1229                 :                :                                   true, true,
                               1230                 :                :                                   0, false);
                               1231                 :                : }
                               1232                 :                : 
                               1233                 :                : /* Internal version that just reports the key-column definitions */
                               1234                 :                : char *
 5932                          1235                 :            533 : pg_get_indexdef_columns(Oid indexrelid, bool pretty)
                               1236                 :                : {
                               1237                 :                :     int         prettyFlags;
                               1238                 :                : 
 1310                          1239         [ +  - ]:            533 :     prettyFlags = GET_PRETTY_FLAGS(pretty);
                               1240                 :                : 
 2658                          1241                 :            533 :     return pg_get_indexdef_worker(indexrelid, 0, NULL,
                               1242                 :                :                                   true, true,
                               1243                 :                :                                   false, false,
                               1244                 :                :                                   prettyFlags, false);
                               1245                 :                : }
                               1246                 :                : 
                               1247                 :                : /* Internal version, extensible with flags to control its behavior */
                               1248                 :                : char *
  893 michael@paquier.xyz      1249                 :              4 : pg_get_indexdef_columns_extended(Oid indexrelid, bits16 flags)
                               1250                 :                : {
                               1251                 :              4 :     bool        pretty = ((flags & RULE_INDEXDEF_PRETTY) != 0);
                               1252                 :              4 :     bool        keys_only = ((flags & RULE_INDEXDEF_KEYS_ONLY) != 0);
                               1253                 :                :     int         prettyFlags;
                               1254                 :                : 
                               1255         [ +  - ]:              4 :     prettyFlags = GET_PRETTY_FLAGS(pretty);
                               1256                 :                : 
                               1257                 :              4 :     return pg_get_indexdef_worker(indexrelid, 0, NULL,
                               1258                 :                :                                   true, keys_only,
                               1259                 :                :                                   false, false,
                               1260                 :                :                                   prettyFlags, false);
                               1261                 :                : }
                               1262                 :                : 
                               1263                 :                : /*
                               1264                 :                :  * Internal workhorse to decompile an index definition.
                               1265                 :                :  *
                               1266                 :                :  * This is now used for exclusion constraints as well: if excludeOps is not
                               1267                 :                :  * NULL then it points to an array of exclusion operator OIDs.
                               1268                 :                :  */
                               1269                 :                : static char *
 5932 tgl@sss.pgh.pa.us        1270                 :           4511 : pg_get_indexdef_worker(Oid indexrelid, int colno,
                               1271                 :                :                        const Oid *excludeOps,
                               1272                 :                :                        bool attrsOnly, bool keysOnly,
                               1273                 :                :                        bool showTblSpc, bool inherits,
                               1274                 :                :                        int prettyFlags, bool missing_ok)
                               1275                 :                : {
                               1276                 :                :     /* might want a separate isConstraint parameter later */
 5804                          1277                 :           4511 :     bool        isConstraint = (excludeOps != NULL);
                               1278                 :                :     HeapTuple   ht_idx;
                               1279                 :                :     HeapTuple   ht_idxrel;
                               1280                 :                :     HeapTuple   ht_am;
                               1281                 :                :     Form_pg_index idxrec;
                               1282                 :                :     Form_pg_class idxrelrec;
                               1283                 :                :     Form_pg_am  amrec;
                               1284                 :                :     IndexAmRoutine *amroutine;
                               1285                 :                :     List       *indexprs;
                               1286                 :                :     ListCell   *indexpr_item;
                               1287                 :                :     List       *context;
                               1288                 :                :     Oid         indrelid;
                               1289                 :                :     int         keyno;
                               1290                 :                :     Datum       indcollDatum;
                               1291                 :                :     Datum       indclassDatum;
                               1292                 :                :     Datum       indoptionDatum;
                               1293                 :                :     oidvector  *indcollation;
                               1294                 :                :     oidvector  *indclass;
                               1295                 :                :     int2vector *indoption;
                               1296                 :                :     StringInfoData buf;
                               1297                 :                :     char       *str;
                               1298                 :                :     char       *sep;
                               1299                 :                : 
                               1300                 :                :     /*
                               1301                 :                :      * Fetch the pg_index tuple by the Oid of the index
                               1302                 :                :      */
 5735 rhaas@postgresql.org     1303                 :           4511 :     ht_idx = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexrelid));
 9888 bruce@momjian.us         1304         [ +  + ]:           4511 :     if (!HeapTupleIsValid(ht_idx))
                               1305                 :                :     {
 3381 rhaas@postgresql.org     1306         [ +  - ]:              3 :         if (missing_ok)
                               1307                 :              3 :             return NULL;
 8129 tgl@sss.pgh.pa.us        1308         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for index %u", indexrelid);
                               1309                 :                :     }
 9653 bruce@momjian.us         1310                 :CBC        4508 :     idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
                               1311                 :                : 
 8579 tgl@sss.pgh.pa.us        1312                 :           4508 :     indrelid = idxrec->indrelid;
                               1313         [ -  + ]:           4508 :     Assert(indexrelid == idxrec->indexrelid);
                               1314                 :                : 
                               1315                 :                :     /* Must get indcollation, indclass, and indoption the hard way */
  948 dgustafsson@postgres     1316                 :           4508 :     indcollDatum = SysCacheGetAttrNotNull(INDEXRELID, ht_idx,
                               1317                 :                :                                           Anum_pg_index_indcollation);
 5376 peter_e@gmx.net          1318                 :           4508 :     indcollation = (oidvector *) DatumGetPointer(indcollDatum);
                               1319                 :                : 
  948 dgustafsson@postgres     1320                 :           4508 :     indclassDatum = SysCacheGetAttrNotNull(INDEXRELID, ht_idx,
                               1321                 :                :                                            Anum_pg_index_indclass);
 7518 tgl@sss.pgh.pa.us        1322                 :           4508 :     indclass = (oidvector *) DatumGetPointer(indclassDatum);
                               1323                 :                : 
  948 dgustafsson@postgres     1324                 :           4508 :     indoptionDatum = SysCacheGetAttrNotNull(INDEXRELID, ht_idx,
                               1325                 :                :                                             Anum_pg_index_indoption);
 6867 tgl@sss.pgh.pa.us        1326                 :           4508 :     indoption = (int2vector *) DatumGetPointer(indoptionDatum);
                               1327                 :                : 
                               1328                 :                :     /*
                               1329                 :                :      * Fetch the pg_class tuple of the index relation
                               1330                 :                :      */
 5735 rhaas@postgresql.org     1331                 :           4508 :     ht_idxrel = SearchSysCache1(RELOID, ObjectIdGetDatum(indexrelid));
 9888 bruce@momjian.us         1332         [ -  + ]:           4508 :     if (!HeapTupleIsValid(ht_idxrel))
 8129 tgl@sss.pgh.pa.us        1333         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for relation %u", indexrelid);
 9653 bruce@momjian.us         1334                 :CBC        4508 :     idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
                               1335                 :                : 
                               1336                 :                :     /*
                               1337                 :                :      * Fetch the pg_am tuple of the index' access method
                               1338                 :                :      */
 5735 rhaas@postgresql.org     1339                 :           4508 :     ht_am = SearchSysCache1(AMOID, ObjectIdGetDatum(idxrelrec->relam));
 8652 tgl@sss.pgh.pa.us        1340         [ -  + ]:           4508 :     if (!HeapTupleIsValid(ht_am))
 8129 tgl@sss.pgh.pa.us        1341         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for access method %u",
                               1342                 :                :              idxrelrec->relam);
 8652 tgl@sss.pgh.pa.us        1343                 :CBC        4508 :     amrec = (Form_pg_am) GETSTRUCT(ht_am);
                               1344                 :                : 
                               1345                 :                :     /* Fetch the index AM's API struct */
 3572                          1346                 :           4508 :     amroutine = GetIndexAmRoutine(amrec->amhandler);
                               1347                 :                : 
                               1348                 :                :     /*
                               1349                 :                :      * Get the index expressions, if any.  (NOTE: we do not use the relcache
                               1350                 :                :      * versions of the expressions and predicate, because we want to display
                               1351                 :                :      * non-const-folded expressions.)
                               1352                 :                :      */
 2771 andrew@dunslane.net      1353         [ +  + ]:           4508 :     if (!heap_attisnull(ht_idx, Anum_pg_index_indexprs, NULL))
                               1354                 :                :     {
                               1355                 :                :         Datum       exprsDatum;
                               1356                 :                :         char       *exprsString;
                               1357                 :                : 
  948 dgustafsson@postgres     1358                 :            326 :         exprsDatum = SysCacheGetAttrNotNull(INDEXRELID, ht_idx,
                               1359                 :                :                                             Anum_pg_index_indexprs);
 6426 tgl@sss.pgh.pa.us        1360                 :            326 :         exprsString = TextDatumGetCString(exprsDatum);
 8189                          1361                 :            326 :         indexprs = (List *) stringToNode(exprsString);
                               1362                 :            326 :         pfree(exprsString);
                               1363                 :                :     }
                               1364                 :                :     else
                               1365                 :           4182 :         indexprs = NIL;
                               1366                 :                : 
 7825 neilc@samurai.com        1367                 :           4508 :     indexpr_item = list_head(indexprs);
                               1368                 :                : 
 5474 tgl@sss.pgh.pa.us        1369                 :           4508 :     context = deparse_context_for(get_relation_name(indrelid), indrelid);
                               1370                 :                : 
                               1371                 :                :     /*
                               1372                 :                :      * Start the index definition.  Note that the index's name should never be
                               1373                 :                :      * schema-qualified, but the indexed rel's name may be.
                               1374                 :                :      */
 9523                          1375                 :           4508 :     initStringInfo(&buf);
                               1376                 :                : 
 5932                          1377         [ +  + ]:           4508 :     if (!attrsOnly)
                               1378                 :                :     {
 5804                          1379         [ +  + ]:           3740 :         if (!isConstraint)
 2839 alvherre@alvh.no-ip.     1380                 :           7376 :             appendStringInfo(&buf, "CREATE %sINDEX %s ON %s%s USING %s (",
 5804 tgl@sss.pgh.pa.us        1381         [ +  + ]:           3688 :                              idxrec->indisunique ? "UNIQUE " : "",
                               1382                 :           3688 :                              quote_identifier(NameStr(idxrelrec->relname)),
 2839 alvherre@alvh.no-ip.     1383         [ +  + ]:           3688 :                              idxrelrec->relkind == RELKIND_PARTITIONED_INDEX
                               1384         [ +  + ]:            335 :                              && !inherits ? "ONLY " : "",
 2801 tgl@sss.pgh.pa.us        1385         [ +  + ]:           3688 :                              (prettyFlags & PRETTYFLAG_SCHEMA) ?
                               1386                 :            766 :                              generate_relation_name(indrelid, NIL) :
                               1387                 :           2922 :                              generate_qualified_relation_name(indrelid),
 5804                          1388                 :           3688 :                              quote_identifier(NameStr(amrec->amname)));
                               1389                 :                :         else                    /* currently, must be EXCLUDE constraint */
                               1390                 :             52 :             appendStringInfo(&buf, "EXCLUDE USING %s (",
                               1391                 :             52 :                              quote_identifier(NameStr(amrec->amname)));
                               1392                 :                :     }
                               1393                 :                : 
                               1394                 :                :     /*
                               1395                 :                :      * Report the indexed attributes
                               1396                 :                :      */
 9888 bruce@momjian.us         1397                 :           4508 :     sep = "";
 8189 tgl@sss.pgh.pa.us        1398         [ +  + ]:          11319 :     for (keyno = 0; keyno < idxrec->indnatts; keyno++)
                               1399                 :                :     {
 7518                          1400                 :           6860 :         AttrNumber  attnum = idxrec->indkey.values[keyno];
                               1401                 :                :         Oid         keycoltype;
                               1402                 :                :         Oid         keycolcollation;
                               1403                 :                : 
                               1404                 :                :         /*
                               1405                 :                :          * Ignore non-key attributes if told to.
                               1406                 :                :          */
 2658                          1407   [ +  +  +  + ]:           6860 :         if (keysOnly && keyno >= idxrec->indnkeyatts)
 2761 teodor@sigaev.ru         1408                 :             49 :             break;
                               1409                 :                : 
                               1410                 :                :         /* Otherwise, print INCLUDE to divide key and non-key attrs. */
 2658 tgl@sss.pgh.pa.us        1411   [ +  +  +  + ]:           6811 :         if (!colno && keyno == idxrec->indnkeyatts)
                               1412                 :                :         {
 2761 teodor@sigaev.ru         1413                 :            125 :             appendStringInfoString(&buf, ") INCLUDE (");
                               1414                 :            125 :             sep = "";
                               1415                 :                :         }
                               1416                 :                : 
 8126 tgl@sss.pgh.pa.us        1417         [ +  + ]:           6811 :         if (!colno)
 7486 neilc@samurai.com        1418                 :           6490 :             appendStringInfoString(&buf, sep);
 9888 bruce@momjian.us         1419                 :           6811 :         sep = ", ";
                               1420                 :                : 
 8189 tgl@sss.pgh.pa.us        1421         [ +  + ]:           6811 :         if (attnum != 0)
                               1422                 :                :         {
                               1423                 :                :             /* Simple index column */
                               1424                 :                :             char       *attname;
                               1425                 :                :             int32       keycoltypmod;
                               1426                 :                : 
 2815 alvherre@alvh.no-ip.     1427                 :           6408 :             attname = get_attname(indrelid, attnum, false);
 8121 bruce@momjian.us         1428   [ +  +  +  + ]:           6408 :             if (!colno || colno == keyno + 1)
 7941 neilc@samurai.com        1429                 :           6324 :                 appendStringInfoString(&buf, quote_identifier(attname));
 5330 tgl@sss.pgh.pa.us        1430                 :           6408 :             get_atttypetypmodcoll(indrelid, attnum,
                               1431                 :                :                                   &keycoltype, &keycoltypmod,
                               1432                 :                :                                   &keycolcollation);
                               1433                 :                :         }
                               1434                 :                :         else
                               1435                 :                :         {
                               1436                 :                :             /* expressional index */
                               1437                 :                :             Node       *indexkey;
                               1438                 :                : 
 7825 neilc@samurai.com        1439         [ -  + ]:            403 :             if (indexpr_item == NULL)
 8189 tgl@sss.pgh.pa.us        1440         [ #  # ]:UBC           0 :                 elog(ERROR, "too few entries in indexprs list");
 7825 neilc@samurai.com        1441                 :CBC         403 :             indexkey = (Node *) lfirst(indexpr_item);
 2297 tgl@sss.pgh.pa.us        1442                 :            403 :             indexpr_item = lnext(indexprs, indexpr_item);
                               1443                 :                :             /* Deparse */
 8126                          1444                 :            403 :             str = deparse_expression_pretty(indexkey, context, false, false,
                               1445                 :                :                                             prettyFlags, 0);
 8121 bruce@momjian.us         1446   [ +  +  +  + ]:            403 :             if (!colno || colno == keyno + 1)
                               1447                 :                :             {
                               1448                 :                :                 /* Need parens if it's not a bare function call */
 3029 tgl@sss.pgh.pa.us        1449         [ +  + ]:            397 :                 if (looks_like_function(indexkey))
 7941 neilc@samurai.com        1450                 :             26 :                     appendStringInfoString(&buf, str);
                               1451                 :                :                 else
 8126 tgl@sss.pgh.pa.us        1452                 :            371 :                     appendStringInfo(&buf, "(%s)", str);
                               1453                 :                :             }
 8189                          1454                 :            403 :             keycoltype = exprType(indexkey);
 5332                          1455                 :            403 :             keycolcollation = exprCollation(indexkey);
                               1456                 :                :         }
                               1457                 :                : 
                               1458                 :                :         /* Print additional decoration for (selected) key columns */
 2658                          1459   [ +  +  +  +  :           6811 :         if (!attrsOnly && keyno < idxrec->indnkeyatts &&
                                              -  + ]
 2658 tgl@sss.pgh.pa.us        1460         [ #  # ]:UBC           0 :             (!colno || colno == keyno + 1))
                               1461                 :                :         {
 2396 tgl@sss.pgh.pa.us        1462                 :CBC        5540 :             int16       opt = indoption->values[keyno];
                               1463                 :           5540 :             Oid         indcoll = indcollation->values[keyno];
 2038 akorotkov@postgresql     1464                 :           5540 :             Datum       attoptions = get_attoptions(indexrelid, keyno + 1);
                               1465                 :           5540 :             bool        has_options = attoptions != (Datum) 0;
                               1466                 :                : 
                               1467                 :                :             /* Add collation, if not default for column */
 5332 tgl@sss.pgh.pa.us        1468   [ +  +  +  + ]:           5540 :             if (OidIsValid(indcoll) && indcoll != keycolcollation)
                               1469                 :             47 :                 appendStringInfo(&buf, " COLLATE %s",
                               1470                 :                :                                  generate_collation_name((indcoll)));
                               1471                 :                : 
                               1472                 :                :             /* Add the operator class name, if not default */
 2038 akorotkov@postgresql     1473         [ +  + ]:           5540 :             get_opclass_name(indclass->values[keyno],
                               1474                 :                :                              has_options ? InvalidOid : keycoltype, &buf);
                               1475                 :                : 
                               1476         [ +  + ]:           5540 :             if (has_options)
                               1477                 :                :             {
                               1478                 :             17 :                 appendStringInfoString(&buf, " (");
                               1479                 :             17 :                 get_reloptions(&buf, attoptions);
                               1480                 :             17 :                 appendStringInfoChar(&buf, ')');
                               1481                 :                :             }
                               1482                 :                : 
                               1483                 :                :             /* Add options if relevant */
 3572 tgl@sss.pgh.pa.us        1484         [ +  + ]:           5540 :             if (amroutine->amcanorder)
                               1485                 :                :             {
                               1486                 :                :                 /* if it supports sort ordering, report DESC and NULLS opts */
 6522                          1487         [ -  + ]:           4492 :                 if (opt & INDOPTION_DESC)
                               1488                 :                :                 {
 4380 rhaas@postgresql.org     1489                 :UBC           0 :                     appendStringInfoString(&buf, " DESC");
                               1490                 :                :                     /* NULLS FIRST is the default in this case */
 6522 tgl@sss.pgh.pa.us        1491         [ #  # ]:              0 :                     if (!(opt & INDOPTION_NULLS_FIRST))
 4380 rhaas@postgresql.org     1492                 :              0 :                         appendStringInfoString(&buf, " NULLS LAST");
                               1493                 :                :                 }
                               1494                 :                :                 else
                               1495                 :                :                 {
 6522 tgl@sss.pgh.pa.us        1496         [ -  + ]:CBC        4492 :                     if (opt & INDOPTION_NULLS_FIRST)
 4380 rhaas@postgresql.org     1497                 :UBC           0 :                         appendStringInfoString(&buf, " NULLS FIRST");
                               1498                 :                :                 }
                               1499                 :                :             }
                               1500                 :                : 
                               1501                 :                :             /* Add the exclusion operator if relevant */
 5804 tgl@sss.pgh.pa.us        1502         [ +  + ]:CBC        5540 :             if (excludeOps != NULL)
                               1503                 :             62 :                 appendStringInfo(&buf, " WITH %s",
                               1504                 :             62 :                                  generate_operator_name(excludeOps[keyno],
                               1505                 :                :                                                         keycoltype,
                               1506                 :                :                                                         keycoltype));
                               1507                 :                :         }
                               1508                 :                :     }
                               1509                 :                : 
 5932                          1510         [ +  + ]:           4508 :     if (!attrsOnly)
                               1511                 :                :     {
 8121 bruce@momjian.us         1512                 :           3740 :         appendStringInfoChar(&buf, ')');
                               1513                 :                : 
 1363 peter@eisentraut.org     1514         [ +  + ]:           3740 :         if (idxrec->indnullsnotdistinct)
 1148 drowley@postgresql.o     1515                 :              6 :             appendStringInfoString(&buf, " NULLS NOT DISTINCT");
                               1516                 :                : 
                               1517                 :                :         /*
                               1518                 :                :          * If it has options, append "WITH (options)"
                               1519                 :                :          */
 7057 tgl@sss.pgh.pa.us        1520                 :           3740 :         str = flatten_reloptions(indexrelid);
                               1521         [ +  + ]:           3740 :         if (str)
                               1522                 :                :         {
                               1523                 :            105 :             appendStringInfo(&buf, " WITH (%s)", str);
                               1524                 :            105 :             pfree(str);
                               1525                 :                :         }
                               1526                 :                : 
                               1527                 :                :         /*
                               1528                 :                :          * Print tablespace, but only if requested
                               1529                 :                :          */
 6590                          1530         [ +  + ]:           3740 :         if (showTblSpc)
                               1531                 :                :         {
                               1532                 :                :             Oid         tblspc;
                               1533                 :                : 
                               1534                 :            114 :             tblspc = get_rel_tablespace(indexrelid);
 2378 alvherre@alvh.no-ip.     1535         [ +  + ]:            114 :             if (OidIsValid(tblspc))
                               1536                 :                :             {
                               1537         [ -  + ]:             27 :                 if (isConstraint)
 2378 alvherre@alvh.no-ip.     1538                 :UBC           0 :                     appendStringInfoString(&buf, " USING INDEX");
 2378 alvherre@alvh.no-ip.     1539                 :CBC          27 :                 appendStringInfo(&buf, " TABLESPACE %s",
                               1540                 :             27 :                                  quote_identifier(get_tablespace_name(tblspc)));
                               1541                 :                :             }
                               1542                 :                :         }
                               1543                 :                : 
                               1544                 :                :         /*
                               1545                 :                :          * If it's a partial index, decompile and append the predicate
                               1546                 :                :          */
 2771 andrew@dunslane.net      1547         [ +  + ]:           3740 :         if (!heap_attisnull(ht_idx, Anum_pg_index_indpred, NULL))
                               1548                 :                :         {
                               1549                 :                :             Node       *node;
                               1550                 :                :             Datum       predDatum;
                               1551                 :                :             char       *predString;
                               1552                 :                : 
                               1553                 :                :             /* Convert text string to node tree */
  948 dgustafsson@postgres     1554                 :            157 :             predDatum = SysCacheGetAttrNotNull(INDEXRELID, ht_idx,
                               1555                 :                :                                                Anum_pg_index_indpred);
 6426 tgl@sss.pgh.pa.us        1556                 :            157 :             predString = TextDatumGetCString(predDatum);
 8126                          1557                 :            157 :             node = (Node *) stringToNode(predString);
                               1558                 :            157 :             pfree(predString);
                               1559                 :                : 
                               1560                 :                :             /* Deparse */
                               1561                 :            157 :             str = deparse_expression_pretty(node, context, false, false,
                               1562                 :                :                                             prettyFlags, 0);
 5804                          1563         [ +  + ]:            157 :             if (isConstraint)
                               1564                 :             21 :                 appendStringInfo(&buf, " WHERE (%s)", str);
                               1565                 :                :             else
                               1566                 :            136 :                 appendStringInfo(&buf, " WHERE %s", str);
                               1567                 :                :         }
                               1568                 :                :     }
                               1569                 :                : 
                               1570                 :                :     /* Clean up */
 9112                          1571                 :           4508 :     ReleaseSysCache(ht_idx);
                               1572                 :           4508 :     ReleaseSysCache(ht_idxrel);
 8652                          1573                 :           4508 :     ReleaseSysCache(ht_am);
                               1574                 :                : 
 7846                          1575                 :           4508 :     return buf.data;
                               1576                 :                : }
                               1577                 :                : 
                               1578                 :                : /* ----------
                               1579                 :                :  * pg_get_querydef
                               1580                 :                :  *
                               1581                 :                :  * Public entry point to deparse one query parsetree.
                               1582                 :                :  * The pretty flags are determined by GET_PRETTY_FLAGS(pretty).
                               1583                 :                :  *
                               1584                 :                :  * The result is a palloc'd C string.
                               1585                 :                :  * ----------
                               1586                 :                :  */
                               1587                 :                : char *
 1310 tgl@sss.pgh.pa.us        1588                 :UBC           0 : pg_get_querydef(Query *query, bool pretty)
                               1589                 :                : {
                               1590                 :                :     StringInfoData buf;
                               1591                 :                :     int         prettyFlags;
                               1592                 :                : 
                               1593         [ #  # ]:              0 :     prettyFlags = GET_PRETTY_FLAGS(pretty);
                               1594                 :                : 
                               1595                 :              0 :     initStringInfo(&buf);
                               1596                 :                : 
 1256                          1597                 :              0 :     get_query_def(query, &buf, NIL, NULL, true,
                               1598                 :                :                   prettyFlags, WRAP_COLUMN_DEFAULT, 0);
                               1599                 :                : 
 1310                          1600                 :              0 :     return buf.data;
                               1601                 :                : }
                               1602                 :                : 
                               1603                 :                : /*
                               1604                 :                :  * pg_get_statisticsobjdef
                               1605                 :                :  *      Get the definition of an extended statistics object
                               1606                 :                :  */
                               1607                 :                : Datum
 3089 tgl@sss.pgh.pa.us        1608                 :CBC         121 : pg_get_statisticsobjdef(PG_FUNCTION_ARGS)
                               1609                 :                : {
 3140 alvherre@alvh.no-ip.     1610                 :            121 :     Oid         statextid = PG_GETARG_OID(0);
                               1611                 :                :     char       *res;
                               1612                 :                : 
 1677 tomas.vondra@postgre     1613                 :            121 :     res = pg_get_statisticsobj_worker(statextid, false, true);
                               1614                 :                : 
                               1615         [ +  + ]:            121 :     if (res == NULL)
                               1616                 :              3 :         PG_RETURN_NULL();
                               1617                 :                : 
                               1618                 :            118 :     PG_RETURN_TEXT_P(string_to_text(res));
                               1619                 :                : }
                               1620                 :                : 
                               1621                 :                : /*
                               1622                 :                :  * Internal version for use by ALTER TABLE.
                               1623                 :                :  * Returns a palloc'd C string; no pretty-printing.
                               1624                 :                :  */
                               1625                 :                : char *
                               1626                 :             13 : pg_get_statisticsobjdef_string(Oid statextid)
                               1627                 :                : {
                               1628                 :             13 :     return pg_get_statisticsobj_worker(statextid, false, false);
                               1629                 :                : }
                               1630                 :                : 
                               1631                 :                : /*
                               1632                 :                :  * pg_get_statisticsobjdef_columns
                               1633                 :                :  *      Get columns and expressions for an extended statistics object
                               1634                 :                :  */
                               1635                 :                : Datum
                               1636                 :            207 : pg_get_statisticsobjdef_columns(PG_FUNCTION_ARGS)
                               1637                 :                : {
                               1638                 :            207 :     Oid         statextid = PG_GETARG_OID(0);
                               1639                 :                :     char       *res;
                               1640                 :                : 
                               1641                 :            207 :     res = pg_get_statisticsobj_worker(statextid, true, true);
                               1642                 :                : 
 3140 alvherre@alvh.no-ip.     1643         [ -  + ]:            207 :     if (res == NULL)
 3140 alvherre@alvh.no-ip.     1644                 :UBC           0 :         PG_RETURN_NULL();
                               1645                 :                : 
 3140 alvherre@alvh.no-ip.     1646                 :CBC         207 :     PG_RETURN_TEXT_P(string_to_text(res));
                               1647                 :                : }
                               1648                 :                : 
                               1649                 :                : /*
                               1650                 :                :  * Internal workhorse to decompile an extended statistics object.
                               1651                 :                :  */
                               1652                 :                : static char *
 1677 tomas.vondra@postgre     1653                 :            341 : pg_get_statisticsobj_worker(Oid statextid, bool columns_only, bool missing_ok)
                               1654                 :                : {
                               1655                 :                :     Form_pg_statistic_ext statextrec;
                               1656                 :                :     HeapTuple   statexttup;
                               1657                 :                :     StringInfoData buf;
                               1658                 :                :     int         colno;
                               1659                 :                :     char       *nsp;
                               1660                 :                :     ArrayType  *arr;
                               1661                 :                :     char       *enabled;
                               1662                 :                :     Datum       datum;
                               1663                 :                :     bool        ndistinct_enabled;
                               1664                 :                :     bool        dependencies_enabled;
                               1665                 :                :     bool        mcv_enabled;
                               1666                 :                :     int         i;
                               1667                 :                :     List       *context;
                               1668                 :                :     ListCell   *lc;
                               1669                 :            341 :     List       *exprs = NIL;
                               1670                 :                :     bool        has_exprs;
                               1671                 :                :     int         ncolumns;
                               1672                 :                : 
 3140 alvherre@alvh.no-ip.     1673                 :            341 :     statexttup = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(statextid));
                               1674                 :                : 
                               1675         [ +  + ]:            341 :     if (!HeapTupleIsValid(statexttup))
                               1676                 :                :     {
                               1677         [ +  - ]:              3 :         if (missing_ok)
                               1678                 :              3 :             return NULL;
 3089 tgl@sss.pgh.pa.us        1679         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for statistics object %u", statextid);
                               1680                 :                :     }
                               1681                 :                : 
                               1682                 :                :     /* has the statistics expressions? */
 1677 tomas.vondra@postgre     1683                 :CBC         338 :     has_exprs = !heap_attisnull(statexttup, Anum_pg_statistic_ext_stxexprs, NULL);
                               1684                 :                : 
                               1685                 :            338 :     statextrec = (Form_pg_statistic_ext) GETSTRUCT(statexttup);
                               1686                 :                : 
                               1687                 :                :     /*
                               1688                 :                :      * Get the statistics expressions, if any.  (NOTE: we do not use the
                               1689                 :                :      * relcache versions of the expressions, because we want to display
                               1690                 :                :      * non-const-folded expressions.)
                               1691                 :                :      */
                               1692         [ +  + ]:            338 :     if (has_exprs)
                               1693                 :                :     {
                               1694                 :                :         Datum       exprsDatum;
                               1695                 :                :         char       *exprsString;
                               1696                 :                : 
  948 dgustafsson@postgres     1697                 :             76 :         exprsDatum = SysCacheGetAttrNotNull(STATEXTOID, statexttup,
                               1698                 :                :                                             Anum_pg_statistic_ext_stxexprs);
 1677 tomas.vondra@postgre     1699                 :             76 :         exprsString = TextDatumGetCString(exprsDatum);
                               1700                 :             76 :         exprs = (List *) stringToNode(exprsString);
                               1701                 :             76 :         pfree(exprsString);
                               1702                 :                :     }
                               1703                 :                :     else
                               1704                 :            262 :         exprs = NIL;
                               1705                 :                : 
                               1706                 :                :     /* count the number of columns (attributes and expressions) */
                               1707                 :            338 :     ncolumns = statextrec->stxkeys.dim1 + list_length(exprs);
                               1708                 :                : 
                               1709                 :            338 :     initStringInfo(&buf);
                               1710                 :                : 
                               1711         [ +  + ]:            338 :     if (!columns_only)
                               1712                 :                :     {
 1554 tgl@sss.pgh.pa.us        1713                 :            131 :         nsp = get_namespace_name_or_temp(statextrec->stxnamespace);
 1677 tomas.vondra@postgre     1714                 :            131 :         appendStringInfo(&buf, "CREATE STATISTICS %s",
                               1715                 :                :                          quote_qualified_identifier(nsp,
                               1716                 :            131 :                                                     NameStr(statextrec->stxname)));
                               1717                 :                : 
                               1718                 :                :         /*
                               1719                 :                :          * Decode the stxkind column so that we know which stats types to
                               1720                 :                :          * print.
                               1721                 :                :          */
  948 dgustafsson@postgres     1722                 :            131 :         datum = SysCacheGetAttrNotNull(STATEXTOID, statexttup,
                               1723                 :                :                                        Anum_pg_statistic_ext_stxkind);
 1677 tomas.vondra@postgre     1724                 :            131 :         arr = DatumGetArrayTypeP(datum);
                               1725         [ +  - ]:            131 :         if (ARR_NDIM(arr) != 1 ||
                               1726         [ +  - ]:            131 :             ARR_HASNULL(arr) ||
                               1727         [ -  + ]:            131 :             ARR_ELEMTYPE(arr) != CHAROID)
 1677 tomas.vondra@postgre     1728         [ #  # ]:UBC           0 :             elog(ERROR, "stxkind is not a 1-D char array");
 1677 tomas.vondra@postgre     1729         [ -  + ]:CBC         131 :         enabled = (char *) ARR_DATA_PTR(arr);
                               1730                 :                : 
                               1731                 :            131 :         ndistinct_enabled = false;
                               1732                 :            131 :         dependencies_enabled = false;
                               1733                 :            131 :         mcv_enabled = false;
                               1734                 :                : 
                               1735         [ +  + ]:            335 :         for (i = 0; i < ARR_DIMS(arr)[0]; i++)
                               1736                 :                :         {
                               1737         [ +  + ]:            204 :             if (enabled[i] == STATS_EXT_NDISTINCT)
                               1738                 :             66 :                 ndistinct_enabled = true;
                               1739         [ +  + ]:            138 :             else if (enabled[i] == STATS_EXT_DEPENDENCIES)
                               1740                 :             43 :                 dependencies_enabled = true;
                               1741         [ +  + ]:             95 :             else if (enabled[i] == STATS_EXT_MCV)
                               1742                 :             52 :                 mcv_enabled = true;
                               1743                 :                : 
                               1744                 :                :             /* ignore STATS_EXT_EXPRESSIONS (it's built automatically) */
                               1745                 :                :         }
                               1746                 :                : 
                               1747                 :                :         /*
                               1748                 :                :          * If any option is disabled, then we'll need to append the types
                               1749                 :                :          * clause to show which options are enabled.  We omit the types clause
                               1750                 :                :          * on purpose when all options are enabled, so a pg_dump/pg_restore
                               1751                 :                :          * will create all statistics types on a newer postgres version, if
                               1752                 :                :          * the statistics had all options enabled on the original version.
                               1753                 :                :          *
                               1754                 :                :          * But if the statistics is defined on just a single column, it has to
                               1755                 :                :          * be an expression statistics. In that case we don't need to specify
                               1756                 :                :          * kinds.
                               1757                 :                :          */
                               1758   [ +  +  +  +  :            131 :         if ((!ndistinct_enabled || !dependencies_enabled || !mcv_enabled) &&
                                        -  +  +  + ]
                               1759                 :                :             (ncolumns > 1))
                               1760                 :                :         {
                               1761                 :             59 :             bool        gotone = false;
                               1762                 :                : 
                               1763                 :             59 :             appendStringInfoString(&buf, " (");
                               1764                 :                : 
                               1765         [ +  + ]:             59 :             if (ndistinct_enabled)
                               1766                 :                :             {
                               1767                 :             32 :                 appendStringInfoString(&buf, "ndistinct");
                               1768                 :             32 :                 gotone = true;
                               1769                 :                :             }
                               1770                 :                : 
                               1771         [ +  + ]:             59 :             if (dependencies_enabled)
                               1772                 :                :             {
                               1773         [ -  + ]:              9 :                 appendStringInfo(&buf, "%sdependencies", gotone ? ", " : "");
                               1774                 :              9 :                 gotone = true;
                               1775                 :                :             }
                               1776                 :                : 
                               1777         [ +  + ]:             59 :             if (mcv_enabled)
                               1778         [ -  + ]:             18 :                 appendStringInfo(&buf, "%smcv", gotone ? ", " : "");
                               1779                 :                : 
                               1780                 :             59 :             appendStringInfoChar(&buf, ')');
                               1781                 :                :         }
                               1782                 :                : 
                               1783                 :            131 :         appendStringInfoString(&buf, " ON ");
                               1784                 :                :     }
                               1785                 :                : 
                               1786                 :                :     /* decode simple column references */
 3116 alvherre@alvh.no-ip.     1787         [ +  + ]:            952 :     for (colno = 0; colno < statextrec->stxkeys.dim1; colno++)
                               1788                 :                :     {
                               1789                 :            614 :         AttrNumber  attnum = statextrec->stxkeys.values[colno];
                               1790                 :                :         char       *attname;
                               1791                 :                : 
 3140                          1792         [ +  + ]:            614 :         if (colno > 0)
                               1793                 :            346 :             appendStringInfoString(&buf, ", ");
                               1794                 :                : 
 2815                          1795                 :            614 :         attname = get_attname(statextrec->stxrelid, attnum, false);
                               1796                 :                : 
 3140                          1797                 :            614 :         appendStringInfoString(&buf, quote_identifier(attname));
                               1798                 :                :     }
                               1799                 :                : 
 1677 tomas.vondra@postgre     1800                 :            338 :     context = deparse_context_for(get_relation_name(statextrec->stxrelid),
                               1801                 :                :                                   statextrec->stxrelid);
                               1802                 :                : 
                               1803   [ +  +  +  +  :            457 :     foreach(lc, exprs)
                                              +  + ]
                               1804                 :                :     {
                               1805                 :            119 :         Node       *expr = (Node *) lfirst(lc);
                               1806                 :                :         char       *str;
 1518                          1807                 :            119 :         int         prettyFlags = PRETTYFLAG_PAREN;
                               1808                 :                : 
 1677                          1809                 :            119 :         str = deparse_expression_pretty(expr, context, false, false,
                               1810                 :                :                                         prettyFlags, 0);
                               1811                 :                : 
                               1812         [ +  + ]:            119 :         if (colno > 0)
                               1813                 :             49 :             appendStringInfoString(&buf, ", ");
                               1814                 :                : 
                               1815                 :                :         /* Need parens if it's not a bare function call */
                               1816         [ +  + ]:            119 :         if (looks_like_function(expr))
                               1817                 :             17 :             appendStringInfoString(&buf, str);
                               1818                 :                :         else
                               1819                 :            102 :             appendStringInfo(&buf, "(%s)", str);
                               1820                 :                : 
                               1821                 :            119 :         colno++;
                               1822                 :                :     }
                               1823                 :                : 
                               1824         [ +  + ]:            338 :     if (!columns_only)
                               1825                 :            131 :         appendStringInfo(&buf, " FROM %s",
                               1826                 :                :                          generate_relation_name(statextrec->stxrelid, NIL));
                               1827                 :                : 
 3140 alvherre@alvh.no-ip.     1828                 :            338 :     ReleaseSysCache(statexttup);
                               1829                 :                : 
                               1830                 :            338 :     return buf.data;
                               1831                 :                : }
                               1832                 :                : 
                               1833                 :                : /*
                               1834                 :                :  * Generate text array of expressions for statistics object.
                               1835                 :                :  */
                               1836                 :                : Datum
 1677 tomas.vondra@postgre     1837                 :             12 : pg_get_statisticsobjdef_expressions(PG_FUNCTION_ARGS)
                               1838                 :                : {
                               1839                 :             12 :     Oid         statextid = PG_GETARG_OID(0);
                               1840                 :                :     Form_pg_statistic_ext statextrec;
                               1841                 :                :     HeapTuple   statexttup;
                               1842                 :                :     Datum       datum;
                               1843                 :                :     List       *context;
                               1844                 :                :     ListCell   *lc;
                               1845                 :             12 :     List       *exprs = NIL;
                               1846                 :                :     bool        has_exprs;
                               1847                 :                :     char       *tmp;
                               1848                 :             12 :     ArrayBuildState *astate = NULL;
                               1849                 :                : 
                               1850                 :             12 :     statexttup = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(statextid));
                               1851                 :                : 
                               1852         [ -  + ]:             12 :     if (!HeapTupleIsValid(statexttup))
 1635 tomas.vondra@postgre     1853                 :UBC           0 :         PG_RETURN_NULL();
                               1854                 :                : 
                               1855                 :                :     /* Does the stats object have expressions? */
 1677 tomas.vondra@postgre     1856                 :CBC          12 :     has_exprs = !heap_attisnull(statexttup, Anum_pg_statistic_ext_stxexprs, NULL);
                               1857                 :                : 
                               1858                 :                :     /* no expressions? we're done */
                               1859         [ +  + ]:             12 :     if (!has_exprs)
                               1860                 :                :     {
                               1861                 :              6 :         ReleaseSysCache(statexttup);
                               1862                 :              6 :         PG_RETURN_NULL();
                               1863                 :                :     }
                               1864                 :                : 
                               1865                 :              6 :     statextrec = (Form_pg_statistic_ext) GETSTRUCT(statexttup);
                               1866                 :                : 
                               1867                 :                :     /*
                               1868                 :                :      * Get the statistics expressions, and deparse them into text values.
                               1869                 :                :      */
  948 dgustafsson@postgres     1870                 :              6 :     datum = SysCacheGetAttrNotNull(STATEXTOID, statexttup,
                               1871                 :                :                                    Anum_pg_statistic_ext_stxexprs);
 1677 tomas.vondra@postgre     1872                 :              6 :     tmp = TextDatumGetCString(datum);
                               1873                 :              6 :     exprs = (List *) stringToNode(tmp);
                               1874                 :              6 :     pfree(tmp);
                               1875                 :                : 
                               1876                 :              6 :     context = deparse_context_for(get_relation_name(statextrec->stxrelid),
                               1877                 :                :                                   statextrec->stxrelid);
                               1878                 :                : 
                               1879   [ +  -  +  +  :             18 :     foreach(lc, exprs)
                                              +  + ]
                               1880                 :                :     {
                               1881                 :             12 :         Node       *expr = (Node *) lfirst(lc);
                               1882                 :                :         char       *str;
                               1883                 :             12 :         int         prettyFlags = PRETTYFLAG_INDENT;
                               1884                 :                : 
                               1885                 :             12 :         str = deparse_expression_pretty(expr, context, false, false,
                               1886                 :                :                                         prettyFlags, 0);
                               1887                 :                : 
                               1888                 :             12 :         astate = accumArrayResult(astate,
                               1889                 :             12 :                                   PointerGetDatum(cstring_to_text(str)),
                               1890                 :                :                                   false,
                               1891                 :                :                                   TEXTOID,
                               1892                 :                :                                   CurrentMemoryContext);
                               1893                 :                :     }
                               1894                 :                : 
                               1895                 :              6 :     ReleaseSysCache(statexttup);
                               1896                 :                : 
                               1897                 :              6 :     PG_RETURN_DATUM(makeArrayResult(astate, CurrentMemoryContext));
                               1898                 :                : }
                               1899                 :                : 
                               1900                 :                : /*
                               1901                 :                :  * pg_get_partkeydef
                               1902                 :                :  *
                               1903                 :                :  * Returns the partition key specification, ie, the following:
                               1904                 :                :  *
                               1905                 :                :  * { RANGE | LIST | HASH } (column opt_collation opt_opclass [, ...])
                               1906                 :                :  */
                               1907                 :                : Datum
 3247 rhaas@postgresql.org     1908                 :            714 : pg_get_partkeydef(PG_FUNCTION_ARGS)
                               1909                 :                : {
                               1910                 :            714 :     Oid         relid = PG_GETARG_OID(0);
                               1911                 :                :     char       *res;
                               1912                 :                : 
 3107 sfrost@snowman.net       1913                 :            714 :     res = pg_get_partkeydef_worker(relid, PRETTYFLAG_INDENT, false, true);
                               1914                 :                : 
                               1915         [ +  + ]:            714 :     if (res == NULL)
                               1916                 :              3 :         PG_RETURN_NULL();
                               1917                 :                : 
                               1918                 :            711 :     PG_RETURN_TEXT_P(string_to_text(res));
                               1919                 :                : }
                               1920                 :                : 
                               1921                 :                : /* Internal version that just reports the column definitions */
                               1922                 :                : char *
 3161 rhaas@postgresql.org     1923                 :             71 : pg_get_partkeydef_columns(Oid relid, bool pretty)
                               1924                 :                : {
                               1925                 :                :     int         prettyFlags;
                               1926                 :                : 
 1310 tgl@sss.pgh.pa.us        1927         [ +  - ]:             71 :     prettyFlags = GET_PRETTY_FLAGS(pretty);
                               1928                 :                : 
 3107 sfrost@snowman.net       1929                 :             71 :     return pg_get_partkeydef_worker(relid, prettyFlags, true, false);
                               1930                 :                : }
                               1931                 :                : 
                               1932                 :                : /*
                               1933                 :                :  * Internal workhorse to decompile a partition key definition.
                               1934                 :                :  */
                               1935                 :                : static char *
 3161 rhaas@postgresql.org     1936                 :            785 : pg_get_partkeydef_worker(Oid relid, int prettyFlags,
                               1937                 :                :                          bool attrsOnly, bool missing_ok)
                               1938                 :                : {
                               1939                 :                :     Form_pg_partitioned_table form;
                               1940                 :                :     HeapTuple   tuple;
                               1941                 :                :     oidvector  *partclass;
                               1942                 :                :     oidvector  *partcollation;
                               1943                 :                :     List       *partexprs;
                               1944                 :                :     ListCell   *partexpr_item;
                               1945                 :                :     List       *context;
                               1946                 :                :     Datum       datum;
                               1947                 :                :     StringInfoData buf;
                               1948                 :                :     int         keyno;
                               1949                 :                :     char       *str;
                               1950                 :                :     char       *sep;
                               1951                 :                : 
 3247                          1952                 :            785 :     tuple = SearchSysCache1(PARTRELID, ObjectIdGetDatum(relid));
                               1953         [ +  + ]:            785 :     if (!HeapTupleIsValid(tuple))
                               1954                 :                :     {
 3107 sfrost@snowman.net       1955         [ +  - ]:              3 :         if (missing_ok)
                               1956                 :              3 :             return NULL;
 3247 rhaas@postgresql.org     1957         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for partition key of %u", relid);
                               1958                 :                :     }
                               1959                 :                : 
 3247 rhaas@postgresql.org     1960                 :CBC         782 :     form = (Form_pg_partitioned_table) GETSTRUCT(tuple);
                               1961                 :                : 
                               1962         [ -  + ]:            782 :     Assert(form->partrelid == relid);
                               1963                 :                : 
                               1964                 :                :     /* Must get partclass and partcollation the hard way */
  948 dgustafsson@postgres     1965                 :            782 :     datum = SysCacheGetAttrNotNull(PARTRELID, tuple,
                               1966                 :                :                                    Anum_pg_partitioned_table_partclass);
 3247 rhaas@postgresql.org     1967                 :            782 :     partclass = (oidvector *) DatumGetPointer(datum);
                               1968                 :                : 
  948 dgustafsson@postgres     1969                 :            782 :     datum = SysCacheGetAttrNotNull(PARTRELID, tuple,
                               1970                 :                :                                    Anum_pg_partitioned_table_partcollation);
 3247 rhaas@postgresql.org     1971                 :            782 :     partcollation = (oidvector *) DatumGetPointer(datum);
                               1972                 :                : 
                               1973                 :                : 
                               1974                 :                :     /*
                               1975                 :                :      * Get the expressions, if any.  (NOTE: we do not use the relcache
                               1976                 :                :      * versions of the expressions, because we want to display
                               1977                 :                :      * non-const-folded expressions.)
                               1978                 :                :      */
 2771 andrew@dunslane.net      1979         [ +  + ]:            782 :     if (!heap_attisnull(tuple, Anum_pg_partitioned_table_partexprs, NULL))
                               1980                 :                :     {
                               1981                 :                :         Datum       exprsDatum;
                               1982                 :                :         char       *exprsString;
                               1983                 :                : 
  948 dgustafsson@postgres     1984                 :             73 :         exprsDatum = SysCacheGetAttrNotNull(PARTRELID, tuple,
                               1985                 :                :                                             Anum_pg_partitioned_table_partexprs);
 3247 rhaas@postgresql.org     1986                 :             73 :         exprsString = TextDatumGetCString(exprsDatum);
                               1987                 :             73 :         partexprs = (List *) stringToNode(exprsString);
                               1988                 :                : 
                               1989         [ -  + ]:             73 :         if (!IsA(partexprs, List))
 3247 rhaas@postgresql.org     1990         [ #  # ]:UBC           0 :             elog(ERROR, "unexpected node type found in partexprs: %d",
                               1991                 :                :                  (int) nodeTag(partexprs));
                               1992                 :                : 
 3247 rhaas@postgresql.org     1993                 :CBC          73 :         pfree(exprsString);
                               1994                 :                :     }
                               1995                 :                :     else
                               1996                 :            709 :         partexprs = NIL;
                               1997                 :                : 
                               1998                 :            782 :     partexpr_item = list_head(partexprs);
                               1999                 :            782 :     context = deparse_context_for(get_relation_name(relid), relid);
                               2000                 :                : 
                               2001                 :            782 :     initStringInfo(&buf);
                               2002                 :                : 
                               2003   [ +  +  +  - ]:            782 :     switch (form->partstrat)
                               2004                 :                :     {
 2910                          2005                 :             58 :         case PARTITION_STRATEGY_HASH:
                               2006         [ +  - ]:             58 :             if (!attrsOnly)
 2308 drowley@postgresql.o     2007                 :             58 :                 appendStringInfoString(&buf, "HASH");
 2910 rhaas@postgresql.org     2008                 :             58 :             break;
 3247                          2009                 :            293 :         case PARTITION_STRATEGY_LIST:
 3161                          2010         [ +  + ]:            293 :             if (!attrsOnly)
 2996 peter_e@gmx.net          2011                 :            273 :                 appendStringInfoString(&buf, "LIST");
 3247 rhaas@postgresql.org     2012                 :            293 :             break;
                               2013                 :            431 :         case PARTITION_STRATEGY_RANGE:
 3161                          2014         [ +  + ]:            431 :             if (!attrsOnly)
 2996 peter_e@gmx.net          2015                 :            380 :                 appendStringInfoString(&buf, "RANGE");
 3247 rhaas@postgresql.org     2016                 :            431 :             break;
 3247 rhaas@postgresql.org     2017                 :UBC           0 :         default:
                               2018         [ #  # ]:              0 :             elog(ERROR, "unexpected partition strategy: %d",
                               2019                 :                :                  (int) form->partstrat);
                               2020                 :                :     }
                               2021                 :                : 
 3161 rhaas@postgresql.org     2022         [ +  + ]:CBC         782 :     if (!attrsOnly)
 2996 peter_e@gmx.net          2023                 :            711 :         appendStringInfoString(&buf, " (");
 3247 rhaas@postgresql.org     2024                 :            782 :     sep = "";
                               2025         [ +  + ]:           1640 :     for (keyno = 0; keyno < form->partnatts; keyno++)
                               2026                 :                :     {
                               2027                 :            858 :         AttrNumber  attnum = form->partattrs.values[keyno];
                               2028                 :                :         Oid         keycoltype;
                               2029                 :                :         Oid         keycolcollation;
                               2030                 :                :         Oid         partcoll;
                               2031                 :                : 
                               2032                 :            858 :         appendStringInfoString(&buf, sep);
                               2033                 :            858 :         sep = ", ";
                               2034         [ +  + ]:            858 :         if (attnum != 0)
                               2035                 :                :         {
                               2036                 :                :             /* Simple attribute reference */
                               2037                 :                :             char       *attname;
                               2038                 :                :             int32       keycoltypmod;
                               2039                 :                : 
 2815 alvherre@alvh.no-ip.     2040                 :            779 :             attname = get_attname(relid, attnum, false);
 3247 rhaas@postgresql.org     2041                 :            779 :             appendStringInfoString(&buf, quote_identifier(attname));
                               2042                 :            779 :             get_atttypetypmodcoll(relid, attnum,
                               2043                 :                :                                   &keycoltype, &keycoltypmod,
                               2044                 :                :                                   &keycolcollation);
                               2045                 :                :         }
                               2046                 :                :         else
                               2047                 :                :         {
                               2048                 :                :             /* Expression */
                               2049                 :                :             Node       *partkey;
                               2050                 :                : 
                               2051         [ -  + ]:             79 :             if (partexpr_item == NULL)
 3247 rhaas@postgresql.org     2052         [ #  # ]:UBC           0 :                 elog(ERROR, "too few entries in partexprs list");
 3247 rhaas@postgresql.org     2053                 :CBC          79 :             partkey = (Node *) lfirst(partexpr_item);
 2297 tgl@sss.pgh.pa.us        2054                 :             79 :             partexpr_item = lnext(partexprs, partexpr_item);
                               2055                 :                : 
                               2056                 :                :             /* Deparse */
 3247 rhaas@postgresql.org     2057                 :             79 :             str = deparse_expression_pretty(partkey, context, false, false,
                               2058                 :                :                                             prettyFlags, 0);
                               2059                 :                :             /* Need parens if it's not a bare function call */
 3029 tgl@sss.pgh.pa.us        2060         [ +  + ]:             79 :             if (looks_like_function(partkey))
                               2061                 :             28 :                 appendStringInfoString(&buf, str);
                               2062                 :                :             else
                               2063                 :             51 :                 appendStringInfo(&buf, "(%s)", str);
                               2064                 :                : 
 3247 rhaas@postgresql.org     2065                 :             79 :             keycoltype = exprType(partkey);
                               2066                 :             79 :             keycolcollation = exprCollation(partkey);
                               2067                 :                :         }
                               2068                 :                : 
                               2069                 :                :         /* Add collation, if not default for column */
                               2070                 :            858 :         partcoll = partcollation->values[keyno];
 3161                          2071   [ +  +  +  +  :            858 :         if (!attrsOnly && OidIsValid(partcoll) && partcoll != keycolcollation)
                                              +  + ]
 3247                          2072                 :              3 :             appendStringInfo(&buf, " COLLATE %s",
                               2073                 :                :                              generate_collation_name((partcoll)));
                               2074                 :                : 
                               2075                 :                :         /* Add the operator class name, if not default */
 3161                          2076         [ +  + ]:            858 :         if (!attrsOnly)
                               2077                 :            760 :             get_opclass_name(partclass->values[keyno], keycoltype, &buf);
                               2078                 :                :     }
                               2079                 :                : 
                               2080         [ +  + ]:            782 :     if (!attrsOnly)
                               2081                 :            711 :         appendStringInfoChar(&buf, ')');
                               2082                 :                : 
                               2083                 :                :     /* Clean up */
 3247                          2084                 :            782 :     ReleaseSysCache(tuple);
                               2085                 :                : 
                               2086                 :            782 :     return buf.data;
                               2087                 :                : }
                               2088                 :                : 
                               2089                 :                : /*
                               2090                 :                :  * pg_get_partition_constraintdef
                               2091                 :                :  *
                               2092                 :                :  * Returns partition constraint expression as a string for the input relation
                               2093                 :                :  */
                               2094                 :                : Datum
 3090                          2095                 :             91 : pg_get_partition_constraintdef(PG_FUNCTION_ARGS)
                               2096                 :                : {
 3086 bruce@momjian.us         2097                 :             91 :     Oid         relationId = PG_GETARG_OID(0);
                               2098                 :                :     Expr       *constr_expr;
                               2099                 :                :     int         prettyFlags;
                               2100                 :                :     List       *context;
                               2101                 :                :     char       *consrc;
                               2102                 :                : 
 3090 rhaas@postgresql.org     2103                 :             91 :     constr_expr = get_partition_qual_relid(relationId);
                               2104                 :                : 
                               2105                 :                :     /* Quick exit if no partition constraint */
                               2106         [ +  + ]:             91 :     if (constr_expr == NULL)
                               2107                 :              9 :         PG_RETURN_NULL();
                               2108                 :                : 
                               2109                 :                :     /*
                               2110                 :                :      * Deparse and return the constraint expression.
                               2111                 :                :      */
                               2112                 :             82 :     prettyFlags = PRETTYFLAG_INDENT;
                               2113                 :             82 :     context = deparse_context_for(get_relation_name(relationId), relationId);
                               2114                 :             82 :     consrc = deparse_expression_pretty((Node *) constr_expr, context, false,
                               2115                 :                :                                        false, prettyFlags, 0);
                               2116                 :                : 
                               2117                 :             82 :     PG_RETURN_TEXT_P(string_to_text(consrc));
                               2118                 :                : }
                               2119                 :                : 
                               2120                 :                : /*
                               2121                 :                :  * pg_get_partconstrdef_string
                               2122                 :                :  *
                               2123                 :                :  * Returns the partition constraint as a C-string for the input relation, with
                               2124                 :                :  * the given alias.  No pretty-printing.
                               2125                 :                :  */
                               2126                 :                : char *
 2400 alvherre@alvh.no-ip.     2127                 :             55 : pg_get_partconstrdef_string(Oid partitionId, char *aliasname)
                               2128                 :                : {
                               2129                 :                :     Expr       *constr_expr;
                               2130                 :                :     List       *context;
                               2131                 :                : 
                               2132                 :             55 :     constr_expr = get_partition_qual_relid(partitionId);
                               2133                 :             55 :     context = deparse_context_for(aliasname, partitionId);
                               2134                 :                : 
                               2135                 :             55 :     return deparse_expression((Node *) constr_expr, context, true, false);
                               2136                 :                : }
                               2137                 :                : 
                               2138                 :                : /*
                               2139                 :                :  * pg_get_constraintdef
                               2140                 :                :  *
                               2141                 :                :  * Returns the definition for the constraint, ie, everything that needs to
                               2142                 :                :  * appear after "ALTER TABLE ... ADD CONSTRAINT <constraintname>".
                               2143                 :                :  */
                               2144                 :                : Datum
 8474 tgl@sss.pgh.pa.us        2145                 :           1069 : pg_get_constraintdef(PG_FUNCTION_ARGS)
                               2146                 :                : {
 8455 bruce@momjian.us         2147                 :           1069 :     Oid         constraintId = PG_GETARG_OID(0);
                               2148                 :                :     int         prettyFlags;
                               2149                 :                :     char       *res;
                               2150                 :                : 
 4650 tgl@sss.pgh.pa.us        2151                 :           1069 :     prettyFlags = PRETTYFLAG_INDENT;
                               2152                 :                : 
 3381 rhaas@postgresql.org     2153                 :           1069 :     res = pg_get_constraintdef_worker(constraintId, false, prettyFlags, true);
                               2154                 :                : 
                               2155         [ +  + ]:           1069 :     if (res == NULL)
                               2156                 :              3 :         PG_RETURN_NULL();
                               2157                 :                : 
                               2158                 :           1066 :     PG_RETURN_TEXT_P(string_to_text(res));
                               2159                 :                : }
                               2160                 :                : 
                               2161                 :                : Datum
 8126 tgl@sss.pgh.pa.us        2162                 :           2351 : pg_get_constraintdef_ext(PG_FUNCTION_ARGS)
                               2163                 :                : {
                               2164                 :           2351 :     Oid         constraintId = PG_GETARG_OID(0);
                               2165                 :           2351 :     bool        pretty = PG_GETARG_BOOL(1);
                               2166                 :                :     int         prettyFlags;
                               2167                 :                :     char       *res;
                               2168                 :                : 
 1310                          2169         [ +  + ]:           2351 :     prettyFlags = GET_PRETTY_FLAGS(pretty);
                               2170                 :                : 
 3381 rhaas@postgresql.org     2171                 :           2351 :     res = pg_get_constraintdef_worker(constraintId, false, prettyFlags, true);
                               2172                 :                : 
                               2173         [ -  + ]:           2351 :     if (res == NULL)
 3381 rhaas@postgresql.org     2174                 :UBC           0 :         PG_RETURN_NULL();
                               2175                 :                : 
 3381 rhaas@postgresql.org     2176                 :CBC        2351 :     PG_RETURN_TEXT_P(string_to_text(res));
                               2177                 :                : }
                               2178                 :                : 
                               2179                 :                : /*
                               2180                 :                :  * Internal version that returns a full ALTER TABLE ... ADD CONSTRAINT command
                               2181                 :                :  */
                               2182                 :                : char *
 3630 tgl@sss.pgh.pa.us        2183                 :            304 : pg_get_constraintdef_command(Oid constraintId)
                               2184                 :                : {
 3381 rhaas@postgresql.org     2185                 :            304 :     return pg_get_constraintdef_worker(constraintId, true, 0, false);
                               2186                 :                : }
                               2187                 :                : 
                               2188                 :                : /*
                               2189                 :                :  * As of 9.4, we now use an MVCC snapshot for this.
                               2190                 :                :  */
                               2191                 :                : static char *
 7846 tgl@sss.pgh.pa.us        2192                 :           3724 : pg_get_constraintdef_worker(Oid constraintId, bool fullCommand,
                               2193                 :                :                             int prettyFlags, bool missing_ok)
                               2194                 :                : {
                               2195                 :                :     HeapTuple   tup;
                               2196                 :                :     Form_pg_constraint conForm;
                               2197                 :                :     StringInfoData buf;
                               2198                 :                :     SysScanDesc scandesc;
                               2199                 :                :     ScanKeyData scankey[1];
 4193 bruce@momjian.us         2200                 :           3724 :     Snapshot    snapshot = RegisterSnapshot(GetTransactionSnapshot());
 2472 andres@anarazel.de       2201                 :           3724 :     Relation    relation = table_open(ConstraintRelationId, AccessShareLock);
                               2202                 :                : 
 4223 simon@2ndQuadrant.co     2203                 :           3724 :     ScanKeyInit(&scankey[0],
                               2204                 :                :                 Anum_pg_constraint_oid,
                               2205                 :                :                 BTEqualStrategyNumber, F_OIDEQ,
                               2206                 :                :                 ObjectIdGetDatum(constraintId));
                               2207                 :                : 
                               2208                 :           3724 :     scandesc = systable_beginscan(relation,
                               2209                 :                :                                   ConstraintOidIndexId,
                               2210                 :                :                                   true,
                               2211                 :                :                                   snapshot,
                               2212                 :                :                                   1,
                               2213                 :                :                                   scankey);
                               2214                 :                : 
                               2215                 :                :     /*
                               2216                 :                :      * We later use the tuple with SysCacheGetAttr() as if we had obtained it
                               2217                 :                :      * via SearchSysCache, which works fine.
                               2218                 :                :      */
                               2219                 :           3724 :     tup = systable_getnext(scandesc);
                               2220                 :                : 
                               2221                 :           3724 :     UnregisterSnapshot(snapshot);
                               2222                 :                : 
 3381 rhaas@postgresql.org     2223         [ +  + ]:           3724 :     if (!HeapTupleIsValid(tup))
                               2224                 :                :     {
                               2225         [ +  - ]:              3 :         if (missing_ok)
                               2226                 :                :         {
                               2227                 :              3 :             systable_endscan(scandesc);
 2472 andres@anarazel.de       2228                 :              3 :             table_close(relation, AccessShareLock);
 3381 rhaas@postgresql.org     2229                 :              3 :             return NULL;
                               2230                 :                :         }
 3068 tgl@sss.pgh.pa.us        2231         [ #  # ]:UBC           0 :         elog(ERROR, "could not find tuple for constraint %u", constraintId);
                               2232                 :                :     }
                               2233                 :                : 
 8474 tgl@sss.pgh.pa.us        2234                 :CBC        3721 :     conForm = (Form_pg_constraint) GETSTRUCT(tup);
                               2235                 :                : 
                               2236                 :           3721 :     initStringInfo(&buf);
                               2237                 :                : 
 3630                          2238         [ +  + ]:           3721 :     if (fullCommand)
                               2239                 :                :     {
 2918                          2240         [ +  + ]:            304 :         if (OidIsValid(conForm->conrelid))
                               2241                 :                :         {
                               2242                 :                :             /*
                               2243                 :                :              * Currently, callers want ALTER TABLE (without ONLY) for CHECK
                               2244                 :                :              * constraints, and other types of constraints don't inherit
                               2245                 :                :              * anyway so it doesn't matter whether we say ONLY or not. Someday
                               2246                 :                :              * we might need to let callers specify whether to put ONLY in the
                               2247                 :                :              * command.
                               2248                 :                :              */
                               2249                 :            297 :             appendStringInfo(&buf, "ALTER TABLE %s ADD CONSTRAINT %s ",
                               2250                 :                :                              generate_qualified_relation_name(conForm->conrelid),
                               2251                 :            297 :                              quote_identifier(NameStr(conForm->conname)));
                               2252                 :                :         }
                               2253                 :                :         else
                               2254                 :                :         {
                               2255                 :                :             /* Must be a domain constraint */
                               2256         [ -  + ]:              7 :             Assert(OidIsValid(conForm->contypid));
                               2257                 :              7 :             appendStringInfo(&buf, "ALTER DOMAIN %s ADD CONSTRAINT %s ",
                               2258                 :                :                              generate_qualified_type_name(conForm->contypid),
                               2259                 :              7 :                              quote_identifier(NameStr(conForm->conname)));
                               2260                 :                :         }
                               2261                 :                :     }
                               2262                 :                : 
 8474                          2263   [ +  +  +  +  :           3721 :     switch (conForm->contype)
                                           -  +  - ]
                               2264                 :                :     {
                               2265                 :            368 :         case CONSTRAINT_FOREIGN:
                               2266                 :                :             {
                               2267                 :                :                 Datum       val;
                               2268                 :                :                 bool        isnull;
                               2269                 :                :                 const char *string;
                               2270                 :                : 
                               2271                 :                :                 /* Start off the constraint definition */
 4380 rhaas@postgresql.org     2272                 :            368 :                 appendStringInfoString(&buf, "FOREIGN KEY (");
                               2273                 :                : 
                               2274                 :                :                 /* Fetch and build referencing-column list */
  948 dgustafsson@postgres     2275                 :            368 :                 val = SysCacheGetAttrNotNull(CONSTROID, tup,
                               2276                 :                :                                              Anum_pg_constraint_conkey);
                               2277                 :                : 
                               2278                 :                :                 /* If it is a temporal foreign key then it uses PERIOD. */
  406 peter@eisentraut.org     2279                 :            368 :                 decompile_column_index_array(val, conForm->conrelid, conForm->conperiod, &buf);
                               2280                 :                : 
                               2281                 :                :                 /* add foreign relation name */
 8455 bruce@momjian.us         2282                 :            368 :                 appendStringInfo(&buf, ") REFERENCES %s(",
                               2283                 :                :                                  generate_relation_name(conForm->confrelid,
                               2284                 :                :                                                         NIL));
                               2285                 :                : 
                               2286                 :                :                 /* Fetch and build referenced-column list */
  948 dgustafsson@postgres     2287                 :            368 :                 val = SysCacheGetAttrNotNull(CONSTROID, tup,
                               2288                 :                :                                              Anum_pg_constraint_confkey);
                               2289                 :                : 
  406 peter@eisentraut.org     2290                 :            368 :                 decompile_column_index_array(val, conForm->confrelid, conForm->conperiod, &buf);
                               2291                 :                : 
 4380 rhaas@postgresql.org     2292                 :            368 :                 appendStringInfoChar(&buf, ')');
                               2293                 :                : 
                               2294                 :                :                 /* Add match type */
 8455 bruce@momjian.us         2295   [ +  -  +  - ]:            368 :                 switch (conForm->confmatchtype)
                               2296                 :                :                 {
                               2297                 :             17 :                     case FKCONSTR_MATCH_FULL:
                               2298                 :             17 :                         string = " MATCH FULL";
                               2299                 :             17 :                         break;
 8455 bruce@momjian.us         2300                 :UBC           0 :                     case FKCONSTR_MATCH_PARTIAL:
                               2301                 :              0 :                         string = " MATCH PARTIAL";
                               2302                 :              0 :                         break;
 4881 tgl@sss.pgh.pa.us        2303                 :CBC         351 :                     case FKCONSTR_MATCH_SIMPLE:
 8455 bruce@momjian.us         2304                 :            351 :                         string = "";
                               2305                 :            351 :                         break;
 8455 bruce@momjian.us         2306                 :UBC           0 :                     default:
 8129 tgl@sss.pgh.pa.us        2307         [ #  # ]:              0 :                         elog(ERROR, "unrecognized confmatchtype: %d",
                               2308                 :                :                              conForm->confmatchtype);
                               2309                 :                :                         string = "";  /* keep compiler quiet */
                               2310                 :                :                         break;
                               2311                 :                :                 }
 7941 neilc@samurai.com        2312                 :CBC         368 :                 appendStringInfoString(&buf, string);
                               2313                 :                : 
                               2314                 :                :                 /* Add ON UPDATE and ON DELETE clauses, if needed */
 8455 bruce@momjian.us         2315   [ +  -  +  +  :            368 :                 switch (conForm->confupdtype)
                                              -  - ]
                               2316                 :                :                 {
                               2317                 :            300 :                     case FKCONSTR_ACTION_NOACTION:
 8121                          2318                 :            300 :                         string = NULL;  /* suppress default */
 8455                          2319                 :            300 :                         break;
 8455 bruce@momjian.us         2320                 :UBC           0 :                     case FKCONSTR_ACTION_RESTRICT:
                               2321                 :              0 :                         string = "RESTRICT";
                               2322                 :              0 :                         break;
 8455 bruce@momjian.us         2323                 :CBC          54 :                     case FKCONSTR_ACTION_CASCADE:
                               2324                 :             54 :                         string = "CASCADE";
                               2325                 :             54 :                         break;
                               2326                 :             14 :                     case FKCONSTR_ACTION_SETNULL:
                               2327                 :             14 :                         string = "SET NULL";
                               2328                 :             14 :                         break;
 8455 bruce@momjian.us         2329                 :UBC           0 :                     case FKCONSTR_ACTION_SETDEFAULT:
                               2330                 :              0 :                         string = "SET DEFAULT";
                               2331                 :              0 :                         break;
                               2332                 :              0 :                     default:
 8129 tgl@sss.pgh.pa.us        2333         [ #  # ]:              0 :                         elog(ERROR, "unrecognized confupdtype: %d",
                               2334                 :                :                              conForm->confupdtype);
                               2335                 :                :                         string = NULL;  /* keep compiler quiet */
                               2336                 :                :                         break;
                               2337                 :                :                 }
 8303 tgl@sss.pgh.pa.us        2338         [ +  + ]:CBC         368 :                 if (string)
      bruce@momjian.us         2339                 :             68 :                     appendStringInfo(&buf, " ON UPDATE %s", string);
                               2340                 :                : 
 8455                          2341   [ +  -  +  +  :            368 :                 switch (conForm->confdeltype)
                                              +  - ]
                               2342                 :                :                 {
                               2343                 :            302 :                     case FKCONSTR_ACTION_NOACTION:
 8121                          2344                 :            302 :                         string = NULL;  /* suppress default */
 8455                          2345                 :            302 :                         break;
 8455 bruce@momjian.us         2346                 :UBC           0 :                     case FKCONSTR_ACTION_RESTRICT:
                               2347                 :              0 :                         string = "RESTRICT";
                               2348                 :              0 :                         break;
 8455 bruce@momjian.us         2349                 :CBC          54 :                     case FKCONSTR_ACTION_CASCADE:
                               2350                 :             54 :                         string = "CASCADE";
                               2351                 :             54 :                         break;
                               2352                 :              9 :                     case FKCONSTR_ACTION_SETNULL:
                               2353                 :              9 :                         string = "SET NULL";
                               2354                 :              9 :                         break;
                               2355                 :              3 :                     case FKCONSTR_ACTION_SETDEFAULT:
                               2356                 :              3 :                         string = "SET DEFAULT";
                               2357                 :              3 :                         break;
 8455 bruce@momjian.us         2358                 :UBC           0 :                     default:
 8129 tgl@sss.pgh.pa.us        2359         [ #  # ]:              0 :                         elog(ERROR, "unrecognized confdeltype: %d",
                               2360                 :                :                              conForm->confdeltype);
                               2361                 :                :                         string = NULL;  /* keep compiler quiet */
                               2362                 :                :                         break;
                               2363                 :                :                 }
 8303 tgl@sss.pgh.pa.us        2364         [ +  + ]:CBC         368 :                 if (string)
      bruce@momjian.us         2365                 :             66 :                     appendStringInfo(&buf, " ON DELETE %s", string);
                               2366                 :                : 
                               2367                 :                :                 /*
                               2368                 :                :                  * Add columns specified to SET NULL or SET DEFAULT if
                               2369                 :                :                  * provided.
                               2370                 :                :                  */
 1420 peter@eisentraut.org     2371                 :            368 :                 val = SysCacheGetAttr(CONSTROID, tup,
                               2372                 :                :                                       Anum_pg_constraint_confdelsetcols, &isnull);
                               2373         [ +  + ]:            368 :                 if (!isnull)
                               2374                 :                :                 {
 1148 drowley@postgresql.o     2375                 :              6 :                     appendStringInfoString(&buf, " (");
  406 peter@eisentraut.org     2376                 :              6 :                     decompile_column_index_array(val, conForm->conrelid, false, &buf);
 1148 drowley@postgresql.o     2377                 :              6 :                     appendStringInfoChar(&buf, ')');
                               2378                 :                :                 }
                               2379                 :                : 
 8455 bruce@momjian.us         2380                 :            368 :                 break;
                               2381                 :                :             }
 8293                          2382                 :           1960 :         case CONSTRAINT_PRIMARY:
                               2383                 :                :         case CONSTRAINT_UNIQUE:
                               2384                 :                :             {
                               2385                 :                :                 Datum       val;
                               2386                 :                :                 Oid         indexId;
                               2387                 :                :                 int         keyatts;
                               2388                 :                :                 HeapTuple   indtup;
                               2389                 :                : 
                               2390                 :                :                 /* Start off the constraint definition */
                               2391         [ +  + ]:           1960 :                 if (conForm->contype == CONSTRAINT_PRIMARY)
 1363 peter@eisentraut.org     2392                 :           1593 :                     appendStringInfoString(&buf, "PRIMARY KEY ");
                               2393                 :                :                 else
                               2394                 :            367 :                     appendStringInfoString(&buf, "UNIQUE ");
                               2395                 :                : 
                               2396                 :           1960 :                 indexId = conForm->conindid;
                               2397                 :                : 
                               2398                 :           1960 :                 indtup = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexId));
                               2399         [ -  + ]:           1960 :                 if (!HeapTupleIsValid(indtup))
 1363 peter@eisentraut.org     2400         [ #  # ]:UBC           0 :                     elog(ERROR, "cache lookup failed for index %u", indexId);
 1363 peter@eisentraut.org     2401         [ +  + ]:CBC        1960 :                 if (conForm->contype == CONSTRAINT_UNIQUE &&
                               2402         [ -  + ]:            367 :                     ((Form_pg_index) GETSTRUCT(indtup))->indnullsnotdistinct)
 1363 peter@eisentraut.org     2403                 :UBC           0 :                     appendStringInfoString(&buf, "NULLS NOT DISTINCT ");
                               2404                 :                : 
 1148 drowley@postgresql.o     2405                 :CBC        1960 :                 appendStringInfoChar(&buf, '(');
                               2406                 :                : 
                               2407                 :                :                 /* Fetch and build target column list */
  948 dgustafsson@postgres     2408                 :           1960 :                 val = SysCacheGetAttrNotNull(CONSTROID, tup,
                               2409                 :                :                                              Anum_pg_constraint_conkey);
                               2410                 :                : 
  406 peter@eisentraut.org     2411                 :           1960 :                 keyatts = decompile_column_index_array(val, conForm->conrelid, false, &buf);
                               2412         [ +  + ]:           1960 :                 if (conForm->conperiod)
                               2413                 :            191 :                     appendStringInfoString(&buf, " WITHOUT OVERLAPS");
                               2414                 :                : 
 4380 rhaas@postgresql.org     2415                 :           1960 :                 appendStringInfoChar(&buf, ')');
                               2416                 :                : 
                               2417                 :                :                 /* Build including column list (from pg_index.indkeys) */
  948 dgustafsson@postgres     2418                 :           1960 :                 val = SysCacheGetAttrNotNull(INDEXRELID, indtup,
                               2419                 :                :                                              Anum_pg_index_indnatts);
 2612 alvherre@alvh.no-ip.     2420         [ +  + ]:           1960 :                 if (DatumGetInt32(val) > keyatts)
                               2421                 :                :                 {
                               2422                 :                :                     Datum       cols;
                               2423                 :                :                     Datum      *keys;
                               2424                 :                :                     int         nKeys;
                               2425                 :                :                     int         j;
                               2426                 :                : 
 2761 teodor@sigaev.ru         2427                 :             41 :                     appendStringInfoString(&buf, " INCLUDE (");
                               2428                 :                : 
  948 dgustafsson@postgres     2429                 :             41 :                     cols = SysCacheGetAttrNotNull(INDEXRELID, indtup,
                               2430                 :                :                                                   Anum_pg_index_indkey);
                               2431                 :                : 
 1215 peter@eisentraut.org     2432                 :             41 :                     deconstruct_array_builtin(DatumGetArrayTypeP(cols), INT2OID,
                               2433                 :                :                                               &keys, NULL, &nKeys);
                               2434                 :                : 
 2612 alvherre@alvh.no-ip.     2435         [ +  + ]:            123 :                     for (j = keyatts; j < nKeys; j++)
                               2436                 :                :                     {
                               2437                 :                :                         char       *colName;
                               2438                 :                : 
                               2439                 :             82 :                         colName = get_attname(conForm->conrelid,
                               2440                 :             82 :                                               DatumGetInt16(keys[j]), false);
                               2441         [ +  + ]:             82 :                         if (j > keyatts)
                               2442                 :             41 :                             appendStringInfoString(&buf, ", ");
                               2443                 :             82 :                         appendStringInfoString(&buf, quote_identifier(colName));
                               2444                 :                :                     }
                               2445                 :                : 
 2761 teodor@sigaev.ru         2446                 :             41 :                     appendStringInfoChar(&buf, ')');
                               2447                 :                :                 }
 2612 alvherre@alvh.no-ip.     2448                 :           1960 :                 ReleaseSysCache(indtup);
                               2449                 :                : 
                               2450                 :                :                 /* XXX why do we only print these bits if fullCommand? */
 6590 tgl@sss.pgh.pa.us        2451   [ +  +  +  - ]:           1960 :                 if (fullCommand && OidIsValid(indexId))
                               2452                 :                :                 {
                               2453                 :            102 :                     char       *options = flatten_reloptions(indexId);
                               2454                 :                :                     Oid         tblspc;
                               2455                 :                : 
 7058 bruce@momjian.us         2456         [ -  + ]:            102 :                     if (options)
                               2457                 :                :                     {
 7058 bruce@momjian.us         2458                 :UBC           0 :                         appendStringInfo(&buf, " WITH (%s)", options);
                               2459                 :              0 :                         pfree(options);
                               2460                 :                :                     }
                               2461                 :                : 
                               2462                 :                :                     /*
                               2463                 :                :                      * Print the tablespace, unless it's the database default.
                               2464                 :                :                      * This is to help ALTER TABLE usage of this facility,
                               2465                 :                :                      * which needs this behavior to recreate exact catalog
                               2466                 :                :                      * state.
                               2467                 :                :                      */
 6590 tgl@sss.pgh.pa.us        2468                 :CBC         102 :                     tblspc = get_rel_tablespace(indexId);
                               2469         [ +  + ]:            102 :                     if (OidIsValid(tblspc))
                               2470                 :             12 :                         appendStringInfo(&buf, " USING INDEX TABLESPACE %s",
 3051                          2471                 :             12 :                                          quote_identifier(get_tablespace_name(tblspc)));
                               2472                 :                :                 }
                               2473                 :                : 
 8293 bruce@momjian.us         2474                 :           1960 :                 break;
                               2475                 :                :             }
                               2476                 :           1119 :         case CONSTRAINT_CHECK:
                               2477                 :                :             {
                               2478                 :                :                 Datum       val;
                               2479                 :                :                 char       *conbin;
                               2480                 :                :                 char       *consrc;
                               2481                 :                :                 Node       *expr;
                               2482                 :                :                 List       *context;
                               2483                 :                : 
                               2484                 :                :                 /* Fetch constraint expression in parsetree form */
  948 dgustafsson@postgres     2485                 :           1119 :                 val = SysCacheGetAttrNotNull(CONSTROID, tup,
                               2486                 :                :                                              Anum_pg_constraint_conbin);
                               2487                 :                : 
 6426 tgl@sss.pgh.pa.us        2488                 :           1119 :                 conbin = TextDatumGetCString(val);
 8161 bruce@momjian.us         2489                 :           1119 :                 expr = stringToNode(conbin);
                               2490                 :                : 
                               2491                 :                :                 /* Set up deparsing context for Var nodes in constraint */
                               2492         [ +  + ]:           1119 :                 if (conForm->conrelid != InvalidOid)
                               2493                 :                :                 {
                               2494                 :                :                     /* relation constraint */
 5474 tgl@sss.pgh.pa.us        2495                 :            993 :                     context = deparse_context_for(get_relation_name(conForm->conrelid),
                               2496                 :                :                                                   conForm->conrelid);
                               2497                 :                :                 }
                               2498                 :                :                 else
                               2499                 :                :                 {
                               2500                 :                :                     /* domain constraint --- can't have Vars */
 8060                          2501                 :            126 :                     context = NIL;
                               2502                 :                :                 }
                               2503                 :                : 
 8126                          2504                 :           1119 :                 consrc = deparse_expression_pretty(expr, context, false, false,
                               2505                 :                :                                                    prettyFlags, 0);
                               2506                 :                : 
                               2507                 :                :                 /*
                               2508                 :                :                  * Now emit the constraint definition, adding NO INHERIT if
                               2509                 :                :                  * necessary.
                               2510                 :                :                  *
                               2511                 :                :                  * There are cases where the constraint expression will be
                               2512                 :                :                  * fully parenthesized and we don't need the outer parens ...
                               2513                 :                :                  * but there are other cases where we do need 'em.  Be
                               2514                 :                :                  * conservative for now.
                               2515                 :                :                  *
                               2516                 :                :                  * Note that simply checking for leading '(' and trailing ')'
                               2517                 :                :                  * would NOT be good enough, consider "(x > 0) AND (y > 0)".
                               2518                 :                :                  */
 4844 alvherre@alvh.no-ip.     2519                 :           1119 :                 appendStringInfo(&buf, "CHECK (%s)%s",
                               2520                 :                :                                  consrc,
                               2521         [ +  + ]:           1119 :                                  conForm->connoinherit ? " NO INHERIT" : "");
 8293 bruce@momjian.us         2522                 :           1119 :                 break;
                               2523                 :                :             }
  354 alvherre@alvh.no-ip.     2524                 :            222 :         case CONSTRAINT_NOTNULL:
                               2525                 :                :             {
                               2526         [ +  + ]:            222 :                 if (conForm->conrelid)
                               2527                 :                :                 {
                               2528                 :                :                     AttrNumber  attnum;
                               2529                 :                : 
                               2530                 :            166 :                     attnum = extractNotNullColumn(tup);
                               2531                 :                : 
                               2532                 :            166 :                     appendStringInfo(&buf, "NOT NULL %s",
                               2533                 :            166 :                                      quote_identifier(get_attname(conForm->conrelid,
                               2534                 :                :                                                                   attnum, false)));
                               2535         [ -  + ]:            166 :                     if (((Form_pg_constraint) GETSTRUCT(tup))->connoinherit)
  354 alvherre@alvh.no-ip.     2536                 :UBC           0 :                         appendStringInfoString(&buf, " NO INHERIT");
                               2537                 :                :                 }
  354 alvherre@alvh.no-ip.     2538         [ +  - ]:CBC          56 :                 else if (conForm->contypid)
                               2539                 :                :                 {
                               2540                 :                :                     /* conkey is null for domain not-null constraints */
                               2541                 :             56 :                     appendStringInfoString(&buf, "NOT NULL");
                               2542                 :                :                 }
                               2543                 :            222 :                 break;
                               2544                 :                :             }
                               2545                 :                : 
 5763 tgl@sss.pgh.pa.us        2546                 :UBC           0 :         case CONSTRAINT_TRIGGER:
                               2547                 :                : 
                               2548                 :                :             /*
                               2549                 :                :              * There isn't an ALTER TABLE syntax for creating a user-defined
                               2550                 :                :              * constraint trigger, but it seems better to print something than
                               2551                 :                :              * throw an error; if we throw error then this function couldn't
                               2552                 :                :              * safely be applied to all rows of pg_constraint.
                               2553                 :                :              */
 4380 rhaas@postgresql.org     2554                 :              0 :             appendStringInfoString(&buf, "TRIGGER");
 5763 tgl@sss.pgh.pa.us        2555                 :              0 :             break;
 5804 tgl@sss.pgh.pa.us        2556                 :CBC          52 :         case CONSTRAINT_EXCLUSION:
                               2557                 :                :             {
 5723 bruce@momjian.us         2558                 :             52 :                 Oid         indexOid = conForm->conindid;
                               2559                 :                :                 Datum       val;
                               2560                 :                :                 Datum      *elems;
                               2561                 :                :                 int         nElems;
                               2562                 :                :                 int         i;
                               2563                 :                :                 Oid        *operators;
                               2564                 :                : 
                               2565                 :                :                 /* Extract operator OIDs from the pg_constraint tuple */
  948 dgustafsson@postgres     2566                 :             52 :                 val = SysCacheGetAttrNotNull(CONSTROID, tup,
                               2567                 :                :                                              Anum_pg_constraint_conexclop);
                               2568                 :                : 
 1215 peter@eisentraut.org     2569                 :             52 :                 deconstruct_array_builtin(DatumGetArrayTypeP(val), OIDOID,
                               2570                 :                :                                           &elems, NULL, &nElems);
                               2571                 :                : 
 5804 tgl@sss.pgh.pa.us        2572                 :             52 :                 operators = (Oid *) palloc(nElems * sizeof(Oid));
                               2573         [ +  + ]:            114 :                 for (i = 0; i < nElems; i++)
                               2574                 :             62 :                     operators[i] = DatumGetObjectId(elems[i]);
                               2575                 :                : 
                               2576                 :                :                 /* pg_get_indexdef_worker does the rest */
                               2577                 :                :                 /* suppress tablespace because pg_dump wants it that way */
                               2578                 :             52 :                 appendStringInfoString(&buf,
                               2579                 :             52 :                                        pg_get_indexdef_worker(indexOid,
                               2580                 :                :                                                               0,
                               2581                 :                :                                                               operators,
                               2582                 :                :                                                               false,
                               2583                 :                :                                                               false,
                               2584                 :                :                                                               false,
                               2585                 :                :                                                               false,
                               2586                 :                :                                                               prettyFlags,
                               2587                 :                :                                                               false));
                               2588                 :             52 :                 break;
                               2589                 :                :             }
 8474 tgl@sss.pgh.pa.us        2590                 :UBC           0 :         default:
 8079 peter_e@gmx.net          2591         [ #  # ]:              0 :             elog(ERROR, "invalid constraint type \"%c\"", conForm->contype);
                               2592                 :                :             break;
                               2593                 :                :     }
                               2594                 :                : 
 5935 tgl@sss.pgh.pa.us        2595         [ +  + ]:CBC        3721 :     if (conForm->condeferrable)
 4380 rhaas@postgresql.org     2596                 :             60 :         appendStringInfoString(&buf, " DEFERRABLE");
 5935 tgl@sss.pgh.pa.us        2597         [ +  + ]:           3721 :     if (conForm->condeferred)
 4380 rhaas@postgresql.org     2598                 :             24 :         appendStringInfoString(&buf, " INITIALLY DEFERRED");
                               2599                 :                : 
                               2600                 :                :     /* Validated status is irrelevant when the constraint is NOT ENFORCED. */
  290 peter@eisentraut.org     2601         [ +  + ]:           3721 :     if (!conForm->conenforced)
                               2602                 :             46 :         appendStringInfoString(&buf, " NOT ENFORCED");
                               2603         [ +  + ]:           3675 :     else if (!conForm->convalidated)
 5262 alvherre@alvh.no-ip.     2604                 :            124 :         appendStringInfoString(&buf, " NOT VALID");
                               2605                 :                : 
                               2606                 :                :     /* Cleanup */
 4223 simon@2ndQuadrant.co     2607                 :           3721 :     systable_endscan(scandesc);
 2472 andres@anarazel.de       2608                 :           3721 :     table_close(relation, AccessShareLock);
                               2609                 :                : 
 7846 tgl@sss.pgh.pa.us        2610                 :           3721 :     return buf.data;
                               2611                 :                : }
                               2612                 :                : 
                               2613                 :                : 
                               2614                 :                : /*
                               2615                 :                :  * Convert an int16[] Datum into a comma-separated list of column names
                               2616                 :                :  * for the indicated relation; append the list to buf.  Returns the number
                               2617                 :                :  * of keys.
                               2618                 :                :  */
                               2619                 :                : static int
 8474                          2620                 :           2702 : decompile_column_index_array(Datum column_index_array, Oid relId,
                               2621                 :                :                              bool withPeriod, StringInfo buf)
                               2622                 :                : {
                               2623                 :                :     Datum      *keys;
                               2624                 :                :     int         nKeys;
                               2625                 :                :     int         j;
                               2626                 :                : 
                               2627                 :                :     /* Extract data from array of int16 */
 1215 peter@eisentraut.org     2628                 :           2702 :     deconstruct_array_builtin(DatumGetArrayTypeP(column_index_array), INT2OID,
                               2629                 :                :                               &keys, NULL, &nKeys);
                               2630                 :                : 
 8474 tgl@sss.pgh.pa.us        2631         [ +  + ]:           6542 :     for (j = 0; j < nKeys; j++)
                               2632                 :                :     {
                               2633                 :                :         char       *colName;
                               2634                 :                : 
 2815 alvherre@alvh.no-ip.     2635                 :           3840 :         colName = get_attname(relId, DatumGetInt16(keys[j]), false);
                               2636                 :                : 
 8474 tgl@sss.pgh.pa.us        2637         [ +  + ]:           3840 :         if (j == 0)
 7941 neilc@samurai.com        2638                 :           2702 :             appendStringInfoString(buf, quote_identifier(colName));
                               2639                 :                :         else
  406 peter@eisentraut.org     2640         [ +  + ]:           1252 :             appendStringInfo(buf, ", %s%s",
                               2641         [ +  + ]:            114 :                              (withPeriod && j == nKeys - 1) ? "PERIOD " : "",
                               2642                 :                :                              quote_identifier(colName));
                               2643                 :                :     }
                               2644                 :                : 
 2612 alvherre@alvh.no-ip.     2645                 :           2702 :     return nKeys;
                               2646                 :                : }
                               2647                 :                : 
                               2648                 :                : 
                               2649                 :                : /* ----------
                               2650                 :                :  * pg_get_expr          - Decompile an expression tree
                               2651                 :                :  *
                               2652                 :                :  * Input: an expression tree in nodeToString form, and a relation OID
                               2653                 :                :  *
                               2654                 :                :  * Output: reverse-listed expression
                               2655                 :                :  *
                               2656                 :                :  * Currently, the expression can only refer to a single relation, namely
                               2657                 :                :  * the one specified by the second parameter.  This is sufficient for
                               2658                 :                :  * partial indexes, column default expressions, etc.  We also support
                               2659                 :                :  * Var-free expressions, for which the OID can be InvalidOid.
                               2660                 :                :  *
                               2661                 :                :  * If the OID is nonzero but not actually valid, don't throw an error,
                               2662                 :                :  * just return NULL.  This is a bit questionable, but it's what we've
                               2663                 :                :  * done historically, and it can help avoid unwanted failures when
                               2664                 :                :  * examining catalog entries for just-deleted relations.
                               2665                 :                :  *
                               2666                 :                :  * We expect this function to work, or throw a reasonably clean error,
                               2667                 :                :  * for any node tree that can appear in a catalog pg_node_tree column.
                               2668                 :                :  * Query trees, such as those appearing in pg_rewrite.ev_action, are
                               2669                 :                :  * not supported.  Nor are expressions in more than one relation, which
                               2670                 :                :  * can appear in places like pg_rewrite.ev_qual.
                               2671                 :                :  * ----------
                               2672                 :                :  */
                               2673                 :                : Datum
 8870 tgl@sss.pgh.pa.us        2674                 :           4232 : pg_get_expr(PG_FUNCTION_ARGS)
                               2675                 :                : {
 3152 noah@leadboat.com        2676                 :           4232 :     text       *expr = PG_GETARG_TEXT_PP(0);
 8121 bruce@momjian.us         2677                 :           4232 :     Oid         relid = PG_GETARG_OID(1);
                               2678                 :                :     text       *result;
                               2679                 :                :     int         prettyFlags;
                               2680                 :                : 
 4650 tgl@sss.pgh.pa.us        2681                 :           4232 :     prettyFlags = PRETTYFLAG_INDENT;
                               2682                 :                : 
  627                          2683                 :           4232 :     result = pg_get_expr_worker(expr, relid, prettyFlags);
                               2684         [ +  - ]:           4232 :     if (result)
                               2685                 :           4232 :         PG_RETURN_TEXT_P(result);
                               2686                 :                :     else
  627 tgl@sss.pgh.pa.us        2687                 :UBC           0 :         PG_RETURN_NULL();
                               2688                 :                : }
                               2689                 :                : 
                               2690                 :                : Datum
 8126 tgl@sss.pgh.pa.us        2691                 :CBC         362 : pg_get_expr_ext(PG_FUNCTION_ARGS)
                               2692                 :                : {
 3152 noah@leadboat.com        2693                 :            362 :     text       *expr = PG_GETARG_TEXT_PP(0);
 8121 bruce@momjian.us         2694                 :            362 :     Oid         relid = PG_GETARG_OID(1);
 8126 tgl@sss.pgh.pa.us        2695                 :            362 :     bool        pretty = PG_GETARG_BOOL(2);
                               2696                 :                :     text       *result;
                               2697                 :                :     int         prettyFlags;
                               2698                 :                : 
 1310                          2699         [ +  - ]:            362 :     prettyFlags = GET_PRETTY_FLAGS(pretty);
                               2700                 :                : 
  627                          2701                 :            362 :     result = pg_get_expr_worker(expr, relid, prettyFlags);
                               2702         [ +  - ]:            362 :     if (result)
                               2703                 :            362 :         PG_RETURN_TEXT_P(result);
                               2704                 :                :     else
  627 tgl@sss.pgh.pa.us        2705                 :UBC           0 :         PG_RETURN_NULL();
                               2706                 :                : }
                               2707                 :                : 
                               2708                 :                : static text *
  627 tgl@sss.pgh.pa.us        2709                 :CBC        4594 : pg_get_expr_worker(text *expr, Oid relid, int prettyFlags)
                               2710                 :                : {
                               2711                 :                :     Node       *node;
                               2712                 :                :     Node       *tst;
                               2713                 :                :     Relids      relids;
                               2714                 :                :     List       *context;
                               2715                 :                :     char       *exprstr;
                               2716                 :           4594 :     Relation    rel = NULL;
                               2717                 :                :     char       *str;
                               2718                 :                : 
                               2719                 :                :     /* Convert input pg_node_tree (really TEXT) object to C string */
 6426                          2720                 :           4594 :     exprstr = text_to_cstring(expr);
                               2721                 :                : 
                               2722                 :                :     /* Convert expression to node tree */
 8870                          2723                 :           4594 :     node = (Node *) stringToNode(exprstr);
                               2724                 :                : 
 5999                          2725                 :           4594 :     pfree(exprstr);
                               2726                 :                : 
                               2727                 :                :     /*
                               2728                 :                :      * Throw error if the input is a querytree rather than an expression tree.
                               2729                 :                :      * While we could support queries here, there seems no very good reason
                               2730                 :                :      * to.  In most such catalog columns, we'll see a List of Query nodes, or
                               2731                 :                :      * even nested Lists, so drill down to a non-List node before checking.
                               2732                 :                :      */
 1388                          2733                 :           4594 :     tst = node;
                               2734   [ +  -  -  + ]:           4594 :     while (tst && IsA(tst, List))
 1388 tgl@sss.pgh.pa.us        2735                 :UBC           0 :         tst = linitial((List *) tst);
 1388 tgl@sss.pgh.pa.us        2736   [ +  -  -  + ]:CBC        4594 :     if (tst && IsA(tst, Query))
 1388 tgl@sss.pgh.pa.us        2737         [ #  # ]:UBC           0 :         ereport(ERROR,
                               2738                 :                :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                               2739                 :                :                  errmsg("input is a query, not an expression")));
                               2740                 :                : 
                               2741                 :                :     /*
                               2742                 :                :      * Throw error if the expression contains Vars we won't be able to
                               2743                 :                :      * deparse.
                               2744                 :                :      */
 1388 tgl@sss.pgh.pa.us        2745                 :CBC        4594 :     relids = pull_varnos(NULL, node);
                               2746         [ +  + ]:           4594 :     if (OidIsValid(relid))
                               2747                 :                :     {
                               2748         [ -  + ]:           4552 :         if (!bms_is_subset(relids, bms_make_singleton(1)))
 1388 tgl@sss.pgh.pa.us        2749         [ #  # ]:UBC           0 :             ereport(ERROR,
                               2750                 :                :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                               2751                 :                :                      errmsg("expression contains variables of more than one relation")));
                               2752                 :                :     }
                               2753                 :                :     else
                               2754                 :                :     {
 1388 tgl@sss.pgh.pa.us        2755         [ -  + ]:CBC          42 :         if (!bms_is_empty(relids))
 1388 tgl@sss.pgh.pa.us        2756         [ #  # ]:UBC           0 :             ereport(ERROR,
                               2757                 :                :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                               2758                 :                :                      errmsg("expression contains variables")));
                               2759                 :                :     }
                               2760                 :                : 
                               2761                 :                :     /*
                               2762                 :                :      * Prepare deparse context if needed.  If we are deparsing with a relid,
                               2763                 :                :      * we need to transiently open and lock the rel, to make sure it won't go
                               2764                 :                :      * away underneath us.  (set_relation_column_names would lock it anyway,
                               2765                 :                :      * so this isn't really introducing any new behavior.)
                               2766                 :                :      */
 5999 tgl@sss.pgh.pa.us        2767         [ +  + ]:CBC        4594 :     if (OidIsValid(relid))
                               2768                 :                :     {
  627                          2769                 :           4552 :         rel = try_relation_open(relid, AccessShareLock);
                               2770         [ -  + ]:           4552 :         if (rel == NULL)
  627 tgl@sss.pgh.pa.us        2771                 :UBC           0 :             return NULL;
  627 tgl@sss.pgh.pa.us        2772                 :CBC        4552 :         context = deparse_context_for(RelationGetRelationName(rel), relid);
                               2773                 :                :     }
                               2774                 :                :     else
 5999                          2775                 :             42 :         context = NIL;
                               2776                 :                : 
                               2777                 :                :     /* Deparse */
 8126                          2778                 :           4594 :     str = deparse_expression_pretty(node, context, false, false,
                               2779                 :                :                                     prettyFlags, 0);
                               2780                 :                : 
  627                          2781         [ +  + ]:           4594 :     if (rel != NULL)
                               2782                 :           4552 :         relation_close(rel, AccessShareLock);
                               2783                 :                : 
 5999                          2784                 :           4594 :     return string_to_text(str);
                               2785                 :                : }
                               2786                 :                : 
                               2787                 :                : 
                               2788                 :                : /* ----------
                               2789                 :                :  * pg_get_userbyid      - Get a user name by roleid and
                               2790                 :                :  *                fallback to 'unknown (OID=n)'
                               2791                 :                :  * ----------
                               2792                 :                :  */
                               2793                 :                : Datum
 9268                          2794                 :            873 : pg_get_userbyid(PG_FUNCTION_ARGS)
                               2795                 :                : {
 7427                          2796                 :            873 :     Oid         roleid = PG_GETARG_OID(0);
                               2797                 :                :     Name        result;
                               2798                 :                :     HeapTuple   roletup;
                               2799                 :                :     Form_pg_authid role_rec;
                               2800                 :                : 
                               2801                 :                :     /*
                               2802                 :                :      * Allocate space for the result
                               2803                 :                :      */
 9268                          2804                 :            873 :     result = (Name) palloc(NAMEDATALEN);
 9487 bruce@momjian.us         2805                 :            873 :     memset(NameStr(*result), 0, NAMEDATALEN);
                               2806                 :                : 
                               2807                 :                :     /*
                               2808                 :                :      * Get the pg_authid entry and print the result
                               2809                 :                :      */
 5735 rhaas@postgresql.org     2810                 :            873 :     roletup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
 7427 tgl@sss.pgh.pa.us        2811         [ +  - ]:            873 :     if (HeapTupleIsValid(roletup))
                               2812                 :                :     {
                               2813                 :            873 :         role_rec = (Form_pg_authid) GETSTRUCT(roletup);
 1905 peter@eisentraut.org     2814                 :            873 :         *result = role_rec->rolname;
 7427 tgl@sss.pgh.pa.us        2815                 :            873 :         ReleaseSysCache(roletup);
                               2816                 :                :     }
                               2817                 :                :     else
 7427 tgl@sss.pgh.pa.us        2818                 :UBC           0 :         sprintf(NameStr(*result), "unknown (OID=%u)", roleid);
                               2819                 :                : 
 9268 tgl@sss.pgh.pa.us        2820                 :CBC         873 :     PG_RETURN_NAME(result);
                               2821                 :                : }
                               2822                 :                : 
                               2823                 :                : 
                               2824                 :                : /*
                               2825                 :                :  * pg_get_serial_sequence
                               2826                 :                :  *      Get the name of the sequence used by an identity or serial column,
                               2827                 :                :  *      formatted suitably for passing to setval, nextval or currval.
                               2828                 :                :  *      First parameter is not treated as double-quoted, second parameter
                               2829                 :                :  *      is --- see documentation for reason.
                               2830                 :                :  */
                               2831                 :                : Datum
 7795                          2832                 :              6 : pg_get_serial_sequence(PG_FUNCTION_ARGS)
                               2833                 :                : {
 3152 noah@leadboat.com        2834                 :              6 :     text       *tablename = PG_GETARG_TEXT_PP(0);
 6426 tgl@sss.pgh.pa.us        2835                 :              6 :     text       *columnname = PG_GETARG_TEXT_PP(1);
                               2836                 :                :     RangeVar   *tablerv;
                               2837                 :                :     Oid         tableOid;
                               2838                 :                :     char       *column;
                               2839                 :                :     AttrNumber  attnum;
 7730 bruce@momjian.us         2840                 :              6 :     Oid         sequenceId = InvalidOid;
                               2841                 :                :     Relation    depRel;
                               2842                 :                :     ScanKeyData key[3];
                               2843                 :                :     SysScanDesc scan;
                               2844                 :                :     HeapTuple   tup;
                               2845                 :                : 
                               2846                 :                :     /* Look up table name.  Can't lock it - we might not have privileges. */
 7459 neilc@samurai.com        2847                 :              6 :     tablerv = makeRangeVarFromNameList(textToQualifiedNameList(tablename));
 5081 rhaas@postgresql.org     2848                 :              6 :     tableOid = RangeVarGetRelid(tablerv, NoLock, false);
                               2849                 :                : 
                               2850                 :                :     /* Get the number of the column */
 6426 tgl@sss.pgh.pa.us        2851                 :              6 :     column = text_to_cstring(columnname);
                               2852                 :                : 
 7795                          2853                 :              6 :     attnum = get_attnum(tableOid, column);
                               2854         [ -  + ]:              6 :     if (attnum == InvalidAttrNumber)
 7795 tgl@sss.pgh.pa.us        2855         [ #  # ]:UBC           0 :         ereport(ERROR,
                               2856                 :                :                 (errcode(ERRCODE_UNDEFINED_COLUMN),
                               2857                 :                :                  errmsg("column \"%s\" of relation \"%s\" does not exist",
                               2858                 :                :                         column, tablerv->relname)));
                               2859                 :                : 
                               2860                 :                :     /* Search the dependency table for the dependent sequence */
 2472 andres@anarazel.de       2861                 :CBC           6 :     depRel = table_open(DependRelationId, AccessShareLock);
                               2862                 :                : 
 7795 tgl@sss.pgh.pa.us        2863                 :              6 :     ScanKeyInit(&key[0],
                               2864                 :                :                 Anum_pg_depend_refclassid,
                               2865                 :                :                 BTEqualStrategyNumber, F_OIDEQ,
                               2866                 :                :                 ObjectIdGetDatum(RelationRelationId));
                               2867                 :              6 :     ScanKeyInit(&key[1],
                               2868                 :                :                 Anum_pg_depend_refobjid,
                               2869                 :                :                 BTEqualStrategyNumber, F_OIDEQ,
                               2870                 :                :                 ObjectIdGetDatum(tableOid));
                               2871                 :              6 :     ScanKeyInit(&key[2],
                               2872                 :                :                 Anum_pg_depend_refobjsubid,
                               2873                 :                :                 BTEqualStrategyNumber, F_INT4EQ,
                               2874                 :                :                 Int32GetDatum(attnum));
                               2875                 :                : 
 7502                          2876                 :              6 :     scan = systable_beginscan(depRel, DependReferenceIndexId, true,
                               2877                 :                :                               NULL, 3, key);
                               2878                 :                : 
 7795                          2879         [ +  - ]:             15 :     while (HeapTupleIsValid(tup = systable_getnext(scan)))
                               2880                 :                :     {
 7730 bruce@momjian.us         2881                 :             15 :         Form_pg_depend deprec = (Form_pg_depend) GETSTRUCT(tup);
                               2882                 :                : 
                               2883                 :                :         /*
                               2884                 :                :          * Look for an auto dependency (serial column) or internal dependency
                               2885                 :                :          * (identity column) of a sequence on a column.  (We need the relkind
                               2886                 :                :          * test because indexes can also have auto dependencies on columns.)
                               2887                 :                :          */
 7502 tgl@sss.pgh.pa.us        2888         [ +  + ]:             15 :         if (deprec->classid == RelationRelationId &&
 7795                          2889         [ +  - ]:              6 :             deprec->objsubid == 0 &&
 2965 peter_e@gmx.net          2890         [ +  + ]:              6 :             (deprec->deptype == DEPENDENCY_AUTO ||
                               2891   [ +  -  +  - ]:              9 :              deprec->deptype == DEPENDENCY_INTERNAL) &&
 6927 tgl@sss.pgh.pa.us        2892                 :              6 :             get_rel_relkind(deprec->objid) == RELKIND_SEQUENCE)
                               2893                 :                :         {
 7795                          2894                 :              6 :             sequenceId = deprec->objid;
                               2895                 :              6 :             break;
                               2896                 :                :         }
                               2897                 :                :     }
                               2898                 :                : 
                               2899                 :              6 :     systable_endscan(scan);
 2472 andres@anarazel.de       2900                 :              6 :     table_close(depRel, AccessShareLock);
                               2901                 :                : 
 7795 tgl@sss.pgh.pa.us        2902         [ +  - ]:              6 :     if (OidIsValid(sequenceId))
                               2903                 :                :     {
                               2904                 :                :         char       *result;
                               2905                 :                : 
 3630                          2906                 :              6 :         result = generate_qualified_relation_name(sequenceId);
                               2907                 :                : 
 7795                          2908                 :              6 :         PG_RETURN_TEXT_P(string_to_text(result));
                               2909                 :                :     }
                               2910                 :                : 
 7795 tgl@sss.pgh.pa.us        2911                 :UBC           0 :     PG_RETURN_NULL();
                               2912                 :                : }
                               2913                 :                : 
                               2914                 :                : 
                               2915                 :                : /*
                               2916                 :                :  * pg_get_functiondef
                               2917                 :                :  *      Returns the complete "CREATE OR REPLACE FUNCTION ..." statement for
                               2918                 :                :  *      the specified function.
                               2919                 :                :  *
                               2920                 :                :  * Note: if you change the output format of this function, be careful not
                               2921                 :                :  * to break psql's rules (in \ef and \sf) for identifying the start of the
                               2922                 :                :  * function body.  To wit: the function body starts on a line that begins with
                               2923                 :                :  * "AS ", "BEGIN ", or "RETURN ", and no preceding line will look like that.
                               2924                 :                :  */
                               2925                 :                : Datum
 6261 tgl@sss.pgh.pa.us        2926                 :CBC          86 : pg_get_functiondef(PG_FUNCTION_ARGS)
                               2927                 :                : {
                               2928                 :             86 :     Oid         funcid = PG_GETARG_OID(0);
                               2929                 :                :     StringInfoData buf;
                               2930                 :                :     StringInfoData dq;
                               2931                 :                :     HeapTuple   proctup;
                               2932                 :                :     Form_pg_proc proc;
                               2933                 :                :     bool        isfunction;
                               2934                 :                :     Datum       tmp;
                               2935                 :                :     bool        isnull;
                               2936                 :                :     const char *prosrc;
                               2937                 :                :     const char *name;
                               2938                 :                :     const char *nsp;
                               2939                 :                :     float4      procost;
                               2940                 :                :     int         oldlen;
                               2941                 :                : 
                               2942                 :             86 :     initStringInfo(&buf);
                               2943                 :                : 
                               2944                 :                :     /* Look up the function */
 5735 rhaas@postgresql.org     2945                 :             86 :     proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
 6261 tgl@sss.pgh.pa.us        2946         [ +  + ]:             86 :     if (!HeapTupleIsValid(proctup))
 3381 rhaas@postgresql.org     2947                 :              3 :         PG_RETURN_NULL();
                               2948                 :                : 
 6261 tgl@sss.pgh.pa.us        2949                 :             83 :     proc = (Form_pg_proc) GETSTRUCT(proctup);
                               2950                 :             83 :     name = NameStr(proc->proname);
                               2951                 :                : 
 2797 peter_e@gmx.net          2952         [ -  + ]:             83 :     if (proc->prokind == PROKIND_AGGREGATE)
 6261 tgl@sss.pgh.pa.us        2953         [ #  # ]:UBC           0 :         ereport(ERROR,
                               2954                 :                :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
                               2955                 :                :                  errmsg("\"%s\" is an aggregate function", name)));
                               2956                 :                : 
 2797 peter_e@gmx.net          2957                 :CBC          83 :     isfunction = (proc->prokind != PROKIND_PROCEDURE);
                               2958                 :                : 
                               2959                 :                :     /*
                               2960                 :                :      * We always qualify the function name, to ensure the right function gets
                               2961                 :                :      * replaced.
                               2962                 :                :      */
 1554 tgl@sss.pgh.pa.us        2963                 :             83 :     nsp = get_namespace_name_or_temp(proc->pronamespace);
 2814 peter_e@gmx.net          2964         [ +  + ]:             83 :     appendStringInfo(&buf, "CREATE OR REPLACE %s %s(",
                               2965                 :                :                      isfunction ? "FUNCTION" : "PROCEDURE",
                               2966                 :                :                      quote_qualified_identifier(nsp, name));
 6172                          2967                 :             83 :     (void) print_function_arguments(&buf, proctup, false, true);
 2814                          2968                 :             83 :     appendStringInfoString(&buf, ")\n");
                               2969         [ +  + ]:             83 :     if (isfunction)
                               2970                 :                :     {
                               2971                 :             73 :         appendStringInfoString(&buf, " RETURNS ");
                               2972                 :             73 :         print_function_rettype(&buf, proctup);
                               2973                 :             73 :         appendStringInfoChar(&buf, '\n');
                               2974                 :                :     }
                               2975                 :                : 
 3838                          2976                 :             83 :     print_function_trftypes(&buf, proctup);
                               2977                 :                : 
 2814                          2978                 :             83 :     appendStringInfo(&buf, " LANGUAGE %s\n",
 3051 tgl@sss.pgh.pa.us        2979                 :             83 :                      quote_identifier(get_language_name(proc->prolang, false)));
                               2980                 :                : 
                               2981                 :                :     /* Emit some miscellaneous options on one line */
 6261                          2982                 :             83 :     oldlen = buf.len;
                               2983                 :                : 
 2797 peter_e@gmx.net          2984         [ -  + ]:             83 :     if (proc->prokind == PROKIND_WINDOW)
 6145 tgl@sss.pgh.pa.us        2985                 :UBC           0 :         appendStringInfoString(&buf, " WINDOW");
 6261 tgl@sss.pgh.pa.us        2986   [ +  +  +  - ]:CBC          83 :     switch (proc->provolatile)
                               2987                 :                :     {
                               2988                 :              6 :         case PROVOLATILE_IMMUTABLE:
                               2989                 :              6 :             appendStringInfoString(&buf, " IMMUTABLE");
                               2990                 :              6 :             break;
                               2991                 :             15 :         case PROVOLATILE_STABLE:
                               2992                 :             15 :             appendStringInfoString(&buf, " STABLE");
                               2993                 :             15 :             break;
                               2994                 :             62 :         case PROVOLATILE_VOLATILE:
                               2995                 :             62 :             break;
                               2996                 :                :     }
                               2997                 :                : 
 3472 rhaas@postgresql.org     2998   [ +  -  +  - ]:             83 :     switch (proc->proparallel)
                               2999                 :                :     {
                               3000                 :             14 :         case PROPARALLEL_SAFE:
                               3001                 :             14 :             appendStringInfoString(&buf, " PARALLEL SAFE");
                               3002                 :             14 :             break;
 3472 rhaas@postgresql.org     3003                 :UBC           0 :         case PROPARALLEL_RESTRICTED:
                               3004                 :              0 :             appendStringInfoString(&buf, " PARALLEL RESTRICTED");
                               3005                 :              0 :             break;
 3472 rhaas@postgresql.org     3006                 :CBC          69 :         case PROPARALLEL_UNSAFE:
                               3007                 :             69 :             break;
                               3008                 :                :     }
                               3009                 :                : 
 6261 tgl@sss.pgh.pa.us        3010         [ +  + ]:             83 :     if (proc->proisstrict)
                               3011                 :             25 :         appendStringInfoString(&buf, " STRICT");
                               3012         [ +  + ]:             83 :     if (proc->prosecdef)
                               3013                 :              3 :         appendStringInfoString(&buf, " SECURITY DEFINER");
 3806                          3014         [ -  + ]:             83 :     if (proc->proleakproof)
 3806 tgl@sss.pgh.pa.us        3015                 :UBC           0 :         appendStringInfoString(&buf, " LEAKPROOF");
                               3016                 :                : 
                               3017                 :                :     /* This code for the default cost and rows should match functioncmds.c */
 6261 tgl@sss.pgh.pa.us        3018         [ +  - ]:CBC          83 :     if (proc->prolang == INTERNALlanguageId ||
                               3019         [ +  + ]:             83 :         proc->prolang == ClanguageId)
                               3020                 :              5 :         procost = 1;
                               3021                 :                :     else
                               3022                 :             78 :         procost = 100;
                               3023         [ +  + ]:             83 :     if (proc->procost != procost)
                               3024                 :              3 :         appendStringInfo(&buf, " COST %g", proc->procost);
                               3025                 :                : 
                               3026   [ +  +  -  + ]:             83 :     if (proc->prorows > 0 && proc->prorows != 1000)
 6261 tgl@sss.pgh.pa.us        3027                 :UBC           0 :         appendStringInfo(&buf, " ROWS %g", proc->prorows);
                               3028                 :                : 
 2453 tgl@sss.pgh.pa.us        3029         [ -  + ]:CBC          83 :     if (proc->prosupport)
                               3030                 :                :     {
                               3031                 :                :         Oid         argtypes[1];
                               3032                 :                : 
                               3033                 :                :         /*
                               3034                 :                :          * We should qualify the support function's name if it wouldn't be
                               3035                 :                :          * resolved by lookup in the current search path.
                               3036                 :                :          */
 2453 tgl@sss.pgh.pa.us        3037                 :UBC           0 :         argtypes[0] = INTERNALOID;
                               3038                 :              0 :         appendStringInfo(&buf, " SUPPORT %s",
                               3039                 :                :                          generate_function_name(proc->prosupport, 1,
                               3040                 :                :                                                 NIL, argtypes,
                               3041                 :                :                                                 false, NULL, false));
                               3042                 :                :     }
                               3043                 :                : 
 6261 tgl@sss.pgh.pa.us        3044         [ +  + ]:CBC          83 :     if (oldlen != buf.len)
                               3045                 :             32 :         appendStringInfoChar(&buf, '\n');
                               3046                 :                : 
                               3047                 :                :     /* Emit any proconfig options, one per line */
                               3048                 :             83 :     tmp = SysCacheGetAttr(PROCOID, proctup, Anum_pg_proc_proconfig, &isnull);
                               3049         [ +  + ]:             83 :     if (!isnull)
                               3050                 :                :     {
 5983 bruce@momjian.us         3051                 :              3 :         ArrayType  *a = DatumGetArrayTypeP(tmp);
                               3052                 :                :         int         i;
                               3053                 :                : 
 6261 tgl@sss.pgh.pa.us        3054         [ -  + ]:              3 :         Assert(ARR_ELEMTYPE(a) == TEXTOID);
                               3055         [ -  + ]:              3 :         Assert(ARR_NDIM(a) == 1);
                               3056         [ -  + ]:              3 :         Assert(ARR_LBOUND(a)[0] == 1);
                               3057                 :                : 
                               3058         [ +  + ]:             18 :         for (i = 1; i <= ARR_DIMS(a)[0]; i++)
                               3059                 :                :         {
                               3060                 :                :             Datum       d;
                               3061                 :                : 
                               3062                 :             15 :             d = array_ref(a, 1, &i,
                               3063                 :                :                           -1 /* varlenarray */ ,
                               3064                 :                :                           -1 /* TEXT's typlen */ ,
                               3065                 :                :                           false /* TEXT's typbyval */ ,
                               3066                 :                :                           TYPALIGN_INT /* TEXT's typalign */ ,
                               3067                 :                :                           &isnull);
                               3068         [ +  - ]:             15 :             if (!isnull)
                               3069                 :                :             {
                               3070                 :             15 :                 char       *configitem = TextDatumGetCString(d);
                               3071                 :                :                 char       *pos;
                               3072                 :                : 
                               3073                 :             15 :                 pos = strchr(configitem, '=');
                               3074         [ -  + ]:             15 :                 if (pos == NULL)
 6261 tgl@sss.pgh.pa.us        3075                 :UBC           0 :                     continue;
 6261 tgl@sss.pgh.pa.us        3076                 :CBC          15 :                 *pos++ = '\0';
                               3077                 :                : 
                               3078                 :             15 :                 appendStringInfo(&buf, " SET %s TO ",
                               3079                 :                :                                  quote_identifier(configitem));
                               3080                 :                : 
                               3081                 :                :                 /*
                               3082                 :                :                  * Variables that are marked GUC_LIST_QUOTE were already fully
                               3083                 :                :                  * quoted by flatten_set_variable_args() before they were put
                               3084                 :                :                  * into the proconfig array.  However, because the quoting
                               3085                 :                :                  * rules used there aren't exactly like SQL's, we have to
                               3086                 :                :                  * break the list value apart and then quote the elements as
                               3087                 :                :                  * string literals.  (The elements may be double-quoted as-is,
                               3088                 :                :                  * but we can't just feed them to the SQL parser; it would do
                               3089                 :                :                  * the wrong thing with elements that are zero-length or
                               3090                 :                :                  * longer than NAMEDATALEN.)
                               3091                 :                :                  *
                               3092                 :                :                  * Variables that are not so marked should just be emitted as
                               3093                 :                :                  * simple string literals.  If the variable is not known to
                               3094                 :                :                  * guc.c, we'll do that; this makes it unsafe to use
                               3095                 :                :                  * GUC_LIST_QUOTE for extension variables.
                               3096                 :                :                  */
 2778                          3097         [ +  + ]:             15 :                 if (GetConfigOptionFlags(configitem, true) & GUC_LIST_QUOTE)
                               3098                 :                :                 {
                               3099                 :                :                     List       *namelist;
                               3100                 :                :                     ListCell   *lc;
                               3101                 :                : 
                               3102                 :                :                     /* Parse string into list of identifiers */
 2646                          3103         [ -  + ]:              6 :                     if (!SplitGUCList(pos, ',', &namelist))
                               3104                 :                :                     {
                               3105                 :                :                         /* this shouldn't fail really */
 2646 tgl@sss.pgh.pa.us        3106         [ #  # ]:UBC           0 :                         elog(ERROR, "invalid list syntax in proconfig item");
                               3107                 :                :                     }
 2646 tgl@sss.pgh.pa.us        3108   [ +  -  +  +  :CBC          21 :                     foreach(lc, namelist)
                                              +  + ]
                               3109                 :                :                     {
                               3110                 :             15 :                         char       *curname = (char *) lfirst(lc);
                               3111                 :                : 
                               3112                 :             15 :                         simple_quote_literal(&buf, curname);
 2297                          3113         [ +  + ]:             15 :                         if (lnext(namelist, lc))
 2646                          3114                 :              9 :                             appendStringInfoString(&buf, ", ");
                               3115                 :                :                     }
                               3116                 :                :                 }
                               3117                 :                :                 else
 6261                          3118                 :              9 :                     simple_quote_literal(&buf, pos);
                               3119                 :             15 :                 appendStringInfoChar(&buf, '\n');
                               3120                 :                :             }
                               3121                 :                :         }
                               3122                 :                :     }
                               3123                 :                : 
                               3124                 :                :     /* And finally the function definition ... */
 1519                          3125                 :             83 :     (void) SysCacheGetAttr(PROCOID, proctup, Anum_pg_proc_prosqlbody, &isnull);
 1665 peter@eisentraut.org     3126   [ +  +  +  + ]:             83 :     if (proc->prolang == SQLlanguageId && !isnull)
                               3127                 :                :     {
                               3128                 :             57 :         print_function_sqlbody(&buf, proctup);
                               3129                 :                :     }
                               3130                 :                :     else
                               3131                 :                :     {
 1630 tgl@sss.pgh.pa.us        3132                 :             26 :         appendStringInfoString(&buf, "AS ");
                               3133                 :                : 
                               3134                 :             26 :         tmp = SysCacheGetAttr(PROCOID, proctup, Anum_pg_proc_probin, &isnull);
                               3135         [ +  + ]:             26 :         if (!isnull)
                               3136                 :                :         {
                               3137                 :              5 :             simple_quote_literal(&buf, TextDatumGetCString(tmp));
                               3138                 :              5 :             appendStringInfoString(&buf, ", "); /* assume prosrc isn't null */
                               3139                 :                :         }
                               3140                 :                : 
  948 dgustafsson@postgres     3141                 :             26 :         tmp = SysCacheGetAttrNotNull(PROCOID, proctup, Anum_pg_proc_prosrc);
 1630 tgl@sss.pgh.pa.us        3142                 :             26 :         prosrc = TextDatumGetCString(tmp);
                               3143                 :                : 
                               3144                 :                :         /*
                               3145                 :                :          * We always use dollar quoting.  Figure out a suitable delimiter.
                               3146                 :                :          *
                               3147                 :                :          * Since the user is likely to be editing the function body string, we
                               3148                 :                :          * shouldn't use a short delimiter that he might easily create a
                               3149                 :                :          * conflict with.  Hence prefer "$function$"/"$procedure$", but extend
                               3150                 :                :          * if needed.
                               3151                 :                :          */
                               3152                 :             26 :         initStringInfo(&dq);
                               3153                 :             26 :         appendStringInfoChar(&dq, '$');
                               3154         [ +  + ]:             26 :         appendStringInfoString(&dq, (isfunction ? "function" : "procedure"));
                               3155         [ -  + ]:             26 :         while (strstr(prosrc, dq.data) != NULL)
 1630 tgl@sss.pgh.pa.us        3156                 :UBC           0 :             appendStringInfoChar(&dq, 'x');
 1630 tgl@sss.pgh.pa.us        3157                 :CBC          26 :         appendStringInfoChar(&dq, '$');
                               3158                 :                : 
                               3159                 :             26 :         appendBinaryStringInfo(&buf, dq.data, dq.len);
                               3160                 :             26 :         appendStringInfoString(&buf, prosrc);
                               3161                 :             26 :         appendBinaryStringInfo(&buf, dq.data, dq.len);
                               3162                 :                :     }
                               3163                 :                : 
 4380 rhaas@postgresql.org     3164                 :             83 :     appendStringInfoChar(&buf, '\n');
                               3165                 :                : 
 6261 tgl@sss.pgh.pa.us        3166                 :             83 :     ReleaseSysCache(proctup);
                               3167                 :                : 
                               3168                 :             83 :     PG_RETURN_TEXT_P(string_to_text(buf.data));
                               3169                 :                : }
                               3170                 :                : 
                               3171                 :                : /*
                               3172                 :                :  * pg_get_function_arguments
                               3173                 :                :  *      Get a nicely-formatted list of arguments for a function.
                               3174                 :                :  *      This is everything that would go between the parentheses in
                               3175                 :                :  *      CREATE FUNCTION.
                               3176                 :                :  */
                               3177                 :                : Datum
 6311                          3178                 :           2310 : pg_get_function_arguments(PG_FUNCTION_ARGS)
                               3179                 :                : {
                               3180                 :           2310 :     Oid         funcid = PG_GETARG_OID(0);
                               3181                 :                :     StringInfoData buf;
                               3182                 :                :     HeapTuple   proctup;
                               3183                 :                : 
 5735 rhaas@postgresql.org     3184                 :           2310 :     proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
 6311 tgl@sss.pgh.pa.us        3185         [ +  + ]:           2310 :     if (!HeapTupleIsValid(proctup))
 3378 rhaas@postgresql.org     3186                 :              3 :         PG_RETURN_NULL();
                               3187                 :                : 
                               3188                 :           2307 :     initStringInfo(&buf);
                               3189                 :                : 
 6172 peter_e@gmx.net          3190                 :           2307 :     (void) print_function_arguments(&buf, proctup, false, true);
                               3191                 :                : 
 6311 tgl@sss.pgh.pa.us        3192                 :           2307 :     ReleaseSysCache(proctup);
                               3193                 :                : 
                               3194                 :           2307 :     PG_RETURN_TEXT_P(string_to_text(buf.data));
                               3195                 :                : }
                               3196                 :                : 
                               3197                 :                : /*
                               3198                 :                :  * pg_get_function_identity_arguments
                               3199                 :                :  *      Get a formatted list of arguments for a function.
                               3200                 :                :  *      This is everything that would go between the parentheses in
                               3201                 :                :  *      ALTER FUNCTION, etc.  In particular, don't print defaults.
                               3202                 :                :  */
                               3203                 :                : Datum
 6172 peter_e@gmx.net          3204                 :           2044 : pg_get_function_identity_arguments(PG_FUNCTION_ARGS)
                               3205                 :                : {
                               3206                 :           2044 :     Oid         funcid = PG_GETARG_OID(0);
                               3207                 :                :     StringInfoData buf;
                               3208                 :                :     HeapTuple   proctup;
                               3209                 :                : 
 5735 rhaas@postgresql.org     3210                 :           2044 :     proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
 6172 peter_e@gmx.net          3211         [ +  + ]:           2044 :     if (!HeapTupleIsValid(proctup))
 3378 rhaas@postgresql.org     3212                 :              3 :         PG_RETURN_NULL();
                               3213                 :                : 
                               3214                 :           2041 :     initStringInfo(&buf);
                               3215                 :                : 
 6172 peter_e@gmx.net          3216                 :           2041 :     (void) print_function_arguments(&buf, proctup, false, false);
                               3217                 :                : 
                               3218                 :           2041 :     ReleaseSysCache(proctup);
                               3219                 :                : 
                               3220                 :           2041 :     PG_RETURN_TEXT_P(string_to_text(buf.data));
                               3221                 :                : }
                               3222                 :                : 
                               3223                 :                : /*
                               3224                 :                :  * pg_get_function_result
                               3225                 :                :  *      Get a nicely-formatted version of the result type of a function.
                               3226                 :                :  *      This is what would appear after RETURNS in CREATE FUNCTION.
                               3227                 :                :  */
                               3228                 :                : Datum
 6311 tgl@sss.pgh.pa.us        3229                 :           2018 : pg_get_function_result(PG_FUNCTION_ARGS)
                               3230                 :                : {
                               3231                 :           2018 :     Oid         funcid = PG_GETARG_OID(0);
                               3232                 :                :     StringInfoData buf;
                               3233                 :                :     HeapTuple   proctup;
                               3234                 :                : 
 5735 rhaas@postgresql.org     3235                 :           2018 :     proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
 6311 tgl@sss.pgh.pa.us        3236         [ +  + ]:           2018 :     if (!HeapTupleIsValid(proctup))
 3378 rhaas@postgresql.org     3237                 :              3 :         PG_RETURN_NULL();
                               3238                 :                : 
 2797 peter_e@gmx.net          3239         [ +  + ]:           2015 :     if (((Form_pg_proc) GETSTRUCT(proctup))->prokind == PROKIND_PROCEDURE)
                               3240                 :                :     {
 2889                          3241                 :            119 :         ReleaseSysCache(proctup);
                               3242                 :            119 :         PG_RETURN_NULL();
                               3243                 :                :     }
                               3244                 :                : 
 3378 rhaas@postgresql.org     3245                 :           1896 :     initStringInfo(&buf);
                               3246                 :                : 
 6261 tgl@sss.pgh.pa.us        3247                 :           1896 :     print_function_rettype(&buf, proctup);
                               3248                 :                : 
                               3249                 :           1896 :     ReleaseSysCache(proctup);
                               3250                 :                : 
                               3251                 :           1896 :     PG_RETURN_TEXT_P(string_to_text(buf.data));
                               3252                 :                : }
                               3253                 :                : 
                               3254                 :                : /*
                               3255                 :                :  * Guts of pg_get_function_result: append the function's return type
                               3256                 :                :  * to the specified buffer.
                               3257                 :                :  */
                               3258                 :                : static void
                               3259                 :           1969 : print_function_rettype(StringInfo buf, HeapTuple proctup)
                               3260                 :                : {
                               3261                 :           1969 :     Form_pg_proc proc = (Form_pg_proc) GETSTRUCT(proctup);
                               3262                 :           1969 :     int         ntabargs = 0;
                               3263                 :                :     StringInfoData rbuf;
                               3264                 :                : 
                               3265                 :           1969 :     initStringInfo(&rbuf);
                               3266                 :                : 
                               3267         [ +  + ]:           1969 :     if (proc->proretset)
                               3268                 :                :     {
                               3269                 :                :         /* It might be a table function; try to print the arguments */
                               3270                 :            202 :         appendStringInfoString(&rbuf, "TABLE(");
 6158                          3271                 :            202 :         ntabargs = print_function_arguments(&rbuf, proctup, true, false);
 6311                          3272         [ +  + ]:            202 :         if (ntabargs > 0)
 3823 peter_e@gmx.net          3273                 :             38 :             appendStringInfoChar(&rbuf, ')');
                               3274                 :                :         else
 6261 tgl@sss.pgh.pa.us        3275                 :            164 :             resetStringInfo(&rbuf);
                               3276                 :                :     }
                               3277                 :                : 
 6311                          3278         [ +  + ]:           1969 :     if (ntabargs == 0)
                               3279                 :                :     {
                               3280                 :                :         /* Not a table function, so do the normal thing */
 6261                          3281         [ +  + ]:           1931 :         if (proc->proretset)
                               3282                 :            164 :             appendStringInfoString(&rbuf, "SETOF ");
                               3283                 :           1931 :         appendStringInfoString(&rbuf, format_type_be(proc->prorettype));
                               3284                 :                :     }
                               3285                 :                : 
 2289 drowley@postgresql.o     3286                 :           1969 :     appendBinaryStringInfo(buf, rbuf.data, rbuf.len);
 6311 tgl@sss.pgh.pa.us        3287                 :           1969 : }
                               3288                 :                : 
                               3289                 :                : /*
                               3290                 :                :  * Common code for pg_get_function_arguments and pg_get_function_result:
                               3291                 :                :  * append the desired subset of arguments to buf.  We print only TABLE
                               3292                 :                :  * arguments when print_table_args is true, and all the others when it's false.
                               3293                 :                :  * We print argument defaults only if print_defaults is true.
                               3294                 :                :  * Function return value is the number of arguments printed.
                               3295                 :                :  */
                               3296                 :                : static int
                               3297                 :           4633 : print_function_arguments(StringInfo buf, HeapTuple proctup,
                               3298                 :                :                          bool print_table_args, bool print_defaults)
                               3299                 :                : {
 6158                          3300                 :           4633 :     Form_pg_proc proc = (Form_pg_proc) GETSTRUCT(proctup);
                               3301                 :                :     int         numargs;
                               3302                 :                :     Oid        *argtypes;
                               3303                 :                :     char      **argnames;
                               3304                 :                :     char       *argmodes;
 4327                          3305                 :           4633 :     int         insertorderbyat = -1;
                               3306                 :                :     int         argsprinted;
                               3307                 :                :     int         inputargno;
                               3308                 :                :     int         nlackdefaults;
 2297                          3309                 :           4633 :     List       *argdefaults = NIL;
 6158                          3310                 :           4633 :     ListCell   *nextargdefault = NULL;
                               3311                 :                :     int         i;
                               3312                 :                : 
 6311                          3313                 :           4633 :     numargs = get_func_arg_info(proctup,
                               3314                 :                :                                 &argtypes, &argnames, &argmodes);
                               3315                 :                : 
 6158                          3316                 :           4633 :     nlackdefaults = numargs;
                               3317   [ +  +  +  + ]:           4633 :     if (print_defaults && proc->pronargdefaults > 0)
                               3318                 :                :     {
                               3319                 :                :         Datum       proargdefaults;
                               3320                 :                :         bool        isnull;
                               3321                 :                : 
                               3322                 :             19 :         proargdefaults = SysCacheGetAttr(PROCOID, proctup,
                               3323                 :                :                                          Anum_pg_proc_proargdefaults,
                               3324                 :                :                                          &isnull);
                               3325         [ +  - ]:             19 :         if (!isnull)
                               3326                 :                :         {
                               3327                 :                :             char       *str;
                               3328                 :                : 
                               3329                 :             19 :             str = TextDatumGetCString(proargdefaults);
 3171 peter_e@gmx.net          3330                 :             19 :             argdefaults = castNode(List, stringToNode(str));
 6158 tgl@sss.pgh.pa.us        3331                 :             19 :             pfree(str);
                               3332                 :             19 :             nextargdefault = list_head(argdefaults);
                               3333                 :                :             /* nlackdefaults counts only *input* arguments lacking defaults */
                               3334                 :             19 :             nlackdefaults = proc->pronargs - list_length(argdefaults);
                               3335                 :                :         }
                               3336                 :                :     }
                               3337                 :                : 
                               3338                 :                :     /* Check for special treatment of ordered-set aggregates */
 2797 peter_e@gmx.net          3339         [ +  + ]:           4633 :     if (proc->prokind == PROKIND_AGGREGATE)
                               3340                 :                :     {
                               3341                 :                :         HeapTuple   aggtup;
                               3342                 :                :         Form_pg_aggregate agg;
                               3343                 :                : 
  831 michael@paquier.xyz      3344                 :            585 :         aggtup = SearchSysCache1(AGGFNOID, ObjectIdGetDatum(proc->oid));
 4327 tgl@sss.pgh.pa.us        3345         [ -  + ]:            585 :         if (!HeapTupleIsValid(aggtup))
 4327 tgl@sss.pgh.pa.us        3346         [ #  # ]:UBC           0 :             elog(ERROR, "cache lookup failed for aggregate %u",
                               3347                 :                :                  proc->oid);
 4327 tgl@sss.pgh.pa.us        3348                 :CBC         585 :         agg = (Form_pg_aggregate) GETSTRUCT(aggtup);
                               3349         [ +  + ]:            585 :         if (AGGKIND_IS_ORDERED_SET(agg->aggkind))
                               3350                 :             26 :             insertorderbyat = agg->aggnumdirectargs;
                               3351                 :            585 :         ReleaseSysCache(aggtup);
                               3352                 :                :     }
                               3353                 :                : 
 6311                          3354                 :           4633 :     argsprinted = 0;
 6158                          3355                 :           4633 :     inputargno = 0;
 6311                          3356         [ +  + ]:           9338 :     for (i = 0; i < numargs; i++)
                               3357                 :                :     {
 5983 bruce@momjian.us         3358                 :           4705 :         Oid         argtype = argtypes[i];
                               3359         [ +  + ]:           4705 :         char       *argname = argnames ? argnames[i] : NULL;
                               3360         [ +  + ]:           4705 :         char        argmode = argmodes ? argmodes[i] : PROARGMODE_IN;
                               3361                 :                :         const char *modename;
                               3362                 :                :         bool        isinput;
                               3363                 :                : 
 6311 tgl@sss.pgh.pa.us        3364   [ +  +  +  +  :           4705 :         switch (argmode)
                                              +  - ]
                               3365                 :                :         {
                               3366                 :           3866 :             case PROARGMODE_IN:
                               3367                 :                : 
                               3368                 :                :                 /*
                               3369                 :                :                  * For procedures, explicitly mark all argument modes, so as
                               3370                 :                :                  * to avoid ambiguity with the SQL syntax for DROP PROCEDURE.
                               3371                 :                :                  */
 1601                          3372         [ +  + ]:           3866 :                 if (proc->prokind == PROKIND_PROCEDURE)
                               3373                 :            266 :                     modename = "IN ";
                               3374                 :                :                 else
                               3375                 :           3600 :                     modename = "";
 6158                          3376                 :           3866 :                 isinput = true;
 6311                          3377                 :           3866 :                 break;
                               3378                 :             50 :             case PROARGMODE_INOUT:
                               3379                 :             50 :                 modename = "INOUT ";
 6158                          3380                 :             50 :                 isinput = true;
 6311                          3381                 :             50 :                 break;
                               3382                 :            478 :             case PROARGMODE_OUT:
                               3383                 :            478 :                 modename = "OUT ";
 6158                          3384                 :            478 :                 isinput = false;
 6311                          3385                 :            478 :                 break;
                               3386                 :             89 :             case PROARGMODE_VARIADIC:
                               3387                 :             89 :                 modename = "VARIADIC ";
 6158                          3388                 :             89 :                 isinput = true;
 6311                          3389                 :             89 :                 break;
                               3390                 :            222 :             case PROARGMODE_TABLE:
                               3391                 :            222 :                 modename = "";
 6158                          3392                 :            222 :                 isinput = false;
 6311                          3393                 :            222 :                 break;
 6311 tgl@sss.pgh.pa.us        3394                 :UBC           0 :             default:
                               3395         [ #  # ]:              0 :                 elog(ERROR, "invalid parameter mode '%c'", argmode);
                               3396                 :                :                 modename = NULL;    /* keep compiler quiet */
                               3397                 :                :                 isinput = false;
                               3398                 :                :                 break;
                               3399                 :                :         }
 6158 tgl@sss.pgh.pa.us        3400         [ +  + ]:CBC        4705 :         if (isinput)
                               3401                 :           4005 :             inputargno++;       /* this is a 1-based counter */
                               3402                 :                : 
                               3403         [ +  + ]:           4705 :         if (print_table_args != (argmode == PROARGMODE_TABLE))
                               3404                 :            382 :             continue;
                               3405                 :                : 
 4327                          3406         [ +  + ]:           4323 :         if (argsprinted == insertorderbyat)
                               3407                 :                :         {
                               3408         [ +  - ]:             26 :             if (argsprinted)
                               3409                 :             26 :                 appendStringInfoChar(buf, ' ');
                               3410                 :             26 :             appendStringInfoString(buf, "ORDER BY ");
                               3411                 :                :         }
                               3412         [ +  + ]:           4297 :         else if (argsprinted)
 6311                          3413                 :           1388 :             appendStringInfoString(buf, ", ");
                               3414                 :                : 
                               3415                 :           4323 :         appendStringInfoString(buf, modename);
 6158                          3416   [ +  +  +  + ]:           4323 :         if (argname && argname[0])
 5985                          3417                 :           1553 :             appendStringInfo(buf, "%s ", quote_identifier(argname));
 6311                          3418                 :           4323 :         appendStringInfoString(buf, format_type_be(argtype));
 6158                          3419   [ +  +  +  +  :           4323 :         if (print_defaults && isinput && inputargno > nlackdefaults)
                                              +  + ]
                               3420                 :                :         {
                               3421                 :                :             Node       *expr;
                               3422                 :                : 
                               3423         [ -  + ]:             29 :             Assert(nextargdefault != NULL);
                               3424                 :             29 :             expr = (Node *) lfirst(nextargdefault);
 2297                          3425                 :             29 :             nextargdefault = lnext(argdefaults, nextargdefault);
                               3426                 :                : 
 6158                          3427                 :             29 :             appendStringInfo(buf, " DEFAULT %s",
                               3428                 :                :                              deparse_expression(expr, NIL, false, false));
                               3429                 :                :         }
 6311                          3430                 :           4323 :         argsprinted++;
                               3431                 :                : 
                               3432                 :                :         /* nasty hack: print the last arg twice for variadic ordered-set agg */
 4327                          3433   [ +  +  +  + ]:           4323 :         if (argsprinted == insertorderbyat && i == numargs - 1)
                               3434                 :                :         {
                               3435                 :             13 :             i--;
                               3436                 :                :             /* aggs shouldn't have defaults anyway, but just to be sure ... */
                               3437                 :             13 :             print_defaults = false;
                               3438                 :                :         }
                               3439                 :                :     }
                               3440                 :                : 
 6311                          3441                 :           4633 :     return argsprinted;
                               3442                 :                : }
                               3443                 :                : 
                               3444                 :                : static bool
 4354 peter_e@gmx.net          3445                 :             48 : is_input_argument(int nth, const char *argmodes)
                               3446                 :                : {
                               3447                 :                :     return (!argmodes
                               3448         [ +  + ]:             21 :             || argmodes[nth] == PROARGMODE_IN
                               3449         [ +  - ]:              9 :             || argmodes[nth] == PROARGMODE_INOUT
                               3450   [ +  +  -  + ]:             69 :             || argmodes[nth] == PROARGMODE_VARIADIC);
                               3451                 :                : }
                               3452                 :                : 
                               3453                 :                : /*
                               3454                 :                :  * Append used transformed types to specified buffer
                               3455                 :                :  */
                               3456                 :                : static void
 3838                          3457                 :             83 : print_function_trftypes(StringInfo buf, HeapTuple proctup)
                               3458                 :                : {
                               3459                 :                :     Oid        *trftypes;
                               3460                 :                :     int         ntypes;
                               3461                 :                : 
                               3462                 :             83 :     ntypes = get_func_trftypes(proctup, &trftypes);
                               3463         [ +  + ]:             83 :     if (ntypes > 0)
                               3464                 :                :     {
                               3465                 :                :         int         i;
                               3466                 :                : 
 1737 tgl@sss.pgh.pa.us        3467                 :              3 :         appendStringInfoString(buf, " TRANSFORM ");
 3838 peter_e@gmx.net          3468         [ +  + ]:              8 :         for (i = 0; i < ntypes; i++)
                               3469                 :                :         {
                               3470         [ +  + ]:              5 :             if (i != 0)
                               3471                 :              2 :                 appendStringInfoString(buf, ", ");
 3827 magnus@hagander.net      3472                 :              5 :             appendStringInfo(buf, "FOR TYPE %s", format_type_be(trftypes[i]));
                               3473                 :                :         }
 1737 tgl@sss.pgh.pa.us        3474                 :              3 :         appendStringInfoChar(buf, '\n');
                               3475                 :                :     }
 3838 peter_e@gmx.net          3476                 :             83 : }
                               3477                 :                : 
                               3478                 :                : /*
                               3479                 :                :  * Get textual representation of a function argument's default value.  The
                               3480                 :                :  * second argument of this function is the argument number among all arguments
                               3481                 :                :  * (i.e. proallargtypes, *not* proargtypes), starting with 1, because that's
                               3482                 :                :  * how information_schema.sql uses it.
                               3483                 :                :  */
                               3484                 :                : Datum
 4354                          3485                 :             27 : pg_get_function_arg_default(PG_FUNCTION_ARGS)
                               3486                 :                : {
                               3487                 :             27 :     Oid         funcid = PG_GETARG_OID(0);
                               3488                 :             27 :     int32       nth_arg = PG_GETARG_INT32(1);
                               3489                 :                :     HeapTuple   proctup;
                               3490                 :                :     Form_pg_proc proc;
                               3491                 :                :     int         numargs;
                               3492                 :                :     Oid        *argtypes;
                               3493                 :                :     char      **argnames;
                               3494                 :                :     char       *argmodes;
                               3495                 :                :     int         i;
                               3496                 :                :     List       *argdefaults;
                               3497                 :                :     Node       *node;
                               3498                 :                :     char       *str;
                               3499                 :                :     int         nth_inputarg;
                               3500                 :                :     Datum       proargdefaults;
                               3501                 :                :     bool        isnull;
                               3502                 :                :     int         nth_default;
                               3503                 :                : 
                               3504                 :             27 :     proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
                               3505         [ +  + ]:             27 :     if (!HeapTupleIsValid(proctup))
 3378 rhaas@postgresql.org     3506                 :              6 :         PG_RETURN_NULL();
                               3507                 :                : 
 4354 peter_e@gmx.net          3508                 :             21 :     numargs = get_func_arg_info(proctup, &argtypes, &argnames, &argmodes);
                               3509   [ +  -  +  -  :             21 :     if (nth_arg < 1 || nth_arg > numargs || !is_input_argument(nth_arg - 1, argmodes))
                                              +  + ]
                               3510                 :                :     {
                               3511                 :              6 :         ReleaseSysCache(proctup);
                               3512                 :              6 :         PG_RETURN_NULL();
                               3513                 :                :     }
                               3514                 :                : 
                               3515                 :             15 :     nth_inputarg = 0;
                               3516         [ +  + ]:             42 :     for (i = 0; i < nth_arg; i++)
                               3517         [ +  + ]:             27 :         if (is_input_argument(i, argmodes))
                               3518                 :             24 :             nth_inputarg++;
                               3519                 :                : 
                               3520                 :             15 :     proargdefaults = SysCacheGetAttr(PROCOID, proctup,
                               3521                 :                :                                      Anum_pg_proc_proargdefaults,
                               3522                 :                :                                      &isnull);
                               3523         [ -  + ]:             15 :     if (isnull)
                               3524                 :                :     {
 4354 peter_e@gmx.net          3525                 :UBC           0 :         ReleaseSysCache(proctup);
                               3526                 :              0 :         PG_RETURN_NULL();
                               3527                 :                :     }
                               3528                 :                : 
 4354 peter_e@gmx.net          3529                 :CBC          15 :     str = TextDatumGetCString(proargdefaults);
 3171                          3530                 :             15 :     argdefaults = castNode(List, stringToNode(str));
 4354                          3531                 :             15 :     pfree(str);
                               3532                 :                : 
                               3533                 :             15 :     proc = (Form_pg_proc) GETSTRUCT(proctup);
                               3534                 :                : 
                               3535                 :                :     /*
                               3536                 :                :      * Calculate index into proargdefaults: proargdefaults corresponds to the
                               3537                 :                :      * last N input arguments, where N = pronargdefaults.
                               3538                 :                :      */
                               3539                 :             15 :     nth_default = nth_inputarg - 1 - (proc->pronargs - proc->pronargdefaults);
                               3540                 :                : 
                               3541   [ +  +  -  + ]:             15 :     if (nth_default < 0 || nth_default >= list_length(argdefaults))
                               3542                 :                :     {
                               3543                 :              3 :         ReleaseSysCache(proctup);
                               3544                 :              3 :         PG_RETURN_NULL();
                               3545                 :                :     }
                               3546                 :             12 :     node = list_nth(argdefaults, nth_default);
                               3547                 :             12 :     str = deparse_expression(node, NIL, false, false);
                               3548                 :                : 
                               3549                 :             12 :     ReleaseSysCache(proctup);
                               3550                 :                : 
                               3551                 :             12 :     PG_RETURN_TEXT_P(string_to_text(str));
                               3552                 :                : }
                               3553                 :                : 
                               3554                 :                : static void
 1665 peter@eisentraut.org     3555                 :            105 : print_function_sqlbody(StringInfo buf, HeapTuple proctup)
                               3556                 :                : {
                               3557                 :                :     int         numargs;
                               3558                 :                :     Oid        *argtypes;
                               3559                 :                :     char      **argnames;
                               3560                 :                :     char       *argmodes;
                               3561                 :            105 :     deparse_namespace dpns = {0};
                               3562                 :                :     Datum       tmp;
                               3563                 :                :     Node       *n;
                               3564                 :                : 
                               3565                 :            105 :     dpns.funcname = pstrdup(NameStr(((Form_pg_proc) GETSTRUCT(proctup))->proname));
                               3566                 :            105 :     numargs = get_func_arg_info(proctup,
                               3567                 :                :                                 &argtypes, &argnames, &argmodes);
                               3568                 :            105 :     dpns.numargs = numargs;
                               3569                 :            105 :     dpns.argnames = argnames;
                               3570                 :                : 
  948 dgustafsson@postgres     3571                 :            105 :     tmp = SysCacheGetAttrNotNull(PROCOID, proctup, Anum_pg_proc_prosqlbody);
 1665 peter@eisentraut.org     3572                 :            105 :     n = stringToNode(TextDatumGetCString(tmp));
                               3573                 :                : 
                               3574         [ +  + ]:            105 :     if (IsA(n, List))
                               3575                 :                :     {
                               3576                 :                :         List       *stmts;
                               3577                 :                :         ListCell   *lc;
                               3578                 :                : 
                               3579                 :             82 :         stmts = linitial(castNode(List, n));
                               3580                 :                : 
                               3581                 :             82 :         appendStringInfoString(buf, "BEGIN ATOMIC\n");
                               3582                 :                : 
                               3583   [ +  +  +  +  :            159 :         foreach(lc, stmts)
                                              +  + ]
                               3584                 :                :         {
                               3585                 :             77 :             Query      *query = lfirst_node(Query, lc);
                               3586                 :                : 
                               3587                 :                :             /* It seems advisable to get at least AccessShareLock on rels */
 1519 tgl@sss.pgh.pa.us        3588                 :             77 :             AcquireRewriteLocks(query, false, false);
 1256                          3589                 :             77 :             get_query_def(query, buf, list_make1(&dpns), NULL, false,
                               3590                 :                :                           PRETTYFLAG_INDENT, WRAP_COLUMN_DEFAULT, 1);
 1665 peter@eisentraut.org     3591                 :             77 :             appendStringInfoChar(buf, ';');
                               3592                 :             77 :             appendStringInfoChar(buf, '\n');
                               3593                 :                :         }
                               3594                 :                : 
                               3595                 :             82 :         appendStringInfoString(buf, "END");
                               3596                 :                :     }
                               3597                 :                :     else
                               3598                 :                :     {
 1519 tgl@sss.pgh.pa.us        3599                 :             23 :         Query      *query = castNode(Query, n);
                               3600                 :                : 
                               3601                 :                :         /* It seems advisable to get at least AccessShareLock on rels */
                               3602                 :             23 :         AcquireRewriteLocks(query, false, false);
 1256                          3603                 :             23 :         get_query_def(query, buf, list_make1(&dpns), NULL, false,
                               3604                 :                :                       0, WRAP_COLUMN_DEFAULT, 0);
                               3605                 :                :     }
 1665 peter@eisentraut.org     3606                 :            105 : }
                               3607                 :                : 
                               3608                 :                : Datum
                               3609                 :           1756 : pg_get_function_sqlbody(PG_FUNCTION_ARGS)
                               3610                 :                : {
                               3611                 :           1756 :     Oid         funcid = PG_GETARG_OID(0);
                               3612                 :                :     StringInfoData buf;
                               3613                 :                :     HeapTuple   proctup;
                               3614                 :                :     bool        isnull;
                               3615                 :                : 
                               3616                 :           1756 :     initStringInfo(&buf);
                               3617                 :                : 
                               3618                 :                :     /* Look up the function */
                               3619                 :           1756 :     proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
                               3620         [ -  + ]:           1756 :     if (!HeapTupleIsValid(proctup))
 1665 peter@eisentraut.org     3621                 :UBC           0 :         PG_RETURN_NULL();
                               3622                 :                : 
 1519 tgl@sss.pgh.pa.us        3623                 :CBC        1756 :     (void) SysCacheGetAttr(PROCOID, proctup, Anum_pg_proc_prosqlbody, &isnull);
 1665 peter@eisentraut.org     3624         [ +  + ]:           1756 :     if (isnull)
                               3625                 :                :     {
                               3626                 :           1708 :         ReleaseSysCache(proctup);
                               3627                 :           1708 :         PG_RETURN_NULL();
                               3628                 :                :     }
                               3629                 :                : 
                               3630                 :             48 :     print_function_sqlbody(&buf, proctup);
                               3631                 :                : 
                               3632                 :             48 :     ReleaseSysCache(proctup);
                               3633                 :                : 
 1148 drowley@postgresql.o     3634                 :             48 :     PG_RETURN_TEXT_P(cstring_to_text_with_len(buf.data, buf.len));
                               3635                 :                : }
                               3636                 :                : 
                               3637                 :                : 
                               3638                 :                : /*
                               3639                 :                :  * deparse_expression           - General utility for deparsing expressions
                               3640                 :                :  *
                               3641                 :                :  * calls deparse_expression_pretty with all prettyPrinting disabled
                               3642                 :                :  */
                               3643                 :                : char *
 8126 tgl@sss.pgh.pa.us        3644                 :          40455 : deparse_expression(Node *expr, List *dpcontext,
                               3645                 :                :                    bool forceprefix, bool showimplicit)
                               3646                 :                : {
 8121 bruce@momjian.us         3647                 :          40455 :     return deparse_expression_pretty(expr, dpcontext, forceprefix,
                               3648                 :                :                                      showimplicit, 0, 0);
                               3649                 :                : }
                               3650                 :                : 
                               3651                 :                : /* ----------
                               3652                 :                :  * deparse_expression_pretty    - General utility for deparsing expressions
                               3653                 :                :  *
                               3654                 :                :  * expr is the node tree to be deparsed.  It must be a transformed expression
                               3655                 :                :  * tree (ie, not the raw output of gram.y).
                               3656                 :                :  *
                               3657                 :                :  * dpcontext is a list of deparse_namespace nodes representing the context
                               3658                 :                :  * for interpreting Vars in the node tree.  It can be NIL if no Vars are
                               3659                 :                :  * expected.
                               3660                 :                :  *
                               3661                 :                :  * forceprefix is true to force all Vars to be prefixed with their table names.
                               3662                 :                :  *
                               3663                 :                :  * showimplicit is true to force all implicit casts to be shown explicitly.
                               3664                 :                :  *
                               3665                 :                :  * Tries to pretty up the output according to prettyFlags and startIndent.
                               3666                 :                :  *
                               3667                 :                :  * The result is a palloc'd string.
                               3668                 :                :  * ----------
                               3669                 :                :  */
                               3670                 :                : static char *
 8126 tgl@sss.pgh.pa.us        3671                 :          47020 : deparse_expression_pretty(Node *expr, List *dpcontext,
                               3672                 :                :                           bool forceprefix, bool showimplicit,
                               3673                 :                :                           int prettyFlags, int startIndent)
                               3674                 :                : {
                               3675                 :                :     StringInfoData buf;
                               3676                 :                :     deparse_context context;
                               3677                 :                : 
 9522                          3678                 :          47020 :     initStringInfo(&buf);
                               3679                 :          47020 :     context.buf = &buf;
 9022                          3680                 :          47020 :     context.namespaces = dpcontext;
  425                          3681                 :          47020 :     context.resultDesc = NULL;
                               3682                 :          47020 :     context.targetList = NIL;
 6148                          3683                 :          47020 :     context.windowClause = NIL;
 9022                          3684                 :          47020 :     context.varprefix = forceprefix;
 8126                          3685                 :          47020 :     context.prettyFlags = prettyFlags;
 4691                          3686                 :          47020 :     context.wrapColumn = WRAP_COLUMN_DEFAULT;
 8126                          3687                 :          47020 :     context.indentLevel = startIndent;
  425                          3688                 :          47020 :     context.colNamesVisible = true;
                               3689                 :          47020 :     context.inGroupBy = false;
                               3690                 :          47020 :     context.varInOrderBy = false;
 2148                          3691                 :          47020 :     context.appendparents = NULL;
                               3692                 :                : 
 8440                          3693                 :          47020 :     get_rule_expr(expr, &context, showimplicit);
                               3694                 :                : 
 9522                          3695                 :          47020 :     return buf.data;
                               3696                 :                : }
                               3697                 :                : 
                               3698                 :                : /* ----------
                               3699                 :                :  * deparse_context_for          - Build deparse context for a single relation
                               3700                 :                :  *
                               3701                 :                :  * Given the reference name (alias) and OID of a relation, build deparsing
                               3702                 :                :  * context for an expression referencing only that relation (as varno 1,
                               3703                 :                :  * varlevelsup 0).  This is sufficient for many uses of deparse_expression.
                               3704                 :                :  * ----------
                               3705                 :                :  */
                               3706                 :                : List *
 8621                          3707                 :          11791 : deparse_context_for(const char *aliasname, Oid relid)
                               3708                 :                : {
                               3709                 :                :     deparse_namespace *dpns;
                               3710                 :                :     RangeTblEntry *rte;
                               3711                 :                : 
 5586                          3712                 :          11791 :     dpns = (deparse_namespace *) palloc0(sizeof(deparse_namespace));
                               3713                 :                : 
                               3714                 :                :     /* Build a minimal RTE for the rel */
 9022                          3715                 :          11791 :     rte = makeNode(RangeTblEntry);
 8631                          3716                 :          11791 :     rte->rtekind = RTE_RELATION;
 9022                          3717                 :          11791 :     rte->relid = relid;
 5362                          3718                 :          11791 :     rte->relkind = RELKIND_RELATION; /* no need for exactness here */
 2585                          3719                 :          11791 :     rte->rellockmode = AccessShareLock;
 4785                          3720                 :          11791 :     rte->alias = makeAlias(aliasname, NIL);
                               3721                 :          11791 :     rte->eref = rte->alias;
 4830                          3722                 :          11791 :     rte->lateral = false;
 9022                          3723                 :          11791 :     rte->inh = false;
                               3724                 :          11791 :     rte->inFromCl = true;
                               3725                 :                : 
                               3726                 :                :     /* Build one-element rtable */
 7821 neilc@samurai.com        3727                 :          11791 :     dpns->rtable = list_make1(rte);
 2148 tgl@sss.pgh.pa.us        3728                 :          11791 :     dpns->subplans = NIL;
 6231                          3729                 :          11791 :     dpns->ctes = NIL;
 2148                          3730                 :          11791 :     dpns->appendrels = NULL;
 4785                          3731                 :          11791 :     set_rtable_names(dpns, NIL, NULL);
 4684                          3732                 :          11791 :     set_simple_column_names(dpns);
                               3733                 :                : 
                               3734                 :                :     /* Return a one-deep namespace stack */
 7821 neilc@samurai.com        3735                 :          11791 :     return list_make1(dpns);
                               3736                 :                : }
                               3737                 :                : 
                               3738                 :                : /*
                               3739                 :                :  * deparse_context_for_plan_tree - Build deparse context for a Plan tree
                               3740                 :                :  *
                               3741                 :                :  * When deparsing an expression in a Plan tree, we use the plan's rangetable
                               3742                 :                :  * to resolve names of simple Vars.  The initialization of column names for
                               3743                 :                :  * this is rather expensive if the rangetable is large, and it'll be the same
                               3744                 :                :  * for every expression in the Plan tree; so we do it just once and re-use
                               3745                 :                :  * the result of this function for each expression.  (Note that the result
                               3746                 :                :  * is not usable until set_deparse_context_plan() is applied to it.)
                               3747                 :                :  *
                               3748                 :                :  * In addition to the PlannedStmt, pass the per-RTE alias names
                               3749                 :                :  * assigned by a previous call to select_rtable_names_for_explain.
                               3750                 :                :  */
                               3751                 :                : List *
 2148 tgl@sss.pgh.pa.us        3752                 :          12114 : deparse_context_for_plan_tree(PlannedStmt *pstmt, List *rtable_names)
                               3753                 :                : {
                               3754                 :                :     deparse_namespace *dpns;
                               3755                 :                : 
 3939                          3756                 :          12114 :     dpns = (deparse_namespace *) palloc0(sizeof(deparse_namespace));
                               3757                 :                : 
                               3758                 :                :     /* Initialize fields that stay the same across the whole plan tree */
 2148                          3759                 :          12114 :     dpns->rtable = pstmt->rtable;
 3939                          3760                 :          12114 :     dpns->rtable_names = rtable_names;
 2148                          3761                 :          12114 :     dpns->subplans = pstmt->subplans;
 3939                          3762                 :          12114 :     dpns->ctes = NIL;
 2148                          3763         [ +  + ]:          12114 :     if (pstmt->appendRelations)
                               3764                 :                :     {
                               3765                 :                :         /* Set up the array, indexed by child relid */
                               3766                 :           1953 :         int         ntables = list_length(dpns->rtable);
                               3767                 :                :         ListCell   *lc;
                               3768                 :                : 
                               3769                 :           1953 :         dpns->appendrels = (AppendRelInfo **)
                               3770                 :           1953 :             palloc0((ntables + 1) * sizeof(AppendRelInfo *));
                               3771   [ +  -  +  +  :          10834 :         foreach(lc, pstmt->appendRelations)
                                              +  + ]
                               3772                 :                :         {
                               3773                 :           8881 :             AppendRelInfo *appinfo = lfirst_node(AppendRelInfo, lc);
                               3774                 :           8881 :             Index       crelid = appinfo->child_relid;
                               3775                 :                : 
                               3776   [ +  -  -  + ]:           8881 :             Assert(crelid > 0 && crelid <= ntables);
                               3777         [ -  + ]:           8881 :             Assert(dpns->appendrels[crelid] == NULL);
                               3778                 :           8881 :             dpns->appendrels[crelid] = appinfo;
                               3779                 :                :         }
                               3780                 :                :     }
                               3781                 :                :     else
                               3782                 :          10161 :         dpns->appendrels = NULL; /* don't need it */
                               3783                 :                : 
                               3784                 :                :     /*
                               3785                 :                :      * Set up column name aliases, ignoring any join RTEs; they don't matter
                               3786                 :                :      * because plan trees don't contain any join alias Vars.
                               3787                 :                :      */
 3939                          3788                 :          12114 :     set_simple_column_names(dpns);
                               3789                 :                : 
                               3790                 :                :     /* Return a one-deep namespace stack */
                               3791                 :          12114 :     return list_make1(dpns);
                               3792                 :                : }
                               3793                 :                : 
                               3794                 :                : /*
                               3795                 :                :  * set_deparse_context_plan - Specify Plan node containing expression
                               3796                 :                :  *
                               3797                 :                :  * When deparsing an expression in a Plan tree, we might have to resolve
                               3798                 :                :  * OUTER_VAR, INNER_VAR, or INDEX_VAR references.  To do this, the caller must
                               3799                 :                :  * provide the parent Plan node.  Then OUTER_VAR and INNER_VAR references
                               3800                 :                :  * can be resolved by drilling down into the left and right child plans.
                               3801                 :                :  * Similarly, INDEX_VAR references can be resolved by reference to the
                               3802                 :                :  * indextlist given in a parent IndexOnlyScan node, or to the scan tlist in
                               3803                 :                :  * ForeignScan and CustomScan nodes.  (Note that we don't currently support
                               3804                 :                :  * deparsing of indexquals in regular IndexScan or BitmapIndexScan nodes;
                               3805                 :                :  * for those, we can only deparse the indexqualorig fields, which won't
                               3806                 :                :  * contain INDEX_VAR Vars.)
                               3807                 :                :  *
                               3808                 :                :  * The ancestors list is a list of the Plan's parent Plan and SubPlan nodes,
                               3809                 :                :  * the most-closely-nested first.  This is needed to resolve PARAM_EXEC
                               3810                 :                :  * Params.  Note we assume that all the Plan nodes share the same rtable.
                               3811                 :                :  *
                               3812                 :                :  * For a ModifyTable plan, we might also need to resolve references to OLD/NEW
                               3813                 :                :  * variables in the RETURNING list, so we copy the alias names of the OLD and
                               3814                 :                :  * NEW rows from the ModifyTable plan node.
                               3815                 :                :  *
                               3816                 :                :  * Once this function has been called, deparse_expression() can be called on
                               3817                 :                :  * subsidiary expression(s) of the specified Plan node.  To deparse
                               3818                 :                :  * expressions of a different Plan node in the same Plan tree, re-call this
                               3819                 :                :  * function to identify the new parent Plan node.
                               3820                 :                :  *
                               3821                 :                :  * The result is the same List passed in; this is a notational convenience.
                               3822                 :                :  */
                               3823                 :                : List *
 2148                          3824                 :          28823 : set_deparse_context_plan(List *dpcontext, Plan *plan, List *ancestors)
                               3825                 :                : {
                               3826                 :                :     deparse_namespace *dpns;
                               3827                 :                : 
                               3828                 :                :     /* Should always have one-entry namespace list for Plan deparsing */
 3939                          3829         [ -  + ]:          28823 :     Assert(list_length(dpcontext) == 1);
                               3830                 :          28823 :     dpns = (deparse_namespace *) linitial(dpcontext);
                               3831                 :                : 
                               3832                 :                :     /* Set our attention on the specific plan node passed in */
 5586                          3833                 :          28823 :     dpns->ancestors = ancestors;
 1478                          3834                 :          28823 :     set_deparse_plan(dpns, plan);
                               3835                 :                : 
                               3836                 :                :     /* For ModifyTable, set aliases for OLD and NEW in RETURNING */
  285 dean.a.rasheed@gmail     3837         [ +  + ]:          28823 :     if (IsA(plan, ModifyTable))
                               3838                 :                :     {
                               3839                 :            105 :         dpns->ret_old_alias = ((ModifyTable *) plan)->returningOldAlias;
                               3840                 :            105 :         dpns->ret_new_alias = ((ModifyTable *) plan)->returningNewAlias;
                               3841                 :                :     }
                               3842                 :                : 
 3939 tgl@sss.pgh.pa.us        3843                 :          28823 :     return dpcontext;
                               3844                 :                : }
                               3845                 :                : 
                               3846                 :                : /*
                               3847                 :                :  * select_rtable_names_for_explain  - Select RTE aliases for EXPLAIN
                               3848                 :                :  *
                               3849                 :                :  * Determine the relation aliases we'll use during an EXPLAIN operation.
                               3850                 :                :  * This is just a frontend to set_rtable_names.  We have to expose the aliases
                               3851                 :                :  * to EXPLAIN because EXPLAIN needs to know the right alias names to print.
                               3852                 :                :  */
                               3853                 :                : List *
 4785                          3854                 :          12114 : select_rtable_names_for_explain(List *rtable, Bitmapset *rels_used)
                               3855                 :                : {
                               3856                 :                :     deparse_namespace dpns;
                               3857                 :                : 
                               3858                 :          12114 :     memset(&dpns, 0, sizeof(dpns));
                               3859                 :          12114 :     dpns.rtable = rtable;
 2148                          3860                 :          12114 :     dpns.subplans = NIL;
 4785                          3861                 :          12114 :     dpns.ctes = NIL;
 2148                          3862                 :          12114 :     dpns.appendrels = NULL;
 4785                          3863                 :          12114 :     set_rtable_names(&dpns, NIL, rels_used);
                               3864                 :                :     /* We needn't bother computing column aliases yet */
                               3865                 :                : 
                               3866                 :          12114 :     return dpns.rtable_names;
                               3867                 :                : }
                               3868                 :                : 
                               3869                 :                : /*
                               3870                 :                :  * set_rtable_names: select RTE aliases to be used in printing a query
                               3871                 :                :  *
                               3872                 :                :  * We fill in dpns->rtable_names with a list of names that is one-for-one with
                               3873                 :                :  * the already-filled dpns->rtable list.  Each RTE name is unique among those
                               3874                 :                :  * in the new namespace plus any ancestor namespaces listed in
                               3875                 :                :  * parent_namespaces.
                               3876                 :                :  *
                               3877                 :                :  * If rels_used isn't NULL, only RTE indexes listed in it are given aliases.
                               3878                 :                :  *
                               3879                 :                :  * Note that this function is only concerned with relation names, not column
                               3880                 :                :  * names.
                               3881                 :                :  */
                               3882                 :                : static void
                               3883                 :          26912 : set_rtable_names(deparse_namespace *dpns, List *parent_namespaces,
                               3884                 :                :                  Bitmapset *rels_used)
                               3885                 :                : {
                               3886                 :                :     HASHCTL     hash_ctl;
                               3887                 :                :     HTAB       *names_hash;
                               3888                 :                :     NameHashEntry *hentry;
                               3889                 :                :     bool        found;
                               3890                 :                :     int         rtindex;
                               3891                 :                :     ListCell   *lc;
                               3892                 :                : 
                               3893                 :          26912 :     dpns->rtable_names = NIL;
                               3894                 :                :     /* nothing more to do if empty rtable */
 3634                          3895         [ +  + ]:          26912 :     if (dpns->rtable == NIL)
                               3896                 :            286 :         return;
                               3897                 :                : 
                               3898                 :                :     /*
                               3899                 :                :      * We use a hash table to hold known names, so that this process is O(N)
                               3900                 :                :      * not O(N^2) for N names.
                               3901                 :                :      */
                               3902                 :          26626 :     hash_ctl.keysize = NAMEDATALEN;
                               3903                 :          26626 :     hash_ctl.entrysize = sizeof(NameHashEntry);
                               3904                 :          26626 :     hash_ctl.hcxt = CurrentMemoryContext;
                               3905                 :          26626 :     names_hash = hash_create("set_rtable_names names",
                               3906                 :          26626 :                              list_length(dpns->rtable),
                               3907                 :                :                              &hash_ctl,
                               3908                 :                :                              HASH_ELEM | HASH_STRINGS | HASH_CONTEXT);
                               3909                 :                : 
                               3910                 :                :     /* Preload the hash table with names appearing in parent_namespaces */
                               3911   [ +  +  +  +  :          27494 :     foreach(lc, parent_namespaces)
                                              +  + ]
                               3912                 :                :     {
                               3913                 :            868 :         deparse_namespace *olddpns = (deparse_namespace *) lfirst(lc);
                               3914                 :                :         ListCell   *lc2;
                               3915                 :                : 
                               3916   [ +  +  +  +  :           3149 :         foreach(lc2, olddpns->rtable_names)
                                              +  + ]
                               3917                 :                :         {
                               3918                 :           2281 :             char       *oldname = (char *) lfirst(lc2);
                               3919                 :                : 
                               3920         [ +  + ]:           2281 :             if (oldname == NULL)
                               3921                 :            168 :                 continue;
                               3922                 :           2113 :             hentry = (NameHashEntry *) hash_search(names_hash,
                               3923                 :                :                                                    oldname,
                               3924                 :                :                                                    HASH_ENTER,
                               3925                 :                :                                                    &found);
                               3926                 :                :             /* we do not complain about duplicate names in parent namespaces */
                               3927                 :           2113 :             hentry->counter = 0;
                               3928                 :                :         }
                               3929                 :                :     }
                               3930                 :                : 
                               3931                 :                :     /* Now we can scan the rtable */
                               3932                 :          26626 :     rtindex = 1;
 4785                          3933   [ +  -  +  +  :          77319 :     foreach(lc, dpns->rtable)
                                              +  + ]
                               3934                 :                :     {
                               3935                 :          50693 :         RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
                               3936                 :                :         char       *refname;
                               3937                 :                : 
                               3938                 :                :         /* Just in case this takes an unreasonable amount of time ... */
 3634                          3939         [ +  + ]:          50693 :         CHECK_FOR_INTERRUPTS();
                               3940                 :                : 
 4785                          3941   [ +  +  +  + ]:          50693 :         if (rels_used && !bms_is_member(rtindex, rels_used))
                               3942                 :                :         {
                               3943                 :                :             /* Ignore unreferenced RTE */
                               3944                 :           8846 :             refname = NULL;
                               3945                 :                :         }
                               3946         [ +  + ]:          41847 :         else if (rte->alias)
                               3947                 :                :         {
                               3948                 :                :             /* If RTE has a user-defined alias, prefer that */
                               3949                 :          27253 :             refname = rte->alias->aliasname;
                               3950                 :                :         }
                               3951         [ +  + ]:          14594 :         else if (rte->rtekind == RTE_RELATION)
                               3952                 :                :         {
                               3953                 :                :             /* Use the current actual name of the relation */
                               3954                 :          11081 :             refname = get_rel_name(rte->relid);
                               3955                 :                :         }
                               3956         [ +  + ]:           3513 :         else if (rte->rtekind == RTE_JOIN)
                               3957                 :                :         {
                               3958                 :                :             /* Unnamed join has no refname */
                               3959                 :            903 :             refname = NULL;
                               3960                 :                :         }
                               3961                 :                :         else
                               3962                 :                :         {
                               3963                 :                :             /* Otherwise use whatever the parser assigned */
                               3964                 :           2610 :             refname = rte->eref->aliasname;
                               3965                 :                :         }
                               3966                 :                : 
                               3967                 :                :         /*
                               3968                 :                :          * If the selected name isn't unique, append digits to make it so, and
                               3969                 :                :          * make a new hash entry for it once we've got a unique name.  For a
                               3970                 :                :          * very long input name, we might have to truncate to stay within
                               3971                 :                :          * NAMEDATALEN.
                               3972                 :                :          */
 3634                          3973         [ +  + ]:          50693 :         if (refname)
                               3974                 :                :         {
                               3975                 :          40944 :             hentry = (NameHashEntry *) hash_search(names_hash,
                               3976                 :                :                                                    refname,
                               3977                 :                :                                                    HASH_ENTER,
                               3978                 :                :                                                    &found);
                               3979         [ +  + ]:          40944 :             if (found)
                               3980                 :                :             {
                               3981                 :                :                 /* Name already in use, must choose a new one */
                               3982                 :           7602 :                 int         refnamelen = strlen(refname);
                               3983                 :           7602 :                 char       *modname = (char *) palloc(refnamelen + 16);
                               3984                 :                :                 NameHashEntry *hentry2;
                               3985                 :                : 
                               3986                 :                :                 do
                               3987                 :                :                 {
                               3988                 :           7605 :                     hentry->counter++;
                               3989                 :                :                     for (;;)
                               3990                 :                :                     {
                               3991                 :           7611 :                         memcpy(modname, refname, refnamelen);
                               3992                 :           7611 :                         sprintf(modname + refnamelen, "_%d", hentry->counter);
                               3993         [ +  + ]:           7611 :                         if (strlen(modname) < NAMEDATALEN)
                               3994                 :           7605 :                             break;
                               3995                 :                :                         /* drop chars from refname to keep all the digits */
                               3996                 :              6 :                         refnamelen = pg_mbcliplen(refname, refnamelen,
                               3997                 :                :                                                   refnamelen - 1);
                               3998                 :                :                     }
                               3999                 :           7605 :                     hentry2 = (NameHashEntry *) hash_search(names_hash,
                               4000                 :                :                                                             modname,
                               4001                 :                :                                                             HASH_ENTER,
                               4002                 :                :                                                             &found);
                               4003         [ +  + ]:           7605 :                 } while (found);
                               4004                 :           7602 :                 hentry2->counter = 0;    /* init new hash entry */
                               4005                 :           7602 :                 refname = modname;
                               4006                 :                :             }
                               4007                 :                :             else
                               4008                 :                :             {
                               4009                 :                :                 /* Name not previously used, need only initialize hentry */
                               4010                 :          33342 :                 hentry->counter = 0;
                               4011                 :                :             }
                               4012                 :                :         }
                               4013                 :                : 
 4785                          4014                 :          50693 :         dpns->rtable_names = lappend(dpns->rtable_names, refname);
                               4015                 :          50693 :         rtindex++;
                               4016                 :                :     }
                               4017                 :                : 
 3634                          4018                 :          26626 :     hash_destroy(names_hash);
                               4019                 :                : }
                               4020                 :                : 
                               4021                 :                : /*
                               4022                 :                :  * set_deparse_for_query: set up deparse_namespace for deparsing a Query tree
                               4023                 :                :  *
                               4024                 :                :  * For convenience, this is defined to initialize the deparse_namespace struct
                               4025                 :                :  * from scratch.
                               4026                 :                :  */
                               4027                 :                : static void
 4684                          4028                 :           2931 : set_deparse_for_query(deparse_namespace *dpns, Query *query,
                               4029                 :                :                       List *parent_namespaces)
                               4030                 :                : {
                               4031                 :                :     ListCell   *lc;
                               4032                 :                :     ListCell   *lc2;
                               4033                 :                : 
                               4034                 :                :     /* Initialize *dpns and fill rtable/ctes links */
                               4035                 :           2931 :     memset(dpns, 0, sizeof(deparse_namespace));
                               4036                 :           2931 :     dpns->rtable = query->rtable;
 2148                          4037                 :           2931 :     dpns->subplans = NIL;
 4684                          4038                 :           2931 :     dpns->ctes = query->cteList;
 2148                          4039                 :           2931 :     dpns->appendrels = NULL;
  285 dean.a.rasheed@gmail     4040                 :           2931 :     dpns->ret_old_alias = query->returningOldAlias;
                               4041                 :           2931 :     dpns->ret_new_alias = query->returningNewAlias;
                               4042                 :                : 
                               4043                 :                :     /* Assign a unique relation alias to each RTE */
 4684 tgl@sss.pgh.pa.us        4044                 :           2931 :     set_rtable_names(dpns, parent_namespaces, NULL);
                               4045                 :                : 
                               4046                 :                :     /* Initialize dpns->rtable_columns to contain zeroed structs */
                               4047                 :           2931 :     dpns->rtable_columns = NIL;
                               4048         [ +  + ]:           8221 :     while (list_length(dpns->rtable_columns) < list_length(dpns->rtable))
                               4049                 :           5290 :         dpns->rtable_columns = lappend(dpns->rtable_columns,
                               4050                 :                :                                        palloc0(sizeof(deparse_columns)));
                               4051                 :                : 
                               4052                 :                :     /* If it's a utility query, it won't have a jointree */
 4548                          4053         [ +  + ]:           2931 :     if (query->jointree)
                               4054                 :                :     {
                               4055                 :                :         /* Detect whether global uniqueness of USING names is needed */
                               4056                 :           2923 :         dpns->unique_using =
 4480                          4057                 :           2923 :             has_dangerous_join_using(dpns, (Node *) query->jointree);
                               4058                 :                : 
                               4059                 :                :         /*
                               4060                 :                :          * Select names for columns merged by USING, via a recursive pass over
                               4061                 :                :          * the query jointree.
                               4062                 :                :          */
 4198                          4063                 :           2923 :         set_using_names(dpns, (Node *) query->jointree, NIL);
                               4064                 :                :     }
                               4065                 :                : 
                               4066                 :                :     /*
                               4067                 :                :      * Now assign remaining column aliases for each RTE.  We do this in a
                               4068                 :                :      * linear scan of the rtable, so as to process RTEs whether or not they
                               4069                 :                :      * are in the jointree (we mustn't miss NEW.*, INSERT target relations,
                               4070                 :                :      * etc).  JOIN RTEs must be processed after their children, but this is
                               4071                 :                :      * okay because they appear later in the rtable list than their children
                               4072                 :                :      * (cf Asserts in identify_join_columns()).
                               4073                 :                :      */
 4684                          4074   [ +  +  +  +  :           8221 :     forboth(lc, dpns->rtable, lc2, dpns->rtable_columns)
                                     +  +  +  +  +  
                                        +  +  -  +  
                                                 + ]
                               4075                 :                :     {
                               4076                 :           5290 :         RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
                               4077                 :           5290 :         deparse_columns *colinfo = (deparse_columns *) lfirst(lc2);
                               4078                 :                : 
                               4079         [ +  + ]:           5290 :         if (rte->rtekind == RTE_JOIN)
                               4080                 :            761 :             set_join_column_names(dpns, rte, colinfo);
                               4081                 :                :         else
                               4082                 :           4529 :             set_relation_column_names(dpns, rte, colinfo);
                               4083                 :                :     }
                               4084                 :           2931 : }
                               4085                 :                : 
                               4086                 :                : /*
                               4087                 :                :  * set_simple_column_names: fill in column aliases for non-query situations
                               4088                 :                :  *
                               4089                 :                :  * This handles EXPLAIN and cases where we only have relation RTEs.  Without
                               4090                 :                :  * a join tree, we can't do anything smart about join RTEs, but we don't
                               4091                 :                :  * need to, because EXPLAIN should never see join alias Vars anyway.
                               4092                 :                :  * If we find a join RTE we'll just skip it, leaving its deparse_columns
                               4093                 :                :  * struct all-zero.  If somehow we try to deparse a join alias Var, we'll
                               4094                 :                :  * error out cleanly because the struct's num_cols will be zero.
                               4095                 :                :  */
                               4096                 :                : static void
                               4097                 :          23981 : set_simple_column_names(deparse_namespace *dpns)
                               4098                 :                : {
                               4099                 :                :     ListCell   *lc;
                               4100                 :                :     ListCell   *lc2;
                               4101                 :                : 
                               4102                 :                :     /* Initialize dpns->rtable_columns to contain zeroed structs */
                               4103                 :          23981 :     dpns->rtable_columns = NIL;
                               4104         [ +  + ]:          69384 :     while (list_length(dpns->rtable_columns) < list_length(dpns->rtable))
                               4105                 :          45403 :         dpns->rtable_columns = lappend(dpns->rtable_columns,
                               4106                 :                :                                        palloc0(sizeof(deparse_columns)));
                               4107                 :                : 
                               4108                 :                :     /* Assign unique column aliases within each non-join RTE */
                               4109   [ +  -  +  +  :          69384 :     forboth(lc, dpns->rtable, lc2, dpns->rtable_columns)
                                     +  -  +  +  +  
                                        +  +  -  +  
                                                 + ]
                               4110                 :                :     {
                               4111                 :          45403 :         RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
                               4112                 :          45403 :         deparse_columns *colinfo = (deparse_columns *) lfirst(lc2);
                               4113                 :                : 
  315                          4114         [ +  + ]:          45403 :         if (rte->rtekind != RTE_JOIN)
                               4115                 :          42435 :             set_relation_column_names(dpns, rte, colinfo);
                               4116                 :                :     }
 4684                          4117                 :          23981 : }
                               4118                 :                : 
                               4119                 :                : /*
                               4120                 :                :  * has_dangerous_join_using: search jointree for unnamed JOIN USING
                               4121                 :                :  *
                               4122                 :                :  * Merged columns of a JOIN USING may act differently from either of the input
                               4123                 :                :  * columns, either because they are merged with COALESCE (in a FULL JOIN) or
                               4124                 :                :  * because an implicit coercion of the underlying input column is required.
                               4125                 :                :  * In such a case the column must be referenced as a column of the JOIN not as
                               4126                 :                :  * a column of either input.  And this is problematic if the join is unnamed
                               4127                 :                :  * (alias-less): we cannot qualify the column's name with an RTE name, since
                               4128                 :                :  * there is none.  (Forcibly assigning an alias to the join is not a solution,
                               4129                 :                :  * since that will prevent legal references to tables below the join.)
                               4130                 :                :  * To ensure that every column in the query is unambiguously referenceable,
                               4131                 :                :  * we must assign such merged columns names that are globally unique across
                               4132                 :                :  * the whole query, aliasing other columns out of the way as necessary.
                               4133                 :                :  *
                               4134                 :                :  * Because the ensuing re-aliasing is fairly damaging to the readability of
                               4135                 :                :  * the query, we don't do this unless we have to.  So, we must pre-scan
                               4136                 :                :  * the join tree to see if we have to, before starting set_using_names().
                               4137                 :                :  */
                               4138                 :                : static bool
 4480                          4139                 :           6949 : has_dangerous_join_using(deparse_namespace *dpns, Node *jtnode)
                               4140                 :                : {
 4684                          4141         [ +  + ]:           6949 :     if (IsA(jtnode, RangeTblRef))
                               4142                 :                :     {
                               4143                 :                :         /* nothing to do here */
                               4144                 :                :     }
                               4145         [ +  + ]:           3651 :     else if (IsA(jtnode, FromExpr))
                               4146                 :                :     {
                               4147                 :           2923 :         FromExpr   *f = (FromExpr *) jtnode;
                               4148                 :                :         ListCell   *lc;
                               4149                 :                : 
                               4150   [ +  +  +  +  :           5529 :         foreach(lc, f->fromlist)
                                              +  + ]
                               4151                 :                :         {
 4480                          4152         [ +  + ]:           2642 :             if (has_dangerous_join_using(dpns, (Node *) lfirst(lc)))
 4684                          4153                 :             36 :                 return true;
                               4154                 :                :         }
                               4155                 :                :     }
                               4156         [ +  - ]:            728 :     else if (IsA(jtnode, JoinExpr))
                               4157                 :                :     {
                               4158                 :            728 :         JoinExpr   *j = (JoinExpr *) jtnode;
                               4159                 :                : 
                               4160                 :                :         /* Is it an unnamed JOIN with USING? */
 4480                          4161   [ +  +  +  + ]:            728 :         if (j->alias == NULL && j->usingClause)
                               4162                 :                :         {
                               4163                 :                :             /*
                               4164                 :                :              * Yes, so check each join alias var to see if any of them are not
                               4165                 :                :              * simple references to underlying columns.  If so, we have a
                               4166                 :                :              * dangerous situation and must pick unique aliases.
                               4167                 :                :              */
                               4168                 :            143 :             RangeTblEntry *jrte = rt_fetch(j->rtindex, dpns->rtable);
                               4169                 :                : 
                               4170                 :                :             /* We need only examine the merged columns */
 2119                          4171         [ +  + ]:            298 :             for (int i = 0; i < jrte->joinmergedcols; i++)
                               4172                 :                :             {
                               4173                 :            191 :                 Node       *aliasvar = list_nth(jrte->joinaliasvars, i);
                               4174                 :                : 
                               4175         [ +  + ]:            191 :                 if (!IsA(aliasvar, Var))
 4480                          4176                 :             36 :                     return true;
                               4177                 :                :             }
                               4178                 :                :         }
                               4179                 :                : 
                               4180                 :                :         /* Nope, but inspect children */
                               4181         [ -  + ]:            692 :         if (has_dangerous_join_using(dpns, j->larg))
 4684 tgl@sss.pgh.pa.us        4182                 :UBC           0 :             return true;
 4480 tgl@sss.pgh.pa.us        4183         [ -  + ]:CBC         692 :         if (has_dangerous_join_using(dpns, j->rarg))
 4684 tgl@sss.pgh.pa.us        4184                 :UBC           0 :             return true;
                               4185                 :                :     }
                               4186                 :                :     else
                               4187         [ #  # ]:              0 :         elog(ERROR, "unrecognized node type: %d",
                               4188                 :                :              (int) nodeTag(jtnode));
 4684 tgl@sss.pgh.pa.us        4189                 :CBC        6877 :     return false;
                               4190                 :                : }
                               4191                 :                : 
                               4192                 :                : /*
                               4193                 :                :  * set_using_names: select column aliases to be used for merged USING columns
                               4194                 :                :  *
                               4195                 :                :  * We do this during a recursive descent of the query jointree.
                               4196                 :                :  * dpns->unique_using must already be set to determine the global strategy.
                               4197                 :                :  *
                               4198                 :                :  * Column alias info is saved in the dpns->rtable_columns list, which is
                               4199                 :                :  * assumed to be filled with pre-zeroed deparse_columns structs.
                               4200                 :                :  *
                               4201                 :                :  * parentUsing is a list of all USING aliases assigned in parent joins of
                               4202                 :                :  * the current jointree node.  (The passed-in list must not be modified.)
                               4203                 :                :  *
                               4204                 :                :  * Note that we do not use per-deparse_columns hash tables in this function.
                               4205                 :                :  * The number of names that need to be assigned should be small enough that
                               4206                 :                :  * we don't need to trouble with that.
                               4207                 :                :  */
                               4208                 :                : static void
 4198                          4209                 :           7108 : set_using_names(deparse_namespace *dpns, Node *jtnode, List *parentUsing)
                               4210                 :                : {
 4684                          4211         [ +  + ]:           7108 :     if (IsA(jtnode, RangeTblRef))
                               4212                 :                :     {
                               4213                 :                :         /* nothing to do now */
                               4214                 :                :     }
                               4215         [ +  + ]:           3684 :     else if (IsA(jtnode, FromExpr))
                               4216                 :                :     {
                               4217                 :           2923 :         FromExpr   *f = (FromExpr *) jtnode;
                               4218                 :                :         ListCell   *lc;
                               4219                 :                : 
                               4220   [ +  +  +  +  :           5586 :         foreach(lc, f->fromlist)
                                              +  + ]
 4198                          4221                 :           2663 :             set_using_names(dpns, (Node *) lfirst(lc), parentUsing);
                               4222                 :                :     }
 4684                          4223         [ +  - ]:            761 :     else if (IsA(jtnode, JoinExpr))
                               4224                 :                :     {
                               4225                 :            761 :         JoinExpr   *j = (JoinExpr *) jtnode;
                               4226                 :            761 :         RangeTblEntry *rte = rt_fetch(j->rtindex, dpns->rtable);
                               4227                 :            761 :         deparse_columns *colinfo = deparse_columns_fetch(j->rtindex, dpns);
                               4228                 :                :         int        *leftattnos;
                               4229                 :                :         int        *rightattnos;
                               4230                 :                :         deparse_columns *leftcolinfo;
                               4231                 :                :         deparse_columns *rightcolinfo;
                               4232                 :                :         int         i;
                               4233                 :                :         ListCell   *lc;
                               4234                 :                : 
                               4235                 :                :         /* Get info about the shape of the join */
                               4236                 :            761 :         identify_join_columns(j, rte, colinfo);
                               4237                 :            761 :         leftattnos = colinfo->leftattnos;
                               4238                 :            761 :         rightattnos = colinfo->rightattnos;
                               4239                 :                : 
                               4240                 :                :         /* Look up the not-yet-filled-in child deparse_columns structs */
                               4241                 :            761 :         leftcolinfo = deparse_columns_fetch(colinfo->leftrti, dpns);
                               4242                 :            761 :         rightcolinfo = deparse_columns_fetch(colinfo->rightrti, dpns);
                               4243                 :                : 
                               4244                 :                :         /*
                               4245                 :                :          * If this join is unnamed, then we cannot substitute new aliases at
                               4246                 :                :          * this level, so any name requirements pushed down to here must be
                               4247                 :                :          * pushed down again to the children.
                               4248                 :                :          */
                               4249         [ +  + ]:            761 :         if (rte->alias == NULL)
                               4250                 :                :         {
                               4251         [ +  + ]:            776 :             for (i = 0; i < colinfo->num_cols; i++)
                               4252                 :                :             {
                               4253                 :             69 :                 char       *colname = colinfo->colnames[i];
                               4254                 :                : 
                               4255         [ +  + ]:             69 :                 if (colname == NULL)
                               4256                 :             12 :                     continue;
                               4257                 :                : 
                               4258                 :                :                 /* Push down to left column, unless it's a system column */
                               4259         [ +  + ]:             57 :                 if (leftattnos[i] > 0)
                               4260                 :                :                 {
                               4261                 :             51 :                     expand_colnames_array_to(leftcolinfo, leftattnos[i]);
                               4262                 :             51 :                     leftcolinfo->colnames[leftattnos[i] - 1] = colname;
                               4263                 :                :                 }
                               4264                 :                : 
                               4265                 :                :                 /* Same on the righthand side */
                               4266         [ +  - ]:             57 :                 if (rightattnos[i] > 0)
                               4267                 :                :                 {
                               4268                 :             57 :                     expand_colnames_array_to(rightcolinfo, rightattnos[i]);
                               4269                 :             57 :                     rightcolinfo->colnames[rightattnos[i] - 1] = colname;
                               4270                 :                :                 }
                               4271                 :                :             }
                               4272                 :                :         }
                               4273                 :                : 
                               4274                 :                :         /*
                               4275                 :                :          * If there's a USING clause, select the USING column names and push
                               4276                 :                :          * those names down to the children.  We have two strategies:
                               4277                 :                :          *
                               4278                 :                :          * If dpns->unique_using is true, we force all USING names to be
                               4279                 :                :          * unique across the whole query level.  In principle we'd only need
                               4280                 :                :          * the names of dangerous USING columns to be globally unique, but to
                               4281                 :                :          * safely assign all USING names in a single pass, we have to enforce
                               4282                 :                :          * the same uniqueness rule for all of them.  However, if a USING
                               4283                 :                :          * column's name has been pushed down from the parent, we should use
                               4284                 :                :          * it as-is rather than making a uniqueness adjustment.  This is
                               4285                 :                :          * necessary when we're at an unnamed join, and it creates no risk of
                               4286                 :                :          * ambiguity.  Also, if there's a user-written output alias for a
                               4287                 :                :          * merged column, we prefer to use that rather than the input name;
                               4288                 :                :          * this simplifies the logic and seems likely to lead to less aliasing
                               4289                 :                :          * overall.
                               4290                 :                :          *
                               4291                 :                :          * If dpns->unique_using is false, we only need USING names to be
                               4292                 :                :          * unique within their own join RTE.  We still need to honor
                               4293                 :                :          * pushed-down names, though.
                               4294                 :                :          *
                               4295                 :                :          * Though significantly different in results, these two strategies are
                               4296                 :                :          * implemented by the same code, with only the difference of whether
                               4297                 :                :          * to put assigned names into dpns->using_names.
                               4298                 :                :          */
                               4299         [ +  + ]:            761 :         if (j->usingClause)
                               4300                 :                :         {
                               4301                 :                :             /* Copy the input parentUsing list so we don't modify it */
 4198                          4302                 :            212 :             parentUsing = list_copy(parentUsing);
                               4303                 :                : 
                               4304                 :                :             /* USING names must correspond to the first join output columns */
 4684                          4305                 :            212 :             expand_colnames_array_to(colinfo, list_length(j->usingClause));
                               4306                 :            212 :             i = 0;
                               4307   [ +  -  +  +  :            502 :             foreach(lc, j->usingClause)
                                              +  + ]
                               4308                 :                :             {
                               4309                 :            290 :                 char       *colname = strVal(lfirst(lc));
                               4310                 :                : 
                               4311                 :                :                 /* Assert it's a merged column */
                               4312   [ +  -  -  + ]:            290 :                 Assert(leftattnos[i] != 0 && rightattnos[i] != 0);
                               4313                 :                : 
                               4314                 :                :                 /* Adopt passed-down name if any, else select unique name */
                               4315         [ +  + ]:            290 :                 if (colinfo->colnames[i] != NULL)
                               4316                 :             51 :                     colname = colinfo->colnames[i];
                               4317                 :                :                 else
                               4318                 :                :                 {
                               4319                 :                :                     /* Prefer user-written output alias if any */
                               4320   [ +  +  -  + ]:            239 :                     if (rte->alias && i < list_length(rte->alias->colnames))
 4684 tgl@sss.pgh.pa.us        4321                 :UBC           0 :                         colname = strVal(list_nth(rte->alias->colnames, i));
                               4322                 :                :                     /* Make it appropriately unique */
 4684 tgl@sss.pgh.pa.us        4323                 :CBC         239 :                     colname = make_colname_unique(colname, dpns, colinfo);
                               4324         [ +  + ]:            239 :                     if (dpns->unique_using)
                               4325                 :             63 :                         dpns->using_names = lappend(dpns->using_names,
                               4326                 :                :                                                     colname);
                               4327                 :                :                     /* Save it as output column name, too */
                               4328                 :            239 :                     colinfo->colnames[i] = colname;
                               4329                 :                :                 }
                               4330                 :                : 
                               4331                 :                :                 /* Remember selected names for use later */
                               4332                 :            290 :                 colinfo->usingNames = lappend(colinfo->usingNames, colname);
 4198                          4333                 :            290 :                 parentUsing = lappend(parentUsing, colname);
                               4334                 :                : 
                               4335                 :                :                 /* Push down to left column, unless it's a system column */
 4684                          4336         [ +  - ]:            290 :                 if (leftattnos[i] > 0)
                               4337                 :                :                 {
                               4338                 :            290 :                     expand_colnames_array_to(leftcolinfo, leftattnos[i]);
                               4339                 :            290 :                     leftcolinfo->colnames[leftattnos[i] - 1] = colname;
                               4340                 :                :                 }
                               4341                 :                : 
                               4342                 :                :                 /* Same on the righthand side */
                               4343         [ +  - ]:            290 :                 if (rightattnos[i] > 0)
                               4344                 :                :                 {
                               4345                 :            290 :                     expand_colnames_array_to(rightcolinfo, rightattnos[i]);
                               4346                 :            290 :                     rightcolinfo->colnames[rightattnos[i] - 1] = colname;
                               4347                 :                :                 }
                               4348                 :                : 
                               4349                 :            290 :                 i++;
                               4350                 :                :             }
                               4351                 :                :         }
                               4352                 :                : 
                               4353                 :                :         /* Mark child deparse_columns structs with correct parentUsing info */
 4198                          4354                 :            761 :         leftcolinfo->parentUsing = parentUsing;
                               4355                 :            761 :         rightcolinfo->parentUsing = parentUsing;
                               4356                 :                : 
                               4357                 :                :         /* Now recursively assign USING column names in children */
                               4358                 :            761 :         set_using_names(dpns, j->larg, parentUsing);
                               4359                 :            761 :         set_using_names(dpns, j->rarg, parentUsing);
                               4360                 :                :     }
                               4361                 :                :     else
 4684 tgl@sss.pgh.pa.us        4362         [ #  # ]:UBC           0 :         elog(ERROR, "unrecognized node type: %d",
                               4363                 :                :              (int) nodeTag(jtnode));
 4684 tgl@sss.pgh.pa.us        4364                 :CBC        7108 : }
                               4365                 :                : 
                               4366                 :                : /*
                               4367                 :                :  * set_relation_column_names: select column aliases for a non-join RTE
                               4368                 :                :  *
                               4369                 :                :  * Column alias info is saved in *colinfo, which is assumed to be pre-zeroed.
                               4370                 :                :  * If any colnames entries are already filled in, those override local
                               4371                 :                :  * choices.
                               4372                 :                :  */
                               4373                 :                : static void
                               4374                 :          46964 : set_relation_column_names(deparse_namespace *dpns, RangeTblEntry *rte,
                               4375                 :                :                           deparse_columns *colinfo)
                               4376                 :                : {
                               4377                 :                :     int         ncolumns;
                               4378                 :                :     char      **real_colnames;
                               4379                 :                :     bool        changed_any;
                               4380                 :                :     int         noldcolumns;
                               4381                 :                :     int         i;
                               4382                 :                :     int         j;
                               4383                 :                : 
                               4384                 :                :     /*
                               4385                 :                :      * Construct an array of the current "real" column names of the RTE.
                               4386                 :                :      * real_colnames[] will be indexed by physical column number, with NULL
                               4387                 :                :      * entries for dropped columns.
                               4388                 :                :      */
                               4389         [ +  + ]:          46964 :     if (rte->rtekind == RTE_RELATION)
                               4390                 :                :     {
                               4391                 :                :         /* Relation --- look to the system catalogs for up-to-date info */
                               4392                 :                :         Relation    rel;
                               4393                 :                :         TupleDesc   tupdesc;
                               4394                 :                : 
                               4395                 :          39890 :         rel = relation_open(rte->relid, AccessShareLock);
                               4396                 :          39890 :         tupdesc = RelationGetDescr(rel);
                               4397                 :                : 
                               4398                 :          39890 :         ncolumns = tupdesc->natts;
                               4399                 :          39890 :         real_colnames = (char **) palloc(ncolumns * sizeof(char *));
                               4400                 :                : 
                               4401         [ +  + ]:         253998 :         for (i = 0; i < ncolumns; i++)
                               4402                 :                :         {
 2991 andres@anarazel.de       4403                 :         214108 :             Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
                               4404                 :                : 
                               4405         [ +  + ]:         214108 :             if (attr->attisdropped)
 4684 tgl@sss.pgh.pa.us        4406                 :           1592 :                 real_colnames[i] = NULL;
                               4407                 :                :             else
 2991 andres@anarazel.de       4408                 :         212516 :                 real_colnames[i] = pstrdup(NameStr(attr->attname));
                               4409                 :                :         }
 4684 tgl@sss.pgh.pa.us        4410                 :          39890 :         relation_close(rel, AccessShareLock);
                               4411                 :                :     }
                               4412                 :                :     else
                               4413                 :                :     {
                               4414                 :                :         /* Otherwise get the column names from eref or expandRTE() */
                               4415                 :                :         List       *colnames;
                               4416                 :                :         ListCell   *lc;
                               4417                 :                : 
                               4418                 :                :         /*
                               4419                 :                :          * Functions returning composites have the annoying property that some
                               4420                 :                :          * of the composite type's columns might have been dropped since the
                               4421                 :                :          * query was parsed.  If possible, use expandRTE() to handle that
                               4422                 :                :          * case, since it has the tedious logic needed to find out about
                               4423                 :                :          * dropped columns.  However, if we're explaining a plan, then we
                               4424                 :                :          * don't have rte->functions because the planner thinks that won't be
                               4425                 :                :          * needed later, and that breaks expandRTE().  So in that case we have
                               4426                 :                :          * to rely on rte->eref, which may lead us to report a dropped
                               4427                 :                :          * column's old name; that seems close enough for EXPLAIN's purposes.
                               4428                 :                :          *
                               4429                 :                :          * For non-RELATION, non-FUNCTION RTEs, we can just look at rte->eref,
                               4430                 :                :          * which should be sufficiently up-to-date: no other RTE types can
                               4431                 :                :          * have columns get dropped from under them after parsing.
                               4432                 :                :          */
 1195                          4433   [ +  +  +  + ]:           7074 :         if (rte->rtekind == RTE_FUNCTION && rte->functions != NIL)
                               4434                 :                :         {
                               4435                 :                :             /* Since we're not creating Vars, rtindex etc. don't matter */
  285 dean.a.rasheed@gmail     4436                 :            429 :             expandRTE(rte, 1, 0, VAR_RETURNING_DEFAULT, -1,
                               4437                 :                :                       true /* include dropped */ , &colnames, NULL);
                               4438                 :                :         }
                               4439                 :                :         else
 1195 tgl@sss.pgh.pa.us        4440                 :           6645 :             colnames = rte->eref->colnames;
                               4441                 :                : 
                               4442                 :           7074 :         ncolumns = list_length(colnames);
 4684                          4443                 :           7074 :         real_colnames = (char **) palloc(ncolumns * sizeof(char *));
                               4444                 :                : 
                               4445                 :           7074 :         i = 0;
 1195                          4446   [ +  +  +  +  :          23213 :         foreach(lc, colnames)
                                              +  + ]
                               4447                 :                :         {
                               4448                 :                :             /*
                               4449                 :                :              * If the column name we find here is an empty string, then it's a
                               4450                 :                :              * dropped column, so change to NULL.
                               4451                 :                :              */
 4119                          4452                 :          16139 :             char       *cname = strVal(lfirst(lc));
                               4453                 :                : 
                               4454         [ +  + ]:          16139 :             if (cname[0] == '\0')
                               4455                 :             27 :                 cname = NULL;
                               4456                 :          16139 :             real_colnames[i] = cname;
 4684                          4457                 :          16139 :             i++;
                               4458                 :                :         }
                               4459                 :                :     }
                               4460                 :                : 
                               4461                 :                :     /*
                               4462                 :                :      * Ensure colinfo->colnames has a slot for each column.  (It could be long
                               4463                 :                :      * enough already, if we pushed down a name for the last column.)  Note:
                               4464                 :                :      * it's possible that there are now more columns than there were when the
                               4465                 :                :      * query was parsed, ie colnames could be longer than rte->eref->colnames.
                               4466                 :                :      * We must assign unique aliases to the new columns too, else there could
                               4467                 :                :      * be unresolved conflicts when the view/rule is reloaded.
                               4468                 :                :      */
                               4469                 :          46964 :     expand_colnames_array_to(colinfo, ncolumns);
                               4470         [ -  + ]:          46964 :     Assert(colinfo->num_cols == ncolumns);
                               4471                 :                : 
                               4472                 :                :     /*
                               4473                 :                :      * Make sufficiently large new_colnames and is_new_col arrays, too.
                               4474                 :                :      *
                               4475                 :                :      * Note: because we leave colinfo->num_new_cols zero until after the loop,
                               4476                 :                :      * colname_is_unique will not consult that array, which is fine because it
                               4477                 :                :      * would only be duplicate effort.
                               4478                 :                :      */
                               4479                 :          46964 :     colinfo->new_colnames = (char **) palloc(ncolumns * sizeof(char *));
                               4480                 :          46964 :     colinfo->is_new_col = (bool *) palloc(ncolumns * sizeof(bool));
                               4481                 :                : 
                               4482                 :                :     /* If the RTE is wide enough, use a hash table to avoid O(N^2) costs */
  413                          4483                 :          46964 :     build_colinfo_names_hash(colinfo);
                               4484                 :                : 
                               4485                 :                :     /*
                               4486                 :                :      * Scan the columns, select a unique alias for each one, and store it in
                               4487                 :                :      * colinfo->colnames and colinfo->new_colnames.  The former array has NULL
                               4488                 :                :      * entries for dropped columns, the latter omits them.  Also mark
                               4489                 :                :      * new_colnames entries as to whether they are new since parse time; this
                               4490                 :                :      * is the case for entries beyond the length of rte->eref->colnames.
                               4491                 :                :      */
 4684                          4492                 :          46964 :     noldcolumns = list_length(rte->eref->colnames);
                               4493                 :          46964 :     changed_any = false;
                               4494                 :          46964 :     j = 0;
                               4495         [ +  + ]:         277211 :     for (i = 0; i < ncolumns; i++)
                               4496                 :                :     {
                               4497                 :         230247 :         char       *real_colname = real_colnames[i];
                               4498                 :         230247 :         char       *colname = colinfo->colnames[i];
                               4499                 :                : 
                               4500                 :                :         /* Skip dropped columns */
                               4501         [ +  + ]:         230247 :         if (real_colname == NULL)
                               4502                 :                :         {
                               4503         [ -  + ]:           1619 :             Assert(colname == NULL);    /* colnames[i] is already NULL */
                               4504                 :           1619 :             continue;
                               4505                 :                :         }
                               4506                 :                : 
                               4507                 :                :         /* If alias already assigned, that's what to use */
                               4508         [ +  + ]:         228628 :         if (colname == NULL)
                               4509                 :                :         {
                               4510                 :                :             /* If user wrote an alias, prefer that over real column name */
                               4511   [ +  +  +  + ]:         228099 :             if (rte->alias && i < list_length(rte->alias->colnames))
                               4512                 :          22211 :                 colname = strVal(list_nth(rte->alias->colnames, i));
                               4513                 :                :             else
                               4514                 :         205888 :                 colname = real_colname;
                               4515                 :                : 
                               4516                 :                :             /* Unique-ify and insert into colinfo */
                               4517                 :         228099 :             colname = make_colname_unique(colname, dpns, colinfo);
                               4518                 :                : 
                               4519                 :         228099 :             colinfo->colnames[i] = colname;
  413                          4520                 :         228099 :             add_to_names_hash(colinfo, colname);
                               4521                 :                :         }
                               4522                 :                : 
                               4523                 :                :         /* Put names of non-dropped columns in new_colnames[] too */
 4684                          4524                 :         228628 :         colinfo->new_colnames[j] = colname;
                               4525                 :                :         /* And mark them as new or not */
                               4526                 :         228628 :         colinfo->is_new_col[j] = (i >= noldcolumns);
                               4527                 :         228628 :         j++;
                               4528                 :                : 
                               4529                 :                :         /* Remember if any assigned aliases differ from "real" name */
                               4530   [ +  +  +  + ]:         228628 :         if (!changed_any && strcmp(colname, real_colname) != 0)
                               4531                 :            599 :             changed_any = true;
                               4532                 :                :     }
                               4533                 :                : 
                               4534                 :                :     /* We're now done needing the colinfo's names_hash */
  413                          4535                 :          46964 :     destroy_colinfo_names_hash(colinfo);
                               4536                 :                : 
                               4537                 :                :     /*
                               4538                 :                :      * Set correct length for new_colnames[] array.  (Note: if columns have
                               4539                 :                :      * been added, colinfo->num_cols includes them, which is not really quite
                               4540                 :                :      * right but is harmless, since any new columns must be at the end where
                               4541                 :                :      * they won't affect varattnos of pre-existing columns.)
                               4542                 :                :      */
 4684                          4543                 :          46964 :     colinfo->num_new_cols = j;
                               4544                 :                : 
                               4545                 :                :     /*
                               4546                 :                :      * For a relation RTE, we need only print the alias column names if any
                               4547                 :                :      * are different from the underlying "real" names.  For a function RTE,
                               4548                 :                :      * always emit a complete column alias list; this is to protect against
                               4549                 :                :      * possible instability of the default column names (eg, from altering
                               4550                 :                :      * parameter names).  For tablefunc RTEs, we never print aliases, because
                               4551                 :                :      * the column names are part of the clause itself.  For other RTE types,
                               4552                 :                :      * print if we changed anything OR if there were user-written column
                               4553                 :                :      * aliases (since the latter would be part of the underlying "reality").
                               4554                 :                :      */
                               4555         [ +  + ]:          46964 :     if (rte->rtekind == RTE_RELATION)
                               4556                 :          39890 :         colinfo->printaliases = changed_any;
                               4557         [ +  + ]:           7074 :     else if (rte->rtekind == RTE_FUNCTION)
                               4558                 :            717 :         colinfo->printaliases = true;
 3156 alvherre@alvh.no-ip.     4559         [ +  + ]:           6357 :     else if (rte->rtekind == RTE_TABLEFUNC)
                               4560                 :             88 :         colinfo->printaliases = false;
 4684 tgl@sss.pgh.pa.us        4561   [ +  +  +  + ]:           6269 :     else if (rte->alias && rte->alias->colnames != NIL)
                               4562                 :            366 :         colinfo->printaliases = true;
                               4563                 :                :     else
                               4564                 :           5903 :         colinfo->printaliases = changed_any;
                               4565                 :          46964 : }
                               4566                 :                : 
                               4567                 :                : /*
                               4568                 :                :  * set_join_column_names: select column aliases for a join RTE
                               4569                 :                :  *
                               4570                 :                :  * Column alias info is saved in *colinfo, which is assumed to be pre-zeroed.
                               4571                 :                :  * If any colnames entries are already filled in, those override local
                               4572                 :                :  * choices.  Also, names for USING columns were already chosen by
                               4573                 :                :  * set_using_names().  We further expect that column alias selection has been
                               4574                 :                :  * completed for both input RTEs.
                               4575                 :                :  */
                               4576                 :                : static void
                               4577                 :            761 : set_join_column_names(deparse_namespace *dpns, RangeTblEntry *rte,
                               4578                 :                :                       deparse_columns *colinfo)
                               4579                 :                : {
                               4580                 :                :     deparse_columns *leftcolinfo;
                               4581                 :                :     deparse_columns *rightcolinfo;
                               4582                 :                :     bool        changed_any;
                               4583                 :                :     int         noldcolumns;
                               4584                 :                :     int         nnewcolumns;
                               4585                 :            761 :     Bitmapset  *leftmerged = NULL;
                               4586                 :            761 :     Bitmapset  *rightmerged = NULL;
                               4587                 :                :     int         i;
                               4588                 :                :     int         j;
                               4589                 :                :     int         ic;
                               4590                 :                :     int         jc;
                               4591                 :                : 
                               4592                 :                :     /* Look up the previously-filled-in child deparse_columns structs */
                               4593                 :            761 :     leftcolinfo = deparse_columns_fetch(colinfo->leftrti, dpns);
                               4594                 :            761 :     rightcolinfo = deparse_columns_fetch(colinfo->rightrti, dpns);
                               4595                 :                : 
                               4596                 :                :     /*
                               4597                 :                :      * Ensure colinfo->colnames has a slot for each column.  (It could be long
                               4598                 :                :      * enough already, if we pushed down a name for the last column.)  Note:
                               4599                 :                :      * it's possible that one or both inputs now have more columns than there
                               4600                 :                :      * were when the query was parsed, but we'll deal with that below.  We
                               4601                 :                :      * only need entries in colnames for pre-existing columns.
                               4602                 :                :      */
                               4603                 :            761 :     noldcolumns = list_length(rte->eref->colnames);
                               4604                 :            761 :     expand_colnames_array_to(colinfo, noldcolumns);
                               4605         [ -  + ]:            761 :     Assert(colinfo->num_cols == noldcolumns);
                               4606                 :                : 
                               4607                 :                :     /* If the RTE is wide enough, use a hash table to avoid O(N^2) costs */
  413                          4608                 :            761 :     build_colinfo_names_hash(colinfo);
                               4609                 :                : 
                               4610                 :                :     /*
                               4611                 :                :      * Scan the join output columns, select an alias for each one, and store
                               4612                 :                :      * it in colinfo->colnames.  If there are USING columns, set_using_names()
                               4613                 :                :      * already selected their names, so we can start the loop at the first
                               4614                 :                :      * non-merged column.
                               4615                 :                :      */
 4684                          4616                 :            761 :     changed_any = false;
                               4617         [ +  + ]:          25637 :     for (i = list_length(colinfo->usingNames); i < noldcolumns; i++)
                               4618                 :                :     {
                               4619                 :          24876 :         char       *colname = colinfo->colnames[i];
                               4620                 :                :         char       *real_colname;
                               4621                 :                : 
                               4622                 :                :         /* Join column must refer to at least one input column */
 2119                          4623   [ +  +  -  + ]:          24876 :         Assert(colinfo->leftattnos[i] != 0 || colinfo->rightattnos[i] != 0);
                               4624                 :                : 
                               4625                 :                :         /* Get the child column name */
 4684                          4626         [ +  + ]:          24876 :         if (colinfo->leftattnos[i] > 0)
                               4627                 :          17588 :             real_colname = leftcolinfo->colnames[colinfo->leftattnos[i] - 1];
                               4628         [ +  - ]:           7288 :         else if (colinfo->rightattnos[i] > 0)
                               4629                 :           7288 :             real_colname = rightcolinfo->colnames[colinfo->rightattnos[i] - 1];
                               4630                 :                :         else
                               4631                 :                :         {
                               4632                 :                :             /* We're joining system columns --- use eref name */
 4480 tgl@sss.pgh.pa.us        4633                 :UBC           0 :             real_colname = strVal(list_nth(rte->eref->colnames, i));
                               4634                 :                :         }
                               4635                 :                : 
                               4636                 :                :         /* If child col has been dropped, no need to assign a join colname */
 2119 tgl@sss.pgh.pa.us        4637         [ +  + ]:CBC       24876 :         if (real_colname == NULL)
                               4638                 :                :         {
                               4639                 :              3 :             colinfo->colnames[i] = NULL;
                               4640                 :              3 :             continue;
                               4641                 :                :         }
                               4642                 :                : 
                               4643                 :                :         /* In an unnamed join, just report child column names as-is */
 4684                          4644         [ +  + ]:          24873 :         if (rte->alias == NULL)
                               4645                 :                :         {
                               4646                 :          24684 :             colinfo->colnames[i] = real_colname;
  413                          4647                 :          24684 :             add_to_names_hash(colinfo, real_colname);
 4684                          4648                 :          24684 :             continue;
                               4649                 :                :         }
                               4650                 :                : 
                               4651                 :                :         /* If alias already assigned, that's what to use */
                               4652         [ +  - ]:            189 :         if (colname == NULL)
                               4653                 :                :         {
                               4654                 :                :             /* If user wrote an alias, prefer that over real column name */
                               4655   [ +  -  +  + ]:            189 :             if (rte->alias && i < list_length(rte->alias->colnames))
                               4656                 :             48 :                 colname = strVal(list_nth(rte->alias->colnames, i));
                               4657                 :                :             else
                               4658                 :            141 :                 colname = real_colname;
                               4659                 :                : 
                               4660                 :                :             /* Unique-ify and insert into colinfo */
                               4661                 :            189 :             colname = make_colname_unique(colname, dpns, colinfo);
                               4662                 :                : 
                               4663                 :            189 :             colinfo->colnames[i] = colname;
  413                          4664                 :            189 :             add_to_names_hash(colinfo, colname);
                               4665                 :                :         }
                               4666                 :                : 
                               4667                 :                :         /* Remember if any assigned aliases differ from "real" name */
 4684                          4668   [ +  +  +  + ]:            189 :         if (!changed_any && strcmp(colname, real_colname) != 0)
                               4669                 :             12 :             changed_any = true;
                               4670                 :                :     }
                               4671                 :                : 
                               4672                 :                :     /*
                               4673                 :                :      * Calculate number of columns the join would have if it were re-parsed
                               4674                 :                :      * now, and create storage for the new_colnames and is_new_col arrays.
                               4675                 :                :      *
                               4676                 :                :      * Note: colname_is_unique will be consulting new_colnames[] during the
                               4677                 :                :      * loops below, so its not-yet-filled entries must be zeroes.
                               4678                 :                :      */
                               4679                 :           1522 :     nnewcolumns = leftcolinfo->num_new_cols + rightcolinfo->num_new_cols -
                               4680                 :            761 :         list_length(colinfo->usingNames);
                               4681                 :            761 :     colinfo->num_new_cols = nnewcolumns;
                               4682                 :            761 :     colinfo->new_colnames = (char **) palloc0(nnewcolumns * sizeof(char *));
                               4683                 :            761 :     colinfo->is_new_col = (bool *) palloc0(nnewcolumns * sizeof(bool));
                               4684                 :                : 
                               4685                 :                :     /*
                               4686                 :                :      * Generating the new_colnames array is a bit tricky since any new columns
                               4687                 :                :      * added since parse time must be inserted in the right places.  This code
                               4688                 :                :      * must match the parser, which will order a join's columns as merged
                               4689                 :                :      * columns first (in USING-clause order), then non-merged columns from the
                               4690                 :                :      * left input (in attnum order), then non-merged columns from the right
                               4691                 :                :      * input (ditto).  If one of the inputs is itself a join, its columns will
                               4692                 :                :      * be ordered according to the same rule, which means newly-added columns
                               4693                 :                :      * might not be at the end.  We can figure out what's what by consulting
                               4694                 :                :      * the leftattnos and rightattnos arrays plus the input is_new_col arrays.
                               4695                 :                :      *
                               4696                 :                :      * In these loops, i indexes leftattnos/rightattnos (so it's join varattno
                               4697                 :                :      * less one), j indexes new_colnames/is_new_col, and ic/jc have similar
                               4698                 :                :      * meanings for the current child RTE.
                               4699                 :                :      */
                               4700                 :                : 
                               4701                 :                :     /* Handle merged columns; they are first and can't be new */
                               4702                 :            761 :     i = j = 0;
                               4703                 :            761 :     while (i < noldcolumns &&
                               4704   [ +  -  +  - ]:           1051 :            colinfo->leftattnos[i] != 0 &&
                               4705         [ +  + ]:           1051 :            colinfo->rightattnos[i] != 0)
                               4706                 :                :     {
                               4707                 :                :         /* column name is already determined and known unique */
                               4708                 :            290 :         colinfo->new_colnames[j] = colinfo->colnames[i];
                               4709                 :            290 :         colinfo->is_new_col[j] = false;
                               4710                 :                : 
                               4711                 :                :         /* build bitmapsets of child attnums of merged columns */
                               4712         [ +  - ]:            290 :         if (colinfo->leftattnos[i] > 0)
                               4713                 :            290 :             leftmerged = bms_add_member(leftmerged, colinfo->leftattnos[i]);
                               4714         [ +  - ]:            290 :         if (colinfo->rightattnos[i] > 0)
                               4715                 :            290 :             rightmerged = bms_add_member(rightmerged, colinfo->rightattnos[i]);
                               4716                 :                : 
                               4717                 :            290 :         i++, j++;
                               4718                 :                :     }
                               4719                 :                : 
                               4720                 :                :     /* Handle non-merged left-child columns */
                               4721                 :            761 :     ic = 0;
                               4722         [ +  + ]:          18882 :     for (jc = 0; jc < leftcolinfo->num_new_cols; jc++)
                               4723                 :                :     {
                               4724                 :          18121 :         char       *child_colname = leftcolinfo->new_colnames[jc];
                               4725                 :                : 
                               4726         [ +  + ]:          18121 :         if (!leftcolinfo->is_new_col[jc])
                               4727                 :                :         {
                               4728                 :                :             /* Advance ic to next non-dropped old column of left child */
                               4729         [ +  - ]:          17917 :             while (ic < leftcolinfo->num_cols &&
                               4730         [ +  + ]:          17917 :                    leftcolinfo->colnames[ic] == NULL)
                               4731                 :             42 :                 ic++;
                               4732         [ -  + ]:          17875 :             Assert(ic < leftcolinfo->num_cols);
                               4733                 :          17875 :             ic++;
                               4734                 :                :             /* If it is a merged column, we already processed it */
                               4735         [ +  + ]:          17875 :             if (bms_is_member(ic, leftmerged))
                               4736                 :            290 :                 continue;
                               4737                 :                :             /* Else, advance i to the corresponding existing join column */
                               4738         [ +  - ]:          17588 :             while (i < colinfo->num_cols &&
                               4739         [ +  + ]:          17588 :                    colinfo->colnames[i] == NULL)
                               4740                 :              3 :                 i++;
                               4741         [ -  + ]:          17585 :             Assert(i < colinfo->num_cols);
                               4742         [ -  + ]:          17585 :             Assert(ic == colinfo->leftattnos[i]);
                               4743                 :                :             /* Use the already-assigned name of this column */
                               4744                 :          17585 :             colinfo->new_colnames[j] = colinfo->colnames[i];
                               4745                 :          17585 :             i++;
                               4746                 :                :         }
                               4747                 :                :         else
                               4748                 :                :         {
                               4749                 :                :             /*
                               4750                 :                :              * Unique-ify the new child column name and assign, unless we're
                               4751                 :                :              * in an unnamed join, in which case just copy
                               4752                 :                :              */
                               4753         [ +  + ]:            246 :             if (rte->alias != NULL)
                               4754                 :                :             {
                               4755                 :            132 :                 colinfo->new_colnames[j] =
                               4756                 :             66 :                     make_colname_unique(child_colname, dpns, colinfo);
                               4757         [ +  + ]:             66 :                 if (!changed_any &&
                               4758         [ +  + ]:             54 :                     strcmp(colinfo->new_colnames[j], child_colname) != 0)
                               4759                 :              6 :                     changed_any = true;
                               4760                 :                :             }
                               4761                 :                :             else
                               4762                 :            180 :                 colinfo->new_colnames[j] = child_colname;
  413                          4763                 :            246 :             add_to_names_hash(colinfo, colinfo->new_colnames[j]);
                               4764                 :                :         }
                               4765                 :                : 
 4684                          4766                 :          17831 :         colinfo->is_new_col[j] = leftcolinfo->is_new_col[jc];
                               4767                 :          17831 :         j++;
                               4768                 :                :     }
                               4769                 :                : 
                               4770                 :                :     /* Handle non-merged right-child columns in exactly the same way */
                               4771                 :            761 :     ic = 0;
                               4772         [ +  + ]:           8423 :     for (jc = 0; jc < rightcolinfo->num_new_cols; jc++)
                               4773                 :                :     {
                               4774                 :           7662 :         char       *child_colname = rightcolinfo->new_colnames[jc];
                               4775                 :                : 
                               4776         [ +  + ]:           7662 :         if (!rightcolinfo->is_new_col[jc])
                               4777                 :                :         {
                               4778                 :                :             /* Advance ic to next non-dropped old column of right child */
                               4779         [ +  - ]:           7578 :             while (ic < rightcolinfo->num_cols &&
                               4780         [ -  + ]:           7578 :                    rightcolinfo->colnames[ic] == NULL)
 4684 tgl@sss.pgh.pa.us        4781                 :UBC           0 :                 ic++;
 4684 tgl@sss.pgh.pa.us        4782         [ -  + ]:CBC        7578 :             Assert(ic < rightcolinfo->num_cols);
                               4783                 :           7578 :             ic++;
                               4784                 :                :             /* If it is a merged column, we already processed it */
                               4785         [ +  + ]:           7578 :             if (bms_is_member(ic, rightmerged))
                               4786                 :            290 :                 continue;
                               4787                 :                :             /* Else, advance i to the corresponding existing join column */
                               4788         [ +  - ]:           7288 :             while (i < colinfo->num_cols &&
                               4789         [ -  + ]:           7288 :                    colinfo->colnames[i] == NULL)
 4684 tgl@sss.pgh.pa.us        4790                 :UBC           0 :                 i++;
 4684 tgl@sss.pgh.pa.us        4791         [ -  + ]:CBC        7288 :             Assert(i < colinfo->num_cols);
                               4792         [ -  + ]:           7288 :             Assert(ic == colinfo->rightattnos[i]);
                               4793                 :                :             /* Use the already-assigned name of this column */
                               4794                 :           7288 :             colinfo->new_colnames[j] = colinfo->colnames[i];
                               4795                 :           7288 :             i++;
                               4796                 :                :         }
                               4797                 :                :         else
                               4798                 :                :         {
                               4799                 :                :             /*
                               4800                 :                :              * Unique-ify the new child column name and assign, unless we're
                               4801                 :                :              * in an unnamed join, in which case just copy
                               4802                 :                :              */
                               4803         [ +  + ]:             84 :             if (rte->alias != NULL)
                               4804                 :                :             {
                               4805                 :             24 :                 colinfo->new_colnames[j] =
                               4806                 :             12 :                     make_colname_unique(child_colname, dpns, colinfo);
                               4807         [ +  - ]:             12 :                 if (!changed_any &&
                               4808         [ +  + ]:             12 :                     strcmp(colinfo->new_colnames[j], child_colname) != 0)
                               4809                 :              6 :                     changed_any = true;
                               4810                 :                :             }
                               4811                 :                :             else
                               4812                 :             72 :                 colinfo->new_colnames[j] = child_colname;
  413                          4813                 :             84 :             add_to_names_hash(colinfo, colinfo->new_colnames[j]);
                               4814                 :                :         }
                               4815                 :                : 
 4684                          4816                 :           7372 :         colinfo->is_new_col[j] = rightcolinfo->is_new_col[jc];
                               4817                 :           7372 :         j++;
                               4818                 :                :     }
                               4819                 :                : 
                               4820                 :                :     /* Assert we processed the right number of columns */
                               4821                 :                : #ifdef USE_ASSERT_CHECKING
                               4822   [ -  +  -  - ]:            761 :     while (i < colinfo->num_cols && colinfo->colnames[i] == NULL)
 4684 tgl@sss.pgh.pa.us        4823                 :UBC           0 :         i++;
 4684 tgl@sss.pgh.pa.us        4824         [ -  + ]:CBC         761 :     Assert(i == colinfo->num_cols);
                               4825         [ -  + ]:            761 :     Assert(j == nnewcolumns);
                               4826                 :                : #endif
                               4827                 :                : 
                               4828                 :                :     /* We're now done needing the colinfo's names_hash */
  413                          4829                 :            761 :     destroy_colinfo_names_hash(colinfo);
                               4830                 :                : 
                               4831                 :                :     /*
                               4832                 :                :      * For a named join, print column aliases if we changed any from the child
                               4833                 :                :      * names.  Unnamed joins cannot print aliases.
                               4834                 :                :      */
 4684                          4835         [ +  + ]:            761 :     if (rte->alias != NULL)
                               4836                 :             54 :         colinfo->printaliases = changed_any;
                               4837                 :                :     else
                               4838                 :            707 :         colinfo->printaliases = false;
                               4839                 :            761 : }
                               4840                 :                : 
                               4841                 :                : /*
                               4842                 :                :  * colname_is_unique: is colname distinct from already-chosen column names?
                               4843                 :                :  *
                               4844                 :                :  * dpns is query-wide info, colinfo is for the column's RTE
                               4845                 :                :  */
                               4846                 :                : static bool
 2919 peter_e@gmx.net          4847                 :         229789 : colname_is_unique(const char *colname, deparse_namespace *dpns,
                               4848                 :                :                   deparse_columns *colinfo)
                               4849                 :                : {
                               4850                 :                :     int         i;
                               4851                 :                :     ListCell   *lc;
                               4852                 :                : 
                               4853                 :                :     /*
                               4854                 :                :      * If we have a hash table, consult that instead of linearly scanning the
                               4855                 :                :      * colinfo's strings.
                               4856                 :                :      */
  413 tgl@sss.pgh.pa.us        4857         [ +  + ]:         229789 :     if (colinfo->names_hash)
                               4858                 :                :     {
                               4859         [ -  + ]:           9001 :         if (hash_search(colinfo->names_hash,
                               4860                 :                :                         colname,
                               4861                 :                :                         HASH_FIND,
                               4862                 :                :                         NULL) != NULL)
 4684 tgl@sss.pgh.pa.us        4863                 :UBC           0 :             return false;
                               4864                 :                :     }
                               4865                 :                :     else
                               4866                 :                :     {
                               4867                 :                :         /* Check against already-assigned column aliases within RTE */
  413 tgl@sss.pgh.pa.us        4868         [ +  + ]:CBC     3051154 :         for (i = 0; i < colinfo->num_cols; i++)
                               4869                 :                :         {
                               4870                 :        2831514 :             char       *oldname = colinfo->colnames[i];
                               4871                 :                : 
                               4872   [ +  +  +  + ]:        2831514 :             if (oldname && strcmp(oldname, colname) == 0)
                               4873                 :           1148 :                 return false;
                               4874                 :                :         }
                               4875                 :                : 
                               4876                 :                :         /*
                               4877                 :                :          * If we're building a new_colnames array, check that too (this will
                               4878                 :                :          * be partially but not completely redundant with the previous checks)
                               4879                 :                :          */
                               4880         [ +  + ]:         220276 :         for (i = 0; i < colinfo->num_new_cols; i++)
                               4881                 :                :         {
                               4882                 :            648 :             char       *oldname = colinfo->new_colnames[i];
                               4883                 :                : 
                               4884   [ +  +  +  + ]:            648 :             if (oldname && strcmp(oldname, colname) == 0)
                               4885                 :             12 :                 return false;
                               4886                 :                :         }
                               4887                 :                : 
                               4888                 :                :         /*
                               4889                 :                :          * Also check against names already assigned for parent-join USING
                               4890                 :                :          * cols
                               4891                 :                :          */
                               4892   [ +  +  +  +  :         220924 :         foreach(lc, colinfo->parentUsing)
                                              +  + ]
                               4893                 :                :         {
                               4894                 :           1299 :             char       *oldname = (char *) lfirst(lc);
                               4895                 :                : 
                               4896         [ +  + ]:           1299 :             if (strcmp(oldname, colname) == 0)
                               4897                 :              3 :                 return false;
                               4898                 :                :         }
                               4899                 :                :     }
                               4900                 :                : 
                               4901                 :                :     /*
                               4902                 :                :      * Also check against USING-column names that must be globally unique.
                               4903                 :                :      * These are not hashed, but there should be few of them.
                               4904                 :                :      */
                               4905   [ +  +  +  +  :         229046 :     foreach(lc, dpns->using_names)
                                              +  + ]
                               4906                 :                :     {
 4198                          4907                 :            441 :         char       *oldname = (char *) lfirst(lc);
                               4908                 :                : 
                               4909         [ +  + ]:            441 :         if (strcmp(oldname, colname) == 0)
                               4910                 :             21 :             return false;
                               4911                 :                :     }
                               4912                 :                : 
 4684                          4913                 :         228605 :     return true;
                               4914                 :                : }
                               4915                 :                : 
                               4916                 :                : /*
                               4917                 :                :  * make_colname_unique: modify colname if necessary to make it unique
                               4918                 :                :  *
                               4919                 :                :  * dpns is query-wide info, colinfo is for the column's RTE
                               4920                 :                :  */
                               4921                 :                : static char *
                               4922                 :         228605 : make_colname_unique(char *colname, deparse_namespace *dpns,
                               4923                 :                :                     deparse_columns *colinfo)
                               4924                 :                : {
                               4925                 :                :     /*
                               4926                 :                :      * If the selected name isn't unique, append digits to make it so.  For a
                               4927                 :                :      * very long input name, we might have to truncate to stay within
                               4928                 :                :      * NAMEDATALEN.
                               4929                 :                :      */
                               4930         [ +  + ]:         228605 :     if (!colname_is_unique(colname, dpns, colinfo))
                               4931                 :                :     {
 3634                          4932                 :            822 :         int         colnamelen = strlen(colname);
                               4933                 :            822 :         char       *modname = (char *) palloc(colnamelen + 16);
 4684                          4934                 :            822 :         int         i = 0;
                               4935                 :                : 
                               4936                 :                :         do
                               4937                 :                :         {
 3634                          4938                 :           1184 :             i++;
                               4939                 :                :             for (;;)
                               4940                 :                :             {
                               4941                 :           1184 :                 memcpy(modname, colname, colnamelen);
                               4942                 :           1184 :                 sprintf(modname + colnamelen, "_%d", i);
                               4943         [ +  - ]:           1184 :                 if (strlen(modname) < NAMEDATALEN)
                               4944                 :           1184 :                     break;
                               4945                 :                :                 /* drop chars from colname to keep all the digits */
 3634 tgl@sss.pgh.pa.us        4946                 :UBC           0 :                 colnamelen = pg_mbcliplen(colname, colnamelen,
                               4947                 :                :                                           colnamelen - 1);
                               4948                 :                :             }
 4684 tgl@sss.pgh.pa.us        4949         [ +  + ]:CBC        1184 :         } while (!colname_is_unique(modname, dpns, colinfo));
                               4950                 :            822 :         colname = modname;
                               4951                 :                :     }
                               4952                 :         228605 :     return colname;
                               4953                 :                : }
                               4954                 :                : 
                               4955                 :                : /*
                               4956                 :                :  * expand_colnames_array_to: make colinfo->colnames at least n items long
                               4957                 :                :  *
                               4958                 :                :  * Any added array entries are initialized to zero.
                               4959                 :                :  */
                               4960                 :                : static void
                               4961                 :          48625 : expand_colnames_array_to(deparse_columns *colinfo, int n)
                               4962                 :                : {
                               4963         [ +  + ]:          48625 :     if (n > colinfo->num_cols)
                               4964                 :                :     {
                               4965         [ +  + ]:          47299 :         if (colinfo->colnames == NULL)
 1081 peter@eisentraut.org     4966                 :          46591 :             colinfo->colnames = palloc0_array(char *, n);
                               4967                 :                :         else
                               4968                 :            708 :             colinfo->colnames = repalloc0_array(colinfo->colnames, char *, colinfo->num_cols, n);
 4684 tgl@sss.pgh.pa.us        4969                 :          47299 :         colinfo->num_cols = n;
                               4970                 :                :     }
                               4971                 :          48625 : }
                               4972                 :                : 
                               4973                 :                : /*
                               4974                 :                :  * build_colinfo_names_hash: optionally construct a hash table for colinfo
                               4975                 :                :  */
                               4976                 :                : static void
  413                          4977                 :          47725 : build_colinfo_names_hash(deparse_columns *colinfo)
                               4978                 :                : {
                               4979                 :                :     HASHCTL     hash_ctl;
                               4980                 :                :     int         i;
                               4981                 :                :     ListCell   *lc;
                               4982                 :                : 
                               4983                 :                :     /*
                               4984                 :                :      * Use a hash table only for RTEs with at least 32 columns.  (The cutoff
                               4985                 :                :      * is somewhat arbitrary, but let's choose it so that this code does get
                               4986                 :                :      * exercised in the regression tests.)
                               4987                 :                :      */
                               4988         [ +  + ]:          47725 :     if (colinfo->num_cols < 32)
                               4989                 :          47049 :         return;
                               4990                 :                : 
                               4991                 :                :     /*
                               4992                 :                :      * Set up the hash table.  The entries are just strings with no other
                               4993                 :                :      * payload.
                               4994                 :                :      */
                               4995                 :            676 :     hash_ctl.keysize = NAMEDATALEN;
                               4996                 :            676 :     hash_ctl.entrysize = NAMEDATALEN;
                               4997                 :            676 :     hash_ctl.hcxt = CurrentMemoryContext;
                               4998                 :           1352 :     colinfo->names_hash = hash_create("deparse_columns names",
                               4999                 :            676 :                                       colinfo->num_cols + colinfo->num_new_cols,
                               5000                 :                :                                       &hash_ctl,
                               5001                 :                :                                       HASH_ELEM | HASH_STRINGS | HASH_CONTEXT);
                               5002                 :                : 
                               5003                 :                :     /*
                               5004                 :                :      * Preload the hash table with any names already present (these would have
                               5005                 :                :      * come from set_using_names).
                               5006                 :                :      */
                               5007         [ +  + ]:          31970 :     for (i = 0; i < colinfo->num_cols; i++)
                               5008                 :                :     {
                               5009                 :          31294 :         char       *oldname = colinfo->colnames[i];
                               5010                 :                : 
                               5011         [ -  + ]:          31294 :         if (oldname)
  413 tgl@sss.pgh.pa.us        5012                 :UBC           0 :             add_to_names_hash(colinfo, oldname);
                               5013                 :                :     }
                               5014                 :                : 
  413 tgl@sss.pgh.pa.us        5015         [ -  + ]:CBC         676 :     for (i = 0; i < colinfo->num_new_cols; i++)
                               5016                 :                :     {
  413 tgl@sss.pgh.pa.us        5017                 :UBC           0 :         char       *oldname = colinfo->new_colnames[i];
                               5018                 :                : 
                               5019         [ #  # ]:              0 :         if (oldname)
                               5020                 :              0 :             add_to_names_hash(colinfo, oldname);
                               5021                 :                :     }
                               5022                 :                : 
  413 tgl@sss.pgh.pa.us        5023   [ -  +  -  -  :CBC         676 :     foreach(lc, colinfo->parentUsing)
                                              -  + ]
                               5024                 :                :     {
  413 tgl@sss.pgh.pa.us        5025                 :UBC           0 :         char       *oldname = (char *) lfirst(lc);
                               5026                 :                : 
                               5027                 :              0 :         add_to_names_hash(colinfo, oldname);
                               5028                 :                :     }
                               5029                 :                : }
                               5030                 :                : 
                               5031                 :                : /*
                               5032                 :                :  * add_to_names_hash: add a string to the names_hash, if we're using one
                               5033                 :                :  */
                               5034                 :                : static void
  413 tgl@sss.pgh.pa.us        5035                 :CBC      253302 : add_to_names_hash(deparse_columns *colinfo, const char *name)
                               5036                 :                : {
                               5037         [ +  + ]:         253302 :     if (colinfo->names_hash)
                               5038                 :          31294 :         (void) hash_search(colinfo->names_hash,
                               5039                 :                :                            name,
                               5040                 :                :                            HASH_ENTER,
                               5041                 :                :                            NULL);
                               5042                 :         253302 : }
                               5043                 :                : 
                               5044                 :                : /*
                               5045                 :                :  * destroy_colinfo_names_hash: destroy hash table when done with it
                               5046                 :                :  */
                               5047                 :                : static void
                               5048                 :          47725 : destroy_colinfo_names_hash(deparse_columns *colinfo)
                               5049                 :                : {
                               5050         [ +  + ]:          47725 :     if (colinfo->names_hash)
                               5051                 :                :     {
                               5052                 :            676 :         hash_destroy(colinfo->names_hash);
                               5053                 :            676 :         colinfo->names_hash = NULL;
                               5054                 :                :     }
                               5055                 :          47725 : }
                               5056                 :                : 
                               5057                 :                : /*
                               5058                 :                :  * identify_join_columns: figure out where columns of a join come from
                               5059                 :                :  *
                               5060                 :                :  * Fills the join-specific fields of the colinfo struct, except for
                               5061                 :                :  * usingNames which is filled later.
                               5062                 :                :  */
                               5063                 :                : static void
 4684                          5064                 :            761 : identify_join_columns(JoinExpr *j, RangeTblEntry *jrte,
                               5065                 :                :                       deparse_columns *colinfo)
                               5066                 :                : {
                               5067                 :                :     int         numjoincols;
                               5068                 :                :     int         jcolno;
                               5069                 :                :     int         rcolno;
                               5070                 :                :     ListCell   *lc;
                               5071                 :                : 
                               5072                 :                :     /* Extract left/right child RT indexes */
                               5073         [ +  + ]:            761 :     if (IsA(j->larg, RangeTblRef))
                               5074                 :            483 :         colinfo->leftrti = ((RangeTblRef *) j->larg)->rtindex;
                               5075         [ +  - ]:            278 :     else if (IsA(j->larg, JoinExpr))
                               5076                 :            278 :         colinfo->leftrti = ((JoinExpr *) j->larg)->rtindex;
                               5077                 :                :     else
 4684 tgl@sss.pgh.pa.us        5078         [ #  # ]:UBC           0 :         elog(ERROR, "unrecognized node type in jointree: %d",
                               5079                 :                :              (int) nodeTag(j->larg));
 4684 tgl@sss.pgh.pa.us        5080         [ +  - ]:CBC         761 :     if (IsA(j->rarg, RangeTblRef))
                               5081                 :            761 :         colinfo->rightrti = ((RangeTblRef *) j->rarg)->rtindex;
 4684 tgl@sss.pgh.pa.us        5082         [ #  # ]:UBC           0 :     else if (IsA(j->rarg, JoinExpr))
                               5083                 :              0 :         colinfo->rightrti = ((JoinExpr *) j->rarg)->rtindex;
                               5084                 :                :     else
                               5085         [ #  # ]:              0 :         elog(ERROR, "unrecognized node type in jointree: %d",
                               5086                 :                :              (int) nodeTag(j->rarg));
                               5087                 :                : 
                               5088                 :                :     /* Assert children will be processed earlier than join in second pass */
 4684 tgl@sss.pgh.pa.us        5089         [ -  + ]:CBC         761 :     Assert(colinfo->leftrti < j->rtindex);
                               5090         [ -  + ]:            761 :     Assert(colinfo->rightrti < j->rtindex);
                               5091                 :                : 
                               5092                 :                :     /* Initialize result arrays with zeroes */
                               5093                 :            761 :     numjoincols = list_length(jrte->joinaliasvars);
                               5094         [ -  + ]:            761 :     Assert(numjoincols == list_length(jrte->eref->colnames));
                               5095                 :            761 :     colinfo->leftattnos = (int *) palloc0(numjoincols * sizeof(int));
                               5096                 :            761 :     colinfo->rightattnos = (int *) palloc0(numjoincols * sizeof(int));
                               5097                 :                : 
                               5098                 :                :     /*
                               5099                 :                :      * Deconstruct RTE's joinleftcols/joinrightcols into desired format.
                               5100                 :                :      * Recall that the column(s) merged due to USING are the first column(s)
                               5101                 :                :      * of the join output.  We need not do anything special while scanning
                               5102                 :                :      * joinleftcols, but while scanning joinrightcols we must distinguish
                               5103                 :                :      * merged from unmerged columns.
                               5104                 :                :      */
 2119                          5105                 :            761 :     jcolno = 0;
                               5106   [ +  -  +  +  :          18639 :     foreach(lc, jrte->joinleftcols)
                                              +  + ]
                               5107                 :                :     {
                               5108                 :          17878 :         int         leftattno = lfirst_int(lc);
                               5109                 :                : 
                               5110                 :          17878 :         colinfo->leftattnos[jcolno++] = leftattno;
                               5111                 :                :     }
                               5112                 :            761 :     rcolno = 0;
                               5113   [ +  -  +  +  :           8339 :     foreach(lc, jrte->joinrightcols)
                                              +  + ]
                               5114                 :                :     {
                               5115                 :           7578 :         int         rightattno = lfirst_int(lc);
                               5116                 :                : 
                               5117         [ +  + ]:           7578 :         if (rcolno < jrte->joinmergedcols)    /* merged column? */
                               5118                 :            290 :             colinfo->rightattnos[rcolno] = rightattno;
                               5119                 :                :         else
                               5120                 :           7288 :             colinfo->rightattnos[jcolno++] = rightattno;
                               5121                 :           7578 :         rcolno++;
                               5122                 :                :     }
                               5123         [ -  + ]:            761 :     Assert(jcolno == numjoincols);
 4684                          5124                 :            761 : }
                               5125                 :                : 
                               5126                 :                : /*
                               5127                 :                :  * get_rtable_name: convenience function to get a previously assigned RTE alias
                               5128                 :                :  *
                               5129                 :                :  * The RTE must belong to the topmost namespace level in "context".
                               5130                 :                :  */
                               5131                 :                : static char *
 4785                          5132                 :           3347 : get_rtable_name(int rtindex, deparse_context *context)
                               5133                 :                : {
                               5134                 :           3347 :     deparse_namespace *dpns = (deparse_namespace *) linitial(context->namespaces);
                               5135                 :                : 
                               5136   [ +  -  -  + ]:           3347 :     Assert(rtindex > 0 && rtindex <= list_length(dpns->rtable_names));
                               5137                 :           3347 :     return (char *) list_nth(dpns->rtable_names, rtindex - 1);
                               5138                 :                : }
                               5139                 :                : 
                               5140                 :                : /*
                               5141                 :                :  * set_deparse_plan: set up deparse_namespace to parse subexpressions
                               5142                 :                :  * of a given Plan node
                               5143                 :                :  *
                               5144                 :                :  * This sets the plan, outer_plan, inner_plan, outer_tlist, inner_tlist,
                               5145                 :                :  * and index_tlist fields.  Caller must already have adjusted the ancestors
                               5146                 :                :  * list if necessary.  Note that the rtable, subplans, and ctes fields do
                               5147                 :                :  * not need to change when shifting attention to different plan nodes in a
                               5148                 :                :  * single plan tree.
                               5149                 :                :  */
                               5150                 :                : static void
 2148                          5151                 :          74387 : set_deparse_plan(deparse_namespace *dpns, Plan *plan)
                               5152                 :                : {
                               5153                 :          74387 :     dpns->plan = plan;
                               5154                 :                : 
                               5155                 :                :     /*
                               5156                 :                :      * We special-case Append and MergeAppend to pretend that the first child
                               5157                 :                :      * plan is the OUTER referent; we have to interpret OUTER Vars in their
                               5158                 :                :      * tlists according to one of the children, and the first one is the most
                               5159                 :                :      * natural choice.
                               5160                 :                :      */
                               5161         [ +  + ]:          74387 :     if (IsA(plan, Append))
                               5162                 :           2225 :         dpns->outer_plan = linitial(((Append *) plan)->appendplans);
                               5163         [ +  + ]:          72162 :     else if (IsA(plan, MergeAppend))
                               5164                 :            264 :         dpns->outer_plan = linitial(((MergeAppend *) plan)->mergeplans);
                               5165                 :                :     else
                               5166                 :          71898 :         dpns->outer_plan = outerPlan(plan);
                               5167                 :                : 
                               5168         [ +  + ]:          74387 :     if (dpns->outer_plan)
                               5169                 :          35924 :         dpns->outer_tlist = dpns->outer_plan->targetlist;
                               5170                 :                :     else
 5131                          5171                 :          38463 :         dpns->outer_tlist = NIL;
                               5172                 :                : 
                               5173                 :                :     /*
                               5174                 :                :      * For a SubqueryScan, pretend the subplan is INNER referent.  (We don't
                               5175                 :                :      * use OUTER because that could someday conflict with the normal meaning.)
                               5176                 :                :      * Likewise, for a CteScan, pretend the subquery's plan is INNER referent.
                               5177                 :                :      * For a WorkTableScan, locate the parent RecursiveUnion plan node and use
                               5178                 :                :      * that as INNER referent.
                               5179                 :                :      *
                               5180                 :                :      * For MERGE, pretend the ModifyTable's source plan (its outer plan) is
                               5181                 :                :      * INNER referent.  This is the join from the target relation to the data
                               5182                 :                :      * source, and all INNER_VAR Vars in other parts of the query refer to its
                               5183                 :                :      * targetlist.
                               5184                 :                :      *
                               5185                 :                :      * For ON CONFLICT .. UPDATE we just need the inner tlist to point to the
                               5186                 :                :      * excluded expression's tlist. (Similar to the SubqueryScan we don't want
                               5187                 :                :      * to reuse OUTER, it's used for RETURNING in some modify table cases,
                               5188                 :                :      * although not INSERT .. CONFLICT).
                               5189                 :                :      */
 2148                          5190         [ +  + ]:          74387 :     if (IsA(plan, SubqueryScan))
                               5191                 :            331 :         dpns->inner_plan = ((SubqueryScan *) plan)->subplan;
                               5192         [ +  + ]:          74056 :     else if (IsA(plan, CteScan))
                               5193                 :            276 :         dpns->inner_plan = list_nth(dpns->subplans,
                               5194                 :            276 :                                     ((CteScan *) plan)->ctePlanId - 1);
 1503                          5195         [ +  + ]:          73780 :     else if (IsA(plan, WorkTableScan))
                               5196                 :             87 :         dpns->inner_plan = find_recursive_union(dpns,
                               5197                 :                :                                                 (WorkTableScan *) plan);
 2148                          5198         [ +  + ]:          73693 :     else if (IsA(plan, ModifyTable))
                               5199                 :                :     {
 1310 alvherre@alvh.no-ip.     5200         [ +  + ]:            201 :         if (((ModifyTable *) plan)->operation == CMD_MERGE)
  590 dean.a.rasheed@gmail     5201                 :             30 :             dpns->inner_plan = outerPlan(plan);
                               5202                 :                :         else
                               5203                 :            171 :             dpns->inner_plan = plan;
                               5204                 :                :     }
                               5205                 :                :     else
                               5206                 :          73492 :         dpns->inner_plan = innerPlan(plan);
                               5207                 :                : 
                               5208   [ +  +  +  + ]:          74387 :     if (IsA(plan, ModifyTable) && ((ModifyTable *) plan)->operation == CMD_INSERT)
                               5209                 :             85 :         dpns->inner_tlist = ((ModifyTable *) plan)->exclRelTlist;
 2148 tgl@sss.pgh.pa.us        5210         [ +  + ]:          74302 :     else if (dpns->inner_plan)
                               5211                 :          13000 :         dpns->inner_tlist = dpns->inner_plan->targetlist;
                               5212                 :                :     else
 5131                          5213                 :          61302 :         dpns->inner_tlist = NIL;
                               5214                 :                : 
                               5215                 :                :     /* Set up referent for INDEX_VAR Vars, if needed */
 2148                          5216         [ +  + ]:          74387 :     if (IsA(plan, IndexOnlyScan))
                               5217                 :           1742 :         dpns->index_tlist = ((IndexOnlyScan *) plan)->indextlist;
                               5218         [ +  + ]:          72645 :     else if (IsA(plan, ForeignScan))
                               5219                 :           1548 :         dpns->index_tlist = ((ForeignScan *) plan)->fdw_scan_tlist;
                               5220         [ -  + ]:          71097 :     else if (IsA(plan, CustomScan))
 2148 tgl@sss.pgh.pa.us        5221                 :UBC           0 :         dpns->index_tlist = ((CustomScan *) plan)->custom_scan_tlist;
                               5222                 :                :     else
 5131 tgl@sss.pgh.pa.us        5223                 :CBC       71097 :         dpns->index_tlist = NIL;
 5586                          5224                 :          74387 : }
                               5225                 :                : 
                               5226                 :                : /*
                               5227                 :                :  * Locate the ancestor plan node that is the RecursiveUnion generating
                               5228                 :                :  * the WorkTableScan's work table.  We can match on wtParam, since that
                               5229                 :                :  * should be unique within the plan tree.
                               5230                 :                :  */
                               5231                 :                : static Plan *
 1503                          5232                 :             87 : find_recursive_union(deparse_namespace *dpns, WorkTableScan *wtscan)
                               5233                 :                : {
                               5234                 :                :     ListCell   *lc;
                               5235                 :                : 
                               5236   [ +  -  +  -  :            219 :     foreach(lc, dpns->ancestors)
                                              +  - ]
                               5237                 :                :     {
                               5238                 :            219 :         Plan       *ancestor = (Plan *) lfirst(lc);
                               5239                 :                : 
                               5240         [ +  + ]:            219 :         if (IsA(ancestor, RecursiveUnion) &&
                               5241         [ +  - ]:             87 :             ((RecursiveUnion *) ancestor)->wtParam == wtscan->wtParam)
                               5242                 :             87 :             return ancestor;
                               5243                 :                :     }
 1503 tgl@sss.pgh.pa.us        5244         [ #  # ]:UBC           0 :     elog(ERROR, "could not find RecursiveUnion for WorkTableScan with wtParam %d",
                               5245                 :                :          wtscan->wtParam);
                               5246                 :                :     return NULL;
                               5247                 :                : }
                               5248                 :                : 
                               5249                 :                : /*
                               5250                 :                :  * push_child_plan: temporarily transfer deparsing attention to a child plan
                               5251                 :                :  *
                               5252                 :                :  * When expanding an OUTER_VAR or INNER_VAR reference, we must adjust the
                               5253                 :                :  * deparse context in case the referenced expression itself uses
                               5254                 :                :  * OUTER_VAR/INNER_VAR.  We modify the top stack entry in-place to avoid
                               5255                 :                :  * affecting levelsup issues (although in a Plan tree there really shouldn't
                               5256                 :                :  * be any).
                               5257                 :                :  *
                               5258                 :                :  * Caller must provide a local deparse_namespace variable to save the
                               5259                 :                :  * previous state for pop_child_plan.
                               5260                 :                :  */
                               5261                 :                : static void
 2148 tgl@sss.pgh.pa.us        5262                 :CBC       43244 : push_child_plan(deparse_namespace *dpns, Plan *plan,
                               5263                 :                :                 deparse_namespace *save_dpns)
                               5264                 :                : {
                               5265                 :                :     /* Save state for restoration later */
 5586                          5266                 :          43244 :     *save_dpns = *dpns;
                               5267                 :                : 
                               5268                 :                :     /* Link current plan node into ancestors list */
 2148                          5269                 :          43244 :     dpns->ancestors = lcons(dpns->plan, dpns->ancestors);
                               5270                 :                : 
                               5271                 :                :     /* Set attention on selected child */
                               5272                 :          43244 :     set_deparse_plan(dpns, plan);
 9022                          5273                 :          43244 : }
                               5274                 :                : 
                               5275                 :                : /*
                               5276                 :                :  * pop_child_plan: undo the effects of push_child_plan
                               5277                 :                :  */
                               5278                 :                : static void
 5586                          5279                 :          43244 : pop_child_plan(deparse_namespace *dpns, deparse_namespace *save_dpns)
                               5280                 :                : {
                               5281                 :                :     List       *ancestors;
                               5282                 :                : 
                               5283                 :                :     /* Get rid of ancestors list cell added by push_child_plan */
 4807                          5284                 :          43244 :     ancestors = list_delete_first(dpns->ancestors);
                               5285                 :                : 
                               5286                 :                :     /* Restore fields changed by push_child_plan */
 5586                          5287                 :          43244 :     *dpns = *save_dpns;
                               5288                 :                : 
                               5289                 :                :     /* Make sure dpns->ancestors is right (may be unnecessary) */
 4807                          5290                 :          43244 :     dpns->ancestors = ancestors;
 5586                          5291                 :          43244 : }
                               5292                 :                : 
                               5293                 :                : /*
                               5294                 :                :  * push_ancestor_plan: temporarily transfer deparsing attention to an
                               5295                 :                :  * ancestor plan
                               5296                 :                :  *
                               5297                 :                :  * When expanding a Param reference, we must adjust the deparse context
                               5298                 :                :  * to match the plan node that contains the expression being printed;
                               5299                 :                :  * otherwise we'd fail if that expression itself contains a Param or
                               5300                 :                :  * OUTER_VAR/INNER_VAR/INDEX_VAR variable.
                               5301                 :                :  *
                               5302                 :                :  * The target ancestor is conveniently identified by the ListCell holding it
                               5303                 :                :  * in dpns->ancestors.
                               5304                 :                :  *
                               5305                 :                :  * Caller must provide a local deparse_namespace variable to save the
                               5306                 :                :  * previous state for pop_ancestor_plan.
                               5307                 :                :  */
                               5308                 :                : static void
                               5309                 :           2320 : push_ancestor_plan(deparse_namespace *dpns, ListCell *ancestor_cell,
                               5310                 :                :                    deparse_namespace *save_dpns)
                               5311                 :                : {
 2148                          5312                 :           2320 :     Plan       *plan = (Plan *) lfirst(ancestor_cell);
                               5313                 :                : 
                               5314                 :                :     /* Save state for restoration later */
 5586                          5315                 :           2320 :     *save_dpns = *dpns;
                               5316                 :                : 
                               5317                 :                :     /* Build a new ancestor list with just this node's ancestors */
 2297                          5318                 :           2320 :     dpns->ancestors =
                               5319                 :           2320 :         list_copy_tail(dpns->ancestors,
                               5320                 :           2320 :                        list_cell_number(dpns->ancestors, ancestor_cell) + 1);
                               5321                 :                : 
                               5322                 :                :     /* Set attention on selected ancestor */
 2148                          5323                 :           2320 :     set_deparse_plan(dpns, plan);
 5586                          5324                 :           2320 : }
                               5325                 :                : 
                               5326                 :                : /*
                               5327                 :                :  * pop_ancestor_plan: undo the effects of push_ancestor_plan
                               5328                 :                :  */
                               5329                 :                : static void
                               5330                 :           2320 : pop_ancestor_plan(deparse_namespace *dpns, deparse_namespace *save_dpns)
                               5331                 :                : {
                               5332                 :                :     /* Free the ancestor list made in push_ancestor_plan */
                               5333                 :           2320 :     list_free(dpns->ancestors);
                               5334                 :                : 
                               5335                 :                :     /* Restore fields changed by push_ancestor_plan */
                               5336                 :           2320 :     *dpns = *save_dpns;
                               5337                 :           2320 : }
                               5338                 :                : 
                               5339                 :                : 
                               5340                 :                : /* ----------
                               5341                 :                :  * make_ruledef         - reconstruct the CREATE RULE command
                               5342                 :                :  *                for a given pg_rewrite tuple
                               5343                 :                :  * ----------
                               5344                 :                :  */
                               5345                 :                : static void
 8126                          5346                 :            279 : make_ruledef(StringInfo buf, HeapTuple ruletup, TupleDesc rulettc,
                               5347                 :                :              int prettyFlags)
                               5348                 :                : {
                               5349                 :                :     char       *rulename;
                               5350                 :                :     char        ev_type;
                               5351                 :                :     Oid         ev_class;
                               5352                 :                :     bool        is_instead;
                               5353                 :                :     char       *ev_qual;
                               5354                 :                :     char       *ev_action;
                               5355                 :                :     List       *actions;
                               5356                 :                :     Relation    ev_relation;
 3018                          5357                 :            279 :     TupleDesc   viewResultDesc = NULL;
                               5358                 :                :     int         fno;
                               5359                 :                :     Datum       dat;
                               5360                 :                :     bool        isnull;
                               5361                 :                : 
                               5362                 :                :     /*
                               5363                 :                :      * Get the attribute values from the rules tuple
                               5364                 :                :      */
 8594                          5365                 :            279 :     fno = SPI_fnumber(rulettc, "rulename");
                               5366                 :            279 :     dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
                               5367         [ -  + ]:            279 :     Assert(!isnull);
                               5368                 :            279 :     rulename = NameStr(*(DatumGetName(dat)));
                               5369                 :                : 
 9919 bruce@momjian.us         5370                 :            279 :     fno = SPI_fnumber(rulettc, "ev_type");
 8594 tgl@sss.pgh.pa.us        5371                 :            279 :     dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
                               5372         [ -  + ]:            279 :     Assert(!isnull);
                               5373                 :            279 :     ev_type = DatumGetChar(dat);
                               5374                 :                : 
 9919 bruce@momjian.us         5375                 :            279 :     fno = SPI_fnumber(rulettc, "ev_class");
 8594 tgl@sss.pgh.pa.us        5376                 :            279 :     dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
                               5377         [ -  + ]:            279 :     Assert(!isnull);
                               5378                 :            279 :     ev_class = DatumGetObjectId(dat);
                               5379                 :                : 
 9919 bruce@momjian.us         5380                 :            279 :     fno = SPI_fnumber(rulettc, "is_instead");
 8594 tgl@sss.pgh.pa.us        5381                 :            279 :     dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
                               5382         [ -  + ]:            279 :     Assert(!isnull);
                               5383                 :            279 :     is_instead = DatumGetBool(dat);
                               5384                 :                : 
 9919 bruce@momjian.us         5385                 :            279 :     fno = SPI_fnumber(rulettc, "ev_qual");
                               5386                 :            279 :     ev_qual = SPI_getvalue(ruletup, rulettc, fno);
 1821 tgl@sss.pgh.pa.us        5387         [ -  + ]:            279 :     Assert(ev_qual != NULL);
                               5388                 :                : 
 9919 bruce@momjian.us         5389                 :            279 :     fno = SPI_fnumber(rulettc, "ev_action");
                               5390                 :            279 :     ev_action = SPI_getvalue(ruletup, rulettc, fno);
 1821 tgl@sss.pgh.pa.us        5391         [ -  + ]:            279 :     Assert(ev_action != NULL);
                               5392                 :            279 :     actions = (List *) stringToNode(ev_action);
                               5393         [ -  + ]:            279 :     if (actions == NIL)
 1821 tgl@sss.pgh.pa.us        5394         [ #  # ]:UBC           0 :         elog(ERROR, "invalid empty ev_action list");
                               5395                 :                : 
 2472 andres@anarazel.de       5396                 :CBC         279 :     ev_relation = table_open(ev_class, AccessShareLock);
                               5397                 :                : 
                               5398                 :                :     /*
                               5399                 :                :      * Build the rules definition text
                               5400                 :                :      */
 8126 tgl@sss.pgh.pa.us        5401                 :            279 :     appendStringInfo(buf, "CREATE RULE %s AS",
                               5402                 :                :                      quote_identifier(rulename));
                               5403                 :                : 
                               5404         [ +  - ]:            279 :     if (prettyFlags & PRETTYFLAG_INDENT)
 8121 bruce@momjian.us         5405                 :            279 :         appendStringInfoString(buf, "\n    ON ");
                               5406                 :                :     else
 8121 bruce@momjian.us         5407                 :UBC           0 :         appendStringInfoString(buf, " ON ");
                               5408                 :                : 
                               5409                 :                :     /* The event the rule is fired for */
 9919 bruce@momjian.us         5410   [ +  +  +  +  :CBC         279 :     switch (ev_type)
                                                 - ]
                               5411                 :                :     {
                               5412                 :              3 :         case '1':
 4380 rhaas@postgresql.org     5413                 :              3 :             appendStringInfoString(buf, "SELECT");
 3018 tgl@sss.pgh.pa.us        5414                 :              3 :             viewResultDesc = RelationGetDescr(ev_relation);
 9927 bruce@momjian.us         5415                 :              3 :             break;
                               5416                 :                : 
 9919                          5417                 :             77 :         case '2':
 4380 rhaas@postgresql.org     5418                 :             77 :             appendStringInfoString(buf, "UPDATE");
 9927 bruce@momjian.us         5419                 :             77 :             break;
                               5420                 :                : 
 9919                          5421                 :            147 :         case '3':
 4380 rhaas@postgresql.org     5422                 :            147 :             appendStringInfoString(buf, "INSERT");
 9927 bruce@momjian.us         5423                 :            147 :             break;
                               5424                 :                : 
 9919                          5425                 :             52 :         case '4':
 4380 rhaas@postgresql.org     5426                 :             52 :             appendStringInfoString(buf, "DELETE");
 9927 bruce@momjian.us         5427                 :             52 :             break;
                               5428                 :                : 
 9919 bruce@momjian.us         5429                 :UBC           0 :         default:
 8129 tgl@sss.pgh.pa.us        5430         [ #  # ]:              0 :             ereport(ERROR,
                               5431                 :                :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                               5432                 :                :                      errmsg("rule \"%s\" has unsupported event type %d",
                               5433                 :                :                             rulename, ev_type)));
                               5434                 :                :             break;
                               5435                 :                :     }
                               5436                 :                : 
                               5437                 :                :     /* The relation the rule is fired on */
 2801 tgl@sss.pgh.pa.us        5438                 :CBC         279 :     appendStringInfo(buf, " TO %s",
                               5439         [ +  + ]:            279 :                      (prettyFlags & PRETTYFLAG_SCHEMA) ?
                               5440                 :             57 :                      generate_relation_name(ev_class, NIL) :
                               5441                 :            222 :                      generate_qualified_relation_name(ev_class));
                               5442                 :                : 
                               5443                 :                :     /* If the rule has an event qualification, add it */
 1821                          5444         [ +  + ]:            279 :     if (strcmp(ev_qual, "<>") != 0)
                               5445                 :                :     {
                               5446                 :                :         Node       *qual;
                               5447                 :                :         Query      *query;
                               5448                 :                :         deparse_context context;
                               5449                 :                :         deparse_namespace dpns;
                               5450                 :                : 
 8126                          5451         [ +  - ]:             61 :         if (prettyFlags & PRETTYFLAG_INDENT)
 8121 bruce@momjian.us         5452                 :             61 :             appendStringInfoString(buf, "\n  ");
 4380 rhaas@postgresql.org     5453                 :             61 :         appendStringInfoString(buf, " WHERE ");
                               5454                 :                : 
 9919 bruce@momjian.us         5455                 :             61 :         qual = stringToNode(ev_qual);
                               5456                 :                : 
                               5457                 :                :         /*
                               5458                 :                :          * We need to make a context for recognizing any Vars in the qual
                               5459                 :                :          * (which can only be references to OLD and NEW).  Use the rtable of
                               5460                 :                :          * the first query in the action list for this purpose.
                               5461                 :                :          */
 7825 neilc@samurai.com        5462                 :             61 :         query = (Query *) linitial(actions);
                               5463                 :                : 
                               5464                 :                :         /*
                               5465                 :                :          * If the action is INSERT...SELECT, OLD/NEW have been pushed down
                               5466                 :                :          * into the SELECT, and that's what we need to look at. (Ugly kluge
                               5467                 :                :          * ... try to fix this when we redesign querytrees.)
                               5468                 :                :          */
 8737 tgl@sss.pgh.pa.us        5469                 :             61 :         query = getInsertSelectQuery(query, NULL);
                               5470                 :                : 
                               5471                 :                :         /* Must acquire locks right away; see notes in get_query_def() */
 4254                          5472                 :             61 :         AcquireRewriteLocks(query, false, false);
                               5473                 :                : 
 9522                          5474                 :             61 :         context.buf = buf;
 7821 neilc@samurai.com        5475                 :             61 :         context.namespaces = list_make1(&dpns);
  425 tgl@sss.pgh.pa.us        5476                 :             61 :         context.resultDesc = NULL;
                               5477                 :             61 :         context.targetList = NIL;
 6148                          5478                 :             61 :         context.windowClause = NIL;
 7821 neilc@samurai.com        5479                 :             61 :         context.varprefix = (list_length(query->rtable) != 1);
 8126 tgl@sss.pgh.pa.us        5480                 :             61 :         context.prettyFlags = prettyFlags;
 4691                          5481                 :             61 :         context.wrapColumn = WRAP_COLUMN_DEFAULT;
 8126                          5482                 :             61 :         context.indentLevel = PRETTYINDENT_STD;
  425                          5483                 :             61 :         context.colNamesVisible = true;
                               5484                 :             61 :         context.inGroupBy = false;
                               5485                 :             61 :         context.varInOrderBy = false;
 2148                          5486                 :             61 :         context.appendparents = NULL;
                               5487                 :                : 
 4684                          5488                 :             61 :         set_deparse_for_query(&dpns, query, NIL);
                               5489                 :                : 
 8440                          5490                 :             61 :         get_rule_expr(qual, &context, false);
                               5491                 :                :     }
                               5492                 :                : 
 4380 rhaas@postgresql.org     5493                 :            279 :     appendStringInfoString(buf, " DO ");
                               5494                 :                : 
                               5495                 :                :     /* The INSTEAD keyword (if so) */
 9919 bruce@momjian.us         5496         [ +  + ]:            279 :     if (is_instead)
 4380 rhaas@postgresql.org     5497                 :            165 :         appendStringInfoString(buf, "INSTEAD ");
                               5498                 :                : 
                               5499                 :                :     /* Finally the rules actions */
 7821 neilc@samurai.com        5500         [ +  + ]:            279 :     if (list_length(actions) > 1)
                               5501                 :                :     {
                               5502                 :                :         ListCell   *action;
                               5503                 :                :         Query      *query;
                               5504                 :                : 
 4380 rhaas@postgresql.org     5505                 :             10 :         appendStringInfoChar(buf, '(');
 9919 bruce@momjian.us         5506   [ +  -  +  +  :             30 :         foreach(action, actions)
                                              +  + ]
                               5507                 :                :         {
                               5508                 :             20 :             query = (Query *) lfirst(action);
 1256 tgl@sss.pgh.pa.us        5509                 :             20 :             get_query_def(query, buf, NIL, viewResultDesc, true,
                               5510                 :                :                           prettyFlags, WRAP_COLUMN_DEFAULT, 0);
 8126                          5511         [ +  - ]:             20 :             if (prettyFlags)
 4380 rhaas@postgresql.org     5512                 :             20 :                 appendStringInfoString(buf, ";\n");
                               5513                 :                :             else
 4380 rhaas@postgresql.org     5514                 :UBC           0 :                 appendStringInfoString(buf, "; ");
                               5515                 :                :         }
 4380 rhaas@postgresql.org     5516                 :CBC          10 :         appendStringInfoString(buf, ");");
                               5517                 :                :     }
                               5518                 :                :     else
                               5519                 :                :     {
                               5520                 :                :         Query      *query;
                               5521                 :                : 
 7825 neilc@samurai.com        5522                 :            269 :         query = (Query *) linitial(actions);
 1256 tgl@sss.pgh.pa.us        5523                 :            269 :         get_query_def(query, buf, NIL, viewResultDesc, true,
                               5524                 :                :                       prettyFlags, WRAP_COLUMN_DEFAULT, 0);
 4380 rhaas@postgresql.org     5525                 :            269 :         appendStringInfoChar(buf, ';');
                               5526                 :                :     }
                               5527                 :                : 
 2472 andres@anarazel.de       5528                 :            279 :     table_close(ev_relation, AccessShareLock);
 9927 bruce@momjian.us         5529                 :            279 : }
                               5530                 :                : 
                               5531                 :                : 
                               5532                 :                : /* ----------
                               5533                 :                :  * make_viewdef         - reconstruct the SELECT part of a
                               5534                 :                :  *                view rewrite rule
                               5535                 :                :  * ----------
                               5536                 :                :  */
                               5537                 :                : static void
 8126 tgl@sss.pgh.pa.us        5538                 :           1759 : make_viewdef(StringInfo buf, HeapTuple ruletup, TupleDesc rulettc,
                               5539                 :                :              int prettyFlags, int wrapColumn)
                               5540                 :                : {
                               5541                 :                :     Query      *query;
                               5542                 :                :     char        ev_type;
                               5543                 :                :     Oid         ev_class;
                               5544                 :                :     bool        is_instead;
                               5545                 :                :     char       *ev_qual;
                               5546                 :                :     char       *ev_action;
                               5547                 :                :     List       *actions;
                               5548                 :                :     Relation    ev_relation;
                               5549                 :                :     int         fno;
                               5550                 :                :     Datum       dat;
                               5551                 :                :     bool        isnull;
                               5552                 :                : 
                               5553                 :                :     /*
                               5554                 :                :      * Get the attribute values from the rules tuple
                               5555                 :                :      */
 9919 bruce@momjian.us         5556                 :           1759 :     fno = SPI_fnumber(rulettc, "ev_type");
 3018 tgl@sss.pgh.pa.us        5557                 :           1759 :     dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
                               5558         [ -  + ]:           1759 :     Assert(!isnull);
                               5559                 :           1759 :     ev_type = DatumGetChar(dat);
                               5560                 :                : 
 9919 bruce@momjian.us         5561                 :           1759 :     fno = SPI_fnumber(rulettc, "ev_class");
 3018 tgl@sss.pgh.pa.us        5562                 :           1759 :     dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
                               5563         [ -  + ]:           1759 :     Assert(!isnull);
                               5564                 :           1759 :     ev_class = DatumGetObjectId(dat);
                               5565                 :                : 
 9919 bruce@momjian.us         5566                 :           1759 :     fno = SPI_fnumber(rulettc, "is_instead");
 3018 tgl@sss.pgh.pa.us        5567                 :           1759 :     dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
                               5568         [ -  + ]:           1759 :     Assert(!isnull);
                               5569                 :           1759 :     is_instead = DatumGetBool(dat);
                               5570                 :                : 
 9919 bruce@momjian.us         5571                 :           1759 :     fno = SPI_fnumber(rulettc, "ev_qual");
                               5572                 :           1759 :     ev_qual = SPI_getvalue(ruletup, rulettc, fno);
 1821 tgl@sss.pgh.pa.us        5573         [ -  + ]:           1759 :     Assert(ev_qual != NULL);
                               5574                 :                : 
 9919 bruce@momjian.us         5575                 :           1759 :     fno = SPI_fnumber(rulettc, "ev_action");
                               5576                 :           1759 :     ev_action = SPI_getvalue(ruletup, rulettc, fno);
 1821 tgl@sss.pgh.pa.us        5577         [ -  + ]:           1759 :     Assert(ev_action != NULL);
                               5578                 :           1759 :     actions = (List *) stringToNode(ev_action);
                               5579                 :                : 
 7821 neilc@samurai.com        5580         [ -  + ]:           1759 :     if (list_length(actions) != 1)
                               5581                 :                :     {
                               5582                 :                :         /* keep output buffer empty and leave */
 9523 tgl@sss.pgh.pa.us        5583                 :UBC           0 :         return;
                               5584                 :                :     }
                               5585                 :                : 
 7825 neilc@samurai.com        5586                 :CBC        1759 :     query = (Query *) linitial(actions);
                               5587                 :                : 
 4436 kgrittn@postgresql.o     5588   [ +  -  +  - ]:           1759 :     if (ev_type != '1' || !is_instead ||
 8482 tgl@sss.pgh.pa.us        5589   [ +  -  -  + ]:           1759 :         strcmp(ev_qual, "<>") != 0 || query->commandType != CMD_SELECT)
                               5590                 :                :     {
                               5591                 :                :         /* keep output buffer empty and leave */
 9523 tgl@sss.pgh.pa.us        5592                 :UBC           0 :         return;
                               5593                 :                :     }
                               5594                 :                : 
 2472 andres@anarazel.de       5595                 :CBC        1759 :     ev_relation = table_open(ev_class, AccessShareLock);
                               5596                 :                : 
 1256 tgl@sss.pgh.pa.us        5597                 :           1759 :     get_query_def(query, buf, NIL, RelationGetDescr(ev_relation), true,
                               5598                 :                :                   prettyFlags, wrapColumn, 0);
 4380 rhaas@postgresql.org     5599                 :           1759 :     appendStringInfoChar(buf, ';');
                               5600                 :                : 
 2472 andres@anarazel.de       5601                 :           1759 :     table_close(ev_relation, AccessShareLock);
                               5602                 :                : }
                               5603                 :                : 
                               5604                 :                : 
                               5605                 :                : /* ----------
                               5606                 :                :  * get_query_def            - Parse back one query parsetree
                               5607                 :                :  *
                               5608                 :                :  * query: parsetree to be displayed
                               5609                 :                :  * buf: output text is appended to buf
                               5610                 :                :  * parentnamespace: list (initially empty) of outer-level deparse_namespace's
                               5611                 :                :  * resultDesc: if not NULL, the output tuple descriptor for the view
                               5612                 :                :  *      represented by a SELECT query.  We use the column names from it
                               5613                 :                :  *      to label SELECT output columns, in preference to names in the query
                               5614                 :                :  * colNamesVisible: true if the surrounding context cares about the output
                               5615                 :                :  *      column names at all (as, for example, an EXISTS() context does not);
                               5616                 :                :  *      when false, we can suppress dummy column labels such as "?column?"
                               5617                 :                :  * prettyFlags: bitmask of PRETTYFLAG_XXX options
                               5618                 :                :  * wrapColumn: maximum line length, or -1 to disable wrapping
                               5619                 :                :  * startIndent: initial indentation amount
                               5620                 :                :  * ----------
                               5621                 :                :  */
                               5622                 :                : static void
 8482 tgl@sss.pgh.pa.us        5623                 :           2852 : get_query_def(Query *query, StringInfo buf, List *parentnamespace,
                               5624                 :                :               TupleDesc resultDesc, bool colNamesVisible,
                               5625                 :                :               int prettyFlags, int wrapColumn, int startIndent)
                               5626                 :                : {
                               5627                 :                :     deparse_context context;
                               5628                 :                :     deparse_namespace dpns;
                               5629                 :                :     int         rtable_size;
                               5630                 :                : 
                               5631                 :                :     /* Guard against excessively long or deeply-nested queries */
 4199                          5632         [ -  + ]:           2852 :     CHECK_FOR_INTERRUPTS();
                               5633                 :           2852 :     check_stack_depth();
                               5634                 :                : 
  413 rguo@postgresql.org      5635                 :           5704 :     rtable_size = query->hasGroupRTE ?
                               5636         [ +  + ]:           2852 :         list_length(query->rtable) - 1 :
                               5637                 :           2742 :         list_length(query->rtable);
                               5638                 :                : 
                               5639                 :                :     /*
                               5640                 :                :      * Replace any Vars in the query's targetlist and havingQual that
                               5641                 :                :      * reference GROUP outputs with the underlying grouping expressions.
                               5642                 :                :      */
                               5643         [ +  + ]:           2852 :     if (query->hasGroupRTE)
                               5644                 :                :     {
                               5645                 :            110 :         query->targetList = (List *)
                               5646                 :            110 :             flatten_group_exprs(NULL, query, (Node *) query->targetList);
                               5647                 :            110 :         query->havingQual =
                               5648                 :            110 :             flatten_group_exprs(NULL, query, query->havingQual);
                               5649                 :                :     }
                               5650                 :                : 
                               5651                 :                :     /*
                               5652                 :                :      * Before we begin to examine the query, acquire locks on referenced
                               5653                 :                :      * relations, and fix up deleted columns in JOIN RTEs.  This ensures
                               5654                 :                :      * consistent results.  Note we assume it's OK to scribble on the passed
                               5655                 :                :      * querytree!
                               5656                 :                :      *
                               5657                 :                :      * We are only deparsing the query (we are not about to execute it), so we
                               5658                 :                :      * only need AccessShareLock on the relations it mentions.
                               5659                 :                :      */
 4254 tgl@sss.pgh.pa.us        5660                 :           2852 :     AcquireRewriteLocks(query, false, false);
                               5661                 :                : 
 9522                          5662                 :           2852 :     context.buf = buf;
 7825 neilc@samurai.com        5663                 :           2852 :     context.namespaces = lcons(&dpns, list_copy(parentnamespace));
  425 tgl@sss.pgh.pa.us        5664                 :           2852 :     context.resultDesc = NULL;
                               5665                 :           2852 :     context.targetList = NIL;
 6148                          5666                 :           2852 :     context.windowClause = NIL;
 9022                          5667   [ +  +  +  + ]:           2852 :     context.varprefix = (parentnamespace != NIL ||
                               5668                 :                :                          rtable_size != 1);
 8126                          5669                 :           2852 :     context.prettyFlags = prettyFlags;
 4691                          5670                 :           2852 :     context.wrapColumn = wrapColumn;
 8126                          5671                 :           2852 :     context.indentLevel = startIndent;
  425                          5672                 :           2852 :     context.colNamesVisible = colNamesVisible;
                               5673                 :           2852 :     context.inGroupBy = false;
                               5674                 :           2852 :     context.varInOrderBy = false;
 2148                          5675                 :           2852 :     context.appendparents = NULL;
                               5676                 :                : 
 4684                          5677                 :           2852 :     set_deparse_for_query(&dpns, query, parentnamespace);
                               5678                 :                : 
 9919 bruce@momjian.us         5679   [ +  +  +  +  :           2852 :     switch (query->commandType)
                                        +  +  +  - ]
                               5680                 :                :     {
 9653                          5681                 :           2532 :         case CMD_SELECT:
                               5682                 :                :             /* We set context.resultDesc only if it's a SELECT */
  425 tgl@sss.pgh.pa.us        5683                 :           2532 :             context.resultDesc = resultDesc;
                               5684                 :           2532 :             get_select_query_def(query, &context);
 9919 bruce@momjian.us         5685                 :           2532 :             break;
                               5686                 :                : 
                               5687                 :             77 :         case CMD_UPDATE:
  425 tgl@sss.pgh.pa.us        5688                 :             77 :             get_update_query_def(query, &context);
 9919 bruce@momjian.us         5689                 :             77 :             break;
                               5690                 :                : 
                               5691                 :            170 :         case CMD_INSERT:
  425 tgl@sss.pgh.pa.us        5692                 :            170 :             get_insert_query_def(query, &context);
 9919 bruce@momjian.us         5693                 :            170 :             break;
                               5694                 :                : 
                               5695                 :             38 :         case CMD_DELETE:
  425 tgl@sss.pgh.pa.us        5696                 :             38 :             get_delete_query_def(query, &context);
 9919 bruce@momjian.us         5697                 :             38 :             break;
                               5698                 :                : 
  905 tgl@sss.pgh.pa.us        5699                 :              6 :         case CMD_MERGE:
  425                          5700                 :              6 :             get_merge_query_def(query, &context);
  905                          5701                 :              6 :             break;
                               5702                 :                : 
 9919 bruce@momjian.us         5703                 :             21 :         case CMD_NOTHING:
 4380 rhaas@postgresql.org     5704                 :             21 :             appendStringInfoString(buf, "NOTHING");
 9919 bruce@momjian.us         5705                 :             21 :             break;
                               5706                 :                : 
 9064 tgl@sss.pgh.pa.us        5707                 :              8 :         case CMD_UTILITY:
                               5708                 :              8 :             get_utility_query_def(query, &context);
                               5709                 :              8 :             break;
                               5710                 :                : 
 9919 bruce@momjian.us         5711                 :UBC           0 :         default:
 8129 tgl@sss.pgh.pa.us        5712         [ #  # ]:              0 :             elog(ERROR, "unrecognized query command type: %d",
                               5713                 :                :                  query->commandType);
                               5714                 :                :             break;
                               5715                 :                :     }
 9927 bruce@momjian.us         5716                 :CBC        2852 : }
                               5717                 :                : 
                               5718                 :                : /* ----------
                               5719                 :                :  * get_values_def           - Parse back a VALUES list
                               5720                 :                :  * ----------
                               5721                 :                :  */
                               5722                 :                : static void
 7027 mail@joeconway.com       5723                 :            136 : get_values_def(List *values_lists, deparse_context *context)
                               5724                 :                : {
                               5725                 :            136 :     StringInfo  buf = context->buf;
                               5726                 :            136 :     bool        first_list = true;
                               5727                 :                :     ListCell   *vtl;
                               5728                 :                : 
                               5729                 :            136 :     appendStringInfoString(buf, "VALUES ");
                               5730                 :                : 
                               5731   [ +  -  +  +  :            389 :     foreach(vtl, values_lists)
                                              +  + ]
                               5732                 :                :     {
                               5733                 :            253 :         List       *sublist = (List *) lfirst(vtl);
                               5734                 :            253 :         bool        first_col = true;
                               5735                 :                :         ListCell   *lc;
                               5736                 :                : 
                               5737         [ +  + ]:            253 :         if (first_list)
                               5738                 :            136 :             first_list = false;
                               5739                 :                :         else
                               5740                 :            117 :             appendStringInfoString(buf, ", ");
                               5741                 :                : 
                               5742                 :            253 :         appendStringInfoChar(buf, '(');
                               5743   [ +  -  +  +  :            979 :         foreach(lc, sublist)
                                              +  + ]
                               5744                 :                :         {
 6964 bruce@momjian.us         5745                 :            726 :             Node       *col = (Node *) lfirst(lc);
                               5746                 :                : 
 7027 mail@joeconway.com       5747         [ +  + ]:            726 :             if (first_col)
                               5748                 :            253 :                 first_col = false;
                               5749                 :                :             else
                               5750                 :            473 :                 appendStringInfoChar(buf, ',');
                               5751                 :                : 
                               5752                 :                :             /*
                               5753                 :                :              * Print the value.  Whole-row Vars need special treatment.
                               5754                 :                :              */
 3373 tgl@sss.pgh.pa.us        5755                 :            726 :             get_rule_expr_toplevel(col, context, false);
                               5756                 :                :         }
 7027 mail@joeconway.com       5757                 :            253 :         appendStringInfoChar(buf, ')');
                               5758                 :                :     }
                               5759                 :            136 : }
                               5760                 :                : 
                               5761                 :                : /* ----------
                               5762                 :                :  * get_with_clause          - Parse back a WITH clause
                               5763                 :                :  * ----------
                               5764                 :                :  */
                               5765                 :                : static void
 6233 tgl@sss.pgh.pa.us        5766                 :           2823 : get_with_clause(Query *query, deparse_context *context)
                               5767                 :                : {
                               5768                 :           2823 :     StringInfo  buf = context->buf;
                               5769                 :                :     const char *sep;
                               5770                 :                :     ListCell   *l;
                               5771                 :                : 
                               5772         [ +  + ]:           2823 :     if (query->cteList == NIL)
                               5773                 :           2775 :         return;
                               5774                 :                : 
                               5775         [ +  - ]:             48 :     if (PRETTY_INDENT(context))
                               5776                 :                :     {
                               5777                 :             48 :         context->indentLevel += PRETTYINDENT_STD;
                               5778                 :             48 :         appendStringInfoChar(buf, ' ');
                               5779                 :                :     }
                               5780                 :                : 
                               5781         [ +  + ]:             48 :     if (query->hasRecursive)
                               5782                 :             28 :         sep = "WITH RECURSIVE ";
                               5783                 :                :     else
                               5784                 :             20 :         sep = "WITH ";
                               5785   [ +  -  +  +  :            121 :     foreach(l, query->cteList)
                                              +  + ]
                               5786                 :                :     {
                               5787                 :             73 :         CommonTableExpr *cte = (CommonTableExpr *) lfirst(l);
                               5788                 :                : 
                               5789                 :             73 :         appendStringInfoString(buf, sep);
                               5790                 :             73 :         appendStringInfoString(buf, quote_identifier(cte->ctename));
                               5791         [ +  + ]:             73 :         if (cte->aliascolnames)
                               5792                 :                :         {
                               5793                 :             28 :             bool        first = true;
                               5794                 :                :             ListCell   *col;
                               5795                 :                : 
                               5796                 :             28 :             appendStringInfoChar(buf, '(');
                               5797   [ +  -  +  +  :             74 :             foreach(col, cte->aliascolnames)
                                              +  + ]
                               5798                 :                :             {
                               5799         [ +  + ]:             46 :                 if (first)
                               5800                 :             28 :                     first = false;
                               5801                 :                :                 else
                               5802                 :             18 :                     appendStringInfoString(buf, ", ");
                               5803                 :             46 :                 appendStringInfoString(buf,
                               5804                 :             46 :                                        quote_identifier(strVal(lfirst(col))));
                               5805                 :                :             }
                               5806                 :             28 :             appendStringInfoChar(buf, ')');
                               5807                 :                :         }
 2446                          5808                 :             73 :         appendStringInfoString(buf, " AS ");
                               5809   [ +  +  -  - ]:             73 :         switch (cte->ctematerialized)
                               5810                 :                :         {
                               5811                 :             64 :             case CTEMaterializeDefault:
                               5812                 :             64 :                 break;
                               5813                 :              9 :             case CTEMaterializeAlways:
                               5814                 :              9 :                 appendStringInfoString(buf, "MATERIALIZED ");
                               5815                 :              9 :                 break;
 2446 tgl@sss.pgh.pa.us        5816                 :UBC           0 :             case CTEMaterializeNever:
                               5817                 :              0 :                 appendStringInfoString(buf, "NOT MATERIALIZED ");
                               5818                 :              0 :                 break;
                               5819                 :                :         }
 2446 tgl@sss.pgh.pa.us        5820                 :CBC          73 :         appendStringInfoChar(buf, '(');
 6233                          5821         [ +  - ]:             73 :         if (PRETTY_INDENT(context))
                               5822                 :             73 :             appendContextKeyword(context, "", 0, 0, 0);
                               5823                 :             73 :         get_query_def((Query *) cte->ctequery, buf, context->namespaces, NULL,
                               5824                 :                :                       true,
                               5825                 :                :                       context->prettyFlags, context->wrapColumn,
                               5826                 :                :                       context->indentLevel);
                               5827         [ +  - ]:             73 :         if (PRETTY_INDENT(context))
                               5828                 :             73 :             appendContextKeyword(context, "", 0, 0, 0);
                               5829                 :             73 :         appendStringInfoChar(buf, ')');
                               5830                 :                : 
 1730 peter@eisentraut.org     5831         [ +  + ]:             73 :         if (cte->search_clause)
                               5832                 :                :         {
                               5833                 :              3 :             bool        first = true;
                               5834                 :                :             ListCell   *lc;
                               5835                 :                : 
                               5836                 :              3 :             appendStringInfo(buf, " SEARCH %s FIRST BY ",
                               5837         [ -  + ]:              3 :                              cte->search_clause->search_breadth_first ? "BREADTH" : "DEPTH");
                               5838                 :                : 
                               5839   [ +  -  +  +  :              9 :             foreach(lc, cte->search_clause->search_col_list)
                                              +  + ]
                               5840                 :                :             {
                               5841         [ +  + ]:              6 :                 if (first)
                               5842                 :              3 :                     first = false;
                               5843                 :                :                 else
                               5844                 :              3 :                     appendStringInfoString(buf, ", ");
                               5845                 :              6 :                 appendStringInfoString(buf,
                               5846                 :              6 :                                        quote_identifier(strVal(lfirst(lc))));
                               5847                 :                :             }
                               5848                 :                : 
                               5849                 :              3 :             appendStringInfo(buf, " SET %s", quote_identifier(cte->search_clause->search_seq_column));
                               5850                 :                :         }
                               5851                 :                : 
                               5852         [ +  + ]:             73 :         if (cte->cycle_clause)
                               5853                 :                :         {
                               5854                 :              6 :             bool        first = true;
                               5855                 :                :             ListCell   *lc;
                               5856                 :                : 
                               5857                 :              6 :             appendStringInfoString(buf, " CYCLE ");
                               5858                 :                : 
                               5859   [ +  -  +  +  :             18 :             foreach(lc, cte->cycle_clause->cycle_col_list)
                                              +  + ]
                               5860                 :                :             {
                               5861         [ +  + ]:             12 :                 if (first)
                               5862                 :              6 :                     first = false;
                               5863                 :                :                 else
                               5864                 :              6 :                     appendStringInfoString(buf, ", ");
                               5865                 :             12 :                 appendStringInfoString(buf,
                               5866                 :             12 :                                        quote_identifier(strVal(lfirst(lc))));
                               5867                 :                :             }
                               5868                 :                : 
                               5869                 :              6 :             appendStringInfo(buf, " SET %s", quote_identifier(cte->cycle_clause->cycle_mark_column));
                               5870                 :                : 
                               5871                 :                :             {
 1704                          5872                 :              6 :                 Const      *cmv = castNode(Const, cte->cycle_clause->cycle_mark_value);
                               5873                 :              6 :                 Const      *cmd = castNode(Const, cte->cycle_clause->cycle_mark_default);
                               5874                 :                : 
                               5875   [ +  +  +  -  :              9 :                 if (!(cmv->consttype == BOOLOID && !cmv->constisnull && DatumGetBool(cmv->constvalue) == true &&
                                        +  -  -  + ]
                               5876   [ +  -  +  - ]:              3 :                       cmd->consttype == BOOLOID && !cmd->constisnull && DatumGetBool(cmd->constvalue) == false))
                               5877                 :                :                 {
                               5878                 :              3 :                     appendStringInfoString(buf, " TO ");
                               5879                 :              3 :                     get_rule_expr(cte->cycle_clause->cycle_mark_value, context, false);
                               5880                 :              3 :                     appendStringInfoString(buf, " DEFAULT ");
                               5881                 :              3 :                     get_rule_expr(cte->cycle_clause->cycle_mark_default, context, false);
                               5882                 :                :                 }
                               5883                 :                :             }
                               5884                 :                : 
 1730                          5885                 :              6 :             appendStringInfo(buf, " USING %s", quote_identifier(cte->cycle_clause->cycle_path_column));
                               5886                 :                :         }
                               5887                 :                : 
 6233 tgl@sss.pgh.pa.us        5888                 :             73 :         sep = ", ";
                               5889                 :                :     }
                               5890                 :                : 
                               5891         [ +  - ]:             48 :     if (PRETTY_INDENT(context))
                               5892                 :                :     {
                               5893                 :             48 :         context->indentLevel -= PRETTYINDENT_STD;
                               5894                 :             48 :         appendContextKeyword(context, "", 0, 0, 0);
                               5895                 :                :     }
                               5896                 :                :     else
 6233 tgl@sss.pgh.pa.us        5897                 :UBC           0 :         appendStringInfoChar(buf, ' ');
                               5898                 :                : }
                               5899                 :                : 
                               5900                 :                : /* ----------
                               5901                 :                :  * get_select_query_def         - Parse back a SELECT parsetree
                               5902                 :                :  * ----------
                               5903                 :                :  */
                               5904                 :                : static void
  425 tgl@sss.pgh.pa.us        5905                 :CBC        2532 : get_select_query_def(Query *query, deparse_context *context)
                               5906                 :                : {
 9154                          5907                 :           2532 :     StringInfo  buf = context->buf;
                               5908                 :                :     bool        force_colno;
                               5909                 :                :     ListCell   *l;
                               5910                 :                : 
                               5911                 :                :     /* Insert the WITH clause if given */
 6233                          5912                 :           2532 :     get_with_clause(query, context);
                               5913                 :                : 
                               5914                 :                :     /* Subroutines may need to consult the SELECT targetlist and windowClause */
  425                          5915                 :           2532 :     context->targetList = query->targetList;
 6148                          5916                 :           2532 :     context->windowClause = query->windowClause;
                               5917                 :                : 
                               5918                 :                :     /*
                               5919                 :                :      * If the Query node has a setOperations tree, then it's the top level of
                               5920                 :                :      * a UNION/INTERSECT/EXCEPT query; only the WITH, ORDER BY and LIMIT
                               5921                 :                :      * fields are interesting in the top query itself.
                               5922                 :                :      */
 9154                          5923         [ +  + ]:           2532 :     if (query->setOperations)
                               5924                 :                :     {
  425                          5925                 :             82 :         get_setop_query(query->setOperations, query, context);
                               5926                 :                :         /* ORDER BY clauses must be simple in this case */
 8962                          5927                 :             82 :         force_colno = true;
                               5928                 :                :     }
                               5929                 :                :     else
                               5930                 :                :     {
  425                          5931                 :           2450 :         get_basic_select_query(query, context);
 8962                          5932                 :           2450 :         force_colno = false;
                               5933                 :                :     }
                               5934                 :                : 
                               5935                 :                :     /* Add the ORDER BY clause if given */
 9154                          5936         [ +  + ]:           2532 :     if (query->sortClause != NIL)
                               5937                 :                :     {
 8121 bruce@momjian.us         5938                 :             90 :         appendContextKeyword(context, " ORDER BY ",
                               5939                 :                :                              -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
 6148 tgl@sss.pgh.pa.us        5940                 :             90 :         get_rule_orderby(query->sortClause, query->targetList,
                               5941                 :                :                          force_colno, context);
                               5942                 :                :     }
                               5943                 :                : 
                               5944                 :                :     /*
                               5945                 :                :      * Add the LIMIT/OFFSET clauses if given. If non-default options, use the
                               5946                 :                :      * standard spelling of LIMIT.
                               5947                 :                :      */
 9133                          5948         [ +  + ]:           2532 :     if (query->limitOffset != NULL)
                               5949                 :                :     {
 8126                          5950                 :             16 :         appendContextKeyword(context, " OFFSET ",
                               5951                 :                :                              -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
 8440                          5952                 :             16 :         get_rule_expr(query->limitOffset, context, false);
                               5953                 :                :     }
 9133                          5954         [ +  + ]:           2532 :     if (query->limitCount != NULL)
                               5955                 :                :     {
 2030 alvherre@alvh.no-ip.     5956         [ +  + ]:             43 :         if (query->limitOption == LIMIT_OPTION_WITH_TIES)
                               5957                 :                :         {
                               5958                 :                :             /*
                               5959                 :                :              * The limitCount arg is a c_expr, so it needs parens. Simple
                               5960                 :                :              * literals and function expressions would not need parens, but
                               5961                 :                :              * unfortunately it's hard to tell if the expression will be
                               5962                 :                :              * printed as a simple literal like 123 or as a typecast
                               5963                 :                :              * expression, like '-123'::int4. The grammar accepts the former
                               5964                 :                :              * without quoting, but not the latter.
                               5965                 :                :              */
                               5966                 :             24 :             appendContextKeyword(context, " FETCH FIRST ",
                               5967                 :                :                                  -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
  162 heikki.linnakangas@i     5968                 :             24 :             appendStringInfoChar(buf, '(');
 8440 tgl@sss.pgh.pa.us        5969                 :             24 :             get_rule_expr(query->limitCount, context, false);
  162 heikki.linnakangas@i     5970                 :             24 :             appendStringInfoChar(buf, ')');
 1839 drowley@postgresql.o     5971                 :             24 :             appendStringInfoString(buf, " ROWS WITH TIES");
                               5972                 :                :         }
                               5973                 :                :         else
                               5974                 :                :         {
 2030 alvherre@alvh.no-ip.     5975                 :             19 :             appendContextKeyword(context, " LIMIT ",
                               5976                 :                :                                  -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
                               5977         [ +  + ]:             19 :             if (IsA(query->limitCount, Const) &&
                               5978         [ +  - ]:              8 :                 ((Const *) query->limitCount)->constisnull)
                               5979                 :              8 :                 appendStringInfoString(buf, "ALL");
                               5980                 :                :             else
                               5981                 :             11 :                 get_rule_expr(query->limitCount, context, false);
                               5982                 :                :         }
                               5983                 :                :     }
                               5984                 :                : 
                               5985                 :                :     /* Add FOR [KEY] UPDATE/SHARE clauses if present */
 5844 tgl@sss.pgh.pa.us        5986         [ +  + ]:           2532 :     if (query->hasForUpdate)
                               5987                 :                :     {
                               5988   [ +  -  +  +  :              6 :         foreach(l, query->rowMarks)
                                              +  + ]
                               5989                 :                :         {
                               5990                 :              3 :             RowMarkClause *rc = (RowMarkClause *) lfirst(l);
                               5991                 :                : 
                               5992                 :                :             /* don't print implicit clauses */
                               5993         [ -  + ]:              3 :             if (rc->pushedDown)
 5844 tgl@sss.pgh.pa.us        5994                 :UBC           0 :                 continue;
                               5995                 :                : 
 4661 alvherre@alvh.no-ip.     5996   [ -  -  -  -  :CBC           3 :             switch (rc->strength)
                                              +  - ]
                               5997                 :                :             {
 3880 tgl@sss.pgh.pa.us        5998                 :UBC           0 :                 case LCS_NONE:
                               5999                 :                :                     /* we intentionally throw an error for LCS_NONE */
                               6000         [ #  # ]:              0 :                     elog(ERROR, "unrecognized LockClauseStrength %d",
                               6001                 :                :                          (int) rc->strength);
                               6002                 :                :                     break;
 4661 alvherre@alvh.no-ip.     6003                 :              0 :                 case LCS_FORKEYSHARE:
                               6004                 :              0 :                     appendContextKeyword(context, " FOR KEY SHARE",
                               6005                 :                :                                          -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
                               6006                 :              0 :                     break;
                               6007                 :              0 :                 case LCS_FORSHARE:
                               6008                 :              0 :                     appendContextKeyword(context, " FOR SHARE",
                               6009                 :                :                                          -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
                               6010                 :              0 :                     break;
                               6011                 :              0 :                 case LCS_FORNOKEYUPDATE:
                               6012                 :              0 :                     appendContextKeyword(context, " FOR NO KEY UPDATE",
                               6013                 :                :                                          -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
                               6014                 :              0 :                     break;
 4661 alvherre@alvh.no-ip.     6015                 :CBC           3 :                 case LCS_FORUPDATE:
                               6016                 :              3 :                     appendContextKeyword(context, " FOR UPDATE",
                               6017                 :                :                                          -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
                               6018                 :              3 :                     break;
                               6019                 :                :             }
                               6020                 :                : 
 5844 tgl@sss.pgh.pa.us        6021                 :              3 :             appendStringInfo(buf, " OF %s",
 4785                          6022                 :              3 :                              quote_identifier(get_rtable_name(rc->rti,
                               6023                 :                :                                                               context)));
 4039 alvherre@alvh.no-ip.     6024         [ -  + ]:              3 :             if (rc->waitPolicy == LockWaitError)
 4380 rhaas@postgresql.org     6025                 :UBC           0 :                 appendStringInfoString(buf, " NOWAIT");
 4039 alvherre@alvh.no-ip.     6026         [ -  + ]:CBC           3 :             else if (rc->waitPolicy == LockWaitSkip)
 4039 alvherre@alvh.no-ip.     6027                 :UBC           0 :                 appendStringInfoString(buf, " SKIP LOCKED");
                               6028                 :                :         }
                               6029                 :                :     }
 9154 tgl@sss.pgh.pa.us        6030                 :CBC        2532 : }
                               6031                 :                : 
                               6032                 :                : /*
                               6033                 :                :  * Detect whether query looks like SELECT ... FROM VALUES(),
                               6034                 :                :  * with no need to rename the output columns of the VALUES RTE.
                               6035                 :                :  * If so, return the VALUES RTE.  Otherwise return NULL.
                               6036                 :                :  */
                               6037                 :                : static RangeTblEntry *
 2173                          6038                 :           2450 : get_simple_values_rte(Query *query, TupleDesc resultDesc)
                               6039                 :                : {
 4818                          6040                 :           2450 :     RangeTblEntry *result = NULL;
                               6041                 :                :     ListCell   *lc;
                               6042                 :                : 
                               6043                 :                :     /*
                               6044                 :                :      * We want to detect a match even if the Query also contains OLD or NEW
                               6045                 :                :      * rule RTEs.  So the idea is to scan the rtable and see if there is only
                               6046                 :                :      * one inFromCl RTE that is a VALUES RTE.
                               6047                 :                :      */
                               6048   [ +  +  +  +  :           2636 :     foreach(lc, query->rtable)
                                              +  + ]
                               6049                 :                :     {
                               6050                 :           2227 :         RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
                               6051                 :                : 
                               6052   [ +  +  +  - ]:           2227 :         if (rte->rtekind == RTE_VALUES && rte->inFromCl)
                               6053                 :                :         {
                               6054         [ -  + ]:            114 :             if (result)
                               6055                 :           2041 :                 return NULL;    /* multiple VALUES (probably not possible) */
                               6056                 :            114 :             result = rte;
                               6057                 :                :         }
                               6058   [ +  +  +  + ]:           2113 :         else if (rte->rtekind == RTE_RELATION && !rte->inFromCl)
                               6059                 :             72 :             continue;           /* ignore rule entries */
                               6060                 :                :         else
                               6061                 :           2041 :             return NULL;        /* something else -> not simple VALUES */
                               6062                 :                :     }
                               6063                 :                : 
                               6064                 :                :     /*
                               6065                 :                :      * We don't need to check the targetlist in any great detail, because
                               6066                 :                :      * parser/analyze.c will never generate a "bare" VALUES RTE --- they only
                               6067                 :                :      * appear inside auto-generated sub-queries with very restricted
                               6068                 :                :      * structure.  However, DefineView might have modified the tlist by
                               6069                 :                :      * injecting new column aliases, or we might have some other column
                               6070                 :                :      * aliases forced by a resultDesc.  We can only simplify if the RTE's
                               6071                 :                :      * column names match the names that get_target_list() would select.
                               6072                 :                :      */
 3898                          6073         [ +  + ]:            409 :     if (result)
                               6074                 :                :     {
                               6075                 :                :         ListCell   *lcn;
                               6076                 :                :         int         colno;
                               6077                 :                : 
                               6078         [ -  + ]:            114 :         if (list_length(query->targetList) != list_length(result->eref->colnames))
 3898 tgl@sss.pgh.pa.us        6079                 :UBC           0 :             return NULL;        /* this probably cannot happen */
 2173 tgl@sss.pgh.pa.us        6080                 :CBC         114 :         colno = 0;
 3898                          6081   [ +  -  +  +  :            421 :         forboth(lc, query->targetList, lcn, result->eref->colnames)
                                     +  -  +  +  +  
                                        +  +  -  +  
                                                 + ]
                               6082                 :                :         {
                               6083                 :            313 :             TargetEntry *tle = (TargetEntry *) lfirst(lc);
                               6084                 :            313 :             char       *cname = strVal(lfirst(lcn));
                               6085                 :                :             char       *colname;
                               6086                 :                : 
                               6087         [ -  + ]:            313 :             if (tle->resjunk)
                               6088                 :              6 :                 return NULL;    /* this probably cannot happen */
                               6089                 :                : 
                               6090                 :                :             /* compute name that get_target_list would use for column */
 2173                          6091                 :            313 :             colno++;
                               6092   [ +  +  +  - ]:            313 :             if (resultDesc && colno <= resultDesc->natts)
                               6093                 :             15 :                 colname = NameStr(TupleDescAttr(resultDesc, colno - 1)->attname);
                               6094                 :                :             else
                               6095                 :            298 :                 colname = tle->resname;
                               6096                 :                : 
                               6097                 :                :             /* does it match the VALUES RTE? */
                               6098   [ +  -  +  + ]:            313 :             if (colname == NULL || strcmp(colname, cname) != 0)
 3898                          6099                 :              6 :                 return NULL;    /* column name has been changed */
                               6100                 :                :         }
                               6101                 :                :     }
                               6102                 :                : 
 4818                          6103                 :            403 :     return result;
                               6104                 :                : }
                               6105                 :                : 
                               6106                 :                : static void
  425                          6107                 :           2450 : get_basic_select_query(Query *query, deparse_context *context)
                               6108                 :                : {
 9522                          6109                 :           2450 :     StringInfo  buf = context->buf;
                               6110                 :                :     RangeTblEntry *values_rte;
                               6111                 :                :     char       *sep;
                               6112                 :                :     ListCell   *l;
                               6113                 :                : 
 8126                          6114         [ +  + ]:           2450 :     if (PRETTY_INDENT(context))
                               6115                 :                :     {
 8121 bruce@momjian.us         6116                 :           2427 :         context->indentLevel += PRETTYINDENT_STD;
                               6117                 :           2427 :         appendStringInfoChar(buf, ' ');
                               6118                 :                :     }
                               6119                 :                : 
                               6120                 :                :     /*
                               6121                 :                :      * If the query looks like SELECT * FROM (VALUES ...), then print just the
                               6122                 :                :      * VALUES part.  This reverses what transformValuesClause() did at parse
                               6123                 :                :      * time.
                               6124                 :                :      */
  425 tgl@sss.pgh.pa.us        6125                 :           2450 :     values_rte = get_simple_values_rte(query, context->resultDesc);
 4818                          6126         [ +  + ]:           2450 :     if (values_rte)
                               6127                 :                :     {
                               6128                 :            108 :         get_values_def(values_rte->values_lists, context);
                               6129                 :            108 :         return;
                               6130                 :                :     }
                               6131                 :                : 
                               6132                 :                :     /*
                               6133                 :                :      * Build up the query string - first we say SELECT
                               6134                 :                :      */
 1665 peter@eisentraut.org     6135         [ +  + ]:           2342 :     if (query->isReturn)
                               6136                 :             26 :         appendStringInfoString(buf, "RETURN");
                               6137                 :                :     else
                               6138                 :           2316 :         appendStringInfoString(buf, "SELECT");
                               6139                 :                : 
                               6140                 :                :     /* Add the DISTINCT clause if given */
 9154 tgl@sss.pgh.pa.us        6141         [ -  + ]:           2342 :     if (query->distinctClause != NIL)
                               6142                 :                :     {
 6296 tgl@sss.pgh.pa.us        6143         [ #  # ]:UBC           0 :         if (query->hasDistinctOn)
                               6144                 :                :         {
 4380 rhaas@postgresql.org     6145                 :              0 :             appendStringInfoString(buf, " DISTINCT ON (");
 9154 tgl@sss.pgh.pa.us        6146                 :              0 :             sep = "";
                               6147   [ #  #  #  #  :              0 :             foreach(l, query->distinctClause)
                                              #  # ]
                               6148                 :                :             {
 6296                          6149                 :              0 :                 SortGroupClause *srt = (SortGroupClause *) lfirst(l);
                               6150                 :                : 
 7486 neilc@samurai.com        6151                 :              0 :                 appendStringInfoString(buf, sep);
 3818 andres@anarazel.de       6152                 :              0 :                 get_rule_sortgroupclause(srt->tleSortGroupRef, query->targetList,
                               6153                 :                :                                          false, context);
 9154 tgl@sss.pgh.pa.us        6154                 :              0 :                 sep = ", ";
                               6155                 :                :             }
 4380 rhaas@postgresql.org     6156                 :              0 :             appendStringInfoChar(buf, ')');
                               6157                 :                :         }
                               6158                 :                :         else
                               6159                 :              0 :             appendStringInfoString(buf, " DISTINCT");
                               6160                 :                :     }
                               6161                 :                : 
                               6162                 :                :     /* Then we tell what to select (the targetlist) */
  425 tgl@sss.pgh.pa.us        6163                 :CBC        2342 :     get_target_list(query->targetList, context);
                               6164                 :                : 
                               6165                 :                :     /* Add the FROM clause if needed */
 7017                          6166                 :           2342 :     get_from_clause(query, " FROM ", context);
                               6167                 :                : 
                               6168                 :                :     /* Add the WHERE clause if given */
                               6169         [ +  + ]:           2342 :     if (query->jointree->quals != NULL)
                               6170                 :                :     {
                               6171                 :            742 :         appendContextKeyword(context, " WHERE ",
                               6172                 :                :                              -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
                               6173                 :            742 :         get_rule_expr(query->jointree->quals, context, false);
                               6174                 :                :     }
                               6175                 :                : 
                               6176                 :                :     /* Add the GROUP BY clause if given */
 3818 andres@anarazel.de       6177   [ +  +  -  + ]:           2342 :     if (query->groupClause != NULL || query->groupingSets != NULL)
                               6178                 :                :     {
                               6179                 :                :         bool        save_ingroupby;
                               6180                 :                : 
 7017 tgl@sss.pgh.pa.us        6181                 :            110 :         appendContextKeyword(context, " GROUP BY ",
                               6182                 :                :                              -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
 1685 tomas.vondra@postgre     6183         [ -  + ]:            110 :         if (query->groupDistinct)
 1685 tomas.vondra@postgre     6184                 :UBC           0 :             appendStringInfoString(buf, "DISTINCT ");
                               6185                 :                : 
  425 tgl@sss.pgh.pa.us        6186                 :CBC         110 :         save_ingroupby = context->inGroupBy;
                               6187                 :            110 :         context->inGroupBy = true;
                               6188                 :                : 
   29 tgl@sss.pgh.pa.us        6189         [ +  + ]:GNC         110 :         if (query->groupByAll)
                               6190                 :              3 :             appendStringInfoString(buf, "ALL");
                               6191         [ +  + ]:            107 :         else if (query->groupingSets == NIL)
                               6192                 :                :         {
 3818 andres@anarazel.de       6193                 :CBC         104 :             sep = "";
                               6194   [ +  -  +  +  :            237 :             foreach(l, query->groupClause)
                                              +  + ]
                               6195                 :                :             {
                               6196                 :            133 :                 SortGroupClause *grp = (SortGroupClause *) lfirst(l);
                               6197                 :                : 
                               6198                 :            133 :                 appendStringInfoString(buf, sep);
                               6199                 :            133 :                 get_rule_sortgroupclause(grp->tleSortGroupRef, query->targetList,
                               6200                 :                :                                          false, context);
                               6201                 :            133 :                 sep = ", ";
                               6202                 :                :             }
                               6203                 :                :         }
                               6204                 :                :         else
                               6205                 :                :         {
                               6206                 :              3 :             sep = "";
                               6207   [ +  -  +  +  :              6 :             foreach(l, query->groupingSets)
                                              +  + ]
                               6208                 :                :             {
                               6209                 :              3 :                 GroupingSet *grp = lfirst(l);
                               6210                 :                : 
                               6211                 :              3 :                 appendStringInfoString(buf, sep);
                               6212                 :              3 :                 get_rule_groupingset(grp, query->targetList, true, context);
                               6213                 :              3 :                 sep = ", ";
                               6214                 :                :             }
                               6215                 :                :         }
                               6216                 :                : 
  425 tgl@sss.pgh.pa.us        6217                 :            110 :         context->inGroupBy = save_ingroupby;
                               6218                 :                :     }
                               6219                 :                : 
                               6220                 :                :     /* Add the HAVING clause if given */
 7017                          6221         [ +  + ]:           2342 :     if (query->havingQual != NULL)
                               6222                 :                :     {
                               6223                 :              5 :         appendContextKeyword(context, " HAVING ",
                               6224                 :                :                              -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
                               6225                 :              5 :         get_rule_expr(query->havingQual, context, false);
                               6226                 :                :     }
                               6227                 :                : 
                               6228                 :                :     /* Add the WINDOW clause if needed */
 6148                          6229         [ +  + ]:           2342 :     if (query->windowClause != NIL)
                               6230                 :             24 :         get_rule_windowclause(query, context);
                               6231                 :                : }
                               6232                 :                : 
                               6233                 :                : /* ----------
                               6234                 :                :  * get_target_list          - Parse back a SELECT target list
                               6235                 :                :  *
                               6236                 :                :  * This is also used for RETURNING lists in INSERT/UPDATE/DELETE/MERGE.
                               6237                 :                :  * ----------
                               6238                 :                :  */
                               6239                 :                : static void
  425                          6240                 :           2415 : get_target_list(List *targetList, deparse_context *context)
                               6241                 :                : {
 7017                          6242                 :           2415 :     StringInfo  buf = context->buf;
                               6243                 :                :     StringInfoData targetbuf;
 4691                          6244                 :           2415 :     bool        last_was_multiline = false;
                               6245                 :                :     char       *sep;
                               6246                 :                :     int         colno;
                               6247                 :                :     ListCell   *l;
                               6248                 :                : 
                               6249                 :                :     /* we use targetbuf to hold each TLE's text temporarily */
                               6250                 :           2415 :     initStringInfo(&targetbuf);
                               6251                 :                : 
 9927 bruce@momjian.us         6252                 :           2415 :     sep = " ";
 8482 tgl@sss.pgh.pa.us        6253                 :           2415 :     colno = 0;
 7017                          6254   [ +  -  +  +  :          12565 :     foreach(l, targetList)
                                              +  + ]
                               6255                 :                :     {
 9177                          6256                 :          10150 :         TargetEntry *tle = (TargetEntry *) lfirst(l);
                               6257                 :                :         char       *colname;
                               6258                 :                :         char       *attname;
                               6259                 :                : 
 7510                          6260         [ +  + ]:          10150 :         if (tle->resjunk)
 9160                          6261                 :             17 :             continue;           /* ignore junk entries */
                               6262                 :                : 
 7486 neilc@samurai.com        6263                 :          10133 :         appendStringInfoString(buf, sep);
 9919 bruce@momjian.us         6264                 :          10133 :         sep = ", ";
 8482 tgl@sss.pgh.pa.us        6265                 :          10133 :         colno++;
                               6266                 :                : 
                               6267                 :                :         /*
                               6268                 :                :          * Put the new field text into targetbuf so we can decide after we've
                               6269                 :                :          * got it whether or not it needs to go on a new line.
                               6270                 :                :          */
 4691                          6271                 :          10133 :         resetStringInfo(&targetbuf);
 5000 andrew@dunslane.net      6272                 :          10133 :         context->buf = &targetbuf;
                               6273                 :                : 
                               6274                 :                :         /*
                               6275                 :                :          * We special-case Var nodes rather than using get_rule_expr. This is
                               6276                 :                :          * needed because get_rule_expr will display a whole-row Var as
                               6277                 :                :          * "foo.*", which is the preferred notation in most contexts, but at
                               6278                 :                :          * the top level of a SELECT list it's not right (the parser will
                               6279                 :                :          * expand that notation into multiple columns, yielding behavior
                               6280                 :                :          * different from a whole-row Var).  We need to call get_variable
                               6281                 :                :          * directly so that we can tell it to do the right thing, and so that
                               6282                 :                :          * we can get the attribute name which is the default AS label.
                               6283                 :                :          */
 3818 andres@anarazel.de       6284   [ +  -  +  + ]:          10133 :         if (tle->expr && (IsA(tle->expr, Var)))
                               6285                 :                :         {
 4932 tgl@sss.pgh.pa.us        6286                 :           7816 :             attname = get_variable((Var *) tle->expr, 0, true, context);
                               6287                 :                :         }
                               6288                 :                :         else
                               6289                 :                :         {
 7215                          6290                 :           2317 :             get_rule_expr((Node *) tle->expr, context, true);
                               6291                 :                : 
                               6292                 :                :             /*
                               6293                 :                :              * When colNamesVisible is true, we should always show the
                               6294                 :                :              * assigned column name explicitly.  Otherwise, show it only if
                               6295                 :                :              * it's not FigureColname's fallback.
                               6296                 :                :              */
  425                          6297         [ +  + ]:           2317 :             attname = context->colNamesVisible ? NULL : "?column?";
                               6298                 :                :         }
                               6299                 :                : 
                               6300                 :                :         /*
                               6301                 :                :          * Figure out what the result column should be called.  In the context
                               6302                 :                :          * of a view, use the view's tuple descriptor (so as to pick up the
                               6303                 :                :          * effects of any column RENAME that's been done on the view).
                               6304                 :                :          * Otherwise, just use what we can find in the TLE.
                               6305                 :                :          */
                               6306   [ +  +  +  - ]:          10133 :         if (context->resultDesc && colno <= context->resultDesc->natts)
                               6307                 :           9227 :             colname = NameStr(TupleDescAttr(context->resultDesc,
                               6308                 :                :                                             colno - 1)->attname);
                               6309                 :                :         else
 7510                          6310                 :            906 :             colname = tle->resname;
                               6311                 :                : 
                               6312                 :                :         /* Show AS unless the column's name is correct as-is */
 8114                          6313         [ +  + ]:          10133 :         if (colname)            /* resname could be NULL */
                               6314                 :                :         {
 7215                          6315   [ +  +  +  + ]:          10107 :             if (attname == NULL || strcmp(attname, colname) != 0)
 5000 andrew@dunslane.net      6316                 :           3290 :                 appendStringInfo(&targetbuf, " AS %s", quote_identifier(colname));
                               6317                 :                :         }
                               6318                 :                : 
                               6319                 :                :         /* Restore context's output buffer */
                               6320                 :          10133 :         context->buf = buf;
                               6321                 :                : 
                               6322                 :                :         /* Consider line-wrapping if enabled */
 4691 tgl@sss.pgh.pa.us        6323   [ +  +  +  - ]:          10133 :         if (PRETTY_INDENT(context) && context->wrapColumn >= 0)
                               6324                 :                :         {
                               6325                 :                :             int         leading_nl_pos;
                               6326                 :                : 
                               6327                 :                :             /* Does the new field start with a new line? */
 4369                          6328   [ +  -  +  + ]:          10110 :             if (targetbuf.len > 0 && targetbuf.data[0] == '\n')
                               6329                 :            241 :                 leading_nl_pos = 0;
                               6330                 :                :             else
                               6331                 :           9869 :                 leading_nl_pos = -1;
                               6332                 :                : 
                               6333                 :                :             /* If so, we shouldn't add anything */
                               6334         [ +  + ]:          10110 :             if (leading_nl_pos >= 0)
                               6335                 :                :             {
                               6336                 :                :                 /* instead, remove any trailing spaces currently in buf */
                               6337                 :            241 :                 removeStringInfoSpaces(buf);
                               6338                 :                :             }
                               6339                 :                :             else
                               6340                 :                :             {
                               6341                 :                :                 char       *trailing_nl;
                               6342                 :                : 
                               6343                 :                :                 /* Locate the start of the current line in the output buffer */
                               6344                 :           9869 :                 trailing_nl = strrchr(buf->data, '\n');
                               6345         [ +  + ]:           9869 :                 if (trailing_nl == NULL)
                               6346                 :           2965 :                     trailing_nl = buf->data;
                               6347                 :                :                 else
                               6348                 :           6904 :                     trailing_nl++;
                               6349                 :                : 
                               6350                 :                :                 /*
                               6351                 :                :                  * Add a newline, plus some indentation, if the new field is
                               6352                 :                :                  * not the first and either the new field would cause an
                               6353                 :                :                  * overflow or the last field used more than one line.
                               6354                 :                :                  */
                               6355         [ +  + ]:           9869 :                 if (colno > 1 &&
                               6356   [ -  +  -  - ]:           7485 :                     ((strlen(trailing_nl) + targetbuf.len > context->wrapColumn) ||
                               6357                 :                :                      last_was_multiline))
                               6358                 :           7485 :                     appendContextKeyword(context, "", -PRETTYINDENT_STD,
                               6359                 :                :                                          PRETTYINDENT_STD, PRETTYINDENT_VAR);
                               6360                 :                :             }
                               6361                 :                : 
                               6362                 :                :             /* Remember this field's multiline status for next iteration */
 4691                          6363                 :          10110 :             last_was_multiline =
                               6364                 :          10110 :                 (strchr(targetbuf.data + leading_nl_pos + 1, '\n') != NULL);
                               6365                 :                :         }
                               6366                 :                : 
                               6367                 :                :         /* Add the new field */
 2289 drowley@postgresql.o     6368                 :          10133 :         appendBinaryStringInfo(buf, targetbuf.data, targetbuf.len);
                               6369                 :                :     }
                               6370                 :                : 
                               6371                 :                :     /* clean up */
 4691 tgl@sss.pgh.pa.us        6372                 :           2415 :     pfree(targetbuf.data);
 9154                          6373                 :           2415 : }
                               6374                 :                : 
                               6375                 :                : static void
  285 dean.a.rasheed@gmail     6376                 :             73 : get_returning_clause(Query *query, deparse_context *context)
                               6377                 :                : {
                               6378                 :             73 :     StringInfo  buf = context->buf;
                               6379                 :                : 
                               6380         [ +  - ]:             73 :     if (query->returningList)
                               6381                 :                :     {
                               6382                 :             73 :         bool        have_with = false;
                               6383                 :                : 
                               6384                 :             73 :         appendContextKeyword(context, " RETURNING",
                               6385                 :                :                              -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
                               6386                 :                : 
                               6387                 :                :         /* Add WITH (OLD/NEW) options, if they're not the defaults */
                               6388   [ +  +  +  + ]:             73 :         if (query->returningOldAlias && strcmp(query->returningOldAlias, "old") != 0)
                               6389                 :                :         {
                               6390                 :              9 :             appendStringInfo(buf, " WITH (OLD AS %s",
                               6391                 :              9 :                              quote_identifier(query->returningOldAlias));
                               6392                 :              9 :             have_with = true;
                               6393                 :                :         }
                               6394   [ +  +  +  + ]:             73 :         if (query->returningNewAlias && strcmp(query->returningNewAlias, "new") != 0)
                               6395                 :                :         {
                               6396         [ +  + ]:              9 :             if (have_with)
                               6397                 :              6 :                 appendStringInfo(buf, ", NEW AS %s",
                               6398                 :              6 :                                  quote_identifier(query->returningNewAlias));
                               6399                 :                :             else
                               6400                 :                :             {
                               6401                 :              3 :                 appendStringInfo(buf, " WITH (NEW AS %s",
                               6402                 :              3 :                                  quote_identifier(query->returningNewAlias));
                               6403                 :              3 :                 have_with = true;
                               6404                 :                :             }
                               6405                 :                :         }
                               6406         [ +  + ]:             73 :         if (have_with)
                               6407                 :             12 :             appendStringInfoChar(buf, ')');
                               6408                 :                : 
                               6409                 :                :         /* Add the returning expressions themselves */
                               6410                 :             73 :         get_target_list(query->returningList, context);
                               6411                 :                :     }
                               6412                 :             73 : }
                               6413                 :                : 
                               6414                 :                : static void
  425 tgl@sss.pgh.pa.us        6415                 :            378 : get_setop_query(Node *setOp, Query *query, deparse_context *context)
                               6416                 :                : {
 9154                          6417                 :            378 :     StringInfo  buf = context->buf;
                               6418                 :                :     bool        need_paren;
                               6419                 :                : 
                               6420                 :                :     /* Guard against excessively long or deeply-nested queries */
 4199                          6421         [ -  + ]:            378 :     CHECK_FOR_INTERRUPTS();
                               6422                 :            378 :     check_stack_depth();
                               6423                 :                : 
 9154                          6424         [ +  + ]:            378 :     if (IsA(setOp, RangeTblRef))
                               6425                 :                :     {
                               6426                 :            230 :         RangeTblRef *rtr = (RangeTblRef *) setOp;
                               6427                 :            230 :         RangeTblEntry *rte = rt_fetch(rtr->rtindex, query->rtable);
 8986 bruce@momjian.us         6428                 :            230 :         Query      *subquery = rte->subquery;
                               6429                 :                : 
 9154 tgl@sss.pgh.pa.us        6430         [ -  + ]:            230 :         Assert(subquery != NULL);
                               6431                 :                : 
                               6432                 :                :         /*
                               6433                 :                :          * We need parens if WITH, ORDER BY, FOR UPDATE, or LIMIT; see gram.y.
                               6434                 :                :          * Also add parens if the leaf query contains its own set operations.
                               6435                 :                :          * (That shouldn't happen unless one of the other clauses is also
                               6436                 :                :          * present, see transformSetOperationTree; but let's be safe.)
                               6437                 :                :          */
 6233                          6438                 :            690 :         need_paren = (subquery->cteList ||
                               6439         [ +  - ]:            230 :                       subquery->sortClause ||
 7784                          6440         [ +  - ]:            230 :                       subquery->rowMarks ||
                               6441         [ +  - ]:            230 :                       subquery->limitOffset ||
  342                          6442   [ +  -  +  - ]:            690 :                       subquery->limitCount ||
                               6443         [ -  + ]:            230 :                       subquery->setOperations);
 7784                          6444         [ -  + ]:            230 :         if (need_paren)
 7784 tgl@sss.pgh.pa.us        6445                 :UBC           0 :             appendStringInfoChar(buf, '(');
  425 tgl@sss.pgh.pa.us        6446                 :CBC         230 :         get_query_def(subquery, buf, context->namespaces,
                               6447                 :            230 :                       context->resultDesc, context->colNamesVisible,
                               6448                 :                :                       context->prettyFlags, context->wrapColumn,
                               6449                 :                :                       context->indentLevel);
 7784                          6450         [ -  + ]:            230 :         if (need_paren)
 7784 tgl@sss.pgh.pa.us        6451                 :UBC           0 :             appendStringInfoChar(buf, ')');
                               6452                 :                :     }
 9154 tgl@sss.pgh.pa.us        6453         [ +  - ]:CBC         148 :     else if (IsA(setOp, SetOperationStmt))
                               6454                 :                :     {
                               6455                 :            148 :         SetOperationStmt *op = (SetOperationStmt *) setOp;
                               6456                 :                :         int         subindent;
                               6457                 :                :         bool        save_colnamesvisible;
                               6458                 :                : 
                               6459                 :                :         /*
                               6460                 :                :          * We force parens when nesting two SetOperationStmts, except when the
                               6461                 :                :          * lefthand input is another setop of the same kind.  Syntactically,
                               6462                 :                :          * we could omit parens in rather more cases, but it seems best to use
                               6463                 :                :          * parens to flag cases where the setop operator changes.  If we use
                               6464                 :                :          * parens, we also increase the indentation level for the child query.
                               6465                 :                :          *
                               6466                 :                :          * There are some cases in which parens are needed around a leaf query
                               6467                 :                :          * too, but those are more easily handled at the next level down (see
                               6468                 :                :          * code above).
                               6469                 :                :          */
 4199                          6470         [ +  + ]:            148 :         if (IsA(op->larg, SetOperationStmt))
                               6471                 :                :         {
                               6472                 :             66 :             SetOperationStmt *lop = (SetOperationStmt *) op->larg;
                               6473                 :                : 
                               6474   [ +  -  +  - ]:             66 :             if (op->op == lop->op && op->all == lop->all)
                               6475                 :             66 :                 need_paren = false;
                               6476                 :                :             else
 4199 tgl@sss.pgh.pa.us        6477                 :UBC           0 :                 need_paren = true;
                               6478                 :                :         }
                               6479                 :                :         else
 4199 tgl@sss.pgh.pa.us        6480                 :CBC          82 :             need_paren = false;
                               6481                 :                : 
 7784                          6482         [ -  + ]:            148 :         if (need_paren)
                               6483                 :                :         {
 7784 tgl@sss.pgh.pa.us        6484                 :UBC           0 :             appendStringInfoChar(buf, '(');
 4199                          6485                 :              0 :             subindent = PRETTYINDENT_STD;
                               6486                 :              0 :             appendContextKeyword(context, "", subindent, 0, 0);
                               6487                 :                :         }
                               6488                 :                :         else
 4199 tgl@sss.pgh.pa.us        6489                 :CBC         148 :             subindent = 0;
                               6490                 :                : 
  425                          6491                 :            148 :         get_setop_query(op->larg, query, context);
                               6492                 :                : 
 4199                          6493         [ -  + ]:            148 :         if (need_paren)
 4199 tgl@sss.pgh.pa.us        6494                 :UBC           0 :             appendContextKeyword(context, ") ", -subindent, 0, 0);
 4199 tgl@sss.pgh.pa.us        6495         [ +  - ]:CBC         148 :         else if (PRETTY_INDENT(context))
                               6496                 :            148 :             appendContextKeyword(context, "", -subindent, 0, 0);
                               6497                 :                :         else
 8121 bruce@momjian.us         6498                 :UBC           0 :             appendStringInfoChar(buf, ' ');
                               6499                 :                : 
 9154 tgl@sss.pgh.pa.us        6500   [ +  -  -  - ]:CBC         148 :         switch (op->op)
                               6501                 :                :         {
                               6502                 :            148 :             case SETOP_UNION:
 4199                          6503                 :            148 :                 appendStringInfoString(buf, "UNION ");
 9154                          6504                 :            148 :                 break;
 9154 tgl@sss.pgh.pa.us        6505                 :UBC           0 :             case SETOP_INTERSECT:
 4199                          6506                 :              0 :                 appendStringInfoString(buf, "INTERSECT ");
 9154                          6507                 :              0 :                 break;
                               6508                 :              0 :             case SETOP_EXCEPT:
 4199                          6509                 :              0 :                 appendStringInfoString(buf, "EXCEPT ");
 9154                          6510                 :              0 :                 break;
                               6511                 :              0 :             default:
 8129                          6512         [ #  # ]:              0 :                 elog(ERROR, "unrecognized set op: %d",
                               6513                 :                :                      (int) op->op);
                               6514                 :                :         }
 9154 tgl@sss.pgh.pa.us        6515         [ +  + ]:CBC         148 :         if (op->all)
 4380 rhaas@postgresql.org     6516                 :            142 :             appendStringInfoString(buf, "ALL ");
                               6517                 :                : 
                               6518                 :                :         /* Always parenthesize if RHS is another setop */
 4199 tgl@sss.pgh.pa.us        6519                 :            148 :         need_paren = IsA(op->rarg, SetOperationStmt);
                               6520                 :                : 
                               6521                 :                :         /*
                               6522                 :                :          * The indentation code here is deliberately a bit different from that
                               6523                 :                :          * for the lefthand input, because we want the line breaks in
                               6524                 :                :          * different places.
                               6525                 :                :          */
 7784                          6526         [ -  + ]:            148 :         if (need_paren)
                               6527                 :                :         {
 7784 tgl@sss.pgh.pa.us        6528                 :UBC           0 :             appendStringInfoChar(buf, '(');
 4199                          6529                 :              0 :             subindent = PRETTYINDENT_STD;
                               6530                 :                :         }
                               6531                 :                :         else
 4199 tgl@sss.pgh.pa.us        6532                 :CBC         148 :             subindent = 0;
                               6533                 :            148 :         appendContextKeyword(context, "", subindent, 0, 0);
                               6534                 :                : 
                               6535                 :                :         /*
                               6536                 :                :          * The output column names of the RHS sub-select don't matter.
                               6537                 :                :          */
  425                          6538                 :            148 :         save_colnamesvisible = context->colNamesVisible;
                               6539                 :            148 :         context->colNamesVisible = false;
                               6540                 :                : 
                               6541                 :            148 :         get_setop_query(op->rarg, query, context);
                               6542                 :                : 
                               6543                 :            148 :         context->colNamesVisible = save_colnamesvisible;
                               6544                 :                : 
 6233                          6545         [ +  - ]:            148 :         if (PRETTY_INDENT(context))
 4199                          6546                 :            148 :             context->indentLevel -= subindent;
                               6547         [ -  + ]:            148 :         if (need_paren)
 4199 tgl@sss.pgh.pa.us        6548                 :UBC           0 :             appendContextKeyword(context, ")", 0, 0, 0);
                               6549                 :                :     }
                               6550                 :                :     else
                               6551                 :                :     {
 8129                          6552         [ #  # ]:              0 :         elog(ERROR, "unrecognized node type: %d",
                               6553                 :                :              (int) nodeTag(setOp));
                               6554                 :                :     }
 9154 tgl@sss.pgh.pa.us        6555                 :CBC         378 : }
                               6556                 :                : 
                               6557                 :                : /*
                               6558                 :                :  * Display a sort/group clause.
                               6559                 :                :  *
                               6560                 :                :  * Also returns the expression tree, so caller need not find it again.
                               6561                 :                :  */
                               6562                 :                : static Node *
 3818 andres@anarazel.de       6563                 :            333 : get_rule_sortgroupclause(Index ref, List *tlist, bool force_colno,
                               6564                 :                :                          deparse_context *context)
                               6565                 :                : {
 8962 tgl@sss.pgh.pa.us        6566                 :            333 :     StringInfo  buf = context->buf;
                               6567                 :                :     TargetEntry *tle;
                               6568                 :                :     Node       *expr;
                               6569                 :                : 
 3818 andres@anarazel.de       6570                 :            333 :     tle = get_sortgroupref_tle(ref, tlist);
 8356 tgl@sss.pgh.pa.us        6571                 :            333 :     expr = (Node *) tle->expr;
                               6572                 :                : 
                               6573                 :                :     /*
                               6574                 :                :      * Use column-number form if requested by caller.  Otherwise, if
                               6575                 :                :      * expression is a constant, force it to be dumped with an explicit cast
                               6576                 :                :      * as decoration --- this is because a simple integer constant is
                               6577                 :                :      * ambiguous (and will be misinterpreted by findTargetlistEntrySQL92()) if
                               6578                 :                :      * we dump it without any decoration.  Similarly, if it's just a Var,
                               6579                 :                :      * there is risk of misinterpretation if the column name is reassigned in
                               6580                 :                :      * the SELECT list, so we may need to force table qualification.  And, if
                               6581                 :                :      * it's anything more complex than a simple Var, then force extra parens
                               6582                 :                :      * around it, to ensure it can't be misinterpreted as a cube() or rollup()
                               6583                 :                :      * construct.
                               6584                 :                :      */
 6505                          6585         [ +  + ]:            333 :     if (force_colno)
                               6586                 :                :     {
 7510                          6587         [ -  + ]:              6 :         Assert(!tle->resjunk);
                               6588                 :              6 :         appendStringInfo(buf, "%d", tle->resno);
                               6589                 :                :     }
  425                          6590         [ +  - ]:            327 :     else if (!expr)
                               6591                 :                :          /* do nothing, probably can't happen */ ;
                               6592         [ -  + ]:            327 :     else if (IsA(expr, Const))
 6505 tgl@sss.pgh.pa.us        6593                 :UBC           0 :         get_const_expr((Const *) expr, context, 1);
  425 tgl@sss.pgh.pa.us        6594         [ +  + ]:CBC         327 :     else if (IsA(expr, Var))
                               6595                 :                :     {
                               6596                 :                :         /* Tell get_variable to check for name conflict */
                               6597                 :            313 :         bool        save_varinorderby = context->varInOrderBy;
                               6598                 :                : 
                               6599                 :            313 :         context->varInOrderBy = true;
                               6600                 :            313 :         (void) get_variable((Var *) expr, 0, false, context);
                               6601                 :            313 :         context->varInOrderBy = save_varinorderby;
                               6602                 :                :     }
                               6603                 :                :     else
                               6604                 :                :     {
                               6605                 :                :         /*
                               6606                 :                :          * We must force parens for function-like expressions even if
                               6607                 :                :          * PRETTY_PAREN is off, since those are the ones in danger of
                               6608                 :                :          * misparsing. For other expressions we need to force them only if
                               6609                 :                :          * PRETTY_PAREN is on, since otherwise the expression will output them
                               6610                 :                :          * itself. (We can't skip the parens.)
                               6611                 :                :          */
 3811 bruce@momjian.us         6612                 :             28 :         bool        need_paren = (PRETTY_PAREN(context)
                               6613         [ +  + ]:             14 :                                   || IsA(expr, FuncExpr)
 1991 tgl@sss.pgh.pa.us        6614         [ +  - ]:             12 :                                   || IsA(expr, Aggref)
  944 alvherre@alvh.no-ip.     6615         [ +  - ]:             12 :                                   || IsA(expr, WindowFunc)
                               6616   [ +  -  -  + ]:             28 :                                   || IsA(expr, JsonConstructorExpr));
                               6617                 :                : 
 3818 andres@anarazel.de       6618         [ +  + ]:             14 :         if (need_paren)
 2996 peter_e@gmx.net          6619                 :              2 :             appendStringInfoChar(context->buf, '(');
 8440 tgl@sss.pgh.pa.us        6620                 :             14 :         get_rule_expr(expr, context, true);
 3818 andres@anarazel.de       6621         [ +  + ]:             14 :         if (need_paren)
 2996 peter_e@gmx.net          6622                 :              2 :             appendStringInfoChar(context->buf, ')');
                               6623                 :                :     }
                               6624                 :                : 
 8579 tgl@sss.pgh.pa.us        6625                 :            333 :     return expr;
                               6626                 :                : }
                               6627                 :                : 
                               6628                 :                : /*
                               6629                 :                :  * Display a GroupingSet
                               6630                 :                :  */
                               6631                 :                : static void
 3818 andres@anarazel.de       6632                 :              9 : get_rule_groupingset(GroupingSet *gset, List *targetlist,
                               6633                 :                :                      bool omit_parens, deparse_context *context)
                               6634                 :                : {
                               6635                 :                :     ListCell   *l;
                               6636                 :              9 :     StringInfo  buf = context->buf;
                               6637                 :              9 :     bool        omit_child_parens = true;
                               6638                 :              9 :     char       *sep = "";
                               6639                 :                : 
                               6640   [ -  +  +  -  :              9 :     switch (gset->kind)
                                              -  - ]
                               6641                 :                :     {
 3818 andres@anarazel.de       6642                 :UBC           0 :         case GROUPING_SET_EMPTY:
                               6643                 :              0 :             appendStringInfoString(buf, "()");
                               6644                 :              0 :             return;
                               6645                 :                : 
 3818 andres@anarazel.de       6646                 :CBC           6 :         case GROUPING_SET_SIMPLE:
                               6647                 :                :             {
                               6648   [ +  -  +  - ]:              6 :                 if (!omit_parens || list_length(gset->content) != 1)
 2996 peter_e@gmx.net          6649                 :              6 :                     appendStringInfoChar(buf, '(');
                               6650                 :                : 
 3818 andres@anarazel.de       6651   [ +  -  +  +  :             21 :                 foreach(l, gset->content)
                                              +  + ]
                               6652                 :                :                 {
 3811 bruce@momjian.us         6653                 :             15 :                     Index       ref = lfirst_int(l);
                               6654                 :                : 
 3818 andres@anarazel.de       6655                 :             15 :                     appendStringInfoString(buf, sep);
                               6656                 :             15 :                     get_rule_sortgroupclause(ref, targetlist,
                               6657                 :                :                                              false, context);
                               6658                 :             15 :                     sep = ", ";
                               6659                 :                :                 }
                               6660                 :                : 
                               6661   [ +  -  +  - ]:              6 :                 if (!omit_parens || list_length(gset->content) != 1)
 2996 peter_e@gmx.net          6662                 :              6 :                     appendStringInfoChar(buf, ')');
                               6663                 :                :             }
 3818 andres@anarazel.de       6664                 :              6 :             return;
                               6665                 :                : 
                               6666                 :              3 :         case GROUPING_SET_ROLLUP:
                               6667                 :              3 :             appendStringInfoString(buf, "ROLLUP(");
                               6668                 :              3 :             break;
 3818 andres@anarazel.de       6669                 :UBC           0 :         case GROUPING_SET_CUBE:
                               6670                 :              0 :             appendStringInfoString(buf, "CUBE(");
                               6671                 :              0 :             break;
                               6672                 :              0 :         case GROUPING_SET_SETS:
                               6673                 :              0 :             appendStringInfoString(buf, "GROUPING SETS (");
                               6674                 :              0 :             omit_child_parens = false;
                               6675                 :              0 :             break;
                               6676                 :                :     }
                               6677                 :                : 
 3818 andres@anarazel.de       6678   [ +  -  +  +  :CBC           9 :     foreach(l, gset->content)
                                              +  + ]
                               6679                 :                :     {
                               6680                 :              6 :         appendStringInfoString(buf, sep);
                               6681                 :              6 :         get_rule_groupingset(lfirst(l), targetlist, omit_child_parens, context);
                               6682                 :              6 :         sep = ", ";
                               6683                 :                :     }
                               6684                 :                : 
 2996 peter_e@gmx.net          6685                 :              3 :     appendStringInfoChar(buf, ')');
                               6686                 :                : }
                               6687                 :                : 
                               6688                 :                : /*
                               6689                 :                :  * Display an ORDER BY list.
                               6690                 :                :  */
                               6691                 :                : static void
 6148 tgl@sss.pgh.pa.us        6692                 :            169 : get_rule_orderby(List *orderList, List *targetList,
                               6693                 :                :                  bool force_colno, deparse_context *context)
                               6694                 :                : {
                               6695                 :            169 :     StringInfo  buf = context->buf;
                               6696                 :                :     const char *sep;
                               6697                 :                :     ListCell   *l;
                               6698                 :                : 
                               6699                 :            169 :     sep = "";
                               6700   [ +  -  +  +  :            354 :     foreach(l, orderList)
                                              +  + ]
                               6701                 :                :     {
                               6702                 :            185 :         SortGroupClause *srt = (SortGroupClause *) lfirst(l);
                               6703                 :                :         Node       *sortexpr;
                               6704                 :                :         Oid         sortcoltype;
                               6705                 :                :         TypeCacheEntry *typentry;
                               6706                 :                : 
                               6707                 :            185 :         appendStringInfoString(buf, sep);
 3818 andres@anarazel.de       6708                 :            185 :         sortexpr = get_rule_sortgroupclause(srt->tleSortGroupRef, targetList,
                               6709                 :                :                                             force_colno, context);
 6148 tgl@sss.pgh.pa.us        6710                 :            185 :         sortcoltype = exprType(sortexpr);
                               6711                 :                :         /* See whether operator is default < or > for datatype */
                               6712                 :            185 :         typentry = lookup_type_cache(sortcoltype,
                               6713                 :                :                                      TYPECACHE_LT_OPR | TYPECACHE_GT_OPR);
                               6714         [ +  + ]:            185 :         if (srt->sortop == typentry->lt_opr)
                               6715                 :                :         {
                               6716                 :                :             /* ASC is default, so emit nothing for it */
                               6717         [ -  + ]:            171 :             if (srt->nulls_first)
 4380 rhaas@postgresql.org     6718                 :UBC           0 :                 appendStringInfoString(buf, " NULLS FIRST");
                               6719                 :                :         }
 6148 tgl@sss.pgh.pa.us        6720         [ +  + ]:CBC          14 :         else if (srt->sortop == typentry->gt_opr)
                               6721                 :                :         {
 4380 rhaas@postgresql.org     6722                 :              5 :             appendStringInfoString(buf, " DESC");
                               6723                 :                :             /* DESC defaults to NULLS FIRST */
 6148 tgl@sss.pgh.pa.us        6724         [ +  + ]:              5 :             if (!srt->nulls_first)
 4380 rhaas@postgresql.org     6725                 :              1 :                 appendStringInfoString(buf, " NULLS LAST");
                               6726                 :                :         }
                               6727                 :                :         else
                               6728                 :                :         {
 6148 tgl@sss.pgh.pa.us        6729                 :              9 :             appendStringInfo(buf, " USING %s",
                               6730                 :                :                              generate_operator_name(srt->sortop,
                               6731                 :                :                                                     sortcoltype,
                               6732                 :                :                                                     sortcoltype));
                               6733                 :                :             /* be specific to eliminate ambiguity */
                               6734         [ -  + ]:              9 :             if (srt->nulls_first)
 4380 rhaas@postgresql.org     6735                 :UBC           0 :                 appendStringInfoString(buf, " NULLS FIRST");
                               6736                 :                :             else
 4380 rhaas@postgresql.org     6737                 :CBC           9 :                 appendStringInfoString(buf, " NULLS LAST");
                               6738                 :                :         }
 6148 tgl@sss.pgh.pa.us        6739                 :            185 :         sep = ", ";
                               6740                 :                :     }
                               6741                 :            169 : }
                               6742                 :                : 
                               6743                 :                : /*
                               6744                 :                :  * Display a WINDOW clause.
                               6745                 :                :  *
                               6746                 :                :  * Note that the windowClause list might contain only anonymous window
                               6747                 :                :  * specifications, in which case we should print nothing here.
                               6748                 :                :  */
                               6749                 :                : static void
                               6750                 :             24 : get_rule_windowclause(Query *query, deparse_context *context)
                               6751                 :                : {
                               6752                 :             24 :     StringInfo  buf = context->buf;
                               6753                 :                :     const char *sep;
                               6754                 :                :     ListCell   *l;
                               6755                 :                : 
                               6756                 :             24 :     sep = NULL;
                               6757   [ +  -  +  +  :             48 :     foreach(l, query->windowClause)
                                              +  + ]
                               6758                 :                :     {
                               6759                 :             24 :         WindowClause *wc = (WindowClause *) lfirst(l);
                               6760                 :                : 
                               6761         [ +  + ]:             24 :         if (wc->name == NULL)
                               6762                 :             21 :             continue;           /* ignore anonymous windows */
                               6763                 :                : 
 6148 tgl@sss.pgh.pa.us        6764         [ +  - ]:GBC           3 :         if (sep == NULL)
                               6765                 :              3 :             appendContextKeyword(context, " WINDOW ",
                               6766                 :                :                                  -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
                               6767                 :                :         else
 6148 tgl@sss.pgh.pa.us        6768                 :UBC           0 :             appendStringInfoString(buf, sep);
                               6769                 :                : 
 6148 tgl@sss.pgh.pa.us        6770                 :GBC           3 :         appendStringInfo(buf, "%s AS ", quote_identifier(wc->name));
                               6771                 :                : 
                               6772                 :              3 :         get_rule_windowspec(wc, query->targetList, context);
                               6773                 :                : 
                               6774                 :              3 :         sep = ", ";
                               6775                 :                :     }
 6148 tgl@sss.pgh.pa.us        6776                 :CBC          24 : }
                               6777                 :                : 
                               6778                 :                : /*
                               6779                 :                :  * Display a window definition
                               6780                 :                :  */
                               6781                 :                : static void
                               6782                 :             24 : get_rule_windowspec(WindowClause *wc, List *targetList,
                               6783                 :                :                     deparse_context *context)
                               6784                 :                : {
                               6785                 :             24 :     StringInfo  buf = context->buf;
                               6786                 :             24 :     bool        needspace = false;
                               6787                 :                :     const char *sep;
                               6788                 :                :     ListCell   *l;
                               6789                 :                : 
                               6790                 :             24 :     appendStringInfoChar(buf, '(');
                               6791         [ -  + ]:             24 :     if (wc->refname)
                               6792                 :                :     {
 6148 tgl@sss.pgh.pa.us        6793                 :UBC           0 :         appendStringInfoString(buf, quote_identifier(wc->refname));
                               6794                 :              0 :         needspace = true;
                               6795                 :                :     }
                               6796                 :                :     /* partition clauses are always inherited, so only print if no refname */
 6148 tgl@sss.pgh.pa.us        6797   [ -  +  -  - ]:CBC          24 :     if (wc->partitionClause && !wc->refname)
                               6798                 :                :     {
 6148 tgl@sss.pgh.pa.us        6799         [ #  # ]:UBC           0 :         if (needspace)
                               6800                 :              0 :             appendStringInfoChar(buf, ' ');
                               6801                 :              0 :         appendStringInfoString(buf, "PARTITION BY ");
                               6802                 :              0 :         sep = "";
                               6803   [ #  #  #  #  :              0 :         foreach(l, wc->partitionClause)
                                              #  # ]
                               6804                 :                :         {
                               6805                 :              0 :             SortGroupClause *grp = (SortGroupClause *) lfirst(l);
                               6806                 :                : 
                               6807                 :              0 :             appendStringInfoString(buf, sep);
 3818 andres@anarazel.de       6808                 :              0 :             get_rule_sortgroupclause(grp->tleSortGroupRef, targetList,
                               6809                 :                :                                      false, context);
 6148 tgl@sss.pgh.pa.us        6810                 :              0 :             sep = ", ";
                               6811                 :                :         }
                               6812                 :              0 :         needspace = true;
                               6813                 :                :     }
                               6814                 :                :     /* print ordering clause only if not inherited */
 6148 tgl@sss.pgh.pa.us        6815   [ +  -  +  - ]:CBC          24 :     if (wc->orderClause && !wc->copiedOrder)
                               6816                 :                :     {
                               6817         [ -  + ]:             24 :         if (needspace)
 6148 tgl@sss.pgh.pa.us        6818                 :UBC           0 :             appendStringInfoChar(buf, ' ');
 6148 tgl@sss.pgh.pa.us        6819                 :CBC          24 :         appendStringInfoString(buf, "ORDER BY ");
                               6820                 :             24 :         get_rule_orderby(wc->orderClause, targetList, false, context);
                               6821                 :             24 :         needspace = true;
                               6822                 :                :     }
                               6823                 :                :     /* framing clause is never inherited, so print unless it's default */
 6145                          6824         [ +  + ]:             24 :     if (wc->frameOptions & FRAMEOPTION_NONDEFAULT)
                               6825                 :                :     {
                               6826         [ +  - ]:             21 :         if (needspace)
                               6827                 :             21 :             appendStringInfoChar(buf, ' ');
  231                          6828                 :             21 :         get_window_frame_options(wc->frameOptions,
                               6829                 :                :                                  wc->startOffset, wc->endOffset,
                               6830                 :                :                                  context);
                               6831                 :                :     }
                               6832                 :             24 :     appendStringInfoChar(buf, ')');
                               6833                 :             24 : }
                               6834                 :                : 
                               6835                 :                : /*
                               6836                 :                :  * Append the description of a window's framing options to context->buf
                               6837                 :                :  */
                               6838                 :                : static void
                               6839                 :            119 : get_window_frame_options(int frameOptions,
                               6840                 :                :                          Node *startOffset, Node *endOffset,
                               6841                 :                :                          deparse_context *context)
                               6842                 :                : {
                               6843                 :            119 :     StringInfo  buf = context->buf;
                               6844                 :                : 
                               6845         [ +  - ]:            119 :     if (frameOptions & FRAMEOPTION_NONDEFAULT)
                               6846                 :                :     {
                               6847         [ +  + ]:            119 :         if (frameOptions & FRAMEOPTION_RANGE)
 6145                          6848                 :             10 :             appendStringInfoString(buf, "RANGE ");
  231                          6849         [ +  + ]:            109 :         else if (frameOptions & FRAMEOPTION_ROWS)
 6145                          6850                 :            103 :             appendStringInfoString(buf, "ROWS ");
  231                          6851         [ +  - ]:              6 :         else if (frameOptions & FRAMEOPTION_GROUPS)
 2820                          6852                 :              6 :             appendStringInfoString(buf, "GROUPS ");
                               6853                 :                :         else
 6145 tgl@sss.pgh.pa.us        6854                 :UBC           0 :             Assert(false);
  231 tgl@sss.pgh.pa.us        6855         [ +  + ]:CBC         119 :         if (frameOptions & FRAMEOPTION_BETWEEN)
 6145                          6856                 :             46 :             appendStringInfoString(buf, "BETWEEN ");
  231                          6857         [ +  + ]:            119 :         if (frameOptions & FRAMEOPTION_START_UNBOUNDED_PRECEDING)
 6145                          6858                 :             76 :             appendStringInfoString(buf, "UNBOUNDED PRECEDING ");
  231                          6859         [ +  + ]:             43 :         else if (frameOptions & FRAMEOPTION_START_CURRENT_ROW)
 6145                          6860                 :             13 :             appendStringInfoString(buf, "CURRENT ROW ");
  231                          6861         [ +  - ]:             30 :         else if (frameOptions & FRAMEOPTION_START_OFFSET)
                               6862                 :                :         {
                               6863                 :             30 :             get_rule_expr(startOffset, context, false);
                               6864         [ +  - ]:             30 :             if (frameOptions & FRAMEOPTION_START_OFFSET_PRECEDING)
 5737                          6865                 :             30 :                 appendStringInfoString(buf, " PRECEDING ");
  231 tgl@sss.pgh.pa.us        6866         [ #  # ]:UBC           0 :             else if (frameOptions & FRAMEOPTION_START_OFFSET_FOLLOWING)
 5737                          6867                 :              0 :                 appendStringInfoString(buf, " FOLLOWING ");
                               6868                 :                :             else
                               6869                 :              0 :                 Assert(false);
                               6870                 :                :         }
                               6871                 :                :         else
 6145                          6872                 :              0 :             Assert(false);
  231 tgl@sss.pgh.pa.us        6873         [ +  + ]:CBC         119 :         if (frameOptions & FRAMEOPTION_BETWEEN)
                               6874                 :                :         {
 6145                          6875                 :             46 :             appendStringInfoString(buf, "AND ");
  231                          6876         [ +  + ]:             46 :             if (frameOptions & FRAMEOPTION_END_UNBOUNDED_FOLLOWING)
 6145                          6877                 :             10 :                 appendStringInfoString(buf, "UNBOUNDED FOLLOWING ");
  231                          6878         [ +  + ]:             36 :             else if (frameOptions & FRAMEOPTION_END_CURRENT_ROW)
 6145                          6879                 :              3 :                 appendStringInfoString(buf, "CURRENT ROW ");
  231                          6880         [ +  - ]:             33 :             else if (frameOptions & FRAMEOPTION_END_OFFSET)
                               6881                 :                :             {
                               6882                 :             33 :                 get_rule_expr(endOffset, context, false);
                               6883         [ -  + ]:             33 :                 if (frameOptions & FRAMEOPTION_END_OFFSET_PRECEDING)
 5737 tgl@sss.pgh.pa.us        6884                 :UBC           0 :                     appendStringInfoString(buf, " PRECEDING ");
  231 tgl@sss.pgh.pa.us        6885         [ +  - ]:CBC          33 :                 else if (frameOptions & FRAMEOPTION_END_OFFSET_FOLLOWING)
 5737                          6886                 :             33 :                     appendStringInfoString(buf, " FOLLOWING ");
                               6887                 :                :                 else
 5737 tgl@sss.pgh.pa.us        6888                 :UBC           0 :                     Assert(false);
                               6889                 :                :             }
                               6890                 :                :             else
 6145                          6891                 :              0 :                 Assert(false);
                               6892                 :                :         }
  231 tgl@sss.pgh.pa.us        6893         [ +  + ]:CBC         119 :         if (frameOptions & FRAMEOPTION_EXCLUDE_CURRENT_ROW)
 2820                          6894                 :              3 :             appendStringInfoString(buf, "EXCLUDE CURRENT ROW ");
  231                          6895         [ +  + ]:            116 :         else if (frameOptions & FRAMEOPTION_EXCLUDE_GROUP)
 2820                          6896                 :              3 :             appendStringInfoString(buf, "EXCLUDE GROUP ");
  231                          6897         [ +  + ]:            113 :         else if (frameOptions & FRAMEOPTION_EXCLUDE_TIES)
 2820                          6898                 :              3 :             appendStringInfoString(buf, "EXCLUDE TIES ");
                               6899                 :                :         /* we will now have a trailing space; remove it */
  231                          6900                 :            119 :         buf->data[--(buf->len)] = '\0';
                               6901                 :                :     }
                               6902                 :            119 : }
                               6903                 :                : 
                               6904                 :                : /*
                               6905                 :                :  * Return the description of a window's framing options as a palloc'd string
                               6906                 :                :  */
                               6907                 :                : char *
                               6908                 :             98 : get_window_frame_options_for_explain(int frameOptions,
                               6909                 :                :                                      Node *startOffset, Node *endOffset,
                               6910                 :                :                                      List *dpcontext, bool forceprefix)
                               6911                 :                : {
                               6912                 :                :     StringInfoData buf;
                               6913                 :                :     deparse_context context;
                               6914                 :                : 
                               6915                 :             98 :     initStringInfo(&buf);
                               6916                 :             98 :     context.buf = &buf;
                               6917                 :             98 :     context.namespaces = dpcontext;
                               6918                 :             98 :     context.resultDesc = NULL;
                               6919                 :             98 :     context.targetList = NIL;
                               6920                 :             98 :     context.windowClause = NIL;
                               6921                 :             98 :     context.varprefix = forceprefix;
                               6922                 :             98 :     context.prettyFlags = 0;
                               6923                 :             98 :     context.wrapColumn = WRAP_COLUMN_DEFAULT;
                               6924                 :             98 :     context.indentLevel = 0;
                               6925                 :             98 :     context.colNamesVisible = true;
                               6926                 :             98 :     context.inGroupBy = false;
                               6927                 :             98 :     context.varInOrderBy = false;
                               6928                 :             98 :     context.appendparents = NULL;
                               6929                 :                : 
                               6930                 :             98 :     get_window_frame_options(frameOptions, startOffset, endOffset, &context);
                               6931                 :                : 
                               6932                 :             98 :     return buf.data;
                               6933                 :                : }
                               6934                 :                : 
                               6935                 :                : /* ----------
                               6936                 :                :  * get_insert_query_def         - Parse back an INSERT parsetree
                               6937                 :                :  * ----------
                               6938                 :                :  */
                               6939                 :                : static void
  425                          6940                 :            170 : get_insert_query_def(Query *query, deparse_context *context)
                               6941                 :                : {
 9522                          6942                 :            170 :     StringInfo  buf = context->buf;
 9154                          6943                 :            170 :     RangeTblEntry *select_rte = NULL;
 7027 mail@joeconway.com       6944                 :            170 :     RangeTblEntry *values_rte = NULL;
                               6945                 :                :     RangeTblEntry *rte;
                               6946                 :                :     char       *sep;
                               6947                 :                :     ListCell   *l;
                               6948                 :                :     List       *strippedexprs;
                               6949                 :                : 
                               6950                 :                :     /* Insert the WITH clause if given */
 5492 tgl@sss.pgh.pa.us        6951                 :            170 :     get_with_clause(query, context);
                               6952                 :                : 
                               6953                 :                :     /*
                               6954                 :                :      * If it's an INSERT ... SELECT or multi-row VALUES, there will be a
                               6955                 :                :      * single RTE for the SELECT or VALUES.  Plain VALUES has neither.
                               6956                 :                :      */
 9919 bruce@momjian.us         6957   [ +  -  +  +  :            661 :     foreach(l, query->rtable)
                                              +  + ]
                               6958                 :                :     {
                               6959                 :            491 :         rte = (RangeTblEntry *) lfirst(l);
                               6960                 :                : 
 7027 mail@joeconway.com       6961         [ +  + ]:            491 :         if (rte->rtekind == RTE_SUBQUERY)
                               6962                 :                :         {
                               6963         [ -  + ]:             25 :             if (select_rte)
 7027 mail@joeconway.com       6964         [ #  # ]:UBC           0 :                 elog(ERROR, "too many subquery RTEs in INSERT");
 7027 mail@joeconway.com       6965                 :CBC          25 :             select_rte = rte;
                               6966                 :                :         }
                               6967                 :                : 
                               6968         [ +  + ]:            491 :         if (rte->rtekind == RTE_VALUES)
                               6969                 :                :         {
                               6970         [ -  + ]:             22 :             if (values_rte)
 7027 mail@joeconway.com       6971         [ #  # ]:UBC           0 :                 elog(ERROR, "too many values RTEs in INSERT");
 7027 mail@joeconway.com       6972                 :CBC          22 :             values_rte = rte;
                               6973                 :                :         }
                               6974                 :                :     }
                               6975   [ +  +  -  + ]:            170 :     if (select_rte && values_rte)
 7027 mail@joeconway.com       6976         [ #  # ]:UBC           0 :         elog(ERROR, "both subquery and values RTEs in INSERT");
                               6977                 :                : 
                               6978                 :                :     /*
                               6979                 :                :      * Start the query with INSERT INTO relname
                               6980                 :                :      */
 9494 tgl@sss.pgh.pa.us        6981                 :CBC         170 :     rte = rt_fetch(query->resultRelation, query->rtable);
 8579                          6982         [ -  + ]:            170 :     Assert(rte->rtekind == RTE_RELATION);
                               6983                 :                : 
 8126                          6984         [ +  - ]:            170 :     if (PRETTY_INDENT(context))
                               6985                 :                :     {
 8121 bruce@momjian.us         6986                 :            170 :         context->indentLevel += PRETTYINDENT_STD;
                               6987                 :            170 :         appendStringInfoChar(buf, ' ');
                               6988                 :                :     }
  984 tgl@sss.pgh.pa.us        6989                 :            170 :     appendStringInfo(buf, "INSERT INTO %s",
                               6990                 :                :                      generate_relation_name(rte->relid, NIL));
                               6991                 :                : 
                               6992                 :                :     /* Print the relation alias, if needed; INSERT requires explicit AS */
                               6993                 :            170 :     get_rte_alias(rte, query->resultRelation, true, context);
                               6994                 :                : 
                               6995                 :                :     /* always want a space here */
                               6996                 :            170 :     appendStringInfoChar(buf, ' ');
                               6997                 :                : 
                               6998                 :                :     /*
                               6999                 :                :      * Add the insert-column-names list.  Any indirection decoration needed on
                               7000                 :                :      * the column names can be inferred from the top targetlist.
                               7001                 :                :      */
 7811                          7002                 :            170 :     strippedexprs = NIL;
                               7003                 :            170 :     sep = "";
 4757                          7004         [ +  - ]:            170 :     if (query->targetList)
                               7005                 :            170 :         appendStringInfoChar(buf, '(');
 9919 bruce@momjian.us         7006   [ +  -  +  +  :            621 :     foreach(l, query->targetList)
                                              +  + ]
                               7007                 :                :     {
 9177 tgl@sss.pgh.pa.us        7008                 :            451 :         TargetEntry *tle = (TargetEntry *) lfirst(l);
                               7009                 :                : 
 7510                          7010         [ -  + ]:            451 :         if (tle->resjunk)
 9160 tgl@sss.pgh.pa.us        7011                 :UBC           0 :             continue;           /* ignore junk entries */
                               7012                 :                : 
 7486 neilc@samurai.com        7013                 :CBC         451 :         appendStringInfoString(buf, sep);
 9919 bruce@momjian.us         7014                 :            451 :         sep = ", ";
                               7015                 :                : 
                               7016                 :                :         /*
                               7017                 :                :          * Put out name of target column; look in the catalogs, not at
                               7018                 :                :          * tle->resname, since resname will fail to track RENAME.
                               7019                 :                :          */
 7941 neilc@samurai.com        7020                 :            451 :         appendStringInfoString(buf,
 2815 alvherre@alvh.no-ip.     7021                 :            451 :                                quote_identifier(get_attname(rte->relid,
                               7022                 :            451 :                                                             tle->resno,
                               7023                 :                :                                                             false)));
                               7024                 :                : 
                               7025                 :                :         /*
                               7026                 :                :          * Print any indirection needed (subfields or subscripts), and strip
                               7027                 :                :          * off the top-level nodes representing the indirection assignments.
                               7028                 :                :          * Add the stripped expressions to strippedexprs.  (If it's a
                               7029                 :                :          * single-VALUES statement, the stripped expressions are the VALUES to
                               7030                 :                :          * print below.  Otherwise they're just Vars and not really
                               7031                 :                :          * interesting.)
                               7032                 :                :          */
 3373 tgl@sss.pgh.pa.us        7033                 :            451 :         strippedexprs = lappend(strippedexprs,
                               7034                 :            451 :                                 processIndirection((Node *) tle->expr,
                               7035                 :                :                                                    context));
                               7036                 :                :     }
 4757                          7037         [ +  - ]:            170 :     if (query->targetList)
 4380 rhaas@postgresql.org     7038                 :            170 :         appendStringInfoString(buf, ") ");
                               7039                 :                : 
 3127 peter_e@gmx.net          7040         [ -  + ]:            170 :     if (query->override)
                               7041                 :                :     {
 3127 peter_e@gmx.net          7042         [ #  # ]:UBC           0 :         if (query->override == OVERRIDING_SYSTEM_VALUE)
                               7043                 :              0 :             appendStringInfoString(buf, "OVERRIDING SYSTEM VALUE ");
                               7044         [ #  # ]:              0 :         else if (query->override == OVERRIDING_USER_VALUE)
                               7045                 :              0 :             appendStringInfoString(buf, "OVERRIDING USER VALUE ");
                               7046                 :                :     }
                               7047                 :                : 
 7027 mail@joeconway.com       7048         [ +  + ]:CBC         170 :     if (select_rte)
                               7049                 :                :     {
                               7050                 :                :         /* Add the SELECT */
 1441 tgl@sss.pgh.pa.us        7051                 :             25 :         get_query_def(select_rte->subquery, buf, context->namespaces, NULL,
                               7052                 :                :                       false,
                               7053                 :                :                       context->prettyFlags, context->wrapColumn,
                               7054                 :                :                       context->indentLevel);
                               7055                 :                :     }
 7027 mail@joeconway.com       7056         [ +  + ]:            145 :     else if (values_rte)
                               7057                 :                :     {
                               7058                 :                :         /* Add the multi-VALUES expression lists */
                               7059                 :             22 :         get_values_def(values_rte->values_lists, context);
                               7060                 :                :     }
 4757 tgl@sss.pgh.pa.us        7061         [ +  - ]:            123 :     else if (strippedexprs)
                               7062                 :                :     {
                               7063                 :                :         /* Add the single-VALUES expression list */
 8126                          7064                 :            123 :         appendContextKeyword(context, "VALUES (",
                               7065                 :                :                              -PRETTYINDENT_STD, PRETTYINDENT_STD, 2);
 1384                          7066                 :            123 :         get_rule_list_toplevel(strippedexprs, context, false);
 9382                          7067                 :            123 :         appendStringInfoChar(buf, ')');
                               7068                 :                :     }
                               7069                 :                :     else
                               7070                 :                :     {
                               7071                 :                :         /* No expressions, so it must be DEFAULT VALUES */
 4380 rhaas@postgresql.org     7072                 :UBC           0 :         appendStringInfoString(buf, "DEFAULT VALUES");
                               7073                 :                :     }
                               7074                 :                : 
                               7075                 :                :     /* Add ON CONFLICT if present */
 3826 andres@anarazel.de       7076         [ +  + ]:CBC         170 :     if (query->onConflict)
                               7077                 :                :     {
                               7078                 :             15 :         OnConflictExpr *confl = query->onConflict;
                               7079                 :                : 
 3771 heikki.linnakangas@i     7080                 :             15 :         appendStringInfoString(buf, " ON CONFLICT");
                               7081                 :                : 
 3815 andres@anarazel.de       7082         [ +  + ]:             15 :         if (confl->arbiterElems)
                               7083                 :                :         {
                               7084                 :                :             /* Add the single-VALUES expression list */
                               7085                 :             12 :             appendStringInfoChar(buf, '(');
                               7086                 :             12 :             get_rule_expr((Node *) confl->arbiterElems, context, false);
                               7087                 :             12 :             appendStringInfoChar(buf, ')');
                               7088                 :                : 
                               7089                 :                :             /* Add a WHERE clause (for partial indexes) if given */
                               7090         [ +  + ]:             12 :             if (confl->arbiterWhere != NULL)
                               7091                 :                :             {
                               7092                 :                :                 bool        save_varprefix;
                               7093                 :                : 
                               7094                 :                :                 /*
                               7095                 :                :                  * Force non-prefixing of Vars, since parser assumes that they
                               7096                 :                :                  * belong to target relation.  WHERE clause does not use
                               7097                 :                :                  * InferenceElem, so this is separately required.
                               7098                 :                :                  */
 3551 tgl@sss.pgh.pa.us        7099                 :              6 :                 save_varprefix = context->varprefix;
                               7100                 :              6 :                 context->varprefix = false;
                               7101                 :                : 
 3815 andres@anarazel.de       7102                 :              6 :                 appendContextKeyword(context, " WHERE ",
                               7103                 :                :                                      -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
                               7104                 :              6 :                 get_rule_expr(confl->arbiterWhere, context, false);
                               7105                 :                : 
 3551 tgl@sss.pgh.pa.us        7106                 :              6 :                 context->varprefix = save_varprefix;
                               7107                 :                :             }
                               7108                 :                :         }
 3457                          7109         [ -  + ]:              3 :         else if (OidIsValid(confl->constraint))
                               7110                 :                :         {
 3811 bruce@momjian.us         7111                 :UBC           0 :             char       *constraint = get_constraint_name(confl->constraint);
                               7112                 :                : 
 3457 tgl@sss.pgh.pa.us        7113         [ #  # ]:              0 :             if (!constraint)
                               7114         [ #  # ]:              0 :                 elog(ERROR, "cache lookup failed for constraint %u",
                               7115                 :                :                      confl->constraint);
 3815 andres@anarazel.de       7116                 :              0 :             appendStringInfo(buf, " ON CONSTRAINT %s",
                               7117                 :                :                              quote_identifier(constraint));
                               7118                 :                :         }
                               7119                 :                : 
 3826 andres@anarazel.de       7120         [ +  + ]:CBC          15 :         if (confl->action == ONCONFLICT_NOTHING)
                               7121                 :                :         {
 3815                          7122                 :              9 :             appendStringInfoString(buf, " DO NOTHING");
                               7123                 :                :         }
                               7124                 :                :         else
                               7125                 :                :         {
                               7126                 :              6 :             appendStringInfoString(buf, " DO UPDATE SET ");
                               7127                 :                :             /* Deparse targetlist */
 3826                          7128                 :              6 :             get_update_query_targetlist_def(query, confl->onConflictSet,
                               7129                 :                :                                             context, rte);
                               7130                 :                : 
                               7131                 :                :             /* Add a WHERE clause if given */
                               7132         [ +  - ]:              6 :             if (confl->onConflictWhere != NULL)
                               7133                 :                :             {
                               7134                 :              6 :                 appendContextKeyword(context, " WHERE ",
                               7135                 :                :                                      -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
                               7136                 :              6 :                 get_rule_expr(confl->onConflictWhere, context, false);
                               7137                 :                :             }
                               7138                 :                :         }
                               7139                 :                :     }
                               7140                 :                : 
                               7141                 :                :     /* Add RETURNING if present */
 7017 tgl@sss.pgh.pa.us        7142         [ +  + ]:            170 :     if (query->returningList)
  285 dean.a.rasheed@gmail     7143                 :             39 :         get_returning_clause(query, context);
 9927 bruce@momjian.us         7144                 :            170 : }
                               7145                 :                : 
                               7146                 :                : 
                               7147                 :                : /* ----------
                               7148                 :                :  * get_update_query_def         - Parse back an UPDATE parsetree
                               7149                 :                :  * ----------
                               7150                 :                :  */
                               7151                 :                : static void
  425 tgl@sss.pgh.pa.us        7152                 :             77 : get_update_query_def(Query *query, deparse_context *context)
                               7153                 :                : {
 7730 bruce@momjian.us         7154                 :             77 :     StringInfo  buf = context->buf;
                               7155                 :                :     RangeTblEntry *rte;
                               7156                 :                : 
                               7157                 :                :     /* Insert the WITH clause if given */
 5492 tgl@sss.pgh.pa.us        7158                 :             77 :     get_with_clause(query, context);
                               7159                 :                : 
                               7160                 :                :     /*
                               7161                 :                :      * Start the query with UPDATE relname SET
                               7162                 :                :      */
 9494                          7163                 :             77 :     rte = rt_fetch(query->resultRelation, query->rtable);
 8579                          7164         [ -  + ]:             77 :     Assert(rte->rtekind == RTE_RELATION);
 8126                          7165         [ +  - ]:             77 :     if (PRETTY_INDENT(context))
                               7166                 :                :     {
 8121 bruce@momjian.us         7167                 :             77 :         appendStringInfoChar(buf, ' ');
                               7168                 :             77 :         context->indentLevel += PRETTYINDENT_STD;
                               7169                 :                :     }
 6387 tgl@sss.pgh.pa.us        7170                 :            154 :     appendStringInfo(buf, "UPDATE %s%s",
 9271                          7171         [ +  - ]:             77 :                      only_marker(rte),
                               7172                 :                :                      generate_relation_name(rte->relid, NIL));
                               7173                 :                : 
                               7174                 :                :     /* Print the relation alias, if needed */
  984                          7175                 :             77 :     get_rte_alias(rte, query->resultRelation, false, context);
                               7176                 :                : 
 6387                          7177                 :             77 :     appendStringInfoString(buf, " SET ");
                               7178                 :                : 
                               7179                 :                :     /* Deparse targetlist */
 3826 andres@anarazel.de       7180                 :             77 :     get_update_query_targetlist_def(query, query->targetList, context, rte);
                               7181                 :                : 
                               7182                 :                :     /* Add the FROM clause if needed */
                               7183                 :             77 :     get_from_clause(query, " FROM ", context);
                               7184                 :                : 
                               7185                 :                :     /* Add a WHERE clause if given */
                               7186         [ +  + ]:             77 :     if (query->jointree->quals != NULL)
                               7187                 :                :     {
                               7188                 :             57 :         appendContextKeyword(context, " WHERE ",
                               7189                 :                :                              -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
                               7190                 :             57 :         get_rule_expr(query->jointree->quals, context, false);
                               7191                 :                :     }
                               7192                 :                : 
                               7193                 :                :     /* Add RETURNING if present */
                               7194         [ +  + ]:             77 :     if (query->returningList)
  285 dean.a.rasheed@gmail     7195                 :             23 :         get_returning_clause(query, context);
 3826 andres@anarazel.de       7196                 :             77 : }
                               7197                 :                : 
                               7198                 :                : 
                               7199                 :                : /* ----------
                               7200                 :                :  * get_update_query_targetlist_def          - Parse back an UPDATE targetlist
                               7201                 :                :  * ----------
                               7202                 :                :  */
                               7203                 :                : static void
                               7204                 :             95 : get_update_query_targetlist_def(Query *query, List *targetList,
                               7205                 :                :                                 deparse_context *context, RangeTblEntry *rte)
                               7206                 :                : {
                               7207                 :             95 :     StringInfo  buf = context->buf;
                               7208                 :                :     ListCell   *l;
                               7209                 :                :     ListCell   *next_ma_cell;
                               7210                 :                :     int         remaining_ma_columns;
                               7211                 :                :     const char *sep;
                               7212                 :                :     SubLink    *cur_ma_sublink;
                               7213                 :                :     List       *ma_sublinks;
                               7214                 :                : 
                               7215                 :                :     /*
                               7216                 :                :      * Prepare to deal with MULTIEXPR assignments: collect the source SubLinks
                               7217                 :                :      * into a list.  We expect them to appear, in ID order, in resjunk tlist
                               7218                 :                :      * entries.
                               7219                 :                :      */
 4150 tgl@sss.pgh.pa.us        7220                 :             95 :     ma_sublinks = NIL;
                               7221         [ +  + ]:             95 :     if (query->hasSubLinks)      /* else there can't be any */
                               7222                 :                :     {
 3826 andres@anarazel.de       7223   [ +  -  +  +  :             21 :         foreach(l, targetList)
                                              +  + ]
                               7224                 :                :         {
 4150 tgl@sss.pgh.pa.us        7225                 :             15 :             TargetEntry *tle = (TargetEntry *) lfirst(l);
                               7226                 :                : 
                               7227   [ +  +  +  - ]:             15 :             if (tle->resjunk && IsA(tle->expr, SubLink))
                               7228                 :                :             {
                               7229                 :              3 :                 SubLink    *sl = (SubLink *) tle->expr;
                               7230                 :                : 
                               7231         [ +  - ]:              3 :                 if (sl->subLinkType == MULTIEXPR_SUBLINK)
                               7232                 :                :                 {
                               7233                 :              3 :                     ma_sublinks = lappend(ma_sublinks, sl);
                               7234         [ -  + ]:              3 :                     Assert(sl->subLinkId == list_length(ma_sublinks));
                               7235                 :                :                 }
                               7236                 :                :             }
                               7237                 :                :         }
                               7238                 :                :     }
                               7239                 :             95 :     next_ma_cell = list_head(ma_sublinks);
                               7240                 :             95 :     cur_ma_sublink = NULL;
                               7241                 :             95 :     remaining_ma_columns = 0;
                               7242                 :                : 
                               7243                 :                :     /* Add the comma separated list of 'attname = value' */
 9919 bruce@momjian.us         7244                 :             95 :     sep = "";
 3826 andres@anarazel.de       7245   [ +  -  +  +  :            244 :     foreach(l, targetList)
                                              +  + ]
                               7246                 :                :     {
 9160 tgl@sss.pgh.pa.us        7247                 :            149 :         TargetEntry *tle = (TargetEntry *) lfirst(l);
                               7248                 :                :         Node       *expr;
                               7249                 :                : 
 7510                          7250         [ +  + ]:            149 :         if (tle->resjunk)
 9160                          7251                 :              3 :             continue;           /* ignore junk entries */
                               7252                 :                : 
                               7253                 :                :         /* Emit separator (OK whether we're in multiassignment or not) */
 7486 neilc@samurai.com        7254                 :            146 :         appendStringInfoString(buf, sep);
 9919 bruce@momjian.us         7255                 :            146 :         sep = ", ";
                               7256                 :                : 
                               7257                 :                :         /*
                               7258                 :                :          * Check to see if we're starting a multiassignment group: if so,
                               7259                 :                :          * output a left paren.
                               7260                 :                :          */
 4150 tgl@sss.pgh.pa.us        7261   [ +  +  +  - ]:            146 :         if (next_ma_cell != NULL && cur_ma_sublink == NULL)
                               7262                 :                :         {
                               7263                 :                :             /*
                               7264                 :                :              * We must dig down into the expr to see if it's a PARAM_MULTIEXPR
                               7265                 :                :              * Param.  That could be buried under FieldStores and
                               7266                 :                :              * SubscriptingRefs and CoerceToDomains (cf processIndirection()),
                               7267                 :                :              * and underneath those there could be an implicit type coercion.
                               7268                 :                :              * Because we would ignore implicit type coercions anyway, we
                               7269                 :                :              * don't need to be as careful as processIndirection() is about
                               7270                 :                :              * descending past implicit CoerceToDomains.
                               7271                 :                :              */
                               7272                 :              3 :             expr = (Node *) tle->expr;
                               7273         [ +  - ]:              6 :             while (expr)
                               7274                 :                :             {
                               7275         [ -  + ]:              6 :                 if (IsA(expr, FieldStore))
                               7276                 :                :                 {
 4150 tgl@sss.pgh.pa.us        7277                 :UBC           0 :                     FieldStore *fstore = (FieldStore *) expr;
                               7278                 :                : 
                               7279                 :              0 :                     expr = (Node *) linitial(fstore->newvals);
                               7280                 :                :                 }
 2461 alvherre@alvh.no-ip.     7281         [ +  + ]:CBC           6 :                 else if (IsA(expr, SubscriptingRef))
                               7282                 :                :                 {
                               7283                 :              3 :                     SubscriptingRef *sbsref = (SubscriptingRef *) expr;
                               7284                 :                : 
                               7285         [ -  + ]:              3 :                     if (sbsref->refassgnexpr == NULL)
 4150 tgl@sss.pgh.pa.us        7286                 :UBC           0 :                         break;
                               7287                 :                : 
 2461 alvherre@alvh.no-ip.     7288                 :CBC           3 :                     expr = (Node *) sbsref->refassgnexpr;
                               7289                 :                :                 }
 3030 tgl@sss.pgh.pa.us        7290         [ -  + ]:              3 :                 else if (IsA(expr, CoerceToDomain))
                               7291                 :                :                 {
 3030 tgl@sss.pgh.pa.us        7292                 :UBC           0 :                     CoerceToDomain *cdomain = (CoerceToDomain *) expr;
                               7293                 :                : 
                               7294         [ #  # ]:              0 :                     if (cdomain->coercionformat != COERCE_IMPLICIT_CAST)
                               7295                 :              0 :                         break;
                               7296                 :              0 :                     expr = (Node *) cdomain->arg;
                               7297                 :                :                 }
                               7298                 :                :                 else
 4150 tgl@sss.pgh.pa.us        7299                 :CBC           3 :                     break;
                               7300                 :                :             }
                               7301                 :              3 :             expr = strip_implicit_coercions(expr);
                               7302                 :                : 
                               7303   [ +  -  +  - ]:              3 :             if (expr && IsA(expr, Param) &&
                               7304         [ +  - ]:              3 :                 ((Param *) expr)->paramkind == PARAM_MULTIEXPR)
                               7305                 :                :             {
                               7306                 :              3 :                 cur_ma_sublink = (SubLink *) lfirst(next_ma_cell);
 2297                          7307                 :              3 :                 next_ma_cell = lnext(ma_sublinks, next_ma_cell);
 2098 alvherre@alvh.no-ip.     7308                 :              3 :                 remaining_ma_columns = count_nonjunk_tlist_entries(((Query *) cur_ma_sublink->subselect)->targetList);
 4150 tgl@sss.pgh.pa.us        7309         [ -  + ]:              3 :                 Assert(((Param *) expr)->paramid ==
                               7310                 :                :                        ((cur_ma_sublink->subLinkId << 16) | 1));
                               7311                 :              3 :                 appendStringInfoChar(buf, '(');
                               7312                 :                :             }
                               7313                 :                :         }
                               7314                 :                : 
                               7315                 :                :         /*
                               7316                 :                :          * Put out name of target column; look in the catalogs, not at
                               7317                 :                :          * tle->resname, since resname will fail to track RENAME.
                               7318                 :                :          */
 7811                          7319                 :            146 :         appendStringInfoString(buf,
 2815 alvherre@alvh.no-ip.     7320                 :            146 :                                quote_identifier(get_attname(rte->relid,
                               7321                 :            146 :                                                             tle->resno,
                               7322                 :                :                                                             false)));
                               7323                 :                : 
                               7324                 :                :         /*
                               7325                 :                :          * Print any indirection needed (subfields or subscripts), and strip
                               7326                 :                :          * off the top-level nodes representing the indirection assignments.
                               7327                 :                :          */
 3373 tgl@sss.pgh.pa.us        7328                 :            146 :         expr = processIndirection((Node *) tle->expr, context);
                               7329                 :                : 
                               7330                 :                :         /*
                               7331                 :                :          * If we're in a multiassignment, skip printing anything more, unless
                               7332                 :                :          * this is the last column; in which case, what we print should be the
                               7333                 :                :          * sublink, not the Param.
                               7334                 :                :          */
 4150                          7335         [ +  + ]:            146 :         if (cur_ma_sublink != NULL)
                               7336                 :                :         {
                               7337         [ +  + ]:              9 :             if (--remaining_ma_columns > 0)
                               7338                 :              6 :                 continue;       /* not the last column of multiassignment */
                               7339                 :              3 :             appendStringInfoChar(buf, ')');
                               7340                 :              3 :             expr = (Node *) cur_ma_sublink;
                               7341                 :              3 :             cur_ma_sublink = NULL;
                               7342                 :                :         }
                               7343                 :                : 
 4380 rhaas@postgresql.org     7344                 :            140 :         appendStringInfoString(buf, " = ");
                               7345                 :                : 
 7811 tgl@sss.pgh.pa.us        7346                 :            140 :         get_rule_expr(expr, context, false);
                               7347                 :                :     }
 9927 bruce@momjian.us         7348                 :             95 : }
                               7349                 :                : 
                               7350                 :                : 
                               7351                 :                : /* ----------
                               7352                 :                :  * get_delete_query_def         - Parse back a DELETE parsetree
                               7353                 :                :  * ----------
                               7354                 :                :  */
                               7355                 :                : static void
  425 tgl@sss.pgh.pa.us        7356                 :             38 : get_delete_query_def(Query *query, deparse_context *context)
                               7357                 :                : {
 9522                          7358                 :             38 :     StringInfo  buf = context->buf;
                               7359                 :                :     RangeTblEntry *rte;
                               7360                 :                : 
                               7361                 :                :     /* Insert the WITH clause if given */
 5492                          7362                 :             38 :     get_with_clause(query, context);
                               7363                 :                : 
                               7364                 :                :     /*
                               7365                 :                :      * Start the query with DELETE FROM relname
                               7366                 :                :      */
 9494                          7367                 :             38 :     rte = rt_fetch(query->resultRelation, query->rtable);
 8579                          7368         [ -  + ]:             38 :     Assert(rte->rtekind == RTE_RELATION);
 8126                          7369         [ +  - ]:             38 :     if (PRETTY_INDENT(context))
                               7370                 :                :     {
 8121 bruce@momjian.us         7371                 :             38 :         appendStringInfoChar(buf, ' ');
 6387 tgl@sss.pgh.pa.us        7372                 :             38 :         context->indentLevel += PRETTYINDENT_STD;
                               7373                 :                :     }
 9494                          7374                 :             76 :     appendStringInfo(buf, "DELETE FROM %s%s",
 9271                          7375         [ +  - ]:             38 :                      only_marker(rte),
                               7376                 :                :                      generate_relation_name(rte->relid, NIL));
                               7377                 :                : 
                               7378                 :                :     /* Print the relation alias, if needed */
  984                          7379                 :             38 :     get_rte_alias(rte, query->resultRelation, false, context);
                               7380                 :                : 
                               7381                 :                :     /* Add the USING clause if given */
 7393                          7382                 :             38 :     get_from_clause(query, " USING ", context);
                               7383                 :                : 
                               7384                 :                :     /* Add a WHERE clause if given */
 9160                          7385         [ +  - ]:             38 :     if (query->jointree->quals != NULL)
                               7386                 :                :     {
 8126                          7387                 :             38 :         appendContextKeyword(context, " WHERE ",
                               7388                 :                :                              -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
 8440                          7389                 :             38 :         get_rule_expr(query->jointree->quals, context, false);
                               7390                 :                :     }
                               7391                 :                : 
                               7392                 :                :     /* Add RETURNING if present */
 7017                          7393         [ +  + ]:             38 :     if (query->returningList)
  285 dean.a.rasheed@gmail     7394                 :              8 :         get_returning_clause(query, context);
 9927 bruce@momjian.us         7395                 :             38 : }
                               7396                 :                : 
                               7397                 :                : 
                               7398                 :                : /* ----------
                               7399                 :                :  * get_merge_query_def              - Parse back a MERGE parsetree
                               7400                 :                :  * ----------
                               7401                 :                :  */
                               7402                 :                : static void
  425 tgl@sss.pgh.pa.us        7403                 :              6 : get_merge_query_def(Query *query, deparse_context *context)
                               7404                 :                : {
  905                          7405                 :              6 :     StringInfo  buf = context->buf;
                               7406                 :                :     RangeTblEntry *rte;
                               7407                 :                :     ListCell   *lc;
                               7408                 :                :     bool        haveNotMatchedBySource;
                               7409                 :                : 
                               7410                 :                :     /* Insert the WITH clause if given */
                               7411                 :              6 :     get_with_clause(query, context);
                               7412                 :                : 
                               7413                 :                :     /*
                               7414                 :                :      * Start the query with MERGE INTO relname
                               7415                 :                :      */
                               7416                 :              6 :     rte = rt_fetch(query->resultRelation, query->rtable);
                               7417         [ -  + ]:              6 :     Assert(rte->rtekind == RTE_RELATION);
                               7418         [ +  - ]:              6 :     if (PRETTY_INDENT(context))
                               7419                 :                :     {
                               7420                 :              6 :         appendStringInfoChar(buf, ' ');
                               7421                 :              6 :         context->indentLevel += PRETTYINDENT_STD;
                               7422                 :                :     }
                               7423                 :             12 :     appendStringInfo(buf, "MERGE INTO %s%s",
                               7424         [ +  - ]:              6 :                      only_marker(rte),
                               7425                 :                :                      generate_relation_name(rte->relid, NIL));
                               7426                 :                : 
                               7427                 :                :     /* Print the relation alias, if needed */
                               7428                 :              6 :     get_rte_alias(rte, query->resultRelation, false, context);
                               7429                 :                : 
                               7430                 :                :     /* Print the source relation and join clause */
                               7431                 :              6 :     get_from_clause(query, " USING ", context);
                               7432                 :              6 :     appendContextKeyword(context, " ON ",
                               7433                 :                :                          -PRETTYINDENT_STD, PRETTYINDENT_STD, 2);
  577 dean.a.rasheed@gmail     7434                 :              6 :     get_rule_expr(query->mergeJoinCondition, context, false);
                               7435                 :                : 
                               7436                 :                :     /*
                               7437                 :                :      * Test for any NOT MATCHED BY SOURCE actions.  If there are none, then
                               7438                 :                :      * any NOT MATCHED BY TARGET actions are output as "WHEN NOT MATCHED", per
                               7439                 :                :      * SQL standard.  Otherwise, we have a non-SQL-standard query, so output
                               7440                 :                :      * "BY SOURCE" / "BY TARGET" qualifiers for all NOT MATCHED actions, to be
                               7441                 :                :      * more explicit.
                               7442                 :                :      */
                               7443                 :              6 :     haveNotMatchedBySource = false;
                               7444   [ +  -  +  +  :             42 :     foreach(lc, query->mergeActionList)
                                              +  + ]
                               7445                 :                :     {
                               7446                 :             39 :         MergeAction *action = lfirst_node(MergeAction, lc);
                               7447                 :                : 
                               7448         [ +  + ]:             39 :         if (action->matchKind == MERGE_WHEN_NOT_MATCHED_BY_SOURCE)
                               7449                 :                :         {
                               7450                 :              3 :             haveNotMatchedBySource = true;
                               7451                 :              3 :             break;
                               7452                 :                :         }
                               7453                 :                :     }
                               7454                 :                : 
                               7455                 :                :     /* Print each merge action */
  905 tgl@sss.pgh.pa.us        7456   [ +  -  +  +  :             45 :     foreach(lc, query->mergeActionList)
                                              +  + ]
                               7457                 :                :     {
                               7458                 :             39 :         MergeAction *action = lfirst_node(MergeAction, lc);
                               7459                 :                : 
                               7460                 :             39 :         appendContextKeyword(context, " WHEN ",
                               7461                 :                :                              -PRETTYINDENT_STD, PRETTYINDENT_STD, 2);
  577 dean.a.rasheed@gmail     7462   [ +  +  +  - ]:             39 :         switch (action->matchKind)
                               7463                 :                :         {
                               7464                 :             18 :             case MERGE_WHEN_MATCHED:
  566 drowley@postgresql.o     7465                 :             18 :                 appendStringInfoString(buf, "MATCHED");
  577 dean.a.rasheed@gmail     7466                 :             18 :                 break;
                               7467                 :              3 :             case MERGE_WHEN_NOT_MATCHED_BY_SOURCE:
  566 drowley@postgresql.o     7468                 :              3 :                 appendStringInfoString(buf, "NOT MATCHED BY SOURCE");
  577 dean.a.rasheed@gmail     7469                 :              3 :                 break;
                               7470                 :             18 :             case MERGE_WHEN_NOT_MATCHED_BY_TARGET:
                               7471         [ +  + ]:             18 :                 if (haveNotMatchedBySource)
  566 drowley@postgresql.o     7472                 :              3 :                     appendStringInfoString(buf, "NOT MATCHED BY TARGET");
                               7473                 :                :                 else
                               7474                 :             15 :                     appendStringInfoString(buf, "NOT MATCHED");
  577 dean.a.rasheed@gmail     7475                 :             18 :                 break;
  577 dean.a.rasheed@gmail     7476                 :UBC           0 :             default:
                               7477         [ #  # ]:              0 :                 elog(ERROR, "unrecognized matchKind: %d",
                               7478                 :                :                      (int) action->matchKind);
                               7479                 :                :         }
                               7480                 :                : 
  905 tgl@sss.pgh.pa.us        7481         [ +  + ]:CBC          39 :         if (action->qual)
                               7482                 :                :         {
                               7483                 :             24 :             appendContextKeyword(context, " AND ",
                               7484                 :                :                                  -PRETTYINDENT_STD, PRETTYINDENT_STD, 3);
                               7485                 :             24 :             get_rule_expr(action->qual, context, false);
                               7486                 :                :         }
                               7487                 :             39 :         appendContextKeyword(context, " THEN ",
                               7488                 :                :                              -PRETTYINDENT_STD, PRETTYINDENT_STD, 3);
                               7489                 :                : 
                               7490         [ +  + ]:             39 :         if (action->commandType == CMD_INSERT)
                               7491                 :                :         {
                               7492                 :                :             /* This generally matches get_insert_query_def() */
                               7493                 :             18 :             List       *strippedexprs = NIL;
                               7494                 :             18 :             const char *sep = "";
                               7495                 :                :             ListCell   *lc2;
                               7496                 :                : 
                               7497                 :             18 :             appendStringInfoString(buf, "INSERT");
                               7498                 :                : 
                               7499         [ +  + ]:             18 :             if (action->targetList)
                               7500                 :             15 :                 appendStringInfoString(buf, " (");
                               7501   [ +  +  +  +  :             51 :             foreach(lc2, action->targetList)
                                              +  + ]
                               7502                 :                :             {
                               7503                 :             33 :                 TargetEntry *tle = (TargetEntry *) lfirst(lc2);
                               7504                 :                : 
                               7505         [ -  + ]:             33 :                 Assert(!tle->resjunk);
                               7506                 :                : 
                               7507                 :             33 :                 appendStringInfoString(buf, sep);
                               7508                 :             33 :                 sep = ", ";
                               7509                 :                : 
                               7510                 :             33 :                 appendStringInfoString(buf,
                               7511                 :             33 :                                        quote_identifier(get_attname(rte->relid,
                               7512                 :             33 :                                                                     tle->resno,
                               7513                 :                :                                                                     false)));
                               7514                 :             33 :                 strippedexprs = lappend(strippedexprs,
                               7515                 :             33 :                                         processIndirection((Node *) tle->expr,
                               7516                 :                :                                                            context));
                               7517                 :                :             }
                               7518         [ +  + ]:             18 :             if (action->targetList)
                               7519                 :             15 :                 appendStringInfoChar(buf, ')');
                               7520                 :                : 
                               7521         [ +  + ]:             18 :             if (action->override)
                               7522                 :                :             {
                               7523         [ -  + ]:              3 :                 if (action->override == OVERRIDING_SYSTEM_VALUE)
  905 tgl@sss.pgh.pa.us        7524                 :UBC           0 :                     appendStringInfoString(buf, " OVERRIDING SYSTEM VALUE");
  905 tgl@sss.pgh.pa.us        7525         [ +  - ]:CBC           3 :                 else if (action->override == OVERRIDING_USER_VALUE)
                               7526                 :              3 :                     appendStringInfoString(buf, " OVERRIDING USER VALUE");
                               7527                 :                :             }
                               7528                 :                : 
                               7529         [ +  + ]:             18 :             if (strippedexprs)
                               7530                 :                :             {
                               7531                 :             15 :                 appendContextKeyword(context, " VALUES (",
                               7532                 :                :                                      -PRETTYINDENT_STD, PRETTYINDENT_STD, 4);
                               7533                 :             15 :                 get_rule_list_toplevel(strippedexprs, context, false);
                               7534                 :             15 :                 appendStringInfoChar(buf, ')');
                               7535                 :                :             }
                               7536                 :                :             else
                               7537                 :              3 :                 appendStringInfoString(buf, " DEFAULT VALUES");
                               7538                 :                :         }
                               7539         [ +  + ]:             21 :         else if (action->commandType == CMD_UPDATE)
                               7540                 :                :         {
                               7541                 :             12 :             appendStringInfoString(buf, "UPDATE SET ");
                               7542                 :             12 :             get_update_query_targetlist_def(query, action->targetList,
                               7543                 :                :                                             context, rte);
                               7544                 :                :         }
                               7545         [ +  + ]:              9 :         else if (action->commandType == CMD_DELETE)
                               7546                 :              6 :             appendStringInfoString(buf, "DELETE");
                               7547         [ +  - ]:              3 :         else if (action->commandType == CMD_NOTHING)
                               7548                 :              3 :             appendStringInfoString(buf, "DO NOTHING");
                               7549                 :                :     }
                               7550                 :                : 
                               7551                 :                :     /* Add RETURNING if present */
  590 dean.a.rasheed@gmail     7552         [ +  + ]:              6 :     if (query->returningList)
  285                          7553                 :              3 :         get_returning_clause(query, context);
  905 tgl@sss.pgh.pa.us        7554                 :              6 : }
                               7555                 :                : 
                               7556                 :                : 
                               7557                 :                : /* ----------
                               7558                 :                :  * get_utility_query_def            - Parse back a UTILITY parsetree
                               7559                 :                :  * ----------
                               7560                 :                :  */
                               7561                 :                : static void
 9064                          7562                 :              8 : get_utility_query_def(Query *query, deparse_context *context)
                               7563                 :                : {
                               7564                 :              8 :     StringInfo  buf = context->buf;
                               7565                 :                : 
                               7566   [ +  -  +  - ]:              8 :     if (query->utilityStmt && IsA(query->utilityStmt, NotifyStmt))
                               7567                 :              8 :     {
                               7568                 :              8 :         NotifyStmt *stmt = (NotifyStmt *) query->utilityStmt;
                               7569                 :                : 
 8126                          7570                 :              8 :         appendContextKeyword(context, "",
                               7571                 :                :                              0, PRETTYINDENT_STD, 1);
 8621                          7572                 :              8 :         appendStringInfo(buf, "NOTIFY %s",
 6266                          7573                 :              8 :                          quote_identifier(stmt->conditionname));
 5733                          7574         [ -  + ]:              8 :         if (stmt->payload)
                               7575                 :                :         {
 5733 tgl@sss.pgh.pa.us        7576                 :UBC           0 :             appendStringInfoString(buf, ", ");
                               7577                 :              0 :             simple_quote_literal(buf, stmt->payload);
                               7578                 :                :         }
                               7579                 :                :     }
                               7580                 :                :     else
                               7581                 :                :     {
                               7582                 :                :         /* Currently only NOTIFY utility commands can appear in rules */
 8129                          7583         [ #  # ]:              0 :         elog(ERROR, "unexpected utility statement type");
                               7584                 :                :     }
 9064 tgl@sss.pgh.pa.us        7585                 :CBC           8 : }
                               7586                 :                : 
                               7587                 :                : /*
                               7588                 :                :  * Display a Var appropriately.
                               7589                 :                :  *
                               7590                 :                :  * In some cases (currently only when recursing into an unnamed join)
                               7591                 :                :  * the Var's varlevelsup has to be interpreted with respect to a context
                               7592                 :                :  * above the current one; levelsup indicates the offset.
                               7593                 :                :  *
                               7594                 :                :  * If istoplevel is true, the Var is at the top level of a SELECT's
                               7595                 :                :  * targetlist, which means we need special treatment of whole-row Vars.
                               7596                 :                :  * Instead of the normal "tab.*", we'll print "tab.*::typename", which is a
                               7597                 :                :  * dirty hack to prevent "tab.*" from being expanded into multiple columns.
                               7598                 :                :  * (The parser will strip the useless coercion, so no inefficiency is added in
                               7599                 :                :  * dump and reload.)  We used to print just "tab" in such cases, but that is
                               7600                 :                :  * ambiguous and will yield the wrong result if "tab" is also a plain column
                               7601                 :                :  * name in the query.
                               7602                 :                :  *
                               7603                 :                :  * Returns the attname of the Var, or NULL if the Var has no attname (because
                               7604                 :                :  * it is a whole-row Var or a subplan output reference).
                               7605                 :                :  */
                               7606                 :                : static char *
 4932                          7607                 :          94085 : get_variable(Var *var, int levelsup, bool istoplevel, deparse_context *context)
                               7608                 :                : {
 6822                          7609                 :          94085 :     StringInfo  buf = context->buf;
                               7610                 :                :     RangeTblEntry *rte;
                               7611                 :                :     AttrNumber  attnum;
                               7612                 :                :     int         netlevelsup;
                               7613                 :                :     deparse_namespace *dpns;
                               7614                 :                :     int         varno;
                               7615                 :                :     AttrNumber  varattno;
                               7616                 :                :     deparse_columns *colinfo;
                               7617                 :                :     char       *refname;
                               7618                 :                :     char       *attname;
                               7619                 :                :     bool        need_prefix;
                               7620                 :                : 
                               7621                 :                :     /* Find appropriate nesting depth */
 7593                          7622                 :          94085 :     netlevelsup = var->varlevelsup + levelsup;
                               7623         [ -  + ]:          94085 :     if (netlevelsup >= list_length(context->namespaces))
 7593 tgl@sss.pgh.pa.us        7624         [ #  # ]:UBC           0 :         elog(ERROR, "bogus varlevelsup: %d offset %d",
                               7625                 :                :              var->varlevelsup, levelsup);
 7825 tgl@sss.pgh.pa.us        7626                 :CBC       94085 :     dpns = (deparse_namespace *) list_nth(context->namespaces,
                               7627                 :                :                                           netlevelsup);
                               7628                 :                : 
                               7629                 :                :     /*
                               7630                 :                :      * If we have a syntactic referent for the Var, and we're working from a
                               7631                 :                :      * parse tree, prefer to use the syntactic referent.  Otherwise, fall back
                               7632                 :                :      * on the semantic referent.  (Forcing use of the semantic referent when
                               7633                 :                :      * printing plan trees is a design choice that's perhaps more motivated by
                               7634                 :                :      * backwards compatibility than anything else.  But it does have the
                               7635                 :                :      * advantage of making plans more explicit.)
                               7636                 :                :      */
 2119                          7637   [ +  +  +  + ]:          94085 :     if (var->varnosyn > 0 && dpns->plan == NULL)
                               7638                 :                :     {
                               7639                 :          19065 :         varno = var->varnosyn;
                               7640                 :          19065 :         varattno = var->varattnosyn;
                               7641                 :                :     }
                               7642                 :                :     else
                               7643                 :                :     {
                               7644                 :          75020 :         varno = var->varno;
                               7645                 :          75020 :         varattno = var->varattno;
                               7646                 :                :     }
                               7647                 :                : 
                               7648                 :                :     /*
                               7649                 :                :      * Try to find the relevant RTE in this rtable.  In a plan tree, it's
                               7650                 :                :      * likely that varno is OUTER_VAR or INNER_VAR, in which case we must dig
                               7651                 :                :      * down into the subplans, or INDEX_VAR, which is resolved similarly. Also
                               7652                 :                :      * find the aliases previously assigned for this RTE.
                               7653                 :                :      */
                               7654   [ +  +  +  - ]:          94085 :     if (varno >= 1 && varno <= list_length(dpns->rtable))
                               7655                 :                :     {
                               7656                 :                :         /*
                               7657                 :                :          * We might have been asked to map child Vars to some parent relation.
                               7658                 :                :          */
 2148                          7659   [ +  +  +  + ]:          68620 :         if (context->appendparents && dpns->appendrels)
                               7660                 :                :         {
 1504                          7661                 :           1914 :             int         pvarno = varno;
 2148                          7662                 :           1914 :             AttrNumber  pvarattno = varattno;
                               7663                 :           1914 :             AppendRelInfo *appinfo = dpns->appendrels[pvarno];
                               7664                 :           1914 :             bool        found = false;
                               7665                 :                : 
                               7666                 :                :             /* Only map up to inheritance parents, not UNION ALL appendrels */
                               7667         [ +  + ]:           3865 :             while (appinfo &&
                               7668                 :           2126 :                    rt_fetch(appinfo->parent_relid,
                               7669         [ +  + ]:           2126 :                             dpns->rtable)->rtekind == RTE_RELATION)
                               7670                 :                :             {
                               7671                 :           1951 :                 found = false;
                               7672         [ +  + ]:           1951 :                 if (pvarattno > 0)   /* system columns stay as-is */
                               7673                 :                :                 {
                               7674         [ -  + ]:           1812 :                     if (pvarattno > appinfo->num_child_cols)
 2148 tgl@sss.pgh.pa.us        7675                 :UBC           0 :                         break;  /* safety check */
 2148 tgl@sss.pgh.pa.us        7676                 :CBC        1812 :                     pvarattno = appinfo->parent_colnos[pvarattno - 1];
                               7677         [ -  + ]:           1812 :                     if (pvarattno == 0)
 2148 tgl@sss.pgh.pa.us        7678                 :UBC           0 :                         break;  /* Var is local to child */
                               7679                 :                :                 }
                               7680                 :                : 
 2148 tgl@sss.pgh.pa.us        7681                 :CBC        1951 :                 pvarno = appinfo->parent_relid;
                               7682                 :           1951 :                 found = true;
                               7683                 :                : 
                               7684                 :                :                 /* If the parent is itself a child, continue up. */
                               7685   [ +  -  -  + ]:           1951 :                 Assert(pvarno > 0 && pvarno <= list_length(dpns->rtable));
                               7686                 :           1951 :                 appinfo = dpns->appendrels[pvarno];
                               7687                 :                :             }
                               7688                 :                : 
                               7689                 :                :             /*
                               7690                 :                :              * If we found an ancestral rel, and that rel is included in
                               7691                 :                :              * appendparents, print that column not the original one.
                               7692                 :                :              */
                               7693   [ +  +  +  + ]:           1914 :             if (found && bms_is_member(pvarno, context->appendparents))
                               7694                 :                :             {
                               7695                 :           1556 :                 varno = pvarno;
                               7696                 :           1556 :                 varattno = pvarattno;
                               7697                 :                :             }
                               7698                 :                :         }
                               7699                 :                : 
                               7700                 :          68620 :         rte = rt_fetch(varno, dpns->rtable);
                               7701                 :                : 
                               7702                 :                :         /* might be returning old/new column value */
  285 dean.a.rasheed@gmail     7703         [ +  + ]:          68620 :         if (var->varreturningtype == VAR_RETURNING_OLD)
                               7704                 :            208 :             refname = dpns->ret_old_alias;
                               7705         [ +  + ]:          68412 :         else if (var->varreturningtype == VAR_RETURNING_NEW)
                               7706                 :            207 :             refname = dpns->ret_new_alias;
                               7707                 :                :         else
                               7708                 :          68205 :             refname = (char *) list_nth(dpns->rtable_names, varno - 1);
                               7709                 :                : 
 2148 tgl@sss.pgh.pa.us        7710                 :          68620 :         colinfo = deparse_columns_fetch(varno, dpns);
                               7711                 :          68620 :         attnum = varattno;
                               7712                 :                :     }
                               7713                 :                :     else
                               7714                 :                :     {
                               7715                 :          25465 :         resolve_special_varno((Node *) var, context,
                               7716                 :                :                               get_special_variable, NULL);
 3471 rhaas@postgresql.org     7717                 :          25465 :         return NULL;
                               7718                 :                :     }
                               7719                 :                : 
                               7720                 :                :     /*
                               7721                 :                :      * The planner will sometimes emit Vars referencing resjunk elements of a
                               7722                 :                :      * subquery's target list (this is currently only possible if it chooses
                               7723                 :                :      * to generate a "physical tlist" for a SubqueryScan or CteScan node).
                               7724                 :                :      * Although we prefer to print subquery-referencing Vars using the
                               7725                 :                :      * subquery's alias, that's not possible for resjunk items since they have
                               7726                 :                :      * no alias.  So in that case, drill down to the subplan and print the
                               7727                 :                :      * contents of the referenced tlist item.  This works because in a plan
                               7728                 :                :      * tree, such Vars can only occur in a SubqueryScan or CteScan node, and
                               7729                 :                :      * we'll have set dpns->inner_plan to reference the child plan node.
                               7730                 :                :      */
 5590 tgl@sss.pgh.pa.us        7731   [ +  +  +  +  :          70776 :     if ((rte->rtekind == RTE_SUBQUERY || rte->rtekind == RTE_CTE) &&
                                              +  + ]
                               7732                 :           2156 :         attnum > list_length(rte->eref->colnames) &&
 2148                          7733         [ +  - ]:              1 :         dpns->inner_plan)
                               7734                 :                :     {
                               7735                 :                :         TargetEntry *tle;
                               7736                 :                :         deparse_namespace save_dpns;
                               7737                 :                : 
                               7738                 :              1 :         tle = get_tle_by_resno(dpns->inner_tlist, attnum);
 5590                          7739         [ -  + ]:              1 :         if (!tle)
 3406 tgl@sss.pgh.pa.us        7740         [ #  # ]:UBC           0 :             elog(ERROR, "invalid attnum %d for relation \"%s\"",
                               7741                 :                :                  attnum, rte->eref->aliasname);
                               7742                 :                : 
 5590 tgl@sss.pgh.pa.us        7743         [ -  + ]:CBC           1 :         Assert(netlevelsup == 0);
 2148                          7744                 :              1 :         push_child_plan(dpns, dpns->inner_plan, &save_dpns);
                               7745                 :                : 
                               7746                 :                :         /*
                               7747                 :                :          * Force parentheses because our caller probably assumed a Var is a
                               7748                 :                :          * simple expression.
                               7749                 :                :          */
 5590                          7750         [ -  + ]:              1 :         if (!IsA(tle->expr, Var))
 5590 tgl@sss.pgh.pa.us        7751                 :UBC           0 :             appendStringInfoChar(buf, '(');
 5590 tgl@sss.pgh.pa.us        7752                 :CBC           1 :         get_rule_expr((Node *) tle->expr, context, true);
                               7753         [ -  + ]:              1 :         if (!IsA(tle->expr, Var))
 5590 tgl@sss.pgh.pa.us        7754                 :UBC           0 :             appendStringInfoChar(buf, ')');
                               7755                 :                : 
 5586 tgl@sss.pgh.pa.us        7756                 :CBC           1 :         pop_child_plan(dpns, &save_dpns);
 5590                          7757                 :              1 :         return NULL;
                               7758                 :                :     }
                               7759                 :                : 
                               7760                 :                :     /*
                               7761                 :                :      * If it's an unnamed join, look at the expansion of the alias variable.
                               7762                 :                :      * If it's a simple reference to one of the input vars, then recursively
                               7763                 :                :      * print the name of that var instead.  When it's not a simple reference,
                               7764                 :                :      * we have to just print the unqualified join column name.  (This can only
                               7765                 :                :      * happen with "dangerous" merged columns in a JOIN USING; we took pains
                               7766                 :                :      * previously to make the unqualified column name unique in such cases.)
                               7767                 :                :      *
                               7768                 :                :      * This wouldn't work in decompiling plan trees, because we don't store
                               7769                 :                :      * joinaliasvars lists after planning; but a plan tree should never
                               7770                 :                :      * contain a join alias variable.
                               7771                 :                :      */
 4785                          7772   [ +  +  +  + ]:          68619 :     if (rte->rtekind == RTE_JOIN && rte->alias == NULL)
                               7773                 :                :     {
                               7774         [ -  + ]:             48 :         if (rte->joinaliasvars == NIL)
 4785 tgl@sss.pgh.pa.us        7775         [ #  # ]:UBC           0 :             elog(ERROR, "cannot decompile join alias var in plan tree");
 4785 tgl@sss.pgh.pa.us        7776         [ +  - ]:CBC          48 :         if (attnum > 0)
                               7777                 :                :         {
                               7778                 :                :             Var        *aliasvar;
                               7779                 :                : 
                               7780                 :             48 :             aliasvar = (Var *) list_nth(rte->joinaliasvars, attnum - 1);
                               7781                 :                :             /* we intentionally don't strip implicit coercions here */
 4480                          7782   [ +  -  -  + ]:             48 :             if (aliasvar && IsA(aliasvar, Var))
                               7783                 :                :             {
 4785 tgl@sss.pgh.pa.us        7784                 :UBC           0 :                 return get_variable(aliasvar, var->varlevelsup + levelsup,
                               7785                 :                :                                     istoplevel, context);
                               7786                 :                :             }
                               7787                 :                :         }
                               7788                 :                : 
                               7789                 :                :         /*
                               7790                 :                :          * Unnamed join has no refname.  (Note: since it's unnamed, there is
                               7791                 :                :          * no way the user could have referenced it to create a whole-row Var
                               7792                 :                :          * for it.  So we don't have to cover that case below.)
                               7793                 :                :          */
 4785 tgl@sss.pgh.pa.us        7794         [ -  + ]:CBC          48 :         Assert(refname == NULL);
                               7795                 :                :     }
                               7796                 :                : 
 7143                          7797         [ +  + ]:          68619 :     if (attnum == InvalidAttrNumber)
 6822                          7798                 :            507 :         attname = NULL;
 4684                          7799         [ +  + ]:          68112 :     else if (attnum > 0)
                               7800                 :                :     {
                               7801                 :                :         /* Get column name to use from the colinfo struct */
 3406                          7802         [ -  + ]:          67173 :         if (attnum > colinfo->num_cols)
 3406 tgl@sss.pgh.pa.us        7803         [ #  # ]:UBC           0 :             elog(ERROR, "invalid attnum %d for relation \"%s\"",
                               7804                 :                :                  attnum, rte->eref->aliasname);
 4684 tgl@sss.pgh.pa.us        7805                 :CBC       67173 :         attname = colinfo->colnames[attnum - 1];
                               7806                 :                : 
                               7807                 :                :         /*
                               7808                 :                :          * If we find a Var referencing a dropped column, it seems better to
                               7809                 :                :          * print something (anything) than to fail.  In general this should
                               7810                 :                :          * not happen, but it used to be possible for some cases involving
                               7811                 :                :          * functions returning named composite types, and perhaps there are
                               7812                 :                :          * still bugs out there.
                               7813                 :                :          */
 1195                          7814         [ +  + ]:          67173 :         if (attname == NULL)
                               7815                 :              3 :             attname = "?dropped?column?";
                               7816                 :                :     }
                               7817                 :                :     else
                               7818                 :                :     {
                               7819                 :                :         /* System column - name is fixed, get it from the catalog */
 6822                          7820                 :            939 :         attname = get_rte_attribute_name(rte, attnum);
                               7821                 :                :     }
                               7822                 :                : 
  285 dean.a.rasheed@gmail     7823   [ +  +  +  + ]:         100889 :     need_prefix = (context->varprefix || attname == NULL ||
                               7824         [ +  + ]:          32270 :                    var->varreturningtype != VAR_RETURNING_DEFAULT);
                               7825                 :                : 
                               7826                 :                :     /*
                               7827                 :                :      * If we're considering a plain Var in an ORDER BY (but not GROUP BY)
                               7828                 :                :      * clause, we may need to add a table-name prefix to prevent
                               7829                 :                :      * findTargetlistEntrySQL92 from misinterpreting the name as an
                               7830                 :                :      * output-column name.  To avoid cluttering the output with unnecessary
                               7831                 :                :      * prefixes, do so only if there is a name match to a SELECT tlist item
                               7832                 :                :      * that is different from the Var.
                               7833                 :                :      */
  425 tgl@sss.pgh.pa.us        7834   [ +  +  +  +  :          68619 :     if (context->varInOrderBy && !context->inGroupBy && !need_prefix)
                                              +  + ]
                               7835                 :                :     {
                               7836                 :            123 :         int         colno = 0;
                               7837                 :                : 
                               7838   [ +  +  +  +  :            482 :         foreach_node(TargetEntry, tle, context->targetList)
                                              +  + ]
                               7839                 :                :         {
                               7840                 :                :             char       *colname;
                               7841                 :                : 
                               7842         [ -  + ]:            242 :             if (tle->resjunk)
  425 tgl@sss.pgh.pa.us        7843                 :UBC           0 :                 continue;       /* ignore junk entries */
  425 tgl@sss.pgh.pa.us        7844                 :CBC         242 :             colno++;
                               7845                 :                : 
                               7846                 :                :             /* This must match colname-choosing logic in get_target_list() */
                               7847   [ +  -  +  - ]:            242 :             if (context->resultDesc && colno <= context->resultDesc->natts)
                               7848                 :            242 :                 colname = NameStr(TupleDescAttr(context->resultDesc,
                               7849                 :                :                                                 colno - 1)->attname);
                               7850                 :                :             else
  425 tgl@sss.pgh.pa.us        7851                 :UBC           0 :                 colname = tle->resname;
                               7852                 :                : 
  425 tgl@sss.pgh.pa.us        7853   [ +  -  +  + ]:CBC         242 :             if (colname && strcmp(colname, attname) == 0 &&
                               7854         [ +  + ]:             87 :                 !equal(var, tle->expr))
                               7855                 :                :             {
                               7856                 :              6 :                 need_prefix = true;
                               7857                 :              6 :                 break;
                               7858                 :                :             }
                               7859                 :                :         }
                               7860                 :                :     }
                               7861                 :                : 
                               7862   [ +  +  +  + ]:          68619 :     if (refname && need_prefix)
                               7863                 :                :     {
 5836                          7864                 :          36321 :         appendStringInfoString(buf, quote_identifier(refname));
 4932                          7865                 :          36321 :         appendStringInfoChar(buf, '.');
                               7866                 :                :     }
 6822                          7867         [ +  + ]:          68619 :     if (attname)
                               7868                 :          68112 :         appendStringInfoString(buf, quote_identifier(attname));
                               7869                 :                :     else
                               7870                 :                :     {
                               7871                 :            507 :         appendStringInfoChar(buf, '*');
 4932                          7872         [ +  + ]:            507 :         if (istoplevel)
                               7873                 :             42 :             appendStringInfo(buf, "::%s",
                               7874                 :                :                              format_type_with_typemod(var->vartype,
                               7875                 :                :                                                       var->vartypmod));
                               7876                 :                :     }
                               7877                 :                : 
 6822                          7878                 :          68619 :     return attname;
                               7879                 :                : }
                               7880                 :                : 
                               7881                 :                : /*
                               7882                 :                :  * Deparse a Var which references OUTER_VAR, INNER_VAR, or INDEX_VAR.  This
                               7883                 :                :  * routine is actually a callback for resolve_special_varno, which handles
                               7884                 :                :  * finding the correct TargetEntry.  We get the expression contained in that
                               7885                 :                :  * TargetEntry and just need to deparse it, a job we can throw back on
                               7886                 :                :  * get_rule_expr.
                               7887                 :                :  */
                               7888                 :                : static void
 2148                          7889                 :          25465 : get_special_variable(Node *node, deparse_context *context, void *callback_arg)
                               7890                 :                : {
 3471 rhaas@postgresql.org     7891                 :          25465 :     StringInfo  buf = context->buf;
                               7892                 :                : 
                               7893                 :                :     /*
                               7894                 :                :      * For a non-Var referent, force parentheses because our caller probably
                               7895                 :                :      * assumed a Var is a simple expression.
                               7896                 :                :      */
                               7897         [ +  + ]:          25465 :     if (!IsA(node, Var))
                               7898                 :           2546 :         appendStringInfoChar(buf, '(');
                               7899                 :          25465 :     get_rule_expr(node, context, true);
                               7900         [ +  + ]:          25465 :     if (!IsA(node, Var))
                               7901                 :           2546 :         appendStringInfoChar(buf, ')');
                               7902                 :          25465 : }
                               7903                 :                : 
                               7904                 :                : /*
                               7905                 :                :  * Chase through plan references to special varnos (OUTER_VAR, INNER_VAR,
                               7906                 :                :  * INDEX_VAR) until we find a real Var or some kind of non-Var node; then,
                               7907                 :                :  * invoke the callback provided.
                               7908                 :                :  */
                               7909                 :                : static void
 2148 tgl@sss.pgh.pa.us        7910                 :          71807 : resolve_special_varno(Node *node, deparse_context *context,
                               7911                 :                :                       rsv_callback callback, void *callback_arg)
                               7912                 :                : {
                               7913                 :                :     Var        *var;
                               7914                 :                :     deparse_namespace *dpns;
                               7915                 :                : 
                               7916                 :                :     /* This function is recursive, so let's be paranoid. */
                               7917                 :          71807 :     check_stack_depth();
                               7918                 :                : 
                               7919                 :                :     /* If it's not a Var, invoke the callback. */
 3471 rhaas@postgresql.org     7920         [ +  + ]:          71807 :     if (!IsA(node, Var))
                               7921                 :                :     {
 2148 tgl@sss.pgh.pa.us        7922                 :           2934 :         (*callback) (node, context, callback_arg);
 3471 rhaas@postgresql.org     7923                 :           2934 :         return;
                               7924                 :                :     }
                               7925                 :                : 
                               7926                 :                :     /* Find appropriate nesting depth */
                               7927                 :          68873 :     var = (Var *) node;
                               7928                 :          68873 :     dpns = (deparse_namespace *) list_nth(context->namespaces,
                               7929                 :          68873 :                                           var->varlevelsup);
                               7930                 :                : 
                               7931                 :                :     /*
                               7932                 :                :      * If varno is special, recurse.  (Don't worry about varnosyn; if we're
                               7933                 :                :      * here, we already decided not to use that.)
                               7934                 :                :      */
                               7935   [ +  +  +  - ]:          68873 :     if (var->varno == OUTER_VAR && dpns->outer_tlist)
                               7936                 :                :     {
                               7937                 :                :         TargetEntry *tle;
                               7938                 :                :         deparse_namespace save_dpns;
                               7939                 :                :         Bitmapset  *save_appendparents;
                               7940                 :                : 
                               7941                 :          34695 :         tle = get_tle_by_resno(dpns->outer_tlist, var->varattno);
                               7942         [ -  + ]:          34695 :         if (!tle)
 3471 rhaas@postgresql.org     7943         [ #  # ]:UBC           0 :             elog(ERROR, "bogus varattno for OUTER_VAR var: %d", var->varattno);
                               7944                 :                : 
                               7945                 :                :         /*
                               7946                 :                :          * If we're descending to the first child of an Append or MergeAppend,
                               7947                 :                :          * update appendparents.  This will affect deparsing of all Vars
                               7948                 :                :          * appearing within the eventually-resolved subexpression.
                               7949                 :                :          */
 2148 tgl@sss.pgh.pa.us        7950                 :CBC       34695 :         save_appendparents = context->appendparents;
                               7951                 :                : 
                               7952         [ +  + ]:          34695 :         if (IsA(dpns->plan, Append))
                               7953                 :           2246 :             context->appendparents = bms_union(context->appendparents,
                               7954                 :           2246 :                                                ((Append *) dpns->plan)->apprelids);
                               7955         [ +  + ]:          32449 :         else if (IsA(dpns->plan, MergeAppend))
                               7956                 :            304 :             context->appendparents = bms_union(context->appendparents,
                               7957                 :            304 :                                                ((MergeAppend *) dpns->plan)->apprelids);
                               7958                 :                : 
                               7959                 :          34695 :         push_child_plan(dpns, dpns->outer_plan, &save_dpns);
                               7960                 :          34695 :         resolve_special_varno((Node *) tle->expr, context,
                               7961                 :                :                               callback, callback_arg);
 3471 rhaas@postgresql.org     7962                 :          34695 :         pop_child_plan(dpns, &save_dpns);
 2148 tgl@sss.pgh.pa.us        7963                 :          34695 :         context->appendparents = save_appendparents;
 3471 rhaas@postgresql.org     7964                 :          34695 :         return;
                               7965                 :                :     }
                               7966   [ +  +  +  - ]:          34178 :     else if (var->varno == INNER_VAR && dpns->inner_tlist)
                               7967                 :                :     {
                               7968                 :                :         TargetEntry *tle;
                               7969                 :                :         deparse_namespace save_dpns;
                               7970                 :                : 
                               7971                 :           8482 :         tle = get_tle_by_resno(dpns->inner_tlist, var->varattno);
                               7972         [ -  + ]:           8482 :         if (!tle)
 3471 rhaas@postgresql.org     7973         [ #  # ]:UBC           0 :             elog(ERROR, "bogus varattno for INNER_VAR var: %d", var->varattno);
                               7974                 :                : 
 2148 tgl@sss.pgh.pa.us        7975                 :CBC        8482 :         push_child_plan(dpns, dpns->inner_plan, &save_dpns);
                               7976                 :           8482 :         resolve_special_varno((Node *) tle->expr, context,
                               7977                 :                :                               callback, callback_arg);
 3471 rhaas@postgresql.org     7978                 :           8482 :         pop_child_plan(dpns, &save_dpns);
                               7979                 :           8482 :         return;
                               7980                 :                :     }
                               7981   [ +  +  +  - ]:          25696 :     else if (var->varno == INDEX_VAR && dpns->index_tlist)
                               7982                 :                :     {
                               7983                 :                :         TargetEntry *tle;
                               7984                 :                : 
                               7985                 :           2777 :         tle = get_tle_by_resno(dpns->index_tlist, var->varattno);
                               7986         [ -  + ]:           2777 :         if (!tle)
 3471 rhaas@postgresql.org     7987         [ #  # ]:UBC           0 :             elog(ERROR, "bogus varattno for INDEX_VAR var: %d", var->varattno);
                               7988                 :                : 
 2148 tgl@sss.pgh.pa.us        7989                 :CBC        2777 :         resolve_special_varno((Node *) tle->expr, context,
                               7990                 :                :                               callback, callback_arg);
 3471 rhaas@postgresql.org     7991                 :           2777 :         return;
                               7992                 :                :     }
                               7993   [ +  -  -  + ]:          22919 :     else if (var->varno < 1 || var->varno > list_length(dpns->rtable))
 3471 rhaas@postgresql.org     7994         [ #  # ]:UBC           0 :         elog(ERROR, "bogus varno: %d", var->varno);
                               7995                 :                : 
                               7996                 :                :     /* Not special.  Just invoke the callback. */
 2148 tgl@sss.pgh.pa.us        7997                 :CBC       22919 :     (*callback) (node, context, callback_arg);
                               7998                 :                : }
                               7999                 :                : 
                               8000                 :                : /*
                               8001                 :                :  * Get the name of a field of an expression of composite type.  The
                               8002                 :                :  * expression is usually a Var, but we handle other cases too.
                               8003                 :                :  *
                               8004                 :                :  * levelsup is an extra offset to interpret the Var's varlevelsup correctly.
                               8005                 :                :  *
                               8006                 :                :  * This is fairly straightforward when the expression has a named composite
                               8007                 :                :  * type; we need only look up the type in the catalogs.  However, the type
                               8008                 :                :  * could also be RECORD.  Since no actual table or view column is allowed to
                               8009                 :                :  * have type RECORD, a Var of type RECORD must refer to a JOIN or FUNCTION RTE
                               8010                 :                :  * or to a subquery output.  We drill down to find the ultimate defining
                               8011                 :                :  * expression and attempt to infer the field name from it.  We ereport if we
                               8012                 :                :  * can't determine the name.
                               8013                 :                :  *
                               8014                 :                :  * Similarly, a PARAM of type RECORD has to refer to some expression of
                               8015                 :                :  * a determinable composite type.
                               8016                 :                :  */
                               8017                 :                : static const char *
 7455                          8018                 :            670 : get_name_for_var_field(Var *var, int fieldno,
                               8019                 :                :                        int levelsup, deparse_context *context)
                               8020                 :                : {
                               8021                 :                :     RangeTblEntry *rte;
                               8022                 :                :     AttrNumber  attnum;
                               8023                 :                :     int         netlevelsup;
                               8024                 :                :     deparse_namespace *dpns;
                               8025                 :                :     int         varno;
                               8026                 :                :     AttrNumber  varattno;
                               8027                 :                :     TupleDesc   tupleDesc;
                               8028                 :                :     Node       *expr;
                               8029                 :                : 
                               8030                 :                :     /*
                               8031                 :                :      * If it's a RowExpr that was expanded from a whole-row Var, use the
                               8032                 :                :      * column names attached to it.  (We could let get_expr_result_tupdesc()
                               8033                 :                :      * handle this, but it's much cheaper to just pull out the name we need.)
                               8034                 :                :      */
 6231                          8035         [ +  + ]:            670 :     if (IsA(var, RowExpr))
                               8036                 :                :     {
 5983 bruce@momjian.us         8037                 :             18 :         RowExpr    *r = (RowExpr *) var;
                               8038                 :                : 
 6231 tgl@sss.pgh.pa.us        8039   [ +  -  +  - ]:             18 :         if (fieldno > 0 && fieldno <= list_length(r->colnames))
                               8040                 :             18 :             return strVal(list_nth(r->colnames, fieldno - 1));
                               8041                 :                :     }
                               8042                 :                : 
                               8043                 :                :     /*
                               8044                 :                :      * If it's a Param of type RECORD, try to find what the Param refers to.
                               8045                 :                :      */
 5165                          8046         [ +  + ]:            652 :     if (IsA(var, Param))
                               8047                 :                :     {
                               8048                 :              9 :         Param      *param = (Param *) var;
                               8049                 :                :         ListCell   *ancestor_cell;
                               8050                 :                : 
                               8051                 :              9 :         expr = find_param_referent(param, context, &dpns, &ancestor_cell);
                               8052         [ +  - ]:              9 :         if (expr)
                               8053                 :                :         {
                               8054                 :                :             /* Found a match, so recurse to decipher the field name */
                               8055                 :                :             deparse_namespace save_dpns;
                               8056                 :                :             const char *result;
                               8057                 :                : 
                               8058                 :              9 :             push_ancestor_plan(dpns, ancestor_cell, &save_dpns);
                               8059                 :              9 :             result = get_name_for_var_field((Var *) expr, fieldno,
                               8060                 :                :                                             0, context);
                               8061                 :              9 :             pop_ancestor_plan(dpns, &save_dpns);
                               8062                 :              9 :             return result;
                               8063                 :                :         }
                               8064                 :                :     }
                               8065                 :                : 
                               8066                 :                :     /*
                               8067                 :                :      * If it's a Var of type RECORD, we have to find what the Var refers to;
                               8068                 :                :      * if not, we can use get_expr_result_tupdesc().
                               8069                 :                :      */
 6822                          8070         [ +  + ]:            643 :     if (!IsA(var, Var) ||
                               8071         [ +  + ]:            603 :         var->vartype != RECORDOID)
                               8072                 :                :     {
 2924                          8073                 :            520 :         tupleDesc = get_expr_result_tupdesc((Node *) var, false);
                               8074                 :                :         /* Got the tupdesc, so we can extract the field name */
 6822                          8075   [ +  -  -  + ]:            520 :         Assert(fieldno >= 1 && fieldno <= tupleDesc->natts);
 2991 andres@anarazel.de       8076                 :            520 :         return NameStr(TupleDescAttr(tupleDesc, fieldno - 1)->attname);
                               8077                 :                :     }
                               8078                 :                : 
                               8079                 :                :     /* Find appropriate nesting depth */
 6822 tgl@sss.pgh.pa.us        8080                 :            123 :     netlevelsup = var->varlevelsup + levelsup;
                               8081         [ -  + ]:            123 :     if (netlevelsup >= list_length(context->namespaces))
 6822 tgl@sss.pgh.pa.us        8082         [ #  # ]:UBC           0 :         elog(ERROR, "bogus varlevelsup: %d offset %d",
                               8083                 :                :              var->varlevelsup, levelsup);
 6822 tgl@sss.pgh.pa.us        8084                 :CBC         123 :     dpns = (deparse_namespace *) list_nth(context->namespaces,
                               8085                 :                :                                           netlevelsup);
                               8086                 :                : 
                               8087                 :                :     /*
                               8088                 :                :      * If we have a syntactic referent for the Var, and we're working from a
                               8089                 :                :      * parse tree, prefer to use the syntactic referent.  Otherwise, fall back
                               8090                 :                :      * on the semantic referent.  (See comments in get_variable().)
                               8091                 :                :      */
 2119                          8092   [ +  +  +  + ]:            123 :     if (var->varnosyn > 0 && dpns->plan == NULL)
                               8093                 :                :     {
                               8094                 :             48 :         varno = var->varnosyn;
                               8095                 :             48 :         varattno = var->varattnosyn;
                               8096                 :                :     }
                               8097                 :                :     else
                               8098                 :                :     {
                               8099                 :             75 :         varno = var->varno;
                               8100                 :             75 :         varattno = var->varattno;
                               8101                 :                :     }
                               8102                 :                : 
                               8103                 :                :     /*
                               8104                 :                :      * Try to find the relevant RTE in this rtable.  In a plan tree, it's
                               8105                 :                :      * likely that varno is OUTER_VAR or INNER_VAR, in which case we must dig
                               8106                 :                :      * down into the subplans, or INDEX_VAR, which is resolved similarly.
                               8107                 :                :      *
                               8108                 :                :      * Note: unlike get_variable and resolve_special_varno, we need not worry
                               8109                 :                :      * about inheritance mapping: a child Var should have the same datatype as
                               8110                 :                :      * its parent, and here we're really only interested in the Var's type.
                               8111                 :                :      */
                               8112   [ +  +  +  - ]:            123 :     if (varno >= 1 && varno <= list_length(dpns->rtable))
                               8113                 :                :     {
                               8114                 :             84 :         rte = rt_fetch(varno, dpns->rtable);
                               8115                 :             84 :         attnum = varattno;
                               8116                 :                :     }
                               8117   [ +  +  +  - ]:             39 :     else if (varno == OUTER_VAR && dpns->outer_tlist)
                               8118                 :                :     {
                               8119                 :                :         TargetEntry *tle;
                               8120                 :                :         deparse_namespace save_dpns;
                               8121                 :                :         const char *result;
                               8122                 :                : 
                               8123                 :             30 :         tle = get_tle_by_resno(dpns->outer_tlist, varattno);
 6822                          8124         [ -  + ]:             30 :         if (!tle)
 2119 tgl@sss.pgh.pa.us        8125         [ #  # ]:UBC           0 :             elog(ERROR, "bogus varattno for OUTER_VAR var: %d", varattno);
                               8126                 :                : 
 6822 tgl@sss.pgh.pa.us        8127         [ -  + ]:CBC          30 :         Assert(netlevelsup == 0);
 2148                          8128                 :             30 :         push_child_plan(dpns, dpns->outer_plan, &save_dpns);
                               8129                 :                : 
 6822                          8130                 :             30 :         result = get_name_for_var_field((Var *) tle->expr, fieldno,
                               8131                 :                :                                         levelsup, context);
                               8132                 :                : 
 5586                          8133                 :             30 :         pop_child_plan(dpns, &save_dpns);
 6822                          8134                 :             30 :         return result;
                               8135                 :                :     }
 2119                          8136   [ +  -  +  - ]:              9 :     else if (varno == INNER_VAR && dpns->inner_tlist)
                               8137                 :                :     {
                               8138                 :                :         TargetEntry *tle;
                               8139                 :                :         deparse_namespace save_dpns;
                               8140                 :                :         const char *result;
                               8141                 :                : 
                               8142                 :              9 :         tle = get_tle_by_resno(dpns->inner_tlist, varattno);
 6822                          8143         [ -  + ]:              9 :         if (!tle)
 2119 tgl@sss.pgh.pa.us        8144         [ #  # ]:UBC           0 :             elog(ERROR, "bogus varattno for INNER_VAR var: %d", varattno);
                               8145                 :                : 
 6822 tgl@sss.pgh.pa.us        8146         [ -  + ]:CBC           9 :         Assert(netlevelsup == 0);
 2148                          8147                 :              9 :         push_child_plan(dpns, dpns->inner_plan, &save_dpns);
                               8148                 :                : 
 6822                          8149                 :              9 :         result = get_name_for_var_field((Var *) tle->expr, fieldno,
                               8150                 :                :                                         levelsup, context);
                               8151                 :                : 
 5586                          8152                 :              9 :         pop_child_plan(dpns, &save_dpns);
 6822                          8153                 :              9 :         return result;
                               8154                 :                :     }
 2119 tgl@sss.pgh.pa.us        8155   [ #  #  #  # ]:UBC           0 :     else if (varno == INDEX_VAR && dpns->index_tlist)
                               8156                 :                :     {
                               8157                 :                :         TargetEntry *tle;
                               8158                 :                :         const char *result;
                               8159                 :                : 
                               8160                 :              0 :         tle = get_tle_by_resno(dpns->index_tlist, varattno);
 5131                          8161         [ #  # ]:              0 :         if (!tle)
 2119                          8162         [ #  # ]:              0 :             elog(ERROR, "bogus varattno for INDEX_VAR var: %d", varattno);
                               8163                 :                : 
 5131                          8164         [ #  # ]:              0 :         Assert(netlevelsup == 0);
                               8165                 :                : 
                               8166                 :              0 :         result = get_name_for_var_field((Var *) tle->expr, fieldno,
                               8167                 :                :                                         levelsup, context);
                               8168                 :                : 
                               8169                 :              0 :         return result;
                               8170                 :                :     }
                               8171                 :                :     else
                               8172                 :                :     {
 2119                          8173         [ #  # ]:              0 :         elog(ERROR, "bogus varno: %d", varno);
                               8174                 :                :         return NULL;            /* keep compiler quiet */
                               8175                 :                :     }
                               8176                 :                : 
 7455 tgl@sss.pgh.pa.us        8177         [ +  + ]:CBC          84 :     if (attnum == InvalidAttrNumber)
                               8178                 :                :     {
                               8179                 :                :         /* Var is whole-row reference to RTE, so select the right field */
                               8180                 :             12 :         return get_rte_attribute_name(rte, fieldno);
                               8181                 :                :     }
                               8182                 :                : 
                               8183                 :                :     /*
                               8184                 :                :      * This part has essentially the same logic as the parser's
                               8185                 :                :      * expandRecordVariable() function, but we are dealing with a different
                               8186                 :                :      * representation of the input context, and we only need one field name
                               8187                 :                :      * not a TupleDesc.  Also, we need special cases for finding subquery and
                               8188                 :                :      * CTE subplans when deparsing Plan trees.
                               8189                 :                :      */
                               8190                 :             72 :     expr = (Node *) var;        /* default if we can't drill down */
                               8191                 :                : 
                               8192   [ -  +  -  -  :             72 :     switch (rte->rtekind)
                                           +  -  - ]
                               8193                 :                :     {
 7455 tgl@sss.pgh.pa.us        8194                 :UBC           0 :         case RTE_RELATION:
                               8195                 :                :         case RTE_VALUES:
                               8196                 :                :         case RTE_NAMEDTUPLESTORE:
                               8197                 :                :         case RTE_RESULT:
                               8198                 :                : 
                               8199                 :                :             /*
                               8200                 :                :              * This case should not occur: a column of a table, values list,
                               8201                 :                :              * or ENR shouldn't have type RECORD.  Fall through and fail (most
                               8202                 :                :              * likely) at the bottom.
                               8203                 :                :              */
                               8204                 :              0 :             break;
 7455 tgl@sss.pgh.pa.us        8205                 :CBC          36 :         case RTE_SUBQUERY:
                               8206                 :                :             /* Subselect-in-FROM: examine sub-select's output expr */
                               8207                 :                :             {
 6822                          8208         [ +  + ]:             36 :                 if (rte->subquery)
                               8209                 :                :                 {
                               8210                 :             21 :                     TargetEntry *ste = get_tle_by_resno(rte->subquery->targetList,
                               8211                 :                :                                                         attnum);
                               8212                 :                : 
                               8213   [ +  -  -  + ]:             21 :                     if (ste == NULL || ste->resjunk)
 6822 tgl@sss.pgh.pa.us        8214         [ #  # ]:UBC           0 :                         elog(ERROR, "subquery %s does not have attribute %d",
                               8215                 :                :                              rte->eref->aliasname, attnum);
 6822 tgl@sss.pgh.pa.us        8216                 :CBC          21 :                     expr = (Node *) ste->expr;
                               8217         [ +  + ]:             21 :                     if (IsA(expr, Var))
                               8218                 :                :                     {
                               8219                 :                :                         /*
                               8220                 :                :                          * Recurse into the sub-select to see what its Var
                               8221                 :                :                          * refers to. We have to build an additional level of
                               8222                 :                :                          * namespace to keep in step with varlevelsup in the
                               8223                 :                :                          * subselect; furthermore, the subquery RTE might be
                               8224                 :                :                          * from an outer query level, in which case the
                               8225                 :                :                          * namespace for the subselect must have that outer
                               8226                 :                :                          * level as parent namespace.
                               8227                 :                :                          */
  774                          8228                 :              9 :                         List       *save_nslist = context->namespaces;
                               8229                 :                :                         List       *parent_namespaces;
                               8230                 :                :                         deparse_namespace mydpns;
                               8231                 :                :                         const char *result;
                               8232                 :                : 
                               8233                 :              9 :                         parent_namespaces = list_copy_tail(context->namespaces,
                               8234                 :                :                                                            netlevelsup);
                               8235                 :                : 
 4684                          8236                 :              9 :                         set_deparse_for_query(&mydpns, rte->subquery,
                               8237                 :                :                                               parent_namespaces);
                               8238                 :                : 
  774                          8239                 :              9 :                         context->namespaces = lcons(&mydpns, parent_namespaces);
                               8240                 :                : 
 6822                          8241                 :              9 :                         result = get_name_for_var_field((Var *) expr, fieldno,
                               8242                 :                :                                                         0, context);
                               8243                 :                : 
  774                          8244                 :              9 :                         context->namespaces = save_nslist;
                               8245                 :                : 
 6822                          8246                 :              9 :                         return result;
                               8247                 :                :                     }
                               8248                 :                :                     /* else fall through to inspect the expression */
                               8249                 :                :                 }
                               8250                 :                :                 else
                               8251                 :                :                 {
                               8252                 :                :                     /*
                               8253                 :                :                      * We're deparsing a Plan tree so we don't have complete
                               8254                 :                :                      * RTE entries (in particular, rte->subquery is NULL). But
                               8255                 :                :                      * the only place we'd normally see a Var directly
                               8256                 :                :                      * referencing a SUBQUERY RTE is in a SubqueryScan plan
                               8257                 :                :                      * node, and we can look into the child plan's tlist
                               8258                 :                :                      * instead.  An exception occurs if the subquery was
                               8259                 :                :                      * proven empty and optimized away: then we'd find such a
                               8260                 :                :                      * Var in a childless Result node, and there's nothing in
                               8261                 :                :                      * the plan tree that would let us figure out what it had
                               8262                 :                :                      * originally referenced.  In that case, fall back on
                               8263                 :                :                      * printing "fN", analogously to the default column names
                               8264                 :                :                      * for RowExprs.
                               8265                 :                :                      */
                               8266                 :                :                     TargetEntry *tle;
                               8267                 :                :                     deparse_namespace save_dpns;
                               8268                 :                :                     const char *result;
                               8269                 :                : 
 2148                          8270         [ +  + ]:             15 :                     if (!dpns->inner_plan)
                               8271                 :                :                     {
  445                          8272                 :              6 :                         char       *dummy_name = palloc(32);
                               8273                 :                : 
  443                          8274   [ +  -  -  + ]:              6 :                         Assert(dpns->plan && IsA(dpns->plan, Result));
  445                          8275                 :              6 :                         snprintf(dummy_name, 32, "f%d", fieldno);
                               8276                 :              6 :                         return dummy_name;
                               8277                 :                :                     }
  443                          8278   [ +  -  -  + ]:              9 :                     Assert(dpns->plan && IsA(dpns->plan, SubqueryScan));
                               8279                 :                : 
 5131                          8280                 :              9 :                     tle = get_tle_by_resno(dpns->inner_tlist, attnum);
 6822                          8281         [ -  + ]:              9 :                     if (!tle)
 6822 tgl@sss.pgh.pa.us        8282         [ #  # ]:UBC           0 :                         elog(ERROR, "bogus varattno for subquery var: %d",
                               8283                 :                :                              attnum);
 6822 tgl@sss.pgh.pa.us        8284         [ -  + ]:CBC           9 :                     Assert(netlevelsup == 0);
 2148                          8285                 :              9 :                     push_child_plan(dpns, dpns->inner_plan, &save_dpns);
                               8286                 :                : 
 6822                          8287                 :              9 :                     result = get_name_for_var_field((Var *) tle->expr, fieldno,
                               8288                 :                :                                                     levelsup, context);
                               8289                 :                : 
 5586                          8290                 :              9 :                     pop_child_plan(dpns, &save_dpns);
 7455                          8291                 :              9 :                     return result;
                               8292                 :                :                 }
                               8293                 :                :             }
                               8294                 :             12 :             break;
 7455 tgl@sss.pgh.pa.us        8295                 :UBC           0 :         case RTE_JOIN:
                               8296                 :                :             /* Join RTE --- recursively inspect the alias variable */
 6732                          8297         [ #  # ]:              0 :             if (rte->joinaliasvars == NIL)
                               8298         [ #  # ]:              0 :                 elog(ERROR, "cannot decompile join alias var in plan tree");
 7455                          8299   [ #  #  #  # ]:              0 :             Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
                               8300                 :              0 :             expr = (Node *) list_nth(rte->joinaliasvars, attnum - 1);
 4480                          8301         [ #  # ]:              0 :             Assert(expr != NULL);
                               8302                 :                :             /* we intentionally don't strip implicit coercions here */
 7455                          8303         [ #  # ]:              0 :             if (IsA(expr, Var))
                               8304                 :              0 :                 return get_name_for_var_field((Var *) expr, fieldno,
                               8305                 :              0 :                                               var->varlevelsup + levelsup,
                               8306                 :                :                                               context);
                               8307                 :                :             /* else fall through to inspect the expression */
                               8308                 :              0 :             break;
                               8309                 :              0 :         case RTE_FUNCTION:
                               8310                 :                :         case RTE_TABLEFUNC:
                               8311                 :                : 
                               8312                 :                :             /*
                               8313                 :                :              * We couldn't get here unless a function is declared with one of
                               8314                 :                :              * its result columns as RECORD, which is not allowed.
                               8315                 :                :              */
                               8316                 :              0 :             break;
 6233 tgl@sss.pgh.pa.us        8317                 :CBC          36 :         case RTE_CTE:
                               8318                 :                :             /* CTE reference: examine subquery's output expr */
                               8319                 :                :             {
 6231                          8320                 :             36 :                 CommonTableExpr *cte = NULL;
                               8321                 :                :                 Index       ctelevelsup;
                               8322                 :                :                 ListCell   *lc;
                               8323                 :                : 
                               8324                 :                :                 /*
                               8325                 :                :                  * Try to find the referenced CTE using the namespace stack.
                               8326                 :                :                  */
                               8327                 :             36 :                 ctelevelsup = rte->ctelevelsup + netlevelsup;
                               8328         [ +  + ]:             36 :                 if (ctelevelsup >= list_length(context->namespaces))
                               8329                 :              6 :                     lc = NULL;
                               8330                 :                :                 else
                               8331                 :                :                 {
                               8332                 :                :                     deparse_namespace *ctedpns;
                               8333                 :                : 
                               8334                 :                :                     ctedpns = (deparse_namespace *)
                               8335                 :             30 :                         list_nth(context->namespaces, ctelevelsup);
                               8336   [ +  +  +  -  :             33 :                     foreach(lc, ctedpns->ctes)
                                              +  + ]
                               8337                 :                :                     {
                               8338                 :             18 :                         cte = (CommonTableExpr *) lfirst(lc);
                               8339         [ +  + ]:             18 :                         if (strcmp(cte->ctename, rte->ctename) == 0)
                               8340                 :             15 :                             break;
                               8341                 :                :                     }
                               8342                 :                :                 }
                               8343         [ +  + ]:             36 :                 if (lc != NULL)
                               8344                 :                :                 {
                               8345                 :             15 :                     Query      *ctequery = (Query *) cte->ctequery;
 5315 bruce@momjian.us         8346   [ -  +  +  - ]:             15 :                     TargetEntry *ste = get_tle_by_resno(GetCTETargetList(cte),
                               8347                 :                :                                                         attnum);
                               8348                 :                : 
 6231 tgl@sss.pgh.pa.us        8349   [ +  -  -  + ]:             15 :                     if (ste == NULL || ste->resjunk)
  774 tgl@sss.pgh.pa.us        8350         [ #  # ]:UBC           0 :                         elog(ERROR, "CTE %s does not have attribute %d",
                               8351                 :                :                              rte->eref->aliasname, attnum);
 6231 tgl@sss.pgh.pa.us        8352                 :CBC          15 :                     expr = (Node *) ste->expr;
                               8353         [ +  + ]:             15 :                     if (IsA(expr, Var))
                               8354                 :                :                     {
                               8355                 :                :                         /*
                               8356                 :                :                          * Recurse into the CTE to see what its Var refers to.
                               8357                 :                :                          * We have to build an additional level of namespace
                               8358                 :                :                          * to keep in step with varlevelsup in the CTE;
                               8359                 :                :                          * furthermore it could be an outer CTE (compare
                               8360                 :                :                          * SUBQUERY case above).
                               8361                 :                :                          */
                               8362                 :              9 :                         List       *save_nslist = context->namespaces;
                               8363                 :                :                         List       *parent_namespaces;
                               8364                 :                :                         deparse_namespace mydpns;
                               8365                 :                :                         const char *result;
                               8366                 :                : 
  774                          8367                 :              9 :                         parent_namespaces = list_copy_tail(context->namespaces,
                               8368                 :                :                                                            ctelevelsup);
                               8369                 :                : 
 4684                          8370                 :              9 :                         set_deparse_for_query(&mydpns, ctequery,
                               8371                 :                :                                               parent_namespaces);
                               8372                 :                : 
  774                          8373                 :              9 :                         context->namespaces = lcons(&mydpns, parent_namespaces);
                               8374                 :                : 
 6231                          8375                 :              9 :                         result = get_name_for_var_field((Var *) expr, fieldno,
                               8376                 :                :                                                         0, context);
                               8377                 :                : 
                               8378                 :              9 :                         context->namespaces = save_nslist;
                               8379                 :                : 
                               8380                 :              9 :                         return result;
                               8381                 :                :                     }
                               8382                 :                :                     /* else fall through to inspect the expression */
                               8383                 :                :                 }
                               8384                 :                :                 else
                               8385                 :                :                 {
                               8386                 :                :                     /*
                               8387                 :                :                      * We're deparsing a Plan tree so we don't have a CTE
                               8388                 :                :                      * list.  But the only places we'd normally see a Var
                               8389                 :                :                      * directly referencing a CTE RTE are in CteScan or
                               8390                 :                :                      * WorkTableScan plan nodes.  For those cases,
                               8391                 :                :                      * set_deparse_plan arranged for dpns->inner_plan to be
                               8392                 :                :                      * the plan node that emits the CTE or RecursiveUnion
                               8393                 :                :                      * result, and we can look at its tlist instead.  As
                               8394                 :                :                      * above, this can fail if the CTE has been proven empty,
                               8395                 :                :                      * in which case fall back to "fN".
                               8396                 :                :                      */
                               8397                 :                :                     TargetEntry *tle;
                               8398                 :                :                     deparse_namespace save_dpns;
                               8399                 :                :                     const char *result;
                               8400                 :                : 
 2148                          8401         [ +  + ]:             21 :                     if (!dpns->inner_plan)
                               8402                 :                :                     {
  445                          8403                 :              3 :                         char       *dummy_name = palloc(32);
                               8404                 :                : 
  443                          8405   [ +  -  -  + ]:              3 :                         Assert(dpns->plan && IsA(dpns->plan, Result));
  445                          8406                 :              3 :                         snprintf(dummy_name, 32, "f%d", fieldno);
                               8407                 :              3 :                         return dummy_name;
                               8408                 :                :                     }
  443                          8409   [ +  -  +  +  :             18 :                     Assert(dpns->plan && (IsA(dpns->plan, CteScan) ||
                                              -  + ]
                               8410                 :                :                                           IsA(dpns->plan, WorkTableScan)));
                               8411                 :                : 
 5131                          8412                 :             18 :                     tle = get_tle_by_resno(dpns->inner_tlist, attnum);
 6231                          8413         [ -  + ]:             18 :                     if (!tle)
 6231 tgl@sss.pgh.pa.us        8414         [ #  # ]:UBC           0 :                         elog(ERROR, "bogus varattno for subquery var: %d",
                               8415                 :                :                              attnum);
 6231 tgl@sss.pgh.pa.us        8416         [ -  + ]:CBC          18 :                     Assert(netlevelsup == 0);
 2148                          8417                 :             18 :                     push_child_plan(dpns, dpns->inner_plan, &save_dpns);
                               8418                 :                : 
 6231                          8419                 :             18 :                     result = get_name_for_var_field((Var *) tle->expr, fieldno,
                               8420                 :                :                                                     levelsup, context);
                               8421                 :                : 
 5586                          8422                 :             18 :                     pop_child_plan(dpns, &save_dpns);
 6231                          8423                 :             18 :                     return result;
                               8424                 :                :                 }
                               8425                 :                :             }
 6233                          8426                 :              6 :             break;
  413 rguo@postgresql.org      8427                 :UBC           0 :         case RTE_GROUP:
                               8428                 :                : 
                               8429                 :                :             /*
                               8430                 :                :              * We couldn't get here: any Vars that reference the RTE_GROUP RTE
                               8431                 :                :              * should have been replaced with the underlying grouping
                               8432                 :                :              * expressions.
                               8433                 :                :              */
                               8434                 :              0 :             break;
                               8435                 :                :     }
                               8436                 :                : 
                               8437                 :                :     /*
                               8438                 :                :      * We now have an expression we can't expand any more, so see if
                               8439                 :                :      * get_expr_result_tupdesc() can do anything with it.
                               8440                 :                :      */
 2924 tgl@sss.pgh.pa.us        8441                 :CBC          18 :     tupleDesc = get_expr_result_tupdesc(expr, false);
                               8442                 :                :     /* Got the tupdesc, so we can extract the field name */
 7455                          8443   [ +  -  -  + ]:             18 :     Assert(fieldno >= 1 && fieldno <= tupleDesc->natts);
 2991 andres@anarazel.de       8444                 :             18 :     return NameStr(TupleDescAttr(tupleDesc, fieldno - 1)->attname);
                               8445                 :                : }
                               8446                 :                : 
                               8447                 :                : /*
                               8448                 :                :  * Try to find the referenced expression for a PARAM_EXEC Param that might
                               8449                 :                :  * reference a parameter supplied by an upper NestLoop or SubPlan plan node.
                               8450                 :                :  *
                               8451                 :                :  * If successful, return the expression and set *dpns_p and *ancestor_cell_p
                               8452                 :                :  * appropriately for calling push_ancestor_plan().  If no referent can be
                               8453                 :                :  * found, return NULL.
                               8454                 :                :  */
                               8455                 :                : static Node *
 5165 tgl@sss.pgh.pa.us        8456                 :           3596 : find_param_referent(Param *param, deparse_context *context,
                               8457                 :                :                     deparse_namespace **dpns_p, ListCell **ancestor_cell_p)
                               8458                 :                : {
                               8459                 :                :     /* Initialize output parameters to prevent compiler warnings */
                               8460                 :           3596 :     *dpns_p = NULL;
                               8461                 :           3596 :     *ancestor_cell_p = NULL;
                               8462                 :                : 
                               8463                 :                :     /*
                               8464                 :                :      * If it's a PARAM_EXEC parameter, look for a matching NestLoopParam or
                               8465                 :                :      * SubPlan argument.  This will necessarily be in some ancestor of the
                               8466                 :                :      * current expression's Plan node.
                               8467                 :                :      */
 5586                          8468         [ +  + ]:           3596 :     if (param->paramkind == PARAM_EXEC)
                               8469                 :                :     {
                               8470                 :                :         deparse_namespace *dpns;
                               8471                 :                :         Plan       *child_plan;
                               8472                 :                :         ListCell   *lc;
                               8473                 :                : 
                               8474                 :           3150 :         dpns = (deparse_namespace *) linitial(context->namespaces);
 2148                          8475                 :           3150 :         child_plan = dpns->plan;
                               8476                 :                : 
 5586                          8477   [ +  +  +  +  :           5584 :         foreach(lc, dpns->ancestors)
                                              +  + ]
                               8478                 :                :         {
 2148                          8479                 :           4754 :             Node       *ancestor = (Node *) lfirst(lc);
                               8480                 :                :             ListCell   *lc2;
                               8481                 :                : 
                               8482                 :                :             /*
                               8483                 :                :              * NestLoops transmit params to their inner child only.
                               8484                 :                :              */
                               8485         [ +  + ]:           4754 :             if (IsA(ancestor, NestLoop) &&
 1077                          8486         [ +  + ]:           2166 :                 child_plan == innerPlan(ancestor))
                               8487                 :                :             {
 2148                          8488                 :           2076 :                 NestLoop   *nl = (NestLoop *) ancestor;
                               8489                 :                : 
 5586                          8490   [ +  +  +  +  :           2569 :                 foreach(lc2, nl->nestParams)
                                              +  + ]
                               8491                 :                :                 {
 5315 bruce@momjian.us         8492                 :           2482 :                     NestLoopParam *nlp = (NestLoopParam *) lfirst(lc2);
                               8493                 :                : 
 5586 tgl@sss.pgh.pa.us        8494         [ +  + ]:           2482 :                     if (nlp->paramno == param->paramid)
                               8495                 :                :                     {
                               8496                 :                :                         /* Found a match, so return it */
 5165                          8497                 :           1989 :                         *dpns_p = dpns;
                               8498                 :           1989 :                         *ancestor_cell_p = lc;
                               8499                 :           1989 :                         return (Node *) nlp->paramval;
                               8500                 :                :                     }
                               8501                 :                :                 }
                               8502                 :                :             }
                               8503                 :                : 
                               8504                 :                :             /*
                               8505                 :                :              * If ancestor is a SubPlan, check the arguments it provides.
                               8506                 :                :              */
 2148                          8507         [ +  + ]:           2765 :             if (IsA(ancestor, SubPlan))
 5586                          8508                 :            183 :             {
 2148                          8509                 :            514 :                 SubPlan    *subplan = (SubPlan *) ancestor;
                               8510                 :                :                 ListCell   *lc3;
                               8511                 :                :                 ListCell   *lc4;
                               8512                 :                : 
 5586                          8513   [ +  +  +  +  :            685 :                 forboth(lc3, subplan->parParam, lc4, subplan->args)
                                     +  +  +  +  +  
                                        +  +  -  +  
                                                 + ]
                               8514                 :                :                 {
 5315 bruce@momjian.us         8515                 :            502 :                     int         paramid = lfirst_int(lc3);
                               8516                 :            502 :                     Node       *arg = (Node *) lfirst(lc4);
                               8517                 :                : 
 5586 tgl@sss.pgh.pa.us        8518         [ +  + ]:            502 :                     if (paramid == param->paramid)
                               8519                 :                :                     {
                               8520                 :                :                         /*
                               8521                 :                :                          * Found a match, so return it.  But, since Vars in
                               8522                 :                :                          * the arg are to be evaluated in the surrounding
                               8523                 :                :                          * context, we have to point to the next ancestor item
                               8524                 :                :                          * that is *not* a SubPlan.
                               8525                 :                :                          */
                               8526                 :                :                         ListCell   *rest;
                               8527                 :                : 
 2148                          8528   [ +  -  +  -  :            331 :                         for_each_cell(rest, dpns->ancestors,
                                              +  - ]
                               8529                 :                :                                       lnext(dpns->ancestors, lc))
                               8530                 :                :                         {
                               8531                 :            331 :                             Node       *ancestor2 = (Node *) lfirst(rest);
                               8532                 :                : 
                               8533         [ +  - ]:            331 :                             if (!IsA(ancestor2, SubPlan))
                               8534                 :                :                             {
                               8535                 :            331 :                                 *dpns_p = dpns;
                               8536                 :            331 :                                 *ancestor_cell_p = rest;
                               8537                 :            331 :                                 return arg;
                               8538                 :                :                             }
                               8539                 :                :                         }
 2148 tgl@sss.pgh.pa.us        8540         [ #  # ]:UBC           0 :                         elog(ERROR, "SubPlan cannot be outermost ancestor");
                               8541                 :                :                     }
                               8542                 :                :                 }
                               8543                 :                : 
                               8544                 :                :                 /* SubPlan isn't a kind of Plan, so skip the rest */
 2148 tgl@sss.pgh.pa.us        8545                 :CBC         183 :                 continue;
                               8546                 :                :             }
                               8547                 :                : 
                               8548                 :                :             /*
                               8549                 :                :              * We need not consider the ancestor's initPlan list, since
                               8550                 :                :              * initplans never have any parParams.
                               8551                 :                :              */
                               8552                 :                : 
                               8553                 :                :             /* No luck, crawl up to next ancestor */
                               8554                 :           2251 :             child_plan = (Plan *) ancestor;
                               8555                 :                :         }
                               8556                 :                :     }
                               8557                 :                : 
                               8558                 :                :     /* No referent found */
 5165                          8559                 :           1276 :     return NULL;
                               8560                 :                : }
                               8561                 :                : 
                               8562                 :                : /*
                               8563                 :                :  * Try to find a subplan/initplan that emits the value for a PARAM_EXEC Param.
                               8564                 :                :  *
                               8565                 :                :  * If successful, return the generating subplan/initplan and set *column_p
                               8566                 :                :  * to the subplan's 0-based output column number.
                               8567                 :                :  * Otherwise, return NULL.
                               8568                 :                :  */
                               8569                 :                : static SubPlan *
  588                          8570                 :           1276 : find_param_generator(Param *param, deparse_context *context, int *column_p)
                               8571                 :                : {
                               8572                 :                :     /* Initialize output parameter to prevent compiler warnings */
                               8573                 :           1276 :     *column_p = 0;
                               8574                 :                : 
                               8575                 :                :     /*
                               8576                 :                :      * If it's a PARAM_EXEC parameter, search the current plan node as well as
                               8577                 :                :      * ancestor nodes looking for a subplan or initplan that emits the value
                               8578                 :                :      * for the Param.  It could appear in the setParams of an initplan or
                               8579                 :                :      * MULTIEXPR_SUBLINK subplan, or in the paramIds of an ancestral SubPlan.
                               8580                 :                :      */
                               8581         [ +  + ]:           1276 :     if (param->paramkind == PARAM_EXEC)
                               8582                 :                :     {
                               8583                 :                :         SubPlan    *result;
                               8584                 :                :         deparse_namespace *dpns;
                               8585                 :                :         ListCell   *lc;
                               8586                 :                : 
                               8587                 :            830 :         dpns = (deparse_namespace *) linitial(context->namespaces);
                               8588                 :                : 
                               8589                 :                :         /* First check the innermost plan node's initplans */
                               8590                 :            830 :         result = find_param_generator_initplan(param, dpns->plan, column_p);
                               8591         [ +  + ]:            830 :         if (result)
                               8592                 :            250 :             return result;
                               8593                 :                : 
                               8594                 :                :         /*
                               8595                 :                :          * The plan's targetlist might contain MULTIEXPR_SUBLINK SubPlans,
                               8596                 :                :          * which can be referenced by Params elsewhere in the targetlist.
                               8597                 :                :          * (Such Params should always be in the same targetlist, so there's no
                               8598                 :                :          * need to do this work at upper plan nodes.)
                               8599                 :                :          */
                               8600   [ +  +  +  +  :           2972 :         foreach_node(TargetEntry, tle, dpns->plan->targetlist)
                                              +  + ]
                               8601                 :                :         {
                               8602   [ +  -  +  + ]:           1864 :             if (tle->expr && IsA(tle->expr, SubPlan))
                               8603                 :                :             {
                               8604                 :             50 :                 SubPlan    *subplan = (SubPlan *) tle->expr;
                               8605                 :                : 
                               8606         [ +  + ]:             50 :                 if (subplan->subLinkType == MULTIEXPR_SUBLINK)
                               8607                 :                :                 {
                               8608   [ +  -  +  -  :             39 :                     foreach_int(paramid, subplan->setParam)
                                              +  - ]
                               8609                 :                :                     {
                               8610         [ +  + ]:             39 :                         if (paramid == param->paramid)
                               8611                 :                :                         {
                               8612                 :                :                             /* Found a match, so return it. */
                               8613                 :             26 :                             *column_p = foreach_current_index(paramid);
                               8614                 :             26 :                             return subplan;
                               8615                 :                :                         }
                               8616                 :                :                     }
                               8617                 :                :                 }
                               8618                 :                :             }
                               8619                 :                :         }
                               8620                 :                : 
                               8621                 :                :         /* No luck, so check the ancestor nodes */
                               8622   [ +  -  +  -  :            731 :         foreach(lc, dpns->ancestors)
                                              +  - ]
                               8623                 :                :         {
                               8624                 :            731 :             Node       *ancestor = (Node *) lfirst(lc);
                               8625                 :                : 
                               8626                 :                :             /*
                               8627                 :                :              * If ancestor is a SubPlan, check the paramIds it provides.
                               8628                 :                :              */
                               8629         [ +  + ]:            731 :             if (IsA(ancestor, SubPlan))
  588 tgl@sss.pgh.pa.us        8630                 :UBC           0 :             {
  588 tgl@sss.pgh.pa.us        8631                 :CBC         105 :                 SubPlan    *subplan = (SubPlan *) ancestor;
                               8632                 :                : 
                               8633   [ +  -  +  -  :            118 :                 foreach_int(paramid, subplan->paramIds)
                                              +  - ]
                               8634                 :                :                 {
                               8635         [ +  + ]:            118 :                     if (paramid == param->paramid)
                               8636                 :                :                     {
                               8637                 :                :                         /* Found a match, so return it. */
                               8638                 :            105 :                         *column_p = foreach_current_index(paramid);
                               8639                 :            105 :                         return subplan;
                               8640                 :                :                     }
                               8641                 :                :                 }
                               8642                 :                : 
                               8643                 :                :                 /* SubPlan isn't a kind of Plan, so skip the rest */
  588 tgl@sss.pgh.pa.us        8644                 :UBC           0 :                 continue;
                               8645                 :                :             }
                               8646                 :                : 
                               8647                 :                :             /*
                               8648                 :                :              * Otherwise, it's some kind of Plan node, so check its initplans.
                               8649                 :                :              */
  588 tgl@sss.pgh.pa.us        8650                 :CBC         626 :             result = find_param_generator_initplan(param, (Plan *) ancestor,
                               8651                 :                :                                                    column_p);
                               8652         [ +  + ]:            626 :             if (result)
                               8653                 :            449 :                 return result;
                               8654                 :                : 
                               8655                 :                :             /* No luck, crawl up to next ancestor */
                               8656                 :                :         }
                               8657                 :                :     }
                               8658                 :                : 
                               8659                 :                :     /* No generator found */
                               8660                 :            446 :     return NULL;
                               8661                 :                : }
                               8662                 :                : 
                               8663                 :                : /*
                               8664                 :                :  * Subroutine for find_param_generator: search one Plan node's initplans
                               8665                 :                :  */
                               8666                 :                : static SubPlan *
                               8667                 :           1456 : find_param_generator_initplan(Param *param, Plan *plan, int *column_p)
                               8668                 :                : {
                               8669   [ +  +  +  -  :           2283 :     foreach_node(SubPlan, subplan, plan->initPlan)
                                              +  + ]
                               8670                 :                :     {
                               8671   [ +  -  +  +  :            912 :         foreach_int(paramid, subplan->setParam)
                                              +  + ]
                               8672                 :                :         {
                               8673         [ +  + ]:            772 :             if (paramid == param->paramid)
                               8674                 :                :             {
                               8675                 :                :                 /* Found a match, so return it. */
                               8676                 :            699 :                 *column_p = foreach_current_index(paramid);
                               8677                 :            699 :                 return subplan;
                               8678                 :                :             }
                               8679                 :                :         }
                               8680                 :                :     }
                               8681                 :            757 :     return NULL;
                               8682                 :                : }
                               8683                 :                : 
                               8684                 :                : /*
                               8685                 :                :  * Display a Param appropriately.
                               8686                 :                :  */
                               8687                 :                : static void
 5165                          8688                 :           3587 : get_parameter(Param *param, deparse_context *context)
                               8689                 :                : {
                               8690                 :                :     Node       *expr;
                               8691                 :                :     deparse_namespace *dpns;
                               8692                 :                :     ListCell   *ancestor_cell;
                               8693                 :                :     SubPlan    *subplan;
                               8694                 :                :     int         column;
                               8695                 :                : 
                               8696                 :                :     /*
                               8697                 :                :      * If it's a PARAM_EXEC parameter, try to locate the expression from which
                               8698                 :                :      * the parameter was computed.  This stanza handles only cases in which
                               8699                 :                :      * the Param represents an input to the subplan we are currently in.
                               8700                 :                :      */
                               8701                 :           3587 :     expr = find_param_referent(param, context, &dpns, &ancestor_cell);
                               8702         [ +  + ]:           3587 :     if (expr)
                               8703                 :                :     {
                               8704                 :                :         /* Found a match, so print it */
                               8705                 :                :         deparse_namespace save_dpns;
                               8706                 :                :         bool        save_varprefix;
                               8707                 :                :         bool        need_paren;
                               8708                 :                : 
                               8709                 :                :         /* Switch attention to the ancestor plan node */
                               8710                 :           2311 :         push_ancestor_plan(dpns, ancestor_cell, &save_dpns);
                               8711                 :                : 
                               8712                 :                :         /*
                               8713                 :                :          * Force prefixing of Vars, since they won't belong to the relation
                               8714                 :                :          * being scanned in the original plan node.
                               8715                 :                :          */
                               8716                 :           2311 :         save_varprefix = context->varprefix;
                               8717                 :           2311 :         context->varprefix = true;
                               8718                 :                : 
                               8719                 :                :         /*
                               8720                 :                :          * A Param's expansion is typically a Var, Aggref, GroupingFunc, or
                               8721                 :                :          * upper-level Param, which wouldn't need extra parentheses.
                               8722                 :                :          * Otherwise, insert parens to ensure the expression looks atomic.
                               8723                 :                :          */
                               8724         [ +  + ]:           2320 :         need_paren = !(IsA(expr, Var) ||
                               8725         [ +  - ]:              9 :                        IsA(expr, Aggref) ||
 1317                          8726         [ +  + ]:              9 :                        IsA(expr, GroupingFunc) ||
 5165                          8727         [ -  + ]:              6 :                        IsA(expr, Param));
                               8728         [ -  + ]:           2311 :         if (need_paren)
 5165 tgl@sss.pgh.pa.us        8729                 :UBC           0 :             appendStringInfoChar(context->buf, '(');
                               8730                 :                : 
 5165 tgl@sss.pgh.pa.us        8731                 :CBC        2311 :         get_rule_expr(expr, context, false);
                               8732                 :                : 
                               8733         [ -  + ]:           2311 :         if (need_paren)
 5165 tgl@sss.pgh.pa.us        8734                 :UBC           0 :             appendStringInfoChar(context->buf, ')');
                               8735                 :                : 
 5165 tgl@sss.pgh.pa.us        8736                 :CBC        2311 :         context->varprefix = save_varprefix;
                               8737                 :                : 
                               8738                 :           2311 :         pop_ancestor_plan(dpns, &save_dpns);
                               8739                 :                : 
                               8740                 :           2311 :         return;
                               8741                 :                :     }
                               8742                 :                : 
                               8743                 :                :     /*
                               8744                 :                :      * Alternatively, maybe it's a subplan output, which we print as a
                               8745                 :                :      * reference to the subplan.  (We could drill down into the subplan and
                               8746                 :                :      * print the relevant targetlist expression, but that has been deemed too
                               8747                 :                :      * confusing since it would violate normal SQL scope rules.  Also, we're
                               8748                 :                :      * relying on this reference to show that the testexpr containing the
                               8749                 :                :      * Param has anything to do with that subplan at all.)
                               8750                 :                :      */
  588                          8751                 :           1276 :     subplan = find_param_generator(param, context, &column);
                               8752         [ +  + ]:           1276 :     if (subplan)
                               8753                 :                :     {
                               8754                 :                :         const char *nameprefix;
                               8755                 :                : 
   21 rhaas@postgresql.org     8756         [ +  + ]:GNC         830 :         if (subplan->isInitPlan)
                               8757                 :            699 :             nameprefix = "InitPlan ";
                               8758                 :                :         else
                               8759                 :            131 :             nameprefix = "SubPlan ";
                               8760                 :                : 
                               8761                 :            830 :         appendStringInfo(context->buf, "(%s%s%s).col%d",
  588 tgl@sss.pgh.pa.us        8762         [ +  + ]:CBC         830 :                          subplan->useHashTable ? "hashed " : "",
                               8763                 :                :                          nameprefix,
                               8764                 :                :                          subplan->plan_name, column + 1);
                               8765                 :                : 
                               8766                 :            830 :         return;
                               8767                 :                :     }
                               8768                 :                : 
                               8769                 :                :     /*
                               8770                 :                :      * If it's an external parameter, see if the outermost namespace provides
                               8771                 :                :      * function argument names.
                               8772                 :                :      */
 1441                          8773   [ +  -  +  - ]:            446 :     if (param->paramkind == PARAM_EXTERN && context->namespaces != NIL)
                               8774                 :                :     {
                               8775                 :            446 :         dpns = llast(context->namespaces);
                               8776         [ +  + ]:            446 :         if (dpns->argnames &&
                               8777         [ +  - ]:             34 :             param->paramid > 0 &&
                               8778         [ +  - ]:             34 :             param->paramid <= dpns->numargs)
                               8779                 :                :         {
 1665 peter@eisentraut.org     8780                 :             34 :             char       *argname = dpns->argnames[param->paramid - 1];
                               8781                 :                : 
                               8782         [ +  - ]:             34 :             if (argname)
                               8783                 :                :             {
                               8784                 :             34 :                 bool        should_qualify = false;
                               8785                 :                :                 ListCell   *lc;
                               8786                 :                : 
                               8787                 :                :                 /*
                               8788                 :                :                  * Qualify the parameter name if there are any other deparse
                               8789                 :                :                  * namespaces with range tables.  This avoids qualifying in
                               8790                 :                :                  * trivial cases like "RETURN a + b", but makes it safe in all
                               8791                 :                :                  * other cases.
                               8792                 :                :                  */
                               8793   [ +  -  +  +  :             78 :                 foreach(lc, context->namespaces)
                                              +  + ]
                               8794                 :                :                 {
 1119 drowley@postgresql.o     8795                 :             59 :                     deparse_namespace *depns = lfirst(lc);
                               8796                 :                : 
                               8797         [ +  + ]:             59 :                     if (depns->rtable_names != NIL)
                               8798                 :                :                     {
 1665 peter@eisentraut.org     8799                 :             15 :                         should_qualify = true;
                               8800                 :             15 :                         break;
                               8801                 :                :                     }
                               8802                 :                :                 }
                               8803         [ +  + ]:             34 :                 if (should_qualify)
                               8804                 :                :                 {
                               8805                 :             15 :                     appendStringInfoString(context->buf, quote_identifier(dpns->funcname));
                               8806                 :             15 :                     appendStringInfoChar(context->buf, '.');
                               8807                 :                :                 }
                               8808                 :                : 
                               8809                 :             34 :                 appendStringInfoString(context->buf, quote_identifier(argname));
                               8810                 :             34 :                 return;
                               8811                 :                :             }
                               8812                 :                :         }
                               8813                 :                :     }
                               8814                 :                : 
                               8815                 :                :     /*
                               8816                 :                :      * Not PARAM_EXEC, or couldn't find referent: just print $N.
                               8817                 :                :      *
                               8818                 :                :      * It's a bug if we get here for anything except PARAM_EXTERN Params, but
                               8819                 :                :      * in production builds printing $N seems more useful than failing.
                               8820                 :                :      */
  588 tgl@sss.pgh.pa.us        8821         [ -  + ]:            412 :     Assert(param->paramkind == PARAM_EXTERN);
                               8822                 :                : 
 5165                          8823                 :            412 :     appendStringInfo(context->buf, "$%d", param->paramid);
                               8824                 :                : }
                               8825                 :                : 
                               8826                 :                : /*
                               8827                 :                :  * get_simple_binary_op_name
                               8828                 :                :  *
                               8829                 :                :  * helper function for isSimpleNode
                               8830                 :                :  * will return single char binary operator name, or NULL if it's not
                               8831                 :                :  */
                               8832                 :                : static const char *
 8117 bruce@momjian.us         8833                 :             75 : get_simple_binary_op_name(OpExpr *expr)
                               8834                 :                : {
 8126 tgl@sss.pgh.pa.us        8835                 :             75 :     List       *args = expr->args;
                               8836                 :                : 
 7821 neilc@samurai.com        8837         [ +  - ]:             75 :     if (list_length(args) == 2)
                               8838                 :                :     {
                               8839                 :                :         /* binary operator */
 7825                          8840                 :             75 :         Node       *arg1 = (Node *) linitial(args);
 8126 tgl@sss.pgh.pa.us        8841                 :             75 :         Node       *arg2 = (Node *) lsecond(args);
                               8842                 :                :         const char *op;
                               8843                 :                : 
                               8844                 :             75 :         op = generate_operator_name(expr->opno, exprType(arg1), exprType(arg2));
                               8845         [ +  - ]:             75 :         if (strlen(op) == 1)
 8121 bruce@momjian.us         8846                 :             75 :             return op;
                               8847                 :                :     }
 8126 tgl@sss.pgh.pa.us        8848                 :UBC           0 :     return NULL;
                               8849                 :                : }
                               8850                 :                : 
                               8851                 :                : 
                               8852                 :                : /*
                               8853                 :                :  * isSimpleNode - check if given node is simple (doesn't need parenthesizing)
                               8854                 :                :  *
                               8855                 :                :  *  true   : simple in the context of parent node's type
                               8856                 :                :  *  false  : not simple
                               8857                 :                :  */
                               8858                 :                : static bool
 8126 tgl@sss.pgh.pa.us        8859                 :CBC        2806 : isSimpleNode(Node *node, Node *parentNode, int prettyFlags)
                               8860                 :                : {
 8121 bruce@momjian.us         8861         [ -  + ]:           2806 :     if (!node)
 8126 tgl@sss.pgh.pa.us        8862                 :UBC           0 :         return false;
                               8863                 :                : 
 8121 bruce@momjian.us         8864   [ +  +  +  +  :CBC        2806 :     switch (nodeTag(node))
                                     -  -  +  -  -  
                                     -  -  +  +  +  
                                              -  + ]
                               8865                 :                :     {
 8126 tgl@sss.pgh.pa.us        8866                 :           2345 :         case T_Var:
                               8867                 :                :         case T_Const:
                               8868                 :                :         case T_Param:
                               8869                 :                :         case T_CoerceToDomainValue:
                               8870                 :                :         case T_SetToDefault:
                               8871                 :                :         case T_CurrentOfExpr:
                               8872                 :                :             /* single words: always simple */
                               8873                 :           2345 :             return true;
                               8874                 :                : 
 2461 alvherre@alvh.no-ip.     8875                 :            250 :         case T_SubscriptingRef:
                               8876                 :                :         case T_ArrayExpr:
                               8877                 :                :         case T_RowExpr:
                               8878                 :                :         case T_CoalesceExpr:
                               8879                 :                :         case T_MinMaxExpr:
                               8880                 :                :         case T_SQLValueFunction:
                               8881                 :                :         case T_XmlExpr:
                               8882                 :                :         case T_NextValueExpr:
                               8883                 :                :         case T_NullIfExpr:
                               8884                 :                :         case T_Aggref:
                               8885                 :                :         case T_GroupingFunc:
                               8886                 :                :         case T_WindowFunc:
                               8887                 :                :         case T_MergeSupportFunc:
                               8888                 :                :         case T_FuncExpr:
                               8889                 :                :         case T_JsonConstructorExpr:
                               8890                 :                :         case T_JsonExpr:
                               8891                 :                :             /* function-like: name(..) or name[..] */
 8126 tgl@sss.pgh.pa.us        8892                 :            250 :             return true;
                               8893                 :                : 
                               8894                 :                :             /* CASE keywords act as parentheses */
 8126 tgl@sss.pgh.pa.us        8895                 :GBC           4 :         case T_CaseExpr:
                               8896                 :              4 :             return true;
                               8897                 :                : 
 8126 tgl@sss.pgh.pa.us        8898                 :CBC          33 :         case T_FieldSelect:
                               8899                 :                : 
                               8900                 :                :             /*
                               8901                 :                :              * appears simple since . has top precedence, unless parent is
                               8902                 :                :              * T_FieldSelect itself!
                               8903                 :                :              */
 1511 michael@paquier.xyz      8904                 :             33 :             return !IsA(parentNode, FieldSelect);
                               8905                 :                : 
 7811 tgl@sss.pgh.pa.us        8906                 :UBC           0 :         case T_FieldStore:
                               8907                 :                : 
                               8908                 :                :             /*
                               8909                 :                :              * treat like FieldSelect (probably doesn't matter)
                               8910                 :                :              */
 1511 michael@paquier.xyz      8911                 :              0 :             return !IsA(parentNode, FieldStore);
                               8912                 :                : 
 8126 tgl@sss.pgh.pa.us        8913                 :              0 :         case T_CoerceToDomain:
                               8914                 :                :             /* maybe simple, check args */
 8121 bruce@momjian.us         8915                 :              0 :             return isSimpleNode((Node *) ((CoerceToDomain *) node)->arg,
                               8916                 :                :                                 node, prettyFlags);
 8126 tgl@sss.pgh.pa.us        8917                 :CBC          13 :         case T_RelabelType:
 8121 bruce@momjian.us         8918                 :             13 :             return isSimpleNode((Node *) ((RelabelType *) node)->arg,
                               8919                 :                :                                 node, prettyFlags);
 6720 tgl@sss.pgh.pa.us        8920                 :UBC           0 :         case T_CoerceViaIO:
                               8921                 :              0 :             return isSimpleNode((Node *) ((CoerceViaIO *) node)->arg,
                               8922                 :                :                                 node, prettyFlags);
 6790                          8923                 :              0 :         case T_ArrayCoerceExpr:
                               8924                 :              0 :             return isSimpleNode((Node *) ((ArrayCoerceExpr *) node)->arg,
                               8925                 :                :                                 node, prettyFlags);
 7626                          8926                 :              0 :         case T_ConvertRowtypeExpr:
                               8927                 :              0 :             return isSimpleNode((Node *) ((ConvertRowtypeExpr *) node)->arg,
                               8928                 :                :                                 node, prettyFlags);
  285 dean.a.rasheed@gmail     8929                 :              0 :         case T_ReturningExpr:
                               8930                 :              0 :             return isSimpleNode((Node *) ((ReturningExpr *) node)->retexpr,
                               8931                 :                :                                 node, prettyFlags);
                               8932                 :                : 
 8126 tgl@sss.pgh.pa.us        8933                 :CBC         139 :         case T_OpExpr:
                               8934                 :                :             {
                               8935                 :                :                 /* depends on parent node type; needs further checking */
 8121 bruce@momjian.us         8936   [ +  -  +  + ]:            139 :                 if (prettyFlags & PRETTYFLAG_PAREN && IsA(parentNode, OpExpr))
                               8937                 :                :                 {
                               8938                 :                :                     const char *op;
                               8939                 :                :                     const char *parentOp;
                               8940                 :                :                     bool        is_lopriop;
                               8941                 :                :                     bool        is_hipriop;
                               8942                 :                :                     bool        is_lopriparent;
                               8943                 :                :                     bool        is_hipriparent;
                               8944                 :                : 
                               8945                 :             39 :                     op = get_simple_binary_op_name((OpExpr *) node);
                               8946         [ -  + ]:             39 :                     if (!op)
 8121 bruce@momjian.us         8947                 :UBC           0 :                         return false;
                               8948                 :                : 
                               8949                 :                :                     /* We know only the basic operators + - and * / % */
 8121 bruce@momjian.us         8950                 :CBC          39 :                     is_lopriop = (strchr("+-", *op) != NULL);
                               8951                 :             39 :                     is_hipriop = (strchr("*/%", *op) != NULL);
                               8952   [ +  +  +  + ]:             39 :                     if (!(is_lopriop || is_hipriop))
                               8953                 :              3 :                         return false;
                               8954                 :                : 
                               8955                 :             36 :                     parentOp = get_simple_binary_op_name((OpExpr *) parentNode);
                               8956         [ -  + ]:             36 :                     if (!parentOp)
 8121 bruce@momjian.us         8957                 :UBC           0 :                         return false;
                               8958                 :                : 
 8121 bruce@momjian.us         8959                 :CBC          36 :                     is_lopriparent = (strchr("+-", *parentOp) != NULL);
                               8960                 :             36 :                     is_hipriparent = (strchr("*/%", *parentOp) != NULL);
                               8961   [ +  +  -  + ]:             36 :                     if (!(is_lopriparent || is_hipriparent))
 8121 bruce@momjian.us         8962                 :UBC           0 :                         return false;
                               8963                 :                : 
 8121 bruce@momjian.us         8964   [ +  +  +  - ]:CBC          36 :                     if (is_hipriop && is_lopriparent)
                               8965                 :              6 :                         return true;    /* op binds tighter than parent */
                               8966                 :                : 
                               8967   [ +  -  +  + ]:             30 :                     if (is_lopriop && is_hipriparent)
                               8968                 :             24 :                         return false;
                               8969                 :                : 
                               8970                 :                :                     /*
                               8971                 :                :                      * Operators are same priority --- can skip parens only if
                               8972                 :                :                      * we have (a - b) - c, not a - (b - c).
                               8973                 :                :                      */
 7825 neilc@samurai.com        8974         [ +  + ]:              6 :                     if (node == (Node *) linitial(((OpExpr *) parentNode)->args))
 8121 bruce@momjian.us         8975                 :              3 :                         return true;
                               8976                 :                : 
                               8977                 :              3 :                     return false;
                               8978                 :                :                 }
                               8979                 :                :                 /* else do the same stuff as for T_SubLink et al. */
                               8980                 :                :             }
                               8981                 :                :             /* FALLTHROUGH */
                               8982                 :                : 
                               8983                 :                :         case T_SubLink:
                               8984                 :                :         case T_NullTest:
                               8985                 :                :         case T_BooleanTest:
                               8986                 :                :         case T_DistinctExpr:
                               8987                 :                :         case T_JsonIsPredicate:
 8126 tgl@sss.pgh.pa.us        8988      [ +  +  + ]:            109 :             switch (nodeTag(parentNode))
                               8989                 :                :             {
                               8990                 :             18 :                 case T_FuncExpr:
                               8991                 :                :                     {
                               8992                 :                :                         /* special handling for casts and COERCE_SQL_SYNTAX */
 8121 bruce@momjian.us         8993                 :             18 :                         CoercionForm type = ((FuncExpr *) parentNode)->funcformat;
                               8994                 :                : 
                               8995   [ +  +  +  + ]:             18 :                         if (type == COERCE_EXPLICIT_CAST ||
 1062 tgl@sss.pgh.pa.us        8996         [ +  - ]:              3 :                             type == COERCE_IMPLICIT_CAST ||
                               8997                 :                :                             type == COERCE_SQL_SYNTAX)
 8121 bruce@momjian.us         8998                 :             18 :                             return false;
 8121 bruce@momjian.us         8999                 :UBC           0 :                         return true;    /* own parentheses */
                               9000                 :                :                     }
 3051 tgl@sss.pgh.pa.us        9001                 :CBC          76 :                 case T_BoolExpr:    /* lower precedence */
                               9002                 :                :                 case T_SubscriptingRef: /* other separators */
                               9003                 :                :                 case T_ArrayExpr:   /* other separators */
                               9004                 :                :                 case T_RowExpr: /* other separators */
                               9005                 :                :                 case T_CoalesceExpr:    /* own parentheses */
                               9006                 :                :                 case T_MinMaxExpr:  /* own parentheses */
                               9007                 :                :                 case T_XmlExpr: /* own parentheses */
                               9008                 :                :                 case T_NullIfExpr:  /* other separators */
                               9009                 :                :                 case T_Aggref:  /* own parentheses */
                               9010                 :                :                 case T_GroupingFunc:    /* own parentheses */
                               9011                 :                :                 case T_WindowFunc:  /* own parentheses */
                               9012                 :                :                 case T_CaseExpr:    /* other separators */
 8126                          9013                 :             76 :                     return true;
                               9014                 :             15 :                 default:
                               9015                 :             15 :                     return false;
                               9016                 :                :             }
                               9017                 :                : 
                               9018                 :              9 :         case T_BoolExpr:
                               9019   [ +  -  -  - ]:              9 :             switch (nodeTag(parentNode))
                               9020                 :                :             {
                               9021                 :              9 :                 case T_BoolExpr:
                               9022         [ +  - ]:              9 :                     if (prettyFlags & PRETTYFLAG_PAREN)
                               9023                 :                :                     {
                               9024                 :                :                         BoolExprType type;
                               9025                 :                :                         BoolExprType parentType;
                               9026                 :                : 
 8121 bruce@momjian.us         9027                 :              9 :                         type = ((BoolExpr *) node)->boolop;
                               9028                 :              9 :                         parentType = ((BoolExpr *) parentNode)->boolop;
 8126 tgl@sss.pgh.pa.us        9029      [ +  +  - ]:              9 :                         switch (type)
                               9030                 :                :                         {
                               9031                 :              6 :                             case NOT_EXPR:
                               9032                 :                :                             case AND_EXPR:
                               9033   [ +  +  +  - ]:              6 :                                 if (parentType == AND_EXPR || parentType == OR_EXPR)
                               9034                 :              6 :                                     return true;
 8126 tgl@sss.pgh.pa.us        9035                 :UBC           0 :                                 break;
 8126 tgl@sss.pgh.pa.us        9036                 :CBC           3 :                             case OR_EXPR:
                               9037         [ -  + ]:              3 :                                 if (parentType == OR_EXPR)
 8126 tgl@sss.pgh.pa.us        9038                 :UBC           0 :                                     return true;
 8126 tgl@sss.pgh.pa.us        9039                 :CBC           3 :                                 break;
                               9040                 :                :                         }
                               9041                 :                :                     }
                               9042                 :              3 :                     return false;
 8126 tgl@sss.pgh.pa.us        9043                 :UBC           0 :                 case T_FuncExpr:
                               9044                 :                :                     {
                               9045                 :                :                         /* special handling for casts and COERCE_SQL_SYNTAX */
 8121 bruce@momjian.us         9046                 :              0 :                         CoercionForm type = ((FuncExpr *) parentNode)->funcformat;
                               9047                 :                : 
                               9048   [ #  #  #  # ]:              0 :                         if (type == COERCE_EXPLICIT_CAST ||
 1062 tgl@sss.pgh.pa.us        9049         [ #  # ]:              0 :                             type == COERCE_IMPLICIT_CAST ||
                               9050                 :                :                             type == COERCE_SQL_SYNTAX)
 8121 bruce@momjian.us         9051                 :              0 :                             return false;
                               9052                 :              0 :                         return true;    /* own parentheses */
                               9053                 :                :                     }
 2461 alvherre@alvh.no-ip.     9054                 :              0 :                 case T_SubscriptingRef: /* other separators */
                               9055                 :                :                 case T_ArrayExpr:   /* other separators */
                               9056                 :                :                 case T_RowExpr: /* other separators */
                               9057                 :                :                 case T_CoalesceExpr:    /* own parentheses */
                               9058                 :                :                 case T_MinMaxExpr:  /* own parentheses */
                               9059                 :                :                 case T_XmlExpr: /* own parentheses */
                               9060                 :                :                 case T_NullIfExpr:  /* other separators */
                               9061                 :                :                 case T_Aggref:  /* own parentheses */
                               9062                 :                :                 case T_GroupingFunc:    /* own parentheses */
                               9063                 :                :                 case T_WindowFunc:  /* own parentheses */
                               9064                 :                :                 case T_CaseExpr:    /* other separators */
                               9065                 :                :                 case T_JsonExpr:    /* own parentheses */
 8126 tgl@sss.pgh.pa.us        9066                 :              0 :                     return true;
                               9067                 :              0 :                 default:
                               9068                 :              0 :                     return false;
                               9069                 :                :             }
                               9070                 :                : 
  944 alvherre@alvh.no-ip.     9071                 :              0 :         case T_JsonValueExpr:
                               9072                 :                :             /* maybe simple, check args */
                               9073                 :              0 :             return isSimpleNode((Node *) ((JsonValueExpr *) node)->raw_expr,
                               9074                 :                :                                 node, prettyFlags);
                               9075                 :                : 
 8126 tgl@sss.pgh.pa.us        9076                 :CBC           4 :         default:
                               9077                 :              4 :             break;
                               9078                 :                :     }
                               9079                 :                :     /* those we don't know: in dubio complexo */
 8121 bruce@momjian.us         9080                 :              4 :     return false;
                               9081                 :                : }
                               9082                 :                : 
                               9083                 :                : 
                               9084                 :                : /*
                               9085                 :                :  * appendContextKeyword - append a keyword to buffer
                               9086                 :                :  *
                               9087                 :                :  * If prettyPrint is enabled, perform a line break, and adjust indentation.
                               9088                 :                :  * Otherwise, just append the keyword.
                               9089                 :                :  */
                               9090                 :                : static void
 8126 tgl@sss.pgh.pa.us        9091                 :          15040 : appendContextKeyword(deparse_context *context, const char *str,
                               9092                 :                :                      int indentBefore, int indentAfter, int indentPlus)
                               9093                 :                : {
 4369                          9094                 :          15040 :     StringInfo  buf = context->buf;
                               9095                 :                : 
 8121 bruce@momjian.us         9096         [ +  + ]:          15040 :     if (PRETTY_INDENT(context))
                               9097                 :                :     {
                               9098                 :                :         int         indentAmount;
                               9099                 :                : 
 8126 tgl@sss.pgh.pa.us        9100                 :          14582 :         context->indentLevel += indentBefore;
                               9101                 :                : 
                               9102                 :                :         /* remove any trailing spaces currently in the buffer ... */
 4369                          9103                 :          14582 :         removeStringInfoSpaces(buf);
                               9104                 :                :         /* ... then add a newline and some spaces */
                               9105                 :          14582 :         appendStringInfoChar(buf, '\n');
                               9106                 :                : 
 4199                          9107         [ +  - ]:          14582 :         if (context->indentLevel < PRETTYINDENT_LIMIT)
                               9108                 :          14582 :             indentAmount = Max(context->indentLevel, 0) + indentPlus;
                               9109                 :                :         else
                               9110                 :                :         {
                               9111                 :                :             /*
                               9112                 :                :              * If we're indented more than PRETTYINDENT_LIMIT characters, try
                               9113                 :                :              * to conserve horizontal space by reducing the per-level
                               9114                 :                :              * indentation.  For best results the scale factor here should
                               9115                 :                :              * divide all the indent amounts that get added to indentLevel
                               9116                 :                :              * (PRETTYINDENT_STD, etc).  It's important that the indentation
                               9117                 :                :              * not grow unboundedly, else deeply-nested trees use O(N^2)
                               9118                 :                :              * whitespace; so we also wrap modulo PRETTYINDENT_LIMIT.
                               9119                 :                :              */
 4199 tgl@sss.pgh.pa.us        9120                 :UBC           0 :             indentAmount = PRETTYINDENT_LIMIT +
                               9121                 :              0 :                 (context->indentLevel - PRETTYINDENT_LIMIT) /
                               9122                 :                :                 (PRETTYINDENT_STD / 2);
                               9123                 :              0 :             indentAmount %= PRETTYINDENT_LIMIT;
                               9124                 :                :             /* scale/wrap logic affects indentLevel, but not indentPlus */
                               9125                 :              0 :             indentAmount += indentPlus;
                               9126                 :                :         }
 4199 tgl@sss.pgh.pa.us        9127                 :CBC       14582 :         appendStringInfoSpaces(buf, indentAmount);
                               9128                 :                : 
 4369                          9129                 :          14582 :         appendStringInfoString(buf, str);
                               9130                 :                : 
 8126                          9131                 :          14582 :         context->indentLevel += indentAfter;
                               9132         [ -  + ]:          14582 :         if (context->indentLevel < 0)
 8126 tgl@sss.pgh.pa.us        9133                 :UBC           0 :             context->indentLevel = 0;
                               9134                 :                :     }
                               9135                 :                :     else
 4369 tgl@sss.pgh.pa.us        9136                 :CBC         458 :         appendStringInfoString(buf, str);
 8126                          9137                 :          15040 : }
                               9138                 :                : 
                               9139                 :                : /*
                               9140                 :                :  * removeStringInfoSpaces - delete trailing spaces from a buffer.
                               9141                 :                :  *
                               9142                 :                :  * Possibly this should move to stringinfo.c at some point.
                               9143                 :                :  */
                               9144                 :                : static void
 4369                          9145                 :          14823 : removeStringInfoSpaces(StringInfo str)
                               9146                 :                : {
                               9147   [ +  +  +  + ]:          23241 :     while (str->len > 0 && str->data[str->len - 1] == ' ')
                               9148                 :           8418 :         str->data[--(str->len)] = '\0';
                               9149                 :          14823 : }
                               9150                 :                : 
                               9151                 :                : 
                               9152                 :                : /*
                               9153                 :                :  * get_rule_expr_paren  - deparse expr using get_rule_expr,
                               9154                 :                :  * embracing the string with parentheses if necessary for prettyPrint.
                               9155                 :                :  *
                               9156                 :                :  * Never embrace if prettyFlags=0, because it's done in the calling node.
                               9157                 :                :  *
                               9158                 :                :  * Any node that does *not* embrace its argument node by sql syntax (with
                               9159                 :                :  * parentheses, non-operator keywords like CASE/WHEN/ON, or comma etc) should
                               9160                 :                :  * use get_rule_expr_paren instead of get_rule_expr so parentheses can be
                               9161                 :                :  * added.
                               9162                 :                :  */
                               9163                 :                : static void
 8121 bruce@momjian.us         9164                 :          81616 : get_rule_expr_paren(Node *node, deparse_context *context,
                               9165                 :                :                     bool showimplicit, Node *parentNode)
                               9166                 :                : {
                               9167                 :                :     bool        need_paren;
                               9168                 :                : 
 8126 tgl@sss.pgh.pa.us        9169         [ +  + ]:          84409 :     need_paren = PRETTY_PAREN(context) &&
                               9170         [ +  + ]:           2793 :         !isSimpleNode(node, parentNode, context->prettyFlags);
                               9171                 :                : 
                               9172         [ +  + ]:          81616 :     if (need_paren)
 8121 bruce@momjian.us         9173                 :             70 :         appendStringInfoChar(context->buf, '(');
                               9174                 :                : 
 8126 tgl@sss.pgh.pa.us        9175                 :          81616 :     get_rule_expr(node, context, showimplicit);
                               9176                 :                : 
                               9177         [ +  + ]:          81616 :     if (need_paren)
 8121 bruce@momjian.us         9178                 :             70 :         appendStringInfoChar(context->buf, ')');
 8126 tgl@sss.pgh.pa.us        9179                 :          81616 : }
                               9180                 :                : 
                               9181                 :                : static void
  586 amitlan@postgresql.o     9182                 :             42 : get_json_behavior(JsonBehavior *behavior, deparse_context *context,
                               9183                 :                :                   const char *on)
                               9184                 :                : {
                               9185                 :                :     /*
                               9186                 :                :      * The order of array elements must correspond to the order of
                               9187                 :                :      * JsonBehaviorType members.
                               9188                 :                :      */
                               9189                 :             42 :     const char *behavior_names[] =
                               9190                 :                :     {
                               9191                 :                :         " NULL",
                               9192                 :                :         " ERROR",
                               9193                 :                :         " EMPTY",
                               9194                 :                :         " TRUE",
                               9195                 :                :         " FALSE",
                               9196                 :                :         " UNKNOWN",
                               9197                 :                :         " EMPTY ARRAY",
                               9198                 :                :         " EMPTY OBJECT",
                               9199                 :                :         " DEFAULT "
                               9200                 :                :     };
                               9201                 :                : 
                               9202   [ +  -  -  + ]:             42 :     if ((int) behavior->btype < 0 || behavior->btype >= lengthof(behavior_names))
  586 amitlan@postgresql.o     9203         [ #  # ]:UBC           0 :         elog(ERROR, "invalid json behavior type: %d", behavior->btype);
                               9204                 :                : 
  586 amitlan@postgresql.o     9205                 :CBC          42 :     appendStringInfoString(context->buf, behavior_names[behavior->btype]);
                               9206                 :                : 
                               9207         [ +  + ]:             42 :     if (behavior->btype == JSON_BEHAVIOR_DEFAULT)
                               9208                 :              9 :         get_rule_expr(behavior->expr, context, false);
                               9209                 :                : 
                               9210                 :             42 :     appendStringInfo(context->buf, " ON %s", on);
                               9211                 :             42 : }
                               9212                 :                : 
                               9213                 :                : /*
                               9214                 :                :  * get_json_expr_options
                               9215                 :                :  *
                               9216                 :                :  * Parse back common options for JSON_QUERY, JSON_VALUE, JSON_EXISTS and
                               9217                 :                :  * JSON_TABLE columns.
                               9218                 :                :  */
                               9219                 :                : static void
                               9220                 :            228 : get_json_expr_options(JsonExpr *jsexpr, deparse_context *context,
                               9221                 :                :                       JsonBehaviorType default_behavior)
                               9222                 :                : {
                               9223         [ +  + ]:            228 :     if (jsexpr->op == JSON_QUERY_OP)
                               9224                 :                :     {
                               9225         [ +  + ]:            105 :         if (jsexpr->wrapper == JSW_CONDITIONAL)
  566 drowley@postgresql.o     9226                 :              6 :             appendStringInfoString(context->buf, " WITH CONDITIONAL WRAPPER");
  586 amitlan@postgresql.o     9227         [ +  + ]:             99 :         else if (jsexpr->wrapper == JSW_UNCONDITIONAL)
  566 drowley@postgresql.o     9228                 :             15 :             appendStringInfoString(context->buf, " WITH UNCONDITIONAL WRAPPER");
                               9229                 :                :         /* The default */
  568 amitlan@postgresql.o     9230   [ +  +  +  - ]:             84 :         else if (jsexpr->wrapper == JSW_NONE || jsexpr->wrapper == JSW_UNSPEC)
  566 drowley@postgresql.o     9231                 :             84 :             appendStringInfoString(context->buf, " WITHOUT WRAPPER");
                               9232                 :                : 
  586 amitlan@postgresql.o     9233         [ +  + ]:            105 :         if (jsexpr->omit_quotes)
  566 drowley@postgresql.o     9234                 :             21 :             appendStringInfoString(context->buf, " OMIT QUOTES");
                               9235                 :                :         /* The default */
                               9236                 :                :         else
                               9237                 :             84 :             appendStringInfoString(context->buf, " KEEP QUOTES");
                               9238                 :                :     }
                               9239                 :                : 
  586 amitlan@postgresql.o     9240   [ +  +  +  + ]:            228 :     if (jsexpr->on_empty && jsexpr->on_empty->btype != default_behavior)
                               9241                 :             15 :         get_json_behavior(jsexpr->on_empty, context, "EMPTY");
                               9242                 :                : 
                               9243   [ +  -  +  + ]:            228 :     if (jsexpr->on_error && jsexpr->on_error->btype != default_behavior)
                               9244                 :             24 :         get_json_behavior(jsexpr->on_error, context, "ERROR");
                               9245                 :            228 : }
                               9246                 :                : 
                               9247                 :                : /* ----------
                               9248                 :                :  * get_rule_expr            - Parse back an expression
                               9249                 :                :  *
                               9250                 :                :  * Note: showimplicit determines whether we display any implicit cast that
                               9251                 :                :  * is present at the top of the expression tree.  It is a passed argument,
                               9252                 :                :  * not a field of the context struct, because we change the value as we
                               9253                 :                :  * recurse down into the expression.  In general we suppress implicit casts
                               9254                 :                :  * when the result type is known with certainty (eg, the arguments of an
                               9255                 :                :  * OR must be boolean).  We display implicit casts for arguments of functions
                               9256                 :                :  * and operators, since this is needed to be certain that the same function
                               9257                 :                :  * or operator will be chosen when the expression is re-parsed.
                               9258                 :                :  * ----------
                               9259                 :                :  */
                               9260                 :                : static void
 8440 tgl@sss.pgh.pa.us        9261                 :         176484 : get_rule_expr(Node *node, deparse_context *context,
                               9262                 :                :               bool showimplicit)
                               9263                 :                : {
 9522                          9264                 :         176484 :     StringInfo  buf = context->buf;
                               9265                 :                : 
 9919 bruce@momjian.us         9266         [ +  + ]:         176484 :     if (node == NULL)
 9523 tgl@sss.pgh.pa.us        9267                 :             45 :         return;
                               9268                 :                : 
                               9269                 :                :     /* Guard against excessively long or deeply-nested queries */
 4199                          9270         [ -  + ]:         176439 :     CHECK_FOR_INTERRUPTS();
                               9271                 :         176439 :     check_stack_depth();
                               9272                 :                : 
                               9273                 :                :     /*
                               9274                 :                :      * Each level of get_rule_expr must emit an indivisible term
                               9275                 :                :      * (parenthesized if necessary) to ensure result is reparsed into the same
                               9276                 :                :      * expression tree.  The only exception is that when the input is a List,
                               9277                 :                :      * we emit the component items comma-separated with no surrounding
                               9278                 :                :      * decoration; this is convenient for most callers.
                               9279                 :                :      */
 9919 bruce@momjian.us         9280   [ +  +  +  +  :         176439 :     switch (nodeTag(node))
                                     +  +  +  +  +  
                                     +  +  +  +  +  
                                     +  +  +  -  +  
                                     +  +  +  +  +  
                                     +  +  -  +  +  
                                     +  +  +  +  +  
                                     +  +  +  +  +  
                                     +  -  +  +  +  
                                     +  +  +  +  +  
                                              +  - ]
                               9281                 :                :     {
 9558 tgl@sss.pgh.pa.us        9282                 :          85349 :         case T_Var:
 4932                          9283                 :          85349 :             (void) get_variable((Var *) node, 0, false, context);
 9919 bruce@momjian.us         9284                 :          85349 :             break;
                               9285                 :                : 
 8356 tgl@sss.pgh.pa.us        9286                 :          30887 :         case T_Const:
 6505                          9287                 :          30887 :             get_const_expr((Const *) node, context, 0);
 8356                          9288                 :          30887 :             break;
                               9289                 :                : 
                               9290                 :           3587 :         case T_Param:
 5586                          9291                 :           3587 :             get_parameter((Param *) node, context);
 9919 bruce@momjian.us         9292                 :           3587 :             break;
                               9293                 :                : 
 9558 tgl@sss.pgh.pa.us        9294                 :           1961 :         case T_Aggref:
 3471 rhaas@postgresql.org     9295                 :           1961 :             get_agg_expr((Aggref *) node, context, (Aggref *) node);
 9558 tgl@sss.pgh.pa.us        9296                 :           1961 :             break;
                               9297                 :                : 
 3818 andres@anarazel.de       9298                 :             56 :         case T_GroupingFunc:
                               9299                 :                :             {
                               9300                 :             56 :                 GroupingFunc *gexpr = (GroupingFunc *) node;
                               9301                 :                : 
                               9302                 :             56 :                 appendStringInfoString(buf, "GROUPING(");
                               9303                 :             56 :                 get_rule_expr((Node *) gexpr->args, context, true);
                               9304                 :             56 :                 appendStringInfoChar(buf, ')');
                               9305                 :                :             }
                               9306                 :             56 :             break;
                               9307                 :                : 
 6148 tgl@sss.pgh.pa.us        9308                 :            162 :         case T_WindowFunc:
                               9309                 :            162 :             get_windowfunc_expr((WindowFunc *) node, context);
                               9310                 :            162 :             break;
                               9311                 :                : 
  590 dean.a.rasheed@gmail     9312                 :              3 :         case T_MergeSupportFunc:
                               9313                 :              3 :             appendStringInfoString(buf, "MERGE_ACTION()");
                               9314                 :              3 :             break;
                               9315                 :                : 
 2461 alvherre@alvh.no-ip.     9316                 :            164 :         case T_SubscriptingRef:
                               9317                 :                :             {
                               9318                 :            164 :                 SubscriptingRef *sbsref = (SubscriptingRef *) node;
                               9319                 :                :                 bool        need_parens;
                               9320                 :                : 
                               9321                 :                :                 /*
                               9322                 :                :                  * If the argument is a CaseTestExpr, we must be inside a
                               9323                 :                :                  * FieldStore, ie, we are assigning to an element of an array
                               9324                 :                :                  * within a composite column.  Since we already punted on
                               9325                 :                :                  * displaying the FieldStore's target information, just punt
                               9326                 :                :                  * here too, and display only the assignment source
                               9327                 :                :                  * expression.
                               9328                 :                :                  */
                               9329         [ -  + ]:            164 :                 if (IsA(sbsref->refexpr, CaseTestExpr))
                               9330                 :                :                 {
 2461 alvherre@alvh.no-ip.     9331         [ #  # ]:UBC           0 :                     Assert(sbsref->refassgnexpr);
                               9332                 :              0 :                     get_rule_expr((Node *) sbsref->refassgnexpr,
                               9333                 :                :                                   context, showimplicit);
 5731 tgl@sss.pgh.pa.us        9334                 :              0 :                     break;
                               9335                 :                :                 }
                               9336                 :                : 
                               9337                 :                :                 /*
                               9338                 :                :                  * Parenthesize the argument unless it's a simple Var or a
                               9339                 :                :                  * FieldSelect.  (In particular, if it's another
                               9340                 :                :                  * SubscriptingRef, we *must* parenthesize to avoid
                               9341                 :                :                  * confusion.)
                               9342                 :                :                  */
 2461 alvherre@alvh.no-ip.     9343         [ +  + ]:CBC         241 :                 need_parens = !IsA(sbsref->refexpr, Var) &&
                               9344         [ +  + ]:             77 :                     !IsA(sbsref->refexpr, FieldSelect);
 8239 tgl@sss.pgh.pa.us        9345         [ +  + ]:            164 :                 if (need_parens)
                               9346                 :             47 :                     appendStringInfoChar(buf, '(');
 2461 alvherre@alvh.no-ip.     9347                 :            164 :                 get_rule_expr((Node *) sbsref->refexpr, context, showimplicit);
 8239 tgl@sss.pgh.pa.us        9348         [ +  + ]:            164 :                 if (need_parens)
                               9349                 :             47 :                     appendStringInfoChar(buf, ')');
                               9350                 :                : 
                               9351                 :                :                 /*
                               9352                 :                :                  * If there's a refassgnexpr, we want to print the node in the
                               9353                 :                :                  * format "container[subscripts] := refassgnexpr".  This is
                               9354                 :                :                  * not legal SQL, so decompilation of INSERT or UPDATE
                               9355                 :                :                  * statements should always use processIndirection as part of
                               9356                 :                :                  * the statement-level syntax.  We should only see this when
                               9357                 :                :                  * EXPLAIN tries to print the targetlist of a plan resulting
                               9358                 :                :                  * from such a statement.
                               9359                 :                :                  */
 2461 alvherre@alvh.no-ip.     9360         [ +  + ]:            164 :                 if (sbsref->refassgnexpr)
                               9361                 :                :                 {
                               9362                 :                :                     Node       *refassgnexpr;
                               9363                 :                : 
                               9364                 :                :                     /*
                               9365                 :                :                      * Use processIndirection to print this node's subscripts
                               9366                 :                :                      * as well as any additional field selections or
                               9367                 :                :                      * subscripting in immediate descendants.  It returns the
                               9368                 :                :                      * RHS expr that is actually being "assigned".
                               9369                 :                :                      */
 3373 tgl@sss.pgh.pa.us        9370                 :              6 :                     refassgnexpr = processIndirection(node, context);
 5731                          9371                 :              6 :                     appendStringInfoString(buf, " := ");
                               9372                 :              6 :                     get_rule_expr(refassgnexpr, context, showimplicit);
                               9373                 :                :                 }
                               9374                 :                :                 else
                               9375                 :                :                 {
                               9376                 :                :                     /* Just an ordinary container fetch, so print subscripts */
 2461 alvherre@alvh.no-ip.     9377                 :            158 :                     printSubscripts(sbsref, context);
                               9378                 :                :                 }
                               9379                 :                :             }
 8356 tgl@sss.pgh.pa.us        9380                 :            164 :             break;
                               9381                 :                : 
                               9382                 :           6284 :         case T_FuncExpr:
                               9383                 :           6284 :             get_func_expr((FuncExpr *) node, context, showimplicit);
                               9384                 :           6284 :             break;
                               9385                 :                : 
 5864                          9386                 :             15 :         case T_NamedArgExpr:
                               9387                 :                :             {
                               9388                 :             15 :                 NamedArgExpr *na = (NamedArgExpr *) node;
                               9389                 :                : 
 3833 rhaas@postgresql.org     9390                 :             15 :                 appendStringInfo(buf, "%s => ", quote_identifier(na->name));
 5864 tgl@sss.pgh.pa.us        9391                 :             15 :                 get_rule_expr((Node *) na->arg, context, showimplicit);
                               9392                 :                :             }
                               9393                 :             15 :             break;
                               9394                 :                : 
 8356                          9395                 :          30559 :         case T_OpExpr:
                               9396                 :          30559 :             get_oper_expr((OpExpr *) node, context);
                               9397                 :          30559 :             break;
                               9398                 :                : 
                               9399                 :              9 :         case T_DistinctExpr:
                               9400                 :                :             {
                               9401                 :              9 :                 DistinctExpr *expr = (DistinctExpr *) node;
                               9402                 :              9 :                 List       *args = expr->args;
 7825 neilc@samurai.com        9403                 :              9 :                 Node       *arg1 = (Node *) linitial(args);
 8157 tgl@sss.pgh.pa.us        9404                 :              9 :                 Node       *arg2 = (Node *) lsecond(args);
                               9405                 :                : 
 8126                          9406         [ +  + ]:              9 :                 if (!PRETTY_PAREN(context))
 8121 bruce@momjian.us         9407                 :              6 :                     appendStringInfoChar(buf, '(');
 8126 tgl@sss.pgh.pa.us        9408                 :              9 :                 get_rule_expr_paren(arg1, context, true, node);
 4380 rhaas@postgresql.org     9409                 :              9 :                 appendStringInfoString(buf, " IS DISTINCT FROM ");
 8126 tgl@sss.pgh.pa.us        9410                 :              9 :                 get_rule_expr_paren(arg2, context, true, node);
                               9411         [ +  + ]:              9 :                 if (!PRETTY_PAREN(context))
 8121 bruce@momjian.us         9412                 :              6 :                     appendStringInfoChar(buf, ')');
                               9413                 :                :             }
 8157 tgl@sss.pgh.pa.us        9414                 :              9 :             break;
                               9415                 :                : 
 5337                          9416                 :             80 :         case T_NullIfExpr:
                               9417                 :                :             {
                               9418                 :             80 :                 NullIfExpr *nullifexpr = (NullIfExpr *) node;
                               9419                 :                : 
 4380 rhaas@postgresql.org     9420                 :             80 :                 appendStringInfoString(buf, "NULLIF(");
 5337 tgl@sss.pgh.pa.us        9421                 :             80 :                 get_rule_expr((Node *) nullifexpr->args, context, true);
                               9422                 :             80 :                 appendStringInfoChar(buf, ')');
                               9423                 :                :             }
                               9424                 :             80 :             break;
                               9425                 :                : 
 8157                          9426                 :           1516 :         case T_ScalarArrayOpExpr:
                               9427                 :                :             {
                               9428                 :           1516 :                 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
                               9429                 :           1516 :                 List       *args = expr->args;
 7825 neilc@samurai.com        9430                 :           1516 :                 Node       *arg1 = (Node *) linitial(args);
 8157 tgl@sss.pgh.pa.us        9431                 :           1516 :                 Node       *arg2 = (Node *) lsecond(args);
                               9432                 :                : 
 8126                          9433         [ +  + ]:           1516 :                 if (!PRETTY_PAREN(context))
 8121 bruce@momjian.us         9434                 :           1509 :                     appendStringInfoChar(buf, '(');
 8126 tgl@sss.pgh.pa.us        9435                 :           1516 :                 get_rule_expr_paren(arg1, context, true, node);
 8157                          9436                 :           1516 :                 appendStringInfo(buf, " %s %s (",
                               9437                 :                :                                  generate_operator_name(expr->opno,
                               9438                 :                :                                                         exprType(arg1),
                               9439                 :                :                                                         get_base_element_type(exprType(arg2))),
                               9440         [ +  + ]:           1516 :                                  expr->useOr ? "ANY" : "ALL");
 8126                          9441                 :           1516 :                 get_rule_expr_paren(arg2, context, true, node);
                               9442                 :                : 
                               9443                 :                :                 /*
                               9444                 :                :                  * There's inherent ambiguity in "x op ANY/ALL (y)" when y is
                               9445                 :                :                  * a bare sub-SELECT.  Since we're here, the sub-SELECT must
                               9446                 :                :                  * be meant as a scalar sub-SELECT yielding an array value to
                               9447                 :                :                  * be used in ScalarArrayOpExpr; but the grammar will
                               9448                 :                :                  * preferentially interpret such a construct as an ANY/ALL
                               9449                 :                :                  * SubLink.  To prevent misparsing the output that way, insert
                               9450                 :                :                  * a dummy coercion (which will be stripped by parse analysis,
                               9451                 :                :                  * so no inefficiency is added in dump and reload).  This is
                               9452                 :                :                  * indeed most likely what the user wrote to get the construct
                               9453                 :                :                  * accepted in the first place.
                               9454                 :                :                  */
 3477                          9455         [ +  + ]:           1516 :                 if (IsA(arg2, SubLink) &&
                               9456         [ +  - ]:              3 :                     ((SubLink *) arg2)->subLinkType == EXPR_SUBLINK)
                               9457                 :              3 :                     appendStringInfo(buf, "::%s",
                               9458                 :                :                                      format_type_with_typemod(exprType(arg2),
                               9459                 :                :                                                               exprTypmod(arg2)));
 8126                          9460                 :           1516 :                 appendStringInfoChar(buf, ')');
                               9461         [ +  + ]:           1516 :                 if (!PRETTY_PAREN(context))
 8121 bruce@momjian.us         9462                 :           1509 :                     appendStringInfoChar(buf, ')');
                               9463                 :                :             }
 9919                          9464                 :           1516 :             break;
                               9465                 :                : 
 8356 tgl@sss.pgh.pa.us        9466                 :           5588 :         case T_BoolExpr:
                               9467                 :                :             {
                               9468                 :           5588 :                 BoolExpr   *expr = (BoolExpr *) node;
 7825 neilc@samurai.com        9469                 :           5588 :                 Node       *first_arg = linitial(expr->args);
                               9470                 :                :                 ListCell   *arg;
                               9471                 :                : 
 8356 tgl@sss.pgh.pa.us        9472   [ +  +  +  - ]:           5588 :                 switch (expr->boolop)
                               9473                 :                :                 {
                               9474                 :           4454 :                     case AND_EXPR:
 8126                          9475         [ +  + ]:           4454 :                         if (!PRETTY_PAREN(context))
 8121 bruce@momjian.us         9476                 :           4423 :                             appendStringInfoChar(buf, '(');
 7825 neilc@samurai.com        9477                 :           4454 :                         get_rule_expr_paren(first_arg, context,
                               9478                 :                :                                             false, node);
 1856 tgl@sss.pgh.pa.us        9479   [ +  -  +  +  :          10150 :                         for_each_from(arg, expr->args, 1)
                                              +  + ]
                               9480                 :                :                         {
 4380 rhaas@postgresql.org     9481                 :           5696 :                             appendStringInfoString(buf, " AND ");
 7825 neilc@samurai.com        9482                 :           5696 :                             get_rule_expr_paren((Node *) lfirst(arg), context,
                               9483                 :                :                                                 false, node);
                               9484                 :                :                         }
 8126 tgl@sss.pgh.pa.us        9485         [ +  + ]:           4454 :                         if (!PRETTY_PAREN(context))
 8121 bruce@momjian.us         9486                 :           4423 :                             appendStringInfoChar(buf, ')');
 8356 tgl@sss.pgh.pa.us        9487                 :           4454 :                         break;
                               9488                 :                : 
                               9489                 :            951 :                     case OR_EXPR:
 8126                          9490         [ +  + ]:            951 :                         if (!PRETTY_PAREN(context))
 8121 bruce@momjian.us         9491                 :            944 :                             appendStringInfoChar(buf, '(');
 7825 neilc@samurai.com        9492                 :            951 :                         get_rule_expr_paren(first_arg, context,
                               9493                 :                :                                             false, node);
 1856 tgl@sss.pgh.pa.us        9494   [ +  -  +  +  :           2260 :                         for_each_from(arg, expr->args, 1)
                                              +  + ]
                               9495                 :                :                         {
 4380 rhaas@postgresql.org     9496                 :           1309 :                             appendStringInfoString(buf, " OR ");
 7825 neilc@samurai.com        9497                 :           1309 :                             get_rule_expr_paren((Node *) lfirst(arg), context,
                               9498                 :                :                                                 false, node);
                               9499                 :                :                         }
 8126 tgl@sss.pgh.pa.us        9500         [ +  + ]:            951 :                         if (!PRETTY_PAREN(context))
 8121 bruce@momjian.us         9501                 :            944 :                             appendStringInfoChar(buf, ')');
 8356 tgl@sss.pgh.pa.us        9502                 :            951 :                         break;
                               9503                 :                : 
                               9504                 :            183 :                     case NOT_EXPR:
 8126                          9505         [ +  + ]:            183 :                         if (!PRETTY_PAREN(context))
 8121 bruce@momjian.us         9506                 :            177 :                             appendStringInfoChar(buf, '(');
 4380 rhaas@postgresql.org     9507                 :            183 :                         appendStringInfoString(buf, "NOT ");
 7825 neilc@samurai.com        9508                 :            183 :                         get_rule_expr_paren(first_arg, context,
                               9509                 :                :                                             false, node);
 8126 tgl@sss.pgh.pa.us        9510         [ +  + ]:            183 :                         if (!PRETTY_PAREN(context))
 8121 bruce@momjian.us         9511                 :            177 :                             appendStringInfoChar(buf, ')');
 8356 tgl@sss.pgh.pa.us        9512                 :            183 :                         break;
                               9513                 :                : 
 8356 tgl@sss.pgh.pa.us        9514                 :UBC           0 :                     default:
 8129                          9515         [ #  # ]:              0 :                         elog(ERROR, "unrecognized boolop: %d",
                               9516                 :                :                              (int) expr->boolop);
                               9517                 :                :                 }
                               9518                 :                :             }
 8356 tgl@sss.pgh.pa.us        9519                 :CBC        5588 :             break;
                               9520                 :                : 
                               9521                 :            230 :         case T_SubLink:
                               9522                 :            230 :             get_sublink_expr((SubLink *) node, context);
                               9523                 :            230 :             break;
                               9524                 :                : 
 8354                          9525                 :            364 :         case T_SubPlan:
                               9526                 :                :             {
 5983 bruce@momjian.us         9527                 :            364 :                 SubPlan    *subplan = (SubPlan *) node;
                               9528                 :                : 
                               9529                 :                :                 /*
                               9530                 :                :                  * We cannot see an already-planned subplan in rule deparsing,
                               9531                 :                :                  * only while EXPLAINing a query plan.  We don't try to
                               9532                 :                :                  * reconstruct the original SQL, just reference the subplan
                               9533                 :                :                  * that appears elsewhere in EXPLAIN's result.  It does seem
                               9534                 :                :                  * useful to show the subLinkType and testexpr (if any), and
                               9535                 :                :                  * we also note whether the subplan will be hashed.
                               9536                 :                :                  */
  588 tgl@sss.pgh.pa.us        9537   [ +  +  +  +  :            364 :                 switch (subplan->subLinkType)
                                        +  +  +  -  
                                                 - ]
                               9538                 :                :                 {
                               9539                 :             48 :                     case EXISTS_SUBLINK:
                               9540                 :             48 :                         appendStringInfoString(buf, "EXISTS(");
                               9541         [ -  + ]:             48 :                         Assert(subplan->testexpr == NULL);
                               9542                 :             48 :                         break;
                               9543                 :              3 :                     case ALL_SUBLINK:
                               9544                 :              3 :                         appendStringInfoString(buf, "(ALL ");
                               9545         [ -  + ]:              3 :                         Assert(subplan->testexpr != NULL);
                               9546                 :              3 :                         break;
                               9547                 :             83 :                     case ANY_SUBLINK:
                               9548                 :             83 :                         appendStringInfoString(buf, "(ANY ");
                               9549         [ -  + ]:             83 :                         Assert(subplan->testexpr != NULL);
                               9550                 :             83 :                         break;
                               9551                 :              3 :                     case ROWCOMPARE_SUBLINK:
                               9552                 :                :                         /* Parenthesizing the testexpr seems sufficient */
                               9553                 :              3 :                         appendStringInfoChar(buf, '(');
                               9554         [ -  + ]:              3 :                         Assert(subplan->testexpr != NULL);
                               9555                 :              3 :                         break;
                               9556                 :            208 :                     case EXPR_SUBLINK:
                               9557                 :                :                         /* No need to decorate these subplan references */
                               9558                 :            208 :                         appendStringInfoChar(buf, '(');
                               9559         [ -  + ]:            208 :                         Assert(subplan->testexpr == NULL);
                               9560                 :            208 :                         break;
                               9561                 :             13 :                     case MULTIEXPR_SUBLINK:
                               9562                 :                :                         /* MULTIEXPR isn't executed in the normal way */
                               9563                 :             13 :                         appendStringInfoString(buf, "(rescan ");
                               9564         [ -  + ]:             13 :                         Assert(subplan->testexpr == NULL);
                               9565                 :             13 :                         break;
                               9566                 :              6 :                     case ARRAY_SUBLINK:
                               9567                 :              6 :                         appendStringInfoString(buf, "ARRAY(");
                               9568         [ -  + ]:              6 :                         Assert(subplan->testexpr == NULL);
                               9569                 :              6 :                         break;
  588 tgl@sss.pgh.pa.us        9570                 :UBC           0 :                     case CTE_SUBLINK:
                               9571                 :                :                         /* This case is unreachable within expressions */
                               9572                 :              0 :                         appendStringInfoString(buf, "CTE(");
                               9573         [ #  # ]:              0 :                         Assert(subplan->testexpr == NULL);
                               9574                 :              0 :                         break;
                               9575                 :                :                 }
                               9576                 :                : 
  588 tgl@sss.pgh.pa.us        9577         [ +  + ]:CBC         364 :                 if (subplan->testexpr != NULL)
                               9578                 :                :                 {
                               9579                 :                :                     deparse_namespace *dpns;
                               9580                 :                : 
                               9581                 :                :                     /*
                               9582                 :                :                      * Push SubPlan into ancestors list while deparsing
                               9583                 :                :                      * testexpr, so that we can handle PARAM_EXEC references
                               9584                 :                :                      * to the SubPlan's paramIds.  (This makes it look like
                               9585                 :                :                      * the SubPlan is an "ancestor" of the current plan node,
                               9586                 :                :                      * which is a little weird, but it does no harm.)  In this
                               9587                 :                :                      * path, we don't need to mention the SubPlan explicitly,
                               9588                 :                :                      * because the referencing Params will show its existence.
                               9589                 :                :                      */
                               9590                 :             89 :                     dpns = (deparse_namespace *) linitial(context->namespaces);
                               9591                 :             89 :                     dpns->ancestors = lcons(subplan, dpns->ancestors);
                               9592                 :                : 
                               9593                 :             89 :                     get_rule_expr(subplan->testexpr, context, showimplicit);
                               9594                 :             89 :                     appendStringInfoChar(buf, ')');
                               9595                 :                : 
                               9596                 :             89 :                     dpns->ancestors = list_delete_first(dpns->ancestors);
                               9597                 :                :                 }
                               9598                 :                :                 else
                               9599                 :                :                 {
                               9600                 :                :                     const char *nameprefix;
                               9601                 :                : 
                               9602                 :                :                     /* No referencing Params, so show the SubPlan's name */
   21 rhaas@postgresql.org     9603         [ -  + ]:GNC         275 :                     if (subplan->isInitPlan)
   21 rhaas@postgresql.org     9604                 :UNC           0 :                         nameprefix = "InitPlan ";
                               9605                 :                :                     else
   21 rhaas@postgresql.org     9606                 :GNC         275 :                         nameprefix = "SubPlan ";
  588 tgl@sss.pgh.pa.us        9607         [ -  + ]:CBC         275 :                     if (subplan->useHashTable)
   21 rhaas@postgresql.org     9608                 :UNC           0 :                         appendStringInfo(buf, "hashed %s%s)",
                               9609                 :                :                                          nameprefix, subplan->plan_name);
                               9610                 :                :                     else
   21 rhaas@postgresql.org     9611                 :GNC         275 :                         appendStringInfo(buf, "%s%s)",
                               9612                 :                :                                          nameprefix, subplan->plan_name);
                               9613                 :                :                 }
                               9614                 :                :             }
 8356 tgl@sss.pgh.pa.us        9615                 :CBC         364 :             break;
                               9616                 :                : 
 6276 tgl@sss.pgh.pa.us        9617                 :UBC           0 :         case T_AlternativeSubPlan:
                               9618                 :                :             {
 6050                          9619                 :              0 :                 AlternativeSubPlan *asplan = (AlternativeSubPlan *) node;
                               9620                 :                :                 ListCell   *lc;
                               9621                 :                : 
                               9622                 :                :                 /*
                               9623                 :                :                  * This case cannot be reached in normal usage, since no
                               9624                 :                :                  * AlternativeSubPlan can appear either in parsetrees or
                               9625                 :                :                  * finished plan trees.  We keep it just in case somebody
                               9626                 :                :                  * wants to use this code to print planner data structures.
                               9627                 :                :                  */
 4380 rhaas@postgresql.org     9628                 :              0 :                 appendStringInfoString(buf, "(alternatives: ");
 6050 tgl@sss.pgh.pa.us        9629   [ #  #  #  #  :              0 :                 foreach(lc, asplan->subplans)
                                              #  # ]
                               9630                 :                :                 {
 3123                          9631                 :              0 :                     SubPlan    *splan = lfirst_node(SubPlan, lc);
                               9632                 :                :                     const char *nameprefix;
                               9633                 :                : 
   21 rhaas@postgresql.org     9634         [ #  # ]:UNC           0 :                     if (splan->isInitPlan)
                               9635                 :              0 :                         nameprefix = "InitPlan ";
                               9636                 :                :                     else
                               9637                 :              0 :                         nameprefix = "SubPlan ";
 6050 tgl@sss.pgh.pa.us        9638         [ #  # ]:UBC           0 :                     if (splan->useHashTable)
   21 rhaas@postgresql.org     9639                 :UNC           0 :                         appendStringInfo(buf, "hashed %s%s", nameprefix,
                               9640                 :                :                                          splan->plan_name);
                               9641                 :                :                     else
                               9642                 :              0 :                         appendStringInfo(buf, "%s%s", nameprefix,
                               9643                 :                :                                          splan->plan_name);
 2297 tgl@sss.pgh.pa.us        9644         [ #  # ]:UBC           0 :                     if (lnext(asplan->subplans, lc))
 4380 rhaas@postgresql.org     9645                 :              0 :                         appendStringInfoString(buf, " or ");
                               9646                 :                :                 }
                               9647                 :              0 :                 appendStringInfoChar(buf, ')');
                               9648                 :                :             }
 6276 tgl@sss.pgh.pa.us        9649                 :              0 :             break;
                               9650                 :                : 
 9212 tgl@sss.pgh.pa.us        9651                 :CBC         577 :         case T_FieldSelect:
                               9652                 :                :             {
                               9653                 :            577 :                 FieldSelect *fselect = (FieldSelect *) node;
 7455                          9654                 :            577 :                 Node       *arg = (Node *) fselect->arg;
                               9655                 :            577 :                 int         fno = fselect->fieldnum;
                               9656                 :                :                 const char *fieldname;
                               9657                 :                :                 bool        need_parens;
                               9658                 :                : 
                               9659                 :                :                 /*
                               9660                 :                :                  * Parenthesize the argument unless it's an SubscriptingRef or
                               9661                 :                :                  * another FieldSelect.  Note in particular that it would be
                               9662                 :                :                  * WRONG to not parenthesize a Var argument; simplicity is not
                               9663                 :                :                  * the issue here, having the right number of names is.
                               9664                 :                :                  */
 2461 alvherre@alvh.no-ip.     9665         [ +  + ]:           1136 :                 need_parens = !IsA(arg, SubscriptingRef) &&
                               9666         [ +  - ]:            559 :                     !IsA(arg, FieldSelect);
 7811 tgl@sss.pgh.pa.us        9667         [ +  + ]:            577 :                 if (need_parens)
                               9668                 :            559 :                     appendStringInfoChar(buf, '(');
 7455                          9669                 :            577 :                 get_rule_expr(arg, context, true);
 7811                          9670         [ +  + ]:            577 :                 if (need_parens)
                               9671                 :            559 :                     appendStringInfoChar(buf, ')');
                               9672                 :                : 
                               9673                 :                :                 /*
                               9674                 :                :                  * Get and print the field name.
                               9675                 :                :                  */
 6822                          9676                 :            577 :                 fieldname = get_name_for_var_field((Var *) arg, fno,
                               9677                 :                :                                                    0, context);
 8126                          9678                 :            577 :                 appendStringInfo(buf, ".%s", quote_identifier(fieldname));
                               9679                 :                :             }
 9212                          9680                 :            577 :             break;
                               9681                 :                : 
 7811                          9682                 :              3 :         case T_FieldStore:
                               9683                 :                :             {
 5731                          9684                 :              3 :                 FieldStore *fstore = (FieldStore *) node;
                               9685                 :                :                 bool        need_parens;
                               9686                 :                : 
                               9687                 :                :                 /*
                               9688                 :                :                  * There is no good way to represent a FieldStore as real SQL,
                               9689                 :                :                  * so decompilation of INSERT or UPDATE statements should
                               9690                 :                :                  * always use processIndirection as part of the
                               9691                 :                :                  * statement-level syntax.  We should only get here when
                               9692                 :                :                  * EXPLAIN tries to print the targetlist of a plan resulting
                               9693                 :                :                  * from such a statement.  The plan case is even harder than
                               9694                 :                :                  * ordinary rules would be, because the planner tries to
                               9695                 :                :                  * collapse multiple assignments to the same field or subfield
                               9696                 :                :                  * into one FieldStore; so we can see a list of target fields
                               9697                 :                :                  * not just one, and the arguments could be FieldStores
                               9698                 :                :                  * themselves.  We don't bother to try to print the target
                               9699                 :                :                  * field names; we just print the source arguments, with a
                               9700                 :                :                  * ROW() around them if there's more than one.  This isn't
                               9701                 :                :                  * terribly complete, but it's probably good enough for
                               9702                 :                :                  * EXPLAIN's purposes; especially since anything more would be
                               9703                 :                :                  * either hopelessly confusing or an even poorer
                               9704                 :                :                  * representation of what the plan is actually doing.
                               9705                 :                :                  */
                               9706                 :              3 :                 need_parens = (list_length(fstore->newvals) != 1);
                               9707         [ +  - ]:              3 :                 if (need_parens)
                               9708                 :              3 :                     appendStringInfoString(buf, "ROW(");
                               9709                 :              3 :                 get_rule_expr((Node *) fstore->newvals, context, showimplicit);
                               9710         [ +  - ]:              3 :                 if (need_parens)
                               9711                 :              3 :                     appendStringInfoChar(buf, ')');
                               9712                 :                :             }
 7811                          9713                 :              3 :             break;
                               9714                 :                : 
 9382                          9715                 :           1312 :         case T_RelabelType:
                               9716                 :                :             {
                               9717                 :           1312 :                 RelabelType *relabel = (RelabelType *) node;
 8121 bruce@momjian.us         9718                 :           1312 :                 Node       *arg = (Node *) relabel->arg;
                               9719                 :                : 
 8440 tgl@sss.pgh.pa.us        9720         [ +  + ]:           1312 :                 if (relabel->relabelformat == COERCE_IMPLICIT_CAST &&
                               9721         [ +  + ]:           1212 :                     !showimplicit)
                               9722                 :                :                 {
                               9723                 :                :                     /* don't show the implicit cast */
 7804                          9724                 :             37 :                     get_rule_expr_paren(arg, context, false, node);
                               9725                 :                :                 }
                               9726                 :                :                 else
                               9727                 :                :                 {
 6800                          9728                 :           1275 :                     get_coercion_expr(arg, context,
                               9729                 :                :                                       relabel->resulttype,
                               9730                 :                :                                       relabel->resulttypmod,
                               9731                 :                :                                       node);
                               9732                 :                :                 }
                               9733                 :                :             }
 9382                          9734                 :           1312 :             break;
                               9735                 :                : 
 6720                          9736                 :            334 :         case T_CoerceViaIO:
                               9737                 :                :             {
                               9738                 :            334 :                 CoerceViaIO *iocoerce = (CoerceViaIO *) node;
                               9739                 :            334 :                 Node       *arg = (Node *) iocoerce->arg;
                               9740                 :                : 
                               9741         [ +  + ]:            334 :                 if (iocoerce->coerceformat == COERCE_IMPLICIT_CAST &&
                               9742         [ +  - ]:             12 :                     !showimplicit)
                               9743                 :                :                 {
                               9744                 :                :                     /* don't show the implicit cast */
                               9745                 :             12 :                     get_rule_expr_paren(arg, context, false, node);
                               9746                 :                :                 }
                               9747                 :                :                 else
                               9748                 :                :                 {
                               9749                 :            322 :                     get_coercion_expr(arg, context,
                               9750                 :                :                                       iocoerce->resulttype,
                               9751                 :                :                                       -1,
                               9752                 :                :                                       node);
                               9753                 :                :                 }
                               9754                 :                :             }
                               9755                 :            334 :             break;
                               9756                 :                : 
 6790                          9757                 :             26 :         case T_ArrayCoerceExpr:
                               9758                 :                :             {
                               9759                 :             26 :                 ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
                               9760                 :             26 :                 Node       *arg = (Node *) acoerce->arg;
                               9761                 :                : 
                               9762         [ +  - ]:             26 :                 if (acoerce->coerceformat == COERCE_IMPLICIT_CAST &&
                               9763         [ -  + ]:             26 :                     !showimplicit)
                               9764                 :                :                 {
                               9765                 :                :                     /* don't show the implicit cast */
 6790 tgl@sss.pgh.pa.us        9766                 :UBC           0 :                     get_rule_expr_paren(arg, context, false, node);
                               9767                 :                :                 }
                               9768                 :                :                 else
                               9769                 :                :                 {
 6790 tgl@sss.pgh.pa.us        9770                 :CBC          26 :                     get_coercion_expr(arg, context,
                               9771                 :                :                                       acoerce->resulttype,
                               9772                 :                :                                       acoerce->resulttypmod,
                               9773                 :                :                                       node);
                               9774                 :                :                 }
                               9775                 :                :             }
                               9776                 :             26 :             break;
                               9777                 :                : 
 7626                          9778                 :             44 :         case T_ConvertRowtypeExpr:
                               9779                 :                :             {
                               9780                 :             44 :                 ConvertRowtypeExpr *convert = (ConvertRowtypeExpr *) node;
                               9781                 :             44 :                 Node       *arg = (Node *) convert->arg;
                               9782                 :                : 
                               9783         [ +  + ]:             44 :                 if (convert->convertformat == COERCE_IMPLICIT_CAST &&
                               9784         [ +  + ]:             41 :                     !showimplicit)
                               9785                 :                :                 {
                               9786                 :                :                     /* don't show the implicit cast */
                               9787                 :             12 :                     get_rule_expr_paren(arg, context, false, node);
                               9788                 :                :                 }
                               9789                 :                :                 else
                               9790                 :                :                 {
 6800                          9791                 :             32 :                     get_coercion_expr(arg, context,
                               9792                 :                :                                       convert->resulttype, -1,
                               9793                 :                :                                       node);
                               9794                 :                :                 }
                               9795                 :                :             }
 7626                          9796                 :             44 :             break;
                               9797                 :                : 
 5345                          9798                 :             45 :         case T_CollateExpr:
                               9799                 :                :             {
                               9800                 :             45 :                 CollateExpr *collate = (CollateExpr *) node;
                               9801                 :             45 :                 Node       *arg = (Node *) collate->arg;
                               9802                 :                : 
                               9803         [ +  + ]:             45 :                 if (!PRETTY_PAREN(context))
                               9804                 :             42 :                     appendStringInfoChar(buf, '(');
                               9805                 :             45 :                 get_rule_expr_paren(arg, context, showimplicit, node);
                               9806                 :             45 :                 appendStringInfo(buf, " COLLATE %s",
                               9807                 :                :                                  generate_collation_name(collate->collOid));
                               9808         [ +  + ]:             45 :                 if (!PRETTY_PAREN(context))
                               9809                 :             42 :                     appendStringInfoChar(buf, ')');
                               9810                 :                :             }
                               9811                 :             45 :             break;
                               9812                 :                : 
 9558                          9813                 :            307 :         case T_CaseExpr:
                               9814                 :                :             {
                               9815                 :            307 :                 CaseExpr   *caseexpr = (CaseExpr *) node;
                               9816                 :                :                 ListCell   *temp;
                               9817                 :                : 
 8126                          9818                 :            307 :                 appendContextKeyword(context, "CASE",
                               9819                 :                :                                      0, PRETTYINDENT_VAR, 0);
 7895                          9820         [ +  + ]:            307 :                 if (caseexpr->arg)
                               9821                 :                :                 {
                               9822                 :             96 :                     appendStringInfoChar(buf, ' ');
                               9823                 :             96 :                     get_rule_expr((Node *) caseexpr->arg, context, true);
                               9824                 :                :                 }
 9558                          9825   [ +  -  +  +  :           1349 :                 foreach(temp, caseexpr->args)
                                              +  + ]
                               9826                 :                :                 {
                               9827                 :           1042 :                     CaseWhen   *when = (CaseWhen *) lfirst(temp);
 7262                          9828                 :           1042 :                     Node       *w = (Node *) when->expr;
                               9829                 :                : 
 7895                          9830         [ +  + ]:           1042 :                     if (caseexpr->arg)
                               9831                 :                :                     {
                               9832                 :                :                         /*
                               9833                 :                :                          * The parser should have produced WHEN clauses of the
                               9834                 :                :                          * form "CaseTestExpr = RHS", possibly with an
                               9835                 :                :                          * implicit coercion inserted above the CaseTestExpr.
                               9836                 :                :                          * For accurate decompilation of rules it's essential
                               9837                 :                :                          * that we show just the RHS.  However in an
                               9838                 :                :                          * expression that's been through the optimizer, the
                               9839                 :                :                          * WHEN clause could be almost anything (since the
                               9840                 :                :                          * equality operator could have been expanded into an
                               9841                 :                :                          * inline function).  If we don't recognize the form
                               9842                 :                :                          * of the WHEN clause, just punt and display it as-is.
                               9843                 :                :                          */
 7262                          9844         [ +  - ]:            399 :                         if (IsA(w, OpExpr))
                               9845                 :                :                         {
 6089                          9846                 :            399 :                             List       *args = ((OpExpr *) w)->args;
                               9847                 :                : 
 5269                          9848         [ +  - ]:            399 :                             if (list_length(args) == 2 &&
                               9849         [ +  - ]:            399 :                                 IsA(strip_implicit_coercions(linitial(args)),
                               9850                 :                :                                     CaseTestExpr))
                               9851                 :            399 :                                 w = (Node *) lsecond(args);
                               9852                 :                :                         }
                               9853                 :                :                     }
                               9854                 :                : 
                               9855         [ +  + ]:           1042 :                     if (!PRETTY_INDENT(context))
                               9856                 :             59 :                         appendStringInfoChar(buf, ' ');
                               9857                 :           1042 :                     appendContextKeyword(context, "WHEN ",
                               9858                 :                :                                          0, 0, 0);
                               9859                 :           1042 :                     get_rule_expr(w, context, false);
 4380 rhaas@postgresql.org     9860                 :           1042 :                     appendStringInfoString(buf, " THEN ");
 8356 tgl@sss.pgh.pa.us        9861                 :           1042 :                     get_rule_expr((Node *) when->result, context, true);
                               9862                 :                :                 }
 8126                          9863         [ +  + ]:            307 :                 if (!PRETTY_INDENT(context))
 8121 bruce@momjian.us         9864                 :             54 :                     appendStringInfoChar(buf, ' ');
 8126 tgl@sss.pgh.pa.us        9865                 :            307 :                 appendContextKeyword(context, "ELSE ",
                               9866                 :                :                                      0, 0, 0);
 8356                          9867                 :            307 :                 get_rule_expr((Node *) caseexpr->defresult, context, true);
 8126                          9868         [ +  + ]:            307 :                 if (!PRETTY_INDENT(context))
 8121 bruce@momjian.us         9869                 :             54 :                     appendStringInfoChar(buf, ' ');
 8126 tgl@sss.pgh.pa.us        9870                 :            307 :                 appendContextKeyword(context, "END",
                               9871                 :                :                                      -PRETTYINDENT_VAR, 0, 0);
                               9872                 :                :             }
 9919 bruce@momjian.us         9873                 :            307 :             break;
                               9874                 :                : 
 5269 tgl@sss.pgh.pa.us        9875                 :UBC           0 :         case T_CaseTestExpr:
                               9876                 :                :             {
                               9877                 :                :                 /*
                               9878                 :                :                  * Normally we should never get here, since for expressions
                               9879                 :                :                  * that can contain this node type we attempt to avoid
                               9880                 :                :                  * recursing to it.  But in an optimized expression we might
                               9881                 :                :                  * be unable to avoid that (see comments for CaseExpr).  If we
                               9882                 :                :                  * do see one, print it as CASE_TEST_EXPR.
                               9883                 :                :                  */
 4380 rhaas@postgresql.org     9884                 :              0 :                 appendStringInfoString(buf, "CASE_TEST_EXPR");
                               9885                 :                :             }
 5269 tgl@sss.pgh.pa.us        9886                 :              0 :             break;
                               9887                 :                : 
 8239 tgl@sss.pgh.pa.us        9888                 :CBC         281 :         case T_ArrayExpr:
                               9889                 :                :             {
 8121 bruce@momjian.us         9890                 :            281 :                 ArrayExpr  *arrayexpr = (ArrayExpr *) node;
                               9891                 :                : 
 4380 rhaas@postgresql.org     9892                 :            281 :                 appendStringInfoString(buf, "ARRAY[");
 7691 tgl@sss.pgh.pa.us        9893                 :            281 :                 get_rule_expr((Node *) arrayexpr->elements, context, true);
                               9894                 :            281 :                 appendStringInfoChar(buf, ']');
                               9895                 :                : 
                               9896                 :                :                 /*
                               9897                 :                :                  * If the array isn't empty, we assume its elements are
                               9898                 :                :                  * coerced to the desired type.  If it's empty, though, we
                               9899                 :                :                  * need an explicit coercion to the array type.
                               9900                 :                :                  */
 6157                          9901         [ +  + ]:            281 :                 if (arrayexpr->elements == NIL)
                               9902                 :              3 :                     appendStringInfo(buf, "::%s",
                               9903                 :                :                                      format_type_with_typemod(arrayexpr->array_typeid, -1));
                               9904                 :                :             }
 8239                          9905                 :            281 :             break;
                               9906                 :                : 
 7841                          9907                 :             96 :         case T_RowExpr:
                               9908                 :                :             {
 7730 bruce@momjian.us         9909                 :             96 :                 RowExpr    *rowexpr = (RowExpr *) node;
 7742 tgl@sss.pgh.pa.us        9910                 :             96 :                 TupleDesc   tupdesc = NULL;
                               9911                 :                :                 ListCell   *arg;
                               9912                 :                :                 int         i;
                               9913                 :                :                 char       *sep;
                               9914                 :                : 
                               9915                 :                :                 /*
                               9916                 :                :                  * If it's a named type and not RECORD, we may have to skip
                               9917                 :                :                  * dropped columns and/or claim there are NULLs for added
                               9918                 :                :                  * columns.
                               9919                 :                :                  */
                               9920         [ +  + ]:             96 :                 if (rowexpr->row_typeid != RECORDOID)
                               9921                 :                :                 {
                               9922                 :             27 :                     tupdesc = lookup_rowtype_tupdesc(rowexpr->row_typeid, -1);
                               9923         [ -  + ]:             27 :                     Assert(list_length(rowexpr->args) <= tupdesc->natts);
                               9924                 :                :                 }
                               9925                 :                : 
                               9926                 :                :                 /*
                               9927                 :                :                  * SQL99 allows "ROW" to be omitted when there is more than
                               9928                 :                :                  * one column, but for simplicity we always print it.
                               9929                 :                :                  */
 4380 rhaas@postgresql.org     9930                 :             96 :                 appendStringInfoString(buf, "ROW(");
 7841 tgl@sss.pgh.pa.us        9931                 :             96 :                 sep = "";
 7742                          9932                 :             96 :                 i = 0;
 7841                          9933   [ +  -  +  +  :            285 :                 foreach(arg, rowexpr->args)
                                              +  + ]
                               9934                 :                :                 {
                               9935                 :            189 :                     Node       *e = (Node *) lfirst(arg);
                               9936                 :                : 
 7742                          9937         [ +  + ]:            189 :                     if (tupdesc == NULL ||
    6 drowley@postgresql.o     9938         [ +  - ]:GNC          60 :                         !TupleDescCompactAttr(tupdesc, i)->attisdropped)
                               9939                 :                :                     {
 7486 neilc@samurai.com        9940                 :CBC         189 :                         appendStringInfoString(buf, sep);
                               9941                 :                :                         /* Whole-row Vars need special treatment here */
 3635 tgl@sss.pgh.pa.us        9942                 :            189 :                         get_rule_expr_toplevel(e, context, true);
 7742                          9943                 :            189 :                         sep = ", ";
                               9944                 :                :                     }
                               9945                 :            189 :                     i++;
                               9946                 :                :                 }
                               9947         [ +  + ]:             96 :                 if (tupdesc != NULL)
                               9948                 :                :                 {
                               9949         [ -  + ]:             27 :                     while (i < tupdesc->natts)
                               9950                 :                :                     {
    6 drowley@postgresql.o     9951         [ #  # ]:UNC           0 :                         if (!TupleDescCompactAttr(tupdesc, i)->attisdropped)
                               9952                 :                :                         {
 7486 neilc@samurai.com        9953                 :UBC           0 :                             appendStringInfoString(buf, sep);
 4380 rhaas@postgresql.org     9954                 :              0 :                             appendStringInfoString(buf, "NULL");
 7742 tgl@sss.pgh.pa.us        9955                 :              0 :                             sep = ", ";
                               9956                 :                :                         }
                               9957                 :              0 :                         i++;
                               9958                 :                :                     }
                               9959                 :                : 
 7074 tgl@sss.pgh.pa.us        9960         [ +  - ]:CBC          27 :                     ReleaseTupleDesc(tupdesc);
                               9961                 :                :                 }
 4380 rhaas@postgresql.org     9962                 :             96 :                 appendStringInfoChar(buf, ')');
 7841 tgl@sss.pgh.pa.us        9963         [ +  + ]:             96 :                 if (rowexpr->row_format == COERCE_EXPLICIT_CAST)
                               9964                 :             18 :                     appendStringInfo(buf, "::%s",
                               9965                 :                :                                      format_type_with_typemod(rowexpr->row_typeid, -1));
                               9966                 :                :             }
                               9967                 :             96 :             break;
                               9968                 :                : 
 7244                          9969                 :             57 :         case T_RowCompareExpr:
                               9970                 :                :             {
                               9971                 :             57 :                 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
                               9972                 :                : 
                               9973                 :                :                 /*
                               9974                 :                :                  * SQL99 allows "ROW" to be omitted when there is more than
                               9975                 :                :                  * one column, but for simplicity we always print it.  Within
                               9976                 :                :                  * a ROW expression, whole-row Vars need special treatment, so
                               9977                 :                :                  * use get_rule_list_toplevel.
                               9978                 :                :                  */
 4380 rhaas@postgresql.org     9979                 :             57 :                 appendStringInfoString(buf, "(ROW(");
 1384 tgl@sss.pgh.pa.us        9980                 :             57 :                 get_rule_list_toplevel(rcexpr->largs, context, true);
                               9981                 :                : 
                               9982                 :                :                 /*
                               9983                 :                :                  * We assume that the name of the first-column operator will
                               9984                 :                :                  * do for all the rest too.  This is definitely open to
                               9985                 :                :                  * failure, eg if some but not all operators were renamed
                               9986                 :                :                  * since the construct was parsed, but there seems no way to
                               9987                 :                :                  * be perfect.
                               9988                 :                :                  */
 7244                          9989                 :             57 :                 appendStringInfo(buf, ") %s ROW(",
 3051                          9990                 :             57 :                                  generate_operator_name(linitial_oid(rcexpr->opnos),
                               9991                 :             57 :                                                         exprType(linitial(rcexpr->largs)),
                               9992                 :             57 :                                                         exprType(linitial(rcexpr->rargs))));
 1384                          9993                 :             57 :                 get_rule_list_toplevel(rcexpr->rargs, context, true);
 4380 rhaas@postgresql.org     9994                 :             57 :                 appendStringInfoString(buf, "))");
                               9995                 :                :             }
 7244 tgl@sss.pgh.pa.us        9996                 :             57 :             break;
                               9997                 :                : 
 8290                          9998                 :            600 :         case T_CoalesceExpr:
                               9999                 :                :             {
                              10000                 :            600 :                 CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
                              10001                 :                : 
 4380 rhaas@postgresql.org    10002                 :            600 :                 appendStringInfoString(buf, "COALESCE(");
 7691 tgl@sss.pgh.pa.us       10003                 :            600 :                 get_rule_expr((Node *) coalesceexpr->args, context, true);
                              10004                 :            600 :                 appendStringInfoChar(buf, ')');
                              10005                 :                :             }
 8290                         10006                 :            600 :             break;
                              10007                 :                : 
 7429                         10008                 :             18 :         case T_MinMaxExpr:
                              10009                 :                :             {
                              10010                 :             18 :                 MinMaxExpr *minmaxexpr = (MinMaxExpr *) node;
                              10011                 :                : 
                              10012      [ +  +  - ]:             18 :                 switch (minmaxexpr->op)
                              10013                 :                :                 {
                              10014                 :              3 :                     case IS_GREATEST:
 4380 rhaas@postgresql.org    10015                 :              3 :                         appendStringInfoString(buf, "GREATEST(");
 7429 tgl@sss.pgh.pa.us       10016                 :              3 :                         break;
                              10017                 :             15 :                     case IS_LEAST:
 4380 rhaas@postgresql.org    10018                 :             15 :                         appendStringInfoString(buf, "LEAST(");
 7429 tgl@sss.pgh.pa.us       10019                 :             15 :                         break;
                              10020                 :                :                 }
                              10021                 :             18 :                 get_rule_expr((Node *) minmaxexpr->args, context, true);
                              10022                 :             18 :                 appendStringInfoChar(buf, ')');
                              10023                 :                :             }
                              10024                 :             18 :             break;
                              10025                 :                : 
  895 michael@paquier.xyz     10026                 :            358 :         case T_SQLValueFunction:
                              10027                 :                :             {
                              10028                 :            358 :                 SQLValueFunction *svf = (SQLValueFunction *) node;
                              10029                 :                : 
                              10030                 :                :                 /*
                              10031                 :                :                  * Note: this code knows that typmod for time, timestamp, and
                              10032                 :                :                  * timestamptz just prints as integer.
                              10033                 :                :                  */
                              10034   [ +  +  +  +  :            358 :                 switch (svf->op)
                                     +  +  +  +  +  
                                     +  +  +  +  +  
                                              +  - ]
                              10035                 :                :                 {
                              10036                 :             52 :                     case SVFOP_CURRENT_DATE:
                              10037                 :             52 :                         appendStringInfoString(buf, "CURRENT_DATE");
                              10038                 :             52 :                         break;
                              10039                 :              6 :                     case SVFOP_CURRENT_TIME:
                              10040                 :              6 :                         appendStringInfoString(buf, "CURRENT_TIME");
                              10041                 :              6 :                         break;
                              10042                 :              6 :                     case SVFOP_CURRENT_TIME_N:
                              10043                 :              6 :                         appendStringInfo(buf, "CURRENT_TIME(%d)", svf->typmod);
                              10044                 :              6 :                         break;
                              10045                 :              6 :                     case SVFOP_CURRENT_TIMESTAMP:
                              10046                 :              6 :                         appendStringInfoString(buf, "CURRENT_TIMESTAMP");
                              10047                 :              6 :                         break;
                              10048                 :             63 :                     case SVFOP_CURRENT_TIMESTAMP_N:
                              10049                 :             63 :                         appendStringInfo(buf, "CURRENT_TIMESTAMP(%d)",
                              10050                 :                :                                          svf->typmod);
                              10051                 :             63 :                         break;
                              10052                 :              6 :                     case SVFOP_LOCALTIME:
                              10053                 :              6 :                         appendStringInfoString(buf, "LOCALTIME");
                              10054                 :              6 :                         break;
                              10055                 :              6 :                     case SVFOP_LOCALTIME_N:
                              10056                 :              6 :                         appendStringInfo(buf, "LOCALTIME(%d)", svf->typmod);
                              10057                 :              6 :                         break;
                              10058                 :             15 :                     case SVFOP_LOCALTIMESTAMP:
                              10059                 :             15 :                         appendStringInfoString(buf, "LOCALTIMESTAMP");
                              10060                 :             15 :                         break;
                              10061                 :              9 :                     case SVFOP_LOCALTIMESTAMP_N:
                              10062                 :              9 :                         appendStringInfo(buf, "LOCALTIMESTAMP(%d)",
                              10063                 :                :                                          svf->typmod);
                              10064                 :              9 :                         break;
                              10065                 :              6 :                     case SVFOP_CURRENT_ROLE:
                              10066                 :              6 :                         appendStringInfoString(buf, "CURRENT_ROLE");
                              10067                 :              6 :                         break;
                              10068                 :            148 :                     case SVFOP_CURRENT_USER:
                              10069                 :            148 :                         appendStringInfoString(buf, "CURRENT_USER");
                              10070                 :            148 :                         break;
                              10071                 :              6 :                     case SVFOP_USER:
                              10072                 :              6 :                         appendStringInfoString(buf, "USER");
                              10073                 :              6 :                         break;
                              10074                 :             17 :                     case SVFOP_SESSION_USER:
                              10075                 :             17 :                         appendStringInfoString(buf, "SESSION_USER");
                              10076                 :             17 :                         break;
                              10077                 :              6 :                     case SVFOP_CURRENT_CATALOG:
                              10078                 :              6 :                         appendStringInfoString(buf, "CURRENT_CATALOG");
                              10079                 :              6 :                         break;
                              10080                 :              6 :                     case SVFOP_CURRENT_SCHEMA:
                              10081                 :              6 :                         appendStringInfoString(buf, "CURRENT_SCHEMA");
                              10082                 :              6 :                         break;
                              10083                 :                :                 }
                              10084                 :                :             }
                              10085                 :            358 :             break;
                              10086                 :                : 
 6883 tgl@sss.pgh.pa.us       10087                 :             88 :         case T_XmlExpr:
                              10088                 :                :             {
 6557 bruce@momjian.us        10089                 :             88 :                 XmlExpr    *xexpr = (XmlExpr *) node;
                              10090                 :             88 :                 bool        needcomma = false;
                              10091                 :                :                 ListCell   *arg;
                              10092                 :                :                 ListCell   *narg;
                              10093                 :                :                 Const      *con;
                              10094                 :                : 
 6883 tgl@sss.pgh.pa.us       10095   [ +  +  +  +  :             88 :                 switch (xexpr->op)
                                        +  +  +  -  
                                                 - ]
                              10096                 :                :                 {
                              10097                 :              8 :                     case IS_XMLCONCAT:
                              10098                 :              8 :                         appendStringInfoString(buf, "XMLCONCAT(");
                              10099                 :              8 :                         break;
                              10100                 :             16 :                     case IS_XMLELEMENT:
                              10101                 :             16 :                         appendStringInfoString(buf, "XMLELEMENT(");
                              10102                 :             16 :                         break;
                              10103                 :              8 :                     case IS_XMLFOREST:
                              10104                 :              8 :                         appendStringInfoString(buf, "XMLFOREST(");
                              10105                 :              8 :                         break;
                              10106                 :              8 :                     case IS_XMLPARSE:
                              10107                 :              8 :                         appendStringInfoString(buf, "XMLPARSE(");
                              10108                 :              8 :                         break;
                              10109                 :              8 :                     case IS_XMLPI:
                              10110                 :              8 :                         appendStringInfoString(buf, "XMLPI(");
                              10111                 :              8 :                         break;
                              10112                 :              8 :                     case IS_XMLROOT:
                              10113                 :              8 :                         appendStringInfoString(buf, "XMLROOT(");
                              10114                 :              8 :                         break;
 6842 peter_e@gmx.net         10115                 :             32 :                     case IS_XMLSERIALIZE:
                              10116                 :             32 :                         appendStringInfoString(buf, "XMLSERIALIZE(");
                              10117                 :             32 :                         break;
 6862 peter_e@gmx.net         10118                 :UBC           0 :                     case IS_DOCUMENT:
                              10119                 :              0 :                         break;
                              10120                 :                :                 }
 6842 peter_e@gmx.net         10121   [ +  +  +  + ]:CBC          88 :                 if (xexpr->op == IS_XMLPARSE || xexpr->op == IS_XMLSERIALIZE)
                              10122                 :                :                 {
                              10123         [ +  + ]:             40 :                     if (xexpr->xmloption == XMLOPTION_DOCUMENT)
                              10124                 :             16 :                         appendStringInfoString(buf, "DOCUMENT ");
                              10125                 :                :                     else
                              10126                 :             24 :                         appendStringInfoString(buf, "CONTENT ");
                              10127                 :                :                 }
 6883 tgl@sss.pgh.pa.us       10128         [ +  + ]:             88 :                 if (xexpr->name)
                              10129                 :                :                 {
                              10130                 :             24 :                     appendStringInfo(buf, "NAME %s",
 6878 peter_e@gmx.net         10131                 :             24 :                                      quote_identifier(map_xml_name_to_sql_identifier(xexpr->name)));
 6883 tgl@sss.pgh.pa.us       10132                 :             24 :                     needcomma = true;
                              10133                 :                :                 }
                              10134         [ +  + ]:             88 :                 if (xexpr->named_args)
                              10135                 :                :                 {
                              10136         [ +  + ]:             16 :                     if (xexpr->op != IS_XMLFOREST)
                              10137                 :                :                     {
                              10138         [ +  - ]:              8 :                         if (needcomma)
                              10139                 :              8 :                             appendStringInfoString(buf, ", ");
                              10140                 :              8 :                         appendStringInfoString(buf, "XMLATTRIBUTES(");
                              10141                 :              8 :                         needcomma = false;
                              10142                 :                :                     }
                              10143   [ +  -  +  +  :             56 :                     forboth(arg, xexpr->named_args, narg, xexpr->arg_names)
                                     +  -  +  +  +  
                                        +  +  -  +  
                                                 + ]
                              10144                 :                :                     {
 6557 bruce@momjian.us        10145                 :             40 :                         Node       *e = (Node *) lfirst(arg);
                              10146                 :             40 :                         char       *argname = strVal(lfirst(narg));
                              10147                 :                : 
 6883 tgl@sss.pgh.pa.us       10148         [ +  + ]:             40 :                         if (needcomma)
                              10149                 :             24 :                             appendStringInfoString(buf, ", ");
                              10150                 :             40 :                         get_rule_expr((Node *) e, context, true);
                              10151                 :             40 :                         appendStringInfo(buf, " AS %s",
 6878 peter_e@gmx.net         10152                 :             40 :                                          quote_identifier(map_xml_name_to_sql_identifier(argname)));
 6883 tgl@sss.pgh.pa.us       10153                 :             40 :                         needcomma = true;
                              10154                 :                :                     }
                              10155         [ +  + ]:             16 :                     if (xexpr->op != IS_XMLFOREST)
                              10156                 :              8 :                         appendStringInfoChar(buf, ')');
                              10157                 :                :                 }
                              10158         [ +  + ]:             88 :                 if (xexpr->args)
                              10159                 :                :                 {
                              10160         [ +  + ]:             80 :                     if (needcomma)
                              10161                 :             24 :                         appendStringInfoString(buf, ", ");
                              10162   [ +  +  +  -  :             80 :                     switch (xexpr->op)
                                                 - ]
                              10163                 :                :                     {
                              10164                 :             64 :                         case IS_XMLCONCAT:
                              10165                 :                :                         case IS_XMLELEMENT:
                              10166                 :                :                         case IS_XMLFOREST:
                              10167                 :                :                         case IS_XMLPI:
                              10168                 :                :                         case IS_XMLSERIALIZE:
                              10169                 :                :                             /* no extra decoration needed */
                              10170                 :             64 :                             get_rule_expr((Node *) xexpr->args, context, true);
                              10171                 :             64 :                             break;
                              10172                 :              8 :                         case IS_XMLPARSE:
 6842 peter_e@gmx.net         10173         [ -  + ]:              8 :                             Assert(list_length(xexpr->args) == 2);
                              10174                 :                : 
 6883 tgl@sss.pgh.pa.us       10175                 :              8 :                             get_rule_expr((Node *) linitial(xexpr->args),
                              10176                 :                :                                           context, true);
                              10177                 :                : 
 3123                         10178                 :              8 :                             con = lsecond_node(Const, xexpr->args);
 6883                         10179         [ -  + ]:              8 :                             Assert(!con->constisnull);
                              10180         [ -  + ]:              8 :                             if (DatumGetBool(con->constvalue))
 6883 tgl@sss.pgh.pa.us       10181                 :UBC           0 :                                 appendStringInfoString(buf,
                              10182                 :                :                                                        " PRESERVE WHITESPACE");
                              10183                 :                :                             else
 6883 tgl@sss.pgh.pa.us       10184                 :CBC           8 :                                 appendStringInfoString(buf,
                              10185                 :                :                                                        " STRIP WHITESPACE");
                              10186                 :              8 :                             break;
                              10187                 :              8 :                         case IS_XMLROOT:
                              10188         [ -  + ]:              8 :                             Assert(list_length(xexpr->args) == 3);
                              10189                 :                : 
                              10190                 :              8 :                             get_rule_expr((Node *) linitial(xexpr->args),
                              10191                 :                :                                           context, true);
                              10192                 :                : 
                              10193                 :              8 :                             appendStringInfoString(buf, ", VERSION ");
                              10194                 :              8 :                             con = (Const *) lsecond(xexpr->args);
                              10195         [ +  - ]:              8 :                             if (IsA(con, Const) &&
                              10196         [ +  - ]:              8 :                                 con->constisnull)
                              10197                 :              8 :                                 appendStringInfoString(buf, "NO VALUE");
                              10198                 :                :                             else
 6883 tgl@sss.pgh.pa.us       10199                 :UBC           0 :                                 get_rule_expr((Node *) con, context, false);
                              10200                 :                : 
 3123 tgl@sss.pgh.pa.us       10201                 :CBC           8 :                             con = lthird_node(Const, xexpr->args);
 6883                         10202         [ +  - ]:              8 :                             if (con->constisnull)
                              10203                 :                :                                  /* suppress STANDALONE NO VALUE */ ;
                              10204                 :                :                             else
                              10205                 :                :                             {
 6842 peter_e@gmx.net         10206   [ +  -  -  - ]:              8 :                                 switch (DatumGetInt32(con->constvalue))
                              10207                 :                :                                 {
                              10208                 :              8 :                                     case XML_STANDALONE_YES:
                              10209                 :              8 :                                         appendStringInfoString(buf,
                              10210                 :                :                                                                ", STANDALONE YES");
                              10211                 :              8 :                                         break;
 6842 peter_e@gmx.net         10212                 :UBC           0 :                                     case XML_STANDALONE_NO:
                              10213                 :              0 :                                         appendStringInfoString(buf,
                              10214                 :                :                                                                ", STANDALONE NO");
                              10215                 :              0 :                                         break;
                              10216                 :              0 :                                     case XML_STANDALONE_NO_VALUE:
                              10217                 :              0 :                                         appendStringInfoString(buf,
                              10218                 :                :                                                                ", STANDALONE NO VALUE");
                              10219                 :              0 :                                         break;
                              10220                 :              0 :                                     default:
                              10221                 :              0 :                                         break;
                              10222                 :                :                                 }
                              10223                 :                :                             }
 6883 tgl@sss.pgh.pa.us       10224                 :CBC           8 :                             break;
 6862 peter_e@gmx.net         10225                 :UBC           0 :                         case IS_DOCUMENT:
                              10226                 :              0 :                             get_rule_expr_paren((Node *) xexpr->args, context, false, node);
                              10227                 :              0 :                             break;
                              10228                 :                :                     }
                              10229                 :                :                 }
 6842 peter_e@gmx.net         10230         [ +  + ]:CBC          88 :                 if (xexpr->op == IS_XMLSERIALIZE)
                              10231                 :                :                 {
 5337 tgl@sss.pgh.pa.us       10232                 :             32 :                     appendStringInfo(buf, " AS %s",
                              10233                 :                :                                      format_type_with_typemod(xexpr->type,
                              10234                 :                :                                                               xexpr->typmod));
  249 michael@paquier.xyz     10235         [ +  + ]:             32 :                     if (xexpr->indent)
                              10236                 :              8 :                         appendStringInfoString(buf, " INDENT");
                              10237                 :                :                     else
                              10238                 :             24 :                         appendStringInfoString(buf, " NO INDENT");
                              10239                 :                :                 }
                              10240                 :                : 
 6862 peter_e@gmx.net         10241         [ -  + ]:             88 :                 if (xexpr->op == IS_DOCUMENT)
 6862 peter_e@gmx.net         10242                 :UBC           0 :                     appendStringInfoString(buf, " IS DOCUMENT");
                              10243                 :                :                 else
 6862 peter_e@gmx.net         10244                 :CBC          88 :                     appendStringInfoChar(buf, ')');
                              10245                 :                :             }
 6883 tgl@sss.pgh.pa.us       10246                 :             88 :             break;
                              10247                 :                : 
 8897                         10248                 :           1308 :         case T_NullTest:
                              10249                 :                :             {
 8769 bruce@momjian.us        10250                 :           1308 :                 NullTest   *ntest = (NullTest *) node;
                              10251                 :                : 
 8126 tgl@sss.pgh.pa.us       10252         [ +  + ]:           1308 :                 if (!PRETTY_PAREN(context))
 8121 bruce@momjian.us        10253                 :           1280 :                     appendStringInfoChar(buf, '(');
 8126 tgl@sss.pgh.pa.us       10254                 :           1308 :                 get_rule_expr_paren((Node *) ntest->arg, context, true, node);
                              10255                 :                : 
                              10256                 :                :                 /*
                              10257                 :                :                  * For scalar inputs, we prefer to print as IS [NOT] NULL,
                              10258                 :                :                  * which is shorter and traditional.  If it's a rowtype input
                              10259                 :                :                  * but we're applying a scalar test, must print IS [NOT]
                              10260                 :                :                  * DISTINCT FROM NULL to be semantically correct.
                              10261                 :                :                  */
 3379                         10262         [ +  + ]:           1308 :                 if (ntest->argisrow ||
                              10263         [ +  + ]:           1277 :                     !type_is_rowtype(exprType((Node *) ntest->arg)))
                              10264                 :                :                 {
                              10265      [ +  +  - ]:           1299 :                     switch (ntest->nulltesttype)
                              10266                 :                :                     {
                              10267                 :            412 :                         case IS_NULL:
                              10268                 :            412 :                             appendStringInfoString(buf, " IS NULL");
                              10269                 :            412 :                             break;
                              10270                 :            887 :                         case IS_NOT_NULL:
                              10271                 :            887 :                             appendStringInfoString(buf, " IS NOT NULL");
                              10272                 :            887 :                             break;
 3379 tgl@sss.pgh.pa.us       10273                 :UBC           0 :                         default:
                              10274         [ #  # ]:              0 :                             elog(ERROR, "unrecognized nulltesttype: %d",
                              10275                 :                :                                  (int) ntest->nulltesttype);
                              10276                 :                :                     }
                              10277                 :                :                 }
                              10278                 :                :                 else
                              10279                 :                :                 {
 3379 tgl@sss.pgh.pa.us       10280      [ +  +  - ]:CBC           9 :                     switch (ntest->nulltesttype)
                              10281                 :                :                     {
                              10282                 :              3 :                         case IS_NULL:
                              10283                 :              3 :                             appendStringInfoString(buf, " IS NOT DISTINCT FROM NULL");
                              10284                 :              3 :                             break;
                              10285                 :              6 :                         case IS_NOT_NULL:
                              10286                 :              6 :                             appendStringInfoString(buf, " IS DISTINCT FROM NULL");
                              10287                 :              6 :                             break;
 3379 tgl@sss.pgh.pa.us       10288                 :UBC           0 :                         default:
                              10289         [ #  # ]:              0 :                             elog(ERROR, "unrecognized nulltesttype: %d",
                              10290                 :                :                                  (int) ntest->nulltesttype);
                              10291                 :                :                     }
                              10292                 :                :                 }
 8126 tgl@sss.pgh.pa.us       10293         [ +  + ]:CBC        1308 :                 if (!PRETTY_PAREN(context))
 8121 bruce@momjian.us        10294                 :           1280 :                     appendStringInfoChar(buf, ')');
                              10295                 :                :             }
 8897 tgl@sss.pgh.pa.us       10296                 :           1308 :             break;
                              10297                 :                : 
                              10298                 :            153 :         case T_BooleanTest:
                              10299                 :                :             {
 8769 bruce@momjian.us        10300                 :            153 :                 BooleanTest *btest = (BooleanTest *) node;
                              10301                 :                : 
 8126 tgl@sss.pgh.pa.us       10302         [ +  - ]:            153 :                 if (!PRETTY_PAREN(context))
 8121 bruce@momjian.us        10303                 :            153 :                     appendStringInfoChar(buf, '(');
 8126 tgl@sss.pgh.pa.us       10304                 :            153 :                 get_rule_expr_paren((Node *) btest->arg, context, false, node);
 8769 bruce@momjian.us        10305   [ +  +  -  +  :            153 :                 switch (btest->booltesttype)
                                           +  +  - ]
                              10306                 :                :                 {
                              10307                 :             18 :                     case IS_TRUE:
 4380 rhaas@postgresql.org    10308                 :             18 :                         appendStringInfoString(buf, " IS TRUE");
 8897 tgl@sss.pgh.pa.us       10309                 :             18 :                         break;
 8769 bruce@momjian.us        10310                 :             69 :                     case IS_NOT_TRUE:
 4380 rhaas@postgresql.org    10311                 :             69 :                         appendStringInfoString(buf, " IS NOT TRUE");
 8897 tgl@sss.pgh.pa.us       10312                 :             69 :                         break;
 8769 bruce@momjian.us        10313                 :UBC           0 :                     case IS_FALSE:
 4380 rhaas@postgresql.org    10314                 :              0 :                         appendStringInfoString(buf, " IS FALSE");
 8897 tgl@sss.pgh.pa.us       10315                 :              0 :                         break;
 8769 bruce@momjian.us        10316                 :CBC          27 :                     case IS_NOT_FALSE:
 4380 rhaas@postgresql.org    10317                 :             27 :                         appendStringInfoString(buf, " IS NOT FALSE");
 8897 tgl@sss.pgh.pa.us       10318                 :             27 :                         break;
 8769 bruce@momjian.us        10319                 :             12 :                     case IS_UNKNOWN:
 4380 rhaas@postgresql.org    10320                 :             12 :                         appendStringInfoString(buf, " IS UNKNOWN");
 8897 tgl@sss.pgh.pa.us       10321                 :             12 :                         break;
 8769 bruce@momjian.us        10322                 :             27 :                     case IS_NOT_UNKNOWN:
 4380 rhaas@postgresql.org    10323                 :             27 :                         appendStringInfoString(buf, " IS NOT UNKNOWN");
 8897 tgl@sss.pgh.pa.us       10324                 :             27 :                         break;
 8769 bruce@momjian.us        10325                 :UBC           0 :                     default:
 8129 tgl@sss.pgh.pa.us       10326         [ #  # ]:              0 :                         elog(ERROR, "unrecognized booltesttype: %d",
                              10327                 :                :                              (int) btest->booltesttype);
                              10328                 :                :                 }
 8126 tgl@sss.pgh.pa.us       10329         [ +  - ]:CBC         153 :                 if (!PRETTY_PAREN(context))
 8121 bruce@momjian.us        10330                 :            153 :                     appendStringInfoChar(buf, ')');
                              10331                 :                :             }
 8897 tgl@sss.pgh.pa.us       10332                 :            153 :             break;
                              10333                 :                : 
 8303                         10334                 :             58 :         case T_CoerceToDomain:
                              10335                 :                :             {
                              10336                 :             58 :                 CoerceToDomain *ctest = (CoerceToDomain *) node;
 8121 bruce@momjian.us        10337                 :             58 :                 Node       *arg = (Node *) ctest->arg;
                              10338                 :                : 
 8303 tgl@sss.pgh.pa.us       10339         [ +  + ]:             58 :                 if (ctest->coercionformat == COERCE_IMPLICIT_CAST &&
                              10340         [ +  + ]:             24 :                     !showimplicit)
                              10341                 :                :                 {
                              10342                 :                :                     /* don't show the implicit cast */
                              10343                 :             16 :                     get_rule_expr(arg, context, false);
                              10344                 :                :                 }
                              10345                 :                :                 else
                              10346                 :                :                 {
 6800                         10347                 :             42 :                     get_coercion_expr(arg, context,
                              10348                 :                :                                       ctest->resulttype,
                              10349                 :                :                                       ctest->resulttypmod,
                              10350                 :                :                                       node);
                              10351                 :                :                 }
                              10352                 :                :             }
 8459                         10353                 :             58 :             break;
                              10354                 :                : 
 8303                         10355                 :            219 :         case T_CoerceToDomainValue:
 4380 rhaas@postgresql.org    10356                 :            219 :             appendStringInfoString(buf, "VALUE");
 8631 tgl@sss.pgh.pa.us       10357                 :            219 :             break;
                              10358                 :                : 
 8153                         10359                 :             38 :         case T_SetToDefault:
 4380 rhaas@postgresql.org    10360                 :             38 :             appendStringInfoString(buf, "DEFAULT");
 8153 tgl@sss.pgh.pa.us       10361                 :             38 :             break;
                              10362                 :                : 
 6714                         10363                 :             12 :         case T_CurrentOfExpr:
                              10364                 :                :             {
                              10365                 :             12 :                 CurrentOfExpr *cexpr = (CurrentOfExpr *) node;
                              10366                 :                : 
                              10367         [ +  - ]:             12 :                 if (cexpr->cursor_name)
                              10368                 :             12 :                     appendStringInfo(buf, "CURRENT OF %s",
                              10369                 :             12 :                                      quote_identifier(cexpr->cursor_name));
                              10370                 :                :                 else
 6714 tgl@sss.pgh.pa.us       10371                 :UBC           0 :                     appendStringInfo(buf, "CURRENT OF $%d",
                              10372                 :                :                                      cexpr->cursor_param);
                              10373                 :                :             }
 6714 tgl@sss.pgh.pa.us       10374                 :CBC          12 :             break;
                              10375                 :                : 
 3028 tgl@sss.pgh.pa.us       10376                 :UBC           0 :         case T_NextValueExpr:
                              10377                 :                :             {
                              10378                 :              0 :                 NextValueExpr *nvexpr = (NextValueExpr *) node;
                              10379                 :                : 
                              10380                 :                :                 /*
                              10381                 :                :                  * This isn't exactly nextval(), but that seems close enough
                              10382                 :                :                  * for EXPLAIN's purposes.
                              10383                 :                :                  */
                              10384                 :              0 :                 appendStringInfoString(buf, "nextval(");
                              10385                 :              0 :                 simple_quote_literal(buf,
                              10386                 :              0 :                                      generate_relation_name(nvexpr->seqid,
                              10387                 :                :                                                             NIL));
                              10388                 :              0 :                 appendStringInfoChar(buf, ')');
                              10389                 :                :             }
                              10390                 :              0 :             break;
                              10391                 :                : 
 3815 andres@anarazel.de      10392                 :CBC          12 :         case T_InferenceElem:
                              10393                 :                :             {
 3811 bruce@momjian.us        10394                 :             12 :                 InferenceElem *iexpr = (InferenceElem *) node;
                              10395                 :                :                 bool        save_varprefix;
                              10396                 :                :                 bool        need_parens;
                              10397                 :                : 
                              10398                 :                :                 /*
                              10399                 :                :                  * InferenceElem can only refer to target relation, so a
                              10400                 :                :                  * prefix is not useful, and indeed would cause parse errors.
                              10401                 :                :                  */
 3551 tgl@sss.pgh.pa.us       10402                 :             12 :                 save_varprefix = context->varprefix;
 3815 andres@anarazel.de      10403                 :             12 :                 context->varprefix = false;
                              10404                 :                : 
                              10405                 :                :                 /*
                              10406                 :                :                  * Parenthesize the element unless it's a simple Var or a bare
                              10407                 :                :                  * function call.  Follows pg_get_indexdef_worker().
                              10408                 :                :                  */
                              10409                 :             12 :                 need_parens = !IsA(iexpr->expr, Var);
                              10410         [ -  + ]:             12 :                 if (IsA(iexpr->expr, FuncExpr) &&
 3815 andres@anarazel.de      10411         [ #  # ]:UBC           0 :                     ((FuncExpr *) iexpr->expr)->funcformat ==
                              10412                 :                :                     COERCE_EXPLICIT_CALL)
                              10413                 :              0 :                     need_parens = false;
                              10414                 :                : 
 3815 andres@anarazel.de      10415         [ -  + ]:CBC          12 :                 if (need_parens)
 3815 andres@anarazel.de      10416                 :UBC           0 :                     appendStringInfoChar(buf, '(');
 3815 andres@anarazel.de      10417                 :CBC          12 :                 get_rule_expr((Node *) iexpr->expr,
                              10418                 :                :                               context, false);
                              10419         [ -  + ]:             12 :                 if (need_parens)
 3815 andres@anarazel.de      10420                 :UBC           0 :                     appendStringInfoChar(buf, ')');
                              10421                 :                : 
 3551 tgl@sss.pgh.pa.us       10422                 :CBC          12 :                 context->varprefix = save_varprefix;
                              10423                 :                : 
 3815 andres@anarazel.de      10424         [ +  + ]:             12 :                 if (iexpr->infercollid)
                              10425                 :              6 :                     appendStringInfo(buf, " COLLATE %s",
                              10426                 :                :                                      generate_collation_name(iexpr->infercollid));
                              10427                 :                : 
                              10428                 :                :                 /* Add the operator class name, if not default */
                              10429         [ +  + ]:             12 :                 if (iexpr->inferopclass)
                              10430                 :                :                 {
 3811 bruce@momjian.us        10431                 :              6 :                     Oid         inferopclass = iexpr->inferopclass;
                              10432                 :              6 :                     Oid         inferopcinputtype = get_opclass_input_type(iexpr->inferopclass);
                              10433                 :                : 
 3815 andres@anarazel.de      10434                 :              6 :                     get_opclass_name(inferopclass, inferopcinputtype, buf);
                              10435                 :                :                 }
                              10436                 :                :             }
                              10437                 :             12 :             break;
                              10438                 :                : 
  285 dean.a.rasheed@gmail    10439                 :              6 :         case T_ReturningExpr:
                              10440                 :                :             {
                              10441                 :              6 :                 ReturningExpr *retExpr = (ReturningExpr *) node;
                              10442                 :                : 
                              10443                 :                :                 /*
                              10444                 :                :                  * We cannot see a ReturningExpr in rule deparsing, only while
                              10445                 :                :                  * EXPLAINing a query plan (ReturningExpr nodes are only ever
                              10446                 :                :                  * adding during query rewriting). Just display the expression
                              10447                 :                :                  * returned (an expanded view column).
                              10448                 :                :                  */
                              10449                 :              6 :                 get_rule_expr((Node *) retExpr->retexpr, context, showimplicit);
                              10450                 :                :             }
                              10451                 :              6 :             break;
                              10452                 :                : 
 3247 rhaas@postgresql.org    10453                 :           2064 :         case T_PartitionBoundSpec:
                              10454                 :                :             {
                              10455                 :           2064 :                 PartitionBoundSpec *spec = (PartitionBoundSpec *) node;
                              10456                 :                :                 ListCell   *cell;
                              10457                 :                :                 char       *sep;
                              10458                 :                : 
 2972                         10459         [ +  + ]:           2064 :                 if (spec->is_default)
                              10460                 :                :                 {
                              10461                 :             78 :                     appendStringInfoString(buf, "DEFAULT");
                              10462                 :             78 :                     break;
                              10463                 :                :                 }
                              10464                 :                : 
 3247                         10465   [ +  +  +  - ]:           1986 :                 switch (spec->strategy)
                              10466                 :                :                 {
 2910                         10467                 :            153 :                     case PARTITION_STRATEGY_HASH:
                              10468   [ +  -  -  + ]:            153 :                         Assert(spec->modulus > 0 && spec->remainder >= 0);
                              10469         [ -  + ]:            153 :                         Assert(spec->modulus > spec->remainder);
                              10470                 :                : 
                              10471                 :            153 :                         appendStringInfoString(buf, "FOR VALUES");
                              10472                 :            153 :                         appendStringInfo(buf, " WITH (modulus %d, remainder %d)",
                              10473                 :                :                                          spec->modulus, spec->remainder);
                              10474                 :            153 :                         break;
                              10475                 :                : 
 3247                         10476                 :            690 :                     case PARTITION_STRATEGY_LIST:
                              10477         [ -  + ]:            690 :                         Assert(spec->listdatums != NIL);
                              10478                 :                : 
 3075 tgl@sss.pgh.pa.us       10479                 :            690 :                         appendStringInfoString(buf, "FOR VALUES IN (");
 3247 rhaas@postgresql.org    10480                 :            690 :                         sep = "";
 3199                         10481   [ +  -  +  +  :           1833 :                         foreach(cell, spec->listdatums)
                                              +  + ]
                              10482                 :                :                         {
 1562 peter@eisentraut.org    10483                 :           1143 :                             Const      *val = lfirst_node(Const, cell);
                              10484                 :                : 
 3247 rhaas@postgresql.org    10485                 :           1143 :                             appendStringInfoString(buf, sep);
                              10486                 :           1143 :                             get_const_expr(val, context, -1);
                              10487                 :           1143 :                             sep = ", ";
                              10488                 :                :                         }
                              10489                 :                : 
 2996 peter_e@gmx.net         10490                 :            690 :                         appendStringInfoChar(buf, ')');
 3247 rhaas@postgresql.org    10491                 :            690 :                         break;
                              10492                 :                : 
                              10493                 :           1143 :                     case PARTITION_STRATEGY_RANGE:
                              10494   [ +  -  +  -  :           1143 :                         Assert(spec->lowerdatums != NIL &&
                                              -  + ]
                              10495                 :                :                                spec->upperdatums != NIL &&
                              10496                 :                :                                list_length(spec->lowerdatums) ==
                              10497                 :                :                                list_length(spec->upperdatums));
                              10498                 :                : 
 3001                         10499                 :           1143 :                         appendStringInfo(buf, "FOR VALUES FROM %s TO %s",
                              10500                 :                :                                          get_range_partbound_string(spec->lowerdatums),
                              10501                 :                :                                          get_range_partbound_string(spec->upperdatums));
 3247                         10502                 :           1143 :                         break;
                              10503                 :                : 
 3247 rhaas@postgresql.org    10504                 :UBC           0 :                     default:
                              10505         [ #  # ]:              0 :                         elog(ERROR, "unrecognized partition strategy: %d",
                              10506                 :                :                              (int) spec->strategy);
                              10507                 :                :                         break;
                              10508                 :                :                 }
                              10509                 :                :             }
 3247 rhaas@postgresql.org    10510                 :CBC        1986 :             break;
                              10511                 :                : 
  944 alvherre@alvh.no-ip.    10512                 :             75 :         case T_JsonValueExpr:
                              10513                 :                :             {
                              10514                 :             75 :                 JsonValueExpr *jve = (JsonValueExpr *) node;
                              10515                 :                : 
                              10516                 :             75 :                 get_rule_expr((Node *) jve->raw_expr, context, false);
                              10517                 :             75 :                 get_json_format(jve->format, context->buf);
                              10518                 :                :             }
                              10519                 :             75 :             break;
                              10520                 :                : 
                              10521                 :             93 :         case T_JsonConstructorExpr:
                              10522                 :             93 :             get_json_constructor((JsonConstructorExpr *) node, context, false);
                              10523                 :             93 :             break;
                              10524                 :                : 
  942                         10525                 :             30 :         case T_JsonIsPredicate:
                              10526                 :                :             {
                              10527                 :             30 :                 JsonIsPredicate *pred = (JsonIsPredicate *) node;
                              10528                 :                : 
                              10529         [ +  + ]:             30 :                 if (!PRETTY_PAREN(context))
                              10530                 :             15 :                     appendStringInfoChar(context->buf, '(');
                              10531                 :                : 
                              10532                 :             30 :                 get_rule_expr_paren(pred->expr, context, true, node);
                              10533                 :                : 
                              10534                 :             30 :                 appendStringInfoString(context->buf, " IS JSON");
                              10535                 :                : 
                              10536                 :                :                 /* TODO: handle FORMAT clause */
                              10537                 :                : 
                              10538   [ +  +  +  + ]:             30 :                 switch (pred->item_type)
                              10539                 :                :                 {
                              10540                 :              6 :                     case JS_TYPE_SCALAR:
                              10541                 :              6 :                         appendStringInfoString(context->buf, " SCALAR");
                              10542                 :              6 :                         break;
                              10543                 :              6 :                     case JS_TYPE_ARRAY:
                              10544                 :              6 :                         appendStringInfoString(context->buf, " ARRAY");
                              10545                 :              6 :                         break;
                              10546                 :              6 :                     case JS_TYPE_OBJECT:
                              10547                 :              6 :                         appendStringInfoString(context->buf, " OBJECT");
                              10548                 :              6 :                         break;
                              10549                 :             12 :                     default:
                              10550                 :             12 :                         break;
                              10551                 :                :                 }
                              10552                 :                : 
                              10553         [ +  + ]:             30 :                 if (pred->unique_keys)
                              10554                 :              6 :                     appendStringInfoString(context->buf, " WITH UNIQUE KEYS");
                              10555                 :                : 
                              10556         [ +  + ]:             30 :                 if (!PRETTY_PAREN(context))
                              10557                 :             15 :                     appendStringInfoChar(context->buf, ')');
                              10558                 :                :             }
                              10559                 :             30 :             break;
                              10560                 :                : 
  586 amitlan@postgresql.o    10561                 :             30 :         case T_JsonExpr:
                              10562                 :                :             {
                              10563                 :             30 :                 JsonExpr   *jexpr = (JsonExpr *) node;
                              10564                 :                : 
                              10565   [ +  +  +  - ]:             30 :                 switch (jexpr->op)
                              10566                 :                :                 {
                              10567                 :              6 :                     case JSON_EXISTS_OP:
                              10568                 :              6 :                         appendStringInfoString(buf, "JSON_EXISTS(");
                              10569                 :              6 :                         break;
                              10570                 :             18 :                     case JSON_QUERY_OP:
                              10571                 :             18 :                         appendStringInfoString(buf, "JSON_QUERY(");
                              10572                 :             18 :                         break;
                              10573                 :              6 :                     case JSON_VALUE_OP:
                              10574                 :              6 :                         appendStringInfoString(buf, "JSON_VALUE(");
                              10575                 :              6 :                         break;
  586 amitlan@postgresql.o    10576                 :UBC           0 :                     default:
                              10577         [ #  # ]:              0 :                         elog(ERROR, "unrecognized JsonExpr op: %d",
                              10578                 :                :                              (int) jexpr->op);
                              10579                 :                :                 }
                              10580                 :                : 
  586 amitlan@postgresql.o    10581                 :CBC          30 :                 get_rule_expr(jexpr->formatted_expr, context, showimplicit);
                              10582                 :                : 
                              10583                 :             30 :                 appendStringInfoString(buf, ", ");
                              10584                 :                : 
                              10585                 :             30 :                 get_json_path_spec(jexpr->path_spec, context, showimplicit);
                              10586                 :                : 
                              10587         [ +  + ]:             30 :                 if (jexpr->passing_values)
                              10588                 :                :                 {
                              10589                 :                :                     ListCell   *lc1,
                              10590                 :                :                                *lc2;
                              10591                 :              6 :                     bool        needcomma = false;
                              10592                 :                : 
                              10593                 :              6 :                     appendStringInfoString(buf, " PASSING ");
                              10594                 :                : 
                              10595   [ +  -  +  +  :             24 :                     forboth(lc1, jexpr->passing_names,
                                     +  -  +  +  +  
                                        +  +  -  +  
                                                 + ]
                              10596                 :                :                             lc2, jexpr->passing_values)
                              10597                 :                :                     {
                              10598         [ +  + ]:             18 :                         if (needcomma)
                              10599                 :             12 :                             appendStringInfoString(buf, ", ");
                              10600                 :             18 :                         needcomma = true;
                              10601                 :                : 
                              10602                 :             18 :                         get_rule_expr((Node *) lfirst(lc2), context, showimplicit);
                              10603                 :             18 :                         appendStringInfo(buf, " AS %s",
  289 dean.a.rasheed@gmail    10604                 :             18 :                                          quote_identifier(lfirst_node(String, lc1)->sval));
                              10605                 :                :                     }
                              10606                 :                :                 }
                              10607                 :                : 
  586 amitlan@postgresql.o    10608         [ +  + ]:             30 :                 if (jexpr->op != JSON_EXISTS_OP ||
                              10609         [ -  + ]:              6 :                     jexpr->returning->typid != BOOLOID)
                              10610                 :             24 :                     get_json_returning(jexpr->returning, context->buf,
                              10611                 :             24 :                                        jexpr->op == JSON_QUERY_OP);
                              10612                 :                : 
                              10613                 :             30 :                 get_json_expr_options(jexpr, context,
                              10614         [ +  + ]:             30 :                                       jexpr->op != JSON_EXISTS_OP ?
                              10615                 :                :                                       JSON_BEHAVIOR_NULL :
                              10616                 :                :                                       JSON_BEHAVIOR_FALSE);
                              10617                 :                : 
  566 drowley@postgresql.o    10618                 :             30 :                 appendStringInfoChar(buf, ')');
                              10619                 :                :             }
  586 amitlan@postgresql.o    10620                 :             30 :             break;
                              10621                 :                : 
 7691 tgl@sss.pgh.pa.us       10622                 :           1345 :         case T_List:
                              10623                 :                :             {
                              10624                 :                :                 char       *sep;
                              10625                 :                :                 ListCell   *l;
                              10626                 :                : 
                              10627                 :           1345 :                 sep = "";
                              10628   [ +  -  +  +  :           3799 :                 foreach(l, (List *) node)
                                              +  + ]
                              10629                 :                :                 {
 7486 neilc@samurai.com       10630                 :           2454 :                     appendStringInfoString(buf, sep);
 7691 tgl@sss.pgh.pa.us       10631                 :           2454 :                     get_rule_expr((Node *) lfirst(l), context, showimplicit);
                              10632                 :           2454 :                     sep = ", ";
                              10633                 :                :                 }
                              10634                 :                :             }
                              10635                 :           1345 :             break;
                              10636                 :                : 
 3156 alvherre@alvh.no-ip.    10637                 :             36 :         case T_TableFunc:
                              10638                 :             36 :             get_tablefunc((TableFunc *) node, context, showimplicit);
                              10639                 :             36 :             break;
                              10640                 :                : 
 9919 bruce@momjian.us        10641                 :UBC           0 :         default:
 8129 tgl@sss.pgh.pa.us       10642         [ #  # ]:              0 :             elog(ERROR, "unrecognized node type: %d", (int) nodeTag(node));
                              10643                 :                :             break;
                              10644                 :                :     }
                              10645                 :                : }
                              10646                 :                : 
                              10647                 :                : /*
                              10648                 :                :  * get_rule_expr_toplevel       - Parse back a toplevel expression
                              10649                 :                :  *
                              10650                 :                :  * Same as get_rule_expr(), except that if the expr is just a Var, we pass
                              10651                 :                :  * istoplevel = true not false to get_variable().  This causes whole-row Vars
                              10652                 :                :  * to get printed with decoration that will prevent expansion of "*".
                              10653                 :                :  * We need to use this in contexts such as ROW() and VALUES(), where the
                              10654                 :                :  * parser would expand "foo.*" appearing at top level.  (In principle we'd
                              10655                 :                :  * use this in get_target_list() too, but that has additional worries about
                              10656                 :                :  * whether to print AS, so it needs to invoke get_variable() directly anyway.)
                              10657                 :                :  */
                              10658                 :                : static void
 3635 tgl@sss.pgh.pa.us       10659                 :CBC        1522 : get_rule_expr_toplevel(Node *node, deparse_context *context,
                              10660                 :                :                        bool showimplicit)
                              10661                 :                : {
                              10662   [ +  -  +  + ]:           1522 :     if (node && IsA(node, Var))
                              10663                 :            607 :         (void) get_variable((Var *) node, 0, true, context);
                              10664                 :                :     else
                              10665                 :            915 :         get_rule_expr(node, context, showimplicit);
                              10666                 :           1522 : }
                              10667                 :                : 
                              10668                 :                : /*
                              10669                 :                :  * get_rule_list_toplevel       - Parse back a list of toplevel expressions
                              10670                 :                :  *
                              10671                 :                :  * Apply get_rule_expr_toplevel() to each element of a List.
                              10672                 :                :  *
                              10673                 :                :  * This adds commas between the expressions, but caller is responsible
                              10674                 :                :  * for printing surrounding decoration.
                              10675                 :                :  */
                              10676                 :                : static void
 1384                         10677                 :            252 : get_rule_list_toplevel(List *lst, deparse_context *context,
                              10678                 :                :                        bool showimplicit)
                              10679                 :                : {
                              10680                 :                :     const char *sep;
                              10681                 :                :     ListCell   *lc;
                              10682                 :                : 
                              10683                 :            252 :     sep = "";
                              10684   [ +  -  +  +  :            859 :     foreach(lc, lst)
                                              +  + ]
                              10685                 :                :     {
                              10686                 :            607 :         Node       *e = (Node *) lfirst(lc);
                              10687                 :                : 
                              10688                 :            607 :         appendStringInfoString(context->buf, sep);
                              10689                 :            607 :         get_rule_expr_toplevel(e, context, showimplicit);
                              10690                 :            607 :         sep = ", ";
                              10691                 :                :     }
                              10692                 :            252 : }
                              10693                 :                : 
                              10694                 :                : /*
                              10695                 :                :  * get_rule_expr_funccall       - Parse back a function-call expression
                              10696                 :                :  *
                              10697                 :                :  * Same as get_rule_expr(), except that we guarantee that the output will
                              10698                 :                :  * look like a function call, or like one of the things the grammar treats as
                              10699                 :                :  * equivalent to a function call (see the func_expr_windowless production).
                              10700                 :                :  * This is needed in places where the grammar uses func_expr_windowless and
                              10701                 :                :  * you can't substitute a parenthesized a_expr.  If what we have isn't going
                              10702                 :                :  * to look like a function call, wrap it in a dummy CAST() expression, which
                              10703                 :                :  * will satisfy the grammar --- and, indeed, is likely what the user wrote to
                              10704                 :                :  * produce such a thing.
                              10705                 :                :  */
                              10706                 :                : static void
 3029                         10707                 :            438 : get_rule_expr_funccall(Node *node, deparse_context *context,
                              10708                 :                :                        bool showimplicit)
                              10709                 :                : {
                              10710         [ +  + ]:            438 :     if (looks_like_function(node))
                              10711                 :            432 :         get_rule_expr(node, context, showimplicit);
                              10712                 :                :     else
                              10713                 :                :     {
                              10714                 :              6 :         StringInfo  buf = context->buf;
                              10715                 :                : 
                              10716                 :              6 :         appendStringInfoString(buf, "CAST(");
                              10717                 :                :         /* no point in showing any top-level implicit cast */
                              10718                 :              6 :         get_rule_expr(node, context, false);
                              10719                 :              6 :         appendStringInfo(buf, " AS %s)",
                              10720                 :                :                          format_type_with_typemod(exprType(node),
                              10721                 :                :                                                   exprTypmod(node)));
                              10722                 :                :     }
                              10723                 :            438 : }
                              10724                 :                : 
                              10725                 :                : /*
                              10726                 :                :  * Helper function to identify node types that satisfy func_expr_windowless.
                              10727                 :                :  * If in doubt, "false" is always a safe answer.
                              10728                 :                :  */
                              10729                 :                : static bool
                              10730                 :           1033 : looks_like_function(Node *node)
                              10731                 :                : {
                              10732         [ -  + ]:           1033 :     if (node == NULL)
 3029 tgl@sss.pgh.pa.us       10733                 :UBC           0 :         return false;           /* probably shouldn't happen */
 3029 tgl@sss.pgh.pa.us       10734      [ +  +  + ]:CBC        1033 :     switch (nodeTag(node))
                              10735                 :                :     {
                              10736                 :            452 :         case T_FuncExpr:
                              10737                 :                :             /* OK, unless it's going to deparse as a cast */
 1819                         10738         [ +  + ]:            461 :             return (((FuncExpr *) node)->funcformat == COERCE_EXPLICIT_CALL ||
                              10739         [ +  + ]:              9 :                     ((FuncExpr *) node)->funcformat == COERCE_SQL_SYNTAX);
 3029                         10740                 :             54 :         case T_NullIfExpr:
                              10741                 :                :         case T_CoalesceExpr:
                              10742                 :                :         case T_MinMaxExpr:
                              10743                 :                :         case T_SQLValueFunction:
                              10744                 :                :         case T_XmlExpr:
                              10745                 :                :         case T_JsonExpr:
                              10746                 :                :             /* these are all accepted by func_expr_common_subexpr */
                              10747                 :             54 :             return true;
                              10748                 :            527 :         default:
                              10749                 :            527 :             break;
                              10750                 :                :     }
                              10751                 :            527 :     return false;
                              10752                 :                : }
                              10753                 :                : 
                              10754                 :                : 
                              10755                 :                : /*
                              10756                 :                :  * get_oper_expr            - Parse back an OpExpr node
                              10757                 :                :  */
                              10758                 :                : static void
 8117 bruce@momjian.us        10759                 :          30559 : get_oper_expr(OpExpr *expr, deparse_context *context)
                              10760                 :                : {
 8579 tgl@sss.pgh.pa.us       10761                 :          30559 :     StringInfo  buf = context->buf;
 8356                         10762                 :          30559 :     Oid         opno = expr->opno;
 8579                         10763                 :          30559 :     List       *args = expr->args;
                              10764                 :                : 
 8126                         10765         [ +  + ]:          30559 :     if (!PRETTY_PAREN(context))
 8121 bruce@momjian.us        10766                 :          29413 :         appendStringInfoChar(buf, '(');
 7821 neilc@samurai.com       10767         [ +  + ]:          30559 :     if (list_length(args) == 2)
                              10768                 :                :     {
                              10769                 :                :         /* binary operator */
 7825                         10770                 :          30544 :         Node       *arg1 = (Node *) linitial(args);
 8455 bruce@momjian.us        10771                 :          30544 :         Node       *arg2 = (Node *) lsecond(args);
                              10772                 :                : 
 8121                         10773                 :          30544 :         get_rule_expr_paren(arg1, context, true, (Node *) expr);
 8579 tgl@sss.pgh.pa.us       10774                 :          30544 :         appendStringInfo(buf, " %s ",
                              10775                 :                :                          generate_operator_name(opno,
                              10776                 :                :                                                 exprType(arg1),
                              10777                 :                :                                                 exprType(arg2)));
 8121 bruce@momjian.us        10778                 :          30544 :         get_rule_expr_paren(arg2, context, true, (Node *) expr);
                              10779                 :                :     }
                              10780                 :                :     else
                              10781                 :                :     {
                              10782                 :                :         /* prefix operator */
 7825 neilc@samurai.com       10783                 :             15 :         Node       *arg = (Node *) linitial(args);
                              10784                 :                : 
 1867 tgl@sss.pgh.pa.us       10785                 :             15 :         appendStringInfo(buf, "%s ",
                              10786                 :                :                          generate_operator_name(opno,
                              10787                 :                :                                                 InvalidOid,
                              10788                 :                :                                                 exprType(arg)));
                              10789                 :             15 :         get_rule_expr_paren(arg, context, true, (Node *) expr);
                              10790                 :                :     }
 8126                         10791         [ +  + ]:          30559 :     if (!PRETTY_PAREN(context))
 8121 bruce@momjian.us        10792                 :          29413 :         appendStringInfoChar(buf, ')');
 8579 tgl@sss.pgh.pa.us       10793                 :          30559 : }
                              10794                 :                : 
                              10795                 :                : /*
                              10796                 :                :  * get_func_expr            - Parse back a FuncExpr node
                              10797                 :                :  */
                              10798                 :                : static void
 8117 bruce@momjian.us        10799                 :           6284 : get_func_expr(FuncExpr *expr, deparse_context *context,
                              10800                 :                :               bool showimplicit)
                              10801                 :                : {
 9522 tgl@sss.pgh.pa.us       10802                 :           6284 :     StringInfo  buf = context->buf;
 8356                         10803                 :           6284 :     Oid         funcoid = expr->funcid;
                              10804                 :                :     Oid         argtypes[FUNC_MAX_ARGS];
                              10805                 :                :     int         nargs;
                              10806                 :                :     List       *argnames;
                              10807                 :                :     bool        use_variadic;
                              10808                 :                :     ListCell   *l;
                              10809                 :                : 
                              10810                 :                :     /*
                              10811                 :                :      * If the function call came from an implicit coercion, then just show the
                              10812                 :                :      * first argument --- unless caller wants to see implicit coercions.
                              10813                 :                :      */
                              10814   [ +  +  +  + ]:           6284 :     if (expr->funcformat == COERCE_IMPLICIT_CAST && !showimplicit)
                              10815                 :                :     {
 7825 neilc@samurai.com       10816                 :            657 :         get_rule_expr_paren((Node *) linitial(expr->args), context,
                              10817                 :                :                             false, (Node *) expr);
 8441 tgl@sss.pgh.pa.us       10818                 :           1636 :         return;
                              10819                 :                :     }
                              10820                 :                : 
                              10821                 :                :     /*
                              10822                 :                :      * If the function call came from a cast, then show the first argument
                              10823                 :                :      * plus an explicit cast operation.
                              10824                 :                :      */
 8356                         10825         [ +  + ]:           5627 :     if (expr->funcformat == COERCE_EXPLICIT_CAST ||
                              10826         [ +  + ]:           5281 :         expr->funcformat == COERCE_IMPLICIT_CAST)
                              10827                 :                :     {
 7825 neilc@samurai.com       10828                 :            892 :         Node       *arg = linitial(expr->args);
 8356 tgl@sss.pgh.pa.us       10829                 :            892 :         Oid         rettype = expr->funcresulttype;
                              10830                 :                :         int32       coercedTypmod;
                              10831                 :                : 
                              10832                 :                :         /* Get the typmod if this is a length-coercion function */
 8441                         10833                 :            892 :         (void) exprIsLengthCoercion((Node *) expr, &coercedTypmod);
                              10834                 :                : 
 6800                         10835                 :            892 :         get_coercion_expr(arg, context,
                              10836                 :                :                           rettype, coercedTypmod,
                              10837                 :                :                           (Node *) expr);
                              10838                 :                : 
 9376                         10839                 :            892 :         return;
                              10840                 :                :     }
                              10841                 :                : 
                              10842                 :                :     /*
                              10843                 :                :      * If the function was called using one of the SQL spec's random special
                              10844                 :                :      * syntaxes, try to reproduce that.  If we don't recognize the function,
                              10845                 :                :      * fall through.
                              10846                 :                :      */
 1819                         10847         [ +  + ]:           4735 :     if (expr->funcformat == COERCE_SQL_SYNTAX)
                              10848                 :                :     {
                              10849         [ +  + ]:             90 :         if (get_func_sql_syntax(expr, context))
                              10850                 :             87 :             return;
                              10851                 :                :     }
                              10852                 :                : 
                              10853                 :                :     /*
                              10854                 :                :      * Normal function: display as proname(args).  First we need to extract
                              10855                 :                :      * the argument datatypes.
                              10856                 :                :      */
 6148                         10857         [ -  + ]:           4648 :     if (list_length(expr->args) > FUNC_MAX_ARGS)
 6148 tgl@sss.pgh.pa.us       10858         [ #  # ]:UBC           0 :         ereport(ERROR,
                              10859                 :                :                 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
                              10860                 :                :                  errmsg("too many arguments")));
 8579 tgl@sss.pgh.pa.us       10861                 :CBC        4648 :     nargs = 0;
 5864                         10862                 :           4648 :     argnames = NIL;
 8579                         10863   [ +  +  +  +  :           9613 :     foreach(l, expr->args)
                                              +  + ]
                              10864                 :                :     {
 5723 bruce@momjian.us        10865                 :           4965 :         Node       *arg = (Node *) lfirst(l);
                              10866                 :                : 
 5864 tgl@sss.pgh.pa.us       10867         [ +  + ]:           4965 :         if (IsA(arg, NamedArgExpr))
                              10868                 :             15 :             argnames = lappend(argnames, ((NamedArgExpr *) arg)->name);
                              10869                 :           4965 :         argtypes[nargs] = exprType(arg);
 8579                         10870                 :           4965 :         nargs++;
                              10871                 :                :     }
                              10872                 :                : 
                              10873                 :           4648 :     appendStringInfo(buf, "%s(",
                              10874                 :                :                      generate_function_name(funcoid, nargs,
                              10875                 :                :                                             argnames, argtypes,
 4663                         10876                 :           4648 :                                             expr->funcvariadic,
                              10877                 :                :                                             &use_variadic,
  425                         10878                 :           4648 :                                             context->inGroupBy));
 6313                         10879                 :           4648 :     nargs = 0;
                              10880   [ +  +  +  +  :           9613 :     foreach(l, expr->args)
                                              +  + ]
                              10881                 :                :     {
                              10882         [ +  + ]:           4965 :         if (nargs++ > 0)
                              10883                 :            912 :             appendStringInfoString(buf, ", ");
 2297                         10884   [ +  +  +  - ]:           4965 :         if (use_variadic && lnext(expr->args, l) == NULL)
 6313                         10885                 :              6 :             appendStringInfoString(buf, "VARIADIC ");
                              10886                 :           4965 :         get_rule_expr((Node *) lfirst(l), context, true);
                              10887                 :                :     }
 9382                         10888                 :           4648 :     appendStringInfoChar(buf, ')');
                              10889                 :                : }
                              10890                 :                : 
                              10891                 :                : /*
                              10892                 :                :  * get_agg_expr         - Parse back an Aggref node
                              10893                 :                :  */
                              10894                 :                : static void
 1153 andrew@dunslane.net     10895                 :           2349 : get_agg_expr(Aggref *aggref, deparse_context *context,
                              10896                 :                :              Aggref *original_aggref)
                              10897                 :                : {
  944 alvherre@alvh.no-ip.    10898                 :           2349 :     get_agg_expr_helper(aggref, context, original_aggref, NULL, NULL,
                              10899                 :                :                         false);
                              10900                 :           2349 : }
                              10901                 :                : 
                              10902                 :                : /*
                              10903                 :                :  * get_agg_expr_helper      - subroutine for get_agg_expr and
                              10904                 :                :  *                          get_json_agg_constructor
                              10905                 :                :  */
                              10906                 :                : static void
                              10907                 :           2376 : get_agg_expr_helper(Aggref *aggref, deparse_context *context,
                              10908                 :                :                     Aggref *original_aggref, const char *funcname,
                              10909                 :                :                     const char *options, bool is_json_objectagg)
                              10910                 :                : {
 8601 tgl@sss.pgh.pa.us       10911                 :           2376 :     StringInfo  buf = context->buf;
                              10912                 :                :     Oid         argtypes[FUNC_MAX_ARGS];
                              10913                 :                :     int         nargs;
  944 alvherre@alvh.no-ip.    10914                 :           2376 :     bool        use_variadic = false;
                              10915                 :                : 
                              10916                 :                :     /*
                              10917                 :                :      * For a combining aggregate, we look up and deparse the corresponding
                              10918                 :                :      * partial aggregate instead.  This is necessary because our input
                              10919                 :                :      * argument list has been replaced; the new argument list always has just
                              10920                 :                :      * one element, which will point to a partial Aggref that supplies us with
                              10921                 :                :      * transition states to combine.
                              10922                 :                :      */
 3411 tgl@sss.pgh.pa.us       10923         [ +  + ]:           2376 :     if (DO_AGGSPLIT_COMBINE(aggref->aggsplit))
                              10924                 :                :     {
                              10925                 :                :         TargetEntry *tle;
                              10926                 :                : 
 3471 rhaas@postgresql.org    10927         [ -  + ]:            388 :         Assert(list_length(aggref->args) == 1);
 2148 tgl@sss.pgh.pa.us       10928                 :            388 :         tle = linitial_node(TargetEntry, aggref->args);
                              10929                 :            388 :         resolve_special_varno((Node *) tle->expr, context,
                              10930                 :                :                               get_agg_combine_expr, original_aggref);
 3471 rhaas@postgresql.org    10931                 :            388 :         return;
                              10932                 :                :     }
                              10933                 :                : 
                              10934                 :                :     /*
                              10935                 :                :      * Mark as PARTIAL, if appropriate.  We look to the original aggref so as
                              10936                 :                :      * to avoid printing this when recursing from the code just above.
                              10937                 :                :      */
 3411 tgl@sss.pgh.pa.us       10938         [ +  + ]:           1988 :     if (DO_AGGSPLIT_SKIPFINAL(original_aggref->aggsplit))
 3471 rhaas@postgresql.org    10939                 :            862 :         appendStringInfoString(buf, "PARTIAL ");
                              10940                 :                : 
                              10941                 :                :     /* Extract the argument types as seen by the parser */
 4327 tgl@sss.pgh.pa.us       10942                 :           1988 :     nargs = get_aggregate_argtypes(aggref, argtypes);
                              10943                 :                : 
  944 alvherre@alvh.no-ip.    10944         [ +  + ]:           1988 :     if (!funcname)
                              10945                 :           1961 :         funcname = generate_function_name(aggref->aggfnoid, nargs, NIL,
                              10946                 :           1961 :                                           argtypes, aggref->aggvariadic,
                              10947                 :                :                                           &use_variadic,
  425 tgl@sss.pgh.pa.us       10948                 :           1961 :                                           context->inGroupBy);
                              10949                 :                : 
                              10950                 :                :     /* Print the aggregate name, schema-qualified if needed */
  944 alvherre@alvh.no-ip.    10951                 :           1988 :     appendStringInfo(buf, "%s(%s", funcname,
 5796 tgl@sss.pgh.pa.us       10952         [ +  + ]:           1988 :                      (aggref->aggdistinct != NIL) ? "DISTINCT " : "");
                              10953                 :                : 
 4327                         10954         [ +  + ]:           1988 :     if (AGGKIND_IS_ORDERED_SET(aggref->aggkind))
                              10955                 :                :     {
                              10956                 :                :         /*
                              10957                 :                :          * Ordered-set aggregates do not use "*" syntax.  Also, we needn't
                              10958                 :                :          * worry about inserting VARIADIC.  So we can just dump the direct
                              10959                 :                :          * args as-is.
                              10960                 :                :          */
                              10961         [ -  + ]:             14 :         Assert(!aggref->aggvariadic);
                              10962                 :             14 :         get_rule_expr((Node *) aggref->aggdirectargs, context, true);
                              10963         [ -  + ]:             14 :         Assert(aggref->aggorder != NIL);
                              10964                 :             14 :         appendStringInfoString(buf, ") WITHIN GROUP (ORDER BY ");
                              10965                 :             14 :         get_rule_orderby(aggref->aggorder, aggref->args, false, context);
                              10966                 :                :     }
                              10967                 :                :     else
                              10968                 :                :     {
                              10969                 :                :         /* aggstar can be set only in zero-argument aggregates */
                              10970         [ +  + ]:           1974 :         if (aggref->aggstar)
                              10971                 :            579 :             appendStringInfoChar(buf, '*');
                              10972                 :                :         else
                              10973                 :                :         {
                              10974                 :                :             ListCell   *l;
                              10975                 :                :             int         i;
                              10976                 :                : 
                              10977                 :           1395 :             i = 0;
                              10978   [ +  -  +  +  :           2884 :             foreach(l, aggref->args)
                                              +  + ]
                              10979                 :                :             {
                              10980                 :           1489 :                 TargetEntry *tle = (TargetEntry *) lfirst(l);
                              10981                 :           1489 :                 Node       *arg = (Node *) tle->expr;
                              10982                 :                : 
                              10983         [ -  + ]:           1489 :                 Assert(!IsA(arg, NamedArgExpr));
                              10984         [ +  + ]:           1489 :                 if (tle->resjunk)
                              10985                 :             25 :                     continue;
                              10986         [ +  + ]:           1464 :                 if (i++ > 0)
                              10987                 :                :                 {
  944 alvherre@alvh.no-ip.    10988         [ +  + ]:             69 :                     if (is_json_objectagg)
                              10989                 :                :                     {
                              10990                 :                :                         /*
                              10991                 :                :                          * the ABSENT ON NULL and WITH UNIQUE args are printed
                              10992                 :                :                          * separately, so ignore them here
                              10993                 :                :                          */
                              10994         [ -  + ]:             15 :                         if (i > 2)
  944 alvherre@alvh.no-ip.    10995                 :UBC           0 :                             break;
                              10996                 :                : 
  944 alvherre@alvh.no-ip.    10997                 :CBC          15 :                         appendStringInfoString(buf, " : ");
                              10998                 :                :                     }
                              10999                 :                :                     else
                              11000                 :             54 :                         appendStringInfoString(buf, ", ");
                              11001                 :                :                 }
 4327 tgl@sss.pgh.pa.us       11002   [ +  +  +  - ]:           1464 :                 if (use_variadic && i == nargs)
                              11003                 :              4 :                     appendStringInfoString(buf, "VARIADIC ");
                              11004                 :           1464 :                 get_rule_expr(arg, context, true);
                              11005                 :                :             }
                              11006                 :                :         }
                              11007                 :                : 
                              11008         [ +  + ]:           1974 :         if (aggref->aggorder != NIL)
                              11009                 :                :         {
                              11010                 :             41 :             appendStringInfoString(buf, " ORDER BY ");
                              11011                 :             41 :             get_rule_orderby(aggref->aggorder, aggref->args, false, context);
                              11012                 :                :         }
                              11013                 :                :     }
                              11014                 :                : 
  944 alvherre@alvh.no-ip.    11015         [ +  + ]:           1988 :     if (options)
                              11016                 :             27 :         appendStringInfoString(buf, options);
                              11017                 :                : 
 4487 noah@leadboat.com       11018         [ +  + ]:           1988 :     if (aggref->aggfilter != NULL)
                              11019                 :                :     {
                              11020                 :             23 :         appendStringInfoString(buf, ") FILTER (WHERE ");
                              11021                 :             23 :         get_rule_expr((Node *) aggref->aggfilter, context, false);
                              11022                 :                :     }
                              11023                 :                : 
 8601 tgl@sss.pgh.pa.us       11024                 :           1988 :     appendStringInfoChar(buf, ')');
                              11025                 :                : }
                              11026                 :                : 
                              11027                 :                : /*
                              11028                 :                :  * This is a helper function for get_agg_expr().  It's used when we deparse
                              11029                 :                :  * a combining Aggref; resolve_special_varno locates the corresponding partial
                              11030                 :                :  * Aggref and then calls this.
                              11031                 :                :  */
                              11032                 :                : static void
 2148                         11033                 :            388 : get_agg_combine_expr(Node *node, deparse_context *context, void *callback_arg)
                              11034                 :                : {
                              11035                 :                :     Aggref     *aggref;
                              11036                 :            388 :     Aggref     *original_aggref = callback_arg;
                              11037                 :                : 
 3471 rhaas@postgresql.org    11038         [ -  + ]:            388 :     if (!IsA(node, Aggref))
 3471 rhaas@postgresql.org    11039         [ #  # ]:UBC           0 :         elog(ERROR, "combining Aggref does not point to an Aggref");
                              11040                 :                : 
 3471 rhaas@postgresql.org    11041                 :CBC         388 :     aggref = (Aggref *) node;
                              11042                 :            388 :     get_agg_expr(aggref, context, original_aggref);
                              11043                 :            388 : }
                              11044                 :                : 
                              11045                 :                : /*
                              11046                 :                :  * get_windowfunc_expr  - Parse back a WindowFunc node
                              11047                 :                :  */
                              11048                 :                : static void
 1153 andrew@dunslane.net     11049                 :            162 : get_windowfunc_expr(WindowFunc *wfunc, deparse_context *context)
                              11050                 :                : {
  944 alvherre@alvh.no-ip.    11051                 :            162 :     get_windowfunc_expr_helper(wfunc, context, NULL, NULL, false);
                              11052                 :            162 : }
                              11053                 :                : 
                              11054                 :                : 
                              11055                 :                : /*
                              11056                 :                :  * get_windowfunc_expr_helper   - subroutine for get_windowfunc_expr and
                              11057                 :                :  *                              get_json_agg_constructor
                              11058                 :                :  */
                              11059                 :                : static void
                              11060                 :            168 : get_windowfunc_expr_helper(WindowFunc *wfunc, deparse_context *context,
                              11061                 :                :                            const char *funcname, const char *options,
                              11062                 :                :                            bool is_json_objectagg)
                              11063                 :                : {
 6148 tgl@sss.pgh.pa.us       11064                 :            168 :     StringInfo  buf = context->buf;
                              11065                 :                :     Oid         argtypes[FUNC_MAX_ARGS];
                              11066                 :                :     int         nargs;
                              11067                 :                :     List       *argnames;
                              11068                 :                :     ListCell   *l;
                              11069                 :                : 
                              11070         [ -  + ]:            168 :     if (list_length(wfunc->args) > FUNC_MAX_ARGS)
 6148 tgl@sss.pgh.pa.us       11071         [ #  # ]:UBC           0 :         ereport(ERROR,
                              11072                 :                :                 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
                              11073                 :                :                  errmsg("too many arguments")));
 6148 tgl@sss.pgh.pa.us       11074                 :CBC         168 :     nargs = 0;
 4374                         11075                 :            168 :     argnames = NIL;
 6148                         11076   [ +  +  +  +  :            285 :     foreach(l, wfunc->args)
                                              +  + ]
                              11077                 :                :     {
 5723 bruce@momjian.us        11078                 :            117 :         Node       *arg = (Node *) lfirst(l);
                              11079                 :                : 
 4374 tgl@sss.pgh.pa.us       11080         [ -  + ]:            117 :         if (IsA(arg, NamedArgExpr))
 4374 tgl@sss.pgh.pa.us       11081                 :UBC           0 :             argnames = lappend(argnames, ((NamedArgExpr *) arg)->name);
 5864 tgl@sss.pgh.pa.us       11082                 :CBC         117 :         argtypes[nargs] = exprType(arg);
 6148                         11083                 :            117 :         nargs++;
                              11084                 :                :     }
                              11085                 :                : 
  944 alvherre@alvh.no-ip.    11086         [ +  + ]:            168 :     if (!funcname)
                              11087                 :            162 :         funcname = generate_function_name(wfunc->winfnoid, nargs, argnames,
                              11088                 :                :                                           argtypes, false, NULL,
  425 tgl@sss.pgh.pa.us       11089                 :            162 :                                           context->inGroupBy);
                              11090                 :                : 
  944 alvherre@alvh.no-ip.    11091                 :            168 :     appendStringInfo(buf, "%s(", funcname);
                              11092                 :                : 
                              11093                 :                :     /* winstar can be set only in zero-argument aggregates */
 6148 tgl@sss.pgh.pa.us       11094         [ +  + ]:            168 :     if (wfunc->winstar)
                              11095                 :             12 :         appendStringInfoChar(buf, '*');
                              11096                 :                :     else
                              11097                 :                :     {
  944 alvherre@alvh.no-ip.    11098         [ +  + ]:            156 :         if (is_json_objectagg)
                              11099                 :                :         {
                              11100                 :              3 :             get_rule_expr((Node *) linitial(wfunc->args), context, false);
                              11101                 :              3 :             appendStringInfoString(buf, " : ");
                              11102                 :              3 :             get_rule_expr((Node *) lsecond(wfunc->args), context, false);
                              11103                 :                :         }
                              11104                 :                :         else
                              11105                 :            153 :             get_rule_expr((Node *) wfunc->args, context, true);
                              11106                 :                :     }
                              11107                 :                : 
                              11108         [ +  + ]:            168 :     if (options)
                              11109                 :              6 :         appendStringInfoString(buf, options);
                              11110                 :                : 
 4487 noah@leadboat.com       11111         [ -  + ]:            168 :     if (wfunc->aggfilter != NULL)
                              11112                 :                :     {
 4487 noah@leadboat.com       11113                 :UBC           0 :         appendStringInfoString(buf, ") FILTER (WHERE ");
                              11114                 :              0 :         get_rule_expr((Node *) wfunc->aggfilter, context, false);
                              11115                 :                :     }
                              11116                 :                : 
   25 ishii@postgresql.org    11117                 :GNC         168 :     appendStringInfoString(buf, ") ");
                              11118                 :                : 
                              11119         [ +  + ]:            168 :     if (wfunc->ignore_nulls == PARSER_IGNORE_NULLS)
                              11120                 :              3 :         appendStringInfoString(buf, "IGNORE NULLS ");
                              11121                 :                : 
                              11122                 :            168 :     appendStringInfoString(buf, "OVER ");
                              11123                 :                : 
  231 tgl@sss.pgh.pa.us       11124         [ +  + ]:CBC         168 :     if (context->windowClause)
                              11125                 :                :     {
                              11126                 :                :         /* Query-decompilation case: search the windowClause list */
                              11127   [ +  -  +  -  :             30 :         foreach(l, context->windowClause)
                                              +  - ]
                              11128                 :                :         {
                              11129                 :             30 :             WindowClause *wc = (WindowClause *) lfirst(l);
                              11130                 :                : 
                              11131         [ +  - ]:             30 :             if (wc->winref == wfunc->winref)
                              11132                 :                :             {
                              11133         [ +  + ]:             30 :                 if (wc->name)
  231 tgl@sss.pgh.pa.us       11134                 :GBC           9 :                     appendStringInfoString(buf, quote_identifier(wc->name));
                              11135                 :                :                 else
  231 tgl@sss.pgh.pa.us       11136                 :CBC          21 :                     get_rule_windowspec(wc, context->targetList, context);
                              11137                 :             30 :                 break;
                              11138                 :                :             }
                              11139                 :                :         }
                              11140         [ -  + ]:             30 :         if (l == NULL)
 6148 tgl@sss.pgh.pa.us       11141         [ #  # ]:UBC           0 :             elog(ERROR, "could not find window clause for winref %u",
                              11142                 :                :                  wfunc->winref);
                              11143                 :                :     }
                              11144                 :                :     else
                              11145                 :                :     {
                              11146                 :                :         /*
                              11147                 :                :          * In EXPLAIN, search the namespace stack for a matching WindowAgg
                              11148                 :                :          * node (probably it's always the first entry), and print winname.
                              11149                 :                :          */
  231 tgl@sss.pgh.pa.us       11150   [ +  -  +  -  :CBC         138 :         foreach(l, context->namespaces)
                                              +  - ]
                              11151                 :                :         {
                              11152                 :            138 :             deparse_namespace *dpns = (deparse_namespace *) lfirst(l);
                              11153                 :                : 
                              11154   [ +  -  +  - ]:            138 :             if (dpns->plan && IsA(dpns->plan, WindowAgg))
                              11155                 :                :             {
                              11156                 :            138 :                 WindowAgg  *wagg = (WindowAgg *) dpns->plan;
                              11157                 :                : 
                              11158         [ +  - ]:            138 :                 if (wagg->winref == wfunc->winref)
                              11159                 :                :                 {
                              11160                 :            138 :                     appendStringInfoString(buf, quote_identifier(wagg->winname));
                              11161                 :            138 :                     break;
                              11162                 :                :                 }
                              11163                 :                :             }
                              11164                 :                :         }
                              11165         [ -  + ]:            138 :         if (l == NULL)
  231 tgl@sss.pgh.pa.us       11166         [ #  # ]:UBC           0 :             elog(ERROR, "could not find window clause for winref %u",
                              11167                 :                :                  wfunc->winref);
                              11168                 :                :     }
 6148 tgl@sss.pgh.pa.us       11169                 :CBC         168 : }
                              11170                 :                : 
                              11171                 :                : /*
                              11172                 :                :  * get_func_sql_syntax      - Parse back a SQL-syntax function call
                              11173                 :                :  *
                              11174                 :                :  * Returns true if we successfully deparsed, false if we did not
                              11175                 :                :  * recognize the function.
                              11176                 :                :  */
                              11177                 :                : static bool
 1819                         11178                 :             90 : get_func_sql_syntax(FuncExpr *expr, deparse_context *context)
                              11179                 :                : {
                              11180                 :             90 :     StringInfo  buf = context->buf;
                              11181                 :             90 :     Oid         funcoid = expr->funcid;
                              11182                 :                : 
                              11183   [ +  +  +  +  :             90 :     switch (funcoid)
                                     +  +  +  +  +  
                                     +  +  +  +  +  
                                           +  -  + ]
                              11184                 :                :     {
                              11185                 :             12 :         case F_TIMEZONE_INTERVAL_TIMESTAMP:
                              11186                 :                :         case F_TIMEZONE_INTERVAL_TIMESTAMPTZ:
                              11187                 :                :         case F_TIMEZONE_INTERVAL_TIMETZ:
                              11188                 :                :         case F_TIMEZONE_TEXT_TIMESTAMP:
                              11189                 :                :         case F_TIMEZONE_TEXT_TIMESTAMPTZ:
                              11190                 :                :         case F_TIMEZONE_TEXT_TIMETZ:
                              11191                 :                :             /* AT TIME ZONE ... note reversed argument order */
                              11192                 :             12 :             appendStringInfoChar(buf, '(');
 1062                         11193                 :             12 :             get_rule_expr_paren((Node *) lsecond(expr->args), context, false,
                              11194                 :                :                                 (Node *) expr);
 1819                         11195                 :             12 :             appendStringInfoString(buf, " AT TIME ZONE ");
 1062                         11196                 :             12 :             get_rule_expr_paren((Node *) linitial(expr->args), context, false,
                              11197                 :                :                                 (Node *) expr);
 1819                         11198                 :             12 :             appendStringInfoChar(buf, ')');
                              11199                 :             12 :             return true;
                              11200                 :                : 
  746 michael@paquier.xyz     11201                 :              9 :         case F_TIMEZONE_TIMESTAMP:
                              11202                 :                :         case F_TIMEZONE_TIMESTAMPTZ:
                              11203                 :                :         case F_TIMEZONE_TIMETZ:
                              11204                 :                :             /* AT LOCAL */
                              11205                 :              9 :             appendStringInfoChar(buf, '(');
                              11206                 :              9 :             get_rule_expr_paren((Node *) linitial(expr->args), context, false,
                              11207                 :                :                                 (Node *) expr);
                              11208                 :              9 :             appendStringInfoString(buf, " AT LOCAL)");
                              11209                 :              9 :             return true;
                              11210                 :                : 
 1819 tgl@sss.pgh.pa.us       11211                 :              3 :         case F_OVERLAPS_TIMESTAMPTZ_INTERVAL_TIMESTAMPTZ_INTERVAL:
                              11212                 :                :         case F_OVERLAPS_TIMESTAMPTZ_INTERVAL_TIMESTAMPTZ_TIMESTAMPTZ:
                              11213                 :                :         case F_OVERLAPS_TIMESTAMPTZ_TIMESTAMPTZ_TIMESTAMPTZ_INTERVAL:
                              11214                 :                :         case F_OVERLAPS_TIMESTAMPTZ_TIMESTAMPTZ_TIMESTAMPTZ_TIMESTAMPTZ:
                              11215                 :                :         case F_OVERLAPS_TIMESTAMP_INTERVAL_TIMESTAMP_INTERVAL:
                              11216                 :                :         case F_OVERLAPS_TIMESTAMP_INTERVAL_TIMESTAMP_TIMESTAMP:
                              11217                 :                :         case F_OVERLAPS_TIMESTAMP_TIMESTAMP_TIMESTAMP_INTERVAL:
                              11218                 :                :         case F_OVERLAPS_TIMESTAMP_TIMESTAMP_TIMESTAMP_TIMESTAMP:
                              11219                 :                :         case F_OVERLAPS_TIMETZ_TIMETZ_TIMETZ_TIMETZ:
                              11220                 :                :         case F_OVERLAPS_TIME_INTERVAL_TIME_INTERVAL:
                              11221                 :                :         case F_OVERLAPS_TIME_INTERVAL_TIME_TIME:
                              11222                 :                :         case F_OVERLAPS_TIME_TIME_TIME_INTERVAL:
                              11223                 :                :         case F_OVERLAPS_TIME_TIME_TIME_TIME:
                              11224                 :                :             /* (x1, x2) OVERLAPS (y1, y2) */
                              11225                 :              3 :             appendStringInfoString(buf, "((");
                              11226                 :              3 :             get_rule_expr((Node *) linitial(expr->args), context, false);
                              11227                 :              3 :             appendStringInfoString(buf, ", ");
                              11228                 :              3 :             get_rule_expr((Node *) lsecond(expr->args), context, false);
                              11229                 :              3 :             appendStringInfoString(buf, ") OVERLAPS (");
                              11230                 :              3 :             get_rule_expr((Node *) lthird(expr->args), context, false);
                              11231                 :              3 :             appendStringInfoString(buf, ", ");
                              11232                 :              3 :             get_rule_expr((Node *) lfourth(expr->args), context, false);
                              11233                 :              3 :             appendStringInfoString(buf, "))");
                              11234                 :              3 :             return true;
                              11235                 :                : 
 1666 peter@eisentraut.org    11236                 :              9 :         case F_EXTRACT_TEXT_DATE:
                              11237                 :                :         case F_EXTRACT_TEXT_TIME:
                              11238                 :                :         case F_EXTRACT_TEXT_TIMETZ:
                              11239                 :                :         case F_EXTRACT_TEXT_TIMESTAMP:
                              11240                 :                :         case F_EXTRACT_TEXT_TIMESTAMPTZ:
                              11241                 :                :         case F_EXTRACT_TEXT_INTERVAL:
                              11242                 :                :             /* EXTRACT (x FROM y) */
                              11243                 :              9 :             appendStringInfoString(buf, "EXTRACT(");
                              11244                 :                :             {
                              11245                 :              9 :                 Const      *con = (Const *) linitial(expr->args);
                              11246                 :                : 
                              11247   [ +  -  +  -  :              9 :                 Assert(IsA(con, Const) &&
                                              -  + ]
                              11248                 :                :                        con->consttype == TEXTOID &&
                              11249                 :                :                        !con->constisnull);
                              11250                 :              9 :                 appendStringInfoString(buf, TextDatumGetCString(con->constvalue));
                              11251                 :                :             }
                              11252                 :              9 :             appendStringInfoString(buf, " FROM ");
                              11253                 :              9 :             get_rule_expr((Node *) lsecond(expr->args), context, false);
                              11254                 :              9 :             appendStringInfoChar(buf, ')');
                              11255                 :              9 :             return true;
                              11256                 :                : 
 1819 tgl@sss.pgh.pa.us       11257                 :              6 :         case F_IS_NORMALIZED:
                              11258                 :                :             /* IS xxx NORMALIZED */
  756 drowley@postgresql.o    11259                 :              6 :             appendStringInfoChar(buf, '(');
 1062 tgl@sss.pgh.pa.us       11260                 :              6 :             get_rule_expr_paren((Node *) linitial(expr->args), context, false,
                              11261                 :                :                                 (Node *) expr);
                              11262                 :              6 :             appendStringInfoString(buf, " IS");
 1819                         11263         [ +  + ]:              6 :             if (list_length(expr->args) == 2)
                              11264                 :                :             {
                              11265                 :              3 :                 Const      *con = (Const *) lsecond(expr->args);
                              11266                 :                : 
                              11267   [ +  -  +  -  :              3 :                 Assert(IsA(con, Const) &&
                                              -  + ]
                              11268                 :                :                        con->consttype == TEXTOID &&
                              11269                 :                :                        !con->constisnull);
                              11270                 :              3 :                 appendStringInfo(buf, " %s",
                              11271                 :              3 :                                  TextDatumGetCString(con->constvalue));
                              11272                 :                :             }
                              11273                 :              6 :             appendStringInfoString(buf, " NORMALIZED)");
                              11274                 :              6 :             return true;
                              11275                 :                : 
                              11276                 :              3 :         case F_PG_COLLATION_FOR:
                              11277                 :                :             /* COLLATION FOR */
                              11278                 :              3 :             appendStringInfoString(buf, "COLLATION FOR (");
                              11279                 :              3 :             get_rule_expr((Node *) linitial(expr->args), context, false);
                              11280                 :              3 :             appendStringInfoChar(buf, ')');
                              11281                 :              3 :             return true;
                              11282                 :                : 
                              11283                 :              6 :         case F_NORMALIZE:
                              11284                 :                :             /* NORMALIZE() */
                              11285                 :              6 :             appendStringInfoString(buf, "NORMALIZE(");
                              11286                 :              6 :             get_rule_expr((Node *) linitial(expr->args), context, false);
                              11287         [ +  + ]:              6 :             if (list_length(expr->args) == 2)
                              11288                 :                :             {
                              11289                 :              3 :                 Const      *con = (Const *) lsecond(expr->args);
                              11290                 :                : 
                              11291   [ +  -  +  -  :              3 :                 Assert(IsA(con, Const) &&
                                              -  + ]
                              11292                 :                :                        con->consttype == TEXTOID &&
                              11293                 :                :                        !con->constisnull);
                              11294                 :              3 :                 appendStringInfo(buf, ", %s",
                              11295                 :              3 :                                  TextDatumGetCString(con->constvalue));
                              11296                 :                :             }
                              11297                 :              6 :             appendStringInfoChar(buf, ')');
                              11298                 :              6 :             return true;
                              11299                 :                : 
                              11300                 :              6 :         case F_OVERLAY_BIT_BIT_INT4:
                              11301                 :                :         case F_OVERLAY_BIT_BIT_INT4_INT4:
                              11302                 :                :         case F_OVERLAY_BYTEA_BYTEA_INT4:
                              11303                 :                :         case F_OVERLAY_BYTEA_BYTEA_INT4_INT4:
                              11304                 :                :         case F_OVERLAY_TEXT_TEXT_INT4:
                              11305                 :                :         case F_OVERLAY_TEXT_TEXT_INT4_INT4:
                              11306                 :                :             /* OVERLAY() */
                              11307                 :              6 :             appendStringInfoString(buf, "OVERLAY(");
                              11308                 :              6 :             get_rule_expr((Node *) linitial(expr->args), context, false);
                              11309                 :              6 :             appendStringInfoString(buf, " PLACING ");
                              11310                 :              6 :             get_rule_expr((Node *) lsecond(expr->args), context, false);
                              11311                 :              6 :             appendStringInfoString(buf, " FROM ");
                              11312                 :              6 :             get_rule_expr((Node *) lthird(expr->args), context, false);
                              11313         [ +  + ]:              6 :             if (list_length(expr->args) == 4)
                              11314                 :                :             {
                              11315                 :              3 :                 appendStringInfoString(buf, " FOR ");
                              11316                 :              3 :                 get_rule_expr((Node *) lfourth(expr->args), context, false);
                              11317                 :                :             }
                              11318                 :              6 :             appendStringInfoChar(buf, ')');
                              11319                 :              6 :             return true;
                              11320                 :                : 
                              11321                 :              3 :         case F_POSITION_BIT_BIT:
                              11322                 :                :         case F_POSITION_BYTEA_BYTEA:
                              11323                 :                :         case F_POSITION_TEXT_TEXT:
                              11324                 :                :             /* POSITION() ... extra parens since args are b_expr not a_expr */
                              11325                 :              3 :             appendStringInfoString(buf, "POSITION((");
                              11326                 :              3 :             get_rule_expr((Node *) lsecond(expr->args), context, false);
                              11327                 :              3 :             appendStringInfoString(buf, ") IN (");
                              11328                 :              3 :             get_rule_expr((Node *) linitial(expr->args), context, false);
                              11329                 :              3 :             appendStringInfoString(buf, "))");
                              11330                 :              3 :             return true;
                              11331                 :                : 
                              11332                 :              3 :         case F_SUBSTRING_BIT_INT4:
                              11333                 :                :         case F_SUBSTRING_BIT_INT4_INT4:
                              11334                 :                :         case F_SUBSTRING_BYTEA_INT4:
                              11335                 :                :         case F_SUBSTRING_BYTEA_INT4_INT4:
                              11336                 :                :         case F_SUBSTRING_TEXT_INT4:
                              11337                 :                :         case F_SUBSTRING_TEXT_INT4_INT4:
                              11338                 :                :             /* SUBSTRING FROM/FOR (i.e., integer-position variants) */
                              11339                 :              3 :             appendStringInfoString(buf, "SUBSTRING(");
                              11340                 :              3 :             get_rule_expr((Node *) linitial(expr->args), context, false);
                              11341                 :              3 :             appendStringInfoString(buf, " FROM ");
                              11342                 :              3 :             get_rule_expr((Node *) lsecond(expr->args), context, false);
                              11343         [ +  - ]:              3 :             if (list_length(expr->args) == 3)
                              11344                 :                :             {
                              11345                 :              3 :                 appendStringInfoString(buf, " FOR ");
                              11346                 :              3 :                 get_rule_expr((Node *) lthird(expr->args), context, false);
                              11347                 :                :             }
                              11348                 :              3 :             appendStringInfoChar(buf, ')');
                              11349                 :              3 :             return true;
                              11350                 :                : 
                              11351                 :              3 :         case F_SUBSTRING_TEXT_TEXT_TEXT:
                              11352                 :                :             /* SUBSTRING SIMILAR/ESCAPE */
                              11353                 :              3 :             appendStringInfoString(buf, "SUBSTRING(");
                              11354                 :              3 :             get_rule_expr((Node *) linitial(expr->args), context, false);
                              11355                 :              3 :             appendStringInfoString(buf, " SIMILAR ");
                              11356                 :              3 :             get_rule_expr((Node *) lsecond(expr->args), context, false);
                              11357                 :              3 :             appendStringInfoString(buf, " ESCAPE ");
                              11358                 :              3 :             get_rule_expr((Node *) lthird(expr->args), context, false);
                              11359                 :              3 :             appendStringInfoChar(buf, ')');
                              11360                 :              3 :             return true;
                              11361                 :                : 
                              11362                 :              6 :         case F_BTRIM_BYTEA_BYTEA:
                              11363                 :                :         case F_BTRIM_TEXT:
                              11364                 :                :         case F_BTRIM_TEXT_TEXT:
                              11365                 :                :             /* TRIM() */
                              11366                 :              6 :             appendStringInfoString(buf, "TRIM(BOTH");
                              11367         [ +  - ]:              6 :             if (list_length(expr->args) == 2)
                              11368                 :                :             {
                              11369                 :              6 :                 appendStringInfoChar(buf, ' ');
                              11370                 :              6 :                 get_rule_expr((Node *) lsecond(expr->args), context, false);
                              11371                 :                :             }
                              11372                 :              6 :             appendStringInfoString(buf, " FROM ");
                              11373                 :              6 :             get_rule_expr((Node *) linitial(expr->args), context, false);
                              11374                 :              6 :             appendStringInfoChar(buf, ')');
                              11375                 :              6 :             return true;
                              11376                 :                : 
 1744                         11377                 :              6 :         case F_LTRIM_BYTEA_BYTEA:
                              11378                 :                :         case F_LTRIM_TEXT:
                              11379                 :                :         case F_LTRIM_TEXT_TEXT:
                              11380                 :                :             /* TRIM() */
 1819                         11381                 :              6 :             appendStringInfoString(buf, "TRIM(LEADING");
                              11382         [ +  - ]:              6 :             if (list_length(expr->args) == 2)
                              11383                 :                :             {
                              11384                 :              6 :                 appendStringInfoChar(buf, ' ');
                              11385                 :              6 :                 get_rule_expr((Node *) lsecond(expr->args), context, false);
                              11386                 :                :             }
                              11387                 :              6 :             appendStringInfoString(buf, " FROM ");
                              11388                 :              6 :             get_rule_expr((Node *) linitial(expr->args), context, false);
                              11389                 :              6 :             appendStringInfoChar(buf, ')');
                              11390                 :              6 :             return true;
                              11391                 :                : 
 1744                         11392                 :              6 :         case F_RTRIM_BYTEA_BYTEA:
                              11393                 :                :         case F_RTRIM_TEXT:
                              11394                 :                :         case F_RTRIM_TEXT_TEXT:
                              11395                 :                :             /* TRIM() */
 1819                         11396                 :              6 :             appendStringInfoString(buf, "TRIM(TRAILING");
                              11397         [ +  + ]:              6 :             if (list_length(expr->args) == 2)
                              11398                 :                :             {
                              11399                 :              3 :                 appendStringInfoChar(buf, ' ');
                              11400                 :              3 :                 get_rule_expr((Node *) lsecond(expr->args), context, false);
                              11401                 :                :             }
                              11402                 :              6 :             appendStringInfoString(buf, " FROM ");
                              11403                 :              6 :             get_rule_expr((Node *) linitial(expr->args), context, false);
                              11404                 :              6 :             appendStringInfoChar(buf, ')');
                              11405                 :              6 :             return true;
                              11406                 :                : 
 1125 michael@paquier.xyz     11407                 :              6 :         case F_SYSTEM_USER:
                              11408                 :              6 :             appendStringInfoString(buf, "SYSTEM_USER");
                              11409                 :              6 :             return true;
                              11410                 :                : 
 1819 tgl@sss.pgh.pa.us       11411                 :UBC           0 :         case F_XMLEXISTS:
                              11412                 :                :             /* XMLEXISTS ... extra parens because args are c_expr */
                              11413                 :              0 :             appendStringInfoString(buf, "XMLEXISTS((");
                              11414                 :              0 :             get_rule_expr((Node *) linitial(expr->args), context, false);
                              11415                 :              0 :             appendStringInfoString(buf, ") PASSING (");
                              11416                 :              0 :             get_rule_expr((Node *) lsecond(expr->args), context, false);
                              11417                 :              0 :             appendStringInfoString(buf, "))");
                              11418                 :              0 :             return true;
                              11419                 :                :     }
 1819 tgl@sss.pgh.pa.us       11420                 :CBC           3 :     return false;
                              11421                 :                : }
                              11422                 :                : 
                              11423                 :                : /* ----------
                              11424                 :                :  * get_coercion_expr
                              11425                 :                :  *
                              11426                 :                :  *  Make a string representation of a value coerced to a specific type
                              11427                 :                :  * ----------
                              11428                 :                :  */
                              11429                 :                : static void
 6800                         11430                 :           2589 : get_coercion_expr(Node *arg, deparse_context *context,
                              11431                 :                :                   Oid resulttype, int32 resulttypmod,
                              11432                 :                :                   Node *parentNode)
                              11433                 :                : {
                              11434                 :           2589 :     StringInfo  buf = context->buf;
                              11435                 :                : 
                              11436                 :                :     /*
                              11437                 :                :      * Since parse_coerce.c doesn't immediately collapse application of
                              11438                 :                :      * length-coercion functions to constants, what we'll typically see in
                              11439                 :                :      * such cases is a Const with typmod -1 and a length-coercion function
                              11440                 :                :      * right above it.  Avoid generating redundant output. However, beware of
                              11441                 :                :      * suppressing casts when the user actually wrote something like
                              11442                 :                :      * 'foo'::text::char(3).
                              11443                 :                :      *
                              11444                 :                :      * Note: it might seem that we are missing the possibility of needing to
                              11445                 :                :      * print a COLLATE clause for such a Const.  However, a Const could only
                              11446                 :                :      * have nondefault collation in a post-constant-folding tree, in which the
                              11447                 :                :      * length coercion would have been folded too.  See also the special
                              11448                 :                :      * handling of CollateExpr in coerce_to_target_type(): any collation
                              11449                 :                :      * marking will be above the coercion node, not below it.
                              11450                 :                :      */
                              11451   [ +  -  +  + ]:           2589 :     if (arg && IsA(arg, Const) &&
                              11452         [ +  + ]:            307 :         ((Const *) arg)->consttype == resulttype &&
                              11453         [ +  - ]:             12 :         ((Const *) arg)->consttypmod == -1)
                              11454                 :                :     {
                              11455                 :                :         /* Show the constant without normal ::typename decoration */
 6505                         11456                 :             12 :         get_const_expr((Const *) arg, context, -1);
                              11457                 :                :     }
                              11458                 :                :     else
                              11459                 :                :     {
 6800                         11460         [ +  + ]:           2577 :         if (!PRETTY_PAREN(context))
                              11461                 :           2373 :             appendStringInfoChar(buf, '(');
                              11462                 :           2577 :         get_rule_expr_paren(arg, context, false, parentNode);
                              11463         [ +  + ]:           2577 :         if (!PRETTY_PAREN(context))
                              11464                 :           2373 :             appendStringInfoChar(buf, ')');
                              11465                 :                :     }
                              11466                 :                : 
                              11467                 :                :     /*
                              11468                 :                :      * Never emit resulttype(arg) functional notation. A pg_proc entry could
                              11469                 :                :      * take precedence, and a resulttype in pg_temp would require schema
                              11470                 :                :      * qualification that format_type_with_typemod() would usually omit. We've
                              11471                 :                :      * standardized on arg::resulttype, but CAST(arg AS resulttype) notation
                              11472                 :                :      * would work fine.
                              11473                 :                :      */
                              11474                 :           2589 :     appendStringInfo(buf, "::%s",
                              11475                 :                :                      format_type_with_typemod(resulttype, resulttypmod));
                              11476                 :           2589 : }
                              11477                 :                : 
                              11478                 :                : /* ----------
                              11479                 :                :  * get_const_expr
                              11480                 :                :  *
                              11481                 :                :  *  Make a string representation of a Const
                              11482                 :                :  *
                              11483                 :                :  * showtype can be -1 to never show "::typename" decoration, or +1 to always
                              11484                 :                :  * show it, or 0 to show it only if the constant wouldn't be assumed to be
                              11485                 :                :  * the right type by default.
                              11486                 :                :  *
                              11487                 :                :  * If the Const's collation isn't default for its type, show that too.
                              11488                 :                :  * We mustn't do this when showtype is -1 (since that means the caller will
                              11489                 :                :  * print "::typename", and we can't put a COLLATE clause in between).  It's
                              11490                 :                :  * caller's responsibility that collation isn't missed in such cases.
                              11491                 :                :  * ----------
                              11492                 :                :  */
                              11493                 :                : static void
 6505                         11494                 :          34883 : get_const_expr(Const *constval, deparse_context *context, int showtype)
                              11495                 :                : {
 9522                         11496                 :          34883 :     StringInfo  buf = context->buf;
                              11497                 :                :     Oid         typoutput;
                              11498                 :                :     bool        typIsVarlena;
                              11499                 :                :     char       *extval;
 3865                         11500                 :          34883 :     bool        needlabel = false;
                              11501                 :                : 
 9440                         11502         [ +  + ]:          34883 :     if (constval->constisnull)
                              11503                 :                :     {
                              11504                 :                :         /*
                              11505                 :                :          * Always label the type of a NULL constant to prevent misdecisions
                              11506                 :                :          * about type when reparsing.
                              11507                 :                :          */
 4380 rhaas@postgresql.org    11508                 :            585 :         appendStringInfoString(buf, "NULL");
 6505 tgl@sss.pgh.pa.us       11509         [ +  + ]:            585 :         if (showtype >= 0)
                              11510                 :                :         {
 6800                         11511                 :            558 :             appendStringInfo(buf, "::%s",
                              11512                 :                :                              format_type_with_typemod(constval->consttype,
                              11513                 :                :                                                       constval->consttypmod));
 5345                         11514                 :            558 :             get_const_collation(constval, context);
                              11515                 :                :         }
 9440                         11516                 :           4554 :         return;
                              11517                 :                :     }
                              11518                 :                : 
 7814                         11519                 :          34298 :     getTypeOutputInfo(constval->consttype,
                              11520                 :                :                       &typoutput, &typIsVarlena);
                              11521                 :                : 
 7147                         11522                 :          34298 :     extval = OidOutputFunctionCall(typoutput, constval->constvalue);
                              11523                 :                : 
 9521                         11524   [ +  +  +  + ]:          34298 :     switch (constval->consttype)
                              11525                 :                :     {
                              11526                 :          19719 :         case INT4OID:
                              11527                 :                : 
                              11528                 :                :             /*
                              11529                 :                :              * INT4 can be printed without any decoration, unless it is
                              11530                 :                :              * negative; in that case print it as '-nnn'::integer to ensure
                              11531                 :                :              * that the output will re-parse as a constant, not as a constant
                              11532                 :                :              * plus operator.  In most cases we could get away with printing
                              11533                 :                :              * (-nnn) instead, because of the way that gram.y handles negative
                              11534                 :                :              * literals; but that doesn't work for INT_MIN, and it doesn't
                              11535                 :                :              * seem that much prettier anyway.
                              11536                 :                :              */
 3865                         11537         [ +  + ]:          19719 :             if (extval[0] != '-')
                              11538                 :          19467 :                 appendStringInfoString(buf, extval);
                              11539                 :                :             else
                              11540                 :                :             {
                              11541                 :            252 :                 appendStringInfo(buf, "'%s'", extval);
 3051                         11542                 :            252 :                 needlabel = true;   /* we must attach a cast */
                              11543                 :                :             }
 3865                         11544                 :          19719 :             break;
                              11545                 :                : 
 8472 peter_e@gmx.net         11546                 :            545 :         case NUMERICOID:
                              11547                 :                : 
                              11548                 :                :             /*
                              11549                 :                :              * NUMERIC can be printed without quotes if it looks like a float
                              11550                 :                :              * constant (not an integer, and not Infinity or NaN) and doesn't
                              11551                 :                :              * have a leading sign (for the same reason as for INT4).
                              11552                 :                :              */
 3865 tgl@sss.pgh.pa.us       11553         [ +  - ]:            545 :             if (isdigit((unsigned char) extval[0]) &&
                              11554         [ +  + ]:            545 :                 strcspn(extval, "eE.") != strlen(extval))
                              11555                 :                :             {
                              11556                 :            190 :                 appendStringInfoString(buf, extval);
                              11557                 :                :             }
                              11558                 :                :             else
                              11559                 :                :             {
                              11560                 :            355 :                 appendStringInfo(buf, "'%s'", extval);
 3051                         11561                 :            355 :                 needlabel = true;   /* we must attach a cast */
                              11562                 :                :             }
 8455 bruce@momjian.us        11563                 :            545 :             break;
                              11564                 :                : 
 8472 peter_e@gmx.net         11565                 :            834 :         case BOOLOID:
 8455 bruce@momjian.us        11566         [ +  + ]:            834 :             if (strcmp(extval, "t") == 0)
 4380 rhaas@postgresql.org    11567                 :            370 :                 appendStringInfoString(buf, "true");
                              11568                 :                :             else
                              11569                 :            464 :                 appendStringInfoString(buf, "false");
 8472 peter_e@gmx.net         11570                 :            834 :             break;
                              11571                 :                : 
                              11572                 :          13200 :         default:
 6261 tgl@sss.pgh.pa.us       11573                 :          13200 :             simple_quote_literal(buf, extval);
 9521                         11574                 :          13200 :             break;
                              11575                 :                :     }
                              11576                 :                : 
 9523                         11577                 :          34298 :     pfree(extval);
                              11578                 :                : 
 6505                         11579         [ +  + ]:          34298 :     if (showtype < 0)
 6800                         11580                 :           3969 :         return;
                              11581                 :                : 
                              11582                 :                :     /*
                              11583                 :                :      * For showtype == 0, append ::typename unless the constant will be
                              11584                 :                :      * implicitly typed as the right type when it is read in.
                              11585                 :                :      *
                              11586                 :                :      * XXX this code has to be kept in sync with the behavior of the parser,
                              11587                 :                :      * especially make_const.
                              11588                 :                :      */
 9521                         11589   [ +  +  +  + ]:          30329 :     switch (constval->consttype)
                              11590                 :                :     {
 8472 peter_e@gmx.net         11591                 :            868 :         case BOOLOID:
                              11592                 :                :         case UNKNOWNOID:
                              11593                 :                :             /* These types can be left unlabeled */
 8441 tgl@sss.pgh.pa.us       11594                 :            868 :             needlabel = false;
                              11595                 :            868 :             break;
 3865                         11596                 :          17492 :         case INT4OID:
                              11597                 :                :             /* We determined above whether a label is needed */
                              11598                 :          17492 :             break;
 8441                         11599                 :            545 :         case NUMERICOID:
                              11600                 :                : 
                              11601                 :                :             /*
                              11602                 :                :              * Float-looking constants will be typed as numeric, which we
                              11603                 :                :              * checked above; but if there's a nondefault typmod we need to
                              11604                 :                :              * show it.
                              11605                 :                :              */
 3865                         11606                 :            545 :             needlabel |= (constval->consttypmod >= 0);
 9521                         11607                 :            545 :             break;
                              11608                 :          11424 :         default:
 8441                         11609                 :          11424 :             needlabel = true;
 9521                         11610                 :          11424 :             break;
                              11611                 :                :     }
 6505                         11612   [ +  +  -  + ]:          30329 :     if (needlabel || showtype > 0)
 8441                         11613                 :          12024 :         appendStringInfo(buf, "::%s",
                              11614                 :                :                          format_type_with_typemod(constval->consttype,
                              11615                 :                :                                                   constval->consttypmod));
                              11616                 :                : 
 5345                         11617                 :          30329 :     get_const_collation(constval, context);
                              11618                 :                : }
                              11619                 :                : 
                              11620                 :                : /*
                              11621                 :                :  * helper for get_const_expr: append COLLATE if needed
                              11622                 :                :  */
                              11623                 :                : static void
                              11624                 :          30887 : get_const_collation(Const *constval, deparse_context *context)
                              11625                 :                : {
                              11626                 :          30887 :     StringInfo  buf = context->buf;
                              11627                 :                : 
                              11628         [ +  + ]:          30887 :     if (OidIsValid(constval->constcollid))
                              11629                 :                :     {
 5315 bruce@momjian.us        11630                 :           4444 :         Oid         typcollation = get_typcollation(constval->consttype);
                              11631                 :                : 
 5345 tgl@sss.pgh.pa.us       11632         [ +  + ]:           4444 :         if (constval->constcollid != typcollation)
                              11633                 :                :         {
                              11634                 :             37 :             appendStringInfo(buf, " COLLATE %s",
                              11635                 :                :                              generate_collation_name(constval->constcollid));
                              11636                 :                :         }
                              11637                 :                :     }
 9888 bruce@momjian.us        11638                 :          30887 : }
                              11639                 :                : 
                              11640                 :                : /*
                              11641                 :                :  * get_json_path_spec       - Parse back a JSON path specification
                              11642                 :                :  */
                              11643                 :                : static void
  586 amitlan@postgresql.o    11644                 :            228 : get_json_path_spec(Node *path_spec, deparse_context *context, bool showimplicit)
                              11645                 :                : {
                              11646         [ +  - ]:            228 :     if (IsA(path_spec, Const))
                              11647                 :            228 :         get_const_expr((Const *) path_spec, context, -1);
                              11648                 :                :     else
  586 amitlan@postgresql.o    11649                 :UBC           0 :         get_rule_expr(path_spec, context, showimplicit);
  586 amitlan@postgresql.o    11650                 :CBC         228 : }
                              11651                 :                : 
                              11652                 :                : /*
                              11653                 :                :  * get_json_format          - Parse back a JsonFormat node
                              11654                 :                :  */
                              11655                 :                : static void
  944 alvherre@alvh.no-ip.    11656                 :             93 : get_json_format(JsonFormat *format, StringInfo buf)
                              11657                 :                : {
                              11658         [ +  + ]:             93 :     if (format->format_type == JS_FORMAT_DEFAULT)
                              11659                 :             54 :         return;
                              11660                 :                : 
                              11661                 :             39 :     appendStringInfoString(buf,
                              11662         [ -  + ]:             39 :                            format->format_type == JS_FORMAT_JSONB ?
                              11663                 :                :                            " FORMAT JSONB" : " FORMAT JSON");
                              11664                 :                : 
                              11665         [ +  + ]:             39 :     if (format->encoding != JS_ENC_DEFAULT)
                              11666                 :                :     {
                              11667                 :                :         const char *encoding;
                              11668                 :                : 
                              11669                 :              3 :         encoding =
                              11670         [ +  - ]:              6 :             format->encoding == JS_ENC_UTF16 ? "UTF16" :
                              11671         [ -  + ]:              3 :             format->encoding == JS_ENC_UTF32 ? "UTF32" : "UTF8";
                              11672                 :                : 
                              11673                 :              3 :         appendStringInfo(buf, " ENCODING %s", encoding);
                              11674                 :                :     }
                              11675                 :                : }
                              11676                 :                : 
                              11677                 :                : /*
                              11678                 :                :  * get_json_returning       - Parse back a JsonReturning structure
                              11679                 :                :  */
                              11680                 :                : static void
                              11681                 :             90 : get_json_returning(JsonReturning *returning, StringInfo buf,
                              11682                 :                :                    bool json_format_by_default)
                              11683                 :                : {
                              11684         [ -  + ]:             90 :     if (!OidIsValid(returning->typid))
  944 alvherre@alvh.no-ip.    11685                 :UBC           0 :         return;
                              11686                 :                : 
  944 alvherre@alvh.no-ip.    11687                 :CBC          90 :     appendStringInfo(buf, " RETURNING %s",
                              11688                 :                :                      format_type_with_typemod(returning->typid,
                              11689                 :                :                                               returning->typmod));
                              11690                 :                : 
                              11691   [ +  +  +  + ]:            174 :     if (!json_format_by_default ||
                              11692                 :             84 :         returning->format->format_type !=
                              11693         [ +  + ]:             84 :         (returning->typid == JSONBOID ? JS_FORMAT_JSONB : JS_FORMAT_JSON))
                              11694                 :             18 :         get_json_format(returning->format, buf);
                              11695                 :                : }
                              11696                 :                : 
                              11697                 :                : /*
                              11698                 :                :  * get_json_constructor     - Parse back a JsonConstructorExpr node
                              11699                 :                :  */
                              11700                 :                : static void
                              11701                 :             93 : get_json_constructor(JsonConstructorExpr *ctor, deparse_context *context,
                              11702                 :                :                      bool showimplicit)
                              11703                 :                : {
                              11704                 :             93 :     StringInfo  buf = context->buf;
                              11705                 :                :     const char *funcname;
                              11706                 :                :     bool        is_json_object;
                              11707                 :                :     int         curridx;
                              11708                 :                :     ListCell   *lc;
                              11709                 :                : 
                              11710         [ +  + ]:             93 :     if (ctor->type == JSCTOR_JSON_OBJECTAGG)
                              11711                 :                :     {
                              11712                 :             18 :         get_json_agg_constructor(ctor, context, "JSON_OBJECTAGG", true);
                              11713                 :             18 :         return;
                              11714                 :                :     }
                              11715         [ +  + ]:             75 :     else if (ctor->type == JSCTOR_JSON_ARRAYAGG)
                              11716                 :                :     {
                              11717                 :             15 :         get_json_agg_constructor(ctor, context, "JSON_ARRAYAGG", false);
                              11718                 :             15 :         return;
                              11719                 :                :     }
                              11720                 :                : 
                              11721   [ +  +  +  +  :             60 :     switch (ctor->type)
                                              +  - ]
                              11722                 :                :     {
                              11723                 :             15 :         case JSCTOR_JSON_OBJECT:
                              11724                 :             15 :             funcname = "JSON_OBJECT";
                              11725                 :             15 :             break;
                              11726                 :             12 :         case JSCTOR_JSON_ARRAY:
                              11727                 :             12 :             funcname = "JSON_ARRAY";
                              11728                 :             12 :             break;
  831 amitlan@postgresql.o    11729                 :             21 :         case JSCTOR_JSON_PARSE:
                              11730                 :             21 :             funcname = "JSON";
                              11731                 :             21 :             break;
                              11732                 :              6 :         case JSCTOR_JSON_SCALAR:
                              11733                 :              6 :             funcname = "JSON_SCALAR";
                              11734                 :              6 :             break;
                              11735                 :              6 :         case JSCTOR_JSON_SERIALIZE:
                              11736                 :              6 :             funcname = "JSON_SERIALIZE";
                              11737                 :              6 :             break;
  944 alvherre@alvh.no-ip.    11738                 :UBC           0 :         default:
  943                         11739         [ #  # ]:              0 :             elog(ERROR, "invalid JsonConstructorType %d", ctor->type);
                              11740                 :                :     }
                              11741                 :                : 
  944 alvherre@alvh.no-ip.    11742                 :CBC          60 :     appendStringInfo(buf, "%s(", funcname);
                              11743                 :                : 
                              11744                 :             60 :     is_json_object = ctor->type == JSCTOR_JSON_OBJECT;
                              11745   [ +  -  +  +  :            159 :     foreach(lc, ctor->args)
                                              +  + ]
                              11746                 :                :     {
                              11747                 :             99 :         curridx = foreach_current_index(lc);
                              11748         [ +  + ]:             99 :         if (curridx > 0)
                              11749                 :                :         {
                              11750                 :                :             const char *sep;
                              11751                 :                : 
                              11752   [ +  +  +  + ]:             39 :             sep = (is_json_object && (curridx % 2) != 0) ? " : " : ", ";
                              11753                 :             39 :             appendStringInfoString(buf, sep);
                              11754                 :                :         }
                              11755                 :                : 
                              11756                 :             99 :         get_rule_expr((Node *) lfirst(lc), context, true);
                              11757                 :                :     }
                              11758                 :                : 
                              11759                 :             60 :     get_json_constructor_options(ctor, buf);
  756 drowley@postgresql.o    11760                 :             60 :     appendStringInfoChar(buf, ')');
                              11761                 :                : }
                              11762                 :                : 
                              11763                 :                : /*
                              11764                 :                :  * Append options, if any, to the JSON constructor being deparsed
                              11765                 :                :  */
                              11766                 :                : static void
  944 alvherre@alvh.no-ip.    11767                 :             93 : get_json_constructor_options(JsonConstructorExpr *ctor, StringInfo buf)
                              11768                 :                : {
                              11769         [ +  + ]:             93 :     if (ctor->absent_on_null)
                              11770                 :                :     {
                              11771         [ +  - ]:             18 :         if (ctor->type == JSCTOR_JSON_OBJECT ||
                              11772         [ -  + ]:             18 :             ctor->type == JSCTOR_JSON_OBJECTAGG)
  944 alvherre@alvh.no-ip.    11773                 :UBC           0 :             appendStringInfoString(buf, " ABSENT ON NULL");
                              11774                 :                :     }
                              11775                 :                :     else
                              11776                 :                :     {
  944 alvherre@alvh.no-ip.    11777         [ +  - ]:CBC          75 :         if (ctor->type == JSCTOR_JSON_ARRAY ||
                              11778         [ +  + ]:             75 :             ctor->type == JSCTOR_JSON_ARRAYAGG)
                              11779                 :              9 :             appendStringInfoString(buf, " NULL ON NULL");
                              11780                 :                :     }
                              11781                 :                : 
                              11782         [ +  + ]:             93 :     if (ctor->unique)
                              11783                 :             12 :         appendStringInfoString(buf, " WITH UNIQUE KEYS");
                              11784                 :                : 
                              11785                 :                :     /*
                              11786                 :                :      * Append RETURNING clause if needed; JSON() and JSON_SCALAR() don't
                              11787                 :                :      * support one.
                              11788                 :                :      */
  831 amitlan@postgresql.o    11789   [ +  +  +  + ]:             93 :     if (ctor->type != JSCTOR_JSON_PARSE && ctor->type != JSCTOR_JSON_SCALAR)
                              11790                 :             66 :         get_json_returning(ctor->returning, buf, true);
  944 alvherre@alvh.no-ip.    11791                 :             93 : }
                              11792                 :                : 
                              11793                 :                : /*
                              11794                 :                :  * get_json_agg_constructor - Parse back an aggregate JsonConstructorExpr node
                              11795                 :                :  */
                              11796                 :                : static void
                              11797                 :             33 : get_json_agg_constructor(JsonConstructorExpr *ctor, deparse_context *context,
                              11798                 :                :                          const char *funcname, bool is_json_objectagg)
                              11799                 :                : {
                              11800                 :                :     StringInfoData options;
                              11801                 :                : 
                              11802                 :             33 :     initStringInfo(&options);
                              11803                 :             33 :     get_json_constructor_options(ctor, &options);
                              11804                 :                : 
                              11805         [ +  + ]:             33 :     if (IsA(ctor->func, Aggref))
                              11806                 :             27 :         get_agg_expr_helper((Aggref *) ctor->func, context,
                              11807                 :             27 :                             (Aggref *) ctor->func,
                              11808                 :             27 :                             funcname, options.data, is_json_objectagg);
                              11809         [ +  - ]:              6 :     else if (IsA(ctor->func, WindowFunc))
                              11810                 :              6 :         get_windowfunc_expr_helper((WindowFunc *) ctor->func, context,
                              11811                 :              6 :                                    funcname, options.data,
                              11812                 :                :                                    is_json_objectagg);
                              11813                 :                :     else
  944 alvherre@alvh.no-ip.    11814         [ #  # ]:UBC           0 :         elog(ERROR, "invalid JsonConstructorExpr underlying node type: %d",
                              11815                 :                :              nodeTag(ctor->func));
  944 alvherre@alvh.no-ip.    11816                 :CBC          33 : }
                              11817                 :                : 
                              11818                 :                : /*
                              11819                 :                :  * simple_quote_literal - Format a string as a SQL literal, append to buf
                              11820                 :                :  */
                              11821                 :                : static void
 6261 tgl@sss.pgh.pa.us       11822                 :          13618 : simple_quote_literal(StringInfo buf, const char *val)
                              11823                 :                : {
                              11824                 :                :     const char *valptr;
                              11825                 :                : 
                              11826                 :                :     /*
                              11827                 :                :      * We form the string literal according to the prevailing setting of
                              11828                 :                :      * standard_conforming_strings; we never use E''. User is responsible for
                              11829                 :                :      * making sure result is used correctly.
                              11830                 :                :      */
                              11831                 :          13618 :     appendStringInfoChar(buf, '\'');
                              11832         [ +  + ]:         139288 :     for (valptr = val; *valptr; valptr++)
                              11833                 :                :     {
                              11834                 :         125670 :         char        ch = *valptr;
                              11835                 :                : 
                              11836   [ +  +  +  +  :         125670 :         if (SQL_STR_DOUBLE(ch, !standard_conforming_strings))
                                              -  + ]
                              11837                 :            153 :             appendStringInfoChar(buf, ch);
                              11838                 :         125670 :         appendStringInfoChar(buf, ch);
                              11839                 :                :     }
                              11840                 :          13618 :     appendStringInfoChar(buf, '\'');
                              11841                 :          13618 : }
                              11842                 :                : 
                              11843                 :                : 
                              11844                 :                : /* ----------
                              11845                 :                :  * get_sublink_expr         - Parse back a sublink
                              11846                 :                :  * ----------
                              11847                 :                :  */
                              11848                 :                : static void
 8356                         11849                 :            230 : get_sublink_expr(SubLink *sublink, deparse_context *context)
                              11850                 :                : {
 9522                         11851                 :            230 :     StringInfo  buf = context->buf;
 9888 bruce@momjian.us        11852                 :            230 :     Query      *query = (Query *) (sublink->subselect);
 7244 tgl@sss.pgh.pa.us       11853                 :            230 :     char       *opname = NULL;
                              11854                 :                :     bool        need_paren;
                              11855                 :                : 
 8239                         11856         [ +  + ]:            230 :     if (sublink->subLinkType == ARRAY_SUBLINK)
 4380 rhaas@postgresql.org    11857                 :             12 :         appendStringInfoString(buf, "ARRAY(");
                              11858                 :                :     else
 8239 tgl@sss.pgh.pa.us       11859                 :            218 :         appendStringInfoChar(buf, '(');
                              11860                 :                : 
                              11861                 :                :     /*
                              11862                 :                :      * Note that we print the name of only the first operator, when there are
                              11863                 :                :      * multiple combining operators.  This is an approximation that could go
                              11864                 :                :      * wrong in various scenarios (operators in different schemas, renamed
                              11865                 :                :      * operators, etc) but there is not a whole lot we can do about it, since
                              11866                 :                :      * the syntax allows only one operator to be shown.
                              11867                 :                :      */
 7244                         11868         [ +  + ]:            230 :     if (sublink->testexpr)
                              11869                 :                :     {
                              11870         [ +  + ]:              9 :         if (IsA(sublink->testexpr, OpExpr))
                              11871                 :                :         {
                              11872                 :                :             /* single combining operator */
 6964 bruce@momjian.us        11873                 :              3 :             OpExpr     *opexpr = (OpExpr *) sublink->testexpr;
                              11874                 :                : 
 7244 tgl@sss.pgh.pa.us       11875                 :              3 :             get_rule_expr(linitial(opexpr->args), context, true);
                              11876                 :              3 :             opname = generate_operator_name(opexpr->opno,
                              11877                 :              3 :                                             exprType(linitial(opexpr->args)),
                              11878                 :              3 :                                             exprType(lsecond(opexpr->args)));
                              11879                 :                :         }
                              11880         [ +  + ]:              6 :         else if (IsA(sublink->testexpr, BoolExpr))
                              11881                 :                :         {
                              11882                 :                :             /* multiple combining operators, = or <> cases */
                              11883                 :                :             char       *sep;
                              11884                 :                :             ListCell   *l;
                              11885                 :                : 
 9382                         11886                 :              3 :             appendStringInfoChar(buf, '(');
 7244                         11887                 :              3 :             sep = "";
                              11888   [ +  -  +  +  :              9 :             foreach(l, ((BoolExpr *) sublink->testexpr)->args)
                                              +  + ]
                              11889                 :                :             {
 3123                         11890                 :              6 :                 OpExpr     *opexpr = lfirst_node(OpExpr, l);
                              11891                 :                : 
 7244                         11892                 :              6 :                 appendStringInfoString(buf, sep);
                              11893                 :              6 :                 get_rule_expr(linitial(opexpr->args), context, true);
                              11894         [ +  + ]:              6 :                 if (!opname)
                              11895                 :              3 :                     opname = generate_operator_name(opexpr->opno,
 3051                         11896                 :              3 :                                                     exprType(linitial(opexpr->args)),
                              11897                 :              3 :                                                     exprType(lsecond(opexpr->args)));
 7244                         11898                 :              6 :                 sep = ", ";
                              11899                 :                :             }
 7691                         11900                 :              3 :             appendStringInfoChar(buf, ')');
                              11901                 :                :         }
 7244                         11902         [ +  - ]:              3 :         else if (IsA(sublink->testexpr, RowCompareExpr))
                              11903                 :                :         {
                              11904                 :                :             /* multiple combining operators, < <= > >= cases */
                              11905                 :              3 :             RowCompareExpr *rcexpr = (RowCompareExpr *) sublink->testexpr;
                              11906                 :                : 
                              11907                 :              3 :             appendStringInfoChar(buf, '(');
                              11908                 :              3 :             get_rule_expr((Node *) rcexpr->largs, context, true);
                              11909                 :              3 :             opname = generate_operator_name(linitial_oid(rcexpr->opnos),
                              11910                 :              3 :                                             exprType(linitial(rcexpr->largs)),
 3051                         11911                 :              3 :                                             exprType(linitial(rcexpr->rargs)));
 7244                         11912                 :              3 :             appendStringInfoChar(buf, ')');
                              11913                 :                :         }
                              11914                 :                :         else
 7244 tgl@sss.pgh.pa.us       11915         [ #  # ]:UBC           0 :             elog(ERROR, "unrecognized testexpr type: %d",
                              11916                 :                :                  (int) nodeTag(sublink->testexpr));
                              11917                 :                :     }
                              11918                 :                : 
 9479 tgl@sss.pgh.pa.us       11919                 :CBC         230 :     need_paren = true;
                              11920                 :                : 
 9653 bruce@momjian.us        11921   [ +  +  +  -  :            230 :     switch (sublink->subLinkType)
                                              +  - ]
                              11922                 :                :     {
 9888                         11923                 :             88 :         case EXISTS_SUBLINK:
 4380 rhaas@postgresql.org    11924                 :             88 :             appendStringInfoString(buf, "EXISTS ");
 9888 bruce@momjian.us        11925                 :             88 :             break;
                              11926                 :                : 
                              11927                 :              6 :         case ANY_SUBLINK:
 3051 tgl@sss.pgh.pa.us       11928         [ +  + ]:              6 :             if (strcmp(opname, "=") == 0) /* Represent = ANY as IN */
 4380 rhaas@postgresql.org    11929                 :              3 :                 appendStringInfoString(buf, " IN ");
                              11930                 :                :             else
 7244 tgl@sss.pgh.pa.us       11931                 :              3 :                 appendStringInfo(buf, " %s ANY ", opname);
 9888 bruce@momjian.us        11932                 :              6 :             break;
                              11933                 :                : 
                              11934                 :              3 :         case ALL_SUBLINK:
 7244 tgl@sss.pgh.pa.us       11935                 :              3 :             appendStringInfo(buf, " %s ALL ", opname);
 9888 bruce@momjian.us        11936                 :              3 :             break;
                              11937                 :                : 
 7244 tgl@sss.pgh.pa.us       11938                 :UBC           0 :         case ROWCOMPARE_SUBLINK:
                              11939                 :              0 :             appendStringInfo(buf, " %s ", opname);
 9888 bruce@momjian.us        11940                 :              0 :             break;
                              11941                 :                : 
 9479 tgl@sss.pgh.pa.us       11942                 :CBC         133 :         case EXPR_SUBLINK:
                              11943                 :                :         case MULTIEXPR_SUBLINK:
                              11944                 :                :         case ARRAY_SUBLINK:
                              11945                 :            133 :             need_paren = false;
                              11946                 :            133 :             break;
                              11947                 :                : 
 6233 tgl@sss.pgh.pa.us       11948                 :UBC           0 :         case CTE_SUBLINK:       /* shouldn't occur in a SubLink */
                              11949                 :                :         default:
 8129                         11950         [ #  # ]:              0 :             elog(ERROR, "unrecognized sublink type: %d",
                              11951                 :                :                  (int) sublink->subLinkType);
                              11952                 :                :             break;
                              11953                 :                :     }
                              11954                 :                : 
 9479 tgl@sss.pgh.pa.us       11955         [ +  + ]:CBC         230 :     if (need_paren)
 9382                         11956                 :             97 :         appendStringInfoChar(buf, '(');
                              11957                 :                : 
 1256                         11958                 :            230 :     get_query_def(query, buf, context->namespaces, NULL, false,
                              11959                 :                :                   context->prettyFlags, context->wrapColumn,
                              11960                 :                :                   context->indentLevel);
                              11961                 :                : 
 9479                         11962         [ +  + ]:            230 :     if (need_paren)
 4380 rhaas@postgresql.org    11963                 :             97 :         appendStringInfoString(buf, "))");
                              11964                 :                :     else
 9382 tgl@sss.pgh.pa.us       11965                 :            133 :         appendStringInfoChar(buf, ')');
 9927 bruce@momjian.us        11966                 :            230 : }
                              11967                 :                : 
                              11968                 :                : 
                              11969                 :                : /* ----------
                              11970                 :                :  * get_xmltable         - Parse back a XMLTABLE function
                              11971                 :                :  * ----------
                              11972                 :                :  */
                              11973                 :                : static void
  572 amitlan@postgresql.o    11974                 :             31 : get_xmltable(TableFunc *tf, deparse_context *context, bool showimplicit)
                              11975                 :                : {
 3156 alvherre@alvh.no-ip.    11976                 :             31 :     StringInfo  buf = context->buf;
                              11977                 :                : 
                              11978                 :             31 :     appendStringInfoString(buf, "XMLTABLE(");
                              11979                 :                : 
                              11980         [ +  + ]:             31 :     if (tf->ns_uris != NIL)
                              11981                 :                :     {
                              11982                 :                :         ListCell   *lc1,
                              11983                 :                :                    *lc2;
                              11984                 :              8 :         bool        first = true;
                              11985                 :                : 
                              11986                 :              8 :         appendStringInfoString(buf, "XMLNAMESPACES (");
                              11987   [ +  -  +  +  :             16 :         forboth(lc1, tf->ns_uris, lc2, tf->ns_names)
                                     +  -  +  +  +  
                                        +  +  -  +  
                                                 + ]
                              11988                 :                :         {
                              11989                 :              8 :             Node       *expr = (Node *) lfirst(lc1);
 1510 peter@eisentraut.org    11990                 :              8 :             String     *ns_node = lfirst_node(String, lc2);
                              11991                 :                : 
 3156 alvherre@alvh.no-ip.    11992         [ -  + ]:              8 :             if (!first)
 3156 alvherre@alvh.no-ip.    11993                 :UBC           0 :                 appendStringInfoString(buf, ", ");
                              11994                 :                :             else
 3156 alvherre@alvh.no-ip.    11995                 :CBC           8 :                 first = false;
                              11996                 :                : 
 2598 tgl@sss.pgh.pa.us       11997         [ +  - ]:              8 :             if (ns_node != NULL)
                              11998                 :                :             {
 3156 alvherre@alvh.no-ip.    11999                 :              8 :                 get_rule_expr(expr, context, showimplicit);
  289 dean.a.rasheed@gmail    12000                 :              8 :                 appendStringInfo(buf, " AS %s",
                              12001                 :              8 :                                  quote_identifier(strVal(ns_node)));
                              12002                 :                :             }
                              12003                 :                :             else
                              12004                 :                :             {
 3156 alvherre@alvh.no-ip.    12005                 :UBC           0 :                 appendStringInfoString(buf, "DEFAULT ");
                              12006                 :              0 :                 get_rule_expr(expr, context, showimplicit);
                              12007                 :                :             }
                              12008                 :                :         }
 3156 alvherre@alvh.no-ip.    12009                 :CBC           8 :         appendStringInfoString(buf, "), ");
                              12010                 :                :     }
                              12011                 :                : 
                              12012                 :             31 :     appendStringInfoChar(buf, '(');
                              12013                 :             31 :     get_rule_expr((Node *) tf->rowexpr, context, showimplicit);
                              12014                 :             31 :     appendStringInfoString(buf, ") PASSING (");
                              12015                 :             31 :     get_rule_expr((Node *) tf->docexpr, context, showimplicit);
                              12016                 :             31 :     appendStringInfoChar(buf, ')');
                              12017                 :                : 
                              12018         [ +  - ]:             31 :     if (tf->colexprs != NIL)
                              12019                 :                :     {
                              12020                 :                :         ListCell   *l1;
                              12021                 :                :         ListCell   *l2;
                              12022                 :                :         ListCell   *l3;
                              12023                 :                :         ListCell   *l4;
                              12024                 :                :         ListCell   *l5;
                              12025                 :             31 :         int         colnum = 0;
                              12026                 :                : 
                              12027                 :             31 :         appendStringInfoString(buf, " COLUMNS ");
 2434 tgl@sss.pgh.pa.us       12028   [ +  -  +  +  :            187 :         forfive(l1, tf->colnames, l2, tf->coltypes, l3, tf->coltypmods,
                                     +  -  +  +  +  
                                     -  +  +  +  -  
                                     +  +  +  -  +  
                                     +  +  +  +  -  
                                     +  -  +  -  +  
                                           -  +  + ]
                              12029                 :                :                 l4, tf->colexprs, l5, tf->coldefexprs)
                              12030                 :                :         {
 3156 alvherre@alvh.no-ip.    12031                 :            156 :             char       *colname = strVal(lfirst(l1));
 2434 tgl@sss.pgh.pa.us       12032                 :            156 :             Oid         typid = lfirst_oid(l2);
                              12033                 :            156 :             int32       typmod = lfirst_int(l3);
                              12034                 :            156 :             Node       *colexpr = (Node *) lfirst(l4);
                              12035                 :            156 :             Node       *coldefexpr = (Node *) lfirst(l5);
                              12036                 :            156 :             bool        ordinality = (tf->ordinalitycol == colnum);
 3156 alvherre@alvh.no-ip.    12037                 :            156 :             bool        notnull = bms_is_member(colnum, tf->notnulls);
                              12038                 :                : 
                              12039         [ +  + ]:            156 :             if (colnum > 0)
                              12040                 :            125 :                 appendStringInfoString(buf, ", ");
                              12041                 :            156 :             colnum++;
                              12042                 :                : 
                              12043         [ +  + ]:            295 :             appendStringInfo(buf, "%s %s", quote_identifier(colname),
                              12044                 :                :                              ordinality ? "FOR ORDINALITY" :
                              12045                 :            139 :                              format_type_with_typemod(typid, typmod));
                              12046         [ +  + ]:            156 :             if (ordinality)
                              12047                 :             17 :                 continue;
                              12048                 :                : 
                              12049         [ +  + ]:            139 :             if (coldefexpr != NULL)
                              12050                 :                :             {
                              12051                 :             17 :                 appendStringInfoString(buf, " DEFAULT (");
                              12052                 :             17 :                 get_rule_expr((Node *) coldefexpr, context, showimplicit);
                              12053                 :             17 :                 appendStringInfoChar(buf, ')');
                              12054                 :                :             }
                              12055         [ +  + ]:            139 :             if (colexpr != NULL)
                              12056                 :                :             {
                              12057                 :            127 :                 appendStringInfoString(buf, " PATH (");
                              12058                 :            127 :                 get_rule_expr((Node *) colexpr, context, showimplicit);
                              12059                 :            127 :                 appendStringInfoChar(buf, ')');
                              12060                 :                :             }
                              12061         [ +  + ]:            139 :             if (notnull)
                              12062                 :             17 :                 appendStringInfoString(buf, " NOT NULL");
                              12063                 :                :         }
                              12064                 :                :     }
                              12065                 :                : 
                              12066                 :             31 :     appendStringInfoChar(buf, ')');
                              12067                 :             31 : }
                              12068                 :                : 
                              12069                 :                : /*
                              12070                 :                :  * get_json_table_nested_columns - Parse back nested JSON_TABLE columns
                              12071                 :                :  */
                              12072                 :                : static void
  568 amitlan@postgresql.o    12073                 :             51 : get_json_table_nested_columns(TableFunc *tf, JsonTablePlan *plan,
                              12074                 :                :                               deparse_context *context, bool showimplicit,
                              12075                 :                :                               bool needcomma)
                              12076                 :                : {
                              12077         [ +  + ]:             51 :     if (IsA(plan, JsonTablePathScan))
                              12078                 :                :     {
                              12079                 :             36 :         JsonTablePathScan *scan = castNode(JsonTablePathScan, plan);
                              12080                 :                : 
                              12081         [ +  + ]:             36 :         if (needcomma)
                              12082                 :             24 :             appendStringInfoChar(context->buf, ',');
                              12083                 :                : 
                              12084                 :             36 :         appendStringInfoChar(context->buf, ' ');
                              12085                 :             36 :         appendContextKeyword(context, "NESTED PATH ", 0, 0, 0);
                              12086                 :             36 :         get_const_expr(scan->path->value, context, -1);
                              12087                 :             36 :         appendStringInfo(context->buf, " AS %s", quote_identifier(scan->path->name));
                              12088                 :             36 :         get_json_table_columns(tf, scan, context, showimplicit);
                              12089                 :                :     }
                              12090         [ +  - ]:             15 :     else if (IsA(plan, JsonTableSiblingJoin))
                              12091                 :                :     {
                              12092                 :             15 :         JsonTableSiblingJoin *join = (JsonTableSiblingJoin *) plan;
                              12093                 :                : 
                              12094                 :             15 :         get_json_table_nested_columns(tf, join->lplan, context, showimplicit,
                              12095                 :                :                                       needcomma);
                              12096                 :             15 :         get_json_table_nested_columns(tf, join->rplan, context, showimplicit,
                              12097                 :                :                                       true);
                              12098                 :                :     }
                              12099                 :             51 : }
                              12100                 :                : 
                              12101                 :                : /*
                              12102                 :                :  * get_json_table_columns - Parse back JSON_TABLE columns
                              12103                 :                :  */
                              12104                 :                : static void
                              12105                 :             90 : get_json_table_columns(TableFunc *tf, JsonTablePathScan *scan,
                              12106                 :                :                        deparse_context *context,
                              12107                 :                :                        bool showimplicit)
                              12108                 :                : {
  572                         12109                 :             90 :     StringInfo  buf = context->buf;
                              12110                 :                :     ListCell   *lc_colname;
                              12111                 :                :     ListCell   *lc_coltype;
                              12112                 :                :     ListCell   *lc_coltypmod;
                              12113                 :                :     ListCell   *lc_colvalexpr;
                              12114                 :             90 :     int         colnum = 0;
                              12115                 :                : 
                              12116                 :             90 :     appendStringInfoChar(buf, ' ');
                              12117                 :             90 :     appendContextKeyword(context, "COLUMNS (", 0, 0, 0);
                              12118                 :                : 
                              12119         [ +  + ]:             90 :     if (PRETTY_INDENT(context))
                              12120                 :             69 :         context->indentLevel += PRETTYINDENT_VAR;
                              12121                 :                : 
                              12122   [ +  -  +  +  :            429 :     forfour(lc_colname, tf->colnames,
                                     +  -  +  +  +  
                                     -  +  +  +  -  
                                     +  +  +  +  +  
                                     -  +  -  +  -  
                                              +  + ]
                              12123                 :                :             lc_coltype, tf->coltypes,
                              12124                 :                :             lc_coltypmod, tf->coltypmods,
                              12125                 :                :             lc_colvalexpr, tf->colvalexprs)
                              12126                 :                :     {
                              12127                 :            363 :         char       *colname = strVal(lfirst(lc_colname));
                              12128                 :                :         JsonExpr   *colexpr;
                              12129                 :                :         Oid         typid;
                              12130                 :                :         int32       typmod;
                              12131                 :                :         bool        ordinality;
                              12132                 :                :         JsonBehaviorType default_behavior;
                              12133                 :                : 
                              12134                 :            363 :         typid = lfirst_oid(lc_coltype);
                              12135                 :            363 :         typmod = lfirst_int(lc_coltypmod);
                              12136                 :            363 :         colexpr = castNode(JsonExpr, lfirst(lc_colvalexpr));
                              12137                 :                : 
                              12138                 :                :         /* Skip columns that don't belong to this scan. */
  568                         12139   [ +  +  +  + ]:            363 :         if (scan->colMin < 0 || colnum < scan->colMin)
                              12140                 :                :         {
                              12141                 :            132 :             colnum++;
                              12142                 :            132 :             continue;
                              12143                 :                :         }
                              12144         [ +  + ]:            231 :         if (colnum > scan->colMax)
                              12145                 :             24 :             break;
                              12146                 :                : 
                              12147         [ +  + ]:            207 :         if (colnum > scan->colMin)
  572                         12148                 :            129 :             appendStringInfoString(buf, ", ");
                              12149                 :                : 
                              12150                 :            207 :         colnum++;
                              12151                 :                : 
                              12152                 :            207 :         ordinality = !colexpr;
                              12153                 :                : 
                              12154                 :            207 :         appendContextKeyword(context, "", 0, 0, 0);
                              12155                 :                : 
                              12156         [ +  + ]:            405 :         appendStringInfo(buf, "%s %s", quote_identifier(colname),
                              12157                 :                :                          ordinality ? "FOR ORDINALITY" :
                              12158                 :            198 :                          format_type_with_typemod(typid, typmod));
                              12159         [ +  + ]:            207 :         if (ordinality)
                              12160                 :              9 :             continue;
                              12161                 :                : 
                              12162                 :                :         /*
                              12163                 :                :          * Set default_behavior to guide get_json_expr_options() on whether to
                              12164                 :                :          * emit the ON ERROR / EMPTY clauses.
                              12165                 :                :          */
                              12166         [ +  + ]:            198 :         if (colexpr->op == JSON_EXISTS_OP)
                              12167                 :                :         {
                              12168                 :             18 :             appendStringInfoString(buf, " EXISTS");
                              12169                 :             18 :             default_behavior = JSON_BEHAVIOR_FALSE;
                              12170                 :                :         }
                              12171                 :                :         else
                              12172                 :                :         {
                              12173         [ +  + ]:            180 :             if (colexpr->op == JSON_QUERY_OP)
                              12174                 :                :             {
                              12175                 :                :                 char        typcategory;
                              12176                 :                :                 bool        typispreferred;
                              12177                 :                : 
                              12178                 :             87 :                 get_type_category_preferred(typid, &typcategory, &typispreferred);
                              12179                 :                : 
                              12180         [ +  + ]:             87 :                 if (typcategory == TYPCATEGORY_STRING)
                              12181                 :             18 :                     appendStringInfoString(buf,
                              12182         [ -  + ]:             18 :                                            colexpr->format->format_type == JS_FORMAT_JSONB ?
                              12183                 :                :                                            " FORMAT JSONB" : " FORMAT JSON");
                              12184                 :                :             }
                              12185                 :                : 
                              12186                 :            180 :             default_behavior = JSON_BEHAVIOR_NULL;
                              12187                 :                :         }
                              12188                 :                : 
                              12189                 :            198 :         appendStringInfoString(buf, " PATH ");
                              12190                 :                : 
                              12191                 :            198 :         get_json_path_spec(colexpr->path_spec, context, showimplicit);
                              12192                 :                : 
                              12193                 :            198 :         get_json_expr_options(colexpr, context, default_behavior);
                              12194                 :                :     }
                              12195                 :                : 
  568                         12196         [ +  + ]:             90 :     if (scan->child)
                              12197                 :             21 :         get_json_table_nested_columns(tf, scan->child, context, showimplicit,
                              12198                 :             21 :                                       scan->colMin >= 0);
                              12199                 :                : 
  572                         12200         [ +  + ]:             90 :     if (PRETTY_INDENT(context))
                              12201                 :             69 :         context->indentLevel -= PRETTYINDENT_VAR;
                              12202                 :                : 
                              12203                 :             90 :     appendContextKeyword(context, ")", 0, 0, 0);
                              12204                 :             90 : }
                              12205                 :                : 
                              12206                 :                : /* ----------
                              12207                 :                :  * get_json_table           - Parse back a JSON_TABLE function
                              12208                 :                :  * ----------
                              12209                 :                :  */
                              12210                 :                : static void
                              12211                 :             54 : get_json_table(TableFunc *tf, deparse_context *context, bool showimplicit)
                              12212                 :                : {
                              12213                 :             54 :     StringInfo  buf = context->buf;
                              12214                 :             54 :     JsonExpr   *jexpr = castNode(JsonExpr, tf->docexpr);
                              12215                 :             54 :     JsonTablePathScan *root = castNode(JsonTablePathScan, tf->plan);
                              12216                 :                : 
                              12217                 :             54 :     appendStringInfoString(buf, "JSON_TABLE(");
                              12218                 :                : 
                              12219         [ +  + ]:             54 :     if (PRETTY_INDENT(context))
                              12220                 :             33 :         context->indentLevel += PRETTYINDENT_VAR;
                              12221                 :                : 
                              12222                 :             54 :     appendContextKeyword(context, "", 0, 0, 0);
                              12223                 :                : 
                              12224                 :             54 :     get_rule_expr(jexpr->formatted_expr, context, showimplicit);
                              12225                 :                : 
                              12226                 :             54 :     appendStringInfoString(buf, ", ");
                              12227                 :                : 
                              12228                 :             54 :     get_const_expr(root->path->value, context, -1);
                              12229                 :                : 
                              12230                 :             54 :     appendStringInfo(buf, " AS %s", quote_identifier(root->path->name));
                              12231                 :                : 
                              12232         [ +  + ]:             54 :     if (jexpr->passing_values)
                              12233                 :                :     {
                              12234                 :                :         ListCell   *lc1,
                              12235                 :                :                    *lc2;
                              12236                 :             42 :         bool        needcomma = false;
                              12237                 :                : 
                              12238                 :             42 :         appendStringInfoChar(buf, ' ');
                              12239                 :             42 :         appendContextKeyword(context, "PASSING ", 0, 0, 0);
                              12240                 :                : 
                              12241         [ +  + ]:             42 :         if (PRETTY_INDENT(context))
                              12242                 :             21 :             context->indentLevel += PRETTYINDENT_VAR;
                              12243                 :                : 
                              12244   [ +  -  +  +  :            126 :         forboth(lc1, jexpr->passing_names,
                                     +  -  +  +  +  
                                        +  +  -  +  
                                                 + ]
                              12245                 :                :                 lc2, jexpr->passing_values)
                              12246                 :                :         {
                              12247         [ +  + ]:             84 :             if (needcomma)
                              12248                 :             42 :                 appendStringInfoString(buf, ", ");
                              12249                 :             84 :             needcomma = true;
                              12250                 :                : 
                              12251                 :             84 :             appendContextKeyword(context, "", 0, 0, 0);
                              12252                 :                : 
                              12253                 :             84 :             get_rule_expr((Node *) lfirst(lc2), context, false);
                              12254                 :             84 :             appendStringInfo(buf, " AS %s",
                              12255                 :             84 :                              quote_identifier((lfirst_node(String, lc1))->sval)
                              12256                 :                :                 );
                              12257                 :                :         }
                              12258                 :                : 
                              12259         [ +  + ]:             42 :         if (PRETTY_INDENT(context))
                              12260                 :             21 :             context->indentLevel -= PRETTYINDENT_VAR;
                              12261                 :                :     }
                              12262                 :                : 
  568                         12263                 :             54 :     get_json_table_columns(tf, castNode(JsonTablePathScan, tf->plan), context,
                              12264                 :                :                            showimplicit);
                              12265                 :                : 
  417                         12266         [ +  + ]:             54 :     if (jexpr->on_error->btype != JSON_BEHAVIOR_EMPTY_ARRAY)
  572                         12267                 :              3 :         get_json_behavior(jexpr->on_error, context, "ERROR");
                              12268                 :                : 
                              12269         [ +  + ]:             54 :     if (PRETTY_INDENT(context))
                              12270                 :             33 :         context->indentLevel -= PRETTYINDENT_VAR;
                              12271                 :                : 
                              12272                 :             54 :     appendContextKeyword(context, ")", 0, 0, 0);
                              12273                 :             54 : }
                              12274                 :                : 
                              12275                 :                : /* ----------
                              12276                 :                :  * get_tablefunc            - Parse back a table function
                              12277                 :                :  * ----------
                              12278                 :                :  */
                              12279                 :                : static void
                              12280                 :             85 : get_tablefunc(TableFunc *tf, deparse_context *context, bool showimplicit)
                              12281                 :                : {
                              12282                 :                :     /* XMLTABLE and JSON_TABLE are the only existing implementations.  */
                              12283                 :                : 
                              12284         [ +  + ]:             85 :     if (tf->functype == TFT_XMLTABLE)
                              12285                 :             31 :         get_xmltable(tf, context, showimplicit);
                              12286         [ +  - ]:             54 :     else if (tf->functype == TFT_JSON_TABLE)
                              12287                 :             54 :         get_json_table(tf, context, showimplicit);
                              12288                 :             85 : }
                              12289                 :                : 
                              12290                 :                : /* ----------
                              12291                 :                :  * get_from_clause          - Parse back a FROM clause
                              12292                 :                :  *
                              12293                 :                :  * "prefix" is the keyword that denotes the start of the list of FROM
                              12294                 :                :  * elements. It is FROM when used to parse back SELECT and UPDATE, but
                              12295                 :                :  * is USING when parsing back DELETE.
                              12296                 :                :  * ----------
                              12297                 :                :  */
                              12298                 :                : static void
 7509 neilc@samurai.com       12299                 :           2463 : get_from_clause(Query *query, const char *prefix, deparse_context *context)
                              12300                 :                : {
 9177 tgl@sss.pgh.pa.us       12301                 :           2463 :     StringInfo  buf = context->buf;
 8126                         12302                 :           2463 :     bool        first = true;
                              12303                 :                :     ListCell   *l;
                              12304                 :                : 
                              12305                 :                :     /*
                              12306                 :                :      * We use the query's jointree as a guide to what to print.  However, we
                              12307                 :                :      * must ignore auto-added RTEs that are marked not inFromCl. (These can
                              12308                 :                :      * only appear at the top level of the jointree, so it's sufficient to
                              12309                 :                :      * check here.)  This check also ensures we ignore the rule pseudo-RTEs
                              12310                 :                :      * for NEW and OLD.
                              12311                 :                :      */
 9160                         12312   [ +  +  +  +  :           4901 :     foreach(l, query->jointree->fromlist)
                                              +  + ]
                              12313                 :                :     {
 8986 bruce@momjian.us        12314                 :           2438 :         Node       *jtnode = (Node *) lfirst(l);
                              12315                 :                : 
 9177 tgl@sss.pgh.pa.us       12316         [ +  + ]:           2438 :         if (IsA(jtnode, RangeTblRef))
                              12317                 :                :         {
                              12318                 :           1955 :             int         varno = ((RangeTblRef *) jtnode)->rtindex;
                              12319                 :           1955 :             RangeTblEntry *rte = rt_fetch(varno, query->rtable);
                              12320                 :                : 
                              12321         [ +  + ]:           1955 :             if (!rte->inFromCl)
                              12322                 :            200 :                 continue;
                              12323                 :                :         }
                              12324                 :                : 
 8126                         12325         [ +  + ]:           2238 :         if (first)
                              12326                 :                :         {
 7509 neilc@samurai.com       12327                 :           2053 :             appendContextKeyword(context, prefix,
                              12328                 :                :                                  -PRETTYINDENT_STD, PRETTYINDENT_STD, 2);
 8126 tgl@sss.pgh.pa.us       12329                 :           2053 :             first = false;
                              12330                 :                : 
 5000 andrew@dunslane.net     12331                 :           2053 :             get_from_clause_item(jtnode, query, context);
                              12332                 :                :         }
                              12333                 :                :         else
                              12334                 :                :         {
                              12335                 :                :             StringInfoData itembuf;
                              12336                 :                : 
 8121 bruce@momjian.us        12337                 :            185 :             appendStringInfoString(buf, ", ");
                              12338                 :                : 
                              12339                 :                :             /*
                              12340                 :                :              * Put the new FROM item's text into itembuf so we can decide
                              12341                 :                :              * after we've got it whether or not it needs to go on a new line.
                              12342                 :                :              */
 4691 tgl@sss.pgh.pa.us       12343                 :            185 :             initStringInfo(&itembuf);
                              12344                 :            185 :             context->buf = &itembuf;
                              12345                 :                : 
 5000 andrew@dunslane.net     12346                 :            185 :             get_from_clause_item(jtnode, query, context);
                              12347                 :                : 
                              12348                 :                :             /* Restore context's output buffer */
                              12349                 :            185 :             context->buf = buf;
                              12350                 :                : 
                              12351                 :                :             /* Consider line-wrapping if enabled */
 4691 tgl@sss.pgh.pa.us       12352   [ +  -  +  - ]:            185 :             if (PRETTY_INDENT(context) && context->wrapColumn >= 0)
                              12353                 :                :             {
                              12354                 :                :                 /* Does the new item start with a new line? */
 4369                         12355   [ +  -  -  + ]:            185 :                 if (itembuf.len > 0 && itembuf.data[0] == '\n')
                              12356                 :                :                 {
                              12357                 :                :                     /* If so, we shouldn't add anything */
                              12358                 :                :                     /* instead, remove any trailing spaces currently in buf */
 4369 tgl@sss.pgh.pa.us       12359                 :UBC           0 :                     removeStringInfoSpaces(buf);
                              12360                 :                :                 }
                              12361                 :                :                 else
                              12362                 :                :                 {
                              12363                 :                :                     char       *trailing_nl;
                              12364                 :                : 
                              12365                 :                :                     /* Locate the start of the current line in the buffer */
 4369 tgl@sss.pgh.pa.us       12366                 :CBC         185 :                     trailing_nl = strrchr(buf->data, '\n');
                              12367         [ -  + ]:            185 :                     if (trailing_nl == NULL)
 4369 tgl@sss.pgh.pa.us       12368                 :UBC           0 :                         trailing_nl = buf->data;
                              12369                 :                :                     else
 4369 tgl@sss.pgh.pa.us       12370                 :CBC         185 :                         trailing_nl++;
                              12371                 :                : 
                              12372                 :                :                     /*
                              12373                 :                :                      * Add a newline, plus some indentation, if the new item
                              12374                 :                :                      * would cause an overflow.
                              12375                 :                :                      */
                              12376         [ +  - ]:            185 :                     if (strlen(trailing_nl) + itembuf.len > context->wrapColumn)
                              12377                 :            185 :                         appendContextKeyword(context, "", -PRETTYINDENT_STD,
                              12378                 :                :                                              PRETTYINDENT_STD,
                              12379                 :                :                                              PRETTYINDENT_VAR);
                              12380                 :                :                 }
                              12381                 :                :             }
                              12382                 :                : 
                              12383                 :                :             /* Add the new item */
 2289 drowley@postgresql.o    12384                 :            185 :             appendBinaryStringInfo(buf, itembuf.data, itembuf.len);
                              12385                 :                : 
                              12386                 :                :             /* clean up */
 4691 tgl@sss.pgh.pa.us       12387                 :            185 :             pfree(itembuf.data);
                              12388                 :                :         }
                              12389                 :                :     }
 9177                         12390                 :           2463 : }
                              12391                 :                : 
                              12392                 :                : static void
                              12393                 :           3760 : get_from_clause_item(Node *jtnode, Query *query, deparse_context *context)
                              12394                 :                : {
                              12395                 :           3760 :     StringInfo  buf = context->buf;
 4684                         12396                 :           3760 :     deparse_namespace *dpns = (deparse_namespace *) linitial(context->namespaces);
                              12397                 :                : 
 9177                         12398         [ +  + ]:           3760 :     if (IsA(jtnode, RangeTblRef))
                              12399                 :                :     {
                              12400                 :           2999 :         int         varno = ((RangeTblRef *) jtnode)->rtindex;
                              12401                 :           2999 :         RangeTblEntry *rte = rt_fetch(varno, query->rtable);
 4684                         12402                 :           2999 :         deparse_columns *colinfo = deparse_columns_fetch(varno, dpns);
 4359                         12403                 :           2999 :         RangeTblFunction *rtfunc1 = NULL;
                              12404                 :                : 
 4830                         12405         [ +  + ]:           2999 :         if (rte->lateral)
                              12406                 :             62 :             appendStringInfoString(buf, "LATERAL ");
                              12407                 :                : 
                              12408                 :                :         /* Print the FROM item proper */
 8621                         12409   [ +  +  +  +  :           2999 :         switch (rte->rtekind)
                                           +  +  - ]
                              12410                 :                :         {
                              12411                 :           2277 :             case RTE_RELATION:
                              12412                 :                :                 /* Normal relation RTE */
                              12413                 :           4554 :                 appendStringInfo(buf, "%s%s",
                              12414         [ +  + ]:           2277 :                                  only_marker(rte),
                              12415                 :                :                                  generate_relation_name(rte->relid,
                              12416                 :                :                                                         context->namespaces));
                              12417                 :           2277 :                 break;
                              12418                 :            146 :             case RTE_SUBQUERY:
                              12419                 :                :                 /* Subquery RTE */
                              12420                 :            146 :                 appendStringInfoChar(buf, '(');
 8121 bruce@momjian.us        12421                 :            146 :                 get_query_def(rte->subquery, buf, context->namespaces, NULL,
                              12422                 :                :                               true,
                              12423                 :                :                               context->prettyFlags, context->wrapColumn,
                              12424                 :                :                               context->indentLevel);
 8621 tgl@sss.pgh.pa.us       12425                 :            146 :                 appendStringInfoChar(buf, ')');
                              12426                 :            146 :                 break;
 8570                         12427                 :            429 :             case RTE_FUNCTION:
                              12428                 :                :                 /* Function RTE */
 4359                         12429                 :            429 :                 rtfunc1 = (RangeTblFunction *) linitial(rte->functions);
                              12430                 :                : 
                              12431                 :                :                 /*
                              12432                 :                :                  * Omit ROWS FROM() syntax for just one function, unless it
                              12433                 :                :                  * has both a coldeflist and WITH ORDINALITY. If it has both,
                              12434                 :                :                  * we must use ROWS FROM() syntax to avoid ambiguity about
                              12435                 :                :                  * whether the coldeflist includes the ordinality column.
                              12436                 :                :                  */
                              12437         [ +  + ]:            429 :                 if (list_length(rte->functions) == 1 &&
                              12438   [ -  +  -  - ]:            414 :                     (rtfunc1->funccolnames == NIL || !rte->funcordinality))
                              12439                 :                :                 {
 3029                         12440                 :            414 :                     get_rule_expr_funccall(rtfunc1->funcexpr, context, true);
                              12441                 :                :                     /* we'll print the coldeflist below, if it has one */
                              12442                 :                :                 }
                              12443                 :                :                 else
                              12444                 :                :                 {
                              12445                 :                :                     bool        all_unnest;
                              12446                 :                :                     ListCell   *lc;
                              12447                 :                : 
                              12448                 :                :                     /*
                              12449                 :                :                      * If all the function calls in the list are to unnest,
                              12450                 :                :                      * and none need a coldeflist, then collapse the list back
                              12451                 :                :                      * down to UNNEST(args).  (If we had more than one
                              12452                 :                :                      * built-in unnest function, this would get more
                              12453                 :                :                      * difficult.)
                              12454                 :                :                      *
                              12455                 :                :                      * XXX This is pretty ugly, since it makes not-terribly-
                              12456                 :                :                      * future-proof assumptions about what the parser would do
                              12457                 :                :                      * with the output; but the alternative is to emit our
                              12458                 :                :                      * nonstandard ROWS FROM() notation for what might have
                              12459                 :                :                      * been a perfectly spec-compliant multi-argument
                              12460                 :                :                      * UNNEST().
                              12461                 :                :                      */
 4359                         12462                 :             15 :                     all_unnest = true;
                              12463   [ +  -  +  +  :             39 :                     foreach(lc, rte->functions)
                                              +  + ]
                              12464                 :                :                     {
                              12465                 :             33 :                         RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
                              12466                 :                : 
                              12467         [ +  - ]:             33 :                         if (!IsA(rtfunc->funcexpr, FuncExpr) ||
 1821                         12468         [ +  + ]:             33 :                             ((FuncExpr *) rtfunc->funcexpr)->funcid != F_UNNEST_ANYARRAY ||
 4359                         12469         [ -  + ]:             24 :                             rtfunc->funccolnames != NIL)
                              12470                 :                :                         {
                              12471                 :              9 :                             all_unnest = false;
                              12472                 :              9 :                             break;
                              12473                 :                :                         }
                              12474                 :                :                     }
                              12475                 :                : 
                              12476         [ +  + ]:             15 :                     if (all_unnest)
                              12477                 :                :                     {
                              12478                 :              6 :                         List       *allargs = NIL;
                              12479                 :                : 
                              12480   [ +  -  +  +  :             24 :                         foreach(lc, rte->functions)
                                              +  + ]
                              12481                 :                :                         {
                              12482                 :             18 :                             RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
                              12483                 :             18 :                             List       *args = ((FuncExpr *) rtfunc->funcexpr)->args;
                              12484                 :                : 
 2269                         12485                 :             18 :                             allargs = list_concat(allargs, args);
                              12486                 :                :                         }
                              12487                 :                : 
 4359                         12488                 :              6 :                         appendStringInfoString(buf, "UNNEST(");
                              12489                 :              6 :                         get_rule_expr((Node *) allargs, context, true);
                              12490                 :              6 :                         appendStringInfoChar(buf, ')');
                              12491                 :                :                     }
                              12492                 :                :                     else
                              12493                 :                :                     {
                              12494                 :              9 :                         int         funcno = 0;
                              12495                 :                : 
 4340 noah@leadboat.com       12496                 :              9 :                         appendStringInfoString(buf, "ROWS FROM(");
 4359 tgl@sss.pgh.pa.us       12497   [ +  -  +  +  :             33 :                         foreach(lc, rte->functions)
                                              +  + ]
                              12498                 :                :                         {
                              12499                 :             24 :                             RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
                              12500                 :                : 
                              12501         [ +  + ]:             24 :                             if (funcno > 0)
                              12502                 :             15 :                                 appendStringInfoString(buf, ", ");
 3029                         12503                 :             24 :                             get_rule_expr_funccall(rtfunc->funcexpr, context, true);
 4359                         12504         [ +  + ]:             24 :                             if (rtfunc->funccolnames != NIL)
                              12505                 :                :                             {
                              12506                 :                :                                 /* Reconstruct the column definition list */
                              12507                 :              3 :                                 appendStringInfoString(buf, " AS ");
                              12508                 :              3 :                                 get_from_clause_coldeflist(rtfunc,
                              12509                 :                :                                                            NULL,
                              12510                 :                :                                                            context);
                              12511                 :                :                             }
                              12512                 :             24 :                             funcno++;
                              12513                 :                :                         }
                              12514                 :              9 :                         appendStringInfoChar(buf, ')');
                              12515                 :                :                     }
                              12516                 :                :                     /* prevent printing duplicate coldeflist below */
                              12517                 :             15 :                     rtfunc1 = NULL;
                              12518                 :                :                 }
 4474 stark@mit.edu           12519         [ +  + ]:            429 :                 if (rte->funcordinality)
                              12520                 :              9 :                     appendStringInfoString(buf, " WITH ORDINALITY");
 8570 tgl@sss.pgh.pa.us       12521                 :            429 :                 break;
 3156 alvherre@alvh.no-ip.    12522                 :             49 :             case RTE_TABLEFUNC:
                              12523                 :             49 :                 get_tablefunc(rte->tablefunc, context, true);
                              12524                 :             49 :                 break;
 7027 mail@joeconway.com      12525                 :              6 :             case RTE_VALUES:
                              12526                 :                :                 /* Values list RTE */
 3898 tgl@sss.pgh.pa.us       12527                 :              6 :                 appendStringInfoChar(buf, '(');
 7027 mail@joeconway.com      12528                 :              6 :                 get_values_def(rte->values_lists, context);
 3898 tgl@sss.pgh.pa.us       12529                 :              6 :                 appendStringInfoChar(buf, ')');
 7027 mail@joeconway.com      12530                 :              6 :                 break;
 6233 tgl@sss.pgh.pa.us       12531                 :             92 :             case RTE_CTE:
                              12532                 :             92 :                 appendStringInfoString(buf, quote_identifier(rte->ctename));
                              12533                 :             92 :                 break;
 8621 tgl@sss.pgh.pa.us       12534                 :UBC           0 :             default:
 8129                         12535         [ #  # ]:              0 :                 elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
                              12536                 :                :                 break;
                              12537                 :                :         }
                              12538                 :                : 
                              12539                 :                :         /* Print the relation alias, if needed */
  984 tgl@sss.pgh.pa.us       12540                 :CBC        2999 :         get_rte_alias(rte, varno, false, context);
                              12541                 :                : 
                              12542                 :                :         /* Print the column definitions or aliases, if needed */
 4359                         12543   [ +  +  -  + ]:           2999 :         if (rtfunc1 && rtfunc1->funccolnames != NIL)
                              12544                 :                :         {
                              12545                 :                :             /* Reconstruct the columndef list, which is also the aliases */
 4359 tgl@sss.pgh.pa.us       12546                 :UBC           0 :             get_from_clause_coldeflist(rtfunc1, colinfo, context);
                              12547                 :                :         }
                              12548                 :                :         else
                              12549                 :                :         {
                              12550                 :                :             /* Else print column aliases as needed */
 4684 tgl@sss.pgh.pa.us       12551                 :CBC        2999 :             get_column_alias_list(colinfo, context);
                              12552                 :                :         }
                              12553                 :                : 
                              12554                 :                :         /* Tablesample clause must go after any alias */
 3748                         12555   [ +  +  +  + ]:           2999 :         if (rte->rtekind == RTE_RELATION && rte->tablesample)
                              12556                 :             16 :             get_tablesample_def(rte->tablesample, context);
                              12557                 :                :     }
 9177                         12558         [ +  - ]:            761 :     else if (IsA(jtnode, JoinExpr))
                              12559                 :                :     {
                              12560                 :            761 :         JoinExpr   *j = (JoinExpr *) jtnode;
 4684                         12561                 :            761 :         deparse_columns *colinfo = deparse_columns_fetch(j->rtindex, dpns);
                              12562                 :                :         bool        need_paren_on_right;
                              12563                 :                : 
 8126                         12564                 :           1747 :         need_paren_on_right = PRETTY_PAREN(context) &&
 7429                         12565   [ +  +  -  + ]:            761 :             !IsA(j->rarg, RangeTblRef) &&
 1991 tgl@sss.pgh.pa.us       12566   [ #  #  #  # ]:UBC           0 :             !(IsA(j->rarg, JoinExpr) && ((JoinExpr *) j->rarg)->alias != NULL);
                              12567                 :                : 
 8126 tgl@sss.pgh.pa.us       12568   [ +  +  +  + ]:CBC         761 :         if (!PRETTY_PAREN(context) || j->alias != NULL)
 8121 bruce@momjian.us        12569                 :            590 :             appendStringInfoChar(buf, '(');
                              12570                 :                : 
 9177 tgl@sss.pgh.pa.us       12571                 :            761 :         get_from_clause_item(j->larg, query, context);
                              12572                 :                : 
 4684                         12573   [ +  +  +  -  :            761 :         switch (j->jointype)
                                                 - ]
                              12574                 :                :         {
                              12575                 :            418 :             case JOIN_INNER:
                              12576         [ +  + ]:            418 :                 if (j->quals)
                              12577                 :            397 :                     appendContextKeyword(context, " JOIN ",
                              12578                 :                :                                          -PRETTYINDENT_STD,
                              12579                 :                :                                          PRETTYINDENT_STD,
                              12580                 :                :                                          PRETTYINDENT_JOIN);
                              12581                 :                :                 else
                              12582                 :             21 :                     appendContextKeyword(context, " CROSS JOIN ",
                              12583                 :                :                                          -PRETTYINDENT_STD,
                              12584                 :                :                                          PRETTYINDENT_STD,
                              12585                 :                :                                          PRETTYINDENT_JOIN);
                              12586                 :            418 :                 break;
                              12587                 :            292 :             case JOIN_LEFT:
                              12588                 :            292 :                 appendContextKeyword(context, " LEFT JOIN ",
                              12589                 :                :                                      -PRETTYINDENT_STD,
                              12590                 :                :                                      PRETTYINDENT_STD,
                              12591                 :                :                                      PRETTYINDENT_JOIN);
                              12592                 :            292 :                 break;
                              12593                 :             51 :             case JOIN_FULL:
                              12594                 :             51 :                 appendContextKeyword(context, " FULL JOIN ",
                              12595                 :                :                                      -PRETTYINDENT_STD,
                              12596                 :                :                                      PRETTYINDENT_STD,
                              12597                 :                :                                      PRETTYINDENT_JOIN);
                              12598                 :             51 :                 break;
 4684 tgl@sss.pgh.pa.us       12599                 :UBC           0 :             case JOIN_RIGHT:
                              12600                 :              0 :                 appendContextKeyword(context, " RIGHT JOIN ",
                              12601                 :                :                                      -PRETTYINDENT_STD,
                              12602                 :                :                                      PRETTYINDENT_STD,
                              12603                 :                :                                      PRETTYINDENT_JOIN);
                              12604                 :              0 :                 break;
                              12605                 :              0 :             default:
                              12606         [ #  # ]:              0 :                 elog(ERROR, "unrecognized join type: %d",
                              12607                 :                :                      (int) j->jointype);
                              12608                 :                :         }
                              12609                 :                : 
 8126 tgl@sss.pgh.pa.us       12610         [ -  + ]:CBC         761 :         if (need_paren_on_right)
 8121 bruce@momjian.us        12611                 :UBC           0 :             appendStringInfoChar(buf, '(');
 9177 tgl@sss.pgh.pa.us       12612                 :CBC         761 :         get_from_clause_item(j->rarg, query, context);
 8126                         12613         [ -  + ]:            761 :         if (need_paren_on_right)
 8121 bruce@momjian.us        12614                 :UBC           0 :             appendStringInfoChar(buf, ')');
                              12615                 :                : 
 4684 tgl@sss.pgh.pa.us       12616         [ +  + ]:CBC         761 :         if (j->usingClause)
                              12617                 :                :         {
                              12618                 :                :             ListCell   *lc;
                              12619                 :            212 :             bool        first = true;
                              12620                 :                : 
 4380 rhaas@postgresql.org    12621                 :            212 :             appendStringInfoString(buf, " USING (");
                              12622                 :                :             /* Use the assigned names, not what's in usingClause */
 4684 tgl@sss.pgh.pa.us       12623   [ +  -  +  +  :            502 :             foreach(lc, colinfo->usingNames)
                                              +  + ]
                              12624                 :                :             {
                              12625                 :            290 :                 char       *colname = (char *) lfirst(lc);
                              12626                 :                : 
                              12627         [ +  + ]:            290 :                 if (first)
                              12628                 :            212 :                     first = false;
                              12629                 :                :                 else
 4380 rhaas@postgresql.org    12630                 :             78 :                     appendStringInfoString(buf, ", ");
 4684 tgl@sss.pgh.pa.us       12631                 :            290 :                 appendStringInfoString(buf, quote_identifier(colname));
                              12632                 :                :             }
                              12633                 :            212 :             appendStringInfoChar(buf, ')');
                              12634                 :                : 
 1672 peter@eisentraut.org    12635         [ +  + ]:            212 :             if (j->join_using_alias)
                              12636                 :              6 :                 appendStringInfo(buf, " AS %s",
                              12637                 :              6 :                                  quote_identifier(j->join_using_alias->aliasname));
                              12638                 :                :         }
 4684 tgl@sss.pgh.pa.us       12639         [ +  + ]:            549 :         else if (j->quals)
                              12640                 :                :         {
 4380 rhaas@postgresql.org    12641                 :            525 :             appendStringInfoString(buf, " ON ");
 4684 tgl@sss.pgh.pa.us       12642         [ +  + ]:            525 :             if (!PRETTY_PAREN(context))
                              12643                 :            516 :                 appendStringInfoChar(buf, '(');
                              12644                 :            525 :             get_rule_expr(j->quals, context, false);
                              12645         [ +  + ]:            525 :             if (!PRETTY_PAREN(context))
                              12646                 :            516 :                 appendStringInfoChar(buf, ')');
                              12647                 :                :         }
 3022                         12648         [ +  + ]:             24 :         else if (j->jointype != JOIN_INNER)
                              12649                 :                :         {
                              12650                 :                :             /* If we didn't say CROSS JOIN above, we must provide an ON */
                              12651                 :              3 :             appendStringInfoString(buf, " ON TRUE");
                              12652                 :                :         }
                              12653                 :                : 
 8126                         12654   [ +  +  +  + ]:            761 :         if (!PRETTY_PAREN(context) || j->alias != NULL)
 8121 bruce@momjian.us        12655                 :            590 :             appendStringInfoChar(buf, ')');
                              12656                 :                : 
                              12657                 :                :         /* Yes, it's correct to put alias after the right paren ... */
 9177 tgl@sss.pgh.pa.us       12658         [ +  + ]:            761 :         if (j->alias != NULL)
                              12659                 :                :         {
                              12660                 :                :             /*
                              12661                 :                :              * Note that it's correct to emit an alias clause if and only if
                              12662                 :                :              * there was one originally.  Otherwise we'd be converting a named
                              12663                 :                :              * join to unnamed or vice versa, which creates semantic
                              12664                 :                :              * subtleties we don't want.  However, we might print a different
                              12665                 :                :              * alias name than was there originally.
                              12666                 :                :              */
                              12667                 :             54 :             appendStringInfo(buf, " %s",
 2330                         12668                 :             54 :                              quote_identifier(get_rtable_name(j->rtindex,
                              12669                 :                :                                                               context)));
 4684                         12670                 :             54 :             get_column_alias_list(colinfo, context);
                              12671                 :                :         }
                              12672                 :                :     }
                              12673                 :                :     else
 8129 tgl@sss.pgh.pa.us       12674         [ #  # ]:UBC           0 :         elog(ERROR, "unrecognized node type: %d",
                              12675                 :                :              (int) nodeTag(jtnode));
 9177 tgl@sss.pgh.pa.us       12676                 :CBC        3760 : }
                              12677                 :                : 
                              12678                 :                : /*
                              12679                 :                :  * get_rte_alias - print the relation's alias, if needed
                              12680                 :                :  *
                              12681                 :                :  * If printed, the alias is preceded by a space, or by " AS " if use_as is true.
                              12682                 :                :  */
                              12683                 :                : static void
  984                         12684                 :           3290 : get_rte_alias(RangeTblEntry *rte, int varno, bool use_as,
                              12685                 :                :               deparse_context *context)
                              12686                 :                : {
                              12687                 :           3290 :     deparse_namespace *dpns = (deparse_namespace *) linitial(context->namespaces);
                              12688                 :           3290 :     char       *refname = get_rtable_name(varno, context);
                              12689                 :           3290 :     deparse_columns *colinfo = deparse_columns_fetch(varno, dpns);
                              12690                 :           3290 :     bool        printalias = false;
                              12691                 :                : 
                              12692         [ +  + ]:           3290 :     if (rte->alias != NULL)
                              12693                 :                :     {
                              12694                 :                :         /* Always print alias if user provided one */
                              12695                 :           1548 :         printalias = true;
                              12696                 :                :     }
                              12697         [ +  + ]:           1742 :     else if (colinfo->printaliases)
                              12698                 :                :     {
                              12699                 :                :         /* Always print alias if we need to print column aliases */
                              12700                 :            165 :         printalias = true;
                              12701                 :                :     }
                              12702         [ +  + ]:           1577 :     else if (rte->rtekind == RTE_RELATION)
                              12703                 :                :     {
                              12704                 :                :         /*
                              12705                 :                :          * No need to print alias if it's same as relation name (this would
                              12706                 :                :          * normally be the case, but not if set_rtable_names had to resolve a
                              12707                 :                :          * conflict).
                              12708                 :                :          */
                              12709         [ +  + ]:           1441 :         if (strcmp(refname, get_relation_name(rte->relid)) != 0)
                              12710                 :             40 :             printalias = true;
                              12711                 :                :     }
                              12712         [ -  + ]:            136 :     else if (rte->rtekind == RTE_FUNCTION)
                              12713                 :                :     {
                              12714                 :                :         /*
                              12715                 :                :          * For a function RTE, always print alias.  This covers possible
                              12716                 :                :          * renaming of the function and/or instability of the FigureColname
                              12717                 :                :          * rules for things that aren't simple functions.  Note we'd need to
                              12718                 :                :          * force it anyway for the columndef list case.
                              12719                 :                :          */
  984 tgl@sss.pgh.pa.us       12720                 :UBC           0 :         printalias = true;
                              12721                 :                :     }
  984 tgl@sss.pgh.pa.us       12722         [ +  + ]:CBC         136 :     else if (rte->rtekind == RTE_SUBQUERY ||
                              12723         [ +  + ]:            124 :              rte->rtekind == RTE_VALUES)
                              12724                 :                :     {
                              12725                 :                :         /*
                              12726                 :                :          * For a subquery, always print alias.  This makes the output
                              12727                 :                :          * SQL-spec-compliant, even though we allow such aliases to be omitted
                              12728                 :                :          * on input.
                              12729                 :                :          */
                              12730                 :             18 :         printalias = true;
                              12731                 :                :     }
                              12732         [ +  + ]:            118 :     else if (rte->rtekind == RTE_CTE)
                              12733                 :                :     {
                              12734                 :                :         /*
                              12735                 :                :          * No need to print alias if it's same as CTE name (this would
                              12736                 :                :          * normally be the case, but not if set_rtable_names had to resolve a
                              12737                 :                :          * conflict).
                              12738                 :                :          */
                              12739         [ +  + ]:             72 :         if (strcmp(refname, rte->ctename) != 0)
                              12740                 :             11 :             printalias = true;
                              12741                 :                :     }
                              12742                 :                : 
                              12743         [ +  + ]:           3290 :     if (printalias)
                              12744         [ +  + ]:           1782 :         appendStringInfo(context->buf, "%s%s",
                              12745                 :                :                          use_as ? " AS " : " ",
                              12746                 :                :                          quote_identifier(refname));
                              12747                 :           3290 : }
                              12748                 :                : 
                              12749                 :                : /*
                              12750                 :                :  * get_column_alias_list - print column alias list for an RTE
                              12751                 :                :  *
                              12752                 :                :  * Caller must already have printed the relation's alias name.
                              12753                 :                :  */
                              12754                 :                : static void
 4684                         12755                 :           3053 : get_column_alias_list(deparse_columns *colinfo, deparse_context *context)
                              12756                 :                : {
 7740                         12757                 :           3053 :     StringInfo  buf = context->buf;
                              12758                 :                :     int         i;
                              12759                 :           3053 :     bool        first = true;
                              12760                 :                : 
                              12761                 :                :     /* Don't print aliases if not needed */
 4684                         12762         [ +  + ]:           3053 :     if (!colinfo->printaliases)
                              12763                 :           2444 :         return;
                              12764                 :                : 
                              12765         [ +  + ]:           4866 :     for (i = 0; i < colinfo->num_new_cols; i++)
                              12766                 :                :     {
                              12767                 :           4257 :         char       *colname = colinfo->new_colnames[i];
                              12768                 :                : 
 7740                         12769         [ +  + ]:           4257 :         if (first)
                              12770                 :                :         {
                              12771                 :            609 :             appendStringInfoChar(buf, '(');
                              12772                 :            609 :             first = false;
                              12773                 :                :         }
                              12774                 :                :         else
 4380 rhaas@postgresql.org    12775                 :           3648 :             appendStringInfoString(buf, ", ");
 4684 tgl@sss.pgh.pa.us       12776                 :           4257 :         appendStringInfoString(buf, quote_identifier(colname));
                              12777                 :                :     }
 7740                         12778         [ +  - ]:            609 :     if (!first)
                              12779                 :            609 :         appendStringInfoChar(buf, ')');
                              12780                 :                : }
                              12781                 :                : 
                              12782                 :                : /*
                              12783                 :                :  * get_from_clause_coldeflist - reproduce FROM clause coldeflist
                              12784                 :                :  *
                              12785                 :                :  * When printing a top-level coldeflist (which is syntactically also the
                              12786                 :                :  * relation's column alias list), use column names from colinfo.  But when
                              12787                 :                :  * printing a coldeflist embedded inside ROWS FROM(), we prefer to use the
                              12788                 :                :  * original coldeflist's names, which are available in rtfunc->funccolnames.
                              12789                 :                :  * Pass NULL for colinfo to select the latter behavior.
                              12790                 :                :  *
                              12791                 :                :  * The coldeflist is appended immediately (no space) to buf.  Caller is
                              12792                 :                :  * responsible for ensuring that an alias or AS is present before it.
                              12793                 :                :  */
                              12794                 :                : static void
 4359                         12795                 :              3 : get_from_clause_coldeflist(RangeTblFunction *rtfunc,
                              12796                 :                :                            deparse_columns *colinfo,
                              12797                 :                :                            deparse_context *context)
                              12798                 :                : {
 8461                         12799                 :              3 :     StringInfo  buf = context->buf;
                              12800                 :                :     ListCell   *l1;
                              12801                 :                :     ListCell   *l2;
                              12802                 :                :     ListCell   *l3;
                              12803                 :                :     ListCell   *l4;
                              12804                 :                :     int         i;
                              12805                 :                : 
                              12806                 :              3 :     appendStringInfoChar(buf, '(');
                              12807                 :                : 
 4684                         12808                 :              3 :     i = 0;
 2434                         12809   [ +  -  +  +  :             12 :     forfour(l1, rtfunc->funccoltypes,
                                     +  -  +  +  +  
                                     -  +  +  +  -  
                                     +  +  +  +  +  
                                     -  +  -  +  -  
                                              +  + ]
                              12810                 :                :             l2, rtfunc->funccoltypmods,
                              12811                 :                :             l3, rtfunc->funccolcollations,
                              12812                 :                :             l4, rtfunc->funccolnames)
                              12813                 :                :     {
 4684                         12814                 :              9 :         Oid         atttypid = lfirst_oid(l1);
                              12815                 :              9 :         int32       atttypmod = lfirst_int(l2);
                              12816                 :              9 :         Oid         attcollation = lfirst_oid(l3);
                              12817                 :                :         char       *attname;
                              12818                 :                : 
 4359                         12819         [ -  + ]:              9 :         if (colinfo)
 4359 tgl@sss.pgh.pa.us       12820                 :UBC           0 :             attname = colinfo->colnames[i];
                              12821                 :                :         else
 4359 tgl@sss.pgh.pa.us       12822                 :CBC           9 :             attname = strVal(lfirst(l4));
                              12823                 :                : 
 4684                         12824         [ -  + ]:              9 :         Assert(attname);        /* shouldn't be any dropped columns here */
                              12825                 :                : 
 8461                         12826         [ +  + ]:              9 :         if (i > 0)
 4380 rhaas@postgresql.org    12827                 :              6 :             appendStringInfoString(buf, ", ");
 8461 tgl@sss.pgh.pa.us       12828                 :              9 :         appendStringInfo(buf, "%s %s",
                              12829                 :                :                          quote_identifier(attname),
                              12830                 :                :                          format_type_with_typemod(atttypid, atttypmod));
 5303                         12831   [ +  +  -  + ]:             12 :         if (OidIsValid(attcollation) &&
                              12832                 :              3 :             attcollation != get_typcollation(atttypid))
 5332 tgl@sss.pgh.pa.us       12833                 :UBC           0 :             appendStringInfo(buf, " COLLATE %s",
                              12834                 :                :                              generate_collation_name(attcollation));
                              12835                 :                : 
 8461 tgl@sss.pgh.pa.us       12836                 :CBC           9 :         i++;
                              12837                 :                :     }
                              12838                 :                : 
                              12839                 :              3 :     appendStringInfoChar(buf, ')');
                              12840                 :              3 : }
                              12841                 :                : 
                              12842                 :                : /*
                              12843                 :                :  * get_tablesample_def          - print a TableSampleClause
                              12844                 :                :  */
                              12845                 :                : static void
 3748                         12846                 :             16 : get_tablesample_def(TableSampleClause *tablesample, deparse_context *context)
                              12847                 :                : {
                              12848                 :             16 :     StringInfo  buf = context->buf;
                              12849                 :                :     Oid         argtypes[1];
                              12850                 :                :     int         nargs;
                              12851                 :                :     ListCell   *l;
                              12852                 :                : 
                              12853                 :                :     /*
                              12854                 :                :      * We should qualify the handler's function name if it wouldn't be
                              12855                 :                :      * resolved by lookup in the current search path.
                              12856                 :                :      */
                              12857                 :             16 :     argtypes[0] = INTERNALOID;
                              12858                 :             16 :     appendStringInfo(buf, " TABLESAMPLE %s (",
                              12859                 :                :                      generate_function_name(tablesample->tsmhandler, 1,
                              12860                 :                :                                             NIL, argtypes,
                              12861                 :                :                                             false, NULL, false));
                              12862                 :                : 
                              12863                 :             16 :     nargs = 0;
                              12864   [ +  -  +  +  :             32 :     foreach(l, tablesample->args)
                                              +  + ]
                              12865                 :                :     {
                              12866         [ -  + ]:             16 :         if (nargs++ > 0)
 3748 tgl@sss.pgh.pa.us       12867                 :UBC           0 :             appendStringInfoString(buf, ", ");
 3748 tgl@sss.pgh.pa.us       12868                 :CBC          16 :         get_rule_expr((Node *) lfirst(l), context, false);
                              12869                 :                :     }
                              12870                 :             16 :     appendStringInfoChar(buf, ')');
                              12871                 :                : 
                              12872         [ +  + ]:             16 :     if (tablesample->repeatable != NULL)
                              12873                 :                :     {
                              12874                 :              8 :         appendStringInfoString(buf, " REPEATABLE (");
                              12875                 :              8 :         get_rule_expr((Node *) tablesample->repeatable, context, false);
                              12876                 :              8 :         appendStringInfoChar(buf, ')');
                              12877                 :                :     }
                              12878                 :             16 : }
                              12879                 :                : 
                              12880                 :                : /*
                              12881                 :                :  * get_opclass_name         - fetch name of an index operator class
                              12882                 :                :  *
                              12883                 :                :  * The opclass name is appended (after a space) to buf.
                              12884                 :                :  *
                              12885                 :                :  * Output is suppressed if the opclass is the default for the given
                              12886                 :                :  * actual_datatype.  (If you don't want this behavior, just pass
                              12887                 :                :  * InvalidOid for actual_datatype.)
                              12888                 :                :  */
                              12889                 :                : static void
 8790                         12890                 :           6309 : get_opclass_name(Oid opclass, Oid actual_datatype,
                              12891                 :                :                  StringInfo buf)
                              12892                 :                : {
                              12893                 :                :     HeapTuple   ht_opc;
                              12894                 :                :     Form_pg_opclass opcrec;
                              12895                 :                :     char       *opcname;
                              12896                 :                :     char       *nspname;
                              12897                 :                : 
 5735 rhaas@postgresql.org    12898                 :           6309 :     ht_opc = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
 8793 tgl@sss.pgh.pa.us       12899         [ -  + ]:           6309 :     if (!HeapTupleIsValid(ht_opc))
 8793 tgl@sss.pgh.pa.us       12900         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for opclass %u", opclass);
 8793 tgl@sss.pgh.pa.us       12901                 :CBC        6309 :     opcrec = (Form_pg_opclass) GETSTRUCT(ht_opc);
                              12902                 :                : 
 6884                         12903   [ +  +  +  + ]:          12598 :     if (!OidIsValid(actual_datatype) ||
                              12904                 :           6289 :         GetDefaultOpClass(actual_datatype, opcrec->opcmethod) != opclass)
                              12905                 :                :     {
                              12906                 :                :         /* Okay, we need the opclass name.  Do we need to qualify it? */
 8579                         12907                 :            279 :         opcname = NameStr(opcrec->opcname);
 6884                         12908         [ +  - ]:            279 :         if (OpclassIsVisible(opclass))
 8579                         12909                 :            279 :             appendStringInfo(buf, " %s", quote_identifier(opcname));
                              12910                 :                :         else
                              12911                 :                :         {
 1554 tgl@sss.pgh.pa.us       12912                 :UBC           0 :             nspname = get_namespace_name_or_temp(opcrec->opcnamespace);
 8579                         12913                 :              0 :             appendStringInfo(buf, " %s.%s",
                              12914                 :                :                              quote_identifier(nspname),
                              12915                 :                :                              quote_identifier(opcname));
                              12916                 :                :         }
                              12917                 :                :     }
 8793 tgl@sss.pgh.pa.us       12918                 :CBC        6309 :     ReleaseSysCache(ht_opc);
                              12919                 :           6309 : }
                              12920                 :                : 
                              12921                 :                : /*
                              12922                 :                :  * generate_opclass_name
                              12923                 :                :  *      Compute the name to display for an opclass specified by OID
                              12924                 :                :  *
                              12925                 :                :  * The result includes all necessary quoting and schema-prefixing.
                              12926                 :                :  */
                              12927                 :                : char *
 2038 akorotkov@postgresql    12928                 :              3 : generate_opclass_name(Oid opclass)
                              12929                 :                : {
                              12930                 :                :     StringInfoData buf;
                              12931                 :                : 
                              12932                 :              3 :     initStringInfo(&buf);
                              12933                 :              3 :     get_opclass_name(opclass, InvalidOid, &buf);
                              12934                 :                : 
 1993 tgl@sss.pgh.pa.us       12935                 :              3 :     return &buf.data[1];        /* get_opclass_name() prepends space */
                              12936                 :                : }
                              12937                 :                : 
                              12938                 :                : /*
                              12939                 :                :  * processIndirection - take care of array and subfield assignment
                              12940                 :                :  *
                              12941                 :                :  * We strip any top-level FieldStore or assignment SubscriptingRef nodes that
                              12942                 :                :  * appear in the input, printing them as decoration for the base column
                              12943                 :                :  * name (which we assume the caller just printed).  We might also need to
                              12944                 :                :  * strip CoerceToDomain nodes, but only ones that appear above assignment
                              12945                 :                :  * nodes.
                              12946                 :                :  *
                              12947                 :                :  * Returns the subexpression that's to be assigned.
                              12948                 :                :  */
                              12949                 :                : static Node *
 3373                         12950                 :            636 : processIndirection(Node *node, deparse_context *context)
                              12951                 :                : {
 7811                         12952                 :            636 :     StringInfo  buf = context->buf;
 3030                         12953                 :            636 :     CoerceToDomain *cdomain = NULL;
                              12954                 :                : 
                              12955                 :                :     for (;;)
                              12956                 :                :     {
 7811                         12957         [ -  + ]:            789 :         if (node == NULL)
 7811 tgl@sss.pgh.pa.us       12958                 :UBC           0 :             break;
 7811 tgl@sss.pgh.pa.us       12959         [ +  + ]:CBC         789 :         if (IsA(node, FieldStore))
                              12960                 :                :         {
                              12961                 :             54 :             FieldStore *fstore = (FieldStore *) node;
                              12962                 :                :             Oid         typrelid;
                              12963                 :                :             char       *fieldname;
                              12964                 :                : 
                              12965                 :                :             /* lookup tuple type */
                              12966                 :             54 :             typrelid = get_typ_typrelid(fstore->resulttype);
                              12967         [ -  + ]:             54 :             if (!OidIsValid(typrelid))
 7811 tgl@sss.pgh.pa.us       12968         [ #  # ]:UBC           0 :                 elog(ERROR, "argument type %s of FieldStore is not a tuple type",
                              12969                 :                :                      format_type_be(fstore->resulttype));
                              12970                 :                : 
                              12971                 :                :             /*
                              12972                 :                :              * Print the field name.  There should only be one target field in
                              12973                 :                :              * stored rules.  There could be more than that in executable
                              12974                 :                :              * target lists, but this function cannot be used for that case.
                              12975                 :                :              */
 5731 tgl@sss.pgh.pa.us       12976         [ -  + ]:CBC          54 :             Assert(list_length(fstore->fieldnums) == 1);
 2815 alvherre@alvh.no-ip.    12977                 :             54 :             fieldname = get_attname(typrelid,
                              12978                 :             54 :                                     linitial_int(fstore->fieldnums), false);
 3373 tgl@sss.pgh.pa.us       12979                 :             54 :             appendStringInfo(buf, ".%s", quote_identifier(fieldname));
                              12980                 :                : 
                              12981                 :                :             /*
                              12982                 :                :              * We ignore arg since it should be an uninteresting reference to
                              12983                 :                :              * the target column or subcolumn.
                              12984                 :                :              */
 7811                         12985                 :             54 :             node = (Node *) linitial(fstore->newvals);
                              12986                 :                :         }
 2461 alvherre@alvh.no-ip.    12987         [ +  + ]:            735 :         else if (IsA(node, SubscriptingRef))
                              12988                 :                :         {
                              12989                 :             69 :             SubscriptingRef *sbsref = (SubscriptingRef *) node;
                              12990                 :                : 
                              12991         [ -  + ]:             69 :             if (sbsref->refassgnexpr == NULL)
 7811 tgl@sss.pgh.pa.us       12992                 :UBC           0 :                 break;
                              12993                 :                : 
 2461 alvherre@alvh.no-ip.    12994                 :CBC          69 :             printSubscripts(sbsref, context);
                              12995                 :                : 
                              12996                 :                :             /*
                              12997                 :                :              * We ignore refexpr since it should be an uninteresting reference
                              12998                 :                :              * to the target column or subcolumn.
                              12999                 :                :              */
                              13000                 :             69 :             node = (Node *) sbsref->refassgnexpr;
                              13001                 :                :         }
 3030 tgl@sss.pgh.pa.us       13002         [ +  + ]:            666 :         else if (IsA(node, CoerceToDomain))
                              13003                 :                :         {
                              13004                 :             30 :             cdomain = (CoerceToDomain *) node;
                              13005                 :                :             /* If it's an explicit domain coercion, we're done */
                              13006         [ -  + ]:             30 :             if (cdomain->coercionformat != COERCE_IMPLICIT_CAST)
 3030 tgl@sss.pgh.pa.us       13007                 :UBC           0 :                 break;
                              13008                 :                :             /* Tentatively descend past the CoerceToDomain */
 3030 tgl@sss.pgh.pa.us       13009                 :CBC          30 :             node = (Node *) cdomain->arg;
                              13010                 :                :         }
                              13011                 :                :         else
 7811                         13012                 :            636 :             break;
                              13013                 :                :     }
                              13014                 :                : 
                              13015                 :                :     /*
                              13016                 :                :      * If we descended past a CoerceToDomain whose argument turned out not to
                              13017                 :                :      * be a FieldStore or array assignment, back up to the CoerceToDomain.
                              13018                 :                :      * (This is not enough to be fully correct if there are nested implicit
                              13019                 :                :      * CoerceToDomains, but such cases shouldn't ever occur.)
                              13020                 :                :      */
 3030                         13021   [ +  +  -  + ]:            636 :     if (cdomain && node == (Node *) cdomain->arg)
 3030 tgl@sss.pgh.pa.us       13022                 :UBC           0 :         node = (Node *) cdomain;
                              13023                 :                : 
 7811 tgl@sss.pgh.pa.us       13024                 :CBC         636 :     return node;
                              13025                 :                : }
                              13026                 :                : 
                              13027                 :                : static void
 2461 alvherre@alvh.no-ip.    13028                 :            227 : printSubscripts(SubscriptingRef *sbsref, deparse_context *context)
                              13029                 :                : {
 7811 tgl@sss.pgh.pa.us       13030                 :            227 :     StringInfo  buf = context->buf;
                              13031                 :                :     ListCell   *lowlist_item;
                              13032                 :                :     ListCell   *uplist_item;
                              13033                 :                : 
 2461 alvherre@alvh.no-ip.    13034                 :            227 :     lowlist_item = list_head(sbsref->reflowerindexpr);   /* could be NULL */
                              13035   [ +  -  +  +  :            454 :     foreach(uplist_item, sbsref->refupperindexpr)
                                              +  + ]
                              13036                 :                :     {
 7811 tgl@sss.pgh.pa.us       13037                 :            227 :         appendStringInfoChar(buf, '[');
                              13038         [ -  + ]:            227 :         if (lowlist_item)
                              13039                 :                :         {
                              13040                 :                :             /* If subexpression is NULL, get_rule_expr prints nothing */
 7811 tgl@sss.pgh.pa.us       13041                 :UBC           0 :             get_rule_expr((Node *) lfirst(lowlist_item), context, false);
                              13042                 :              0 :             appendStringInfoChar(buf, ':');
 2297                         13043                 :              0 :             lowlist_item = lnext(sbsref->reflowerindexpr, lowlist_item);
                              13044                 :                :         }
                              13045                 :                :         /* If subexpression is NULL, get_rule_expr prints nothing */
 7811 tgl@sss.pgh.pa.us       13046                 :CBC         227 :         get_rule_expr((Node *) lfirst(uplist_item), context, false);
                              13047                 :            227 :         appendStringInfoChar(buf, ']');
                              13048                 :                :     }
 9208                         13049                 :            227 : }
                              13050                 :                : 
                              13051                 :                : /*
                              13052                 :                :  * quote_identifier         - Quote an identifier only if needed
                              13053                 :                :  *
                              13054                 :                :  * When quotes are needed, we palloc the required space; slightly
                              13055                 :                :  * space-wasteful but well worth it for notational simplicity.
                              13056                 :                :  */
                              13057                 :                : const char *
 8587                         13058                 :        1269277 : quote_identifier(const char *ident)
                              13059                 :                : {
                              13060                 :                :     /*
                              13061                 :                :      * Can avoid quoting if ident starts with a lowercase letter or underscore
                              13062                 :                :      * and contains only lowercase letters, digits, and underscores, *and* is
                              13063                 :                :      * not any SQL keyword.  Otherwise, supply quotes.
                              13064                 :                :      */
 8565                         13065                 :        1269277 :     int         nquotes = 0;
                              13066                 :                :     bool        safe;
                              13067                 :                :     const char *ptr;
                              13068                 :                :     char       *result;
                              13069                 :                :     char       *optr;
                              13070                 :                : 
                              13071                 :                :     /*
                              13072                 :                :      * would like to use <ctype.h> macros here, but they might yield unwanted
                              13073                 :                :      * locale-specific results...
                              13074                 :                :      */
 8584                         13075   [ +  +  -  +  :        1269277 :     safe = ((ident[0] >= 'a' && ident[0] <= 'z') || ident[0] == '_');
                                              +  + ]
                              13076                 :                : 
 8565                         13077         [ +  + ]:       10940612 :     for (ptr = ident; *ptr; ptr++)
                              13078                 :                :     {
                              13079                 :        9671335 :         char        ch = *ptr;
                              13080                 :                : 
                              13081   [ +  +  +  -  :        9671335 :         if ((ch >= 'a' && ch <= 'z') ||
                                              +  + ]
                              13082   [ +  +  +  + ]:        1164443 :             (ch >= '0' && ch <= '9') ||
                              13083                 :                :             (ch == '_'))
                              13084                 :                :         {
                              13085                 :                :             /* okay */
                              13086                 :                :         }
                              13087                 :                :         else
                              13088                 :                :         {
                              13089                 :          31999 :             safe = false;
                              13090         [ +  + ]:          31999 :             if (ch == '"')
                              13091                 :             82 :                 nquotes++;
                              13092                 :                :         }
                              13093                 :                :     }
                              13094                 :                : 
 5577 rhaas@postgresql.org    13095         [ +  + ]:        1269277 :     if (quote_all_identifiers)
                              13096                 :           6549 :         safe = false;
                              13097                 :                : 
 9458 tgl@sss.pgh.pa.us       13098         [ +  + ]:        1269277 :     if (safe)
                              13099                 :                :     {
                              13100                 :                :         /*
                              13101                 :                :          * Check for keyword.  We quote keywords except for unreserved ones.
                              13102                 :                :          * (In some cases we could avoid quoting a col_name or type_func_name
                              13103                 :                :          * keyword, but it seems much harder than it's worth to tell that.)
                              13104                 :                :          *
                              13105                 :                :          * Note: ScanKeywordLookup() does case-insensitive comparison, but
                              13106                 :                :          * that's fine, since we already know we have all-lower-case.
                              13107                 :                :          */
 2487                         13108                 :        1249590 :         int         kwnum = ScanKeywordLookup(ident, &ScanKeywords);
                              13109                 :                : 
                              13110   [ +  +  +  + ]:        1249590 :         if (kwnum >= 0 && ScanKeywordCategories[kwnum] != UNRESERVED_KEYWORD)
 9458                         13111                 :           1751 :             safe = false;
                              13112                 :                :     }
                              13113                 :                : 
 9521                         13114         [ +  + ]:        1269277 :     if (safe)
                              13115                 :        1247839 :         return ident;           /* no change needed */
                              13116                 :                : 
 8565                         13117                 :          21438 :     result = (char *) palloc(strlen(ident) + nquotes + 2 + 1);
                              13118                 :                : 
                              13119                 :          21438 :     optr = result;
                              13120                 :          21438 :     *optr++ = '"';
                              13121         [ +  + ]:         126042 :     for (ptr = ident; *ptr; ptr++)
                              13122                 :                :     {
                              13123                 :         104604 :         char        ch = *ptr;
                              13124                 :                : 
                              13125         [ +  + ]:         104604 :         if (ch == '"')
                              13126                 :             82 :             *optr++ = '"';
                              13127                 :         104604 :         *optr++ = ch;
                              13128                 :                :     }
                              13129                 :          21438 :     *optr++ = '"';
                              13130                 :          21438 :     *optr = '\0';
                              13131                 :                : 
 9521                         13132                 :          21438 :     return result;
                              13133                 :                : }
                              13134                 :                : 
                              13135                 :                : /*
                              13136                 :                :  * quote_qualified_identifier   - Quote a possibly-qualified identifier
                              13137                 :                :  *
                              13138                 :                :  * Return a name of the form qualifier.ident, or just ident if qualifier
                              13139                 :                :  * is NULL, quoting each component if necessary.  The result is palloc'd.
                              13140                 :                :  */
                              13141                 :                : char *
 5948 peter_e@gmx.net         13142                 :         625962 : quote_qualified_identifier(const char *qualifier,
                              13143                 :                :                            const char *ident)
                              13144                 :                : {
                              13145                 :                :     StringInfoData buf;
                              13146                 :                : 
 8587 tgl@sss.pgh.pa.us       13147                 :         625962 :     initStringInfo(&buf);
 5948 peter_e@gmx.net         13148         [ +  + ]:         625962 :     if (qualifier)
                              13149                 :         220888 :         appendStringInfo(&buf, "%s.", quote_identifier(qualifier));
 7941 neilc@samurai.com       13150                 :         625962 :     appendStringInfoString(&buf, quote_identifier(ident));
 8587 tgl@sss.pgh.pa.us       13151                 :         625962 :     return buf.data;
                              13152                 :                : }
                              13153                 :                : 
                              13154                 :                : /*
                              13155                 :                :  * get_relation_name
                              13156                 :                :  *      Get the unqualified name of a relation specified by OID
                              13157                 :                :  *
                              13158                 :                :  * This differs from the underlying get_rel_name() function in that it will
                              13159                 :                :  * throw error instead of silently returning NULL if the OID is bad.
                              13160                 :                :  */
                              13161                 :                : static char *
 5474                         13162                 :           8150 : get_relation_name(Oid relid)
                              13163                 :                : {
                              13164                 :           8150 :     char       *relname = get_rel_name(relid);
                              13165                 :                : 
                              13166         [ -  + ]:           8150 :     if (!relname)
 5474 tgl@sss.pgh.pa.us       13167         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for relation %u", relid);
 5474 tgl@sss.pgh.pa.us       13168                 :CBC        8150 :     return relname;
                              13169                 :                : }
                              13170                 :                : 
                              13171                 :                : /*
                              13172                 :                :  * generate_relation_name
                              13173                 :                :  *      Compute the name to display for a relation specified by OID
                              13174                 :                :  *
                              13175                 :                :  * The result includes all necessary quoting and schema-prefixing.
                              13176                 :                :  *
                              13177                 :                :  * If namespaces isn't NIL, it must be a list of deparse_namespace nodes.
                              13178                 :                :  * We will forcibly qualify the relation name if it equals any CTE name
                              13179                 :                :  * visible in the namespace list.
                              13180                 :                :  */
                              13181                 :                : static char *
 6231                         13182                 :           3959 : generate_relation_name(Oid relid, List *namespaces)
                              13183                 :                : {
                              13184                 :                :     HeapTuple   tp;
                              13185                 :                :     Form_pg_class reltup;
                              13186                 :                :     bool        need_qual;
                              13187                 :                :     ListCell   *nslist;
                              13188                 :                :     char       *relname;
                              13189                 :                :     char       *nspname;
                              13190                 :                :     char       *result;
                              13191                 :                : 
 5735 rhaas@postgresql.org    13192                 :           3959 :     tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
 8579 tgl@sss.pgh.pa.us       13193         [ -  + ]:           3959 :     if (!HeapTupleIsValid(tp))
 8129 tgl@sss.pgh.pa.us       13194         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for relation %u", relid);
 8579 tgl@sss.pgh.pa.us       13195                 :CBC        3959 :     reltup = (Form_pg_class) GETSTRUCT(tp);
 6231                         13196                 :           3959 :     relname = NameStr(reltup->relname);
                              13197                 :                : 
                              13198                 :                :     /* Check for conflicting CTE name */
                              13199                 :           3959 :     need_qual = false;
                              13200   [ +  +  +  +  :           6849 :     foreach(nslist, namespaces)
                                              +  + ]
                              13201                 :                :     {
                              13202                 :           2890 :         deparse_namespace *dpns = (deparse_namespace *) lfirst(nslist);
                              13203                 :                :         ListCell   *ctlist;
                              13204                 :                : 
                              13205   [ +  +  +  +  :           2956 :         foreach(ctlist, dpns->ctes)
                                              +  + ]
                              13206                 :                :         {
                              13207                 :             66 :             CommonTableExpr *cte = (CommonTableExpr *) lfirst(ctlist);
                              13208                 :                : 
                              13209         [ -  + ]:             66 :             if (strcmp(cte->ctename, relname) == 0)
                              13210                 :                :             {
 6231 tgl@sss.pgh.pa.us       13211                 :UBC           0 :                 need_qual = true;
                              13212                 :              0 :                 break;
                              13213                 :                :             }
                              13214                 :                :         }
 6231 tgl@sss.pgh.pa.us       13215         [ -  + ]:CBC        2890 :         if (need_qual)
 6231 tgl@sss.pgh.pa.us       13216                 :UBC           0 :             break;
                              13217                 :                :     }
                              13218                 :                : 
                              13219                 :                :     /* Otherwise, qualify the name if not visible in search path */
 6231 tgl@sss.pgh.pa.us       13220         [ +  - ]:CBC        3959 :     if (!need_qual)
                              13221                 :           3959 :         need_qual = !RelationIsVisible(relid);
                              13222                 :                : 
                              13223         [ +  + ]:           3959 :     if (need_qual)
 1554                         13224                 :           1125 :         nspname = get_namespace_name_or_temp(reltup->relnamespace);
                              13225                 :                :     else
 6231                         13226                 :           2834 :         nspname = NULL;
                              13227                 :                : 
                              13228                 :           3959 :     result = quote_qualified_identifier(nspname, relname);
                              13229                 :                : 
 8579                         13230                 :           3959 :     ReleaseSysCache(tp);
                              13231                 :                : 
                              13232                 :           3959 :     return result;
                              13233                 :                : }
                              13234                 :                : 
                              13235                 :                : /*
                              13236                 :                :  * generate_qualified_relation_name
                              13237                 :                :  *      Compute the name to display for a relation specified by OID
                              13238                 :                :  *
                              13239                 :                :  * As above, but unconditionally schema-qualify the name.
                              13240                 :                :  */
                              13241                 :                : static char *
 3630                         13242                 :           4052 : generate_qualified_relation_name(Oid relid)
                              13243                 :                : {
                              13244                 :                :     HeapTuple   tp;
                              13245                 :                :     Form_pg_class reltup;
                              13246                 :                :     char       *relname;
                              13247                 :                :     char       *nspname;
                              13248                 :                :     char       *result;
                              13249                 :                : 
                              13250                 :           4052 :     tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
                              13251         [ -  + ]:           4052 :     if (!HeapTupleIsValid(tp))
 3630 tgl@sss.pgh.pa.us       13252         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for relation %u", relid);
 3630 tgl@sss.pgh.pa.us       13253                 :CBC        4052 :     reltup = (Form_pg_class) GETSTRUCT(tp);
                              13254                 :           4052 :     relname = NameStr(reltup->relname);
                              13255                 :                : 
 1554                         13256                 :           4052 :     nspname = get_namespace_name_or_temp(reltup->relnamespace);
 3630                         13257         [ -  + ]:           4052 :     if (!nspname)
 3630 tgl@sss.pgh.pa.us       13258         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for namespace %u",
                              13259                 :                :              reltup->relnamespace);
                              13260                 :                : 
 3630 tgl@sss.pgh.pa.us       13261                 :CBC        4052 :     result = quote_qualified_identifier(nspname, relname);
                              13262                 :                : 
                              13263                 :           4052 :     ReleaseSysCache(tp);
                              13264                 :                : 
                              13265                 :           4052 :     return result;
                              13266                 :                : }
                              13267                 :                : 
                              13268                 :                : /*
                              13269                 :                :  * generate_function_name
                              13270                 :                :  *      Compute the name to display for a function specified by OID,
                              13271                 :                :  *      given that it is being called with the specified actual arg names and
                              13272                 :                :  *      types.  (Those matter because of ambiguous-function resolution rules.)
                              13273                 :                :  *
                              13274                 :                :  * If we're dealing with a potentially variadic function (in practice, this
                              13275                 :                :  * means a FuncExpr or Aggref, not some other way of calling a function), then
                              13276                 :                :  * has_variadic must specify whether variadic arguments have been merged,
                              13277                 :                :  * and *use_variadic_p will be set to indicate whether to print VARIADIC in
                              13278                 :                :  * the output.  For non-FuncExpr cases, has_variadic should be false and
                              13279                 :                :  * use_variadic_p can be NULL.
                              13280                 :                :  *
                              13281                 :                :  * inGroupBy must be true if we're deparsing a GROUP BY clause.
                              13282                 :                :  *
                              13283                 :                :  * The result includes all necessary quoting and schema-prefixing.
                              13284                 :                :  */
                              13285                 :                : static char *
 4663                         13286                 :           7461 : generate_function_name(Oid funcid, int nargs, List *argnames, Oid *argtypes,
                              13287                 :                :                        bool has_variadic, bool *use_variadic_p,
                              13288                 :                :                        bool inGroupBy)
                              13289                 :                : {
                              13290                 :                :     char       *result;
                              13291                 :                :     HeapTuple   proctup;
                              13292                 :                :     Form_pg_proc procform;
                              13293                 :                :     char       *proname;
                              13294                 :                :     bool        use_variadic;
                              13295                 :                :     char       *nspname;
                              13296                 :                :     FuncDetailCode p_result;
                              13297                 :                :     int         fgc_flags;
                              13298                 :                :     Oid         p_funcid;
                              13299                 :                :     Oid         p_rettype;
                              13300                 :                :     bool        p_retset;
                              13301                 :                :     int         p_nvargs;
                              13302                 :                :     Oid         p_vatype;
                              13303                 :                :     Oid        *p_true_typeids;
 3818 andres@anarazel.de      13304                 :           7461 :     bool        force_qualify = false;
                              13305                 :                : 
 5735 rhaas@postgresql.org    13306                 :           7461 :     proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
 8579 tgl@sss.pgh.pa.us       13307         [ -  + ]:           7461 :     if (!HeapTupleIsValid(proctup))
 8129 tgl@sss.pgh.pa.us       13308         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for function %u", funcid);
 8579 tgl@sss.pgh.pa.us       13309                 :CBC        7461 :     procform = (Form_pg_proc) GETSTRUCT(proctup);
                              13310                 :           7461 :     proname = NameStr(procform->proname);
                              13311                 :                : 
                              13312                 :                :     /*
                              13313                 :                :      * Due to parser hacks to avoid needing to reserve CUBE, we need to force
                              13314                 :                :      * qualification of some function names within GROUP BY.
                              13315                 :                :      */
  425                         13316         [ -  + ]:           7461 :     if (inGroupBy)
                              13317                 :                :     {
 3818 andres@anarazel.de      13318   [ #  #  #  # ]:UBC           0 :         if (strcmp(proname, "cube") == 0 || strcmp(proname, "rollup") == 0)
                              13319                 :              0 :             force_qualify = true;
                              13320                 :                :     }
                              13321                 :                : 
                              13322                 :                :     /*
                              13323                 :                :      * Determine whether VARIADIC should be printed.  We must do this first
                              13324                 :                :      * since it affects the lookup rules in func_get_detail().
                              13325                 :                :      *
                              13326                 :                :      * We always print VARIADIC if the function has a merged variadic-array
                              13327                 :                :      * argument.  Note that this is always the case for functions taking a
                              13328                 :                :      * VARIADIC argument type other than VARIADIC ANY.  If we omitted VARIADIC
                              13329                 :                :      * and printed the array elements as separate arguments, the call could
                              13330                 :                :      * match a newer non-VARIADIC function.
                              13331                 :                :      */
 4663 tgl@sss.pgh.pa.us       13332         [ +  + ]:CBC        7461 :     if (use_variadic_p)
                              13333                 :                :     {
                              13334                 :                :         /* Parser should not have set funcvariadic unless fn is variadic */
 4226                         13335   [ +  +  -  + ]:           6609 :         Assert(!has_variadic || OidIsValid(procform->provariadic));
                              13336                 :           6609 :         use_variadic = has_variadic;
 4663                         13337                 :           6609 :         *use_variadic_p = use_variadic;
                              13338                 :                :     }
                              13339                 :                :     else
                              13340                 :                :     {
 4226                         13341         [ -  + ]:            852 :         Assert(!has_variadic);
 4663                         13342                 :            852 :         use_variadic = false;
                              13343                 :                :     }
                              13344                 :                : 
                              13345                 :                :     /*
                              13346                 :                :      * The idea here is to schema-qualify only if the parser would fail to
                              13347                 :                :      * resolve the correct function given the unqualified func name with the
                              13348                 :                :      * specified argtypes and VARIADIC flag.  But if we already decided to
                              13349                 :                :      * force qualification, then we can skip the lookup and pretend we didn't
                              13350                 :                :      * find it.
                              13351                 :                :      */
 3818 andres@anarazel.de      13352         [ +  - ]:           7461 :     if (!force_qualify)
                              13353                 :           7461 :         p_result = func_get_detail(list_make1(makeString(proname)),
                              13354                 :                :                                    NIL, argnames, nargs, argtypes,
 1601 tgl@sss.pgh.pa.us       13355                 :           7461 :                                    !use_variadic, true, false,
                              13356                 :                :                                    &fgc_flags,
                              13357                 :                :                                    &p_funcid, &p_rettype,
                              13358                 :                :                                    &p_retset, &p_nvargs, &p_vatype,
 3818 andres@anarazel.de      13359                 :           7461 :                                    &p_true_typeids, NULL);
                              13360                 :                :     else
                              13361                 :                :     {
 3818 andres@anarazel.de      13362                 :UBC           0 :         p_result = FUNCDETAIL_NOTFOUND;
                              13363                 :              0 :         p_funcid = InvalidOid;
                              13364                 :                :     }
                              13365                 :                : 
 6148 tgl@sss.pgh.pa.us       13366   [ +  +  +  + ]:CBC        7461 :     if ((p_result == FUNCDETAIL_NORMAL ||
                              13367         [ +  + ]:            634 :          p_result == FUNCDETAIL_AGGREGATE ||
                              13368                 :           6890 :          p_result == FUNCDETAIL_WINDOWFUNC) &&
 8152                         13369         [ +  - ]:           6890 :         p_funcid == funcid)
 8579                         13370                 :           6890 :         nspname = NULL;
                              13371                 :                :     else
 1554                         13372                 :            571 :         nspname = get_namespace_name_or_temp(procform->pronamespace);
                              13373                 :                : 
 8579                         13374                 :           7461 :     result = quote_qualified_identifier(nspname, proname);
                              13375                 :                : 
                              13376                 :           7461 :     ReleaseSysCache(proctup);
                              13377                 :                : 
                              13378                 :           7461 :     return result;
                              13379                 :                : }
                              13380                 :                : 
                              13381                 :                : /*
                              13382                 :                :  * generate_operator_name
                              13383                 :                :  *      Compute the name to display for an operator specified by OID,
                              13384                 :                :  *      given that it is being called with the specified actual arg types.
                              13385                 :                :  *      (Arg types matter because of ambiguous-operator resolution rules.
                              13386                 :                :  *      Pass InvalidOid for unused arg of a unary operator.)
                              13387                 :                :  *
                              13388                 :                :  * The result includes all necessary quoting and schema-prefixing,
                              13389                 :                :  * plus the OPERATOR() decoration needed to use a qualified operator name
                              13390                 :                :  * in an expression.
                              13391                 :                :  */
                              13392                 :                : static char *
                              13393                 :          32287 : generate_operator_name(Oid operid, Oid arg1, Oid arg2)
                              13394                 :                : {
                              13395                 :                :     StringInfoData buf;
                              13396                 :                :     HeapTuple   opertup;
                              13397                 :                :     Form_pg_operator operform;
                              13398                 :                :     char       *oprname;
                              13399                 :                :     char       *nspname;
                              13400                 :                :     Operator    p_result;
                              13401                 :                : 
                              13402                 :          32287 :     initStringInfo(&buf);
                              13403                 :                : 
 5735 rhaas@postgresql.org    13404                 :          32287 :     opertup = SearchSysCache1(OPEROID, ObjectIdGetDatum(operid));
 8579 tgl@sss.pgh.pa.us       13405         [ -  + ]:          32287 :     if (!HeapTupleIsValid(opertup))
 8129 tgl@sss.pgh.pa.us       13406         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for operator %u", operid);
 8579 tgl@sss.pgh.pa.us       13407                 :CBC       32287 :     operform = (Form_pg_operator) GETSTRUCT(opertup);
                              13408                 :          32287 :     oprname = NameStr(operform->oprname);
                              13409                 :                : 
                              13410                 :                :     /*
                              13411                 :                :      * The idea here is to schema-qualify only if the parser would fail to
                              13412                 :                :      * resolve the correct operator given the unqualified op name with the
                              13413                 :                :      * specified argtypes.
                              13414                 :                :      */
                              13415      [ +  +  - ]:          32287 :     switch (operform->oprkind)
                              13416                 :                :     {
                              13417                 :          32272 :         case 'b':
 7168                         13418                 :          32272 :             p_result = oper(NULL, list_make1(makeString(oprname)), arg1, arg2,
                              13419                 :                :                             true, -1);
 8579                         13420                 :          32272 :             break;
                              13421                 :             15 :         case 'l':
 7168                         13422                 :             15 :             p_result = left_oper(NULL, list_make1(makeString(oprname)), arg2,
                              13423                 :                :                                  true, -1);
 8579                         13424                 :             15 :             break;
 8579 tgl@sss.pgh.pa.us       13425                 :UBC           0 :         default:
 8129                         13426         [ #  # ]:              0 :             elog(ERROR, "unrecognized oprkind: %d", operform->oprkind);
                              13427                 :                :             p_result = NULL;    /* keep compiler quiet */
                              13428                 :                :             break;
                              13429                 :                :     }
                              13430                 :                : 
 8579 tgl@sss.pgh.pa.us       13431   [ +  +  +  - ]:CBC       32287 :     if (p_result != NULL && oprid(p_result) == operid)
                              13432                 :          32282 :         nspname = NULL;
                              13433                 :                :     else
                              13434                 :                :     {
 1554                         13435                 :              5 :         nspname = get_namespace_name_or_temp(operform->oprnamespace);
 8579                         13436                 :              5 :         appendStringInfo(&buf, "OPERATOR(%s.", quote_identifier(nspname));
                              13437                 :                :     }
                              13438                 :                : 
 7941 neilc@samurai.com       13439                 :          32287 :     appendStringInfoString(&buf, oprname);
                              13440                 :                : 
 8579 tgl@sss.pgh.pa.us       13441         [ +  + ]:          32287 :     if (nspname)
                              13442                 :              5 :         appendStringInfoChar(&buf, ')');
                              13443                 :                : 
                              13444         [ +  + ]:          32287 :     if (p_result != NULL)
                              13445                 :          32282 :         ReleaseSysCache(p_result);
                              13446                 :                : 
                              13447                 :          32287 :     ReleaseSysCache(opertup);
                              13448                 :                : 
                              13449                 :          32287 :     return buf.data;
                              13450                 :                : }
                              13451                 :                : 
                              13452                 :                : /*
                              13453                 :                :  * generate_operator_clause --- generate a binary-operator WHERE clause
                              13454                 :                :  *
                              13455                 :                :  * This is used for internally-generated-and-executed SQL queries, where
                              13456                 :                :  * precision is essential and readability is secondary.  The basic
                              13457                 :                :  * requirement is to append "leftop op rightop" to buf, where leftop and
                              13458                 :                :  * rightop are given as strings and are assumed to yield types leftoptype
                              13459                 :                :  * and rightoptype; the operator is identified by OID.  The complexity
                              13460                 :                :  * comes from needing to be sure that the parser will select the desired
                              13461                 :                :  * operator when the query is parsed.  We always name the operator using
                              13462                 :                :  * OPERATOR(schema.op) syntax, so as to avoid search-path uncertainties.
                              13463                 :                :  * We have to emit casts too, if either input isn't already the input type
                              13464                 :                :  * of the operator; else we are at the mercy of the parser's heuristics for
                              13465                 :                :  * ambiguous-operator resolution.  The caller must ensure that leftop and
                              13466                 :                :  * rightop are suitable arguments for a cast operation; it's best to insert
                              13467                 :                :  * parentheses if they aren't just variables or parameters.
                              13468                 :                :  */
                              13469                 :                : void
 2780                         13470                 :           3321 : generate_operator_clause(StringInfo buf,
                              13471                 :                :                          const char *leftop, Oid leftoptype,
                              13472                 :                :                          Oid opoid,
                              13473                 :                :                          const char *rightop, Oid rightoptype)
                              13474                 :                : {
                              13475                 :                :     HeapTuple   opertup;
                              13476                 :                :     Form_pg_operator operform;
                              13477                 :                :     char       *oprname;
                              13478                 :                :     char       *nspname;
                              13479                 :                : 
                              13480                 :           3321 :     opertup = SearchSysCache1(OPEROID, ObjectIdGetDatum(opoid));
                              13481         [ -  + ]:           3321 :     if (!HeapTupleIsValid(opertup))
 2780 tgl@sss.pgh.pa.us       13482         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for operator %u", opoid);
 2780 tgl@sss.pgh.pa.us       13483                 :CBC        3321 :     operform = (Form_pg_operator) GETSTRUCT(opertup);
                              13484         [ -  + ]:           3321 :     Assert(operform->oprkind == 'b');
                              13485                 :           3321 :     oprname = NameStr(operform->oprname);
                              13486                 :                : 
                              13487                 :           3321 :     nspname = get_namespace_name(operform->oprnamespace);
                              13488                 :                : 
                              13489                 :           3321 :     appendStringInfoString(buf, leftop);
                              13490         [ +  + ]:           3321 :     if (leftoptype != operform->oprleft)
                              13491                 :            605 :         add_cast_to(buf, operform->oprleft);
                              13492                 :           3321 :     appendStringInfo(buf, " OPERATOR(%s.", quote_identifier(nspname));
                              13493                 :           3321 :     appendStringInfoString(buf, oprname);
                              13494                 :           3321 :     appendStringInfo(buf, ") %s", rightop);
                              13495         [ +  + ]:           3321 :     if (rightoptype != operform->oprright)
                              13496                 :            490 :         add_cast_to(buf, operform->oprright);
                              13497                 :                : 
                              13498                 :           3321 :     ReleaseSysCache(opertup);
                              13499                 :           3321 : }
                              13500                 :                : 
                              13501                 :                : /*
                              13502                 :                :  * Add a cast specification to buf.  We spell out the type name the hard way,
                              13503                 :                :  * intentionally not using format_type_be().  This is to avoid corner cases
                              13504                 :                :  * for CHARACTER, BIT, and perhaps other types, where specifying the type
                              13505                 :                :  * using SQL-standard syntax results in undesirable data truncation.  By
                              13506                 :                :  * doing it this way we can be certain that the cast will have default (-1)
                              13507                 :                :  * target typmod.
                              13508                 :                :  */
                              13509                 :                : static void
                              13510                 :           1095 : add_cast_to(StringInfo buf, Oid typid)
                              13511                 :                : {
                              13512                 :                :     HeapTuple   typetup;
                              13513                 :                :     Form_pg_type typform;
                              13514                 :                :     char       *typname;
                              13515                 :                :     char       *nspname;
                              13516                 :                : 
                              13517                 :           1095 :     typetup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
                              13518         [ -  + ]:           1095 :     if (!HeapTupleIsValid(typetup))
 2780 tgl@sss.pgh.pa.us       13519         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for type %u", typid);
 2780 tgl@sss.pgh.pa.us       13520                 :CBC        1095 :     typform = (Form_pg_type) GETSTRUCT(typetup);
                              13521                 :                : 
                              13522                 :           1095 :     typname = NameStr(typform->typname);
 1554                         13523                 :           1095 :     nspname = get_namespace_name_or_temp(typform->typnamespace);
                              13524                 :                : 
 2780                         13525                 :           1095 :     appendStringInfo(buf, "::%s.%s",
                              13526                 :                :                      quote_identifier(nspname), quote_identifier(typname));
                              13527                 :                : 
                              13528                 :           1095 :     ReleaseSysCache(typetup);
                              13529                 :           1095 : }
                              13530                 :                : 
                              13531                 :                : /*
                              13532                 :                :  * generate_qualified_type_name
                              13533                 :                :  *      Compute the name to display for a type specified by OID
                              13534                 :                :  *
                              13535                 :                :  * This is different from format_type_be() in that we unconditionally
                              13536                 :                :  * schema-qualify the name.  That also means no special syntax for
                              13537                 :                :  * SQL-standard type names ... although in current usage, this should
                              13538                 :                :  * only get used for domains, so such cases wouldn't occur anyway.
                              13539                 :                :  */
                              13540                 :                : static char *
 2918                         13541                 :              7 : generate_qualified_type_name(Oid typid)
                              13542                 :                : {
                              13543                 :                :     HeapTuple   tp;
                              13544                 :                :     Form_pg_type typtup;
                              13545                 :                :     char       *typname;
                              13546                 :                :     char       *nspname;
                              13547                 :                :     char       *result;
                              13548                 :                : 
                              13549                 :              7 :     tp = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
                              13550         [ -  + ]:              7 :     if (!HeapTupleIsValid(tp))
 2918 tgl@sss.pgh.pa.us       13551         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for type %u", typid);
 2918 tgl@sss.pgh.pa.us       13552                 :CBC           7 :     typtup = (Form_pg_type) GETSTRUCT(tp);
                              13553                 :              7 :     typname = NameStr(typtup->typname);
                              13554                 :                : 
 1554                         13555                 :              7 :     nspname = get_namespace_name_or_temp(typtup->typnamespace);
 2918                         13556         [ -  + ]:              7 :     if (!nspname)
 2918 tgl@sss.pgh.pa.us       13557         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for namespace %u",
                              13558                 :                :              typtup->typnamespace);
                              13559                 :                : 
 2918 tgl@sss.pgh.pa.us       13560                 :CBC           7 :     result = quote_qualified_identifier(nspname, typname);
                              13561                 :                : 
                              13562                 :              7 :     ReleaseSysCache(tp);
                              13563                 :                : 
                              13564                 :              7 :     return result;
                              13565                 :                : }
                              13566                 :                : 
                              13567                 :                : /*
                              13568                 :                :  * generate_collation_name
                              13569                 :                :  *      Compute the name to display for a collation specified by OID
                              13570                 :                :  *
                              13571                 :                :  * The result includes all necessary quoting and schema-prefixing.
                              13572                 :                :  */
                              13573                 :                : char *
 5376 peter_e@gmx.net         13574                 :            147 : generate_collation_name(Oid collid)
                              13575                 :                : {
                              13576                 :                :     HeapTuple   tp;
                              13577                 :                :     Form_pg_collation colltup;
                              13578                 :                :     char       *collname;
                              13579                 :                :     char       *nspname;
                              13580                 :                :     char       *result;
                              13581                 :                : 
                              13582                 :            147 :     tp = SearchSysCache1(COLLOID, ObjectIdGetDatum(collid));
                              13583         [ -  + ]:            147 :     if (!HeapTupleIsValid(tp))
 5376 peter_e@gmx.net         13584         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for collation %u", collid);
 5376 peter_e@gmx.net         13585                 :CBC         147 :     colltup = (Form_pg_collation) GETSTRUCT(tp);
                              13586                 :            147 :     collname = NameStr(colltup->collname);
                              13587                 :                : 
                              13588         [ -  + ]:            147 :     if (!CollationIsVisible(collid))
 1554 tgl@sss.pgh.pa.us       13589                 :UBC           0 :         nspname = get_namespace_name_or_temp(colltup->collnamespace);
                              13590                 :                :     else
 5376 peter_e@gmx.net         13591                 :CBC         147 :         nspname = NULL;
                              13592                 :                : 
                              13593                 :            147 :     result = quote_qualified_identifier(nspname, collname);
                              13594                 :                : 
                              13595                 :            147 :     ReleaseSysCache(tp);
                              13596                 :                : 
                              13597                 :            147 :     return result;
                              13598                 :                : }
                              13599                 :                : 
                              13600                 :                : /*
                              13601                 :                :  * Given a C string, produce a TEXT datum.
                              13602                 :                :  *
                              13603                 :                :  * We assume that the input was palloc'd and may be freed.
                              13604                 :                :  */
                              13605                 :                : static text *
 7846 tgl@sss.pgh.pa.us       13606                 :          21991 : string_to_text(char *str)
                              13607                 :                : {
                              13608                 :                :     text       *result;
                              13609                 :                : 
 6426                         13610                 :          21991 :     result = cstring_to_text(str);
 7846                         13611                 :          21991 :     pfree(str);
                              13612                 :          21991 :     return result;
                              13613                 :                : }
                              13614                 :                : 
                              13615                 :                : /*
                              13616                 :                :  * Generate a C string representing a relation options from text[] datum.
                              13617                 :                :  */
                              13618                 :                : static void
 2038 akorotkov@postgresql    13619                 :            122 : get_reloptions(StringInfo buf, Datum reloptions)
                              13620                 :                : {
                              13621                 :                :     Datum      *options;
                              13622                 :                :     int         noptions;
                              13623                 :                :     int         i;
                              13624                 :                : 
 1215 peter@eisentraut.org    13625                 :            122 :     deconstruct_array_builtin(DatumGetArrayTypeP(reloptions), TEXTOID,
                              13626                 :                :                               &options, NULL, &noptions);
                              13627                 :                : 
 2038 akorotkov@postgresql    13628         [ +  + ]:            254 :     for (i = 0; i < noptions; i++)
                              13629                 :                :     {
                              13630                 :            132 :         char       *option = TextDatumGetCString(options[i]);
                              13631                 :                :         char       *name;
                              13632                 :                :         char       *separator;
                              13633                 :                :         char       *value;
                              13634                 :                : 
                              13635                 :                :         /*
                              13636                 :                :          * Each array element should have the form name=value.  If the "=" is
                              13637                 :                :          * missing for some reason, treat it like an empty value.
                              13638                 :                :          */
                              13639                 :            132 :         name = option;
                              13640                 :            132 :         separator = strchr(option, '=');
                              13641         [ +  - ]:            132 :         if (separator)
                              13642                 :                :         {
                              13643                 :            132 :             *separator = '\0';
                              13644                 :            132 :             value = separator + 1;
                              13645                 :                :         }
                              13646                 :                :         else
 2038 akorotkov@postgresql    13647                 :UBC           0 :             value = "";
                              13648                 :                : 
 2038 akorotkov@postgresql    13649         [ +  + ]:CBC         132 :         if (i > 0)
                              13650                 :             10 :             appendStringInfoString(buf, ", ");
                              13651                 :            132 :         appendStringInfo(buf, "%s=", quote_identifier(name));
                              13652                 :                : 
                              13653                 :                :         /*
                              13654                 :                :          * In general we need to quote the value; but to avoid unnecessary
                              13655                 :                :          * clutter, do not quote if it is an identifier that would not need
                              13656                 :                :          * quoting.  (We could also allow numbers, but that is a bit trickier
                              13657                 :                :          * than it looks --- for example, are leading zeroes significant?  We
                              13658                 :                :          * don't want to assume very much here about what custom reloptions
                              13659                 :                :          * might mean.)
                              13660                 :                :          */
                              13661         [ +  + ]:            132 :         if (quote_identifier(value) == value)
                              13662                 :              4 :             appendStringInfoString(buf, value);
                              13663                 :                :         else
                              13664                 :            128 :             simple_quote_literal(buf, value);
                              13665                 :                : 
                              13666                 :            132 :         pfree(option);
                              13667                 :                :     }
                              13668                 :            122 : }
                              13669                 :                : 
                              13670                 :                : /*
                              13671                 :                :  * Generate a C string representing a relation's reloptions, or NULL if none.
                              13672                 :                :  */
                              13673                 :                : static char *
 7058 bruce@momjian.us        13674                 :           3842 : flatten_reloptions(Oid relid)
                              13675                 :                : {
                              13676                 :           3842 :     char       *result = NULL;
                              13677                 :                :     HeapTuple   tuple;
                              13678                 :                :     Datum       reloptions;
                              13679                 :                :     bool        isnull;
                              13680                 :                : 
 5735 rhaas@postgresql.org    13681                 :           3842 :     tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
 7057 tgl@sss.pgh.pa.us       13682         [ -  + ]:           3842 :     if (!HeapTupleIsValid(tuple))
 7057 tgl@sss.pgh.pa.us       13683         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for relation %u", relid);
                              13684                 :                : 
 7057 tgl@sss.pgh.pa.us       13685                 :CBC        3842 :     reloptions = SysCacheGetAttr(RELOID, tuple,
                              13686                 :                :                                  Anum_pg_class_reloptions, &isnull);
                              13687         [ +  + ]:           3842 :     if (!isnull)
                              13688                 :                :     {
                              13689                 :                :         StringInfoData buf;
                              13690                 :                : 
 3588                         13691                 :            105 :         initStringInfo(&buf);
 2038 akorotkov@postgresql    13692                 :            105 :         get_reloptions(&buf, reloptions);
                              13693                 :                : 
 3588 tgl@sss.pgh.pa.us       13694                 :            105 :         result = buf.data;
                              13695                 :                :     }
                              13696                 :                : 
 7057                         13697                 :           3842 :     ReleaseSysCache(tuple);
                              13698                 :                : 
 7058 bruce@momjian.us        13699                 :           3842 :     return result;
                              13700                 :                : }
                              13701                 :                : 
                              13702                 :                : /*
                              13703                 :                :  * get_range_partbound_string
                              13704                 :                :  *      A C string representation of one range partition bound
                              13705                 :                :  */
                              13706                 :                : char *
 3001 rhaas@postgresql.org    13707                 :           2298 : get_range_partbound_string(List *bound_datums)
                              13708                 :                : {
                              13709                 :                :     deparse_context context;
                              13710                 :           2298 :     StringInfo  buf = makeStringInfo();
                              13711                 :                :     ListCell   *cell;
                              13712                 :                :     char       *sep;
                              13713                 :                : 
                              13714                 :           2298 :     memset(&context, 0, sizeof(deparse_context));
                              13715                 :           2298 :     context.buf = buf;
                              13716                 :                : 
 1839 drowley@postgresql.o    13717                 :           2298 :     appendStringInfoChar(buf, '(');
 3001 rhaas@postgresql.org    13718                 :           2298 :     sep = "";
                              13719   [ +  -  +  +  :           4992 :     foreach(cell, bound_datums)
                                              +  + ]
                              13720                 :                :     {
                              13721                 :                :         PartitionRangeDatum *datum =
  893 tgl@sss.pgh.pa.us       13722                 :           2694 :             lfirst_node(PartitionRangeDatum, cell);
                              13723                 :                : 
 3001 rhaas@postgresql.org    13724                 :           2694 :         appendStringInfoString(buf, sep);
                              13725         [ +  + ]:           2694 :         if (datum->kind == PARTITION_RANGE_DATUM_MINVALUE)
                              13726                 :            111 :             appendStringInfoString(buf, "MINVALUE");
                              13727         [ +  + ]:           2583 :         else if (datum->kind == PARTITION_RANGE_DATUM_MAXVALUE)
                              13728                 :             60 :             appendStringInfoString(buf, "MAXVALUE");
                              13729                 :                :         else
                              13730                 :                :         {
                              13731                 :           2523 :             Const      *val = castNode(Const, datum->value);
                              13732                 :                : 
                              13733                 :           2523 :             get_const_expr(val, &context, -1);
                              13734                 :                :         }
                              13735                 :           2694 :         sep = ", ";
                              13736                 :                :     }
 2996 peter_e@gmx.net         13737                 :           2298 :     appendStringInfoChar(buf, ')');
                              13738                 :                : 
 3001 rhaas@postgresql.org    13739                 :           2298 :     return buf->data;
                              13740                 :                : }
        

Generated by: LCOV version 2.4-beta