Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * ruleutils.c
4 : : * Functions to convert stored expressions/querytrees back to
5 : : * source text
6 : : *
7 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
8 : : * Portions Copyright (c) 1994, Regents of the University of California
9 : : *
10 : : *
11 : : * IDENTIFICATION
12 : : * src/backend/utils/adt/ruleutils.c
13 : : *
14 : : *-------------------------------------------------------------------------
15 : : */
16 : : #include "postgres.h"
17 : :
18 : : #include <ctype.h>
19 : : #include <unistd.h>
20 : : #include <fcntl.h>
21 : :
22 : : #include "access/amapi.h"
23 : : #include "access/htup_details.h"
24 : : #include "access/relation.h"
25 : : #include "access/table.h"
26 : : #include "catalog/pg_aggregate.h"
27 : : #include "catalog/pg_am.h"
28 : : #include "catalog/pg_authid.h"
29 : : #include "catalog/pg_collation.h"
30 : : #include "catalog/pg_constraint.h"
31 : : #include "catalog/pg_depend.h"
32 : : #include "catalog/pg_language.h"
33 : : #include "catalog/pg_opclass.h"
34 : : #include "catalog/pg_operator.h"
35 : : #include "catalog/pg_partitioned_table.h"
36 : : #include "catalog/pg_proc.h"
37 : : #include "catalog/pg_statistic_ext.h"
38 : : #include "catalog/pg_trigger.h"
39 : : #include "catalog/pg_type.h"
40 : : #include "commands/defrem.h"
41 : : #include "commands/tablespace.h"
42 : : #include "common/keywords.h"
43 : : #include "executor/spi.h"
44 : : #include "funcapi.h"
45 : : #include "mb/pg_wchar.h"
46 : : #include "miscadmin.h"
47 : : #include "nodes/makefuncs.h"
48 : : #include "nodes/nodeFuncs.h"
49 : : #include "nodes/pathnodes.h"
50 : : #include "optimizer/optimizer.h"
51 : : #include "parser/parse_agg.h"
52 : : #include "parser/parse_func.h"
53 : : #include "parser/parse_oper.h"
54 : : #include "parser/parse_relation.h"
55 : : #include "parser/parser.h"
56 : : #include "parser/parsetree.h"
57 : : #include "rewrite/rewriteHandler.h"
58 : : #include "rewrite/rewriteManip.h"
59 : : #include "rewrite/rewriteSupport.h"
60 : : #include "utils/array.h"
61 : : #include "utils/builtins.h"
62 : : #include "utils/fmgroids.h"
63 : : #include "utils/guc.h"
64 : : #include "utils/hsearch.h"
65 : : #include "utils/lsyscache.h"
66 : : #include "utils/partcache.h"
67 : : #include "utils/rel.h"
68 : : #include "utils/ruleutils.h"
69 : : #include "utils/snapmgr.h"
70 : : #include "utils/syscache.h"
71 : : #include "utils/typcache.h"
72 : : #include "utils/varlena.h"
73 : : #include "utils/xml.h"
74 : :
75 : : /* ----------
76 : : * Pretty formatting constants
77 : : * ----------
78 : : */
79 : :
80 : : /* Indent counts */
81 : : #define PRETTYINDENT_STD 8
82 : : #define PRETTYINDENT_JOIN 4
83 : : #define PRETTYINDENT_VAR 4
84 : :
85 : : #define PRETTYINDENT_LIMIT 40 /* wrap limit */
86 : :
87 : : /* Pretty flags */
88 : : #define PRETTYFLAG_PAREN 0x0001
89 : : #define PRETTYFLAG_INDENT 0x0002
90 : : #define PRETTYFLAG_SCHEMA 0x0004
91 : :
92 : : /* Standard conversion of a "bool pretty" option to detailed flags */
93 : : #define GET_PRETTY_FLAGS(pretty) \
94 : : ((pretty) ? (PRETTYFLAG_PAREN | PRETTYFLAG_INDENT | PRETTYFLAG_SCHEMA) \
95 : : : PRETTYFLAG_INDENT)
96 : :
97 : : /* Default line length for pretty-print wrapping: 0 means wrap always */
98 : : #define WRAP_COLUMN_DEFAULT 0
99 : :
100 : : /* macros to test if pretty action needed */
101 : : #define PRETTY_PAREN(context) ((context)->prettyFlags & PRETTYFLAG_PAREN)
102 : : #define PRETTY_INDENT(context) ((context)->prettyFlags & PRETTYFLAG_INDENT)
103 : : #define PRETTY_SCHEMA(context) ((context)->prettyFlags & PRETTYFLAG_SCHEMA)
104 : :
105 : :
106 : : /* ----------
107 : : * Local data types
108 : : * ----------
109 : : */
110 : :
111 : : /* Context info needed for invoking a recursive querytree display routine */
112 : : typedef struct
113 : : {
114 : : StringInfo buf; /* output buffer to append to */
115 : : List *namespaces; /* List of deparse_namespace nodes */
116 : : TupleDesc resultDesc; /* if top level of a view, the view's tupdesc */
117 : : List *targetList; /* Current query level's SELECT targetlist */
118 : : List *windowClause; /* Current query level's WINDOW clause */
119 : : int prettyFlags; /* enabling of pretty-print functions */
120 : : int wrapColumn; /* max line length, or -1 for no limit */
121 : : int indentLevel; /* current indent level for pretty-print */
122 : : bool varprefix; /* true to print prefixes on Vars */
123 : : bool colNamesVisible; /* do we care about output column names? */
124 : : bool inGroupBy; /* deparsing GROUP BY clause? */
125 : : bool varInOrderBy; /* deparsing simple Var in ORDER BY? */
126 : : Bitmapset *appendparents; /* if not null, map child Vars of these relids
127 : : * back to the parent rel */
128 : : } deparse_context;
129 : :
130 : : /*
131 : : * Each level of query context around a subtree needs a level of Var namespace.
132 : : * A Var having varlevelsup=N refers to the N'th item (counting from 0) in
133 : : * the current context's namespaces list.
134 : : *
135 : : * rtable is the list of actual RTEs from the Query or PlannedStmt.
136 : : * rtable_names holds the alias name to be used for each RTE (either a C
137 : : * string, or NULL for nameless RTEs such as unnamed joins).
138 : : * rtable_columns holds the column alias names to be used for each RTE.
139 : : *
140 : : * subplans is a list of Plan trees for SubPlans and CTEs (it's only used
141 : : * in the PlannedStmt case).
142 : : * ctes is a list of CommonTableExpr nodes (only used in the Query case).
143 : : * appendrels, if not null (it's only used in the PlannedStmt case), is an
144 : : * array of AppendRelInfo nodes, indexed by child relid. We use that to map
145 : : * child-table Vars to their inheritance parents.
146 : : *
147 : : * In some cases we need to make names of merged JOIN USING columns unique
148 : : * across the whole query, not only per-RTE. If so, unique_using is true
149 : : * and using_names is a list of C strings representing names already assigned
150 : : * to USING columns.
151 : : *
152 : : * When deparsing plan trees, there is always just a single item in the
153 : : * deparse_namespace list (since a plan tree never contains Vars with
154 : : * varlevelsup > 0). We store the Plan node that is the immediate
155 : : * parent of the expression to be deparsed, as well as a list of that
156 : : * Plan's ancestors. In addition, we store its outer and inner subplan nodes,
157 : : * as well as their targetlists, and the index tlist if the current plan node
158 : : * might contain INDEX_VAR Vars. (These fields could be derived on-the-fly
159 : : * from the current Plan node, but it seems notationally clearer to set them
160 : : * up as separate fields.)
161 : : */
162 : : typedef struct
163 : : {
164 : : List *rtable; /* List of RangeTblEntry nodes */
165 : : List *rtable_names; /* Parallel list of names for RTEs */
166 : : List *rtable_columns; /* Parallel list of deparse_columns structs */
167 : : List *subplans; /* List of Plan trees for SubPlans */
168 : : List *ctes; /* List of CommonTableExpr nodes */
169 : : AppendRelInfo **appendrels; /* Array of AppendRelInfo nodes, or NULL */
170 : : char *ret_old_alias; /* alias for OLD in RETURNING list */
171 : : char *ret_new_alias; /* alias for NEW in RETURNING list */
172 : : /* Workspace for column alias assignment: */
173 : : bool unique_using; /* Are we making USING names globally unique */
174 : : List *using_names; /* List of assigned names for USING columns */
175 : : /* Remaining fields are used only when deparsing a Plan tree: */
176 : : Plan *plan; /* immediate parent of current expression */
177 : : List *ancestors; /* ancestors of plan */
178 : : Plan *outer_plan; /* outer subnode, or NULL if none */
179 : : Plan *inner_plan; /* inner subnode, or NULL if none */
180 : : List *outer_tlist; /* referent for OUTER_VAR Vars */
181 : : List *inner_tlist; /* referent for INNER_VAR Vars */
182 : : List *index_tlist; /* referent for INDEX_VAR Vars */
183 : : /* Special namespace representing a function signature: */
184 : : char *funcname;
185 : : int numargs;
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 char *get_lock_clause_strength(LockClauseStrength strength);
430 : : static void get_basic_select_query(Query *query, deparse_context *context);
431 : : static void get_target_list(List *targetList, deparse_context *context);
432 : : static void get_returning_clause(Query *query, deparse_context *context);
433 : : static void get_setop_query(Node *setOp, Query *query,
434 : : deparse_context *context);
435 : : static Node *get_rule_sortgroupclause(Index ref, List *tlist,
436 : : bool force_colno,
437 : : deparse_context *context);
438 : : static void get_rule_groupingset(GroupingSet *gset, List *targetlist,
439 : : bool omit_parens, deparse_context *context);
440 : : static void get_rule_orderby(List *orderList, List *targetList,
441 : : bool force_colno, deparse_context *context);
442 : : static void get_rule_windowclause(Query *query, deparse_context *context);
443 : : static void get_rule_windowspec(WindowClause *wc, List *targetList,
444 : : deparse_context *context);
445 : : static void get_window_frame_options(int frameOptions,
446 : : Node *startOffset, Node *endOffset,
447 : : deparse_context *context);
448 : : static char *get_variable(Var *var, int levelsup, bool istoplevel,
449 : : deparse_context *context);
450 : : static void get_special_variable(Node *node, deparse_context *context,
451 : : void *callback_arg);
452 : : static void resolve_special_varno(Node *node, deparse_context *context,
453 : : rsv_callback callback, void *callback_arg);
454 : : static Node *find_param_referent(Param *param, deparse_context *context,
455 : : deparse_namespace **dpns_p, ListCell **ancestor_cell_p);
456 : : static SubPlan *find_param_generator(Param *param, deparse_context *context,
457 : : int *column_p);
458 : : static SubPlan *find_param_generator_initplan(Param *param, Plan *plan,
459 : : int *column_p);
460 : : static void get_parameter(Param *param, deparse_context *context);
461 : : static const char *get_simple_binary_op_name(OpExpr *expr);
462 : : static bool isSimpleNode(Node *node, Node *parentNode, int prettyFlags);
463 : : static void appendContextKeyword(deparse_context *context, const char *str,
464 : : int indentBefore, int indentAfter, int indentPlus);
465 : : static void removeStringInfoSpaces(StringInfo str);
466 : : static void get_rule_expr(Node *node, deparse_context *context,
467 : : bool showimplicit);
468 : : static void get_rule_expr_toplevel(Node *node, deparse_context *context,
469 : : bool showimplicit);
470 : : static void get_rule_list_toplevel(List *lst, deparse_context *context,
471 : : bool showimplicit);
472 : : static void get_rule_expr_funccall(Node *node, deparse_context *context,
473 : : bool showimplicit);
474 : : static bool looks_like_function(Node *node);
475 : : static void get_oper_expr(OpExpr *expr, deparse_context *context);
476 : : static void get_func_expr(FuncExpr *expr, deparse_context *context,
477 : : bool showimplicit);
478 : : static void get_agg_expr(Aggref *aggref, deparse_context *context,
479 : : Aggref *original_aggref);
480 : : static void get_agg_expr_helper(Aggref *aggref, deparse_context *context,
481 : : Aggref *original_aggref, const char *funcname,
482 : : const char *options, bool is_json_objectagg);
483 : : static void get_agg_combine_expr(Node *node, deparse_context *context,
484 : : void *callback_arg);
485 : : static void get_windowfunc_expr(WindowFunc *wfunc, deparse_context *context);
486 : : static void get_windowfunc_expr_helper(WindowFunc *wfunc, deparse_context *context,
487 : : const char *funcname, const char *options,
488 : : bool is_json_objectagg);
489 : : static bool get_func_sql_syntax(FuncExpr *expr, deparse_context *context);
490 : : static void get_coercion_expr(Node *arg, deparse_context *context,
491 : : Oid resulttype, int32 resulttypmod,
492 : : Node *parentNode);
493 : : static void get_const_expr(Const *constval, deparse_context *context,
494 : : int showtype);
495 : : static void get_const_collation(Const *constval, deparse_context *context);
496 : : static void get_json_format(JsonFormat *format, StringInfo buf);
497 : : static void get_json_returning(JsonReturning *returning, StringInfo buf,
498 : : bool json_format_by_default);
499 : : static void get_json_constructor(JsonConstructorExpr *ctor,
500 : : deparse_context *context, bool showimplicit);
501 : : static void get_json_constructor_options(JsonConstructorExpr *ctor,
502 : : StringInfo buf);
503 : : static void get_json_agg_constructor(JsonConstructorExpr *ctor,
504 : : deparse_context *context,
505 : : const char *funcname,
506 : : bool is_json_objectagg);
507 : : static void get_json_agg_constructor_expr(Node *node, deparse_context *context,
508 : : void *callback_arg);
509 : : static void simple_quote_literal(StringInfo buf, const char *val);
510 : : static void get_sublink_expr(SubLink *sublink, deparse_context *context);
511 : : static void get_tablefunc(TableFunc *tf, deparse_context *context,
512 : : bool showimplicit);
513 : : static void get_from_clause(Query *query, const char *prefix,
514 : : deparse_context *context);
515 : : static void get_from_clause_item(Node *jtnode, Query *query,
516 : : deparse_context *context);
517 : : static void get_rte_alias(RangeTblEntry *rte, int varno, bool use_as,
518 : : deparse_context *context);
519 : : static void get_column_alias_list(deparse_columns *colinfo,
520 : : deparse_context *context);
521 : : static void get_from_clause_coldeflist(RangeTblFunction *rtfunc,
522 : : deparse_columns *colinfo,
523 : : deparse_context *context);
524 : : static void get_tablesample_def(TableSampleClause *tablesample,
525 : : deparse_context *context);
526 : : static void get_opclass_name(Oid opclass, Oid actual_datatype,
527 : : StringInfo buf);
528 : : static Node *processIndirection(Node *node, deparse_context *context);
529 : : static void printSubscripts(SubscriptingRef *sbsref, deparse_context *context);
530 : : static char *get_relation_name(Oid relid);
531 : : static char *generate_relation_name(Oid relid, List *namespaces);
532 : : static char *generate_qualified_relation_name(Oid relid);
533 : : static char *generate_function_name(Oid funcid, int nargs,
534 : : List *argnames, Oid *argtypes,
535 : : bool has_variadic, bool *use_variadic_p,
536 : : bool inGroupBy);
537 : : static char *generate_operator_name(Oid operid, Oid arg1, Oid arg2);
538 : : static void add_cast_to(StringInfo buf, Oid typid);
539 : : static char *generate_qualified_type_name(Oid typid);
540 : : static text *string_to_text(char *str);
541 : : static char *flatten_reloptions(Oid relid);
542 : : void get_reloptions(StringInfo buf, Datum reloptions);
543 : : static void get_json_path_spec(Node *path_spec, deparse_context *context,
544 : : bool showimplicit);
545 : : static void get_json_table_columns(TableFunc *tf, JsonTablePathScan *scan,
546 : : deparse_context *context,
547 : : bool showimplicit);
548 : : static void get_json_table_nested_columns(TableFunc *tf, JsonTablePlan *plan,
549 : : deparse_context *context,
550 : : bool showimplicit,
551 : : bool needcomma);
552 : :
553 : : #define only_marker(rte) ((rte)->inh ? "" : "ONLY ")
554 : :
555 : :
556 : : /* ----------
557 : : * pg_get_ruledef - Do it all and return a text
558 : : * that could be used as a statement
559 : : * to recreate the rule
560 : : * ----------
561 : : */
562 : : Datum
563 : 237 : pg_get_ruledef(PG_FUNCTION_ARGS)
564 : : {
565 : 237 : Oid ruleoid = PG_GETARG_OID(0);
566 : : int prettyFlags;
567 : : char *res;
568 : :
569 : 237 : prettyFlags = PRETTYFLAG_INDENT;
570 : :
571 : 237 : res = pg_get_ruledef_worker(ruleoid, prettyFlags);
572 : :
573 [ + + ]: 237 : if (res == NULL)
574 : 4 : PG_RETURN_NULL();
575 : :
576 : 233 : PG_RETURN_TEXT_P(string_to_text(res));
577 : : }
578 : :
579 : :
580 : : Datum
581 : 76 : pg_get_ruledef_ext(PG_FUNCTION_ARGS)
582 : : {
583 : 76 : Oid ruleoid = PG_GETARG_OID(0);
584 : 76 : bool pretty = PG_GETARG_BOOL(1);
585 : : int prettyFlags;
586 : : char *res;
587 : :
588 [ + - ]: 76 : prettyFlags = GET_PRETTY_FLAGS(pretty);
589 : :
590 : 76 : res = pg_get_ruledef_worker(ruleoid, prettyFlags);
591 : :
592 [ - + ]: 76 : if (res == NULL)
593 : 0 : PG_RETURN_NULL();
594 : :
595 : 76 : PG_RETURN_TEXT_P(string_to_text(res));
596 : : }
597 : :
598 : :
599 : : static char *
600 : 313 : pg_get_ruledef_worker(Oid ruleoid, int prettyFlags)
601 : : {
602 : : Datum args[1];
603 : : char nulls[1];
604 : : int spirc;
605 : : HeapTuple ruletup;
606 : : TupleDesc rulettc;
607 : : StringInfoData buf;
608 : :
609 : : /*
610 : : * Do this first so that string is alloc'd in outer context not SPI's.
611 : : */
612 : 313 : initStringInfo(&buf);
613 : :
614 : : /*
615 : : * Connect to SPI manager
616 : : */
617 : 313 : SPI_connect();
618 : :
619 : : /*
620 : : * On the first call prepare the plan to lookup pg_rewrite. We read
621 : : * pg_rewrite over the SPI manager instead of using the syscache to be
622 : : * checked for read access on pg_rewrite.
623 : : */
624 [ + + ]: 313 : if (plan_getrulebyoid == NULL)
625 : : {
626 : : Oid argtypes[1];
627 : : SPIPlanPtr plan;
628 : :
629 : 24 : argtypes[0] = OIDOID;
630 : 24 : plan = SPI_prepare(query_getrulebyoid, 1, argtypes);
631 [ - + ]: 24 : if (plan == NULL)
632 [ # # ]: 0 : elog(ERROR, "SPI_prepare failed for \"%s\"", query_getrulebyoid);
633 : 24 : SPI_keepplan(plan);
634 : 24 : plan_getrulebyoid = plan;
635 : : }
636 : :
637 : : /*
638 : : * Get the pg_rewrite tuple for this rule
639 : : */
640 : 313 : args[0] = ObjectIdGetDatum(ruleoid);
641 : 313 : nulls[0] = ' ';
642 : 313 : spirc = SPI_execute_plan(plan_getrulebyoid, args, nulls, true, 0);
643 [ - + ]: 313 : if (spirc != SPI_OK_SELECT)
644 [ # # ]: 0 : elog(ERROR, "failed to get pg_rewrite tuple for rule %u", ruleoid);
645 [ + + ]: 313 : if (SPI_processed != 1)
646 : : {
647 : : /*
648 : : * There is no tuple data available here, just keep the output buffer
649 : : * empty.
650 : : */
651 : : }
652 : : else
653 : : {
654 : : /*
655 : : * Get the rule's definition and put it into executor's memory
656 : : */
657 : 309 : ruletup = SPI_tuptable->vals[0];
658 : 309 : rulettc = SPI_tuptable->tupdesc;
659 : 309 : make_ruledef(&buf, ruletup, rulettc, prettyFlags);
660 : : }
661 : :
662 : : /*
663 : : * Disconnect from SPI manager
664 : : */
665 [ - + ]: 313 : if (SPI_finish() != SPI_OK_FINISH)
666 [ # # ]: 0 : elog(ERROR, "SPI_finish failed");
667 : :
668 [ + + ]: 313 : if (buf.len == 0)
669 : 4 : return NULL;
670 : :
671 : 309 : return buf.data;
672 : : }
673 : :
674 : :
675 : : /* ----------
676 : : * pg_get_viewdef - Mainly the same thing, but we
677 : : * only return the SELECT part of a view
678 : : * ----------
679 : : */
680 : : Datum
681 : 1418 : pg_get_viewdef(PG_FUNCTION_ARGS)
682 : : {
683 : : /* By OID */
684 : 1418 : Oid viewoid = PG_GETARG_OID(0);
685 : : int prettyFlags;
686 : : char *res;
687 : :
688 : 1418 : prettyFlags = PRETTYFLAG_INDENT;
689 : :
690 : 1418 : res = pg_get_viewdef_worker(viewoid, prettyFlags, WRAP_COLUMN_DEFAULT);
691 : :
692 [ + + ]: 1418 : if (res == NULL)
693 : 4 : PG_RETURN_NULL();
694 : :
695 : 1414 : PG_RETURN_TEXT_P(string_to_text(res));
696 : : }
697 : :
698 : :
699 : : Datum
700 : 403 : pg_get_viewdef_ext(PG_FUNCTION_ARGS)
701 : : {
702 : : /* By OID */
703 : 403 : Oid viewoid = PG_GETARG_OID(0);
704 : 403 : bool pretty = PG_GETARG_BOOL(1);
705 : : int prettyFlags;
706 : : char *res;
707 : :
708 [ + - ]: 403 : prettyFlags = GET_PRETTY_FLAGS(pretty);
709 : :
710 : 403 : res = pg_get_viewdef_worker(viewoid, prettyFlags, WRAP_COLUMN_DEFAULT);
711 : :
712 [ - + ]: 403 : if (res == NULL)
713 : 0 : PG_RETURN_NULL();
714 : :
715 : 403 : PG_RETURN_TEXT_P(string_to_text(res));
716 : : }
717 : :
718 : : Datum
719 : 4 : pg_get_viewdef_wrap(PG_FUNCTION_ARGS)
720 : : {
721 : : /* By OID */
722 : 4 : Oid viewoid = PG_GETARG_OID(0);
723 : 4 : int wrap = PG_GETARG_INT32(1);
724 : : int prettyFlags;
725 : : char *res;
726 : :
727 : : /* calling this implies we want pretty printing */
728 : 4 : prettyFlags = GET_PRETTY_FLAGS(true);
729 : :
730 : 4 : res = pg_get_viewdef_worker(viewoid, prettyFlags, wrap);
731 : :
732 [ - + ]: 4 : if (res == NULL)
733 : 0 : PG_RETURN_NULL();
734 : :
735 : 4 : PG_RETURN_TEXT_P(string_to_text(res));
736 : : }
737 : :
738 : : Datum
739 : 52 : pg_get_viewdef_name(PG_FUNCTION_ARGS)
740 : : {
741 : : /* By qualified name */
742 : 52 : text *viewname = PG_GETARG_TEXT_PP(0);
743 : : int prettyFlags;
744 : : RangeVar *viewrel;
745 : : Oid viewoid;
746 : : char *res;
747 : :
748 : 52 : prettyFlags = PRETTYFLAG_INDENT;
749 : :
750 : : /* Look up view name. Can't lock it - we might not have privileges. */
751 : 52 : viewrel = makeRangeVarFromNameList(textToQualifiedNameList(viewname));
752 : 52 : viewoid = RangeVarGetRelid(viewrel, NoLock, false);
753 : :
754 : 52 : res = pg_get_viewdef_worker(viewoid, prettyFlags, WRAP_COLUMN_DEFAULT);
755 : :
756 [ - + ]: 52 : if (res == NULL)
757 : 0 : PG_RETURN_NULL();
758 : :
759 : 52 : PG_RETURN_TEXT_P(string_to_text(res));
760 : : }
761 : :
762 : :
763 : : Datum
764 : 268 : pg_get_viewdef_name_ext(PG_FUNCTION_ARGS)
765 : : {
766 : : /* By qualified name */
767 : 268 : text *viewname = PG_GETARG_TEXT_PP(0);
768 : 268 : bool pretty = PG_GETARG_BOOL(1);
769 : : int prettyFlags;
770 : : RangeVar *viewrel;
771 : : Oid viewoid;
772 : : char *res;
773 : :
774 [ + - ]: 268 : prettyFlags = GET_PRETTY_FLAGS(pretty);
775 : :
776 : : /* Look up view name. Can't lock it - we might not have privileges. */
777 : 268 : viewrel = makeRangeVarFromNameList(textToQualifiedNameList(viewname));
778 : 268 : viewoid = RangeVarGetRelid(viewrel, NoLock, false);
779 : :
780 : 268 : res = pg_get_viewdef_worker(viewoid, prettyFlags, WRAP_COLUMN_DEFAULT);
781 : :
782 [ - + ]: 268 : if (res == NULL)
783 : 0 : PG_RETURN_NULL();
784 : :
785 : 268 : PG_RETURN_TEXT_P(string_to_text(res));
786 : : }
787 : :
788 : : /*
789 : : * Common code for by-OID and by-name variants of pg_get_viewdef
790 : : */
791 : : static char *
792 : 2145 : pg_get_viewdef_worker(Oid viewoid, int prettyFlags, int wrapColumn)
793 : : {
794 : : Datum args[2];
795 : : char nulls[2];
796 : : int spirc;
797 : : HeapTuple ruletup;
798 : : TupleDesc rulettc;
799 : : StringInfoData buf;
800 : :
801 : : /*
802 : : * Do this first so that string is alloc'd in outer context not SPI's.
803 : : */
804 : 2145 : initStringInfo(&buf);
805 : :
806 : : /*
807 : : * Connect to SPI manager
808 : : */
809 : 2145 : SPI_connect();
810 : :
811 : : /*
812 : : * On the first call prepare the plan to lookup pg_rewrite. We read
813 : : * pg_rewrite over the SPI manager instead of using the syscache to be
814 : : * checked for read access on pg_rewrite.
815 : : */
816 [ + + ]: 2145 : if (plan_getviewrule == NULL)
817 : : {
818 : : Oid argtypes[2];
819 : : SPIPlanPtr plan;
820 : :
821 : 151 : argtypes[0] = OIDOID;
822 : 151 : argtypes[1] = NAMEOID;
823 : 151 : plan = SPI_prepare(query_getviewrule, 2, argtypes);
824 [ - + ]: 151 : if (plan == NULL)
825 [ # # ]: 0 : elog(ERROR, "SPI_prepare failed for \"%s\"", query_getviewrule);
826 : 151 : SPI_keepplan(plan);
827 : 151 : plan_getviewrule = plan;
828 : : }
829 : :
830 : : /*
831 : : * Get the pg_rewrite tuple for the view's SELECT rule
832 : : */
833 : 2145 : args[0] = ObjectIdGetDatum(viewoid);
834 : 2145 : args[1] = DirectFunctionCall1(namein, CStringGetDatum(ViewSelectRuleName));
835 : 2145 : nulls[0] = ' ';
836 : 2145 : nulls[1] = ' ';
837 : 2145 : spirc = SPI_execute_plan(plan_getviewrule, args, nulls, true, 0);
838 [ - + ]: 2145 : if (spirc != SPI_OK_SELECT)
839 [ # # ]: 0 : elog(ERROR, "failed to get pg_rewrite tuple for view %u", viewoid);
840 [ + + ]: 2145 : if (SPI_processed != 1)
841 : : {
842 : : /*
843 : : * There is no tuple data available here, just keep the output buffer
844 : : * empty.
845 : : */
846 : : }
847 : : else
848 : : {
849 : : /*
850 : : * Get the rule's definition and put it into executor's memory
851 : : */
852 : 2141 : ruletup = SPI_tuptable->vals[0];
853 : 2141 : rulettc = SPI_tuptable->tupdesc;
854 : 2141 : make_viewdef(&buf, ruletup, rulettc, prettyFlags, wrapColumn);
855 : : }
856 : :
857 : : /*
858 : : * Disconnect from SPI manager
859 : : */
860 [ - + ]: 2145 : if (SPI_finish() != SPI_OK_FINISH)
861 [ # # ]: 0 : elog(ERROR, "SPI_finish failed");
862 : :
863 [ + + ]: 2145 : if (buf.len == 0)
864 : 4 : return NULL;
865 : :
866 : 2141 : return buf.data;
867 : : }
868 : :
869 : : /* ----------
870 : : * pg_get_triggerdef - Get the definition of a trigger
871 : : * ----------
872 : : */
873 : : Datum
874 : 96 : pg_get_triggerdef(PG_FUNCTION_ARGS)
875 : : {
876 : 96 : Oid trigid = PG_GETARG_OID(0);
877 : : char *res;
878 : :
879 : 96 : res = pg_get_triggerdef_worker(trigid, false);
880 : :
881 [ + + ]: 96 : if (res == NULL)
882 : 4 : PG_RETURN_NULL();
883 : :
884 : 92 : PG_RETURN_TEXT_P(string_to_text(res));
885 : : }
886 : :
887 : : Datum
888 : 631 : pg_get_triggerdef_ext(PG_FUNCTION_ARGS)
889 : : {
890 : 631 : Oid trigid = PG_GETARG_OID(0);
891 : 631 : bool pretty = PG_GETARG_BOOL(1);
892 : : char *res;
893 : :
894 : 631 : res = pg_get_triggerdef_worker(trigid, pretty);
895 : :
896 [ - + ]: 631 : if (res == NULL)
897 : 0 : PG_RETURN_NULL();
898 : :
899 : 631 : PG_RETURN_TEXT_P(string_to_text(res));
900 : : }
901 : :
902 : : static char *
903 : 727 : pg_get_triggerdef_worker(Oid trigid, bool pretty)
904 : : {
905 : : HeapTuple ht_trig;
906 : : Form_pg_trigger trigrec;
907 : : StringInfoData buf;
908 : : Relation tgrel;
909 : : ScanKeyData skey[1];
910 : : SysScanDesc tgscan;
911 : 727 : int findx = 0;
912 : : char *tgname;
913 : : char *tgoldtable;
914 : : char *tgnewtable;
915 : : Datum value;
916 : : bool isnull;
917 : :
918 : : /*
919 : : * Fetch the pg_trigger tuple by the Oid of the trigger
920 : : */
921 : 727 : tgrel = table_open(TriggerRelationId, AccessShareLock);
922 : :
923 : 727 : ScanKeyInit(&skey[0],
924 : : Anum_pg_trigger_oid,
925 : : BTEqualStrategyNumber, F_OIDEQ,
926 : : ObjectIdGetDatum(trigid));
927 : :
928 : 727 : tgscan = systable_beginscan(tgrel, TriggerOidIndexId, true,
929 : : NULL, 1, skey);
930 : :
931 : 727 : ht_trig = systable_getnext(tgscan);
932 : :
933 [ + + ]: 727 : if (!HeapTupleIsValid(ht_trig))
934 : : {
935 : 4 : systable_endscan(tgscan);
936 : 4 : table_close(tgrel, AccessShareLock);
937 : 4 : return NULL;
938 : : }
939 : :
940 : 723 : trigrec = (Form_pg_trigger) GETSTRUCT(ht_trig);
941 : :
942 : : /*
943 : : * Start the trigger definition. Note that the trigger's name should never
944 : : * be schema-qualified, but the trigger rel's name may be.
945 : : */
946 : 723 : initStringInfo(&buf);
947 : :
948 : 723 : tgname = NameStr(trigrec->tgname);
949 : 1446 : appendStringInfo(&buf, "CREATE %sTRIGGER %s ",
950 [ - + ]: 723 : OidIsValid(trigrec->tgconstraint) ? "CONSTRAINT " : "",
951 : : quote_identifier(tgname));
952 : :
953 [ + + ]: 723 : if (TRIGGER_FOR_BEFORE(trigrec->tgtype))
954 : 263 : appendStringInfoString(&buf, "BEFORE");
955 [ + + ]: 460 : else if (TRIGGER_FOR_AFTER(trigrec->tgtype))
956 : 444 : appendStringInfoString(&buf, "AFTER");
957 [ + - ]: 16 : else if (TRIGGER_FOR_INSTEAD(trigrec->tgtype))
958 : 16 : appendStringInfoString(&buf, "INSTEAD OF");
959 : : else
960 [ # # ]: 0 : elog(ERROR, "unexpected tgtype value: %d", trigrec->tgtype);
961 : :
962 [ + + ]: 723 : if (TRIGGER_FOR_INSERT(trigrec->tgtype))
963 : : {
964 : 488 : appendStringInfoString(&buf, " INSERT");
965 : 488 : findx++;
966 : : }
967 [ + + ]: 723 : if (TRIGGER_FOR_DELETE(trigrec->tgtype))
968 : : {
969 [ + + ]: 113 : if (findx > 0)
970 : 45 : appendStringInfoString(&buf, " OR DELETE");
971 : : else
972 : 68 : appendStringInfoString(&buf, " DELETE");
973 : 113 : findx++;
974 : : }
975 [ + + ]: 723 : if (TRIGGER_FOR_UPDATE(trigrec->tgtype))
976 : : {
977 [ + + ]: 332 : if (findx > 0)
978 : 165 : appendStringInfoString(&buf, " OR UPDATE");
979 : : else
980 : 167 : appendStringInfoString(&buf, " UPDATE");
981 : 332 : findx++;
982 : : /* tgattr is first var-width field, so OK to access directly */
983 [ + + ]: 332 : if (trigrec->tgattr.dim1 > 0)
984 : : {
985 : : int i;
986 : :
987 : 44 : appendStringInfoString(&buf, " OF ");
988 [ + + ]: 97 : for (i = 0; i < trigrec->tgattr.dim1; i++)
989 : : {
990 : : char *attname;
991 : :
992 [ + + ]: 53 : if (i > 0)
993 : 9 : appendStringInfoString(&buf, ", ");
994 : 53 : attname = get_attname(trigrec->tgrelid,
995 : 53 : trigrec->tgattr.values[i], false);
996 : 53 : appendStringInfoString(&buf, quote_identifier(attname));
997 : : }
998 : : }
999 : : }
1000 [ - + ]: 723 : if (TRIGGER_FOR_TRUNCATE(trigrec->tgtype))
1001 : : {
1002 [ # # ]: 0 : if (findx > 0)
1003 : 0 : appendStringInfoString(&buf, " OR TRUNCATE");
1004 : : else
1005 : 0 : appendStringInfoString(&buf, " TRUNCATE");
1006 : 0 : findx++;
1007 : : }
1008 : :
1009 : : /*
1010 : : * In non-pretty mode, always schema-qualify the target table name for
1011 : : * safety. In pretty mode, schema-qualify only if not visible.
1012 : : */
1013 [ + + ]: 1446 : appendStringInfo(&buf, " ON %s ",
1014 : : pretty ?
1015 : 92 : generate_relation_name(trigrec->tgrelid, NIL) :
1016 : 631 : generate_qualified_relation_name(trigrec->tgrelid));
1017 : :
1018 [ - + ]: 723 : if (OidIsValid(trigrec->tgconstraint))
1019 : : {
1020 [ # # ]: 0 : if (OidIsValid(trigrec->tgconstrrelid))
1021 : 0 : appendStringInfo(&buf, "FROM %s ",
1022 : : generate_relation_name(trigrec->tgconstrrelid, NIL));
1023 [ # # ]: 0 : if (!trigrec->tgdeferrable)
1024 : 0 : appendStringInfoString(&buf, "NOT ");
1025 : 0 : appendStringInfoString(&buf, "DEFERRABLE INITIALLY ");
1026 [ # # ]: 0 : if (trigrec->tginitdeferred)
1027 : 0 : appendStringInfoString(&buf, "DEFERRED ");
1028 : : else
1029 : 0 : appendStringInfoString(&buf, "IMMEDIATE ");
1030 : : }
1031 : :
1032 : 723 : value = fastgetattr(ht_trig, Anum_pg_trigger_tgoldtable,
1033 : : tgrel->rd_att, &isnull);
1034 [ + + ]: 723 : if (!isnull)
1035 : 57 : tgoldtable = NameStr(*DatumGetName(value));
1036 : : else
1037 : 666 : tgoldtable = NULL;
1038 : 723 : value = fastgetattr(ht_trig, Anum_pg_trigger_tgnewtable,
1039 : : tgrel->rd_att, &isnull);
1040 [ + + ]: 723 : if (!isnull)
1041 : 62 : tgnewtable = NameStr(*DatumGetName(value));
1042 : : else
1043 : 661 : tgnewtable = NULL;
1044 [ + + + + ]: 723 : if (tgoldtable != NULL || tgnewtable != NULL)
1045 : : {
1046 : 88 : appendStringInfoString(&buf, "REFERENCING ");
1047 [ + + ]: 88 : if (tgoldtable != NULL)
1048 : 57 : appendStringInfo(&buf, "OLD TABLE AS %s ",
1049 : : quote_identifier(tgoldtable));
1050 [ + + ]: 88 : if (tgnewtable != NULL)
1051 : 62 : appendStringInfo(&buf, "NEW TABLE AS %s ",
1052 : : quote_identifier(tgnewtable));
1053 : : }
1054 : :
1055 [ + + ]: 723 : if (TRIGGER_FOR_ROW(trigrec->tgtype))
1056 : 534 : appendStringInfoString(&buf, "FOR EACH ROW ");
1057 : : else
1058 : 189 : appendStringInfoString(&buf, "FOR EACH STATEMENT ");
1059 : :
1060 : : /* If the trigger has a WHEN qualification, add that */
1061 : 723 : value = fastgetattr(ht_trig, Anum_pg_trigger_tgqual,
1062 : : tgrel->rd_att, &isnull);
1063 [ + + ]: 723 : if (!isnull)
1064 : : {
1065 : : Node *qual;
1066 : : char relkind;
1067 : : deparse_context context;
1068 : : deparse_namespace dpns;
1069 : : RangeTblEntry *oldrte;
1070 : : RangeTblEntry *newrte;
1071 : :
1072 : 88 : appendStringInfoString(&buf, "WHEN (");
1073 : :
1074 : 88 : qual = stringToNode(TextDatumGetCString(value));
1075 : :
1076 : 88 : relkind = get_rel_relkind(trigrec->tgrelid);
1077 : :
1078 : : /* Build minimal OLD and NEW RTEs for the rel */
1079 : 88 : oldrte = makeNode(RangeTblEntry);
1080 : 88 : oldrte->rtekind = RTE_RELATION;
1081 : 88 : oldrte->relid = trigrec->tgrelid;
1082 : 88 : oldrte->relkind = relkind;
1083 : 88 : oldrte->rellockmode = AccessShareLock;
1084 : 88 : oldrte->alias = makeAlias("old", NIL);
1085 : 88 : oldrte->eref = oldrte->alias;
1086 : 88 : oldrte->lateral = false;
1087 : 88 : oldrte->inh = false;
1088 : 88 : oldrte->inFromCl = true;
1089 : :
1090 : 88 : newrte = makeNode(RangeTblEntry);
1091 : 88 : newrte->rtekind = RTE_RELATION;
1092 : 88 : newrte->relid = trigrec->tgrelid;
1093 : 88 : newrte->relkind = relkind;
1094 : 88 : newrte->rellockmode = AccessShareLock;
1095 : 88 : newrte->alias = makeAlias("new", NIL);
1096 : 88 : newrte->eref = newrte->alias;
1097 : 88 : newrte->lateral = false;
1098 : 88 : newrte->inh = false;
1099 : 88 : newrte->inFromCl = true;
1100 : :
1101 : : /* Build two-element rtable */
1102 : 88 : memset(&dpns, 0, sizeof(dpns));
1103 : 88 : dpns.rtable = list_make2(oldrte, newrte);
1104 : 88 : dpns.subplans = NIL;
1105 : 88 : dpns.ctes = NIL;
1106 : 88 : dpns.appendrels = NULL;
1107 : 88 : set_rtable_names(&dpns, NIL, NULL);
1108 : 88 : set_simple_column_names(&dpns);
1109 : :
1110 : : /* Set up context with one-deep namespace stack */
1111 : 88 : context.buf = &buf;
1112 : 88 : context.namespaces = list_make1(&dpns);
1113 : 88 : context.resultDesc = NULL;
1114 : 88 : context.targetList = NIL;
1115 : 88 : context.windowClause = NIL;
1116 : 88 : context.varprefix = true;
1117 [ + + ]: 88 : context.prettyFlags = GET_PRETTY_FLAGS(pretty);
1118 : 88 : context.wrapColumn = WRAP_COLUMN_DEFAULT;
1119 : 88 : context.indentLevel = PRETTYINDENT_STD;
1120 : 88 : context.colNamesVisible = true;
1121 : 88 : context.inGroupBy = false;
1122 : 88 : context.varInOrderBy = false;
1123 : 88 : context.appendparents = NULL;
1124 : :
1125 : 88 : get_rule_expr(qual, &context, false);
1126 : :
1127 : 88 : appendStringInfoString(&buf, ") ");
1128 : : }
1129 : :
1130 : 723 : appendStringInfo(&buf, "EXECUTE FUNCTION %s(",
1131 : : generate_function_name(trigrec->tgfoid, 0,
1132 : : NIL, NULL,
1133 : : false, NULL, false));
1134 : :
1135 [ + + ]: 723 : if (trigrec->tgnargs > 0)
1136 : : {
1137 : : char *p;
1138 : : int i;
1139 : :
1140 : 225 : value = fastgetattr(ht_trig, Anum_pg_trigger_tgargs,
1141 : : tgrel->rd_att, &isnull);
1142 [ - + ]: 225 : if (isnull)
1143 [ # # ]: 0 : elog(ERROR, "tgargs is null for trigger %u", trigid);
1144 : 225 : p = (char *) VARDATA_ANY(DatumGetByteaPP(value));
1145 [ + + ]: 460 : for (i = 0; i < trigrec->tgnargs; i++)
1146 : : {
1147 [ + + ]: 235 : if (i > 0)
1148 : 10 : appendStringInfoString(&buf, ", ");
1149 : 235 : simple_quote_literal(&buf, p);
1150 : : /* advance p to next string embedded in tgargs */
1151 [ + + ]: 2825 : while (*p)
1152 : 2590 : p++;
1153 : 235 : p++;
1154 : : }
1155 : : }
1156 : :
1157 : : /* We deliberately do not put semi-colon at end */
1158 : 723 : appendStringInfoChar(&buf, ')');
1159 : :
1160 : : /* Clean up */
1161 : 723 : systable_endscan(tgscan);
1162 : :
1163 : 723 : table_close(tgrel, AccessShareLock);
1164 : :
1165 : 723 : return buf.data;
1166 : : }
1167 : :
1168 : : /* ----------
1169 : : * pg_get_indexdef - Get the definition of an index
1170 : : *
1171 : : * In the extended version, there is a colno argument as well as pretty bool.
1172 : : * if colno == 0, we want a complete index definition.
1173 : : * if colno > 0, we only want the Nth index key's variable or expression.
1174 : : *
1175 : : * Note that the SQL-function versions of this omit any info about the
1176 : : * index tablespace; this is intentional because pg_dump wants it that way.
1177 : : * However pg_get_indexdef_string() includes the index tablespace.
1178 : : * ----------
1179 : : */
1180 : : Datum
1181 : 3042 : pg_get_indexdef(PG_FUNCTION_ARGS)
1182 : : {
1183 : 3042 : Oid indexrelid = PG_GETARG_OID(0);
1184 : : int prettyFlags;
1185 : : char *res;
1186 : :
1187 : 3042 : prettyFlags = PRETTYFLAG_INDENT;
1188 : :
1189 : 3042 : res = pg_get_indexdef_worker(indexrelid, 0, NULL,
1190 : : false, false,
1191 : : false, false,
1192 : : prettyFlags, true);
1193 : :
1194 [ + + ]: 3042 : if (res == NULL)
1195 : 4 : PG_RETURN_NULL();
1196 : :
1197 : 3038 : PG_RETURN_TEXT_P(string_to_text(res));
1198 : : }
1199 : :
1200 : : Datum
1201 : 1375 : pg_get_indexdef_ext(PG_FUNCTION_ARGS)
1202 : : {
1203 : 1375 : Oid indexrelid = PG_GETARG_OID(0);
1204 : 1375 : int32 colno = PG_GETARG_INT32(1);
1205 : 1375 : bool pretty = PG_GETARG_BOOL(2);
1206 : : int prettyFlags;
1207 : : char *res;
1208 : :
1209 [ + - ]: 1375 : prettyFlags = GET_PRETTY_FLAGS(pretty);
1210 : :
1211 : 1375 : res = pg_get_indexdef_worker(indexrelid, colno, NULL,
1212 : : colno != 0, false,
1213 : : false, false,
1214 : : prettyFlags, true);
1215 : :
1216 [ - + ]: 1375 : if (res == NULL)
1217 : 0 : PG_RETURN_NULL();
1218 : :
1219 : 1375 : PG_RETURN_TEXT_P(string_to_text(res));
1220 : : }
1221 : :
1222 : : /*
1223 : : * Internal version for use by ALTER TABLE.
1224 : : * Includes a tablespace clause in the result.
1225 : : * Returns a palloc'd C string; no pretty-printing.
1226 : : */
1227 : : char *
1228 : 179 : pg_get_indexdef_string(Oid indexrelid)
1229 : : {
1230 : 179 : return pg_get_indexdef_worker(indexrelid, 0, NULL,
1231 : : false, false,
1232 : : true, true,
1233 : : 0, false);
1234 : : }
1235 : :
1236 : : /* Internal version that just reports the key-column definitions */
1237 : : char *
1238 : 801 : pg_get_indexdef_columns(Oid indexrelid, bool pretty)
1239 : : {
1240 : : int prettyFlags;
1241 : :
1242 [ + - ]: 801 : prettyFlags = GET_PRETTY_FLAGS(pretty);
1243 : :
1244 : 801 : return pg_get_indexdef_worker(indexrelid, 0, NULL,
1245 : : true, true,
1246 : : false, false,
1247 : : prettyFlags, false);
1248 : : }
1249 : :
1250 : : /* Internal version, extensible with flags to control its behavior */
1251 : : char *
1252 : 4 : pg_get_indexdef_columns_extended(Oid indexrelid, uint16 flags)
1253 : : {
1254 : 4 : bool pretty = ((flags & RULE_INDEXDEF_PRETTY) != 0);
1255 : 4 : bool keys_only = ((flags & RULE_INDEXDEF_KEYS_ONLY) != 0);
1256 : : int prettyFlags;
1257 : :
1258 [ + - ]: 4 : prettyFlags = GET_PRETTY_FLAGS(pretty);
1259 : :
1260 : 4 : return pg_get_indexdef_worker(indexrelid, 0, NULL,
1261 : : true, keys_only,
1262 : : false, false,
1263 : : prettyFlags, false);
1264 : : }
1265 : :
1266 : : /*
1267 : : * Internal workhorse to decompile an index definition.
1268 : : *
1269 : : * This is now used for exclusion constraints as well: if excludeOps is not
1270 : : * NULL then it points to an array of exclusion operator OIDs.
1271 : : */
1272 : : static char *
1273 : 5477 : pg_get_indexdef_worker(Oid indexrelid, int colno,
1274 : : const Oid *excludeOps,
1275 : : bool attrsOnly, bool keysOnly,
1276 : : bool showTblSpc, bool inherits,
1277 : : int prettyFlags, bool missing_ok)
1278 : : {
1279 : : /* might want a separate isConstraint parameter later */
1280 : 5477 : bool isConstraint = (excludeOps != NULL);
1281 : : HeapTuple ht_idx;
1282 : : HeapTuple ht_idxrel;
1283 : : HeapTuple ht_am;
1284 : : Form_pg_index idxrec;
1285 : : Form_pg_class idxrelrec;
1286 : : Form_pg_am amrec;
1287 : : const IndexAmRoutine *amroutine;
1288 : : List *indexprs;
1289 : : ListCell *indexpr_item;
1290 : : List *context;
1291 : : Oid indrelid;
1292 : : int keyno;
1293 : : Datum indcollDatum;
1294 : : Datum indclassDatum;
1295 : : Datum indoptionDatum;
1296 : : oidvector *indcollation;
1297 : : oidvector *indclass;
1298 : : int2vector *indoption;
1299 : : StringInfoData buf;
1300 : : char *str;
1301 : : char *sep;
1302 : :
1303 : : /*
1304 : : * Fetch the pg_index tuple by the Oid of the index
1305 : : */
1306 : 5477 : ht_idx = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexrelid));
1307 [ + + ]: 5477 : if (!HeapTupleIsValid(ht_idx))
1308 : : {
1309 [ + - ]: 4 : if (missing_ok)
1310 : 4 : return NULL;
1311 [ # # ]: 0 : elog(ERROR, "cache lookup failed for index %u", indexrelid);
1312 : : }
1313 : 5473 : idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
1314 : :
1315 : 5473 : indrelid = idxrec->indrelid;
1316 : : Assert(indexrelid == idxrec->indexrelid);
1317 : :
1318 : : /* Must get indcollation, indclass, and indoption the hard way */
1319 : 5473 : indcollDatum = SysCacheGetAttrNotNull(INDEXRELID, ht_idx,
1320 : : Anum_pg_index_indcollation);
1321 : 5473 : indcollation = (oidvector *) DatumGetPointer(indcollDatum);
1322 : :
1323 : 5473 : indclassDatum = SysCacheGetAttrNotNull(INDEXRELID, ht_idx,
1324 : : Anum_pg_index_indclass);
1325 : 5473 : indclass = (oidvector *) DatumGetPointer(indclassDatum);
1326 : :
1327 : 5473 : indoptionDatum = SysCacheGetAttrNotNull(INDEXRELID, ht_idx,
1328 : : Anum_pg_index_indoption);
1329 : 5473 : indoption = (int2vector *) DatumGetPointer(indoptionDatum);
1330 : :
1331 : : /*
1332 : : * Fetch the pg_class tuple of the index relation
1333 : : */
1334 : 5473 : ht_idxrel = SearchSysCache1(RELOID, ObjectIdGetDatum(indexrelid));
1335 [ - + ]: 5473 : if (!HeapTupleIsValid(ht_idxrel))
1336 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", indexrelid);
1337 : 5473 : idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
1338 : :
1339 : : /*
1340 : : * Fetch the pg_am tuple of the index' access method
1341 : : */
1342 : 5473 : ht_am = SearchSysCache1(AMOID, ObjectIdGetDatum(idxrelrec->relam));
1343 [ - + ]: 5473 : if (!HeapTupleIsValid(ht_am))
1344 [ # # ]: 0 : elog(ERROR, "cache lookup failed for access method %u",
1345 : : idxrelrec->relam);
1346 : 5473 : amrec = (Form_pg_am) GETSTRUCT(ht_am);
1347 : :
1348 : : /* Fetch the index AM's API struct */
1349 : 5473 : amroutine = GetIndexAmRoutine(amrec->amhandler);
1350 : :
1351 : : /*
1352 : : * Get the index expressions, if any. (NOTE: we do not use the relcache
1353 : : * versions of the expressions and predicate, because we want to display
1354 : : * non-const-folded expressions.)
1355 : : */
1356 [ + + ]: 5473 : if (!heap_attisnull(ht_idx, Anum_pg_index_indexprs, NULL))
1357 : : {
1358 : : Datum exprsDatum;
1359 : : char *exprsString;
1360 : :
1361 : 430 : exprsDatum = SysCacheGetAttrNotNull(INDEXRELID, ht_idx,
1362 : : Anum_pg_index_indexprs);
1363 : 430 : exprsString = TextDatumGetCString(exprsDatum);
1364 : 430 : indexprs = (List *) stringToNode(exprsString);
1365 : 430 : pfree(exprsString);
1366 : : }
1367 : : else
1368 : 5043 : indexprs = NIL;
1369 : :
1370 : 5473 : indexpr_item = list_head(indexprs);
1371 : :
1372 : 5473 : context = deparse_context_for(get_relation_name(indrelid), indrelid);
1373 : :
1374 : : /*
1375 : : * Start the index definition. Note that the index's name should never be
1376 : : * schema-qualified, but the indexed rel's name may be.
1377 : : */
1378 : 5473 : initStringInfo(&buf);
1379 : :
1380 [ + + ]: 5473 : if (!attrsOnly)
1381 : : {
1382 [ + + ]: 4358 : if (!isConstraint)
1383 : 8564 : appendStringInfo(&buf, "CREATE %sINDEX %s ON %s%s USING %s (",
1384 [ + + ]: 4282 : idxrec->indisunique ? "UNIQUE " : "",
1385 : 4282 : quote_identifier(NameStr(idxrelrec->relname)),
1386 [ + + ]: 4282 : idxrelrec->relkind == RELKIND_PARTITIONED_INDEX
1387 [ + + ]: 414 : && !inherits ? "ONLY " : "",
1388 [ + + ]: 4282 : (prettyFlags & PRETTYFLAG_SCHEMA) ?
1389 : 1065 : generate_relation_name(indrelid, NIL) :
1390 : 3217 : generate_qualified_relation_name(indrelid),
1391 : 4282 : quote_identifier(NameStr(amrec->amname)));
1392 : : else /* currently, must be EXCLUDE constraint */
1393 : 76 : appendStringInfo(&buf, "EXCLUDE USING %s (",
1394 : 76 : quote_identifier(NameStr(amrec->amname)));
1395 : : }
1396 : :
1397 : : /*
1398 : : * Report the indexed attributes
1399 : : */
1400 : 5473 : sep = "";
1401 [ + + ]: 13622 : for (keyno = 0; keyno < idxrec->indnatts; keyno++)
1402 : : {
1403 : 8214 : AttrNumber attnum = idxrec->indkey.values[keyno];
1404 : : Oid keycoltype;
1405 : : Oid keycolcollation;
1406 : :
1407 : : /*
1408 : : * Ignore non-key attributes if told to.
1409 : : */
1410 [ + + + + ]: 8214 : if (keysOnly && keyno >= idxrec->indnkeyatts)
1411 : 65 : break;
1412 : :
1413 : : /* Otherwise, print INCLUDE to divide key and non-key attrs. */
1414 [ + + + + ]: 8149 : if (!colno && keyno == idxrec->indnkeyatts)
1415 : : {
1416 : 148 : appendStringInfoString(&buf, ") INCLUDE (");
1417 : 148 : sep = "";
1418 : : }
1419 : :
1420 [ + + ]: 8149 : if (!colno)
1421 : 7723 : appendStringInfoString(&buf, sep);
1422 : 8149 : sep = ", ";
1423 : :
1424 [ + + ]: 8149 : if (attnum != 0)
1425 : : {
1426 : : /* Simple index column */
1427 : : char *attname;
1428 : : int32 keycoltypmod;
1429 : :
1430 : 7636 : attname = get_attname(indrelid, attnum, false);
1431 [ + + + + ]: 7636 : if (!colno || colno == keyno + 1)
1432 : 7528 : appendStringInfoString(&buf, quote_identifier(attname));
1433 : 7636 : get_atttypetypmodcoll(indrelid, attnum,
1434 : : &keycoltype, &keycoltypmod,
1435 : : &keycolcollation);
1436 : : }
1437 : : else
1438 : : {
1439 : : /* expressional index */
1440 : : Node *indexkey;
1441 : :
1442 [ - + ]: 513 : if (indexpr_item == NULL)
1443 [ # # ]: 0 : elog(ERROR, "too few entries in indexprs list");
1444 : 513 : indexkey = (Node *) lfirst(indexpr_item);
1445 : 513 : indexpr_item = lnext(indexprs, indexpr_item);
1446 : : /* Deparse */
1447 : 513 : str = deparse_expression_pretty(indexkey, context, false, false,
1448 : : prettyFlags, 0);
1449 [ + + + + ]: 513 : if (!colno || colno == keyno + 1)
1450 : : {
1451 : : /* Need parens if it's not a bare function call */
1452 [ + + ]: 505 : if (looks_like_function(indexkey))
1453 : 33 : appendStringInfoString(&buf, str);
1454 : : else
1455 : 472 : appendStringInfo(&buf, "(%s)", str);
1456 : : }
1457 : 513 : keycoltype = exprType(indexkey);
1458 : 513 : keycolcollation = exprCollation(indexkey);
1459 : : }
1460 : :
1461 : : /* Print additional decoration for (selected) key columns */
1462 [ + + + + : 8149 : if (!attrsOnly && keyno < idxrec->indnkeyatts &&
- + ]
1463 [ # # ]: 0 : (!colno || colno == keyno + 1))
1464 : : {
1465 : 6374 : int16 opt = indoption->values[keyno];
1466 : 6374 : Oid indcoll = indcollation->values[keyno];
1467 : 6374 : Datum attoptions = get_attoptions(indexrelid, keyno + 1);
1468 : 6374 : bool has_options = attoptions != (Datum) 0;
1469 : :
1470 : : /* Add collation, if not default for column */
1471 [ + + + + ]: 6374 : if (OidIsValid(indcoll) && indcoll != keycolcollation)
1472 : 62 : appendStringInfo(&buf, " COLLATE %s",
1473 : : generate_collation_name((indcoll)));
1474 : :
1475 : : /* Add the operator class name, if not default */
1476 [ + + ]: 6374 : get_opclass_name(indclass->values[keyno],
1477 : : has_options ? InvalidOid : keycoltype, &buf);
1478 : :
1479 [ + + ]: 6374 : if (has_options)
1480 : : {
1481 : 22 : appendStringInfoString(&buf, " (");
1482 : 22 : get_reloptions(&buf, attoptions);
1483 : 22 : appendStringInfoChar(&buf, ')');
1484 : : }
1485 : :
1486 : : /* Add options if relevant */
1487 [ + + ]: 6374 : if (amroutine->amcanorder)
1488 : : {
1489 : : /* if it supports sort ordering, report DESC and NULLS opts */
1490 [ - + ]: 5194 : if (opt & INDOPTION_DESC)
1491 : : {
1492 : 0 : appendStringInfoString(&buf, " DESC");
1493 : : /* NULLS FIRST is the default in this case */
1494 [ # # ]: 0 : if (!(opt & INDOPTION_NULLS_FIRST))
1495 : 0 : appendStringInfoString(&buf, " NULLS LAST");
1496 : : }
1497 : : else
1498 : : {
1499 [ - + ]: 5194 : if (opt & INDOPTION_NULLS_FIRST)
1500 : 0 : appendStringInfoString(&buf, " NULLS FIRST");
1501 : : }
1502 : : }
1503 : :
1504 : : /* Add the exclusion operator if relevant */
1505 [ + + ]: 6374 : if (excludeOps != NULL)
1506 : 96 : appendStringInfo(&buf, " WITH %s",
1507 : 96 : generate_operator_name(excludeOps[keyno],
1508 : : keycoltype,
1509 : : keycoltype));
1510 : : }
1511 : : }
1512 : :
1513 [ + + ]: 5473 : if (!attrsOnly)
1514 : : {
1515 : 4358 : appendStringInfoChar(&buf, ')');
1516 : :
1517 [ + + ]: 4358 : if (idxrec->indnullsnotdistinct)
1518 : 8 : appendStringInfoString(&buf, " NULLS NOT DISTINCT");
1519 : :
1520 : : /*
1521 : : * If it has options, append "WITH (options)"
1522 : : */
1523 : 4358 : str = flatten_reloptions(indexrelid);
1524 [ + + ]: 4358 : if (str)
1525 : : {
1526 : 105 : appendStringInfo(&buf, " WITH (%s)", str);
1527 : 105 : pfree(str);
1528 : : }
1529 : :
1530 : : /*
1531 : : * Print tablespace, but only if requested
1532 : : */
1533 [ + + ]: 4358 : if (showTblSpc)
1534 : : {
1535 : : Oid tblspc;
1536 : :
1537 : 179 : tblspc = get_rel_tablespace(indexrelid);
1538 [ + + ]: 179 : if (OidIsValid(tblspc))
1539 : : {
1540 [ - + ]: 36 : if (isConstraint)
1541 : 0 : appendStringInfoString(&buf, " USING INDEX");
1542 : 36 : appendStringInfo(&buf, " TABLESPACE %s",
1543 : 36 : quote_identifier(get_tablespace_name(tblspc)));
1544 : : }
1545 : : }
1546 : :
1547 : : /*
1548 : : * If it's a partial index, decompile and append the predicate
1549 : : */
1550 [ + + ]: 4358 : if (!heap_attisnull(ht_idx, Anum_pg_index_indpred, NULL))
1551 : : {
1552 : : Node *node;
1553 : : Datum predDatum;
1554 : : char *predString;
1555 : :
1556 : : /* Convert text string to node tree */
1557 : 234 : predDatum = SysCacheGetAttrNotNull(INDEXRELID, ht_idx,
1558 : : Anum_pg_index_indpred);
1559 : 234 : predString = TextDatumGetCString(predDatum);
1560 : 234 : node = (Node *) stringToNode(predString);
1561 : 234 : pfree(predString);
1562 : :
1563 : : /* Deparse */
1564 : 234 : str = deparse_expression_pretty(node, context, false, false,
1565 : : prettyFlags, 0);
1566 [ + + ]: 234 : if (isConstraint)
1567 : 28 : appendStringInfo(&buf, " WHERE (%s)", str);
1568 : : else
1569 : 206 : appendStringInfo(&buf, " WHERE %s", str);
1570 : : }
1571 : : }
1572 : :
1573 : : /* Clean up */
1574 : 5473 : ReleaseSysCache(ht_idx);
1575 : 5473 : ReleaseSysCache(ht_idxrel);
1576 : 5473 : ReleaseSysCache(ht_am);
1577 : :
1578 : 5473 : return buf.data;
1579 : : }
1580 : :
1581 : : /* ----------
1582 : : * pg_get_querydef
1583 : : *
1584 : : * Public entry point to deparse one query parsetree.
1585 : : * The pretty flags are determined by GET_PRETTY_FLAGS(pretty).
1586 : : *
1587 : : * The result is a palloc'd C string.
1588 : : * ----------
1589 : : */
1590 : : char *
1591 : 0 : pg_get_querydef(Query *query, bool pretty)
1592 : : {
1593 : : StringInfoData buf;
1594 : : int prettyFlags;
1595 : :
1596 [ # # ]: 0 : prettyFlags = GET_PRETTY_FLAGS(pretty);
1597 : :
1598 : 0 : initStringInfo(&buf);
1599 : :
1600 : 0 : get_query_def(query, &buf, NIL, NULL, true,
1601 : : prettyFlags, WRAP_COLUMN_DEFAULT, 0);
1602 : :
1603 : 0 : return buf.data;
1604 : : }
1605 : :
1606 : : /*
1607 : : * pg_get_statisticsobjdef
1608 : : * Get the definition of an extended statistics object
1609 : : */
1610 : : Datum
1611 : 163 : pg_get_statisticsobjdef(PG_FUNCTION_ARGS)
1612 : : {
1613 : 163 : Oid statextid = PG_GETARG_OID(0);
1614 : : char *res;
1615 : :
1616 : 163 : res = pg_get_statisticsobj_worker(statextid, false, true);
1617 : :
1618 [ + + ]: 163 : if (res == NULL)
1619 : 4 : PG_RETURN_NULL();
1620 : :
1621 : 159 : PG_RETURN_TEXT_P(string_to_text(res));
1622 : : }
1623 : :
1624 : : /*
1625 : : * Internal version for use by ALTER TABLE.
1626 : : * Returns a palloc'd C string; no pretty-printing.
1627 : : */
1628 : : char *
1629 : 57 : pg_get_statisticsobjdef_string(Oid statextid)
1630 : : {
1631 : 57 : return pg_get_statisticsobj_worker(statextid, false, false);
1632 : : }
1633 : :
1634 : : /*
1635 : : * pg_get_statisticsobjdef_columns
1636 : : * Get columns and expressions for an extended statistics object
1637 : : */
1638 : : Datum
1639 : 276 : pg_get_statisticsobjdef_columns(PG_FUNCTION_ARGS)
1640 : : {
1641 : 276 : Oid statextid = PG_GETARG_OID(0);
1642 : : char *res;
1643 : :
1644 : 276 : res = pg_get_statisticsobj_worker(statextid, true, true);
1645 : :
1646 [ - + ]: 276 : if (res == NULL)
1647 : 0 : PG_RETURN_NULL();
1648 : :
1649 : 276 : PG_RETURN_TEXT_P(string_to_text(res));
1650 : : }
1651 : :
1652 : : /*
1653 : : * Internal workhorse to decompile an extended statistics object.
1654 : : */
1655 : : static char *
1656 : 496 : pg_get_statisticsobj_worker(Oid statextid, bool columns_only, bool missing_ok)
1657 : : {
1658 : : Form_pg_statistic_ext statextrec;
1659 : : HeapTuple statexttup;
1660 : : StringInfoData buf;
1661 : : int colno;
1662 : : char *nsp;
1663 : : ArrayType *arr;
1664 : : char *enabled;
1665 : : Datum datum;
1666 : : bool ndistinct_enabled;
1667 : : bool dependencies_enabled;
1668 : : bool mcv_enabled;
1669 : : int i;
1670 : : List *context;
1671 : : ListCell *lc;
1672 : 496 : List *exprs = NIL;
1673 : : bool has_exprs;
1674 : : int ncolumns;
1675 : :
1676 : 496 : statexttup = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(statextid));
1677 : :
1678 [ + + ]: 496 : if (!HeapTupleIsValid(statexttup))
1679 : : {
1680 [ + - ]: 4 : if (missing_ok)
1681 : 4 : return NULL;
1682 [ # # ]: 0 : elog(ERROR, "cache lookup failed for statistics object %u", statextid);
1683 : : }
1684 : :
1685 : : /* has the statistics expressions? */
1686 : 492 : has_exprs = !heap_attisnull(statexttup, Anum_pg_statistic_ext_stxexprs, NULL);
1687 : :
1688 : 492 : statextrec = (Form_pg_statistic_ext) GETSTRUCT(statexttup);
1689 : :
1690 : : /*
1691 : : * Get the statistics expressions, if any. (NOTE: we do not use the
1692 : : * relcache versions of the expressions, because we want to display
1693 : : * non-const-folded expressions.)
1694 : : */
1695 [ + + ]: 492 : if (has_exprs)
1696 : : {
1697 : : Datum exprsDatum;
1698 : : char *exprsString;
1699 : :
1700 : 129 : exprsDatum = SysCacheGetAttrNotNull(STATEXTOID, statexttup,
1701 : : Anum_pg_statistic_ext_stxexprs);
1702 : 129 : exprsString = TextDatumGetCString(exprsDatum);
1703 : 129 : exprs = (List *) stringToNode(exprsString);
1704 : 129 : pfree(exprsString);
1705 : : }
1706 : : else
1707 : 363 : exprs = NIL;
1708 : :
1709 : : /* count the number of columns (attributes and expressions) */
1710 : 492 : ncolumns = statextrec->stxkeys.dim1 + list_length(exprs);
1711 : :
1712 : 492 : initStringInfo(&buf);
1713 : :
1714 [ + + ]: 492 : if (!columns_only)
1715 : : {
1716 : 216 : nsp = get_namespace_name_or_temp(statextrec->stxnamespace);
1717 : 216 : appendStringInfo(&buf, "CREATE STATISTICS %s",
1718 : : quote_qualified_identifier(nsp,
1719 : 216 : NameStr(statextrec->stxname)));
1720 : :
1721 : : /*
1722 : : * Decode the stxkind column so that we know which stats types to
1723 : : * print.
1724 : : */
1725 : 216 : datum = SysCacheGetAttrNotNull(STATEXTOID, statexttup,
1726 : : Anum_pg_statistic_ext_stxkind);
1727 : 216 : arr = DatumGetArrayTypeP(datum);
1728 [ + - ]: 216 : if (ARR_NDIM(arr) != 1 ||
1729 [ + - ]: 216 : ARR_HASNULL(arr) ||
1730 [ - + ]: 216 : ARR_ELEMTYPE(arr) != CHAROID)
1731 [ # # ]: 0 : elog(ERROR, "stxkind is not a 1-D char array");
1732 [ - + ]: 216 : enabled = (char *) ARR_DATA_PTR(arr);
1733 : :
1734 : 216 : ndistinct_enabled = false;
1735 : 216 : dependencies_enabled = false;
1736 : 216 : mcv_enabled = false;
1737 : :
1738 [ + + ]: 685 : for (i = 0; i < ARR_DIMS(arr)[0]; i++)
1739 : : {
1740 [ + + ]: 469 : if (enabled[i] == STATS_EXT_NDISTINCT)
1741 : 141 : ndistinct_enabled = true;
1742 [ + + ]: 328 : else if (enabled[i] == STATS_EXT_DEPENDENCIES)
1743 : 117 : dependencies_enabled = true;
1744 [ + + ]: 211 : else if (enabled[i] == STATS_EXT_MCV)
1745 : 126 : mcv_enabled = true;
1746 : :
1747 : : /* ignore STATS_EXT_EXPRESSIONS (it's built automatically) */
1748 : : }
1749 : :
1750 : : /*
1751 : : * If any option is disabled, then we'll need to append the types
1752 : : * clause to show which options are enabled. We omit the types clause
1753 : : * on purpose when all options are enabled, so a pg_dump/pg_restore
1754 : : * will create all statistics types on a newer postgres version, if
1755 : : * the statistics had all options enabled on the original version.
1756 : : *
1757 : : * But if the statistics is defined on just a single column, it has to
1758 : : * be an expression statistics. In that case we don't need to specify
1759 : : * kinds.
1760 : : */
1761 [ + + + + : 216 : if ((!ndistinct_enabled || !dependencies_enabled || !mcv_enabled) &&
- + + + ]
1762 : : (ncolumns > 1))
1763 : : {
1764 : 63 : bool gotone = false;
1765 : :
1766 : 63 : appendStringInfoString(&buf, " (");
1767 : :
1768 [ + + ]: 63 : if (ndistinct_enabled)
1769 : : {
1770 : 34 : appendStringInfoString(&buf, "ndistinct");
1771 : 34 : gotone = true;
1772 : : }
1773 : :
1774 [ + + ]: 63 : if (dependencies_enabled)
1775 : : {
1776 [ - + ]: 10 : appendStringInfo(&buf, "%sdependencies", gotone ? ", " : "");
1777 : 10 : gotone = true;
1778 : : }
1779 : :
1780 [ + + ]: 63 : if (mcv_enabled)
1781 [ - + ]: 19 : appendStringInfo(&buf, "%smcv", gotone ? ", " : "");
1782 : :
1783 : 63 : appendStringInfoChar(&buf, ')');
1784 : : }
1785 : :
1786 : 216 : appendStringInfoString(&buf, " ON ");
1787 : : }
1788 : :
1789 : : /* decode simple column references */
1790 [ + + ]: 1399 : for (colno = 0; colno < statextrec->stxkeys.dim1; colno++)
1791 : : {
1792 : 907 : AttrNumber attnum = statextrec->stxkeys.values[colno];
1793 : : char *attname;
1794 : :
1795 [ + + ]: 907 : if (colno > 0)
1796 : 502 : appendStringInfoString(&buf, ", ");
1797 : :
1798 : 907 : attname = get_attname(statextrec->stxrelid, attnum, false);
1799 : :
1800 : 907 : appendStringInfoString(&buf, quote_identifier(attname));
1801 : : }
1802 : :
1803 : 492 : context = deparse_context_for(get_relation_name(statextrec->stxrelid),
1804 : : statextrec->stxrelid);
1805 : :
1806 [ + + + + : 675 : foreach(lc, exprs)
+ + ]
1807 : : {
1808 : 183 : Node *expr = (Node *) lfirst(lc);
1809 : : char *str;
1810 : 183 : int prettyFlags = PRETTYFLAG_PAREN;
1811 : :
1812 : 183 : str = deparse_expression_pretty(expr, context, false, false,
1813 : : prettyFlags, 0);
1814 : :
1815 [ + + ]: 183 : if (colno > 0)
1816 : 96 : appendStringInfoString(&buf, ", ");
1817 : :
1818 : : /* Need parens if it's not a bare function call */
1819 [ + + ]: 183 : if (looks_like_function(expr))
1820 : 21 : appendStringInfoString(&buf, str);
1821 : : else
1822 : 162 : appendStringInfo(&buf, "(%s)", str);
1823 : :
1824 : 183 : colno++;
1825 : : }
1826 : :
1827 [ + + ]: 492 : if (!columns_only)
1828 : 216 : appendStringInfo(&buf, " FROM %s",
1829 : : generate_relation_name(statextrec->stxrelid, NIL));
1830 : :
1831 : 492 : ReleaseSysCache(statexttup);
1832 : :
1833 : 492 : return buf.data;
1834 : : }
1835 : :
1836 : : /*
1837 : : * Generate text array of expressions for statistics object.
1838 : : */
1839 : : Datum
1840 : 128 : pg_get_statisticsobjdef_expressions(PG_FUNCTION_ARGS)
1841 : : {
1842 : 128 : Oid statextid = PG_GETARG_OID(0);
1843 : : Form_pg_statistic_ext statextrec;
1844 : : HeapTuple statexttup;
1845 : : Datum datum;
1846 : : List *context;
1847 : : ListCell *lc;
1848 : 128 : List *exprs = NIL;
1849 : : bool has_exprs;
1850 : : char *tmp;
1851 : 128 : ArrayBuildState *astate = NULL;
1852 : :
1853 : 128 : statexttup = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(statextid));
1854 : :
1855 [ - + ]: 128 : if (!HeapTupleIsValid(statexttup))
1856 : 0 : PG_RETURN_NULL();
1857 : :
1858 : : /* Does the stats object have expressions? */
1859 : 128 : has_exprs = !heap_attisnull(statexttup, Anum_pg_statistic_ext_stxexprs, NULL);
1860 : :
1861 : : /* no expressions? we're done */
1862 [ + + ]: 128 : if (!has_exprs)
1863 : : {
1864 : 11 : ReleaseSysCache(statexttup);
1865 : 11 : PG_RETURN_NULL();
1866 : : }
1867 : :
1868 : 117 : statextrec = (Form_pg_statistic_ext) GETSTRUCT(statexttup);
1869 : :
1870 : : /*
1871 : : * Get the statistics expressions, and deparse them into text values.
1872 : : */
1873 : 117 : datum = SysCacheGetAttrNotNull(STATEXTOID, statexttup,
1874 : : Anum_pg_statistic_ext_stxexprs);
1875 : 117 : tmp = TextDatumGetCString(datum);
1876 : 117 : exprs = (List *) stringToNode(tmp);
1877 : 117 : pfree(tmp);
1878 : :
1879 : 117 : context = deparse_context_for(get_relation_name(statextrec->stxrelid),
1880 : : statextrec->stxrelid);
1881 : :
1882 [ + - + + : 280 : foreach(lc, exprs)
+ + ]
1883 : : {
1884 : 163 : Node *expr = (Node *) lfirst(lc);
1885 : : char *str;
1886 : 163 : int prettyFlags = PRETTYFLAG_INDENT;
1887 : :
1888 : 163 : str = deparse_expression_pretty(expr, context, false, false,
1889 : : prettyFlags, 0);
1890 : :
1891 : 163 : astate = accumArrayResult(astate,
1892 : 163 : PointerGetDatum(cstring_to_text(str)),
1893 : : false,
1894 : : TEXTOID,
1895 : : CurrentMemoryContext);
1896 : : }
1897 : :
1898 : 117 : ReleaseSysCache(statexttup);
1899 : :
1900 : 117 : PG_RETURN_DATUM(makeArrayResult(astate, CurrentMemoryContext));
1901 : : }
1902 : :
1903 : : /*
1904 : : * pg_get_partkeydef
1905 : : *
1906 : : * Returns the partition key specification, ie, the following:
1907 : : *
1908 : : * { RANGE | LIST | HASH } (column opt_collation opt_opclass [, ...])
1909 : : */
1910 : : Datum
1911 : 813 : pg_get_partkeydef(PG_FUNCTION_ARGS)
1912 : : {
1913 : 813 : Oid relid = PG_GETARG_OID(0);
1914 : : char *res;
1915 : :
1916 : 813 : res = pg_get_partkeydef_worker(relid, PRETTYFLAG_INDENT, false, true);
1917 : :
1918 [ + + ]: 813 : if (res == NULL)
1919 : 4 : PG_RETURN_NULL();
1920 : :
1921 : 809 : PG_RETURN_TEXT_P(string_to_text(res));
1922 : : }
1923 : :
1924 : : /* Internal version that just reports the column definitions */
1925 : : char *
1926 : 94 : pg_get_partkeydef_columns(Oid relid, bool pretty)
1927 : : {
1928 : : int prettyFlags;
1929 : :
1930 [ + - ]: 94 : prettyFlags = GET_PRETTY_FLAGS(pretty);
1931 : :
1932 : 94 : return pg_get_partkeydef_worker(relid, prettyFlags, true, false);
1933 : : }
1934 : :
1935 : : /*
1936 : : * Internal workhorse to decompile a partition key definition.
1937 : : */
1938 : : static char *
1939 : 907 : pg_get_partkeydef_worker(Oid relid, int prettyFlags,
1940 : : bool attrsOnly, bool missing_ok)
1941 : : {
1942 : : Form_pg_partitioned_table form;
1943 : : HeapTuple tuple;
1944 : : oidvector *partclass;
1945 : : oidvector *partcollation;
1946 : : List *partexprs;
1947 : : ListCell *partexpr_item;
1948 : : List *context;
1949 : : Datum datum;
1950 : : StringInfoData buf;
1951 : : int keyno;
1952 : : char *str;
1953 : : char *sep;
1954 : :
1955 : 907 : tuple = SearchSysCache1(PARTRELID, ObjectIdGetDatum(relid));
1956 [ + + ]: 907 : if (!HeapTupleIsValid(tuple))
1957 : : {
1958 [ + - ]: 4 : if (missing_ok)
1959 : 4 : return NULL;
1960 [ # # ]: 0 : elog(ERROR, "cache lookup failed for partition key of %u", relid);
1961 : : }
1962 : :
1963 : 903 : form = (Form_pg_partitioned_table) GETSTRUCT(tuple);
1964 : :
1965 : : Assert(form->partrelid == relid);
1966 : :
1967 : : /* Must get partclass and partcollation the hard way */
1968 : 903 : datum = SysCacheGetAttrNotNull(PARTRELID, tuple,
1969 : : Anum_pg_partitioned_table_partclass);
1970 : 903 : partclass = (oidvector *) DatumGetPointer(datum);
1971 : :
1972 : 903 : datum = SysCacheGetAttrNotNull(PARTRELID, tuple,
1973 : : Anum_pg_partitioned_table_partcollation);
1974 : 903 : partcollation = (oidvector *) DatumGetPointer(datum);
1975 : :
1976 : :
1977 : : /*
1978 : : * Get the expressions, if any. (NOTE: we do not use the relcache
1979 : : * versions of the expressions, because we want to display
1980 : : * non-const-folded expressions.)
1981 : : */
1982 [ + + ]: 903 : if (!heap_attisnull(tuple, Anum_pg_partitioned_table_partexprs, NULL))
1983 : : {
1984 : : Datum exprsDatum;
1985 : : char *exprsString;
1986 : :
1987 : 84 : exprsDatum = SysCacheGetAttrNotNull(PARTRELID, tuple,
1988 : : Anum_pg_partitioned_table_partexprs);
1989 : 84 : exprsString = TextDatumGetCString(exprsDatum);
1990 : 84 : partexprs = (List *) stringToNode(exprsString);
1991 : :
1992 [ - + ]: 84 : if (!IsA(partexprs, List))
1993 [ # # ]: 0 : elog(ERROR, "unexpected node type found in partexprs: %d",
1994 : : (int) nodeTag(partexprs));
1995 : :
1996 : 84 : pfree(exprsString);
1997 : : }
1998 : : else
1999 : 819 : partexprs = NIL;
2000 : :
2001 : 903 : partexpr_item = list_head(partexprs);
2002 : 903 : context = deparse_context_for(get_relation_name(relid), relid);
2003 : :
2004 : 903 : initStringInfo(&buf);
2005 : :
2006 [ + + + - ]: 903 : switch (form->partstrat)
2007 : : {
2008 : 61 : case PARTITION_STRATEGY_HASH:
2009 [ + - ]: 61 : if (!attrsOnly)
2010 : 61 : appendStringInfoString(&buf, "HASH");
2011 : 61 : break;
2012 : 339 : case PARTITION_STRATEGY_LIST:
2013 [ + + ]: 339 : if (!attrsOnly)
2014 : 313 : appendStringInfoString(&buf, "LIST");
2015 : 339 : break;
2016 : 503 : case PARTITION_STRATEGY_RANGE:
2017 [ + + ]: 503 : if (!attrsOnly)
2018 : 435 : appendStringInfoString(&buf, "RANGE");
2019 : 503 : break;
2020 : 0 : default:
2021 [ # # ]: 0 : elog(ERROR, "unexpected partition strategy: %d",
2022 : : (int) form->partstrat);
2023 : : }
2024 : :
2025 [ + + ]: 903 : if (!attrsOnly)
2026 : 809 : appendStringInfoString(&buf, " (");
2027 : 903 : sep = "";
2028 [ + + ]: 1899 : for (keyno = 0; keyno < form->partnatts; keyno++)
2029 : : {
2030 : 996 : AttrNumber attnum = form->partattrs.values[keyno];
2031 : : Oid keycoltype;
2032 : : Oid keycolcollation;
2033 : : Oid partcoll;
2034 : :
2035 : 996 : appendStringInfoString(&buf, sep);
2036 : 996 : sep = ", ";
2037 [ + + ]: 996 : if (attnum != 0)
2038 : : {
2039 : : /* Simple attribute reference */
2040 : : char *attname;
2041 : : int32 keycoltypmod;
2042 : :
2043 : 904 : attname = get_attname(relid, attnum, false);
2044 : 904 : appendStringInfoString(&buf, quote_identifier(attname));
2045 : 904 : get_atttypetypmodcoll(relid, attnum,
2046 : : &keycoltype, &keycoltypmod,
2047 : : &keycolcollation);
2048 : : }
2049 : : else
2050 : : {
2051 : : /* Expression */
2052 : : Node *partkey;
2053 : :
2054 [ - + ]: 92 : if (partexpr_item == NULL)
2055 [ # # ]: 0 : elog(ERROR, "too few entries in partexprs list");
2056 : 92 : partkey = (Node *) lfirst(partexpr_item);
2057 : 92 : partexpr_item = lnext(partexprs, partexpr_item);
2058 : :
2059 : : /* Deparse */
2060 : 92 : str = deparse_expression_pretty(partkey, context, false, false,
2061 : : prettyFlags, 0);
2062 : : /* Need parens if it's not a bare function call */
2063 [ + + ]: 92 : if (looks_like_function(partkey))
2064 : 34 : appendStringInfoString(&buf, str);
2065 : : else
2066 : 58 : appendStringInfo(&buf, "(%s)", str);
2067 : :
2068 : 92 : keycoltype = exprType(partkey);
2069 : 92 : keycolcollation = exprCollation(partkey);
2070 : : }
2071 : :
2072 : : /* Add collation, if not default for column */
2073 : 996 : partcoll = partcollation->values[keyno];
2074 [ + + + + : 996 : if (!attrsOnly && OidIsValid(partcoll) && partcoll != keycolcollation)
+ + ]
2075 : 4 : appendStringInfo(&buf, " COLLATE %s",
2076 : : generate_collation_name((partcoll)));
2077 : :
2078 : : /* Add the operator class name, if not default */
2079 [ + + ]: 996 : if (!attrsOnly)
2080 : 866 : get_opclass_name(partclass->values[keyno], keycoltype, &buf);
2081 : : }
2082 : :
2083 [ + + ]: 903 : if (!attrsOnly)
2084 : 809 : appendStringInfoChar(&buf, ')');
2085 : :
2086 : : /* Clean up */
2087 : 903 : ReleaseSysCache(tuple);
2088 : :
2089 : 903 : return buf.data;
2090 : : }
2091 : :
2092 : : /*
2093 : : * pg_get_partition_constraintdef
2094 : : *
2095 : : * Returns partition constraint expression as a string for the input relation
2096 : : */
2097 : : Datum
2098 : 121 : pg_get_partition_constraintdef(PG_FUNCTION_ARGS)
2099 : : {
2100 : 121 : Oid relationId = PG_GETARG_OID(0);
2101 : : Expr *constr_expr;
2102 : : int prettyFlags;
2103 : : List *context;
2104 : : char *consrc;
2105 : :
2106 : 121 : constr_expr = get_partition_qual_relid(relationId);
2107 : :
2108 : : /* Quick exit if no partition constraint */
2109 [ + + ]: 121 : if (constr_expr == NULL)
2110 : 12 : PG_RETURN_NULL();
2111 : :
2112 : : /*
2113 : : * Deparse and return the constraint expression.
2114 : : */
2115 : 109 : prettyFlags = PRETTYFLAG_INDENT;
2116 : 109 : context = deparse_context_for(get_relation_name(relationId), relationId);
2117 : 109 : consrc = deparse_expression_pretty((Node *) constr_expr, context, false,
2118 : : false, prettyFlags, 0);
2119 : :
2120 : 109 : PG_RETURN_TEXT_P(string_to_text(consrc));
2121 : : }
2122 : :
2123 : : /*
2124 : : * pg_get_partconstrdef_string
2125 : : *
2126 : : * Returns the partition constraint as a C-string for the input relation, with
2127 : : * the given alias. No pretty-printing.
2128 : : */
2129 : : char *
2130 : 65 : pg_get_partconstrdef_string(Oid partitionId, char *aliasname)
2131 : : {
2132 : : Expr *constr_expr;
2133 : : List *context;
2134 : :
2135 : 65 : constr_expr = get_partition_qual_relid(partitionId);
2136 : 65 : context = deparse_context_for(aliasname, partitionId);
2137 : :
2138 : 65 : return deparse_expression((Node *) constr_expr, context, true, false);
2139 : : }
2140 : :
2141 : : /*
2142 : : * pg_get_constraintdef
2143 : : *
2144 : : * Returns the definition for the constraint, ie, everything that needs to
2145 : : * appear after "ALTER TABLE ... ADD CONSTRAINT <constraintname>".
2146 : : */
2147 : : Datum
2148 : 1130 : pg_get_constraintdef(PG_FUNCTION_ARGS)
2149 : : {
2150 : 1130 : Oid constraintId = PG_GETARG_OID(0);
2151 : : int prettyFlags;
2152 : : char *res;
2153 : :
2154 : 1130 : prettyFlags = PRETTYFLAG_INDENT;
2155 : :
2156 : 1130 : res = pg_get_constraintdef_worker(constraintId, false, prettyFlags, true);
2157 : :
2158 [ + + ]: 1130 : if (res == NULL)
2159 : 4 : PG_RETURN_NULL();
2160 : :
2161 : 1126 : PG_RETURN_TEXT_P(string_to_text(res));
2162 : : }
2163 : :
2164 : : Datum
2165 : 2743 : pg_get_constraintdef_ext(PG_FUNCTION_ARGS)
2166 : : {
2167 : 2743 : Oid constraintId = PG_GETARG_OID(0);
2168 : 2743 : bool pretty = PG_GETARG_BOOL(1);
2169 : : int prettyFlags;
2170 : : char *res;
2171 : :
2172 [ + + ]: 2743 : prettyFlags = GET_PRETTY_FLAGS(pretty);
2173 : :
2174 : 2743 : res = pg_get_constraintdef_worker(constraintId, false, prettyFlags, true);
2175 : :
2176 [ - + ]: 2743 : if (res == NULL)
2177 : 0 : PG_RETURN_NULL();
2178 : :
2179 : 2743 : PG_RETURN_TEXT_P(string_to_text(res));
2180 : : }
2181 : :
2182 : : /*
2183 : : * Internal version that returns a full ALTER TABLE ... ADD CONSTRAINT command
2184 : : */
2185 : : char *
2186 : 468 : pg_get_constraintdef_command(Oid constraintId)
2187 : : {
2188 : 468 : return pg_get_constraintdef_worker(constraintId, true, 0, false);
2189 : : }
2190 : :
2191 : : /*
2192 : : * As of 9.4, we now use an MVCC snapshot for this.
2193 : : */
2194 : : static char *
2195 : 4341 : pg_get_constraintdef_worker(Oid constraintId, bool fullCommand,
2196 : : int prettyFlags, bool missing_ok)
2197 : : {
2198 : : HeapTuple tup;
2199 : : Form_pg_constraint conForm;
2200 : : StringInfoData buf;
2201 : : SysScanDesc scandesc;
2202 : : ScanKeyData scankey[1];
2203 : 4341 : Snapshot snapshot = RegisterSnapshot(GetTransactionSnapshot());
2204 : 4341 : Relation relation = table_open(ConstraintRelationId, AccessShareLock);
2205 : :
2206 : 4341 : ScanKeyInit(&scankey[0],
2207 : : Anum_pg_constraint_oid,
2208 : : BTEqualStrategyNumber, F_OIDEQ,
2209 : : ObjectIdGetDatum(constraintId));
2210 : :
2211 : 4341 : scandesc = systable_beginscan(relation,
2212 : : ConstraintOidIndexId,
2213 : : true,
2214 : : snapshot,
2215 : : 1,
2216 : : scankey);
2217 : :
2218 : : /*
2219 : : * We later use the tuple with SysCacheGetAttr() as if we had obtained it
2220 : : * via SearchSysCache, which works fine.
2221 : : */
2222 : 4341 : tup = systable_getnext(scandesc);
2223 : :
2224 : 4341 : UnregisterSnapshot(snapshot);
2225 : :
2226 [ + + ]: 4341 : if (!HeapTupleIsValid(tup))
2227 : : {
2228 [ + - ]: 4 : if (missing_ok)
2229 : : {
2230 : 4 : systable_endscan(scandesc);
2231 : 4 : table_close(relation, AccessShareLock);
2232 : 4 : return NULL;
2233 : : }
2234 [ # # ]: 0 : elog(ERROR, "could not find tuple for constraint %u", constraintId);
2235 : : }
2236 : :
2237 : 4337 : conForm = (Form_pg_constraint) GETSTRUCT(tup);
2238 : :
2239 : 4337 : initStringInfo(&buf);
2240 : :
2241 [ + + ]: 4337 : if (fullCommand)
2242 : : {
2243 [ + + ]: 468 : if (OidIsValid(conForm->conrelid))
2244 : : {
2245 : : /*
2246 : : * Currently, callers want ALTER TABLE (without ONLY) for CHECK
2247 : : * constraints, and other types of constraints don't inherit
2248 : : * anyway so it doesn't matter whether we say ONLY or not. Someday
2249 : : * we might need to let callers specify whether to put ONLY in the
2250 : : * command.
2251 : : */
2252 : 455 : appendStringInfo(&buf, "ALTER TABLE %s ADD CONSTRAINT %s ",
2253 : : generate_qualified_relation_name(conForm->conrelid),
2254 : 455 : quote_identifier(NameStr(conForm->conname)));
2255 : : }
2256 : : else
2257 : : {
2258 : : /* Must be a domain constraint */
2259 : : Assert(OidIsValid(conForm->contypid));
2260 : 13 : appendStringInfo(&buf, "ALTER DOMAIN %s ADD CONSTRAINT %s ",
2261 : : generate_qualified_type_name(conForm->contypid),
2262 : 13 : quote_identifier(NameStr(conForm->conname)));
2263 : : }
2264 : : }
2265 : :
2266 [ + + + + : 4337 : switch (conForm->contype)
- + - ]
2267 : : {
2268 : 463 : case CONSTRAINT_FOREIGN:
2269 : : {
2270 : : Datum val;
2271 : : bool isnull;
2272 : : const char *string;
2273 : :
2274 : : /* Start off the constraint definition */
2275 : 463 : appendStringInfoString(&buf, "FOREIGN KEY (");
2276 : :
2277 : : /* Fetch and build referencing-column list */
2278 : 463 : val = SysCacheGetAttrNotNull(CONSTROID, tup,
2279 : : Anum_pg_constraint_conkey);
2280 : :
2281 : : /* If it is a temporal foreign key then it uses PERIOD. */
2282 : 463 : decompile_column_index_array(val, conForm->conrelid, conForm->conperiod, &buf);
2283 : :
2284 : : /* add foreign relation name */
2285 : 463 : appendStringInfo(&buf, ") REFERENCES %s(",
2286 : : generate_relation_name(conForm->confrelid,
2287 : : NIL));
2288 : :
2289 : : /* Fetch and build referenced-column list */
2290 : 463 : val = SysCacheGetAttrNotNull(CONSTROID, tup,
2291 : : Anum_pg_constraint_confkey);
2292 : :
2293 : 463 : decompile_column_index_array(val, conForm->confrelid, conForm->conperiod, &buf);
2294 : :
2295 : 463 : appendStringInfoChar(&buf, ')');
2296 : :
2297 : : /* Add match type */
2298 [ + - + - ]: 463 : switch (conForm->confmatchtype)
2299 : : {
2300 : 21 : case FKCONSTR_MATCH_FULL:
2301 : 21 : string = " MATCH FULL";
2302 : 21 : break;
2303 : 0 : case FKCONSTR_MATCH_PARTIAL:
2304 : 0 : string = " MATCH PARTIAL";
2305 : 0 : break;
2306 : 442 : case FKCONSTR_MATCH_SIMPLE:
2307 : 442 : string = "";
2308 : 442 : break;
2309 : 0 : default:
2310 [ # # ]: 0 : elog(ERROR, "unrecognized confmatchtype: %d",
2311 : : conForm->confmatchtype);
2312 : : string = ""; /* keep compiler quiet */
2313 : : break;
2314 : : }
2315 : 463 : appendStringInfoString(&buf, string);
2316 : :
2317 : : /* Add ON UPDATE and ON DELETE clauses, if needed */
2318 [ + - + + : 463 : switch (conForm->confupdtype)
- - ]
2319 : : {
2320 : 379 : case FKCONSTR_ACTION_NOACTION:
2321 : 379 : string = NULL; /* suppress default */
2322 : 379 : break;
2323 : 0 : case FKCONSTR_ACTION_RESTRICT:
2324 : 0 : string = "RESTRICT";
2325 : 0 : break;
2326 : 67 : case FKCONSTR_ACTION_CASCADE:
2327 : 67 : string = "CASCADE";
2328 : 67 : break;
2329 : 17 : case FKCONSTR_ACTION_SETNULL:
2330 : 17 : string = "SET NULL";
2331 : 17 : break;
2332 : 0 : case FKCONSTR_ACTION_SETDEFAULT:
2333 : 0 : string = "SET DEFAULT";
2334 : 0 : break;
2335 : 0 : default:
2336 [ # # ]: 0 : elog(ERROR, "unrecognized confupdtype: %d",
2337 : : conForm->confupdtype);
2338 : : string = NULL; /* keep compiler quiet */
2339 : : break;
2340 : : }
2341 [ + + ]: 463 : if (string)
2342 : 84 : appendStringInfo(&buf, " ON UPDATE %s", string);
2343 : :
2344 [ + - + + : 463 : switch (conForm->confdeltype)
+ - ]
2345 : : {
2346 : 380 : case FKCONSTR_ACTION_NOACTION:
2347 : 380 : string = NULL; /* suppress default */
2348 : 380 : break;
2349 : 0 : case FKCONSTR_ACTION_RESTRICT:
2350 : 0 : string = "RESTRICT";
2351 : 0 : break;
2352 : 67 : case FKCONSTR_ACTION_CASCADE:
2353 : 67 : string = "CASCADE";
2354 : 67 : break;
2355 : 12 : case FKCONSTR_ACTION_SETNULL:
2356 : 12 : string = "SET NULL";
2357 : 12 : break;
2358 : 4 : case FKCONSTR_ACTION_SETDEFAULT:
2359 : 4 : string = "SET DEFAULT";
2360 : 4 : break;
2361 : 0 : default:
2362 [ # # ]: 0 : elog(ERROR, "unrecognized confdeltype: %d",
2363 : : conForm->confdeltype);
2364 : : string = NULL; /* keep compiler quiet */
2365 : : break;
2366 : : }
2367 [ + + ]: 463 : if (string)
2368 : 83 : appendStringInfo(&buf, " ON DELETE %s", string);
2369 : :
2370 : : /*
2371 : : * Add columns specified to SET NULL or SET DEFAULT if
2372 : : * provided.
2373 : : */
2374 : 463 : val = SysCacheGetAttr(CONSTROID, tup,
2375 : : Anum_pg_constraint_confdelsetcols, &isnull);
2376 [ + + ]: 463 : if (!isnull)
2377 : : {
2378 : 8 : appendStringInfoString(&buf, " (");
2379 : 8 : decompile_column_index_array(val, conForm->conrelid, false, &buf);
2380 : 8 : appendStringInfoChar(&buf, ')');
2381 : : }
2382 : :
2383 : 463 : break;
2384 : : }
2385 : 2187 : case CONSTRAINT_PRIMARY:
2386 : : case CONSTRAINT_UNIQUE:
2387 : : {
2388 : : Datum val;
2389 : : Oid indexId;
2390 : : int keyatts;
2391 : : HeapTuple indtup;
2392 : :
2393 : : /* Start off the constraint definition */
2394 [ + + ]: 2187 : if (conForm->contype == CONSTRAINT_PRIMARY)
2395 : 1765 : appendStringInfoString(&buf, "PRIMARY KEY ");
2396 : : else
2397 : 422 : appendStringInfoString(&buf, "UNIQUE ");
2398 : :
2399 : 2187 : indexId = conForm->conindid;
2400 : :
2401 : 2187 : indtup = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexId));
2402 [ - + ]: 2187 : if (!HeapTupleIsValid(indtup))
2403 [ # # ]: 0 : elog(ERROR, "cache lookup failed for index %u", indexId);
2404 [ + + ]: 2187 : if (conForm->contype == CONSTRAINT_UNIQUE &&
2405 [ - + ]: 422 : ((Form_pg_index) GETSTRUCT(indtup))->indnullsnotdistinct)
2406 : 0 : appendStringInfoString(&buf, "NULLS NOT DISTINCT ");
2407 : :
2408 : 2187 : appendStringInfoChar(&buf, '(');
2409 : :
2410 : : /* Fetch and build target column list */
2411 : 2187 : val = SysCacheGetAttrNotNull(CONSTROID, tup,
2412 : : Anum_pg_constraint_conkey);
2413 : :
2414 : 2187 : keyatts = decompile_column_index_array(val, conForm->conrelid, false, &buf);
2415 [ + + ]: 2187 : if (conForm->conperiod)
2416 : 221 : appendStringInfoString(&buf, " WITHOUT OVERLAPS");
2417 : :
2418 : 2187 : appendStringInfoChar(&buf, ')');
2419 : :
2420 : : /* Build including column list (from pg_index.indkeys) */
2421 : 2187 : val = SysCacheGetAttrNotNull(INDEXRELID, indtup,
2422 : : Anum_pg_index_indnatts);
2423 [ + + ]: 2187 : if (DatumGetInt32(val) > keyatts)
2424 : : {
2425 : : Datum cols;
2426 : : Datum *keys;
2427 : : int nKeys;
2428 : : int j;
2429 : :
2430 : 48 : appendStringInfoString(&buf, " INCLUDE (");
2431 : :
2432 : 48 : cols = SysCacheGetAttrNotNull(INDEXRELID, indtup,
2433 : : Anum_pg_index_indkey);
2434 : :
2435 : 48 : deconstruct_array_builtin(DatumGetArrayTypeP(cols), INT2OID,
2436 : : &keys, NULL, &nKeys);
2437 : :
2438 [ + + ]: 144 : for (j = keyatts; j < nKeys; j++)
2439 : : {
2440 : : char *colName;
2441 : :
2442 : 96 : colName = get_attname(conForm->conrelid,
2443 : 96 : DatumGetInt16(keys[j]), false);
2444 [ + + ]: 96 : if (j > keyatts)
2445 : 48 : appendStringInfoString(&buf, ", ");
2446 : 96 : appendStringInfoString(&buf, quote_identifier(colName));
2447 : : }
2448 : :
2449 : 48 : appendStringInfoChar(&buf, ')');
2450 : : }
2451 : 2187 : ReleaseSysCache(indtup);
2452 : :
2453 : : /* XXX why do we only print these bits if fullCommand? */
2454 [ + + + - ]: 2187 : if (fullCommand && OidIsValid(indexId))
2455 : : {
2456 : 136 : char *options = flatten_reloptions(indexId);
2457 : : Oid tblspc;
2458 : :
2459 [ - + ]: 136 : if (options)
2460 : : {
2461 : 0 : appendStringInfo(&buf, " WITH (%s)", options);
2462 : 0 : pfree(options);
2463 : : }
2464 : :
2465 : : /*
2466 : : * Print the tablespace, unless it's the database default.
2467 : : * This is to help ALTER TABLE usage of this facility,
2468 : : * which needs this behavior to recreate exact catalog
2469 : : * state.
2470 : : */
2471 : 136 : tblspc = get_rel_tablespace(indexId);
2472 [ + + ]: 136 : if (OidIsValid(tblspc))
2473 : 16 : appendStringInfo(&buf, " USING INDEX TABLESPACE %s",
2474 : 16 : quote_identifier(get_tablespace_name(tblspc)));
2475 : : }
2476 : :
2477 : 2187 : break;
2478 : : }
2479 : 1319 : case CONSTRAINT_CHECK:
2480 : : {
2481 : : Datum val;
2482 : : char *conbin;
2483 : : char *consrc;
2484 : : Node *expr;
2485 : : List *context;
2486 : :
2487 : : /* Fetch constraint expression in parsetree form */
2488 : 1319 : val = SysCacheGetAttrNotNull(CONSTROID, tup,
2489 : : Anum_pg_constraint_conbin);
2490 : :
2491 : 1319 : conbin = TextDatumGetCString(val);
2492 : 1319 : expr = stringToNode(conbin);
2493 : :
2494 : : /* Set up deparsing context for Var nodes in constraint */
2495 [ + + ]: 1319 : if (conForm->conrelid != InvalidOid)
2496 : : {
2497 : : /* relation constraint */
2498 : 1172 : context = deparse_context_for(get_relation_name(conForm->conrelid),
2499 : : conForm->conrelid);
2500 : : }
2501 : : else
2502 : : {
2503 : : /* domain constraint --- can't have Vars */
2504 : 147 : context = NIL;
2505 : : }
2506 : :
2507 : 1319 : consrc = deparse_expression_pretty(expr, context, false, false,
2508 : : prettyFlags, 0);
2509 : :
2510 : : /*
2511 : : * Now emit the constraint definition, adding NO INHERIT if
2512 : : * necessary.
2513 : : *
2514 : : * There are cases where the constraint expression will be
2515 : : * fully parenthesized and we don't need the outer parens ...
2516 : : * but there are other cases where we do need 'em. Be
2517 : : * conservative for now.
2518 : : *
2519 : : * Note that simply checking for leading '(' and trailing ')'
2520 : : * would NOT be good enough, consider "(x > 0) AND (y > 0)".
2521 : : */
2522 : 1319 : appendStringInfo(&buf, "CHECK (%s)%s",
2523 : : consrc,
2524 [ + + ]: 1319 : conForm->connoinherit ? " NO INHERIT" : "");
2525 : 1319 : break;
2526 : : }
2527 : 292 : case CONSTRAINT_NOTNULL:
2528 : : {
2529 [ + + ]: 292 : if (conForm->conrelid)
2530 : : {
2531 : : AttrNumber attnum;
2532 : :
2533 : 232 : attnum = extractNotNullColumn(tup);
2534 : :
2535 : 232 : appendStringInfo(&buf, "NOT NULL %s",
2536 : 232 : quote_identifier(get_attname(conForm->conrelid,
2537 : : attnum, false)));
2538 [ - + ]: 232 : if (((Form_pg_constraint) GETSTRUCT(tup))->connoinherit)
2539 : 0 : appendStringInfoString(&buf, " NO INHERIT");
2540 : : }
2541 [ + - ]: 60 : else if (conForm->contypid)
2542 : : {
2543 : : /* conkey is null for domain not-null constraints */
2544 : 60 : appendStringInfoString(&buf, "NOT NULL");
2545 : : }
2546 : 292 : break;
2547 : : }
2548 : :
2549 : 0 : case CONSTRAINT_TRIGGER:
2550 : :
2551 : : /*
2552 : : * There isn't an ALTER TABLE syntax for creating a user-defined
2553 : : * constraint trigger, but it seems better to print something than
2554 : : * throw an error; if we throw error then this function couldn't
2555 : : * safely be applied to all rows of pg_constraint.
2556 : : */
2557 : 0 : appendStringInfoString(&buf, "TRIGGER");
2558 : 0 : break;
2559 : 76 : case CONSTRAINT_EXCLUSION:
2560 : : {
2561 : 76 : Oid indexOid = conForm->conindid;
2562 : : Datum val;
2563 : : Datum *elems;
2564 : : int nElems;
2565 : : int i;
2566 : : Oid *operators;
2567 : :
2568 : : /* Extract operator OIDs from the pg_constraint tuple */
2569 : 76 : val = SysCacheGetAttrNotNull(CONSTROID, tup,
2570 : : Anum_pg_constraint_conexclop);
2571 : :
2572 : 76 : deconstruct_array_builtin(DatumGetArrayTypeP(val), OIDOID,
2573 : : &elems, NULL, &nElems);
2574 : :
2575 : 76 : operators = palloc_array(Oid, nElems);
2576 [ + + ]: 172 : for (i = 0; i < nElems; i++)
2577 : 96 : operators[i] = DatumGetObjectId(elems[i]);
2578 : :
2579 : : /* pg_get_indexdef_worker does the rest */
2580 : : /* suppress tablespace because pg_dump wants it that way */
2581 : 76 : appendStringInfoString(&buf,
2582 : 76 : pg_get_indexdef_worker(indexOid,
2583 : : 0,
2584 : : operators,
2585 : : false,
2586 : : false,
2587 : : false,
2588 : : false,
2589 : : prettyFlags,
2590 : : false));
2591 : 76 : break;
2592 : : }
2593 : 0 : default:
2594 [ # # ]: 0 : elog(ERROR, "invalid constraint type \"%c\"", conForm->contype);
2595 : : break;
2596 : : }
2597 : :
2598 [ + + ]: 4337 : if (conForm->condeferrable)
2599 : 90 : appendStringInfoString(&buf, " DEFERRABLE");
2600 [ + + ]: 4337 : if (conForm->condeferred)
2601 : 39 : appendStringInfoString(&buf, " INITIALLY DEFERRED");
2602 : :
2603 : : /* Validated status is irrelevant when the constraint is NOT ENFORCED. */
2604 [ + + ]: 4337 : if (!conForm->conenforced)
2605 : 57 : appendStringInfoString(&buf, " NOT ENFORCED");
2606 [ + + ]: 4280 : else if (!conForm->convalidated)
2607 : 130 : appendStringInfoString(&buf, " NOT VALID");
2608 : :
2609 : : /* Cleanup */
2610 : 4337 : systable_endscan(scandesc);
2611 : 4337 : table_close(relation, AccessShareLock);
2612 : :
2613 : 4337 : return buf.data;
2614 : : }
2615 : :
2616 : :
2617 : : /*
2618 : : * Convert an int16[] Datum into a comma-separated list of column names
2619 : : * for the indicated relation; append the list to buf. Returns the number
2620 : : * of keys.
2621 : : */
2622 : : static int
2623 : 3121 : decompile_column_index_array(Datum column_index_array, Oid relId,
2624 : : bool withPeriod, StringInfo buf)
2625 : : {
2626 : : Datum *keys;
2627 : : int nKeys;
2628 : : int j;
2629 : :
2630 : : /* Extract data from array of int16 */
2631 : 3121 : deconstruct_array_builtin(DatumGetArrayTypeP(column_index_array), INT2OID,
2632 : : &keys, NULL, &nKeys);
2633 : :
2634 [ + + ]: 7531 : for (j = 0; j < nKeys; j++)
2635 : : {
2636 : : char *colName;
2637 : :
2638 : 4410 : colName = get_attname(relId, DatumGetInt16(keys[j]), false);
2639 : :
2640 [ + + ]: 4410 : if (j == 0)
2641 : 3121 : appendStringInfoString(buf, quote_identifier(colName));
2642 : : else
2643 [ + + ]: 1423 : appendStringInfo(buf, ", %s%s",
2644 [ + + ]: 134 : (withPeriod && j == nKeys - 1) ? "PERIOD " : "",
2645 : : quote_identifier(colName));
2646 : : }
2647 : :
2648 : 3121 : return nKeys;
2649 : : }
2650 : :
2651 : :
2652 : : /* ----------
2653 : : * pg_get_expr - Decompile an expression tree
2654 : : *
2655 : : * Input: an expression tree in nodeToString form, and a relation OID
2656 : : *
2657 : : * Output: reverse-listed expression
2658 : : *
2659 : : * Currently, the expression can only refer to a single relation, namely
2660 : : * the one specified by the second parameter. This is sufficient for
2661 : : * partial indexes, column default expressions, etc. We also support
2662 : : * Var-free expressions, for which the OID can be InvalidOid.
2663 : : *
2664 : : * If the OID is nonzero but not actually valid, don't throw an error,
2665 : : * just return NULL. This is a bit questionable, but it's what we've
2666 : : * done historically, and it can help avoid unwanted failures when
2667 : : * examining catalog entries for just-deleted relations.
2668 : : *
2669 : : * We expect this function to work, or throw a reasonably clean error,
2670 : : * for any node tree that can appear in a catalog pg_node_tree column.
2671 : : * Query trees, such as those appearing in pg_rewrite.ev_action, are
2672 : : * not supported. Nor are expressions in more than one relation, which
2673 : : * can appear in places like pg_rewrite.ev_qual.
2674 : : * ----------
2675 : : */
2676 : : Datum
2677 : 5199 : pg_get_expr(PG_FUNCTION_ARGS)
2678 : : {
2679 : 5199 : text *expr = PG_GETARG_TEXT_PP(0);
2680 : 5199 : Oid relid = PG_GETARG_OID(1);
2681 : : text *result;
2682 : : int prettyFlags;
2683 : :
2684 : 5199 : prettyFlags = PRETTYFLAG_INDENT;
2685 : :
2686 : 5199 : result = pg_get_expr_worker(expr, relid, prettyFlags);
2687 [ + - ]: 5199 : if (result)
2688 : 5199 : PG_RETURN_TEXT_P(result);
2689 : : else
2690 : 0 : PG_RETURN_NULL();
2691 : : }
2692 : :
2693 : : Datum
2694 : 496 : pg_get_expr_ext(PG_FUNCTION_ARGS)
2695 : : {
2696 : 496 : text *expr = PG_GETARG_TEXT_PP(0);
2697 : 496 : Oid relid = PG_GETARG_OID(1);
2698 : 496 : bool pretty = PG_GETARG_BOOL(2);
2699 : : text *result;
2700 : : int prettyFlags;
2701 : :
2702 [ + - ]: 496 : prettyFlags = GET_PRETTY_FLAGS(pretty);
2703 : :
2704 : 496 : result = pg_get_expr_worker(expr, relid, prettyFlags);
2705 [ + - ]: 496 : if (result)
2706 : 496 : PG_RETURN_TEXT_P(result);
2707 : : else
2708 : 0 : PG_RETURN_NULL();
2709 : : }
2710 : :
2711 : : static text *
2712 : 5695 : pg_get_expr_worker(text *expr, Oid relid, int prettyFlags)
2713 : : {
2714 : : Node *node;
2715 : : Node *tst;
2716 : : Relids relids;
2717 : : List *context;
2718 : : char *exprstr;
2719 : 5695 : Relation rel = NULL;
2720 : : char *str;
2721 : :
2722 : : /* Convert input pg_node_tree (really TEXT) object to C string */
2723 : 5695 : exprstr = text_to_cstring(expr);
2724 : :
2725 : : /* Convert expression to node tree */
2726 : 5695 : node = (Node *) stringToNode(exprstr);
2727 : :
2728 : 5695 : pfree(exprstr);
2729 : :
2730 : : /*
2731 : : * Throw error if the input is a querytree rather than an expression tree.
2732 : : * While we could support queries here, there seems no very good reason
2733 : : * to. In most such catalog columns, we'll see a List of Query nodes, or
2734 : : * even nested Lists, so drill down to a non-List node before checking.
2735 : : */
2736 : 5695 : tst = node;
2737 [ + - - + ]: 5695 : while (tst && IsA(tst, List))
2738 : 0 : tst = linitial((List *) tst);
2739 [ + - - + ]: 5695 : if (tst && IsA(tst, Query))
2740 [ # # ]: 0 : ereport(ERROR,
2741 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2742 : : errmsg("input is a query, not an expression")));
2743 : :
2744 : : /*
2745 : : * Throw error if the expression contains Vars we won't be able to
2746 : : * deparse.
2747 : : */
2748 : 5695 : relids = pull_varnos(NULL, node);
2749 [ + + ]: 5695 : if (OidIsValid(relid))
2750 : : {
2751 [ - + ]: 5631 : if (!bms_is_subset(relids, bms_make_singleton(1)))
2752 [ # # ]: 0 : ereport(ERROR,
2753 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2754 : : errmsg("expression contains variables of more than one relation")));
2755 : : }
2756 : : else
2757 : : {
2758 [ - + ]: 64 : if (!bms_is_empty(relids))
2759 [ # # ]: 0 : ereport(ERROR,
2760 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2761 : : errmsg("expression contains variables")));
2762 : : }
2763 : :
2764 : : /*
2765 : : * Prepare deparse context if needed. If we are deparsing with a relid,
2766 : : * we need to transiently open and lock the rel, to make sure it won't go
2767 : : * away underneath us. (set_relation_column_names would lock it anyway,
2768 : : * so this isn't really introducing any new behavior.)
2769 : : */
2770 [ + + ]: 5695 : if (OidIsValid(relid))
2771 : : {
2772 : 5631 : rel = try_relation_open(relid, AccessShareLock);
2773 [ - + ]: 5631 : if (rel == NULL)
2774 : 0 : return NULL;
2775 : 5631 : context = deparse_context_for(RelationGetRelationName(rel), relid);
2776 : : }
2777 : : else
2778 : 64 : context = NIL;
2779 : :
2780 : : /* Deparse */
2781 : 5695 : str = deparse_expression_pretty(node, context, false, false,
2782 : : prettyFlags, 0);
2783 : :
2784 [ + + ]: 5695 : if (rel != NULL)
2785 : 5631 : relation_close(rel, AccessShareLock);
2786 : :
2787 : 5695 : return string_to_text(str);
2788 : : }
2789 : :
2790 : :
2791 : : /* ----------
2792 : : * pg_get_userbyid - Get a user name by roleid and
2793 : : * fallback to 'unknown (OID=n)'
2794 : : * ----------
2795 : : */
2796 : : Datum
2797 : 1215 : pg_get_userbyid(PG_FUNCTION_ARGS)
2798 : : {
2799 : 1215 : Oid roleid = PG_GETARG_OID(0);
2800 : : Name result;
2801 : : HeapTuple roletup;
2802 : : Form_pg_authid role_rec;
2803 : :
2804 : : /*
2805 : : * Allocate space for the result
2806 : : */
2807 : 1215 : result = (Name) palloc(NAMEDATALEN);
2808 : 1215 : memset(NameStr(*result), 0, NAMEDATALEN);
2809 : :
2810 : : /*
2811 : : * Get the pg_authid entry and print the result
2812 : : */
2813 : 1215 : roletup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
2814 [ + - ]: 1215 : if (HeapTupleIsValid(roletup))
2815 : : {
2816 : 1215 : role_rec = (Form_pg_authid) GETSTRUCT(roletup);
2817 : 1215 : *result = role_rec->rolname;
2818 : 1215 : ReleaseSysCache(roletup);
2819 : : }
2820 : : else
2821 : 0 : sprintf(NameStr(*result), "unknown (OID=%u)", roleid);
2822 : :
2823 : 1215 : PG_RETURN_NAME(result);
2824 : : }
2825 : :
2826 : :
2827 : : /*
2828 : : * pg_get_serial_sequence
2829 : : * Get the name of the sequence used by an identity or serial column,
2830 : : * formatted suitably for passing to setval, nextval or currval.
2831 : : * First parameter is not treated as double-quoted, second parameter
2832 : : * is --- see documentation for reason.
2833 : : */
2834 : : Datum
2835 : 8 : pg_get_serial_sequence(PG_FUNCTION_ARGS)
2836 : : {
2837 : 8 : text *tablename = PG_GETARG_TEXT_PP(0);
2838 : 8 : text *columnname = PG_GETARG_TEXT_PP(1);
2839 : : RangeVar *tablerv;
2840 : : Oid tableOid;
2841 : : char *column;
2842 : : AttrNumber attnum;
2843 : 8 : Oid sequenceId = InvalidOid;
2844 : : Relation depRel;
2845 : : ScanKeyData key[3];
2846 : : SysScanDesc scan;
2847 : : HeapTuple tup;
2848 : :
2849 : : /* Look up table name. Can't lock it - we might not have privileges. */
2850 : 8 : tablerv = makeRangeVarFromNameList(textToQualifiedNameList(tablename));
2851 : 8 : tableOid = RangeVarGetRelid(tablerv, NoLock, false);
2852 : :
2853 : : /* Get the number of the column */
2854 : 8 : column = text_to_cstring(columnname);
2855 : :
2856 : 8 : attnum = get_attnum(tableOid, column);
2857 [ - + ]: 8 : if (attnum == InvalidAttrNumber)
2858 [ # # ]: 0 : ereport(ERROR,
2859 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
2860 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
2861 : : column, tablerv->relname)));
2862 : :
2863 : : /* Search the dependency table for the dependent sequence */
2864 : 8 : depRel = table_open(DependRelationId, AccessShareLock);
2865 : :
2866 : 8 : ScanKeyInit(&key[0],
2867 : : Anum_pg_depend_refclassid,
2868 : : BTEqualStrategyNumber, F_OIDEQ,
2869 : : ObjectIdGetDatum(RelationRelationId));
2870 : 8 : ScanKeyInit(&key[1],
2871 : : Anum_pg_depend_refobjid,
2872 : : BTEqualStrategyNumber, F_OIDEQ,
2873 : : ObjectIdGetDatum(tableOid));
2874 : 8 : ScanKeyInit(&key[2],
2875 : : Anum_pg_depend_refobjsubid,
2876 : : BTEqualStrategyNumber, F_INT4EQ,
2877 : : Int32GetDatum(attnum));
2878 : :
2879 : 8 : scan = systable_beginscan(depRel, DependReferenceIndexId, true,
2880 : : NULL, 3, key);
2881 : :
2882 [ + - ]: 20 : while (HeapTupleIsValid(tup = systable_getnext(scan)))
2883 : : {
2884 : 20 : Form_pg_depend deprec = (Form_pg_depend) GETSTRUCT(tup);
2885 : :
2886 : : /*
2887 : : * Look for an auto dependency (serial column) or internal dependency
2888 : : * (identity column) of a sequence on a column. (We need the relkind
2889 : : * test because indexes can also have auto dependencies on columns.)
2890 : : */
2891 [ + + ]: 20 : if (deprec->classid == RelationRelationId &&
2892 [ + - ]: 8 : deprec->objsubid == 0 &&
2893 [ + + ]: 8 : (deprec->deptype == DEPENDENCY_AUTO ||
2894 [ + - + - ]: 12 : deprec->deptype == DEPENDENCY_INTERNAL) &&
2895 : 8 : get_rel_relkind(deprec->objid) == RELKIND_SEQUENCE)
2896 : : {
2897 : 8 : sequenceId = deprec->objid;
2898 : 8 : break;
2899 : : }
2900 : : }
2901 : :
2902 : 8 : systable_endscan(scan);
2903 : 8 : table_close(depRel, AccessShareLock);
2904 : :
2905 [ + - ]: 8 : if (OidIsValid(sequenceId))
2906 : : {
2907 : : char *result;
2908 : :
2909 : 8 : result = generate_qualified_relation_name(sequenceId);
2910 : :
2911 : 8 : PG_RETURN_TEXT_P(string_to_text(result));
2912 : : }
2913 : :
2914 : 0 : PG_RETURN_NULL();
2915 : : }
2916 : :
2917 : :
2918 : : /*
2919 : : * pg_get_functiondef
2920 : : * Returns the complete "CREATE OR REPLACE FUNCTION ..." statement for
2921 : : * the specified function.
2922 : : *
2923 : : * Note: if you change the output format of this function, be careful not
2924 : : * to break psql's rules (in \ef and \sf) for identifying the start of the
2925 : : * function body. To wit: the function body starts on a line that begins with
2926 : : * "AS ", "BEGIN ", or "RETURN ", and no preceding line will look like that.
2927 : : */
2928 : : Datum
2929 : 115 : pg_get_functiondef(PG_FUNCTION_ARGS)
2930 : : {
2931 : 115 : Oid funcid = PG_GETARG_OID(0);
2932 : : StringInfoData buf;
2933 : : StringInfoData dq;
2934 : : HeapTuple proctup;
2935 : : Form_pg_proc proc;
2936 : : bool isfunction;
2937 : : Datum tmp;
2938 : : bool isnull;
2939 : : const char *prosrc;
2940 : : const char *name;
2941 : : const char *nsp;
2942 : : float4 procost;
2943 : : int oldlen;
2944 : :
2945 : 115 : initStringInfo(&buf);
2946 : :
2947 : : /* Look up the function */
2948 : 115 : proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
2949 [ + + ]: 115 : if (!HeapTupleIsValid(proctup))
2950 : 4 : PG_RETURN_NULL();
2951 : :
2952 : 111 : proc = (Form_pg_proc) GETSTRUCT(proctup);
2953 : 111 : name = NameStr(proc->proname);
2954 : :
2955 [ - + ]: 111 : if (proc->prokind == PROKIND_AGGREGATE)
2956 [ # # ]: 0 : ereport(ERROR,
2957 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2958 : : errmsg("\"%s\" is an aggregate function", name)));
2959 : :
2960 : 111 : isfunction = (proc->prokind != PROKIND_PROCEDURE);
2961 : :
2962 : : /*
2963 : : * We always qualify the function name, to ensure the right function gets
2964 : : * replaced.
2965 : : */
2966 : 111 : nsp = get_namespace_name_or_temp(proc->pronamespace);
2967 [ + + ]: 111 : appendStringInfo(&buf, "CREATE OR REPLACE %s %s(",
2968 : : isfunction ? "FUNCTION" : "PROCEDURE",
2969 : : quote_qualified_identifier(nsp, name));
2970 : 111 : (void) print_function_arguments(&buf, proctup, false, true);
2971 : 111 : appendStringInfoString(&buf, ")\n");
2972 [ + + ]: 111 : if (isfunction)
2973 : : {
2974 : 98 : appendStringInfoString(&buf, " RETURNS ");
2975 : 98 : print_function_rettype(&buf, proctup);
2976 : 98 : appendStringInfoChar(&buf, '\n');
2977 : : }
2978 : :
2979 : 111 : print_function_trftypes(&buf, proctup);
2980 : :
2981 : 111 : appendStringInfo(&buf, " LANGUAGE %s\n",
2982 : 111 : quote_identifier(get_language_name(proc->prolang, false)));
2983 : :
2984 : : /* Emit some miscellaneous options on one line */
2985 : 111 : oldlen = buf.len;
2986 : :
2987 [ - + ]: 111 : if (proc->prokind == PROKIND_WINDOW)
2988 : 0 : appendStringInfoString(&buf, " WINDOW");
2989 [ + + + - ]: 111 : switch (proc->provolatile)
2990 : : {
2991 : 8 : case PROVOLATILE_IMMUTABLE:
2992 : 8 : appendStringInfoString(&buf, " IMMUTABLE");
2993 : 8 : break;
2994 : 20 : case PROVOLATILE_STABLE:
2995 : 20 : appendStringInfoString(&buf, " STABLE");
2996 : 20 : break;
2997 : 83 : case PROVOLATILE_VOLATILE:
2998 : 83 : break;
2999 : : }
3000 : :
3001 [ + - + - ]: 111 : switch (proc->proparallel)
3002 : : {
3003 : 17 : case PROPARALLEL_SAFE:
3004 : 17 : appendStringInfoString(&buf, " PARALLEL SAFE");
3005 : 17 : break;
3006 : 0 : case PROPARALLEL_RESTRICTED:
3007 : 0 : appendStringInfoString(&buf, " PARALLEL RESTRICTED");
3008 : 0 : break;
3009 : 94 : case PROPARALLEL_UNSAFE:
3010 : 94 : break;
3011 : : }
3012 : :
3013 [ + + ]: 111 : if (proc->proisstrict)
3014 : 32 : appendStringInfoString(&buf, " STRICT");
3015 [ + + ]: 111 : if (proc->prosecdef)
3016 : 4 : appendStringInfoString(&buf, " SECURITY DEFINER");
3017 [ - + ]: 111 : if (proc->proleakproof)
3018 : 0 : appendStringInfoString(&buf, " LEAKPROOF");
3019 : :
3020 : : /* This code for the default cost and rows should match functioncmds.c */
3021 [ + - ]: 111 : if (proc->prolang == INTERNALlanguageId ||
3022 [ + + ]: 111 : proc->prolang == ClanguageId)
3023 : 5 : procost = 1;
3024 : : else
3025 : 106 : procost = 100;
3026 [ + + ]: 111 : if (proc->procost != procost)
3027 : 4 : appendStringInfo(&buf, " COST %g", proc->procost);
3028 : :
3029 [ + + - + ]: 111 : if (proc->prorows > 0 && proc->prorows != 1000)
3030 : 0 : appendStringInfo(&buf, " ROWS %g", proc->prorows);
3031 : :
3032 [ - + ]: 111 : if (proc->prosupport)
3033 : : {
3034 : : Oid argtypes[1];
3035 : :
3036 : : /*
3037 : : * We should qualify the support function's name if it wouldn't be
3038 : : * resolved by lookup in the current search path.
3039 : : */
3040 : 0 : argtypes[0] = INTERNALOID;
3041 : 0 : appendStringInfo(&buf, " SUPPORT %s",
3042 : : generate_function_name(proc->prosupport, 1,
3043 : : NIL, argtypes,
3044 : : false, NULL, false));
3045 : : }
3046 : :
3047 [ + + ]: 111 : if (oldlen != buf.len)
3048 : 41 : appendStringInfoChar(&buf, '\n');
3049 : :
3050 : : /* Emit any proconfig options, one per line */
3051 : 111 : tmp = SysCacheGetAttr(PROCOID, proctup, Anum_pg_proc_proconfig, &isnull);
3052 [ + + ]: 111 : if (!isnull)
3053 : : {
3054 : 4 : ArrayType *a = DatumGetArrayTypeP(tmp);
3055 : : int i;
3056 : :
3057 : : Assert(ARR_ELEMTYPE(a) == TEXTOID);
3058 : : Assert(ARR_NDIM(a) == 1);
3059 : : Assert(ARR_LBOUND(a)[0] == 1);
3060 : :
3061 [ + + ]: 28 : for (i = 1; i <= ARR_DIMS(a)[0]; i++)
3062 : : {
3063 : : Datum d;
3064 : :
3065 : 24 : d = array_ref(a, 1, &i,
3066 : : -1 /* varlenarray */ ,
3067 : : -1 /* TEXT's typlen */ ,
3068 : : false /* TEXT's typbyval */ ,
3069 : : TYPALIGN_INT /* TEXT's typalign */ ,
3070 : : &isnull);
3071 [ + - ]: 24 : if (!isnull)
3072 : : {
3073 : 24 : char *configitem = TextDatumGetCString(d);
3074 : : char *pos;
3075 : :
3076 : 24 : pos = strchr(configitem, '=');
3077 [ - + ]: 24 : if (pos == NULL)
3078 : 0 : continue;
3079 : 24 : *pos++ = '\0';
3080 : :
3081 : 24 : appendStringInfo(&buf, " SET %s TO ",
3082 : : quote_identifier(configitem));
3083 : :
3084 : : /*
3085 : : * Variables that are marked GUC_LIST_QUOTE were already fully
3086 : : * quoted by flatten_set_variable_args() before they were put
3087 : : * into the proconfig array. However, because the quoting
3088 : : * rules used there aren't exactly like SQL's, we have to
3089 : : * break the list value apart and then quote the elements as
3090 : : * string literals. (The elements may be double-quoted as-is,
3091 : : * but we can't just feed them to the SQL parser; it would do
3092 : : * the wrong thing with elements that are zero-length or
3093 : : * longer than NAMEDATALEN.) Also, we need a special case for
3094 : : * empty lists.
3095 : : *
3096 : : * Variables that are not so marked should just be emitted as
3097 : : * simple string literals. If the variable is not known to
3098 : : * guc.c, we'll do that; this makes it unsafe to use
3099 : : * GUC_LIST_QUOTE for extension variables.
3100 : : */
3101 [ + + ]: 24 : if (GetConfigOptionFlags(configitem, true) & GUC_LIST_QUOTE)
3102 : : {
3103 : : List *namelist;
3104 : : ListCell *lc;
3105 : :
3106 : : /* Parse string into list of identifiers */
3107 [ - + ]: 12 : if (!SplitGUCList(pos, ',', &namelist))
3108 : : {
3109 : : /* this shouldn't fail really */
3110 [ # # ]: 0 : elog(ERROR, "invalid list syntax in proconfig item");
3111 : : }
3112 : : /* Special case: represent an empty list as NULL */
3113 [ + + ]: 12 : if (namelist == NIL)
3114 : 4 : appendStringInfoString(&buf, "NULL");
3115 [ + + + + : 32 : foreach(lc, namelist)
+ + ]
3116 : : {
3117 : 20 : char *curname = (char *) lfirst(lc);
3118 : :
3119 : 20 : simple_quote_literal(&buf, curname);
3120 [ + + ]: 20 : if (lnext(namelist, lc))
3121 : 12 : appendStringInfoString(&buf, ", ");
3122 : : }
3123 : : }
3124 : : else
3125 : 12 : simple_quote_literal(&buf, pos);
3126 : 24 : appendStringInfoChar(&buf, '\n');
3127 : : }
3128 : : }
3129 : : }
3130 : :
3131 : : /* And finally the function definition ... */
3132 : 111 : (void) SysCacheGetAttr(PROCOID, proctup, Anum_pg_proc_prosqlbody, &isnull);
3133 [ + + + + ]: 111 : if (proc->prolang == SQLlanguageId && !isnull)
3134 : : {
3135 : 79 : print_function_sqlbody(&buf, proctup);
3136 : : }
3137 : : else
3138 : : {
3139 : 32 : appendStringInfoString(&buf, "AS ");
3140 : :
3141 : 32 : tmp = SysCacheGetAttr(PROCOID, proctup, Anum_pg_proc_probin, &isnull);
3142 [ + + ]: 32 : if (!isnull)
3143 : : {
3144 : 5 : simple_quote_literal(&buf, TextDatumGetCString(tmp));
3145 : 5 : appendStringInfoString(&buf, ", "); /* assume prosrc isn't null */
3146 : : }
3147 : :
3148 : 32 : tmp = SysCacheGetAttrNotNull(PROCOID, proctup, Anum_pg_proc_prosrc);
3149 : 32 : prosrc = TextDatumGetCString(tmp);
3150 : :
3151 : : /*
3152 : : * We always use dollar quoting. Figure out a suitable delimiter.
3153 : : *
3154 : : * Since the user is likely to be editing the function body string, we
3155 : : * shouldn't use a short delimiter that he might easily create a
3156 : : * conflict with. Hence prefer "$function$"/"$procedure$", but extend
3157 : : * if needed.
3158 : : */
3159 : 32 : initStringInfo(&dq);
3160 : 32 : appendStringInfoChar(&dq, '$');
3161 [ + + ]: 32 : appendStringInfoString(&dq, (isfunction ? "function" : "procedure"));
3162 [ - + ]: 32 : while (strstr(prosrc, dq.data) != NULL)
3163 : 0 : appendStringInfoChar(&dq, 'x');
3164 : 32 : appendStringInfoChar(&dq, '$');
3165 : :
3166 : 32 : appendBinaryStringInfo(&buf, dq.data, dq.len);
3167 : 32 : appendStringInfoString(&buf, prosrc);
3168 : 32 : appendBinaryStringInfo(&buf, dq.data, dq.len);
3169 : : }
3170 : :
3171 : 111 : appendStringInfoChar(&buf, '\n');
3172 : :
3173 : 111 : ReleaseSysCache(proctup);
3174 : :
3175 : 111 : PG_RETURN_TEXT_P(string_to_text(buf.data));
3176 : : }
3177 : :
3178 : : /*
3179 : : * pg_get_function_arguments
3180 : : * Get a nicely-formatted list of arguments for a function.
3181 : : * This is everything that would go between the parentheses in
3182 : : * CREATE FUNCTION.
3183 : : */
3184 : : Datum
3185 : 2452 : pg_get_function_arguments(PG_FUNCTION_ARGS)
3186 : : {
3187 : 2452 : Oid funcid = PG_GETARG_OID(0);
3188 : : StringInfoData buf;
3189 : : HeapTuple proctup;
3190 : :
3191 : 2452 : proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
3192 [ + + ]: 2452 : if (!HeapTupleIsValid(proctup))
3193 : 4 : PG_RETURN_NULL();
3194 : :
3195 : 2448 : initStringInfo(&buf);
3196 : :
3197 : 2448 : (void) print_function_arguments(&buf, proctup, false, true);
3198 : :
3199 : 2448 : ReleaseSysCache(proctup);
3200 : :
3201 : 2448 : PG_RETURN_TEXT_P(string_to_text(buf.data));
3202 : : }
3203 : :
3204 : : /*
3205 : : * pg_get_function_identity_arguments
3206 : : * Get a formatted list of arguments for a function.
3207 : : * This is everything that would go between the parentheses in
3208 : : * ALTER FUNCTION, etc. In particular, don't print defaults.
3209 : : */
3210 : : Datum
3211 : 2098 : pg_get_function_identity_arguments(PG_FUNCTION_ARGS)
3212 : : {
3213 : 2098 : Oid funcid = PG_GETARG_OID(0);
3214 : : StringInfoData buf;
3215 : : HeapTuple proctup;
3216 : :
3217 : 2098 : proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
3218 [ + + ]: 2098 : if (!HeapTupleIsValid(proctup))
3219 : 4 : PG_RETURN_NULL();
3220 : :
3221 : 2094 : initStringInfo(&buf);
3222 : :
3223 : 2094 : (void) print_function_arguments(&buf, proctup, false, false);
3224 : :
3225 : 2094 : ReleaseSysCache(proctup);
3226 : :
3227 : 2094 : PG_RETURN_TEXT_P(string_to_text(buf.data));
3228 : : }
3229 : :
3230 : : /*
3231 : : * pg_get_function_result
3232 : : * Get a nicely-formatted version of the result type of a function.
3233 : : * This is what would appear after RETURNS in CREATE FUNCTION.
3234 : : */
3235 : : Datum
3236 : 2156 : pg_get_function_result(PG_FUNCTION_ARGS)
3237 : : {
3238 : 2156 : Oid funcid = PG_GETARG_OID(0);
3239 : : StringInfoData buf;
3240 : : HeapTuple proctup;
3241 : :
3242 : 2156 : proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
3243 [ + + ]: 2156 : if (!HeapTupleIsValid(proctup))
3244 : 4 : PG_RETURN_NULL();
3245 : :
3246 [ + + ]: 2152 : if (((Form_pg_proc) GETSTRUCT(proctup))->prokind == PROKIND_PROCEDURE)
3247 : : {
3248 : 130 : ReleaseSysCache(proctup);
3249 : 130 : PG_RETURN_NULL();
3250 : : }
3251 : :
3252 : 2022 : initStringInfo(&buf);
3253 : :
3254 : 2022 : print_function_rettype(&buf, proctup);
3255 : :
3256 : 2022 : ReleaseSysCache(proctup);
3257 : :
3258 : 2022 : PG_RETURN_TEXT_P(string_to_text(buf.data));
3259 : : }
3260 : :
3261 : : /*
3262 : : * Guts of pg_get_function_result: append the function's return type
3263 : : * to the specified buffer.
3264 : : */
3265 : : static void
3266 : 2120 : print_function_rettype(StringInfo buf, HeapTuple proctup)
3267 : : {
3268 : 2120 : Form_pg_proc proc = (Form_pg_proc) GETSTRUCT(proctup);
3269 : 2120 : int ntabargs = 0;
3270 : : StringInfoData rbuf;
3271 : :
3272 : 2120 : initStringInfo(&rbuf);
3273 : :
3274 [ + + ]: 2120 : if (proc->proretset)
3275 : : {
3276 : : /* It might be a table function; try to print the arguments */
3277 : 209 : appendStringInfoString(&rbuf, "TABLE(");
3278 : 209 : ntabargs = print_function_arguments(&rbuf, proctup, true, false);
3279 [ + + ]: 209 : if (ntabargs > 0)
3280 : 39 : appendStringInfoChar(&rbuf, ')');
3281 : : else
3282 : 170 : resetStringInfo(&rbuf);
3283 : : }
3284 : :
3285 [ + + ]: 2120 : if (ntabargs == 0)
3286 : : {
3287 : : /* Not a table function, so do the normal thing */
3288 [ + + ]: 2081 : if (proc->proretset)
3289 : 170 : appendStringInfoString(&rbuf, "SETOF ");
3290 : 2081 : appendStringInfoString(&rbuf, format_type_be(proc->prorettype));
3291 : : }
3292 : :
3293 : 2120 : appendBinaryStringInfo(buf, rbuf.data, rbuf.len);
3294 : 2120 : }
3295 : :
3296 : : /*
3297 : : * Common code for pg_get_function_arguments and pg_get_function_result:
3298 : : * append the desired subset of arguments to buf. We print only TABLE
3299 : : * arguments when print_table_args is true, and all the others when it's false.
3300 : : * We print argument defaults only if print_defaults is true.
3301 : : * Function return value is the number of arguments printed.
3302 : : */
3303 : : static int
3304 : 4862 : print_function_arguments(StringInfo buf, HeapTuple proctup,
3305 : : bool print_table_args, bool print_defaults)
3306 : : {
3307 : 4862 : Form_pg_proc proc = (Form_pg_proc) GETSTRUCT(proctup);
3308 : : int numargs;
3309 : : Oid *argtypes;
3310 : : char **argnames;
3311 : : char *argmodes;
3312 : 4862 : int insertorderbyat = -1;
3313 : : int argsprinted;
3314 : : int inputargno;
3315 : : int nlackdefaults;
3316 : 4862 : List *argdefaults = NIL;
3317 : 4862 : ListCell *nextargdefault = NULL;
3318 : : int i;
3319 : :
3320 : 4862 : numargs = get_func_arg_info(proctup,
3321 : : &argtypes, &argnames, &argmodes);
3322 : :
3323 : 4862 : nlackdefaults = numargs;
3324 [ + + + + ]: 4862 : if (print_defaults && proc->pronargdefaults > 0)
3325 : : {
3326 : : Datum proargdefaults;
3327 : : bool isnull;
3328 : :
3329 : 21 : proargdefaults = SysCacheGetAttr(PROCOID, proctup,
3330 : : Anum_pg_proc_proargdefaults,
3331 : : &isnull);
3332 [ + - ]: 21 : if (!isnull)
3333 : : {
3334 : : char *str;
3335 : :
3336 : 21 : str = TextDatumGetCString(proargdefaults);
3337 : 21 : argdefaults = castNode(List, stringToNode(str));
3338 : 21 : pfree(str);
3339 : 21 : nextargdefault = list_head(argdefaults);
3340 : : /* nlackdefaults counts only *input* arguments lacking defaults */
3341 : 21 : nlackdefaults = proc->pronargs - list_length(argdefaults);
3342 : : }
3343 : : }
3344 : :
3345 : : /* Check for special treatment of ordered-set aggregates */
3346 [ + + ]: 4862 : if (proc->prokind == PROKIND_AGGREGATE)
3347 : : {
3348 : : HeapTuple aggtup;
3349 : : Form_pg_aggregate agg;
3350 : :
3351 : 594 : aggtup = SearchSysCache1(AGGFNOID, ObjectIdGetDatum(proc->oid));
3352 [ - + ]: 594 : if (!HeapTupleIsValid(aggtup))
3353 [ # # ]: 0 : elog(ERROR, "cache lookup failed for aggregate %u",
3354 : : proc->oid);
3355 : 594 : agg = (Form_pg_aggregate) GETSTRUCT(aggtup);
3356 [ + + ]: 594 : if (AGGKIND_IS_ORDERED_SET(agg->aggkind))
3357 : 28 : insertorderbyat = agg->aggnumdirectargs;
3358 : 594 : ReleaseSysCache(aggtup);
3359 : : }
3360 : :
3361 : 4862 : argsprinted = 0;
3362 : 4862 : inputargno = 0;
3363 [ + + ]: 9860 : for (i = 0; i < numargs; i++)
3364 : : {
3365 : 4998 : Oid argtype = argtypes[i];
3366 [ + + ]: 4998 : char *argname = argnames ? argnames[i] : NULL;
3367 [ + + ]: 4998 : char argmode = argmodes ? argmodes[i] : PROARGMODE_IN;
3368 : : const char *modename;
3369 : : bool isinput;
3370 : :
3371 [ + + + + : 4998 : switch (argmode)
+ - ]
3372 : : {
3373 : 4093 : case PROARGMODE_IN:
3374 : :
3375 : : /*
3376 : : * For procedures, explicitly mark all argument modes, so as
3377 : : * to avoid ambiguity with the SQL syntax for DROP PROCEDURE.
3378 : : */
3379 [ + + ]: 4093 : if (proc->prokind == PROKIND_PROCEDURE)
3380 : 287 : modename = "IN ";
3381 : : else
3382 : 3806 : modename = "";
3383 : 4093 : isinput = true;
3384 : 4093 : break;
3385 : 50 : case PROARGMODE_INOUT:
3386 : 50 : modename = "INOUT ";
3387 : 50 : isinput = true;
3388 : 50 : break;
3389 : 517 : case PROARGMODE_OUT:
3390 : 517 : modename = "OUT ";
3391 : 517 : isinput = false;
3392 : 517 : break;
3393 : 92 : case PROARGMODE_VARIADIC:
3394 : 92 : modename = "VARIADIC ";
3395 : 92 : isinput = true;
3396 : 92 : break;
3397 : 246 : case PROARGMODE_TABLE:
3398 : 246 : modename = "";
3399 : 246 : isinput = false;
3400 : 246 : break;
3401 : 0 : default:
3402 [ # # ]: 0 : elog(ERROR, "invalid parameter mode '%c'", argmode);
3403 : : modename = NULL; /* keep compiler quiet */
3404 : : isinput = false;
3405 : : break;
3406 : : }
3407 [ + + ]: 4998 : if (isinput)
3408 : 4235 : inputargno++; /* this is a 1-based counter */
3409 : :
3410 [ + + ]: 4998 : if (print_table_args != (argmode == PROARGMODE_TABLE))
3411 : 416 : continue;
3412 : :
3413 [ + + ]: 4582 : if (argsprinted == insertorderbyat)
3414 : : {
3415 [ + - ]: 28 : if (argsprinted)
3416 : 28 : appendStringInfoChar(buf, ' ');
3417 : 28 : appendStringInfoString(buf, "ORDER BY ");
3418 : : }
3419 [ + + ]: 4554 : else if (argsprinted)
3420 : 1477 : appendStringInfoString(buf, ", ");
3421 : :
3422 : 4582 : appendStringInfoString(buf, modename);
3423 [ + + + + ]: 4582 : if (argname && argname[0])
3424 : 1623 : appendStringInfo(buf, "%s ", quote_identifier(argname));
3425 : 4582 : appendStringInfoString(buf, format_type_be(argtype));
3426 [ + + + + : 4582 : if (print_defaults && isinput && inputargno > nlackdefaults)
+ + ]
3427 : : {
3428 : : Node *expr;
3429 : :
3430 : : Assert(nextargdefault != NULL);
3431 : 32 : expr = (Node *) lfirst(nextargdefault);
3432 : 32 : nextargdefault = lnext(argdefaults, nextargdefault);
3433 : :
3434 : 32 : appendStringInfo(buf, " DEFAULT %s",
3435 : : deparse_expression(expr, NIL, false, false));
3436 : : }
3437 : 4582 : argsprinted++;
3438 : :
3439 : : /* nasty hack: print the last arg twice for variadic ordered-set agg */
3440 [ + + + + ]: 4582 : if (argsprinted == insertorderbyat && i == numargs - 1)
3441 : : {
3442 : 14 : i--;
3443 : : /* aggs shouldn't have defaults anyway, but just to be sure ... */
3444 : 14 : print_defaults = false;
3445 : : }
3446 : : }
3447 : :
3448 : 4862 : return argsprinted;
3449 : : }
3450 : :
3451 : : static bool
3452 : 64 : is_input_argument(int nth, const char *argmodes)
3453 : : {
3454 : : return (!argmodes
3455 [ + + ]: 28 : || argmodes[nth] == PROARGMODE_IN
3456 [ + - ]: 12 : || argmodes[nth] == PROARGMODE_INOUT
3457 [ + + - + ]: 92 : || argmodes[nth] == PROARGMODE_VARIADIC);
3458 : : }
3459 : :
3460 : : /*
3461 : : * Append used transformed types to specified buffer
3462 : : */
3463 : : static void
3464 : 111 : print_function_trftypes(StringInfo buf, HeapTuple proctup)
3465 : : {
3466 : : Oid *trftypes;
3467 : : int ntypes;
3468 : :
3469 : 111 : ntypes = get_func_trftypes(proctup, &trftypes);
3470 [ + + ]: 111 : if (ntypes > 0)
3471 : : {
3472 : : int i;
3473 : :
3474 : 3 : appendStringInfoString(buf, " TRANSFORM ");
3475 [ + + ]: 8 : for (i = 0; i < ntypes; i++)
3476 : : {
3477 [ + + ]: 5 : if (i != 0)
3478 : 2 : appendStringInfoString(buf, ", ");
3479 : 5 : appendStringInfo(buf, "FOR TYPE %s", format_type_be(trftypes[i]));
3480 : : }
3481 : 3 : appendStringInfoChar(buf, '\n');
3482 : : }
3483 : 111 : }
3484 : :
3485 : : /*
3486 : : * Get textual representation of a function argument's default value. The
3487 : : * second argument of this function is the argument number among all arguments
3488 : : * (i.e. proallargtypes, *not* proargtypes), starting with 1, because that's
3489 : : * how information_schema.sql uses it.
3490 : : */
3491 : : Datum
3492 : 36 : pg_get_function_arg_default(PG_FUNCTION_ARGS)
3493 : : {
3494 : 36 : Oid funcid = PG_GETARG_OID(0);
3495 : 36 : int32 nth_arg = PG_GETARG_INT32(1);
3496 : : HeapTuple proctup;
3497 : : Form_pg_proc proc;
3498 : : int numargs;
3499 : : Oid *argtypes;
3500 : : char **argnames;
3501 : : char *argmodes;
3502 : : int i;
3503 : : List *argdefaults;
3504 : : Node *node;
3505 : : char *str;
3506 : : int nth_inputarg;
3507 : : Datum proargdefaults;
3508 : : bool isnull;
3509 : : int nth_default;
3510 : :
3511 : 36 : proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
3512 [ + + ]: 36 : if (!HeapTupleIsValid(proctup))
3513 : 8 : PG_RETURN_NULL();
3514 : :
3515 : 28 : numargs = get_func_arg_info(proctup, &argtypes, &argnames, &argmodes);
3516 [ + - + - : 28 : if (nth_arg < 1 || nth_arg > numargs || !is_input_argument(nth_arg - 1, argmodes))
+ + ]
3517 : : {
3518 : 8 : ReleaseSysCache(proctup);
3519 : 8 : PG_RETURN_NULL();
3520 : : }
3521 : :
3522 : 20 : nth_inputarg = 0;
3523 [ + + ]: 56 : for (i = 0; i < nth_arg; i++)
3524 [ + + ]: 36 : if (is_input_argument(i, argmodes))
3525 : 32 : nth_inputarg++;
3526 : :
3527 : 20 : proargdefaults = SysCacheGetAttr(PROCOID, proctup,
3528 : : Anum_pg_proc_proargdefaults,
3529 : : &isnull);
3530 [ - + ]: 20 : if (isnull)
3531 : : {
3532 : 0 : ReleaseSysCache(proctup);
3533 : 0 : PG_RETURN_NULL();
3534 : : }
3535 : :
3536 : 20 : str = TextDatumGetCString(proargdefaults);
3537 : 20 : argdefaults = castNode(List, stringToNode(str));
3538 : 20 : pfree(str);
3539 : :
3540 : 20 : proc = (Form_pg_proc) GETSTRUCT(proctup);
3541 : :
3542 : : /*
3543 : : * Calculate index into proargdefaults: proargdefaults corresponds to the
3544 : : * last N input arguments, where N = pronargdefaults.
3545 : : */
3546 : 20 : nth_default = nth_inputarg - 1 - (proc->pronargs - proc->pronargdefaults);
3547 : :
3548 [ + + - + ]: 20 : if (nth_default < 0 || nth_default >= list_length(argdefaults))
3549 : : {
3550 : 4 : ReleaseSysCache(proctup);
3551 : 4 : PG_RETURN_NULL();
3552 : : }
3553 : 16 : node = list_nth(argdefaults, nth_default);
3554 : 16 : str = deparse_expression(node, NIL, false, false);
3555 : :
3556 : 16 : ReleaseSysCache(proctup);
3557 : :
3558 : 16 : PG_RETURN_TEXT_P(string_to_text(str));
3559 : : }
3560 : :
3561 : : static void
3562 : 129 : print_function_sqlbody(StringInfo buf, HeapTuple proctup)
3563 : : {
3564 : : int numargs;
3565 : : Oid *argtypes;
3566 : : char **argnames;
3567 : : char *argmodes;
3568 : 129 : deparse_namespace dpns = {0};
3569 : : Datum tmp;
3570 : : Node *n;
3571 : :
3572 : 129 : dpns.funcname = pstrdup(NameStr(((Form_pg_proc) GETSTRUCT(proctup))->proname));
3573 : 129 : numargs = get_func_arg_info(proctup,
3574 : : &argtypes, &argnames, &argmodes);
3575 : 129 : dpns.numargs = numargs;
3576 : 129 : dpns.argnames = argnames;
3577 : :
3578 : 129 : tmp = SysCacheGetAttrNotNull(PROCOID, proctup, Anum_pg_proc_prosqlbody);
3579 : 129 : n = stringToNode(TextDatumGetCString(tmp));
3580 : :
3581 [ + + ]: 129 : if (IsA(n, List))
3582 : : {
3583 : : List *stmts;
3584 : : ListCell *lc;
3585 : :
3586 : 102 : stmts = linitial(castNode(List, n));
3587 : :
3588 : 102 : appendStringInfoString(buf, "BEGIN ATOMIC\n");
3589 : :
3590 [ + + + + : 199 : foreach(lc, stmts)
+ + ]
3591 : : {
3592 : 97 : Query *query = lfirst_node(Query, lc);
3593 : :
3594 : : /* It seems advisable to get at least AccessShareLock on rels */
3595 : 97 : AcquireRewriteLocks(query, false, false);
3596 : 97 : get_query_def(query, buf, list_make1(&dpns), NULL, false,
3597 : : PRETTYFLAG_INDENT, WRAP_COLUMN_DEFAULT, 1);
3598 : 97 : appendStringInfoChar(buf, ';');
3599 : 97 : appendStringInfoChar(buf, '\n');
3600 : : }
3601 : :
3602 : 102 : appendStringInfoString(buf, "END");
3603 : : }
3604 : : else
3605 : : {
3606 : 27 : Query *query = castNode(Query, n);
3607 : :
3608 : : /* It seems advisable to get at least AccessShareLock on rels */
3609 : 27 : AcquireRewriteLocks(query, false, false);
3610 : 27 : get_query_def(query, buf, list_make1(&dpns), NULL, false,
3611 : : 0, WRAP_COLUMN_DEFAULT, 0);
3612 : : }
3613 : 129 : }
3614 : :
3615 : : Datum
3616 : 1807 : pg_get_function_sqlbody(PG_FUNCTION_ARGS)
3617 : : {
3618 : 1807 : Oid funcid = PG_GETARG_OID(0);
3619 : : StringInfoData buf;
3620 : : HeapTuple proctup;
3621 : : bool isnull;
3622 : :
3623 : 1807 : initStringInfo(&buf);
3624 : :
3625 : : /* Look up the function */
3626 : 1807 : proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
3627 [ - + ]: 1807 : if (!HeapTupleIsValid(proctup))
3628 : 0 : PG_RETURN_NULL();
3629 : :
3630 : 1807 : (void) SysCacheGetAttr(PROCOID, proctup, Anum_pg_proc_prosqlbody, &isnull);
3631 [ + + ]: 1807 : if (isnull)
3632 : : {
3633 : 1757 : ReleaseSysCache(proctup);
3634 : 1757 : PG_RETURN_NULL();
3635 : : }
3636 : :
3637 : 50 : print_function_sqlbody(&buf, proctup);
3638 : :
3639 : 50 : ReleaseSysCache(proctup);
3640 : :
3641 : 50 : PG_RETURN_TEXT_P(cstring_to_text_with_len(buf.data, buf.len));
3642 : : }
3643 : :
3644 : :
3645 : : /*
3646 : : * deparse_expression - General utility for deparsing expressions
3647 : : *
3648 : : * calls deparse_expression_pretty with all prettyPrinting disabled
3649 : : */
3650 : : char *
3651 : 56560 : deparse_expression(Node *expr, List *dpcontext,
3652 : : bool forceprefix, bool showimplicit)
3653 : : {
3654 : 56560 : return deparse_expression_pretty(expr, dpcontext, forceprefix,
3655 : : showimplicit, 0, 0);
3656 : : }
3657 : :
3658 : : /* ----------
3659 : : * deparse_expression_pretty - General utility for deparsing expressions
3660 : : *
3661 : : * expr is the node tree to be deparsed. It must be a transformed expression
3662 : : * tree (ie, not the raw output of gram.y).
3663 : : *
3664 : : * dpcontext is a list of deparse_namespace nodes representing the context
3665 : : * for interpreting Vars in the node tree. It can be NIL if no Vars are
3666 : : * expected.
3667 : : *
3668 : : * forceprefix is true to force all Vars to be prefixed with their table names.
3669 : : *
3670 : : * showimplicit is true to force all implicit casts to be shown explicitly.
3671 : : *
3672 : : * Tries to pretty up the output according to prettyFlags and startIndent.
3673 : : *
3674 : : * The result is a palloc'd string.
3675 : : * ----------
3676 : : */
3677 : : static char *
3678 : 64868 : deparse_expression_pretty(Node *expr, List *dpcontext,
3679 : : bool forceprefix, bool showimplicit,
3680 : : int prettyFlags, int startIndent)
3681 : : {
3682 : : StringInfoData buf;
3683 : : deparse_context context;
3684 : :
3685 : 64868 : initStringInfo(&buf);
3686 : 64868 : context.buf = &buf;
3687 : 64868 : context.namespaces = dpcontext;
3688 : 64868 : context.resultDesc = NULL;
3689 : 64868 : context.targetList = NIL;
3690 : 64868 : context.windowClause = NIL;
3691 : 64868 : context.varprefix = forceprefix;
3692 : 64868 : context.prettyFlags = prettyFlags;
3693 : 64868 : context.wrapColumn = WRAP_COLUMN_DEFAULT;
3694 : 64868 : context.indentLevel = startIndent;
3695 : 64868 : context.colNamesVisible = true;
3696 : 64868 : context.inGroupBy = false;
3697 : 64868 : context.varInOrderBy = false;
3698 : 64868 : context.appendparents = NULL;
3699 : :
3700 : 64868 : get_rule_expr(expr, &context, showimplicit);
3701 : :
3702 : 64868 : return buf.data;
3703 : : }
3704 : :
3705 : : /* ----------
3706 : : * deparse_context_for - Build deparse context for a single relation
3707 : : *
3708 : : * Given the reference name (alias) and OID of a relation, build deparsing
3709 : : * context for an expression referencing only that relation (as varno 1,
3710 : : * varlevelsup 0). This is sufficient for many uses of deparse_expression.
3711 : : * ----------
3712 : : */
3713 : : List *
3714 : 14587 : deparse_context_for(const char *aliasname, Oid relid)
3715 : : {
3716 : : deparse_namespace *dpns;
3717 : : RangeTblEntry *rte;
3718 : :
3719 : 14587 : dpns = palloc0_object(deparse_namespace);
3720 : :
3721 : : /* Build a minimal RTE for the rel */
3722 : 14587 : rte = makeNode(RangeTblEntry);
3723 : 14587 : rte->rtekind = RTE_RELATION;
3724 : 14587 : rte->relid = relid;
3725 : 14587 : rte->relkind = RELKIND_RELATION; /* no need for exactness here */
3726 : 14587 : rte->rellockmode = AccessShareLock;
3727 : 14587 : rte->alias = makeAlias(aliasname, NIL);
3728 : 14587 : rte->eref = rte->alias;
3729 : 14587 : rte->lateral = false;
3730 : 14587 : rte->inh = false;
3731 : 14587 : rte->inFromCl = true;
3732 : :
3733 : : /* Build one-element rtable */
3734 : 14587 : dpns->rtable = list_make1(rte);
3735 : 14587 : dpns->subplans = NIL;
3736 : 14587 : dpns->ctes = NIL;
3737 : 14587 : dpns->appendrels = NULL;
3738 : 14587 : set_rtable_names(dpns, NIL, NULL);
3739 : 14587 : set_simple_column_names(dpns);
3740 : :
3741 : : /* Return a one-deep namespace stack */
3742 : 14587 : return list_make1(dpns);
3743 : : }
3744 : :
3745 : : /*
3746 : : * deparse_context_for_plan_tree - Build deparse context for a Plan tree
3747 : : *
3748 : : * When deparsing an expression in a Plan tree, we use the plan's rangetable
3749 : : * to resolve names of simple Vars. The initialization of column names for
3750 : : * this is rather expensive if the rangetable is large, and it'll be the same
3751 : : * for every expression in the Plan tree; so we do it just once and re-use
3752 : : * the result of this function for each expression. (Note that the result
3753 : : * is not usable until set_deparse_context_plan() is applied to it.)
3754 : : *
3755 : : * In addition to the PlannedStmt, pass the per-RTE alias names
3756 : : * assigned by a previous call to select_rtable_names_for_explain.
3757 : : */
3758 : : List *
3759 : 16993 : deparse_context_for_plan_tree(PlannedStmt *pstmt, List *rtable_names)
3760 : : {
3761 : : deparse_namespace *dpns;
3762 : :
3763 : 16993 : dpns = palloc0_object(deparse_namespace);
3764 : :
3765 : : /* Initialize fields that stay the same across the whole plan tree */
3766 : 16993 : dpns->rtable = pstmt->rtable;
3767 : 16993 : dpns->rtable_names = rtable_names;
3768 : 16993 : dpns->subplans = pstmt->subplans;
3769 : 16993 : dpns->ctes = NIL;
3770 [ + + ]: 16993 : if (pstmt->appendRelations)
3771 : : {
3772 : : /* Set up the array, indexed by child relid */
3773 : 2715 : int ntables = list_length(dpns->rtable);
3774 : : ListCell *lc;
3775 : :
3776 : 2715 : dpns->appendrels = palloc0_array(AppendRelInfo *, ntables + 1);
3777 [ + - + + : 14802 : foreach(lc, pstmt->appendRelations)
+ + ]
3778 : : {
3779 : 12087 : AppendRelInfo *appinfo = lfirst_node(AppendRelInfo, lc);
3780 : 12087 : Index crelid = appinfo->child_relid;
3781 : :
3782 : : Assert(crelid > 0 && crelid <= ntables);
3783 : : Assert(dpns->appendrels[crelid] == NULL);
3784 : 12087 : dpns->appendrels[crelid] = appinfo;
3785 : : }
3786 : : }
3787 : : else
3788 : 14278 : dpns->appendrels = NULL; /* don't need it */
3789 : :
3790 : : /*
3791 : : * Set up column name aliases, ignoring any join RTEs; they don't matter
3792 : : * because plan trees don't contain any join alias Vars.
3793 : : */
3794 : 16993 : set_simple_column_names(dpns);
3795 : :
3796 : : /* Return a one-deep namespace stack */
3797 : 16993 : return list_make1(dpns);
3798 : : }
3799 : :
3800 : : /*
3801 : : * set_deparse_context_plan - Specify Plan node containing expression
3802 : : *
3803 : : * When deparsing an expression in a Plan tree, we might have to resolve
3804 : : * OUTER_VAR, INNER_VAR, or INDEX_VAR references. To do this, the caller must
3805 : : * provide the parent Plan node. Then OUTER_VAR and INNER_VAR references
3806 : : * can be resolved by drilling down into the left and right child plans.
3807 : : * Similarly, INDEX_VAR references can be resolved by reference to the
3808 : : * indextlist given in a parent IndexOnlyScan node, or to the scan tlist in
3809 : : * ForeignScan and CustomScan nodes. (Note that we don't currently support
3810 : : * deparsing of indexquals in regular IndexScan or BitmapIndexScan nodes;
3811 : : * for those, we can only deparse the indexqualorig fields, which won't
3812 : : * contain INDEX_VAR Vars.)
3813 : : *
3814 : : * The ancestors list is a list of the Plan's parent Plan and SubPlan nodes,
3815 : : * the most-closely-nested first. This is needed to resolve PARAM_EXEC
3816 : : * Params. Note we assume that all the Plan nodes share the same rtable.
3817 : : *
3818 : : * For a ModifyTable plan, we might also need to resolve references to OLD/NEW
3819 : : * variables in the RETURNING list, so we copy the alias names of the OLD and
3820 : : * NEW rows from the ModifyTable plan node.
3821 : : *
3822 : : * Once this function has been called, deparse_expression() can be called on
3823 : : * subsidiary expression(s) of the specified Plan node. To deparse
3824 : : * expressions of a different Plan node in the same Plan tree, re-call this
3825 : : * function to identify the new parent Plan node.
3826 : : *
3827 : : * The result is the same List passed in; this is a notational convenience.
3828 : : */
3829 : : List *
3830 : 41131 : set_deparse_context_plan(List *dpcontext, Plan *plan, List *ancestors)
3831 : : {
3832 : : deparse_namespace *dpns;
3833 : :
3834 : : /* Should always have one-entry namespace list for Plan deparsing */
3835 : : Assert(list_length(dpcontext) == 1);
3836 : 41131 : dpns = (deparse_namespace *) linitial(dpcontext);
3837 : :
3838 : : /* Set our attention on the specific plan node passed in */
3839 : 41131 : dpns->ancestors = ancestors;
3840 : 41131 : set_deparse_plan(dpns, plan);
3841 : :
3842 : : /* For ModifyTable, set aliases for OLD and NEW in RETURNING */
3843 [ + + ]: 41131 : if (IsA(plan, ModifyTable))
3844 : : {
3845 : 141 : dpns->ret_old_alias = ((ModifyTable *) plan)->returningOldAlias;
3846 : 141 : dpns->ret_new_alias = ((ModifyTable *) plan)->returningNewAlias;
3847 : : }
3848 : :
3849 : 41131 : return dpcontext;
3850 : : }
3851 : :
3852 : : /*
3853 : : * select_rtable_names_for_explain - Select RTE aliases for EXPLAIN
3854 : : *
3855 : : * Determine the relation aliases we'll use during an EXPLAIN operation.
3856 : : * This is just a frontend to set_rtable_names. We have to expose the aliases
3857 : : * to EXPLAIN because EXPLAIN needs to know the right alias names to print.
3858 : : */
3859 : : List *
3860 : 16993 : select_rtable_names_for_explain(List *rtable, Bitmapset *rels_used)
3861 : : {
3862 : : deparse_namespace dpns;
3863 : :
3864 : 16993 : memset(&dpns, 0, sizeof(dpns));
3865 : 16993 : dpns.rtable = rtable;
3866 : 16993 : dpns.subplans = NIL;
3867 : 16993 : dpns.ctes = NIL;
3868 : 16993 : dpns.appendrels = NULL;
3869 : 16993 : set_rtable_names(&dpns, NIL, rels_used);
3870 : : /* We needn't bother computing column aliases yet */
3871 : :
3872 : 16993 : return dpns.rtable_names;
3873 : : }
3874 : :
3875 : : /*
3876 : : * set_rtable_names: select RTE aliases to be used in printing a query
3877 : : *
3878 : : * We fill in dpns->rtable_names with a list of names that is one-for-one with
3879 : : * the already-filled dpns->rtable list. Each RTE name is unique among those
3880 : : * in the new namespace plus any ancestor namespaces listed in
3881 : : * parent_namespaces.
3882 : : *
3883 : : * If rels_used isn't NULL, only RTE indexes listed in it are given aliases.
3884 : : *
3885 : : * Note that this function is only concerned with relation names, not column
3886 : : * names.
3887 : : */
3888 : : static void
3889 : 35254 : set_rtable_names(deparse_namespace *dpns, List *parent_namespaces,
3890 : : Bitmapset *rels_used)
3891 : : {
3892 : : HASHCTL hash_ctl;
3893 : : HTAB *names_hash;
3894 : : NameHashEntry *hentry;
3895 : : bool found;
3896 : : int rtindex;
3897 : : ListCell *lc;
3898 : :
3899 : 35254 : dpns->rtable_names = NIL;
3900 : : /* nothing more to do if empty rtable */
3901 [ + + ]: 35254 : if (dpns->rtable == NIL)
3902 : 352 : return;
3903 : :
3904 : : /*
3905 : : * We use a hash table to hold known names, so that this process is O(N)
3906 : : * not O(N^2) for N names.
3907 : : */
3908 : 34902 : hash_ctl.keysize = NAMEDATALEN;
3909 : 34902 : hash_ctl.entrysize = sizeof(NameHashEntry);
3910 : 34902 : hash_ctl.hcxt = CurrentMemoryContext;
3911 : 34902 : names_hash = hash_create("set_rtable_names names",
3912 : 34902 : list_length(dpns->rtable),
3913 : : &hash_ctl,
3914 : : HASH_ELEM | HASH_STRINGS | HASH_CONTEXT);
3915 : :
3916 : : /* Preload the hash table with names appearing in parent_namespaces */
3917 [ + + + + : 36021 : foreach(lc, parent_namespaces)
+ + ]
3918 : : {
3919 : 1119 : deparse_namespace *olddpns = (deparse_namespace *) lfirst(lc);
3920 : : ListCell *lc2;
3921 : :
3922 [ + + + + : 3891 : foreach(lc2, olddpns->rtable_names)
+ + ]
3923 : : {
3924 : 2772 : char *oldname = (char *) lfirst(lc2);
3925 : :
3926 [ + + ]: 2772 : if (oldname == NULL)
3927 : 201 : continue;
3928 : 2571 : hentry = (NameHashEntry *) hash_search(names_hash,
3929 : : oldname,
3930 : : HASH_ENTER,
3931 : : &found);
3932 : : /* we do not complain about duplicate names in parent namespaces */
3933 : 2571 : hentry->counter = 0;
3934 : : }
3935 : : }
3936 : :
3937 : : /* Now we can scan the rtable */
3938 : 34902 : rtindex = 1;
3939 [ + - + + : 103976 : foreach(lc, dpns->rtable)
+ + ]
3940 : : {
3941 : 69074 : RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
3942 : : char *refname;
3943 : :
3944 : : /* Just in case this takes an unreasonable amount of time ... */
3945 [ + + ]: 69074 : CHECK_FOR_INTERRUPTS();
3946 : :
3947 [ + + + + ]: 69074 : if (rels_used && !bms_is_member(rtindex, rels_used))
3948 : : {
3949 : : /* Ignore unreferenced RTE */
3950 : 13112 : refname = NULL;
3951 : : }
3952 [ + + ]: 55962 : else if (rte->alias)
3953 : : {
3954 : : /* If RTE has a user-defined alias, prefer that */
3955 : 36067 : refname = rte->alias->aliasname;
3956 : : }
3957 [ + + ]: 19895 : else if (rte->rtekind == RTE_RELATION)
3958 : : {
3959 : : /* Use the current actual name of the relation */
3960 : 15146 : refname = get_rel_name(rte->relid);
3961 : : }
3962 [ + + ]: 4749 : else if (rte->rtekind == RTE_JOIN)
3963 : : {
3964 : : /* Unnamed join has no refname */
3965 : 1149 : refname = NULL;
3966 : : }
3967 : : else
3968 : : {
3969 : : /* Otherwise use whatever the parser assigned */
3970 : 3600 : refname = rte->eref->aliasname;
3971 : : }
3972 : :
3973 : : /*
3974 : : * If the selected name isn't unique, append digits to make it so, and
3975 : : * make a new hash entry for it once we've got a unique name. For a
3976 : : * very long input name, we might have to truncate to stay within
3977 : : * NAMEDATALEN.
3978 : : */
3979 [ + + ]: 69074 : if (refname)
3980 : : {
3981 : 54813 : hentry = (NameHashEntry *) hash_search(names_hash,
3982 : : refname,
3983 : : HASH_ENTER,
3984 : : &found);
3985 [ + + ]: 54813 : if (found)
3986 : : {
3987 : : /* Name already in use, must choose a new one */
3988 : 10369 : int refnamelen = strlen(refname);
3989 : 10369 : char *modname = (char *) palloc(refnamelen + 16);
3990 : : NameHashEntry *hentry2;
3991 : :
3992 : : do
3993 : : {
3994 : 10373 : hentry->counter++;
3995 : : for (;;)
3996 : : {
3997 : 10381 : memcpy(modname, refname, refnamelen);
3998 : 10381 : sprintf(modname + refnamelen, "_%d", hentry->counter);
3999 [ + + ]: 10381 : if (strlen(modname) < NAMEDATALEN)
4000 : 10373 : break;
4001 : : /* drop chars from refname to keep all the digits */
4002 : 8 : refnamelen = pg_mbcliplen(refname, refnamelen,
4003 : : refnamelen - 1);
4004 : : }
4005 : 10373 : hentry2 = (NameHashEntry *) hash_search(names_hash,
4006 : : modname,
4007 : : HASH_ENTER,
4008 : : &found);
4009 [ + + ]: 10373 : } while (found);
4010 : 10369 : hentry2->counter = 0; /* init new hash entry */
4011 : 10369 : refname = modname;
4012 : : }
4013 : : else
4014 : : {
4015 : : /* Name not previously used, need only initialize hentry */
4016 : 44444 : hentry->counter = 0;
4017 : : }
4018 : : }
4019 : :
4020 : 69074 : dpns->rtable_names = lappend(dpns->rtable_names, refname);
4021 : 69074 : rtindex++;
4022 : : }
4023 : :
4024 : 34902 : hash_destroy(names_hash);
4025 : : }
4026 : :
4027 : : /*
4028 : : * set_deparse_for_query: set up deparse_namespace for deparsing a Query tree
4029 : : *
4030 : : * For convenience, this is defined to initialize the deparse_namespace struct
4031 : : * from scratch.
4032 : : */
4033 : : static void
4034 : 3586 : set_deparse_for_query(deparse_namespace *dpns, Query *query,
4035 : : List *parent_namespaces)
4036 : : {
4037 : : ListCell *lc;
4038 : : ListCell *lc2;
4039 : :
4040 : : /* Initialize *dpns and fill rtable/ctes links */
4041 : 3586 : memset(dpns, 0, sizeof(deparse_namespace));
4042 : 3586 : dpns->rtable = query->rtable;
4043 : 3586 : dpns->subplans = NIL;
4044 : 3586 : dpns->ctes = query->cteList;
4045 : 3586 : dpns->appendrels = NULL;
4046 : 3586 : dpns->ret_old_alias = query->returningOldAlias;
4047 : 3586 : dpns->ret_new_alias = query->returningNewAlias;
4048 : :
4049 : : /* Assign a unique relation alias to each RTE */
4050 : 3586 : set_rtable_names(dpns, parent_namespaces, NULL);
4051 : :
4052 : : /* Initialize dpns->rtable_columns to contain zeroed structs */
4053 : 3586 : dpns->rtable_columns = NIL;
4054 [ + + ]: 9972 : while (list_length(dpns->rtable_columns) < list_length(dpns->rtable))
4055 : 6386 : dpns->rtable_columns = lappend(dpns->rtable_columns,
4056 : : palloc0_object(deparse_columns));
4057 : :
4058 : : /* If it's a utility query, it won't have a jointree */
4059 [ + + ]: 3586 : if (query->jointree)
4060 : : {
4061 : : /* Detect whether global uniqueness of USING names is needed */
4062 : 3577 : dpns->unique_using =
4063 : 3577 : has_dangerous_join_using(dpns, (Node *) query->jointree);
4064 : :
4065 : : /*
4066 : : * Select names for columns merged by USING, via a recursive pass over
4067 : : * the query jointree.
4068 : : */
4069 : 3577 : set_using_names(dpns, (Node *) query->jointree, NIL);
4070 : : }
4071 : :
4072 : : /*
4073 : : * Now assign remaining column aliases for each RTE. We do this in a
4074 : : * linear scan of the rtable, so as to process RTEs whether or not they
4075 : : * are in the jointree (we mustn't miss NEW.*, INSERT target relations,
4076 : : * etc). JOIN RTEs must be processed after their children, but this is
4077 : : * okay because they appear later in the rtable list than their children
4078 : : * (cf Asserts in identify_join_columns()).
4079 : : */
4080 [ + + + + : 9972 : forboth(lc, dpns->rtable, lc2, dpns->rtable_columns)
+ + + + +
+ + - +
+ ]
4081 : : {
4082 : 6386 : RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
4083 : 6386 : deparse_columns *colinfo = (deparse_columns *) lfirst(lc2);
4084 : :
4085 [ + + ]: 6386 : if (rte->rtekind == RTE_JOIN)
4086 : 940 : set_join_column_names(dpns, rte, colinfo);
4087 : : else
4088 : 5446 : set_relation_column_names(dpns, rte, colinfo);
4089 : : }
4090 : 3586 : }
4091 : :
4092 : : /*
4093 : : * set_simple_column_names: fill in column aliases for non-query situations
4094 : : *
4095 : : * This handles EXPLAIN and cases where we only have relation RTEs. Without
4096 : : * a join tree, we can't do anything smart about join RTEs, but we don't
4097 : : * need to, because EXPLAIN should never see join alias Vars anyway.
4098 : : * If we find a join RTE we'll just skip it, leaving its deparse_columns
4099 : : * struct all-zero. If somehow we try to deparse a join alias Var, we'll
4100 : : * error out cleanly because the struct's num_cols will be zero.
4101 : : */
4102 : : static void
4103 : 31668 : set_simple_column_names(deparse_namespace *dpns)
4104 : : {
4105 : : ListCell *lc;
4106 : : ListCell *lc2;
4107 : :
4108 : : /* Initialize dpns->rtable_columns to contain zeroed structs */
4109 : 31668 : dpns->rtable_columns = NIL;
4110 [ + + ]: 94356 : while (list_length(dpns->rtable_columns) < list_length(dpns->rtable))
4111 : 62688 : dpns->rtable_columns = lappend(dpns->rtable_columns,
4112 : : palloc0_object(deparse_columns));
4113 : :
4114 : : /* Assign unique column aliases within each non-join RTE */
4115 [ + - + + : 94356 : forboth(lc, dpns->rtable, lc2, dpns->rtable_columns)
+ - + + +
+ + - +
+ ]
4116 : : {
4117 : 62688 : RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
4118 : 62688 : deparse_columns *colinfo = (deparse_columns *) lfirst(lc2);
4119 : :
4120 [ + + ]: 62688 : if (rte->rtekind != RTE_JOIN)
4121 : 58229 : set_relation_column_names(dpns, rte, colinfo);
4122 : : }
4123 : 31668 : }
4124 : :
4125 : : /*
4126 : : * has_dangerous_join_using: search jointree for unnamed JOIN USING
4127 : : *
4128 : : * Merged columns of a JOIN USING may act differently from either of the input
4129 : : * columns, either because they are merged with COALESCE (in a FULL JOIN) or
4130 : : * because an implicit coercion of the underlying input column is required.
4131 : : * In such a case the column must be referenced as a column of the JOIN not as
4132 : : * a column of either input. And this is problematic if the join is unnamed
4133 : : * (alias-less): we cannot qualify the column's name with an RTE name, since
4134 : : * there is none. (Forcibly assigning an alias to the join is not a solution,
4135 : : * since that will prevent legal references to tables below the join.)
4136 : : * To ensure that every column in the query is unambiguously referenceable,
4137 : : * we must assign such merged columns names that are globally unique across
4138 : : * the whole query, aliasing other columns out of the way as necessary.
4139 : : *
4140 : : * Because the ensuing re-aliasing is fairly damaging to the readability of
4141 : : * the query, we don't do this unless we have to. So, we must pre-scan
4142 : : * the join tree to see if we have to, before starting set_using_names().
4143 : : */
4144 : : static bool
4145 : 8494 : has_dangerous_join_using(deparse_namespace *dpns, Node *jtnode)
4146 : : {
4147 [ + + ]: 8494 : if (IsA(jtnode, RangeTblRef))
4148 : : {
4149 : : /* nothing to do here */
4150 : : }
4151 [ + + ]: 4473 : else if (IsA(jtnode, FromExpr))
4152 : : {
4153 : 3577 : FromExpr *f = (FromExpr *) jtnode;
4154 : : ListCell *lc;
4155 : :
4156 [ + + + + : 6754 : foreach(lc, f->fromlist)
+ + ]
4157 : : {
4158 [ + + ]: 3229 : if (has_dangerous_join_using(dpns, (Node *) lfirst(lc)))
4159 : 52 : return true;
4160 : : }
4161 : : }
4162 [ + - ]: 896 : else if (IsA(jtnode, JoinExpr))
4163 : : {
4164 : 896 : JoinExpr *j = (JoinExpr *) jtnode;
4165 : :
4166 : : /* Is it an unnamed JOIN with USING? */
4167 [ + + + + ]: 896 : if (j->alias == NULL && j->usingClause)
4168 : : {
4169 : : /*
4170 : : * Yes, so check each join alias var to see if any of them are not
4171 : : * simple references to underlying columns. If so, we have a
4172 : : * dangerous situation and must pick unique aliases.
4173 : : */
4174 : 188 : RangeTblEntry *jrte = rt_fetch(j->rtindex, dpns->rtable);
4175 : :
4176 : : /* We need only examine the merged columns */
4177 [ + + ]: 388 : for (int i = 0; i < jrte->joinmergedcols; i++)
4178 : : {
4179 : 252 : Node *aliasvar = list_nth(jrte->joinaliasvars, i);
4180 : :
4181 [ + + ]: 252 : if (!IsA(aliasvar, Var))
4182 : 52 : return true;
4183 : : }
4184 : : }
4185 : :
4186 : : /* Nope, but inspect children */
4187 [ - + ]: 844 : if (has_dangerous_join_using(dpns, j->larg))
4188 : 0 : return true;
4189 [ - + ]: 844 : if (has_dangerous_join_using(dpns, j->rarg))
4190 : 0 : return true;
4191 : : }
4192 : : else
4193 [ # # ]: 0 : elog(ERROR, "unrecognized node type: %d",
4194 : : (int) nodeTag(jtnode));
4195 : 8390 : return false;
4196 : : }
4197 : :
4198 : : /*
4199 : : * set_using_names: select column aliases to be used for merged USING columns
4200 : : *
4201 : : * We do this during a recursive descent of the query jointree.
4202 : : * dpns->unique_using must already be set to determine the global strategy.
4203 : : *
4204 : : * Column alias info is saved in the dpns->rtable_columns list, which is
4205 : : * assumed to be filled with pre-zeroed deparse_columns structs.
4206 : : *
4207 : : * parentUsing is a list of all USING aliases assigned in parent joins of
4208 : : * the current jointree node. (The passed-in list must not be modified.)
4209 : : *
4210 : : * Note that we do not use per-deparse_columns hash tables in this function.
4211 : : * The number of names that need to be assigned should be small enough that
4212 : : * we don't need to trouble with that.
4213 : : */
4214 : : static void
4215 : 8714 : set_using_names(deparse_namespace *dpns, Node *jtnode, List *parentUsing)
4216 : : {
4217 [ + + ]: 8714 : if (IsA(jtnode, RangeTblRef))
4218 : : {
4219 : : /* nothing to do now */
4220 : : }
4221 [ + + ]: 4517 : else if (IsA(jtnode, FromExpr))
4222 : : {
4223 : 3577 : FromExpr *f = (FromExpr *) jtnode;
4224 : : ListCell *lc;
4225 : :
4226 [ + + + + : 6834 : foreach(lc, f->fromlist)
+ + ]
4227 : 3257 : set_using_names(dpns, (Node *) lfirst(lc), parentUsing);
4228 : : }
4229 [ + - ]: 940 : else if (IsA(jtnode, JoinExpr))
4230 : : {
4231 : 940 : JoinExpr *j = (JoinExpr *) jtnode;
4232 : 940 : RangeTblEntry *rte = rt_fetch(j->rtindex, dpns->rtable);
4233 : 940 : deparse_columns *colinfo = deparse_columns_fetch(j->rtindex, dpns);
4234 : : int *leftattnos;
4235 : : int *rightattnos;
4236 : : deparse_columns *leftcolinfo;
4237 : : deparse_columns *rightcolinfo;
4238 : : int i;
4239 : : ListCell *lc;
4240 : :
4241 : : /* Get info about the shape of the join */
4242 : 940 : identify_join_columns(j, rte, colinfo);
4243 : 940 : leftattnos = colinfo->leftattnos;
4244 : 940 : rightattnos = colinfo->rightattnos;
4245 : :
4246 : : /* Look up the not-yet-filled-in child deparse_columns structs */
4247 : 940 : leftcolinfo = deparse_columns_fetch(colinfo->leftrti, dpns);
4248 : 940 : rightcolinfo = deparse_columns_fetch(colinfo->rightrti, dpns);
4249 : :
4250 : : /*
4251 : : * If this join is unnamed, then we cannot substitute new aliases at
4252 : : * this level, so any name requirements pushed down to here must be
4253 : : * pushed down again to the children.
4254 : : */
4255 [ + + ]: 940 : if (rte->alias == NULL)
4256 : : {
4257 [ + + ]: 960 : for (i = 0; i < colinfo->num_cols; i++)
4258 : : {
4259 : 92 : char *colname = colinfo->colnames[i];
4260 : :
4261 [ + + ]: 92 : if (colname == NULL)
4262 : 16 : continue;
4263 : :
4264 : : /* Push down to left column, unless it's a system column */
4265 [ + + ]: 76 : if (leftattnos[i] > 0)
4266 : : {
4267 : 68 : expand_colnames_array_to(leftcolinfo, leftattnos[i]);
4268 : 68 : leftcolinfo->colnames[leftattnos[i] - 1] = colname;
4269 : : }
4270 : :
4271 : : /* Same on the righthand side */
4272 [ + - ]: 76 : if (rightattnos[i] > 0)
4273 : : {
4274 : 76 : expand_colnames_array_to(rightcolinfo, rightattnos[i]);
4275 : 76 : rightcolinfo->colnames[rightattnos[i] - 1] = colname;
4276 : : }
4277 : : }
4278 : : }
4279 : :
4280 : : /*
4281 : : * If there's a USING clause, select the USING column names and push
4282 : : * those names down to the children. We have two strategies:
4283 : : *
4284 : : * If dpns->unique_using is true, we force all USING names to be
4285 : : * unique across the whole query level. In principle we'd only need
4286 : : * the names of dangerous USING columns to be globally unique, but to
4287 : : * safely assign all USING names in a single pass, we have to enforce
4288 : : * the same uniqueness rule for all of them. However, if a USING
4289 : : * column's name has been pushed down from the parent, we should use
4290 : : * it as-is rather than making a uniqueness adjustment. This is
4291 : : * necessary when we're at an unnamed join, and it creates no risk of
4292 : : * ambiguity. Also, if there's a user-written output alias for a
4293 : : * merged column, we prefer to use that rather than the input name;
4294 : : * this simplifies the logic and seems likely to lead to less aliasing
4295 : : * overall.
4296 : : *
4297 : : * If dpns->unique_using is false, we only need USING names to be
4298 : : * unique within their own join RTE. We still need to honor
4299 : : * pushed-down names, though.
4300 : : *
4301 : : * Though significantly different in results, these two strategies are
4302 : : * implemented by the same code, with only the difference of whether
4303 : : * to put assigned names into dpns->using_names.
4304 : : */
4305 [ + + ]: 940 : if (j->usingClause)
4306 : : {
4307 : : /* Copy the input parentUsing list so we don't modify it */
4308 : 280 : parentUsing = list_copy(parentUsing);
4309 : :
4310 : : /* USING names must correspond to the first join output columns */
4311 : 280 : expand_colnames_array_to(colinfo, list_length(j->usingClause));
4312 : 280 : i = 0;
4313 [ + - + + : 664 : foreach(lc, j->usingClause)
+ + ]
4314 : : {
4315 : 384 : char *colname = strVal(lfirst(lc));
4316 : :
4317 : : /* Assert it's a merged column */
4318 : : Assert(leftattnos[i] != 0 && rightattnos[i] != 0);
4319 : :
4320 : : /* Adopt passed-down name if any, else select unique name */
4321 [ + + ]: 384 : if (colinfo->colnames[i] != NULL)
4322 : 68 : colname = colinfo->colnames[i];
4323 : : else
4324 : : {
4325 : : /* Prefer user-written output alias if any */
4326 [ + + - + ]: 316 : if (rte->alias && i < list_length(rte->alias->colnames))
4327 : 0 : colname = strVal(list_nth(rte->alias->colnames, i));
4328 : : /* Make it appropriately unique */
4329 : 316 : colname = make_colname_unique(colname, dpns, colinfo);
4330 [ + + ]: 316 : if (dpns->unique_using)
4331 : 88 : dpns->using_names = lappend(dpns->using_names,
4332 : : colname);
4333 : : /* Save it as output column name, too */
4334 : 316 : colinfo->colnames[i] = colname;
4335 : : }
4336 : :
4337 : : /* Remember selected names for use later */
4338 : 384 : colinfo->usingNames = lappend(colinfo->usingNames, colname);
4339 : 384 : parentUsing = lappend(parentUsing, colname);
4340 : :
4341 : : /* Push down to left column, unless it's a system column */
4342 [ + - ]: 384 : if (leftattnos[i] > 0)
4343 : : {
4344 : 384 : expand_colnames_array_to(leftcolinfo, leftattnos[i]);
4345 : 384 : leftcolinfo->colnames[leftattnos[i] - 1] = colname;
4346 : : }
4347 : :
4348 : : /* Same on the righthand side */
4349 [ + - ]: 384 : if (rightattnos[i] > 0)
4350 : : {
4351 : 384 : expand_colnames_array_to(rightcolinfo, rightattnos[i]);
4352 : 384 : rightcolinfo->colnames[rightattnos[i] - 1] = colname;
4353 : : }
4354 : :
4355 : 384 : i++;
4356 : : }
4357 : : }
4358 : :
4359 : : /* Mark child deparse_columns structs with correct parentUsing info */
4360 : 940 : leftcolinfo->parentUsing = parentUsing;
4361 : 940 : rightcolinfo->parentUsing = parentUsing;
4362 : :
4363 : : /* Now recursively assign USING column names in children */
4364 : 940 : set_using_names(dpns, j->larg, parentUsing);
4365 : 940 : set_using_names(dpns, j->rarg, parentUsing);
4366 : : }
4367 : : else
4368 [ # # ]: 0 : elog(ERROR, "unrecognized node type: %d",
4369 : : (int) nodeTag(jtnode));
4370 : 8714 : }
4371 : :
4372 : : /*
4373 : : * set_relation_column_names: select column aliases for a non-join RTE
4374 : : *
4375 : : * Column alias info is saved in *colinfo, which is assumed to be pre-zeroed.
4376 : : * If any colnames entries are already filled in, those override local
4377 : : * choices.
4378 : : */
4379 : : static void
4380 : 63675 : set_relation_column_names(deparse_namespace *dpns, RangeTblEntry *rte,
4381 : : deparse_columns *colinfo)
4382 : : {
4383 : : int ncolumns;
4384 : : char **real_colnames;
4385 : : bool changed_any;
4386 : : int noldcolumns;
4387 : : int i;
4388 : : int j;
4389 : :
4390 : : /*
4391 : : * Construct an array of the current "real" column names of the RTE.
4392 : : * real_colnames[] will be indexed by physical column number, with NULL
4393 : : * entries for dropped columns.
4394 : : */
4395 [ + + ]: 63675 : if (rte->rtekind == RTE_RELATION)
4396 : : {
4397 : : /* Relation --- look to the system catalogs for up-to-date info */
4398 : : Relation rel;
4399 : : TupleDesc tupdesc;
4400 : :
4401 : 53227 : rel = relation_open(rte->relid, AccessShareLock);
4402 : 53227 : tupdesc = RelationGetDescr(rel);
4403 : :
4404 : 53227 : ncolumns = tupdesc->natts;
4405 : 53227 : real_colnames = palloc_array(char *, ncolumns);
4406 : :
4407 [ + + ]: 334265 : for (i = 0; i < ncolumns; i++)
4408 : : {
4409 : 281038 : Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
4410 : :
4411 [ + + ]: 281038 : if (attr->attisdropped)
4412 : 1894 : real_colnames[i] = NULL;
4413 : : else
4414 : 279144 : real_colnames[i] = pstrdup(NameStr(attr->attname));
4415 : : }
4416 : 53227 : relation_close(rel, AccessShareLock);
4417 : : }
4418 : : else
4419 : : {
4420 : : /* Otherwise get the column names from eref or expandRTE() */
4421 : : List *colnames;
4422 : : ListCell *lc;
4423 : :
4424 : : /*
4425 : : * Functions returning composites have the annoying property that some
4426 : : * of the composite type's columns might have been dropped since the
4427 : : * query was parsed. If possible, use expandRTE() to handle that
4428 : : * case, since it has the tedious logic needed to find out about
4429 : : * dropped columns. However, if we're explaining a plan, then we
4430 : : * don't have rte->functions because the planner thinks that won't be
4431 : : * needed later, and that breaks expandRTE(). So in that case we have
4432 : : * to rely on rte->eref, which may lead us to report a dropped
4433 : : * column's old name; that seems close enough for EXPLAIN's purposes.
4434 : : *
4435 : : * For non-RELATION, non-FUNCTION RTEs, we can just look at rte->eref,
4436 : : * which should be sufficiently up-to-date: no other RTE types can
4437 : : * have columns get dropped from under them after parsing.
4438 : : */
4439 [ + + + + ]: 10448 : if (rte->rtekind == RTE_FUNCTION && rte->functions != NIL)
4440 : : {
4441 : : /* Since we're not creating Vars, rtindex etc. don't matter */
4442 : 560 : expandRTE(rte, 1, 0, VAR_RETURNING_DEFAULT, -1,
4443 : : true /* include dropped */ , &colnames, NULL);
4444 : : }
4445 : : else
4446 : 9888 : colnames = rte->eref->colnames;
4447 : :
4448 : 10448 : ncolumns = list_length(colnames);
4449 : 10448 : real_colnames = palloc_array(char *, ncolumns);
4450 : :
4451 : 10448 : i = 0;
4452 [ + + + + : 33391 : foreach(lc, colnames)
+ + ]
4453 : : {
4454 : : /*
4455 : : * If the column name we find here is an empty string, then it's a
4456 : : * dropped column, so change to NULL.
4457 : : */
4458 : 22943 : char *cname = strVal(lfirst(lc));
4459 : :
4460 [ + + ]: 22943 : if (cname[0] == '\0')
4461 : 36 : cname = NULL;
4462 : 22943 : real_colnames[i] = cname;
4463 : 22943 : i++;
4464 : : }
4465 : : }
4466 : :
4467 : : /*
4468 : : * Ensure colinfo->colnames has a slot for each column. (It could be long
4469 : : * enough already, if we pushed down a name for the last column.) Note:
4470 : : * it's possible that there are now more columns than there were when the
4471 : : * query was parsed, ie colnames could be longer than rte->eref->colnames.
4472 : : * We must assign unique aliases to the new columns too, else there could
4473 : : * be unresolved conflicts when the view/rule is reloaded.
4474 : : */
4475 : 63675 : expand_colnames_array_to(colinfo, ncolumns);
4476 : : Assert(colinfo->num_cols == ncolumns);
4477 : :
4478 : : /*
4479 : : * Make sufficiently large new_colnames and is_new_col arrays, too.
4480 : : *
4481 : : * Note: because we leave colinfo->num_new_cols zero until after the loop,
4482 : : * colname_is_unique will not consult that array, which is fine because it
4483 : : * would only be duplicate effort.
4484 : : */
4485 : 63675 : colinfo->new_colnames = palloc_array(char *, ncolumns);
4486 : 63675 : colinfo->is_new_col = palloc_array(bool, ncolumns);
4487 : :
4488 : : /* If the RTE is wide enough, use a hash table to avoid O(N^2) costs */
4489 : 63675 : build_colinfo_names_hash(colinfo);
4490 : :
4491 : : /*
4492 : : * Scan the columns, select a unique alias for each one, and store it in
4493 : : * colinfo->colnames and colinfo->new_colnames. The former array has NULL
4494 : : * entries for dropped columns, the latter omits them. Also mark
4495 : : * new_colnames entries as to whether they are new since parse time; this
4496 : : * is the case for entries beyond the length of rte->eref->colnames.
4497 : : */
4498 : 63675 : noldcolumns = list_length(rte->eref->colnames);
4499 : 63675 : changed_any = false;
4500 : 63675 : j = 0;
4501 [ + + ]: 367656 : for (i = 0; i < ncolumns; i++)
4502 : : {
4503 : 303981 : char *real_colname = real_colnames[i];
4504 : 303981 : char *colname = colinfo->colnames[i];
4505 : :
4506 : : /* Skip dropped columns */
4507 [ + + ]: 303981 : if (real_colname == NULL)
4508 : : {
4509 : : Assert(colname == NULL); /* colnames[i] is already NULL */
4510 : 1930 : continue;
4511 : : }
4512 : :
4513 : : /* If alias already assigned, that's what to use */
4514 [ + + ]: 302051 : if (colname == NULL)
4515 : : {
4516 : : /* If user wrote an alias, prefer that over real column name */
4517 [ + + + + ]: 301351 : if (rte->alias && i < list_length(rte->alias->colnames))
4518 : 30198 : colname = strVal(list_nth(rte->alias->colnames, i));
4519 : : else
4520 : 271153 : colname = real_colname;
4521 : :
4522 : : /* Unique-ify and insert into colinfo */
4523 : 301351 : colname = make_colname_unique(colname, dpns, colinfo);
4524 : :
4525 : 301351 : colinfo->colnames[i] = colname;
4526 : 301351 : add_to_names_hash(colinfo, colname);
4527 : : }
4528 : :
4529 : : /* Put names of non-dropped columns in new_colnames[] too */
4530 : 302051 : colinfo->new_colnames[j] = colname;
4531 : : /* And mark them as new or not */
4532 : 302051 : colinfo->is_new_col[j] = (i >= noldcolumns);
4533 : 302051 : j++;
4534 : :
4535 : : /* Remember if any assigned aliases differ from "real" name */
4536 [ + + + + ]: 302051 : if (!changed_any && strcmp(colname, real_colname) != 0)
4537 : 805 : changed_any = true;
4538 : : }
4539 : :
4540 : : /* We're now done needing the colinfo's names_hash */
4541 : 63675 : destroy_colinfo_names_hash(colinfo);
4542 : :
4543 : : /*
4544 : : * Set correct length for new_colnames[] array. (Note: if columns have
4545 : : * been added, colinfo->num_cols includes them, which is not really quite
4546 : : * right but is harmless, since any new columns must be at the end where
4547 : : * they won't affect varattnos of pre-existing columns.)
4548 : : */
4549 : 63675 : colinfo->num_new_cols = j;
4550 : :
4551 : : /*
4552 : : * For a relation RTE, we need only print the alias column names if any
4553 : : * are different from the underlying "real" names. For a function RTE,
4554 : : * always emit a complete column alias list; this is to protect against
4555 : : * possible instability of the default column names (eg, from altering
4556 : : * parameter names). For tablefunc RTEs, we never print aliases, because
4557 : : * the column names are part of the clause itself. For other RTE types,
4558 : : * print if we changed anything OR if there were user-written column
4559 : : * aliases (since the latter would be part of the underlying "reality").
4560 : : */
4561 [ + + ]: 63675 : if (rte->rtekind == RTE_RELATION)
4562 : 53227 : colinfo->printaliases = changed_any;
4563 [ + + ]: 10448 : else if (rte->rtekind == RTE_FUNCTION)
4564 : 1010 : colinfo->printaliases = true;
4565 [ + + ]: 9438 : else if (rte->rtekind == RTE_TABLEFUNC)
4566 : 126 : colinfo->printaliases = false;
4567 [ + + + + ]: 9312 : else if (rte->alias && rte->alias->colnames != NIL)
4568 : 540 : colinfo->printaliases = true;
4569 : : else
4570 : 8772 : colinfo->printaliases = changed_any;
4571 : 63675 : }
4572 : :
4573 : : /*
4574 : : * set_join_column_names: select column aliases for a join RTE
4575 : : *
4576 : : * Column alias info is saved in *colinfo, which is assumed to be pre-zeroed.
4577 : : * If any colnames entries are already filled in, those override local
4578 : : * choices. Also, names for USING columns were already chosen by
4579 : : * set_using_names(). We further expect that column alias selection has been
4580 : : * completed for both input RTEs.
4581 : : */
4582 : : static void
4583 : 940 : set_join_column_names(deparse_namespace *dpns, RangeTblEntry *rte,
4584 : : deparse_columns *colinfo)
4585 : : {
4586 : : deparse_columns *leftcolinfo;
4587 : : deparse_columns *rightcolinfo;
4588 : : bool changed_any;
4589 : : int noldcolumns;
4590 : : int nnewcolumns;
4591 : 940 : Bitmapset *leftmerged = NULL;
4592 : 940 : Bitmapset *rightmerged = NULL;
4593 : : int i;
4594 : : int j;
4595 : : int ic;
4596 : : int jc;
4597 : :
4598 : : /* Look up the previously-filled-in child deparse_columns structs */
4599 : 940 : leftcolinfo = deparse_columns_fetch(colinfo->leftrti, dpns);
4600 : 940 : rightcolinfo = deparse_columns_fetch(colinfo->rightrti, dpns);
4601 : :
4602 : : /*
4603 : : * Ensure colinfo->colnames has a slot for each column. (It could be long
4604 : : * enough already, if we pushed down a name for the last column.) Note:
4605 : : * it's possible that one or both inputs now have more columns than there
4606 : : * were when the query was parsed, but we'll deal with that below. We
4607 : : * only need entries in colnames for pre-existing columns.
4608 : : */
4609 : 940 : noldcolumns = list_length(rte->eref->colnames);
4610 : 940 : expand_colnames_array_to(colinfo, noldcolumns);
4611 : : Assert(colinfo->num_cols == noldcolumns);
4612 : :
4613 : : /* If the RTE is wide enough, use a hash table to avoid O(N^2) costs */
4614 : 940 : build_colinfo_names_hash(colinfo);
4615 : :
4616 : : /*
4617 : : * Scan the join output columns, select an alias for each one, and store
4618 : : * it in colinfo->colnames. If there are USING columns, set_using_names()
4619 : : * already selected their names, so we can start the loop at the first
4620 : : * non-merged column.
4621 : : */
4622 : 940 : changed_any = false;
4623 [ + + ]: 30521 : for (i = list_length(colinfo->usingNames); i < noldcolumns; i++)
4624 : : {
4625 : 29581 : char *colname = colinfo->colnames[i];
4626 : : char *real_colname;
4627 : :
4628 : : /* Join column must refer to at least one input column */
4629 : : Assert(colinfo->leftattnos[i] != 0 || colinfo->rightattnos[i] != 0);
4630 : :
4631 : : /* Get the child column name */
4632 [ + + ]: 29581 : if (colinfo->leftattnos[i] > 0)
4633 : 20735 : real_colname = leftcolinfo->colnames[colinfo->leftattnos[i] - 1];
4634 [ + - ]: 8846 : else if (colinfo->rightattnos[i] > 0)
4635 : 8846 : real_colname = rightcolinfo->colnames[colinfo->rightattnos[i] - 1];
4636 : : else
4637 : : {
4638 : : /* We're joining system columns --- use eref name */
4639 : 0 : real_colname = strVal(list_nth(rte->eref->colnames, i));
4640 : : }
4641 : :
4642 : : /* If child col has been dropped, no need to assign a join colname */
4643 [ + + ]: 29581 : if (real_colname == NULL)
4644 : : {
4645 : 4 : colinfo->colnames[i] = NULL;
4646 : 4 : continue;
4647 : : }
4648 : :
4649 : : /* In an unnamed join, just report child column names as-is */
4650 [ + + ]: 29577 : if (rte->alias == NULL)
4651 : : {
4652 : 29325 : colinfo->colnames[i] = real_colname;
4653 : 29325 : add_to_names_hash(colinfo, real_colname);
4654 : 29325 : continue;
4655 : : }
4656 : :
4657 : : /* If alias already assigned, that's what to use */
4658 [ + - ]: 252 : if (colname == NULL)
4659 : : {
4660 : : /* If user wrote an alias, prefer that over real column name */
4661 [ + - + + ]: 252 : if (rte->alias && i < list_length(rte->alias->colnames))
4662 : 64 : colname = strVal(list_nth(rte->alias->colnames, i));
4663 : : else
4664 : 188 : colname = real_colname;
4665 : :
4666 : : /* Unique-ify and insert into colinfo */
4667 : 252 : colname = make_colname_unique(colname, dpns, colinfo);
4668 : :
4669 : 252 : colinfo->colnames[i] = colname;
4670 : 252 : add_to_names_hash(colinfo, colname);
4671 : : }
4672 : :
4673 : : /* Remember if any assigned aliases differ from "real" name */
4674 [ + + + + ]: 252 : if (!changed_any && strcmp(colname, real_colname) != 0)
4675 : 16 : changed_any = true;
4676 : : }
4677 : :
4678 : : /*
4679 : : * Calculate number of columns the join would have if it were re-parsed
4680 : : * now, and create storage for the new_colnames and is_new_col arrays.
4681 : : *
4682 : : * Note: colname_is_unique will be consulting new_colnames[] during the
4683 : : * loops below, so its not-yet-filled entries must be zeroes.
4684 : : */
4685 : 1880 : nnewcolumns = leftcolinfo->num_new_cols + rightcolinfo->num_new_cols -
4686 : 940 : list_length(colinfo->usingNames);
4687 : 940 : colinfo->num_new_cols = nnewcolumns;
4688 : 940 : colinfo->new_colnames = palloc0_array(char *, nnewcolumns);
4689 : 940 : colinfo->is_new_col = palloc0_array(bool, nnewcolumns);
4690 : :
4691 : : /*
4692 : : * Generating the new_colnames array is a bit tricky since any new columns
4693 : : * added since parse time must be inserted in the right places. This code
4694 : : * must match the parser, which will order a join's columns as merged
4695 : : * columns first (in USING-clause order), then non-merged columns from the
4696 : : * left input (in attnum order), then non-merged columns from the right
4697 : : * input (ditto). If one of the inputs is itself a join, its columns will
4698 : : * be ordered according to the same rule, which means newly-added columns
4699 : : * might not be at the end. We can figure out what's what by consulting
4700 : : * the leftattnos and rightattnos arrays plus the input is_new_col arrays.
4701 : : *
4702 : : * In these loops, i indexes leftattnos/rightattnos (so it's join varattno
4703 : : * less one), j indexes new_colnames/is_new_col, and ic/jc have similar
4704 : : * meanings for the current child RTE.
4705 : : */
4706 : :
4707 : : /* Handle merged columns; they are first and can't be new */
4708 : 940 : i = j = 0;
4709 : 940 : while (i < noldcolumns &&
4710 [ + - + - ]: 1324 : colinfo->leftattnos[i] != 0 &&
4711 [ + + ]: 1324 : colinfo->rightattnos[i] != 0)
4712 : : {
4713 : : /* column name is already determined and known unique */
4714 : 384 : colinfo->new_colnames[j] = colinfo->colnames[i];
4715 : 384 : colinfo->is_new_col[j] = false;
4716 : :
4717 : : /* build bitmapsets of child attnums of merged columns */
4718 [ + - ]: 384 : if (colinfo->leftattnos[i] > 0)
4719 : 384 : leftmerged = bms_add_member(leftmerged, colinfo->leftattnos[i]);
4720 [ + - ]: 384 : if (colinfo->rightattnos[i] > 0)
4721 : 384 : rightmerged = bms_add_member(rightmerged, colinfo->rightattnos[i]);
4722 : :
4723 : 384 : i++, j++;
4724 : : }
4725 : :
4726 : : /* Handle non-merged left-child columns */
4727 : 940 : ic = 0;
4728 [ + + ]: 22383 : for (jc = 0; jc < leftcolinfo->num_new_cols; jc++)
4729 : : {
4730 : 21443 : char *child_colname = leftcolinfo->new_colnames[jc];
4731 : :
4732 [ + + ]: 21443 : if (!leftcolinfo->is_new_col[jc])
4733 : : {
4734 : : /* Advance ic to next non-dropped old column of left child */
4735 [ + - ]: 21171 : while (ic < leftcolinfo->num_cols &&
4736 [ + + ]: 21171 : leftcolinfo->colnames[ic] == NULL)
4737 : 56 : ic++;
4738 : : Assert(ic < leftcolinfo->num_cols);
4739 : 21115 : ic++;
4740 : : /* If it is a merged column, we already processed it */
4741 [ + + ]: 21115 : if (bms_is_member(ic, leftmerged))
4742 : 384 : continue;
4743 : : /* Else, advance i to the corresponding existing join column */
4744 [ + - ]: 20735 : while (i < colinfo->num_cols &&
4745 [ + + ]: 20735 : colinfo->colnames[i] == NULL)
4746 : 4 : i++;
4747 : : Assert(i < colinfo->num_cols);
4748 : : Assert(ic == colinfo->leftattnos[i]);
4749 : : /* Use the already-assigned name of this column */
4750 : 20731 : colinfo->new_colnames[j] = colinfo->colnames[i];
4751 : 20731 : i++;
4752 : : }
4753 : : else
4754 : : {
4755 : : /*
4756 : : * Unique-ify the new child column name and assign, unless we're
4757 : : * in an unnamed join, in which case just copy
4758 : : */
4759 [ + + ]: 328 : if (rte->alias != NULL)
4760 : : {
4761 : 176 : colinfo->new_colnames[j] =
4762 : 88 : make_colname_unique(child_colname, dpns, colinfo);
4763 [ + + ]: 88 : if (!changed_any &&
4764 [ + + ]: 72 : strcmp(colinfo->new_colnames[j], child_colname) != 0)
4765 : 8 : changed_any = true;
4766 : : }
4767 : : else
4768 : 240 : colinfo->new_colnames[j] = child_colname;
4769 : 328 : add_to_names_hash(colinfo, colinfo->new_colnames[j]);
4770 : : }
4771 : :
4772 : 21059 : colinfo->is_new_col[j] = leftcolinfo->is_new_col[jc];
4773 : 21059 : j++;
4774 : : }
4775 : :
4776 : : /* Handle non-merged right-child columns in exactly the same way */
4777 : 940 : ic = 0;
4778 [ + + ]: 10282 : for (jc = 0; jc < rightcolinfo->num_new_cols; jc++)
4779 : : {
4780 : 9342 : char *child_colname = rightcolinfo->new_colnames[jc];
4781 : :
4782 [ + + ]: 9342 : if (!rightcolinfo->is_new_col[jc])
4783 : : {
4784 : : /* Advance ic to next non-dropped old column of right child */
4785 [ + - ]: 9230 : while (ic < rightcolinfo->num_cols &&
4786 [ - + ]: 9230 : rightcolinfo->colnames[ic] == NULL)
4787 : 0 : ic++;
4788 : : Assert(ic < rightcolinfo->num_cols);
4789 : 9230 : ic++;
4790 : : /* If it is a merged column, we already processed it */
4791 [ + + ]: 9230 : if (bms_is_member(ic, rightmerged))
4792 : 384 : continue;
4793 : : /* Else, advance i to the corresponding existing join column */
4794 [ + - ]: 8846 : while (i < colinfo->num_cols &&
4795 [ - + ]: 8846 : colinfo->colnames[i] == NULL)
4796 : 0 : i++;
4797 : : Assert(i < colinfo->num_cols);
4798 : : Assert(ic == colinfo->rightattnos[i]);
4799 : : /* Use the already-assigned name of this column */
4800 : 8846 : colinfo->new_colnames[j] = colinfo->colnames[i];
4801 : 8846 : i++;
4802 : : }
4803 : : else
4804 : : {
4805 : : /*
4806 : : * Unique-ify the new child column name and assign, unless we're
4807 : : * in an unnamed join, in which case just copy
4808 : : */
4809 [ + + ]: 112 : if (rte->alias != NULL)
4810 : : {
4811 : 32 : colinfo->new_colnames[j] =
4812 : 16 : make_colname_unique(child_colname, dpns, colinfo);
4813 [ + - ]: 16 : if (!changed_any &&
4814 [ + + ]: 16 : strcmp(colinfo->new_colnames[j], child_colname) != 0)
4815 : 8 : changed_any = true;
4816 : : }
4817 : : else
4818 : 96 : colinfo->new_colnames[j] = child_colname;
4819 : 112 : add_to_names_hash(colinfo, colinfo->new_colnames[j]);
4820 : : }
4821 : :
4822 : 8958 : colinfo->is_new_col[j] = rightcolinfo->is_new_col[jc];
4823 : 8958 : j++;
4824 : : }
4825 : :
4826 : : /* Assert we processed the right number of columns */
4827 : : #ifdef USE_ASSERT_CHECKING
4828 : : while (i < colinfo->num_cols && colinfo->colnames[i] == NULL)
4829 : : i++;
4830 : : Assert(i == colinfo->num_cols);
4831 : : Assert(j == nnewcolumns);
4832 : : #endif
4833 : :
4834 : : /* We're now done needing the colinfo's names_hash */
4835 : 940 : destroy_colinfo_names_hash(colinfo);
4836 : :
4837 : : /*
4838 : : * For a named join, print column aliases if we changed any from the child
4839 : : * names. Unnamed joins cannot print aliases.
4840 : : */
4841 [ + + ]: 940 : if (rte->alias != NULL)
4842 : 72 : colinfo->printaliases = changed_any;
4843 : : else
4844 : 868 : colinfo->printaliases = false;
4845 : 940 : }
4846 : :
4847 : : /*
4848 : : * colname_is_unique: is colname distinct from already-chosen column names?
4849 : : *
4850 : : * dpns is query-wide info, colinfo is for the column's RTE
4851 : : */
4852 : : static bool
4853 : 303654 : colname_is_unique(const char *colname, deparse_namespace *dpns,
4854 : : deparse_columns *colinfo)
4855 : : {
4856 : : int i;
4857 : : ListCell *lc;
4858 : :
4859 : : /*
4860 : : * If we have a hash table, consult that instead of linearly scanning the
4861 : : * colinfo's strings.
4862 : : */
4863 [ + + ]: 303654 : if (colinfo->names_hash)
4864 : : {
4865 [ + + ]: 10922 : if (hash_search(colinfo->names_hash,
4866 : : colname,
4867 : : HASH_FIND,
4868 : : NULL) != NULL)
4869 : 64 : return false;
4870 : : }
4871 : : else
4872 : : {
4873 : : /* Check against already-assigned column aliases within RTE */
4874 [ + + ]: 4054204 : for (i = 0; i < colinfo->num_cols; i++)
4875 : : {
4876 : 3762991 : char *oldname = colinfo->colnames[i];
4877 : :
4878 [ + + + + ]: 3762991 : if (oldname && strcmp(oldname, colname) == 0)
4879 : 1519 : return false;
4880 : : }
4881 : :
4882 : : /*
4883 : : * If we're building a new_colnames array, check that too (this will
4884 : : * be partially but not completely redundant with the previous checks)
4885 : : */
4886 [ + + ]: 292061 : for (i = 0; i < colinfo->num_new_cols; i++)
4887 : : {
4888 : 864 : char *oldname = colinfo->new_colnames[i];
4889 : :
4890 [ + + + + ]: 864 : if (oldname && strcmp(oldname, colname) == 0)
4891 : 16 : return false;
4892 : : }
4893 : :
4894 : : /*
4895 : : * Also check against names already assigned for parent-join USING
4896 : : * cols
4897 : : */
4898 [ + + + + : 292893 : foreach(lc, colinfo->parentUsing)
+ + ]
4899 : : {
4900 : 1700 : char *oldname = (char *) lfirst(lc);
4901 : :
4902 [ + + ]: 1700 : if (strcmp(oldname, colname) == 0)
4903 : 4 : return false;
4904 : : }
4905 : : }
4906 : :
4907 : : /*
4908 : : * Also check against USING-column names that must be globally unique.
4909 : : * These are not hashed, but there should be few of them.
4910 : : */
4911 [ + + + + : 302623 : foreach(lc, dpns->using_names)
+ + ]
4912 : : {
4913 : 600 : char *oldname = (char *) lfirst(lc);
4914 : :
4915 [ + + ]: 600 : if (strcmp(oldname, colname) == 0)
4916 : 28 : return false;
4917 : : }
4918 : :
4919 : 302023 : return true;
4920 : : }
4921 : :
4922 : : /*
4923 : : * make_colname_unique: modify colname if necessary to make it unique
4924 : : *
4925 : : * dpns is query-wide info, colinfo is for the column's RTE
4926 : : */
4927 : : static char *
4928 : 302023 : make_colname_unique(char *colname, deparse_namespace *dpns,
4929 : : deparse_columns *colinfo)
4930 : : {
4931 : : /*
4932 : : * If the selected name isn't unique, append digits to make it so. For a
4933 : : * very long input name, we might have to truncate to stay within
4934 : : * NAMEDATALEN.
4935 : : */
4936 [ + + ]: 302023 : if (!colname_is_unique(colname, dpns, colinfo))
4937 : : {
4938 : 1150 : int colnamelen = strlen(colname);
4939 : 1150 : char *modname = (char *) palloc(colnamelen + 16);
4940 : 1150 : int i = 0;
4941 : :
4942 : : do
4943 : : {
4944 : 1631 : i++;
4945 : : for (;;)
4946 : : {
4947 : 1631 : memcpy(modname, colname, colnamelen);
4948 : 1631 : sprintf(modname + colnamelen, "_%d", i);
4949 [ + - ]: 1631 : if (strlen(modname) < NAMEDATALEN)
4950 : 1631 : break;
4951 : : /* drop chars from colname to keep all the digits */
4952 : 0 : colnamelen = pg_mbcliplen(colname, colnamelen,
4953 : : colnamelen - 1);
4954 : : }
4955 [ + + ]: 1631 : } while (!colname_is_unique(modname, dpns, colinfo));
4956 : 1150 : colname = modname;
4957 : : }
4958 : 302023 : return colname;
4959 : : }
4960 : :
4961 : : /*
4962 : : * expand_colnames_array_to: make colinfo->colnames at least n items long
4963 : : *
4964 : : * Any added array entries are initialized to zero.
4965 : : */
4966 : : static void
4967 : 65807 : expand_colnames_array_to(deparse_columns *colinfo, int n)
4968 : : {
4969 [ + + ]: 65807 : if (n > colinfo->num_cols)
4970 : : {
4971 [ + + ]: 63944 : if (colinfo->colnames == NULL)
4972 : 63008 : colinfo->colnames = palloc0_array(char *, n);
4973 : : else
4974 : 936 : colinfo->colnames = repalloc0_array(colinfo->colnames, char *, colinfo->num_cols, n);
4975 : 63944 : colinfo->num_cols = n;
4976 : : }
4977 : 65807 : }
4978 : :
4979 : : /*
4980 : : * build_colinfo_names_hash: optionally construct a hash table for colinfo
4981 : : */
4982 : : static void
4983 : 64615 : build_colinfo_names_hash(deparse_columns *colinfo)
4984 : : {
4985 : : HASHCTL hash_ctl;
4986 : : int i;
4987 : : ListCell *lc;
4988 : :
4989 : : /*
4990 : : * Use a hash table only for RTEs with at least 32 columns. (The cutoff
4991 : : * is somewhat arbitrary, but let's choose it so that this code does get
4992 : : * exercised in the regression tests.)
4993 : : */
4994 [ + + ]: 64615 : if (colinfo->num_cols < 32)
4995 : 63795 : return;
4996 : :
4997 : : /*
4998 : : * Set up the hash table. The entries are just strings with no other
4999 : : * payload.
5000 : : */
5001 : 820 : hash_ctl.keysize = NAMEDATALEN;
5002 : 820 : hash_ctl.entrysize = NAMEDATALEN;
5003 : 820 : hash_ctl.hcxt = CurrentMemoryContext;
5004 : 1640 : colinfo->names_hash = hash_create("deparse_columns names",
5005 : 820 : colinfo->num_cols + colinfo->num_new_cols,
5006 : : &hash_ctl,
5007 : : HASH_ELEM | HASH_STRINGS | HASH_CONTEXT);
5008 : :
5009 : : /*
5010 : : * Preload the hash table with any names already present (these would have
5011 : : * come from set_using_names).
5012 : : */
5013 [ + + ]: 38320 : for (i = 0; i < colinfo->num_cols; i++)
5014 : : {
5015 : 37500 : char *oldname = colinfo->colnames[i];
5016 : :
5017 [ - + ]: 37500 : if (oldname)
5018 : 0 : add_to_names_hash(colinfo, oldname);
5019 : : }
5020 : :
5021 [ - + ]: 820 : for (i = 0; i < colinfo->num_new_cols; i++)
5022 : : {
5023 : 0 : char *oldname = colinfo->new_colnames[i];
5024 : :
5025 [ # # ]: 0 : if (oldname)
5026 : 0 : add_to_names_hash(colinfo, oldname);
5027 : : }
5028 : :
5029 [ - + - - : 820 : foreach(lc, colinfo->parentUsing)
- + ]
5030 : : {
5031 : 0 : char *oldname = (char *) lfirst(lc);
5032 : :
5033 : 0 : add_to_names_hash(colinfo, oldname);
5034 : : }
5035 : : }
5036 : :
5037 : : /*
5038 : : * add_to_names_hash: add a string to the names_hash, if we're using one
5039 : : */
5040 : : static void
5041 : 331368 : add_to_names_hash(deparse_columns *colinfo, const char *name)
5042 : : {
5043 [ + + ]: 331368 : if (colinfo->names_hash)
5044 : 37500 : (void) hash_search(colinfo->names_hash,
5045 : : name,
5046 : : HASH_ENTER,
5047 : : NULL);
5048 : 331368 : }
5049 : :
5050 : : /*
5051 : : * destroy_colinfo_names_hash: destroy hash table when done with it
5052 : : */
5053 : : static void
5054 : 64615 : destroy_colinfo_names_hash(deparse_columns *colinfo)
5055 : : {
5056 [ + + ]: 64615 : if (colinfo->names_hash)
5057 : : {
5058 : 820 : hash_destroy(colinfo->names_hash);
5059 : 820 : colinfo->names_hash = NULL;
5060 : : }
5061 : 64615 : }
5062 : :
5063 : : /*
5064 : : * identify_join_columns: figure out where columns of a join come from
5065 : : *
5066 : : * Fills the join-specific fields of the colinfo struct, except for
5067 : : * usingNames which is filled later.
5068 : : */
5069 : : static void
5070 : 940 : identify_join_columns(JoinExpr *j, RangeTblEntry *jrte,
5071 : : deparse_columns *colinfo)
5072 : : {
5073 : : int numjoincols;
5074 : : int jcolno;
5075 : : int rcolno;
5076 : : ListCell *lc;
5077 : :
5078 : : /* Extract left/right child RT indexes */
5079 [ + + ]: 940 : if (IsA(j->larg, RangeTblRef))
5080 : 605 : colinfo->leftrti = ((RangeTblRef *) j->larg)->rtindex;
5081 [ + - ]: 335 : else if (IsA(j->larg, JoinExpr))
5082 : 335 : colinfo->leftrti = ((JoinExpr *) j->larg)->rtindex;
5083 : : else
5084 [ # # ]: 0 : elog(ERROR, "unrecognized node type in jointree: %d",
5085 : : (int) nodeTag(j->larg));
5086 [ + - ]: 940 : if (IsA(j->rarg, RangeTblRef))
5087 : 940 : colinfo->rightrti = ((RangeTblRef *) j->rarg)->rtindex;
5088 [ # # ]: 0 : else if (IsA(j->rarg, JoinExpr))
5089 : 0 : colinfo->rightrti = ((JoinExpr *) j->rarg)->rtindex;
5090 : : else
5091 [ # # ]: 0 : elog(ERROR, "unrecognized node type in jointree: %d",
5092 : : (int) nodeTag(j->rarg));
5093 : :
5094 : : /* Assert children will be processed earlier than join in second pass */
5095 : : Assert(colinfo->leftrti < j->rtindex);
5096 : : Assert(colinfo->rightrti < j->rtindex);
5097 : :
5098 : : /* Initialize result arrays with zeroes */
5099 : 940 : numjoincols = list_length(jrte->joinaliasvars);
5100 : : Assert(numjoincols == list_length(jrte->eref->colnames));
5101 : 940 : colinfo->leftattnos = palloc0_array(int, numjoincols);
5102 : 940 : colinfo->rightattnos = palloc0_array(int, numjoincols);
5103 : :
5104 : : /*
5105 : : * Deconstruct RTE's joinleftcols/joinrightcols into desired format.
5106 : : * Recall that the column(s) merged due to USING are the first column(s)
5107 : : * of the join output. We need not do anything special while scanning
5108 : : * joinleftcols, but while scanning joinrightcols we must distinguish
5109 : : * merged from unmerged columns.
5110 : : */
5111 : 940 : jcolno = 0;
5112 [ + - + + : 22059 : foreach(lc, jrte->joinleftcols)
+ + ]
5113 : : {
5114 : 21119 : int leftattno = lfirst_int(lc);
5115 : :
5116 : 21119 : colinfo->leftattnos[jcolno++] = leftattno;
5117 : : }
5118 : 940 : rcolno = 0;
5119 [ + - + + : 10170 : foreach(lc, jrte->joinrightcols)
+ + ]
5120 : : {
5121 : 9230 : int rightattno = lfirst_int(lc);
5122 : :
5123 [ + + ]: 9230 : if (rcolno < jrte->joinmergedcols) /* merged column? */
5124 : 384 : colinfo->rightattnos[rcolno] = rightattno;
5125 : : else
5126 : 8846 : colinfo->rightattnos[jcolno++] = rightattno;
5127 : 9230 : rcolno++;
5128 : : }
5129 : : Assert(jcolno == numjoincols);
5130 : 940 : }
5131 : :
5132 : : /*
5133 : : * get_rtable_name: convenience function to get a previously assigned RTE alias
5134 : : *
5135 : : * The RTE must belong to the topmost namespace level in "context".
5136 : : */
5137 : : static char *
5138 : 4092 : get_rtable_name(int rtindex, deparse_context *context)
5139 : : {
5140 : 4092 : deparse_namespace *dpns = (deparse_namespace *) linitial(context->namespaces);
5141 : :
5142 : : Assert(rtindex > 0 && rtindex <= list_length(dpns->rtable_names));
5143 : 4092 : return (char *) list_nth(dpns->rtable_names, rtindex - 1);
5144 : : }
5145 : :
5146 : : /*
5147 : : * set_deparse_plan: set up deparse_namespace to parse subexpressions
5148 : : * of a given Plan node
5149 : : *
5150 : : * This sets the plan, outer_plan, inner_plan, outer_tlist, inner_tlist,
5151 : : * and index_tlist fields. Caller must already have adjusted the ancestors
5152 : : * list if necessary. Note that the rtable, subplans, and ctes fields do
5153 : : * not need to change when shifting attention to different plan nodes in a
5154 : : * single plan tree.
5155 : : */
5156 : : static void
5157 : 106073 : set_deparse_plan(deparse_namespace *dpns, Plan *plan)
5158 : : {
5159 : 106073 : dpns->plan = plan;
5160 : :
5161 : : /*
5162 : : * We special-case Append and MergeAppend to pretend that the first child
5163 : : * plan is the OUTER referent; we have to interpret OUTER Vars in their
5164 : : * tlists according to one of the children, and the first one is the most
5165 : : * natural choice.
5166 : : */
5167 [ + + ]: 106073 : if (IsA(plan, Append))
5168 : 3002 : dpns->outer_plan = linitial(((Append *) plan)->appendplans);
5169 [ + + ]: 103071 : else if (IsA(plan, MergeAppend))
5170 : 360 : dpns->outer_plan = linitial(((MergeAppend *) plan)->mergeplans);
5171 : : else
5172 : 102711 : dpns->outer_plan = outerPlan(plan);
5173 : :
5174 [ + + ]: 106073 : if (dpns->outer_plan)
5175 : 51379 : dpns->outer_tlist = dpns->outer_plan->targetlist;
5176 : : else
5177 : 54694 : dpns->outer_tlist = NIL;
5178 : :
5179 : : /*
5180 : : * For a SubqueryScan, pretend the subplan is INNER referent. (We don't
5181 : : * use OUTER because that could someday conflict with the normal meaning.)
5182 : : * Likewise, for a CteScan, pretend the subquery's plan is INNER referent.
5183 : : * For a WorkTableScan, locate the parent RecursiveUnion plan node and use
5184 : : * that as INNER referent.
5185 : : *
5186 : : * For MERGE, pretend the ModifyTable's source plan (its outer plan) is
5187 : : * INNER referent. This is the join from the target relation to the data
5188 : : * source, and all INNER_VAR Vars in other parts of the query refer to its
5189 : : * targetlist.
5190 : : *
5191 : : * For ON CONFLICT DO SELECT/UPDATE we just need the inner tlist to point
5192 : : * to the excluded expression's tlist. (Similar to the SubqueryScan we
5193 : : * don't want to reuse OUTER, it's used for RETURNING in some modify table
5194 : : * cases, although not INSERT .. CONFLICT).
5195 : : */
5196 [ + + ]: 106073 : if (IsA(plan, SubqueryScan))
5197 : 589 : dpns->inner_plan = ((SubqueryScan *) plan)->subplan;
5198 [ + + ]: 105484 : else if (IsA(plan, CteScan))
5199 : 405 : dpns->inner_plan = list_nth(dpns->subplans,
5200 : 405 : ((CteScan *) plan)->ctePlanId - 1);
5201 [ + + ]: 105079 : else if (IsA(plan, WorkTableScan))
5202 : 116 : dpns->inner_plan = find_recursive_union(dpns,
5203 : : (WorkTableScan *) plan);
5204 [ + + ]: 104963 : else if (IsA(plan, ModifyTable))
5205 : : {
5206 [ + + ]: 289 : if (((ModifyTable *) plan)->operation == CMD_MERGE)
5207 : 40 : dpns->inner_plan = outerPlan(plan);
5208 : : else
5209 : 249 : dpns->inner_plan = plan;
5210 : : }
5211 : : else
5212 : 104674 : dpns->inner_plan = innerPlan(plan);
5213 : :
5214 [ + + + + ]: 106073 : if (IsA(plan, ModifyTable) && ((ModifyTable *) plan)->operation == CMD_INSERT)
5215 : 141 : dpns->inner_tlist = ((ModifyTable *) plan)->exclRelTlist;
5216 [ + + ]: 105932 : else if (dpns->inner_plan)
5217 : 18754 : dpns->inner_tlist = dpns->inner_plan->targetlist;
5218 : : else
5219 : 87178 : dpns->inner_tlist = NIL;
5220 : :
5221 : : /* Set up referent for INDEX_VAR Vars, if needed */
5222 [ + + ]: 106073 : if (IsA(plan, IndexOnlyScan))
5223 : 2384 : dpns->index_tlist = ((IndexOnlyScan *) plan)->indextlist;
5224 [ + + ]: 103689 : else if (IsA(plan, ForeignScan))
5225 : 1648 : dpns->index_tlist = ((ForeignScan *) plan)->fdw_scan_tlist;
5226 [ + + ]: 102041 : else if (IsA(plan, CustomScan))
5227 : 4 : dpns->index_tlist = ((CustomScan *) plan)->custom_scan_tlist;
5228 : : else
5229 : 102037 : dpns->index_tlist = NIL;
5230 : 106073 : }
5231 : :
5232 : : /*
5233 : : * Locate the ancestor plan node that is the RecursiveUnion generating
5234 : : * the WorkTableScan's work table. We can match on wtParam, since that
5235 : : * should be unique within the plan tree.
5236 : : */
5237 : : static Plan *
5238 : 116 : find_recursive_union(deparse_namespace *dpns, WorkTableScan *wtscan)
5239 : : {
5240 : : ListCell *lc;
5241 : :
5242 [ + - + - : 292 : foreach(lc, dpns->ancestors)
+ - ]
5243 : : {
5244 : 292 : Plan *ancestor = (Plan *) lfirst(lc);
5245 : :
5246 [ + + ]: 292 : if (IsA(ancestor, RecursiveUnion) &&
5247 [ + - ]: 116 : ((RecursiveUnion *) ancestor)->wtParam == wtscan->wtParam)
5248 : 116 : return ancestor;
5249 : : }
5250 [ # # ]: 0 : elog(ERROR, "could not find RecursiveUnion for WorkTableScan with wtParam %d",
5251 : : wtscan->wtParam);
5252 : : return NULL;
5253 : : }
5254 : :
5255 : : /*
5256 : : * push_child_plan: temporarily transfer deparsing attention to a child plan
5257 : : *
5258 : : * When expanding an OUTER_VAR or INNER_VAR reference, we must adjust the
5259 : : * deparse context in case the referenced expression itself uses
5260 : : * OUTER_VAR/INNER_VAR. We modify the top stack entry in-place to avoid
5261 : : * affecting levelsup issues (although in a Plan tree there really shouldn't
5262 : : * be any).
5263 : : *
5264 : : * Caller must provide a local deparse_namespace variable to save the
5265 : : * previous state for pop_child_plan.
5266 : : */
5267 : : static void
5268 : 61555 : push_child_plan(deparse_namespace *dpns, Plan *plan,
5269 : : deparse_namespace *save_dpns)
5270 : : {
5271 : : /* Save state for restoration later */
5272 : 61555 : *save_dpns = *dpns;
5273 : :
5274 : : /* Link current plan node into ancestors list */
5275 : 61555 : dpns->ancestors = lcons(dpns->plan, dpns->ancestors);
5276 : :
5277 : : /* Set attention on selected child */
5278 : 61555 : set_deparse_plan(dpns, plan);
5279 : 61555 : }
5280 : :
5281 : : /*
5282 : : * pop_child_plan: undo the effects of push_child_plan
5283 : : */
5284 : : static void
5285 : 61555 : pop_child_plan(deparse_namespace *dpns, deparse_namespace *save_dpns)
5286 : : {
5287 : : List *ancestors;
5288 : :
5289 : : /* Get rid of ancestors list cell added by push_child_plan */
5290 : 61555 : ancestors = list_delete_first(dpns->ancestors);
5291 : :
5292 : : /* Restore fields changed by push_child_plan */
5293 : 61555 : *dpns = *save_dpns;
5294 : :
5295 : : /* Make sure dpns->ancestors is right (may be unnecessary) */
5296 : 61555 : dpns->ancestors = ancestors;
5297 : 61555 : }
5298 : :
5299 : : /*
5300 : : * push_ancestor_plan: temporarily transfer deparsing attention to an
5301 : : * ancestor plan
5302 : : *
5303 : : * When expanding a Param reference, we must adjust the deparse context
5304 : : * to match the plan node that contains the expression being printed;
5305 : : * otherwise we'd fail if that expression itself contains a Param or
5306 : : * OUTER_VAR/INNER_VAR/INDEX_VAR variable.
5307 : : *
5308 : : * The target ancestor is conveniently identified by the ListCell holding it
5309 : : * in dpns->ancestors.
5310 : : *
5311 : : * Caller must provide a local deparse_namespace variable to save the
5312 : : * previous state for pop_ancestor_plan.
5313 : : */
5314 : : static void
5315 : 3387 : push_ancestor_plan(deparse_namespace *dpns, ListCell *ancestor_cell,
5316 : : deparse_namespace *save_dpns)
5317 : : {
5318 : 3387 : Plan *plan = (Plan *) lfirst(ancestor_cell);
5319 : :
5320 : : /* Save state for restoration later */
5321 : 3387 : *save_dpns = *dpns;
5322 : :
5323 : : /* Build a new ancestor list with just this node's ancestors */
5324 : 3387 : dpns->ancestors =
5325 : 3387 : list_copy_tail(dpns->ancestors,
5326 : 3387 : list_cell_number(dpns->ancestors, ancestor_cell) + 1);
5327 : :
5328 : : /* Set attention on selected ancestor */
5329 : 3387 : set_deparse_plan(dpns, plan);
5330 : 3387 : }
5331 : :
5332 : : /*
5333 : : * pop_ancestor_plan: undo the effects of push_ancestor_plan
5334 : : */
5335 : : static void
5336 : 3387 : pop_ancestor_plan(deparse_namespace *dpns, deparse_namespace *save_dpns)
5337 : : {
5338 : : /* Free the ancestor list made in push_ancestor_plan */
5339 : 3387 : list_free(dpns->ancestors);
5340 : :
5341 : : /* Restore fields changed by push_ancestor_plan */
5342 : 3387 : *dpns = *save_dpns;
5343 : 3387 : }
5344 : :
5345 : :
5346 : : /* ----------
5347 : : * make_ruledef - reconstruct the CREATE RULE command
5348 : : * for a given pg_rewrite tuple
5349 : : * ----------
5350 : : */
5351 : : static void
5352 : 309 : make_ruledef(StringInfo buf, HeapTuple ruletup, TupleDesc rulettc,
5353 : : int prettyFlags)
5354 : : {
5355 : : char *rulename;
5356 : : char ev_type;
5357 : : Oid ev_class;
5358 : : bool is_instead;
5359 : : char *ev_qual;
5360 : : char *ev_action;
5361 : : List *actions;
5362 : : Relation ev_relation;
5363 : 309 : TupleDesc viewResultDesc = NULL;
5364 : : int fno;
5365 : : Datum dat;
5366 : : bool isnull;
5367 : :
5368 : : /*
5369 : : * Get the attribute values from the rules tuple
5370 : : */
5371 : 309 : fno = SPI_fnumber(rulettc, "rulename");
5372 : 309 : dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
5373 : : Assert(!isnull);
5374 : 309 : rulename = NameStr(*(DatumGetName(dat)));
5375 : :
5376 : 309 : fno = SPI_fnumber(rulettc, "ev_type");
5377 : 309 : dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
5378 : : Assert(!isnull);
5379 : 309 : ev_type = DatumGetChar(dat);
5380 : :
5381 : 309 : fno = SPI_fnumber(rulettc, "ev_class");
5382 : 309 : dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
5383 : : Assert(!isnull);
5384 : 309 : ev_class = DatumGetObjectId(dat);
5385 : :
5386 : 309 : fno = SPI_fnumber(rulettc, "is_instead");
5387 : 309 : dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
5388 : : Assert(!isnull);
5389 : 309 : is_instead = DatumGetBool(dat);
5390 : :
5391 : 309 : fno = SPI_fnumber(rulettc, "ev_qual");
5392 : 309 : ev_qual = SPI_getvalue(ruletup, rulettc, fno);
5393 : : Assert(ev_qual != NULL);
5394 : :
5395 : 309 : fno = SPI_fnumber(rulettc, "ev_action");
5396 : 309 : ev_action = SPI_getvalue(ruletup, rulettc, fno);
5397 : : Assert(ev_action != NULL);
5398 : 309 : actions = (List *) stringToNode(ev_action);
5399 [ - + ]: 309 : if (actions == NIL)
5400 [ # # ]: 0 : elog(ERROR, "invalid empty ev_action list");
5401 : :
5402 : 309 : ev_relation = table_open(ev_class, AccessShareLock);
5403 : :
5404 : : /*
5405 : : * Build the rules definition text
5406 : : */
5407 : 309 : appendStringInfo(buf, "CREATE RULE %s AS",
5408 : : quote_identifier(rulename));
5409 : :
5410 [ + - ]: 309 : if (prettyFlags & PRETTYFLAG_INDENT)
5411 : 309 : appendStringInfoString(buf, "\n ON ");
5412 : : else
5413 : 0 : appendStringInfoString(buf, " ON ");
5414 : :
5415 : : /* The event the rule is fired for */
5416 [ + + + + : 309 : switch (ev_type)
- ]
5417 : : {
5418 : 4 : case '1':
5419 : 4 : appendStringInfoString(buf, "SELECT");
5420 : 4 : viewResultDesc = RelationGetDescr(ev_relation);
5421 : 4 : break;
5422 : :
5423 : 84 : case '2':
5424 : 84 : appendStringInfoString(buf, "UPDATE");
5425 : 84 : break;
5426 : :
5427 : 165 : case '3':
5428 : 165 : appendStringInfoString(buf, "INSERT");
5429 : 165 : break;
5430 : :
5431 : 56 : case '4':
5432 : 56 : appendStringInfoString(buf, "DELETE");
5433 : 56 : break;
5434 : :
5435 : 0 : default:
5436 [ # # ]: 0 : ereport(ERROR,
5437 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5438 : : errmsg("rule \"%s\" has unsupported event type %d",
5439 : : rulename, ev_type)));
5440 : : break;
5441 : : }
5442 : :
5443 : : /* The relation the rule is fired on */
5444 : 309 : appendStringInfo(buf, " TO %s",
5445 [ + + ]: 309 : (prettyFlags & PRETTYFLAG_SCHEMA) ?
5446 : 76 : generate_relation_name(ev_class, NIL) :
5447 : 233 : generate_qualified_relation_name(ev_class));
5448 : :
5449 : : /* If the rule has an event qualification, add it */
5450 [ + + ]: 309 : if (strcmp(ev_qual, "<>") != 0)
5451 : : {
5452 : : Node *qual;
5453 : : Query *query;
5454 : : deparse_context context;
5455 : : deparse_namespace dpns;
5456 : :
5457 [ + - ]: 62 : if (prettyFlags & PRETTYFLAG_INDENT)
5458 : 62 : appendStringInfoString(buf, "\n ");
5459 : 62 : appendStringInfoString(buf, " WHERE ");
5460 : :
5461 : 62 : qual = stringToNode(ev_qual);
5462 : :
5463 : : /*
5464 : : * We need to make a context for recognizing any Vars in the qual
5465 : : * (which can only be references to OLD and NEW). Use the rtable of
5466 : : * the first query in the action list for this purpose.
5467 : : */
5468 : 62 : query = (Query *) linitial(actions);
5469 : :
5470 : : /*
5471 : : * If the action is INSERT...SELECT, OLD/NEW have been pushed down
5472 : : * into the SELECT, and that's what we need to look at. (Ugly kluge
5473 : : * ... try to fix this when we redesign querytrees.)
5474 : : */
5475 : 62 : query = getInsertSelectQuery(query, NULL);
5476 : :
5477 : : /* Must acquire locks right away; see notes in get_query_def() */
5478 : 62 : AcquireRewriteLocks(query, false, false);
5479 : :
5480 : 62 : context.buf = buf;
5481 : 62 : context.namespaces = list_make1(&dpns);
5482 : 62 : context.resultDesc = NULL;
5483 : 62 : context.targetList = NIL;
5484 : 62 : context.windowClause = NIL;
5485 : 62 : context.varprefix = (list_length(query->rtable) != 1);
5486 : 62 : context.prettyFlags = prettyFlags;
5487 : 62 : context.wrapColumn = WRAP_COLUMN_DEFAULT;
5488 : 62 : context.indentLevel = PRETTYINDENT_STD;
5489 : 62 : context.colNamesVisible = true;
5490 : 62 : context.inGroupBy = false;
5491 : 62 : context.varInOrderBy = false;
5492 : 62 : context.appendparents = NULL;
5493 : :
5494 : 62 : set_deparse_for_query(&dpns, query, NIL);
5495 : :
5496 : 62 : get_rule_expr(qual, &context, false);
5497 : : }
5498 : :
5499 : 309 : appendStringInfoString(buf, " DO ");
5500 : :
5501 : : /* The INSTEAD keyword (if so) */
5502 [ + + ]: 309 : if (is_instead)
5503 : 183 : appendStringInfoString(buf, "INSTEAD ");
5504 : :
5505 : : /* Finally the rules actions */
5506 [ + + ]: 309 : if (list_length(actions) > 1)
5507 : : {
5508 : : ListCell *action;
5509 : : Query *query;
5510 : :
5511 : 10 : appendStringInfoChar(buf, '(');
5512 [ + - + + : 30 : foreach(action, actions)
+ + ]
5513 : : {
5514 : 20 : query = (Query *) lfirst(action);
5515 : 20 : get_query_def(query, buf, NIL, viewResultDesc, true,
5516 : : prettyFlags, WRAP_COLUMN_DEFAULT, 0);
5517 [ + - ]: 20 : if (prettyFlags)
5518 : 20 : appendStringInfoString(buf, ";\n");
5519 : : else
5520 : 0 : appendStringInfoString(buf, "; ");
5521 : : }
5522 : 10 : appendStringInfoString(buf, ");");
5523 : : }
5524 : : else
5525 : : {
5526 : : Query *query;
5527 : :
5528 : 299 : query = (Query *) linitial(actions);
5529 : 299 : get_query_def(query, buf, NIL, viewResultDesc, true,
5530 : : prettyFlags, WRAP_COLUMN_DEFAULT, 0);
5531 : 299 : appendStringInfoChar(buf, ';');
5532 : : }
5533 : :
5534 : 309 : table_close(ev_relation, AccessShareLock);
5535 : 309 : }
5536 : :
5537 : :
5538 : : /* ----------
5539 : : * make_viewdef - reconstruct the SELECT part of a
5540 : : * view rewrite rule
5541 : : * ----------
5542 : : */
5543 : : static void
5544 : 2141 : make_viewdef(StringInfo buf, HeapTuple ruletup, TupleDesc rulettc,
5545 : : int prettyFlags, int wrapColumn)
5546 : : {
5547 : : Query *query;
5548 : : char ev_type;
5549 : : Oid ev_class;
5550 : : bool is_instead;
5551 : : char *ev_qual;
5552 : : char *ev_action;
5553 : : List *actions;
5554 : : Relation ev_relation;
5555 : : int fno;
5556 : : Datum dat;
5557 : : bool isnull;
5558 : :
5559 : : /*
5560 : : * Get the attribute values from the rules tuple
5561 : : */
5562 : 2141 : fno = SPI_fnumber(rulettc, "ev_type");
5563 : 2141 : dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
5564 : : Assert(!isnull);
5565 : 2141 : ev_type = DatumGetChar(dat);
5566 : :
5567 : 2141 : fno = SPI_fnumber(rulettc, "ev_class");
5568 : 2141 : dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
5569 : : Assert(!isnull);
5570 : 2141 : ev_class = DatumGetObjectId(dat);
5571 : :
5572 : 2141 : fno = SPI_fnumber(rulettc, "is_instead");
5573 : 2141 : dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
5574 : : Assert(!isnull);
5575 : 2141 : is_instead = DatumGetBool(dat);
5576 : :
5577 : 2141 : fno = SPI_fnumber(rulettc, "ev_qual");
5578 : 2141 : ev_qual = SPI_getvalue(ruletup, rulettc, fno);
5579 : : Assert(ev_qual != NULL);
5580 : :
5581 : 2141 : fno = SPI_fnumber(rulettc, "ev_action");
5582 : 2141 : ev_action = SPI_getvalue(ruletup, rulettc, fno);
5583 : : Assert(ev_action != NULL);
5584 : 2141 : actions = (List *) stringToNode(ev_action);
5585 : :
5586 [ - + ]: 2141 : if (list_length(actions) != 1)
5587 : : {
5588 : : /* keep output buffer empty and leave */
5589 : 0 : return;
5590 : : }
5591 : :
5592 : 2141 : query = (Query *) linitial(actions);
5593 : :
5594 [ + - + - ]: 2141 : if (ev_type != '1' || !is_instead ||
5595 [ + - - + ]: 2141 : strcmp(ev_qual, "<>") != 0 || query->commandType != CMD_SELECT)
5596 : : {
5597 : : /* keep output buffer empty and leave */
5598 : 0 : return;
5599 : : }
5600 : :
5601 : 2141 : ev_relation = table_open(ev_class, AccessShareLock);
5602 : :
5603 : 2141 : get_query_def(query, buf, NIL, RelationGetDescr(ev_relation), true,
5604 : : prettyFlags, wrapColumn, 0);
5605 : 2141 : appendStringInfoChar(buf, ';');
5606 : :
5607 : 2141 : table_close(ev_relation, AccessShareLock);
5608 : : }
5609 : :
5610 : :
5611 : : /* ----------
5612 : : * get_query_def - Parse back one query parsetree
5613 : : *
5614 : : * query: parsetree to be displayed
5615 : : * buf: output text is appended to buf
5616 : : * parentnamespace: list (initially empty) of outer-level deparse_namespace's
5617 : : * resultDesc: if not NULL, the output tuple descriptor for the view
5618 : : * represented by a SELECT query. We use the column names from it
5619 : : * to label SELECT output columns, in preference to names in the query
5620 : : * colNamesVisible: true if the surrounding context cares about the output
5621 : : * column names at all (as, for example, an EXISTS() context does not);
5622 : : * when false, we can suppress dummy column labels such as "?column?"
5623 : : * prettyFlags: bitmask of PRETTYFLAG_XXX options
5624 : : * wrapColumn: maximum line length, or -1 to disable wrapping
5625 : : * startIndent: initial indentation amount
5626 : : * ----------
5627 : : */
5628 : : static void
5629 : 3500 : get_query_def(Query *query, StringInfo buf, List *parentnamespace,
5630 : : TupleDesc resultDesc, bool colNamesVisible,
5631 : : int prettyFlags, int wrapColumn, int startIndent)
5632 : : {
5633 : : deparse_context context;
5634 : : deparse_namespace dpns;
5635 : : int rtable_size;
5636 : :
5637 : : /* Guard against excessively long or deeply-nested queries */
5638 [ - + ]: 3500 : CHECK_FOR_INTERRUPTS();
5639 : 3500 : check_stack_depth();
5640 : :
5641 : 7000 : rtable_size = query->hasGroupRTE ?
5642 [ + + ]: 3500 : list_length(query->rtable) - 1 :
5643 : 3381 : list_length(query->rtable);
5644 : :
5645 : : /*
5646 : : * Replace any Vars in the query's targetlist and havingQual that
5647 : : * reference GROUP outputs with the underlying grouping expressions.
5648 : : *
5649 : : * We can safely pass NULL for the root here. Preserving varnullingrels
5650 : : * makes no difference to the deparsed source text.
5651 : : */
5652 [ + + ]: 3500 : if (query->hasGroupRTE)
5653 : : {
5654 : 119 : query->targetList = (List *)
5655 : 119 : flatten_group_exprs(NULL, query, (Node *) query->targetList);
5656 : 119 : query->havingQual =
5657 : 119 : flatten_group_exprs(NULL, query, query->havingQual);
5658 : : }
5659 : :
5660 : : /*
5661 : : * Before we begin to examine the query, acquire locks on referenced
5662 : : * relations, and fix up deleted columns in JOIN RTEs. This ensures
5663 : : * consistent results. Note we assume it's OK to scribble on the passed
5664 : : * querytree!
5665 : : *
5666 : : * We are only deparsing the query (we are not about to execute it), so we
5667 : : * only need AccessShareLock on the relations it mentions.
5668 : : */
5669 : 3500 : AcquireRewriteLocks(query, false, false);
5670 : :
5671 : 3500 : context.buf = buf;
5672 : 3500 : context.namespaces = lcons(&dpns, list_copy(parentnamespace));
5673 : 3500 : context.resultDesc = NULL;
5674 : 3500 : context.targetList = NIL;
5675 : 3500 : context.windowClause = NIL;
5676 [ + + + + ]: 3500 : context.varprefix = (parentnamespace != NIL ||
5677 : 3500 : rtable_size != 1);
5678 : 3500 : context.prettyFlags = prettyFlags;
5679 : 3500 : context.wrapColumn = wrapColumn;
5680 : 3500 : context.indentLevel = startIndent;
5681 : 3500 : context.colNamesVisible = colNamesVisible;
5682 : 3500 : context.inGroupBy = false;
5683 : 3500 : context.varInOrderBy = false;
5684 : 3500 : context.appendparents = NULL;
5685 : :
5686 : 3500 : set_deparse_for_query(&dpns, query, parentnamespace);
5687 : :
5688 [ + + + + : 3500 : switch (query->commandType)
+ + + - ]
5689 : : {
5690 : 3142 : case CMD_SELECT:
5691 : : /* We set context.resultDesc only if it's a SELECT */
5692 : 3142 : context.resultDesc = resultDesc;
5693 : 3142 : get_select_query_def(query, &context);
5694 : 3142 : break;
5695 : :
5696 : 86 : case CMD_UPDATE:
5697 : 86 : get_update_query_def(query, &context);
5698 : 86 : break;
5699 : :
5700 : 194 : case CMD_INSERT:
5701 : 194 : get_insert_query_def(query, &context);
5702 : 194 : break;
5703 : :
5704 : 39 : case CMD_DELETE:
5705 : 39 : get_delete_query_def(query, &context);
5706 : 39 : break;
5707 : :
5708 : 8 : case CMD_MERGE:
5709 : 8 : get_merge_query_def(query, &context);
5710 : 8 : break;
5711 : :
5712 : 22 : case CMD_NOTHING:
5713 : 22 : appendStringInfoString(buf, "NOTHING");
5714 : 22 : break;
5715 : :
5716 : 9 : case CMD_UTILITY:
5717 : 9 : get_utility_query_def(query, &context);
5718 : 9 : break;
5719 : :
5720 : 0 : default:
5721 [ # # ]: 0 : elog(ERROR, "unrecognized query command type: %d",
5722 : : query->commandType);
5723 : : break;
5724 : : }
5725 : 3500 : }
5726 : :
5727 : : /* ----------
5728 : : * get_values_def - Parse back a VALUES list
5729 : : * ----------
5730 : : */
5731 : : static void
5732 : 193 : get_values_def(List *values_lists, deparse_context *context)
5733 : : {
5734 : 193 : StringInfo buf = context->buf;
5735 : 193 : bool first_list = true;
5736 : : ListCell *vtl;
5737 : :
5738 : 193 : appendStringInfoString(buf, "VALUES ");
5739 : :
5740 [ + - + + : 581 : foreach(vtl, values_lists)
+ + ]
5741 : : {
5742 : 388 : List *sublist = (List *) lfirst(vtl);
5743 : 388 : bool first_col = true;
5744 : : ListCell *lc;
5745 : :
5746 [ + + ]: 388 : if (first_list)
5747 : 193 : first_list = false;
5748 : : else
5749 : 195 : appendStringInfoString(buf, ", ");
5750 : :
5751 : 388 : appendStringInfoChar(buf, '(');
5752 [ + - + + : 1380 : foreach(lc, sublist)
+ + ]
5753 : : {
5754 : 992 : Node *col = (Node *) lfirst(lc);
5755 : :
5756 [ + + ]: 992 : if (first_col)
5757 : 388 : first_col = false;
5758 : : else
5759 : 604 : appendStringInfoChar(buf, ',');
5760 : :
5761 : : /*
5762 : : * Print the value. Whole-row Vars need special treatment.
5763 : : */
5764 : 992 : get_rule_expr_toplevel(col, context, false);
5765 : : }
5766 : 388 : appendStringInfoChar(buf, ')');
5767 : : }
5768 : 193 : }
5769 : :
5770 : : /* ----------
5771 : : * get_with_clause - Parse back a WITH clause
5772 : : * ----------
5773 : : */
5774 : : static void
5775 : 3469 : get_with_clause(Query *query, deparse_context *context)
5776 : : {
5777 : 3469 : StringInfo buf = context->buf;
5778 : : const char *sep;
5779 : : ListCell *l;
5780 : :
5781 [ + + ]: 3469 : if (query->cteList == NIL)
5782 : 3406 : return;
5783 : :
5784 [ + - ]: 63 : if (PRETTY_INDENT(context))
5785 : : {
5786 : 63 : context->indentLevel += PRETTYINDENT_STD;
5787 : 63 : appendStringInfoChar(buf, ' ');
5788 : : }
5789 : :
5790 [ + + ]: 63 : if (query->hasRecursive)
5791 : 34 : sep = "WITH RECURSIVE ";
5792 : : else
5793 : 29 : sep = "WITH ";
5794 [ + - + + : 156 : foreach(l, query->cteList)
+ + ]
5795 : : {
5796 : 93 : CommonTableExpr *cte = (CommonTableExpr *) lfirst(l);
5797 : :
5798 : 93 : appendStringInfoString(buf, sep);
5799 : 93 : appendStringInfoString(buf, quote_identifier(cte->ctename));
5800 [ + + ]: 93 : if (cte->aliascolnames)
5801 : : {
5802 : 38 : bool first = true;
5803 : : ListCell *col;
5804 : :
5805 : 38 : appendStringInfoChar(buf, '(');
5806 [ + - + + : 100 : foreach(col, cte->aliascolnames)
+ + ]
5807 : : {
5808 [ + + ]: 62 : if (first)
5809 : 38 : first = false;
5810 : : else
5811 : 24 : appendStringInfoString(buf, ", ");
5812 : 62 : appendStringInfoString(buf,
5813 : 62 : quote_identifier(strVal(lfirst(col))));
5814 : : }
5815 : 38 : appendStringInfoChar(buf, ')');
5816 : : }
5817 : 93 : appendStringInfoString(buf, " AS ");
5818 [ + + - - ]: 93 : switch (cte->ctematerialized)
5819 : : {
5820 : 81 : case CTEMaterializeDefault:
5821 : 81 : break;
5822 : 12 : case CTEMaterializeAlways:
5823 : 12 : appendStringInfoString(buf, "MATERIALIZED ");
5824 : 12 : break;
5825 : 0 : case CTEMaterializeNever:
5826 : 0 : appendStringInfoString(buf, "NOT MATERIALIZED ");
5827 : 0 : break;
5828 : : }
5829 : 93 : appendStringInfoChar(buf, '(');
5830 [ + - ]: 93 : if (PRETTY_INDENT(context))
5831 : 93 : appendContextKeyword(context, "", 0, 0, 0);
5832 : 93 : get_query_def((Query *) cte->ctequery, buf, context->namespaces, NULL,
5833 : : true,
5834 : : context->prettyFlags, context->wrapColumn,
5835 : : context->indentLevel);
5836 [ + - ]: 93 : if (PRETTY_INDENT(context))
5837 : 93 : appendContextKeyword(context, "", 0, 0, 0);
5838 : 93 : appendStringInfoChar(buf, ')');
5839 : :
5840 [ + + ]: 93 : if (cte->search_clause)
5841 : : {
5842 : 4 : bool first = true;
5843 : : ListCell *lc;
5844 : :
5845 : 4 : appendStringInfo(buf, " SEARCH %s FIRST BY ",
5846 [ - + ]: 4 : cte->search_clause->search_breadth_first ? "BREADTH" : "DEPTH");
5847 : :
5848 [ + - + + : 12 : foreach(lc, cte->search_clause->search_col_list)
+ + ]
5849 : : {
5850 [ + + ]: 8 : if (first)
5851 : 4 : first = false;
5852 : : else
5853 : 4 : appendStringInfoString(buf, ", ");
5854 : 8 : appendStringInfoString(buf,
5855 : 8 : quote_identifier(strVal(lfirst(lc))));
5856 : : }
5857 : :
5858 : 4 : appendStringInfo(buf, " SET %s", quote_identifier(cte->search_clause->search_seq_column));
5859 : : }
5860 : :
5861 [ + + ]: 93 : if (cte->cycle_clause)
5862 : : {
5863 : 8 : bool first = true;
5864 : : ListCell *lc;
5865 : :
5866 : 8 : appendStringInfoString(buf, " CYCLE ");
5867 : :
5868 [ + - + + : 24 : foreach(lc, cte->cycle_clause->cycle_col_list)
+ + ]
5869 : : {
5870 [ + + ]: 16 : if (first)
5871 : 8 : first = false;
5872 : : else
5873 : 8 : appendStringInfoString(buf, ", ");
5874 : 16 : appendStringInfoString(buf,
5875 : 16 : quote_identifier(strVal(lfirst(lc))));
5876 : : }
5877 : :
5878 : 8 : appendStringInfo(buf, " SET %s", quote_identifier(cte->cycle_clause->cycle_mark_column));
5879 : :
5880 : : {
5881 : 8 : Const *cmv = castNode(Const, cte->cycle_clause->cycle_mark_value);
5882 : 8 : Const *cmd = castNode(Const, cte->cycle_clause->cycle_mark_default);
5883 : :
5884 [ + + + - : 12 : if (!(cmv->consttype == BOOLOID && !cmv->constisnull && DatumGetBool(cmv->constvalue) == true &&
+ - - + ]
5885 [ + - + - ]: 4 : cmd->consttype == BOOLOID && !cmd->constisnull && DatumGetBool(cmd->constvalue) == false))
5886 : : {
5887 : 4 : appendStringInfoString(buf, " TO ");
5888 : 4 : get_rule_expr(cte->cycle_clause->cycle_mark_value, context, false);
5889 : 4 : appendStringInfoString(buf, " DEFAULT ");
5890 : 4 : get_rule_expr(cte->cycle_clause->cycle_mark_default, context, false);
5891 : : }
5892 : : }
5893 : :
5894 : 8 : appendStringInfo(buf, " USING %s", quote_identifier(cte->cycle_clause->cycle_path_column));
5895 : : }
5896 : :
5897 : 93 : sep = ", ";
5898 : : }
5899 : :
5900 [ + - ]: 63 : if (PRETTY_INDENT(context))
5901 : : {
5902 : 63 : context->indentLevel -= PRETTYINDENT_STD;
5903 : 63 : appendContextKeyword(context, "", 0, 0, 0);
5904 : : }
5905 : : else
5906 : 0 : appendStringInfoChar(buf, ' ');
5907 : : }
5908 : :
5909 : : /* ----------
5910 : : * get_select_query_def - Parse back a SELECT parsetree
5911 : : * ----------
5912 : : */
5913 : : static void
5914 : 3142 : get_select_query_def(Query *query, deparse_context *context)
5915 : : {
5916 : 3142 : StringInfo buf = context->buf;
5917 : : bool force_colno;
5918 : : ListCell *l;
5919 : :
5920 : : /* Insert the WITH clause if given */
5921 : 3142 : get_with_clause(query, context);
5922 : :
5923 : : /* Subroutines may need to consult the SELECT targetlist and windowClause */
5924 : 3142 : context->targetList = query->targetList;
5925 : 3142 : context->windowClause = query->windowClause;
5926 : :
5927 : : /*
5928 : : * If the Query node has a setOperations tree, then it's the top level of
5929 : : * a UNION/INTERSECT/EXCEPT query; only the WITH, ORDER BY and LIMIT
5930 : : * fields are interesting in the top query itself.
5931 : : */
5932 [ + + ]: 3142 : if (query->setOperations)
5933 : : {
5934 : 103 : get_setop_query(query->setOperations, query, context);
5935 : : /* ORDER BY clauses must be simple in this case */
5936 : 103 : force_colno = true;
5937 : : }
5938 : : else
5939 : : {
5940 : 3039 : get_basic_select_query(query, context);
5941 : 3039 : force_colno = false;
5942 : : }
5943 : :
5944 : : /* Add the ORDER BY clause if given */
5945 [ + + ]: 3142 : if (query->sortClause != NIL)
5946 : : {
5947 : 119 : appendContextKeyword(context, " ORDER BY ",
5948 : : -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
5949 : 119 : get_rule_orderby(query->sortClause, query->targetList,
5950 : : force_colno, context);
5951 : : }
5952 : :
5953 : : /*
5954 : : * Add the LIMIT/OFFSET clauses if given. If non-default options, use the
5955 : : * standard spelling of LIMIT.
5956 : : */
5957 [ + + ]: 3142 : if (query->limitOffset != NULL)
5958 : : {
5959 : 18 : appendContextKeyword(context, " OFFSET ",
5960 : : -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
5961 : 18 : get_rule_expr(query->limitOffset, context, false);
5962 : : }
5963 [ + + ]: 3142 : if (query->limitCount != NULL)
5964 : : {
5965 [ + + ]: 53 : if (query->limitOption == LIMIT_OPTION_WITH_TIES)
5966 : : {
5967 : : /*
5968 : : * The limitCount arg is a c_expr, so it needs parens. Simple
5969 : : * literals and function expressions would not need parens, but
5970 : : * unfortunately it's hard to tell if the expression will be
5971 : : * printed as a simple literal like 123 or as a typecast
5972 : : * expression, like '-123'::int4. The grammar accepts the former
5973 : : * without quoting, but not the latter.
5974 : : */
5975 : 27 : appendContextKeyword(context, " FETCH FIRST ",
5976 : : -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
5977 : 27 : appendStringInfoChar(buf, '(');
5978 : 27 : get_rule_expr(query->limitCount, context, false);
5979 : 27 : appendStringInfoChar(buf, ')');
5980 : 27 : appendStringInfoString(buf, " ROWS WITH TIES");
5981 : : }
5982 : : else
5983 : : {
5984 : 26 : appendContextKeyword(context, " LIMIT ",
5985 : : -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
5986 [ + + ]: 26 : if (IsA(query->limitCount, Const) &&
5987 [ + - ]: 9 : ((Const *) query->limitCount)->constisnull)
5988 : 9 : appendStringInfoString(buf, "ALL");
5989 : : else
5990 : 17 : get_rule_expr(query->limitCount, context, false);
5991 : : }
5992 : : }
5993 : :
5994 : : /* Add FOR [KEY] UPDATE/SHARE clauses if present */
5995 [ + + ]: 3142 : if (query->hasForUpdate)
5996 : : {
5997 [ + - + + : 8 : foreach(l, query->rowMarks)
+ + ]
5998 : : {
5999 : 4 : RowMarkClause *rc = (RowMarkClause *) lfirst(l);
6000 : :
6001 : : /* don't print implicit clauses */
6002 [ - + ]: 4 : if (rc->pushedDown)
6003 : 0 : continue;
6004 : :
6005 : 4 : appendContextKeyword(context,
6006 : 4 : get_lock_clause_strength(rc->strength),
6007 : : -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
6008 : :
6009 : 4 : appendStringInfo(buf, " OF %s",
6010 : 4 : quote_identifier(get_rtable_name(rc->rti,
6011 : : context)));
6012 [ - + ]: 4 : if (rc->waitPolicy == LockWaitError)
6013 : 0 : appendStringInfoString(buf, " NOWAIT");
6014 [ - + ]: 4 : else if (rc->waitPolicy == LockWaitSkip)
6015 : 0 : appendStringInfoString(buf, " SKIP LOCKED");
6016 : : }
6017 : : }
6018 : 3142 : }
6019 : :
6020 : : static char *
6021 : 8 : get_lock_clause_strength(LockClauseStrength strength)
6022 : : {
6023 [ - - - - : 8 : switch (strength)
+ - ]
6024 : : {
6025 : 0 : case LCS_NONE:
6026 : : /* we intentionally throw an error for LCS_NONE */
6027 [ # # ]: 0 : elog(ERROR, "unrecognized LockClauseStrength %d",
6028 : : (int) strength);
6029 : : break;
6030 : 0 : case LCS_FORKEYSHARE:
6031 : 0 : return " FOR KEY SHARE";
6032 : 0 : case LCS_FORSHARE:
6033 : 0 : return " FOR SHARE";
6034 : 0 : case LCS_FORNOKEYUPDATE:
6035 : 0 : return " FOR NO KEY UPDATE";
6036 : 8 : case LCS_FORUPDATE:
6037 : 8 : return " FOR UPDATE";
6038 : : }
6039 : 0 : return NULL; /* keep compiler quiet */
6040 : : }
6041 : :
6042 : : /*
6043 : : * Detect whether query looks like SELECT ... FROM VALUES(),
6044 : : * with no need to rename the output columns of the VALUES RTE.
6045 : : * If so, return the VALUES RTE. Otherwise return NULL.
6046 : : */
6047 : : static RangeTblEntry *
6048 : 3039 : get_simple_values_rte(Query *query, TupleDesc resultDesc)
6049 : : {
6050 : 3039 : RangeTblEntry *result = NULL;
6051 : : ListCell *lc;
6052 : :
6053 : : /*
6054 : : * We want to detect a match even if the Query also contains OLD or NEW
6055 : : * rule RTEs. So the idea is to scan the rtable and see if there is only
6056 : : * one inFromCl RTE that is a VALUES RTE.
6057 : : */
6058 [ + + + + : 3290 : foreach(lc, query->rtable)
+ + ]
6059 : : {
6060 : 2760 : RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
6061 : :
6062 [ + + + - ]: 2760 : if (rte->rtekind == RTE_VALUES && rte->inFromCl)
6063 : : {
6064 [ - + ]: 167 : if (result)
6065 : 2509 : return NULL; /* multiple VALUES (probably not possible) */
6066 : 167 : result = rte;
6067 : : }
6068 [ + + + + ]: 2593 : else if (rte->rtekind == RTE_RELATION && !rte->inFromCl)
6069 : 84 : continue; /* ignore rule entries */
6070 : : else
6071 : 2509 : return NULL; /* something else -> not simple VALUES */
6072 : : }
6073 : :
6074 : : /*
6075 : : * We don't need to check the targetlist in any great detail, because
6076 : : * parser/analyze.c will never generate a "bare" VALUES RTE --- they only
6077 : : * appear inside auto-generated sub-queries with very restricted
6078 : : * structure. However, DefineView might have modified the tlist by
6079 : : * injecting new column aliases, or we might have some other column
6080 : : * aliases forced by a resultDesc. We can only simplify if the RTE's
6081 : : * column names match the names that get_target_list() would select.
6082 : : */
6083 [ + + ]: 530 : if (result)
6084 : : {
6085 : : ListCell *lcn;
6086 : : int colno;
6087 : :
6088 [ - + ]: 167 : if (list_length(query->targetList) != list_length(result->eref->colnames))
6089 : 0 : return NULL; /* this probably cannot happen */
6090 : 167 : colno = 0;
6091 [ + - + + : 588 : forboth(lc, query->targetList, lcn, result->eref->colnames)
+ - + + +
+ + - +
+ ]
6092 : : {
6093 : 429 : TargetEntry *tle = (TargetEntry *) lfirst(lc);
6094 : 429 : char *cname = strVal(lfirst(lcn));
6095 : : char *colname;
6096 : :
6097 [ - + ]: 429 : if (tle->resjunk)
6098 : 8 : return NULL; /* this probably cannot happen */
6099 : :
6100 : : /* compute name that get_target_list would use for column */
6101 : 429 : colno++;
6102 [ + + + - ]: 429 : if (resultDesc && colno <= resultDesc->natts)
6103 : 20 : colname = NameStr(TupleDescAttr(resultDesc, colno - 1)->attname);
6104 : : else
6105 : 409 : colname = tle->resname;
6106 : :
6107 : : /* does it match the VALUES RTE? */
6108 [ + - + + ]: 429 : if (colname == NULL || strcmp(colname, cname) != 0)
6109 : 8 : return NULL; /* column name has been changed */
6110 : : }
6111 : : }
6112 : :
6113 : 522 : return result;
6114 : : }
6115 : :
6116 : : static void
6117 : 3039 : get_basic_select_query(Query *query, deparse_context *context)
6118 : : {
6119 : 3039 : StringInfo buf = context->buf;
6120 : : RangeTblEntry *values_rte;
6121 : : char *sep;
6122 : : ListCell *l;
6123 : :
6124 [ + + ]: 3039 : if (PRETTY_INDENT(context))
6125 : : {
6126 : 3012 : context->indentLevel += PRETTYINDENT_STD;
6127 : 3012 : appendStringInfoChar(buf, ' ');
6128 : : }
6129 : :
6130 : : /*
6131 : : * If the query looks like SELECT * FROM (VALUES ...), then print just the
6132 : : * VALUES part. This reverses what transformValuesClause() did at parse
6133 : : * time.
6134 : : */
6135 : 3039 : values_rte = get_simple_values_rte(query, context->resultDesc);
6136 [ + + ]: 3039 : if (values_rte)
6137 : : {
6138 : 159 : get_values_def(values_rte->values_lists, context);
6139 : 159 : return;
6140 : : }
6141 : :
6142 : : /*
6143 : : * Build up the query string - first we say SELECT
6144 : : */
6145 [ + + ]: 2880 : if (query->isReturn)
6146 : 31 : appendStringInfoString(buf, "RETURN");
6147 : : else
6148 : 2849 : appendStringInfoString(buf, "SELECT");
6149 : :
6150 : : /* Add the DISTINCT clause if given */
6151 [ - + ]: 2880 : if (query->distinctClause != NIL)
6152 : : {
6153 [ # # ]: 0 : if (query->hasDistinctOn)
6154 : : {
6155 : 0 : appendStringInfoString(buf, " DISTINCT ON (");
6156 : 0 : sep = "";
6157 [ # # # # : 0 : foreach(l, query->distinctClause)
# # ]
6158 : : {
6159 : 0 : SortGroupClause *srt = (SortGroupClause *) lfirst(l);
6160 : :
6161 : 0 : appendStringInfoString(buf, sep);
6162 : 0 : get_rule_sortgroupclause(srt->tleSortGroupRef, query->targetList,
6163 : : false, context);
6164 : 0 : sep = ", ";
6165 : : }
6166 : 0 : appendStringInfoChar(buf, ')');
6167 : : }
6168 : : else
6169 : 0 : appendStringInfoString(buf, " DISTINCT");
6170 : : }
6171 : :
6172 : : /* Then we tell what to select (the targetlist) */
6173 : 2880 : get_target_list(query->targetList, context);
6174 : :
6175 : : /* Add the FROM clause if needed */
6176 : 2880 : get_from_clause(query, " FROM ", context);
6177 : :
6178 : : /* Add the WHERE clause if given */
6179 [ + + ]: 2880 : if (query->jointree->quals != NULL)
6180 : : {
6181 : 903 : appendContextKeyword(context, " WHERE ",
6182 : : -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
6183 : 903 : get_rule_expr(query->jointree->quals, context, false);
6184 : : }
6185 : :
6186 : : /* Add the GROUP BY clause if given */
6187 [ + + - + ]: 2880 : if (query->groupClause != NULL || query->groupingSets != NULL)
6188 : : {
6189 : : bool save_ingroupby;
6190 : :
6191 : 119 : appendContextKeyword(context, " GROUP BY ",
6192 : : -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
6193 [ - + ]: 119 : if (query->groupDistinct)
6194 : 0 : appendStringInfoString(buf, "DISTINCT ");
6195 : :
6196 : 119 : save_ingroupby = context->inGroupBy;
6197 : 119 : context->inGroupBy = true;
6198 : :
6199 [ + + ]: 119 : if (query->groupingSets == NIL)
6200 : : {
6201 : 115 : sep = "";
6202 [ + - + + : 263 : foreach(l, query->groupClause)
+ + ]
6203 : : {
6204 : 148 : SortGroupClause *grp = (SortGroupClause *) lfirst(l);
6205 : :
6206 : 148 : appendStringInfoString(buf, sep);
6207 : 148 : get_rule_sortgroupclause(grp->tleSortGroupRef, query->targetList,
6208 : : false, context);
6209 : 148 : sep = ", ";
6210 : : }
6211 : : }
6212 : : else
6213 : : {
6214 : 4 : sep = "";
6215 [ + - + + : 8 : foreach(l, query->groupingSets)
+ + ]
6216 : : {
6217 : 4 : GroupingSet *grp = lfirst(l);
6218 : :
6219 : 4 : appendStringInfoString(buf, sep);
6220 : 4 : get_rule_groupingset(grp, query->targetList, true, context);
6221 : 4 : sep = ", ";
6222 : : }
6223 : : }
6224 : :
6225 : 119 : context->inGroupBy = save_ingroupby;
6226 : : }
6227 : :
6228 : : /* Add the HAVING clause if given */
6229 [ + + ]: 2880 : if (query->havingQual != NULL)
6230 : : {
6231 : 5 : appendContextKeyword(context, " HAVING ",
6232 : : -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
6233 : 5 : get_rule_expr(query->havingQual, context, false);
6234 : : }
6235 : :
6236 : : /* Add the WINDOW clause if needed */
6237 [ + + ]: 2880 : if (query->windowClause != NIL)
6238 : 32 : get_rule_windowclause(query, context);
6239 : : }
6240 : :
6241 : : /* ----------
6242 : : * get_target_list - Parse back a SELECT target list
6243 : : *
6244 : : * This is also used for RETURNING lists in INSERT/UPDATE/DELETE/MERGE.
6245 : : * ----------
6246 : : */
6247 : : static void
6248 : 2973 : get_target_list(List *targetList, deparse_context *context)
6249 : : {
6250 : 2973 : StringInfo buf = context->buf;
6251 : : StringInfoData targetbuf;
6252 : 2973 : bool last_was_multiline = false;
6253 : : char *sep;
6254 : : int colno;
6255 : : ListCell *l;
6256 : :
6257 : : /* we use targetbuf to hold each TLE's text temporarily */
6258 : 2973 : initStringInfo(&targetbuf);
6259 : :
6260 : 2973 : sep = " ";
6261 : 2973 : colno = 0;
6262 [ + - + + : 15716 : foreach(l, targetList)
+ + ]
6263 : : {
6264 : 12743 : TargetEntry *tle = (TargetEntry *) lfirst(l);
6265 : : char *colname;
6266 : : char *attname;
6267 : :
6268 [ + + ]: 12743 : if (tle->resjunk)
6269 : 25 : continue; /* ignore junk entries */
6270 : :
6271 : 12718 : appendStringInfoString(buf, sep);
6272 : 12718 : sep = ", ";
6273 : 12718 : colno++;
6274 : :
6275 : : /*
6276 : : * Put the new field text into targetbuf so we can decide after we've
6277 : : * got it whether or not it needs to go on a new line.
6278 : : */
6279 : 12718 : resetStringInfo(&targetbuf);
6280 : 12718 : context->buf = &targetbuf;
6281 : :
6282 : : /*
6283 : : * We special-case Var nodes rather than using get_rule_expr. This is
6284 : : * needed because get_rule_expr will display a whole-row Var as
6285 : : * "foo.*", which is the preferred notation in most contexts, but at
6286 : : * the top level of a SELECT list it's not right (the parser will
6287 : : * expand that notation into multiple columns, yielding behavior
6288 : : * different from a whole-row Var). We need to call get_variable
6289 : : * directly so that we can tell it to do the right thing, and so that
6290 : : * we can get the attribute name which is the default AS label.
6291 : : */
6292 [ + - + + ]: 12718 : if (tle->expr && (IsA(tle->expr, Var)))
6293 : : {
6294 : 9786 : attname = get_variable((Var *) tle->expr, 0, true, context);
6295 : : }
6296 : : else
6297 : : {
6298 : 2932 : get_rule_expr((Node *) tle->expr, context, true);
6299 : :
6300 : : /*
6301 : : * When colNamesVisible is true, we should always show the
6302 : : * assigned column name explicitly. Otherwise, show it only if
6303 : : * it's not FigureColname's fallback.
6304 : : */
6305 [ + + ]: 2932 : attname = context->colNamesVisible ? NULL : "?column?";
6306 : : }
6307 : :
6308 : : /*
6309 : : * Figure out what the result column should be called. In the context
6310 : : * of a view, use the view's tuple descriptor (so as to pick up the
6311 : : * effects of any column RENAME that's been done on the view).
6312 : : * Otherwise, just use what we can find in the TLE.
6313 : : */
6314 [ + + + - ]: 12718 : if (context->resultDesc && colno <= context->resultDesc->natts)
6315 : 11559 : colname = NameStr(TupleDescAttr(context->resultDesc,
6316 : : colno - 1)->attname);
6317 : : else
6318 : 1159 : colname = tle->resname;
6319 : :
6320 : : /* Show AS unless the column's name is correct as-is */
6321 [ + + ]: 12718 : if (colname) /* resname could be NULL */
6322 : : {
6323 [ + + + + ]: 12687 : if (attname == NULL || strcmp(attname, colname) != 0)
6324 : 4151 : appendStringInfo(&targetbuf, " AS %s", quote_identifier(colname));
6325 : : }
6326 : :
6327 : : /* Restore context's output buffer */
6328 : 12718 : context->buf = buf;
6329 : :
6330 : : /* Consider line-wrapping if enabled */
6331 [ + + + - ]: 12718 : if (PRETTY_INDENT(context) && context->wrapColumn >= 0)
6332 : : {
6333 : : int leading_nl_pos;
6334 : :
6335 : : /* Does the new field start with a new line? */
6336 [ + - + + ]: 12691 : if (targetbuf.len > 0 && targetbuf.data[0] == '\n')
6337 : 375 : leading_nl_pos = 0;
6338 : : else
6339 : 12316 : leading_nl_pos = -1;
6340 : :
6341 : : /* If so, we shouldn't add anything */
6342 [ + + ]: 12691 : if (leading_nl_pos >= 0)
6343 : : {
6344 : : /* instead, remove any trailing spaces currently in buf */
6345 : 375 : removeStringInfoSpaces(buf);
6346 : : }
6347 : : else
6348 : : {
6349 : : char *trailing_nl;
6350 : :
6351 : : /* Locate the start of the current line in the output buffer */
6352 : 12316 : trailing_nl = strrchr(buf->data, '\n');
6353 [ + + ]: 12316 : if (trailing_nl == NULL)
6354 : 3651 : trailing_nl = buf->data;
6355 : : else
6356 : 8665 : trailing_nl++;
6357 : :
6358 : : /*
6359 : : * Add a newline, plus some indentation, if the new field is
6360 : : * not the first and either the new field would cause an
6361 : : * overflow or the last field used more than one line.
6362 : : */
6363 [ + + ]: 12316 : if (colno > 1 &&
6364 [ - + - - ]: 9379 : ((strlen(trailing_nl) + targetbuf.len > context->wrapColumn) ||
6365 : : last_was_multiline))
6366 : 9379 : appendContextKeyword(context, "", -PRETTYINDENT_STD,
6367 : : PRETTYINDENT_STD, PRETTYINDENT_VAR);
6368 : : }
6369 : :
6370 : : /* Remember this field's multiline status for next iteration */
6371 : 12691 : last_was_multiline =
6372 : 12691 : (strchr(targetbuf.data + leading_nl_pos + 1, '\n') != NULL);
6373 : : }
6374 : :
6375 : : /* Add the new field */
6376 : 12718 : appendBinaryStringInfo(buf, targetbuf.data, targetbuf.len);
6377 : : }
6378 : :
6379 : : /* clean up */
6380 : 2973 : pfree(targetbuf.data);
6381 : 2973 : }
6382 : :
6383 : : static void
6384 : 93 : get_returning_clause(Query *query, deparse_context *context)
6385 : : {
6386 : 93 : StringInfo buf = context->buf;
6387 : :
6388 [ + - ]: 93 : if (query->returningList)
6389 : : {
6390 : 93 : bool have_with = false;
6391 : :
6392 : 93 : appendContextKeyword(context, " RETURNING",
6393 : : -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
6394 : :
6395 : : /* Add WITH (OLD/NEW) options, if they're not the defaults */
6396 [ + + + + ]: 93 : if (query->returningOldAlias && strcmp(query->returningOldAlias, "old") != 0)
6397 : : {
6398 : 12 : appendStringInfo(buf, " WITH (OLD AS %s",
6399 : 12 : quote_identifier(query->returningOldAlias));
6400 : 12 : have_with = true;
6401 : : }
6402 [ + + + + ]: 93 : if (query->returningNewAlias && strcmp(query->returningNewAlias, "new") != 0)
6403 : : {
6404 [ + + ]: 12 : if (have_with)
6405 : 8 : appendStringInfo(buf, ", NEW AS %s",
6406 : 8 : quote_identifier(query->returningNewAlias));
6407 : : else
6408 : : {
6409 : 4 : appendStringInfo(buf, " WITH (NEW AS %s",
6410 : 4 : quote_identifier(query->returningNewAlias));
6411 : 4 : have_with = true;
6412 : : }
6413 : : }
6414 [ + + ]: 93 : if (have_with)
6415 : 16 : appendStringInfoChar(buf, ')');
6416 : :
6417 : : /* Add the returning expressions themselves */
6418 : 93 : get_target_list(query->returningList, context);
6419 : : }
6420 : 93 : }
6421 : :
6422 : : static void
6423 : 463 : get_setop_query(Node *setOp, Query *query, deparse_context *context)
6424 : : {
6425 : 463 : StringInfo buf = context->buf;
6426 : : bool need_paren;
6427 : :
6428 : : /* Guard against excessively long or deeply-nested queries */
6429 [ - + ]: 463 : CHECK_FOR_INTERRUPTS();
6430 : 463 : check_stack_depth();
6431 : :
6432 [ + + ]: 463 : if (IsA(setOp, RangeTblRef))
6433 : : {
6434 : 283 : RangeTblRef *rtr = (RangeTblRef *) setOp;
6435 : 283 : RangeTblEntry *rte = rt_fetch(rtr->rtindex, query->rtable);
6436 : 283 : Query *subquery = rte->subquery;
6437 : :
6438 : : Assert(subquery != NULL);
6439 : :
6440 : : /*
6441 : : * We need parens if WITH, ORDER BY, FOR UPDATE, or LIMIT; see gram.y.
6442 : : * Also add parens if the leaf query contains its own set operations.
6443 : : * (That shouldn't happen unless one of the other clauses is also
6444 : : * present, see transformSetOperationTree; but let's be safe.)
6445 : : */
6446 : 849 : need_paren = (subquery->cteList ||
6447 [ + - ]: 283 : subquery->sortClause ||
6448 [ + - ]: 283 : subquery->rowMarks ||
6449 [ + - ]: 283 : subquery->limitOffset ||
6450 [ + - + - ]: 849 : subquery->limitCount ||
6451 [ - + ]: 283 : subquery->setOperations);
6452 [ - + ]: 283 : if (need_paren)
6453 : 0 : appendStringInfoChar(buf, '(');
6454 : 283 : get_query_def(subquery, buf, context->namespaces,
6455 : 283 : context->resultDesc, context->colNamesVisible,
6456 : : context->prettyFlags, context->wrapColumn,
6457 : : context->indentLevel);
6458 [ - + ]: 283 : if (need_paren)
6459 : 0 : appendStringInfoChar(buf, ')');
6460 : : }
6461 [ + - ]: 180 : else if (IsA(setOp, SetOperationStmt))
6462 : : {
6463 : 180 : SetOperationStmt *op = (SetOperationStmt *) setOp;
6464 : : int subindent;
6465 : : bool save_colnamesvisible;
6466 : :
6467 : : /*
6468 : : * We force parens when nesting two SetOperationStmts, except when the
6469 : : * lefthand input is another setop of the same kind. Syntactically,
6470 : : * we could omit parens in rather more cases, but it seems best to use
6471 : : * parens to flag cases where the setop operator changes. If we use
6472 : : * parens, we also increase the indentation level for the child query.
6473 : : *
6474 : : * There are some cases in which parens are needed around a leaf query
6475 : : * too, but those are more easily handled at the next level down (see
6476 : : * code above).
6477 : : */
6478 [ + + ]: 180 : if (IsA(op->larg, SetOperationStmt))
6479 : : {
6480 : 77 : SetOperationStmt *lop = (SetOperationStmt *) op->larg;
6481 : :
6482 [ + - + - ]: 77 : if (op->op == lop->op && op->all == lop->all)
6483 : 77 : need_paren = false;
6484 : : else
6485 : 0 : need_paren = true;
6486 : : }
6487 : : else
6488 : 103 : need_paren = false;
6489 : :
6490 [ - + ]: 180 : if (need_paren)
6491 : : {
6492 : 0 : appendStringInfoChar(buf, '(');
6493 : 0 : subindent = PRETTYINDENT_STD;
6494 : 0 : appendContextKeyword(context, "", subindent, 0, 0);
6495 : : }
6496 : : else
6497 : 180 : subindent = 0;
6498 : :
6499 : 180 : get_setop_query(op->larg, query, context);
6500 : :
6501 [ - + ]: 180 : if (need_paren)
6502 : 0 : appendContextKeyword(context, ") ", -subindent, 0, 0);
6503 [ + - ]: 180 : else if (PRETTY_INDENT(context))
6504 : 180 : appendContextKeyword(context, "", -subindent, 0, 0);
6505 : : else
6506 : 0 : appendStringInfoChar(buf, ' ');
6507 : :
6508 [ + - - - ]: 180 : switch (op->op)
6509 : : {
6510 : 180 : case SETOP_UNION:
6511 : 180 : appendStringInfoString(buf, "UNION ");
6512 : 180 : break;
6513 : 0 : case SETOP_INTERSECT:
6514 : 0 : appendStringInfoString(buf, "INTERSECT ");
6515 : 0 : break;
6516 : 0 : case SETOP_EXCEPT:
6517 : 0 : appendStringInfoString(buf, "EXCEPT ");
6518 : 0 : break;
6519 : 0 : default:
6520 [ # # ]: 0 : elog(ERROR, "unrecognized set op: %d",
6521 : : (int) op->op);
6522 : : }
6523 [ + + ]: 180 : if (op->all)
6524 : 172 : appendStringInfoString(buf, "ALL ");
6525 : :
6526 : : /* Always parenthesize if RHS is another setop */
6527 : 180 : need_paren = IsA(op->rarg, SetOperationStmt);
6528 : :
6529 : : /*
6530 : : * The indentation code here is deliberately a bit different from that
6531 : : * for the lefthand input, because we want the line breaks in
6532 : : * different places.
6533 : : */
6534 [ - + ]: 180 : if (need_paren)
6535 : : {
6536 : 0 : appendStringInfoChar(buf, '(');
6537 : 0 : subindent = PRETTYINDENT_STD;
6538 : : }
6539 : : else
6540 : 180 : subindent = 0;
6541 : 180 : appendContextKeyword(context, "", subindent, 0, 0);
6542 : :
6543 : : /*
6544 : : * The output column names of the RHS sub-select don't matter.
6545 : : */
6546 : 180 : save_colnamesvisible = context->colNamesVisible;
6547 : 180 : context->colNamesVisible = false;
6548 : :
6549 : 180 : get_setop_query(op->rarg, query, context);
6550 : :
6551 : 180 : context->colNamesVisible = save_colnamesvisible;
6552 : :
6553 [ + - ]: 180 : if (PRETTY_INDENT(context))
6554 : 180 : context->indentLevel -= subindent;
6555 [ - + ]: 180 : if (need_paren)
6556 : 0 : appendContextKeyword(context, ")", 0, 0, 0);
6557 : : }
6558 : : else
6559 : : {
6560 [ # # ]: 0 : elog(ERROR, "unrecognized node type: %d",
6561 : : (int) nodeTag(setOp));
6562 : : }
6563 : 463 : }
6564 : :
6565 : : /*
6566 : : * Display a sort/group clause.
6567 : : *
6568 : : * Also returns the expression tree, so caller need not find it again.
6569 : : */
6570 : : static Node *
6571 : 435 : get_rule_sortgroupclause(Index ref, List *tlist, bool force_colno,
6572 : : deparse_context *context)
6573 : : {
6574 : 435 : StringInfo buf = context->buf;
6575 : : TargetEntry *tle;
6576 : : Node *expr;
6577 : :
6578 : 435 : tle = get_sortgroupref_tle(ref, tlist);
6579 : 435 : expr = (Node *) tle->expr;
6580 : :
6581 : : /*
6582 : : * Use column-number form if requested by caller. Otherwise, if
6583 : : * expression is a constant, force it to be dumped with an explicit cast
6584 : : * as decoration --- this is because a simple integer constant is
6585 : : * ambiguous (and will be misinterpreted by findTargetlistEntrySQL92()) if
6586 : : * we dump it without any decoration. Similarly, if it's just a Var,
6587 : : * there is risk of misinterpretation if the column name is reassigned in
6588 : : * the SELECT list, so we may need to force table qualification. And, if
6589 : : * it's anything more complex than a simple Var, then force extra parens
6590 : : * around it, to ensure it can't be misinterpreted as a cube() or rollup()
6591 : : * construct.
6592 : : */
6593 [ + + ]: 435 : if (force_colno)
6594 : : {
6595 : : Assert(!tle->resjunk);
6596 : 7 : appendStringInfo(buf, "%d", tle->resno);
6597 : : }
6598 [ + - ]: 428 : else if (!expr)
6599 : : /* do nothing, probably can't happen */ ;
6600 [ - + ]: 428 : else if (IsA(expr, Const))
6601 : 0 : get_const_expr((Const *) expr, context, 1);
6602 [ + + ]: 428 : else if (IsA(expr, Var))
6603 : : {
6604 : : /* Tell get_variable to check for name conflict */
6605 : 411 : bool save_varinorderby = context->varInOrderBy;
6606 : :
6607 : 411 : context->varInOrderBy = true;
6608 : 411 : (void) get_variable((Var *) expr, 0, false, context);
6609 : 411 : context->varInOrderBy = save_varinorderby;
6610 : : }
6611 : : else
6612 : : {
6613 : : /*
6614 : : * We must force parens for function-like expressions even if
6615 : : * PRETTY_PAREN is off, since those are the ones in danger of
6616 : : * misparsing. For other expressions we need to force them only if
6617 : : * PRETTY_PAREN is on, since otherwise the expression will output them
6618 : : * itself. (We can't skip the parens.)
6619 : : */
6620 : 34 : bool need_paren = (PRETTY_PAREN(context)
6621 [ + + ]: 17 : || IsA(expr, FuncExpr)
6622 [ + - ]: 15 : || IsA(expr, Aggref)
6623 [ + - ]: 15 : || IsA(expr, WindowFunc)
6624 [ + - - + ]: 34 : || IsA(expr, JsonConstructorExpr));
6625 : :
6626 [ + + ]: 17 : if (need_paren)
6627 : 2 : appendStringInfoChar(context->buf, '(');
6628 : 17 : get_rule_expr(expr, context, true);
6629 [ + + ]: 17 : if (need_paren)
6630 : 2 : appendStringInfoChar(context->buf, ')');
6631 : : }
6632 : :
6633 : 435 : return expr;
6634 : : }
6635 : :
6636 : : /*
6637 : : * Display a GroupingSet
6638 : : */
6639 : : static void
6640 : 12 : get_rule_groupingset(GroupingSet *gset, List *targetlist,
6641 : : bool omit_parens, deparse_context *context)
6642 : : {
6643 : : ListCell *l;
6644 : 12 : StringInfo buf = context->buf;
6645 : 12 : bool omit_child_parens = true;
6646 : 12 : char *sep = "";
6647 : :
6648 [ - + + - : 12 : switch (gset->kind)
- - ]
6649 : : {
6650 : 0 : case GROUPING_SET_EMPTY:
6651 : 0 : appendStringInfoString(buf, "()");
6652 : 0 : return;
6653 : :
6654 : 8 : case GROUPING_SET_SIMPLE:
6655 : : {
6656 [ + - + - ]: 8 : if (!omit_parens || list_length(gset->content) != 1)
6657 : 8 : appendStringInfoChar(buf, '(');
6658 : :
6659 [ + - + + : 28 : foreach(l, gset->content)
+ + ]
6660 : : {
6661 : 20 : Index ref = lfirst_int(l);
6662 : :
6663 : 20 : appendStringInfoString(buf, sep);
6664 : 20 : get_rule_sortgroupclause(ref, targetlist,
6665 : : false, context);
6666 : 20 : sep = ", ";
6667 : : }
6668 : :
6669 [ + - + - ]: 8 : if (!omit_parens || list_length(gset->content) != 1)
6670 : 8 : appendStringInfoChar(buf, ')');
6671 : : }
6672 : 8 : return;
6673 : :
6674 : 4 : case GROUPING_SET_ROLLUP:
6675 : 4 : appendStringInfoString(buf, "ROLLUP(");
6676 : 4 : break;
6677 : 0 : case GROUPING_SET_CUBE:
6678 : 0 : appendStringInfoString(buf, "CUBE(");
6679 : 0 : break;
6680 : 0 : case GROUPING_SET_SETS:
6681 : 0 : appendStringInfoString(buf, "GROUPING SETS (");
6682 : 0 : omit_child_parens = false;
6683 : 0 : break;
6684 : : }
6685 : :
6686 [ + - + + : 12 : foreach(l, gset->content)
+ + ]
6687 : : {
6688 : 8 : appendStringInfoString(buf, sep);
6689 : 8 : get_rule_groupingset(lfirst(l), targetlist, omit_child_parens, context);
6690 : 8 : sep = ", ";
6691 : : }
6692 : :
6693 : 4 : appendStringInfoChar(buf, ')');
6694 : : }
6695 : :
6696 : : /*
6697 : : * Display an ORDER BY list.
6698 : : */
6699 : : static void
6700 : 246 : get_rule_orderby(List *orderList, List *targetList,
6701 : : bool force_colno, deparse_context *context)
6702 : : {
6703 : 246 : StringInfo buf = context->buf;
6704 : : const char *sep;
6705 : : ListCell *l;
6706 : :
6707 : 246 : sep = "";
6708 [ + - + + : 513 : foreach(l, orderList)
+ + ]
6709 : : {
6710 : 267 : SortGroupClause *srt = (SortGroupClause *) lfirst(l);
6711 : : Node *sortexpr;
6712 : : Oid sortcoltype;
6713 : : TypeCacheEntry *typentry;
6714 : :
6715 : 267 : appendStringInfoString(buf, sep);
6716 : 267 : sortexpr = get_rule_sortgroupclause(srt->tleSortGroupRef, targetList,
6717 : : force_colno, context);
6718 : 267 : sortcoltype = exprType(sortexpr);
6719 : : /* See whether operator is default < or > for datatype */
6720 : 267 : typentry = lookup_type_cache(sortcoltype,
6721 : : TYPECACHE_LT_OPR | TYPECACHE_GT_OPR);
6722 [ + + ]: 267 : if (srt->sortop == typentry->lt_opr)
6723 : : {
6724 : : /* ASC is default, so emit nothing for it */
6725 [ - + ]: 250 : if (srt->nulls_first)
6726 : 0 : appendStringInfoString(buf, " NULLS FIRST");
6727 : : }
6728 [ + + ]: 17 : else if (srt->sortop == typentry->gt_opr)
6729 : : {
6730 : 6 : appendStringInfoString(buf, " DESC");
6731 : : /* DESC defaults to NULLS FIRST */
6732 [ + + ]: 6 : if (!srt->nulls_first)
6733 : 1 : appendStringInfoString(buf, " NULLS LAST");
6734 : : }
6735 : : else
6736 : : {
6737 : 11 : appendStringInfo(buf, " USING %s",
6738 : : generate_operator_name(srt->sortop,
6739 : : sortcoltype,
6740 : : sortcoltype));
6741 : : /* be specific to eliminate ambiguity */
6742 [ - + ]: 11 : if (srt->nulls_first)
6743 : 0 : appendStringInfoString(buf, " NULLS FIRST");
6744 : : else
6745 : 11 : appendStringInfoString(buf, " NULLS LAST");
6746 : : }
6747 : 267 : sep = ", ";
6748 : : }
6749 : 246 : }
6750 : :
6751 : : /*
6752 : : * Display a WINDOW clause.
6753 : : *
6754 : : * Note that the windowClause list might contain only anonymous window
6755 : : * specifications, in which case we should print nothing here.
6756 : : */
6757 : : static void
6758 : 32 : get_rule_windowclause(Query *query, deparse_context *context)
6759 : : {
6760 : 32 : StringInfo buf = context->buf;
6761 : : const char *sep;
6762 : : ListCell *l;
6763 : :
6764 : 32 : sep = NULL;
6765 [ + - + + : 64 : foreach(l, query->windowClause)
+ + ]
6766 : : {
6767 : 32 : WindowClause *wc = (WindowClause *) lfirst(l);
6768 : :
6769 [ + + ]: 32 : if (wc->name == NULL)
6770 : 28 : continue; /* ignore anonymous windows */
6771 : :
6772 [ + - ]: 4 : if (sep == NULL)
6773 : 4 : appendContextKeyword(context, " WINDOW ",
6774 : : -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
6775 : : else
6776 : 0 : appendStringInfoString(buf, sep);
6777 : :
6778 : 4 : appendStringInfo(buf, "%s AS ", quote_identifier(wc->name));
6779 : :
6780 : 4 : get_rule_windowspec(wc, query->targetList, context);
6781 : :
6782 : 4 : sep = ", ";
6783 : : }
6784 : 32 : }
6785 : :
6786 : : /*
6787 : : * Display a window definition
6788 : : */
6789 : : static void
6790 : 32 : get_rule_windowspec(WindowClause *wc, List *targetList,
6791 : : deparse_context *context)
6792 : : {
6793 : 32 : StringInfo buf = context->buf;
6794 : 32 : bool needspace = false;
6795 : : const char *sep;
6796 : : ListCell *l;
6797 : :
6798 : 32 : appendStringInfoChar(buf, '(');
6799 [ - + ]: 32 : if (wc->refname)
6800 : : {
6801 : 0 : appendStringInfoString(buf, quote_identifier(wc->refname));
6802 : 0 : needspace = true;
6803 : : }
6804 : : /* partition clauses are always inherited, so only print if no refname */
6805 [ - + - - ]: 32 : if (wc->partitionClause && !wc->refname)
6806 : : {
6807 [ # # ]: 0 : if (needspace)
6808 : 0 : appendStringInfoChar(buf, ' ');
6809 : 0 : appendStringInfoString(buf, "PARTITION BY ");
6810 : 0 : sep = "";
6811 [ # # # # : 0 : foreach(l, wc->partitionClause)
# # ]
6812 : : {
6813 : 0 : SortGroupClause *grp = (SortGroupClause *) lfirst(l);
6814 : :
6815 : 0 : appendStringInfoString(buf, sep);
6816 : 0 : get_rule_sortgroupclause(grp->tleSortGroupRef, targetList,
6817 : : false, context);
6818 : 0 : sep = ", ";
6819 : : }
6820 : 0 : needspace = true;
6821 : : }
6822 : : /* print ordering clause only if not inherited */
6823 [ + - + - ]: 32 : if (wc->orderClause && !wc->copiedOrder)
6824 : : {
6825 [ - + ]: 32 : if (needspace)
6826 : 0 : appendStringInfoChar(buf, ' ');
6827 : 32 : appendStringInfoString(buf, "ORDER BY ");
6828 : 32 : get_rule_orderby(wc->orderClause, targetList, false, context);
6829 : 32 : needspace = true;
6830 : : }
6831 : : /* framing clause is never inherited, so print unless it's default */
6832 [ + + ]: 32 : if (wc->frameOptions & FRAMEOPTION_NONDEFAULT)
6833 : : {
6834 [ + - ]: 28 : if (needspace)
6835 : 28 : appendStringInfoChar(buf, ' ');
6836 : 28 : get_window_frame_options(wc->frameOptions,
6837 : : wc->startOffset, wc->endOffset,
6838 : : context);
6839 : : }
6840 : 32 : appendStringInfoChar(buf, ')');
6841 : 32 : }
6842 : :
6843 : : /*
6844 : : * Append the description of a window's framing options to context->buf
6845 : : */
6846 : : static void
6847 : 218 : get_window_frame_options(int frameOptions,
6848 : : Node *startOffset, Node *endOffset,
6849 : : deparse_context *context)
6850 : : {
6851 : 218 : StringInfo buf = context->buf;
6852 : :
6853 [ + - ]: 218 : if (frameOptions & FRAMEOPTION_NONDEFAULT)
6854 : : {
6855 [ + + ]: 218 : if (frameOptions & FRAMEOPTION_RANGE)
6856 : 29 : appendStringInfoString(buf, "RANGE ");
6857 [ + + ]: 189 : else if (frameOptions & FRAMEOPTION_ROWS)
6858 : 169 : appendStringInfoString(buf, "ROWS ");
6859 [ + - ]: 20 : else if (frameOptions & FRAMEOPTION_GROUPS)
6860 : 20 : appendStringInfoString(buf, "GROUPS ");
6861 : : else
6862 : : Assert(false);
6863 [ + + ]: 218 : if (frameOptions & FRAMEOPTION_BETWEEN)
6864 : 113 : appendStringInfoString(buf, "BETWEEN ");
6865 [ + + ]: 218 : if (frameOptions & FRAMEOPTION_START_UNBOUNDED_PRECEDING)
6866 : 145 : appendStringInfoString(buf, "UNBOUNDED PRECEDING ");
6867 [ + + ]: 73 : else if (frameOptions & FRAMEOPTION_START_CURRENT_ROW)
6868 : 33 : appendStringInfoString(buf, "CURRENT ROW ");
6869 [ + - ]: 40 : else if (frameOptions & FRAMEOPTION_START_OFFSET)
6870 : : {
6871 : 40 : get_rule_expr(startOffset, context, false);
6872 [ + - ]: 40 : if (frameOptions & FRAMEOPTION_START_OFFSET_PRECEDING)
6873 : 40 : appendStringInfoString(buf, " PRECEDING ");
6874 [ # # ]: 0 : else if (frameOptions & FRAMEOPTION_START_OFFSET_FOLLOWING)
6875 : 0 : appendStringInfoString(buf, " FOLLOWING ");
6876 : : else
6877 : : Assert(false);
6878 : : }
6879 : : else
6880 : : Assert(false);
6881 [ + + ]: 218 : if (frameOptions & FRAMEOPTION_BETWEEN)
6882 : : {
6883 : 113 : appendStringInfoString(buf, "AND ");
6884 [ + + ]: 113 : if (frameOptions & FRAMEOPTION_END_UNBOUNDED_FOLLOWING)
6885 : 13 : appendStringInfoString(buf, "UNBOUNDED FOLLOWING ");
6886 [ + + ]: 100 : else if (frameOptions & FRAMEOPTION_END_CURRENT_ROW)
6887 : 28 : appendStringInfoString(buf, "CURRENT ROW ");
6888 [ + - ]: 72 : else if (frameOptions & FRAMEOPTION_END_OFFSET)
6889 : : {
6890 : 72 : get_rule_expr(endOffset, context, false);
6891 [ + + ]: 72 : if (frameOptions & FRAMEOPTION_END_OFFSET_PRECEDING)
6892 : 28 : appendStringInfoString(buf, " PRECEDING ");
6893 [ + - ]: 44 : else if (frameOptions & FRAMEOPTION_END_OFFSET_FOLLOWING)
6894 : 44 : appendStringInfoString(buf, " FOLLOWING ");
6895 : : else
6896 : : Assert(false);
6897 : : }
6898 : : else
6899 : : Assert(false);
6900 : : }
6901 [ + + ]: 218 : if (frameOptions & FRAMEOPTION_EXCLUDE_CURRENT_ROW)
6902 : 24 : appendStringInfoString(buf, "EXCLUDE CURRENT ROW ");
6903 [ + + ]: 194 : else if (frameOptions & FRAMEOPTION_EXCLUDE_GROUP)
6904 : 12 : appendStringInfoString(buf, "EXCLUDE GROUP ");
6905 [ + + ]: 182 : else if (frameOptions & FRAMEOPTION_EXCLUDE_TIES)
6906 : 12 : appendStringInfoString(buf, "EXCLUDE TIES ");
6907 : : /* we will now have a trailing space; remove it */
6908 : 218 : buf->data[--(buf->len)] = '\0';
6909 : : }
6910 : 218 : }
6911 : :
6912 : : /*
6913 : : * Return the description of a window's framing options as a palloc'd string
6914 : : */
6915 : : char *
6916 : 190 : get_window_frame_options_for_explain(int frameOptions,
6917 : : Node *startOffset, Node *endOffset,
6918 : : List *dpcontext, bool forceprefix)
6919 : : {
6920 : : StringInfoData buf;
6921 : : deparse_context context;
6922 : :
6923 : 190 : initStringInfo(&buf);
6924 : 190 : context.buf = &buf;
6925 : 190 : context.namespaces = dpcontext;
6926 : 190 : context.resultDesc = NULL;
6927 : 190 : context.targetList = NIL;
6928 : 190 : context.windowClause = NIL;
6929 : 190 : context.varprefix = forceprefix;
6930 : 190 : context.prettyFlags = 0;
6931 : 190 : context.wrapColumn = WRAP_COLUMN_DEFAULT;
6932 : 190 : context.indentLevel = 0;
6933 : 190 : context.colNamesVisible = true;
6934 : 190 : context.inGroupBy = false;
6935 : 190 : context.varInOrderBy = false;
6936 : 190 : context.appendparents = NULL;
6937 : :
6938 : 190 : get_window_frame_options(frameOptions, startOffset, endOffset, &context);
6939 : :
6940 : 190 : return buf.data;
6941 : : }
6942 : :
6943 : : /* ----------
6944 : : * get_insert_query_def - Parse back an INSERT parsetree
6945 : : * ----------
6946 : : */
6947 : : static void
6948 : 194 : get_insert_query_def(Query *query, deparse_context *context)
6949 : : {
6950 : 194 : StringInfo buf = context->buf;
6951 : 194 : RangeTblEntry *select_rte = NULL;
6952 : 194 : RangeTblEntry *values_rte = NULL;
6953 : : RangeTblEntry *rte;
6954 : : char *sep;
6955 : : ListCell *l;
6956 : : List *strippedexprs;
6957 : :
6958 : : /* Insert the WITH clause if given */
6959 : 194 : get_with_clause(query, context);
6960 : :
6961 : : /*
6962 : : * If it's an INSERT ... SELECT or multi-row VALUES, there will be a
6963 : : * single RTE for the SELECT or VALUES. Plain VALUES has neither.
6964 : : */
6965 [ + - + + : 758 : foreach(l, query->rtable)
+ + ]
6966 : : {
6967 : 564 : rte = (RangeTblEntry *) lfirst(l);
6968 : :
6969 [ + + ]: 564 : if (rte->rtekind == RTE_SUBQUERY)
6970 : : {
6971 [ - + ]: 30 : if (select_rte)
6972 [ # # ]: 0 : elog(ERROR, "too many subquery RTEs in INSERT");
6973 : 30 : select_rte = rte;
6974 : : }
6975 : :
6976 [ + + ]: 564 : if (rte->rtekind == RTE_VALUES)
6977 : : {
6978 [ - + ]: 26 : if (values_rte)
6979 [ # # ]: 0 : elog(ERROR, "too many values RTEs in INSERT");
6980 : 26 : values_rte = rte;
6981 : : }
6982 : : }
6983 [ + + - + ]: 194 : if (select_rte && values_rte)
6984 [ # # ]: 0 : elog(ERROR, "both subquery and values RTEs in INSERT");
6985 : :
6986 : : /*
6987 : : * Start the query with INSERT INTO relname
6988 : : */
6989 : 194 : rte = rt_fetch(query->resultRelation, query->rtable);
6990 : : Assert(rte->rtekind == RTE_RELATION);
6991 : :
6992 [ + - ]: 194 : if (PRETTY_INDENT(context))
6993 : : {
6994 : 194 : context->indentLevel += PRETTYINDENT_STD;
6995 : 194 : appendStringInfoChar(buf, ' ');
6996 : : }
6997 : 194 : appendStringInfo(buf, "INSERT INTO %s",
6998 : : generate_relation_name(rte->relid, NIL));
6999 : :
7000 : : /* Print the relation alias, if needed; INSERT requires explicit AS */
7001 : 194 : get_rte_alias(rte, query->resultRelation, true, context);
7002 : :
7003 : : /* always want a space here */
7004 : 194 : appendStringInfoChar(buf, ' ');
7005 : :
7006 : : /*
7007 : : * Add the insert-column-names list. Any indirection decoration needed on
7008 : : * the column names can be inferred from the top targetlist.
7009 : : */
7010 : 194 : strippedexprs = NIL;
7011 : 194 : sep = "";
7012 [ + - ]: 194 : if (query->targetList)
7013 : 194 : appendStringInfoChar(buf, '(');
7014 [ + - + + : 695 : foreach(l, query->targetList)
+ + ]
7015 : : {
7016 : 501 : TargetEntry *tle = (TargetEntry *) lfirst(l);
7017 : :
7018 [ - + ]: 501 : if (tle->resjunk)
7019 : 0 : continue; /* ignore junk entries */
7020 : :
7021 : 501 : appendStringInfoString(buf, sep);
7022 : 501 : sep = ", ";
7023 : :
7024 : : /*
7025 : : * Put out name of target column; look in the catalogs, not at
7026 : : * tle->resname, since resname will fail to track RENAME.
7027 : : */
7028 : 501 : appendStringInfoString(buf,
7029 : 501 : quote_identifier(get_attname(rte->relid,
7030 : 501 : tle->resno,
7031 : : false)));
7032 : :
7033 : : /*
7034 : : * Print any indirection needed (subfields or subscripts), and strip
7035 : : * off the top-level nodes representing the indirection assignments.
7036 : : * Add the stripped expressions to strippedexprs. (If it's a
7037 : : * single-VALUES statement, the stripped expressions are the VALUES to
7038 : : * print below. Otherwise they're just Vars and not really
7039 : : * interesting.)
7040 : : */
7041 : 501 : strippedexprs = lappend(strippedexprs,
7042 : 501 : processIndirection((Node *) tle->expr,
7043 : : context));
7044 : : }
7045 [ + - ]: 194 : if (query->targetList)
7046 : 194 : appendStringInfoString(buf, ") ");
7047 : :
7048 [ - + ]: 194 : if (query->override)
7049 : : {
7050 [ # # ]: 0 : if (query->override == OVERRIDING_SYSTEM_VALUE)
7051 : 0 : appendStringInfoString(buf, "OVERRIDING SYSTEM VALUE ");
7052 [ # # ]: 0 : else if (query->override == OVERRIDING_USER_VALUE)
7053 : 0 : appendStringInfoString(buf, "OVERRIDING USER VALUE ");
7054 : : }
7055 : :
7056 [ + + ]: 194 : if (select_rte)
7057 : : {
7058 : : /* Add the SELECT */
7059 : 30 : get_query_def(select_rte->subquery, buf, context->namespaces, NULL,
7060 : : false,
7061 : : context->prettyFlags, context->wrapColumn,
7062 : : context->indentLevel);
7063 : : }
7064 [ + + ]: 164 : else if (values_rte)
7065 : : {
7066 : : /* Add the multi-VALUES expression lists */
7067 : 26 : get_values_def(values_rte->values_lists, context);
7068 : : }
7069 [ + - ]: 138 : else if (strippedexprs)
7070 : : {
7071 : : /* Add the single-VALUES expression list */
7072 : 138 : appendContextKeyword(context, "VALUES (",
7073 : : -PRETTYINDENT_STD, PRETTYINDENT_STD, 2);
7074 : 138 : get_rule_list_toplevel(strippedexprs, context, false);
7075 : 138 : appendStringInfoChar(buf, ')');
7076 : : }
7077 : : else
7078 : : {
7079 : : /* No expressions, so it must be DEFAULT VALUES */
7080 : 0 : appendStringInfoString(buf, "DEFAULT VALUES");
7081 : : }
7082 : :
7083 : : /* Add ON CONFLICT if present */
7084 [ + + ]: 194 : if (query->onConflict)
7085 : : {
7086 : 24 : OnConflictExpr *confl = query->onConflict;
7087 : :
7088 : 24 : appendStringInfoString(buf, " ON CONFLICT");
7089 : :
7090 [ + + ]: 24 : if (confl->arbiterElems)
7091 : : {
7092 : : /* Add the single-VALUES expression list */
7093 : 20 : appendStringInfoChar(buf, '(');
7094 : 20 : get_rule_expr((Node *) confl->arbiterElems, context, false);
7095 : 20 : appendStringInfoChar(buf, ')');
7096 : :
7097 : : /* Add a WHERE clause (for partial indexes) if given */
7098 [ + + ]: 20 : if (confl->arbiterWhere != NULL)
7099 : : {
7100 : : bool save_varprefix;
7101 : :
7102 : : /*
7103 : : * Force non-prefixing of Vars, since parser assumes that they
7104 : : * belong to target relation. WHERE clause does not use
7105 : : * InferenceElem, so this is separately required.
7106 : : */
7107 : 8 : save_varprefix = context->varprefix;
7108 : 8 : context->varprefix = false;
7109 : :
7110 : 8 : appendContextKeyword(context, " WHERE ",
7111 : : -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
7112 : 8 : get_rule_expr(confl->arbiterWhere, context, false);
7113 : :
7114 : 8 : context->varprefix = save_varprefix;
7115 : : }
7116 : : }
7117 [ - + ]: 4 : else if (OidIsValid(confl->constraint))
7118 : : {
7119 : 0 : char *constraint = get_constraint_name(confl->constraint);
7120 : :
7121 [ # # ]: 0 : if (!constraint)
7122 [ # # ]: 0 : elog(ERROR, "cache lookup failed for constraint %u",
7123 : : confl->constraint);
7124 : 0 : appendStringInfo(buf, " ON CONSTRAINT %s",
7125 : : quote_identifier(constraint));
7126 : : }
7127 : :
7128 [ + + ]: 24 : if (confl->action == ONCONFLICT_NOTHING)
7129 : : {
7130 : 12 : appendStringInfoString(buf, " DO NOTHING");
7131 : : }
7132 [ + + ]: 12 : else if (confl->action == ONCONFLICT_UPDATE)
7133 : : {
7134 : 8 : appendStringInfoString(buf, " DO UPDATE SET ");
7135 : : /* Deparse targetlist */
7136 : 8 : get_update_query_targetlist_def(query, confl->onConflictSet,
7137 : : context, rte);
7138 : :
7139 : : /* Add a WHERE clause if given */
7140 [ + - ]: 8 : if (confl->onConflictWhere != NULL)
7141 : : {
7142 : 8 : appendContextKeyword(context, " WHERE ",
7143 : : -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
7144 : 8 : get_rule_expr(confl->onConflictWhere, context, false);
7145 : : }
7146 : : }
7147 : : else
7148 : : {
7149 : : Assert(confl->action == ONCONFLICT_SELECT);
7150 : 4 : appendStringInfoString(buf, " DO SELECT");
7151 : :
7152 : : /* Add FOR [KEY] UPDATE/SHARE clause if present */
7153 [ + - ]: 4 : if (confl->lockStrength != LCS_NONE)
7154 : 4 : appendStringInfoString(buf, get_lock_clause_strength(confl->lockStrength));
7155 : :
7156 : : /* Add a WHERE clause if given */
7157 [ + - ]: 4 : if (confl->onConflictWhere != NULL)
7158 : : {
7159 : 4 : appendContextKeyword(context, " WHERE ",
7160 : : -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
7161 : 4 : get_rule_expr(confl->onConflictWhere, context, false);
7162 : : }
7163 : : }
7164 : : }
7165 : :
7166 : : /* Add RETURNING if present */
7167 [ + + ]: 194 : if (query->returningList)
7168 : 51 : get_returning_clause(query, context);
7169 : 194 : }
7170 : :
7171 : :
7172 : : /* ----------
7173 : : * get_update_query_def - Parse back an UPDATE parsetree
7174 : : * ----------
7175 : : */
7176 : : static void
7177 : 86 : get_update_query_def(Query *query, deparse_context *context)
7178 : : {
7179 : 86 : StringInfo buf = context->buf;
7180 : : RangeTblEntry *rte;
7181 : :
7182 : : /* Insert the WITH clause if given */
7183 : 86 : get_with_clause(query, context);
7184 : :
7185 : : /*
7186 : : * Start the query with UPDATE relname SET
7187 : : */
7188 : 86 : rte = rt_fetch(query->resultRelation, query->rtable);
7189 : : Assert(rte->rtekind == RTE_RELATION);
7190 [ + - ]: 86 : if (PRETTY_INDENT(context))
7191 : : {
7192 : 86 : appendStringInfoChar(buf, ' ');
7193 : 86 : context->indentLevel += PRETTYINDENT_STD;
7194 : : }
7195 : 172 : appendStringInfo(buf, "UPDATE %s%s",
7196 [ + - ]: 86 : only_marker(rte),
7197 : : generate_relation_name(rte->relid, NIL));
7198 : :
7199 : : /* Print the relation alias, if needed */
7200 : 86 : get_rte_alias(rte, query->resultRelation, false, context);
7201 : :
7202 : 86 : appendStringInfoString(buf, " SET ");
7203 : :
7204 : : /* Deparse targetlist */
7205 : 86 : get_update_query_targetlist_def(query, query->targetList, context, rte);
7206 : :
7207 : : /* Add the FROM clause if needed */
7208 : 86 : get_from_clause(query, " FROM ", context);
7209 : :
7210 : : /* Add a WHERE clause if given */
7211 [ + + ]: 86 : if (query->jointree->quals != NULL)
7212 : : {
7213 : 61 : appendContextKeyword(context, " WHERE ",
7214 : : -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
7215 : 61 : get_rule_expr(query->jointree->quals, context, false);
7216 : : }
7217 : :
7218 : : /* Add RETURNING if present */
7219 [ + + ]: 86 : if (query->returningList)
7220 : 29 : get_returning_clause(query, context);
7221 : 86 : }
7222 : :
7223 : :
7224 : : /* ----------
7225 : : * get_update_query_targetlist_def - Parse back an UPDATE targetlist
7226 : : * ----------
7227 : : */
7228 : : static void
7229 : 110 : get_update_query_targetlist_def(Query *query, List *targetList,
7230 : : deparse_context *context, RangeTblEntry *rte)
7231 : : {
7232 : 110 : StringInfo buf = context->buf;
7233 : : ListCell *l;
7234 : : ListCell *next_ma_cell;
7235 : : int remaining_ma_columns;
7236 : : const char *sep;
7237 : : SubLink *cur_ma_sublink;
7238 : : List *ma_sublinks;
7239 : :
7240 : : /*
7241 : : * Prepare to deal with MULTIEXPR assignments: collect the source SubLinks
7242 : : * into a list. We expect them to appear, in ID order, in resjunk tlist
7243 : : * entries.
7244 : : */
7245 : 110 : ma_sublinks = NIL;
7246 [ + + ]: 110 : if (query->hasSubLinks) /* else there can't be any */
7247 : : {
7248 [ + - + + : 28 : foreach(l, targetList)
+ + ]
7249 : : {
7250 : 20 : TargetEntry *tle = (TargetEntry *) lfirst(l);
7251 : :
7252 [ + + + - ]: 20 : if (tle->resjunk && IsA(tle->expr, SubLink))
7253 : : {
7254 : 4 : SubLink *sl = (SubLink *) tle->expr;
7255 : :
7256 [ + - ]: 4 : if (sl->subLinkType == MULTIEXPR_SUBLINK)
7257 : : {
7258 : 4 : ma_sublinks = lappend(ma_sublinks, sl);
7259 : : Assert(sl->subLinkId == list_length(ma_sublinks));
7260 : : }
7261 : : }
7262 : : }
7263 : : }
7264 : 110 : next_ma_cell = list_head(ma_sublinks);
7265 : 110 : cur_ma_sublink = NULL;
7266 : 110 : remaining_ma_columns = 0;
7267 : :
7268 : : /* Add the comma separated list of 'attname = value' */
7269 : 110 : sep = "";
7270 [ + - + + : 282 : foreach(l, targetList)
+ + ]
7271 : : {
7272 : 172 : TargetEntry *tle = (TargetEntry *) lfirst(l);
7273 : : Node *expr;
7274 : :
7275 [ + + ]: 172 : if (tle->resjunk)
7276 : 4 : continue; /* ignore junk entries */
7277 : :
7278 : : /* Emit separator (OK whether we're in multiassignment or not) */
7279 : 168 : appendStringInfoString(buf, sep);
7280 : 168 : sep = ", ";
7281 : :
7282 : : /*
7283 : : * Check to see if we're starting a multiassignment group: if so,
7284 : : * output a left paren.
7285 : : */
7286 [ + + + - ]: 168 : if (next_ma_cell != NULL && cur_ma_sublink == NULL)
7287 : : {
7288 : : /*
7289 : : * We must dig down into the expr to see if it's a PARAM_MULTIEXPR
7290 : : * Param. That could be buried under FieldStores and
7291 : : * SubscriptingRefs and CoerceToDomains (cf processIndirection()),
7292 : : * and underneath those there could be an implicit type coercion.
7293 : : * Because we would ignore implicit type coercions anyway, we
7294 : : * don't need to be as careful as processIndirection() is about
7295 : : * descending past implicit CoerceToDomains.
7296 : : */
7297 : 4 : expr = (Node *) tle->expr;
7298 [ + - ]: 8 : while (expr)
7299 : : {
7300 [ - + ]: 8 : if (IsA(expr, FieldStore))
7301 : : {
7302 : 0 : FieldStore *fstore = (FieldStore *) expr;
7303 : :
7304 : 0 : expr = (Node *) linitial(fstore->newvals);
7305 : : }
7306 [ + + ]: 8 : else if (IsA(expr, SubscriptingRef))
7307 : : {
7308 : 4 : SubscriptingRef *sbsref = (SubscriptingRef *) expr;
7309 : :
7310 [ - + ]: 4 : if (sbsref->refassgnexpr == NULL)
7311 : 0 : break;
7312 : :
7313 : 4 : expr = (Node *) sbsref->refassgnexpr;
7314 : : }
7315 [ - + ]: 4 : else if (IsA(expr, CoerceToDomain))
7316 : : {
7317 : 0 : CoerceToDomain *cdomain = (CoerceToDomain *) expr;
7318 : :
7319 [ # # ]: 0 : if (cdomain->coercionformat != COERCE_IMPLICIT_CAST)
7320 : 0 : break;
7321 : 0 : expr = (Node *) cdomain->arg;
7322 : : }
7323 : : else
7324 : 4 : break;
7325 : : }
7326 : 4 : expr = strip_implicit_coercions(expr);
7327 : :
7328 [ + - + - ]: 4 : if (expr && IsA(expr, Param) &&
7329 [ + - ]: 4 : ((Param *) expr)->paramkind == PARAM_MULTIEXPR)
7330 : : {
7331 : 4 : cur_ma_sublink = (SubLink *) lfirst(next_ma_cell);
7332 : 4 : next_ma_cell = lnext(ma_sublinks, next_ma_cell);
7333 : 4 : remaining_ma_columns = count_nonjunk_tlist_entries(((Query *) cur_ma_sublink->subselect)->targetList);
7334 : : Assert(((Param *) expr)->paramid ==
7335 : : ((cur_ma_sublink->subLinkId << 16) | 1));
7336 : 4 : appendStringInfoChar(buf, '(');
7337 : : }
7338 : : }
7339 : :
7340 : : /*
7341 : : * Put out name of target column; look in the catalogs, not at
7342 : : * tle->resname, since resname will fail to track RENAME.
7343 : : */
7344 : 168 : appendStringInfoString(buf,
7345 : 168 : quote_identifier(get_attname(rte->relid,
7346 : 168 : tle->resno,
7347 : : false)));
7348 : :
7349 : : /*
7350 : : * Print any indirection needed (subfields or subscripts), and strip
7351 : : * off the top-level nodes representing the indirection assignments.
7352 : : */
7353 : 168 : expr = processIndirection((Node *) tle->expr, context);
7354 : :
7355 : : /*
7356 : : * If we're in a multiassignment, skip printing anything more, unless
7357 : : * this is the last column; in which case, what we print should be the
7358 : : * sublink, not the Param.
7359 : : */
7360 [ + + ]: 168 : if (cur_ma_sublink != NULL)
7361 : : {
7362 [ + + ]: 12 : if (--remaining_ma_columns > 0)
7363 : 8 : continue; /* not the last column of multiassignment */
7364 : 4 : appendStringInfoChar(buf, ')');
7365 : 4 : expr = (Node *) cur_ma_sublink;
7366 : 4 : cur_ma_sublink = NULL;
7367 : : }
7368 : :
7369 : 160 : appendStringInfoString(buf, " = ");
7370 : :
7371 : 160 : get_rule_expr(expr, context, false);
7372 : : }
7373 : 110 : }
7374 : :
7375 : :
7376 : : /* ----------
7377 : : * get_delete_query_def - Parse back a DELETE parsetree
7378 : : * ----------
7379 : : */
7380 : : static void
7381 : 39 : get_delete_query_def(Query *query, deparse_context *context)
7382 : : {
7383 : 39 : StringInfo buf = context->buf;
7384 : : RangeTblEntry *rte;
7385 : :
7386 : : /* Insert the WITH clause if given */
7387 : 39 : get_with_clause(query, context);
7388 : :
7389 : : /*
7390 : : * Start the query with DELETE FROM relname
7391 : : */
7392 : 39 : rte = rt_fetch(query->resultRelation, query->rtable);
7393 : : Assert(rte->rtekind == RTE_RELATION);
7394 [ + - ]: 39 : if (PRETTY_INDENT(context))
7395 : : {
7396 : 39 : appendStringInfoChar(buf, ' ');
7397 : 39 : context->indentLevel += PRETTYINDENT_STD;
7398 : : }
7399 : 78 : appendStringInfo(buf, "DELETE FROM %s%s",
7400 [ + - ]: 39 : only_marker(rte),
7401 : : generate_relation_name(rte->relid, NIL));
7402 : :
7403 : : /* Print the relation alias, if needed */
7404 : 39 : get_rte_alias(rte, query->resultRelation, false, context);
7405 : :
7406 : : /* Add the USING clause if given */
7407 : 39 : get_from_clause(query, " USING ", context);
7408 : :
7409 : : /* Add a WHERE clause if given */
7410 [ + - ]: 39 : if (query->jointree->quals != NULL)
7411 : : {
7412 : 39 : appendContextKeyword(context, " WHERE ",
7413 : : -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
7414 : 39 : get_rule_expr(query->jointree->quals, context, false);
7415 : : }
7416 : :
7417 : : /* Add RETURNING if present */
7418 [ + + ]: 39 : if (query->returningList)
7419 : 9 : get_returning_clause(query, context);
7420 : 39 : }
7421 : :
7422 : :
7423 : : /* ----------
7424 : : * get_merge_query_def - Parse back a MERGE parsetree
7425 : : * ----------
7426 : : */
7427 : : static void
7428 : 8 : get_merge_query_def(Query *query, deparse_context *context)
7429 : : {
7430 : 8 : StringInfo buf = context->buf;
7431 : : RangeTblEntry *rte;
7432 : : ListCell *lc;
7433 : : bool haveNotMatchedBySource;
7434 : :
7435 : : /* Insert the WITH clause if given */
7436 : 8 : get_with_clause(query, context);
7437 : :
7438 : : /*
7439 : : * Start the query with MERGE INTO relname
7440 : : */
7441 : 8 : rte = rt_fetch(query->resultRelation, query->rtable);
7442 : : Assert(rte->rtekind == RTE_RELATION);
7443 [ + - ]: 8 : if (PRETTY_INDENT(context))
7444 : : {
7445 : 8 : appendStringInfoChar(buf, ' ');
7446 : 8 : context->indentLevel += PRETTYINDENT_STD;
7447 : : }
7448 : 16 : appendStringInfo(buf, "MERGE INTO %s%s",
7449 [ + - ]: 8 : only_marker(rte),
7450 : : generate_relation_name(rte->relid, NIL));
7451 : :
7452 : : /* Print the relation alias, if needed */
7453 : 8 : get_rte_alias(rte, query->resultRelation, false, context);
7454 : :
7455 : : /* Print the source relation and join clause */
7456 : 8 : get_from_clause(query, " USING ", context);
7457 : 8 : appendContextKeyword(context, " ON ",
7458 : : -PRETTYINDENT_STD, PRETTYINDENT_STD, 2);
7459 : 8 : get_rule_expr(query->mergeJoinCondition, context, false);
7460 : :
7461 : : /*
7462 : : * Test for any NOT MATCHED BY SOURCE actions. If there are none, then
7463 : : * any NOT MATCHED BY TARGET actions are output as "WHEN NOT MATCHED", per
7464 : : * SQL standard. Otherwise, we have a non-SQL-standard query, so output
7465 : : * "BY SOURCE" / "BY TARGET" qualifiers for all NOT MATCHED actions, to be
7466 : : * more explicit.
7467 : : */
7468 : 8 : haveNotMatchedBySource = false;
7469 [ + - + + : 56 : foreach(lc, query->mergeActionList)
+ + ]
7470 : : {
7471 : 52 : MergeAction *action = lfirst_node(MergeAction, lc);
7472 : :
7473 [ + + ]: 52 : if (action->matchKind == MERGE_WHEN_NOT_MATCHED_BY_SOURCE)
7474 : : {
7475 : 4 : haveNotMatchedBySource = true;
7476 : 4 : break;
7477 : : }
7478 : : }
7479 : :
7480 : : /* Print each merge action */
7481 [ + - + + : 60 : foreach(lc, query->mergeActionList)
+ + ]
7482 : : {
7483 : 52 : MergeAction *action = lfirst_node(MergeAction, lc);
7484 : :
7485 : 52 : appendContextKeyword(context, " WHEN ",
7486 : : -PRETTYINDENT_STD, PRETTYINDENT_STD, 2);
7487 [ + + + - ]: 52 : switch (action->matchKind)
7488 : : {
7489 : 24 : case MERGE_WHEN_MATCHED:
7490 : 24 : appendStringInfoString(buf, "MATCHED");
7491 : 24 : break;
7492 : 4 : case MERGE_WHEN_NOT_MATCHED_BY_SOURCE:
7493 : 4 : appendStringInfoString(buf, "NOT MATCHED BY SOURCE");
7494 : 4 : break;
7495 : 24 : case MERGE_WHEN_NOT_MATCHED_BY_TARGET:
7496 [ + + ]: 24 : if (haveNotMatchedBySource)
7497 : 4 : appendStringInfoString(buf, "NOT MATCHED BY TARGET");
7498 : : else
7499 : 20 : appendStringInfoString(buf, "NOT MATCHED");
7500 : 24 : break;
7501 : 0 : default:
7502 [ # # ]: 0 : elog(ERROR, "unrecognized matchKind: %d",
7503 : : (int) action->matchKind);
7504 : : }
7505 : :
7506 [ + + ]: 52 : if (action->qual)
7507 : : {
7508 : 32 : appendContextKeyword(context, " AND ",
7509 : : -PRETTYINDENT_STD, PRETTYINDENT_STD, 3);
7510 : 32 : get_rule_expr(action->qual, context, false);
7511 : : }
7512 : 52 : appendContextKeyword(context, " THEN ",
7513 : : -PRETTYINDENT_STD, PRETTYINDENT_STD, 3);
7514 : :
7515 [ + + ]: 52 : if (action->commandType == CMD_INSERT)
7516 : : {
7517 : : /* This generally matches get_insert_query_def() */
7518 : 24 : List *strippedexprs = NIL;
7519 : 24 : const char *sep = "";
7520 : : ListCell *lc2;
7521 : :
7522 : 24 : appendStringInfoString(buf, "INSERT");
7523 : :
7524 [ + + ]: 24 : if (action->targetList)
7525 : 20 : appendStringInfoString(buf, " (");
7526 [ + + + + : 68 : foreach(lc2, action->targetList)
+ + ]
7527 : : {
7528 : 44 : TargetEntry *tle = (TargetEntry *) lfirst(lc2);
7529 : :
7530 : : Assert(!tle->resjunk);
7531 : :
7532 : 44 : appendStringInfoString(buf, sep);
7533 : 44 : sep = ", ";
7534 : :
7535 : 44 : appendStringInfoString(buf,
7536 : 44 : quote_identifier(get_attname(rte->relid,
7537 : 44 : tle->resno,
7538 : : false)));
7539 : 44 : strippedexprs = lappend(strippedexprs,
7540 : 44 : processIndirection((Node *) tle->expr,
7541 : : context));
7542 : : }
7543 [ + + ]: 24 : if (action->targetList)
7544 : 20 : appendStringInfoChar(buf, ')');
7545 : :
7546 [ + + ]: 24 : if (action->override)
7547 : : {
7548 [ - + ]: 4 : if (action->override == OVERRIDING_SYSTEM_VALUE)
7549 : 0 : appendStringInfoString(buf, " OVERRIDING SYSTEM VALUE");
7550 [ + - ]: 4 : else if (action->override == OVERRIDING_USER_VALUE)
7551 : 4 : appendStringInfoString(buf, " OVERRIDING USER VALUE");
7552 : : }
7553 : :
7554 [ + + ]: 24 : if (strippedexprs)
7555 : : {
7556 : 20 : appendContextKeyword(context, " VALUES (",
7557 : : -PRETTYINDENT_STD, PRETTYINDENT_STD, 4);
7558 : 20 : get_rule_list_toplevel(strippedexprs, context, false);
7559 : 20 : appendStringInfoChar(buf, ')');
7560 : : }
7561 : : else
7562 : 4 : appendStringInfoString(buf, " DEFAULT VALUES");
7563 : : }
7564 [ + + ]: 28 : else if (action->commandType == CMD_UPDATE)
7565 : : {
7566 : 16 : appendStringInfoString(buf, "UPDATE SET ");
7567 : 16 : get_update_query_targetlist_def(query, action->targetList,
7568 : : context, rte);
7569 : : }
7570 [ + + ]: 12 : else if (action->commandType == CMD_DELETE)
7571 : 8 : appendStringInfoString(buf, "DELETE");
7572 [ + - ]: 4 : else if (action->commandType == CMD_NOTHING)
7573 : 4 : appendStringInfoString(buf, "DO NOTHING");
7574 : : }
7575 : :
7576 : : /* Add RETURNING if present */
7577 [ + + ]: 8 : if (query->returningList)
7578 : 4 : get_returning_clause(query, context);
7579 : 8 : }
7580 : :
7581 : :
7582 : : /* ----------
7583 : : * get_utility_query_def - Parse back a UTILITY parsetree
7584 : : * ----------
7585 : : */
7586 : : static void
7587 : 9 : get_utility_query_def(Query *query, deparse_context *context)
7588 : : {
7589 : 9 : StringInfo buf = context->buf;
7590 : :
7591 [ + - + - ]: 9 : if (query->utilityStmt && IsA(query->utilityStmt, NotifyStmt))
7592 : 9 : {
7593 : 9 : NotifyStmt *stmt = (NotifyStmt *) query->utilityStmt;
7594 : :
7595 : 9 : appendContextKeyword(context, "",
7596 : : 0, PRETTYINDENT_STD, 1);
7597 : 9 : appendStringInfo(buf, "NOTIFY %s",
7598 : 9 : quote_identifier(stmt->conditionname));
7599 [ - + ]: 9 : if (stmt->payload)
7600 : : {
7601 : 0 : appendStringInfoString(buf, ", ");
7602 : 0 : simple_quote_literal(buf, stmt->payload);
7603 : : }
7604 : : }
7605 : : else
7606 : : {
7607 : : /* Currently only NOTIFY utility commands can appear in rules */
7608 [ # # ]: 0 : elog(ERROR, "unexpected utility statement type");
7609 : : }
7610 : 9 : }
7611 : :
7612 : : /*
7613 : : * Display a Var appropriately.
7614 : : *
7615 : : * In some cases (currently only when recursing into an unnamed join)
7616 : : * the Var's varlevelsup has to be interpreted with respect to a context
7617 : : * above the current one; levelsup indicates the offset.
7618 : : *
7619 : : * If istoplevel is true, the Var is at the top level of a SELECT's
7620 : : * targetlist, which means we need special treatment of whole-row Vars.
7621 : : * Instead of the normal "tab.*", we'll print "tab.*::typename", which is a
7622 : : * dirty hack to prevent "tab.*" from being expanded into multiple columns.
7623 : : * (The parser will strip the useless coercion, so no inefficiency is added in
7624 : : * dump and reload.) We used to print just "tab" in such cases, but that is
7625 : : * ambiguous and will yield the wrong result if "tab" is also a plain column
7626 : : * name in the query.
7627 : : *
7628 : : * Returns the attname of the Var, or NULL if the Var has no attname (because
7629 : : * it is a whole-row Var or a subplan output reference).
7630 : : */
7631 : : static char *
7632 : 129713 : get_variable(Var *var, int levelsup, bool istoplevel, deparse_context *context)
7633 : : {
7634 : 129713 : StringInfo buf = context->buf;
7635 : : RangeTblEntry *rte;
7636 : : AttrNumber attnum;
7637 : : int netlevelsup;
7638 : : deparse_namespace *dpns;
7639 : : int varno;
7640 : : AttrNumber varattno;
7641 : : deparse_columns *colinfo;
7642 : : char *refname;
7643 : : char *attname;
7644 : : bool need_prefix;
7645 : :
7646 : : /* Find appropriate nesting depth */
7647 : 129713 : netlevelsup = var->varlevelsup + levelsup;
7648 [ - + ]: 129713 : if (netlevelsup >= list_length(context->namespaces))
7649 [ # # ]: 0 : elog(ERROR, "bogus varlevelsup: %d offset %d",
7650 : : var->varlevelsup, levelsup);
7651 : 129713 : dpns = (deparse_namespace *) list_nth(context->namespaces,
7652 : : netlevelsup);
7653 : :
7654 : : /*
7655 : : * If we have a syntactic referent for the Var, and we're working from a
7656 : : * parse tree, prefer to use the syntactic referent. Otherwise, fall back
7657 : : * on the semantic referent. (Forcing use of the semantic referent when
7658 : : * printing plan trees is a design choice that's perhaps more motivated by
7659 : : * backwards compatibility than anything else. But it does have the
7660 : : * advantage of making plans more explicit.)
7661 : : */
7662 [ + + + + ]: 129713 : if (var->varnosyn > 0 && dpns->plan == NULL)
7663 : : {
7664 : 24262 : varno = var->varnosyn;
7665 : 24262 : varattno = var->varattnosyn;
7666 : : }
7667 : : else
7668 : : {
7669 : 105451 : varno = var->varno;
7670 : 105451 : varattno = var->varattno;
7671 : : }
7672 : :
7673 : : /*
7674 : : * Try to find the relevant RTE in this rtable. In a plan tree, it's
7675 : : * likely that varno is OUTER_VAR or INNER_VAR, in which case we must dig
7676 : : * down into the subplans, or INDEX_VAR, which is resolved similarly. Also
7677 : : * find the aliases previously assigned for this RTE.
7678 : : */
7679 [ + + + - ]: 129713 : if (varno >= 1 && varno <= list_length(dpns->rtable))
7680 : : {
7681 : : /*
7682 : : * We might have been asked to map child Vars to some parent relation.
7683 : : */
7684 [ + + + + ]: 93504 : if (context->appendparents && dpns->appendrels)
7685 : : {
7686 : 2531 : int pvarno = varno;
7687 : 2531 : AttrNumber pvarattno = varattno;
7688 : 2531 : AppendRelInfo *appinfo = dpns->appendrels[pvarno];
7689 : 2531 : bool found = false;
7690 : :
7691 : : /* Only map up to inheritance parents, not UNION ALL appendrels */
7692 [ + + ]: 5108 : while (appinfo &&
7693 : 2808 : rt_fetch(appinfo->parent_relid,
7694 [ + + ]: 2808 : dpns->rtable)->rtekind == RTE_RELATION)
7695 : : {
7696 : 2577 : found = false;
7697 [ + + ]: 2577 : if (pvarattno > 0) /* system columns stay as-is */
7698 : : {
7699 [ - + ]: 2425 : if (pvarattno > appinfo->num_child_cols)
7700 : 0 : break; /* safety check */
7701 : 2425 : pvarattno = appinfo->parent_colnos[pvarattno - 1];
7702 [ - + ]: 2425 : if (pvarattno == 0)
7703 : 0 : break; /* Var is local to child */
7704 : : }
7705 : :
7706 : 2577 : pvarno = appinfo->parent_relid;
7707 : 2577 : found = true;
7708 : :
7709 : : /* If the parent is itself a child, continue up. */
7710 : : Assert(pvarno > 0 && pvarno <= list_length(dpns->rtable));
7711 : 2577 : appinfo = dpns->appendrels[pvarno];
7712 : : }
7713 : :
7714 : : /*
7715 : : * If we found an ancestral rel, and that rel is included in
7716 : : * appendparents, print that column not the original one.
7717 : : */
7718 [ + + + + ]: 2531 : if (found && bms_is_member(pvarno, context->appendparents))
7719 : : {
7720 : 2052 : varno = pvarno;
7721 : 2052 : varattno = pvarattno;
7722 : : }
7723 : : }
7724 : :
7725 : 93504 : rte = rt_fetch(varno, dpns->rtable);
7726 : :
7727 : : /* might be returning old/new column value */
7728 [ + + ]: 93504 : if (var->varreturningtype == VAR_RETURNING_OLD)
7729 : 274 : refname = dpns->ret_old_alias;
7730 [ + + ]: 93230 : else if (var->varreturningtype == VAR_RETURNING_NEW)
7731 : 273 : refname = dpns->ret_new_alias;
7732 : : else
7733 : 92957 : refname = (char *) list_nth(dpns->rtable_names, varno - 1);
7734 : :
7735 : 93504 : colinfo = deparse_columns_fetch(varno, dpns);
7736 : 93504 : attnum = varattno;
7737 : : }
7738 : : else
7739 : : {
7740 : 36209 : resolve_special_varno((Node *) var, context,
7741 : : get_special_variable, NULL);
7742 : 36209 : return NULL;
7743 : : }
7744 : :
7745 : : /*
7746 : : * The planner will sometimes emit Vars referencing resjunk elements of a
7747 : : * subquery's target list (this is currently only possible if it chooses
7748 : : * to generate a "physical tlist" for a SubqueryScan or CteScan node).
7749 : : * Although we prefer to print subquery-referencing Vars using the
7750 : : * subquery's alias, that's not possible for resjunk items since they have
7751 : : * no alias. So in that case, drill down to the subplan and print the
7752 : : * contents of the referenced tlist item. This works because in a plan
7753 : : * tree, such Vars can only occur in a SubqueryScan or CteScan node, and
7754 : : * we'll have set dpns->inner_plan to reference the child plan node.
7755 : : */
7756 [ + + + + : 96695 : if ((rte->rtekind == RTE_SUBQUERY || rte->rtekind == RTE_CTE) &&
+ + ]
7757 : 3191 : attnum > list_length(rte->eref->colnames) &&
7758 [ + - ]: 1 : dpns->inner_plan)
7759 : : {
7760 : : TargetEntry *tle;
7761 : : deparse_namespace save_dpns;
7762 : :
7763 : 1 : tle = get_tle_by_resno(dpns->inner_tlist, attnum);
7764 [ - + ]: 1 : if (!tle)
7765 [ # # ]: 0 : elog(ERROR, "invalid attnum %d for relation \"%s\"",
7766 : : attnum, rte->eref->aliasname);
7767 : :
7768 : : Assert(netlevelsup == 0);
7769 : 1 : push_child_plan(dpns, dpns->inner_plan, &save_dpns);
7770 : :
7771 : : /*
7772 : : * Force parentheses because our caller probably assumed a Var is a
7773 : : * simple expression.
7774 : : */
7775 [ - + ]: 1 : if (!IsA(tle->expr, Var))
7776 : 0 : appendStringInfoChar(buf, '(');
7777 : 1 : get_rule_expr((Node *) tle->expr, context, true);
7778 [ - + ]: 1 : if (!IsA(tle->expr, Var))
7779 : 0 : appendStringInfoChar(buf, ')');
7780 : :
7781 : 1 : pop_child_plan(dpns, &save_dpns);
7782 : 1 : return NULL;
7783 : : }
7784 : :
7785 : : /*
7786 : : * If it's an unnamed join, look at the expansion of the alias variable.
7787 : : * If it's a simple reference to one of the input vars, then recursively
7788 : : * print the name of that var instead. When it's not a simple reference,
7789 : : * we have to just print the unqualified join column name. (This can only
7790 : : * happen with "dangerous" merged columns in a JOIN USING; we took pains
7791 : : * previously to make the unqualified column name unique in such cases.)
7792 : : *
7793 : : * This wouldn't work in decompiling plan trees, because we don't store
7794 : : * joinaliasvars lists after planning; but a plan tree should never
7795 : : * contain a join alias variable.
7796 : : */
7797 [ + + + + ]: 93503 : if (rte->rtekind == RTE_JOIN && rte->alias == NULL)
7798 : : {
7799 [ - + ]: 72 : if (rte->joinaliasvars == NIL)
7800 [ # # ]: 0 : elog(ERROR, "cannot decompile join alias var in plan tree");
7801 [ + - ]: 72 : if (attnum > 0)
7802 : : {
7803 : : Var *aliasvar;
7804 : :
7805 : 72 : aliasvar = (Var *) list_nth(rte->joinaliasvars, attnum - 1);
7806 : : /* we intentionally don't strip implicit coercions here */
7807 [ + - - + ]: 72 : if (aliasvar && IsA(aliasvar, Var))
7808 : : {
7809 : 0 : return get_variable(aliasvar, var->varlevelsup + levelsup,
7810 : : istoplevel, context);
7811 : : }
7812 : : }
7813 : :
7814 : : /*
7815 : : * Unnamed join has no refname. (Note: since it's unnamed, there is
7816 : : * no way the user could have referenced it to create a whole-row Var
7817 : : * for it. So we don't have to cover that case below.)
7818 : : */
7819 : : Assert(refname == NULL);
7820 : : }
7821 : :
7822 [ + + ]: 93503 : if (attnum == InvalidAttrNumber)
7823 : 752 : attname = NULL;
7824 [ + + ]: 92751 : else if (attnum > 0)
7825 : : {
7826 : : /* Get column name to use from the colinfo struct */
7827 [ - + ]: 91543 : if (attnum > colinfo->num_cols)
7828 [ # # ]: 0 : elog(ERROR, "invalid attnum %d for relation \"%s\"",
7829 : : attnum, rte->eref->aliasname);
7830 : 91543 : attname = colinfo->colnames[attnum - 1];
7831 : :
7832 : : /*
7833 : : * If we find a Var referencing a dropped column, it seems better to
7834 : : * print something (anything) than to fail. In general this should
7835 : : * not happen, but it used to be possible for some cases involving
7836 : : * functions returning named composite types, and perhaps there are
7837 : : * still bugs out there.
7838 : : */
7839 [ + + ]: 91543 : if (attname == NULL)
7840 : 4 : attname = "?dropped?column?";
7841 : : }
7842 : : else
7843 : : {
7844 : : /* System column - name is fixed, get it from the catalog */
7845 : 1208 : attname = get_rte_attribute_name(rte, attnum);
7846 : : }
7847 : :
7848 [ + + + + ]: 136913 : need_prefix = (context->varprefix || attname == NULL ||
7849 [ + + ]: 43410 : var->varreturningtype != VAR_RETURNING_DEFAULT);
7850 : :
7851 : : /*
7852 : : * If we're considering a plain Var in an ORDER BY (but not GROUP BY)
7853 : : * clause, we may need to add a table-name prefix to prevent
7854 : : * findTargetlistEntrySQL92 from misinterpreting the name as an
7855 : : * output-column name. To avoid cluttering the output with unnecessary
7856 : : * prefixes, do so only if there is a name match to a SELECT tlist item
7857 : : * that is different from the Var.
7858 : : */
7859 [ + + + + : 93503 : if (context->varInOrderBy && !context->inGroupBy && !need_prefix)
+ + ]
7860 : : {
7861 : 179 : int colno = 0;
7862 : :
7863 [ + + + + : 661 : foreach_node(TargetEntry, tle, context->targetList)
+ + ]
7864 : : {
7865 : : char *colname;
7866 : :
7867 [ - + ]: 311 : if (tle->resjunk)
7868 : 0 : continue; /* ignore junk entries */
7869 : 311 : colno++;
7870 : :
7871 : : /* This must match colname-choosing logic in get_target_list() */
7872 [ + - + - ]: 311 : if (context->resultDesc && colno <= context->resultDesc->natts)
7873 : 311 : colname = NameStr(TupleDescAttr(context->resultDesc,
7874 : : colno - 1)->attname);
7875 : : else
7876 : 0 : colname = tle->resname;
7877 : :
7878 [ + - + + ]: 311 : if (colname && strcmp(colname, attname) == 0 &&
7879 [ + + ]: 106 : !equal(var, tle->expr))
7880 : : {
7881 : 8 : need_prefix = true;
7882 : 8 : break;
7883 : : }
7884 : : }
7885 : : }
7886 : :
7887 [ + + + + ]: 93503 : if (refname && need_prefix)
7888 : : {
7889 : 50042 : appendStringInfoString(buf, quote_identifier(refname));
7890 : 50042 : appendStringInfoChar(buf, '.');
7891 : : }
7892 [ + + ]: 93503 : if (attname)
7893 : 92751 : appendStringInfoString(buf, quote_identifier(attname));
7894 : : else
7895 : : {
7896 : 752 : appendStringInfoChar(buf, '*');
7897 [ + + ]: 752 : if (istoplevel)
7898 : 56 : appendStringInfo(buf, "::%s",
7899 : : format_type_with_typemod(var->vartype,
7900 : : var->vartypmod));
7901 : : }
7902 : :
7903 : 93503 : return attname;
7904 : : }
7905 : :
7906 : : /*
7907 : : * Deparse a Var which references OUTER_VAR, INNER_VAR, or INDEX_VAR. This
7908 : : * routine is actually a callback for resolve_special_varno, which handles
7909 : : * finding the correct TargetEntry. We get the expression contained in that
7910 : : * TargetEntry and just need to deparse it, a job we can throw back on
7911 : : * get_rule_expr.
7912 : : */
7913 : : static void
7914 : 36209 : get_special_variable(Node *node, deparse_context *context, void *callback_arg)
7915 : : {
7916 : 36209 : StringInfo buf = context->buf;
7917 : :
7918 : : /*
7919 : : * For a non-Var referent, force parentheses because our caller probably
7920 : : * assumed a Var is a simple expression.
7921 : : */
7922 [ + + ]: 36209 : if (!IsA(node, Var))
7923 : 3856 : appendStringInfoChar(buf, '(');
7924 : 36209 : get_rule_expr(node, context, true);
7925 [ + + ]: 36209 : if (!IsA(node, Var))
7926 : 3856 : appendStringInfoChar(buf, ')');
7927 : 36209 : }
7928 : :
7929 : : /*
7930 : : * Chase through plan references to special varnos (OUTER_VAR, INNER_VAR,
7931 : : * INDEX_VAR) until we find a real Var or some kind of non-Var node; then,
7932 : : * invoke the callback provided.
7933 : : */
7934 : : static void
7935 : 101816 : resolve_special_varno(Node *node, deparse_context *context,
7936 : : rsv_callback callback, void *callback_arg)
7937 : : {
7938 : : Var *var;
7939 : : deparse_namespace *dpns;
7940 : :
7941 : : /* This function is recursive, so let's be paranoid. */
7942 : 101816 : check_stack_depth();
7943 : :
7944 : : /* If it's not a Var, invoke the callback. */
7945 [ + + ]: 101816 : if (!IsA(node, Var))
7946 : : {
7947 : 4408 : (*callback) (node, context, callback_arg);
7948 : 4408 : return;
7949 : : }
7950 : :
7951 : : /* Find appropriate nesting depth */
7952 : 97408 : var = (Var *) node;
7953 : 97408 : dpns = (deparse_namespace *) list_nth(context->namespaces,
7954 : 97408 : var->varlevelsup);
7955 : :
7956 : : /*
7957 : : * If varno is special, recurse. (Don't worry about varnosyn; if we're
7958 : : * here, we already decided not to use that.)
7959 : : */
7960 [ + + + - ]: 97408 : if (var->varno == OUTER_VAR && dpns->outer_tlist)
7961 : : {
7962 : : TargetEntry *tle;
7963 : : deparse_namespace save_dpns;
7964 : : Bitmapset *save_appendparents;
7965 : :
7966 : 49336 : tle = get_tle_by_resno(dpns->outer_tlist, var->varattno);
7967 [ - + ]: 49336 : if (!tle)
7968 [ # # ]: 0 : elog(ERROR, "bogus varattno for OUTER_VAR var: %d", var->varattno);
7969 : :
7970 : : /*
7971 : : * If we're descending to the first child of an Append or MergeAppend,
7972 : : * update appendparents. This will affect deparsing of all Vars
7973 : : * appearing within the eventually-resolved subexpression.
7974 : : */
7975 : 49336 : save_appendparents = context->appendparents;
7976 : :
7977 [ + + ]: 49336 : if (IsA(dpns->plan, Append))
7978 : 3021 : context->appendparents = bms_union(context->appendparents,
7979 : 3021 : ((Append *) dpns->plan)->apprelids);
7980 [ + + ]: 46315 : else if (IsA(dpns->plan, MergeAppend))
7981 : 413 : context->appendparents = bms_union(context->appendparents,
7982 : 413 : ((MergeAppend *) dpns->plan)->apprelids);
7983 : :
7984 : 49336 : push_child_plan(dpns, dpns->outer_plan, &save_dpns);
7985 : 49336 : resolve_special_varno((Node *) tle->expr, context,
7986 : : callback, callback_arg);
7987 : 49336 : pop_child_plan(dpns, &save_dpns);
7988 : 49336 : context->appendparents = save_appendparents;
7989 : 49336 : return;
7990 : : }
7991 [ + + + - ]: 48072 : else if (var->varno == INNER_VAR && dpns->inner_tlist)
7992 : : {
7993 : : TargetEntry *tle;
7994 : : deparse_namespace save_dpns;
7995 : :
7996 : 12130 : tle = get_tle_by_resno(dpns->inner_tlist, var->varattno);
7997 [ - + ]: 12130 : if (!tle)
7998 [ # # ]: 0 : elog(ERROR, "bogus varattno for INNER_VAR var: %d", var->varattno);
7999 : :
8000 : 12130 : push_child_plan(dpns, dpns->inner_plan, &save_dpns);
8001 : 12130 : resolve_special_varno((Node *) tle->expr, context,
8002 : : callback, callback_arg);
8003 : 12130 : pop_child_plan(dpns, &save_dpns);
8004 : 12130 : return;
8005 : : }
8006 [ + + + - ]: 35942 : else if (var->varno == INDEX_VAR && dpns->index_tlist)
8007 : : {
8008 : : TargetEntry *tle;
8009 : :
8010 : 3589 : tle = get_tle_by_resno(dpns->index_tlist, var->varattno);
8011 [ - + ]: 3589 : if (!tle)
8012 [ # # ]: 0 : elog(ERROR, "bogus varattno for INDEX_VAR var: %d", var->varattno);
8013 : :
8014 : 3589 : resolve_special_varno((Node *) tle->expr, context,
8015 : : callback, callback_arg);
8016 : 3589 : return;
8017 : : }
8018 [ + - - + ]: 32353 : else if (var->varno < 1 || var->varno > list_length(dpns->rtable))
8019 [ # # ]: 0 : elog(ERROR, "bogus varno: %d", var->varno);
8020 : :
8021 : : /* Not special. Just invoke the callback. */
8022 : 32353 : (*callback) (node, context, callback_arg);
8023 : : }
8024 : :
8025 : : /*
8026 : : * Get the name of a field of an expression of composite type. The
8027 : : * expression is usually a Var, but we handle other cases too.
8028 : : *
8029 : : * levelsup is an extra offset to interpret the Var's varlevelsup correctly.
8030 : : *
8031 : : * This is fairly straightforward when the expression has a named composite
8032 : : * type; we need only look up the type in the catalogs. However, the type
8033 : : * could also be RECORD. Since no actual table or view column is allowed to
8034 : : * have type RECORD, a Var of type RECORD must refer to a JOIN or FUNCTION RTE
8035 : : * or to a subquery output. We drill down to find the ultimate defining
8036 : : * expression and attempt to infer the field name from it. We ereport if we
8037 : : * can't determine the name.
8038 : : *
8039 : : * Similarly, a PARAM of type RECORD has to refer to some expression of
8040 : : * a determinable composite type.
8041 : : */
8042 : : static const char *
8043 : 1058 : get_name_for_var_field(Var *var, int fieldno,
8044 : : int levelsup, deparse_context *context)
8045 : : {
8046 : : RangeTblEntry *rte;
8047 : : AttrNumber attnum;
8048 : : int netlevelsup;
8049 : : deparse_namespace *dpns;
8050 : : int varno;
8051 : : AttrNumber varattno;
8052 : : TupleDesc tupleDesc;
8053 : : Node *expr;
8054 : :
8055 : : /*
8056 : : * If it's a RowExpr that was expanded from a whole-row Var, use the
8057 : : * column names attached to it. (We could let get_expr_result_tupdesc()
8058 : : * handle this, but it's much cheaper to just pull out the name we need.)
8059 : : */
8060 [ + + ]: 1058 : if (IsA(var, RowExpr))
8061 : : {
8062 : 24 : RowExpr *r = (RowExpr *) var;
8063 : :
8064 [ + - + - ]: 24 : if (fieldno > 0 && fieldno <= list_length(r->colnames))
8065 : 24 : return strVal(list_nth(r->colnames, fieldno - 1));
8066 : : }
8067 : :
8068 : : /*
8069 : : * If it's a Param of type RECORD, try to find what the Param refers to.
8070 : : */
8071 [ + + ]: 1034 : if (IsA(var, Param))
8072 : : {
8073 : 12 : Param *param = (Param *) var;
8074 : : ListCell *ancestor_cell;
8075 : :
8076 : 12 : expr = find_param_referent(param, context, &dpns, &ancestor_cell);
8077 [ + - ]: 12 : if (expr)
8078 : : {
8079 : : /* Found a match, so recurse to decipher the field name */
8080 : : deparse_namespace save_dpns;
8081 : : const char *result;
8082 : :
8083 : 12 : push_ancestor_plan(dpns, ancestor_cell, &save_dpns);
8084 : 12 : result = get_name_for_var_field((Var *) expr, fieldno,
8085 : : 0, context);
8086 : 12 : pop_ancestor_plan(dpns, &save_dpns);
8087 : 12 : return result;
8088 : : }
8089 : : }
8090 : :
8091 : : /*
8092 : : * If it's a Var of type RECORD, we have to find what the Var refers to;
8093 : : * if not, we can use get_expr_result_tupdesc().
8094 : : */
8095 [ + + ]: 1022 : if (!IsA(var, Var) ||
8096 [ + + ]: 961 : var->vartype != RECORDOID)
8097 : : {
8098 : 858 : tupleDesc = get_expr_result_tupdesc((Node *) var, false);
8099 : : /* Got the tupdesc, so we can extract the field name */
8100 : : Assert(fieldno >= 1 && fieldno <= tupleDesc->natts);
8101 : 858 : return NameStr(TupleDescAttr(tupleDesc, fieldno - 1)->attname);
8102 : : }
8103 : :
8104 : : /* Find appropriate nesting depth */
8105 : 164 : netlevelsup = var->varlevelsup + levelsup;
8106 [ - + ]: 164 : if (netlevelsup >= list_length(context->namespaces))
8107 [ # # ]: 0 : elog(ERROR, "bogus varlevelsup: %d offset %d",
8108 : : var->varlevelsup, levelsup);
8109 : 164 : dpns = (deparse_namespace *) list_nth(context->namespaces,
8110 : : netlevelsup);
8111 : :
8112 : : /*
8113 : : * If we have a syntactic referent for the Var, and we're working from a
8114 : : * parse tree, prefer to use the syntactic referent. Otherwise, fall back
8115 : : * on the semantic referent. (See comments in get_variable().)
8116 : : */
8117 [ + + + + ]: 164 : if (var->varnosyn > 0 && dpns->plan == NULL)
8118 : : {
8119 : 64 : varno = var->varnosyn;
8120 : 64 : varattno = var->varattnosyn;
8121 : : }
8122 : : else
8123 : : {
8124 : 100 : varno = var->varno;
8125 : 100 : varattno = var->varattno;
8126 : : }
8127 : :
8128 : : /*
8129 : : * Try to find the relevant RTE in this rtable. In a plan tree, it's
8130 : : * likely that varno is OUTER_VAR or INNER_VAR, in which case we must dig
8131 : : * down into the subplans, or INDEX_VAR, which is resolved similarly.
8132 : : *
8133 : : * Note: unlike get_variable and resolve_special_varno, we need not worry
8134 : : * about inheritance mapping: a child Var should have the same datatype as
8135 : : * its parent, and here we're really only interested in the Var's type.
8136 : : */
8137 [ + + + - ]: 164 : if (varno >= 1 && varno <= list_length(dpns->rtable))
8138 : : {
8139 : 112 : rte = rt_fetch(varno, dpns->rtable);
8140 : 112 : attnum = varattno;
8141 : : }
8142 [ + + + - ]: 52 : else if (varno == OUTER_VAR && dpns->outer_tlist)
8143 : : {
8144 : : TargetEntry *tle;
8145 : : deparse_namespace save_dpns;
8146 : : const char *result;
8147 : :
8148 : 40 : tle = get_tle_by_resno(dpns->outer_tlist, varattno);
8149 [ - + ]: 40 : if (!tle)
8150 [ # # ]: 0 : elog(ERROR, "bogus varattno for OUTER_VAR var: %d", varattno);
8151 : :
8152 : : Assert(netlevelsup == 0);
8153 : 40 : push_child_plan(dpns, dpns->outer_plan, &save_dpns);
8154 : :
8155 : 40 : result = get_name_for_var_field((Var *) tle->expr, fieldno,
8156 : : levelsup, context);
8157 : :
8158 : 40 : pop_child_plan(dpns, &save_dpns);
8159 : 40 : return result;
8160 : : }
8161 [ + - + - ]: 12 : else if (varno == INNER_VAR && dpns->inner_tlist)
8162 : : {
8163 : : TargetEntry *tle;
8164 : : deparse_namespace save_dpns;
8165 : : const char *result;
8166 : :
8167 : 12 : tle = get_tle_by_resno(dpns->inner_tlist, varattno);
8168 [ - + ]: 12 : if (!tle)
8169 [ # # ]: 0 : elog(ERROR, "bogus varattno for INNER_VAR var: %d", varattno);
8170 : :
8171 : : Assert(netlevelsup == 0);
8172 : 12 : push_child_plan(dpns, dpns->inner_plan, &save_dpns);
8173 : :
8174 : 12 : result = get_name_for_var_field((Var *) tle->expr, fieldno,
8175 : : levelsup, context);
8176 : :
8177 : 12 : pop_child_plan(dpns, &save_dpns);
8178 : 12 : return result;
8179 : : }
8180 [ # # # # ]: 0 : else if (varno == INDEX_VAR && dpns->index_tlist)
8181 : : {
8182 : : TargetEntry *tle;
8183 : : const char *result;
8184 : :
8185 : 0 : tle = get_tle_by_resno(dpns->index_tlist, varattno);
8186 [ # # ]: 0 : if (!tle)
8187 [ # # ]: 0 : elog(ERROR, "bogus varattno for INDEX_VAR var: %d", varattno);
8188 : :
8189 : : Assert(netlevelsup == 0);
8190 : :
8191 : 0 : result = get_name_for_var_field((Var *) tle->expr, fieldno,
8192 : : levelsup, context);
8193 : :
8194 : 0 : return result;
8195 : : }
8196 : : else
8197 : : {
8198 [ # # ]: 0 : elog(ERROR, "bogus varno: %d", varno);
8199 : : return NULL; /* keep compiler quiet */
8200 : : }
8201 : :
8202 [ + + ]: 112 : if (attnum == InvalidAttrNumber)
8203 : : {
8204 : : /* Var is whole-row reference to RTE, so select the right field */
8205 : 16 : return get_rte_attribute_name(rte, fieldno);
8206 : : }
8207 : :
8208 : : /*
8209 : : * This part has essentially the same logic as the parser's
8210 : : * expandRecordVariable() function, but we are dealing with a different
8211 : : * representation of the input context, and we only need one field name
8212 : : * not a TupleDesc. Also, we need special cases for finding subquery and
8213 : : * CTE subplans when deparsing Plan trees.
8214 : : */
8215 : 96 : expr = (Node *) var; /* default if we can't drill down */
8216 : :
8217 [ - + - - : 96 : switch (rte->rtekind)
+ - - ]
8218 : : {
8219 : 0 : case RTE_RELATION:
8220 : : case RTE_VALUES:
8221 : : case RTE_NAMEDTUPLESTORE:
8222 : : case RTE_RESULT:
8223 : :
8224 : : /*
8225 : : * This case should not occur: a column of a table, values list,
8226 : : * or ENR shouldn't have type RECORD. Fall through and fail (most
8227 : : * likely) at the bottom.
8228 : : */
8229 : 0 : break;
8230 : 48 : case RTE_SUBQUERY:
8231 : : /* Subselect-in-FROM: examine sub-select's output expr */
8232 : : {
8233 [ + + ]: 48 : if (rte->subquery)
8234 : : {
8235 : 28 : TargetEntry *ste = get_tle_by_resno(rte->subquery->targetList,
8236 : : attnum);
8237 : :
8238 [ + - - + ]: 28 : if (ste == NULL || ste->resjunk)
8239 [ # # ]: 0 : elog(ERROR, "subquery %s does not have attribute %d",
8240 : : rte->eref->aliasname, attnum);
8241 : 28 : expr = (Node *) ste->expr;
8242 [ + + ]: 28 : if (IsA(expr, Var))
8243 : : {
8244 : : /*
8245 : : * Recurse into the sub-select to see what its Var
8246 : : * refers to. We have to build an additional level of
8247 : : * namespace to keep in step with varlevelsup in the
8248 : : * subselect; furthermore, the subquery RTE might be
8249 : : * from an outer query level, in which case the
8250 : : * namespace for the subselect must have that outer
8251 : : * level as parent namespace.
8252 : : */
8253 : 12 : List *save_nslist = context->namespaces;
8254 : : List *parent_namespaces;
8255 : : deparse_namespace mydpns;
8256 : : const char *result;
8257 : :
8258 : 12 : parent_namespaces = list_copy_tail(context->namespaces,
8259 : : netlevelsup);
8260 : :
8261 : 12 : set_deparse_for_query(&mydpns, rte->subquery,
8262 : : parent_namespaces);
8263 : :
8264 : 12 : context->namespaces = lcons(&mydpns, parent_namespaces);
8265 : :
8266 : 12 : result = get_name_for_var_field((Var *) expr, fieldno,
8267 : : 0, context);
8268 : :
8269 : 12 : context->namespaces = save_nslist;
8270 : :
8271 : 12 : return result;
8272 : : }
8273 : : /* else fall through to inspect the expression */
8274 : : }
8275 : : else
8276 : : {
8277 : : /*
8278 : : * We're deparsing a Plan tree so we don't have complete
8279 : : * RTE entries (in particular, rte->subquery is NULL). But
8280 : : * the only place we'd normally see a Var directly
8281 : : * referencing a SUBQUERY RTE is in a SubqueryScan plan
8282 : : * node, and we can look into the child plan's tlist
8283 : : * instead. An exception occurs if the subquery was
8284 : : * proven empty and optimized away: then we'd find such a
8285 : : * Var in a childless Result node, and there's nothing in
8286 : : * the plan tree that would let us figure out what it had
8287 : : * originally referenced. In that case, fall back on
8288 : : * printing "fN", analogously to the default column names
8289 : : * for RowExprs.
8290 : : */
8291 : : TargetEntry *tle;
8292 : : deparse_namespace save_dpns;
8293 : : const char *result;
8294 : :
8295 [ + + ]: 20 : if (!dpns->inner_plan)
8296 : : {
8297 : 8 : char *dummy_name = palloc(32);
8298 : :
8299 : : Assert(dpns->plan && IsA(dpns->plan, Result));
8300 : 8 : snprintf(dummy_name, 32, "f%d", fieldno);
8301 : 8 : return dummy_name;
8302 : : }
8303 : : Assert(dpns->plan && IsA(dpns->plan, SubqueryScan));
8304 : :
8305 : 12 : tle = get_tle_by_resno(dpns->inner_tlist, attnum);
8306 [ - + ]: 12 : if (!tle)
8307 [ # # ]: 0 : elog(ERROR, "bogus varattno for subquery var: %d",
8308 : : attnum);
8309 : : Assert(netlevelsup == 0);
8310 : 12 : push_child_plan(dpns, dpns->inner_plan, &save_dpns);
8311 : :
8312 : 12 : result = get_name_for_var_field((Var *) tle->expr, fieldno,
8313 : : levelsup, context);
8314 : :
8315 : 12 : pop_child_plan(dpns, &save_dpns);
8316 : 12 : return result;
8317 : : }
8318 : : }
8319 : 16 : break;
8320 : 0 : case RTE_JOIN:
8321 : : /* Join RTE --- recursively inspect the alias variable */
8322 [ # # ]: 0 : if (rte->joinaliasvars == NIL)
8323 [ # # ]: 0 : elog(ERROR, "cannot decompile join alias var in plan tree");
8324 : : Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
8325 : 0 : expr = (Node *) list_nth(rte->joinaliasvars, attnum - 1);
8326 : : Assert(expr != NULL);
8327 : : /* we intentionally don't strip implicit coercions here */
8328 [ # # ]: 0 : if (IsA(expr, Var))
8329 : 0 : return get_name_for_var_field((Var *) expr, fieldno,
8330 : 0 : var->varlevelsup + levelsup,
8331 : : context);
8332 : : /* else fall through to inspect the expression */
8333 : 0 : break;
8334 : 0 : case RTE_FUNCTION:
8335 : : case RTE_TABLEFUNC:
8336 : :
8337 : : /*
8338 : : * We couldn't get here unless a function is declared with one of
8339 : : * its result columns as RECORD, which is not allowed.
8340 : : */
8341 : 0 : break;
8342 : 48 : case RTE_CTE:
8343 : : /* CTE reference: examine subquery's output expr */
8344 : : {
8345 : 48 : CommonTableExpr *cte = NULL;
8346 : : Index ctelevelsup;
8347 : : ListCell *lc;
8348 : :
8349 : : /*
8350 : : * Try to find the referenced CTE using the namespace stack.
8351 : : */
8352 : 48 : ctelevelsup = rte->ctelevelsup + netlevelsup;
8353 [ + + ]: 48 : if (ctelevelsup >= list_length(context->namespaces))
8354 : 8 : lc = NULL;
8355 : : else
8356 : : {
8357 : : deparse_namespace *ctedpns;
8358 : :
8359 : : ctedpns = (deparse_namespace *)
8360 : 40 : list_nth(context->namespaces, ctelevelsup);
8361 [ + + + - : 44 : foreach(lc, ctedpns->ctes)
+ + ]
8362 : : {
8363 : 24 : cte = (CommonTableExpr *) lfirst(lc);
8364 [ + + ]: 24 : if (strcmp(cte->ctename, rte->ctename) == 0)
8365 : 20 : break;
8366 : : }
8367 : : }
8368 [ + + ]: 48 : if (lc != NULL)
8369 : : {
8370 : 20 : Query *ctequery = (Query *) cte->ctequery;
8371 [ + - ]: 20 : TargetEntry *ste = get_tle_by_resno(GetCTETargetList(cte),
8372 : : attnum);
8373 : :
8374 [ + - - + ]: 20 : if (ste == NULL || ste->resjunk)
8375 [ # # ]: 0 : elog(ERROR, "CTE %s does not have attribute %d",
8376 : : rte->eref->aliasname, attnum);
8377 : 20 : expr = (Node *) ste->expr;
8378 [ + + ]: 20 : if (IsA(expr, Var))
8379 : : {
8380 : : /*
8381 : : * Recurse into the CTE to see what its Var refers to.
8382 : : * We have to build an additional level of namespace
8383 : : * to keep in step with varlevelsup in the CTE;
8384 : : * furthermore it could be an outer CTE (compare
8385 : : * SUBQUERY case above).
8386 : : */
8387 : 12 : List *save_nslist = context->namespaces;
8388 : : List *parent_namespaces;
8389 : : deparse_namespace mydpns;
8390 : : const char *result;
8391 : :
8392 : 12 : parent_namespaces = list_copy_tail(context->namespaces,
8393 : : ctelevelsup);
8394 : :
8395 : 12 : set_deparse_for_query(&mydpns, ctequery,
8396 : : parent_namespaces);
8397 : :
8398 : 12 : context->namespaces = lcons(&mydpns, parent_namespaces);
8399 : :
8400 : 12 : result = get_name_for_var_field((Var *) expr, fieldno,
8401 : : 0, context);
8402 : :
8403 : 12 : context->namespaces = save_nslist;
8404 : :
8405 : 12 : return result;
8406 : : }
8407 : : /* else fall through to inspect the expression */
8408 : : }
8409 : : else
8410 : : {
8411 : : /*
8412 : : * We're deparsing a Plan tree so we don't have a CTE
8413 : : * list. But the only places we'd normally see a Var
8414 : : * directly referencing a CTE RTE are in CteScan or
8415 : : * WorkTableScan plan nodes. For those cases,
8416 : : * set_deparse_plan arranged for dpns->inner_plan to be
8417 : : * the plan node that emits the CTE or RecursiveUnion
8418 : : * result, and we can look at its tlist instead. As
8419 : : * above, this can fail if the CTE has been proven empty,
8420 : : * in which case fall back to "fN".
8421 : : */
8422 : : TargetEntry *tle;
8423 : : deparse_namespace save_dpns;
8424 : : const char *result;
8425 : :
8426 [ + + ]: 28 : if (!dpns->inner_plan)
8427 : : {
8428 : 4 : char *dummy_name = palloc(32);
8429 : :
8430 : : Assert(dpns->plan && IsA(dpns->plan, Result));
8431 : 4 : snprintf(dummy_name, 32, "f%d", fieldno);
8432 : 4 : return dummy_name;
8433 : : }
8434 : : Assert(dpns->plan && (IsA(dpns->plan, CteScan) ||
8435 : : IsA(dpns->plan, WorkTableScan)));
8436 : :
8437 : 24 : tle = get_tle_by_resno(dpns->inner_tlist, attnum);
8438 [ - + ]: 24 : if (!tle)
8439 [ # # ]: 0 : elog(ERROR, "bogus varattno for subquery var: %d",
8440 : : attnum);
8441 : : Assert(netlevelsup == 0);
8442 : 24 : push_child_plan(dpns, dpns->inner_plan, &save_dpns);
8443 : :
8444 : 24 : result = get_name_for_var_field((Var *) tle->expr, fieldno,
8445 : : levelsup, context);
8446 : :
8447 : 24 : pop_child_plan(dpns, &save_dpns);
8448 : 24 : return result;
8449 : : }
8450 : : }
8451 : 8 : break;
8452 : 0 : case RTE_GROUP:
8453 : :
8454 : : /*
8455 : : * We couldn't get here: any Vars that reference the RTE_GROUP RTE
8456 : : * should have been replaced with the underlying grouping
8457 : : * expressions.
8458 : : */
8459 : 0 : break;
8460 : : }
8461 : :
8462 : : /*
8463 : : * We now have an expression we can't expand any more, so see if
8464 : : * get_expr_result_tupdesc() can do anything with it.
8465 : : */
8466 : 24 : tupleDesc = get_expr_result_tupdesc(expr, false);
8467 : : /* Got the tupdesc, so we can extract the field name */
8468 : : Assert(fieldno >= 1 && fieldno <= tupleDesc->natts);
8469 : 24 : return NameStr(TupleDescAttr(tupleDesc, fieldno - 1)->attname);
8470 : : }
8471 : :
8472 : : /*
8473 : : * Try to find the referenced expression for a PARAM_EXEC Param that might
8474 : : * reference a parameter supplied by an upper NestLoop or SubPlan plan node.
8475 : : *
8476 : : * If successful, return the expression and set *dpns_p and *ancestor_cell_p
8477 : : * appropriately for calling push_ancestor_plan(). If no referent can be
8478 : : * found, return NULL.
8479 : : */
8480 : : static Node *
8481 : 5104 : find_param_referent(Param *param, deparse_context *context,
8482 : : deparse_namespace **dpns_p, ListCell **ancestor_cell_p)
8483 : : {
8484 : : /* Initialize output parameters to prevent compiler warnings */
8485 : 5104 : *dpns_p = NULL;
8486 : 5104 : *ancestor_cell_p = NULL;
8487 : :
8488 : : /*
8489 : : * If it's a PARAM_EXEC parameter, look for a matching NestLoopParam or
8490 : : * SubPlan argument. This will necessarily be in some ancestor of the
8491 : : * current expression's Plan node.
8492 : : */
8493 [ + + ]: 5104 : if (param->paramkind == PARAM_EXEC)
8494 : : {
8495 : : deparse_namespace *dpns;
8496 : : Plan *child_plan;
8497 : : ListCell *lc;
8498 : :
8499 : 4511 : dpns = (deparse_namespace *) linitial(context->namespaces);
8500 : 4511 : child_plan = dpns->plan;
8501 : :
8502 [ + + + + : 7914 : foreach(lc, dpns->ancestors)
+ + ]
8503 : : {
8504 : 6790 : Node *ancestor = (Node *) lfirst(lc);
8505 : : ListCell *lc2;
8506 : :
8507 : : /*
8508 : : * NestLoops transmit params to their inner child only.
8509 : : */
8510 [ + + ]: 6790 : if (IsA(ancestor, NestLoop) &&
8511 [ + + ]: 3165 : child_plan == innerPlan(ancestor))
8512 : : {
8513 : 3023 : NestLoop *nl = (NestLoop *) ancestor;
8514 : :
8515 [ + + + + : 3766 : foreach(lc2, nl->nestParams)
+ + ]
8516 : : {
8517 : 3637 : NestLoopParam *nlp = (NestLoopParam *) lfirst(lc2);
8518 : :
8519 [ + + ]: 3637 : if (nlp->paramno == param->paramid)
8520 : : {
8521 : : /* Found a match, so return it */
8522 : 2894 : *dpns_p = dpns;
8523 : 2894 : *ancestor_cell_p = lc;
8524 : 2894 : return (Node *) nlp->paramval;
8525 : : }
8526 : : }
8527 : : }
8528 : :
8529 : : /*
8530 : : * If ancestor is a SubPlan, check the arguments it provides.
8531 : : */
8532 [ + + ]: 3896 : if (IsA(ancestor, SubPlan))
8533 : 297 : {
8534 : 790 : SubPlan *subplan = (SubPlan *) ancestor;
8535 : : ListCell *lc3;
8536 : : ListCell *lc4;
8537 : :
8538 [ + + + + : 1021 : forboth(lc3, subplan->parParam, lc4, subplan->args)
+ + + + +
+ + - +
+ ]
8539 : : {
8540 : 724 : int paramid = lfirst_int(lc3);
8541 : 724 : Node *arg = (Node *) lfirst(lc4);
8542 : :
8543 [ + + ]: 724 : if (paramid == param->paramid)
8544 : : {
8545 : : /*
8546 : : * Found a match, so return it. But, since Vars in
8547 : : * the arg are to be evaluated in the surrounding
8548 : : * context, we have to point to the next ancestor item
8549 : : * that is *not* a SubPlan.
8550 : : */
8551 : : ListCell *rest;
8552 : :
8553 [ + - + - : 493 : for_each_cell(rest, dpns->ancestors,
+ - ]
8554 : : lnext(dpns->ancestors, lc))
8555 : : {
8556 : 493 : Node *ancestor2 = (Node *) lfirst(rest);
8557 : :
8558 [ + - ]: 493 : if (!IsA(ancestor2, SubPlan))
8559 : : {
8560 : 493 : *dpns_p = dpns;
8561 : 493 : *ancestor_cell_p = rest;
8562 : 493 : return arg;
8563 : : }
8564 : : }
8565 [ # # ]: 0 : elog(ERROR, "SubPlan cannot be outermost ancestor");
8566 : : }
8567 : : }
8568 : :
8569 : : /* SubPlan isn't a kind of Plan, so skip the rest */
8570 : 297 : continue;
8571 : : }
8572 : :
8573 : : /*
8574 : : * We need not consider the ancestor's initPlan list, since
8575 : : * initplans never have any parParams.
8576 : : */
8577 : :
8578 : : /* No luck, crawl up to next ancestor */
8579 : 3106 : child_plan = (Plan *) ancestor;
8580 : : }
8581 : : }
8582 : :
8583 : : /* No referent found */
8584 : 1717 : return NULL;
8585 : : }
8586 : :
8587 : : /*
8588 : : * Try to find a subplan/initplan that emits the value for a PARAM_EXEC Param.
8589 : : *
8590 : : * If successful, return the generating subplan/initplan and set *column_p
8591 : : * to the subplan's 0-based output column number.
8592 : : * Otherwise, return NULL.
8593 : : */
8594 : : static SubPlan *
8595 : 1717 : find_param_generator(Param *param, deparse_context *context, int *column_p)
8596 : : {
8597 : : /* Initialize output parameter to prevent compiler warnings */
8598 : 1717 : *column_p = 0;
8599 : :
8600 : : /*
8601 : : * If it's a PARAM_EXEC parameter, search the current plan node as well as
8602 : : * ancestor nodes looking for a subplan or initplan that emits the value
8603 : : * for the Param. It could appear in the setParams of an initplan or
8604 : : * MULTIEXPR_SUBLINK subplan, or in the paramIds of an ancestral SubPlan.
8605 : : */
8606 [ + + ]: 1717 : if (param->paramkind == PARAM_EXEC)
8607 : : {
8608 : : SubPlan *result;
8609 : : deparse_namespace *dpns;
8610 : : ListCell *lc;
8611 : :
8612 : 1124 : dpns = (deparse_namespace *) linitial(context->namespaces);
8613 : :
8614 : : /* First check the innermost plan node's initplans */
8615 : 1124 : result = find_param_generator_initplan(param, dpns->plan, column_p);
8616 [ + + ]: 1124 : if (result)
8617 : 297 : return result;
8618 : :
8619 : : /*
8620 : : * The plan's targetlist might contain MULTIEXPR_SUBLINK SubPlans,
8621 : : * which can be referenced by Params elsewhere in the targetlist.
8622 : : * (Such Params should always be in the same targetlist, so there's no
8623 : : * need to do this work at upper plan nodes.)
8624 : : */
8625 [ + + + + : 4151 : foreach_node(TargetEntry, tle, dpns->plan->targetlist)
+ + ]
8626 : : {
8627 [ + - + + ]: 2565 : if (tle->expr && IsA(tle->expr, SubPlan))
8628 : : {
8629 : 66 : SubPlan *subplan = (SubPlan *) tle->expr;
8630 : :
8631 [ + + ]: 66 : if (subplan->subLinkType == MULTIEXPR_SUBLINK)
8632 : : {
8633 [ + - + - : 51 : foreach_int(paramid, subplan->setParam)
+ - ]
8634 : : {
8635 [ + + ]: 51 : if (paramid == param->paramid)
8636 : : {
8637 : : /* Found a match, so return it. */
8638 : 34 : *column_p = foreach_current_index(paramid);
8639 : 34 : return subplan;
8640 : : }
8641 : : }
8642 : : }
8643 : : }
8644 : : }
8645 : :
8646 : : /* No luck, so check the ancestor nodes */
8647 [ + - + - : 1028 : foreach(lc, dpns->ancestors)
+ - ]
8648 : : {
8649 : 1028 : Node *ancestor = (Node *) lfirst(lc);
8650 : :
8651 : : /*
8652 : : * If ancestor is a SubPlan, check the paramIds it provides.
8653 : : */
8654 [ + + ]: 1028 : if (IsA(ancestor, SubPlan))
8655 : 0 : {
8656 : 201 : SubPlan *subplan = (SubPlan *) ancestor;
8657 : :
8658 [ + - + - : 226 : foreach_int(paramid, subplan->paramIds)
+ - ]
8659 : : {
8660 [ + + ]: 226 : if (paramid == param->paramid)
8661 : : {
8662 : : /* Found a match, so return it. */
8663 : 201 : *column_p = foreach_current_index(paramid);
8664 : 201 : return subplan;
8665 : : }
8666 : : }
8667 : :
8668 : : /* SubPlan isn't a kind of Plan, so skip the rest */
8669 : 0 : continue;
8670 : : }
8671 : :
8672 : : /*
8673 : : * Otherwise, it's some kind of Plan node, so check its initplans.
8674 : : */
8675 : 827 : result = find_param_generator_initplan(param, (Plan *) ancestor,
8676 : : column_p);
8677 [ + + ]: 827 : if (result)
8678 : 592 : return result;
8679 : :
8680 : : /* No luck, crawl up to next ancestor */
8681 : : }
8682 : : }
8683 : :
8684 : : /* No generator found */
8685 : 593 : return NULL;
8686 : : }
8687 : :
8688 : : /*
8689 : : * Subroutine for find_param_generator: search one Plan node's initplans
8690 : : */
8691 : : static SubPlan *
8692 : 1951 : find_param_generator_initplan(Param *param, Plan *plan, int *column_p)
8693 : : {
8694 [ + + + - : 3105 : foreach_node(SubPlan, subplan, plan->initPlan)
+ + ]
8695 : : {
8696 [ + - + + : 1169 : foreach_int(paramid, subplan->setParam)
+ + ]
8697 : : {
8698 [ + + ]: 985 : if (paramid == param->paramid)
8699 : : {
8700 : : /* Found a match, so return it. */
8701 : 889 : *column_p = foreach_current_index(paramid);
8702 : 889 : return subplan;
8703 : : }
8704 : : }
8705 : : }
8706 : 1062 : return NULL;
8707 : : }
8708 : :
8709 : : /*
8710 : : * Display a Param appropriately.
8711 : : */
8712 : : static void
8713 : 5092 : get_parameter(Param *param, deparse_context *context)
8714 : : {
8715 : : Node *expr;
8716 : : deparse_namespace *dpns;
8717 : : ListCell *ancestor_cell;
8718 : : SubPlan *subplan;
8719 : : int column;
8720 : :
8721 : : /*
8722 : : * If it's a PARAM_EXEC parameter, try to locate the expression from which
8723 : : * the parameter was computed. This stanza handles only cases in which
8724 : : * the Param represents an input to the subplan we are currently in.
8725 : : */
8726 : 5092 : expr = find_param_referent(param, context, &dpns, &ancestor_cell);
8727 [ + + ]: 5092 : if (expr)
8728 : : {
8729 : : /* Found a match, so print it */
8730 : : deparse_namespace save_dpns;
8731 : : bool save_varprefix;
8732 : : bool need_paren;
8733 : :
8734 : : /* Switch attention to the ancestor plan node */
8735 : 3375 : push_ancestor_plan(dpns, ancestor_cell, &save_dpns);
8736 : :
8737 : : /*
8738 : : * Force prefixing of Vars, since they won't belong to the relation
8739 : : * being scanned in the original plan node.
8740 : : */
8741 : 3375 : save_varprefix = context->varprefix;
8742 : 3375 : context->varprefix = true;
8743 : :
8744 : : /*
8745 : : * A Param's expansion is typically a Var, Aggref, GroupingFunc, or
8746 : : * upper-level Param, which wouldn't need extra parentheses.
8747 : : * Otherwise, insert parens to ensure the expression looks atomic.
8748 : : */
8749 [ + + ]: 3399 : need_paren = !(IsA(expr, Var) ||
8750 [ + + ]: 24 : IsA(expr, Aggref) ||
8751 [ + + ]: 20 : IsA(expr, GroupingFunc) ||
8752 [ - + ]: 16 : IsA(expr, Param));
8753 [ - + ]: 3375 : if (need_paren)
8754 : 0 : appendStringInfoChar(context->buf, '(');
8755 : :
8756 : 3375 : get_rule_expr(expr, context, false);
8757 : :
8758 [ - + ]: 3375 : if (need_paren)
8759 : 0 : appendStringInfoChar(context->buf, ')');
8760 : :
8761 : 3375 : context->varprefix = save_varprefix;
8762 : :
8763 : 3375 : pop_ancestor_plan(dpns, &save_dpns);
8764 : :
8765 : 3375 : return;
8766 : : }
8767 : :
8768 : : /*
8769 : : * Alternatively, maybe it's a subplan output, which we print as a
8770 : : * reference to the subplan. (We could drill down into the subplan and
8771 : : * print the relevant targetlist expression, but that has been deemed too
8772 : : * confusing since it would violate normal SQL scope rules. Also, we're
8773 : : * relying on this reference to show that the testexpr containing the
8774 : : * Param has anything to do with that subplan at all.)
8775 : : */
8776 : 1717 : subplan = find_param_generator(param, context, &column);
8777 [ + + ]: 1717 : if (subplan)
8778 : : {
8779 : : const char *nameprefix;
8780 : :
8781 [ + + ]: 1124 : if (subplan->isInitPlan)
8782 : 889 : nameprefix = "InitPlan ";
8783 : : else
8784 : 235 : nameprefix = "SubPlan ";
8785 : :
8786 : 1124 : appendStringInfo(context->buf, "(%s%s%s).col%d",
8787 [ + + ]: 1124 : subplan->useHashTable ? "hashed " : "",
8788 : : nameprefix,
8789 : : subplan->plan_name, column + 1);
8790 : :
8791 : 1124 : return;
8792 : : }
8793 : :
8794 : : /*
8795 : : * If it's an external parameter, see if the outermost namespace provides
8796 : : * function argument names.
8797 : : */
8798 [ + - + - ]: 593 : if (param->paramkind == PARAM_EXTERN && context->namespaces != NIL)
8799 : : {
8800 : 593 : dpns = llast(context->namespaces);
8801 [ + + ]: 593 : if (dpns->argnames &&
8802 [ + - ]: 45 : param->paramid > 0 &&
8803 [ + - ]: 45 : param->paramid <= dpns->numargs)
8804 : : {
8805 : 45 : char *argname = dpns->argnames[param->paramid - 1];
8806 : :
8807 [ + - ]: 45 : if (argname)
8808 : : {
8809 : 45 : bool should_qualify = false;
8810 : : ListCell *lc;
8811 : :
8812 : : /*
8813 : : * Qualify the parameter name if there are any other deparse
8814 : : * namespaces with range tables. This avoids qualifying in
8815 : : * trivial cases like "RETURN a + b", but makes it safe in all
8816 : : * other cases.
8817 : : */
8818 [ + - + + : 103 : foreach(lc, context->namespaces)
+ + ]
8819 : : {
8820 : 78 : deparse_namespace *depns = lfirst(lc);
8821 : :
8822 [ + + ]: 78 : if (depns->rtable_names != NIL)
8823 : : {
8824 : 20 : should_qualify = true;
8825 : 20 : break;
8826 : : }
8827 : : }
8828 [ + + ]: 45 : if (should_qualify)
8829 : : {
8830 : 20 : appendStringInfoString(context->buf, quote_identifier(dpns->funcname));
8831 : 20 : appendStringInfoChar(context->buf, '.');
8832 : : }
8833 : :
8834 : 45 : appendStringInfoString(context->buf, quote_identifier(argname));
8835 : 45 : return;
8836 : : }
8837 : : }
8838 : : }
8839 : :
8840 : : /*
8841 : : * Not PARAM_EXEC, or couldn't find referent: just print $N.
8842 : : *
8843 : : * It's a bug if we get here for anything except PARAM_EXTERN Params, but
8844 : : * in production builds printing $N seems more useful than failing.
8845 : : */
8846 : : Assert(param->paramkind == PARAM_EXTERN);
8847 : :
8848 : 548 : appendStringInfo(context->buf, "$%d", param->paramid);
8849 : : }
8850 : :
8851 : : /*
8852 : : * get_simple_binary_op_name
8853 : : *
8854 : : * helper function for isSimpleNode
8855 : : * will return single char binary operator name, or NULL if it's not
8856 : : */
8857 : : static const char *
8858 : 100 : get_simple_binary_op_name(OpExpr *expr)
8859 : : {
8860 : 100 : List *args = expr->args;
8861 : :
8862 [ + - ]: 100 : if (list_length(args) == 2)
8863 : : {
8864 : : /* binary operator */
8865 : 100 : Node *arg1 = (Node *) linitial(args);
8866 : 100 : Node *arg2 = (Node *) lsecond(args);
8867 : : const char *op;
8868 : :
8869 : 100 : op = generate_operator_name(expr->opno, exprType(arg1), exprType(arg2));
8870 [ + - ]: 100 : if (strlen(op) == 1)
8871 : 100 : return op;
8872 : : }
8873 : 0 : return NULL;
8874 : : }
8875 : :
8876 : :
8877 : : /*
8878 : : * isSimpleNode - check if given node is simple (doesn't need parenthesizing)
8879 : : *
8880 : : * true : simple in the context of parent node's type
8881 : : * false : not simple
8882 : : */
8883 : : static bool
8884 : 3809 : isSimpleNode(Node *node, Node *parentNode, int prettyFlags)
8885 : : {
8886 [ - + ]: 3809 : if (!node)
8887 : 0 : return false;
8888 : :
8889 [ + + - + : 3809 : switch (nodeTag(node))
- + + + -
- - + + +
+ + ]
8890 : : {
8891 : 3186 : case T_Var:
8892 : : case T_Const:
8893 : : case T_Param:
8894 : : case T_CoerceToDomainValue:
8895 : : case T_SetToDefault:
8896 : : case T_CurrentOfExpr:
8897 : : /* single words: always simple */
8898 : 3186 : return true;
8899 : :
8900 : 335 : case T_SubscriptingRef:
8901 : : case T_ArrayExpr:
8902 : : case T_RowExpr:
8903 : : case T_CoalesceExpr:
8904 : : case T_MinMaxExpr:
8905 : : case T_SQLValueFunction:
8906 : : case T_XmlExpr:
8907 : : case T_NextValueExpr:
8908 : : case T_NullIfExpr:
8909 : : case T_Aggref:
8910 : : case T_GroupingFunc:
8911 : : case T_WindowFunc:
8912 : : case T_MergeSupportFunc:
8913 : : case T_FuncExpr:
8914 : : case T_JsonConstructorExpr:
8915 : : case T_JsonExpr:
8916 : : /* function-like: name(..) or name[..] */
8917 : 335 : return true;
8918 : :
8919 : : /* CASE keywords act as parentheses */
8920 : 0 : case T_CaseExpr:
8921 : 0 : return true;
8922 : :
8923 : 48 : case T_FieldSelect:
8924 : :
8925 : : /*
8926 : : * appears simple since . has top precedence, unless parent is
8927 : : * T_FieldSelect itself!
8928 : : */
8929 : 48 : return !IsA(parentNode, FieldSelect);
8930 : :
8931 : 0 : case T_FieldStore:
8932 : :
8933 : : /*
8934 : : * treat like FieldSelect (probably doesn't matter)
8935 : : */
8936 : 0 : return !IsA(parentNode, FieldStore);
8937 : :
8938 : 12 : case T_CoerceToDomain:
8939 : : /* maybe simple, check args */
8940 : 12 : return isSimpleNode((Node *) ((CoerceToDomain *) node)->arg,
8941 : : node, prettyFlags);
8942 : 12 : case T_RelabelType:
8943 : 12 : return isSimpleNode((Node *) ((RelabelType *) node)->arg,
8944 : : node, prettyFlags);
8945 : 16 : case T_CoerceViaIO:
8946 : 16 : return isSimpleNode((Node *) ((CoerceViaIO *) node)->arg,
8947 : : node, prettyFlags);
8948 : 0 : case T_ArrayCoerceExpr:
8949 : 0 : return isSimpleNode((Node *) ((ArrayCoerceExpr *) node)->arg,
8950 : : node, prettyFlags);
8951 : 0 : case T_ConvertRowtypeExpr:
8952 : 0 : return isSimpleNode((Node *) ((ConvertRowtypeExpr *) node)->arg,
8953 : : node, prettyFlags);
8954 : 0 : case T_ReturningExpr:
8955 : 0 : return isSimpleNode((Node *) ((ReturningExpr *) node)->retexpr,
8956 : : node, prettyFlags);
8957 : :
8958 : 168 : case T_OpExpr:
8959 : : {
8960 : : /* depends on parent node type; needs further checking */
8961 [ + - + + ]: 168 : if (prettyFlags & PRETTYFLAG_PAREN && IsA(parentNode, OpExpr))
8962 : : {
8963 : : const char *op;
8964 : : const char *parentOp;
8965 : : bool is_lopriop;
8966 : : bool is_hipriop;
8967 : : bool is_lopriparent;
8968 : : bool is_hipriparent;
8969 : :
8970 : 52 : op = get_simple_binary_op_name((OpExpr *) node);
8971 [ - + ]: 52 : if (!op)
8972 : 0 : return false;
8973 : :
8974 : : /* We know only the basic operators + - and * / % */
8975 : 52 : is_lopriop = (strchr("+-", *op) != NULL);
8976 : 52 : is_hipriop = (strchr("*/%", *op) != NULL);
8977 [ + + + + ]: 52 : if (!(is_lopriop || is_hipriop))
8978 : 4 : return false;
8979 : :
8980 : 48 : parentOp = get_simple_binary_op_name((OpExpr *) parentNode);
8981 [ - + ]: 48 : if (!parentOp)
8982 : 0 : return false;
8983 : :
8984 : 48 : is_lopriparent = (strchr("+-", *parentOp) != NULL);
8985 : 48 : is_hipriparent = (strchr("*/%", *parentOp) != NULL);
8986 [ + + - + ]: 48 : if (!(is_lopriparent || is_hipriparent))
8987 : 0 : return false;
8988 : :
8989 [ + + + - ]: 48 : if (is_hipriop && is_lopriparent)
8990 : 8 : return true; /* op binds tighter than parent */
8991 : :
8992 [ + - + + ]: 40 : if (is_lopriop && is_hipriparent)
8993 : 32 : return false;
8994 : :
8995 : : /*
8996 : : * Operators are same priority --- can skip parens only if
8997 : : * we have (a - b) - c, not a - (b - c).
8998 : : */
8999 [ + + ]: 8 : if (node == (Node *) linitial(((OpExpr *) parentNode)->args))
9000 : 4 : return true;
9001 : :
9002 : 4 : return false;
9003 : : }
9004 : : /* else do the same stuff as for T_SubLink et al. */
9005 : : }
9006 : : pg_fallthrough;
9007 : :
9008 : : case T_SubLink:
9009 : : case T_NullTest:
9010 : : case T_BooleanTest:
9011 : : case T_DistinctExpr:
9012 : : case T_JsonIsPredicate:
9013 [ + + + ]: 128 : switch (nodeTag(parentNode))
9014 : : {
9015 : 24 : case T_FuncExpr:
9016 : : {
9017 : : /* special handling for casts and COERCE_SQL_SYNTAX */
9018 : 24 : CoercionForm type = ((FuncExpr *) parentNode)->funcformat;
9019 : :
9020 [ + + + + ]: 24 : if (type == COERCE_EXPLICIT_CAST ||
9021 [ + - ]: 4 : type == COERCE_IMPLICIT_CAST ||
9022 : : type == COERCE_SQL_SYNTAX)
9023 : 24 : return false;
9024 : 0 : return true; /* own parentheses */
9025 : : }
9026 : 84 : case T_BoolExpr: /* lower precedence */
9027 : : case T_SubscriptingRef: /* other separators */
9028 : : case T_ArrayExpr: /* other separators */
9029 : : case T_RowExpr: /* other separators */
9030 : : case T_CoalesceExpr: /* own parentheses */
9031 : : case T_MinMaxExpr: /* own parentheses */
9032 : : case T_XmlExpr: /* own parentheses */
9033 : : case T_NullIfExpr: /* other separators */
9034 : : case T_Aggref: /* own parentheses */
9035 : : case T_GroupingFunc: /* own parentheses */
9036 : : case T_WindowFunc: /* own parentheses */
9037 : : case T_CaseExpr: /* other separators */
9038 : 84 : return true;
9039 : 20 : default:
9040 : 20 : return false;
9041 : : }
9042 : :
9043 : 12 : case T_BoolExpr:
9044 [ + - - - ]: 12 : switch (nodeTag(parentNode))
9045 : : {
9046 : 12 : case T_BoolExpr:
9047 [ + - ]: 12 : if (prettyFlags & PRETTYFLAG_PAREN)
9048 : : {
9049 : : BoolExprType type;
9050 : : BoolExprType parentType;
9051 : :
9052 : 12 : type = ((BoolExpr *) node)->boolop;
9053 : 12 : parentType = ((BoolExpr *) parentNode)->boolop;
9054 [ + + - ]: 12 : switch (type)
9055 : : {
9056 : 8 : case NOT_EXPR:
9057 : : case AND_EXPR:
9058 [ + + + - ]: 8 : if (parentType == AND_EXPR || parentType == OR_EXPR)
9059 : 8 : return true;
9060 : 0 : break;
9061 : 4 : case OR_EXPR:
9062 [ - + ]: 4 : if (parentType == OR_EXPR)
9063 : 0 : return true;
9064 : 4 : break;
9065 : : }
9066 : : }
9067 : 4 : return false;
9068 : 0 : case T_FuncExpr:
9069 : : {
9070 : : /* special handling for casts and COERCE_SQL_SYNTAX */
9071 : 0 : CoercionForm type = ((FuncExpr *) parentNode)->funcformat;
9072 : :
9073 [ # # # # ]: 0 : if (type == COERCE_EXPLICIT_CAST ||
9074 [ # # ]: 0 : type == COERCE_IMPLICIT_CAST ||
9075 : : type == COERCE_SQL_SYNTAX)
9076 : 0 : return false;
9077 : 0 : return true; /* own parentheses */
9078 : : }
9079 : 0 : case T_SubscriptingRef: /* other separators */
9080 : : case T_ArrayExpr: /* other separators */
9081 : : case T_RowExpr: /* other separators */
9082 : : case T_CoalesceExpr: /* own parentheses */
9083 : : case T_MinMaxExpr: /* own parentheses */
9084 : : case T_XmlExpr: /* own parentheses */
9085 : : case T_NullIfExpr: /* other separators */
9086 : : case T_Aggref: /* own parentheses */
9087 : : case T_GroupingFunc: /* own parentheses */
9088 : : case T_WindowFunc: /* own parentheses */
9089 : : case T_CaseExpr: /* other separators */
9090 : : case T_JsonExpr: /* own parentheses */
9091 : 0 : return true;
9092 : 0 : default:
9093 : 0 : return false;
9094 : : }
9095 : :
9096 : 4 : case T_JsonValueExpr:
9097 : : /* maybe simple, check args */
9098 : 4 : return isSimpleNode((Node *) ((JsonValueExpr *) node)->raw_expr,
9099 : : node, prettyFlags);
9100 : :
9101 : 4 : default:
9102 : 4 : break;
9103 : : }
9104 : : /* those we don't know: in dubio complexo */
9105 : 4 : return false;
9106 : : }
9107 : :
9108 : :
9109 : : /*
9110 : : * appendContextKeyword - append a keyword to buffer
9111 : : *
9112 : : * If prettyPrint is enabled, perform a line break, and adjust indentation.
9113 : : * Otherwise, just append the keyword.
9114 : : */
9115 : : static void
9116 : 19582 : appendContextKeyword(deparse_context *context, const char *str,
9117 : : int indentBefore, int indentAfter, int indentPlus)
9118 : : {
9119 : 19582 : StringInfo buf = context->buf;
9120 : :
9121 [ + + ]: 19582 : if (PRETTY_INDENT(context))
9122 : : {
9123 : : int indentAmount;
9124 : :
9125 : 18625 : context->indentLevel += indentBefore;
9126 : :
9127 : : /* remove any trailing spaces currently in the buffer ... */
9128 : 18625 : removeStringInfoSpaces(buf);
9129 : : /* ... then add a newline and some spaces */
9130 : 18625 : appendStringInfoChar(buf, '\n');
9131 : :
9132 [ + - ]: 18625 : if (context->indentLevel < PRETTYINDENT_LIMIT)
9133 : 18625 : indentAmount = Max(context->indentLevel, 0) + indentPlus;
9134 : : else
9135 : : {
9136 : : /*
9137 : : * If we're indented more than PRETTYINDENT_LIMIT characters, try
9138 : : * to conserve horizontal space by reducing the per-level
9139 : : * indentation. For best results the scale factor here should
9140 : : * divide all the indent amounts that get added to indentLevel
9141 : : * (PRETTYINDENT_STD, etc). It's important that the indentation
9142 : : * not grow unboundedly, else deeply-nested trees use O(N^2)
9143 : : * whitespace; so we also wrap modulo PRETTYINDENT_LIMIT.
9144 : : */
9145 : 0 : indentAmount = PRETTYINDENT_LIMIT +
9146 : 0 : (context->indentLevel - PRETTYINDENT_LIMIT) /
9147 : : (PRETTYINDENT_STD / 2);
9148 : 0 : indentAmount %= PRETTYINDENT_LIMIT;
9149 : : /* scale/wrap logic affects indentLevel, but not indentPlus */
9150 : 0 : indentAmount += indentPlus;
9151 : : }
9152 : 18625 : appendStringInfoSpaces(buf, indentAmount);
9153 : :
9154 : 18625 : appendStringInfoString(buf, str);
9155 : :
9156 : 18625 : context->indentLevel += indentAfter;
9157 [ - + ]: 18625 : if (context->indentLevel < 0)
9158 : 0 : context->indentLevel = 0;
9159 : : }
9160 : : else
9161 : 957 : appendStringInfoString(buf, str);
9162 : 19582 : }
9163 : :
9164 : : /*
9165 : : * removeStringInfoSpaces - delete trailing spaces from a buffer.
9166 : : *
9167 : : * Possibly this should move to stringinfo.c at some point.
9168 : : */
9169 : : static void
9170 : 19000 : removeStringInfoSpaces(StringInfo str)
9171 : : {
9172 [ + + + + ]: 29637 : while (str->len > 0 && str->data[str->len - 1] == ' ')
9173 : 10637 : str->data[--(str->len)] = '\0';
9174 : 19000 : }
9175 : :
9176 : :
9177 : : /*
9178 : : * get_rule_expr_paren - deparse expr using get_rule_expr,
9179 : : * embracing the string with parentheses if necessary for prettyPrint.
9180 : : *
9181 : : * Never embrace if prettyFlags=0, because it's done in the calling node.
9182 : : *
9183 : : * Any node that does *not* embrace its argument node by sql syntax (with
9184 : : * parentheses, non-operator keywords like CASE/WHEN/ON, or comma etc) should
9185 : : * use get_rule_expr_paren instead of get_rule_expr so parentheses can be
9186 : : * added.
9187 : : */
9188 : : static void
9189 : 111197 : get_rule_expr_paren(Node *node, deparse_context *context,
9190 : : bool showimplicit, Node *parentNode)
9191 : : {
9192 : : bool need_paren;
9193 : :
9194 [ + + ]: 114962 : need_paren = PRETTY_PAREN(context) &&
9195 [ + + ]: 3765 : !isSimpleNode(node, parentNode, context->prettyFlags);
9196 : :
9197 [ + + ]: 111197 : if (need_paren)
9198 : 92 : appendStringInfoChar(context->buf, '(');
9199 : :
9200 : 111197 : get_rule_expr(node, context, showimplicit);
9201 : :
9202 [ + + ]: 111197 : if (need_paren)
9203 : 92 : appendStringInfoChar(context->buf, ')');
9204 : 111197 : }
9205 : :
9206 : : static void
9207 : 80 : get_json_behavior(JsonBehavior *behavior, deparse_context *context,
9208 : : const char *on)
9209 : : {
9210 : : /*
9211 : : * The order of array elements must correspond to the order of
9212 : : * JsonBehaviorType members.
9213 : : */
9214 : 80 : const char *behavior_names[] =
9215 : : {
9216 : : " NULL",
9217 : : " ERROR",
9218 : : " EMPTY",
9219 : : " TRUE",
9220 : : " FALSE",
9221 : : " UNKNOWN",
9222 : : " EMPTY ARRAY",
9223 : : " EMPTY OBJECT",
9224 : : " DEFAULT "
9225 : : };
9226 : :
9227 [ + - - + ]: 80 : if ((int) behavior->btype < 0 || behavior->btype >= lengthof(behavior_names))
9228 [ # # ]: 0 : elog(ERROR, "invalid json behavior type: %d", behavior->btype);
9229 : :
9230 : 80 : appendStringInfoString(context->buf, behavior_names[behavior->btype]);
9231 : :
9232 [ + + ]: 80 : if (behavior->btype == JSON_BEHAVIOR_DEFAULT)
9233 : 12 : get_rule_expr(behavior->expr, context, false);
9234 : :
9235 : 80 : appendStringInfo(context->buf, " ON %s", on);
9236 : 80 : }
9237 : :
9238 : : /*
9239 : : * get_json_expr_options
9240 : : *
9241 : : * Parse back common options for JSON_QUERY, JSON_VALUE, JSON_EXISTS and
9242 : : * JSON_TABLE columns.
9243 : : */
9244 : : static void
9245 : 428 : get_json_expr_options(JsonExpr *jsexpr, deparse_context *context,
9246 : : JsonBehaviorType default_behavior)
9247 : : {
9248 [ + + ]: 428 : if (jsexpr->op == JSON_QUERY_OP)
9249 : : {
9250 [ + + ]: 192 : if (jsexpr->wrapper == JSW_CONDITIONAL)
9251 : 8 : appendStringInfoString(context->buf, " WITH CONDITIONAL WRAPPER");
9252 [ + + ]: 184 : else if (jsexpr->wrapper == JSW_UNCONDITIONAL)
9253 : 24 : appendStringInfoString(context->buf, " WITH UNCONDITIONAL WRAPPER");
9254 : : /* The default */
9255 [ + + + - ]: 160 : else if (jsexpr->wrapper == JSW_NONE || jsexpr->wrapper == JSW_UNSPEC)
9256 : 160 : appendStringInfoString(context->buf, " WITHOUT WRAPPER");
9257 : :
9258 [ + + ]: 192 : if (jsexpr->omit_quotes)
9259 : 36 : appendStringInfoString(context->buf, " OMIT QUOTES");
9260 : : /* The default */
9261 : : else
9262 : 156 : appendStringInfoString(context->buf, " KEEP QUOTES");
9263 : : }
9264 : :
9265 [ + + + + ]: 428 : if (jsexpr->on_empty && jsexpr->on_empty->btype != default_behavior)
9266 : 24 : get_json_behavior(jsexpr->on_empty, context, "EMPTY");
9267 : :
9268 [ + - + + ]: 428 : if (jsexpr->on_error && jsexpr->on_error->btype != default_behavior)
9269 : 48 : get_json_behavior(jsexpr->on_error, context, "ERROR");
9270 : 428 : }
9271 : :
9272 : : /* ----------
9273 : : * get_rule_expr - Parse back an expression
9274 : : *
9275 : : * Note: showimplicit determines whether we display any implicit cast that
9276 : : * is present at the top of the expression tree. It is a passed argument,
9277 : : * not a field of the context struct, because we change the value as we
9278 : : * recurse down into the expression. In general we suppress implicit casts
9279 : : * when the result type is known with certainty (eg, the arguments of an
9280 : : * OR must be boolean). We display implicit casts for arguments of functions
9281 : : * and operators, since this is needed to be certain that the same function
9282 : : * or operator will be chosen when the expression is re-parsed.
9283 : : * ----------
9284 : : */
9285 : : static void
9286 : 243410 : get_rule_expr(Node *node, deparse_context *context,
9287 : : bool showimplicit)
9288 : : {
9289 : 243410 : StringInfo buf = context->buf;
9290 : :
9291 [ + + ]: 243410 : if (node == NULL)
9292 : 72 : return;
9293 : :
9294 : : /* Guard against excessively long or deeply-nested queries */
9295 [ - + ]: 243338 : CHECK_FOR_INTERRUPTS();
9296 : 243338 : check_stack_depth();
9297 : :
9298 : : /*
9299 : : * Each level of get_rule_expr must emit an indivisible term
9300 : : * (parenthesized if necessary) to ensure result is reparsed into the same
9301 : : * expression tree. The only exception is that when the input is a List,
9302 : : * we emit the component items comma-separated with no surrounding
9303 : : * decoration; this is convenient for most callers.
9304 : : */
9305 [ + + + + : 243338 : switch (nodeTag(node))
+ + + + +
+ + + + +
+ + + - +
+ + + + +
+ + - + +
+ + + + +
+ + + + +
+ - + + +
+ + + + +
+ - ]
9306 : : {
9307 : 118686 : case T_Var:
9308 : 118686 : (void) get_variable((Var *) node, 0, false, context);
9309 : 118686 : break;
9310 : :
9311 : 42247 : case T_Const:
9312 : 42247 : get_const_expr((Const *) node, context, 0);
9313 : 42247 : break;
9314 : :
9315 : 5092 : case T_Param:
9316 : 5092 : get_parameter((Param *) node, context);
9317 : 5092 : break;
9318 : :
9319 : 2640 : case T_Aggref:
9320 : 2640 : get_agg_expr((Aggref *) node, context, (Aggref *) node);
9321 : 2640 : break;
9322 : :
9323 : 74 : case T_GroupingFunc:
9324 : : {
9325 : 74 : GroupingFunc *gexpr = (GroupingFunc *) node;
9326 : :
9327 : 74 : appendStringInfoString(buf, "GROUPING(");
9328 : 74 : get_rule_expr((Node *) gexpr->args, context, true);
9329 : 74 : appendStringInfoChar(buf, ')');
9330 : : }
9331 : 74 : break;
9332 : :
9333 : 254 : case T_WindowFunc:
9334 : 254 : get_windowfunc_expr((WindowFunc *) node, context);
9335 : 254 : break;
9336 : :
9337 : 4 : case T_MergeSupportFunc:
9338 : 4 : appendStringInfoString(buf, "MERGE_ACTION()");
9339 : 4 : break;
9340 : :
9341 : 236 : case T_SubscriptingRef:
9342 : : {
9343 : 236 : SubscriptingRef *sbsref = (SubscriptingRef *) node;
9344 : : bool need_parens;
9345 : :
9346 : : /*
9347 : : * If the argument is a CaseTestExpr, we must be inside a
9348 : : * FieldStore, ie, we are assigning to an element of an array
9349 : : * within a composite column. Since we already punted on
9350 : : * displaying the FieldStore's target information, just punt
9351 : : * here too, and display only the assignment source
9352 : : * expression.
9353 : : */
9354 [ - + ]: 236 : if (IsA(sbsref->refexpr, CaseTestExpr))
9355 : : {
9356 : : Assert(sbsref->refassgnexpr);
9357 : 0 : get_rule_expr((Node *) sbsref->refassgnexpr,
9358 : : context, showimplicit);
9359 : 0 : break;
9360 : : }
9361 : :
9362 : : /*
9363 : : * Parenthesize the argument unless it's a simple Var or a
9364 : : * FieldSelect. (In particular, if it's another
9365 : : * SubscriptingRef, we *must* parenthesize to avoid
9366 : : * confusion.)
9367 : : */
9368 [ + + ]: 366 : need_parens = !IsA(sbsref->refexpr, Var) &&
9369 [ + + ]: 130 : !IsA(sbsref->refexpr, FieldSelect);
9370 [ + + ]: 236 : if (need_parens)
9371 : 60 : appendStringInfoChar(buf, '(');
9372 : 236 : get_rule_expr((Node *) sbsref->refexpr, context, showimplicit);
9373 [ + + ]: 236 : if (need_parens)
9374 : 60 : appendStringInfoChar(buf, ')');
9375 : :
9376 : : /*
9377 : : * If there's a refassgnexpr, we want to print the node in the
9378 : : * format "container[subscripts] := refassgnexpr". This is
9379 : : * not legal SQL, so decompilation of INSERT or UPDATE
9380 : : * statements should always use processIndirection as part of
9381 : : * the statement-level syntax. We should only see this when
9382 : : * EXPLAIN tries to print the targetlist of a plan resulting
9383 : : * from such a statement.
9384 : : */
9385 [ + + ]: 236 : if (sbsref->refassgnexpr)
9386 : : {
9387 : : Node *refassgnexpr;
9388 : :
9389 : : /*
9390 : : * Use processIndirection to print this node's subscripts
9391 : : * as well as any additional field selections or
9392 : : * subscripting in immediate descendants. It returns the
9393 : : * RHS expr that is actually being "assigned".
9394 : : */
9395 : 8 : refassgnexpr = processIndirection(node, context);
9396 : 8 : appendStringInfoString(buf, " := ");
9397 : 8 : get_rule_expr(refassgnexpr, context, showimplicit);
9398 : : }
9399 : : else
9400 : : {
9401 : : /* Just an ordinary container fetch, so print subscripts */
9402 : 228 : printSubscripts(sbsref, context);
9403 : : }
9404 : : }
9405 : 236 : break;
9406 : :
9407 : 8062 : case T_FuncExpr:
9408 : 8062 : get_func_expr((FuncExpr *) node, context, showimplicit);
9409 : 8062 : break;
9410 : :
9411 : 20 : case T_NamedArgExpr:
9412 : : {
9413 : 20 : NamedArgExpr *na = (NamedArgExpr *) node;
9414 : :
9415 : 20 : appendStringInfo(buf, "%s => ", quote_identifier(na->name));
9416 : 20 : get_rule_expr((Node *) na->arg, context, showimplicit);
9417 : : }
9418 : 20 : break;
9419 : :
9420 : 41659 : case T_OpExpr:
9421 : 41659 : get_oper_expr((OpExpr *) node, context);
9422 : 41659 : break;
9423 : :
9424 : 16 : case T_DistinctExpr:
9425 : : {
9426 : 16 : DistinctExpr *expr = (DistinctExpr *) node;
9427 : 16 : List *args = expr->args;
9428 : 16 : Node *arg1 = (Node *) linitial(args);
9429 : 16 : Node *arg2 = (Node *) lsecond(args);
9430 : :
9431 [ + + ]: 16 : if (!PRETTY_PAREN(context))
9432 : 12 : appendStringInfoChar(buf, '(');
9433 : 16 : get_rule_expr_paren(arg1, context, true, node);
9434 : 16 : appendStringInfoString(buf, " IS DISTINCT FROM ");
9435 : 16 : get_rule_expr_paren(arg2, context, true, node);
9436 [ + + ]: 16 : if (!PRETTY_PAREN(context))
9437 : 12 : appendStringInfoChar(buf, ')');
9438 : : }
9439 : 16 : break;
9440 : :
9441 : 140 : case T_NullIfExpr:
9442 : : {
9443 : 140 : NullIfExpr *nullifexpr = (NullIfExpr *) node;
9444 : :
9445 : 140 : appendStringInfoString(buf, "NULLIF(");
9446 : 140 : get_rule_expr((Node *) nullifexpr->args, context, true);
9447 : 140 : appendStringInfoChar(buf, ')');
9448 : : }
9449 : 140 : break;
9450 : :
9451 : 2058 : case T_ScalarArrayOpExpr:
9452 : : {
9453 : 2058 : ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
9454 : 2058 : List *args = expr->args;
9455 : 2058 : Node *arg1 = (Node *) linitial(args);
9456 : 2058 : Node *arg2 = (Node *) lsecond(args);
9457 : :
9458 [ + + ]: 2058 : if (!PRETTY_PAREN(context))
9459 : 2050 : appendStringInfoChar(buf, '(');
9460 : 2058 : get_rule_expr_paren(arg1, context, true, node);
9461 : 2058 : appendStringInfo(buf, " %s %s (",
9462 : : generate_operator_name(expr->opno,
9463 : : exprType(arg1),
9464 : : get_base_element_type(exprType(arg2))),
9465 [ + + ]: 2058 : expr->useOr ? "ANY" : "ALL");
9466 : 2058 : get_rule_expr_paren(arg2, context, true, node);
9467 : :
9468 : : /*
9469 : : * There's inherent ambiguity in "x op ANY/ALL (y)" when y is
9470 : : * a bare sub-SELECT. Since we're here, the sub-SELECT must
9471 : : * be meant as a scalar sub-SELECT yielding an array value to
9472 : : * be used in ScalarArrayOpExpr; but the grammar will
9473 : : * preferentially interpret such a construct as an ANY/ALL
9474 : : * SubLink. To prevent misparsing the output that way, insert
9475 : : * a dummy coercion (which will be stripped by parse analysis,
9476 : : * so no inefficiency is added in dump and reload). This is
9477 : : * indeed most likely what the user wrote to get the construct
9478 : : * accepted in the first place.
9479 : : */
9480 [ + + ]: 2058 : if (IsA(arg2, SubLink) &&
9481 [ + - ]: 4 : ((SubLink *) arg2)->subLinkType == EXPR_SUBLINK)
9482 : 4 : appendStringInfo(buf, "::%s",
9483 : : format_type_with_typemod(exprType(arg2),
9484 : : exprTypmod(arg2)));
9485 : 2058 : appendStringInfoChar(buf, ')');
9486 [ + + ]: 2058 : if (!PRETTY_PAREN(context))
9487 : 2050 : appendStringInfoChar(buf, ')');
9488 : : }
9489 : 2058 : break;
9490 : :
9491 : 7584 : case T_BoolExpr:
9492 : : {
9493 : 7584 : BoolExpr *expr = (BoolExpr *) node;
9494 : 7584 : Node *first_arg = linitial(expr->args);
9495 : : ListCell *arg;
9496 : :
9497 [ + + + - ]: 7584 : switch (expr->boolop)
9498 : : {
9499 : 6039 : case AND_EXPR:
9500 [ + + ]: 6039 : if (!PRETTY_PAREN(context))
9501 : 6003 : appendStringInfoChar(buf, '(');
9502 : 6039 : get_rule_expr_paren(first_arg, context,
9503 : : false, node);
9504 [ + - + + : 13731 : for_each_from(arg, expr->args, 1)
+ + ]
9505 : : {
9506 : 7692 : appendStringInfoString(buf, " AND ");
9507 : 7692 : get_rule_expr_paren((Node *) lfirst(arg), context,
9508 : : false, node);
9509 : : }
9510 [ + + ]: 6039 : if (!PRETTY_PAREN(context))
9511 : 6003 : appendStringInfoChar(buf, ')');
9512 : 6039 : break;
9513 : :
9514 : 1254 : case OR_EXPR:
9515 [ + + ]: 1254 : if (!PRETTY_PAREN(context))
9516 : 1246 : appendStringInfoChar(buf, '(');
9517 : 1254 : get_rule_expr_paren(first_arg, context,
9518 : : false, node);
9519 [ + - + + : 2983 : for_each_from(arg, expr->args, 1)
+ + ]
9520 : : {
9521 : 1729 : appendStringInfoString(buf, " OR ");
9522 : 1729 : get_rule_expr_paren((Node *) lfirst(arg), context,
9523 : : false, node);
9524 : : }
9525 [ + + ]: 1254 : if (!PRETTY_PAREN(context))
9526 : 1246 : appendStringInfoChar(buf, ')');
9527 : 1254 : break;
9528 : :
9529 : 291 : case NOT_EXPR:
9530 [ + + ]: 291 : if (!PRETTY_PAREN(context))
9531 : 283 : appendStringInfoChar(buf, '(');
9532 : 291 : appendStringInfoString(buf, "NOT ");
9533 : 291 : get_rule_expr_paren(first_arg, context,
9534 : : false, node);
9535 [ + + ]: 291 : if (!PRETTY_PAREN(context))
9536 : 283 : appendStringInfoChar(buf, ')');
9537 : 291 : break;
9538 : :
9539 : 0 : default:
9540 [ # # ]: 0 : elog(ERROR, "unrecognized boolop: %d",
9541 : : (int) expr->boolop);
9542 : : }
9543 : : }
9544 : 7584 : break;
9545 : :
9546 : 290 : case T_SubLink:
9547 : 290 : get_sublink_expr((SubLink *) node, context);
9548 : 290 : break;
9549 : :
9550 : 681 : case T_SubPlan:
9551 : : {
9552 : 681 : SubPlan *subplan = (SubPlan *) node;
9553 : :
9554 : : /*
9555 : : * We cannot see an already-planned subplan in rule deparsing,
9556 : : * only while EXPLAINing a query plan. We don't try to
9557 : : * reconstruct the original SQL, just reference the subplan
9558 : : * that appears elsewhere in EXPLAIN's result. It does seem
9559 : : * useful to show the subLinkType and testexpr (if any), and
9560 : : * we also note whether the subplan will be hashed.
9561 : : */
9562 [ + + + + : 681 : switch (subplan->subLinkType)
+ + + -
- ]
9563 : : {
9564 : 70 : case EXISTS_SUBLINK:
9565 : 70 : appendStringInfoString(buf, "EXISTS(");
9566 : : Assert(subplan->testexpr == NULL);
9567 : 70 : break;
9568 : 4 : case ALL_SUBLINK:
9569 : 4 : appendStringInfoString(buf, "(ALL ");
9570 : : Assert(subplan->testexpr != NULL);
9571 : 4 : break;
9572 : 164 : case ANY_SUBLINK:
9573 : 164 : appendStringInfoString(buf, "(ANY ");
9574 : : Assert(subplan->testexpr != NULL);
9575 : 164 : break;
9576 : 4 : case ROWCOMPARE_SUBLINK:
9577 : : /* Parenthesizing the testexpr seems sufficient */
9578 : 4 : appendStringInfoChar(buf, '(');
9579 : : Assert(subplan->testexpr != NULL);
9580 : 4 : break;
9581 : 414 : case EXPR_SUBLINK:
9582 : : /* No need to decorate these subplan references */
9583 : 414 : appendStringInfoChar(buf, '(');
9584 : : Assert(subplan->testexpr == NULL);
9585 : 414 : break;
9586 : 17 : case MULTIEXPR_SUBLINK:
9587 : : /* MULTIEXPR isn't executed in the normal way */
9588 : 17 : appendStringInfoString(buf, "(rescan ");
9589 : : Assert(subplan->testexpr == NULL);
9590 : 17 : break;
9591 : 8 : case ARRAY_SUBLINK:
9592 : 8 : appendStringInfoString(buf, "ARRAY(");
9593 : : Assert(subplan->testexpr == NULL);
9594 : 8 : break;
9595 : 0 : case CTE_SUBLINK:
9596 : : /* This case is unreachable within expressions */
9597 : 0 : appendStringInfoString(buf, "CTE(");
9598 : : Assert(subplan->testexpr == NULL);
9599 : 0 : break;
9600 : : }
9601 : :
9602 [ + + ]: 681 : if (subplan->testexpr != NULL)
9603 : : {
9604 : : deparse_namespace *dpns;
9605 : :
9606 : : /*
9607 : : * Push SubPlan into ancestors list while deparsing
9608 : : * testexpr, so that we can handle PARAM_EXEC references
9609 : : * to the SubPlan's paramIds. (This makes it look like
9610 : : * the SubPlan is an "ancestor" of the current plan node,
9611 : : * which is a little weird, but it does no harm.) In this
9612 : : * path, we don't need to mention the SubPlan explicitly,
9613 : : * because the referencing Params will show its existence.
9614 : : */
9615 : 172 : dpns = (deparse_namespace *) linitial(context->namespaces);
9616 : 172 : dpns->ancestors = lcons(subplan, dpns->ancestors);
9617 : :
9618 : 172 : get_rule_expr(subplan->testexpr, context, showimplicit);
9619 : 172 : appendStringInfoChar(buf, ')');
9620 : :
9621 : 172 : dpns->ancestors = list_delete_first(dpns->ancestors);
9622 : : }
9623 : : else
9624 : : {
9625 : : const char *nameprefix;
9626 : :
9627 : : /* No referencing Params, so show the SubPlan's name */
9628 [ - + ]: 509 : if (subplan->isInitPlan)
9629 : 0 : nameprefix = "InitPlan ";
9630 : : else
9631 : 509 : nameprefix = "SubPlan ";
9632 [ - + ]: 509 : if (subplan->useHashTable)
9633 : 0 : appendStringInfo(buf, "hashed %s%s)",
9634 : : nameprefix, subplan->plan_name);
9635 : : else
9636 : 509 : appendStringInfo(buf, "%s%s)",
9637 : : nameprefix, subplan->plan_name);
9638 : : }
9639 : : }
9640 : 681 : break;
9641 : :
9642 : 0 : case T_AlternativeSubPlan:
9643 : : {
9644 : 0 : AlternativeSubPlan *asplan = (AlternativeSubPlan *) node;
9645 : : ListCell *lc;
9646 : :
9647 : : /*
9648 : : * This case cannot be reached in normal usage, since no
9649 : : * AlternativeSubPlan can appear either in parsetrees or
9650 : : * finished plan trees. We keep it just in case somebody
9651 : : * wants to use this code to print planner data structures.
9652 : : */
9653 : 0 : appendStringInfoString(buf, "(alternatives: ");
9654 [ # # # # : 0 : foreach(lc, asplan->subplans)
# # ]
9655 : : {
9656 : 0 : SubPlan *splan = lfirst_node(SubPlan, lc);
9657 : : const char *nameprefix;
9658 : :
9659 [ # # ]: 0 : if (splan->isInitPlan)
9660 : 0 : nameprefix = "InitPlan ";
9661 : : else
9662 : 0 : nameprefix = "SubPlan ";
9663 [ # # ]: 0 : if (splan->useHashTable)
9664 : 0 : appendStringInfo(buf, "hashed %s%s", nameprefix,
9665 : : splan->plan_name);
9666 : : else
9667 : 0 : appendStringInfo(buf, "%s%s", nameprefix,
9668 : : splan->plan_name);
9669 [ # # ]: 0 : if (lnext(asplan->subplans, lc))
9670 : 0 : appendStringInfoString(buf, " or ");
9671 : : }
9672 : 0 : appendStringInfoChar(buf, ')');
9673 : : }
9674 : 0 : break;
9675 : :
9676 : 934 : case T_FieldSelect:
9677 : : {
9678 : 934 : FieldSelect *fselect = (FieldSelect *) node;
9679 : 934 : Node *arg = (Node *) fselect->arg;
9680 : 934 : int fno = fselect->fieldnum;
9681 : : const char *fieldname;
9682 : : bool need_parens;
9683 : :
9684 : : /*
9685 : : * Parenthesize the argument unless it's a SubscriptingRef or
9686 : : * another FieldSelect. Note in particular that it would be
9687 : : * WRONG to not parenthesize a Var argument; simplicity is not
9688 : : * the issue here, having the right number of names is.
9689 : : */
9690 [ + + ]: 1844 : need_parens = !IsA(arg, SubscriptingRef) &&
9691 [ + - ]: 910 : !IsA(arg, FieldSelect);
9692 [ + + ]: 934 : if (need_parens)
9693 : 910 : appendStringInfoChar(buf, '(');
9694 : 934 : get_rule_expr(arg, context, true);
9695 [ + + ]: 934 : if (need_parens)
9696 : 910 : appendStringInfoChar(buf, ')');
9697 : :
9698 : : /*
9699 : : * Get and print the field name.
9700 : : */
9701 : 934 : fieldname = get_name_for_var_field((Var *) arg, fno,
9702 : : 0, context);
9703 : 934 : appendStringInfo(buf, ".%s", quote_identifier(fieldname));
9704 : : }
9705 : 934 : break;
9706 : :
9707 : 4 : case T_FieldStore:
9708 : : {
9709 : 4 : FieldStore *fstore = (FieldStore *) node;
9710 : : bool need_parens;
9711 : :
9712 : : /*
9713 : : * There is no good way to represent a FieldStore as real SQL,
9714 : : * so decompilation of INSERT or UPDATE statements should
9715 : : * always use processIndirection as part of the
9716 : : * statement-level syntax. We should only get here when
9717 : : * EXPLAIN tries to print the targetlist of a plan resulting
9718 : : * from such a statement. The plan case is even harder than
9719 : : * ordinary rules would be, because the planner tries to
9720 : : * collapse multiple assignments to the same field or subfield
9721 : : * into one FieldStore; so we can see a list of target fields
9722 : : * not just one, and the arguments could be FieldStores
9723 : : * themselves. We don't bother to try to print the target
9724 : : * field names; we just print the source arguments, with a
9725 : : * ROW() around them if there's more than one. This isn't
9726 : : * terribly complete, but it's probably good enough for
9727 : : * EXPLAIN's purposes; especially since anything more would be
9728 : : * either hopelessly confusing or an even poorer
9729 : : * representation of what the plan is actually doing.
9730 : : */
9731 : 4 : need_parens = (list_length(fstore->newvals) != 1);
9732 [ + - ]: 4 : if (need_parens)
9733 : 4 : appendStringInfoString(buf, "ROW(");
9734 : 4 : get_rule_expr((Node *) fstore->newvals, context, showimplicit);
9735 [ + - ]: 4 : if (need_parens)
9736 : 4 : appendStringInfoChar(buf, ')');
9737 : : }
9738 : 4 : break;
9739 : :
9740 : 1901 : case T_RelabelType:
9741 : : {
9742 : 1901 : RelabelType *relabel = (RelabelType *) node;
9743 : 1901 : Node *arg = (Node *) relabel->arg;
9744 : :
9745 [ + + ]: 1901 : if (relabel->relabelformat == COERCE_IMPLICIT_CAST &&
9746 [ + + ]: 1734 : !showimplicit)
9747 : : {
9748 : : /* don't show the implicit cast */
9749 : 44 : get_rule_expr_paren(arg, context, false, node);
9750 : : }
9751 : : else
9752 : : {
9753 : 1857 : get_coercion_expr(arg, context,
9754 : : relabel->resulttype,
9755 : : relabel->resulttypmod,
9756 : : node);
9757 : : }
9758 : : }
9759 : 1901 : break;
9760 : :
9761 : 503 : case T_CoerceViaIO:
9762 : : {
9763 : 503 : CoerceViaIO *iocoerce = (CoerceViaIO *) node;
9764 : 503 : Node *arg = (Node *) iocoerce->arg;
9765 : :
9766 [ + + ]: 503 : if (iocoerce->coerceformat == COERCE_IMPLICIT_CAST &&
9767 [ + - ]: 24 : !showimplicit)
9768 : : {
9769 : : /* don't show the implicit cast */
9770 : 24 : get_rule_expr_paren(arg, context, false, node);
9771 : : }
9772 : : else
9773 : : {
9774 : 479 : get_coercion_expr(arg, context,
9775 : : iocoerce->resulttype,
9776 : : -1,
9777 : : node);
9778 : : }
9779 : : }
9780 : 503 : break;
9781 : :
9782 : 43 : case T_ArrayCoerceExpr:
9783 : : {
9784 : 43 : ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
9785 : 43 : Node *arg = (Node *) acoerce->arg;
9786 : :
9787 [ + + ]: 43 : if (acoerce->coerceformat == COERCE_IMPLICIT_CAST &&
9788 [ + + ]: 37 : !showimplicit)
9789 : : {
9790 : : /* don't show the implicit cast */
9791 : 4 : get_rule_expr_paren(arg, context, false, node);
9792 : : }
9793 : : else
9794 : : {
9795 : 39 : get_coercion_expr(arg, context,
9796 : : acoerce->resulttype,
9797 : : acoerce->resulttypmod,
9798 : : node);
9799 : : }
9800 : : }
9801 : 43 : break;
9802 : :
9803 : 53 : case T_ConvertRowtypeExpr:
9804 : : {
9805 : 53 : ConvertRowtypeExpr *convert = (ConvertRowtypeExpr *) node;
9806 : 53 : Node *arg = (Node *) convert->arg;
9807 : :
9808 [ + + ]: 53 : if (convert->convertformat == COERCE_IMPLICIT_CAST &&
9809 [ + + ]: 49 : !showimplicit)
9810 : : {
9811 : : /* don't show the implicit cast */
9812 : 12 : get_rule_expr_paren(arg, context, false, node);
9813 : : }
9814 : : else
9815 : : {
9816 : 41 : get_coercion_expr(arg, context,
9817 : : convert->resulttype, -1,
9818 : : node);
9819 : : }
9820 : : }
9821 : 53 : break;
9822 : :
9823 : 60 : case T_CollateExpr:
9824 : : {
9825 : 60 : CollateExpr *collate = (CollateExpr *) node;
9826 : 60 : Node *arg = (Node *) collate->arg;
9827 : :
9828 [ + + ]: 60 : if (!PRETTY_PAREN(context))
9829 : 56 : appendStringInfoChar(buf, '(');
9830 : 60 : get_rule_expr_paren(arg, context, showimplicit, node);
9831 : 60 : appendStringInfo(buf, " COLLATE %s",
9832 : : generate_collation_name(collate->collOid));
9833 [ + + ]: 60 : if (!PRETTY_PAREN(context))
9834 : 56 : appendStringInfoChar(buf, ')');
9835 : : }
9836 : 60 : break;
9837 : :
9838 : 496 : case T_CaseExpr:
9839 : : {
9840 : 496 : CaseExpr *caseexpr = (CaseExpr *) node;
9841 : : ListCell *temp;
9842 : :
9843 : 496 : appendContextKeyword(context, "CASE",
9844 : : 0, PRETTYINDENT_VAR, 0);
9845 [ + + ]: 496 : if (caseexpr->arg)
9846 : : {
9847 : 207 : appendStringInfoChar(buf, ' ');
9848 : 207 : get_rule_expr((Node *) caseexpr->arg, context, true);
9849 : : }
9850 [ + - + + : 2012 : foreach(temp, caseexpr->args)
+ + ]
9851 : : {
9852 : 1516 : CaseWhen *when = (CaseWhen *) lfirst(temp);
9853 : 1516 : Node *w = (Node *) when->expr;
9854 : :
9855 [ + + ]: 1516 : if (caseexpr->arg)
9856 : : {
9857 : : /*
9858 : : * The parser should have produced WHEN clauses of the
9859 : : * form "CaseTestExpr = RHS", possibly with an
9860 : : * implicit coercion inserted above the CaseTestExpr.
9861 : : * For accurate decompilation of rules it's essential
9862 : : * that we show just the RHS. However in an
9863 : : * expression that's been through the optimizer, the
9864 : : * WHEN clause could be almost anything (since the
9865 : : * equality operator could have been expanded into an
9866 : : * inline function). If we don't recognize the form
9867 : : * of the WHEN clause, just punt and display it as-is.
9868 : : */
9869 [ + - ]: 625 : if (IsA(w, OpExpr))
9870 : : {
9871 : 625 : List *args = ((OpExpr *) w)->args;
9872 : :
9873 [ + - ]: 625 : if (list_length(args) == 2 &&
9874 [ + - ]: 625 : IsA(strip_implicit_coercions(linitial(args)),
9875 : : CaseTestExpr))
9876 : 625 : w = (Node *) lsecond(args);
9877 : : }
9878 : : }
9879 : :
9880 [ + + ]: 1516 : if (!PRETTY_INDENT(context))
9881 : 112 : appendStringInfoChar(buf, ' ');
9882 : 1516 : appendContextKeyword(context, "WHEN ",
9883 : : 0, 0, 0);
9884 : 1516 : get_rule_expr(w, context, false);
9885 : 1516 : appendStringInfoString(buf, " THEN ");
9886 : 1516 : get_rule_expr((Node *) when->result, context, true);
9887 : : }
9888 [ + + ]: 496 : if (!PRETTY_INDENT(context))
9889 : 107 : appendStringInfoChar(buf, ' ');
9890 : 496 : appendContextKeyword(context, "ELSE ",
9891 : : 0, 0, 0);
9892 : 496 : get_rule_expr((Node *) caseexpr->defresult, context, true);
9893 [ + + ]: 496 : if (!PRETTY_INDENT(context))
9894 : 107 : appendStringInfoChar(buf, ' ');
9895 : 496 : appendContextKeyword(context, "END",
9896 : : -PRETTYINDENT_VAR, 0, 0);
9897 : : }
9898 : 496 : break;
9899 : :
9900 : 0 : case T_CaseTestExpr:
9901 : : {
9902 : : /*
9903 : : * Normally we should never get here, since for expressions
9904 : : * that can contain this node type we attempt to avoid
9905 : : * recursing to it. But in an optimized expression we might
9906 : : * be unable to avoid that (see comments for CaseExpr). If we
9907 : : * do see one, print it as CASE_TEST_EXPR.
9908 : : */
9909 : 0 : appendStringInfoString(buf, "CASE_TEST_EXPR");
9910 : : }
9911 : 0 : break;
9912 : :
9913 : 368 : case T_ArrayExpr:
9914 : : {
9915 : 368 : ArrayExpr *arrayexpr = (ArrayExpr *) node;
9916 : :
9917 : 368 : appendStringInfoString(buf, "ARRAY[");
9918 : 368 : get_rule_expr((Node *) arrayexpr->elements, context, true);
9919 : 368 : appendStringInfoChar(buf, ']');
9920 : :
9921 : : /*
9922 : : * If the array isn't empty, we assume its elements are
9923 : : * coerced to the desired type. If it's empty, though, we
9924 : : * need an explicit coercion to the array type.
9925 : : */
9926 [ + + ]: 368 : if (arrayexpr->elements == NIL)
9927 : 4 : appendStringInfo(buf, "::%s",
9928 : : format_type_with_typemod(arrayexpr->array_typeid, -1));
9929 : : }
9930 : 368 : break;
9931 : :
9932 : 186 : case T_RowExpr:
9933 : : {
9934 : 186 : RowExpr *rowexpr = (RowExpr *) node;
9935 : 186 : TupleDesc tupdesc = NULL;
9936 : : ListCell *arg;
9937 : : int i;
9938 : : char *sep;
9939 : :
9940 : : /*
9941 : : * If it's a named type and not RECORD, we may have to skip
9942 : : * dropped columns and/or claim there are NULLs for added
9943 : : * columns.
9944 : : */
9945 [ + + ]: 186 : if (rowexpr->row_typeid != RECORDOID)
9946 : : {
9947 : 44 : tupdesc = lookup_rowtype_tupdesc(rowexpr->row_typeid, -1);
9948 : : Assert(list_length(rowexpr->args) <= tupdesc->natts);
9949 : : }
9950 : :
9951 : : /*
9952 : : * SQL99 allows "ROW" to be omitted when there is more than
9953 : : * one column, but for simplicity we always print it.
9954 : : */
9955 : 186 : appendStringInfoString(buf, "ROW(");
9956 : 186 : sep = "";
9957 : 186 : i = 0;
9958 [ + - + + : 564 : foreach(arg, rowexpr->args)
+ + ]
9959 : : {
9960 : 378 : Node *e = (Node *) lfirst(arg);
9961 : :
9962 [ + + ]: 378 : if (tupdesc == NULL ||
9963 [ + - ]: 104 : !TupleDescCompactAttr(tupdesc, i)->attisdropped)
9964 : : {
9965 : 378 : appendStringInfoString(buf, sep);
9966 : : /* Whole-row Vars need special treatment here */
9967 : 378 : get_rule_expr_toplevel(e, context, true);
9968 : 378 : sep = ", ";
9969 : : }
9970 : 378 : i++;
9971 : : }
9972 [ + + ]: 186 : if (tupdesc != NULL)
9973 : : {
9974 [ - + ]: 44 : while (i < tupdesc->natts)
9975 : : {
9976 [ # # ]: 0 : if (!TupleDescCompactAttr(tupdesc, i)->attisdropped)
9977 : : {
9978 : 0 : appendStringInfoString(buf, sep);
9979 : 0 : appendStringInfoString(buf, "NULL");
9980 : 0 : sep = ", ";
9981 : : }
9982 : 0 : i++;
9983 : : }
9984 : :
9985 [ + - ]: 44 : ReleaseTupleDesc(tupdesc);
9986 : : }
9987 : 186 : appendStringInfoChar(buf, ')');
9988 [ + + ]: 186 : if (rowexpr->row_format == COERCE_EXPLICIT_CAST)
9989 : 24 : appendStringInfo(buf, "::%s",
9990 : : format_type_with_typemod(rowexpr->row_typeid, -1));
9991 : : }
9992 : 186 : break;
9993 : :
9994 : 100 : case T_RowCompareExpr:
9995 : : {
9996 : 100 : RowCompareExpr *rcexpr = (RowCompareExpr *) node;
9997 : :
9998 : : /*
9999 : : * SQL99 allows "ROW" to be omitted when there is more than
10000 : : * one column, but for simplicity we always print it. Within
10001 : : * a ROW expression, whole-row Vars need special treatment, so
10002 : : * use get_rule_list_toplevel.
10003 : : */
10004 : 100 : appendStringInfoString(buf, "(ROW(");
10005 : 100 : get_rule_list_toplevel(rcexpr->largs, context, true);
10006 : :
10007 : : /*
10008 : : * We assume that the name of the first-column operator will
10009 : : * do for all the rest too. This is definitely open to
10010 : : * failure, eg if some but not all operators were renamed
10011 : : * since the construct was parsed, but there seems no way to
10012 : : * be perfect.
10013 : : */
10014 : 100 : appendStringInfo(buf, ") %s ROW(",
10015 : 100 : generate_operator_name(linitial_oid(rcexpr->opnos),
10016 : 100 : exprType(linitial(rcexpr->largs)),
10017 : 100 : exprType(linitial(rcexpr->rargs))));
10018 : 100 : get_rule_list_toplevel(rcexpr->rargs, context, true);
10019 : 100 : appendStringInfoString(buf, "))");
10020 : : }
10021 : 100 : break;
10022 : :
10023 : 929 : case T_CoalesceExpr:
10024 : : {
10025 : 929 : CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
10026 : :
10027 : 929 : appendStringInfoString(buf, "COALESCE(");
10028 : 929 : get_rule_expr((Node *) coalesceexpr->args, context, true);
10029 : 929 : appendStringInfoChar(buf, ')');
10030 : : }
10031 : 929 : break;
10032 : :
10033 : 28 : case T_MinMaxExpr:
10034 : : {
10035 : 28 : MinMaxExpr *minmaxexpr = (MinMaxExpr *) node;
10036 : :
10037 [ + + - ]: 28 : switch (minmaxexpr->op)
10038 : : {
10039 : 8 : case IS_GREATEST:
10040 : 8 : appendStringInfoString(buf, "GREATEST(");
10041 : 8 : break;
10042 : 20 : case IS_LEAST:
10043 : 20 : appendStringInfoString(buf, "LEAST(");
10044 : 20 : break;
10045 : : }
10046 : 28 : get_rule_expr((Node *) minmaxexpr->args, context, true);
10047 : 28 : appendStringInfoChar(buf, ')');
10048 : : }
10049 : 28 : break;
10050 : :
10051 : 455 : case T_SQLValueFunction:
10052 : : {
10053 : 455 : SQLValueFunction *svf = (SQLValueFunction *) node;
10054 : :
10055 : : /*
10056 : : * Note: this code knows that typmod for time, timestamp, and
10057 : : * timestamptz just prints as integer.
10058 : : */
10059 [ + + + + : 455 : switch (svf->op)
+ + + + +
+ + + + +
+ - ]
10060 : : {
10061 : 69 : case SVFOP_CURRENT_DATE:
10062 : 69 : appendStringInfoString(buf, "CURRENT_DATE");
10063 : 69 : break;
10064 : 8 : case SVFOP_CURRENT_TIME:
10065 : 8 : appendStringInfoString(buf, "CURRENT_TIME");
10066 : 8 : break;
10067 : 8 : case SVFOP_CURRENT_TIME_N:
10068 : 8 : appendStringInfo(buf, "CURRENT_TIME(%d)", svf->typmod);
10069 : 8 : break;
10070 : 8 : case SVFOP_CURRENT_TIMESTAMP:
10071 : 8 : appendStringInfoString(buf, "CURRENT_TIMESTAMP");
10072 : 8 : break;
10073 : 77 : case SVFOP_CURRENT_TIMESTAMP_N:
10074 : 77 : appendStringInfo(buf, "CURRENT_TIMESTAMP(%d)",
10075 : : svf->typmod);
10076 : 77 : break;
10077 : 8 : case SVFOP_LOCALTIME:
10078 : 8 : appendStringInfoString(buf, "LOCALTIME");
10079 : 8 : break;
10080 : 8 : case SVFOP_LOCALTIME_N:
10081 : 8 : appendStringInfo(buf, "LOCALTIME(%d)", svf->typmod);
10082 : 8 : break;
10083 : 20 : case SVFOP_LOCALTIMESTAMP:
10084 : 20 : appendStringInfoString(buf, "LOCALTIMESTAMP");
10085 : 20 : break;
10086 : 12 : case SVFOP_LOCALTIMESTAMP_N:
10087 : 12 : appendStringInfo(buf, "LOCALTIMESTAMP(%d)",
10088 : : svf->typmod);
10089 : 12 : break;
10090 : 8 : case SVFOP_CURRENT_ROLE:
10091 : 8 : appendStringInfoString(buf, "CURRENT_ROLE");
10092 : 8 : break;
10093 : 185 : case SVFOP_CURRENT_USER:
10094 : 185 : appendStringInfoString(buf, "CURRENT_USER");
10095 : 185 : break;
10096 : 8 : case SVFOP_USER:
10097 : 8 : appendStringInfoString(buf, "USER");
10098 : 8 : break;
10099 : 20 : case SVFOP_SESSION_USER:
10100 : 20 : appendStringInfoString(buf, "SESSION_USER");
10101 : 20 : break;
10102 : 8 : case SVFOP_CURRENT_CATALOG:
10103 : 8 : appendStringInfoString(buf, "CURRENT_CATALOG");
10104 : 8 : break;
10105 : 8 : case SVFOP_CURRENT_SCHEMA:
10106 : 8 : appendStringInfoString(buf, "CURRENT_SCHEMA");
10107 : 8 : break;
10108 : : }
10109 : : }
10110 : 455 : break;
10111 : :
10112 : 99 : case T_XmlExpr:
10113 : : {
10114 : 99 : XmlExpr *xexpr = (XmlExpr *) node;
10115 : 99 : bool needcomma = false;
10116 : : ListCell *arg;
10117 : : ListCell *narg;
10118 : : Const *con;
10119 : :
10120 [ + + + + : 99 : switch (xexpr->op)
+ + + -
- ]
10121 : : {
10122 : 9 : case IS_XMLCONCAT:
10123 : 9 : appendStringInfoString(buf, "XMLCONCAT(");
10124 : 9 : break;
10125 : 18 : case IS_XMLELEMENT:
10126 : 18 : appendStringInfoString(buf, "XMLELEMENT(");
10127 : 18 : break;
10128 : 9 : case IS_XMLFOREST:
10129 : 9 : appendStringInfoString(buf, "XMLFOREST(");
10130 : 9 : break;
10131 : 9 : case IS_XMLPARSE:
10132 : 9 : appendStringInfoString(buf, "XMLPARSE(");
10133 : 9 : break;
10134 : 9 : case IS_XMLPI:
10135 : 9 : appendStringInfoString(buf, "XMLPI(");
10136 : 9 : break;
10137 : 9 : case IS_XMLROOT:
10138 : 9 : appendStringInfoString(buf, "XMLROOT(");
10139 : 9 : break;
10140 : 36 : case IS_XMLSERIALIZE:
10141 : 36 : appendStringInfoString(buf, "XMLSERIALIZE(");
10142 : 36 : break;
10143 : 0 : case IS_DOCUMENT:
10144 : 0 : break;
10145 : : }
10146 [ + + + + ]: 99 : if (xexpr->op == IS_XMLPARSE || xexpr->op == IS_XMLSERIALIZE)
10147 : : {
10148 [ + + ]: 45 : if (xexpr->xmloption == XMLOPTION_DOCUMENT)
10149 : 18 : appendStringInfoString(buf, "DOCUMENT ");
10150 : : else
10151 : 27 : appendStringInfoString(buf, "CONTENT ");
10152 : : }
10153 [ + + ]: 99 : if (xexpr->name)
10154 : : {
10155 : 27 : appendStringInfo(buf, "NAME %s",
10156 : 27 : quote_identifier(map_xml_name_to_sql_identifier(xexpr->name)));
10157 : 27 : needcomma = true;
10158 : : }
10159 [ + + ]: 99 : if (xexpr->named_args)
10160 : : {
10161 [ + + ]: 18 : if (xexpr->op != IS_XMLFOREST)
10162 : : {
10163 [ + - ]: 9 : if (needcomma)
10164 : 9 : appendStringInfoString(buf, ", ");
10165 : 9 : appendStringInfoString(buf, "XMLATTRIBUTES(");
10166 : 9 : needcomma = false;
10167 : : }
10168 [ + - + + : 63 : forboth(arg, xexpr->named_args, narg, xexpr->arg_names)
+ - + + +
+ + - +
+ ]
10169 : : {
10170 : 45 : Node *e = (Node *) lfirst(arg);
10171 : 45 : char *argname = strVal(lfirst(narg));
10172 : :
10173 [ + + ]: 45 : if (needcomma)
10174 : 27 : appendStringInfoString(buf, ", ");
10175 : 45 : get_rule_expr(e, context, true);
10176 : 45 : appendStringInfo(buf, " AS %s",
10177 : 45 : quote_identifier(map_xml_name_to_sql_identifier(argname)));
10178 : 45 : needcomma = true;
10179 : : }
10180 [ + + ]: 18 : if (xexpr->op != IS_XMLFOREST)
10181 : 9 : appendStringInfoChar(buf, ')');
10182 : : }
10183 [ + + ]: 99 : if (xexpr->args)
10184 : : {
10185 [ + + ]: 90 : if (needcomma)
10186 : 27 : appendStringInfoString(buf, ", ");
10187 [ + + + - : 90 : switch (xexpr->op)
- ]
10188 : : {
10189 : 72 : case IS_XMLCONCAT:
10190 : : case IS_XMLELEMENT:
10191 : : case IS_XMLFOREST:
10192 : : case IS_XMLPI:
10193 : : case IS_XMLSERIALIZE:
10194 : : /* no extra decoration needed */
10195 : 72 : get_rule_expr((Node *) xexpr->args, context, true);
10196 : 72 : break;
10197 : 9 : case IS_XMLPARSE:
10198 : : Assert(list_length(xexpr->args) == 2);
10199 : :
10200 : 9 : get_rule_expr((Node *) linitial(xexpr->args),
10201 : : context, true);
10202 : :
10203 : 9 : con = lsecond_node(Const, xexpr->args);
10204 : : Assert(!con->constisnull);
10205 [ - + ]: 9 : if (DatumGetBool(con->constvalue))
10206 : 0 : appendStringInfoString(buf,
10207 : : " PRESERVE WHITESPACE");
10208 : : else
10209 : 9 : appendStringInfoString(buf,
10210 : : " STRIP WHITESPACE");
10211 : 9 : break;
10212 : 9 : case IS_XMLROOT:
10213 : : Assert(list_length(xexpr->args) == 3);
10214 : :
10215 : 9 : get_rule_expr((Node *) linitial(xexpr->args),
10216 : : context, true);
10217 : :
10218 : 9 : appendStringInfoString(buf, ", VERSION ");
10219 : 9 : con = (Const *) lsecond(xexpr->args);
10220 [ + - ]: 9 : if (IsA(con, Const) &&
10221 [ + - ]: 9 : con->constisnull)
10222 : 9 : appendStringInfoString(buf, "NO VALUE");
10223 : : else
10224 : 0 : get_rule_expr((Node *) con, context, false);
10225 : :
10226 : 9 : con = lthird_node(Const, xexpr->args);
10227 [ + - ]: 9 : if (con->constisnull)
10228 : : /* suppress STANDALONE NO VALUE */ ;
10229 : : else
10230 : : {
10231 [ + - - - ]: 9 : switch (DatumGetInt32(con->constvalue))
10232 : : {
10233 : 9 : case XML_STANDALONE_YES:
10234 : 9 : appendStringInfoString(buf,
10235 : : ", STANDALONE YES");
10236 : 9 : break;
10237 : 0 : case XML_STANDALONE_NO:
10238 : 0 : appendStringInfoString(buf,
10239 : : ", STANDALONE NO");
10240 : 0 : break;
10241 : 0 : case XML_STANDALONE_NO_VALUE:
10242 : 0 : appendStringInfoString(buf,
10243 : : ", STANDALONE NO VALUE");
10244 : 0 : break;
10245 : 0 : default:
10246 : 0 : break;
10247 : : }
10248 : : }
10249 : 9 : break;
10250 : 0 : case IS_DOCUMENT:
10251 : 0 : get_rule_expr_paren((Node *) xexpr->args, context, false, node);
10252 : 0 : break;
10253 : : }
10254 : : }
10255 [ + + ]: 99 : if (xexpr->op == IS_XMLSERIALIZE)
10256 : : {
10257 : 36 : appendStringInfo(buf, " AS %s",
10258 : : format_type_with_typemod(xexpr->type,
10259 : : xexpr->typmod));
10260 [ + + ]: 36 : if (xexpr->indent)
10261 : 9 : appendStringInfoString(buf, " INDENT");
10262 : : else
10263 : 27 : appendStringInfoString(buf, " NO INDENT");
10264 : : }
10265 : :
10266 [ - + ]: 99 : if (xexpr->op == IS_DOCUMENT)
10267 : 0 : appendStringInfoString(buf, " IS DOCUMENT");
10268 : : else
10269 : 99 : appendStringInfoChar(buf, ')');
10270 : : }
10271 : 99 : break;
10272 : :
10273 : 1962 : case T_NullTest:
10274 : : {
10275 : 1962 : NullTest *ntest = (NullTest *) node;
10276 : :
10277 [ + + ]: 1962 : if (!PRETTY_PAREN(context))
10278 : 1922 : appendStringInfoChar(buf, '(');
10279 : 1962 : get_rule_expr_paren((Node *) ntest->arg, context, true, node);
10280 : :
10281 : : /*
10282 : : * For scalar inputs, we prefer to print as IS [NOT] NULL,
10283 : : * which is shorter and traditional. If it's a rowtype input
10284 : : * but we're applying a scalar test, must print IS [NOT]
10285 : : * DISTINCT FROM NULL to be semantically correct.
10286 : : */
10287 [ + + ]: 1962 : if (ntest->argisrow ||
10288 [ + + ]: 1868 : !type_is_rowtype(exprType((Node *) ntest->arg)))
10289 : : {
10290 [ + + - ]: 1942 : switch (ntest->nulltesttype)
10291 : : {
10292 : 636 : case IS_NULL:
10293 : 636 : appendStringInfoString(buf, " IS NULL");
10294 : 636 : break;
10295 : 1306 : case IS_NOT_NULL:
10296 : 1306 : appendStringInfoString(buf, " IS NOT NULL");
10297 : 1306 : break;
10298 : 0 : default:
10299 [ # # ]: 0 : elog(ERROR, "unrecognized nulltesttype: %d",
10300 : : (int) ntest->nulltesttype);
10301 : : }
10302 : : }
10303 : : else
10304 : : {
10305 [ + + - ]: 20 : switch (ntest->nulltesttype)
10306 : : {
10307 : 8 : case IS_NULL:
10308 : 8 : appendStringInfoString(buf, " IS NOT DISTINCT FROM NULL");
10309 : 8 : break;
10310 : 12 : case IS_NOT_NULL:
10311 : 12 : appendStringInfoString(buf, " IS DISTINCT FROM NULL");
10312 : 12 : break;
10313 : 0 : default:
10314 [ # # ]: 0 : elog(ERROR, "unrecognized nulltesttype: %d",
10315 : : (int) ntest->nulltesttype);
10316 : : }
10317 : : }
10318 [ + + ]: 1962 : if (!PRETTY_PAREN(context))
10319 : 1922 : appendStringInfoChar(buf, ')');
10320 : : }
10321 : 1962 : break;
10322 : :
10323 : 212 : case T_BooleanTest:
10324 : : {
10325 : 212 : BooleanTest *btest = (BooleanTest *) node;
10326 : :
10327 [ + - ]: 212 : if (!PRETTY_PAREN(context))
10328 : 212 : appendStringInfoChar(buf, '(');
10329 : 212 : get_rule_expr_paren((Node *) btest->arg, context, false, node);
10330 [ + + - + : 212 : switch (btest->booltesttype)
+ + - ]
10331 : : {
10332 : 28 : case IS_TRUE:
10333 : 28 : appendStringInfoString(buf, " IS TRUE");
10334 : 28 : break;
10335 : 92 : case IS_NOT_TRUE:
10336 : 92 : appendStringInfoString(buf, " IS NOT TRUE");
10337 : 92 : break;
10338 : 0 : case IS_FALSE:
10339 : 0 : appendStringInfoString(buf, " IS FALSE");
10340 : 0 : break;
10341 : 36 : case IS_NOT_FALSE:
10342 : 36 : appendStringInfoString(buf, " IS NOT FALSE");
10343 : 36 : break;
10344 : 20 : case IS_UNKNOWN:
10345 : 20 : appendStringInfoString(buf, " IS UNKNOWN");
10346 : 20 : break;
10347 : 36 : case IS_NOT_UNKNOWN:
10348 : 36 : appendStringInfoString(buf, " IS NOT UNKNOWN");
10349 : 36 : break;
10350 : 0 : default:
10351 [ # # ]: 0 : elog(ERROR, "unrecognized booltesttype: %d",
10352 : : (int) btest->booltesttype);
10353 : : }
10354 [ + - ]: 212 : if (!PRETTY_PAREN(context))
10355 : 212 : appendStringInfoChar(buf, ')');
10356 : : }
10357 : 212 : break;
10358 : :
10359 : 75 : case T_CoerceToDomain:
10360 : : {
10361 : 75 : CoerceToDomain *ctest = (CoerceToDomain *) node;
10362 : 75 : Node *arg = (Node *) ctest->arg;
10363 : :
10364 [ + + ]: 75 : if (ctest->coercionformat == COERCE_IMPLICIT_CAST &&
10365 [ + + ]: 36 : !showimplicit)
10366 : : {
10367 : : /* don't show the implicit cast */
10368 : 28 : get_rule_expr(arg, context, false);
10369 : : }
10370 : : else
10371 : : {
10372 : 47 : get_coercion_expr(arg, context,
10373 : : ctest->resulttype,
10374 : : ctest->resulttypmod,
10375 : : node);
10376 : : }
10377 : : }
10378 : 75 : break;
10379 : :
10380 : 266 : case T_CoerceToDomainValue:
10381 : 266 : appendStringInfoString(buf, "VALUE");
10382 : 266 : break;
10383 : :
10384 : 44 : case T_SetToDefault:
10385 : 44 : appendStringInfoString(buf, "DEFAULT");
10386 : 44 : break;
10387 : :
10388 : 16 : case T_CurrentOfExpr:
10389 : : {
10390 : 16 : CurrentOfExpr *cexpr = (CurrentOfExpr *) node;
10391 : :
10392 [ + - ]: 16 : if (cexpr->cursor_name)
10393 : 16 : appendStringInfo(buf, "CURRENT OF %s",
10394 : 16 : quote_identifier(cexpr->cursor_name));
10395 : : else
10396 : 0 : appendStringInfo(buf, "CURRENT OF $%d",
10397 : : cexpr->cursor_param);
10398 : : }
10399 : 16 : break;
10400 : :
10401 : 0 : case T_NextValueExpr:
10402 : : {
10403 : 0 : NextValueExpr *nvexpr = (NextValueExpr *) node;
10404 : :
10405 : : /*
10406 : : * This isn't exactly nextval(), but that seems close enough
10407 : : * for EXPLAIN's purposes.
10408 : : */
10409 : 0 : appendStringInfoString(buf, "nextval(");
10410 : 0 : simple_quote_literal(buf,
10411 : 0 : generate_relation_name(nvexpr->seqid,
10412 : : NIL));
10413 : 0 : appendStringInfoChar(buf, ')');
10414 : : }
10415 : 0 : break;
10416 : :
10417 : 20 : case T_InferenceElem:
10418 : : {
10419 : 20 : InferenceElem *iexpr = (InferenceElem *) node;
10420 : : bool save_varprefix;
10421 : : bool need_parens;
10422 : :
10423 : : /*
10424 : : * InferenceElem can only refer to target relation, so a
10425 : : * prefix is not useful, and indeed would cause parse errors.
10426 : : */
10427 : 20 : save_varprefix = context->varprefix;
10428 : 20 : context->varprefix = false;
10429 : :
10430 : : /*
10431 : : * Parenthesize the element unless it's a simple Var or a bare
10432 : : * function call. Follows pg_get_indexdef_worker().
10433 : : */
10434 : 20 : need_parens = !IsA(iexpr->expr, Var);
10435 [ - + ]: 20 : if (IsA(iexpr->expr, FuncExpr) &&
10436 [ # # ]: 0 : ((FuncExpr *) iexpr->expr)->funcformat ==
10437 : : COERCE_EXPLICIT_CALL)
10438 : 0 : need_parens = false;
10439 : :
10440 [ - + ]: 20 : if (need_parens)
10441 : 0 : appendStringInfoChar(buf, '(');
10442 : 20 : get_rule_expr((Node *) iexpr->expr,
10443 : : context, false);
10444 [ - + ]: 20 : if (need_parens)
10445 : 0 : appendStringInfoChar(buf, ')');
10446 : :
10447 : 20 : context->varprefix = save_varprefix;
10448 : :
10449 [ + + ]: 20 : if (iexpr->infercollid)
10450 : 8 : appendStringInfo(buf, " COLLATE %s",
10451 : : generate_collation_name(iexpr->infercollid));
10452 : :
10453 : : /* Add the operator class name, if not default */
10454 [ + + ]: 20 : if (iexpr->inferopclass)
10455 : : {
10456 : 8 : Oid inferopclass = iexpr->inferopclass;
10457 : 8 : Oid inferopcinputtype = get_opclass_input_type(iexpr->inferopclass);
10458 : :
10459 : 8 : get_opclass_name(inferopclass, inferopcinputtype, buf);
10460 : : }
10461 : : }
10462 : 20 : break;
10463 : :
10464 : 8 : case T_ReturningExpr:
10465 : : {
10466 : 8 : ReturningExpr *retExpr = (ReturningExpr *) node;
10467 : :
10468 : : /*
10469 : : * We cannot see a ReturningExpr in rule deparsing, only while
10470 : : * EXPLAINing a query plan (ReturningExpr nodes are only ever
10471 : : * adding during query rewriting). Just display the expression
10472 : : * returned (an expanded view column).
10473 : : */
10474 : 8 : get_rule_expr((Node *) retExpr->retexpr, context, showimplicit);
10475 : : }
10476 : 8 : break;
10477 : :
10478 : 2417 : case T_PartitionBoundSpec:
10479 : : {
10480 : 2417 : PartitionBoundSpec *spec = (PartitionBoundSpec *) node;
10481 : : ListCell *cell;
10482 : : char *sep;
10483 : :
10484 [ + + ]: 2417 : if (spec->is_default)
10485 : : {
10486 : 89 : appendStringInfoString(buf, "DEFAULT");
10487 : 89 : break;
10488 : : }
10489 : :
10490 [ + + + - ]: 2328 : switch (spec->strategy)
10491 : : {
10492 : 165 : case PARTITION_STRATEGY_HASH:
10493 : : Assert(spec->modulus > 0 && spec->remainder >= 0);
10494 : : Assert(spec->modulus > spec->remainder);
10495 : :
10496 : 165 : appendStringInfoString(buf, "FOR VALUES");
10497 : 165 : appendStringInfo(buf, " WITH (modulus %d, remainder %d)",
10498 : : spec->modulus, spec->remainder);
10499 : 165 : break;
10500 : :
10501 : 820 : case PARTITION_STRATEGY_LIST:
10502 : : Assert(spec->listdatums != NIL);
10503 : :
10504 : 820 : appendStringInfoString(buf, "FOR VALUES IN (");
10505 : 820 : sep = "";
10506 [ + - + + : 2114 : foreach(cell, spec->listdatums)
+ + ]
10507 : : {
10508 : 1294 : Const *val = lfirst_node(Const, cell);
10509 : :
10510 : 1294 : appendStringInfoString(buf, sep);
10511 : 1294 : get_const_expr(val, context, -1);
10512 : 1294 : sep = ", ";
10513 : : }
10514 : :
10515 : 820 : appendStringInfoChar(buf, ')');
10516 : 820 : break;
10517 : :
10518 : 1343 : case PARTITION_STRATEGY_RANGE:
10519 : : Assert(spec->lowerdatums != NIL &&
10520 : : spec->upperdatums != NIL &&
10521 : : list_length(spec->lowerdatums) ==
10522 : : list_length(spec->upperdatums));
10523 : :
10524 : 1343 : appendStringInfo(buf, "FOR VALUES FROM %s TO %s",
10525 : : get_range_partbound_string(spec->lowerdatums),
10526 : : get_range_partbound_string(spec->upperdatums));
10527 : 1343 : break;
10528 : :
10529 : 0 : default:
10530 [ # # ]: 0 : elog(ERROR, "unrecognized partition strategy: %d",
10531 : : (int) spec->strategy);
10532 : : break;
10533 : : }
10534 : : }
10535 : 2328 : break;
10536 : :
10537 : 104 : case T_JsonValueExpr:
10538 : : {
10539 : 104 : JsonValueExpr *jve = (JsonValueExpr *) node;
10540 : :
10541 : 104 : get_rule_expr((Node *) jve->raw_expr, context, false);
10542 : 104 : get_json_format(jve->format, context->buf);
10543 : : }
10544 : 104 : break;
10545 : :
10546 : 188 : case T_JsonConstructorExpr:
10547 : 188 : get_json_constructor((JsonConstructorExpr *) node, context, false);
10548 : 188 : break;
10549 : :
10550 : 52 : case T_JsonIsPredicate:
10551 : : {
10552 : 52 : JsonIsPredicate *pred = (JsonIsPredicate *) node;
10553 : :
10554 [ + + ]: 52 : if (!PRETTY_PAREN(context))
10555 : 20 : appendStringInfoChar(context->buf, '(');
10556 : :
10557 : 52 : get_rule_expr_paren(pred->expr, context, true, node);
10558 : :
10559 : 52 : appendStringInfoString(context->buf, " IS JSON");
10560 : :
10561 : : /* TODO: handle FORMAT clause */
10562 : :
10563 [ + + + + ]: 52 : switch (pred->item_type)
10564 : : {
10565 : 8 : case JS_TYPE_SCALAR:
10566 : 8 : appendStringInfoString(context->buf, " SCALAR");
10567 : 8 : break;
10568 : 8 : case JS_TYPE_ARRAY:
10569 : 8 : appendStringInfoString(context->buf, " ARRAY");
10570 : 8 : break;
10571 : 8 : case JS_TYPE_OBJECT:
10572 : 8 : appendStringInfoString(context->buf, " OBJECT");
10573 : 8 : break;
10574 : 28 : default:
10575 : 28 : break;
10576 : : }
10577 : :
10578 [ + + ]: 52 : if (pred->unique_keys)
10579 : 20 : appendStringInfoString(context->buf, " WITH UNIQUE KEYS");
10580 : :
10581 [ + + ]: 52 : if (!PRETTY_PAREN(context))
10582 : 20 : appendStringInfoChar(context->buf, ')');
10583 : : }
10584 : 52 : break;
10585 : :
10586 : 40 : case T_JsonExpr:
10587 : : {
10588 : 40 : JsonExpr *jexpr = (JsonExpr *) node;
10589 : :
10590 [ + + + - ]: 40 : switch (jexpr->op)
10591 : : {
10592 : 8 : case JSON_EXISTS_OP:
10593 : 8 : appendStringInfoString(buf, "JSON_EXISTS(");
10594 : 8 : break;
10595 : 24 : case JSON_QUERY_OP:
10596 : 24 : appendStringInfoString(buf, "JSON_QUERY(");
10597 : 24 : break;
10598 : 8 : case JSON_VALUE_OP:
10599 : 8 : appendStringInfoString(buf, "JSON_VALUE(");
10600 : 8 : break;
10601 : 0 : default:
10602 [ # # ]: 0 : elog(ERROR, "unrecognized JsonExpr op: %d",
10603 : : (int) jexpr->op);
10604 : : }
10605 : :
10606 : 40 : get_rule_expr(jexpr->formatted_expr, context, showimplicit);
10607 : :
10608 : 40 : appendStringInfoString(buf, ", ");
10609 : :
10610 : 40 : get_json_path_spec(jexpr->path_spec, context, showimplicit);
10611 : :
10612 [ + + ]: 40 : if (jexpr->passing_values)
10613 : : {
10614 : : ListCell *lc1,
10615 : : *lc2;
10616 : 8 : bool needcomma = false;
10617 : :
10618 : 8 : appendStringInfoString(buf, " PASSING ");
10619 : :
10620 [ + - + + : 32 : forboth(lc1, jexpr->passing_names,
+ - + + +
+ + - +
+ ]
10621 : : lc2, jexpr->passing_values)
10622 : : {
10623 [ + + ]: 24 : if (needcomma)
10624 : 16 : appendStringInfoString(buf, ", ");
10625 : 24 : needcomma = true;
10626 : :
10627 : 24 : get_rule_expr((Node *) lfirst(lc2), context, showimplicit);
10628 : 24 : appendStringInfo(buf, " AS %s",
10629 : 24 : quote_identifier(lfirst_node(String, lc1)->sval));
10630 : : }
10631 : : }
10632 : :
10633 [ + + ]: 40 : if (jexpr->op != JSON_EXISTS_OP ||
10634 [ - + ]: 8 : jexpr->returning->typid != BOOLOID)
10635 : 32 : get_json_returning(jexpr->returning, context->buf,
10636 : 32 : jexpr->op == JSON_QUERY_OP);
10637 : :
10638 : 40 : get_json_expr_options(jexpr, context,
10639 [ + + ]: 40 : jexpr->op != JSON_EXISTS_OP ?
10640 : : JSON_BEHAVIOR_NULL :
10641 : : JSON_BEHAVIOR_FALSE);
10642 : :
10643 : 40 : appendStringInfoChar(buf, ')');
10644 : : }
10645 : 40 : break;
10646 : :
10647 : 1980 : case T_List:
10648 : : {
10649 : : char *sep;
10650 : : ListCell *l;
10651 : :
10652 : 1980 : sep = "";
10653 [ + - + + : 5601 : foreach(l, (List *) node)
+ + ]
10654 : : {
10655 : 3621 : appendStringInfoString(buf, sep);
10656 : 3621 : get_rule_expr((Node *) lfirst(l), context, showimplicit);
10657 : 3621 : sep = ", ";
10658 : : }
10659 : : }
10660 : 1980 : break;
10661 : :
10662 : 52 : case T_TableFunc:
10663 : 52 : get_tablefunc((TableFunc *) node, context, showimplicit);
10664 : 52 : break;
10665 : :
10666 : 0 : default:
10667 [ # # ]: 0 : elog(ERROR, "unrecognized node type: %d", (int) nodeTag(node));
10668 : : break;
10669 : : }
10670 : : }
10671 : :
10672 : : /*
10673 : : * get_rule_expr_toplevel - Parse back a toplevel expression
10674 : : *
10675 : : * Same as get_rule_expr(), except that if the expr is just a Var, we pass
10676 : : * istoplevel = true not false to get_variable(). This causes whole-row Vars
10677 : : * to get printed with decoration that will prevent expansion of "*".
10678 : : * We need to use this in contexts such as ROW() and VALUES(), where the
10679 : : * parser would expand "foo.*" appearing at top level. (In principle we'd
10680 : : * use this in get_target_list() too, but that has additional worries about
10681 : : * whether to print AS, so it needs to invoke get_variable() directly anyway.)
10682 : : */
10683 : : static void
10684 : 2195 : get_rule_expr_toplevel(Node *node, deparse_context *context,
10685 : : bool showimplicit)
10686 : : {
10687 [ + - + + ]: 2195 : if (node && IsA(node, Var))
10688 : 830 : (void) get_variable((Var *) node, 0, true, context);
10689 : : else
10690 : 1365 : get_rule_expr(node, context, showimplicit);
10691 : 2195 : }
10692 : :
10693 : : /*
10694 : : * get_rule_list_toplevel - Parse back a list of toplevel expressions
10695 : : *
10696 : : * Apply get_rule_expr_toplevel() to each element of a List.
10697 : : *
10698 : : * This adds commas between the expressions, but caller is responsible
10699 : : * for printing surrounding decoration.
10700 : : */
10701 : : static void
10702 : 358 : get_rule_list_toplevel(List *lst, deparse_context *context,
10703 : : bool showimplicit)
10704 : : {
10705 : : const char *sep;
10706 : : ListCell *lc;
10707 : :
10708 : 358 : sep = "";
10709 [ + - + + : 1183 : foreach(lc, lst)
+ + ]
10710 : : {
10711 : 825 : Node *e = (Node *) lfirst(lc);
10712 : :
10713 : 825 : appendStringInfoString(context->buf, sep);
10714 : 825 : get_rule_expr_toplevel(e, context, showimplicit);
10715 : 825 : sep = ", ";
10716 : : }
10717 : 358 : }
10718 : :
10719 : : /*
10720 : : * get_rule_expr_funccall - Parse back a function-call expression
10721 : : *
10722 : : * Same as get_rule_expr(), except that we guarantee that the output will
10723 : : * look like a function call, or like one of the things the grammar treats as
10724 : : * equivalent to a function call (see the func_expr_windowless production).
10725 : : * This is needed in places where the grammar uses func_expr_windowless and
10726 : : * you can't substitute a parenthesized a_expr. If what we have isn't going
10727 : : * to look like a function call, wrap it in a dummy CAST() expression, which
10728 : : * will satisfy the grammar --- and, indeed, is likely what the user wrote to
10729 : : * produce such a thing.
10730 : : */
10731 : : static void
10732 : 572 : get_rule_expr_funccall(Node *node, deparse_context *context,
10733 : : bool showimplicit)
10734 : : {
10735 [ + + ]: 572 : if (looks_like_function(node))
10736 : 564 : get_rule_expr(node, context, showimplicit);
10737 : : else
10738 : : {
10739 : 8 : StringInfo buf = context->buf;
10740 : :
10741 : 8 : appendStringInfoString(buf, "CAST(");
10742 : : /* no point in showing any top-level implicit cast */
10743 : 8 : get_rule_expr(node, context, false);
10744 : 8 : appendStringInfo(buf, " AS %s)",
10745 : : format_type_with_typemod(exprType(node),
10746 : : exprTypmod(node)));
10747 : : }
10748 : 572 : }
10749 : :
10750 : : /*
10751 : : * Helper function to identify node types that satisfy func_expr_windowless.
10752 : : * If in doubt, "false" is always a safe answer.
10753 : : */
10754 : : static bool
10755 : 1352 : looks_like_function(Node *node)
10756 : : {
10757 [ - + ]: 1352 : if (node == NULL)
10758 : 0 : return false; /* probably shouldn't happen */
10759 [ + + + ]: 1352 : switch (nodeTag(node))
10760 : : {
10761 : 584 : case T_FuncExpr:
10762 : : /* OK, unless it's going to deparse as a cast */
10763 [ + + ]: 596 : return (((FuncExpr *) node)->funcformat == COERCE_EXPLICIT_CALL ||
10764 [ + + ]: 12 : ((FuncExpr *) node)->funcformat == COERCE_SQL_SYNTAX);
10765 : 72 : case T_NullIfExpr:
10766 : : case T_CoalesceExpr:
10767 : : case T_MinMaxExpr:
10768 : : case T_SQLValueFunction:
10769 : : case T_XmlExpr:
10770 : : case T_JsonExpr:
10771 : : /* these are all accepted by func_expr_common_subexpr */
10772 : 72 : return true;
10773 : 696 : default:
10774 : 696 : break;
10775 : : }
10776 : 696 : return false;
10777 : : }
10778 : :
10779 : :
10780 : : /*
10781 : : * get_oper_expr - Parse back an OpExpr node
10782 : : */
10783 : : static void
10784 : 41659 : get_oper_expr(OpExpr *expr, deparse_context *context)
10785 : : {
10786 : 41659 : StringInfo buf = context->buf;
10787 : 41659 : Oid opno = expr->opno;
10788 : 41659 : List *args = expr->args;
10789 : :
10790 [ + + ]: 41659 : if (!PRETTY_PAREN(context))
10791 : 40111 : appendStringInfoChar(buf, '(');
10792 [ + + ]: 41659 : if (list_length(args) == 2)
10793 : : {
10794 : : /* binary operator */
10795 : 41639 : Node *arg1 = (Node *) linitial(args);
10796 : 41639 : Node *arg2 = (Node *) lsecond(args);
10797 : :
10798 : 41639 : get_rule_expr_paren(arg1, context, true, (Node *) expr);
10799 : 41639 : appendStringInfo(buf, " %s ",
10800 : : generate_operator_name(opno,
10801 : : exprType(arg1),
10802 : : exprType(arg2)));
10803 : 41639 : get_rule_expr_paren(arg2, context, true, (Node *) expr);
10804 : : }
10805 : : else
10806 : : {
10807 : : /* prefix operator */
10808 : 20 : Node *arg = (Node *) linitial(args);
10809 : :
10810 : 20 : appendStringInfo(buf, "%s ",
10811 : : generate_operator_name(opno,
10812 : : InvalidOid,
10813 : : exprType(arg)));
10814 : 20 : get_rule_expr_paren(arg, context, true, (Node *) expr);
10815 : : }
10816 [ + + ]: 41659 : if (!PRETTY_PAREN(context))
10817 : 40111 : appendStringInfoChar(buf, ')');
10818 : 41659 : }
10819 : :
10820 : : /*
10821 : : * get_func_expr - Parse back a FuncExpr node
10822 : : */
10823 : : static void
10824 : 8062 : get_func_expr(FuncExpr *expr, deparse_context *context,
10825 : : bool showimplicit)
10826 : : {
10827 : 8062 : StringInfo buf = context->buf;
10828 : 8062 : Oid funcoid = expr->funcid;
10829 : : Oid argtypes[FUNC_MAX_ARGS];
10830 : : int nargs;
10831 : : List *argnames;
10832 : : bool use_variadic;
10833 : : ListCell *l;
10834 : :
10835 : : /*
10836 : : * If the function call came from an implicit coercion, then just show the
10837 : : * first argument --- unless caller wants to see implicit coercions.
10838 : : */
10839 [ + + + + ]: 8062 : if (expr->funcformat == COERCE_IMPLICIT_CAST && !showimplicit)
10840 : : {
10841 : 769 : get_rule_expr_paren((Node *) linitial(expr->args), context,
10842 : : false, (Node *) expr);
10843 : 1993 : return;
10844 : : }
10845 : :
10846 : : /*
10847 : : * If the function call came from a cast, then show the first argument
10848 : : * plus an explicit cast operation.
10849 : : */
10850 [ + + ]: 7293 : if (expr->funcformat == COERCE_EXPLICIT_CAST ||
10851 [ + + ]: 6864 : expr->funcformat == COERCE_IMPLICIT_CAST)
10852 : : {
10853 : 1108 : Node *arg = linitial(expr->args);
10854 : 1108 : Oid rettype = expr->funcresulttype;
10855 : : int32 coercedTypmod;
10856 : :
10857 : : /* Get the typmod if this is a length-coercion function */
10858 : 1108 : (void) exprIsLengthCoercion((Node *) expr, &coercedTypmod);
10859 : :
10860 : 1108 : get_coercion_expr(arg, context,
10861 : : rettype, coercedTypmod,
10862 : : (Node *) expr);
10863 : :
10864 : 1108 : return;
10865 : : }
10866 : :
10867 : : /*
10868 : : * If the function was called using one of the SQL spec's random special
10869 : : * syntaxes, try to reproduce that. If we don't recognize the function,
10870 : : * fall through.
10871 : : */
10872 [ + + ]: 6185 : if (expr->funcformat == COERCE_SQL_SYNTAX)
10873 : : {
10874 [ + + ]: 120 : if (get_func_sql_syntax(expr, context))
10875 : 116 : return;
10876 : : }
10877 : :
10878 : : /*
10879 : : * Normal function: display as proname(args). First we need to extract
10880 : : * the argument datatypes.
10881 : : */
10882 [ - + ]: 6069 : if (list_length(expr->args) > FUNC_MAX_ARGS)
10883 [ # # ]: 0 : ereport(ERROR,
10884 : : (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
10885 : : errmsg("too many arguments")));
10886 : 6069 : nargs = 0;
10887 : 6069 : argnames = NIL;
10888 [ + + + + : 12697 : foreach(l, expr->args)
+ + ]
10889 : : {
10890 : 6628 : Node *arg = (Node *) lfirst(l);
10891 : :
10892 [ + + ]: 6628 : if (IsA(arg, NamedArgExpr))
10893 : 20 : argnames = lappend(argnames, ((NamedArgExpr *) arg)->name);
10894 : 6628 : argtypes[nargs] = exprType(arg);
10895 : 6628 : nargs++;
10896 : : }
10897 : :
10898 : 6069 : appendStringInfo(buf, "%s(",
10899 : : generate_function_name(funcoid, nargs,
10900 : : argnames, argtypes,
10901 : 6069 : expr->funcvariadic,
10902 : : &use_variadic,
10903 : 6069 : context->inGroupBy));
10904 : 6069 : nargs = 0;
10905 [ + + + + : 12697 : foreach(l, expr->args)
+ + ]
10906 : : {
10907 [ + + ]: 6628 : if (nargs++ > 0)
10908 : 1320 : appendStringInfoString(buf, ", ");
10909 [ + + + - ]: 6628 : if (use_variadic && lnext(expr->args, l) == NULL)
10910 : 7 : appendStringInfoString(buf, "VARIADIC ");
10911 : 6628 : get_rule_expr((Node *) lfirst(l), context, true);
10912 : : }
10913 : 6069 : appendStringInfoChar(buf, ')');
10914 : : }
10915 : :
10916 : : /*
10917 : : * get_agg_expr - Parse back an Aggref node
10918 : : */
10919 : : static void
10920 : 3164 : get_agg_expr(Aggref *aggref, deparse_context *context,
10921 : : Aggref *original_aggref)
10922 : : {
10923 : 3164 : get_agg_expr_helper(aggref, context, original_aggref, NULL, NULL,
10924 : : false);
10925 : 3164 : }
10926 : :
10927 : : /*
10928 : : * get_agg_expr_helper - subroutine for get_agg_expr and
10929 : : * get_json_agg_constructor
10930 : : */
10931 : : static void
10932 : 3232 : get_agg_expr_helper(Aggref *aggref, deparse_context *context,
10933 : : Aggref *original_aggref, const char *funcname,
10934 : : const char *options, bool is_json_objectagg)
10935 : : {
10936 : 3232 : StringInfo buf = context->buf;
10937 : : Oid argtypes[FUNC_MAX_ARGS];
10938 : : int nargs;
10939 : 3232 : bool use_variadic = false;
10940 : :
10941 : : /*
10942 : : * For a combining aggregate, we look up and deparse the corresponding
10943 : : * partial aggregate instead. This is necessary because our input
10944 : : * argument list has been replaced; the new argument list always has just
10945 : : * one element, which will point to a partial Aggref that supplies us with
10946 : : * transition states to combine.
10947 : : */
10948 [ + + ]: 3232 : if (DO_AGGSPLIT_COMBINE(aggref->aggsplit))
10949 : : {
10950 : : TargetEntry *tle;
10951 : :
10952 : : Assert(list_length(aggref->args) == 1);
10953 : 524 : tle = linitial_node(TargetEntry, aggref->args);
10954 : 524 : resolve_special_varno((Node *) tle->expr, context,
10955 : : get_agg_combine_expr, original_aggref);
10956 : 524 : return;
10957 : : }
10958 : :
10959 : : /*
10960 : : * Mark as PARTIAL, if appropriate. We look to the original aggref so as
10961 : : * to avoid printing this when recursing from the code just above.
10962 : : */
10963 [ + + ]: 2708 : if (DO_AGGSPLIT_SKIPFINAL(original_aggref->aggsplit))
10964 : 1164 : appendStringInfoString(buf, "PARTIAL ");
10965 : :
10966 : : /* Extract the argument types as seen by the parser */
10967 : 2708 : nargs = get_aggregate_argtypes(aggref, argtypes);
10968 : :
10969 [ + + ]: 2708 : if (!funcname)
10970 : 2640 : funcname = generate_function_name(aggref->aggfnoid, nargs, NIL,
10971 : 2640 : argtypes, aggref->aggvariadic,
10972 : : &use_variadic,
10973 : 2640 : context->inGroupBy);
10974 : :
10975 : : /* Print the aggregate name, schema-qualified if needed */
10976 : 2708 : appendStringInfo(buf, "%s(%s", funcname,
10977 [ + + ]: 2708 : (aggref->aggdistinct != NIL) ? "DISTINCT " : "");
10978 : :
10979 [ + + ]: 2708 : if (AGGKIND_IS_ORDERED_SET(aggref->aggkind))
10980 : : {
10981 : : /*
10982 : : * Ordered-set aggregates do not use "*" syntax. Also, we needn't
10983 : : * worry about inserting VARIADIC. So we can just dump the direct
10984 : : * args as-is.
10985 : : */
10986 : : Assert(!aggref->aggvariadic);
10987 : 17 : get_rule_expr((Node *) aggref->aggdirectargs, context, true);
10988 : : Assert(aggref->aggorder != NIL);
10989 : 17 : appendStringInfoString(buf, ") WITHIN GROUP (ORDER BY ");
10990 : 17 : get_rule_orderby(aggref->aggorder, aggref->args, false, context);
10991 : : }
10992 : : else
10993 : : {
10994 : : /* aggstar can be set only in zero-argument aggregates */
10995 [ + + ]: 2691 : if (aggref->aggstar)
10996 : 817 : appendStringInfoChar(buf, '*');
10997 : : else
10998 : : {
10999 : : ListCell *l;
11000 : : int i;
11001 : :
11002 : 1874 : i = 0;
11003 [ + - + + : 3887 : foreach(l, aggref->args)
+ + ]
11004 : : {
11005 : 2013 : TargetEntry *tle = (TargetEntry *) lfirst(l);
11006 : 2013 : Node *arg = (Node *) tle->expr;
11007 : :
11008 : : Assert(!IsA(arg, NamedArgExpr));
11009 [ + + ]: 2013 : if (tle->resjunk)
11010 : 31 : continue;
11011 [ + + ]: 1982 : if (i++ > 0)
11012 : : {
11013 [ + + ]: 108 : if (is_json_objectagg)
11014 : : {
11015 : : /*
11016 : : * the ABSENT ON NULL and WITH UNIQUE args are printed
11017 : : * separately, so ignore them here
11018 : : */
11019 [ - + ]: 28 : if (i > 2)
11020 : 0 : break;
11021 : :
11022 : 28 : appendStringInfoString(buf, " : ");
11023 : : }
11024 : : else
11025 : 80 : appendStringInfoString(buf, ", ");
11026 : : }
11027 [ + + + - ]: 1982 : if (use_variadic && i == nargs)
11028 : 4 : appendStringInfoString(buf, "VARIADIC ");
11029 : 1982 : get_rule_expr(arg, context, true);
11030 : : }
11031 : : }
11032 : :
11033 [ + + ]: 2691 : if (aggref->aggorder != NIL)
11034 : : {
11035 : 78 : appendStringInfoString(buf, " ORDER BY ");
11036 : 78 : get_rule_orderby(aggref->aggorder, aggref->args, false, context);
11037 : : }
11038 : : }
11039 : :
11040 [ + + ]: 2708 : if (options)
11041 : 68 : appendStringInfoString(buf, options);
11042 : :
11043 [ + + ]: 2708 : if (aggref->aggfilter != NULL)
11044 : : {
11045 : 28 : appendStringInfoString(buf, ") FILTER (WHERE ");
11046 : 28 : get_rule_expr((Node *) aggref->aggfilter, context, false);
11047 : : }
11048 : :
11049 : 2708 : appendStringInfoChar(buf, ')');
11050 : : }
11051 : :
11052 : : /*
11053 : : * This is a helper function for get_agg_expr(). It's used when we deparse
11054 : : * a combining Aggref; resolve_special_varno locates the corresponding partial
11055 : : * Aggref and then calls this.
11056 : : */
11057 : : static void
11058 : 524 : get_agg_combine_expr(Node *node, deparse_context *context, void *callback_arg)
11059 : : {
11060 : : Aggref *aggref;
11061 : 524 : Aggref *original_aggref = callback_arg;
11062 : :
11063 [ - + ]: 524 : if (!IsA(node, Aggref))
11064 [ # # ]: 0 : elog(ERROR, "combining Aggref does not point to an Aggref");
11065 : :
11066 : 524 : aggref = (Aggref *) node;
11067 : 524 : get_agg_expr(aggref, context, original_aggref);
11068 : 524 : }
11069 : :
11070 : : /*
11071 : : * get_windowfunc_expr - Parse back a WindowFunc node
11072 : : */
11073 : : static void
11074 : 254 : get_windowfunc_expr(WindowFunc *wfunc, deparse_context *context)
11075 : : {
11076 : 254 : get_windowfunc_expr_helper(wfunc, context, NULL, NULL, false);
11077 : 254 : }
11078 : :
11079 : :
11080 : : /*
11081 : : * get_windowfunc_expr_helper - subroutine for get_windowfunc_expr and
11082 : : * get_json_agg_constructor
11083 : : */
11084 : : static void
11085 : 266 : get_windowfunc_expr_helper(WindowFunc *wfunc, deparse_context *context,
11086 : : const char *funcname, const char *options,
11087 : : bool is_json_objectagg)
11088 : : {
11089 : 266 : StringInfo buf = context->buf;
11090 : : Oid argtypes[FUNC_MAX_ARGS];
11091 : : int nargs;
11092 : : List *argnames;
11093 : : ListCell *l;
11094 : :
11095 [ - + ]: 266 : if (list_length(wfunc->args) > FUNC_MAX_ARGS)
11096 [ # # ]: 0 : ereport(ERROR,
11097 : : (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
11098 : : errmsg("too many arguments")));
11099 : 266 : nargs = 0;
11100 : 266 : argnames = NIL;
11101 [ + + + + : 440 : foreach(l, wfunc->args)
+ + ]
11102 : : {
11103 : 174 : Node *arg = (Node *) lfirst(l);
11104 : :
11105 [ - + ]: 174 : if (IsA(arg, NamedArgExpr))
11106 : 0 : argnames = lappend(argnames, ((NamedArgExpr *) arg)->name);
11107 : 174 : argtypes[nargs] = exprType(arg);
11108 : 174 : nargs++;
11109 : : }
11110 : :
11111 [ + + ]: 266 : if (!funcname)
11112 : 254 : funcname = generate_function_name(wfunc->winfnoid, nargs, argnames,
11113 : : argtypes, false, NULL,
11114 : 254 : context->inGroupBy);
11115 : :
11116 : 266 : appendStringInfo(buf, "%s(", funcname);
11117 : :
11118 : : /* winstar can be set only in zero-argument aggregates */
11119 [ + + ]: 266 : if (wfunc->winstar)
11120 : 28 : appendStringInfoChar(buf, '*');
11121 : : else
11122 : : {
11123 [ + + ]: 238 : if (is_json_objectagg)
11124 : : {
11125 : 4 : get_rule_expr((Node *) linitial(wfunc->args), context, false);
11126 : 4 : appendStringInfoString(buf, " : ");
11127 : 4 : get_rule_expr((Node *) lsecond(wfunc->args), context, false);
11128 : : }
11129 : : else
11130 : 234 : get_rule_expr((Node *) wfunc->args, context, true);
11131 : : }
11132 : :
11133 [ + + ]: 266 : if (options)
11134 : 12 : appendStringInfoString(buf, options);
11135 : :
11136 [ - + ]: 266 : if (wfunc->aggfilter != NULL)
11137 : : {
11138 : 0 : appendStringInfoString(buf, ") FILTER (WHERE ");
11139 : 0 : get_rule_expr((Node *) wfunc->aggfilter, context, false);
11140 : : }
11141 : :
11142 : 266 : appendStringInfoString(buf, ") ");
11143 : :
11144 [ + + ]: 266 : if (wfunc->ignore_nulls == PARSER_IGNORE_NULLS)
11145 : 4 : appendStringInfoString(buf, "IGNORE NULLS ");
11146 : :
11147 : 266 : appendStringInfoString(buf, "OVER ");
11148 : :
11149 [ + + ]: 266 : if (context->windowClause)
11150 : : {
11151 : : /* Query-decompilation case: search the windowClause list */
11152 [ + - + - : 40 : foreach(l, context->windowClause)
+ - ]
11153 : : {
11154 : 40 : WindowClause *wc = (WindowClause *) lfirst(l);
11155 : :
11156 [ + - ]: 40 : if (wc->winref == wfunc->winref)
11157 : : {
11158 [ + + ]: 40 : if (wc->name)
11159 : 12 : appendStringInfoString(buf, quote_identifier(wc->name));
11160 : : else
11161 : 28 : get_rule_windowspec(wc, context->targetList, context);
11162 : 40 : break;
11163 : : }
11164 : : }
11165 [ - + ]: 40 : if (l == NULL)
11166 [ # # ]: 0 : elog(ERROR, "could not find window clause for winref %u",
11167 : : wfunc->winref);
11168 : : }
11169 : : else
11170 : : {
11171 : : /*
11172 : : * In EXPLAIN, search the namespace stack for a matching WindowAgg
11173 : : * node (probably it's always the first entry), and print winname.
11174 : : */
11175 [ + - + - : 226 : foreach(l, context->namespaces)
+ - ]
11176 : : {
11177 : 226 : deparse_namespace *dpns = (deparse_namespace *) lfirst(l);
11178 : :
11179 [ + - + - ]: 226 : if (dpns->plan && IsA(dpns->plan, WindowAgg))
11180 : : {
11181 : 226 : WindowAgg *wagg = (WindowAgg *) dpns->plan;
11182 : :
11183 [ + - ]: 226 : if (wagg->winref == wfunc->winref)
11184 : : {
11185 : 226 : appendStringInfoString(buf, quote_identifier(wagg->winname));
11186 : 226 : break;
11187 : : }
11188 : : }
11189 : : }
11190 [ - + ]: 226 : if (l == NULL)
11191 [ # # ]: 0 : elog(ERROR, "could not find window clause for winref %u",
11192 : : wfunc->winref);
11193 : : }
11194 : 266 : }
11195 : :
11196 : : /*
11197 : : * get_func_sql_syntax - Parse back a SQL-syntax function call
11198 : : *
11199 : : * Returns true if we successfully deparsed, false if we did not
11200 : : * recognize the function.
11201 : : */
11202 : : static bool
11203 : 120 : get_func_sql_syntax(FuncExpr *expr, deparse_context *context)
11204 : : {
11205 : 120 : StringInfo buf = context->buf;
11206 : 120 : Oid funcoid = expr->funcid;
11207 : :
11208 [ + + + + : 120 : switch (funcoid)
+ + + + +
+ + + + +
+ - + ]
11209 : : {
11210 : 16 : case F_TIMEZONE_INTERVAL_TIMESTAMP:
11211 : : case F_TIMEZONE_INTERVAL_TIMESTAMPTZ:
11212 : : case F_TIMEZONE_INTERVAL_TIMETZ:
11213 : : case F_TIMEZONE_TEXT_TIMESTAMP:
11214 : : case F_TIMEZONE_TEXT_TIMESTAMPTZ:
11215 : : case F_TIMEZONE_TEXT_TIMETZ:
11216 : : /* AT TIME ZONE ... note reversed argument order */
11217 : 16 : appendStringInfoChar(buf, '(');
11218 : 16 : get_rule_expr_paren((Node *) lsecond(expr->args), context, false,
11219 : : (Node *) expr);
11220 : 16 : appendStringInfoString(buf, " AT TIME ZONE ");
11221 : 16 : get_rule_expr_paren((Node *) linitial(expr->args), context, false,
11222 : : (Node *) expr);
11223 : 16 : appendStringInfoChar(buf, ')');
11224 : 16 : return true;
11225 : :
11226 : 12 : case F_TIMEZONE_TIMESTAMP:
11227 : : case F_TIMEZONE_TIMESTAMPTZ:
11228 : : case F_TIMEZONE_TIMETZ:
11229 : : /* AT LOCAL */
11230 : 12 : appendStringInfoChar(buf, '(');
11231 : 12 : get_rule_expr_paren((Node *) linitial(expr->args), context, false,
11232 : : (Node *) expr);
11233 : 12 : appendStringInfoString(buf, " AT LOCAL)");
11234 : 12 : return true;
11235 : :
11236 : 4 : case F_OVERLAPS_TIMESTAMPTZ_INTERVAL_TIMESTAMPTZ_INTERVAL:
11237 : : case F_OVERLAPS_TIMESTAMPTZ_INTERVAL_TIMESTAMPTZ_TIMESTAMPTZ:
11238 : : case F_OVERLAPS_TIMESTAMPTZ_TIMESTAMPTZ_TIMESTAMPTZ_INTERVAL:
11239 : : case F_OVERLAPS_TIMESTAMPTZ_TIMESTAMPTZ_TIMESTAMPTZ_TIMESTAMPTZ:
11240 : : case F_OVERLAPS_TIMESTAMP_INTERVAL_TIMESTAMP_INTERVAL:
11241 : : case F_OVERLAPS_TIMESTAMP_INTERVAL_TIMESTAMP_TIMESTAMP:
11242 : : case F_OVERLAPS_TIMESTAMP_TIMESTAMP_TIMESTAMP_INTERVAL:
11243 : : case F_OVERLAPS_TIMESTAMP_TIMESTAMP_TIMESTAMP_TIMESTAMP:
11244 : : case F_OVERLAPS_TIMETZ_TIMETZ_TIMETZ_TIMETZ:
11245 : : case F_OVERLAPS_TIME_INTERVAL_TIME_INTERVAL:
11246 : : case F_OVERLAPS_TIME_INTERVAL_TIME_TIME:
11247 : : case F_OVERLAPS_TIME_TIME_TIME_INTERVAL:
11248 : : case F_OVERLAPS_TIME_TIME_TIME_TIME:
11249 : : /* (x1, x2) OVERLAPS (y1, y2) */
11250 : 4 : appendStringInfoString(buf, "((");
11251 : 4 : get_rule_expr((Node *) linitial(expr->args), context, false);
11252 : 4 : appendStringInfoString(buf, ", ");
11253 : 4 : get_rule_expr((Node *) lsecond(expr->args), context, false);
11254 : 4 : appendStringInfoString(buf, ") OVERLAPS (");
11255 : 4 : get_rule_expr((Node *) lthird(expr->args), context, false);
11256 : 4 : appendStringInfoString(buf, ", ");
11257 : 4 : get_rule_expr((Node *) lfourth(expr->args), context, false);
11258 : 4 : appendStringInfoString(buf, "))");
11259 : 4 : return true;
11260 : :
11261 : 12 : case F_EXTRACT_TEXT_DATE:
11262 : : case F_EXTRACT_TEXT_TIME:
11263 : : case F_EXTRACT_TEXT_TIMETZ:
11264 : : case F_EXTRACT_TEXT_TIMESTAMP:
11265 : : case F_EXTRACT_TEXT_TIMESTAMPTZ:
11266 : : case F_EXTRACT_TEXT_INTERVAL:
11267 : : /* EXTRACT (x FROM y) */
11268 : 12 : appendStringInfoString(buf, "EXTRACT(");
11269 : : {
11270 : 12 : Const *con = (Const *) linitial(expr->args);
11271 : :
11272 : : Assert(IsA(con, Const) &&
11273 : : con->consttype == TEXTOID &&
11274 : : !con->constisnull);
11275 : 12 : appendStringInfoString(buf, quote_identifier(TextDatumGetCString(con->constvalue)));
11276 : : }
11277 : 12 : appendStringInfoString(buf, " FROM ");
11278 : 12 : get_rule_expr((Node *) lsecond(expr->args), context, false);
11279 : 12 : appendStringInfoChar(buf, ')');
11280 : 12 : return true;
11281 : :
11282 : 8 : case F_IS_NORMALIZED:
11283 : : /* IS xxx NORMALIZED */
11284 : 8 : appendStringInfoChar(buf, '(');
11285 : 8 : get_rule_expr_paren((Node *) linitial(expr->args), context, false,
11286 : : (Node *) expr);
11287 : 8 : appendStringInfoString(buf, " IS");
11288 [ + + ]: 8 : if (list_length(expr->args) == 2)
11289 : : {
11290 : 4 : Const *con = (Const *) lsecond(expr->args);
11291 : :
11292 : : Assert(IsA(con, Const) &&
11293 : : con->consttype == TEXTOID &&
11294 : : !con->constisnull);
11295 : : /* NB: safe because no allowed words need quoted/escaped */
11296 : 4 : appendStringInfo(buf, " %s",
11297 : 4 : TextDatumGetCString(con->constvalue));
11298 : : }
11299 : 8 : appendStringInfoString(buf, " NORMALIZED)");
11300 : 8 : return true;
11301 : :
11302 : 4 : case F_PG_COLLATION_FOR:
11303 : : /* COLLATION FOR */
11304 : 4 : appendStringInfoString(buf, "COLLATION FOR (");
11305 : 4 : get_rule_expr((Node *) linitial(expr->args), context, false);
11306 : 4 : appendStringInfoChar(buf, ')');
11307 : 4 : return true;
11308 : :
11309 : 8 : case F_NORMALIZE:
11310 : : /* NORMALIZE() */
11311 : 8 : appendStringInfoString(buf, "NORMALIZE(");
11312 : 8 : get_rule_expr((Node *) linitial(expr->args), context, false);
11313 [ + + ]: 8 : if (list_length(expr->args) == 2)
11314 : : {
11315 : 4 : Const *con = (Const *) lsecond(expr->args);
11316 : :
11317 : : Assert(IsA(con, Const) &&
11318 : : con->consttype == TEXTOID &&
11319 : : !con->constisnull);
11320 : 4 : appendStringInfo(buf, ", %s",
11321 : 4 : TextDatumGetCString(con->constvalue));
11322 : : }
11323 : 8 : appendStringInfoChar(buf, ')');
11324 : 8 : return true;
11325 : :
11326 : 8 : case F_OVERLAY_BIT_BIT_INT4:
11327 : : case F_OVERLAY_BIT_BIT_INT4_INT4:
11328 : : case F_OVERLAY_BYTEA_BYTEA_INT4:
11329 : : case F_OVERLAY_BYTEA_BYTEA_INT4_INT4:
11330 : : case F_OVERLAY_TEXT_TEXT_INT4:
11331 : : case F_OVERLAY_TEXT_TEXT_INT4_INT4:
11332 : : /* OVERLAY() */
11333 : 8 : appendStringInfoString(buf, "OVERLAY(");
11334 : 8 : get_rule_expr((Node *) linitial(expr->args), context, false);
11335 : 8 : appendStringInfoString(buf, " PLACING ");
11336 : 8 : get_rule_expr((Node *) lsecond(expr->args), context, false);
11337 : 8 : appendStringInfoString(buf, " FROM ");
11338 : 8 : get_rule_expr((Node *) lthird(expr->args), context, false);
11339 [ + + ]: 8 : if (list_length(expr->args) == 4)
11340 : : {
11341 : 4 : appendStringInfoString(buf, " FOR ");
11342 : 4 : get_rule_expr((Node *) lfourth(expr->args), context, false);
11343 : : }
11344 : 8 : appendStringInfoChar(buf, ')');
11345 : 8 : return true;
11346 : :
11347 : 4 : case F_POSITION_BIT_BIT:
11348 : : case F_POSITION_BYTEA_BYTEA:
11349 : : case F_POSITION_TEXT_TEXT:
11350 : : /* POSITION() ... extra parens since args are b_expr not a_expr */
11351 : 4 : appendStringInfoString(buf, "POSITION((");
11352 : 4 : get_rule_expr((Node *) lsecond(expr->args), context, false);
11353 : 4 : appendStringInfoString(buf, ") IN (");
11354 : 4 : get_rule_expr((Node *) linitial(expr->args), context, false);
11355 : 4 : appendStringInfoString(buf, "))");
11356 : 4 : return true;
11357 : :
11358 : 4 : case F_SUBSTRING_BIT_INT4:
11359 : : case F_SUBSTRING_BIT_INT4_INT4:
11360 : : case F_SUBSTRING_BYTEA_INT4:
11361 : : case F_SUBSTRING_BYTEA_INT4_INT4:
11362 : : case F_SUBSTRING_TEXT_INT4:
11363 : : case F_SUBSTRING_TEXT_INT4_INT4:
11364 : : /* SUBSTRING FROM/FOR (i.e., integer-position variants) */
11365 : 4 : appendStringInfoString(buf, "SUBSTRING(");
11366 : 4 : get_rule_expr((Node *) linitial(expr->args), context, false);
11367 : 4 : appendStringInfoString(buf, " FROM ");
11368 : 4 : get_rule_expr((Node *) lsecond(expr->args), context, false);
11369 [ + - ]: 4 : if (list_length(expr->args) == 3)
11370 : : {
11371 : 4 : appendStringInfoString(buf, " FOR ");
11372 : 4 : get_rule_expr((Node *) lthird(expr->args), context, false);
11373 : : }
11374 : 4 : appendStringInfoChar(buf, ')');
11375 : 4 : return true;
11376 : :
11377 : 4 : case F_SUBSTRING_TEXT_TEXT_TEXT:
11378 : : /* SUBSTRING SIMILAR/ESCAPE */
11379 : 4 : appendStringInfoString(buf, "SUBSTRING(");
11380 : 4 : get_rule_expr((Node *) linitial(expr->args), context, false);
11381 : 4 : appendStringInfoString(buf, " SIMILAR ");
11382 : 4 : get_rule_expr((Node *) lsecond(expr->args), context, false);
11383 : 4 : appendStringInfoString(buf, " ESCAPE ");
11384 : 4 : get_rule_expr((Node *) lthird(expr->args), context, false);
11385 : 4 : appendStringInfoChar(buf, ')');
11386 : 4 : return true;
11387 : :
11388 : 8 : case F_BTRIM_BYTEA_BYTEA:
11389 : : case F_BTRIM_TEXT:
11390 : : case F_BTRIM_TEXT_TEXT:
11391 : : /* TRIM() */
11392 : 8 : appendStringInfoString(buf, "TRIM(BOTH");
11393 [ + - ]: 8 : if (list_length(expr->args) == 2)
11394 : : {
11395 : 8 : appendStringInfoChar(buf, ' ');
11396 : 8 : get_rule_expr((Node *) lsecond(expr->args), context, false);
11397 : : }
11398 : 8 : appendStringInfoString(buf, " FROM ");
11399 : 8 : get_rule_expr((Node *) linitial(expr->args), context, false);
11400 : 8 : appendStringInfoChar(buf, ')');
11401 : 8 : return true;
11402 : :
11403 : 8 : case F_LTRIM_BYTEA_BYTEA:
11404 : : case F_LTRIM_TEXT:
11405 : : case F_LTRIM_TEXT_TEXT:
11406 : : /* TRIM() */
11407 : 8 : appendStringInfoString(buf, "TRIM(LEADING");
11408 [ + - ]: 8 : if (list_length(expr->args) == 2)
11409 : : {
11410 : 8 : appendStringInfoChar(buf, ' ');
11411 : 8 : get_rule_expr((Node *) lsecond(expr->args), context, false);
11412 : : }
11413 : 8 : appendStringInfoString(buf, " FROM ");
11414 : 8 : get_rule_expr((Node *) linitial(expr->args), context, false);
11415 : 8 : appendStringInfoChar(buf, ')');
11416 : 8 : return true;
11417 : :
11418 : 8 : case F_RTRIM_BYTEA_BYTEA:
11419 : : case F_RTRIM_TEXT:
11420 : : case F_RTRIM_TEXT_TEXT:
11421 : : /* TRIM() */
11422 : 8 : appendStringInfoString(buf, "TRIM(TRAILING");
11423 [ + + ]: 8 : if (list_length(expr->args) == 2)
11424 : : {
11425 : 4 : appendStringInfoChar(buf, ' ');
11426 : 4 : get_rule_expr((Node *) lsecond(expr->args), context, false);
11427 : : }
11428 : 8 : appendStringInfoString(buf, " FROM ");
11429 : 8 : get_rule_expr((Node *) linitial(expr->args), context, false);
11430 : 8 : appendStringInfoChar(buf, ')');
11431 : 8 : return true;
11432 : :
11433 : 8 : case F_SYSTEM_USER:
11434 : 8 : appendStringInfoString(buf, "SYSTEM_USER");
11435 : 8 : return true;
11436 : :
11437 : 0 : case F_XMLEXISTS:
11438 : : /* XMLEXISTS ... extra parens because args are c_expr */
11439 : 0 : appendStringInfoString(buf, "XMLEXISTS((");
11440 : 0 : get_rule_expr((Node *) linitial(expr->args), context, false);
11441 : 0 : appendStringInfoString(buf, ") PASSING (");
11442 : 0 : get_rule_expr((Node *) lsecond(expr->args), context, false);
11443 : 0 : appendStringInfoString(buf, "))");
11444 : 0 : return true;
11445 : : }
11446 : 4 : return false;
11447 : : }
11448 : :
11449 : : /* ----------
11450 : : * get_coercion_expr
11451 : : *
11452 : : * Make a string representation of a value coerced to a specific type
11453 : : * ----------
11454 : : */
11455 : : static void
11456 : 3571 : get_coercion_expr(Node *arg, deparse_context *context,
11457 : : Oid resulttype, int32 resulttypmod,
11458 : : Node *parentNode)
11459 : : {
11460 : 3571 : StringInfo buf = context->buf;
11461 : :
11462 : : /*
11463 : : * Since parse_coerce.c doesn't immediately collapse application of
11464 : : * length-coercion functions to constants, what we'll typically see in
11465 : : * such cases is a Const with typmod -1 and a length-coercion function
11466 : : * right above it. Avoid generating redundant output. However, beware of
11467 : : * suppressing casts when the user actually wrote something like
11468 : : * 'foo'::text::char(3).
11469 : : *
11470 : : * Note: it might seem that we are missing the possibility of needing to
11471 : : * print a COLLATE clause for such a Const. However, a Const could only
11472 : : * have nondefault collation in a post-constant-folding tree, in which the
11473 : : * length coercion would have been folded too. See also the special
11474 : : * handling of CollateExpr in coerce_to_target_type(): any collation
11475 : : * marking will be above the coercion node, not below it.
11476 : : */
11477 [ + - + + ]: 3571 : if (arg && IsA(arg, Const) &&
11478 [ + + ]: 376 : ((Const *) arg)->consttype == resulttype &&
11479 [ + - ]: 16 : ((Const *) arg)->consttypmod == -1)
11480 : : {
11481 : : /* Show the constant without normal ::typename decoration */
11482 : 16 : get_const_expr((Const *) arg, context, -1);
11483 : : }
11484 : : else
11485 : : {
11486 [ + + ]: 3555 : if (!PRETTY_PAREN(context))
11487 : 3290 : appendStringInfoChar(buf, '(');
11488 : 3555 : get_rule_expr_paren(arg, context, false, parentNode);
11489 [ + + ]: 3555 : if (!PRETTY_PAREN(context))
11490 : 3290 : appendStringInfoChar(buf, ')');
11491 : : }
11492 : :
11493 : : /*
11494 : : * Never emit resulttype(arg) functional notation. A pg_proc entry could
11495 : : * take precedence, and a resulttype in pg_temp would require schema
11496 : : * qualification that format_type_with_typemod() would usually omit. We've
11497 : : * standardized on arg::resulttype, but CAST(arg AS resulttype) notation
11498 : : * would work fine.
11499 : : */
11500 : 3571 : appendStringInfo(buf, "::%s",
11501 : : format_type_with_typemod(resulttype, resulttypmod));
11502 : 3571 : }
11503 : :
11504 : : /* ----------
11505 : : * get_const_expr
11506 : : *
11507 : : * Make a string representation of a Const
11508 : : *
11509 : : * showtype can be -1 to never show "::typename" decoration, or +1 to always
11510 : : * show it, or 0 to show it only if the constant wouldn't be assumed to be
11511 : : * the right type by default.
11512 : : *
11513 : : * If the Const's collation isn't default for its type, show that too.
11514 : : * We mustn't do this when showtype is -1 (since that means the caller will
11515 : : * print "::typename", and we can't put a COLLATE clause in between). It's
11516 : : * caller's responsibility that collation isn't missed in such cases.
11517 : : * ----------
11518 : : */
11519 : : static void
11520 : 47097 : get_const_expr(Const *constval, deparse_context *context, int showtype)
11521 : : {
11522 : 47097 : StringInfo buf = context->buf;
11523 : : Oid typoutput;
11524 : : bool typIsVarlena;
11525 : : char *extval;
11526 : 47097 : bool needlabel = false;
11527 : :
11528 [ + + ]: 47097 : if (constval->constisnull)
11529 : : {
11530 : : /*
11531 : : * Always label the type of a NULL constant to prevent misdecisions
11532 : : * about type when reparsing.
11533 : : */
11534 : 951 : appendStringInfoString(buf, "NULL");
11535 [ + + ]: 951 : if (showtype >= 0)
11536 : : {
11537 : 920 : appendStringInfo(buf, "::%s",
11538 : : format_type_with_typemod(constval->consttype,
11539 : : constval->consttypmod));
11540 : 920 : get_const_collation(constval, context);
11541 : : }
11542 : 5770 : return;
11543 : : }
11544 : :
11545 : 46146 : getTypeOutputInfo(constval->consttype,
11546 : : &typoutput, &typIsVarlena);
11547 : :
11548 : 46146 : extval = OidOutputFunctionCall(typoutput, constval->constvalue);
11549 : :
11550 [ + + + + ]: 46146 : switch (constval->consttype)
11551 : : {
11552 : 26780 : case INT4OID:
11553 : :
11554 : : /*
11555 : : * INT4 can be printed without any decoration, unless it is
11556 : : * negative; in that case print it as '-nnn'::integer to ensure
11557 : : * that the output will re-parse as a constant, not as a constant
11558 : : * plus operator. In most cases we could get away with printing
11559 : : * (-nnn) instead, because of the way that gram.y handles negative
11560 : : * literals; but that doesn't work for INT_MIN, and it doesn't
11561 : : * seem that much prettier anyway.
11562 : : */
11563 [ + + ]: 26780 : if (extval[0] != '-')
11564 : 26430 : appendStringInfoString(buf, extval);
11565 : : else
11566 : : {
11567 : 350 : appendStringInfo(buf, "'%s'", extval);
11568 : 350 : needlabel = true; /* we must attach a cast */
11569 : : }
11570 : 26780 : break;
11571 : :
11572 : 720 : case NUMERICOID:
11573 : :
11574 : : /*
11575 : : * NUMERIC can be printed without quotes if it looks like a float
11576 : : * constant (not an integer, and not Infinity or NaN) and doesn't
11577 : : * have a leading sign (for the same reason as for INT4).
11578 : : */
11579 [ + - ]: 720 : if (isdigit((unsigned char) extval[0]) &&
11580 [ + + ]: 720 : strcspn(extval, "eE.") != strlen(extval))
11581 : : {
11582 : 251 : appendStringInfoString(buf, extval);
11583 : : }
11584 : : else
11585 : : {
11586 : 469 : appendStringInfo(buf, "'%s'", extval);
11587 : 469 : needlabel = true; /* we must attach a cast */
11588 : : }
11589 : 720 : break;
11590 : :
11591 : 1149 : case BOOLOID:
11592 [ + + ]: 1149 : if (strcmp(extval, "t") == 0)
11593 : 448 : appendStringInfoString(buf, "true");
11594 : : else
11595 : 701 : appendStringInfoString(buf, "false");
11596 : 1149 : break;
11597 : :
11598 : 17497 : default:
11599 : 17497 : simple_quote_literal(buf, extval);
11600 : 17497 : break;
11601 : : }
11602 : :
11603 : 46146 : pfree(extval);
11604 : :
11605 [ + + ]: 46146 : if (showtype < 0)
11606 : 4819 : return;
11607 : :
11608 : : /*
11609 : : * For showtype == 0, append ::typename unless the constant will be
11610 : : * implicitly typed as the right type when it is read in.
11611 : : *
11612 : : * XXX this code has to be kept in sync with the behavior of the parser,
11613 : : * especially make_const.
11614 : : */
11615 [ + + + + ]: 41327 : switch (constval->consttype)
11616 : : {
11617 : 1199 : case BOOLOID:
11618 : : case UNKNOWNOID:
11619 : : /* These types can be left unlabeled */
11620 : 1199 : needlabel = false;
11621 : 1199 : break;
11622 : 24159 : case INT4OID:
11623 : : /* We determined above whether a label is needed */
11624 : 24159 : break;
11625 : 720 : case NUMERICOID:
11626 : :
11627 : : /*
11628 : : * Float-looking constants will be typed as numeric, which we
11629 : : * checked above; but if there's a nondefault typmod we need to
11630 : : * show it.
11631 : : */
11632 : 720 : needlabel |= (constval->consttypmod >= 0);
11633 : 720 : break;
11634 : 15249 : default:
11635 : 15249 : needlabel = true;
11636 : 15249 : break;
11637 : : }
11638 [ + + - + ]: 41327 : if (needlabel || showtype > 0)
11639 : 16062 : appendStringInfo(buf, "::%s",
11640 : : format_type_with_typemod(constval->consttype,
11641 : : constval->consttypmod));
11642 : :
11643 : 41327 : get_const_collation(constval, context);
11644 : : }
11645 : :
11646 : : /*
11647 : : * helper for get_const_expr: append COLLATE if needed
11648 : : */
11649 : : static void
11650 : 42247 : get_const_collation(Const *constval, deparse_context *context)
11651 : : {
11652 : 42247 : StringInfo buf = context->buf;
11653 : :
11654 [ + + ]: 42247 : if (OidIsValid(constval->constcollid))
11655 : : {
11656 : 5960 : Oid typcollation = get_typcollation(constval->consttype);
11657 : :
11658 [ + + ]: 5960 : if (constval->constcollid != typcollation)
11659 : : {
11660 : 160 : appendStringInfo(buf, " COLLATE %s",
11661 : : generate_collation_name(constval->constcollid));
11662 : : }
11663 : : }
11664 : 42247 : }
11665 : :
11666 : : /*
11667 : : * get_json_path_spec - Parse back a JSON path specification
11668 : : */
11669 : : static void
11670 : 428 : get_json_path_spec(Node *path_spec, deparse_context *context, bool showimplicit)
11671 : : {
11672 [ + - ]: 428 : if (IsA(path_spec, Const))
11673 : 428 : get_const_expr((Const *) path_spec, context, -1);
11674 : : else
11675 : 0 : get_rule_expr(path_spec, context, showimplicit);
11676 : 428 : }
11677 : :
11678 : : /*
11679 : : * get_json_format - Parse back a JsonFormat node
11680 : : */
11681 : : static void
11682 : 148 : get_json_format(JsonFormat *format, StringInfo buf)
11683 : : {
11684 [ + + ]: 148 : if (format->format_type == JS_FORMAT_DEFAULT)
11685 : 92 : return;
11686 : :
11687 : 56 : appendStringInfoString(buf,
11688 [ - + ]: 56 : format->format_type == JS_FORMAT_JSONB ?
11689 : : " FORMAT JSONB" : " FORMAT JSON");
11690 : :
11691 [ + + ]: 56 : if (format->encoding != JS_ENC_DEFAULT)
11692 : : {
11693 : : const char *encoding;
11694 : :
11695 : 4 : encoding =
11696 [ + - ]: 8 : format->encoding == JS_ENC_UTF16 ? "UTF16" :
11697 [ - + ]: 4 : format->encoding == JS_ENC_UTF32 ? "UTF32" : "UTF8";
11698 : :
11699 : 4 : appendStringInfo(buf, " ENCODING %s", encoding);
11700 : : }
11701 : : }
11702 : :
11703 : : /*
11704 : : * get_json_returning - Parse back a JsonReturning structure
11705 : : */
11706 : : static void
11707 : 212 : get_json_returning(JsonReturning *returning, StringInfo buf,
11708 : : bool json_format_by_default)
11709 : : {
11710 [ - + ]: 212 : if (!OidIsValid(returning->typid))
11711 : 0 : return;
11712 : :
11713 : 212 : appendStringInfo(buf, " RETURNING %s",
11714 : : format_type_with_typemod(returning->typid,
11715 : : returning->typmod));
11716 : :
11717 [ + + + + ]: 416 : if (!json_format_by_default ||
11718 : 204 : returning->format->format_type !=
11719 [ + + ]: 204 : (returning->typid == JSONBOID ? JS_FORMAT_JSONB : JS_FORMAT_JSON))
11720 : 24 : get_json_format(returning->format, buf);
11721 : : }
11722 : :
11723 : : /*
11724 : : * get_json_constructor - Parse back a JsonConstructorExpr node
11725 : : */
11726 : : static void
11727 : 216 : get_json_constructor(JsonConstructorExpr *ctor, deparse_context *context,
11728 : : bool showimplicit)
11729 : : {
11730 : 216 : StringInfo buf = context->buf;
11731 : : const char *funcname;
11732 : : bool is_json_object;
11733 : : int curridx;
11734 : : ListCell *lc;
11735 : :
11736 [ + + ]: 216 : if (ctor->type == JSCTOR_JSON_OBJECTAGG)
11737 : : {
11738 : 40 : get_json_agg_constructor(ctor, context, "JSON_OBJECTAGG", true);
11739 : 40 : return;
11740 : : }
11741 [ + + ]: 176 : else if (ctor->type == JSCTOR_JSON_ARRAYAGG)
11742 : : {
11743 : 68 : get_json_agg_constructor(ctor, context, "JSON_ARRAYAGG", false);
11744 : 68 : return;
11745 : : }
11746 [ + + ]: 108 : else if (ctor->type == JSCTOR_JSON_ARRAY_QUERY)
11747 : : {
11748 : 20 : Query *query = castNode(Query, ctor->orig_query);
11749 : :
11750 : 20 : appendStringInfo(buf, "JSON_ARRAY(");
11751 : :
11752 : 20 : get_query_def(query, buf, context->namespaces, NULL, false,
11753 : : context->prettyFlags, context->wrapColumn,
11754 : : context->indentLevel);
11755 : :
11756 : 20 : get_json_format(ctor->format, buf);
11757 : 20 : get_json_constructor_options(ctor, buf);
11758 : 20 : appendStringInfoChar(buf, ')');
11759 : :
11760 : 20 : return;
11761 : : }
11762 : :
11763 [ + + + + : 88 : switch (ctor->type)
+ - ]
11764 : : {
11765 : 28 : case JSCTOR_JSON_OBJECT:
11766 : 28 : funcname = "JSON_OBJECT";
11767 : 28 : break;
11768 : 16 : case JSCTOR_JSON_ARRAY:
11769 : 16 : funcname = "JSON_ARRAY";
11770 : 16 : break;
11771 : 28 : case JSCTOR_JSON_PARSE:
11772 : 28 : funcname = "JSON";
11773 : 28 : break;
11774 : 8 : case JSCTOR_JSON_SCALAR:
11775 : 8 : funcname = "JSON_SCALAR";
11776 : 8 : break;
11777 : 8 : case JSCTOR_JSON_SERIALIZE:
11778 : 8 : funcname = "JSON_SERIALIZE";
11779 : 8 : break;
11780 : 0 : default:
11781 [ # # ]: 0 : elog(ERROR, "invalid JsonConstructorType %d", ctor->type);
11782 : : }
11783 : :
11784 : 88 : appendStringInfo(buf, "%s(", funcname);
11785 : :
11786 : 88 : is_json_object = ctor->type == JSCTOR_JSON_OBJECT;
11787 [ + - + + : 236 : foreach(lc, ctor->args)
+ + ]
11788 : : {
11789 : 148 : curridx = foreach_current_index(lc);
11790 [ + + ]: 148 : if (curridx > 0)
11791 : : {
11792 : : const char *sep;
11793 : :
11794 [ + + + + ]: 60 : sep = (is_json_object && (curridx % 2) != 0) ? " : " : ", ";
11795 : 60 : appendStringInfoString(buf, sep);
11796 : : }
11797 : :
11798 : 148 : get_rule_expr((Node *) lfirst(lc), context, true);
11799 : : }
11800 : :
11801 : 88 : get_json_constructor_options(ctor, buf);
11802 : 88 : appendStringInfoChar(buf, ')');
11803 : : }
11804 : :
11805 : : /*
11806 : : * Append options, if any, to the JSON constructor being deparsed
11807 : : */
11808 : : static void
11809 : 216 : get_json_constructor_options(JsonConstructorExpr *ctor, StringInfo buf)
11810 : : {
11811 [ + + ]: 216 : if (ctor->absent_on_null)
11812 : : {
11813 [ + - ]: 84 : if (ctor->type == JSCTOR_JSON_OBJECT ||
11814 [ + + ]: 84 : ctor->type == JSCTOR_JSON_OBJECTAGG)
11815 : 8 : appendStringInfoString(buf, " ABSENT ON NULL");
11816 : : }
11817 : : else
11818 : : {
11819 [ + - ]: 132 : if (ctor->type == JSCTOR_JSON_ARRAY ||
11820 [ + + ]: 132 : ctor->type == JSCTOR_JSON_ARRAYAGG)
11821 : 28 : appendStringInfoString(buf, " NULL ON NULL");
11822 : : }
11823 : :
11824 [ + + ]: 216 : if (ctor->unique)
11825 : 24 : appendStringInfoString(buf, " WITH UNIQUE KEYS");
11826 : :
11827 : : /*
11828 : : * Append RETURNING clause if needed; JSON() and JSON_SCALAR() don't
11829 : : * support one.
11830 : : */
11831 [ + + + + ]: 216 : if (ctor->type != JSCTOR_JSON_PARSE && ctor->type != JSCTOR_JSON_SCALAR)
11832 : 180 : get_json_returning(ctor->returning, buf, true);
11833 : 216 : }
11834 : :
11835 : : /*
11836 : : * get_json_agg_constructor - Parse back an aggregate JsonConstructorExpr node
11837 : : */
11838 : : static void
11839 : 108 : get_json_agg_constructor(JsonConstructorExpr *ctor, deparse_context *context,
11840 : : const char *funcname, bool is_json_objectagg)
11841 : : {
11842 : : StringInfoData options;
11843 : :
11844 : 108 : initStringInfo(&options);
11845 : 108 : get_json_constructor_options(ctor, &options);
11846 : :
11847 [ + + ]: 108 : if (IsA(ctor->func, Aggref))
11848 : 68 : get_agg_expr_helper((Aggref *) ctor->func, context,
11849 : 68 : (Aggref *) ctor->func,
11850 : 68 : funcname, options.data, is_json_objectagg);
11851 [ + + ]: 40 : else if (IsA(ctor->func, WindowFunc))
11852 : 12 : get_windowfunc_expr_helper((WindowFunc *) ctor->func, context,
11853 : 12 : funcname, options.data,
11854 : : is_json_objectagg);
11855 [ + - ]: 28 : else if (IsA(ctor->func, Var))
11856 : : {
11857 : : /*
11858 : : * If the aggregate is computed by a lower plan node, setrefs.c will
11859 : : * have replaced the Aggref or WindowFunc with a Var referencing that
11860 : : * node's output. Chase the Var back to it so we can still print the
11861 : : * original JSON aggregate syntax. This only happens in EXPLAIN.
11862 : : */
11863 : 28 : resolve_special_varno((Node *) ctor->func, context,
11864 : : get_json_agg_constructor_expr, ctor);
11865 : : }
11866 : : else
11867 [ # # ]: 0 : elog(ERROR, "invalid JsonConstructorExpr underlying node type: %d",
11868 : : nodeTag(ctor->func));
11869 : 108 : }
11870 : :
11871 : : /*
11872 : : * Deparse a JsonConstructorExpr whose aggregate is computed by a lower plan
11873 : : * node; resolve_special_varno has located the underlying Aggref/WindowFunc.
11874 : : */
11875 : : static void
11876 : 28 : get_json_agg_constructor_expr(Node *node, deparse_context *context,
11877 : : void *callback_arg)
11878 : : {
11879 : : JsonConstructorExpr ctor;
11880 : :
11881 [ + + - + ]: 28 : if (!IsA(node, Aggref) && !IsA(node, WindowFunc))
11882 [ # # ]: 0 : elog(ERROR, "JSON aggregate constructor does not point to an Aggref or WindowFunc");
11883 : :
11884 : : /* Flat copy suffices; we only replace func. */
11885 : 28 : ctor = *(JsonConstructorExpr *) callback_arg;
11886 : 28 : ctor.func = (Expr *) node;
11887 : 28 : get_json_constructor(&ctor, context, false);
11888 : 28 : }
11889 : :
11890 : : /*
11891 : : * simple_quote_literal - Format a string as a SQL literal, append to buf
11892 : : */
11893 : : static void
11894 : 17918 : simple_quote_literal(StringInfo buf, const char *val)
11895 : : {
11896 : : const char *valptr;
11897 : :
11898 : : /*
11899 : : * We always form the string literal according to standard SQL rules.
11900 : : */
11901 : 17918 : appendStringInfoChar(buf, '\'');
11902 [ + + ]: 180476 : for (valptr = val; *valptr; valptr++)
11903 : : {
11904 : 162558 : char ch = *valptr;
11905 : :
11906 [ + + ]: 162558 : if (SQL_STR_DOUBLE(ch, false))
11907 : 204 : appendStringInfoChar(buf, ch);
11908 : 162558 : appendStringInfoChar(buf, ch);
11909 : : }
11910 : 17918 : appendStringInfoChar(buf, '\'');
11911 : 17918 : }
11912 : :
11913 : :
11914 : : /* ----------
11915 : : * get_sublink_expr - Parse back a sublink
11916 : : * ----------
11917 : : */
11918 : : static void
11919 : 290 : get_sublink_expr(SubLink *sublink, deparse_context *context)
11920 : : {
11921 : 290 : StringInfo buf = context->buf;
11922 : 290 : Query *query = (Query *) (sublink->subselect);
11923 : 290 : char *opname = NULL;
11924 : : bool need_paren;
11925 : :
11926 [ + + ]: 290 : if (sublink->subLinkType == ARRAY_SUBLINK)
11927 : 14 : appendStringInfoString(buf, "ARRAY(");
11928 : : else
11929 : 276 : appendStringInfoChar(buf, '(');
11930 : :
11931 : : /*
11932 : : * Note that we print the name of only the first operator, when there are
11933 : : * multiple combining operators. This is an approximation that could go
11934 : : * wrong in various scenarios (operators in different schemas, renamed
11935 : : * operators, etc) but there is not a whole lot we can do about it, since
11936 : : * the syntax allows only one operator to be shown.
11937 : : */
11938 [ + + ]: 290 : if (sublink->testexpr)
11939 : : {
11940 [ + + ]: 12 : if (IsA(sublink->testexpr, OpExpr))
11941 : : {
11942 : : /* single combining operator */
11943 : 4 : OpExpr *opexpr = (OpExpr *) sublink->testexpr;
11944 : :
11945 : 4 : get_rule_expr(linitial(opexpr->args), context, true);
11946 : 4 : opname = generate_operator_name(opexpr->opno,
11947 : 4 : exprType(linitial(opexpr->args)),
11948 : 4 : exprType(lsecond(opexpr->args)));
11949 : : }
11950 [ + + ]: 8 : else if (IsA(sublink->testexpr, BoolExpr))
11951 : : {
11952 : : /* multiple combining operators, = or <> cases */
11953 : : char *sep;
11954 : : ListCell *l;
11955 : :
11956 : 4 : appendStringInfoChar(buf, '(');
11957 : 4 : sep = "";
11958 [ + - + + : 12 : foreach(l, ((BoolExpr *) sublink->testexpr)->args)
+ + ]
11959 : : {
11960 : 8 : OpExpr *opexpr = lfirst_node(OpExpr, l);
11961 : :
11962 : 8 : appendStringInfoString(buf, sep);
11963 : 8 : get_rule_expr(linitial(opexpr->args), context, true);
11964 [ + + ]: 8 : if (!opname)
11965 : 4 : opname = generate_operator_name(opexpr->opno,
11966 : 4 : exprType(linitial(opexpr->args)),
11967 : 4 : exprType(lsecond(opexpr->args)));
11968 : 8 : sep = ", ";
11969 : : }
11970 : 4 : appendStringInfoChar(buf, ')');
11971 : : }
11972 [ + - ]: 4 : else if (IsA(sublink->testexpr, RowCompareExpr))
11973 : : {
11974 : : /* multiple combining operators, < <= > >= cases */
11975 : 4 : RowCompareExpr *rcexpr = (RowCompareExpr *) sublink->testexpr;
11976 : :
11977 : 4 : appendStringInfoChar(buf, '(');
11978 : 4 : get_rule_expr((Node *) rcexpr->largs, context, true);
11979 : 4 : opname = generate_operator_name(linitial_oid(rcexpr->opnos),
11980 : 4 : exprType(linitial(rcexpr->largs)),
11981 : 4 : exprType(linitial(rcexpr->rargs)));
11982 : 4 : appendStringInfoChar(buf, ')');
11983 : : }
11984 : : else
11985 [ # # ]: 0 : elog(ERROR, "unrecognized testexpr type: %d",
11986 : : (int) nodeTag(sublink->testexpr));
11987 : : }
11988 : :
11989 : 290 : need_paren = true;
11990 : :
11991 [ + + + - : 290 : switch (sublink->subLinkType)
+ - ]
11992 : : {
11993 : 113 : case EXISTS_SUBLINK:
11994 : 113 : appendStringInfoString(buf, "EXISTS ");
11995 : 113 : break;
11996 : :
11997 : 8 : case ANY_SUBLINK:
11998 [ + + ]: 8 : if (strcmp(opname, "=") == 0) /* Represent = ANY as IN */
11999 : 4 : appendStringInfoString(buf, " IN ");
12000 : : else
12001 : 4 : appendStringInfo(buf, " %s ANY ", opname);
12002 : 8 : break;
12003 : :
12004 : 4 : case ALL_SUBLINK:
12005 : 4 : appendStringInfo(buf, " %s ALL ", opname);
12006 : 4 : break;
12007 : :
12008 : 0 : case ROWCOMPARE_SUBLINK:
12009 : 0 : appendStringInfo(buf, " %s ", opname);
12010 : 0 : break;
12011 : :
12012 : 165 : case EXPR_SUBLINK:
12013 : : case MULTIEXPR_SUBLINK:
12014 : : case ARRAY_SUBLINK:
12015 : 165 : need_paren = false;
12016 : 165 : break;
12017 : :
12018 : 0 : case CTE_SUBLINK: /* shouldn't occur in a SubLink */
12019 : : default:
12020 [ # # ]: 0 : elog(ERROR, "unrecognized sublink type: %d",
12021 : : (int) sublink->subLinkType);
12022 : : break;
12023 : : }
12024 : :
12025 [ + + ]: 290 : if (need_paren)
12026 : 125 : appendStringInfoChar(buf, '(');
12027 : :
12028 : 290 : get_query_def(query, buf, context->namespaces, NULL, false,
12029 : : context->prettyFlags, context->wrapColumn,
12030 : : context->indentLevel);
12031 : :
12032 [ + + ]: 290 : if (need_paren)
12033 : 125 : appendStringInfoString(buf, "))");
12034 : : else
12035 : 165 : appendStringInfoChar(buf, ')');
12036 : 290 : }
12037 : :
12038 : :
12039 : : /* ----------
12040 : : * get_xmltable - Parse back a XMLTABLE function
12041 : : * ----------
12042 : : */
12043 : : static void
12044 : 38 : get_xmltable(TableFunc *tf, deparse_context *context, bool showimplicit)
12045 : : {
12046 : 38 : StringInfo buf = context->buf;
12047 : :
12048 : 38 : appendStringInfoString(buf, "XMLTABLE(");
12049 : :
12050 [ + + ]: 38 : if (tf->ns_uris != NIL)
12051 : : {
12052 : : ListCell *lc1,
12053 : : *lc2;
12054 : 9 : bool first = true;
12055 : :
12056 : 9 : appendStringInfoString(buf, "XMLNAMESPACES (");
12057 [ + - + + : 18 : forboth(lc1, tf->ns_uris, lc2, tf->ns_names)
+ - + + +
+ + - +
+ ]
12058 : : {
12059 : 9 : Node *expr = (Node *) lfirst(lc1);
12060 : 9 : String *ns_node = lfirst_node(String, lc2);
12061 : :
12062 [ - + ]: 9 : if (!first)
12063 : 0 : appendStringInfoString(buf, ", ");
12064 : : else
12065 : 9 : first = false;
12066 : :
12067 [ + - ]: 9 : if (ns_node != NULL)
12068 : : {
12069 : 9 : get_rule_expr(expr, context, showimplicit);
12070 : 9 : appendStringInfo(buf, " AS %s",
12071 : 9 : quote_identifier(strVal(ns_node)));
12072 : : }
12073 : : else
12074 : : {
12075 : 0 : appendStringInfoString(buf, "DEFAULT ");
12076 : 0 : get_rule_expr(expr, context, showimplicit);
12077 : : }
12078 : : }
12079 : 9 : appendStringInfoString(buf, "), ");
12080 : : }
12081 : :
12082 : 38 : appendStringInfoChar(buf, '(');
12083 : 38 : get_rule_expr((Node *) tf->rowexpr, context, showimplicit);
12084 : 38 : appendStringInfoString(buf, ") PASSING (");
12085 : 38 : get_rule_expr((Node *) tf->docexpr, context, showimplicit);
12086 : 38 : appendStringInfoChar(buf, ')');
12087 : :
12088 [ + - ]: 38 : if (tf->colexprs != NIL)
12089 : : {
12090 : : ListCell *l1;
12091 : : ListCell *l2;
12092 : : ListCell *l3;
12093 : : ListCell *l4;
12094 : : ListCell *l5;
12095 : 38 : int colnum = 0;
12096 : :
12097 : 38 : appendStringInfoString(buf, " COLUMNS ");
12098 [ + - + + : 231 : forfive(l1, tf->colnames, l2, tf->coltypes, l3, tf->coltypmods,
+ - + + +
- + + + -
+ + + - +
+ + + + -
+ - + - +
- + + ]
12099 : : l4, tf->colexprs, l5, tf->coldefexprs)
12100 : : {
12101 : 193 : char *colname = strVal(lfirst(l1));
12102 : 193 : Oid typid = lfirst_oid(l2);
12103 : 193 : int32 typmod = lfirst_int(l3);
12104 : 193 : Node *colexpr = (Node *) lfirst(l4);
12105 : 193 : Node *coldefexpr = (Node *) lfirst(l5);
12106 : 193 : bool ordinality = (tf->ordinalitycol == colnum);
12107 : 193 : bool notnull = bms_is_member(colnum, tf->notnulls);
12108 : :
12109 [ + + ]: 193 : if (colnum > 0)
12110 : 155 : appendStringInfoString(buf, ", ");
12111 : 193 : colnum++;
12112 : :
12113 [ + + ]: 365 : appendStringInfo(buf, "%s %s", quote_identifier(colname),
12114 : : ordinality ? "FOR ORDINALITY" :
12115 : 172 : format_type_with_typemod(typid, typmod));
12116 [ + + ]: 193 : if (ordinality)
12117 : 21 : continue;
12118 : :
12119 [ + + ]: 172 : if (coldefexpr != NULL)
12120 : : {
12121 : 21 : appendStringInfoString(buf, " DEFAULT (");
12122 : 21 : get_rule_expr((Node *) coldefexpr, context, showimplicit);
12123 : 21 : appendStringInfoChar(buf, ')');
12124 : : }
12125 [ + + ]: 172 : if (colexpr != NULL)
12126 : : {
12127 : 156 : appendStringInfoString(buf, " PATH (");
12128 : 156 : get_rule_expr((Node *) colexpr, context, showimplicit);
12129 : 156 : appendStringInfoChar(buf, ')');
12130 : : }
12131 [ + + ]: 172 : if (notnull)
12132 : 21 : appendStringInfoString(buf, " NOT NULL");
12133 : : }
12134 : : }
12135 : :
12136 : 38 : appendStringInfoChar(buf, ')');
12137 : 38 : }
12138 : :
12139 : : /*
12140 : : * get_json_table_nested_columns - Parse back nested JSON_TABLE columns
12141 : : */
12142 : : static void
12143 : 104 : get_json_table_nested_columns(TableFunc *tf, JsonTablePlan *plan,
12144 : : deparse_context *context, bool showimplicit,
12145 : : bool needcomma)
12146 : : {
12147 [ + + ]: 104 : if (IsA(plan, JsonTablePathScan))
12148 : : {
12149 : 76 : JsonTablePathScan *scan = castNode(JsonTablePathScan, plan);
12150 : :
12151 [ + + ]: 76 : if (needcomma)
12152 : 48 : appendStringInfoChar(context->buf, ',');
12153 : :
12154 : 76 : appendStringInfoChar(context->buf, ' ');
12155 : 76 : appendContextKeyword(context, "NESTED PATH ", 0, 0, 0);
12156 : 76 : get_const_expr(scan->path->value, context, -1);
12157 : 76 : appendStringInfo(context->buf, " AS %s", quote_identifier(scan->path->name));
12158 : 76 : get_json_table_columns(tf, scan, context, showimplicit);
12159 : : }
12160 [ + - ]: 28 : else if (IsA(plan, JsonTableSiblingJoin))
12161 : : {
12162 : 28 : JsonTableSiblingJoin *join = (JsonTableSiblingJoin *) plan;
12163 : :
12164 : 28 : get_json_table_nested_columns(tf, join->lplan, context, showimplicit,
12165 : : needcomma);
12166 : 28 : get_json_table_nested_columns(tf, join->rplan, context, showimplicit,
12167 : : true);
12168 : : }
12169 : 104 : }
12170 : :
12171 : : /*
12172 : : * json_table_plan_is_default - does this plan match the implicit default?
12173 : : *
12174 : : * When no PLAN clause is given, JSON_TABLE builds a default plan that joins
12175 : : * every nested path to its parent with OUTER and every set of sibling paths
12176 : : * with UNION (see transformJsonTableColumns()). Such a plan is fully implied
12177 : : * by the NESTED COLUMNS structure, so we need not (and, to match the input,
12178 : : * should not) print a PLAN clause for it; we only deparse a PLAN clause when
12179 : : * the plan deviates from the default, i.e. uses an INNER or CROSS join
12180 : : * somewhere. This follows the usual ruleutils convention of omitting a clause
12181 : : * that merely restates the default (cf. get_json_expr_options() for ON
12182 : : * EMPTY/ON ERROR, or the NULLS FIRST/LAST handling in get_rule_orderby()).
12183 : : */
12184 : : static bool
12185 : 116 : json_table_plan_is_default(JsonTablePlan *plan)
12186 : : {
12187 [ + + ]: 116 : if (IsA(plan, JsonTablePathScan))
12188 : : {
12189 : 88 : JsonTablePathScan *scan = castNode(JsonTablePathScan, plan);
12190 : :
12191 [ + + ]: 88 : if (scan->child)
12192 : : {
12193 [ + + ]: 48 : if (!scan->outerJoin)
12194 : 4 : return false; /* INNER is not the default */
12195 : 44 : return json_table_plan_is_default(scan->child);
12196 : : }
12197 : :
12198 : 40 : return true;
12199 : : }
12200 : : else
12201 : : {
12202 : 28 : JsonTableSiblingJoin *join = castNode(JsonTableSiblingJoin, plan);
12203 : :
12204 [ - + ]: 28 : if (join->cross)
12205 : 0 : return false; /* CROSS is not the default */
12206 [ + - + - ]: 56 : return json_table_plan_is_default(join->lplan) &&
12207 : 28 : json_table_plan_is_default(join->rplan);
12208 : : }
12209 : : }
12210 : :
12211 : : /*
12212 : : * get_json_table_plan - Parse back a JSON_TABLE plan
12213 : : */
12214 : : static void
12215 : 12 : get_json_table_plan(TableFunc *tf, JsonTablePlan *plan, deparse_context *context,
12216 : : bool parenthesize)
12217 : : {
12218 [ + + ]: 12 : if (parenthesize)
12219 : 8 : appendStringInfoChar(context->buf, '(');
12220 : :
12221 [ + - ]: 12 : if (IsA(plan, JsonTablePathScan))
12222 : : {
12223 : 12 : JsonTablePathScan *s = castNode(JsonTablePathScan, plan);
12224 : :
12225 : 12 : appendStringInfoString(context->buf, quote_identifier(s->path->name));
12226 : :
12227 [ + + ]: 12 : if (s->child)
12228 : : {
12229 : 8 : appendStringInfoString(context->buf,
12230 [ + + ]: 8 : s->outerJoin ? " OUTER " : " INNER ");
12231 : 8 : get_json_table_plan(tf, s->child, context,
12232 [ + - ]: 16 : IsA(s->child, JsonTableSiblingJoin) ||
12233 [ + + ]: 16 : castNode(JsonTablePathScan, s->child)->child);
12234 : : }
12235 : : }
12236 [ # # ]: 0 : else if (IsA(plan, JsonTableSiblingJoin))
12237 : : {
12238 : 0 : JsonTableSiblingJoin *j = (JsonTableSiblingJoin *) plan;
12239 : :
12240 : 0 : get_json_table_plan(tf, j->lplan, context,
12241 [ # # ]: 0 : IsA(j->lplan, JsonTableSiblingJoin) ||
12242 [ # # ]: 0 : castNode(JsonTablePathScan, j->lplan)->child);
12243 : :
12244 [ # # ]: 0 : appendStringInfoString(context->buf, j->cross ? " CROSS " : " UNION ");
12245 : :
12246 : 0 : get_json_table_plan(tf, j->rplan, context,
12247 [ # # ]: 0 : IsA(j->rplan, JsonTableSiblingJoin) ||
12248 [ # # ]: 0 : castNode(JsonTablePathScan, j->rplan)->child);
12249 : : }
12250 : :
12251 [ + + ]: 12 : if (parenthesize)
12252 : 8 : appendStringInfoChar(context->buf, ')');
12253 : 12 : }
12254 : :
12255 : : /*
12256 : : * get_json_table_columns - Parse back JSON_TABLE columns
12257 : : */
12258 : : static void
12259 : 160 : get_json_table_columns(TableFunc *tf, JsonTablePathScan *scan,
12260 : : deparse_context *context,
12261 : : bool showimplicit)
12262 : : {
12263 : 160 : StringInfo buf = context->buf;
12264 : : ListCell *lc_colname;
12265 : : ListCell *lc_coltype;
12266 : : ListCell *lc_coltypmod;
12267 : : ListCell *lc_colvalexpr;
12268 : 160 : int colnum = 0;
12269 : :
12270 : 160 : appendStringInfoChar(buf, ' ');
12271 : 160 : appendContextKeyword(context, "COLUMNS (", 0, 0, 0);
12272 : :
12273 [ + + ]: 160 : if (PRETTY_INDENT(context))
12274 : 108 : context->indentLevel += PRETTYINDENT_VAR;
12275 : :
12276 [ + - + + : 1304 : forfour(lc_colname, tf->colnames,
+ - + + +
- + + + -
+ + + + +
- + - + -
+ + ]
12277 : : lc_coltype, tf->coltypes,
12278 : : lc_coltypmod, tf->coltypmods,
12279 : : lc_colvalexpr, tf->colvalexprs)
12280 : : {
12281 : 1192 : char *colname = strVal(lfirst(lc_colname));
12282 : : JsonExpr *colexpr;
12283 : : Oid typid;
12284 : : int32 typmod;
12285 : : bool ordinality;
12286 : : JsonBehaviorType default_behavior;
12287 : :
12288 : 1192 : typid = lfirst_oid(lc_coltype);
12289 : 1192 : typmod = lfirst_int(lc_coltypmod);
12290 : 1192 : colexpr = castNode(JsonExpr, lfirst(lc_colvalexpr));
12291 : :
12292 : : /* Skip columns that don't belong to this scan. */
12293 [ + + + + ]: 1192 : if (scan->colMin < 0 || colnum < scan->colMin)
12294 : : {
12295 : 740 : colnum++;
12296 : 740 : continue;
12297 : : }
12298 [ + + ]: 452 : if (colnum > scan->colMax)
12299 : 48 : break;
12300 : :
12301 [ + + ]: 404 : if (colnum > scan->colMin)
12302 : 272 : appendStringInfoString(buf, ", ");
12303 : :
12304 : 404 : colnum++;
12305 : :
12306 : 404 : ordinality = !colexpr;
12307 : :
12308 : 404 : appendContextKeyword(context, "", 0, 0, 0);
12309 : :
12310 [ + + ]: 792 : appendStringInfo(buf, "%s %s", quote_identifier(colname),
12311 : : ordinality ? "FOR ORDINALITY" :
12312 : 388 : format_type_with_typemod(typid, typmod));
12313 [ + + ]: 404 : if (ordinality)
12314 : 16 : continue;
12315 : :
12316 : : /*
12317 : : * Set default_behavior to guide get_json_expr_options() on whether to
12318 : : * emit the ON ERROR / EMPTY clauses.
12319 : : */
12320 [ + + ]: 388 : if (colexpr->op == JSON_EXISTS_OP)
12321 : : {
12322 : 36 : appendStringInfoString(buf, " EXISTS");
12323 : 36 : default_behavior = JSON_BEHAVIOR_FALSE;
12324 : : }
12325 : : else
12326 : : {
12327 [ + + ]: 352 : if (colexpr->op == JSON_QUERY_OP)
12328 : : {
12329 : : char typcategory;
12330 : : bool typispreferred;
12331 : :
12332 : 168 : get_type_category_preferred(typid, &typcategory, &typispreferred);
12333 : :
12334 [ + + ]: 168 : if (typcategory == TYPCATEGORY_STRING)
12335 : 36 : appendStringInfoString(buf,
12336 [ - + ]: 36 : colexpr->format->format_type == JS_FORMAT_JSONB ?
12337 : : " FORMAT JSONB" : " FORMAT JSON");
12338 : : }
12339 : :
12340 : 352 : default_behavior = JSON_BEHAVIOR_NULL;
12341 : : }
12342 : :
12343 : 388 : appendStringInfoString(buf, " PATH ");
12344 : :
12345 : 388 : get_json_path_spec(colexpr->path_spec, context, showimplicit);
12346 : :
12347 : 388 : get_json_expr_options(colexpr, context, default_behavior);
12348 : : }
12349 : :
12350 [ + + ]: 160 : if (scan->child)
12351 : 48 : get_json_table_nested_columns(tf, scan->child, context, showimplicit,
12352 : 48 : scan->colMin >= 0);
12353 : :
12354 [ + + ]: 160 : if (PRETTY_INDENT(context))
12355 : 108 : context->indentLevel -= PRETTYINDENT_VAR;
12356 : :
12357 : 160 : appendContextKeyword(context, ")", 0, 0, 0);
12358 : 160 : }
12359 : :
12360 : : /* ----------
12361 : : * get_json_table - Parse back a JSON_TABLE function
12362 : : * ----------
12363 : : */
12364 : : static void
12365 : 84 : get_json_table(TableFunc *tf, deparse_context *context, bool showimplicit)
12366 : : {
12367 : 84 : StringInfo buf = context->buf;
12368 : 84 : JsonExpr *jexpr = castNode(JsonExpr, tf->docexpr);
12369 : 84 : JsonTablePathScan *root = castNode(JsonTablePathScan, tf->plan);
12370 : :
12371 : 84 : appendStringInfoString(buf, "JSON_TABLE(");
12372 : :
12373 [ + + ]: 84 : if (PRETTY_INDENT(context))
12374 : 52 : context->indentLevel += PRETTYINDENT_VAR;
12375 : :
12376 : 84 : appendContextKeyword(context, "", 0, 0, 0);
12377 : :
12378 : 84 : get_rule_expr(jexpr->formatted_expr, context, showimplicit);
12379 : :
12380 : 84 : appendStringInfoString(buf, ", ");
12381 : :
12382 : 84 : get_const_expr(root->path->value, context, -1);
12383 : :
12384 : 84 : appendStringInfo(buf, " AS %s", quote_identifier(root->path->name));
12385 : :
12386 [ + + ]: 84 : if (jexpr->passing_values)
12387 : : {
12388 : : ListCell *lc1,
12389 : : *lc2;
12390 : 60 : bool needcomma = false;
12391 : :
12392 : 60 : appendStringInfoChar(buf, ' ');
12393 : 60 : appendContextKeyword(context, "PASSING ", 0, 0, 0);
12394 : :
12395 [ + + ]: 60 : if (PRETTY_INDENT(context))
12396 : 28 : context->indentLevel += PRETTYINDENT_VAR;
12397 : :
12398 [ + - + + : 180 : forboth(lc1, jexpr->passing_names,
+ - + + +
+ + - +
+ ]
12399 : : lc2, jexpr->passing_values)
12400 : : {
12401 [ + + ]: 120 : if (needcomma)
12402 : 60 : appendStringInfoString(buf, ", ");
12403 : 120 : needcomma = true;
12404 : :
12405 : 120 : appendContextKeyword(context, "", 0, 0, 0);
12406 : :
12407 : 120 : get_rule_expr((Node *) lfirst(lc2), context, false);
12408 : 120 : appendStringInfo(buf, " AS %s",
12409 : 120 : quote_identifier((lfirst_node(String, lc1))->sval)
12410 : : );
12411 : : }
12412 : :
12413 [ + + ]: 60 : if (PRETTY_INDENT(context))
12414 : 28 : context->indentLevel -= PRETTYINDENT_VAR;
12415 : : }
12416 : :
12417 : 84 : get_json_table_columns(tf, castNode(JsonTablePathScan, tf->plan), context,
12418 : : showimplicit);
12419 : :
12420 : : /*
12421 : : * Deparse a PLAN clause only for a non-default plan; the default plan is
12422 : : * implied by the NESTED COLUMNS structure (see
12423 : : * json_table_plan_is_default).
12424 : : */
12425 [ + + + + ]: 84 : if (root->child && !json_table_plan_is_default((JsonTablePlan *) root))
12426 : : {
12427 : 4 : appendStringInfoChar(buf, ' ');
12428 : 4 : appendContextKeyword(context, "PLAN ", 0, 0, 0);
12429 : 4 : get_json_table_plan(tf, (JsonTablePlan *) root, context, true);
12430 : : }
12431 : :
12432 [ + + ]: 84 : if (jexpr->on_error->btype != JSON_BEHAVIOR_EMPTY_ARRAY)
12433 : 8 : get_json_behavior(jexpr->on_error, context, "ERROR");
12434 : :
12435 [ + + ]: 84 : if (PRETTY_INDENT(context))
12436 : 52 : context->indentLevel -= PRETTYINDENT_VAR;
12437 : :
12438 : 84 : appendContextKeyword(context, ")", 0, 0, 0);
12439 : 84 : }
12440 : :
12441 : : /* ----------
12442 : : * get_tablefunc - Parse back a table function
12443 : : * ----------
12444 : : */
12445 : : static void
12446 : 122 : get_tablefunc(TableFunc *tf, deparse_context *context, bool showimplicit)
12447 : : {
12448 : : /* XMLTABLE and JSON_TABLE are the only existing implementations. */
12449 : :
12450 [ + + ]: 122 : if (tf->functype == TFT_XMLTABLE)
12451 : 38 : get_xmltable(tf, context, showimplicit);
12452 [ + - ]: 84 : else if (tf->functype == TFT_JSON_TABLE)
12453 : 84 : get_json_table(tf, context, showimplicit);
12454 : 122 : }
12455 : :
12456 : : /* ----------
12457 : : * get_from_clause - Parse back a FROM clause
12458 : : *
12459 : : * "prefix" is the keyword that denotes the start of the list of FROM
12460 : : * elements. It is FROM when used to parse back SELECT and UPDATE, but
12461 : : * is USING when parsing back DELETE.
12462 : : * ----------
12463 : : */
12464 : : static void
12465 : 3013 : get_from_clause(Query *query, const char *prefix, deparse_context *context)
12466 : : {
12467 : 3013 : StringInfo buf = context->buf;
12468 : 3013 : bool first = true;
12469 : : ListCell *l;
12470 : :
12471 : : /*
12472 : : * We use the query's jointree as a guide to what to print. However, we
12473 : : * must ignore auto-added RTEs that are marked not inFromCl. (These can
12474 : : * only appear at the top level of the jointree, so it's sufficient to
12475 : : * check here.) This check also ensures we ignore the rule pseudo-RTEs
12476 : : * for NEW and OLD.
12477 : : */
12478 [ + + + + : 5976 : foreach(l, query->jointree->fromlist)
+ + ]
12479 : : {
12480 : 2963 : Node *jtnode = (Node *) lfirst(l);
12481 : :
12482 [ + + ]: 2963 : if (IsA(jtnode, RangeTblRef))
12483 : : {
12484 : 2358 : int varno = ((RangeTblRef *) jtnode)->rtindex;
12485 : 2358 : RangeTblEntry *rte = rt_fetch(varno, query->rtable);
12486 : :
12487 [ + + ]: 2358 : if (!rte->inFromCl)
12488 : 214 : continue;
12489 : : }
12490 : :
12491 [ + + ]: 2749 : if (first)
12492 : : {
12493 : 2525 : appendContextKeyword(context, prefix,
12494 : : -PRETTYINDENT_STD, PRETTYINDENT_STD, 2);
12495 : 2525 : first = false;
12496 : :
12497 : 2525 : get_from_clause_item(jtnode, query, context);
12498 : : }
12499 : : else
12500 : : {
12501 : : StringInfoData itembuf;
12502 : :
12503 : 224 : appendStringInfoString(buf, ", ");
12504 : :
12505 : : /*
12506 : : * Put the new FROM item's text into itembuf so we can decide
12507 : : * after we've got it whether or not it needs to go on a new line.
12508 : : */
12509 : 224 : initStringInfo(&itembuf);
12510 : 224 : context->buf = &itembuf;
12511 : :
12512 : 224 : get_from_clause_item(jtnode, query, context);
12513 : :
12514 : : /* Restore context's output buffer */
12515 : 224 : context->buf = buf;
12516 : :
12517 : : /* Consider line-wrapping if enabled */
12518 [ + - + - ]: 224 : if (PRETTY_INDENT(context) && context->wrapColumn >= 0)
12519 : : {
12520 : : /* Does the new item start with a new line? */
12521 [ + - - + ]: 224 : if (itembuf.len > 0 && itembuf.data[0] == '\n')
12522 : : {
12523 : : /* If so, we shouldn't add anything */
12524 : : /* instead, remove any trailing spaces currently in buf */
12525 : 0 : removeStringInfoSpaces(buf);
12526 : : }
12527 : : else
12528 : : {
12529 : : char *trailing_nl;
12530 : :
12531 : : /* Locate the start of the current line in the buffer */
12532 : 224 : trailing_nl = strrchr(buf->data, '\n');
12533 [ - + ]: 224 : if (trailing_nl == NULL)
12534 : 0 : trailing_nl = buf->data;
12535 : : else
12536 : 224 : trailing_nl++;
12537 : :
12538 : : /*
12539 : : * Add a newline, plus some indentation, if the new item
12540 : : * would cause an overflow.
12541 : : */
12542 [ + - ]: 224 : if (strlen(trailing_nl) + itembuf.len > context->wrapColumn)
12543 : 224 : appendContextKeyword(context, "", -PRETTYINDENT_STD,
12544 : : PRETTYINDENT_STD,
12545 : : PRETTYINDENT_VAR);
12546 : : }
12547 : : }
12548 : :
12549 : : /* Add the new item */
12550 : 224 : appendBinaryStringInfo(buf, itembuf.data, itembuf.len);
12551 : :
12552 : : /* clean up */
12553 : 224 : pfree(itembuf.data);
12554 : : }
12555 : : }
12556 : 3013 : }
12557 : :
12558 : : static void
12559 : 4629 : get_from_clause_item(Node *jtnode, Query *query, deparse_context *context)
12560 : : {
12561 : 4629 : StringInfo buf = context->buf;
12562 : 4629 : deparse_namespace *dpns = (deparse_namespace *) linitial(context->namespaces);
12563 : :
12564 [ + + ]: 4629 : if (IsA(jtnode, RangeTblRef))
12565 : : {
12566 : 3689 : int varno = ((RangeTblRef *) jtnode)->rtindex;
12567 : 3689 : RangeTblEntry *rte = rt_fetch(varno, query->rtable);
12568 : 3689 : deparse_columns *colinfo = deparse_columns_fetch(varno, dpns);
12569 : 3689 : RangeTblFunction *rtfunc1 = NULL;
12570 : :
12571 [ + + ]: 3689 : if (rte->lateral)
12572 : 73 : appendStringInfoString(buf, "LATERAL ");
12573 : :
12574 : : /* Print the FROM item proper */
12575 [ + + + + : 3689 : switch (rte->rtekind)
+ + - ]
12576 : : {
12577 : 2736 : case RTE_RELATION:
12578 : : /* Normal relation RTE */
12579 : 5472 : appendStringInfo(buf, "%s%s",
12580 [ + + ]: 2736 : only_marker(rte),
12581 : : generate_relation_name(rte->relid,
12582 : : context->namespaces));
12583 : 2736 : break;
12584 : 200 : case RTE_SUBQUERY:
12585 : : /* Subquery RTE */
12586 : 200 : appendStringInfoChar(buf, '(');
12587 : 200 : get_query_def(rte->subquery, buf, context->namespaces, NULL,
12588 : : true,
12589 : : context->prettyFlags, context->wrapColumn,
12590 : : context->indentLevel);
12591 : 200 : appendStringInfoChar(buf, ')');
12592 : 200 : break;
12593 : 560 : case RTE_FUNCTION:
12594 : : /* Function RTE */
12595 : 560 : rtfunc1 = (RangeTblFunction *) linitial(rte->functions);
12596 : :
12597 : : /*
12598 : : * Omit ROWS FROM() syntax for just one function, unless it
12599 : : * has both a coldeflist and WITH ORDINALITY. If it has both,
12600 : : * we must use ROWS FROM() syntax to avoid ambiguity about
12601 : : * whether the coldeflist includes the ordinality column.
12602 : : */
12603 [ + + ]: 560 : if (list_length(rte->functions) == 1 &&
12604 [ - + - - ]: 540 : (rtfunc1->funccolnames == NIL || !rte->funcordinality))
12605 : : {
12606 : 540 : get_rule_expr_funccall(rtfunc1->funcexpr, context, true);
12607 : : /* we'll print the coldeflist below, if it has one */
12608 : : }
12609 : : else
12610 : : {
12611 : : bool all_unnest;
12612 : : ListCell *lc;
12613 : :
12614 : : /*
12615 : : * If all the function calls in the list are to unnest,
12616 : : * and none need a coldeflist, then collapse the list back
12617 : : * down to UNNEST(args). (If we had more than one
12618 : : * built-in unnest function, this would get more
12619 : : * difficult.)
12620 : : *
12621 : : * XXX This is pretty ugly, since it makes not-terribly-
12622 : : * future-proof assumptions about what the parser would do
12623 : : * with the output; but the alternative is to emit our
12624 : : * nonstandard ROWS FROM() notation for what might have
12625 : : * been a perfectly spec-compliant multi-argument
12626 : : * UNNEST().
12627 : : */
12628 : 20 : all_unnest = true;
12629 [ + - + + : 52 : foreach(lc, rte->functions)
+ + ]
12630 : : {
12631 : 44 : RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
12632 : :
12633 [ + - ]: 44 : if (!IsA(rtfunc->funcexpr, FuncExpr) ||
12634 [ + + ]: 44 : ((FuncExpr *) rtfunc->funcexpr)->funcid != F_UNNEST_ANYARRAY ||
12635 [ - + ]: 32 : rtfunc->funccolnames != NIL)
12636 : : {
12637 : 12 : all_unnest = false;
12638 : 12 : break;
12639 : : }
12640 : : }
12641 : :
12642 [ + + ]: 20 : if (all_unnest)
12643 : : {
12644 : 8 : List *allargs = NIL;
12645 : :
12646 [ + - + + : 32 : foreach(lc, rte->functions)
+ + ]
12647 : : {
12648 : 24 : RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
12649 : 24 : List *args = ((FuncExpr *) rtfunc->funcexpr)->args;
12650 : :
12651 : 24 : allargs = list_concat(allargs, args);
12652 : : }
12653 : :
12654 : 8 : appendStringInfoString(buf, "UNNEST(");
12655 : 8 : get_rule_expr((Node *) allargs, context, true);
12656 : 8 : appendStringInfoChar(buf, ')');
12657 : : }
12658 : : else
12659 : : {
12660 : 12 : int funcno = 0;
12661 : :
12662 : 12 : appendStringInfoString(buf, "ROWS FROM(");
12663 [ + - + + : 44 : foreach(lc, rte->functions)
+ + ]
12664 : : {
12665 : 32 : RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
12666 : :
12667 [ + + ]: 32 : if (funcno > 0)
12668 : 20 : appendStringInfoString(buf, ", ");
12669 : 32 : get_rule_expr_funccall(rtfunc->funcexpr, context, true);
12670 [ + + ]: 32 : if (rtfunc->funccolnames != NIL)
12671 : : {
12672 : : /* Reconstruct the column definition list */
12673 : 4 : appendStringInfoString(buf, " AS ");
12674 : 4 : get_from_clause_coldeflist(rtfunc,
12675 : : NULL,
12676 : : context);
12677 : : }
12678 : 32 : funcno++;
12679 : : }
12680 : 12 : appendStringInfoChar(buf, ')');
12681 : : }
12682 : : /* prevent printing duplicate coldeflist below */
12683 : 20 : rtfunc1 = NULL;
12684 : : }
12685 [ + + ]: 560 : if (rte->funcordinality)
12686 : 12 : appendStringInfoString(buf, " WITH ORDINALITY");
12687 : 560 : break;
12688 : 70 : case RTE_TABLEFUNC:
12689 : 70 : get_tablefunc(rte->tablefunc, context, true);
12690 : 70 : break;
12691 : 8 : case RTE_VALUES:
12692 : : /* Values list RTE */
12693 : 8 : appendStringInfoChar(buf, '(');
12694 : 8 : get_values_def(rte->values_lists, context);
12695 : 8 : appendStringInfoChar(buf, ')');
12696 : 8 : break;
12697 : 115 : case RTE_CTE:
12698 : 115 : appendStringInfoString(buf, quote_identifier(rte->ctename));
12699 : 115 : break;
12700 : 0 : default:
12701 [ # # ]: 0 : elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
12702 : : break;
12703 : : }
12704 : :
12705 : : /* Print the relation alias, if needed */
12706 : 3689 : get_rte_alias(rte, varno, false, context);
12707 : :
12708 : : /* Print the column definitions or aliases, if needed */
12709 [ + + - + ]: 3689 : if (rtfunc1 && rtfunc1->funccolnames != NIL)
12710 : : {
12711 : : /* Reconstruct the columndef list, which is also the aliases */
12712 : 0 : get_from_clause_coldeflist(rtfunc1, colinfo, context);
12713 : : }
12714 : : else
12715 : : {
12716 : : /* Else print column aliases as needed */
12717 : 3689 : get_column_alias_list(colinfo, context);
12718 : : }
12719 : :
12720 : : /* Tablesample clause must go after any alias */
12721 [ + + + + ]: 3689 : if (rte->rtekind == RTE_RELATION && rte->tablesample)
12722 : 18 : get_tablesample_def(rte->tablesample, context);
12723 : : }
12724 [ + - ]: 940 : else if (IsA(jtnode, JoinExpr))
12725 : : {
12726 : 940 : JoinExpr *j = (JoinExpr *) jtnode;
12727 : 940 : deparse_columns *colinfo = deparse_columns_fetch(j->rtindex, dpns);
12728 : : bool need_paren_on_right;
12729 : :
12730 : 2172 : need_paren_on_right = PRETTY_PAREN(context) &&
12731 [ + + - + ]: 940 : !IsA(j->rarg, RangeTblRef) &&
12732 [ # # # # ]: 0 : !(IsA(j->rarg, JoinExpr) && ((JoinExpr *) j->rarg)->alias != NULL);
12733 : :
12734 [ + + + + ]: 940 : if (!PRETTY_PAREN(context) || j->alias != NULL)
12735 : 720 : appendStringInfoChar(buf, '(');
12736 : :
12737 : 940 : get_from_clause_item(j->larg, query, context);
12738 : :
12739 [ + + + - : 940 : switch (j->jointype)
- ]
12740 : : {
12741 : 517 : case JOIN_INNER:
12742 [ + + ]: 517 : if (j->quals)
12743 : 489 : appendContextKeyword(context, " JOIN ",
12744 : : -PRETTYINDENT_STD,
12745 : : PRETTYINDENT_STD,
12746 : : PRETTYINDENT_JOIN);
12747 : : else
12748 : 28 : appendContextKeyword(context, " CROSS JOIN ",
12749 : : -PRETTYINDENT_STD,
12750 : : PRETTYINDENT_STD,
12751 : : PRETTYINDENT_JOIN);
12752 : 517 : break;
12753 : 355 : case JOIN_LEFT:
12754 : 355 : appendContextKeyword(context, " LEFT JOIN ",
12755 : : -PRETTYINDENT_STD,
12756 : : PRETTYINDENT_STD,
12757 : : PRETTYINDENT_JOIN);
12758 : 355 : break;
12759 : 68 : case JOIN_FULL:
12760 : 68 : appendContextKeyword(context, " FULL JOIN ",
12761 : : -PRETTYINDENT_STD,
12762 : : PRETTYINDENT_STD,
12763 : : PRETTYINDENT_JOIN);
12764 : 68 : break;
12765 : 0 : case JOIN_RIGHT:
12766 : 0 : appendContextKeyword(context, " RIGHT JOIN ",
12767 : : -PRETTYINDENT_STD,
12768 : : PRETTYINDENT_STD,
12769 : : PRETTYINDENT_JOIN);
12770 : 0 : break;
12771 : 0 : default:
12772 [ # # ]: 0 : elog(ERROR, "unrecognized join type: %d",
12773 : : (int) j->jointype);
12774 : : }
12775 : :
12776 [ - + ]: 940 : if (need_paren_on_right)
12777 : 0 : appendStringInfoChar(buf, '(');
12778 : 940 : get_from_clause_item(j->rarg, query, context);
12779 [ - + ]: 940 : if (need_paren_on_right)
12780 : 0 : appendStringInfoChar(buf, ')');
12781 : :
12782 [ + + ]: 940 : if (j->usingClause)
12783 : : {
12784 : : ListCell *lc;
12785 : 280 : bool first = true;
12786 : :
12787 : 280 : appendStringInfoString(buf, " USING (");
12788 : : /* Use the assigned names, not what's in usingClause */
12789 [ + - + + : 664 : foreach(lc, colinfo->usingNames)
+ + ]
12790 : : {
12791 : 384 : char *colname = (char *) lfirst(lc);
12792 : :
12793 [ + + ]: 384 : if (first)
12794 : 280 : first = false;
12795 : : else
12796 : 104 : appendStringInfoString(buf, ", ");
12797 : 384 : appendStringInfoString(buf, quote_identifier(colname));
12798 : : }
12799 : 280 : appendStringInfoChar(buf, ')');
12800 : :
12801 [ + + ]: 280 : if (j->join_using_alias)
12802 : 8 : appendStringInfo(buf, " AS %s",
12803 : 8 : quote_identifier(j->join_using_alias->aliasname));
12804 : : }
12805 [ + + ]: 660 : else if (j->quals)
12806 : : {
12807 : 628 : appendStringInfoString(buf, " ON ");
12808 [ + + ]: 628 : if (!PRETTY_PAREN(context))
12809 : 624 : appendStringInfoChar(buf, '(');
12810 : 628 : get_rule_expr(j->quals, context, false);
12811 [ + + ]: 628 : if (!PRETTY_PAREN(context))
12812 : 624 : appendStringInfoChar(buf, ')');
12813 : : }
12814 [ + + ]: 32 : else if (j->jointype != JOIN_INNER)
12815 : : {
12816 : : /* If we didn't say CROSS JOIN above, we must provide an ON */
12817 : 4 : appendStringInfoString(buf, " ON TRUE");
12818 : : }
12819 : :
12820 [ + + + + ]: 940 : if (!PRETTY_PAREN(context) || j->alias != NULL)
12821 : 720 : appendStringInfoChar(buf, ')');
12822 : :
12823 : : /* Yes, it's correct to put alias after the right paren ... */
12824 [ + + ]: 940 : if (j->alias != NULL)
12825 : : {
12826 : : /*
12827 : : * Note that it's correct to emit an alias clause if and only if
12828 : : * there was one originally. Otherwise we'd be converting a named
12829 : : * join to unnamed or vice versa, which creates semantic
12830 : : * subtleties we don't want. However, we might print a different
12831 : : * alias name than was there originally.
12832 : : */
12833 : 72 : appendStringInfo(buf, " %s",
12834 : 72 : quote_identifier(get_rtable_name(j->rtindex,
12835 : : context)));
12836 : 72 : get_column_alias_list(colinfo, context);
12837 : : }
12838 : : }
12839 : : else
12840 [ # # ]: 0 : elog(ERROR, "unrecognized node type: %d",
12841 : : (int) nodeTag(jtnode));
12842 : 4629 : }
12843 : :
12844 : : /*
12845 : : * get_rte_alias - print the relation's alias, if needed
12846 : : *
12847 : : * If printed, the alias is preceded by a space, or by " AS " if use_as is true.
12848 : : */
12849 : : static void
12850 : 4016 : get_rte_alias(RangeTblEntry *rte, int varno, bool use_as,
12851 : : deparse_context *context)
12852 : : {
12853 : 4016 : deparse_namespace *dpns = (deparse_namespace *) linitial(context->namespaces);
12854 : 4016 : char *refname = get_rtable_name(varno, context);
12855 : 4016 : deparse_columns *colinfo = deparse_columns_fetch(varno, dpns);
12856 : 4016 : bool printalias = false;
12857 : :
12858 [ + + ]: 4016 : if (rte->alias != NULL)
12859 : : {
12860 : : /* Always print alias if user provided one */
12861 : 1903 : printalias = true;
12862 : : }
12863 [ + + ]: 2113 : else if (colinfo->printaliases)
12864 : : {
12865 : : /* Always print alias if we need to print column aliases */
12866 : 210 : printalias = true;
12867 : : }
12868 [ + + ]: 1903 : else if (rte->rtekind == RTE_RELATION)
12869 : : {
12870 : : /*
12871 : : * No need to print alias if it's same as relation name (this would
12872 : : * normally be the case, but not if set_rtable_names had to resolve a
12873 : : * conflict).
12874 : : */
12875 [ + + ]: 1724 : if (strcmp(refname, get_relation_name(rte->relid)) != 0)
12876 : 52 : printalias = true;
12877 : : }
12878 [ - + ]: 179 : else if (rte->rtekind == RTE_FUNCTION)
12879 : : {
12880 : : /*
12881 : : * For a function RTE, always print alias. This covers possible
12882 : : * renaming of the function and/or instability of the FigureColname
12883 : : * rules for things that aren't simple functions. Note we'd need to
12884 : : * force it anyway for the columndef list case.
12885 : : */
12886 : 0 : printalias = true;
12887 : : }
12888 [ + + ]: 179 : else if (rte->rtekind == RTE_SUBQUERY ||
12889 [ + + ]: 163 : rte->rtekind == RTE_VALUES)
12890 : : {
12891 : : /*
12892 : : * For a subquery, always print alias. This makes the output
12893 : : * SQL-spec-compliant, even though we allow such aliases to be omitted
12894 : : * on input.
12895 : : */
12896 : 24 : printalias = true;
12897 : : }
12898 [ + + ]: 155 : else if (rte->rtekind == RTE_CTE)
12899 : : {
12900 : : /*
12901 : : * No need to print alias if it's same as CTE name (this would
12902 : : * normally be the case, but not if set_rtable_names had to resolve a
12903 : : * conflict).
12904 : : */
12905 [ + + ]: 89 : if (strcmp(refname, rte->ctename) != 0)
12906 : 12 : printalias = true;
12907 : : }
12908 : :
12909 [ + + ]: 4016 : if (printalias)
12910 [ + + ]: 2201 : appendStringInfo(context->buf, "%s%s",
12911 : : use_as ? " AS " : " ",
12912 : : quote_identifier(refname));
12913 : 4016 : }
12914 : :
12915 : : /*
12916 : : * get_column_alias_list - print column alias list for an RTE
12917 : : *
12918 : : * Caller must already have printed the relation's alias name.
12919 : : */
12920 : : static void
12921 : 3761 : get_column_alias_list(deparse_columns *colinfo, deparse_context *context)
12922 : : {
12923 : 3761 : StringInfo buf = context->buf;
12924 : : int i;
12925 : 3761 : bool first = true;
12926 : :
12927 : : /* Don't print aliases if not needed */
12928 [ + + ]: 3761 : if (!colinfo->printaliases)
12929 : 2949 : return;
12930 : :
12931 [ + + ]: 6378 : for (i = 0; i < colinfo->num_new_cols; i++)
12932 : : {
12933 : 5566 : char *colname = colinfo->new_colnames[i];
12934 : :
12935 [ + + ]: 5566 : if (first)
12936 : : {
12937 : 812 : appendStringInfoChar(buf, '(');
12938 : 812 : first = false;
12939 : : }
12940 : : else
12941 : 4754 : appendStringInfoString(buf, ", ");
12942 : 5566 : appendStringInfoString(buf, quote_identifier(colname));
12943 : : }
12944 [ + - ]: 812 : if (!first)
12945 : 812 : appendStringInfoChar(buf, ')');
12946 : : }
12947 : :
12948 : : /*
12949 : : * get_from_clause_coldeflist - reproduce FROM clause coldeflist
12950 : : *
12951 : : * When printing a top-level coldeflist (which is syntactically also the
12952 : : * relation's column alias list), use column names from colinfo. But when
12953 : : * printing a coldeflist embedded inside ROWS FROM(), we prefer to use the
12954 : : * original coldeflist's names, which are available in rtfunc->funccolnames.
12955 : : * Pass NULL for colinfo to select the latter behavior.
12956 : : *
12957 : : * The coldeflist is appended immediately (no space) to buf. Caller is
12958 : : * responsible for ensuring that an alias or AS is present before it.
12959 : : */
12960 : : static void
12961 : 4 : get_from_clause_coldeflist(RangeTblFunction *rtfunc,
12962 : : deparse_columns *colinfo,
12963 : : deparse_context *context)
12964 : : {
12965 : 4 : StringInfo buf = context->buf;
12966 : : ListCell *l1;
12967 : : ListCell *l2;
12968 : : ListCell *l3;
12969 : : ListCell *l4;
12970 : : int i;
12971 : :
12972 : 4 : appendStringInfoChar(buf, '(');
12973 : :
12974 : 4 : i = 0;
12975 [ + - + + : 16 : forfour(l1, rtfunc->funccoltypes,
+ - + + +
- + + + -
+ + + + +
- + - + -
+ + ]
12976 : : l2, rtfunc->funccoltypmods,
12977 : : l3, rtfunc->funccolcollations,
12978 : : l4, rtfunc->funccolnames)
12979 : : {
12980 : 12 : Oid atttypid = lfirst_oid(l1);
12981 : 12 : int32 atttypmod = lfirst_int(l2);
12982 : 12 : Oid attcollation = lfirst_oid(l3);
12983 : : char *attname;
12984 : :
12985 [ - + ]: 12 : if (colinfo)
12986 : 0 : attname = colinfo->colnames[i];
12987 : : else
12988 : 12 : attname = strVal(lfirst(l4));
12989 : :
12990 : : Assert(attname); /* shouldn't be any dropped columns here */
12991 : :
12992 [ + + ]: 12 : if (i > 0)
12993 : 8 : appendStringInfoString(buf, ", ");
12994 : 12 : appendStringInfo(buf, "%s %s",
12995 : : quote_identifier(attname),
12996 : : format_type_with_typemod(atttypid, atttypmod));
12997 [ + + - + ]: 16 : if (OidIsValid(attcollation) &&
12998 : 4 : attcollation != get_typcollation(atttypid))
12999 : 0 : appendStringInfo(buf, " COLLATE %s",
13000 : : generate_collation_name(attcollation));
13001 : :
13002 : 12 : i++;
13003 : : }
13004 : :
13005 : 4 : appendStringInfoChar(buf, ')');
13006 : 4 : }
13007 : :
13008 : : /*
13009 : : * get_tablesample_def - print a TableSampleClause
13010 : : */
13011 : : static void
13012 : 18 : get_tablesample_def(TableSampleClause *tablesample, deparse_context *context)
13013 : : {
13014 : 18 : StringInfo buf = context->buf;
13015 : : Oid argtypes[1];
13016 : : int nargs;
13017 : : ListCell *l;
13018 : :
13019 : : /*
13020 : : * We should qualify the handler's function name if it wouldn't be
13021 : : * resolved by lookup in the current search path.
13022 : : */
13023 : 18 : argtypes[0] = INTERNALOID;
13024 : 18 : appendStringInfo(buf, " TABLESAMPLE %s (",
13025 : : generate_function_name(tablesample->tsmhandler, 1,
13026 : : NIL, argtypes,
13027 : : false, NULL, false));
13028 : :
13029 : 18 : nargs = 0;
13030 [ + - + + : 36 : foreach(l, tablesample->args)
+ + ]
13031 : : {
13032 [ - + ]: 18 : if (nargs++ > 0)
13033 : 0 : appendStringInfoString(buf, ", ");
13034 : 18 : get_rule_expr((Node *) lfirst(l), context, false);
13035 : : }
13036 : 18 : appendStringInfoChar(buf, ')');
13037 : :
13038 [ + + ]: 18 : if (tablesample->repeatable != NULL)
13039 : : {
13040 : 9 : appendStringInfoString(buf, " REPEATABLE (");
13041 : 9 : get_rule_expr((Node *) tablesample->repeatable, context, false);
13042 : 9 : appendStringInfoChar(buf, ')');
13043 : : }
13044 : 18 : }
13045 : :
13046 : : /*
13047 : : * get_opclass_name - fetch name of an index operator class
13048 : : *
13049 : : * The opclass name is appended (after a space) to buf.
13050 : : *
13051 : : * Output is suppressed if the opclass is the default for the given
13052 : : * actual_datatype. (If you don't want this behavior, just pass
13053 : : * InvalidOid for actual_datatype.)
13054 : : */
13055 : : static void
13056 : 7252 : get_opclass_name(Oid opclass, Oid actual_datatype,
13057 : : StringInfo buf)
13058 : : {
13059 : : HeapTuple ht_opc;
13060 : : Form_pg_opclass opcrec;
13061 : : char *opcname;
13062 : : char *nspname;
13063 : :
13064 : 7252 : ht_opc = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
13065 [ - + ]: 7252 : if (!HeapTupleIsValid(ht_opc))
13066 [ # # ]: 0 : elog(ERROR, "cache lookup failed for opclass %u", opclass);
13067 : 7252 : opcrec = (Form_pg_opclass) GETSTRUCT(ht_opc);
13068 : :
13069 [ + + + + ]: 14478 : if (!OidIsValid(actual_datatype) ||
13070 : 7226 : GetDefaultOpClass(actual_datatype, opcrec->opcmethod) != opclass)
13071 : : {
13072 : : /* Okay, we need the opclass name. Do we need to qualify it? */
13073 : 293 : opcname = NameStr(opcrec->opcname);
13074 [ + - ]: 293 : if (OpclassIsVisible(opclass))
13075 : 293 : appendStringInfo(buf, " %s", quote_identifier(opcname));
13076 : : else
13077 : : {
13078 : 0 : nspname = get_namespace_name_or_temp(opcrec->opcnamespace);
13079 : 0 : appendStringInfo(buf, " %s.%s",
13080 : : quote_identifier(nspname),
13081 : : quote_identifier(opcname));
13082 : : }
13083 : : }
13084 : 7252 : ReleaseSysCache(ht_opc);
13085 : 7252 : }
13086 : :
13087 : : /*
13088 : : * generate_opclass_name
13089 : : * Compute the name to display for an opclass specified by OID
13090 : : *
13091 : : * The result includes all necessary quoting and schema-prefixing.
13092 : : */
13093 : : char *
13094 : 4 : generate_opclass_name(Oid opclass)
13095 : : {
13096 : : StringInfoData buf;
13097 : :
13098 : 4 : initStringInfo(&buf);
13099 : 4 : get_opclass_name(opclass, InvalidOid, &buf);
13100 : :
13101 : 4 : return &buf.data[1]; /* get_opclass_name() prepends space */
13102 : : }
13103 : :
13104 : : /*
13105 : : * processIndirection - take care of array and subfield assignment
13106 : : *
13107 : : * We strip any top-level FieldStore or assignment SubscriptingRef nodes that
13108 : : * appear in the input, printing them as decoration for the base column
13109 : : * name (which we assume the caller just printed). We might also need to
13110 : : * strip CoerceToDomain nodes, but only ones that appear above assignment
13111 : : * nodes.
13112 : : *
13113 : : * Returns the subexpression that's to be assigned.
13114 : : */
13115 : : static Node *
13116 : 721 : processIndirection(Node *node, deparse_context *context)
13117 : : {
13118 : 721 : StringInfo buf = context->buf;
13119 : 721 : CoerceToDomain *cdomain = NULL;
13120 : :
13121 : : for (;;)
13122 : : {
13123 [ - + ]: 925 : if (node == NULL)
13124 : 0 : break;
13125 [ + + ]: 925 : if (IsA(node, FieldStore))
13126 : : {
13127 : 72 : FieldStore *fstore = (FieldStore *) node;
13128 : : Oid typrelid;
13129 : : char *fieldname;
13130 : :
13131 : : /* lookup tuple type */
13132 : 72 : typrelid = get_typ_typrelid(fstore->resulttype);
13133 [ - + ]: 72 : if (!OidIsValid(typrelid))
13134 [ # # ]: 0 : elog(ERROR, "argument type %s of FieldStore is not a tuple type",
13135 : : format_type_be(fstore->resulttype));
13136 : :
13137 : : /*
13138 : : * Print the field name. There should only be one target field in
13139 : : * stored rules. There could be more than that in executable
13140 : : * target lists, but this function cannot be used for that case.
13141 : : */
13142 : : Assert(list_length(fstore->fieldnums) == 1);
13143 : 72 : fieldname = get_attname(typrelid,
13144 : 72 : linitial_int(fstore->fieldnums), false);
13145 : 72 : appendStringInfo(buf, ".%s", quote_identifier(fieldname));
13146 : :
13147 : : /*
13148 : : * We ignore arg since it should be an uninteresting reference to
13149 : : * the target column or subcolumn.
13150 : : */
13151 : 72 : node = (Node *) linitial(fstore->newvals);
13152 : : }
13153 [ + + ]: 853 : else if (IsA(node, SubscriptingRef))
13154 : : {
13155 : 92 : SubscriptingRef *sbsref = (SubscriptingRef *) node;
13156 : :
13157 [ - + ]: 92 : if (sbsref->refassgnexpr == NULL)
13158 : 0 : break;
13159 : :
13160 : 92 : printSubscripts(sbsref, context);
13161 : :
13162 : : /*
13163 : : * We ignore refexpr since it should be an uninteresting reference
13164 : : * to the target column or subcolumn.
13165 : : */
13166 : 92 : node = (Node *) sbsref->refassgnexpr;
13167 : : }
13168 [ + + ]: 761 : else if (IsA(node, CoerceToDomain))
13169 : : {
13170 : 40 : cdomain = (CoerceToDomain *) node;
13171 : : /* If it's an explicit domain coercion, we're done */
13172 [ - + ]: 40 : if (cdomain->coercionformat != COERCE_IMPLICIT_CAST)
13173 : 0 : break;
13174 : : /* Tentatively descend past the CoerceToDomain */
13175 : 40 : node = (Node *) cdomain->arg;
13176 : : }
13177 : : else
13178 : 721 : break;
13179 : : }
13180 : :
13181 : : /*
13182 : : * If we descended past a CoerceToDomain whose argument turned out not to
13183 : : * be a FieldStore or array assignment, back up to the CoerceToDomain.
13184 : : * (This is not enough to be fully correct if there are nested implicit
13185 : : * CoerceToDomains, but such cases shouldn't ever occur.)
13186 : : */
13187 [ + + - + ]: 721 : if (cdomain && node == (Node *) cdomain->arg)
13188 : 0 : node = (Node *) cdomain;
13189 : :
13190 : 721 : return node;
13191 : : }
13192 : :
13193 : : static void
13194 : 320 : printSubscripts(SubscriptingRef *sbsref, deparse_context *context)
13195 : : {
13196 : 320 : StringInfo buf = context->buf;
13197 : : ListCell *lowlist_item;
13198 : : ListCell *uplist_item;
13199 : :
13200 : 320 : lowlist_item = list_head(sbsref->reflowerindexpr); /* could be NULL */
13201 [ + - + + : 640 : foreach(uplist_item, sbsref->refupperindexpr)
+ + ]
13202 : : {
13203 : 320 : appendStringInfoChar(buf, '[');
13204 [ - + ]: 320 : if (lowlist_item)
13205 : : {
13206 : : /* If subexpression is NULL, get_rule_expr prints nothing */
13207 : 0 : get_rule_expr((Node *) lfirst(lowlist_item), context, false);
13208 : 0 : appendStringInfoChar(buf, ':');
13209 : 0 : lowlist_item = lnext(sbsref->reflowerindexpr, lowlist_item);
13210 : : }
13211 : : /* If subexpression is NULL, get_rule_expr prints nothing */
13212 : 320 : get_rule_expr((Node *) lfirst(uplist_item), context, false);
13213 : 320 : appendStringInfoChar(buf, ']');
13214 : : }
13215 : 320 : }
13216 : :
13217 : : /*
13218 : : * quote_identifier - Quote an identifier only if needed
13219 : : *
13220 : : * When quotes are needed, we palloc the required space; slightly
13221 : : * space-wasteful but well worth it for notational simplicity.
13222 : : */
13223 : : const char *
13224 : 1860706 : quote_identifier(const char *ident)
13225 : : {
13226 : : /*
13227 : : * Can avoid quoting if ident starts with a lowercase letter or underscore
13228 : : * and contains only lowercase letters, digits, and underscores, *and* is
13229 : : * not any SQL keyword. Otherwise, supply quotes.
13230 : : */
13231 : 1860706 : int nquotes = 0;
13232 : : bool safe;
13233 : : const char *ptr;
13234 : : char *result;
13235 : : char *optr;
13236 : :
13237 : : /*
13238 : : * would like to use <ctype.h> macros here, but they might yield unwanted
13239 : : * locale-specific results...
13240 : : */
13241 [ + + - + : 1860706 : safe = ((ident[0] >= 'a' && ident[0] <= 'z') || ident[0] == '_');
+ + ]
13242 : :
13243 [ + + ]: 16338455 : for (ptr = ident; *ptr; ptr++)
13244 : : {
13245 : 14477749 : char ch = *ptr;
13246 : :
13247 [ + + + - : 14477749 : if ((ch >= 'a' && ch <= 'z') ||
+ + ]
13248 [ + + + + ]: 2198425 : (ch >= '0' && ch <= '9') ||
13249 : : (ch == '_'))
13250 : : {
13251 : : /* okay */
13252 : : }
13253 : : else
13254 : : {
13255 : 363445 : safe = false;
13256 [ + + ]: 363445 : if (ch == '"')
13257 : 89 : nquotes++;
13258 : : }
13259 : : }
13260 : :
13261 [ + + ]: 1860706 : if (quote_all_identifiers)
13262 : 6832 : safe = false;
13263 : :
13264 [ + + ]: 1860706 : if (safe)
13265 : : {
13266 : : /*
13267 : : * Check for keyword. We quote keywords except for unreserved ones.
13268 : : * (In some cases we could avoid quoting a col_name or type_func_name
13269 : : * keyword, but it seems much harder than it's worth to tell that.)
13270 : : *
13271 : : * Note: ScanKeywordLookup() does case-insensitive comparison, but
13272 : : * that's fine, since we already know we have all-lower-case.
13273 : : */
13274 : 1798948 : int kwnum = ScanKeywordLookup(ident, &ScanKeywords);
13275 : :
13276 [ + + + + ]: 1798948 : if (kwnum >= 0 && ScanKeywordCategories[kwnum] != UNRESERVED_KEYWORD)
13277 : 2424 : safe = false;
13278 : : }
13279 : :
13280 [ + + ]: 1860706 : if (safe)
13281 : 1796524 : return ident; /* no change needed */
13282 : :
13283 : 64182 : result = (char *) palloc(strlen(ident) + nquotes + 2 + 1);
13284 : :
13285 : 64182 : optr = result;
13286 : 64182 : *optr++ = '"';
13287 [ + + ]: 513246 : for (ptr = ident; *ptr; ptr++)
13288 : : {
13289 : 449064 : char ch = *ptr;
13290 : :
13291 [ + + ]: 449064 : if (ch == '"')
13292 : 89 : *optr++ = '"';
13293 : 449064 : *optr++ = ch;
13294 : : }
13295 : 64182 : *optr++ = '"';
13296 : 64182 : *optr = '\0';
13297 : :
13298 : 64182 : return result;
13299 : : }
13300 : :
13301 : : /*
13302 : : * quote_qualified_identifier - Quote a possibly-qualified identifier
13303 : : *
13304 : : * Return a name of the form qualifier.ident, or just ident if qualifier
13305 : : * is NULL, quoting each component if necessary. The result is palloc'd.
13306 : : */
13307 : : char *
13308 : 721427 : quote_qualified_identifier(const char *qualifier,
13309 : : const char *ident)
13310 : : {
13311 : : StringInfoData buf;
13312 : :
13313 : 721427 : initStringInfo(&buf);
13314 [ + + ]: 721427 : if (qualifier)
13315 : 248039 : appendStringInfo(&buf, "%s.", quote_identifier(qualifier));
13316 : 721427 : appendStringInfoString(&buf, quote_identifier(ident));
13317 : 721427 : return buf.data;
13318 : : }
13319 : :
13320 : : /*
13321 : : * get_relation_name
13322 : : * Get the unqualified name of a relation specified by OID
13323 : : *
13324 : : * This differs from the underlying get_rel_name() function in that it will
13325 : : * throw error instead of silently returning NULL if the OID is bad.
13326 : : */
13327 : : static char *
13328 : 9990 : get_relation_name(Oid relid)
13329 : : {
13330 : 9990 : char *relname = get_rel_name(relid);
13331 : :
13332 [ - + ]: 9990 : if (!relname)
13333 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", relid);
13334 : 9990 : return relname;
13335 : : }
13336 : :
13337 : : /*
13338 : : * generate_relation_name
13339 : : * Compute the name to display for a relation specified by OID
13340 : : *
13341 : : * The result includes all necessary quoting and schema-prefixing.
13342 : : *
13343 : : * If namespaces isn't NIL, it must be a list of deparse_namespace nodes.
13344 : : * We will forcibly qualify the relation name if it equals any CTE name
13345 : : * visible in the namespace list.
13346 : : */
13347 : : static char *
13348 : 4975 : generate_relation_name(Oid relid, List *namespaces)
13349 : : {
13350 : : HeapTuple tp;
13351 : : Form_pg_class reltup;
13352 : : bool need_qual;
13353 : : ListCell *nslist;
13354 : : char *relname;
13355 : : char *nspname;
13356 : : char *result;
13357 : :
13358 : 4975 : tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
13359 [ - + ]: 4975 : if (!HeapTupleIsValid(tp))
13360 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", relid);
13361 : 4975 : reltup = (Form_pg_class) GETSTRUCT(tp);
13362 : 4975 : relname = NameStr(reltup->relname);
13363 : :
13364 : : /* Check for conflicting CTE name */
13365 : 4975 : need_qual = false;
13366 [ + + + + : 8471 : foreach(nslist, namespaces)
+ + ]
13367 : : {
13368 : 3496 : deparse_namespace *dpns = (deparse_namespace *) lfirst(nslist);
13369 : : ListCell *ctlist;
13370 : :
13371 [ + + + + : 3584 : foreach(ctlist, dpns->ctes)
+ + ]
13372 : : {
13373 : 88 : CommonTableExpr *cte = (CommonTableExpr *) lfirst(ctlist);
13374 : :
13375 [ - + ]: 88 : if (strcmp(cte->ctename, relname) == 0)
13376 : : {
13377 : 0 : need_qual = true;
13378 : 0 : break;
13379 : : }
13380 : : }
13381 [ - + ]: 3496 : if (need_qual)
13382 : 0 : break;
13383 : : }
13384 : :
13385 : : /* Otherwise, qualify the name if not visible in search path */
13386 [ + - ]: 4975 : if (!need_qual)
13387 : 4975 : need_qual = !RelationIsVisible(relid);
13388 : :
13389 [ + + ]: 4975 : if (need_qual)
13390 : 1272 : nspname = get_namespace_name_or_temp(reltup->relnamespace);
13391 : : else
13392 : 3703 : nspname = NULL;
13393 : :
13394 : 4975 : result = quote_qualified_identifier(nspname, relname);
13395 : :
13396 : 4975 : ReleaseSysCache(tp);
13397 : :
13398 : 4975 : return result;
13399 : : }
13400 : :
13401 : : /*
13402 : : * generate_qualified_relation_name
13403 : : * Compute the name to display for a relation specified by OID
13404 : : *
13405 : : * As above, but unconditionally schema-qualify the name.
13406 : : */
13407 : : static char *
13408 : 4544 : generate_qualified_relation_name(Oid relid)
13409 : : {
13410 : : HeapTuple tp;
13411 : : Form_pg_class reltup;
13412 : : char *result;
13413 : :
13414 : 4544 : tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
13415 [ - + ]: 4544 : if (!HeapTupleIsValid(tp))
13416 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", relid);
13417 : 4544 : reltup = (Form_pg_class) GETSTRUCT(tp);
13418 : :
13419 : 4544 : result = get_qualified_objname(reltup->relnamespace,
13420 : 4544 : NameStr(reltup->relname));
13421 : 4544 : ReleaseSysCache(tp);
13422 : :
13423 : 4544 : return result;
13424 : : }
13425 : :
13426 : : /*
13427 : : * generate_function_name
13428 : : * Compute the name to display for a function specified by OID,
13429 : : * given that it is being called with the specified actual arg names and
13430 : : * types. (Those matter because of ambiguous-function resolution rules.)
13431 : : *
13432 : : * If we're dealing with a potentially variadic function (in practice, this
13433 : : * means a FuncExpr or Aggref, not some other way of calling a function), then
13434 : : * has_variadic must specify whether variadic arguments have been merged,
13435 : : * and *use_variadic_p will be set to indicate whether to print VARIADIC in
13436 : : * the output. For non-FuncExpr cases, has_variadic should be false and
13437 : : * use_variadic_p can be NULL.
13438 : : *
13439 : : * inGroupBy must be true if we're deparsing a GROUP BY clause.
13440 : : *
13441 : : * The result includes all necessary quoting and schema-prefixing.
13442 : : */
13443 : : static char *
13444 : 9704 : generate_function_name(Oid funcid, int nargs, List *argnames, Oid *argtypes,
13445 : : bool has_variadic, bool *use_variadic_p,
13446 : : bool inGroupBy)
13447 : : {
13448 : : char *result;
13449 : : HeapTuple proctup;
13450 : : Form_pg_proc procform;
13451 : : char *proname;
13452 : : bool use_variadic;
13453 : : char *nspname;
13454 : : FuncDetailCode p_result;
13455 : : int fgc_flags;
13456 : : Oid p_funcid;
13457 : : Oid p_rettype;
13458 : : bool p_retset;
13459 : : int p_nvargs;
13460 : : Oid p_vatype;
13461 : : Oid *p_true_typeids;
13462 : 9704 : bool force_qualify = false;
13463 : :
13464 : 9704 : proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
13465 [ - + ]: 9704 : if (!HeapTupleIsValid(proctup))
13466 [ # # ]: 0 : elog(ERROR, "cache lookup failed for function %u", funcid);
13467 : 9704 : procform = (Form_pg_proc) GETSTRUCT(proctup);
13468 : 9704 : proname = NameStr(procform->proname);
13469 : :
13470 : : /*
13471 : : * Due to parser hacks to avoid needing to reserve CUBE, we need to force
13472 : : * qualification of some function names within GROUP BY.
13473 : : */
13474 [ - + ]: 9704 : if (inGroupBy)
13475 : : {
13476 [ # # # # ]: 0 : if (strcmp(proname, "cube") == 0 || strcmp(proname, "rollup") == 0)
13477 : 0 : force_qualify = true;
13478 : : }
13479 : :
13480 : : /*
13481 : : * Determine whether VARIADIC should be printed. We must do this first
13482 : : * since it affects the lookup rules in func_get_detail().
13483 : : *
13484 : : * We always print VARIADIC if the function has a merged variadic-array
13485 : : * argument. Note that this is always the case for functions taking a
13486 : : * VARIADIC argument type other than VARIADIC ANY. If we omitted VARIADIC
13487 : : * and printed the array elements as separate arguments, the call could
13488 : : * match a newer non-VARIADIC function.
13489 : : */
13490 [ + + ]: 9704 : if (use_variadic_p)
13491 : : {
13492 : : /* Parser should not have set funcvariadic unless fn is variadic */
13493 : : Assert(!has_variadic || OidIsValid(procform->provariadic));
13494 : 8709 : use_variadic = has_variadic;
13495 : 8709 : *use_variadic_p = use_variadic;
13496 : : }
13497 : : else
13498 : : {
13499 : : Assert(!has_variadic);
13500 : 995 : use_variadic = false;
13501 : : }
13502 : :
13503 : : /*
13504 : : * The idea here is to schema-qualify only if the parser would fail to
13505 : : * resolve the correct function given the unqualified func name with the
13506 : : * specified argtypes and VARIADIC flag. But if we already decided to
13507 : : * force qualification, then we can skip the lookup and pretend we didn't
13508 : : * find it.
13509 : : */
13510 [ + - ]: 9704 : if (!force_qualify)
13511 : 9704 : p_result = func_get_detail(list_make1(makeString(proname)),
13512 : : NIL, argnames, nargs, argtypes,
13513 : : !use_variadic, true, false,
13514 : : &fgc_flags,
13515 : : &p_funcid, &p_rettype,
13516 : : &p_retset, &p_nvargs, &p_vatype,
13517 : 9704 : &p_true_typeids, NULL);
13518 : : else
13519 : : {
13520 : 0 : p_result = FUNCDETAIL_NOTFOUND;
13521 : 0 : p_funcid = InvalidOid;
13522 : : }
13523 : :
13524 [ + + + + ]: 9704 : if ((p_result == FUNCDETAIL_NORMAL ||
13525 [ + + ]: 683 : p_result == FUNCDETAIL_AGGREGATE ||
13526 : 9117 : p_result == FUNCDETAIL_WINDOWFUNC) &&
13527 [ + - ]: 9117 : p_funcid == funcid)
13528 : 9117 : nspname = NULL;
13529 : : else
13530 : 587 : nspname = get_namespace_name_or_temp(procform->pronamespace);
13531 : :
13532 : 9704 : result = quote_qualified_identifier(nspname, proname);
13533 : :
13534 : 9704 : ReleaseSysCache(proctup);
13535 : :
13536 : 9704 : return result;
13537 : : }
13538 : :
13539 : : /*
13540 : : * generate_operator_name
13541 : : * Compute the name to display for an operator specified by OID,
13542 : : * given that it is being called with the specified actual arg types.
13543 : : * (Arg types matter because of ambiguous-operator resolution rules.
13544 : : * Pass InvalidOid for unused arg of a unary operator.)
13545 : : *
13546 : : * The result includes all necessary quoting and schema-prefixing,
13547 : : * plus the OPERATOR() decoration needed to use a qualified operator name
13548 : : * in an expression.
13549 : : */
13550 : : static char *
13551 : 44036 : generate_operator_name(Oid operid, Oid arg1, Oid arg2)
13552 : : {
13553 : : StringInfoData buf;
13554 : : HeapTuple opertup;
13555 : : Form_pg_operator operform;
13556 : : char *oprname;
13557 : : char *nspname;
13558 : : Operator p_result;
13559 : :
13560 : 44036 : initStringInfo(&buf);
13561 : :
13562 : 44036 : opertup = SearchSysCache1(OPEROID, ObjectIdGetDatum(operid));
13563 [ - + ]: 44036 : if (!HeapTupleIsValid(opertup))
13564 [ # # ]: 0 : elog(ERROR, "cache lookup failed for operator %u", operid);
13565 : 44036 : operform = (Form_pg_operator) GETSTRUCT(opertup);
13566 : 44036 : oprname = NameStr(operform->oprname);
13567 : :
13568 : : /*
13569 : : * The idea here is to schema-qualify only if the parser would fail to
13570 : : * resolve the correct operator given the unqualified op name with the
13571 : : * specified argtypes.
13572 : : */
13573 [ + + - ]: 44036 : switch (operform->oprkind)
13574 : : {
13575 : 44016 : case 'b':
13576 : 44016 : p_result = oper(NULL, list_make1(makeString(oprname)), arg1, arg2,
13577 : : true, -1);
13578 : 44016 : break;
13579 : 20 : case 'l':
13580 : 20 : p_result = left_oper(NULL, list_make1(makeString(oprname)), arg2,
13581 : : true, -1);
13582 : 20 : break;
13583 : 0 : default:
13584 [ # # ]: 0 : elog(ERROR, "unrecognized oprkind: %d", operform->oprkind);
13585 : : p_result = NULL; /* keep compiler quiet */
13586 : : break;
13587 : : }
13588 : :
13589 [ + + + - ]: 44036 : if (p_result != NULL && oprid(p_result) == operid)
13590 : 44031 : nspname = NULL;
13591 : : else
13592 : : {
13593 : 5 : nspname = get_namespace_name_or_temp(operform->oprnamespace);
13594 : 5 : appendStringInfo(&buf, "OPERATOR(%s.", quote_identifier(nspname));
13595 : : }
13596 : :
13597 : 44036 : appendStringInfoString(&buf, oprname);
13598 : :
13599 [ + + ]: 44036 : if (nspname)
13600 : 5 : appendStringInfoChar(&buf, ')');
13601 : :
13602 [ + + ]: 44036 : if (p_result != NULL)
13603 : 44031 : ReleaseSysCache(p_result);
13604 : :
13605 : 44036 : ReleaseSysCache(opertup);
13606 : :
13607 : 44036 : return buf.data;
13608 : : }
13609 : :
13610 : : /*
13611 : : * generate_operator_clause --- generate a binary-operator WHERE clause
13612 : : *
13613 : : * This is used for internally-generated-and-executed SQL queries, where
13614 : : * precision is essential and readability is secondary. The basic
13615 : : * requirement is to append "leftop op rightop" to buf, where leftop and
13616 : : * rightop are given as strings and are assumed to yield types leftoptype
13617 : : * and rightoptype; the operator is identified by OID. The complexity
13618 : : * comes from needing to be sure that the parser will select the desired
13619 : : * operator when the query is parsed. We always name the operator using
13620 : : * OPERATOR(schema.op) syntax, so as to avoid search-path uncertainties.
13621 : : * We have to emit casts too, if either input isn't already the input type
13622 : : * of the operator; else we are at the mercy of the parser's heuristics for
13623 : : * ambiguous-operator resolution. The caller must ensure that leftop and
13624 : : * rightop are suitable arguments for a cast operation; it's best to insert
13625 : : * parentheses if they aren't just variables or parameters.
13626 : : */
13627 : : void
13628 : 3135 : generate_operator_clause(StringInfo buf,
13629 : : const char *leftop, Oid leftoptype,
13630 : : Oid opoid,
13631 : : const char *rightop, Oid rightoptype)
13632 : : {
13633 : : HeapTuple opertup;
13634 : : Form_pg_operator operform;
13635 : : char *oprname;
13636 : : char *nspname;
13637 : :
13638 : 3135 : opertup = SearchSysCache1(OPEROID, ObjectIdGetDatum(opoid));
13639 [ - + ]: 3135 : if (!HeapTupleIsValid(opertup))
13640 [ # # ]: 0 : elog(ERROR, "cache lookup failed for operator %u", opoid);
13641 : 3135 : operform = (Form_pg_operator) GETSTRUCT(opertup);
13642 : : Assert(operform->oprkind == 'b');
13643 : 3135 : oprname = NameStr(operform->oprname);
13644 : :
13645 : 3135 : nspname = get_namespace_name(operform->oprnamespace);
13646 : :
13647 : 3135 : appendStringInfoString(buf, leftop);
13648 [ + + ]: 3135 : if (leftoptype != operform->oprleft)
13649 : 743 : add_cast_to(buf, operform->oprleft);
13650 : 3135 : appendStringInfo(buf, " OPERATOR(%s.", quote_identifier(nspname));
13651 : 3135 : appendStringInfoString(buf, oprname);
13652 : 3135 : appendStringInfo(buf, ") %s", rightop);
13653 [ + + ]: 3135 : if (rightoptype != operform->oprright)
13654 : 597 : add_cast_to(buf, operform->oprright);
13655 : :
13656 : 3135 : ReleaseSysCache(opertup);
13657 : 3135 : }
13658 : :
13659 : : /*
13660 : : * Add a cast specification to buf. We spell out the type name the hard way,
13661 : : * intentionally not using format_type_be(). This is to avoid corner cases
13662 : : * for CHARACTER, BIT, and perhaps other types, where specifying the type
13663 : : * using SQL-standard syntax results in undesirable data truncation. By
13664 : : * doing it this way we can be certain that the cast will have default (-1)
13665 : : * target typmod.
13666 : : */
13667 : : static void
13668 : 1340 : add_cast_to(StringInfo buf, Oid typid)
13669 : : {
13670 : : HeapTuple typetup;
13671 : : Form_pg_type typform;
13672 : : char *typname;
13673 : : char *nspname;
13674 : :
13675 : 1340 : typetup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
13676 [ - + ]: 1340 : if (!HeapTupleIsValid(typetup))
13677 [ # # ]: 0 : elog(ERROR, "cache lookup failed for type %u", typid);
13678 : 1340 : typform = (Form_pg_type) GETSTRUCT(typetup);
13679 : :
13680 : 1340 : typname = NameStr(typform->typname);
13681 : 1340 : nspname = get_namespace_name_or_temp(typform->typnamespace);
13682 : :
13683 : 1340 : appendStringInfo(buf, "::%s.%s",
13684 : : quote_identifier(nspname), quote_identifier(typname));
13685 : :
13686 : 1340 : ReleaseSysCache(typetup);
13687 : 1340 : }
13688 : :
13689 : : /*
13690 : : * generate_qualified_type_name
13691 : : * Compute the name to display for a type specified by OID
13692 : : *
13693 : : * This is different from format_type_be() in that we unconditionally
13694 : : * schema-qualify the name. That also means no special syntax for
13695 : : * SQL-standard type names ... although in current usage, this should
13696 : : * only get used for domains, so such cases wouldn't occur anyway.
13697 : : */
13698 : : static char *
13699 : 13 : generate_qualified_type_name(Oid typid)
13700 : : {
13701 : : HeapTuple tp;
13702 : : Form_pg_type typtup;
13703 : : char *typname;
13704 : : char *nspname;
13705 : : char *result;
13706 : :
13707 : 13 : tp = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
13708 [ - + ]: 13 : if (!HeapTupleIsValid(tp))
13709 [ # # ]: 0 : elog(ERROR, "cache lookup failed for type %u", typid);
13710 : 13 : typtup = (Form_pg_type) GETSTRUCT(tp);
13711 : 13 : typname = NameStr(typtup->typname);
13712 : :
13713 : 13 : nspname = get_namespace_name_or_temp(typtup->typnamespace);
13714 [ - + ]: 13 : if (!nspname)
13715 [ # # ]: 0 : elog(ERROR, "cache lookup failed for namespace %u",
13716 : : typtup->typnamespace);
13717 : :
13718 : 13 : result = quote_qualified_identifier(nspname, typname);
13719 : :
13720 : 13 : ReleaseSysCache(tp);
13721 : :
13722 : 13 : return result;
13723 : : }
13724 : :
13725 : : /*
13726 : : * generate_collation_name
13727 : : * Compute the name to display for a collation specified by OID
13728 : : *
13729 : : * The result includes all necessary quoting and schema-prefixing.
13730 : : */
13731 : : char *
13732 : 306 : generate_collation_name(Oid collid)
13733 : : {
13734 : : HeapTuple tp;
13735 : : Form_pg_collation colltup;
13736 : : char *collname;
13737 : : char *nspname;
13738 : : char *result;
13739 : :
13740 : 306 : tp = SearchSysCache1(COLLOID, ObjectIdGetDatum(collid));
13741 [ - + ]: 306 : if (!HeapTupleIsValid(tp))
13742 [ # # ]: 0 : elog(ERROR, "cache lookup failed for collation %u", collid);
13743 : 306 : colltup = (Form_pg_collation) GETSTRUCT(tp);
13744 : 306 : collname = NameStr(colltup->collname);
13745 : :
13746 [ - + ]: 306 : if (!CollationIsVisible(collid))
13747 : 0 : nspname = get_namespace_name_or_temp(colltup->collnamespace);
13748 : : else
13749 : 306 : nspname = NULL;
13750 : :
13751 : 306 : result = quote_qualified_identifier(nspname, collname);
13752 : :
13753 : 306 : ReleaseSysCache(tp);
13754 : :
13755 : 306 : return result;
13756 : : }
13757 : :
13758 : : /*
13759 : : * Given a C string, produce a TEXT datum.
13760 : : *
13761 : : * We assume that the input was palloc'd and may be freed.
13762 : : */
13763 : : static text *
13764 : 25202 : string_to_text(char *str)
13765 : : {
13766 : : text *result;
13767 : :
13768 : 25202 : result = cstring_to_text(str);
13769 : 25202 : pfree(str);
13770 : 25202 : return result;
13771 : : }
13772 : :
13773 : : /*
13774 : : * Generate a C string representing a relation options from text[] datum.
13775 : : */
13776 : : void
13777 : 131 : get_reloptions(StringInfo buf, Datum reloptions)
13778 : : {
13779 : : Datum *options;
13780 : : int noptions;
13781 : : int i;
13782 : :
13783 : 131 : deconstruct_array_builtin(DatumGetArrayTypeP(reloptions), TEXTOID,
13784 : : &options, NULL, &noptions);
13785 : :
13786 [ + + ]: 284 : for (i = 0; i < noptions; i++)
13787 : : {
13788 : 153 : char *option = TextDatumGetCString(options[i]);
13789 : : char *name;
13790 : : char *separator;
13791 : : char *value;
13792 : :
13793 : : /*
13794 : : * Each array element should have the form name=value. If the "=" is
13795 : : * missing for some reason, treat it like an empty value.
13796 : : */
13797 : 153 : name = option;
13798 : 153 : separator = strchr(option, '=');
13799 [ + - ]: 153 : if (separator)
13800 : : {
13801 : 153 : *separator = '\0';
13802 : 153 : value = separator + 1;
13803 : : }
13804 : : else
13805 : 0 : value = "";
13806 : :
13807 [ + + ]: 153 : if (i > 0)
13808 : 22 : appendStringInfoString(buf, ", ");
13809 : 153 : appendStringInfo(buf, "%s=", quote_identifier(name));
13810 : :
13811 : : /*
13812 : : * In general we need to quote the value; but to avoid unnecessary
13813 : : * clutter, do not quote if it is an identifier that would not need
13814 : : * quoting. (We could also allow numbers, but that is a bit trickier
13815 : : * than it looks --- for example, are leading zeroes significant? We
13816 : : * don't want to assume very much here about what custom reloptions
13817 : : * might mean.)
13818 : : */
13819 [ + + ]: 153 : if (quote_identifier(value) == value)
13820 : 4 : appendStringInfoString(buf, value);
13821 : : else
13822 : 149 : simple_quote_literal(buf, value);
13823 : :
13824 : 153 : pfree(option);
13825 : : }
13826 : 131 : }
13827 : :
13828 : : /*
13829 : : * Generate a C string representing a relation's reloptions, or NULL if none.
13830 : : */
13831 : : static char *
13832 : 4494 : flatten_reloptions(Oid relid)
13833 : : {
13834 : 4494 : char *result = NULL;
13835 : : HeapTuple tuple;
13836 : : Datum reloptions;
13837 : : bool isnull;
13838 : :
13839 : 4494 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
13840 [ - + ]: 4494 : if (!HeapTupleIsValid(tuple))
13841 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", relid);
13842 : :
13843 : 4494 : reloptions = SysCacheGetAttr(RELOID, tuple,
13844 : : Anum_pg_class_reloptions, &isnull);
13845 [ + + ]: 4494 : if (!isnull)
13846 : : {
13847 : : StringInfoData buf;
13848 : :
13849 : 105 : initStringInfo(&buf);
13850 : 105 : get_reloptions(&buf, reloptions);
13851 : :
13852 : 105 : result = buf.data;
13853 : : }
13854 : :
13855 : 4494 : ReleaseSysCache(tuple);
13856 : :
13857 : 4494 : return result;
13858 : : }
13859 : :
13860 : : /*
13861 : : * get_range_partbound_string
13862 : : * A C string representation of one range partition bound
13863 : : */
13864 : : char *
13865 : 2702 : get_range_partbound_string(List *bound_datums)
13866 : : {
13867 : : deparse_context context;
13868 : : StringInfoData buf;
13869 : : ListCell *cell;
13870 : : char *sep;
13871 : :
13872 : 2702 : initStringInfo(&buf);
13873 : 2702 : memset(&context, 0, sizeof(deparse_context));
13874 : 2702 : context.buf = &buf;
13875 : :
13876 : 2702 : appendStringInfoChar(&buf, '(');
13877 : 2702 : sep = "";
13878 [ + - + + : 5882 : foreach(cell, bound_datums)
+ + ]
13879 : : {
13880 : 3180 : PartitionRangeDatum *datum =
13881 : : lfirst_node(PartitionRangeDatum, cell);
13882 : :
13883 : 3180 : appendStringInfoString(&buf, sep);
13884 [ + + ]: 3180 : if (datum->kind == PARTITION_RANGE_DATUM_MINVALUE)
13885 : 148 : appendStringInfoString(&buf, "MINVALUE");
13886 [ + + ]: 3032 : else if (datum->kind == PARTITION_RANGE_DATUM_MAXVALUE)
13887 : 80 : appendStringInfoString(&buf, "MAXVALUE");
13888 : : else
13889 : : {
13890 : 2952 : Const *val = castNode(Const, datum->value);
13891 : :
13892 : 2952 : get_const_expr(val, &context, -1);
13893 : : }
13894 : 3180 : sep = ", ";
13895 : : }
13896 : 2702 : appendStringInfoChar(&buf, ')');
13897 : :
13898 : 2702 : return buf.data;
13899 : : }
|