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_propgraph_element.h"
38 : : #include "catalog/pg_propgraph_element_label.h"
39 : : #include "catalog/pg_propgraph_label.h"
40 : : #include "catalog/pg_propgraph_label_property.h"
41 : : #include "catalog/pg_propgraph_property.h"
42 : : #include "catalog/pg_statistic_ext.h"
43 : : #include "catalog/pg_trigger.h"
44 : : #include "catalog/pg_type.h"
45 : : #include "commands/defrem.h"
46 : : #include "commands/tablespace.h"
47 : : #include "common/keywords.h"
48 : : #include "executor/spi.h"
49 : : #include "funcapi.h"
50 : : #include "mb/pg_wchar.h"
51 : : #include "miscadmin.h"
52 : : #include "nodes/makefuncs.h"
53 : : #include "nodes/nodeFuncs.h"
54 : : #include "nodes/pathnodes.h"
55 : : #include "optimizer/optimizer.h"
56 : : #include "parser/parse_agg.h"
57 : : #include "parser/parse_func.h"
58 : : #include "parser/parse_oper.h"
59 : : #include "parser/parse_relation.h"
60 : : #include "parser/parser.h"
61 : : #include "parser/parsetree.h"
62 : : #include "rewrite/rewriteHandler.h"
63 : : #include "rewrite/rewriteManip.h"
64 : : #include "rewrite/rewriteSupport.h"
65 : : #include "utils/array.h"
66 : : #include "utils/builtins.h"
67 : : #include "utils/fmgroids.h"
68 : : #include "utils/guc.h"
69 : : #include "utils/hsearch.h"
70 : : #include "utils/lsyscache.h"
71 : : #include "utils/partcache.h"
72 : : #include "utils/rel.h"
73 : : #include "utils/ruleutils.h"
74 : : #include "utils/snapmgr.h"
75 : : #include "utils/syscache.h"
76 : : #include "utils/typcache.h"
77 : : #include "utils/varlena.h"
78 : : #include "utils/xml.h"
79 : :
80 : : /* ----------
81 : : * Pretty formatting constants
82 : : * ----------
83 : : */
84 : :
85 : : /* Indent counts */
86 : : #define PRETTYINDENT_STD 8
87 : : #define PRETTYINDENT_JOIN 4
88 : : #define PRETTYINDENT_VAR 4
89 : :
90 : : #define PRETTYINDENT_LIMIT 40 /* wrap limit */
91 : :
92 : : /* Pretty flags */
93 : : #define PRETTYFLAG_PAREN 0x0001
94 : : #define PRETTYFLAG_INDENT 0x0002
95 : : #define PRETTYFLAG_SCHEMA 0x0004
96 : :
97 : : /* Standard conversion of a "bool pretty" option to detailed flags */
98 : : #define GET_PRETTY_FLAGS(pretty) \
99 : : ((pretty) ? (PRETTYFLAG_PAREN | PRETTYFLAG_INDENT | PRETTYFLAG_SCHEMA) \
100 : : : PRETTYFLAG_INDENT)
101 : :
102 : : /* Default line length for pretty-print wrapping: 0 means wrap always */
103 : : #define WRAP_COLUMN_DEFAULT 0
104 : :
105 : : /* macros to test if pretty action needed */
106 : : #define PRETTY_PAREN(context) ((context)->prettyFlags & PRETTYFLAG_PAREN)
107 : : #define PRETTY_INDENT(context) ((context)->prettyFlags & PRETTYFLAG_INDENT)
108 : : #define PRETTY_SCHEMA(context) ((context)->prettyFlags & PRETTYFLAG_SCHEMA)
109 : :
110 : :
111 : : /* ----------
112 : : * Local data types
113 : : * ----------
114 : : */
115 : :
116 : : /* Context info needed for invoking a recursive querytree display routine */
117 : : typedef struct
118 : : {
119 : : StringInfo buf; /* output buffer to append to */
120 : : List *namespaces; /* List of deparse_namespace nodes */
121 : : TupleDesc resultDesc; /* if top level of a view, the view's tupdesc */
122 : : List *targetList; /* Current query level's SELECT targetlist */
123 : : List *windowClause; /* Current query level's WINDOW clause */
124 : : int prettyFlags; /* enabling of pretty-print functions */
125 : : int wrapColumn; /* max line length, or -1 for no limit */
126 : : int indentLevel; /* current indent level for pretty-print */
127 : : bool varprefix; /* true to print prefixes on Vars */
128 : : bool colNamesVisible; /* do we care about output column names? */
129 : : bool inGroupBy; /* deparsing GROUP BY clause? */
130 : : bool varInOrderBy; /* deparsing simple Var in ORDER BY? */
131 : : Bitmapset *appendparents; /* if not null, map child Vars of these relids
132 : : * back to the parent rel */
133 : : } deparse_context;
134 : :
135 : : /*
136 : : * Each level of query context around a subtree needs a level of Var namespace.
137 : : * A Var having varlevelsup=N refers to the N'th item (counting from 0) in
138 : : * the current context's namespaces list.
139 : : *
140 : : * rtable is the list of actual RTEs from the Query or PlannedStmt.
141 : : * rtable_names holds the alias name to be used for each RTE (either a C
142 : : * string, or NULL for nameless RTEs such as unnamed joins).
143 : : * rtable_columns holds the column alias names to be used for each RTE.
144 : : *
145 : : * subplans is a list of Plan trees for SubPlans and CTEs (it's only used
146 : : * in the PlannedStmt case).
147 : : * ctes is a list of CommonTableExpr nodes (only used in the Query case).
148 : : * appendrels, if not null (it's only used in the PlannedStmt case), is an
149 : : * array of AppendRelInfo nodes, indexed by child relid. We use that to map
150 : : * child-table Vars to their inheritance parents.
151 : : *
152 : : * In some cases we need to make names of merged JOIN USING columns unique
153 : : * across the whole query, not only per-RTE. If so, unique_using is true
154 : : * and using_names is a list of C strings representing names already assigned
155 : : * to USING columns.
156 : : *
157 : : * When deparsing plan trees, there is always just a single item in the
158 : : * deparse_namespace list (since a plan tree never contains Vars with
159 : : * varlevelsup > 0). We store the Plan node that is the immediate
160 : : * parent of the expression to be deparsed, as well as a list of that
161 : : * Plan's ancestors. In addition, we store its outer and inner subplan nodes,
162 : : * as well as their targetlists, and the index tlist if the current plan node
163 : : * might contain INDEX_VAR Vars. (These fields could be derived on-the-fly
164 : : * from the current Plan node, but it seems notationally clearer to set them
165 : : * up as separate fields.)
166 : : */
167 : : typedef struct
168 : : {
169 : : List *rtable; /* List of RangeTblEntry nodes */
170 : : List *rtable_names; /* Parallel list of names for RTEs */
171 : : List *rtable_columns; /* Parallel list of deparse_columns structs */
172 : : List *subplans; /* List of Plan trees for SubPlans */
173 : : List *ctes; /* List of CommonTableExpr nodes */
174 : : AppendRelInfo **appendrels; /* Array of AppendRelInfo nodes, or NULL */
175 : : char *ret_old_alias; /* alias for OLD in RETURNING list */
176 : : char *ret_new_alias; /* alias for NEW in RETURNING list */
177 : : /* Workspace for column alias assignment: */
178 : : bool unique_using; /* Are we making USING names globally unique */
179 : : List *using_names; /* List of assigned names for USING columns */
180 : : /* Remaining fields are used only when deparsing a Plan tree: */
181 : : Plan *plan; /* immediate parent of current expression */
182 : : List *ancestors; /* ancestors of plan */
183 : : Plan *outer_plan; /* outer subnode, or NULL if none */
184 : : Plan *inner_plan; /* inner subnode, or NULL if none */
185 : : List *outer_tlist; /* referent for OUTER_VAR Vars */
186 : : List *inner_tlist; /* referent for INNER_VAR Vars */
187 : : List *index_tlist; /* referent for INDEX_VAR Vars */
188 : : /* Special namespace representing a function signature: */
189 : : char *funcname;
190 : : int numargs;
191 : : char **argnames;
192 : : } deparse_namespace;
193 : :
194 : : /*
195 : : * Per-relation data about column alias names.
196 : : *
197 : : * Selecting aliases is unreasonably complicated because of the need to dump
198 : : * rules/views whose underlying tables may have had columns added, deleted, or
199 : : * renamed since the query was parsed. We must nonetheless print the rule/view
200 : : * in a form that can be reloaded and will produce the same results as before.
201 : : *
202 : : * For each RTE used in the query, we must assign column aliases that are
203 : : * unique within that RTE. SQL does not require this of the original query,
204 : : * but due to factors such as *-expansion we need to be able to uniquely
205 : : * reference every column in a decompiled query. As long as we qualify all
206 : : * column references, per-RTE uniqueness is sufficient for that.
207 : : *
208 : : * However, we can't ensure per-column name uniqueness for unnamed join RTEs,
209 : : * since they just inherit column names from their input RTEs, and we can't
210 : : * rename the columns at the join level. Most of the time this isn't an issue
211 : : * because we don't need to reference the join's output columns as such; we
212 : : * can reference the input columns instead. That approach can fail for merged
213 : : * JOIN USING columns, however, so when we have one of those in an unnamed
214 : : * join, we have to make that column's alias globally unique across the whole
215 : : * query to ensure it can be referenced unambiguously.
216 : : *
217 : : * Another problem is that a JOIN USING clause requires the columns to be
218 : : * merged to have the same aliases in both input RTEs, and that no other
219 : : * columns in those RTEs or their children conflict with the USING names.
220 : : * To handle that, we do USING-column alias assignment in a recursive
221 : : * traversal of the query's jointree. When descending through a JOIN with
222 : : * USING, we preassign the USING column names to the child columns, overriding
223 : : * other rules for column alias assignment. We also mark each RTE with a list
224 : : * of all USING column names selected for joins containing that RTE, so that
225 : : * when we assign other columns' aliases later, we can avoid conflicts.
226 : : *
227 : : * Another problem is that if a JOIN's input tables have had columns added or
228 : : * deleted since the query was parsed, we must generate a column alias list
229 : : * for the join that matches the current set of input columns --- otherwise, a
230 : : * change in the number of columns in the left input would throw off matching
231 : : * of aliases to columns of the right input. Thus, positions in the printable
232 : : * column alias list are not necessarily one-for-one with varattnos of the
233 : : * JOIN, so we need a separate new_colnames[] array for printing purposes.
234 : : *
235 : : * Finally, when dealing with wide tables we risk O(N^2) costs in assigning
236 : : * non-duplicate column names. We ameliorate that by using a hash table that
237 : : * holds all the strings appearing in colnames, new_colnames, and parentUsing.
238 : : */
239 : : typedef struct
240 : : {
241 : : /*
242 : : * colnames is an array containing column aliases to use for columns that
243 : : * existed when the query was parsed. Dropped columns have NULL entries.
244 : : * This array can be directly indexed by varattno to get a Var's name.
245 : : *
246 : : * Non-NULL entries are guaranteed unique within the RTE, *except* when
247 : : * this is for an unnamed JOIN RTE. In that case we merely copy up names
248 : : * from the two input RTEs.
249 : : *
250 : : * During the recursive descent in set_using_names(), forcible assignment
251 : : * of a child RTE's column name is represented by pre-setting that element
252 : : * of the child's colnames array. So at that stage, NULL entries in this
253 : : * array just mean that no name has been preassigned, not necessarily that
254 : : * the column is dropped.
255 : : */
256 : : int num_cols; /* length of colnames[] array */
257 : : char **colnames; /* array of C strings and NULLs */
258 : :
259 : : /*
260 : : * new_colnames is an array containing column aliases to use for columns
261 : : * that would exist if the query was re-parsed against the current
262 : : * definitions of its base tables. This is what to print as the column
263 : : * alias list for the RTE. This array does not include dropped columns,
264 : : * but it will include columns added since original parsing. Indexes in
265 : : * it therefore have little to do with current varattno values. As above,
266 : : * entries are unique unless this is for an unnamed JOIN RTE. (In such an
267 : : * RTE, we never actually print this array, but we must compute it anyway
268 : : * for possible use in computing column names of upper joins.) The
269 : : * parallel array is_new_col marks which of these columns are new since
270 : : * original parsing. Entries with is_new_col false must match the
271 : : * non-NULL colnames entries one-for-one.
272 : : */
273 : : int num_new_cols; /* length of new_colnames[] array */
274 : : char **new_colnames; /* array of C strings */
275 : : bool *is_new_col; /* array of bool flags */
276 : :
277 : : /* This flag tells whether we should actually print a column alias list */
278 : : bool printaliases;
279 : :
280 : : /* This list has all names used as USING names in joins above this RTE */
281 : : List *parentUsing; /* names assigned to parent merged columns */
282 : :
283 : : /*
284 : : * If this struct is for a JOIN RTE, we fill these fields during the
285 : : * set_using_names() pass to describe its relationship to its child RTEs.
286 : : *
287 : : * leftattnos and rightattnos are arrays with one entry per existing
288 : : * output column of the join (hence, indexable by join varattno). For a
289 : : * simple reference to a column of the left child, leftattnos[i] is the
290 : : * child RTE's attno and rightattnos[i] is zero; and conversely for a
291 : : * column of the right child. But for merged columns produced by JOIN
292 : : * USING/NATURAL JOIN, both leftattnos[i] and rightattnos[i] are nonzero.
293 : : * Note that a simple reference might be to a child RTE column that's been
294 : : * dropped; but that's OK since the column could not be used in the query.
295 : : *
296 : : * If it's a JOIN USING, usingNames holds the alias names selected for the
297 : : * merged columns (these might be different from the original USING list,
298 : : * if we had to modify names to achieve uniqueness).
299 : : */
300 : : int leftrti; /* rangetable index of left child */
301 : : int rightrti; /* rangetable index of right child */
302 : : int *leftattnos; /* left-child varattnos of join cols, or 0 */
303 : : int *rightattnos; /* right-child varattnos of join cols, or 0 */
304 : : List *usingNames; /* names assigned to merged columns */
305 : :
306 : : /*
307 : : * Hash table holding copies of all the strings appearing in this struct's
308 : : * colnames, new_colnames, and parentUsing. We use a hash table only for
309 : : * sufficiently wide relations, and only during the colname-assignment
310 : : * functions set_relation_column_names and set_join_column_names;
311 : : * otherwise, names_hash is NULL.
312 : : */
313 : : HTAB *names_hash; /* entries are just strings */
314 : : } deparse_columns;
315 : :
316 : : /* This macro is analogous to rt_fetch(), but for deparse_columns structs */
317 : : #define deparse_columns_fetch(rangetable_index, dpns) \
318 : : ((deparse_columns *) list_nth((dpns)->rtable_columns, (rangetable_index)-1))
319 : :
320 : : /*
321 : : * Entry in set_rtable_names' hash table
322 : : */
323 : : typedef struct
324 : : {
325 : : char name[NAMEDATALEN]; /* Hash key --- must be first */
326 : : int counter; /* Largest addition used so far for name */
327 : : } NameHashEntry;
328 : :
329 : : /* Callback signature for resolve_special_varno() */
330 : : typedef void (*rsv_callback) (Node *node, deparse_context *context,
331 : : void *callback_arg);
332 : :
333 : :
334 : : /* ----------
335 : : * Global data
336 : : * ----------
337 : : */
338 : : static SPIPlanPtr plan_getrulebyoid = NULL;
339 : : static const char *const query_getrulebyoid = "SELECT * FROM pg_catalog.pg_rewrite WHERE oid = $1";
340 : : static SPIPlanPtr plan_getviewrule = NULL;
341 : : static const char *const query_getviewrule = "SELECT * FROM pg_catalog.pg_rewrite WHERE ev_class = $1 AND rulename = $2";
342 : :
343 : : /* GUC parameters */
344 : : bool quote_all_identifiers = false;
345 : :
346 : :
347 : : /* ----------
348 : : * Local functions
349 : : *
350 : : * Most of these functions used to use fixed-size buffers to build their
351 : : * results. Now, they take an (already initialized) StringInfo object
352 : : * as a parameter, and append their text output to its contents.
353 : : * ----------
354 : : */
355 : : static char *deparse_expression_pretty(Node *expr, List *dpcontext,
356 : : bool forceprefix, bool showimplicit,
357 : : int prettyFlags, int startIndent);
358 : : static char *pg_get_viewdef_worker(Oid viewoid,
359 : : int prettyFlags, int wrapColumn);
360 : : static char *pg_get_triggerdef_worker(Oid trigid, bool pretty);
361 : : static int decompile_column_index_array(Datum column_index_array, Oid relId,
362 : : bool withPeriod, StringInfo buf);
363 : : static char *pg_get_ruledef_worker(Oid ruleoid, int prettyFlags);
364 : : static char *pg_get_indexdef_worker(Oid indexrelid, int colno,
365 : : const Oid *excludeOps,
366 : : bool attrsOnly, bool keysOnly,
367 : : bool showTblSpc, bool inherits,
368 : : int prettyFlags, bool missing_ok);
369 : : static void make_propgraphdef_elements(StringInfo buf, Oid pgrelid, char pgekind);
370 : : static void make_propgraphdef_labels(StringInfo buf, Oid elid, const char *elalias, Oid elrelid);
371 : : static void make_propgraphdef_properties(StringInfo buf, Oid ellabelid, Oid elrelid);
372 : : static char *pg_get_statisticsobj_worker(Oid statextid, bool columns_only,
373 : : bool missing_ok);
374 : : static char *pg_get_partkeydef_worker(Oid relid, int prettyFlags,
375 : : bool attrsOnly, bool missing_ok);
376 : : static char *pg_get_constraintdef_worker(Oid constraintId, bool fullCommand,
377 : : int prettyFlags, bool missing_ok);
378 : : static text *pg_get_expr_worker(text *expr, Oid relid, int prettyFlags);
379 : : static int print_function_arguments(StringInfo buf, HeapTuple proctup,
380 : : bool print_table_args, bool print_defaults);
381 : : static void print_function_rettype(StringInfo buf, HeapTuple proctup);
382 : : static void print_function_trftypes(StringInfo buf, HeapTuple proctup);
383 : : static void print_function_sqlbody(StringInfo buf, HeapTuple proctup);
384 : : static void set_rtable_names(deparse_namespace *dpns, List *parent_namespaces,
385 : : Bitmapset *rels_used);
386 : : static void set_deparse_for_query(deparse_namespace *dpns, Query *query,
387 : : List *parent_namespaces);
388 : : static void set_simple_column_names(deparse_namespace *dpns);
389 : : static bool has_dangerous_join_using(deparse_namespace *dpns, Node *jtnode);
390 : : static void set_using_names(deparse_namespace *dpns, Node *jtnode,
391 : : List *parentUsing);
392 : : static void set_relation_column_names(deparse_namespace *dpns,
393 : : RangeTblEntry *rte,
394 : : deparse_columns *colinfo);
395 : : static void set_join_column_names(deparse_namespace *dpns, RangeTblEntry *rte,
396 : : deparse_columns *colinfo);
397 : : static bool colname_is_unique(const char *colname, deparse_namespace *dpns,
398 : : deparse_columns *colinfo);
399 : : static char *make_colname_unique(char *colname, deparse_namespace *dpns,
400 : : deparse_columns *colinfo);
401 : : static void expand_colnames_array_to(deparse_columns *colinfo, int n);
402 : : static void build_colinfo_names_hash(deparse_columns *colinfo);
403 : : static void add_to_names_hash(deparse_columns *colinfo, const char *name);
404 : : static void destroy_colinfo_names_hash(deparse_columns *colinfo);
405 : : static void identify_join_columns(JoinExpr *j, RangeTblEntry *jrte,
406 : : deparse_columns *colinfo);
407 : : static char *get_rtable_name(int rtindex, deparse_context *context);
408 : : static void set_deparse_plan(deparse_namespace *dpns, Plan *plan);
409 : : static Plan *find_recursive_union(deparse_namespace *dpns,
410 : : WorkTableScan *wtscan);
411 : : static void push_child_plan(deparse_namespace *dpns, Plan *plan,
412 : : deparse_namespace *save_dpns);
413 : : static void pop_child_plan(deparse_namespace *dpns,
414 : : deparse_namespace *save_dpns);
415 : : static void push_ancestor_plan(deparse_namespace *dpns, ListCell *ancestor_cell,
416 : : deparse_namespace *save_dpns);
417 : : static void pop_ancestor_plan(deparse_namespace *dpns,
418 : : deparse_namespace *save_dpns);
419 : : static void make_ruledef(StringInfo buf, HeapTuple ruletup, TupleDesc rulettc,
420 : : int prettyFlags);
421 : : static void make_viewdef(StringInfo buf, HeapTuple ruletup, TupleDesc rulettc,
422 : : int prettyFlags, int wrapColumn);
423 : : static void get_query_def(Query *query, StringInfo buf, List *parentnamespace,
424 : : TupleDesc resultDesc, bool colNamesVisible,
425 : : int prettyFlags, int wrapColumn, int startIndent);
426 : : static void get_values_def(List *values_lists, deparse_context *context);
427 : : static void get_with_clause(Query *query, deparse_context *context);
428 : : static void get_select_query_def(Query *query, deparse_context *context);
429 : : static void get_insert_query_def(Query *query, deparse_context *context);
430 : : static void get_update_query_def(Query *query, deparse_context *context);
431 : : static void get_update_query_targetlist_def(Query *query, List *targetList,
432 : : deparse_context *context,
433 : : RangeTblEntry *rte);
434 : : static void get_delete_query_def(Query *query, deparse_context *context);
435 : : static void get_merge_query_def(Query *query, deparse_context *context);
436 : : static void get_utility_query_def(Query *query, deparse_context *context);
437 : : static char *get_lock_clause_strength(LockClauseStrength strength);
438 : : static void get_basic_select_query(Query *query, deparse_context *context);
439 : : static void get_target_list(List *targetList, deparse_context *context);
440 : : static void get_returning_clause(Query *query, deparse_context *context);
441 : : static void get_setop_query(Node *setOp, Query *query,
442 : : deparse_context *context);
443 : : static Node *get_rule_sortgroupclause(Index ref, List *tlist,
444 : : bool force_colno,
445 : : deparse_context *context);
446 : : static void get_rule_groupingset(GroupingSet *gset, List *targetlist,
447 : : bool omit_parens, deparse_context *context);
448 : : static void get_rule_orderby(List *orderList, List *targetList,
449 : : bool force_colno, deparse_context *context);
450 : : static void get_rule_windowclause(Query *query, deparse_context *context);
451 : : static void get_rule_windowspec(WindowClause *wc, List *targetList,
452 : : deparse_context *context);
453 : : static void get_window_frame_options(int frameOptions,
454 : : Node *startOffset, Node *endOffset,
455 : : deparse_context *context);
456 : : static char *get_variable(Var *var, int levelsup, bool istoplevel,
457 : : deparse_context *context);
458 : : static void get_special_variable(Node *node, deparse_context *context,
459 : : void *callback_arg);
460 : : static void resolve_special_varno(Node *node, deparse_context *context,
461 : : rsv_callback callback, void *callback_arg);
462 : : static Node *find_param_referent(Param *param, deparse_context *context,
463 : : deparse_namespace **dpns_p, ListCell **ancestor_cell_p);
464 : : static SubPlan *find_param_generator(Param *param, deparse_context *context,
465 : : int *column_p);
466 : : static SubPlan *find_param_generator_initplan(Param *param, Plan *plan,
467 : : int *column_p);
468 : : static void get_parameter(Param *param, deparse_context *context);
469 : : static const char *get_simple_binary_op_name(OpExpr *expr);
470 : : static bool isSimpleNode(Node *node, Node *parentNode, int prettyFlags);
471 : : static void appendContextKeyword(deparse_context *context, const char *str,
472 : : int indentBefore, int indentAfter, int indentPlus);
473 : : static void removeStringInfoSpaces(StringInfo str);
474 : : static void get_rule_expr(Node *node, deparse_context *context,
475 : : bool showimplicit);
476 : : static void get_rule_expr_toplevel(Node *node, deparse_context *context,
477 : : bool showimplicit);
478 : : static void get_rule_list_toplevel(List *lst, deparse_context *context,
479 : : bool showimplicit);
480 : : static void get_rule_expr_funccall(Node *node, deparse_context *context,
481 : : bool showimplicit);
482 : : static bool looks_like_function(Node *node);
483 : : static void get_oper_expr(OpExpr *expr, deparse_context *context);
484 : : static void get_func_expr(FuncExpr *expr, deparse_context *context,
485 : : bool showimplicit);
486 : : static void get_agg_expr(Aggref *aggref, deparse_context *context,
487 : : Aggref *original_aggref);
488 : : static void get_agg_expr_helper(Aggref *aggref, deparse_context *context,
489 : : Aggref *original_aggref, const char *funcname,
490 : : const char *options, bool is_json_objectagg);
491 : : static void get_agg_combine_expr(Node *node, deparse_context *context,
492 : : void *callback_arg);
493 : : static void get_windowfunc_expr(WindowFunc *wfunc, deparse_context *context);
494 : : static void get_windowfunc_expr_helper(WindowFunc *wfunc, deparse_context *context,
495 : : const char *funcname, const char *options,
496 : : bool is_json_objectagg);
497 : : static bool get_func_sql_syntax(FuncExpr *expr, deparse_context *context);
498 : : static void get_coercion_expr(Node *arg, deparse_context *context,
499 : : Oid resulttype, int32 resulttypmod,
500 : : Node *parentNode);
501 : : static void get_const_expr(Const *constval, deparse_context *context,
502 : : int showtype);
503 : : static void get_const_collation(Const *constval, deparse_context *context);
504 : : static void get_json_format(JsonFormat *format, StringInfo buf);
505 : : static void get_json_returning(JsonReturning *returning, StringInfo buf,
506 : : bool json_format_by_default);
507 : : static void get_json_constructor(JsonConstructorExpr *ctor,
508 : : deparse_context *context, bool showimplicit);
509 : : static void get_json_constructor_options(JsonConstructorExpr *ctor,
510 : : StringInfo buf);
511 : : static void get_json_agg_constructor(JsonConstructorExpr *ctor,
512 : : deparse_context *context,
513 : : const char *funcname,
514 : : bool is_json_objectagg);
515 : : static void get_json_agg_constructor_expr(Node *node, deparse_context *context,
516 : : void *callback_arg);
517 : : static void simple_quote_literal(StringInfo buf, const char *val);
518 : : static void get_sublink_expr(SubLink *sublink, deparse_context *context);
519 : : static void get_tablefunc(TableFunc *tf, deparse_context *context,
520 : : bool showimplicit);
521 : : static void get_from_clause(Query *query, const char *prefix,
522 : : deparse_context *context);
523 : : static void get_from_clause_item(Node *jtnode, Query *query,
524 : : deparse_context *context);
525 : : static void get_rte_alias(RangeTblEntry *rte, int varno, bool use_as,
526 : : deparse_context *context);
527 : : static void get_column_alias_list(deparse_columns *colinfo,
528 : : deparse_context *context);
529 : : static void get_for_portion_of(ForPortionOfExpr *forPortionOf,
530 : : deparse_context *context);
531 : : static void get_from_clause_coldeflist(RangeTblFunction *rtfunc,
532 : : deparse_columns *colinfo,
533 : : deparse_context *context);
534 : : static void get_tablesample_def(TableSampleClause *tablesample,
535 : : deparse_context *context);
536 : : static void get_opclass_name(Oid opclass, Oid actual_datatype,
537 : : StringInfo buf);
538 : : static Node *processIndirection(Node *node, deparse_context *context);
539 : : static void printSubscripts(SubscriptingRef *sbsref, deparse_context *context);
540 : : static char *get_relation_name(Oid relid);
541 : : static char *generate_relation_name(Oid relid, List *namespaces);
542 : : static char *generate_qualified_relation_name(Oid relid);
543 : : static char *generate_function_name(Oid funcid, int nargs,
544 : : List *argnames, Oid *argtypes,
545 : : bool has_variadic, bool *use_variadic_p,
546 : : bool inGroupBy);
547 : : static char *generate_operator_name(Oid operid, Oid arg1, Oid arg2);
548 : : static void add_cast_to(StringInfo buf, Oid typid);
549 : : static char *generate_qualified_type_name(Oid typid);
550 : : static text *string_to_text(char *str);
551 : : static char *flatten_reloptions(Oid relid);
552 : : void get_reloptions(StringInfo buf, Datum reloptions);
553 : : static void get_json_path_spec(Node *path_spec, deparse_context *context,
554 : : bool showimplicit);
555 : : static void get_json_table_columns(TableFunc *tf, JsonTablePathScan *scan,
556 : : deparse_context *context,
557 : : bool showimplicit);
558 : : static void get_json_table_nested_columns(TableFunc *tf, JsonTablePlan *plan,
559 : : deparse_context *context,
560 : : bool showimplicit,
561 : : bool needcomma);
562 : :
563 : : #define only_marker(rte) ((rte)->inh ? "" : "ONLY ")
564 : :
565 : :
566 : : /* ----------
567 : : * pg_get_ruledef - Do it all and return a text
568 : : * that could be used as a statement
569 : : * to recreate the rule
570 : : * ----------
571 : : */
572 : : Datum
573 : 237 : pg_get_ruledef(PG_FUNCTION_ARGS)
574 : : {
575 : 237 : Oid ruleoid = PG_GETARG_OID(0);
576 : : int prettyFlags;
577 : : char *res;
578 : :
579 : 237 : prettyFlags = PRETTYFLAG_INDENT;
580 : :
581 : 237 : res = pg_get_ruledef_worker(ruleoid, prettyFlags);
582 : :
583 [ + + ]: 237 : if (res == NULL)
584 : 4 : PG_RETURN_NULL();
585 : :
586 : 233 : PG_RETURN_TEXT_P(string_to_text(res));
587 : : }
588 : :
589 : :
590 : : Datum
591 : 76 : pg_get_ruledef_ext(PG_FUNCTION_ARGS)
592 : : {
593 : 76 : Oid ruleoid = PG_GETARG_OID(0);
594 : 76 : bool pretty = PG_GETARG_BOOL(1);
595 : : int prettyFlags;
596 : : char *res;
597 : :
598 [ + - ]: 76 : prettyFlags = GET_PRETTY_FLAGS(pretty);
599 : :
600 : 76 : res = pg_get_ruledef_worker(ruleoid, prettyFlags);
601 : :
602 [ - + ]: 76 : if (res == NULL)
603 : 0 : PG_RETURN_NULL();
604 : :
605 : 76 : PG_RETURN_TEXT_P(string_to_text(res));
606 : : }
607 : :
608 : :
609 : : static char *
610 : 313 : pg_get_ruledef_worker(Oid ruleoid, int prettyFlags)
611 : : {
612 : : Datum args[1];
613 : : char nulls[1];
614 : : int spirc;
615 : : HeapTuple ruletup;
616 : : TupleDesc rulettc;
617 : : StringInfoData buf;
618 : :
619 : : /*
620 : : * Do this first so that string is alloc'd in outer context not SPI's.
621 : : */
622 : 313 : initStringInfo(&buf);
623 : :
624 : : /*
625 : : * Connect to SPI manager
626 : : */
627 : 313 : SPI_connect();
628 : :
629 : : /*
630 : : * On the first call prepare the plan to lookup pg_rewrite. We read
631 : : * pg_rewrite over the SPI manager instead of using the syscache to be
632 : : * checked for read access on pg_rewrite.
633 : : */
634 [ + + ]: 313 : if (plan_getrulebyoid == NULL)
635 : : {
636 : : Oid argtypes[1];
637 : : SPIPlanPtr plan;
638 : :
639 : 24 : argtypes[0] = OIDOID;
640 : 24 : plan = SPI_prepare(query_getrulebyoid, 1, argtypes);
641 [ - + ]: 24 : if (plan == NULL)
642 [ # # ]: 0 : elog(ERROR, "SPI_prepare failed for \"%s\"", query_getrulebyoid);
643 : 24 : SPI_keepplan(plan);
644 : 24 : plan_getrulebyoid = plan;
645 : : }
646 : :
647 : : /*
648 : : * Get the pg_rewrite tuple for this rule
649 : : */
650 : 313 : args[0] = ObjectIdGetDatum(ruleoid);
651 : 313 : nulls[0] = ' ';
652 : 313 : spirc = SPI_execute_plan(plan_getrulebyoid, args, nulls, true, 0);
653 [ - + ]: 313 : if (spirc != SPI_OK_SELECT)
654 [ # # ]: 0 : elog(ERROR, "failed to get pg_rewrite tuple for rule %u", ruleoid);
655 [ + + ]: 313 : if (SPI_processed != 1)
656 : : {
657 : : /*
658 : : * There is no tuple data available here, just keep the output buffer
659 : : * empty.
660 : : */
661 : : }
662 : : else
663 : : {
664 : : /*
665 : : * Get the rule's definition and put it into executor's memory
666 : : */
667 : 309 : ruletup = SPI_tuptable->vals[0];
668 : 309 : rulettc = SPI_tuptable->tupdesc;
669 : 309 : make_ruledef(&buf, ruletup, rulettc, prettyFlags);
670 : : }
671 : :
672 : : /*
673 : : * Disconnect from SPI manager
674 : : */
675 [ - + ]: 313 : if (SPI_finish() != SPI_OK_FINISH)
676 [ # # ]: 0 : elog(ERROR, "SPI_finish failed");
677 : :
678 [ + + ]: 313 : if (buf.len == 0)
679 : 4 : return NULL;
680 : :
681 : 309 : return buf.data;
682 : : }
683 : :
684 : :
685 : : /* ----------
686 : : * pg_get_viewdef - Mainly the same thing, but we
687 : : * only return the SELECT part of a view
688 : : * ----------
689 : : */
690 : : Datum
691 : 1442 : pg_get_viewdef(PG_FUNCTION_ARGS)
692 : : {
693 : : /* By OID */
694 : 1442 : Oid viewoid = PG_GETARG_OID(0);
695 : : int prettyFlags;
696 : : char *res;
697 : :
698 : 1442 : prettyFlags = PRETTYFLAG_INDENT;
699 : :
700 : 1442 : res = pg_get_viewdef_worker(viewoid, prettyFlags, WRAP_COLUMN_DEFAULT);
701 : :
702 [ + + ]: 1442 : if (res == NULL)
703 : 4 : PG_RETURN_NULL();
704 : :
705 : 1438 : PG_RETURN_TEXT_P(string_to_text(res));
706 : : }
707 : :
708 : :
709 : : Datum
710 : 399 : pg_get_viewdef_ext(PG_FUNCTION_ARGS)
711 : : {
712 : : /* By OID */
713 : 399 : Oid viewoid = PG_GETARG_OID(0);
714 : 399 : bool pretty = PG_GETARG_BOOL(1);
715 : : int prettyFlags;
716 : : char *res;
717 : :
718 [ + - ]: 399 : prettyFlags = GET_PRETTY_FLAGS(pretty);
719 : :
720 : 399 : res = pg_get_viewdef_worker(viewoid, prettyFlags, WRAP_COLUMN_DEFAULT);
721 : :
722 [ - + ]: 399 : if (res == NULL)
723 : 0 : PG_RETURN_NULL();
724 : :
725 : 399 : PG_RETURN_TEXT_P(string_to_text(res));
726 : : }
727 : :
728 : : Datum
729 : 4 : pg_get_viewdef_wrap(PG_FUNCTION_ARGS)
730 : : {
731 : : /* By OID */
732 : 4 : Oid viewoid = PG_GETARG_OID(0);
733 : 4 : int wrap = PG_GETARG_INT32(1);
734 : : int prettyFlags;
735 : : char *res;
736 : :
737 : : /* calling this implies we want pretty printing */
738 : 4 : prettyFlags = GET_PRETTY_FLAGS(true);
739 : :
740 : 4 : res = pg_get_viewdef_worker(viewoid, prettyFlags, wrap);
741 : :
742 [ - + ]: 4 : if (res == NULL)
743 : 0 : PG_RETURN_NULL();
744 : :
745 : 4 : PG_RETURN_TEXT_P(string_to_text(res));
746 : : }
747 : :
748 : : Datum
749 : 52 : pg_get_viewdef_name(PG_FUNCTION_ARGS)
750 : : {
751 : : /* By qualified name */
752 : 52 : text *viewname = PG_GETARG_TEXT_PP(0);
753 : : int prettyFlags;
754 : : RangeVar *viewrel;
755 : : Oid viewoid;
756 : : char *res;
757 : :
758 : 52 : prettyFlags = PRETTYFLAG_INDENT;
759 : :
760 : : /* Look up view name. Can't lock it - we might not have privileges. */
761 : 52 : viewrel = makeRangeVarFromNameList(textToQualifiedNameList(viewname));
762 : 52 : viewoid = RangeVarGetRelid(viewrel, NoLock, false);
763 : :
764 : 52 : res = pg_get_viewdef_worker(viewoid, prettyFlags, WRAP_COLUMN_DEFAULT);
765 : :
766 [ - + ]: 52 : if (res == NULL)
767 : 0 : PG_RETURN_NULL();
768 : :
769 : 52 : PG_RETURN_TEXT_P(string_to_text(res));
770 : : }
771 : :
772 : :
773 : : Datum
774 : 268 : pg_get_viewdef_name_ext(PG_FUNCTION_ARGS)
775 : : {
776 : : /* By qualified name */
777 : 268 : text *viewname = PG_GETARG_TEXT_PP(0);
778 : 268 : bool pretty = PG_GETARG_BOOL(1);
779 : : int prettyFlags;
780 : : RangeVar *viewrel;
781 : : Oid viewoid;
782 : : char *res;
783 : :
784 [ + - ]: 268 : prettyFlags = GET_PRETTY_FLAGS(pretty);
785 : :
786 : : /* Look up view name. Can't lock it - we might not have privileges. */
787 : 268 : viewrel = makeRangeVarFromNameList(textToQualifiedNameList(viewname));
788 : 268 : viewoid = RangeVarGetRelid(viewrel, NoLock, false);
789 : :
790 : 268 : res = pg_get_viewdef_worker(viewoid, prettyFlags, WRAP_COLUMN_DEFAULT);
791 : :
792 [ - + ]: 268 : if (res == NULL)
793 : 0 : PG_RETURN_NULL();
794 : :
795 : 268 : PG_RETURN_TEXT_P(string_to_text(res));
796 : : }
797 : :
798 : : /*
799 : : * Common code for by-OID and by-name variants of pg_get_viewdef
800 : : */
801 : : static char *
802 : 2165 : pg_get_viewdef_worker(Oid viewoid, int prettyFlags, int wrapColumn)
803 : : {
804 : : Datum args[2];
805 : : char nulls[2];
806 : : int spirc;
807 : : HeapTuple ruletup;
808 : : TupleDesc rulettc;
809 : : StringInfoData buf;
810 : :
811 : : /*
812 : : * Do this first so that string is alloc'd in outer context not SPI's.
813 : : */
814 : 2165 : initStringInfo(&buf);
815 : :
816 : : /*
817 : : * Connect to SPI manager
818 : : */
819 : 2165 : SPI_connect();
820 : :
821 : : /*
822 : : * On the first call prepare the plan to lookup pg_rewrite. We read
823 : : * pg_rewrite over the SPI manager instead of using the syscache to be
824 : : * checked for read access on pg_rewrite.
825 : : */
826 [ + + ]: 2165 : if (plan_getviewrule == NULL)
827 : : {
828 : : Oid argtypes[2];
829 : : SPIPlanPtr plan;
830 : :
831 : 155 : argtypes[0] = OIDOID;
832 : 155 : argtypes[1] = NAMEOID;
833 : 155 : plan = SPI_prepare(query_getviewrule, 2, argtypes);
834 [ - + ]: 155 : if (plan == NULL)
835 [ # # ]: 0 : elog(ERROR, "SPI_prepare failed for \"%s\"", query_getviewrule);
836 : 155 : SPI_keepplan(plan);
837 : 155 : plan_getviewrule = plan;
838 : : }
839 : :
840 : : /*
841 : : * Get the pg_rewrite tuple for the view's SELECT rule
842 : : */
843 : 2165 : args[0] = ObjectIdGetDatum(viewoid);
844 : 2165 : args[1] = DirectFunctionCall1(namein, CStringGetDatum(ViewSelectRuleName));
845 : 2165 : nulls[0] = ' ';
846 : 2165 : nulls[1] = ' ';
847 : 2165 : spirc = SPI_execute_plan(plan_getviewrule, args, nulls, true, 0);
848 [ - + ]: 2165 : if (spirc != SPI_OK_SELECT)
849 [ # # ]: 0 : elog(ERROR, "failed to get pg_rewrite tuple for view %u", viewoid);
850 [ + + ]: 2165 : if (SPI_processed != 1)
851 : : {
852 : : /*
853 : : * There is no tuple data available here, just keep the output buffer
854 : : * empty.
855 : : */
856 : : }
857 : : else
858 : : {
859 : : /*
860 : : * Get the rule's definition and put it into executor's memory
861 : : */
862 : 2161 : ruletup = SPI_tuptable->vals[0];
863 : 2161 : rulettc = SPI_tuptable->tupdesc;
864 : 2161 : make_viewdef(&buf, ruletup, rulettc, prettyFlags, wrapColumn);
865 : : }
866 : :
867 : : /*
868 : : * Disconnect from SPI manager
869 : : */
870 [ - + ]: 2165 : if (SPI_finish() != SPI_OK_FINISH)
871 [ # # ]: 0 : elog(ERROR, "SPI_finish failed");
872 : :
873 [ + + ]: 2165 : if (buf.len == 0)
874 : 4 : return NULL;
875 : :
876 : 2161 : return buf.data;
877 : : }
878 : :
879 : : /* ----------
880 : : * pg_get_triggerdef - Get the definition of a trigger
881 : : * ----------
882 : : */
883 : : Datum
884 : 96 : pg_get_triggerdef(PG_FUNCTION_ARGS)
885 : : {
886 : 96 : Oid trigid = PG_GETARG_OID(0);
887 : : char *res;
888 : :
889 : 96 : res = pg_get_triggerdef_worker(trigid, false);
890 : :
891 [ + + ]: 96 : if (res == NULL)
892 : 4 : PG_RETURN_NULL();
893 : :
894 : 92 : PG_RETURN_TEXT_P(string_to_text(res));
895 : : }
896 : :
897 : : Datum
898 : 655 : pg_get_triggerdef_ext(PG_FUNCTION_ARGS)
899 : : {
900 : 655 : Oid trigid = PG_GETARG_OID(0);
901 : 655 : bool pretty = PG_GETARG_BOOL(1);
902 : : char *res;
903 : :
904 : 655 : res = pg_get_triggerdef_worker(trigid, pretty);
905 : :
906 [ - + ]: 655 : if (res == NULL)
907 : 0 : PG_RETURN_NULL();
908 : :
909 : 655 : PG_RETURN_TEXT_P(string_to_text(res));
910 : : }
911 : :
912 : : static char *
913 : 751 : pg_get_triggerdef_worker(Oid trigid, bool pretty)
914 : : {
915 : : HeapTuple ht_trig;
916 : : Form_pg_trigger trigrec;
917 : : StringInfoData buf;
918 : : Relation tgrel;
919 : : ScanKeyData skey[1];
920 : : SysScanDesc tgscan;
921 : 751 : int findx = 0;
922 : : char *tgname;
923 : : char *tgoldtable;
924 : : char *tgnewtable;
925 : : Datum value;
926 : : bool isnull;
927 : :
928 : : /*
929 : : * Fetch the pg_trigger tuple by the Oid of the trigger
930 : : */
931 : 751 : tgrel = table_open(TriggerRelationId, AccessShareLock);
932 : :
933 : 751 : ScanKeyInit(&skey[0],
934 : : Anum_pg_trigger_oid,
935 : : BTEqualStrategyNumber, F_OIDEQ,
936 : : ObjectIdGetDatum(trigid));
937 : :
938 : 751 : tgscan = systable_beginscan(tgrel, TriggerOidIndexId, true,
939 : : NULL, 1, skey);
940 : :
941 : 751 : ht_trig = systable_getnext(tgscan);
942 : :
943 [ + + ]: 751 : if (!HeapTupleIsValid(ht_trig))
944 : : {
945 : 4 : systable_endscan(tgscan);
946 : 4 : table_close(tgrel, AccessShareLock);
947 : 4 : return NULL;
948 : : }
949 : :
950 : 747 : trigrec = (Form_pg_trigger) GETSTRUCT(ht_trig);
951 : :
952 : : /*
953 : : * Start the trigger definition. Note that the trigger's name should never
954 : : * be schema-qualified, but the trigger rel's name may be.
955 : : */
956 : 747 : initStringInfo(&buf);
957 : :
958 : 747 : tgname = NameStr(trigrec->tgname);
959 : 1494 : appendStringInfo(&buf, "CREATE %sTRIGGER %s ",
960 [ - + ]: 747 : OidIsValid(trigrec->tgconstraint) ? "CONSTRAINT " : "",
961 : : quote_identifier(tgname));
962 : :
963 [ + + ]: 747 : if (TRIGGER_FOR_BEFORE(trigrec->tgtype))
964 : 287 : appendStringInfoString(&buf, "BEFORE");
965 [ + + ]: 460 : else if (TRIGGER_FOR_AFTER(trigrec->tgtype))
966 : 444 : appendStringInfoString(&buf, "AFTER");
967 [ + - ]: 16 : else if (TRIGGER_FOR_INSTEAD(trigrec->tgtype))
968 : 16 : appendStringInfoString(&buf, "INSTEAD OF");
969 : : else
970 [ # # ]: 0 : elog(ERROR, "unexpected tgtype value: %d", trigrec->tgtype);
971 : :
972 [ + + ]: 747 : if (TRIGGER_FOR_INSERT(trigrec->tgtype))
973 : : {
974 : 512 : appendStringInfoString(&buf, " INSERT");
975 : 512 : findx++;
976 : : }
977 [ + + ]: 747 : if (TRIGGER_FOR_DELETE(trigrec->tgtype))
978 : : {
979 [ + + ]: 113 : if (findx > 0)
980 : 45 : appendStringInfoString(&buf, " OR DELETE");
981 : : else
982 : 68 : appendStringInfoString(&buf, " DELETE");
983 : 113 : findx++;
984 : : }
985 [ + + ]: 747 : if (TRIGGER_FOR_UPDATE(trigrec->tgtype))
986 : : {
987 [ + + ]: 332 : if (findx > 0)
988 : 165 : appendStringInfoString(&buf, " OR UPDATE");
989 : : else
990 : 167 : appendStringInfoString(&buf, " UPDATE");
991 : 332 : findx++;
992 : : /* tgattr is first var-width field, so OK to access directly */
993 [ + + ]: 332 : if (trigrec->tgattr.dim1 > 0)
994 : : {
995 : : int i;
996 : :
997 : 44 : appendStringInfoString(&buf, " OF ");
998 [ + + ]: 97 : for (i = 0; i < trigrec->tgattr.dim1; i++)
999 : : {
1000 : : char *attname;
1001 : :
1002 [ + + ]: 53 : if (i > 0)
1003 : 9 : appendStringInfoString(&buf, ", ");
1004 : 53 : attname = get_attname(trigrec->tgrelid,
1005 : 53 : trigrec->tgattr.values[i], false);
1006 : 53 : appendStringInfoString(&buf, quote_identifier(attname));
1007 : : }
1008 : : }
1009 : : }
1010 [ - + ]: 747 : if (TRIGGER_FOR_TRUNCATE(trigrec->tgtype))
1011 : : {
1012 [ # # ]: 0 : if (findx > 0)
1013 : 0 : appendStringInfoString(&buf, " OR TRUNCATE");
1014 : : else
1015 : 0 : appendStringInfoString(&buf, " TRUNCATE");
1016 : 0 : findx++;
1017 : : }
1018 : :
1019 : : /*
1020 : : * In non-pretty mode, always schema-qualify the target table name for
1021 : : * safety. In pretty mode, schema-qualify only if not visible.
1022 : : */
1023 [ + + ]: 1494 : appendStringInfo(&buf, " ON %s ",
1024 : : pretty ?
1025 : 116 : generate_relation_name(trigrec->tgrelid, NIL) :
1026 : 631 : generate_qualified_relation_name(trigrec->tgrelid));
1027 : :
1028 [ - + ]: 747 : if (OidIsValid(trigrec->tgconstraint))
1029 : : {
1030 [ # # ]: 0 : if (OidIsValid(trigrec->tgconstrrelid))
1031 : 0 : appendStringInfo(&buf, "FROM %s ",
1032 : : generate_relation_name(trigrec->tgconstrrelid, NIL));
1033 [ # # ]: 0 : if (!trigrec->tgdeferrable)
1034 : 0 : appendStringInfoString(&buf, "NOT ");
1035 : 0 : appendStringInfoString(&buf, "DEFERRABLE INITIALLY ");
1036 [ # # ]: 0 : if (trigrec->tginitdeferred)
1037 : 0 : appendStringInfoString(&buf, "DEFERRED ");
1038 : : else
1039 : 0 : appendStringInfoString(&buf, "IMMEDIATE ");
1040 : : }
1041 : :
1042 : 747 : value = fastgetattr(ht_trig, Anum_pg_trigger_tgoldtable,
1043 : : tgrel->rd_att, &isnull);
1044 [ + + ]: 747 : if (!isnull)
1045 : 57 : tgoldtable = NameStr(*DatumGetName(value));
1046 : : else
1047 : 690 : tgoldtable = NULL;
1048 : 747 : value = fastgetattr(ht_trig, Anum_pg_trigger_tgnewtable,
1049 : : tgrel->rd_att, &isnull);
1050 [ + + ]: 747 : if (!isnull)
1051 : 62 : tgnewtable = NameStr(*DatumGetName(value));
1052 : : else
1053 : 685 : tgnewtable = NULL;
1054 [ + + + + ]: 747 : if (tgoldtable != NULL || tgnewtable != NULL)
1055 : : {
1056 : 88 : appendStringInfoString(&buf, "REFERENCING ");
1057 [ + + ]: 88 : if (tgoldtable != NULL)
1058 : 57 : appendStringInfo(&buf, "OLD TABLE AS %s ",
1059 : : quote_identifier(tgoldtable));
1060 [ + + ]: 88 : if (tgnewtable != NULL)
1061 : 62 : appendStringInfo(&buf, "NEW TABLE AS %s ",
1062 : : quote_identifier(tgnewtable));
1063 : : }
1064 : :
1065 [ + + ]: 747 : if (TRIGGER_FOR_ROW(trigrec->tgtype))
1066 : 558 : appendStringInfoString(&buf, "FOR EACH ROW ");
1067 : : else
1068 : 189 : appendStringInfoString(&buf, "FOR EACH STATEMENT ");
1069 : :
1070 : : /* If the trigger has a WHEN qualification, add that */
1071 : 747 : value = fastgetattr(ht_trig, Anum_pg_trigger_tgqual,
1072 : : tgrel->rd_att, &isnull);
1073 [ + + ]: 747 : if (!isnull)
1074 : : {
1075 : : Node *qual;
1076 : : char relkind;
1077 : : deparse_context context;
1078 : : deparse_namespace dpns;
1079 : : RangeTblEntry *oldrte;
1080 : : RangeTblEntry *newrte;
1081 : :
1082 : 88 : appendStringInfoString(&buf, "WHEN (");
1083 : :
1084 : 88 : qual = stringToNode(TextDatumGetCString(value));
1085 : :
1086 : 88 : relkind = get_rel_relkind(trigrec->tgrelid);
1087 : :
1088 : : /* Build minimal OLD and NEW RTEs for the rel */
1089 : 88 : oldrte = makeNode(RangeTblEntry);
1090 : 88 : oldrte->rtekind = RTE_RELATION;
1091 : 88 : oldrte->relid = trigrec->tgrelid;
1092 : 88 : oldrte->relkind = relkind;
1093 : 88 : oldrte->rellockmode = AccessShareLock;
1094 : 88 : oldrte->alias = makeAlias("old", NIL);
1095 : 88 : oldrte->eref = oldrte->alias;
1096 : 88 : oldrte->lateral = false;
1097 : 88 : oldrte->inh = false;
1098 : 88 : oldrte->inFromCl = true;
1099 : :
1100 : 88 : newrte = makeNode(RangeTblEntry);
1101 : 88 : newrte->rtekind = RTE_RELATION;
1102 : 88 : newrte->relid = trigrec->tgrelid;
1103 : 88 : newrte->relkind = relkind;
1104 : 88 : newrte->rellockmode = AccessShareLock;
1105 : 88 : newrte->alias = makeAlias("new", NIL);
1106 : 88 : newrte->eref = newrte->alias;
1107 : 88 : newrte->lateral = false;
1108 : 88 : newrte->inh = false;
1109 : 88 : newrte->inFromCl = true;
1110 : :
1111 : : /* Build two-element rtable */
1112 : 88 : memset(&dpns, 0, sizeof(dpns));
1113 : 88 : dpns.rtable = list_make2(oldrte, newrte);
1114 : 88 : dpns.subplans = NIL;
1115 : 88 : dpns.ctes = NIL;
1116 : 88 : dpns.appendrels = NULL;
1117 : 88 : set_rtable_names(&dpns, NIL, NULL);
1118 : 88 : set_simple_column_names(&dpns);
1119 : :
1120 : : /* Set up context with one-deep namespace stack */
1121 : 88 : context.buf = &buf;
1122 : 88 : context.namespaces = list_make1(&dpns);
1123 : 88 : context.resultDesc = NULL;
1124 : 88 : context.targetList = NIL;
1125 : 88 : context.windowClause = NIL;
1126 : 88 : context.varprefix = true;
1127 [ + + ]: 88 : context.prettyFlags = GET_PRETTY_FLAGS(pretty);
1128 : 88 : context.wrapColumn = WRAP_COLUMN_DEFAULT;
1129 : 88 : context.indentLevel = PRETTYINDENT_STD;
1130 : 88 : context.colNamesVisible = true;
1131 : 88 : context.inGroupBy = false;
1132 : 88 : context.varInOrderBy = false;
1133 : 88 : context.appendparents = NULL;
1134 : :
1135 : 88 : get_rule_expr(qual, &context, false);
1136 : :
1137 : 88 : appendStringInfoString(&buf, ") ");
1138 : : }
1139 : :
1140 : 747 : appendStringInfo(&buf, "EXECUTE FUNCTION %s(",
1141 : : generate_function_name(trigrec->tgfoid, 0,
1142 : : NIL, NULL,
1143 : : false, NULL, false));
1144 : :
1145 [ + + ]: 747 : if (trigrec->tgnargs > 0)
1146 : : {
1147 : : char *p;
1148 : : int i;
1149 : :
1150 : 249 : value = fastgetattr(ht_trig, Anum_pg_trigger_tgargs,
1151 : : tgrel->rd_att, &isnull);
1152 [ - + ]: 249 : if (isnull)
1153 [ # # ]: 0 : elog(ERROR, "tgargs is null for trigger %u", trigid);
1154 : 249 : p = (char *) VARDATA_ANY(DatumGetByteaPP(value));
1155 [ + + ]: 508 : for (i = 0; i < trigrec->tgnargs; i++)
1156 : : {
1157 [ + + ]: 259 : if (i > 0)
1158 : 10 : appendStringInfoString(&buf, ", ");
1159 : 259 : simple_quote_literal(&buf, p);
1160 : : /* advance p to next string embedded in tgargs */
1161 [ + + ]: 2905 : while (*p)
1162 : 2646 : p++;
1163 : 259 : p++;
1164 : : }
1165 : : }
1166 : :
1167 : : /* We deliberately do not put semi-colon at end */
1168 : 747 : appendStringInfoChar(&buf, ')');
1169 : :
1170 : : /* Clean up */
1171 : 747 : systable_endscan(tgscan);
1172 : :
1173 : 747 : table_close(tgrel, AccessShareLock);
1174 : :
1175 : 747 : return buf.data;
1176 : : }
1177 : :
1178 : : /* ----------
1179 : : * pg_get_indexdef - Get the definition of an index
1180 : : *
1181 : : * In the extended version, there is a colno argument as well as pretty bool.
1182 : : * if colno == 0, we want a complete index definition.
1183 : : * if colno > 0, we only want the Nth index key's variable or expression.
1184 : : *
1185 : : * Note that the SQL-function versions of this omit any info about the
1186 : : * index tablespace; this is intentional because pg_dump wants it that way.
1187 : : * However pg_get_indexdef_string() includes the index tablespace.
1188 : : * ----------
1189 : : */
1190 : : Datum
1191 : 3184 : pg_get_indexdef(PG_FUNCTION_ARGS)
1192 : : {
1193 : 3184 : Oid indexrelid = PG_GETARG_OID(0);
1194 : : int prettyFlags;
1195 : : char *res;
1196 : :
1197 : 3184 : prettyFlags = PRETTYFLAG_INDENT;
1198 : :
1199 : 3184 : res = pg_get_indexdef_worker(indexrelid, 0, NULL,
1200 : : false, false,
1201 : : false, false,
1202 : : prettyFlags, true);
1203 : :
1204 [ + + ]: 3184 : if (res == NULL)
1205 : 4 : PG_RETURN_NULL();
1206 : :
1207 : 3180 : PG_RETURN_TEXT_P(string_to_text(res));
1208 : : }
1209 : :
1210 : : Datum
1211 : 1347 : pg_get_indexdef_ext(PG_FUNCTION_ARGS)
1212 : : {
1213 : 1347 : Oid indexrelid = PG_GETARG_OID(0);
1214 : 1347 : int32 colno = PG_GETARG_INT32(1);
1215 : 1347 : bool pretty = PG_GETARG_BOOL(2);
1216 : : int prettyFlags;
1217 : : char *res;
1218 : :
1219 [ + - ]: 1347 : prettyFlags = GET_PRETTY_FLAGS(pretty);
1220 : :
1221 : 1347 : res = pg_get_indexdef_worker(indexrelid, colno, NULL,
1222 : : colno != 0, false,
1223 : : false, false,
1224 : : prettyFlags, true);
1225 : :
1226 [ - + ]: 1347 : if (res == NULL)
1227 : 0 : PG_RETURN_NULL();
1228 : :
1229 : 1347 : PG_RETURN_TEXT_P(string_to_text(res));
1230 : : }
1231 : :
1232 : : /*
1233 : : * Internal version for use by ALTER TABLE.
1234 : : * Includes a tablespace clause in the result.
1235 : : * Returns a palloc'd C string; no pretty-printing.
1236 : : */
1237 : : char *
1238 : 179 : pg_get_indexdef_string(Oid indexrelid)
1239 : : {
1240 : 179 : return pg_get_indexdef_worker(indexrelid, 0, NULL,
1241 : : false, false,
1242 : : true, true,
1243 : : 0, false);
1244 : : }
1245 : :
1246 : : /* Internal version that just reports the key-column definitions */
1247 : : char *
1248 : 778 : pg_get_indexdef_columns(Oid indexrelid, bool pretty)
1249 : : {
1250 : : int prettyFlags;
1251 : :
1252 [ + - ]: 778 : prettyFlags = GET_PRETTY_FLAGS(pretty);
1253 : :
1254 : 778 : return pg_get_indexdef_worker(indexrelid, 0, NULL,
1255 : : true, true,
1256 : : false, false,
1257 : : prettyFlags, false);
1258 : : }
1259 : :
1260 : : /* Internal version, extensible with flags to control its behavior */
1261 : : char *
1262 : 4 : pg_get_indexdef_columns_extended(Oid indexrelid, uint16 flags)
1263 : : {
1264 : 4 : bool pretty = ((flags & RULE_INDEXDEF_PRETTY) != 0);
1265 : 4 : bool keys_only = ((flags & RULE_INDEXDEF_KEYS_ONLY) != 0);
1266 : : int prettyFlags;
1267 : :
1268 [ + - ]: 4 : prettyFlags = GET_PRETTY_FLAGS(pretty);
1269 : :
1270 : 4 : return pg_get_indexdef_worker(indexrelid, 0, NULL,
1271 : : true, keys_only,
1272 : : false, false,
1273 : : prettyFlags, false);
1274 : : }
1275 : :
1276 : : /*
1277 : : * Internal workhorse to decompile an index definition.
1278 : : *
1279 : : * This is now used for exclusion constraints as well: if excludeOps is not
1280 : : * NULL then it points to an array of exclusion operator OIDs.
1281 : : */
1282 : : static char *
1283 : 5568 : pg_get_indexdef_worker(Oid indexrelid, int colno,
1284 : : const Oid *excludeOps,
1285 : : bool attrsOnly, bool keysOnly,
1286 : : bool showTblSpc, bool inherits,
1287 : : int prettyFlags, bool missing_ok)
1288 : : {
1289 : : /* might want a separate isConstraint parameter later */
1290 : 5568 : bool isConstraint = (excludeOps != NULL);
1291 : : HeapTuple ht_idx;
1292 : : HeapTuple ht_idxrel;
1293 : : HeapTuple ht_am;
1294 : : Form_pg_index idxrec;
1295 : : Form_pg_class idxrelrec;
1296 : : Form_pg_am amrec;
1297 : : const IndexAmRoutine *amroutine;
1298 : : List *indexprs;
1299 : : ListCell *indexpr_item;
1300 : : List *context;
1301 : : Oid indrelid;
1302 : : int keyno;
1303 : : Datum indcollDatum;
1304 : : Datum indclassDatum;
1305 : : Datum indoptionDatum;
1306 : : oidvector *indcollation;
1307 : : oidvector *indclass;
1308 : : int2vector *indoption;
1309 : : StringInfoData buf;
1310 : : char *str;
1311 : : char *sep;
1312 : :
1313 : : /*
1314 : : * Fetch the pg_index tuple by the Oid of the index
1315 : : */
1316 : 5568 : ht_idx = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexrelid));
1317 [ + + ]: 5568 : if (!HeapTupleIsValid(ht_idx))
1318 : : {
1319 [ + - ]: 4 : if (missing_ok)
1320 : 4 : return NULL;
1321 [ # # ]: 0 : elog(ERROR, "cache lookup failed for index %u", indexrelid);
1322 : : }
1323 : 5564 : idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
1324 : :
1325 : 5564 : indrelid = idxrec->indrelid;
1326 : : Assert(indexrelid == idxrec->indexrelid);
1327 : :
1328 : : /* Must get indcollation, indclass, and indoption the hard way */
1329 : 5564 : indcollDatum = SysCacheGetAttrNotNull(INDEXRELID, ht_idx,
1330 : : Anum_pg_index_indcollation);
1331 : 5564 : indcollation = (oidvector *) DatumGetPointer(indcollDatum);
1332 : :
1333 : 5564 : indclassDatum = SysCacheGetAttrNotNull(INDEXRELID, ht_idx,
1334 : : Anum_pg_index_indclass);
1335 : 5564 : indclass = (oidvector *) DatumGetPointer(indclassDatum);
1336 : :
1337 : 5564 : indoptionDatum = SysCacheGetAttrNotNull(INDEXRELID, ht_idx,
1338 : : Anum_pg_index_indoption);
1339 : 5564 : indoption = (int2vector *) DatumGetPointer(indoptionDatum);
1340 : :
1341 : : /*
1342 : : * Fetch the pg_class tuple of the index relation
1343 : : */
1344 : 5564 : ht_idxrel = SearchSysCache1(RELOID, ObjectIdGetDatum(indexrelid));
1345 [ - + ]: 5564 : if (!HeapTupleIsValid(ht_idxrel))
1346 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", indexrelid);
1347 : 5564 : idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
1348 : :
1349 : : /*
1350 : : * Fetch the pg_am tuple of the index' access method
1351 : : */
1352 : 5564 : ht_am = SearchSysCache1(AMOID, ObjectIdGetDatum(idxrelrec->relam));
1353 [ - + ]: 5564 : if (!HeapTupleIsValid(ht_am))
1354 [ # # ]: 0 : elog(ERROR, "cache lookup failed for access method %u",
1355 : : idxrelrec->relam);
1356 : 5564 : amrec = (Form_pg_am) GETSTRUCT(ht_am);
1357 : :
1358 : : /* Fetch the index AM's API struct */
1359 : 5564 : amroutine = GetIndexAmRoutine(amrec->amhandler);
1360 : :
1361 : : /*
1362 : : * Get the index expressions, if any. (NOTE: we do not use the relcache
1363 : : * versions of the expressions and predicate, because we want to display
1364 : : * non-const-folded expressions.)
1365 : : */
1366 [ + + ]: 5564 : if (!heap_attisnull(ht_idx, Anum_pg_index_indexprs, NULL))
1367 : : {
1368 : : Datum exprsDatum;
1369 : : char *exprsString;
1370 : :
1371 : 413 : exprsDatum = SysCacheGetAttrNotNull(INDEXRELID, ht_idx,
1372 : : Anum_pg_index_indexprs);
1373 : 413 : exprsString = TextDatumGetCString(exprsDatum);
1374 : 413 : indexprs = (List *) stringToNode(exprsString);
1375 : 413 : pfree(exprsString);
1376 : : }
1377 : : else
1378 : 5151 : indexprs = NIL;
1379 : :
1380 : 5564 : indexpr_item = list_head(indexprs);
1381 : :
1382 : 5564 : context = deparse_context_for(get_relation_name(indrelid), indrelid);
1383 : :
1384 : : /*
1385 : : * Start the index definition. Note that the index's name should never be
1386 : : * schema-qualified, but the indexed rel's name may be.
1387 : : */
1388 : 5564 : initStringInfo(&buf);
1389 : :
1390 [ + + ]: 5564 : if (!attrsOnly)
1391 : : {
1392 [ + + ]: 4476 : if (!isConstraint)
1393 : 8800 : appendStringInfo(&buf, "CREATE %sINDEX %s ON %s%s USING %s (",
1394 [ + + ]: 4400 : idxrec->indisunique ? "UNIQUE " : "",
1395 : 4400 : quote_identifier(NameStr(idxrelrec->relname)),
1396 [ + + ]: 4400 : idxrelrec->relkind == RELKIND_PARTITIONED_INDEX
1397 [ + + ]: 414 : && !inherits ? "ONLY " : "",
1398 [ + + ]: 4400 : (prettyFlags & PRETTYFLAG_SCHEMA) ?
1399 : 1041 : generate_relation_name(indrelid, NIL) :
1400 : 3359 : generate_qualified_relation_name(indrelid),
1401 : 4400 : quote_identifier(NameStr(amrec->amname)));
1402 : : else /* currently, must be EXCLUDE constraint */
1403 : 76 : appendStringInfo(&buf, "EXCLUDE USING %s (",
1404 : 76 : quote_identifier(NameStr(amrec->amname)));
1405 : : }
1406 : :
1407 : : /*
1408 : : * Report the indexed attributes
1409 : : */
1410 : 5564 : sep = "";
1411 [ + + ]: 13810 : for (keyno = 0; keyno < idxrec->indnatts; keyno++)
1412 : : {
1413 : 8311 : AttrNumber attnum = idxrec->indkey.values[keyno];
1414 : : Oid keycoltype;
1415 : : Oid keycolcollation;
1416 : :
1417 : : /*
1418 : : * Ignore non-key attributes if told to.
1419 : : */
1420 [ + + + + ]: 8311 : if (keysOnly && keyno >= idxrec->indnkeyatts)
1421 : 65 : break;
1422 : :
1423 : : /* Otherwise, print INCLUDE to divide key and non-key attrs. */
1424 [ + + + + ]: 8246 : if (!colno && keyno == idxrec->indnkeyatts)
1425 : : {
1426 : 148 : appendStringInfoString(&buf, ") INCLUDE (");
1427 : 148 : sep = "";
1428 : : }
1429 : :
1430 [ + + ]: 8246 : if (!colno)
1431 : 7824 : appendStringInfoString(&buf, sep);
1432 : 8246 : sep = ", ";
1433 : :
1434 [ + + ]: 8246 : if (attnum != 0)
1435 : : {
1436 : : /* Simple index column */
1437 : : char *attname;
1438 : : int32 keycoltypmod;
1439 : :
1440 : 7750 : attname = get_attname(indrelid, attnum, false);
1441 [ + + + + ]: 7750 : if (!colno || colno == keyno + 1)
1442 : 7642 : appendStringInfoString(&buf, quote_identifier(attname));
1443 : 7750 : get_atttypetypmodcoll(indrelid, attnum,
1444 : : &keycoltype, &keycoltypmod,
1445 : : &keycolcollation);
1446 : : }
1447 : : else
1448 : : {
1449 : : /* expressional index */
1450 : : Node *indexkey;
1451 : :
1452 [ - + ]: 496 : if (indexpr_item == NULL)
1453 [ # # ]: 0 : elog(ERROR, "too few entries in indexprs list");
1454 : 496 : indexkey = (Node *) lfirst(indexpr_item);
1455 : 496 : indexpr_item = lnext(indexprs, indexpr_item);
1456 : : /* Deparse */
1457 : 496 : str = deparse_expression_pretty(indexkey, context, false, false,
1458 : : prettyFlags, 0);
1459 [ + + + + ]: 496 : if (!colno || colno == keyno + 1)
1460 : : {
1461 : : /* Need parens if it's not a bare function call */
1462 [ + + ]: 488 : if (looks_like_function(indexkey))
1463 : 33 : appendStringInfoString(&buf, str);
1464 : : else
1465 : 455 : appendStringInfo(&buf, "(%s)", str);
1466 : : }
1467 : 496 : keycoltype = exprType(indexkey);
1468 : 496 : keycolcollation = exprCollation(indexkey);
1469 : : }
1470 : :
1471 : : /* Print additional decoration for (selected) key columns */
1472 [ + + + + : 8246 : if (!attrsOnly && keyno < idxrec->indnkeyatts &&
- + ]
1473 [ # # ]: 0 : (!colno || colno == keyno + 1))
1474 : : {
1475 : 6470 : int16 opt = indoption->values[keyno];
1476 : 6470 : Oid indcoll = indcollation->values[keyno];
1477 : 6470 : Datum attoptions = get_attoptions(indexrelid, keyno + 1);
1478 : 6470 : bool has_options = attoptions != (Datum) 0;
1479 : :
1480 : : /* Add collation, if not default for column */
1481 [ + + + + ]: 6470 : if (OidIsValid(indcoll) && indcoll != keycolcollation)
1482 : 62 : appendStringInfo(&buf, " COLLATE %s",
1483 : : generate_collation_name((indcoll)));
1484 : :
1485 : : /* Add the operator class name, if not default */
1486 [ + + ]: 6470 : get_opclass_name(indclass->values[keyno],
1487 : : has_options ? InvalidOid : keycoltype, &buf);
1488 : :
1489 [ + + ]: 6470 : if (has_options)
1490 : : {
1491 : 22 : appendStringInfoString(&buf, " (");
1492 : 22 : get_reloptions(&buf, attoptions);
1493 : 22 : appendStringInfoChar(&buf, ')');
1494 : : }
1495 : :
1496 : : /* Add options if relevant */
1497 [ + + ]: 6470 : if (amroutine->amcanorder)
1498 : : {
1499 : : /* if it supports sort ordering, report DESC and NULLS opts */
1500 [ - + ]: 5284 : if (opt & INDOPTION_DESC)
1501 : : {
1502 : 0 : appendStringInfoString(&buf, " DESC");
1503 : : /* NULLS FIRST is the default in this case */
1504 [ # # ]: 0 : if (!(opt & INDOPTION_NULLS_FIRST))
1505 : 0 : appendStringInfoString(&buf, " NULLS LAST");
1506 : : }
1507 : : else
1508 : : {
1509 [ - + ]: 5284 : if (opt & INDOPTION_NULLS_FIRST)
1510 : 0 : appendStringInfoString(&buf, " NULLS FIRST");
1511 : : }
1512 : : }
1513 : :
1514 : : /* Add the exclusion operator if relevant */
1515 [ + + ]: 6470 : if (excludeOps != NULL)
1516 : 96 : appendStringInfo(&buf, " WITH %s",
1517 : 96 : generate_operator_name(excludeOps[keyno],
1518 : : keycoltype,
1519 : : keycoltype));
1520 : : }
1521 : : }
1522 : :
1523 [ + + ]: 5564 : if (!attrsOnly)
1524 : : {
1525 : 4476 : appendStringInfoChar(&buf, ')');
1526 : :
1527 [ + + ]: 4476 : if (idxrec->indnullsnotdistinct)
1528 : 8 : appendStringInfoString(&buf, " NULLS NOT DISTINCT");
1529 : :
1530 : : /*
1531 : : * If it has options, append "WITH (options)"
1532 : : */
1533 : 4476 : str = flatten_reloptions(indexrelid);
1534 [ + + ]: 4476 : if (str)
1535 : : {
1536 : 105 : appendStringInfo(&buf, " WITH (%s)", str);
1537 : 105 : pfree(str);
1538 : : }
1539 : :
1540 : : /*
1541 : : * Print tablespace, but only if requested
1542 : : */
1543 [ + + ]: 4476 : if (showTblSpc)
1544 : : {
1545 : : Oid tblspc;
1546 : :
1547 : 179 : tblspc = get_rel_tablespace(indexrelid);
1548 [ + + ]: 179 : if (OidIsValid(tblspc))
1549 : : {
1550 [ - + ]: 36 : if (isConstraint)
1551 : 0 : appendStringInfoString(&buf, " USING INDEX");
1552 : 36 : appendStringInfo(&buf, " TABLESPACE %s",
1553 : 36 : quote_identifier(get_tablespace_name(tblspc)));
1554 : : }
1555 : : }
1556 : :
1557 : : /*
1558 : : * If it's a partial index, decompile and append the predicate
1559 : : */
1560 [ + + ]: 4476 : if (!heap_attisnull(ht_idx, Anum_pg_index_indpred, NULL))
1561 : : {
1562 : : Node *node;
1563 : : Datum predDatum;
1564 : : char *predString;
1565 : :
1566 : : /* Convert text string to node tree */
1567 : 230 : predDatum = SysCacheGetAttrNotNull(INDEXRELID, ht_idx,
1568 : : Anum_pg_index_indpred);
1569 : 230 : predString = TextDatumGetCString(predDatum);
1570 : 230 : node = (Node *) stringToNode(predString);
1571 : 230 : pfree(predString);
1572 : :
1573 : : /* Deparse */
1574 : 230 : str = deparse_expression_pretty(node, context, false, false,
1575 : : prettyFlags, 0);
1576 [ + + ]: 230 : if (isConstraint)
1577 : 28 : appendStringInfo(&buf, " WHERE (%s)", str);
1578 : : else
1579 : 202 : appendStringInfo(&buf, " WHERE %s", str);
1580 : : }
1581 : : }
1582 : :
1583 : : /* Clean up */
1584 : 5564 : ReleaseSysCache(ht_idx);
1585 : 5564 : ReleaseSysCache(ht_idxrel);
1586 : 5564 : ReleaseSysCache(ht_am);
1587 : :
1588 : 5564 : return buf.data;
1589 : : }
1590 : :
1591 : : /* ----------
1592 : : * pg_get_querydef
1593 : : *
1594 : : * Public entry point to deparse one query parsetree.
1595 : : * The pretty flags are determined by GET_PRETTY_FLAGS(pretty).
1596 : : *
1597 : : * The result is a palloc'd C string.
1598 : : * ----------
1599 : : */
1600 : : char *
1601 : 0 : pg_get_querydef(Query *query, bool pretty)
1602 : : {
1603 : : StringInfoData buf;
1604 : : int prettyFlags;
1605 : :
1606 [ # # ]: 0 : prettyFlags = GET_PRETTY_FLAGS(pretty);
1607 : :
1608 : 0 : initStringInfo(&buf);
1609 : :
1610 : 0 : get_query_def(query, &buf, NIL, NULL, true,
1611 : : prettyFlags, WRAP_COLUMN_DEFAULT, 0);
1612 : :
1613 : 0 : return buf.data;
1614 : : }
1615 : :
1616 : : /*
1617 : : * pg_get_propgraphdef - get the definition of a property graph
1618 : : */
1619 : : Datum
1620 : 132 : pg_get_propgraphdef(PG_FUNCTION_ARGS)
1621 : : {
1622 : 132 : Oid pgrelid = PG_GETARG_OID(0);
1623 : : StringInfoData buf;
1624 : : HeapTuple classtup;
1625 : : Form_pg_class classform;
1626 : : char *name;
1627 : : char *nsp;
1628 : :
1629 : 132 : initStringInfo(&buf);
1630 : :
1631 : 132 : classtup = SearchSysCache1(RELOID, ObjectIdGetDatum(pgrelid));
1632 [ - + ]: 132 : if (!HeapTupleIsValid(classtup))
1633 : 0 : PG_RETURN_NULL();
1634 : :
1635 : 132 : classform = (Form_pg_class) GETSTRUCT(classtup);
1636 : 132 : name = NameStr(classform->relname);
1637 : :
1638 [ + + ]: 132 : if (classform->relkind != RELKIND_PROPGRAPH)
1639 [ + - ]: 4 : ereport(ERROR,
1640 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1641 : : errmsg("\"%s\" is not a property graph", name)));
1642 : :
1643 : 128 : nsp = get_namespace_name(classform->relnamespace);
1644 : :
1645 : 128 : appendStringInfo(&buf, "CREATE PROPERTY GRAPH %s",
1646 : : quote_qualified_identifier(nsp, name));
1647 : :
1648 : 128 : ReleaseSysCache(classtup);
1649 : :
1650 : 128 : make_propgraphdef_elements(&buf, pgrelid, PGEKIND_VERTEX);
1651 : 128 : make_propgraphdef_elements(&buf, pgrelid, PGEKIND_EDGE);
1652 : :
1653 : 128 : PG_RETURN_TEXT_P(string_to_text(buf.data));
1654 : : }
1655 : :
1656 : : /*
1657 : : * Generates a VERTEX TABLES (...) or EDGE TABLES (...) clause. Pass in the
1658 : : * property graph relation OID and the element kind (vertex or edge). Result
1659 : : * is appended to buf.
1660 : : */
1661 : : static void
1662 : 256 : make_propgraphdef_elements(StringInfo buf, Oid pgrelid, char pgekind)
1663 : : {
1664 : : Relation pgerel;
1665 : : ScanKeyData scankey[1];
1666 : : SysScanDesc scan;
1667 : : bool first;
1668 : : HeapTuple tup;
1669 : :
1670 : 256 : pgerel = table_open(PropgraphElementRelationId, AccessShareLock);
1671 : :
1672 : 256 : ScanKeyInit(&scankey[0],
1673 : : Anum_pg_propgraph_element_pgepgid,
1674 : : BTEqualStrategyNumber, F_OIDEQ,
1675 : : ObjectIdGetDatum(pgrelid));
1676 : :
1677 : 256 : scan = systable_beginscan(pgerel, PropgraphElementAliasIndexId, true, NULL, 1, scankey);
1678 : :
1679 : 256 : first = true;
1680 [ + + ]: 1016 : while ((tup = systable_getnext(scan)))
1681 : : {
1682 : 760 : Form_pg_propgraph_element pgeform = (Form_pg_propgraph_element) GETSTRUCT(tup);
1683 : : char *relname;
1684 : : Datum datum;
1685 : : bool isnull;
1686 : :
1687 [ + + ]: 760 : if (pgeform->pgekind != pgekind)
1688 : 380 : continue;
1689 : :
1690 [ + + ]: 380 : if (first)
1691 : : {
1692 [ + + ]: 166 : appendStringInfo(buf, "\n %s TABLES (\n", pgekind == PGEKIND_VERTEX ? "VERTEX" : "EDGE");
1693 : 166 : first = false;
1694 : : }
1695 : : else
1696 : 214 : appendStringInfoString(buf, ",\n");
1697 : :
1698 : 380 : relname = get_rel_name(pgeform->pgerelid);
1699 [ + - + - ]: 380 : if (relname && strcmp(relname, NameStr(pgeform->pgealias)) == 0)
1700 : 380 : appendStringInfo(buf, " %s",
1701 : : generate_relation_name(pgeform->pgerelid, NIL));
1702 : : else
1703 : 0 : appendStringInfo(buf, " %s AS %s",
1704 : : generate_relation_name(pgeform->pgerelid, NIL),
1705 : 0 : quote_identifier(NameStr(pgeform->pgealias)));
1706 : :
1707 : 380 : datum = heap_getattr(tup, Anum_pg_propgraph_element_pgekey, RelationGetDescr(pgerel), &isnull);
1708 [ + - ]: 380 : if (!isnull)
1709 : : {
1710 : 380 : appendStringInfoString(buf, " KEY (");
1711 : 380 : decompile_column_index_array(datum, pgeform->pgerelid, false, buf);
1712 : 380 : appendStringInfoChar(buf, ')');
1713 : : }
1714 : : else
1715 [ # # ]: 0 : elog(ERROR, "null pgekey for element %u", pgeform->oid);
1716 : :
1717 [ + + ]: 380 : if (pgekind == PGEKIND_EDGE)
1718 : : {
1719 : : Datum srckey;
1720 : : Datum srcref;
1721 : : Datum destkey;
1722 : : Datum destref;
1723 : : HeapTuple tup2;
1724 : : Form_pg_propgraph_element pgeform2;
1725 : :
1726 : 163 : datum = heap_getattr(tup, Anum_pg_propgraph_element_pgesrckey, RelationGetDescr(pgerel), &isnull);
1727 [ - + ]: 163 : srckey = isnull ? 0 : datum;
1728 : 163 : datum = heap_getattr(tup, Anum_pg_propgraph_element_pgesrcref, RelationGetDescr(pgerel), &isnull);
1729 [ - + ]: 163 : srcref = isnull ? 0 : datum;
1730 : 163 : datum = heap_getattr(tup, Anum_pg_propgraph_element_pgedestkey, RelationGetDescr(pgerel), &isnull);
1731 [ - + ]: 163 : destkey = isnull ? 0 : datum;
1732 : 163 : datum = heap_getattr(tup, Anum_pg_propgraph_element_pgedestref, RelationGetDescr(pgerel), &isnull);
1733 [ - + ]: 163 : destref = isnull ? 0 : datum;
1734 : :
1735 : 163 : appendStringInfoString(buf, " SOURCE");
1736 : 163 : tup2 = SearchSysCache1(PROPGRAPHELOID, ObjectIdGetDatum(pgeform->pgesrcvertexid));
1737 [ - + ]: 163 : if (!tup2)
1738 [ # # ]: 0 : elog(ERROR, "cache lookup failed for property graph element %u", pgeform->pgesrcvertexid);
1739 : 163 : pgeform2 = (Form_pg_propgraph_element) GETSTRUCT(tup2);
1740 [ + - ]: 163 : if (srckey)
1741 : : {
1742 : 163 : appendStringInfoString(buf, " KEY (");
1743 : 163 : decompile_column_index_array(srckey, pgeform->pgerelid, false, buf);
1744 : 163 : appendStringInfo(buf, ") REFERENCES %s (", quote_identifier(NameStr(pgeform2->pgealias)));
1745 : 163 : decompile_column_index_array(srcref, pgeform2->pgerelid, false, buf);
1746 : 163 : appendStringInfoChar(buf, ')');
1747 : : }
1748 : : else
1749 : 0 : appendStringInfo(buf, " %s ", quote_identifier(NameStr(pgeform2->pgealias)));
1750 : 163 : ReleaseSysCache(tup2);
1751 : :
1752 : 163 : appendStringInfoString(buf, " DESTINATION");
1753 : 163 : tup2 = SearchSysCache1(PROPGRAPHELOID, ObjectIdGetDatum(pgeform->pgedestvertexid));
1754 [ - + ]: 163 : if (!tup2)
1755 [ # # ]: 0 : elog(ERROR, "cache lookup failed for property graph element %u", pgeform->pgedestvertexid);
1756 : 163 : pgeform2 = (Form_pg_propgraph_element) GETSTRUCT(tup2);
1757 [ + - ]: 163 : if (destkey)
1758 : : {
1759 : 163 : appendStringInfoString(buf, " KEY (");
1760 : 163 : decompile_column_index_array(destkey, pgeform->pgerelid, false, buf);
1761 : 163 : appendStringInfo(buf, ") REFERENCES %s (", quote_identifier(NameStr(pgeform2->pgealias)));
1762 : 163 : decompile_column_index_array(destref, pgeform2->pgerelid, false, buf);
1763 : 163 : appendStringInfoChar(buf, ')');
1764 : : }
1765 : : else
1766 : 0 : appendStringInfo(buf, " %s", quote_identifier(NameStr(pgeform2->pgealias)));
1767 : 163 : ReleaseSysCache(tup2);
1768 : : }
1769 : :
1770 : 380 : make_propgraphdef_labels(buf, pgeform->oid, NameStr(pgeform->pgealias), pgeform->pgerelid);
1771 : : }
1772 [ + + ]: 256 : if (!first)
1773 : 166 : appendStringInfoString(buf, "\n )");
1774 : :
1775 : 256 : systable_endscan(scan);
1776 : 256 : table_close(pgerel, AccessShareLock);
1777 : 256 : }
1778 : :
1779 : : struct oid_str_pair
1780 : : {
1781 : : Oid oid;
1782 : : char *str;
1783 : : };
1784 : :
1785 : : static int
1786 : 97 : list_oid_str_pair_cmp_by_str(const ListCell *p1, const ListCell *p2)
1787 : : {
1788 : 97 : struct oid_str_pair *v1 = lfirst(p1);
1789 : 97 : struct oid_str_pair *v2 = lfirst(p2);
1790 : :
1791 : 97 : return strcmp(v1->str, v2->str);
1792 : : }
1793 : :
1794 : : /*
1795 : : * Generates label and properties list. Pass in the element OID, the element
1796 : : * alias, and the graph relation OID. Result is appended to buf.
1797 : : */
1798 : : static void
1799 : 380 : make_propgraphdef_labels(StringInfo buf, Oid elid, const char *elalias, Oid elrelid)
1800 : : {
1801 : : Relation pglrel;
1802 : : ScanKeyData scankey[1];
1803 : : SysScanDesc scan;
1804 : : int count;
1805 : : HeapTuple tup;
1806 : 380 : List *label_list = NIL;
1807 : :
1808 : 380 : pglrel = table_open(PropgraphElementLabelRelationId, AccessShareLock);
1809 : :
1810 : 380 : ScanKeyInit(&scankey[0],
1811 : : Anum_pg_propgraph_element_label_pgelelid,
1812 : : BTEqualStrategyNumber, F_OIDEQ,
1813 : : ObjectIdGetDatum(elid));
1814 : :
1815 : : /*
1816 : : * We want to output the labels in a deterministic order. So we first
1817 : : * read all the data, then sort, then print it.
1818 : : */
1819 : 380 : scan = systable_beginscan(pglrel, PropgraphElementLabelElementLabelIndexId, true, NULL, 1, scankey);
1820 : :
1821 [ + + ]: 857 : while ((tup = systable_getnext(scan)))
1822 : : {
1823 : 477 : Form_pg_propgraph_element_label pgelform = (Form_pg_propgraph_element_label) GETSTRUCT(tup);
1824 : : struct oid_str_pair *osp;
1825 : :
1826 : 477 : osp = palloc_object(struct oid_str_pair);
1827 : 477 : osp->oid = pgelform->oid;
1828 : 477 : osp->str = get_propgraph_label_name(pgelform->pgellabelid);
1829 : :
1830 : 477 : label_list = lappend(label_list, osp);
1831 : : }
1832 : :
1833 : 380 : systable_endscan(scan);
1834 : 380 : table_close(pglrel, AccessShareLock);
1835 : :
1836 : 380 : count = list_length(label_list);
1837 : :
1838 : : /* Each element has at least one label. */
1839 : : Assert(count > 0);
1840 : :
1841 : : /*
1842 : : * It is enough for the comparison function to compare just labels, since
1843 : : * all the labels of an element table should have distinct names.
1844 : : */
1845 : 380 : list_sort(label_list, list_oid_str_pair_cmp_by_str);
1846 : :
1847 [ + - + + : 1237 : foreach_ptr(struct oid_str_pair, osp, label_list)
+ + ]
1848 : : {
1849 [ + + ]: 477 : if (strcmp(osp->str, elalias) == 0)
1850 : : {
1851 : : /* If the default label is the only label, don't print anything. */
1852 [ + + ]: 259 : if (count != 1)
1853 : 30 : appendStringInfoString(buf, " DEFAULT LABEL");
1854 : : }
1855 : : else
1856 : 218 : appendStringInfo(buf, " LABEL %s", quote_identifier(osp->str));
1857 : :
1858 : 477 : make_propgraphdef_properties(buf, osp->oid, elrelid);
1859 : : }
1860 : 380 : }
1861 : :
1862 : : /*
1863 : : * Helper function for make_propgraphdef_properties(): Sort (propname, expr)
1864 : : * pairs by name.
1865 : : */
1866 : : static int
1867 : 773 : propdata_by_name_cmp(const ListCell *a, const ListCell *b)
1868 : : {
1869 : 773 : List *la = lfirst_node(List, a);
1870 : 773 : List *lb = lfirst_node(List, b);
1871 : 773 : char *pna = strVal(linitial(la));
1872 : 773 : char *pnb = strVal(linitial(lb));
1873 : :
1874 : 773 : return strcmp(pna, pnb);
1875 : : }
1876 : :
1877 : : /*
1878 : : * Generates element table properties clause (PROPERTIES (...) or NO
1879 : : * PROPERTIES). Pass in label OID and element table OID. Result is appended
1880 : : * to buf.
1881 : : */
1882 : : static void
1883 : 477 : make_propgraphdef_properties(StringInfo buf, Oid ellabelid, Oid elrelid)
1884 : : {
1885 : : Relation plprel;
1886 : : ScanKeyData scankey[1];
1887 : : SysScanDesc scan;
1888 : : HeapTuple tup;
1889 : 477 : List *outlist = NIL;
1890 : :
1891 : 477 : plprel = table_open(PropgraphLabelPropertyRelationId, AccessShareLock);
1892 : :
1893 : 477 : ScanKeyInit(&scankey[0],
1894 : : Anum_pg_propgraph_label_property_plpellabelid,
1895 : : BTEqualStrategyNumber, F_OIDEQ,
1896 : : ObjectIdGetDatum(ellabelid));
1897 : :
1898 : : /*
1899 : : * We want to output the properties in a deterministic order. So we first
1900 : : * read all the data, then sort, then print it.
1901 : : */
1902 : 477 : scan = systable_beginscan(plprel, PropgraphLabelPropertyLabelPropIndexId, true, NULL, 1, scankey);
1903 : :
1904 [ + + ]: 1570 : while ((tup = systable_getnext(scan)))
1905 : : {
1906 : 1093 : Form_pg_propgraph_label_property plpform = (Form_pg_propgraph_label_property) GETSTRUCT(tup);
1907 : : Datum exprDatum;
1908 : : bool isnull;
1909 : : char *tmp;
1910 : : Node *expr;
1911 : : char *propname;
1912 : :
1913 : 1093 : exprDatum = heap_getattr(tup, Anum_pg_propgraph_label_property_plpexpr, RelationGetDescr(plprel), &isnull);
1914 : : Assert(!isnull);
1915 : 1093 : tmp = TextDatumGetCString(exprDatum);
1916 : 1093 : expr = stringToNode(tmp);
1917 : 1093 : pfree(tmp);
1918 : :
1919 : 1093 : propname = get_propgraph_property_name(plpform->plppropid);
1920 : :
1921 : 1093 : outlist = lappend(outlist, list_make2(makeString(propname), expr));
1922 : : }
1923 : :
1924 : 477 : systable_endscan(scan);
1925 : 477 : table_close(plprel, AccessShareLock);
1926 : :
1927 : 477 : list_sort(outlist, propdata_by_name_cmp);
1928 : :
1929 [ + + ]: 477 : if (outlist)
1930 : : {
1931 : : List *context;
1932 : : ListCell *lc;
1933 : 468 : bool first = true;
1934 : :
1935 : 468 : context = deparse_context_for(get_relation_name(elrelid), elrelid);
1936 : :
1937 : 468 : appendStringInfoString(buf, " PROPERTIES (");
1938 : :
1939 [ + - + + : 1561 : foreach(lc, outlist)
+ + ]
1940 : : {
1941 : 1093 : List *data = lfirst_node(List, lc);
1942 : 1093 : char *propname = strVal(linitial(data));
1943 : 1093 : Node *expr = lsecond(data);
1944 : :
1945 [ + + ]: 1093 : if (first)
1946 : 468 : first = false;
1947 : : else
1948 : 625 : appendStringInfoString(buf, ", ");
1949 : :
1950 [ + + + + ]: 1093 : if (IsA(expr, Var) && strcmp(propname, get_attname(elrelid, castNode(Var, expr)->varattno, false)) == 0)
1951 : 881 : appendStringInfoString(buf, quote_identifier(propname));
1952 : : else
1953 : 212 : appendStringInfo(buf, "%s AS %s",
1954 : : deparse_expression_pretty(expr, context, false, false, 0, 0),
1955 : : quote_identifier(propname));
1956 : : }
1957 : :
1958 : 468 : appendStringInfoChar(buf, ')');
1959 : : }
1960 : : else
1961 : 9 : appendStringInfoString(buf, " NO PROPERTIES");
1962 : 477 : }
1963 : :
1964 : : /*
1965 : : * pg_get_statisticsobjdef
1966 : : * Get the definition of an extended statistics object
1967 : : */
1968 : : Datum
1969 : 163 : pg_get_statisticsobjdef(PG_FUNCTION_ARGS)
1970 : : {
1971 : 163 : Oid statextid = PG_GETARG_OID(0);
1972 : : char *res;
1973 : :
1974 : 163 : res = pg_get_statisticsobj_worker(statextid, false, true);
1975 : :
1976 [ + + ]: 163 : if (res == NULL)
1977 : 4 : PG_RETURN_NULL();
1978 : :
1979 : 159 : PG_RETURN_TEXT_P(string_to_text(res));
1980 : : }
1981 : :
1982 : : /*
1983 : : * Internal version for use by ALTER TABLE.
1984 : : * Returns a palloc'd C string; no pretty-printing.
1985 : : */
1986 : : char *
1987 : 53 : pg_get_statisticsobjdef_string(Oid statextid)
1988 : : {
1989 : 53 : return pg_get_statisticsobj_worker(statextid, false, false);
1990 : : }
1991 : :
1992 : : /*
1993 : : * pg_get_statisticsobjdef_columns
1994 : : * Get columns and expressions for an extended statistics object
1995 : : */
1996 : : Datum
1997 : 284 : pg_get_statisticsobjdef_columns(PG_FUNCTION_ARGS)
1998 : : {
1999 : 284 : Oid statextid = PG_GETARG_OID(0);
2000 : : char *res;
2001 : :
2002 : 284 : res = pg_get_statisticsobj_worker(statextid, true, true);
2003 : :
2004 [ - + ]: 284 : if (res == NULL)
2005 : 0 : PG_RETURN_NULL();
2006 : :
2007 : 284 : PG_RETURN_TEXT_P(string_to_text(res));
2008 : : }
2009 : :
2010 : : /*
2011 : : * Internal workhorse to decompile an extended statistics object.
2012 : : */
2013 : : static char *
2014 : 500 : pg_get_statisticsobj_worker(Oid statextid, bool columns_only, bool missing_ok)
2015 : : {
2016 : : Form_pg_statistic_ext statextrec;
2017 : : HeapTuple statexttup;
2018 : : StringInfoData buf;
2019 : : int colno;
2020 : : char *nsp;
2021 : : ArrayType *arr;
2022 : : char *enabled;
2023 : : Datum datum;
2024 : : bool ndistinct_enabled;
2025 : : bool dependencies_enabled;
2026 : : bool mcv_enabled;
2027 : : int i;
2028 : : List *context;
2029 : : ListCell *lc;
2030 : 500 : List *exprs = NIL;
2031 : : bool has_exprs;
2032 : : int ncolumns;
2033 : :
2034 : 500 : statexttup = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(statextid));
2035 : :
2036 [ + + ]: 500 : if (!HeapTupleIsValid(statexttup))
2037 : : {
2038 [ + - ]: 4 : if (missing_ok)
2039 : 4 : return NULL;
2040 [ # # ]: 0 : elog(ERROR, "cache lookup failed for statistics object %u", statextid);
2041 : : }
2042 : :
2043 : : /* has the statistics expressions? */
2044 : 496 : has_exprs = !heap_attisnull(statexttup, Anum_pg_statistic_ext_stxexprs, NULL);
2045 : :
2046 : 496 : statextrec = (Form_pg_statistic_ext) GETSTRUCT(statexttup);
2047 : :
2048 : : /*
2049 : : * Get the statistics expressions, if any. (NOTE: we do not use the
2050 : : * relcache versions of the expressions, because we want to display
2051 : : * non-const-folded expressions.)
2052 : : */
2053 [ + + ]: 496 : if (has_exprs)
2054 : : {
2055 : : Datum exprsDatum;
2056 : : char *exprsString;
2057 : :
2058 : 129 : exprsDatum = SysCacheGetAttrNotNull(STATEXTOID, statexttup,
2059 : : Anum_pg_statistic_ext_stxexprs);
2060 : 129 : exprsString = TextDatumGetCString(exprsDatum);
2061 : 129 : exprs = (List *) stringToNode(exprsString);
2062 : 129 : pfree(exprsString);
2063 : : }
2064 : : else
2065 : 367 : exprs = NIL;
2066 : :
2067 : : /* count the number of columns (attributes and expressions) */
2068 : 496 : ncolumns = statextrec->stxkeys.dim1 + list_length(exprs);
2069 : :
2070 : 496 : initStringInfo(&buf);
2071 : :
2072 [ + + ]: 496 : if (!columns_only)
2073 : : {
2074 : 212 : nsp = get_namespace_name_or_temp(statextrec->stxnamespace);
2075 : 212 : appendStringInfo(&buf, "CREATE STATISTICS %s",
2076 : : quote_qualified_identifier(nsp,
2077 : 212 : NameStr(statextrec->stxname)));
2078 : :
2079 : : /*
2080 : : * Decode the stxkind column so that we know which stats types to
2081 : : * print.
2082 : : */
2083 : 212 : datum = SysCacheGetAttrNotNull(STATEXTOID, statexttup,
2084 : : Anum_pg_statistic_ext_stxkind);
2085 : 212 : arr = DatumGetArrayTypeP(datum);
2086 [ + - ]: 212 : if (ARR_NDIM(arr) != 1 ||
2087 [ + - ]: 212 : ARR_HASNULL(arr) ||
2088 [ - + ]: 212 : ARR_ELEMTYPE(arr) != CHAROID)
2089 [ # # ]: 0 : elog(ERROR, "stxkind is not a 1-D char array");
2090 [ - + ]: 212 : enabled = (char *) ARR_DATA_PTR(arr);
2091 : :
2092 : 212 : ndistinct_enabled = false;
2093 : 212 : dependencies_enabled = false;
2094 : 212 : mcv_enabled = false;
2095 : :
2096 [ + + ]: 669 : for (i = 0; i < ARR_DIMS(arr)[0]; i++)
2097 : : {
2098 [ + + ]: 457 : if (enabled[i] == STATS_EXT_NDISTINCT)
2099 : 137 : ndistinct_enabled = true;
2100 [ + + ]: 320 : else if (enabled[i] == STATS_EXT_DEPENDENCIES)
2101 : 113 : dependencies_enabled = true;
2102 [ + + ]: 207 : else if (enabled[i] == STATS_EXT_MCV)
2103 : 122 : mcv_enabled = true;
2104 : :
2105 : : /* ignore STATS_EXT_EXPRESSIONS (it's built automatically) */
2106 : : }
2107 : :
2108 : : /*
2109 : : * If any option is disabled, then we'll need to append the types
2110 : : * clause to show which options are enabled. We omit the types clause
2111 : : * on purpose when all options are enabled, so a pg_dump/pg_restore
2112 : : * will create all statistics types on a newer postgres version, if
2113 : : * the statistics had all options enabled on the original version.
2114 : : *
2115 : : * But if the statistics is defined on just a single column, it has to
2116 : : * be an expression statistics. In that case we don't need to specify
2117 : : * kinds.
2118 : : */
2119 [ + + + + : 212 : if ((!ndistinct_enabled || !dependencies_enabled || !mcv_enabled) &&
- + + + ]
2120 : : (ncolumns > 1))
2121 : : {
2122 : 63 : bool gotone = false;
2123 : :
2124 : 63 : appendStringInfoString(&buf, " (");
2125 : :
2126 [ + + ]: 63 : if (ndistinct_enabled)
2127 : : {
2128 : 34 : appendStringInfoString(&buf, "ndistinct");
2129 : 34 : gotone = true;
2130 : : }
2131 : :
2132 [ + + ]: 63 : if (dependencies_enabled)
2133 : : {
2134 [ - + ]: 10 : appendStringInfo(&buf, "%sdependencies", gotone ? ", " : "");
2135 : 10 : gotone = true;
2136 : : }
2137 : :
2138 [ + + ]: 63 : if (mcv_enabled)
2139 [ - + ]: 19 : appendStringInfo(&buf, "%smcv", gotone ? ", " : "");
2140 : :
2141 : 63 : appendStringInfoChar(&buf, ')');
2142 : : }
2143 : :
2144 : 212 : appendStringInfoString(&buf, " ON ");
2145 : : }
2146 : :
2147 : : /* decode simple column references */
2148 [ + + ]: 1411 : for (colno = 0; colno < statextrec->stxkeys.dim1; colno++)
2149 : : {
2150 : 915 : AttrNumber attnum = statextrec->stxkeys.values[colno];
2151 : : char *attname;
2152 : :
2153 [ + + ]: 915 : if (colno > 0)
2154 : 506 : appendStringInfoString(&buf, ", ");
2155 : :
2156 : 915 : attname = get_attname(statextrec->stxrelid, attnum, false);
2157 : :
2158 : 915 : appendStringInfoString(&buf, quote_identifier(attname));
2159 : : }
2160 : :
2161 : 496 : context = deparse_context_for(get_relation_name(statextrec->stxrelid),
2162 : : statextrec->stxrelid);
2163 : :
2164 [ + + + + : 679 : foreach(lc, exprs)
+ + ]
2165 : : {
2166 : 183 : Node *expr = (Node *) lfirst(lc);
2167 : : char *str;
2168 : 183 : int prettyFlags = PRETTYFLAG_PAREN;
2169 : :
2170 : 183 : str = deparse_expression_pretty(expr, context, false, false,
2171 : : prettyFlags, 0);
2172 : :
2173 [ + + ]: 183 : if (colno > 0)
2174 : 96 : appendStringInfoString(&buf, ", ");
2175 : :
2176 : : /* Need parens if it's not a bare function call */
2177 [ + + ]: 183 : if (looks_like_function(expr))
2178 : 21 : appendStringInfoString(&buf, str);
2179 : : else
2180 : 162 : appendStringInfo(&buf, "(%s)", str);
2181 : :
2182 : 183 : colno++;
2183 : : }
2184 : :
2185 [ + + ]: 496 : if (!columns_only)
2186 : 212 : appendStringInfo(&buf, " FROM %s",
2187 : : generate_relation_name(statextrec->stxrelid, NIL));
2188 : :
2189 : 496 : ReleaseSysCache(statexttup);
2190 : :
2191 : 496 : return buf.data;
2192 : : }
2193 : :
2194 : : /*
2195 : : * Generate text array of expressions for statistics object.
2196 : : */
2197 : : Datum
2198 : 128 : pg_get_statisticsobjdef_expressions(PG_FUNCTION_ARGS)
2199 : : {
2200 : 128 : Oid statextid = PG_GETARG_OID(0);
2201 : : Form_pg_statistic_ext statextrec;
2202 : : HeapTuple statexttup;
2203 : : Datum datum;
2204 : : List *context;
2205 : : ListCell *lc;
2206 : 128 : List *exprs = NIL;
2207 : : bool has_exprs;
2208 : : char *tmp;
2209 : 128 : ArrayBuildState *astate = NULL;
2210 : :
2211 : 128 : statexttup = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(statextid));
2212 : :
2213 [ - + ]: 128 : if (!HeapTupleIsValid(statexttup))
2214 : 0 : PG_RETURN_NULL();
2215 : :
2216 : : /* Does the stats object have expressions? */
2217 : 128 : has_exprs = !heap_attisnull(statexttup, Anum_pg_statistic_ext_stxexprs, NULL);
2218 : :
2219 : : /* no expressions? we're done */
2220 [ + + ]: 128 : if (!has_exprs)
2221 : : {
2222 : 11 : ReleaseSysCache(statexttup);
2223 : 11 : PG_RETURN_NULL();
2224 : : }
2225 : :
2226 : 117 : statextrec = (Form_pg_statistic_ext) GETSTRUCT(statexttup);
2227 : :
2228 : : /*
2229 : : * Get the statistics expressions, and deparse them into text values.
2230 : : */
2231 : 117 : datum = SysCacheGetAttrNotNull(STATEXTOID, statexttup,
2232 : : Anum_pg_statistic_ext_stxexprs);
2233 : 117 : tmp = TextDatumGetCString(datum);
2234 : 117 : exprs = (List *) stringToNode(tmp);
2235 : 117 : pfree(tmp);
2236 : :
2237 : 117 : context = deparse_context_for(get_relation_name(statextrec->stxrelid),
2238 : : statextrec->stxrelid);
2239 : :
2240 [ + - + + : 280 : foreach(lc, exprs)
+ + ]
2241 : : {
2242 : 163 : Node *expr = (Node *) lfirst(lc);
2243 : : char *str;
2244 : 163 : int prettyFlags = PRETTYFLAG_INDENT;
2245 : :
2246 : 163 : str = deparse_expression_pretty(expr, context, false, false,
2247 : : prettyFlags, 0);
2248 : :
2249 : 163 : astate = accumArrayResult(astate,
2250 : 163 : PointerGetDatum(cstring_to_text(str)),
2251 : : false,
2252 : : TEXTOID,
2253 : : CurrentMemoryContext);
2254 : : }
2255 : :
2256 : 117 : ReleaseSysCache(statexttup);
2257 : :
2258 : 117 : PG_RETURN_DATUM(makeArrayResult(astate, CurrentMemoryContext));
2259 : : }
2260 : :
2261 : : /*
2262 : : * pg_get_partkeydef
2263 : : *
2264 : : * Returns the partition key specification, ie, the following:
2265 : : *
2266 : : * { RANGE | LIST | HASH } (column opt_collation opt_opclass [, ...])
2267 : : */
2268 : : Datum
2269 : 826 : pg_get_partkeydef(PG_FUNCTION_ARGS)
2270 : : {
2271 : 826 : Oid relid = PG_GETARG_OID(0);
2272 : : char *res;
2273 : :
2274 : 826 : res = pg_get_partkeydef_worker(relid, PRETTYFLAG_INDENT, false, true);
2275 : :
2276 [ + + ]: 826 : if (res == NULL)
2277 : 4 : PG_RETURN_NULL();
2278 : :
2279 : 822 : PG_RETURN_TEXT_P(string_to_text(res));
2280 : : }
2281 : :
2282 : : /* Internal version that just reports the column definitions */
2283 : : char *
2284 : 94 : pg_get_partkeydef_columns(Oid relid, bool pretty)
2285 : : {
2286 : : int prettyFlags;
2287 : :
2288 [ + - ]: 94 : prettyFlags = GET_PRETTY_FLAGS(pretty);
2289 : :
2290 : 94 : return pg_get_partkeydef_worker(relid, prettyFlags, true, false);
2291 : : }
2292 : :
2293 : : /*
2294 : : * Internal workhorse to decompile a partition key definition.
2295 : : */
2296 : : static char *
2297 : 920 : pg_get_partkeydef_worker(Oid relid, int prettyFlags,
2298 : : bool attrsOnly, bool missing_ok)
2299 : : {
2300 : : Form_pg_partitioned_table form;
2301 : : HeapTuple tuple;
2302 : : oidvector *partclass;
2303 : : oidvector *partcollation;
2304 : : List *partexprs;
2305 : : ListCell *partexpr_item;
2306 : : List *context;
2307 : : Datum datum;
2308 : : StringInfoData buf;
2309 : : int keyno;
2310 : : char *str;
2311 : : char *sep;
2312 : :
2313 : 920 : tuple = SearchSysCache1(PARTRELID, ObjectIdGetDatum(relid));
2314 [ + + ]: 920 : if (!HeapTupleIsValid(tuple))
2315 : : {
2316 [ + - ]: 4 : if (missing_ok)
2317 : 4 : return NULL;
2318 [ # # ]: 0 : elog(ERROR, "cache lookup failed for partition key of %u", relid);
2319 : : }
2320 : :
2321 : 916 : form = (Form_pg_partitioned_table) GETSTRUCT(tuple);
2322 : :
2323 : : Assert(form->partrelid == relid);
2324 : :
2325 : : /* Must get partclass and partcollation the hard way */
2326 : 916 : datum = SysCacheGetAttrNotNull(PARTRELID, tuple,
2327 : : Anum_pg_partitioned_table_partclass);
2328 : 916 : partclass = (oidvector *) DatumGetPointer(datum);
2329 : :
2330 : 916 : datum = SysCacheGetAttrNotNull(PARTRELID, tuple,
2331 : : Anum_pg_partitioned_table_partcollation);
2332 : 916 : partcollation = (oidvector *) DatumGetPointer(datum);
2333 : :
2334 : :
2335 : : /*
2336 : : * Get the expressions, if any. (NOTE: we do not use the relcache
2337 : : * versions of the expressions, because we want to display
2338 : : * non-const-folded expressions.)
2339 : : */
2340 [ + + ]: 916 : if (!heap_attisnull(tuple, Anum_pg_partitioned_table_partexprs, NULL))
2341 : : {
2342 : : Datum exprsDatum;
2343 : : char *exprsString;
2344 : :
2345 : 84 : exprsDatum = SysCacheGetAttrNotNull(PARTRELID, tuple,
2346 : : Anum_pg_partitioned_table_partexprs);
2347 : 84 : exprsString = TextDatumGetCString(exprsDatum);
2348 : 84 : partexprs = (List *) stringToNode(exprsString);
2349 : :
2350 [ - + ]: 84 : if (!IsA(partexprs, List))
2351 [ # # ]: 0 : elog(ERROR, "unexpected node type found in partexprs: %d",
2352 : : (int) nodeTag(partexprs));
2353 : :
2354 : 84 : pfree(exprsString);
2355 : : }
2356 : : else
2357 : 832 : partexprs = NIL;
2358 : :
2359 : 916 : partexpr_item = list_head(partexprs);
2360 : 916 : context = deparse_context_for(get_relation_name(relid), relid);
2361 : :
2362 : 916 : initStringInfo(&buf);
2363 : :
2364 [ + + + - ]: 916 : switch (form->partstrat)
2365 : : {
2366 : 61 : case PARTITION_STRATEGY_HASH:
2367 [ + - ]: 61 : if (!attrsOnly)
2368 : 61 : appendStringInfoString(&buf, "HASH");
2369 : 61 : break;
2370 : 346 : case PARTITION_STRATEGY_LIST:
2371 [ + + ]: 346 : if (!attrsOnly)
2372 : 320 : appendStringInfoString(&buf, "LIST");
2373 : 346 : break;
2374 : 509 : case PARTITION_STRATEGY_RANGE:
2375 [ + + ]: 509 : if (!attrsOnly)
2376 : 441 : appendStringInfoString(&buf, "RANGE");
2377 : 509 : break;
2378 : 0 : default:
2379 [ # # ]: 0 : elog(ERROR, "unexpected partition strategy: %d",
2380 : : (int) form->partstrat);
2381 : : }
2382 : :
2383 [ + + ]: 916 : if (!attrsOnly)
2384 : 822 : appendStringInfoString(&buf, " (");
2385 : 916 : sep = "";
2386 [ + + ]: 1925 : for (keyno = 0; keyno < form->partnatts; keyno++)
2387 : : {
2388 : 1009 : AttrNumber attnum = form->partattrs.values[keyno];
2389 : : Oid keycoltype;
2390 : : Oid keycolcollation;
2391 : : Oid partcoll;
2392 : :
2393 : 1009 : appendStringInfoString(&buf, sep);
2394 : 1009 : sep = ", ";
2395 [ + + ]: 1009 : if (attnum != 0)
2396 : : {
2397 : : /* Simple attribute reference */
2398 : : char *attname;
2399 : : int32 keycoltypmod;
2400 : :
2401 : 917 : attname = get_attname(relid, attnum, false);
2402 : 917 : appendStringInfoString(&buf, quote_identifier(attname));
2403 : 917 : get_atttypetypmodcoll(relid, attnum,
2404 : : &keycoltype, &keycoltypmod,
2405 : : &keycolcollation);
2406 : : }
2407 : : else
2408 : : {
2409 : : /* Expression */
2410 : : Node *partkey;
2411 : :
2412 [ - + ]: 92 : if (partexpr_item == NULL)
2413 [ # # ]: 0 : elog(ERROR, "too few entries in partexprs list");
2414 : 92 : partkey = (Node *) lfirst(partexpr_item);
2415 : 92 : partexpr_item = lnext(partexprs, partexpr_item);
2416 : :
2417 : : /* Deparse */
2418 : 92 : str = deparse_expression_pretty(partkey, context, false, false,
2419 : : prettyFlags, 0);
2420 : : /* Need parens if it's not a bare function call */
2421 [ + + ]: 92 : if (looks_like_function(partkey))
2422 : 34 : appendStringInfoString(&buf, str);
2423 : : else
2424 : 58 : appendStringInfo(&buf, "(%s)", str);
2425 : :
2426 : 92 : keycoltype = exprType(partkey);
2427 : 92 : keycolcollation = exprCollation(partkey);
2428 : : }
2429 : :
2430 : : /* Add collation, if not default for column */
2431 : 1009 : partcoll = partcollation->values[keyno];
2432 [ + + + + : 1009 : if (!attrsOnly && OidIsValid(partcoll) && partcoll != keycolcollation)
+ + ]
2433 : 4 : appendStringInfo(&buf, " COLLATE %s",
2434 : : generate_collation_name((partcoll)));
2435 : :
2436 : : /* Add the operator class name, if not default */
2437 [ + + ]: 1009 : if (!attrsOnly)
2438 : 879 : get_opclass_name(partclass->values[keyno], keycoltype, &buf);
2439 : : }
2440 : :
2441 [ + + ]: 916 : if (!attrsOnly)
2442 : 822 : appendStringInfoChar(&buf, ')');
2443 : :
2444 : : /* Clean up */
2445 : 916 : ReleaseSysCache(tuple);
2446 : :
2447 : 916 : return buf.data;
2448 : : }
2449 : :
2450 : : /*
2451 : : * pg_get_partition_constraintdef
2452 : : *
2453 : : * Returns partition constraint expression as a string for the input relation
2454 : : */
2455 : : Datum
2456 : 153 : pg_get_partition_constraintdef(PG_FUNCTION_ARGS)
2457 : : {
2458 : 153 : Oid relationId = PG_GETARG_OID(0);
2459 : : Expr *constr_expr;
2460 : : int prettyFlags;
2461 : : List *context;
2462 : : char *consrc;
2463 : :
2464 : 153 : constr_expr = get_partition_qual_relid(relationId);
2465 : :
2466 : : /* Quick exit if no partition constraint */
2467 [ + + ]: 153 : if (constr_expr == NULL)
2468 : 16 : PG_RETURN_NULL();
2469 : :
2470 : : /*
2471 : : * Deparse and return the constraint expression.
2472 : : */
2473 : 137 : prettyFlags = PRETTYFLAG_INDENT;
2474 : 137 : context = deparse_context_for(get_relation_name(relationId), relationId);
2475 : 137 : consrc = deparse_expression_pretty((Node *) constr_expr, context, false,
2476 : : false, prettyFlags, 0);
2477 : :
2478 : 137 : PG_RETURN_TEXT_P(string_to_text(consrc));
2479 : : }
2480 : :
2481 : : /*
2482 : : * pg_get_partconstrdef_string
2483 : : *
2484 : : * Returns the partition constraint as a C-string for the input relation, with
2485 : : * the given alias. No pretty-printing.
2486 : : */
2487 : : char *
2488 : 65 : pg_get_partconstrdef_string(Oid partitionId, char *aliasname)
2489 : : {
2490 : : Expr *constr_expr;
2491 : : List *context;
2492 : :
2493 : 65 : constr_expr = get_partition_qual_relid(partitionId);
2494 : 65 : context = deparse_context_for(aliasname, partitionId);
2495 : :
2496 : 65 : return deparse_expression((Node *) constr_expr, context, true, false);
2497 : : }
2498 : :
2499 : : /*
2500 : : * pg_get_constraintdef
2501 : : *
2502 : : * Returns the definition for the constraint, ie, everything that needs to
2503 : : * appear after "ALTER TABLE ... ADD CONSTRAINT <constraintname>".
2504 : : */
2505 : : Datum
2506 : 1232 : pg_get_constraintdef(PG_FUNCTION_ARGS)
2507 : : {
2508 : 1232 : Oid constraintId = PG_GETARG_OID(0);
2509 : : int prettyFlags;
2510 : : char *res;
2511 : :
2512 : 1232 : prettyFlags = PRETTYFLAG_INDENT;
2513 : :
2514 : 1232 : res = pg_get_constraintdef_worker(constraintId, false, prettyFlags, true);
2515 : :
2516 [ + + ]: 1232 : if (res == NULL)
2517 : 4 : PG_RETURN_NULL();
2518 : :
2519 : 1228 : PG_RETURN_TEXT_P(string_to_text(res));
2520 : : }
2521 : :
2522 : : Datum
2523 : 2959 : pg_get_constraintdef_ext(PG_FUNCTION_ARGS)
2524 : : {
2525 : 2959 : Oid constraintId = PG_GETARG_OID(0);
2526 : 2959 : bool pretty = PG_GETARG_BOOL(1);
2527 : : int prettyFlags;
2528 : : char *res;
2529 : :
2530 [ + + ]: 2959 : prettyFlags = GET_PRETTY_FLAGS(pretty);
2531 : :
2532 : 2959 : res = pg_get_constraintdef_worker(constraintId, false, prettyFlags, true);
2533 : :
2534 [ - + ]: 2959 : if (res == NULL)
2535 : 0 : PG_RETURN_NULL();
2536 : :
2537 : 2959 : PG_RETURN_TEXT_P(string_to_text(res));
2538 : : }
2539 : :
2540 : : /*
2541 : : * Internal version that returns a full ALTER TABLE ... ADD CONSTRAINT command
2542 : : */
2543 : : char *
2544 : 460 : pg_get_constraintdef_command(Oid constraintId)
2545 : : {
2546 : 460 : return pg_get_constraintdef_worker(constraintId, true, 0, false);
2547 : : }
2548 : :
2549 : : /*
2550 : : * As of 9.4, we now use an MVCC snapshot for this.
2551 : : */
2552 : : static char *
2553 : 4651 : pg_get_constraintdef_worker(Oid constraintId, bool fullCommand,
2554 : : int prettyFlags, bool missing_ok)
2555 : : {
2556 : : HeapTuple tup;
2557 : : Form_pg_constraint conForm;
2558 : : StringInfoData buf;
2559 : : SysScanDesc scandesc;
2560 : : ScanKeyData scankey[1];
2561 : 4651 : Snapshot snapshot = RegisterSnapshot(GetTransactionSnapshot());
2562 : 4651 : Relation relation = table_open(ConstraintRelationId, AccessShareLock);
2563 : :
2564 : 4651 : ScanKeyInit(&scankey[0],
2565 : : Anum_pg_constraint_oid,
2566 : : BTEqualStrategyNumber, F_OIDEQ,
2567 : : ObjectIdGetDatum(constraintId));
2568 : :
2569 : 4651 : scandesc = systable_beginscan(relation,
2570 : : ConstraintOidIndexId,
2571 : : true,
2572 : : snapshot,
2573 : : 1,
2574 : : scankey);
2575 : :
2576 : : /*
2577 : : * We later use the tuple with SysCacheGetAttr() as if we had obtained it
2578 : : * via SearchSysCache, which works fine.
2579 : : */
2580 : 4651 : tup = systable_getnext(scandesc);
2581 : :
2582 : 4651 : UnregisterSnapshot(snapshot);
2583 : :
2584 [ + + ]: 4651 : if (!HeapTupleIsValid(tup))
2585 : : {
2586 [ + - ]: 4 : if (missing_ok)
2587 : : {
2588 : 4 : systable_endscan(scandesc);
2589 : 4 : table_close(relation, AccessShareLock);
2590 : 4 : return NULL;
2591 : : }
2592 [ # # ]: 0 : elog(ERROR, "could not find tuple for constraint %u", constraintId);
2593 : : }
2594 : :
2595 : 4647 : conForm = (Form_pg_constraint) GETSTRUCT(tup);
2596 : :
2597 : 4647 : initStringInfo(&buf);
2598 : :
2599 [ + + ]: 4647 : if (fullCommand)
2600 : : {
2601 [ + + ]: 460 : if (OidIsValid(conForm->conrelid))
2602 : : {
2603 : : /*
2604 : : * Currently, callers want ALTER TABLE (without ONLY) for CHECK
2605 : : * constraints, and other types of constraints don't inherit
2606 : : * anyway so it doesn't matter whether we say ONLY or not. Someday
2607 : : * we might need to let callers specify whether to put ONLY in the
2608 : : * command.
2609 : : */
2610 : 451 : appendStringInfo(&buf, "ALTER TABLE %s ADD CONSTRAINT %s ",
2611 : : generate_qualified_relation_name(conForm->conrelid),
2612 : 451 : quote_identifier(NameStr(conForm->conname)));
2613 : : }
2614 : : else
2615 : : {
2616 : : /* Must be a domain constraint */
2617 : : Assert(OidIsValid(conForm->contypid));
2618 : 9 : appendStringInfo(&buf, "ALTER DOMAIN %s ADD CONSTRAINT %s ",
2619 : : generate_qualified_type_name(conForm->contypid),
2620 : 9 : quote_identifier(NameStr(conForm->conname)));
2621 : : }
2622 : : }
2623 : :
2624 [ + + + + : 4647 : switch (conForm->contype)
- + - ]
2625 : : {
2626 : 547 : case CONSTRAINT_FOREIGN:
2627 : : {
2628 : : Datum val;
2629 : : bool isnull;
2630 : : const char *string;
2631 : :
2632 : : /* Start off the constraint definition */
2633 : 547 : appendStringInfoString(&buf, "FOREIGN KEY (");
2634 : :
2635 : : /* Fetch and build referencing-column list */
2636 : 547 : val = SysCacheGetAttrNotNull(CONSTROID, tup,
2637 : : Anum_pg_constraint_conkey);
2638 : :
2639 : : /* If it is a temporal foreign key then it uses PERIOD. */
2640 : 547 : decompile_column_index_array(val, conForm->conrelid, conForm->conperiod, &buf);
2641 : :
2642 : : /* add foreign relation name */
2643 : 547 : appendStringInfo(&buf, ") REFERENCES %s(",
2644 : : generate_relation_name(conForm->confrelid,
2645 : : NIL));
2646 : :
2647 : : /* Fetch and build referenced-column list */
2648 : 547 : val = SysCacheGetAttrNotNull(CONSTROID, tup,
2649 : : Anum_pg_constraint_confkey);
2650 : :
2651 : 547 : decompile_column_index_array(val, conForm->confrelid, conForm->conperiod, &buf);
2652 : :
2653 : 547 : appendStringInfoChar(&buf, ')');
2654 : :
2655 : : /* Add match type */
2656 [ + - + - ]: 547 : switch (conForm->confmatchtype)
2657 : : {
2658 : 21 : case FKCONSTR_MATCH_FULL:
2659 : 21 : string = " MATCH FULL";
2660 : 21 : break;
2661 : 0 : case FKCONSTR_MATCH_PARTIAL:
2662 : 0 : string = " MATCH PARTIAL";
2663 : 0 : break;
2664 : 526 : case FKCONSTR_MATCH_SIMPLE:
2665 : 526 : string = "";
2666 : 526 : break;
2667 : 0 : default:
2668 [ # # ]: 0 : elog(ERROR, "unrecognized confmatchtype: %d",
2669 : : conForm->confmatchtype);
2670 : : string = ""; /* keep compiler quiet */
2671 : : break;
2672 : : }
2673 : 547 : appendStringInfoString(&buf, string);
2674 : :
2675 : : /* Add ON UPDATE and ON DELETE clauses, if needed */
2676 [ + - + + : 547 : switch (conForm->confupdtype)
- - ]
2677 : : {
2678 : 463 : case FKCONSTR_ACTION_NOACTION:
2679 : 463 : string = NULL; /* suppress default */
2680 : 463 : break;
2681 : 0 : case FKCONSTR_ACTION_RESTRICT:
2682 : 0 : string = "RESTRICT";
2683 : 0 : break;
2684 : 67 : case FKCONSTR_ACTION_CASCADE:
2685 : 67 : string = "CASCADE";
2686 : 67 : break;
2687 : 17 : case FKCONSTR_ACTION_SETNULL:
2688 : 17 : string = "SET NULL";
2689 : 17 : break;
2690 : 0 : case FKCONSTR_ACTION_SETDEFAULT:
2691 : 0 : string = "SET DEFAULT";
2692 : 0 : break;
2693 : 0 : default:
2694 [ # # ]: 0 : elog(ERROR, "unrecognized confupdtype: %d",
2695 : : conForm->confupdtype);
2696 : : string = NULL; /* keep compiler quiet */
2697 : : break;
2698 : : }
2699 [ + + ]: 547 : if (string)
2700 : 84 : appendStringInfo(&buf, " ON UPDATE %s", string);
2701 : :
2702 [ + - + + : 547 : switch (conForm->confdeltype)
+ - ]
2703 : : {
2704 : 464 : case FKCONSTR_ACTION_NOACTION:
2705 : 464 : string = NULL; /* suppress default */
2706 : 464 : break;
2707 : 0 : case FKCONSTR_ACTION_RESTRICT:
2708 : 0 : string = "RESTRICT";
2709 : 0 : break;
2710 : 67 : case FKCONSTR_ACTION_CASCADE:
2711 : 67 : string = "CASCADE";
2712 : 67 : break;
2713 : 12 : case FKCONSTR_ACTION_SETNULL:
2714 : 12 : string = "SET NULL";
2715 : 12 : break;
2716 : 4 : case FKCONSTR_ACTION_SETDEFAULT:
2717 : 4 : string = "SET DEFAULT";
2718 : 4 : break;
2719 : 0 : default:
2720 [ # # ]: 0 : elog(ERROR, "unrecognized confdeltype: %d",
2721 : : conForm->confdeltype);
2722 : : string = NULL; /* keep compiler quiet */
2723 : : break;
2724 : : }
2725 [ + + ]: 547 : if (string)
2726 : 83 : appendStringInfo(&buf, " ON DELETE %s", string);
2727 : :
2728 : : /*
2729 : : * Add columns specified to SET NULL or SET DEFAULT if
2730 : : * provided.
2731 : : */
2732 : 547 : val = SysCacheGetAttr(CONSTROID, tup,
2733 : : Anum_pg_constraint_confdelsetcols, &isnull);
2734 [ + + ]: 547 : if (!isnull)
2735 : : {
2736 : 8 : appendStringInfoString(&buf, " (");
2737 : 8 : decompile_column_index_array(val, conForm->conrelid, false, &buf);
2738 : 8 : appendStringInfoChar(&buf, ')');
2739 : : }
2740 : :
2741 : 547 : break;
2742 : : }
2743 : 2347 : case CONSTRAINT_PRIMARY:
2744 : : case CONSTRAINT_UNIQUE:
2745 : : {
2746 : : Datum val;
2747 : : Oid indexId;
2748 : : int keyatts;
2749 : : HeapTuple indtup;
2750 : :
2751 : : /* Start off the constraint definition */
2752 [ + + ]: 2347 : if (conForm->contype == CONSTRAINT_PRIMARY)
2753 : 1918 : appendStringInfoString(&buf, "PRIMARY KEY ");
2754 : : else
2755 : 429 : appendStringInfoString(&buf, "UNIQUE ");
2756 : :
2757 : 2347 : indexId = conForm->conindid;
2758 : :
2759 : 2347 : indtup = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexId));
2760 [ - + ]: 2347 : if (!HeapTupleIsValid(indtup))
2761 [ # # ]: 0 : elog(ERROR, "cache lookup failed for index %u", indexId);
2762 [ + + ]: 2347 : if (conForm->contype == CONSTRAINT_UNIQUE &&
2763 [ - + ]: 429 : ((Form_pg_index) GETSTRUCT(indtup))->indnullsnotdistinct)
2764 : 0 : appendStringInfoString(&buf, "NULLS NOT DISTINCT ");
2765 : :
2766 : 2347 : appendStringInfoChar(&buf, '(');
2767 : :
2768 : : /* Fetch and build target column list */
2769 : 2347 : val = SysCacheGetAttrNotNull(CONSTROID, tup,
2770 : : Anum_pg_constraint_conkey);
2771 : :
2772 : 2347 : keyatts = decompile_column_index_array(val, conForm->conrelid, false, &buf);
2773 [ + + ]: 2347 : if (conForm->conperiod)
2774 : 226 : appendStringInfoString(&buf, " WITHOUT OVERLAPS");
2775 : :
2776 : 2347 : appendStringInfoChar(&buf, ')');
2777 : :
2778 : : /* Build including column list (from pg_index.indkeys) */
2779 : 2347 : val = SysCacheGetAttrNotNull(INDEXRELID, indtup,
2780 : : Anum_pg_index_indnatts);
2781 [ + + ]: 2347 : if (DatumGetInt32(val) > keyatts)
2782 : : {
2783 : : Datum cols;
2784 : : Datum *keys;
2785 : : int nKeys;
2786 : : int j;
2787 : :
2788 : 48 : appendStringInfoString(&buf, " INCLUDE (");
2789 : :
2790 : 48 : cols = SysCacheGetAttrNotNull(INDEXRELID, indtup,
2791 : : Anum_pg_index_indkey);
2792 : :
2793 : 48 : deconstruct_array_builtin(DatumGetArrayTypeP(cols), INT2OID,
2794 : : &keys, NULL, &nKeys);
2795 : :
2796 [ + + ]: 144 : for (j = keyatts; j < nKeys; j++)
2797 : : {
2798 : : char *colName;
2799 : :
2800 : 96 : colName = get_attname(conForm->conrelid,
2801 : 96 : DatumGetInt16(keys[j]), false);
2802 [ + + ]: 96 : if (j > keyatts)
2803 : 48 : appendStringInfoString(&buf, ", ");
2804 : 96 : appendStringInfoString(&buf, quote_identifier(colName));
2805 : : }
2806 : :
2807 : 48 : appendStringInfoChar(&buf, ')');
2808 : : }
2809 : 2347 : ReleaseSysCache(indtup);
2810 : :
2811 : : /* XXX why do we only print these bits if fullCommand? */
2812 [ + + + - ]: 2347 : if (fullCommand && OidIsValid(indexId))
2813 : : {
2814 : 136 : char *options = flatten_reloptions(indexId);
2815 : : Oid tblspc;
2816 : :
2817 [ - + ]: 136 : if (options)
2818 : : {
2819 : 0 : appendStringInfo(&buf, " WITH (%s)", options);
2820 : 0 : pfree(options);
2821 : : }
2822 : :
2823 : : /*
2824 : : * Print the tablespace, unless it's the database default.
2825 : : * This is to help ALTER TABLE usage of this facility,
2826 : : * which needs this behavior to recreate exact catalog
2827 : : * state.
2828 : : */
2829 : 136 : tblspc = get_rel_tablespace(indexId);
2830 [ + + ]: 136 : if (OidIsValid(tblspc))
2831 : 16 : appendStringInfo(&buf, " USING INDEX TABLESPACE %s",
2832 : 16 : quote_identifier(get_tablespace_name(tblspc)));
2833 : : }
2834 : :
2835 : 2347 : break;
2836 : : }
2837 : 1385 : case CONSTRAINT_CHECK:
2838 : : {
2839 : : Datum val;
2840 : : char *conbin;
2841 : : char *consrc;
2842 : : Node *expr;
2843 : : List *context;
2844 : :
2845 : : /* Fetch constraint expression in parsetree form */
2846 : 1385 : val = SysCacheGetAttrNotNull(CONSTROID, tup,
2847 : : Anum_pg_constraint_conbin);
2848 : :
2849 : 1385 : conbin = TextDatumGetCString(val);
2850 : 1385 : expr = stringToNode(conbin);
2851 : :
2852 : : /* Set up deparsing context for Var nodes in constraint */
2853 [ + + ]: 1385 : if (conForm->conrelid != InvalidOid)
2854 : : {
2855 : : /* relation constraint */
2856 : 1232 : context = deparse_context_for(get_relation_name(conForm->conrelid),
2857 : : conForm->conrelid);
2858 : : }
2859 : : else
2860 : : {
2861 : : /* domain constraint --- can't have Vars */
2862 : 153 : context = NIL;
2863 : : }
2864 : :
2865 : 1385 : consrc = deparse_expression_pretty(expr, context, false, false,
2866 : : prettyFlags, 0);
2867 : :
2868 : : /*
2869 : : * Now emit the constraint definition, adding NO INHERIT if
2870 : : * necessary.
2871 : : *
2872 : : * There are cases where the constraint expression will be
2873 : : * fully parenthesized and we don't need the outer parens ...
2874 : : * but there are other cases where we do need 'em. Be
2875 : : * conservative for now.
2876 : : *
2877 : : * Note that simply checking for leading '(' and trailing ')'
2878 : : * would NOT be good enough, consider "(x > 0) AND (y > 0)".
2879 : : */
2880 : 1385 : appendStringInfo(&buf, "CHECK (%s)%s",
2881 : : consrc,
2882 [ + + ]: 1385 : conForm->connoinherit ? " NO INHERIT" : "");
2883 : 1385 : break;
2884 : : }
2885 : 292 : case CONSTRAINT_NOTNULL:
2886 : : {
2887 [ + + ]: 292 : if (conForm->conrelid)
2888 : : {
2889 : : AttrNumber attnum;
2890 : :
2891 : 232 : attnum = extractNotNullColumn(tup);
2892 : :
2893 : 232 : appendStringInfo(&buf, "NOT NULL %s",
2894 : 232 : quote_identifier(get_attname(conForm->conrelid,
2895 : : attnum, false)));
2896 [ - + ]: 232 : if (((Form_pg_constraint) GETSTRUCT(tup))->connoinherit)
2897 : 0 : appendStringInfoString(&buf, " NO INHERIT");
2898 : : }
2899 [ + - ]: 60 : else if (conForm->contypid)
2900 : : {
2901 : : /* conkey is null for domain not-null constraints */
2902 : 60 : appendStringInfoString(&buf, "NOT NULL");
2903 : : }
2904 : 292 : break;
2905 : : }
2906 : :
2907 : 0 : case CONSTRAINT_TRIGGER:
2908 : :
2909 : : /*
2910 : : * There isn't an ALTER TABLE syntax for creating a user-defined
2911 : : * constraint trigger, but it seems better to print something than
2912 : : * throw an error; if we throw error then this function couldn't
2913 : : * safely be applied to all rows of pg_constraint.
2914 : : */
2915 : 0 : appendStringInfoString(&buf, "TRIGGER");
2916 : 0 : break;
2917 : 76 : case CONSTRAINT_EXCLUSION:
2918 : : {
2919 : 76 : Oid indexOid = conForm->conindid;
2920 : : Datum val;
2921 : : Datum *elems;
2922 : : int nElems;
2923 : : int i;
2924 : : Oid *operators;
2925 : :
2926 : : /* Extract operator OIDs from the pg_constraint tuple */
2927 : 76 : val = SysCacheGetAttrNotNull(CONSTROID, tup,
2928 : : Anum_pg_constraint_conexclop);
2929 : :
2930 : 76 : deconstruct_array_builtin(DatumGetArrayTypeP(val), OIDOID,
2931 : : &elems, NULL, &nElems);
2932 : :
2933 : 76 : operators = (Oid *) palloc(nElems * sizeof(Oid));
2934 [ + + ]: 172 : for (i = 0; i < nElems; i++)
2935 : 96 : operators[i] = DatumGetObjectId(elems[i]);
2936 : :
2937 : : /* pg_get_indexdef_worker does the rest */
2938 : : /* suppress tablespace because pg_dump wants it that way */
2939 : 76 : appendStringInfoString(&buf,
2940 : 76 : pg_get_indexdef_worker(indexOid,
2941 : : 0,
2942 : : operators,
2943 : : false,
2944 : : false,
2945 : : false,
2946 : : false,
2947 : : prettyFlags,
2948 : : false));
2949 : 76 : break;
2950 : : }
2951 : 0 : default:
2952 [ # # ]: 0 : elog(ERROR, "invalid constraint type \"%c\"", conForm->contype);
2953 : : break;
2954 : : }
2955 : :
2956 [ + + ]: 4647 : if (conForm->condeferrable)
2957 : 86 : appendStringInfoString(&buf, " DEFERRABLE");
2958 [ + + ]: 4647 : if (conForm->condeferred)
2959 : 39 : appendStringInfoString(&buf, " INITIALLY DEFERRED");
2960 : :
2961 : : /* Validated status is irrelevant when the constraint is NOT ENFORCED. */
2962 [ + + ]: 4647 : if (!conForm->conenforced)
2963 : 77 : appendStringInfoString(&buf, " NOT ENFORCED");
2964 [ + + ]: 4570 : else if (!conForm->convalidated)
2965 : 150 : appendStringInfoString(&buf, " NOT VALID");
2966 : :
2967 : : /* Cleanup */
2968 : 4647 : systable_endscan(scandesc);
2969 : 4647 : table_close(relation, AccessShareLock);
2970 : :
2971 : 4647 : return buf.data;
2972 : : }
2973 : :
2974 : :
2975 : : /*
2976 : : * Convert an int16[] Datum into a comma-separated list of column names
2977 : : * for the indicated relation; append the list to buf. Returns the number
2978 : : * of keys.
2979 : : */
2980 : : static int
2981 : 4481 : decompile_column_index_array(Datum column_index_array, Oid relId,
2982 : : bool withPeriod, StringInfo buf)
2983 : : {
2984 : : Datum *keys;
2985 : : int nKeys;
2986 : : int j;
2987 : :
2988 : : /* Extract data from array of int16 */
2989 : 4481 : deconstruct_array_builtin(DatumGetArrayTypeP(column_index_array), INT2OID,
2990 : : &keys, NULL, &nKeys);
2991 : :
2992 [ + + ]: 10526 : for (j = 0; j < nKeys; j++)
2993 : : {
2994 : : char *colName;
2995 : :
2996 : 6045 : colName = get_attname(relId, DatumGetInt16(keys[j]), false);
2997 : :
2998 [ + + ]: 6045 : if (j == 0)
2999 : 4481 : appendStringInfoString(buf, quote_identifier(colName));
3000 : : else
3001 [ + + ]: 1698 : appendStringInfo(buf, ", %s%s",
3002 [ + + ]: 134 : (withPeriod && j == nKeys - 1) ? "PERIOD " : "",
3003 : : quote_identifier(colName));
3004 : : }
3005 : :
3006 : 4481 : return nKeys;
3007 : : }
3008 : :
3009 : :
3010 : : /* ----------
3011 : : * pg_get_expr - Decompile an expression tree
3012 : : *
3013 : : * Input: an expression tree in nodeToString form, and a relation OID
3014 : : *
3015 : : * Output: reverse-listed expression
3016 : : *
3017 : : * Currently, the expression can only refer to a single relation, namely
3018 : : * the one specified by the second parameter. This is sufficient for
3019 : : * partial indexes, column default expressions, etc. We also support
3020 : : * Var-free expressions, for which the OID can be InvalidOid.
3021 : : *
3022 : : * If the OID is nonzero but not actually valid, don't throw an error,
3023 : : * just return NULL. This is a bit questionable, but it's what we've
3024 : : * done historically, and it can help avoid unwanted failures when
3025 : : * examining catalog entries for just-deleted relations.
3026 : : *
3027 : : * We expect this function to work, or throw a reasonably clean error,
3028 : : * for any node tree that can appear in a catalog pg_node_tree column.
3029 : : * Query trees, such as those appearing in pg_rewrite.ev_action, are
3030 : : * not supported. Nor are expressions in more than one relation, which
3031 : : * can appear in places like pg_rewrite.ev_qual.
3032 : : * ----------
3033 : : */
3034 : : Datum
3035 : 5957 : pg_get_expr(PG_FUNCTION_ARGS)
3036 : : {
3037 : 5957 : text *expr = PG_GETARG_TEXT_PP(0);
3038 : 5957 : Oid relid = PG_GETARG_OID(1);
3039 : : text *result;
3040 : : int prettyFlags;
3041 : :
3042 : 5957 : prettyFlags = PRETTYFLAG_INDENT;
3043 : :
3044 : 5957 : result = pg_get_expr_worker(expr, relid, prettyFlags);
3045 [ + - ]: 5957 : if (result)
3046 : 5957 : PG_RETURN_TEXT_P(result);
3047 : : else
3048 : 0 : PG_RETURN_NULL();
3049 : : }
3050 : :
3051 : : Datum
3052 : 572 : pg_get_expr_ext(PG_FUNCTION_ARGS)
3053 : : {
3054 : 572 : text *expr = PG_GETARG_TEXT_PP(0);
3055 : 572 : Oid relid = PG_GETARG_OID(1);
3056 : 572 : bool pretty = PG_GETARG_BOOL(2);
3057 : : text *result;
3058 : : int prettyFlags;
3059 : :
3060 [ + - ]: 572 : prettyFlags = GET_PRETTY_FLAGS(pretty);
3061 : :
3062 : 572 : result = pg_get_expr_worker(expr, relid, prettyFlags);
3063 [ + - ]: 572 : if (result)
3064 : 572 : PG_RETURN_TEXT_P(result);
3065 : : else
3066 : 0 : PG_RETURN_NULL();
3067 : : }
3068 : :
3069 : : static text *
3070 : 6529 : pg_get_expr_worker(text *expr, Oid relid, int prettyFlags)
3071 : : {
3072 : : Node *node;
3073 : : Node *tst;
3074 : : Relids relids;
3075 : : List *context;
3076 : : char *exprstr;
3077 : 6529 : Relation rel = NULL;
3078 : : char *str;
3079 : :
3080 : : /* Convert input pg_node_tree (really TEXT) object to C string */
3081 : 6529 : exprstr = text_to_cstring(expr);
3082 : :
3083 : : /* Convert expression to node tree */
3084 : 6529 : node = (Node *) stringToNode(exprstr);
3085 : :
3086 : 6529 : pfree(exprstr);
3087 : :
3088 : : /*
3089 : : * Throw error if the input is a querytree rather than an expression tree.
3090 : : * While we could support queries here, there seems no very good reason
3091 : : * to. In most such catalog columns, we'll see a List of Query nodes, or
3092 : : * even nested Lists, so drill down to a non-List node before checking.
3093 : : */
3094 : 6529 : tst = node;
3095 [ + - - + ]: 6529 : while (tst && IsA(tst, List))
3096 : 0 : tst = linitial((List *) tst);
3097 [ + - - + ]: 6529 : if (tst && IsA(tst, Query))
3098 [ # # ]: 0 : ereport(ERROR,
3099 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3100 : : errmsg("input is a query, not an expression")));
3101 : :
3102 : : /*
3103 : : * Throw error if the expression contains Vars we won't be able to
3104 : : * deparse.
3105 : : */
3106 : 6529 : relids = pull_varnos(NULL, node);
3107 [ + + ]: 6529 : if (OidIsValid(relid))
3108 : : {
3109 [ - + ]: 6457 : if (!bms_is_subset(relids, bms_make_singleton(1)))
3110 [ # # ]: 0 : ereport(ERROR,
3111 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3112 : : errmsg("expression contains variables of more than one relation")));
3113 : : }
3114 : : else
3115 : : {
3116 [ - + ]: 72 : if (!bms_is_empty(relids))
3117 [ # # ]: 0 : ereport(ERROR,
3118 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3119 : : errmsg("expression contains variables")));
3120 : : }
3121 : :
3122 : : /*
3123 : : * Prepare deparse context if needed. If we are deparsing with a relid,
3124 : : * we need to transiently open and lock the rel, to make sure it won't go
3125 : : * away underneath us. (set_relation_column_names would lock it anyway,
3126 : : * so this isn't really introducing any new behavior.)
3127 : : */
3128 [ + + ]: 6529 : if (OidIsValid(relid))
3129 : : {
3130 : 6457 : rel = try_relation_open(relid, AccessShareLock);
3131 [ - + ]: 6457 : if (rel == NULL)
3132 : 0 : return NULL;
3133 : 6457 : context = deparse_context_for(RelationGetRelationName(rel), relid);
3134 : : }
3135 : : else
3136 : 72 : context = NIL;
3137 : :
3138 : : /* Deparse */
3139 : 6529 : str = deparse_expression_pretty(node, context, false, false,
3140 : : prettyFlags, 0);
3141 : :
3142 [ + + ]: 6529 : if (rel != NULL)
3143 : 6457 : relation_close(rel, AccessShareLock);
3144 : :
3145 : 6529 : return string_to_text(str);
3146 : : }
3147 : :
3148 : :
3149 : : /* ----------
3150 : : * pg_get_userbyid - Get a user name by roleid and
3151 : : * fallback to 'unknown (OID=n)'
3152 : : * ----------
3153 : : */
3154 : : Datum
3155 : 1251 : pg_get_userbyid(PG_FUNCTION_ARGS)
3156 : : {
3157 : 1251 : Oid roleid = PG_GETARG_OID(0);
3158 : : Name result;
3159 : : HeapTuple roletup;
3160 : : Form_pg_authid role_rec;
3161 : :
3162 : : /*
3163 : : * Allocate space for the result
3164 : : */
3165 : 1251 : result = (Name) palloc(NAMEDATALEN);
3166 : 1251 : memset(NameStr(*result), 0, NAMEDATALEN);
3167 : :
3168 : : /*
3169 : : * Get the pg_authid entry and print the result
3170 : : */
3171 : 1251 : roletup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
3172 [ + - ]: 1251 : if (HeapTupleIsValid(roletup))
3173 : : {
3174 : 1251 : role_rec = (Form_pg_authid) GETSTRUCT(roletup);
3175 : 1251 : *result = role_rec->rolname;
3176 : 1251 : ReleaseSysCache(roletup);
3177 : : }
3178 : : else
3179 : 0 : sprintf(NameStr(*result), "unknown (OID=%u)", roleid);
3180 : :
3181 : 1251 : PG_RETURN_NAME(result);
3182 : : }
3183 : :
3184 : :
3185 : : /*
3186 : : * pg_get_serial_sequence
3187 : : * Get the name of the sequence used by an identity or serial column,
3188 : : * formatted suitably for passing to setval, nextval or currval.
3189 : : * First parameter is not treated as double-quoted, second parameter
3190 : : * is --- see documentation for reason.
3191 : : */
3192 : : Datum
3193 : 8 : pg_get_serial_sequence(PG_FUNCTION_ARGS)
3194 : : {
3195 : 8 : text *tablename = PG_GETARG_TEXT_PP(0);
3196 : 8 : text *columnname = PG_GETARG_TEXT_PP(1);
3197 : : RangeVar *tablerv;
3198 : : Oid tableOid;
3199 : : char *column;
3200 : : AttrNumber attnum;
3201 : 8 : Oid sequenceId = InvalidOid;
3202 : : Relation depRel;
3203 : : ScanKeyData key[3];
3204 : : SysScanDesc scan;
3205 : : HeapTuple tup;
3206 : :
3207 : : /* Look up table name. Can't lock it - we might not have privileges. */
3208 : 8 : tablerv = makeRangeVarFromNameList(textToQualifiedNameList(tablename));
3209 : 8 : tableOid = RangeVarGetRelid(tablerv, NoLock, false);
3210 : :
3211 : : /* Get the number of the column */
3212 : 8 : column = text_to_cstring(columnname);
3213 : :
3214 : 8 : attnum = get_attnum(tableOid, column);
3215 [ - + ]: 8 : if (attnum == InvalidAttrNumber)
3216 [ # # ]: 0 : ereport(ERROR,
3217 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
3218 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
3219 : : column, tablerv->relname)));
3220 : :
3221 : : /* Search the dependency table for the dependent sequence */
3222 : 8 : depRel = table_open(DependRelationId, AccessShareLock);
3223 : :
3224 : 8 : ScanKeyInit(&key[0],
3225 : : Anum_pg_depend_refclassid,
3226 : : BTEqualStrategyNumber, F_OIDEQ,
3227 : : ObjectIdGetDatum(RelationRelationId));
3228 : 8 : ScanKeyInit(&key[1],
3229 : : Anum_pg_depend_refobjid,
3230 : : BTEqualStrategyNumber, F_OIDEQ,
3231 : : ObjectIdGetDatum(tableOid));
3232 : 8 : ScanKeyInit(&key[2],
3233 : : Anum_pg_depend_refobjsubid,
3234 : : BTEqualStrategyNumber, F_INT4EQ,
3235 : : Int32GetDatum(attnum));
3236 : :
3237 : 8 : scan = systable_beginscan(depRel, DependReferenceIndexId, true,
3238 : : NULL, 3, key);
3239 : :
3240 [ + - ]: 20 : while (HeapTupleIsValid(tup = systable_getnext(scan)))
3241 : : {
3242 : 20 : Form_pg_depend deprec = (Form_pg_depend) GETSTRUCT(tup);
3243 : :
3244 : : /*
3245 : : * Look for an auto dependency (serial column) or internal dependency
3246 : : * (identity column) of a sequence on a column. (We need the relkind
3247 : : * test because indexes can also have auto dependencies on columns.)
3248 : : */
3249 [ + + ]: 20 : if (deprec->classid == RelationRelationId &&
3250 [ + - ]: 8 : deprec->objsubid == 0 &&
3251 [ + + ]: 8 : (deprec->deptype == DEPENDENCY_AUTO ||
3252 [ + - + - ]: 12 : deprec->deptype == DEPENDENCY_INTERNAL) &&
3253 : 8 : get_rel_relkind(deprec->objid) == RELKIND_SEQUENCE)
3254 : : {
3255 : 8 : sequenceId = deprec->objid;
3256 : 8 : break;
3257 : : }
3258 : : }
3259 : :
3260 : 8 : systable_endscan(scan);
3261 : 8 : table_close(depRel, AccessShareLock);
3262 : :
3263 [ + - ]: 8 : if (OidIsValid(sequenceId))
3264 : : {
3265 : : char *result;
3266 : :
3267 : 8 : result = generate_qualified_relation_name(sequenceId);
3268 : :
3269 : 8 : PG_RETURN_TEXT_P(string_to_text(result));
3270 : : }
3271 : :
3272 : 0 : PG_RETURN_NULL();
3273 : : }
3274 : :
3275 : :
3276 : : /*
3277 : : * pg_get_functiondef
3278 : : * Returns the complete "CREATE OR REPLACE FUNCTION ..." statement for
3279 : : * the specified function.
3280 : : *
3281 : : * Note: if you change the output format of this function, be careful not
3282 : : * to break psql's rules (in \ef and \sf) for identifying the start of the
3283 : : * function body. To wit: the function body starts on a line that begins with
3284 : : * "AS ", "BEGIN ", or "RETURN ", and no preceding line will look like that.
3285 : : */
3286 : : Datum
3287 : 127 : pg_get_functiondef(PG_FUNCTION_ARGS)
3288 : : {
3289 : 127 : Oid funcid = PG_GETARG_OID(0);
3290 : : StringInfoData buf;
3291 : : StringInfoData dq;
3292 : : HeapTuple proctup;
3293 : : Form_pg_proc proc;
3294 : : bool isfunction;
3295 : : Datum tmp;
3296 : : bool isnull;
3297 : : const char *prosrc;
3298 : : const char *name;
3299 : : const char *nsp;
3300 : : float4 procost;
3301 : : int oldlen;
3302 : :
3303 : 127 : initStringInfo(&buf);
3304 : :
3305 : : /* Look up the function */
3306 : 127 : proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
3307 [ + + ]: 127 : if (!HeapTupleIsValid(proctup))
3308 : 4 : PG_RETURN_NULL();
3309 : :
3310 : 123 : proc = (Form_pg_proc) GETSTRUCT(proctup);
3311 : 123 : name = NameStr(proc->proname);
3312 : :
3313 [ - + ]: 123 : if (proc->prokind == PROKIND_AGGREGATE)
3314 [ # # ]: 0 : ereport(ERROR,
3315 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3316 : : errmsg("\"%s\" is an aggregate function", name)));
3317 : :
3318 : 123 : isfunction = (proc->prokind != PROKIND_PROCEDURE);
3319 : :
3320 : : /*
3321 : : * We always qualify the function name, to ensure the right function gets
3322 : : * replaced.
3323 : : */
3324 : 123 : nsp = get_namespace_name_or_temp(proc->pronamespace);
3325 [ + + ]: 123 : appendStringInfo(&buf, "CREATE OR REPLACE %s %s(",
3326 : : isfunction ? "FUNCTION" : "PROCEDURE",
3327 : : quote_qualified_identifier(nsp, name));
3328 : 123 : (void) print_function_arguments(&buf, proctup, false, true);
3329 : 123 : appendStringInfoString(&buf, ")\n");
3330 [ + + ]: 123 : if (isfunction)
3331 : : {
3332 : 110 : appendStringInfoString(&buf, " RETURNS ");
3333 : 110 : print_function_rettype(&buf, proctup);
3334 : 110 : appendStringInfoChar(&buf, '\n');
3335 : : }
3336 : :
3337 : 123 : print_function_trftypes(&buf, proctup);
3338 : :
3339 : 123 : appendStringInfo(&buf, " LANGUAGE %s\n",
3340 : 123 : quote_identifier(get_language_name(proc->prolang, false)));
3341 : :
3342 : : /* Emit some miscellaneous options on one line */
3343 : 123 : oldlen = buf.len;
3344 : :
3345 [ - + ]: 123 : if (proc->prokind == PROKIND_WINDOW)
3346 : 0 : appendStringInfoString(&buf, " WINDOW");
3347 [ + + + - ]: 123 : switch (proc->provolatile)
3348 : : {
3349 : 8 : case PROVOLATILE_IMMUTABLE:
3350 : 8 : appendStringInfoString(&buf, " IMMUTABLE");
3351 : 8 : break;
3352 : 20 : case PROVOLATILE_STABLE:
3353 : 20 : appendStringInfoString(&buf, " STABLE");
3354 : 20 : break;
3355 : 95 : case PROVOLATILE_VOLATILE:
3356 : 95 : break;
3357 : : }
3358 : :
3359 [ + - + - ]: 123 : switch (proc->proparallel)
3360 : : {
3361 : 17 : case PROPARALLEL_SAFE:
3362 : 17 : appendStringInfoString(&buf, " PARALLEL SAFE");
3363 : 17 : break;
3364 : 0 : case PROPARALLEL_RESTRICTED:
3365 : 0 : appendStringInfoString(&buf, " PARALLEL RESTRICTED");
3366 : 0 : break;
3367 : 106 : case PROPARALLEL_UNSAFE:
3368 : 106 : break;
3369 : : }
3370 : :
3371 [ + + ]: 123 : if (proc->proisstrict)
3372 : 32 : appendStringInfoString(&buf, " STRICT");
3373 [ + + ]: 123 : if (proc->prosecdef)
3374 : 4 : appendStringInfoString(&buf, " SECURITY DEFINER");
3375 [ - + ]: 123 : if (proc->proleakproof)
3376 : 0 : appendStringInfoString(&buf, " LEAKPROOF");
3377 : :
3378 : : /* This code for the default cost and rows should match functioncmds.c */
3379 [ + - ]: 123 : if (proc->prolang == INTERNALlanguageId ||
3380 [ + + ]: 123 : proc->prolang == ClanguageId)
3381 : 5 : procost = 1;
3382 : : else
3383 : 118 : procost = 100;
3384 [ + + ]: 123 : if (proc->procost != procost)
3385 : 4 : appendStringInfo(&buf, " COST %g", proc->procost);
3386 : :
3387 [ + + - + ]: 123 : if (proc->prorows > 0 && proc->prorows != 1000)
3388 : 0 : appendStringInfo(&buf, " ROWS %g", proc->prorows);
3389 : :
3390 [ - + ]: 123 : if (proc->prosupport)
3391 : : {
3392 : : Oid argtypes[1];
3393 : :
3394 : : /*
3395 : : * We should qualify the support function's name if it wouldn't be
3396 : : * resolved by lookup in the current search path.
3397 : : */
3398 : 0 : argtypes[0] = INTERNALOID;
3399 : 0 : appendStringInfo(&buf, " SUPPORT %s",
3400 : : generate_function_name(proc->prosupport, 1,
3401 : : NIL, argtypes,
3402 : : false, NULL, false));
3403 : : }
3404 : :
3405 [ + + ]: 123 : if (oldlen != buf.len)
3406 : 41 : appendStringInfoChar(&buf, '\n');
3407 : :
3408 : : /* Emit any proconfig options, one per line */
3409 : 123 : tmp = SysCacheGetAttr(PROCOID, proctup, Anum_pg_proc_proconfig, &isnull);
3410 [ + + ]: 123 : if (!isnull)
3411 : : {
3412 : 4 : ArrayType *a = DatumGetArrayTypeP(tmp);
3413 : : int i;
3414 : :
3415 : : Assert(ARR_ELEMTYPE(a) == TEXTOID);
3416 : : Assert(ARR_NDIM(a) == 1);
3417 : : Assert(ARR_LBOUND(a)[0] == 1);
3418 : :
3419 [ + + ]: 28 : for (i = 1; i <= ARR_DIMS(a)[0]; i++)
3420 : : {
3421 : : Datum d;
3422 : :
3423 : 24 : d = array_ref(a, 1, &i,
3424 : : -1 /* varlenarray */ ,
3425 : : -1 /* TEXT's typlen */ ,
3426 : : false /* TEXT's typbyval */ ,
3427 : : TYPALIGN_INT /* TEXT's typalign */ ,
3428 : : &isnull);
3429 [ + - ]: 24 : if (!isnull)
3430 : : {
3431 : 24 : char *configitem = TextDatumGetCString(d);
3432 : : char *pos;
3433 : :
3434 : 24 : pos = strchr(configitem, '=');
3435 [ - + ]: 24 : if (pos == NULL)
3436 : 0 : continue;
3437 : 24 : *pos++ = '\0';
3438 : :
3439 : 24 : appendStringInfo(&buf, " SET %s TO ",
3440 : : quote_identifier(configitem));
3441 : :
3442 : : /*
3443 : : * Variables that are marked GUC_LIST_QUOTE were already fully
3444 : : * quoted by flatten_set_variable_args() before they were put
3445 : : * into the proconfig array. However, because the quoting
3446 : : * rules used there aren't exactly like SQL's, we have to
3447 : : * break the list value apart and then quote the elements as
3448 : : * string literals. (The elements may be double-quoted as-is,
3449 : : * but we can't just feed them to the SQL parser; it would do
3450 : : * the wrong thing with elements that are zero-length or
3451 : : * longer than NAMEDATALEN.) Also, we need a special case for
3452 : : * empty lists.
3453 : : *
3454 : : * Variables that are not so marked should just be emitted as
3455 : : * simple string literals. If the variable is not known to
3456 : : * guc.c, we'll do that; this makes it unsafe to use
3457 : : * GUC_LIST_QUOTE for extension variables.
3458 : : */
3459 [ + + ]: 24 : if (GetConfigOptionFlags(configitem, true) & GUC_LIST_QUOTE)
3460 : : {
3461 : : List *namelist;
3462 : : ListCell *lc;
3463 : :
3464 : : /* Parse string into list of identifiers */
3465 [ - + ]: 12 : if (!SplitGUCList(pos, ',', &namelist))
3466 : : {
3467 : : /* this shouldn't fail really */
3468 [ # # ]: 0 : elog(ERROR, "invalid list syntax in proconfig item");
3469 : : }
3470 : : /* Special case: represent an empty list as NULL */
3471 [ + + ]: 12 : if (namelist == NIL)
3472 : 4 : appendStringInfoString(&buf, "NULL");
3473 [ + + + + : 32 : foreach(lc, namelist)
+ + ]
3474 : : {
3475 : 20 : char *curname = (char *) lfirst(lc);
3476 : :
3477 : 20 : simple_quote_literal(&buf, curname);
3478 [ + + ]: 20 : if (lnext(namelist, lc))
3479 : 12 : appendStringInfoString(&buf, ", ");
3480 : : }
3481 : : }
3482 : : else
3483 : 12 : simple_quote_literal(&buf, pos);
3484 : 24 : appendStringInfoChar(&buf, '\n');
3485 : : }
3486 : : }
3487 : : }
3488 : :
3489 : : /* And finally the function definition ... */
3490 : 123 : (void) SysCacheGetAttr(PROCOID, proctup, Anum_pg_proc_prosqlbody, &isnull);
3491 [ + + + + ]: 123 : if (proc->prolang == SQLlanguageId && !isnull)
3492 : : {
3493 : 91 : print_function_sqlbody(&buf, proctup);
3494 : : }
3495 : : else
3496 : : {
3497 : 32 : appendStringInfoString(&buf, "AS ");
3498 : :
3499 : 32 : tmp = SysCacheGetAttr(PROCOID, proctup, Anum_pg_proc_probin, &isnull);
3500 [ + + ]: 32 : if (!isnull)
3501 : : {
3502 : 5 : simple_quote_literal(&buf, TextDatumGetCString(tmp));
3503 : 5 : appendStringInfoString(&buf, ", "); /* assume prosrc isn't null */
3504 : : }
3505 : :
3506 : 32 : tmp = SysCacheGetAttrNotNull(PROCOID, proctup, Anum_pg_proc_prosrc);
3507 : 32 : prosrc = TextDatumGetCString(tmp);
3508 : :
3509 : : /*
3510 : : * We always use dollar quoting. Figure out a suitable delimiter.
3511 : : *
3512 : : * Since the user is likely to be editing the function body string, we
3513 : : * shouldn't use a short delimiter that he might easily create a
3514 : : * conflict with. Hence prefer "$function$"/"$procedure$", but extend
3515 : : * if needed.
3516 : : */
3517 : 32 : initStringInfo(&dq);
3518 : 32 : appendStringInfoChar(&dq, '$');
3519 [ + + ]: 32 : appendStringInfoString(&dq, (isfunction ? "function" : "procedure"));
3520 [ - + ]: 32 : while (strstr(prosrc, dq.data) != NULL)
3521 : 0 : appendStringInfoChar(&dq, 'x');
3522 : 32 : appendStringInfoChar(&dq, '$');
3523 : :
3524 : 32 : appendBinaryStringInfo(&buf, dq.data, dq.len);
3525 : 32 : appendStringInfoString(&buf, prosrc);
3526 : 32 : appendBinaryStringInfo(&buf, dq.data, dq.len);
3527 : : }
3528 : :
3529 : 123 : appendStringInfoChar(&buf, '\n');
3530 : :
3531 : 123 : ReleaseSysCache(proctup);
3532 : :
3533 : 123 : PG_RETURN_TEXT_P(string_to_text(buf.data));
3534 : : }
3535 : :
3536 : : /*
3537 : : * pg_get_function_arguments
3538 : : * Get a nicely-formatted list of arguments for a function.
3539 : : * This is everything that would go between the parentheses in
3540 : : * CREATE FUNCTION.
3541 : : */
3542 : : Datum
3543 : 2504 : pg_get_function_arguments(PG_FUNCTION_ARGS)
3544 : : {
3545 : 2504 : Oid funcid = PG_GETARG_OID(0);
3546 : : StringInfoData buf;
3547 : : HeapTuple proctup;
3548 : :
3549 : 2504 : proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
3550 [ + + ]: 2504 : if (!HeapTupleIsValid(proctup))
3551 : 4 : PG_RETURN_NULL();
3552 : :
3553 : 2500 : initStringInfo(&buf);
3554 : :
3555 : 2500 : (void) print_function_arguments(&buf, proctup, false, true);
3556 : :
3557 : 2500 : ReleaseSysCache(proctup);
3558 : :
3559 : 2500 : PG_RETURN_TEXT_P(string_to_text(buf.data));
3560 : : }
3561 : :
3562 : : /*
3563 : : * pg_get_function_identity_arguments
3564 : : * Get a formatted list of arguments for a function.
3565 : : * This is everything that would go between the parentheses in
3566 : : * ALTER FUNCTION, etc. In particular, don't print defaults.
3567 : : */
3568 : : Datum
3569 : 2138 : pg_get_function_identity_arguments(PG_FUNCTION_ARGS)
3570 : : {
3571 : 2138 : Oid funcid = PG_GETARG_OID(0);
3572 : : StringInfoData buf;
3573 : : HeapTuple proctup;
3574 : :
3575 : 2138 : proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
3576 [ + + ]: 2138 : if (!HeapTupleIsValid(proctup))
3577 : 4 : PG_RETURN_NULL();
3578 : :
3579 : 2134 : initStringInfo(&buf);
3580 : :
3581 : 2134 : (void) print_function_arguments(&buf, proctup, false, false);
3582 : :
3583 : 2134 : ReleaseSysCache(proctup);
3584 : :
3585 : 2134 : PG_RETURN_TEXT_P(string_to_text(buf.data));
3586 : : }
3587 : :
3588 : : /*
3589 : : * pg_get_function_result
3590 : : * Get a nicely-formatted version of the result type of a function.
3591 : : * This is what would appear after RETURNS in CREATE FUNCTION.
3592 : : */
3593 : : Datum
3594 : 2204 : pg_get_function_result(PG_FUNCTION_ARGS)
3595 : : {
3596 : 2204 : Oid funcid = PG_GETARG_OID(0);
3597 : : StringInfoData buf;
3598 : : HeapTuple proctup;
3599 : :
3600 : 2204 : proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
3601 [ + + ]: 2204 : if (!HeapTupleIsValid(proctup))
3602 : 4 : PG_RETURN_NULL();
3603 : :
3604 [ + + ]: 2200 : if (((Form_pg_proc) GETSTRUCT(proctup))->prokind == PROKIND_PROCEDURE)
3605 : : {
3606 : 134 : ReleaseSysCache(proctup);
3607 : 134 : PG_RETURN_NULL();
3608 : : }
3609 : :
3610 : 2066 : initStringInfo(&buf);
3611 : :
3612 : 2066 : print_function_rettype(&buf, proctup);
3613 : :
3614 : 2066 : ReleaseSysCache(proctup);
3615 : :
3616 : 2066 : PG_RETURN_TEXT_P(string_to_text(buf.data));
3617 : : }
3618 : :
3619 : : /*
3620 : : * Guts of pg_get_function_result: append the function's return type
3621 : : * to the specified buffer.
3622 : : */
3623 : : static void
3624 : 2176 : print_function_rettype(StringInfo buf, HeapTuple proctup)
3625 : : {
3626 : 2176 : Form_pg_proc proc = (Form_pg_proc) GETSTRUCT(proctup);
3627 : 2176 : int ntabargs = 0;
3628 : : StringInfoData rbuf;
3629 : :
3630 : 2176 : initStringInfo(&rbuf);
3631 : :
3632 [ + + ]: 2176 : if (proc->proretset)
3633 : : {
3634 : : /* It might be a table function; try to print the arguments */
3635 : 214 : appendStringInfoString(&rbuf, "TABLE(");
3636 : 214 : ntabargs = print_function_arguments(&rbuf, proctup, true, false);
3637 [ + + ]: 214 : if (ntabargs > 0)
3638 : 44 : appendStringInfoChar(&rbuf, ')');
3639 : : else
3640 : 170 : resetStringInfo(&rbuf);
3641 : : }
3642 : :
3643 [ + + ]: 2176 : if (ntabargs == 0)
3644 : : {
3645 : : /* Not a table function, so do the normal thing */
3646 [ + + ]: 2132 : if (proc->proretset)
3647 : 170 : appendStringInfoString(&rbuf, "SETOF ");
3648 : 2132 : appendStringInfoString(&rbuf, format_type_be(proc->prorettype));
3649 : : }
3650 : :
3651 : 2176 : appendBinaryStringInfo(buf, rbuf.data, rbuf.len);
3652 : 2176 : }
3653 : :
3654 : : /*
3655 : : * Common code for pg_get_function_arguments and pg_get_function_result:
3656 : : * append the desired subset of arguments to buf. We print only TABLE
3657 : : * arguments when print_table_args is true, and all the others when it's false.
3658 : : * We print argument defaults only if print_defaults is true.
3659 : : * Function return value is the number of arguments printed.
3660 : : */
3661 : : static int
3662 : 4971 : print_function_arguments(StringInfo buf, HeapTuple proctup,
3663 : : bool print_table_args, bool print_defaults)
3664 : : {
3665 : 4971 : Form_pg_proc proc = (Form_pg_proc) GETSTRUCT(proctup);
3666 : : int numargs;
3667 : : Oid *argtypes;
3668 : : char **argnames;
3669 : : char *argmodes;
3670 : 4971 : int insertorderbyat = -1;
3671 : : int argsprinted;
3672 : : int inputargno;
3673 : : int nlackdefaults;
3674 : 4971 : List *argdefaults = NIL;
3675 : 4971 : ListCell *nextargdefault = NULL;
3676 : : int i;
3677 : :
3678 : 4971 : numargs = get_func_arg_info(proctup,
3679 : : &argtypes, &argnames, &argmodes);
3680 : :
3681 : 4971 : nlackdefaults = numargs;
3682 [ + + + + ]: 4971 : if (print_defaults && proc->pronargdefaults > 0)
3683 : : {
3684 : : Datum proargdefaults;
3685 : : bool isnull;
3686 : :
3687 : 21 : proargdefaults = SysCacheGetAttr(PROCOID, proctup,
3688 : : Anum_pg_proc_proargdefaults,
3689 : : &isnull);
3690 [ + - ]: 21 : if (!isnull)
3691 : : {
3692 : : char *str;
3693 : :
3694 : 21 : str = TextDatumGetCString(proargdefaults);
3695 : 21 : argdefaults = castNode(List, stringToNode(str));
3696 : 21 : pfree(str);
3697 : 21 : nextargdefault = list_head(argdefaults);
3698 : : /* nlackdefaults counts only *input* arguments lacking defaults */
3699 : 21 : nlackdefaults = proc->pronargs - list_length(argdefaults);
3700 : : }
3701 : : }
3702 : :
3703 : : /* Check for special treatment of ordered-set aggregates */
3704 [ + + ]: 4971 : if (proc->prokind == PROKIND_AGGREGATE)
3705 : : {
3706 : : HeapTuple aggtup;
3707 : : Form_pg_aggregate agg;
3708 : :
3709 : 598 : aggtup = SearchSysCache1(AGGFNOID, ObjectIdGetDatum(proc->oid));
3710 [ - + ]: 598 : if (!HeapTupleIsValid(aggtup))
3711 [ # # ]: 0 : elog(ERROR, "cache lookup failed for aggregate %u",
3712 : : proc->oid);
3713 : 598 : agg = (Form_pg_aggregate) GETSTRUCT(aggtup);
3714 [ + + ]: 598 : if (AGGKIND_IS_ORDERED_SET(agg->aggkind))
3715 : 28 : insertorderbyat = agg->aggnumdirectargs;
3716 : 598 : ReleaseSysCache(aggtup);
3717 : : }
3718 : :
3719 : 4971 : argsprinted = 0;
3720 : 4971 : inputargno = 0;
3721 [ + + ]: 10110 : for (i = 0; i < numargs; i++)
3722 : : {
3723 : 5139 : Oid argtype = argtypes[i];
3724 [ + + ]: 5139 : char *argname = argnames ? argnames[i] : NULL;
3725 [ + + ]: 5139 : char argmode = argmodes ? argmodes[i] : PROARGMODE_IN;
3726 : : const char *modename;
3727 : : bool isinput;
3728 : :
3729 [ + + + + : 5139 : switch (argmode)
+ - ]
3730 : : {
3731 : 4204 : case PROARGMODE_IN:
3732 : :
3733 : : /*
3734 : : * For procedures, explicitly mark all argument modes, so as
3735 : : * to avoid ambiguity with the SQL syntax for DROP PROCEDURE.
3736 : : */
3737 [ + + ]: 4204 : if (proc->prokind == PROKIND_PROCEDURE)
3738 : 295 : modename = "IN ";
3739 : : else
3740 : 3909 : modename = "";
3741 : 4204 : isinput = true;
3742 : 4204 : break;
3743 : 50 : case PROARGMODE_INOUT:
3744 : 50 : modename = "INOUT ";
3745 : 50 : isinput = true;
3746 : 50 : break;
3747 : 517 : case PROARGMODE_OUT:
3748 : 517 : modename = "OUT ";
3749 : 517 : isinput = false;
3750 : 517 : break;
3751 : 92 : case PROARGMODE_VARIADIC:
3752 : 92 : modename = "VARIADIC ";
3753 : 92 : isinput = true;
3754 : 92 : break;
3755 : 276 : case PROARGMODE_TABLE:
3756 : 276 : modename = "";
3757 : 276 : isinput = false;
3758 : 276 : break;
3759 : 0 : default:
3760 [ # # ]: 0 : elog(ERROR, "invalid parameter mode '%c'", argmode);
3761 : : modename = NULL; /* keep compiler quiet */
3762 : : isinput = false;
3763 : : break;
3764 : : }
3765 [ + + ]: 5139 : if (isinput)
3766 : 4346 : inputargno++; /* this is a 1-based counter */
3767 : :
3768 [ + + ]: 5139 : if (print_table_args != (argmode == PROARGMODE_TABLE))
3769 : 441 : continue;
3770 : :
3771 [ + + ]: 4698 : if (argsprinted == insertorderbyat)
3772 : : {
3773 [ + - ]: 28 : if (argsprinted)
3774 : 28 : appendStringInfoChar(buf, ' ');
3775 : 28 : appendStringInfoString(buf, "ORDER BY ");
3776 : : }
3777 [ + + ]: 4670 : else if (argsprinted)
3778 : 1530 : appendStringInfoString(buf, ", ");
3779 : :
3780 : 4698 : appendStringInfoString(buf, modename);
3781 [ + + + + ]: 4698 : if (argname && argname[0])
3782 : 1733 : appendStringInfo(buf, "%s ", quote_identifier(argname));
3783 : 4698 : appendStringInfoString(buf, format_type_be(argtype));
3784 [ + + + + : 4698 : if (print_defaults && isinput && inputargno > nlackdefaults)
+ + ]
3785 : : {
3786 : : Node *expr;
3787 : :
3788 : : Assert(nextargdefault != NULL);
3789 : 32 : expr = (Node *) lfirst(nextargdefault);
3790 : 32 : nextargdefault = lnext(argdefaults, nextargdefault);
3791 : :
3792 : 32 : appendStringInfo(buf, " DEFAULT %s",
3793 : : deparse_expression(expr, NIL, false, false));
3794 : : }
3795 : 4698 : argsprinted++;
3796 : :
3797 : : /* nasty hack: print the last arg twice for variadic ordered-set agg */
3798 [ + + + + ]: 4698 : if (argsprinted == insertorderbyat && i == numargs - 1)
3799 : : {
3800 : 14 : i--;
3801 : : /* aggs shouldn't have defaults anyway, but just to be sure ... */
3802 : 14 : print_defaults = false;
3803 : : }
3804 : : }
3805 : :
3806 : 4971 : return argsprinted;
3807 : : }
3808 : :
3809 : : static bool
3810 : 64 : is_input_argument(int nth, const char *argmodes)
3811 : : {
3812 : : return (!argmodes
3813 [ + + ]: 28 : || argmodes[nth] == PROARGMODE_IN
3814 [ + - ]: 12 : || argmodes[nth] == PROARGMODE_INOUT
3815 [ + + - + ]: 92 : || argmodes[nth] == PROARGMODE_VARIADIC);
3816 : : }
3817 : :
3818 : : /*
3819 : : * Append used transformed types to specified buffer
3820 : : */
3821 : : static void
3822 : 123 : print_function_trftypes(StringInfo buf, HeapTuple proctup)
3823 : : {
3824 : : Oid *trftypes;
3825 : : int ntypes;
3826 : :
3827 : 123 : ntypes = get_func_trftypes(proctup, &trftypes);
3828 [ + + ]: 123 : if (ntypes > 0)
3829 : : {
3830 : : int i;
3831 : :
3832 : 3 : appendStringInfoString(buf, " TRANSFORM ");
3833 [ + + ]: 8 : for (i = 0; i < ntypes; i++)
3834 : : {
3835 [ + + ]: 5 : if (i != 0)
3836 : 2 : appendStringInfoString(buf, ", ");
3837 : 5 : appendStringInfo(buf, "FOR TYPE %s", format_type_be(trftypes[i]));
3838 : : }
3839 : 3 : appendStringInfoChar(buf, '\n');
3840 : : }
3841 : 123 : }
3842 : :
3843 : : /*
3844 : : * Get textual representation of a function argument's default value. The
3845 : : * second argument of this function is the argument number among all arguments
3846 : : * (i.e. proallargtypes, *not* proargtypes), starting with 1, because that's
3847 : : * how information_schema.sql uses it.
3848 : : */
3849 : : Datum
3850 : 36 : pg_get_function_arg_default(PG_FUNCTION_ARGS)
3851 : : {
3852 : 36 : Oid funcid = PG_GETARG_OID(0);
3853 : 36 : int32 nth_arg = PG_GETARG_INT32(1);
3854 : : HeapTuple proctup;
3855 : : Form_pg_proc proc;
3856 : : int numargs;
3857 : : Oid *argtypes;
3858 : : char **argnames;
3859 : : char *argmodes;
3860 : : int i;
3861 : : List *argdefaults;
3862 : : Node *node;
3863 : : char *str;
3864 : : int nth_inputarg;
3865 : : Datum proargdefaults;
3866 : : bool isnull;
3867 : : int nth_default;
3868 : :
3869 : 36 : proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
3870 [ + + ]: 36 : if (!HeapTupleIsValid(proctup))
3871 : 8 : PG_RETURN_NULL();
3872 : :
3873 : 28 : numargs = get_func_arg_info(proctup, &argtypes, &argnames, &argmodes);
3874 [ + - + - : 28 : if (nth_arg < 1 || nth_arg > numargs || !is_input_argument(nth_arg - 1, argmodes))
+ + ]
3875 : : {
3876 : 8 : ReleaseSysCache(proctup);
3877 : 8 : PG_RETURN_NULL();
3878 : : }
3879 : :
3880 : 20 : nth_inputarg = 0;
3881 [ + + ]: 56 : for (i = 0; i < nth_arg; i++)
3882 [ + + ]: 36 : if (is_input_argument(i, argmodes))
3883 : 32 : nth_inputarg++;
3884 : :
3885 : 20 : proargdefaults = SysCacheGetAttr(PROCOID, proctup,
3886 : : Anum_pg_proc_proargdefaults,
3887 : : &isnull);
3888 [ - + ]: 20 : if (isnull)
3889 : : {
3890 : 0 : ReleaseSysCache(proctup);
3891 : 0 : PG_RETURN_NULL();
3892 : : }
3893 : :
3894 : 20 : str = TextDatumGetCString(proargdefaults);
3895 : 20 : argdefaults = castNode(List, stringToNode(str));
3896 : 20 : pfree(str);
3897 : :
3898 : 20 : proc = (Form_pg_proc) GETSTRUCT(proctup);
3899 : :
3900 : : /*
3901 : : * Calculate index into proargdefaults: proargdefaults corresponds to the
3902 : : * last N input arguments, where N = pronargdefaults.
3903 : : */
3904 : 20 : nth_default = nth_inputarg - 1 - (proc->pronargs - proc->pronargdefaults);
3905 : :
3906 [ + + - + ]: 20 : if (nth_default < 0 || nth_default >= list_length(argdefaults))
3907 : : {
3908 : 4 : ReleaseSysCache(proctup);
3909 : 4 : PG_RETURN_NULL();
3910 : : }
3911 : 16 : node = list_nth(argdefaults, nth_default);
3912 : 16 : str = deparse_expression(node, NIL, false, false);
3913 : :
3914 : 16 : ReleaseSysCache(proctup);
3915 : :
3916 : 16 : PG_RETURN_TEXT_P(string_to_text(str));
3917 : : }
3918 : :
3919 : : static void
3920 : 141 : print_function_sqlbody(StringInfo buf, HeapTuple proctup)
3921 : : {
3922 : : int numargs;
3923 : : Oid *argtypes;
3924 : : char **argnames;
3925 : : char *argmodes;
3926 : 141 : deparse_namespace dpns = {0};
3927 : : Datum tmp;
3928 : : Node *n;
3929 : :
3930 : 141 : dpns.funcname = pstrdup(NameStr(((Form_pg_proc) GETSTRUCT(proctup))->proname));
3931 : 141 : numargs = get_func_arg_info(proctup,
3932 : : &argtypes, &argnames, &argmodes);
3933 : 141 : dpns.numargs = numargs;
3934 : 141 : dpns.argnames = argnames;
3935 : :
3936 : 141 : tmp = SysCacheGetAttrNotNull(PROCOID, proctup, Anum_pg_proc_prosqlbody);
3937 : 141 : n = stringToNode(TextDatumGetCString(tmp));
3938 : :
3939 [ + + ]: 141 : if (IsA(n, List))
3940 : : {
3941 : : List *stmts;
3942 : : ListCell *lc;
3943 : :
3944 : 114 : stmts = linitial(castNode(List, n));
3945 : :
3946 : 114 : appendStringInfoString(buf, "BEGIN ATOMIC\n");
3947 : :
3948 [ + + + + : 223 : foreach(lc, stmts)
+ + ]
3949 : : {
3950 : 109 : Query *query = lfirst_node(Query, lc);
3951 : :
3952 : : /* It seems advisable to get at least AccessShareLock on rels */
3953 : 109 : AcquireRewriteLocks(query, false, false);
3954 : 109 : get_query_def(query, buf, list_make1(&dpns), NULL, false,
3955 : : PRETTYFLAG_INDENT, WRAP_COLUMN_DEFAULT, 1);
3956 : 109 : appendStringInfoChar(buf, ';');
3957 : 109 : appendStringInfoChar(buf, '\n');
3958 : : }
3959 : :
3960 : 114 : appendStringInfoString(buf, "END");
3961 : : }
3962 : : else
3963 : : {
3964 : 27 : Query *query = castNode(Query, n);
3965 : :
3966 : : /* It seems advisable to get at least AccessShareLock on rels */
3967 : 27 : AcquireRewriteLocks(query, false, false);
3968 : 27 : get_query_def(query, buf, list_make1(&dpns), NULL, false,
3969 : : 0, WRAP_COLUMN_DEFAULT, 0);
3970 : : }
3971 : 141 : }
3972 : :
3973 : : Datum
3974 : 1847 : pg_get_function_sqlbody(PG_FUNCTION_ARGS)
3975 : : {
3976 : 1847 : Oid funcid = PG_GETARG_OID(0);
3977 : : StringInfoData buf;
3978 : : HeapTuple proctup;
3979 : : bool isnull;
3980 : :
3981 : 1847 : initStringInfo(&buf);
3982 : :
3983 : : /* Look up the function */
3984 : 1847 : proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
3985 [ - + ]: 1847 : if (!HeapTupleIsValid(proctup))
3986 : 0 : PG_RETURN_NULL();
3987 : :
3988 : 1847 : (void) SysCacheGetAttr(PROCOID, proctup, Anum_pg_proc_prosqlbody, &isnull);
3989 [ + + ]: 1847 : if (isnull)
3990 : : {
3991 : 1797 : ReleaseSysCache(proctup);
3992 : 1797 : PG_RETURN_NULL();
3993 : : }
3994 : :
3995 : 50 : print_function_sqlbody(&buf, proctup);
3996 : :
3997 : 50 : ReleaseSysCache(proctup);
3998 : :
3999 : 50 : PG_RETURN_TEXT_P(cstring_to_text_with_len(buf.data, buf.len));
4000 : : }
4001 : :
4002 : :
4003 : : /*
4004 : : * deparse_expression - General utility for deparsing expressions
4005 : : *
4006 : : * calls deparse_expression_pretty with all prettyPrinting disabled
4007 : : */
4008 : : char *
4009 : 55118 : deparse_expression(Node *expr, List *dpcontext,
4010 : : bool forceprefix, bool showimplicit)
4011 : : {
4012 : 55118 : return deparse_expression_pretty(expr, dpcontext, forceprefix,
4013 : : showimplicit, 0, 0);
4014 : : }
4015 : :
4016 : : /* ----------
4017 : : * deparse_expression_pretty - General utility for deparsing expressions
4018 : : *
4019 : : * expr is the node tree to be deparsed. It must be a transformed expression
4020 : : * tree (ie, not the raw output of gram.y).
4021 : : *
4022 : : * dpcontext is a list of deparse_namespace nodes representing the context
4023 : : * for interpreting Vars in the node tree. It can be NIL if no Vars are
4024 : : * expected.
4025 : : *
4026 : : * forceprefix is true to force all Vars to be prefixed with their table names.
4027 : : *
4028 : : * showimplicit is true to force all implicit casts to be shown explicitly.
4029 : : *
4030 : : * Tries to pretty up the output according to prettyFlags and startIndent.
4031 : : *
4032 : : * The result is a palloc'd string.
4033 : : * ----------
4034 : : */
4035 : : static char *
4036 : 64545 : deparse_expression_pretty(Node *expr, List *dpcontext,
4037 : : bool forceprefix, bool showimplicit,
4038 : : int prettyFlags, int startIndent)
4039 : : {
4040 : : StringInfoData buf;
4041 : : deparse_context context;
4042 : :
4043 : 64545 : initStringInfo(&buf);
4044 : 64545 : context.buf = &buf;
4045 : 64545 : context.namespaces = dpcontext;
4046 : 64545 : context.resultDesc = NULL;
4047 : 64545 : context.targetList = NIL;
4048 : 64545 : context.windowClause = NIL;
4049 : 64545 : context.varprefix = forceprefix;
4050 : 64545 : context.prettyFlags = prettyFlags;
4051 : 64545 : context.wrapColumn = WRAP_COLUMN_DEFAULT;
4052 : 64545 : context.indentLevel = startIndent;
4053 : 64545 : context.colNamesVisible = true;
4054 : 64545 : context.inGroupBy = false;
4055 : 64545 : context.varInOrderBy = false;
4056 : 64545 : context.appendparents = NULL;
4057 : :
4058 : 64545 : get_rule_expr(expr, &context, showimplicit);
4059 : :
4060 : 64545 : return buf.data;
4061 : : }
4062 : :
4063 : : /* ----------
4064 : : * deparse_context_for - Build deparse context for a single relation
4065 : : *
4066 : : * Given the reference name (alias) and OID of a relation, build deparsing
4067 : : * context for an expression referencing only that relation (as varno 1,
4068 : : * varlevelsup 0). This is sufficient for many uses of deparse_expression.
4069 : : * ----------
4070 : : */
4071 : : List *
4072 : 16125 : deparse_context_for(const char *aliasname, Oid relid)
4073 : : {
4074 : : deparse_namespace *dpns;
4075 : : RangeTblEntry *rte;
4076 : :
4077 : 16125 : dpns = palloc0_object(deparse_namespace);
4078 : :
4079 : : /* Build a minimal RTE for the rel */
4080 : 16125 : rte = makeNode(RangeTblEntry);
4081 : 16125 : rte->rtekind = RTE_RELATION;
4082 : 16125 : rte->relid = relid;
4083 : 16125 : rte->relkind = RELKIND_RELATION; /* no need for exactness here */
4084 : 16125 : rte->rellockmode = AccessShareLock;
4085 : 16125 : rte->alias = makeAlias(aliasname, NIL);
4086 : 16125 : rte->eref = rte->alias;
4087 : 16125 : rte->lateral = false;
4088 : 16125 : rte->inh = false;
4089 : 16125 : rte->inFromCl = true;
4090 : :
4091 : : /* Build one-element rtable */
4092 : 16125 : dpns->rtable = list_make1(rte);
4093 : 16125 : dpns->subplans = NIL;
4094 : 16125 : dpns->ctes = NIL;
4095 : 16125 : dpns->appendrels = NULL;
4096 : 16125 : set_rtable_names(dpns, NIL, NULL);
4097 : 16125 : set_simple_column_names(dpns);
4098 : :
4099 : : /* Return a one-deep namespace stack */
4100 : 16125 : return list_make1(dpns);
4101 : : }
4102 : :
4103 : : /*
4104 : : * deparse_context_for_plan_tree - Build deparse context for a Plan tree
4105 : : *
4106 : : * When deparsing an expression in a Plan tree, we use the plan's rangetable
4107 : : * to resolve names of simple Vars. The initialization of column names for
4108 : : * this is rather expensive if the rangetable is large, and it'll be the same
4109 : : * for every expression in the Plan tree; so we do it just once and re-use
4110 : : * the result of this function for each expression. (Note that the result
4111 : : * is not usable until set_deparse_context_plan() is applied to it.)
4112 : : *
4113 : : * In addition to the PlannedStmt, pass the per-RTE alias names
4114 : : * assigned by a previous call to select_rtable_names_for_explain.
4115 : : */
4116 : : List *
4117 : 16606 : deparse_context_for_plan_tree(PlannedStmt *pstmt, List *rtable_names)
4118 : : {
4119 : : deparse_namespace *dpns;
4120 : :
4121 : 16606 : dpns = palloc0_object(deparse_namespace);
4122 : :
4123 : : /* Initialize fields that stay the same across the whole plan tree */
4124 : 16606 : dpns->rtable = pstmt->rtable;
4125 : 16606 : dpns->rtable_names = rtable_names;
4126 : 16606 : dpns->subplans = pstmt->subplans;
4127 : 16606 : dpns->ctes = NIL;
4128 [ + + ]: 16606 : if (pstmt->appendRelations)
4129 : : {
4130 : : /* Set up the array, indexed by child relid */
4131 : 2653 : int ntables = list_length(dpns->rtable);
4132 : : ListCell *lc;
4133 : :
4134 : 2653 : dpns->appendrels = (AppendRelInfo **)
4135 : 2653 : palloc0((ntables + 1) * sizeof(AppendRelInfo *));
4136 [ + - + + : 14610 : foreach(lc, pstmt->appendRelations)
+ + ]
4137 : : {
4138 : 11957 : AppendRelInfo *appinfo = lfirst_node(AppendRelInfo, lc);
4139 : 11957 : Index crelid = appinfo->child_relid;
4140 : :
4141 : : Assert(crelid > 0 && crelid <= ntables);
4142 : : Assert(dpns->appendrels[crelid] == NULL);
4143 : 11957 : dpns->appendrels[crelid] = appinfo;
4144 : : }
4145 : : }
4146 : : else
4147 : 13953 : dpns->appendrels = NULL; /* don't need it */
4148 : :
4149 : : /*
4150 : : * Set up column name aliases, ignoring any join RTEs; they don't matter
4151 : : * because plan trees don't contain any join alias Vars.
4152 : : */
4153 : 16606 : set_simple_column_names(dpns);
4154 : :
4155 : : /* Return a one-deep namespace stack */
4156 : 16606 : return list_make1(dpns);
4157 : : }
4158 : :
4159 : : /*
4160 : : * set_deparse_context_plan - Specify Plan node containing expression
4161 : : *
4162 : : * When deparsing an expression in a Plan tree, we might have to resolve
4163 : : * OUTER_VAR, INNER_VAR, or INDEX_VAR references. To do this, the caller must
4164 : : * provide the parent Plan node. Then OUTER_VAR and INNER_VAR references
4165 : : * can be resolved by drilling down into the left and right child plans.
4166 : : * Similarly, INDEX_VAR references can be resolved by reference to the
4167 : : * indextlist given in a parent IndexOnlyScan node, or to the scan tlist in
4168 : : * ForeignScan and CustomScan nodes. (Note that we don't currently support
4169 : : * deparsing of indexquals in regular IndexScan or BitmapIndexScan nodes;
4170 : : * for those, we can only deparse the indexqualorig fields, which won't
4171 : : * contain INDEX_VAR Vars.)
4172 : : *
4173 : : * The ancestors list is a list of the Plan's parent Plan and SubPlan nodes,
4174 : : * the most-closely-nested first. This is needed to resolve PARAM_EXEC
4175 : : * Params. Note we assume that all the Plan nodes share the same rtable.
4176 : : *
4177 : : * For a ModifyTable plan, we might also need to resolve references to OLD/NEW
4178 : : * variables in the RETURNING list, so we copy the alias names of the OLD and
4179 : : * NEW rows from the ModifyTable plan node.
4180 : : *
4181 : : * Once this function has been called, deparse_expression() can be called on
4182 : : * subsidiary expression(s) of the specified Plan node. To deparse
4183 : : * expressions of a different Plan node in the same Plan tree, re-call this
4184 : : * function to identify the new parent Plan node.
4185 : : *
4186 : : * The result is the same List passed in; this is a notational convenience.
4187 : : */
4188 : : List *
4189 : 39803 : set_deparse_context_plan(List *dpcontext, Plan *plan, List *ancestors)
4190 : : {
4191 : : deparse_namespace *dpns;
4192 : :
4193 : : /* Should always have one-entry namespace list for Plan deparsing */
4194 : : Assert(list_length(dpcontext) == 1);
4195 : 39803 : dpns = (deparse_namespace *) linitial(dpcontext);
4196 : :
4197 : : /* Set our attention on the specific plan node passed in */
4198 : 39803 : dpns->ancestors = ancestors;
4199 : 39803 : set_deparse_plan(dpns, plan);
4200 : :
4201 : : /* For ModifyTable, set aliases for OLD and NEW in RETURNING */
4202 [ + + ]: 39803 : if (IsA(plan, ModifyTable))
4203 : : {
4204 : 141 : dpns->ret_old_alias = ((ModifyTable *) plan)->returningOldAlias;
4205 : 141 : dpns->ret_new_alias = ((ModifyTable *) plan)->returningNewAlias;
4206 : : }
4207 : :
4208 : 39803 : return dpcontext;
4209 : : }
4210 : :
4211 : : /*
4212 : : * select_rtable_names_for_explain - Select RTE aliases for EXPLAIN
4213 : : *
4214 : : * Determine the relation aliases we'll use during an EXPLAIN operation.
4215 : : * This is just a frontend to set_rtable_names. We have to expose the aliases
4216 : : * to EXPLAIN because EXPLAIN needs to know the right alias names to print.
4217 : : */
4218 : : List *
4219 : 16606 : select_rtable_names_for_explain(List *rtable, Bitmapset *rels_used)
4220 : : {
4221 : : deparse_namespace dpns;
4222 : :
4223 : 16606 : memset(&dpns, 0, sizeof(dpns));
4224 : 16606 : dpns.rtable = rtable;
4225 : 16606 : dpns.subplans = NIL;
4226 : 16606 : dpns.ctes = NIL;
4227 : 16606 : dpns.appendrels = NULL;
4228 : 16606 : set_rtable_names(&dpns, NIL, rels_used);
4229 : : /* We needn't bother computing column aliases yet */
4230 : :
4231 : 16606 : return dpns.rtable_names;
4232 : : }
4233 : :
4234 : : /*
4235 : : * set_rtable_names: select RTE aliases to be used in printing a query
4236 : : *
4237 : : * We fill in dpns->rtable_names with a list of names that is one-for-one with
4238 : : * the already-filled dpns->rtable list. Each RTE name is unique among those
4239 : : * in the new namespace plus any ancestor namespaces listed in
4240 : : * parent_namespaces.
4241 : : *
4242 : : * If rels_used isn't NULL, only RTE indexes listed in it are given aliases.
4243 : : *
4244 : : * Note that this function is only concerned with relation names, not column
4245 : : * names.
4246 : : */
4247 : : static void
4248 : 36433 : set_rtable_names(deparse_namespace *dpns, List *parent_namespaces,
4249 : : Bitmapset *rels_used)
4250 : : {
4251 : : HASHCTL hash_ctl;
4252 : : HTAB *names_hash;
4253 : : NameHashEntry *hentry;
4254 : : bool found;
4255 : : int rtindex;
4256 : : ListCell *lc;
4257 : :
4258 : 36433 : dpns->rtable_names = NIL;
4259 : : /* nothing more to do if empty rtable */
4260 [ + + ]: 36433 : if (dpns->rtable == NIL)
4261 : 340 : return;
4262 : :
4263 : : /*
4264 : : * We use a hash table to hold known names, so that this process is O(N)
4265 : : * not O(N^2) for N names.
4266 : : */
4267 : 36093 : hash_ctl.keysize = NAMEDATALEN;
4268 : 36093 : hash_ctl.entrysize = sizeof(NameHashEntry);
4269 : 36093 : hash_ctl.hcxt = CurrentMemoryContext;
4270 : 36093 : names_hash = hash_create("set_rtable_names names",
4271 : 36093 : list_length(dpns->rtable),
4272 : : &hash_ctl,
4273 : : HASH_ELEM | HASH_STRINGS | HASH_CONTEXT);
4274 : :
4275 : : /* Preload the hash table with names appearing in parent_namespaces */
4276 [ + + + + : 37228 : foreach(lc, parent_namespaces)
+ + ]
4277 : : {
4278 : 1135 : deparse_namespace *olddpns = (deparse_namespace *) lfirst(lc);
4279 : : ListCell *lc2;
4280 : :
4281 [ + + + + : 3907 : foreach(lc2, olddpns->rtable_names)
+ + ]
4282 : : {
4283 : 2772 : char *oldname = (char *) lfirst(lc2);
4284 : :
4285 [ + + ]: 2772 : if (oldname == NULL)
4286 : 201 : continue;
4287 : 2571 : hentry = (NameHashEntry *) hash_search(names_hash,
4288 : : oldname,
4289 : : HASH_ENTER,
4290 : : &found);
4291 : : /* we do not complain about duplicate names in parent namespaces */
4292 : 2571 : hentry->counter = 0;
4293 : : }
4294 : : }
4295 : :
4296 : : /* Now we can scan the rtable */
4297 : 36093 : rtindex = 1;
4298 [ + - + + : 105036 : foreach(lc, dpns->rtable)
+ + ]
4299 : : {
4300 : 68943 : RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
4301 : : char *refname;
4302 : :
4303 : : /* Just in case this takes an unreasonable amount of time ... */
4304 [ + + ]: 68943 : CHECK_FOR_INTERRUPTS();
4305 : :
4306 [ + + + + ]: 68943 : if (rels_used && !bms_is_member(rtindex, rels_used))
4307 : : {
4308 : : /* Ignore unreferenced RTE */
4309 : 12399 : refname = NULL;
4310 : : }
4311 [ + + ]: 56544 : else if (rte->alias)
4312 : : {
4313 : : /* If RTE has a user-defined alias, prefer that */
4314 : 36777 : refname = rte->alias->aliasname;
4315 : : }
4316 [ + + ]: 19767 : else if (rte->rtekind == RTE_RELATION)
4317 : : {
4318 : : /* Use the current actual name of the relation */
4319 : 15066 : refname = get_rel_name(rte->relid);
4320 : : }
4321 [ + + ]: 4701 : else if (rte->rtekind == RTE_JOIN)
4322 : : {
4323 : : /* Unnamed join has no refname */
4324 : 1149 : refname = NULL;
4325 : : }
4326 : : else
4327 : : {
4328 : : /* Otherwise use whatever the parser assigned */
4329 : 3552 : refname = rte->eref->aliasname;
4330 : : }
4331 : :
4332 : : /*
4333 : : * If the selected name isn't unique, append digits to make it so, and
4334 : : * make a new hash entry for it once we've got a unique name. For a
4335 : : * very long input name, we might have to truncate to stay within
4336 : : * NAMEDATALEN.
4337 : : */
4338 [ + + ]: 68943 : if (refname)
4339 : : {
4340 : 55395 : hentry = (NameHashEntry *) hash_search(names_hash,
4341 : : refname,
4342 : : HASH_ENTER,
4343 : : &found);
4344 [ + + ]: 55395 : if (found)
4345 : : {
4346 : : /* Name already in use, must choose a new one */
4347 : 10273 : int refnamelen = strlen(refname);
4348 : 10273 : char *modname = (char *) palloc(refnamelen + 16);
4349 : : NameHashEntry *hentry2;
4350 : :
4351 : : do
4352 : : {
4353 : 10277 : hentry->counter++;
4354 : : for (;;)
4355 : : {
4356 : 10285 : memcpy(modname, refname, refnamelen);
4357 : 10285 : sprintf(modname + refnamelen, "_%d", hentry->counter);
4358 [ + + ]: 10285 : if (strlen(modname) < NAMEDATALEN)
4359 : 10277 : break;
4360 : : /* drop chars from refname to keep all the digits */
4361 : 8 : refnamelen = pg_mbcliplen(refname, refnamelen,
4362 : : refnamelen - 1);
4363 : : }
4364 : 10277 : hentry2 = (NameHashEntry *) hash_search(names_hash,
4365 : : modname,
4366 : : HASH_ENTER,
4367 : : &found);
4368 [ + + ]: 10277 : } while (found);
4369 : 10273 : hentry2->counter = 0; /* init new hash entry */
4370 : 10273 : refname = modname;
4371 : : }
4372 : : else
4373 : : {
4374 : : /* Name not previously used, need only initialize hentry */
4375 : 45122 : hentry->counter = 0;
4376 : : }
4377 : : }
4378 : :
4379 : 68943 : dpns->rtable_names = lappend(dpns->rtable_names, refname);
4380 : 68943 : rtindex++;
4381 : : }
4382 : :
4383 : 36093 : hash_destroy(names_hash);
4384 : : }
4385 : :
4386 : : /*
4387 : : * set_deparse_for_query: set up deparse_namespace for deparsing a Query tree
4388 : : *
4389 : : * For convenience, this is defined to initialize the deparse_namespace struct
4390 : : * from scratch.
4391 : : */
4392 : : static void
4393 : 3614 : set_deparse_for_query(deparse_namespace *dpns, Query *query,
4394 : : List *parent_namespaces)
4395 : : {
4396 : : ListCell *lc;
4397 : : ListCell *lc2;
4398 : :
4399 : : /* Initialize *dpns and fill rtable/ctes links */
4400 : 3614 : memset(dpns, 0, sizeof(deparse_namespace));
4401 : 3614 : dpns->rtable = query->rtable;
4402 : 3614 : dpns->subplans = NIL;
4403 : 3614 : dpns->ctes = query->cteList;
4404 : 3614 : dpns->appendrels = NULL;
4405 : 3614 : dpns->ret_old_alias = query->returningOldAlias;
4406 : 3614 : dpns->ret_new_alias = query->returningNewAlias;
4407 : :
4408 : : /* Assign a unique relation alias to each RTE */
4409 : 3614 : set_rtable_names(dpns, parent_namespaces, NULL);
4410 : :
4411 : : /* Initialize dpns->rtable_columns to contain zeroed structs */
4412 : 3614 : dpns->rtable_columns = NIL;
4413 [ + + ]: 10049 : while (list_length(dpns->rtable_columns) < list_length(dpns->rtable))
4414 : 6435 : dpns->rtable_columns = lappend(dpns->rtable_columns,
4415 : : palloc0(sizeof(deparse_columns)));
4416 : :
4417 : : /* If it's a utility query, it won't have a jointree */
4418 [ + + ]: 3614 : if (query->jointree)
4419 : : {
4420 : : /* Detect whether global uniqueness of USING names is needed */
4421 : 3605 : dpns->unique_using =
4422 : 3605 : has_dangerous_join_using(dpns, (Node *) query->jointree);
4423 : :
4424 : : /*
4425 : : * Select names for columns merged by USING, via a recursive pass over
4426 : : * the query jointree.
4427 : : */
4428 : 3605 : set_using_names(dpns, (Node *) query->jointree, NIL);
4429 : : }
4430 : :
4431 : : /*
4432 : : * Now assign remaining column aliases for each RTE. We do this in a
4433 : : * linear scan of the rtable, so as to process RTEs whether or not they
4434 : : * are in the jointree (we mustn't miss NEW.*, INSERT target relations,
4435 : : * etc). JOIN RTEs must be processed after their children, but this is
4436 : : * okay because they appear later in the rtable list than their children
4437 : : * (cf Asserts in identify_join_columns()).
4438 : : */
4439 [ + + + + : 10049 : forboth(lc, dpns->rtable, lc2, dpns->rtable_columns)
+ + + + +
+ + - +
+ ]
4440 : : {
4441 : 6435 : RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
4442 : 6435 : deparse_columns *colinfo = (deparse_columns *) lfirst(lc2);
4443 : :
4444 [ + + ]: 6435 : if (rte->rtekind == RTE_JOIN)
4445 : 940 : set_join_column_names(dpns, rte, colinfo);
4446 : : else
4447 : 5495 : set_relation_column_names(dpns, rte, colinfo);
4448 : : }
4449 : 3614 : }
4450 : :
4451 : : /*
4452 : : * set_simple_column_names: fill in column aliases for non-query situations
4453 : : *
4454 : : * This handles EXPLAIN and cases where we only have relation RTEs. Without
4455 : : * a join tree, we can't do anything smart about join RTEs, but we don't
4456 : : * need to, because EXPLAIN should never see join alias Vars anyway.
4457 : : * If we find a join RTE we'll just skip it, leaving its deparse_columns
4458 : : * struct all-zero. If somehow we try to deparse a join alias Var, we'll
4459 : : * error out cleanly because the struct's num_cols will be zero.
4460 : : */
4461 : : static void
4462 : 32819 : set_simple_column_names(deparse_namespace *dpns)
4463 : : {
4464 : : ListCell *lc;
4465 : : ListCell *lc2;
4466 : :
4467 : : /* Initialize dpns->rtable_columns to contain zeroed structs */
4468 : 32819 : dpns->rtable_columns = NIL;
4469 [ + + ]: 95327 : while (list_length(dpns->rtable_columns) < list_length(dpns->rtable))
4470 : 62508 : dpns->rtable_columns = lappend(dpns->rtable_columns,
4471 : : palloc0(sizeof(deparse_columns)));
4472 : :
4473 : : /* Assign unique column aliases within each non-join RTE */
4474 [ + - + + : 95327 : forboth(lc, dpns->rtable, lc2, dpns->rtable_columns)
+ - + + +
+ + - +
+ ]
4475 : : {
4476 : 62508 : RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
4477 : 62508 : deparse_columns *colinfo = (deparse_columns *) lfirst(lc2);
4478 : :
4479 [ + + ]: 62508 : if (rte->rtekind != RTE_JOIN)
4480 : 58484 : set_relation_column_names(dpns, rte, colinfo);
4481 : : }
4482 : 32819 : }
4483 : :
4484 : : /*
4485 : : * has_dangerous_join_using: search jointree for unnamed JOIN USING
4486 : : *
4487 : : * Merged columns of a JOIN USING may act differently from either of the input
4488 : : * columns, either because they are merged with COALESCE (in a FULL JOIN) or
4489 : : * because an implicit coercion of the underlying input column is required.
4490 : : * In such a case the column must be referenced as a column of the JOIN not as
4491 : : * a column of either input. And this is problematic if the join is unnamed
4492 : : * (alias-less): we cannot qualify the column's name with an RTE name, since
4493 : : * there is none. (Forcibly assigning an alias to the join is not a solution,
4494 : : * since that will prevent legal references to tables below the join.)
4495 : : * To ensure that every column in the query is unambiguously referenceable,
4496 : : * we must assign such merged columns names that are globally unique across
4497 : : * the whole query, aliasing other columns out of the way as necessary.
4498 : : *
4499 : : * Because the ensuing re-aliasing is fairly damaging to the readability of
4500 : : * the query, we don't do this unless we have to. So, we must pre-scan
4501 : : * the join tree to see if we have to, before starting set_using_names().
4502 : : */
4503 : : static bool
4504 : 8571 : has_dangerous_join_using(deparse_namespace *dpns, Node *jtnode)
4505 : : {
4506 [ + + ]: 8571 : if (IsA(jtnode, RangeTblRef))
4507 : : {
4508 : : /* nothing to do here */
4509 : : }
4510 [ + + ]: 4501 : else if (IsA(jtnode, FromExpr))
4511 : : {
4512 : 3605 : FromExpr *f = (FromExpr *) jtnode;
4513 : : ListCell *lc;
4514 : :
4515 [ + + + + : 6831 : foreach(lc, f->fromlist)
+ + ]
4516 : : {
4517 [ + + ]: 3278 : if (has_dangerous_join_using(dpns, (Node *) lfirst(lc)))
4518 : 52 : return true;
4519 : : }
4520 : : }
4521 [ + - ]: 896 : else if (IsA(jtnode, JoinExpr))
4522 : : {
4523 : 896 : JoinExpr *j = (JoinExpr *) jtnode;
4524 : :
4525 : : /* Is it an unnamed JOIN with USING? */
4526 [ + + + + ]: 896 : if (j->alias == NULL && j->usingClause)
4527 : : {
4528 : : /*
4529 : : * Yes, so check each join alias var to see if any of them are not
4530 : : * simple references to underlying columns. If so, we have a
4531 : : * dangerous situation and must pick unique aliases.
4532 : : */
4533 : 188 : RangeTblEntry *jrte = rt_fetch(j->rtindex, dpns->rtable);
4534 : :
4535 : : /* We need only examine the merged columns */
4536 [ + + ]: 388 : for (int i = 0; i < jrte->joinmergedcols; i++)
4537 : : {
4538 : 252 : Node *aliasvar = list_nth(jrte->joinaliasvars, i);
4539 : :
4540 [ + + ]: 252 : if (!IsA(aliasvar, Var))
4541 : 52 : return true;
4542 : : }
4543 : : }
4544 : :
4545 : : /* Nope, but inspect children */
4546 [ - + ]: 844 : if (has_dangerous_join_using(dpns, j->larg))
4547 : 0 : return true;
4548 [ - + ]: 844 : if (has_dangerous_join_using(dpns, j->rarg))
4549 : 0 : return true;
4550 : : }
4551 : : else
4552 [ # # ]: 0 : elog(ERROR, "unrecognized node type: %d",
4553 : : (int) nodeTag(jtnode));
4554 : 8467 : return false;
4555 : : }
4556 : :
4557 : : /*
4558 : : * set_using_names: select column aliases to be used for merged USING columns
4559 : : *
4560 : : * We do this during a recursive descent of the query jointree.
4561 : : * dpns->unique_using must already be set to determine the global strategy.
4562 : : *
4563 : : * Column alias info is saved in the dpns->rtable_columns list, which is
4564 : : * assumed to be filled with pre-zeroed deparse_columns structs.
4565 : : *
4566 : : * parentUsing is a list of all USING aliases assigned in parent joins of
4567 : : * the current jointree node. (The passed-in list must not be modified.)
4568 : : *
4569 : : * Note that we do not use per-deparse_columns hash tables in this function.
4570 : : * The number of names that need to be assigned should be small enough that
4571 : : * we don't need to trouble with that.
4572 : : */
4573 : : static void
4574 : 8791 : set_using_names(deparse_namespace *dpns, Node *jtnode, List *parentUsing)
4575 : : {
4576 [ + + ]: 8791 : if (IsA(jtnode, RangeTblRef))
4577 : : {
4578 : : /* nothing to do now */
4579 : : }
4580 [ + + ]: 4545 : else if (IsA(jtnode, FromExpr))
4581 : : {
4582 : 3605 : FromExpr *f = (FromExpr *) jtnode;
4583 : : ListCell *lc;
4584 : :
4585 [ + + + + : 6911 : foreach(lc, f->fromlist)
+ + ]
4586 : 3306 : set_using_names(dpns, (Node *) lfirst(lc), parentUsing);
4587 : : }
4588 [ + - ]: 940 : else if (IsA(jtnode, JoinExpr))
4589 : : {
4590 : 940 : JoinExpr *j = (JoinExpr *) jtnode;
4591 : 940 : RangeTblEntry *rte = rt_fetch(j->rtindex, dpns->rtable);
4592 : 940 : deparse_columns *colinfo = deparse_columns_fetch(j->rtindex, dpns);
4593 : : int *leftattnos;
4594 : : int *rightattnos;
4595 : : deparse_columns *leftcolinfo;
4596 : : deparse_columns *rightcolinfo;
4597 : : int i;
4598 : : ListCell *lc;
4599 : :
4600 : : /* Get info about the shape of the join */
4601 : 940 : identify_join_columns(j, rte, colinfo);
4602 : 940 : leftattnos = colinfo->leftattnos;
4603 : 940 : rightattnos = colinfo->rightattnos;
4604 : :
4605 : : /* Look up the not-yet-filled-in child deparse_columns structs */
4606 : 940 : leftcolinfo = deparse_columns_fetch(colinfo->leftrti, dpns);
4607 : 940 : rightcolinfo = deparse_columns_fetch(colinfo->rightrti, dpns);
4608 : :
4609 : : /*
4610 : : * If this join is unnamed, then we cannot substitute new aliases at
4611 : : * this level, so any name requirements pushed down to here must be
4612 : : * pushed down again to the children.
4613 : : */
4614 [ + + ]: 940 : if (rte->alias == NULL)
4615 : : {
4616 [ + + ]: 960 : for (i = 0; i < colinfo->num_cols; i++)
4617 : : {
4618 : 92 : char *colname = colinfo->colnames[i];
4619 : :
4620 [ + + ]: 92 : if (colname == NULL)
4621 : 16 : continue;
4622 : :
4623 : : /* Push down to left column, unless it's a system column */
4624 [ + + ]: 76 : if (leftattnos[i] > 0)
4625 : : {
4626 : 68 : expand_colnames_array_to(leftcolinfo, leftattnos[i]);
4627 : 68 : leftcolinfo->colnames[leftattnos[i] - 1] = colname;
4628 : : }
4629 : :
4630 : : /* Same on the righthand side */
4631 [ + - ]: 76 : if (rightattnos[i] > 0)
4632 : : {
4633 : 76 : expand_colnames_array_to(rightcolinfo, rightattnos[i]);
4634 : 76 : rightcolinfo->colnames[rightattnos[i] - 1] = colname;
4635 : : }
4636 : : }
4637 : : }
4638 : :
4639 : : /*
4640 : : * If there's a USING clause, select the USING column names and push
4641 : : * those names down to the children. We have two strategies:
4642 : : *
4643 : : * If dpns->unique_using is true, we force all USING names to be
4644 : : * unique across the whole query level. In principle we'd only need
4645 : : * the names of dangerous USING columns to be globally unique, but to
4646 : : * safely assign all USING names in a single pass, we have to enforce
4647 : : * the same uniqueness rule for all of them. However, if a USING
4648 : : * column's name has been pushed down from the parent, we should use
4649 : : * it as-is rather than making a uniqueness adjustment. This is
4650 : : * necessary when we're at an unnamed join, and it creates no risk of
4651 : : * ambiguity. Also, if there's a user-written output alias for a
4652 : : * merged column, we prefer to use that rather than the input name;
4653 : : * this simplifies the logic and seems likely to lead to less aliasing
4654 : : * overall.
4655 : : *
4656 : : * If dpns->unique_using is false, we only need USING names to be
4657 : : * unique within their own join RTE. We still need to honor
4658 : : * pushed-down names, though.
4659 : : *
4660 : : * Though significantly different in results, these two strategies are
4661 : : * implemented by the same code, with only the difference of whether
4662 : : * to put assigned names into dpns->using_names.
4663 : : */
4664 [ + + ]: 940 : if (j->usingClause)
4665 : : {
4666 : : /* Copy the input parentUsing list so we don't modify it */
4667 : 280 : parentUsing = list_copy(parentUsing);
4668 : :
4669 : : /* USING names must correspond to the first join output columns */
4670 : 280 : expand_colnames_array_to(colinfo, list_length(j->usingClause));
4671 : 280 : i = 0;
4672 [ + - + + : 664 : foreach(lc, j->usingClause)
+ + ]
4673 : : {
4674 : 384 : char *colname = strVal(lfirst(lc));
4675 : :
4676 : : /* Assert it's a merged column */
4677 : : Assert(leftattnos[i] != 0 && rightattnos[i] != 0);
4678 : :
4679 : : /* Adopt passed-down name if any, else select unique name */
4680 [ + + ]: 384 : if (colinfo->colnames[i] != NULL)
4681 : 68 : colname = colinfo->colnames[i];
4682 : : else
4683 : : {
4684 : : /* Prefer user-written output alias if any */
4685 [ + + - + ]: 316 : if (rte->alias && i < list_length(rte->alias->colnames))
4686 : 0 : colname = strVal(list_nth(rte->alias->colnames, i));
4687 : : /* Make it appropriately unique */
4688 : 316 : colname = make_colname_unique(colname, dpns, colinfo);
4689 [ + + ]: 316 : if (dpns->unique_using)
4690 : 88 : dpns->using_names = lappend(dpns->using_names,
4691 : : colname);
4692 : : /* Save it as output column name, too */
4693 : 316 : colinfo->colnames[i] = colname;
4694 : : }
4695 : :
4696 : : /* Remember selected names for use later */
4697 : 384 : colinfo->usingNames = lappend(colinfo->usingNames, colname);
4698 : 384 : parentUsing = lappend(parentUsing, colname);
4699 : :
4700 : : /* Push down to left column, unless it's a system column */
4701 [ + - ]: 384 : if (leftattnos[i] > 0)
4702 : : {
4703 : 384 : expand_colnames_array_to(leftcolinfo, leftattnos[i]);
4704 : 384 : leftcolinfo->colnames[leftattnos[i] - 1] = colname;
4705 : : }
4706 : :
4707 : : /* Same on the righthand side */
4708 [ + - ]: 384 : if (rightattnos[i] > 0)
4709 : : {
4710 : 384 : expand_colnames_array_to(rightcolinfo, rightattnos[i]);
4711 : 384 : rightcolinfo->colnames[rightattnos[i] - 1] = colname;
4712 : : }
4713 : :
4714 : 384 : i++;
4715 : : }
4716 : : }
4717 : :
4718 : : /* Mark child deparse_columns structs with correct parentUsing info */
4719 : 940 : leftcolinfo->parentUsing = parentUsing;
4720 : 940 : rightcolinfo->parentUsing = parentUsing;
4721 : :
4722 : : /* Now recursively assign USING column names in children */
4723 : 940 : set_using_names(dpns, j->larg, parentUsing);
4724 : 940 : set_using_names(dpns, j->rarg, parentUsing);
4725 : : }
4726 : : else
4727 [ # # ]: 0 : elog(ERROR, "unrecognized node type: %d",
4728 : : (int) nodeTag(jtnode));
4729 : 8791 : }
4730 : :
4731 : : /*
4732 : : * set_relation_column_names: select column aliases for a non-join RTE
4733 : : *
4734 : : * Column alias info is saved in *colinfo, which is assumed to be pre-zeroed.
4735 : : * If any colnames entries are already filled in, those override local
4736 : : * choices.
4737 : : */
4738 : : static void
4739 : 63979 : set_relation_column_names(deparse_namespace *dpns, RangeTblEntry *rte,
4740 : : deparse_columns *colinfo)
4741 : : {
4742 : : int ncolumns;
4743 : : char **real_colnames;
4744 : : bool changed_any;
4745 : : int noldcolumns;
4746 : : int i;
4747 : : int j;
4748 : :
4749 : : /*
4750 : : * Construct an array of the current "real" column names of the RTE.
4751 : : * real_colnames[] will be indexed by physical column number, with NULL
4752 : : * entries for dropped columns.
4753 : : */
4754 [ + + ]: 63979 : if (rte->rtekind == RTE_RELATION)
4755 : : {
4756 : : /* Relation --- look to the system catalogs for up-to-date info */
4757 : : Relation rel;
4758 : : TupleDesc tupdesc;
4759 : :
4760 : 53786 : rel = relation_open(rte->relid, AccessShareLock);
4761 : 53786 : tupdesc = RelationGetDescr(rel);
4762 : :
4763 : 53786 : ncolumns = tupdesc->natts;
4764 : 53786 : real_colnames = (char **) palloc(ncolumns * sizeof(char *));
4765 : :
4766 [ + + ]: 336463 : for (i = 0; i < ncolumns; i++)
4767 : : {
4768 : 282677 : Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
4769 : :
4770 [ + + ]: 282677 : if (attr->attisdropped)
4771 : 1908 : real_colnames[i] = NULL;
4772 : : else
4773 : 280769 : real_colnames[i] = pstrdup(NameStr(attr->attname));
4774 : : }
4775 : 53786 : relation_close(rel, AccessShareLock);
4776 : : }
4777 : : else
4778 : : {
4779 : : /* Otherwise get the column names from eref or expandRTE() */
4780 : : List *colnames;
4781 : : ListCell *lc;
4782 : :
4783 : : /*
4784 : : * Functions returning composites have the annoying property that some
4785 : : * of the composite type's columns might have been dropped since the
4786 : : * query was parsed. If possible, use expandRTE() to handle that
4787 : : * case, since it has the tedious logic needed to find out about
4788 : : * dropped columns. However, if we're explaining a plan, then we
4789 : : * don't have rte->functions because the planner thinks that won't be
4790 : : * needed later, and that breaks expandRTE(). So in that case we have
4791 : : * to rely on rte->eref, which may lead us to report a dropped
4792 : : * column's old name; that seems close enough for EXPLAIN's purposes.
4793 : : *
4794 : : * For non-RELATION, non-FUNCTION RTEs, we can just look at rte->eref,
4795 : : * which should be sufficiently up-to-date: no other RTE types can
4796 : : * have columns get dropped from under them after parsing.
4797 : : */
4798 [ + + + + ]: 10193 : if (rte->rtekind == RTE_FUNCTION && rte->functions != NIL)
4799 : : {
4800 : : /* Since we're not creating Vars, rtindex etc. don't matter */
4801 : 560 : expandRTE(rte, 1, 0, VAR_RETURNING_DEFAULT, -1,
4802 : : true /* include dropped */ , &colnames, NULL);
4803 : : }
4804 : : else
4805 : 9633 : colnames = rte->eref->colnames;
4806 : :
4807 : 10193 : ncolumns = list_length(colnames);
4808 : 10193 : real_colnames = (char **) palloc(ncolumns * sizeof(char *));
4809 : :
4810 : 10193 : i = 0;
4811 [ + + + + : 32786 : foreach(lc, colnames)
+ + ]
4812 : : {
4813 : : /*
4814 : : * If the column name we find here is an empty string, then it's a
4815 : : * dropped column, so change to NULL.
4816 : : */
4817 : 22593 : char *cname = strVal(lfirst(lc));
4818 : :
4819 [ + + ]: 22593 : if (cname[0] == '\0')
4820 : 36 : cname = NULL;
4821 : 22593 : real_colnames[i] = cname;
4822 : 22593 : i++;
4823 : : }
4824 : : }
4825 : :
4826 : : /*
4827 : : * Ensure colinfo->colnames has a slot for each column. (It could be long
4828 : : * enough already, if we pushed down a name for the last column.) Note:
4829 : : * it's possible that there are now more columns than there were when the
4830 : : * query was parsed, ie colnames could be longer than rte->eref->colnames.
4831 : : * We must assign unique aliases to the new columns too, else there could
4832 : : * be unresolved conflicts when the view/rule is reloaded.
4833 : : */
4834 : 63979 : expand_colnames_array_to(colinfo, ncolumns);
4835 : : Assert(colinfo->num_cols == ncolumns);
4836 : :
4837 : : /*
4838 : : * Make sufficiently large new_colnames and is_new_col arrays, too.
4839 : : *
4840 : : * Note: because we leave colinfo->num_new_cols zero until after the loop,
4841 : : * colname_is_unique will not consult that array, which is fine because it
4842 : : * would only be duplicate effort.
4843 : : */
4844 : 63979 : colinfo->new_colnames = (char **) palloc(ncolumns * sizeof(char *));
4845 : 63979 : colinfo->is_new_col = (bool *) palloc(ncolumns * sizeof(bool));
4846 : :
4847 : : /* If the RTE is wide enough, use a hash table to avoid O(N^2) costs */
4848 : 63979 : build_colinfo_names_hash(colinfo);
4849 : :
4850 : : /*
4851 : : * Scan the columns, select a unique alias for each one, and store it in
4852 : : * colinfo->colnames and colinfo->new_colnames. The former array has NULL
4853 : : * entries for dropped columns, the latter omits them. Also mark
4854 : : * new_colnames entries as to whether they are new since parse time; this
4855 : : * is the case for entries beyond the length of rte->eref->colnames.
4856 : : */
4857 : 63979 : noldcolumns = list_length(rte->eref->colnames);
4858 : 63979 : changed_any = false;
4859 : 63979 : j = 0;
4860 [ + + ]: 369249 : for (i = 0; i < ncolumns; i++)
4861 : : {
4862 : 305270 : char *real_colname = real_colnames[i];
4863 : 305270 : char *colname = colinfo->colnames[i];
4864 : :
4865 : : /* Skip dropped columns */
4866 [ + + ]: 305270 : if (real_colname == NULL)
4867 : : {
4868 : : Assert(colname == NULL); /* colnames[i] is already NULL */
4869 : 1944 : continue;
4870 : : }
4871 : :
4872 : : /* If alias already assigned, that's what to use */
4873 [ + + ]: 303326 : if (colname == NULL)
4874 : : {
4875 : : /* If user wrote an alias, prefer that over real column name */
4876 [ + + + + ]: 302626 : if (rte->alias && i < list_length(rte->alias->colnames))
4877 : 30012 : colname = strVal(list_nth(rte->alias->colnames, i));
4878 : : else
4879 : 272614 : colname = real_colname;
4880 : :
4881 : : /* Unique-ify and insert into colinfo */
4882 : 302626 : colname = make_colname_unique(colname, dpns, colinfo);
4883 : :
4884 : 302626 : colinfo->colnames[i] = colname;
4885 : 302626 : add_to_names_hash(colinfo, colname);
4886 : : }
4887 : :
4888 : : /* Put names of non-dropped columns in new_colnames[] too */
4889 : 303326 : colinfo->new_colnames[j] = colname;
4890 : : /* And mark them as new or not */
4891 : 303326 : colinfo->is_new_col[j] = (i >= noldcolumns);
4892 : 303326 : j++;
4893 : :
4894 : : /* Remember if any assigned aliases differ from "real" name */
4895 [ + + + + ]: 303326 : if (!changed_any && strcmp(colname, real_colname) != 0)
4896 : 793 : changed_any = true;
4897 : : }
4898 : :
4899 : : /* We're now done needing the colinfo's names_hash */
4900 : 63979 : destroy_colinfo_names_hash(colinfo);
4901 : :
4902 : : /*
4903 : : * Set correct length for new_colnames[] array. (Note: if columns have
4904 : : * been added, colinfo->num_cols includes them, which is not really quite
4905 : : * right but is harmless, since any new columns must be at the end where
4906 : : * they won't affect varattnos of pre-existing columns.)
4907 : : */
4908 : 63979 : colinfo->num_new_cols = j;
4909 : :
4910 : : /*
4911 : : * For a relation RTE, we need only print the alias column names if any
4912 : : * are different from the underlying "real" names. For a function RTE,
4913 : : * always emit a complete column alias list; this is to protect against
4914 : : * possible instability of the default column names (eg, from altering
4915 : : * parameter names). For tablefunc RTEs, we never print aliases, because
4916 : : * the column names are part of the clause itself. For other RTE types,
4917 : : * print if we changed anything OR if there were user-written column
4918 : : * aliases (since the latter would be part of the underlying "reality").
4919 : : */
4920 [ + + ]: 63979 : if (rte->rtekind == RTE_RELATION)
4921 : 53786 : colinfo->printaliases = changed_any;
4922 [ + + ]: 10193 : else if (rte->rtekind == RTE_FUNCTION)
4923 : 987 : colinfo->printaliases = true;
4924 [ + + ]: 9206 : else if (rte->rtekind == RTE_TABLEFUNC)
4925 : 126 : colinfo->printaliases = false;
4926 [ + + + + ]: 9080 : else if (rte->alias && rte->alias->colnames != NIL)
4927 : 534 : colinfo->printaliases = true;
4928 : : else
4929 : 8546 : colinfo->printaliases = changed_any;
4930 : 63979 : }
4931 : :
4932 : : /*
4933 : : * set_join_column_names: select column aliases for a join RTE
4934 : : *
4935 : : * Column alias info is saved in *colinfo, which is assumed to be pre-zeroed.
4936 : : * If any colnames entries are already filled in, those override local
4937 : : * choices. Also, names for USING columns were already chosen by
4938 : : * set_using_names(). We further expect that column alias selection has been
4939 : : * completed for both input RTEs.
4940 : : */
4941 : : static void
4942 : 940 : set_join_column_names(deparse_namespace *dpns, RangeTblEntry *rte,
4943 : : deparse_columns *colinfo)
4944 : : {
4945 : : deparse_columns *leftcolinfo;
4946 : : deparse_columns *rightcolinfo;
4947 : : bool changed_any;
4948 : : int noldcolumns;
4949 : : int nnewcolumns;
4950 : 940 : Bitmapset *leftmerged = NULL;
4951 : 940 : Bitmapset *rightmerged = NULL;
4952 : : int i;
4953 : : int j;
4954 : : int ic;
4955 : : int jc;
4956 : :
4957 : : /* Look up the previously-filled-in child deparse_columns structs */
4958 : 940 : leftcolinfo = deparse_columns_fetch(colinfo->leftrti, dpns);
4959 : 940 : rightcolinfo = deparse_columns_fetch(colinfo->rightrti, dpns);
4960 : :
4961 : : /*
4962 : : * Ensure colinfo->colnames has a slot for each column. (It could be long
4963 : : * enough already, if we pushed down a name for the last column.) Note:
4964 : : * it's possible that one or both inputs now have more columns than there
4965 : : * were when the query was parsed, but we'll deal with that below. We
4966 : : * only need entries in colnames for pre-existing columns.
4967 : : */
4968 : 940 : noldcolumns = list_length(rte->eref->colnames);
4969 : 940 : expand_colnames_array_to(colinfo, noldcolumns);
4970 : : Assert(colinfo->num_cols == noldcolumns);
4971 : :
4972 : : /* If the RTE is wide enough, use a hash table to avoid O(N^2) costs */
4973 : 940 : build_colinfo_names_hash(colinfo);
4974 : :
4975 : : /*
4976 : : * Scan the join output columns, select an alias for each one, and store
4977 : : * it in colinfo->colnames. If there are USING columns, set_using_names()
4978 : : * already selected their names, so we can start the loop at the first
4979 : : * non-merged column.
4980 : : */
4981 : 940 : changed_any = false;
4982 [ + + ]: 30521 : for (i = list_length(colinfo->usingNames); i < noldcolumns; i++)
4983 : : {
4984 : 29581 : char *colname = colinfo->colnames[i];
4985 : : char *real_colname;
4986 : :
4987 : : /* Join column must refer to at least one input column */
4988 : : Assert(colinfo->leftattnos[i] != 0 || colinfo->rightattnos[i] != 0);
4989 : :
4990 : : /* Get the child column name */
4991 [ + + ]: 29581 : if (colinfo->leftattnos[i] > 0)
4992 : 20735 : real_colname = leftcolinfo->colnames[colinfo->leftattnos[i] - 1];
4993 [ + - ]: 8846 : else if (colinfo->rightattnos[i] > 0)
4994 : 8846 : real_colname = rightcolinfo->colnames[colinfo->rightattnos[i] - 1];
4995 : : else
4996 : : {
4997 : : /* We're joining system columns --- use eref name */
4998 : 0 : real_colname = strVal(list_nth(rte->eref->colnames, i));
4999 : : }
5000 : :
5001 : : /* If child col has been dropped, no need to assign a join colname */
5002 [ + + ]: 29581 : if (real_colname == NULL)
5003 : : {
5004 : 4 : colinfo->colnames[i] = NULL;
5005 : 4 : continue;
5006 : : }
5007 : :
5008 : : /* In an unnamed join, just report child column names as-is */
5009 [ + + ]: 29577 : if (rte->alias == NULL)
5010 : : {
5011 : 29325 : colinfo->colnames[i] = real_colname;
5012 : 29325 : add_to_names_hash(colinfo, real_colname);
5013 : 29325 : continue;
5014 : : }
5015 : :
5016 : : /* If alias already assigned, that's what to use */
5017 [ + - ]: 252 : if (colname == NULL)
5018 : : {
5019 : : /* If user wrote an alias, prefer that over real column name */
5020 [ + - + + ]: 252 : if (rte->alias && i < list_length(rte->alias->colnames))
5021 : 64 : colname = strVal(list_nth(rte->alias->colnames, i));
5022 : : else
5023 : 188 : colname = real_colname;
5024 : :
5025 : : /* Unique-ify and insert into colinfo */
5026 : 252 : colname = make_colname_unique(colname, dpns, colinfo);
5027 : :
5028 : 252 : colinfo->colnames[i] = colname;
5029 : 252 : add_to_names_hash(colinfo, colname);
5030 : : }
5031 : :
5032 : : /* Remember if any assigned aliases differ from "real" name */
5033 [ + + + + ]: 252 : if (!changed_any && strcmp(colname, real_colname) != 0)
5034 : 16 : changed_any = true;
5035 : : }
5036 : :
5037 : : /*
5038 : : * Calculate number of columns the join would have if it were re-parsed
5039 : : * now, and create storage for the new_colnames and is_new_col arrays.
5040 : : *
5041 : : * Note: colname_is_unique will be consulting new_colnames[] during the
5042 : : * loops below, so its not-yet-filled entries must be zeroes.
5043 : : */
5044 : 1880 : nnewcolumns = leftcolinfo->num_new_cols + rightcolinfo->num_new_cols -
5045 : 940 : list_length(colinfo->usingNames);
5046 : 940 : colinfo->num_new_cols = nnewcolumns;
5047 : 940 : colinfo->new_colnames = (char **) palloc0(nnewcolumns * sizeof(char *));
5048 : 940 : colinfo->is_new_col = (bool *) palloc0(nnewcolumns * sizeof(bool));
5049 : :
5050 : : /*
5051 : : * Generating the new_colnames array is a bit tricky since any new columns
5052 : : * added since parse time must be inserted in the right places. This code
5053 : : * must match the parser, which will order a join's columns as merged
5054 : : * columns first (in USING-clause order), then non-merged columns from the
5055 : : * left input (in attnum order), then non-merged columns from the right
5056 : : * input (ditto). If one of the inputs is itself a join, its columns will
5057 : : * be ordered according to the same rule, which means newly-added columns
5058 : : * might not be at the end. We can figure out what's what by consulting
5059 : : * the leftattnos and rightattnos arrays plus the input is_new_col arrays.
5060 : : *
5061 : : * In these loops, i indexes leftattnos/rightattnos (so it's join varattno
5062 : : * less one), j indexes new_colnames/is_new_col, and ic/jc have similar
5063 : : * meanings for the current child RTE.
5064 : : */
5065 : :
5066 : : /* Handle merged columns; they are first and can't be new */
5067 : 940 : i = j = 0;
5068 : 940 : while (i < noldcolumns &&
5069 [ + - + - ]: 1324 : colinfo->leftattnos[i] != 0 &&
5070 [ + + ]: 1324 : colinfo->rightattnos[i] != 0)
5071 : : {
5072 : : /* column name is already determined and known unique */
5073 : 384 : colinfo->new_colnames[j] = colinfo->colnames[i];
5074 : 384 : colinfo->is_new_col[j] = false;
5075 : :
5076 : : /* build bitmapsets of child attnums of merged columns */
5077 [ + - ]: 384 : if (colinfo->leftattnos[i] > 0)
5078 : 384 : leftmerged = bms_add_member(leftmerged, colinfo->leftattnos[i]);
5079 [ + - ]: 384 : if (colinfo->rightattnos[i] > 0)
5080 : 384 : rightmerged = bms_add_member(rightmerged, colinfo->rightattnos[i]);
5081 : :
5082 : 384 : i++, j++;
5083 : : }
5084 : :
5085 : : /* Handle non-merged left-child columns */
5086 : 940 : ic = 0;
5087 [ + + ]: 22383 : for (jc = 0; jc < leftcolinfo->num_new_cols; jc++)
5088 : : {
5089 : 21443 : char *child_colname = leftcolinfo->new_colnames[jc];
5090 : :
5091 [ + + ]: 21443 : if (!leftcolinfo->is_new_col[jc])
5092 : : {
5093 : : /* Advance ic to next non-dropped old column of left child */
5094 [ + - ]: 21171 : while (ic < leftcolinfo->num_cols &&
5095 [ + + ]: 21171 : leftcolinfo->colnames[ic] == NULL)
5096 : 56 : ic++;
5097 : : Assert(ic < leftcolinfo->num_cols);
5098 : 21115 : ic++;
5099 : : /* If it is a merged column, we already processed it */
5100 [ + + ]: 21115 : if (bms_is_member(ic, leftmerged))
5101 : 384 : continue;
5102 : : /* Else, advance i to the corresponding existing join column */
5103 [ + - ]: 20735 : while (i < colinfo->num_cols &&
5104 [ + + ]: 20735 : colinfo->colnames[i] == NULL)
5105 : 4 : i++;
5106 : : Assert(i < colinfo->num_cols);
5107 : : Assert(ic == colinfo->leftattnos[i]);
5108 : : /* Use the already-assigned name of this column */
5109 : 20731 : colinfo->new_colnames[j] = colinfo->colnames[i];
5110 : 20731 : i++;
5111 : : }
5112 : : else
5113 : : {
5114 : : /*
5115 : : * Unique-ify the new child column name and assign, unless we're
5116 : : * in an unnamed join, in which case just copy
5117 : : */
5118 [ + + ]: 328 : if (rte->alias != NULL)
5119 : : {
5120 : 176 : colinfo->new_colnames[j] =
5121 : 88 : make_colname_unique(child_colname, dpns, colinfo);
5122 [ + + ]: 88 : if (!changed_any &&
5123 [ + + ]: 72 : strcmp(colinfo->new_colnames[j], child_colname) != 0)
5124 : 8 : changed_any = true;
5125 : : }
5126 : : else
5127 : 240 : colinfo->new_colnames[j] = child_colname;
5128 : 328 : add_to_names_hash(colinfo, colinfo->new_colnames[j]);
5129 : : }
5130 : :
5131 : 21059 : colinfo->is_new_col[j] = leftcolinfo->is_new_col[jc];
5132 : 21059 : j++;
5133 : : }
5134 : :
5135 : : /* Handle non-merged right-child columns in exactly the same way */
5136 : 940 : ic = 0;
5137 [ + + ]: 10282 : for (jc = 0; jc < rightcolinfo->num_new_cols; jc++)
5138 : : {
5139 : 9342 : char *child_colname = rightcolinfo->new_colnames[jc];
5140 : :
5141 [ + + ]: 9342 : if (!rightcolinfo->is_new_col[jc])
5142 : : {
5143 : : /* Advance ic to next non-dropped old column of right child */
5144 [ + - ]: 9230 : while (ic < rightcolinfo->num_cols &&
5145 [ - + ]: 9230 : rightcolinfo->colnames[ic] == NULL)
5146 : 0 : ic++;
5147 : : Assert(ic < rightcolinfo->num_cols);
5148 : 9230 : ic++;
5149 : : /* If it is a merged column, we already processed it */
5150 [ + + ]: 9230 : if (bms_is_member(ic, rightmerged))
5151 : 384 : continue;
5152 : : /* Else, advance i to the corresponding existing join column */
5153 [ + - ]: 8846 : while (i < colinfo->num_cols &&
5154 [ - + ]: 8846 : colinfo->colnames[i] == NULL)
5155 : 0 : i++;
5156 : : Assert(i < colinfo->num_cols);
5157 : : Assert(ic == colinfo->rightattnos[i]);
5158 : : /* Use the already-assigned name of this column */
5159 : 8846 : colinfo->new_colnames[j] = colinfo->colnames[i];
5160 : 8846 : i++;
5161 : : }
5162 : : else
5163 : : {
5164 : : /*
5165 : : * Unique-ify the new child column name and assign, unless we're
5166 : : * in an unnamed join, in which case just copy
5167 : : */
5168 [ + + ]: 112 : if (rte->alias != NULL)
5169 : : {
5170 : 32 : colinfo->new_colnames[j] =
5171 : 16 : make_colname_unique(child_colname, dpns, colinfo);
5172 [ + - ]: 16 : if (!changed_any &&
5173 [ + + ]: 16 : strcmp(colinfo->new_colnames[j], child_colname) != 0)
5174 : 8 : changed_any = true;
5175 : : }
5176 : : else
5177 : 96 : colinfo->new_colnames[j] = child_colname;
5178 : 112 : add_to_names_hash(colinfo, colinfo->new_colnames[j]);
5179 : : }
5180 : :
5181 : 8958 : colinfo->is_new_col[j] = rightcolinfo->is_new_col[jc];
5182 : 8958 : j++;
5183 : : }
5184 : :
5185 : : /* Assert we processed the right number of columns */
5186 : : #ifdef USE_ASSERT_CHECKING
5187 : : while (i < colinfo->num_cols && colinfo->colnames[i] == NULL)
5188 : : i++;
5189 : : Assert(i == colinfo->num_cols);
5190 : : Assert(j == nnewcolumns);
5191 : : #endif
5192 : :
5193 : : /* We're now done needing the colinfo's names_hash */
5194 : 940 : destroy_colinfo_names_hash(colinfo);
5195 : :
5196 : : /*
5197 : : * For a named join, print column aliases if we changed any from the child
5198 : : * names. Unnamed joins cannot print aliases.
5199 : : */
5200 [ + + ]: 940 : if (rte->alias != NULL)
5201 : 72 : colinfo->printaliases = changed_any;
5202 : : else
5203 : 868 : colinfo->printaliases = false;
5204 : 940 : }
5205 : :
5206 : : /*
5207 : : * colname_is_unique: is colname distinct from already-chosen column names?
5208 : : *
5209 : : * dpns is query-wide info, colinfo is for the column's RTE
5210 : : */
5211 : : static bool
5212 : 304865 : colname_is_unique(const char *colname, deparse_namespace *dpns,
5213 : : deparse_columns *colinfo)
5214 : : {
5215 : : int i;
5216 : : ListCell *lc;
5217 : :
5218 : : /*
5219 : : * If we have a hash table, consult that instead of linearly scanning the
5220 : : * colinfo's strings.
5221 : : */
5222 [ + + ]: 304865 : if (colinfo->names_hash)
5223 : : {
5224 [ - + ]: 10726 : if (hash_search(colinfo->names_hash,
5225 : : colname,
5226 : : HASH_FIND,
5227 : : NULL) != NULL)
5228 : 0 : return false;
5229 : : }
5230 : : else
5231 : : {
5232 : : /* Check against already-assigned column aliases within RTE */
5233 [ + + ]: 4042560 : for (i = 0; i < colinfo->num_cols; i++)
5234 : : {
5235 : 3749940 : char *oldname = colinfo->colnames[i];
5236 : :
5237 [ + + + + ]: 3749940 : if (oldname && strcmp(oldname, colname) == 0)
5238 : 1519 : return false;
5239 : : }
5240 : :
5241 : : /*
5242 : : * If we're building a new_colnames array, check that too (this will
5243 : : * be partially but not completely redundant with the previous checks)
5244 : : */
5245 [ + + ]: 293468 : for (i = 0; i < colinfo->num_new_cols; i++)
5246 : : {
5247 : 864 : char *oldname = colinfo->new_colnames[i];
5248 : :
5249 [ + + + + ]: 864 : if (oldname && strcmp(oldname, colname) == 0)
5250 : 16 : return false;
5251 : : }
5252 : :
5253 : : /*
5254 : : * Also check against names already assigned for parent-join USING
5255 : : * cols
5256 : : */
5257 [ + + + + : 294300 : foreach(lc, colinfo->parentUsing)
+ + ]
5258 : : {
5259 : 1700 : char *oldname = (char *) lfirst(lc);
5260 : :
5261 [ + + ]: 1700 : if (strcmp(oldname, colname) == 0)
5262 : 4 : return false;
5263 : : }
5264 : : }
5265 : :
5266 : : /*
5267 : : * Also check against USING-column names that must be globally unique.
5268 : : * These are not hashed, but there should be few of them.
5269 : : */
5270 [ + + + + : 303898 : foreach(lc, dpns->using_names)
+ + ]
5271 : : {
5272 : 600 : char *oldname = (char *) lfirst(lc);
5273 : :
5274 [ + + ]: 600 : if (strcmp(oldname, colname) == 0)
5275 : 28 : return false;
5276 : : }
5277 : :
5278 : 303298 : return true;
5279 : : }
5280 : :
5281 : : /*
5282 : : * make_colname_unique: modify colname if necessary to make it unique
5283 : : *
5284 : : * dpns is query-wide info, colinfo is for the column's RTE
5285 : : */
5286 : : static char *
5287 : 303298 : make_colname_unique(char *colname, deparse_namespace *dpns,
5288 : : deparse_columns *colinfo)
5289 : : {
5290 : : /*
5291 : : * If the selected name isn't unique, append digits to make it so. For a
5292 : : * very long input name, we might have to truncate to stay within
5293 : : * NAMEDATALEN.
5294 : : */
5295 [ + + ]: 303298 : if (!colname_is_unique(colname, dpns, colinfo))
5296 : : {
5297 : 1086 : int colnamelen = strlen(colname);
5298 : 1086 : char *modname = (char *) palloc(colnamelen + 16);
5299 : 1086 : int i = 0;
5300 : :
5301 : : do
5302 : : {
5303 : 1567 : i++;
5304 : : for (;;)
5305 : : {
5306 : 1567 : memcpy(modname, colname, colnamelen);
5307 : 1567 : sprintf(modname + colnamelen, "_%d", i);
5308 [ + - ]: 1567 : if (strlen(modname) < NAMEDATALEN)
5309 : 1567 : break;
5310 : : /* drop chars from colname to keep all the digits */
5311 : 0 : colnamelen = pg_mbcliplen(colname, colnamelen,
5312 : : colnamelen - 1);
5313 : : }
5314 [ + + ]: 1567 : } while (!colname_is_unique(modname, dpns, colinfo));
5315 : 1086 : colname = modname;
5316 : : }
5317 : 303298 : return colname;
5318 : : }
5319 : :
5320 : : /*
5321 : : * expand_colnames_array_to: make colinfo->colnames at least n items long
5322 : : *
5323 : : * Any added array entries are initialized to zero.
5324 : : */
5325 : : static void
5326 : 66111 : expand_colnames_array_to(deparse_columns *colinfo, int n)
5327 : : {
5328 [ + + ]: 66111 : if (n > colinfo->num_cols)
5329 : : {
5330 [ + + ]: 64315 : if (colinfo->colnames == NULL)
5331 : 63379 : colinfo->colnames = palloc0_array(char *, n);
5332 : : else
5333 : 936 : colinfo->colnames = repalloc0_array(colinfo->colnames, char *, colinfo->num_cols, n);
5334 : 64315 : colinfo->num_cols = n;
5335 : : }
5336 : 66111 : }
5337 : :
5338 : : /*
5339 : : * build_colinfo_names_hash: optionally construct a hash table for colinfo
5340 : : */
5341 : : static void
5342 : 64919 : build_colinfo_names_hash(deparse_columns *colinfo)
5343 : : {
5344 : : HASHCTL hash_ctl;
5345 : : int i;
5346 : : ListCell *lc;
5347 : :
5348 : : /*
5349 : : * Use a hash table only for RTEs with at least 32 columns. (The cutoff
5350 : : * is somewhat arbitrary, but let's choose it so that this code does get
5351 : : * exercised in the regression tests.)
5352 : : */
5353 [ + + ]: 64919 : if (colinfo->num_cols < 32)
5354 : 64103 : return;
5355 : :
5356 : : /*
5357 : : * Set up the hash table. The entries are just strings with no other
5358 : : * payload.
5359 : : */
5360 : 816 : hash_ctl.keysize = NAMEDATALEN;
5361 : 816 : hash_ctl.entrysize = NAMEDATALEN;
5362 : 816 : hash_ctl.hcxt = CurrentMemoryContext;
5363 : 1632 : colinfo->names_hash = hash_create("deparse_columns names",
5364 : 816 : colinfo->num_cols + colinfo->num_new_cols,
5365 : : &hash_ctl,
5366 : : HASH_ELEM | HASH_STRINGS | HASH_CONTEXT);
5367 : :
5368 : : /*
5369 : : * Preload the hash table with any names already present (these would have
5370 : : * come from set_using_names).
5371 : : */
5372 [ + + ]: 38184 : for (i = 0; i < colinfo->num_cols; i++)
5373 : : {
5374 : 37368 : char *oldname = colinfo->colnames[i];
5375 : :
5376 [ - + ]: 37368 : if (oldname)
5377 : 0 : add_to_names_hash(colinfo, oldname);
5378 : : }
5379 : :
5380 [ - + ]: 816 : for (i = 0; i < colinfo->num_new_cols; i++)
5381 : : {
5382 : 0 : char *oldname = colinfo->new_colnames[i];
5383 : :
5384 [ # # ]: 0 : if (oldname)
5385 : 0 : add_to_names_hash(colinfo, oldname);
5386 : : }
5387 : :
5388 [ - + - - : 816 : foreach(lc, colinfo->parentUsing)
- + ]
5389 : : {
5390 : 0 : char *oldname = (char *) lfirst(lc);
5391 : :
5392 : 0 : add_to_names_hash(colinfo, oldname);
5393 : : }
5394 : : }
5395 : :
5396 : : /*
5397 : : * add_to_names_hash: add a string to the names_hash, if we're using one
5398 : : */
5399 : : static void
5400 : 332643 : add_to_names_hash(deparse_columns *colinfo, const char *name)
5401 : : {
5402 [ + + ]: 332643 : if (colinfo->names_hash)
5403 : 37368 : (void) hash_search(colinfo->names_hash,
5404 : : name,
5405 : : HASH_ENTER,
5406 : : NULL);
5407 : 332643 : }
5408 : :
5409 : : /*
5410 : : * destroy_colinfo_names_hash: destroy hash table when done with it
5411 : : */
5412 : : static void
5413 : 64919 : destroy_colinfo_names_hash(deparse_columns *colinfo)
5414 : : {
5415 [ + + ]: 64919 : if (colinfo->names_hash)
5416 : : {
5417 : 816 : hash_destroy(colinfo->names_hash);
5418 : 816 : colinfo->names_hash = NULL;
5419 : : }
5420 : 64919 : }
5421 : :
5422 : : /*
5423 : : * identify_join_columns: figure out where columns of a join come from
5424 : : *
5425 : : * Fills the join-specific fields of the colinfo struct, except for
5426 : : * usingNames which is filled later.
5427 : : */
5428 : : static void
5429 : 940 : identify_join_columns(JoinExpr *j, RangeTblEntry *jrte,
5430 : : deparse_columns *colinfo)
5431 : : {
5432 : : int numjoincols;
5433 : : int jcolno;
5434 : : int rcolno;
5435 : : ListCell *lc;
5436 : :
5437 : : /* Extract left/right child RT indexes */
5438 [ + + ]: 940 : if (IsA(j->larg, RangeTblRef))
5439 : 605 : colinfo->leftrti = ((RangeTblRef *) j->larg)->rtindex;
5440 [ + - ]: 335 : else if (IsA(j->larg, JoinExpr))
5441 : 335 : colinfo->leftrti = ((JoinExpr *) j->larg)->rtindex;
5442 : : else
5443 [ # # ]: 0 : elog(ERROR, "unrecognized node type in jointree: %d",
5444 : : (int) nodeTag(j->larg));
5445 [ + - ]: 940 : if (IsA(j->rarg, RangeTblRef))
5446 : 940 : colinfo->rightrti = ((RangeTblRef *) j->rarg)->rtindex;
5447 [ # # ]: 0 : else if (IsA(j->rarg, JoinExpr))
5448 : 0 : colinfo->rightrti = ((JoinExpr *) j->rarg)->rtindex;
5449 : : else
5450 [ # # ]: 0 : elog(ERROR, "unrecognized node type in jointree: %d",
5451 : : (int) nodeTag(j->rarg));
5452 : :
5453 : : /* Assert children will be processed earlier than join in second pass */
5454 : : Assert(colinfo->leftrti < j->rtindex);
5455 : : Assert(colinfo->rightrti < j->rtindex);
5456 : :
5457 : : /* Initialize result arrays with zeroes */
5458 : 940 : numjoincols = list_length(jrte->joinaliasvars);
5459 : : Assert(numjoincols == list_length(jrte->eref->colnames));
5460 : 940 : colinfo->leftattnos = (int *) palloc0(numjoincols * sizeof(int));
5461 : 940 : colinfo->rightattnos = (int *) palloc0(numjoincols * sizeof(int));
5462 : :
5463 : : /*
5464 : : * Deconstruct RTE's joinleftcols/joinrightcols into desired format.
5465 : : * Recall that the column(s) merged due to USING are the first column(s)
5466 : : * of the join output. We need not do anything special while scanning
5467 : : * joinleftcols, but while scanning joinrightcols we must distinguish
5468 : : * merged from unmerged columns.
5469 : : */
5470 : 940 : jcolno = 0;
5471 [ + - + + : 22059 : foreach(lc, jrte->joinleftcols)
+ + ]
5472 : : {
5473 : 21119 : int leftattno = lfirst_int(lc);
5474 : :
5475 : 21119 : colinfo->leftattnos[jcolno++] = leftattno;
5476 : : }
5477 : 940 : rcolno = 0;
5478 [ + - + + : 10170 : foreach(lc, jrte->joinrightcols)
+ + ]
5479 : : {
5480 : 9230 : int rightattno = lfirst_int(lc);
5481 : :
5482 [ + + ]: 9230 : if (rcolno < jrte->joinmergedcols) /* merged column? */
5483 : 384 : colinfo->rightattnos[rcolno] = rightattno;
5484 : : else
5485 : 8846 : colinfo->rightattnos[jcolno++] = rightattno;
5486 : 9230 : rcolno++;
5487 : : }
5488 : : Assert(jcolno == numjoincols);
5489 : 940 : }
5490 : :
5491 : : /*
5492 : : * get_rtable_name: convenience function to get a previously assigned RTE alias
5493 : : *
5494 : : * The RTE must belong to the topmost namespace level in "context".
5495 : : */
5496 : : static char *
5497 : 4141 : get_rtable_name(int rtindex, deparse_context *context)
5498 : : {
5499 : 4141 : deparse_namespace *dpns = (deparse_namespace *) linitial(context->namespaces);
5500 : :
5501 : : Assert(rtindex > 0 && rtindex <= list_length(dpns->rtable_names));
5502 : 4141 : return (char *) list_nth(dpns->rtable_names, rtindex - 1);
5503 : : }
5504 : :
5505 : : /*
5506 : : * set_deparse_plan: set up deparse_namespace to parse subexpressions
5507 : : * of a given Plan node
5508 : : *
5509 : : * This sets the plan, outer_plan, inner_plan, outer_tlist, inner_tlist,
5510 : : * and index_tlist fields. Caller must already have adjusted the ancestors
5511 : : * list if necessary. Note that the rtable, subplans, and ctes fields do
5512 : : * not need to change when shifting attention to different plan nodes in a
5513 : : * single plan tree.
5514 : : */
5515 : : static void
5516 : 102046 : set_deparse_plan(deparse_namespace *dpns, Plan *plan)
5517 : : {
5518 : 102046 : dpns->plan = plan;
5519 : :
5520 : : /*
5521 : : * We special-case Append and MergeAppend to pretend that the first child
5522 : : * plan is the OUTER referent; we have to interpret OUTER Vars in their
5523 : : * tlists according to one of the children, and the first one is the most
5524 : : * natural choice.
5525 : : */
5526 [ + + ]: 102046 : if (IsA(plan, Append))
5527 : 2972 : dpns->outer_plan = linitial(((Append *) plan)->appendplans);
5528 [ + + ]: 99074 : else if (IsA(plan, MergeAppend))
5529 : 360 : dpns->outer_plan = linitial(((MergeAppend *) plan)->mergeplans);
5530 : : else
5531 : 98714 : dpns->outer_plan = outerPlan(plan);
5532 : :
5533 [ + + ]: 102046 : if (dpns->outer_plan)
5534 : 49313 : dpns->outer_tlist = dpns->outer_plan->targetlist;
5535 : : else
5536 : 52733 : dpns->outer_tlist = NIL;
5537 : :
5538 : : /*
5539 : : * For a SubqueryScan, pretend the subplan is INNER referent. (We don't
5540 : : * use OUTER because that could someday conflict with the normal meaning.)
5541 : : * Likewise, for a CteScan, pretend the subquery's plan is INNER referent.
5542 : : * For a WorkTableScan, locate the parent RecursiveUnion plan node and use
5543 : : * that as INNER referent.
5544 : : *
5545 : : * For MERGE, pretend the ModifyTable's source plan (its outer plan) is
5546 : : * INNER referent. This is the join from the target relation to the data
5547 : : * source, and all INNER_VAR Vars in other parts of the query refer to its
5548 : : * targetlist.
5549 : : *
5550 : : * For ON CONFLICT DO SELECT/UPDATE we just need the inner tlist to point
5551 : : * to the excluded expression's tlist. (Similar to the SubqueryScan we
5552 : : * don't want to reuse OUTER, it's used for RETURNING in some modify table
5553 : : * cases, although not INSERT .. CONFLICT).
5554 : : */
5555 [ + + ]: 102046 : if (IsA(plan, SubqueryScan))
5556 : 577 : dpns->inner_plan = ((SubqueryScan *) plan)->subplan;
5557 [ + + ]: 101469 : else if (IsA(plan, CteScan))
5558 : 405 : dpns->inner_plan = list_nth(dpns->subplans,
5559 : 405 : ((CteScan *) plan)->ctePlanId - 1);
5560 [ + + ]: 101064 : else if (IsA(plan, WorkTableScan))
5561 : 116 : dpns->inner_plan = find_recursive_union(dpns,
5562 : : (WorkTableScan *) plan);
5563 [ + + ]: 100948 : else if (IsA(plan, ModifyTable))
5564 : : {
5565 [ + + ]: 289 : if (((ModifyTable *) plan)->operation == CMD_MERGE)
5566 : 40 : dpns->inner_plan = outerPlan(plan);
5567 : : else
5568 : 249 : dpns->inner_plan = plan;
5569 : : }
5570 : : else
5571 : 100659 : dpns->inner_plan = innerPlan(plan);
5572 : :
5573 [ + + + + ]: 102046 : if (IsA(plan, ModifyTable) && ((ModifyTable *) plan)->operation == CMD_INSERT)
5574 : 141 : dpns->inner_tlist = ((ModifyTable *) plan)->exclRelTlist;
5575 [ + + ]: 101905 : else if (dpns->inner_plan)
5576 : 17687 : dpns->inner_tlist = dpns->inner_plan->targetlist;
5577 : : else
5578 : 84218 : dpns->inner_tlist = NIL;
5579 : :
5580 : : /* Set up referent for INDEX_VAR Vars, if needed */
5581 [ + + ]: 102046 : if (IsA(plan, IndexOnlyScan))
5582 : 2296 : dpns->index_tlist = ((IndexOnlyScan *) plan)->indextlist;
5583 [ + + ]: 99750 : else if (IsA(plan, ForeignScan))
5584 : 1566 : dpns->index_tlist = ((ForeignScan *) plan)->fdw_scan_tlist;
5585 [ - + ]: 98184 : else if (IsA(plan, CustomScan))
5586 : 0 : dpns->index_tlist = ((CustomScan *) plan)->custom_scan_tlist;
5587 : : else
5588 : 98184 : dpns->index_tlist = NIL;
5589 : 102046 : }
5590 : :
5591 : : /*
5592 : : * Locate the ancestor plan node that is the RecursiveUnion generating
5593 : : * the WorkTableScan's work table. We can match on wtParam, since that
5594 : : * should be unique within the plan tree.
5595 : : */
5596 : : static Plan *
5597 : 116 : find_recursive_union(deparse_namespace *dpns, WorkTableScan *wtscan)
5598 : : {
5599 : : ListCell *lc;
5600 : :
5601 [ + - + - : 292 : foreach(lc, dpns->ancestors)
+ - ]
5602 : : {
5603 : 292 : Plan *ancestor = (Plan *) lfirst(lc);
5604 : :
5605 [ + + ]: 292 : if (IsA(ancestor, RecursiveUnion) &&
5606 [ + - ]: 116 : ((RecursiveUnion *) ancestor)->wtParam == wtscan->wtParam)
5607 : 116 : return ancestor;
5608 : : }
5609 [ # # ]: 0 : elog(ERROR, "could not find RecursiveUnion for WorkTableScan with wtParam %d",
5610 : : wtscan->wtParam);
5611 : : return NULL;
5612 : : }
5613 : :
5614 : : /*
5615 : : * push_child_plan: temporarily transfer deparsing attention to a child plan
5616 : : *
5617 : : * When expanding an OUTER_VAR or INNER_VAR reference, we must adjust the
5618 : : * deparse context in case the referenced expression itself uses
5619 : : * OUTER_VAR/INNER_VAR. We modify the top stack entry in-place to avoid
5620 : : * affecting levelsup issues (although in a Plan tree there really shouldn't
5621 : : * be any).
5622 : : *
5623 : : * Caller must provide a local deparse_namespace variable to save the
5624 : : * previous state for pop_child_plan.
5625 : : */
5626 : : static void
5627 : 59142 : push_child_plan(deparse_namespace *dpns, Plan *plan,
5628 : : deparse_namespace *save_dpns)
5629 : : {
5630 : : /* Save state for restoration later */
5631 : 59142 : *save_dpns = *dpns;
5632 : :
5633 : : /* Link current plan node into ancestors list */
5634 : 59142 : dpns->ancestors = lcons(dpns->plan, dpns->ancestors);
5635 : :
5636 : : /* Set attention on selected child */
5637 : 59142 : set_deparse_plan(dpns, plan);
5638 : 59142 : }
5639 : :
5640 : : /*
5641 : : * pop_child_plan: undo the effects of push_child_plan
5642 : : */
5643 : : static void
5644 : 59142 : pop_child_plan(deparse_namespace *dpns, deparse_namespace *save_dpns)
5645 : : {
5646 : : List *ancestors;
5647 : :
5648 : : /* Get rid of ancestors list cell added by push_child_plan */
5649 : 59142 : ancestors = list_delete_first(dpns->ancestors);
5650 : :
5651 : : /* Restore fields changed by push_child_plan */
5652 : 59142 : *dpns = *save_dpns;
5653 : :
5654 : : /* Make sure dpns->ancestors is right (may be unnecessary) */
5655 : 59142 : dpns->ancestors = ancestors;
5656 : 59142 : }
5657 : :
5658 : : /*
5659 : : * push_ancestor_plan: temporarily transfer deparsing attention to an
5660 : : * ancestor plan
5661 : : *
5662 : : * When expanding a Param reference, we must adjust the deparse context
5663 : : * to match the plan node that contains the expression being printed;
5664 : : * otherwise we'd fail if that expression itself contains a Param or
5665 : : * OUTER_VAR/INNER_VAR/INDEX_VAR variable.
5666 : : *
5667 : : * The target ancestor is conveniently identified by the ListCell holding it
5668 : : * in dpns->ancestors.
5669 : : *
5670 : : * Caller must provide a local deparse_namespace variable to save the
5671 : : * previous state for pop_ancestor_plan.
5672 : : */
5673 : : static void
5674 : 3101 : push_ancestor_plan(deparse_namespace *dpns, ListCell *ancestor_cell,
5675 : : deparse_namespace *save_dpns)
5676 : : {
5677 : 3101 : Plan *plan = (Plan *) lfirst(ancestor_cell);
5678 : :
5679 : : /* Save state for restoration later */
5680 : 3101 : *save_dpns = *dpns;
5681 : :
5682 : : /* Build a new ancestor list with just this node's ancestors */
5683 : 3101 : dpns->ancestors =
5684 : 3101 : list_copy_tail(dpns->ancestors,
5685 : 3101 : list_cell_number(dpns->ancestors, ancestor_cell) + 1);
5686 : :
5687 : : /* Set attention on selected ancestor */
5688 : 3101 : set_deparse_plan(dpns, plan);
5689 : 3101 : }
5690 : :
5691 : : /*
5692 : : * pop_ancestor_plan: undo the effects of push_ancestor_plan
5693 : : */
5694 : : static void
5695 : 3101 : pop_ancestor_plan(deparse_namespace *dpns, deparse_namespace *save_dpns)
5696 : : {
5697 : : /* Free the ancestor list made in push_ancestor_plan */
5698 : 3101 : list_free(dpns->ancestors);
5699 : :
5700 : : /* Restore fields changed by push_ancestor_plan */
5701 : 3101 : *dpns = *save_dpns;
5702 : 3101 : }
5703 : :
5704 : :
5705 : : /* ----------
5706 : : * make_ruledef - reconstruct the CREATE RULE command
5707 : : * for a given pg_rewrite tuple
5708 : : * ----------
5709 : : */
5710 : : static void
5711 : 309 : make_ruledef(StringInfo buf, HeapTuple ruletup, TupleDesc rulettc,
5712 : : int prettyFlags)
5713 : : {
5714 : : char *rulename;
5715 : : char ev_type;
5716 : : Oid ev_class;
5717 : : bool is_instead;
5718 : : char *ev_qual;
5719 : : char *ev_action;
5720 : : List *actions;
5721 : : Relation ev_relation;
5722 : 309 : TupleDesc viewResultDesc = NULL;
5723 : : int fno;
5724 : : Datum dat;
5725 : : bool isnull;
5726 : :
5727 : : /*
5728 : : * Get the attribute values from the rules tuple
5729 : : */
5730 : 309 : fno = SPI_fnumber(rulettc, "rulename");
5731 : 309 : dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
5732 : : Assert(!isnull);
5733 : 309 : rulename = NameStr(*(DatumGetName(dat)));
5734 : :
5735 : 309 : fno = SPI_fnumber(rulettc, "ev_type");
5736 : 309 : dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
5737 : : Assert(!isnull);
5738 : 309 : ev_type = DatumGetChar(dat);
5739 : :
5740 : 309 : fno = SPI_fnumber(rulettc, "ev_class");
5741 : 309 : dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
5742 : : Assert(!isnull);
5743 : 309 : ev_class = DatumGetObjectId(dat);
5744 : :
5745 : 309 : fno = SPI_fnumber(rulettc, "is_instead");
5746 : 309 : dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
5747 : : Assert(!isnull);
5748 : 309 : is_instead = DatumGetBool(dat);
5749 : :
5750 : 309 : fno = SPI_fnumber(rulettc, "ev_qual");
5751 : 309 : ev_qual = SPI_getvalue(ruletup, rulettc, fno);
5752 : : Assert(ev_qual != NULL);
5753 : :
5754 : 309 : fno = SPI_fnumber(rulettc, "ev_action");
5755 : 309 : ev_action = SPI_getvalue(ruletup, rulettc, fno);
5756 : : Assert(ev_action != NULL);
5757 : 309 : actions = (List *) stringToNode(ev_action);
5758 [ - + ]: 309 : if (actions == NIL)
5759 [ # # ]: 0 : elog(ERROR, "invalid empty ev_action list");
5760 : :
5761 : 309 : ev_relation = table_open(ev_class, AccessShareLock);
5762 : :
5763 : : /*
5764 : : * Build the rules definition text
5765 : : */
5766 : 309 : appendStringInfo(buf, "CREATE RULE %s AS",
5767 : : quote_identifier(rulename));
5768 : :
5769 [ + - ]: 309 : if (prettyFlags & PRETTYFLAG_INDENT)
5770 : 309 : appendStringInfoString(buf, "\n ON ");
5771 : : else
5772 : 0 : appendStringInfoString(buf, " ON ");
5773 : :
5774 : : /* The event the rule is fired for */
5775 [ + + + + : 309 : switch (ev_type)
- ]
5776 : : {
5777 : 4 : case '1':
5778 : 4 : appendStringInfoString(buf, "SELECT");
5779 : 4 : viewResultDesc = RelationGetDescr(ev_relation);
5780 : 4 : break;
5781 : :
5782 : 84 : case '2':
5783 : 84 : appendStringInfoString(buf, "UPDATE");
5784 : 84 : break;
5785 : :
5786 : 165 : case '3':
5787 : 165 : appendStringInfoString(buf, "INSERT");
5788 : 165 : break;
5789 : :
5790 : 56 : case '4':
5791 : 56 : appendStringInfoString(buf, "DELETE");
5792 : 56 : break;
5793 : :
5794 : 0 : default:
5795 [ # # ]: 0 : ereport(ERROR,
5796 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5797 : : errmsg("rule \"%s\" has unsupported event type %d",
5798 : : rulename, ev_type)));
5799 : : break;
5800 : : }
5801 : :
5802 : : /* The relation the rule is fired on */
5803 : 309 : appendStringInfo(buf, " TO %s",
5804 [ + + ]: 309 : (prettyFlags & PRETTYFLAG_SCHEMA) ?
5805 : 76 : generate_relation_name(ev_class, NIL) :
5806 : 233 : generate_qualified_relation_name(ev_class));
5807 : :
5808 : : /* If the rule has an event qualification, add it */
5809 [ + + ]: 309 : if (strcmp(ev_qual, "<>") != 0)
5810 : : {
5811 : : Node *qual;
5812 : : Query *query;
5813 : : deparse_context context;
5814 : : deparse_namespace dpns;
5815 : :
5816 [ + - ]: 62 : if (prettyFlags & PRETTYFLAG_INDENT)
5817 : 62 : appendStringInfoString(buf, "\n ");
5818 : 62 : appendStringInfoString(buf, " WHERE ");
5819 : :
5820 : 62 : qual = stringToNode(ev_qual);
5821 : :
5822 : : /*
5823 : : * We need to make a context for recognizing any Vars in the qual
5824 : : * (which can only be references to OLD and NEW). Use the rtable of
5825 : : * the first query in the action list for this purpose.
5826 : : */
5827 : 62 : query = (Query *) linitial(actions);
5828 : :
5829 : : /*
5830 : : * If the action is INSERT...SELECT, OLD/NEW have been pushed down
5831 : : * into the SELECT, and that's what we need to look at. (Ugly kluge
5832 : : * ... try to fix this when we redesign querytrees.)
5833 : : */
5834 : 62 : query = getInsertSelectQuery(query, NULL);
5835 : :
5836 : : /* Must acquire locks right away; see notes in get_query_def() */
5837 : 62 : AcquireRewriteLocks(query, false, false);
5838 : :
5839 : 62 : context.buf = buf;
5840 : 62 : context.namespaces = list_make1(&dpns);
5841 : 62 : context.resultDesc = NULL;
5842 : 62 : context.targetList = NIL;
5843 : 62 : context.windowClause = NIL;
5844 : 62 : context.varprefix = (list_length(query->rtable) != 1);
5845 : 62 : context.prettyFlags = prettyFlags;
5846 : 62 : context.wrapColumn = WRAP_COLUMN_DEFAULT;
5847 : 62 : context.indentLevel = PRETTYINDENT_STD;
5848 : 62 : context.colNamesVisible = true;
5849 : 62 : context.inGroupBy = false;
5850 : 62 : context.varInOrderBy = false;
5851 : 62 : context.appendparents = NULL;
5852 : :
5853 : 62 : set_deparse_for_query(&dpns, query, NIL);
5854 : :
5855 : 62 : get_rule_expr(qual, &context, false);
5856 : : }
5857 : :
5858 : 309 : appendStringInfoString(buf, " DO ");
5859 : :
5860 : : /* The INSTEAD keyword (if so) */
5861 [ + + ]: 309 : if (is_instead)
5862 : 183 : appendStringInfoString(buf, "INSTEAD ");
5863 : :
5864 : : /* Finally the rules actions */
5865 [ + + ]: 309 : if (list_length(actions) > 1)
5866 : : {
5867 : : ListCell *action;
5868 : : Query *query;
5869 : :
5870 : 10 : appendStringInfoChar(buf, '(');
5871 [ + - + + : 30 : foreach(action, actions)
+ + ]
5872 : : {
5873 : 20 : query = (Query *) lfirst(action);
5874 : 20 : get_query_def(query, buf, NIL, viewResultDesc, true,
5875 : : prettyFlags, WRAP_COLUMN_DEFAULT, 0);
5876 [ + - ]: 20 : if (prettyFlags)
5877 : 20 : appendStringInfoString(buf, ";\n");
5878 : : else
5879 : 0 : appendStringInfoString(buf, "; ");
5880 : : }
5881 : 10 : appendStringInfoString(buf, ");");
5882 : : }
5883 : : else
5884 : : {
5885 : : Query *query;
5886 : :
5887 : 299 : query = (Query *) linitial(actions);
5888 : 299 : get_query_def(query, buf, NIL, viewResultDesc, true,
5889 : : prettyFlags, WRAP_COLUMN_DEFAULT, 0);
5890 : 299 : appendStringInfoChar(buf, ';');
5891 : : }
5892 : :
5893 : 309 : table_close(ev_relation, AccessShareLock);
5894 : 309 : }
5895 : :
5896 : :
5897 : : /* ----------
5898 : : * make_viewdef - reconstruct the SELECT part of a
5899 : : * view rewrite rule
5900 : : * ----------
5901 : : */
5902 : : static void
5903 : 2161 : make_viewdef(StringInfo buf, HeapTuple ruletup, TupleDesc rulettc,
5904 : : int prettyFlags, int wrapColumn)
5905 : : {
5906 : : Query *query;
5907 : : char ev_type;
5908 : : Oid ev_class;
5909 : : bool is_instead;
5910 : : char *ev_qual;
5911 : : char *ev_action;
5912 : : List *actions;
5913 : : Relation ev_relation;
5914 : : int fno;
5915 : : Datum dat;
5916 : : bool isnull;
5917 : :
5918 : : /*
5919 : : * Get the attribute values from the rules tuple
5920 : : */
5921 : 2161 : fno = SPI_fnumber(rulettc, "ev_type");
5922 : 2161 : dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
5923 : : Assert(!isnull);
5924 : 2161 : ev_type = DatumGetChar(dat);
5925 : :
5926 : 2161 : fno = SPI_fnumber(rulettc, "ev_class");
5927 : 2161 : dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
5928 : : Assert(!isnull);
5929 : 2161 : ev_class = DatumGetObjectId(dat);
5930 : :
5931 : 2161 : fno = SPI_fnumber(rulettc, "is_instead");
5932 : 2161 : dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
5933 : : Assert(!isnull);
5934 : 2161 : is_instead = DatumGetBool(dat);
5935 : :
5936 : 2161 : fno = SPI_fnumber(rulettc, "ev_qual");
5937 : 2161 : ev_qual = SPI_getvalue(ruletup, rulettc, fno);
5938 : : Assert(ev_qual != NULL);
5939 : :
5940 : 2161 : fno = SPI_fnumber(rulettc, "ev_action");
5941 : 2161 : ev_action = SPI_getvalue(ruletup, rulettc, fno);
5942 : : Assert(ev_action != NULL);
5943 : 2161 : actions = (List *) stringToNode(ev_action);
5944 : :
5945 [ - + ]: 2161 : if (list_length(actions) != 1)
5946 : : {
5947 : : /* keep output buffer empty and leave */
5948 : 0 : return;
5949 : : }
5950 : :
5951 : 2161 : query = (Query *) linitial(actions);
5952 : :
5953 [ + - + - ]: 2161 : if (ev_type != '1' || !is_instead ||
5954 [ + - - + ]: 2161 : strcmp(ev_qual, "<>") != 0 || query->commandType != CMD_SELECT)
5955 : : {
5956 : : /* keep output buffer empty and leave */
5957 : 0 : return;
5958 : : }
5959 : :
5960 : 2161 : ev_relation = table_open(ev_class, AccessShareLock);
5961 : :
5962 : 2161 : get_query_def(query, buf, NIL, RelationGetDescr(ev_relation), true,
5963 : : prettyFlags, wrapColumn, 0);
5964 : 2161 : appendStringInfoChar(buf, ';');
5965 : :
5966 : 2161 : table_close(ev_relation, AccessShareLock);
5967 : : }
5968 : :
5969 : :
5970 : : /* ----------
5971 : : * get_query_def - Parse back one query parsetree
5972 : : *
5973 : : * query: parsetree to be displayed
5974 : : * buf: output text is appended to buf
5975 : : * parentnamespace: list (initially empty) of outer-level deparse_namespace's
5976 : : * resultDesc: if not NULL, the output tuple descriptor for the view
5977 : : * represented by a SELECT query. We use the column names from it
5978 : : * to label SELECT output columns, in preference to names in the query
5979 : : * colNamesVisible: true if the surrounding context cares about the output
5980 : : * column names at all (as, for example, an EXISTS() context does not);
5981 : : * when false, we can suppress dummy column labels such as "?column?"
5982 : : * prettyFlags: bitmask of PRETTYFLAG_XXX options
5983 : : * wrapColumn: maximum line length, or -1 to disable wrapping
5984 : : * startIndent: initial indentation amount
5985 : : * ----------
5986 : : */
5987 : : static void
5988 : 3528 : get_query_def(Query *query, StringInfo buf, List *parentnamespace,
5989 : : TupleDesc resultDesc, bool colNamesVisible,
5990 : : int prettyFlags, int wrapColumn, int startIndent)
5991 : : {
5992 : : deparse_context context;
5993 : : deparse_namespace dpns;
5994 : : int rtable_size;
5995 : :
5996 : : /* Guard against excessively long or deeply-nested queries */
5997 [ - + ]: 3528 : CHECK_FOR_INTERRUPTS();
5998 : 3528 : check_stack_depth();
5999 : :
6000 : 7056 : rtable_size = query->hasGroupRTE ?
6001 [ + + ]: 3528 : list_length(query->rtable) - 1 :
6002 : 3409 : list_length(query->rtable);
6003 : :
6004 : : /*
6005 : : * Replace any Vars in the query's targetlist and havingQual that
6006 : : * reference GROUP outputs with the underlying grouping expressions.
6007 : : *
6008 : : * We can safely pass NULL for the root here. Preserving varnullingrels
6009 : : * makes no difference to the deparsed source text.
6010 : : */
6011 [ + + ]: 3528 : if (query->hasGroupRTE)
6012 : : {
6013 : 119 : query->targetList = (List *)
6014 : 119 : flatten_group_exprs(NULL, query, (Node *) query->targetList);
6015 : 119 : query->havingQual =
6016 : 119 : flatten_group_exprs(NULL, query, query->havingQual);
6017 : : }
6018 : :
6019 : : /*
6020 : : * Before we begin to examine the query, acquire locks on referenced
6021 : : * relations, and fix up deleted columns in JOIN RTEs. This ensures
6022 : : * consistent results. Note we assume it's OK to scribble on the passed
6023 : : * querytree!
6024 : : *
6025 : : * We are only deparsing the query (we are not about to execute it), so we
6026 : : * only need AccessShareLock on the relations it mentions.
6027 : : */
6028 : 3528 : AcquireRewriteLocks(query, false, false);
6029 : :
6030 : 3528 : context.buf = buf;
6031 : 3528 : context.namespaces = lcons(&dpns, list_copy(parentnamespace));
6032 : 3528 : context.resultDesc = NULL;
6033 : 3528 : context.targetList = NIL;
6034 : 3528 : context.windowClause = NIL;
6035 [ + + + + ]: 3528 : context.varprefix = (parentnamespace != NIL ||
6036 : 3528 : rtable_size != 1);
6037 : 3528 : context.prettyFlags = prettyFlags;
6038 : 3528 : context.wrapColumn = wrapColumn;
6039 : 3528 : context.indentLevel = startIndent;
6040 : 3528 : context.colNamesVisible = colNamesVisible;
6041 : 3528 : context.inGroupBy = false;
6042 : 3528 : context.varInOrderBy = false;
6043 : 3528 : context.appendparents = NULL;
6044 : :
6045 : 3528 : set_deparse_for_query(&dpns, query, parentnamespace);
6046 : :
6047 [ + + + + : 3528 : switch (query->commandType)
+ + + - ]
6048 : : {
6049 : 3154 : case CMD_SELECT:
6050 : : /* We set context.resultDesc only if it's a SELECT */
6051 : 3154 : context.resultDesc = resultDesc;
6052 : 3154 : get_select_query_def(query, &context);
6053 : 3154 : break;
6054 : :
6055 : 94 : case CMD_UPDATE:
6056 : 94 : get_update_query_def(query, &context);
6057 : 94 : break;
6058 : :
6059 : 194 : case CMD_INSERT:
6060 : 194 : get_insert_query_def(query, &context);
6061 : 194 : break;
6062 : :
6063 : 47 : case CMD_DELETE:
6064 : 47 : get_delete_query_def(query, &context);
6065 : 47 : break;
6066 : :
6067 : 8 : case CMD_MERGE:
6068 : 8 : get_merge_query_def(query, &context);
6069 : 8 : break;
6070 : :
6071 : 22 : case CMD_NOTHING:
6072 : 22 : appendStringInfoString(buf, "NOTHING");
6073 : 22 : break;
6074 : :
6075 : 9 : case CMD_UTILITY:
6076 : 9 : get_utility_query_def(query, &context);
6077 : 9 : break;
6078 : :
6079 : 0 : default:
6080 [ # # ]: 0 : elog(ERROR, "unrecognized query command type: %d",
6081 : : query->commandType);
6082 : : break;
6083 : : }
6084 : 3528 : }
6085 : :
6086 : : /* ----------
6087 : : * get_values_def - Parse back a VALUES list
6088 : : * ----------
6089 : : */
6090 : : static void
6091 : 193 : get_values_def(List *values_lists, deparse_context *context)
6092 : : {
6093 : 193 : StringInfo buf = context->buf;
6094 : 193 : bool first_list = true;
6095 : : ListCell *vtl;
6096 : :
6097 : 193 : appendStringInfoString(buf, "VALUES ");
6098 : :
6099 [ + - + + : 581 : foreach(vtl, values_lists)
+ + ]
6100 : : {
6101 : 388 : List *sublist = (List *) lfirst(vtl);
6102 : 388 : bool first_col = true;
6103 : : ListCell *lc;
6104 : :
6105 [ + + ]: 388 : if (first_list)
6106 : 193 : first_list = false;
6107 : : else
6108 : 195 : appendStringInfoString(buf, ", ");
6109 : :
6110 : 388 : appendStringInfoChar(buf, '(');
6111 [ + - + + : 1380 : foreach(lc, sublist)
+ + ]
6112 : : {
6113 : 992 : Node *col = (Node *) lfirst(lc);
6114 : :
6115 [ + + ]: 992 : if (first_col)
6116 : 388 : first_col = false;
6117 : : else
6118 : 604 : appendStringInfoChar(buf, ',');
6119 : :
6120 : : /*
6121 : : * Print the value. Whole-row Vars need special treatment.
6122 : : */
6123 : 992 : get_rule_expr_toplevel(col, context, false);
6124 : : }
6125 : 388 : appendStringInfoChar(buf, ')');
6126 : : }
6127 : 193 : }
6128 : :
6129 : : /* ----------
6130 : : * get_with_clause - Parse back a WITH clause
6131 : : * ----------
6132 : : */
6133 : : static void
6134 : 3497 : get_with_clause(Query *query, deparse_context *context)
6135 : : {
6136 : 3497 : StringInfo buf = context->buf;
6137 : : const char *sep;
6138 : : ListCell *l;
6139 : :
6140 [ + + ]: 3497 : if (query->cteList == NIL)
6141 : 3434 : return;
6142 : :
6143 [ + - ]: 63 : if (PRETTY_INDENT(context))
6144 : : {
6145 : 63 : context->indentLevel += PRETTYINDENT_STD;
6146 : 63 : appendStringInfoChar(buf, ' ');
6147 : : }
6148 : :
6149 [ + + ]: 63 : if (query->hasRecursive)
6150 : 34 : sep = "WITH RECURSIVE ";
6151 : : else
6152 : 29 : sep = "WITH ";
6153 [ + - + + : 156 : foreach(l, query->cteList)
+ + ]
6154 : : {
6155 : 93 : CommonTableExpr *cte = (CommonTableExpr *) lfirst(l);
6156 : :
6157 : 93 : appendStringInfoString(buf, sep);
6158 : 93 : appendStringInfoString(buf, quote_identifier(cte->ctename));
6159 [ + + ]: 93 : if (cte->aliascolnames)
6160 : : {
6161 : 38 : bool first = true;
6162 : : ListCell *col;
6163 : :
6164 : 38 : appendStringInfoChar(buf, '(');
6165 [ + - + + : 100 : foreach(col, cte->aliascolnames)
+ + ]
6166 : : {
6167 [ + + ]: 62 : if (first)
6168 : 38 : first = false;
6169 : : else
6170 : 24 : appendStringInfoString(buf, ", ");
6171 : 62 : appendStringInfoString(buf,
6172 : 62 : quote_identifier(strVal(lfirst(col))));
6173 : : }
6174 : 38 : appendStringInfoChar(buf, ')');
6175 : : }
6176 : 93 : appendStringInfoString(buf, " AS ");
6177 [ + + - - ]: 93 : switch (cte->ctematerialized)
6178 : : {
6179 : 81 : case CTEMaterializeDefault:
6180 : 81 : break;
6181 : 12 : case CTEMaterializeAlways:
6182 : 12 : appendStringInfoString(buf, "MATERIALIZED ");
6183 : 12 : break;
6184 : 0 : case CTEMaterializeNever:
6185 : 0 : appendStringInfoString(buf, "NOT MATERIALIZED ");
6186 : 0 : break;
6187 : : }
6188 : 93 : appendStringInfoChar(buf, '(');
6189 [ + - ]: 93 : if (PRETTY_INDENT(context))
6190 : 93 : appendContextKeyword(context, "", 0, 0, 0);
6191 : 93 : get_query_def((Query *) cte->ctequery, buf, context->namespaces, NULL,
6192 : : true,
6193 : : context->prettyFlags, context->wrapColumn,
6194 : : context->indentLevel);
6195 [ + - ]: 93 : if (PRETTY_INDENT(context))
6196 : 93 : appendContextKeyword(context, "", 0, 0, 0);
6197 : 93 : appendStringInfoChar(buf, ')');
6198 : :
6199 [ + + ]: 93 : if (cte->search_clause)
6200 : : {
6201 : 4 : bool first = true;
6202 : : ListCell *lc;
6203 : :
6204 : 4 : appendStringInfo(buf, " SEARCH %s FIRST BY ",
6205 [ - + ]: 4 : cte->search_clause->search_breadth_first ? "BREADTH" : "DEPTH");
6206 : :
6207 [ + - + + : 12 : foreach(lc, cte->search_clause->search_col_list)
+ + ]
6208 : : {
6209 [ + + ]: 8 : if (first)
6210 : 4 : first = false;
6211 : : else
6212 : 4 : appendStringInfoString(buf, ", ");
6213 : 8 : appendStringInfoString(buf,
6214 : 8 : quote_identifier(strVal(lfirst(lc))));
6215 : : }
6216 : :
6217 : 4 : appendStringInfo(buf, " SET %s", quote_identifier(cte->search_clause->search_seq_column));
6218 : : }
6219 : :
6220 [ + + ]: 93 : if (cte->cycle_clause)
6221 : : {
6222 : 8 : bool first = true;
6223 : : ListCell *lc;
6224 : :
6225 : 8 : appendStringInfoString(buf, " CYCLE ");
6226 : :
6227 [ + - + + : 24 : foreach(lc, cte->cycle_clause->cycle_col_list)
+ + ]
6228 : : {
6229 [ + + ]: 16 : if (first)
6230 : 8 : first = false;
6231 : : else
6232 : 8 : appendStringInfoString(buf, ", ");
6233 : 16 : appendStringInfoString(buf,
6234 : 16 : quote_identifier(strVal(lfirst(lc))));
6235 : : }
6236 : :
6237 : 8 : appendStringInfo(buf, " SET %s", quote_identifier(cte->cycle_clause->cycle_mark_column));
6238 : :
6239 : : {
6240 : 8 : Const *cmv = castNode(Const, cte->cycle_clause->cycle_mark_value);
6241 : 8 : Const *cmd = castNode(Const, cte->cycle_clause->cycle_mark_default);
6242 : :
6243 [ + + + - : 12 : if (!(cmv->consttype == BOOLOID && !cmv->constisnull && DatumGetBool(cmv->constvalue) == true &&
+ - - + ]
6244 [ + - + - ]: 4 : cmd->consttype == BOOLOID && !cmd->constisnull && DatumGetBool(cmd->constvalue) == false))
6245 : : {
6246 : 4 : appendStringInfoString(buf, " TO ");
6247 : 4 : get_rule_expr(cte->cycle_clause->cycle_mark_value, context, false);
6248 : 4 : appendStringInfoString(buf, " DEFAULT ");
6249 : 4 : get_rule_expr(cte->cycle_clause->cycle_mark_default, context, false);
6250 : : }
6251 : : }
6252 : :
6253 : 8 : appendStringInfo(buf, " USING %s", quote_identifier(cte->cycle_clause->cycle_path_column));
6254 : : }
6255 : :
6256 : 93 : sep = ", ";
6257 : : }
6258 : :
6259 [ + - ]: 63 : if (PRETTY_INDENT(context))
6260 : : {
6261 : 63 : context->indentLevel -= PRETTYINDENT_STD;
6262 : 63 : appendContextKeyword(context, "", 0, 0, 0);
6263 : : }
6264 : : else
6265 : 0 : appendStringInfoChar(buf, ' ');
6266 : : }
6267 : :
6268 : : /* ----------
6269 : : * get_select_query_def - Parse back a SELECT parsetree
6270 : : * ----------
6271 : : */
6272 : : static void
6273 : 3154 : get_select_query_def(Query *query, deparse_context *context)
6274 : : {
6275 : 3154 : StringInfo buf = context->buf;
6276 : : bool force_colno;
6277 : : ListCell *l;
6278 : :
6279 : : /* Insert the WITH clause if given */
6280 : 3154 : get_with_clause(query, context);
6281 : :
6282 : : /* Subroutines may need to consult the SELECT targetlist and windowClause */
6283 : 3154 : context->targetList = query->targetList;
6284 : 3154 : context->windowClause = query->windowClause;
6285 : :
6286 : : /*
6287 : : * If the Query node has a setOperations tree, then it's the top level of
6288 : : * a UNION/INTERSECT/EXCEPT query; only the WITH, ORDER BY and LIMIT
6289 : : * fields are interesting in the top query itself.
6290 : : */
6291 [ + + ]: 3154 : if (query->setOperations)
6292 : : {
6293 : 103 : get_setop_query(query->setOperations, query, context);
6294 : : /* ORDER BY clauses must be simple in this case */
6295 : 103 : force_colno = true;
6296 : : }
6297 : : else
6298 : : {
6299 : 3051 : get_basic_select_query(query, context);
6300 : 3051 : force_colno = false;
6301 : : }
6302 : :
6303 : : /* Add the ORDER BY clause if given */
6304 [ + + ]: 3154 : if (query->sortClause != NIL)
6305 : : {
6306 : 128 : appendContextKeyword(context, " ORDER BY ",
6307 : : -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
6308 : 128 : get_rule_orderby(query->sortClause, query->targetList,
6309 : : force_colno, context);
6310 : : }
6311 : :
6312 : : /*
6313 : : * Add the LIMIT/OFFSET clauses if given. If non-default options, use the
6314 : : * standard spelling of LIMIT.
6315 : : */
6316 [ + + ]: 3154 : if (query->limitOffset != NULL)
6317 : : {
6318 : 18 : appendContextKeyword(context, " OFFSET ",
6319 : : -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
6320 : 18 : get_rule_expr(query->limitOffset, context, false);
6321 : : }
6322 [ + + ]: 3154 : if (query->limitCount != NULL)
6323 : : {
6324 [ + + ]: 53 : if (query->limitOption == LIMIT_OPTION_WITH_TIES)
6325 : : {
6326 : : /*
6327 : : * The limitCount arg is a c_expr, so it needs parens. Simple
6328 : : * literals and function expressions would not need parens, but
6329 : : * unfortunately it's hard to tell if the expression will be
6330 : : * printed as a simple literal like 123 or as a typecast
6331 : : * expression, like '-123'::int4. The grammar accepts the former
6332 : : * without quoting, but not the latter.
6333 : : */
6334 : 27 : appendContextKeyword(context, " FETCH FIRST ",
6335 : : -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
6336 : 27 : appendStringInfoChar(buf, '(');
6337 : 27 : get_rule_expr(query->limitCount, context, false);
6338 : 27 : appendStringInfoChar(buf, ')');
6339 : 27 : appendStringInfoString(buf, " ROWS WITH TIES");
6340 : : }
6341 : : else
6342 : : {
6343 : 26 : appendContextKeyword(context, " LIMIT ",
6344 : : -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
6345 [ + + ]: 26 : if (IsA(query->limitCount, Const) &&
6346 [ + - ]: 9 : ((Const *) query->limitCount)->constisnull)
6347 : 9 : appendStringInfoString(buf, "ALL");
6348 : : else
6349 : 17 : get_rule_expr(query->limitCount, context, false);
6350 : : }
6351 : : }
6352 : :
6353 : : /* Add FOR [KEY] UPDATE/SHARE clauses if present */
6354 [ + + ]: 3154 : if (query->hasForUpdate)
6355 : : {
6356 [ + - + + : 8 : foreach(l, query->rowMarks)
+ + ]
6357 : : {
6358 : 4 : RowMarkClause *rc = (RowMarkClause *) lfirst(l);
6359 : :
6360 : : /* don't print implicit clauses */
6361 [ - + ]: 4 : if (rc->pushedDown)
6362 : 0 : continue;
6363 : :
6364 : 4 : appendContextKeyword(context,
6365 : 4 : get_lock_clause_strength(rc->strength),
6366 : : -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
6367 : :
6368 : 4 : appendStringInfo(buf, " OF %s",
6369 : 4 : quote_identifier(get_rtable_name(rc->rti,
6370 : : context)));
6371 [ - + ]: 4 : if (rc->waitPolicy == LockWaitError)
6372 : 0 : appendStringInfoString(buf, " NOWAIT");
6373 [ - + ]: 4 : else if (rc->waitPolicy == LockWaitSkip)
6374 : 0 : appendStringInfoString(buf, " SKIP LOCKED");
6375 : : }
6376 : : }
6377 : 3154 : }
6378 : :
6379 : : static char *
6380 : 8 : get_lock_clause_strength(LockClauseStrength strength)
6381 : : {
6382 [ - - - - : 8 : switch (strength)
+ - ]
6383 : : {
6384 : 0 : case LCS_NONE:
6385 : : /* we intentionally throw an error for LCS_NONE */
6386 [ # # ]: 0 : elog(ERROR, "unrecognized LockClauseStrength %d",
6387 : : (int) strength);
6388 : : break;
6389 : 0 : case LCS_FORKEYSHARE:
6390 : 0 : return " FOR KEY SHARE";
6391 : 0 : case LCS_FORSHARE:
6392 : 0 : return " FOR SHARE";
6393 : 0 : case LCS_FORNOKEYUPDATE:
6394 : 0 : return " FOR NO KEY UPDATE";
6395 : 8 : case LCS_FORUPDATE:
6396 : 8 : return " FOR UPDATE";
6397 : : }
6398 : 0 : return NULL; /* keep compiler quiet */
6399 : : }
6400 : :
6401 : : /*
6402 : : * Detect whether query looks like SELECT ... FROM VALUES(),
6403 : : * with no need to rename the output columns of the VALUES RTE.
6404 : : * If so, return the VALUES RTE. Otherwise return NULL.
6405 : : */
6406 : : static RangeTblEntry *
6407 : 3051 : get_simple_values_rte(Query *query, TupleDesc resultDesc)
6408 : : {
6409 : 3051 : RangeTblEntry *result = NULL;
6410 : : ListCell *lc;
6411 : :
6412 : : /*
6413 : : * We want to detect a match even if the Query also contains OLD or NEW
6414 : : * rule RTEs. So the idea is to scan the rtable and see if there is only
6415 : : * one inFromCl RTE that is a VALUES RTE.
6416 : : */
6417 [ + + + + : 3302 : foreach(lc, query->rtable)
+ + ]
6418 : : {
6419 : 2784 : RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
6420 : :
6421 [ + + + - ]: 2784 : if (rte->rtekind == RTE_VALUES && rte->inFromCl)
6422 : : {
6423 [ - + ]: 167 : if (result)
6424 : 2533 : return NULL; /* multiple VALUES (probably not possible) */
6425 : 167 : result = rte;
6426 : : }
6427 [ + + + + ]: 2617 : else if (rte->rtekind == RTE_RELATION && !rte->inFromCl)
6428 : 84 : continue; /* ignore rule entries */
6429 : : else
6430 : 2533 : return NULL; /* something else -> not simple VALUES */
6431 : : }
6432 : :
6433 : : /*
6434 : : * We don't need to check the targetlist in any great detail, because
6435 : : * parser/analyze.c will never generate a "bare" VALUES RTE --- they only
6436 : : * appear inside auto-generated sub-queries with very restricted
6437 : : * structure. However, DefineView might have modified the tlist by
6438 : : * injecting new column aliases, or we might have some other column
6439 : : * aliases forced by a resultDesc. We can only simplify if the RTE's
6440 : : * column names match the names that get_target_list() would select.
6441 : : */
6442 [ + + ]: 518 : if (result)
6443 : : {
6444 : : ListCell *lcn;
6445 : : int colno;
6446 : :
6447 [ - + ]: 167 : if (list_length(query->targetList) != list_length(result->eref->colnames))
6448 : 0 : return NULL; /* this probably cannot happen */
6449 : 167 : colno = 0;
6450 [ + - + + : 588 : forboth(lc, query->targetList, lcn, result->eref->colnames)
+ - + + +
+ + - +
+ ]
6451 : : {
6452 : 429 : TargetEntry *tle = (TargetEntry *) lfirst(lc);
6453 : 429 : char *cname = strVal(lfirst(lcn));
6454 : : char *colname;
6455 : :
6456 [ - + ]: 429 : if (tle->resjunk)
6457 : 8 : return NULL; /* this probably cannot happen */
6458 : :
6459 : : /* compute name that get_target_list would use for column */
6460 : 429 : colno++;
6461 [ + + + - ]: 429 : if (resultDesc && colno <= resultDesc->natts)
6462 : 20 : colname = NameStr(TupleDescAttr(resultDesc, colno - 1)->attname);
6463 : : else
6464 : 409 : colname = tle->resname;
6465 : :
6466 : : /* does it match the VALUES RTE? */
6467 [ + - + + ]: 429 : if (colname == NULL || strcmp(colname, cname) != 0)
6468 : 8 : return NULL; /* column name has been changed */
6469 : : }
6470 : : }
6471 : :
6472 : 510 : return result;
6473 : : }
6474 : :
6475 : : static void
6476 : 3051 : get_basic_select_query(Query *query, deparse_context *context)
6477 : : {
6478 : 3051 : StringInfo buf = context->buf;
6479 : : RangeTblEntry *values_rte;
6480 : : char *sep;
6481 : : ListCell *l;
6482 : :
6483 [ + + ]: 3051 : if (PRETTY_INDENT(context))
6484 : : {
6485 : 3024 : context->indentLevel += PRETTYINDENT_STD;
6486 : 3024 : appendStringInfoChar(buf, ' ');
6487 : : }
6488 : :
6489 : : /*
6490 : : * If the query looks like SELECT * FROM (VALUES ...), then print just the
6491 : : * VALUES part. This reverses what transformValuesClause() did at parse
6492 : : * time.
6493 : : */
6494 : 3051 : values_rte = get_simple_values_rte(query, context->resultDesc);
6495 [ + + ]: 3051 : if (values_rte)
6496 : : {
6497 : 159 : get_values_def(values_rte->values_lists, context);
6498 : 159 : return;
6499 : : }
6500 : :
6501 : : /*
6502 : : * Build up the query string - first we say SELECT
6503 : : */
6504 [ + + ]: 2892 : if (query->isReturn)
6505 : 31 : appendStringInfoString(buf, "RETURN");
6506 : : else
6507 : 2861 : appendStringInfoString(buf, "SELECT");
6508 : :
6509 : : /* Add the DISTINCT clause if given */
6510 [ - + ]: 2892 : if (query->distinctClause != NIL)
6511 : : {
6512 [ # # ]: 0 : if (query->hasDistinctOn)
6513 : : {
6514 : 0 : appendStringInfoString(buf, " DISTINCT ON (");
6515 : 0 : sep = "";
6516 [ # # # # : 0 : foreach(l, query->distinctClause)
# # ]
6517 : : {
6518 : 0 : SortGroupClause *srt = (SortGroupClause *) lfirst(l);
6519 : :
6520 : 0 : appendStringInfoString(buf, sep);
6521 : 0 : get_rule_sortgroupclause(srt->tleSortGroupRef, query->targetList,
6522 : : false, context);
6523 : 0 : sep = ", ";
6524 : : }
6525 : 0 : appendStringInfoChar(buf, ')');
6526 : : }
6527 : : else
6528 : 0 : appendStringInfoString(buf, " DISTINCT");
6529 : : }
6530 : :
6531 : : /* Then we tell what to select (the targetlist) */
6532 : 2892 : get_target_list(query->targetList, context);
6533 : :
6534 : : /* Add the FROM clause if needed */
6535 : 2892 : get_from_clause(query, " FROM ", context);
6536 : :
6537 : : /* Add the WHERE clause if given */
6538 [ + + ]: 2892 : if (query->jointree->quals != NULL)
6539 : : {
6540 : 903 : appendContextKeyword(context, " WHERE ",
6541 : : -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
6542 : 903 : get_rule_expr(query->jointree->quals, context, false);
6543 : : }
6544 : :
6545 : : /* Add the GROUP BY clause if given */
6546 [ + + - + ]: 2892 : if (query->groupClause != NULL || query->groupingSets != NULL)
6547 : : {
6548 : : bool save_ingroupby;
6549 : :
6550 : 119 : appendContextKeyword(context, " GROUP BY ",
6551 : : -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
6552 [ - + ]: 119 : if (query->groupDistinct)
6553 : 0 : appendStringInfoString(buf, "DISTINCT ");
6554 : :
6555 : 119 : save_ingroupby = context->inGroupBy;
6556 : 119 : context->inGroupBy = true;
6557 : :
6558 [ + + ]: 119 : if (query->groupingSets == NIL)
6559 : : {
6560 : 115 : sep = "";
6561 [ + - + + : 263 : foreach(l, query->groupClause)
+ + ]
6562 : : {
6563 : 148 : SortGroupClause *grp = (SortGroupClause *) lfirst(l);
6564 : :
6565 : 148 : appendStringInfoString(buf, sep);
6566 : 148 : get_rule_sortgroupclause(grp->tleSortGroupRef, query->targetList,
6567 : : false, context);
6568 : 148 : sep = ", ";
6569 : : }
6570 : : }
6571 : : else
6572 : : {
6573 : 4 : sep = "";
6574 [ + - + + : 8 : foreach(l, query->groupingSets)
+ + ]
6575 : : {
6576 : 4 : GroupingSet *grp = lfirst(l);
6577 : :
6578 : 4 : appendStringInfoString(buf, sep);
6579 : 4 : get_rule_groupingset(grp, query->targetList, true, context);
6580 : 4 : sep = ", ";
6581 : : }
6582 : : }
6583 : :
6584 : 119 : context->inGroupBy = save_ingroupby;
6585 : : }
6586 : :
6587 : : /* Add the HAVING clause if given */
6588 [ + + ]: 2892 : if (query->havingQual != NULL)
6589 : : {
6590 : 5 : appendContextKeyword(context, " HAVING ",
6591 : : -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
6592 : 5 : get_rule_expr(query->havingQual, context, false);
6593 : : }
6594 : :
6595 : : /* Add the WINDOW clause if needed */
6596 [ + + ]: 2892 : if (query->windowClause != NIL)
6597 : 32 : get_rule_windowclause(query, context);
6598 : : }
6599 : :
6600 : : /* ----------
6601 : : * get_target_list - Parse back a SELECT target list
6602 : : *
6603 : : * This is also used for RETURNING lists in INSERT/UPDATE/DELETE/MERGE.
6604 : : * ----------
6605 : : */
6606 : : static void
6607 : 3001 : get_target_list(List *targetList, deparse_context *context)
6608 : : {
6609 : 3001 : StringInfo buf = context->buf;
6610 : : StringInfoData targetbuf;
6611 : 3001 : bool last_was_multiline = false;
6612 : : char *sep;
6613 : : int colno;
6614 : : ListCell *l;
6615 : :
6616 : : /* we use targetbuf to hold each TLE's text temporarily */
6617 : 3001 : initStringInfo(&targetbuf);
6618 : :
6619 : 3001 : sep = " ";
6620 : 3001 : colno = 0;
6621 [ + - + + : 15829 : foreach(l, targetList)
+ + ]
6622 : : {
6623 : 12828 : TargetEntry *tle = (TargetEntry *) lfirst(l);
6624 : : char *colname;
6625 : : char *attname;
6626 : :
6627 [ + + ]: 12828 : if (tle->resjunk)
6628 : 25 : continue; /* ignore junk entries */
6629 : :
6630 : 12803 : appendStringInfoString(buf, sep);
6631 : 12803 : sep = ", ";
6632 : 12803 : colno++;
6633 : :
6634 : : /*
6635 : : * Put the new field text into targetbuf so we can decide after we've
6636 : : * got it whether or not it needs to go on a new line.
6637 : : */
6638 : 12803 : resetStringInfo(&targetbuf);
6639 : 12803 : context->buf = &targetbuf;
6640 : :
6641 : : /*
6642 : : * We special-case Var nodes rather than using get_rule_expr. This is
6643 : : * needed because get_rule_expr will display a whole-row Var as
6644 : : * "foo.*", which is the preferred notation in most contexts, but at
6645 : : * the top level of a SELECT list it's not right (the parser will
6646 : : * expand that notation into multiple columns, yielding behavior
6647 : : * different from a whole-row Var). We need to call get_variable
6648 : : * directly so that we can tell it to do the right thing, and so that
6649 : : * we can get the attribute name which is the default AS label.
6650 : : */
6651 [ + - + + ]: 12803 : if (tle->expr && (IsA(tle->expr, Var)))
6652 : : {
6653 : 9868 : attname = get_variable((Var *) tle->expr, 0, true, context);
6654 : : }
6655 : : else
6656 : : {
6657 : 2935 : get_rule_expr((Node *) tle->expr, context, true);
6658 : :
6659 : : /*
6660 : : * When colNamesVisible is true, we should always show the
6661 : : * assigned column name explicitly. Otherwise, show it only if
6662 : : * it's not FigureColname's fallback.
6663 : : */
6664 [ + + ]: 2935 : attname = context->colNamesVisible ? NULL : "?column?";
6665 : : }
6666 : :
6667 : : /*
6668 : : * Figure out what the result column should be called. In the context
6669 : : * of a view, use the view's tuple descriptor (so as to pick up the
6670 : : * effects of any column RENAME that's been done on the view).
6671 : : * Otherwise, just use what we can find in the TLE.
6672 : : */
6673 [ + + + - ]: 12803 : if (context->resultDesc && colno <= context->resultDesc->natts)
6674 : 11636 : colname = NameStr(TupleDescAttr(context->resultDesc,
6675 : : colno - 1)->attname);
6676 : : else
6677 : 1167 : colname = tle->resname;
6678 : :
6679 : : /* Show AS unless the column's name is correct as-is */
6680 [ + + ]: 12803 : if (colname) /* resname could be NULL */
6681 : : {
6682 [ + + + + ]: 12772 : if (attname == NULL || strcmp(attname, colname) != 0)
6683 : 4158 : appendStringInfo(&targetbuf, " AS %s", quote_identifier(colname));
6684 : : }
6685 : :
6686 : : /* Restore context's output buffer */
6687 : 12803 : context->buf = buf;
6688 : :
6689 : : /* Consider line-wrapping if enabled */
6690 [ + + + - ]: 12803 : if (PRETTY_INDENT(context) && context->wrapColumn >= 0)
6691 : : {
6692 : : int leading_nl_pos;
6693 : :
6694 : : /* Does the new field start with a new line? */
6695 [ + - + + ]: 12776 : if (targetbuf.len > 0 && targetbuf.data[0] == '\n')
6696 : 375 : leading_nl_pos = 0;
6697 : : else
6698 : 12401 : leading_nl_pos = -1;
6699 : :
6700 : : /* If so, we shouldn't add anything */
6701 [ + + ]: 12776 : if (leading_nl_pos >= 0)
6702 : : {
6703 : : /* instead, remove any trailing spaces currently in buf */
6704 : 375 : removeStringInfoSpaces(buf);
6705 : : }
6706 : : else
6707 : : {
6708 : : char *trailing_nl;
6709 : :
6710 : : /* Locate the start of the current line in the output buffer */
6711 : 12401 : trailing_nl = strrchr(buf->data, '\n');
6712 [ + + ]: 12401 : if (trailing_nl == NULL)
6713 : 3686 : trailing_nl = buf->data;
6714 : : else
6715 : 8715 : trailing_nl++;
6716 : :
6717 : : /*
6718 : : * Add a newline, plus some indentation, if the new field is
6719 : : * not the first and either the new field would cause an
6720 : : * overflow or the last field used more than one line.
6721 : : */
6722 [ + + ]: 12401 : if (colno > 1 &&
6723 [ - + - - ]: 9436 : ((strlen(trailing_nl) + targetbuf.len > context->wrapColumn) ||
6724 : : last_was_multiline))
6725 : 9436 : appendContextKeyword(context, "", -PRETTYINDENT_STD,
6726 : : PRETTYINDENT_STD, PRETTYINDENT_VAR);
6727 : : }
6728 : :
6729 : : /* Remember this field's multiline status for next iteration */
6730 : 12776 : last_was_multiline =
6731 : 12776 : (strchr(targetbuf.data + leading_nl_pos + 1, '\n') != NULL);
6732 : : }
6733 : :
6734 : : /* Add the new field */
6735 : 12803 : appendBinaryStringInfo(buf, targetbuf.data, targetbuf.len);
6736 : : }
6737 : :
6738 : : /* clean up */
6739 : 3001 : pfree(targetbuf.data);
6740 : 3001 : }
6741 : :
6742 : : static void
6743 : 109 : get_returning_clause(Query *query, deparse_context *context)
6744 : : {
6745 : 109 : StringInfo buf = context->buf;
6746 : :
6747 [ + - ]: 109 : if (query->returningList)
6748 : : {
6749 : 109 : bool have_with = false;
6750 : :
6751 : 109 : appendContextKeyword(context, " RETURNING",
6752 : : -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
6753 : :
6754 : : /* Add WITH (OLD/NEW) options, if they're not the defaults */
6755 [ + + + + ]: 109 : if (query->returningOldAlias && strcmp(query->returningOldAlias, "old") != 0)
6756 : : {
6757 : 12 : appendStringInfo(buf, " WITH (OLD AS %s",
6758 : 12 : quote_identifier(query->returningOldAlias));
6759 : 12 : have_with = true;
6760 : : }
6761 [ + + + + ]: 109 : if (query->returningNewAlias && strcmp(query->returningNewAlias, "new") != 0)
6762 : : {
6763 [ + + ]: 12 : if (have_with)
6764 : 8 : appendStringInfo(buf, ", NEW AS %s",
6765 : 8 : quote_identifier(query->returningNewAlias));
6766 : : else
6767 : : {
6768 : 4 : appendStringInfo(buf, " WITH (NEW AS %s",
6769 : 4 : quote_identifier(query->returningNewAlias));
6770 : 4 : have_with = true;
6771 : : }
6772 : : }
6773 [ + + ]: 109 : if (have_with)
6774 : 16 : appendStringInfoChar(buf, ')');
6775 : :
6776 : : /* Add the returning expressions themselves */
6777 : 109 : get_target_list(query->returningList, context);
6778 : : }
6779 : 109 : }
6780 : :
6781 : : static void
6782 : 463 : get_setop_query(Node *setOp, Query *query, deparse_context *context)
6783 : : {
6784 : 463 : StringInfo buf = context->buf;
6785 : : bool need_paren;
6786 : :
6787 : : /* Guard against excessively long or deeply-nested queries */
6788 [ - + ]: 463 : CHECK_FOR_INTERRUPTS();
6789 : 463 : check_stack_depth();
6790 : :
6791 [ + + ]: 463 : if (IsA(setOp, RangeTblRef))
6792 : : {
6793 : 283 : RangeTblRef *rtr = (RangeTblRef *) setOp;
6794 : 283 : RangeTblEntry *rte = rt_fetch(rtr->rtindex, query->rtable);
6795 : 283 : Query *subquery = rte->subquery;
6796 : :
6797 : : Assert(subquery != NULL);
6798 : :
6799 : : /*
6800 : : * We need parens if WITH, ORDER BY, FOR UPDATE, or LIMIT; see gram.y.
6801 : : * Also add parens if the leaf query contains its own set operations.
6802 : : * (That shouldn't happen unless one of the other clauses is also
6803 : : * present, see transformSetOperationTree; but let's be safe.)
6804 : : */
6805 : 849 : need_paren = (subquery->cteList ||
6806 [ + - ]: 283 : subquery->sortClause ||
6807 [ + - ]: 283 : subquery->rowMarks ||
6808 [ + - ]: 283 : subquery->limitOffset ||
6809 [ + - + - ]: 849 : subquery->limitCount ||
6810 [ - + ]: 283 : subquery->setOperations);
6811 [ - + ]: 283 : if (need_paren)
6812 : 0 : appendStringInfoChar(buf, '(');
6813 : 283 : get_query_def(subquery, buf, context->namespaces,
6814 : 283 : context->resultDesc, context->colNamesVisible,
6815 : : context->prettyFlags, context->wrapColumn,
6816 : : context->indentLevel);
6817 [ - + ]: 283 : if (need_paren)
6818 : 0 : appendStringInfoChar(buf, ')');
6819 : : }
6820 [ + - ]: 180 : else if (IsA(setOp, SetOperationStmt))
6821 : : {
6822 : 180 : SetOperationStmt *op = (SetOperationStmt *) setOp;
6823 : : int subindent;
6824 : : bool save_colnamesvisible;
6825 : :
6826 : : /*
6827 : : * We force parens when nesting two SetOperationStmts, except when the
6828 : : * lefthand input is another setop of the same kind. Syntactically,
6829 : : * we could omit parens in rather more cases, but it seems best to use
6830 : : * parens to flag cases where the setop operator changes. If we use
6831 : : * parens, we also increase the indentation level for the child query.
6832 : : *
6833 : : * There are some cases in which parens are needed around a leaf query
6834 : : * too, but those are more easily handled at the next level down (see
6835 : : * code above).
6836 : : */
6837 [ + + ]: 180 : if (IsA(op->larg, SetOperationStmt))
6838 : : {
6839 : 77 : SetOperationStmt *lop = (SetOperationStmt *) op->larg;
6840 : :
6841 [ + - + - ]: 77 : if (op->op == lop->op && op->all == lop->all)
6842 : 77 : need_paren = false;
6843 : : else
6844 : 0 : need_paren = true;
6845 : : }
6846 : : else
6847 : 103 : need_paren = false;
6848 : :
6849 [ - + ]: 180 : if (need_paren)
6850 : : {
6851 : 0 : appendStringInfoChar(buf, '(');
6852 : 0 : subindent = PRETTYINDENT_STD;
6853 : 0 : appendContextKeyword(context, "", subindent, 0, 0);
6854 : : }
6855 : : else
6856 : 180 : subindent = 0;
6857 : :
6858 : 180 : get_setop_query(op->larg, query, context);
6859 : :
6860 [ - + ]: 180 : if (need_paren)
6861 : 0 : appendContextKeyword(context, ") ", -subindent, 0, 0);
6862 [ + - ]: 180 : else if (PRETTY_INDENT(context))
6863 : 180 : appendContextKeyword(context, "", -subindent, 0, 0);
6864 : : else
6865 : 0 : appendStringInfoChar(buf, ' ');
6866 : :
6867 [ + - - - ]: 180 : switch (op->op)
6868 : : {
6869 : 180 : case SETOP_UNION:
6870 : 180 : appendStringInfoString(buf, "UNION ");
6871 : 180 : break;
6872 : 0 : case SETOP_INTERSECT:
6873 : 0 : appendStringInfoString(buf, "INTERSECT ");
6874 : 0 : break;
6875 : 0 : case SETOP_EXCEPT:
6876 : 0 : appendStringInfoString(buf, "EXCEPT ");
6877 : 0 : break;
6878 : 0 : default:
6879 [ # # ]: 0 : elog(ERROR, "unrecognized set op: %d",
6880 : : (int) op->op);
6881 : : }
6882 [ + + ]: 180 : if (op->all)
6883 : 172 : appendStringInfoString(buf, "ALL ");
6884 : :
6885 : : /* Always parenthesize if RHS is another setop */
6886 : 180 : need_paren = IsA(op->rarg, SetOperationStmt);
6887 : :
6888 : : /*
6889 : : * The indentation code here is deliberately a bit different from that
6890 : : * for the lefthand input, because we want the line breaks in
6891 : : * different places.
6892 : : */
6893 [ - + ]: 180 : if (need_paren)
6894 : : {
6895 : 0 : appendStringInfoChar(buf, '(');
6896 : 0 : subindent = PRETTYINDENT_STD;
6897 : : }
6898 : : else
6899 : 180 : subindent = 0;
6900 : 180 : appendContextKeyword(context, "", subindent, 0, 0);
6901 : :
6902 : : /*
6903 : : * The output column names of the RHS sub-select don't matter.
6904 : : */
6905 : 180 : save_colnamesvisible = context->colNamesVisible;
6906 : 180 : context->colNamesVisible = false;
6907 : :
6908 : 180 : get_setop_query(op->rarg, query, context);
6909 : :
6910 : 180 : context->colNamesVisible = save_colnamesvisible;
6911 : :
6912 [ + - ]: 180 : if (PRETTY_INDENT(context))
6913 : 180 : context->indentLevel -= subindent;
6914 [ - + ]: 180 : if (need_paren)
6915 : 0 : appendContextKeyword(context, ")", 0, 0, 0);
6916 : : }
6917 : : else
6918 : : {
6919 [ # # ]: 0 : elog(ERROR, "unrecognized node type: %d",
6920 : : (int) nodeTag(setOp));
6921 : : }
6922 : 463 : }
6923 : :
6924 : : /*
6925 : : * Display a sort/group clause.
6926 : : *
6927 : : * Also returns the expression tree, so caller need not find it again.
6928 : : */
6929 : : static Node *
6930 : 453 : get_rule_sortgroupclause(Index ref, List *tlist, bool force_colno,
6931 : : deparse_context *context)
6932 : : {
6933 : 453 : StringInfo buf = context->buf;
6934 : : TargetEntry *tle;
6935 : : Node *expr;
6936 : :
6937 : 453 : tle = get_sortgroupref_tle(ref, tlist);
6938 : 453 : expr = (Node *) tle->expr;
6939 : :
6940 : : /*
6941 : : * Use column-number form if requested by caller. Otherwise, if
6942 : : * expression is a constant, force it to be dumped with an explicit cast
6943 : : * as decoration --- this is because a simple integer constant is
6944 : : * ambiguous (and will be misinterpreted by findTargetlistEntrySQL92()) if
6945 : : * we dump it without any decoration. Similarly, if it's just a Var,
6946 : : * there is risk of misinterpretation if the column name is reassigned in
6947 : : * the SELECT list, so we may need to force table qualification. And, if
6948 : : * it's anything more complex than a simple Var, then force extra parens
6949 : : * around it, to ensure it can't be misinterpreted as a cube() or rollup()
6950 : : * construct.
6951 : : */
6952 [ + + ]: 453 : if (force_colno)
6953 : : {
6954 : : Assert(!tle->resjunk);
6955 : 7 : appendStringInfo(buf, "%d", tle->resno);
6956 : : }
6957 [ + - ]: 446 : else if (!expr)
6958 : : /* do nothing, probably can't happen */ ;
6959 [ - + ]: 446 : else if (IsA(expr, Const))
6960 : 0 : get_const_expr((Const *) expr, context, 1);
6961 [ + + ]: 446 : else if (IsA(expr, Var))
6962 : : {
6963 : : /* Tell get_variable to check for name conflict */
6964 : 429 : bool save_varinorderby = context->varInOrderBy;
6965 : :
6966 : 429 : context->varInOrderBy = true;
6967 : 429 : (void) get_variable((Var *) expr, 0, false, context);
6968 : 429 : context->varInOrderBy = save_varinorderby;
6969 : : }
6970 : : else
6971 : : {
6972 : : /*
6973 : : * We must force parens for function-like expressions even if
6974 : : * PRETTY_PAREN is off, since those are the ones in danger of
6975 : : * misparsing. For other expressions we need to force them only if
6976 : : * PRETTY_PAREN is on, since otherwise the expression will output them
6977 : : * itself. (We can't skip the parens.)
6978 : : */
6979 : 34 : bool need_paren = (PRETTY_PAREN(context)
6980 [ + + ]: 17 : || IsA(expr, FuncExpr)
6981 [ + - ]: 15 : || IsA(expr, Aggref)
6982 [ + - ]: 15 : || IsA(expr, WindowFunc)
6983 [ + - - + ]: 34 : || IsA(expr, JsonConstructorExpr));
6984 : :
6985 [ + + ]: 17 : if (need_paren)
6986 : 2 : appendStringInfoChar(context->buf, '(');
6987 : 17 : get_rule_expr(expr, context, true);
6988 [ + + ]: 17 : if (need_paren)
6989 : 2 : appendStringInfoChar(context->buf, ')');
6990 : : }
6991 : :
6992 : 453 : return expr;
6993 : : }
6994 : :
6995 : : /*
6996 : : * Display a GroupingSet
6997 : : */
6998 : : static void
6999 : 12 : get_rule_groupingset(GroupingSet *gset, List *targetlist,
7000 : : bool omit_parens, deparse_context *context)
7001 : : {
7002 : : ListCell *l;
7003 : 12 : StringInfo buf = context->buf;
7004 : 12 : bool omit_child_parens = true;
7005 : 12 : char *sep = "";
7006 : :
7007 [ - + + - : 12 : switch (gset->kind)
- - ]
7008 : : {
7009 : 0 : case GROUPING_SET_EMPTY:
7010 : 0 : appendStringInfoString(buf, "()");
7011 : 0 : return;
7012 : :
7013 : 8 : case GROUPING_SET_SIMPLE:
7014 : : {
7015 [ + - + - ]: 8 : if (!omit_parens || list_length(gset->content) != 1)
7016 : 8 : appendStringInfoChar(buf, '(');
7017 : :
7018 [ + - + + : 28 : foreach(l, gset->content)
+ + ]
7019 : : {
7020 : 20 : Index ref = lfirst_int(l);
7021 : :
7022 : 20 : appendStringInfoString(buf, sep);
7023 : 20 : get_rule_sortgroupclause(ref, targetlist,
7024 : : false, context);
7025 : 20 : sep = ", ";
7026 : : }
7027 : :
7028 [ + - + - ]: 8 : if (!omit_parens || list_length(gset->content) != 1)
7029 : 8 : appendStringInfoChar(buf, ')');
7030 : : }
7031 : 8 : return;
7032 : :
7033 : 4 : case GROUPING_SET_ROLLUP:
7034 : 4 : appendStringInfoString(buf, "ROLLUP(");
7035 : 4 : break;
7036 : 0 : case GROUPING_SET_CUBE:
7037 : 0 : appendStringInfoString(buf, "CUBE(");
7038 : 0 : break;
7039 : 0 : case GROUPING_SET_SETS:
7040 : 0 : appendStringInfoString(buf, "GROUPING SETS (");
7041 : 0 : omit_child_parens = false;
7042 : 0 : break;
7043 : : }
7044 : :
7045 [ + - + + : 12 : foreach(l, gset->content)
+ + ]
7046 : : {
7047 : 8 : appendStringInfoString(buf, sep);
7048 : 8 : get_rule_groupingset(lfirst(l), targetlist, omit_child_parens, context);
7049 : 8 : sep = ", ";
7050 : : }
7051 : :
7052 : 4 : appendStringInfoChar(buf, ')');
7053 : : }
7054 : :
7055 : : /*
7056 : : * Display an ORDER BY list.
7057 : : */
7058 : : static void
7059 : 255 : get_rule_orderby(List *orderList, List *targetList,
7060 : : bool force_colno, deparse_context *context)
7061 : : {
7062 : 255 : StringInfo buf = context->buf;
7063 : : const char *sep;
7064 : : ListCell *l;
7065 : :
7066 : 255 : sep = "";
7067 [ + - + + : 540 : foreach(l, orderList)
+ + ]
7068 : : {
7069 : 285 : SortGroupClause *srt = (SortGroupClause *) lfirst(l);
7070 : : Node *sortexpr;
7071 : : Oid sortcoltype;
7072 : : TypeCacheEntry *typentry;
7073 : :
7074 : 285 : appendStringInfoString(buf, sep);
7075 : 285 : sortexpr = get_rule_sortgroupclause(srt->tleSortGroupRef, targetList,
7076 : : force_colno, context);
7077 : 285 : sortcoltype = exprType(sortexpr);
7078 : : /* See whether operator is default < or > for datatype */
7079 : 285 : typentry = lookup_type_cache(sortcoltype,
7080 : : TYPECACHE_LT_OPR | TYPECACHE_GT_OPR);
7081 [ + + ]: 285 : if (srt->sortop == typentry->lt_opr)
7082 : : {
7083 : : /* ASC is default, so emit nothing for it */
7084 [ - + ]: 268 : if (srt->nulls_first)
7085 : 0 : appendStringInfoString(buf, " NULLS FIRST");
7086 : : }
7087 [ + + ]: 17 : else if (srt->sortop == typentry->gt_opr)
7088 : : {
7089 : 6 : appendStringInfoString(buf, " DESC");
7090 : : /* DESC defaults to NULLS FIRST */
7091 [ + + ]: 6 : if (!srt->nulls_first)
7092 : 1 : appendStringInfoString(buf, " NULLS LAST");
7093 : : }
7094 : : else
7095 : : {
7096 : 11 : appendStringInfo(buf, " USING %s",
7097 : : generate_operator_name(srt->sortop,
7098 : : sortcoltype,
7099 : : sortcoltype));
7100 : : /* be specific to eliminate ambiguity */
7101 [ - + ]: 11 : if (srt->nulls_first)
7102 : 0 : appendStringInfoString(buf, " NULLS FIRST");
7103 : : else
7104 : 11 : appendStringInfoString(buf, " NULLS LAST");
7105 : : }
7106 : 285 : sep = ", ";
7107 : : }
7108 : 255 : }
7109 : :
7110 : : /*
7111 : : * Display a WINDOW clause.
7112 : : *
7113 : : * Note that the windowClause list might contain only anonymous window
7114 : : * specifications, in which case we should print nothing here.
7115 : : */
7116 : : static void
7117 : 32 : get_rule_windowclause(Query *query, deparse_context *context)
7118 : : {
7119 : 32 : StringInfo buf = context->buf;
7120 : : const char *sep;
7121 : : ListCell *l;
7122 : :
7123 : 32 : sep = NULL;
7124 [ + - + + : 64 : foreach(l, query->windowClause)
+ + ]
7125 : : {
7126 : 32 : WindowClause *wc = (WindowClause *) lfirst(l);
7127 : :
7128 [ + + ]: 32 : if (wc->name == NULL)
7129 : 28 : continue; /* ignore anonymous windows */
7130 : :
7131 [ + - ]: 4 : if (sep == NULL)
7132 : 4 : appendContextKeyword(context, " WINDOW ",
7133 : : -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
7134 : : else
7135 : 0 : appendStringInfoString(buf, sep);
7136 : :
7137 : 4 : appendStringInfo(buf, "%s AS ", quote_identifier(wc->name));
7138 : :
7139 : 4 : get_rule_windowspec(wc, query->targetList, context);
7140 : :
7141 : 4 : sep = ", ";
7142 : : }
7143 : 32 : }
7144 : :
7145 : : /*
7146 : : * Display a window definition
7147 : : */
7148 : : static void
7149 : 32 : get_rule_windowspec(WindowClause *wc, List *targetList,
7150 : : deparse_context *context)
7151 : : {
7152 : 32 : StringInfo buf = context->buf;
7153 : 32 : bool needspace = false;
7154 : : const char *sep;
7155 : : ListCell *l;
7156 : :
7157 : 32 : appendStringInfoChar(buf, '(');
7158 [ - + ]: 32 : if (wc->refname)
7159 : : {
7160 : 0 : appendStringInfoString(buf, quote_identifier(wc->refname));
7161 : 0 : needspace = true;
7162 : : }
7163 : : /* partition clauses are always inherited, so only print if no refname */
7164 [ - + - - ]: 32 : if (wc->partitionClause && !wc->refname)
7165 : : {
7166 [ # # ]: 0 : if (needspace)
7167 : 0 : appendStringInfoChar(buf, ' ');
7168 : 0 : appendStringInfoString(buf, "PARTITION BY ");
7169 : 0 : sep = "";
7170 [ # # # # : 0 : foreach(l, wc->partitionClause)
# # ]
7171 : : {
7172 : 0 : SortGroupClause *grp = (SortGroupClause *) lfirst(l);
7173 : :
7174 : 0 : appendStringInfoString(buf, sep);
7175 : 0 : get_rule_sortgroupclause(grp->tleSortGroupRef, targetList,
7176 : : false, context);
7177 : 0 : sep = ", ";
7178 : : }
7179 : 0 : needspace = true;
7180 : : }
7181 : : /* print ordering clause only if not inherited */
7182 [ + - + - ]: 32 : if (wc->orderClause && !wc->copiedOrder)
7183 : : {
7184 [ - + ]: 32 : if (needspace)
7185 : 0 : appendStringInfoChar(buf, ' ');
7186 : 32 : appendStringInfoString(buf, "ORDER BY ");
7187 : 32 : get_rule_orderby(wc->orderClause, targetList, false, context);
7188 : 32 : needspace = true;
7189 : : }
7190 : : /* framing clause is never inherited, so print unless it's default */
7191 [ + + ]: 32 : if (wc->frameOptions & FRAMEOPTION_NONDEFAULT)
7192 : : {
7193 [ + - ]: 28 : if (needspace)
7194 : 28 : appendStringInfoChar(buf, ' ');
7195 : 28 : get_window_frame_options(wc->frameOptions,
7196 : : wc->startOffset, wc->endOffset,
7197 : : context);
7198 : : }
7199 : 32 : appendStringInfoChar(buf, ')');
7200 : 32 : }
7201 : :
7202 : : /*
7203 : : * Append the description of a window's framing options to context->buf
7204 : : */
7205 : : static void
7206 : 214 : get_window_frame_options(int frameOptions,
7207 : : Node *startOffset, Node *endOffset,
7208 : : deparse_context *context)
7209 : : {
7210 : 214 : StringInfo buf = context->buf;
7211 : :
7212 [ + - ]: 214 : if (frameOptions & FRAMEOPTION_NONDEFAULT)
7213 : : {
7214 [ + + ]: 214 : if (frameOptions & FRAMEOPTION_RANGE)
7215 : 25 : appendStringInfoString(buf, "RANGE ");
7216 [ + + ]: 189 : else if (frameOptions & FRAMEOPTION_ROWS)
7217 : 169 : appendStringInfoString(buf, "ROWS ");
7218 [ + - ]: 20 : else if (frameOptions & FRAMEOPTION_GROUPS)
7219 : 20 : appendStringInfoString(buf, "GROUPS ");
7220 : : else
7221 : : Assert(false);
7222 [ + + ]: 214 : if (frameOptions & FRAMEOPTION_BETWEEN)
7223 : 109 : appendStringInfoString(buf, "BETWEEN ");
7224 [ + + ]: 214 : if (frameOptions & FRAMEOPTION_START_UNBOUNDED_PRECEDING)
7225 : 145 : appendStringInfoString(buf, "UNBOUNDED PRECEDING ");
7226 [ + + ]: 69 : else if (frameOptions & FRAMEOPTION_START_CURRENT_ROW)
7227 : 29 : appendStringInfoString(buf, "CURRENT ROW ");
7228 [ + - ]: 40 : else if (frameOptions & FRAMEOPTION_START_OFFSET)
7229 : : {
7230 : 40 : get_rule_expr(startOffset, context, false);
7231 [ + - ]: 40 : if (frameOptions & FRAMEOPTION_START_OFFSET_PRECEDING)
7232 : 40 : appendStringInfoString(buf, " PRECEDING ");
7233 [ # # ]: 0 : else if (frameOptions & FRAMEOPTION_START_OFFSET_FOLLOWING)
7234 : 0 : appendStringInfoString(buf, " FOLLOWING ");
7235 : : else
7236 : : Assert(false);
7237 : : }
7238 : : else
7239 : : Assert(false);
7240 [ + + ]: 214 : if (frameOptions & FRAMEOPTION_BETWEEN)
7241 : : {
7242 : 109 : appendStringInfoString(buf, "AND ");
7243 [ + + ]: 109 : if (frameOptions & FRAMEOPTION_END_UNBOUNDED_FOLLOWING)
7244 : 13 : appendStringInfoString(buf, "UNBOUNDED FOLLOWING ");
7245 [ + + ]: 96 : else if (frameOptions & FRAMEOPTION_END_CURRENT_ROW)
7246 : 24 : appendStringInfoString(buf, "CURRENT ROW ");
7247 [ + - ]: 72 : else if (frameOptions & FRAMEOPTION_END_OFFSET)
7248 : : {
7249 : 72 : get_rule_expr(endOffset, context, false);
7250 [ + + ]: 72 : if (frameOptions & FRAMEOPTION_END_OFFSET_PRECEDING)
7251 : 28 : appendStringInfoString(buf, " PRECEDING ");
7252 [ + - ]: 44 : else if (frameOptions & FRAMEOPTION_END_OFFSET_FOLLOWING)
7253 : 44 : appendStringInfoString(buf, " FOLLOWING ");
7254 : : else
7255 : : Assert(false);
7256 : : }
7257 : : else
7258 : : Assert(false);
7259 : : }
7260 [ + + ]: 214 : if (frameOptions & FRAMEOPTION_EXCLUDE_CURRENT_ROW)
7261 : 24 : appendStringInfoString(buf, "EXCLUDE CURRENT ROW ");
7262 [ + + ]: 190 : else if (frameOptions & FRAMEOPTION_EXCLUDE_GROUP)
7263 : 12 : appendStringInfoString(buf, "EXCLUDE GROUP ");
7264 [ + + ]: 178 : else if (frameOptions & FRAMEOPTION_EXCLUDE_TIES)
7265 : 12 : appendStringInfoString(buf, "EXCLUDE TIES ");
7266 : : /* we will now have a trailing space; remove it */
7267 : 214 : buf->data[--(buf->len)] = '\0';
7268 : : }
7269 : 214 : }
7270 : :
7271 : : /*
7272 : : * Return the description of a window's framing options as a palloc'd string
7273 : : */
7274 : : char *
7275 : 186 : get_window_frame_options_for_explain(int frameOptions,
7276 : : Node *startOffset, Node *endOffset,
7277 : : List *dpcontext, bool forceprefix)
7278 : : {
7279 : : StringInfoData buf;
7280 : : deparse_context context;
7281 : :
7282 : 186 : initStringInfo(&buf);
7283 : 186 : context.buf = &buf;
7284 : 186 : context.namespaces = dpcontext;
7285 : 186 : context.resultDesc = NULL;
7286 : 186 : context.targetList = NIL;
7287 : 186 : context.windowClause = NIL;
7288 : 186 : context.varprefix = forceprefix;
7289 : 186 : context.prettyFlags = 0;
7290 : 186 : context.wrapColumn = WRAP_COLUMN_DEFAULT;
7291 : 186 : context.indentLevel = 0;
7292 : 186 : context.colNamesVisible = true;
7293 : 186 : context.inGroupBy = false;
7294 : 186 : context.varInOrderBy = false;
7295 : 186 : context.appendparents = NULL;
7296 : :
7297 : 186 : get_window_frame_options(frameOptions, startOffset, endOffset, &context);
7298 : :
7299 : 186 : return buf.data;
7300 : : }
7301 : :
7302 : : /* ----------
7303 : : * get_insert_query_def - Parse back an INSERT parsetree
7304 : : * ----------
7305 : : */
7306 : : static void
7307 : 194 : get_insert_query_def(Query *query, deparse_context *context)
7308 : : {
7309 : 194 : StringInfo buf = context->buf;
7310 : 194 : RangeTblEntry *select_rte = NULL;
7311 : 194 : RangeTblEntry *values_rte = NULL;
7312 : : RangeTblEntry *rte;
7313 : : char *sep;
7314 : : ListCell *l;
7315 : : List *strippedexprs;
7316 : :
7317 : : /* Insert the WITH clause if given */
7318 : 194 : get_with_clause(query, context);
7319 : :
7320 : : /*
7321 : : * If it's an INSERT ... SELECT or multi-row VALUES, there will be a
7322 : : * single RTE for the SELECT or VALUES. Plain VALUES has neither.
7323 : : */
7324 [ + - + + : 758 : foreach(l, query->rtable)
+ + ]
7325 : : {
7326 : 564 : rte = (RangeTblEntry *) lfirst(l);
7327 : :
7328 [ + + ]: 564 : if (rte->rtekind == RTE_SUBQUERY)
7329 : : {
7330 [ - + ]: 30 : if (select_rte)
7331 [ # # ]: 0 : elog(ERROR, "too many subquery RTEs in INSERT");
7332 : 30 : select_rte = rte;
7333 : : }
7334 : :
7335 [ + + ]: 564 : if (rte->rtekind == RTE_VALUES)
7336 : : {
7337 [ - + ]: 26 : if (values_rte)
7338 [ # # ]: 0 : elog(ERROR, "too many values RTEs in INSERT");
7339 : 26 : values_rte = rte;
7340 : : }
7341 : : }
7342 [ + + - + ]: 194 : if (select_rte && values_rte)
7343 [ # # ]: 0 : elog(ERROR, "both subquery and values RTEs in INSERT");
7344 : :
7345 : : /*
7346 : : * Start the query with INSERT INTO relname
7347 : : */
7348 : 194 : rte = rt_fetch(query->resultRelation, query->rtable);
7349 : : Assert(rte->rtekind == RTE_RELATION);
7350 : :
7351 [ + - ]: 194 : if (PRETTY_INDENT(context))
7352 : : {
7353 : 194 : context->indentLevel += PRETTYINDENT_STD;
7354 : 194 : appendStringInfoChar(buf, ' ');
7355 : : }
7356 : 194 : appendStringInfo(buf, "INSERT INTO %s",
7357 : : generate_relation_name(rte->relid, NIL));
7358 : :
7359 : : /* Print the relation alias, if needed; INSERT requires explicit AS */
7360 : 194 : get_rte_alias(rte, query->resultRelation, true, context);
7361 : :
7362 : : /* always want a space here */
7363 : 194 : appendStringInfoChar(buf, ' ');
7364 : :
7365 : : /*
7366 : : * Add the insert-column-names list. Any indirection decoration needed on
7367 : : * the column names can be inferred from the top targetlist.
7368 : : */
7369 : 194 : strippedexprs = NIL;
7370 : 194 : sep = "";
7371 [ + - ]: 194 : if (query->targetList)
7372 : 194 : appendStringInfoChar(buf, '(');
7373 [ + - + + : 695 : foreach(l, query->targetList)
+ + ]
7374 : : {
7375 : 501 : TargetEntry *tle = (TargetEntry *) lfirst(l);
7376 : :
7377 [ - + ]: 501 : if (tle->resjunk)
7378 : 0 : continue; /* ignore junk entries */
7379 : :
7380 : 501 : appendStringInfoString(buf, sep);
7381 : 501 : sep = ", ";
7382 : :
7383 : : /*
7384 : : * Put out name of target column; look in the catalogs, not at
7385 : : * tle->resname, since resname will fail to track RENAME.
7386 : : */
7387 : 501 : appendStringInfoString(buf,
7388 : 501 : quote_identifier(get_attname(rte->relid,
7389 : 501 : tle->resno,
7390 : : false)));
7391 : :
7392 : : /*
7393 : : * Print any indirection needed (subfields or subscripts), and strip
7394 : : * off the top-level nodes representing the indirection assignments.
7395 : : * Add the stripped expressions to strippedexprs. (If it's a
7396 : : * single-VALUES statement, the stripped expressions are the VALUES to
7397 : : * print below. Otherwise they're just Vars and not really
7398 : : * interesting.)
7399 : : */
7400 : 501 : strippedexprs = lappend(strippedexprs,
7401 : 501 : processIndirection((Node *) tle->expr,
7402 : : context));
7403 : : }
7404 [ + - ]: 194 : if (query->targetList)
7405 : 194 : appendStringInfoString(buf, ") ");
7406 : :
7407 [ - + ]: 194 : if (query->override)
7408 : : {
7409 [ # # ]: 0 : if (query->override == OVERRIDING_SYSTEM_VALUE)
7410 : 0 : appendStringInfoString(buf, "OVERRIDING SYSTEM VALUE ");
7411 [ # # ]: 0 : else if (query->override == OVERRIDING_USER_VALUE)
7412 : 0 : appendStringInfoString(buf, "OVERRIDING USER VALUE ");
7413 : : }
7414 : :
7415 [ + + ]: 194 : if (select_rte)
7416 : : {
7417 : : /* Add the SELECT */
7418 : 30 : get_query_def(select_rte->subquery, buf, context->namespaces, NULL,
7419 : : false,
7420 : : context->prettyFlags, context->wrapColumn,
7421 : : context->indentLevel);
7422 : : }
7423 [ + + ]: 164 : else if (values_rte)
7424 : : {
7425 : : /* Add the multi-VALUES expression lists */
7426 : 26 : get_values_def(values_rte->values_lists, context);
7427 : : }
7428 [ + - ]: 138 : else if (strippedexprs)
7429 : : {
7430 : : /* Add the single-VALUES expression list */
7431 : 138 : appendContextKeyword(context, "VALUES (",
7432 : : -PRETTYINDENT_STD, PRETTYINDENT_STD, 2);
7433 : 138 : get_rule_list_toplevel(strippedexprs, context, false);
7434 : 138 : appendStringInfoChar(buf, ')');
7435 : : }
7436 : : else
7437 : : {
7438 : : /* No expressions, so it must be DEFAULT VALUES */
7439 : 0 : appendStringInfoString(buf, "DEFAULT VALUES");
7440 : : }
7441 : :
7442 : : /* Add ON CONFLICT if present */
7443 [ + + ]: 194 : if (query->onConflict)
7444 : : {
7445 : 24 : OnConflictExpr *confl = query->onConflict;
7446 : :
7447 : 24 : appendStringInfoString(buf, " ON CONFLICT");
7448 : :
7449 [ + + ]: 24 : if (confl->arbiterElems)
7450 : : {
7451 : : /* Add the single-VALUES expression list */
7452 : 20 : appendStringInfoChar(buf, '(');
7453 : 20 : get_rule_expr((Node *) confl->arbiterElems, context, false);
7454 : 20 : appendStringInfoChar(buf, ')');
7455 : :
7456 : : /* Add a WHERE clause (for partial indexes) if given */
7457 [ + + ]: 20 : if (confl->arbiterWhere != NULL)
7458 : : {
7459 : : bool save_varprefix;
7460 : :
7461 : : /*
7462 : : * Force non-prefixing of Vars, since parser assumes that they
7463 : : * belong to target relation. WHERE clause does not use
7464 : : * InferenceElem, so this is separately required.
7465 : : */
7466 : 8 : save_varprefix = context->varprefix;
7467 : 8 : context->varprefix = false;
7468 : :
7469 : 8 : appendContextKeyword(context, " WHERE ",
7470 : : -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
7471 : 8 : get_rule_expr(confl->arbiterWhere, context, false);
7472 : :
7473 : 8 : context->varprefix = save_varprefix;
7474 : : }
7475 : : }
7476 [ - + ]: 4 : else if (OidIsValid(confl->constraint))
7477 : : {
7478 : 0 : char *constraint = get_constraint_name(confl->constraint);
7479 : :
7480 [ # # ]: 0 : if (!constraint)
7481 [ # # ]: 0 : elog(ERROR, "cache lookup failed for constraint %u",
7482 : : confl->constraint);
7483 : 0 : appendStringInfo(buf, " ON CONSTRAINT %s",
7484 : : quote_identifier(constraint));
7485 : : }
7486 : :
7487 [ + + ]: 24 : if (confl->action == ONCONFLICT_NOTHING)
7488 : : {
7489 : 12 : appendStringInfoString(buf, " DO NOTHING");
7490 : : }
7491 [ + + ]: 12 : else if (confl->action == ONCONFLICT_UPDATE)
7492 : : {
7493 : 8 : appendStringInfoString(buf, " DO UPDATE SET ");
7494 : : /* Deparse targetlist */
7495 : 8 : get_update_query_targetlist_def(query, confl->onConflictSet,
7496 : : context, rte);
7497 : :
7498 : : /* Add a WHERE clause if given */
7499 [ + - ]: 8 : if (confl->onConflictWhere != NULL)
7500 : : {
7501 : 8 : appendContextKeyword(context, " WHERE ",
7502 : : -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
7503 : 8 : get_rule_expr(confl->onConflictWhere, context, false);
7504 : : }
7505 : : }
7506 : : else
7507 : : {
7508 : : Assert(confl->action == ONCONFLICT_SELECT);
7509 : 4 : appendStringInfoString(buf, " DO SELECT");
7510 : :
7511 : : /* Add FOR [KEY] UPDATE/SHARE clause if present */
7512 [ + - ]: 4 : if (confl->lockStrength != LCS_NONE)
7513 : 4 : appendStringInfoString(buf, get_lock_clause_strength(confl->lockStrength));
7514 : :
7515 : : /* Add a WHERE clause if given */
7516 [ + - ]: 4 : if (confl->onConflictWhere != NULL)
7517 : : {
7518 : 4 : appendContextKeyword(context, " WHERE ",
7519 : : -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
7520 : 4 : get_rule_expr(confl->onConflictWhere, context, false);
7521 : : }
7522 : : }
7523 : : }
7524 : :
7525 : : /* Add RETURNING if present */
7526 [ + + ]: 194 : if (query->returningList)
7527 : 51 : get_returning_clause(query, context);
7528 : 194 : }
7529 : :
7530 : :
7531 : : /* ----------
7532 : : * get_update_query_def - Parse back an UPDATE parsetree
7533 : : * ----------
7534 : : */
7535 : : static void
7536 : 94 : get_update_query_def(Query *query, deparse_context *context)
7537 : : {
7538 : 94 : StringInfo buf = context->buf;
7539 : : RangeTblEntry *rte;
7540 : :
7541 : : /* Insert the WITH clause if given */
7542 : 94 : get_with_clause(query, context);
7543 : :
7544 : : /*
7545 : : * Start the query with UPDATE relname SET
7546 : : */
7547 : 94 : rte = rt_fetch(query->resultRelation, query->rtable);
7548 : : Assert(rte->rtekind == RTE_RELATION);
7549 [ + - ]: 94 : if (PRETTY_INDENT(context))
7550 : : {
7551 : 94 : appendStringInfoChar(buf, ' ');
7552 : 94 : context->indentLevel += PRETTYINDENT_STD;
7553 : : }
7554 : 188 : appendStringInfo(buf, "UPDATE %s%s",
7555 [ + - ]: 94 : only_marker(rte),
7556 : : generate_relation_name(rte->relid, NIL));
7557 : :
7558 : : /* Print the FOR PORTION OF, if needed */
7559 : 94 : get_for_portion_of(query->forPortionOf, context);
7560 : :
7561 : : /* Print the relation alias, if needed */
7562 : 94 : get_rte_alias(rte, query->resultRelation, false, context);
7563 : :
7564 : 94 : appendStringInfoString(buf, " SET ");
7565 : :
7566 : : /* Deparse targetlist */
7567 : 94 : get_update_query_targetlist_def(query, query->targetList, context, rte);
7568 : :
7569 : : /* Add the FROM clause if needed */
7570 : 94 : get_from_clause(query, " FROM ", context);
7571 : :
7572 : : /* Add a WHERE clause if given */
7573 [ + + ]: 94 : if (query->jointree->quals != NULL)
7574 : : {
7575 : 61 : appendContextKeyword(context, " WHERE ",
7576 : : -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
7577 : 61 : get_rule_expr(query->jointree->quals, context, false);
7578 : : }
7579 : :
7580 : : /* Add RETURNING if present */
7581 [ + + ]: 94 : if (query->returningList)
7582 : 37 : get_returning_clause(query, context);
7583 : 94 : }
7584 : :
7585 : :
7586 : : /* ----------
7587 : : * get_update_query_targetlist_def - Parse back an UPDATE targetlist
7588 : : * ----------
7589 : : */
7590 : : static void
7591 : 118 : get_update_query_targetlist_def(Query *query, List *targetList,
7592 : : deparse_context *context, RangeTblEntry *rte)
7593 : : {
7594 : 118 : StringInfo buf = context->buf;
7595 : : ListCell *l;
7596 : : ListCell *next_ma_cell;
7597 : : int remaining_ma_columns;
7598 : : const char *sep;
7599 : : SubLink *cur_ma_sublink;
7600 : : List *ma_sublinks;
7601 : :
7602 : : /*
7603 : : * Prepare to deal with MULTIEXPR assignments: collect the source SubLinks
7604 : : * into a list. We expect them to appear, in ID order, in resjunk tlist
7605 : : * entries.
7606 : : */
7607 : 118 : ma_sublinks = NIL;
7608 [ + + ]: 118 : if (query->hasSubLinks) /* else there can't be any */
7609 : : {
7610 [ + - + + : 28 : foreach(l, targetList)
+ + ]
7611 : : {
7612 : 20 : TargetEntry *tle = (TargetEntry *) lfirst(l);
7613 : :
7614 [ + + + - ]: 20 : if (tle->resjunk && IsA(tle->expr, SubLink))
7615 : : {
7616 : 4 : SubLink *sl = (SubLink *) tle->expr;
7617 : :
7618 [ + - ]: 4 : if (sl->subLinkType == MULTIEXPR_SUBLINK)
7619 : : {
7620 : 4 : ma_sublinks = lappend(ma_sublinks, sl);
7621 : : Assert(sl->subLinkId == list_length(ma_sublinks));
7622 : : }
7623 : : }
7624 : : }
7625 : : }
7626 : 118 : next_ma_cell = list_head(ma_sublinks);
7627 : 118 : cur_ma_sublink = NULL;
7628 : 118 : remaining_ma_columns = 0;
7629 : :
7630 : : /* Add the comma separated list of 'attname = value' */
7631 : 118 : sep = "";
7632 [ + - + + : 298 : foreach(l, targetList)
+ + ]
7633 : : {
7634 : 180 : TargetEntry *tle = (TargetEntry *) lfirst(l);
7635 : : Node *expr;
7636 : :
7637 [ + + ]: 180 : if (tle->resjunk)
7638 : 4 : continue; /* ignore junk entries */
7639 : :
7640 : : /* Emit separator (OK whether we're in multiassignment or not) */
7641 : 176 : appendStringInfoString(buf, sep);
7642 : 176 : sep = ", ";
7643 : :
7644 : : /*
7645 : : * Check to see if we're starting a multiassignment group: if so,
7646 : : * output a left paren.
7647 : : */
7648 [ + + + - ]: 176 : if (next_ma_cell != NULL && cur_ma_sublink == NULL)
7649 : : {
7650 : : /*
7651 : : * We must dig down into the expr to see if it's a PARAM_MULTIEXPR
7652 : : * Param. That could be buried under FieldStores and
7653 : : * SubscriptingRefs and CoerceToDomains (cf processIndirection()),
7654 : : * and underneath those there could be an implicit type coercion.
7655 : : * Because we would ignore implicit type coercions anyway, we
7656 : : * don't need to be as careful as processIndirection() is about
7657 : : * descending past implicit CoerceToDomains.
7658 : : */
7659 : 4 : expr = (Node *) tle->expr;
7660 [ + - ]: 8 : while (expr)
7661 : : {
7662 [ - + ]: 8 : if (IsA(expr, FieldStore))
7663 : : {
7664 : 0 : FieldStore *fstore = (FieldStore *) expr;
7665 : :
7666 : 0 : expr = (Node *) linitial(fstore->newvals);
7667 : : }
7668 [ + + ]: 8 : else if (IsA(expr, SubscriptingRef))
7669 : : {
7670 : 4 : SubscriptingRef *sbsref = (SubscriptingRef *) expr;
7671 : :
7672 [ - + ]: 4 : if (sbsref->refassgnexpr == NULL)
7673 : 0 : break;
7674 : :
7675 : 4 : expr = (Node *) sbsref->refassgnexpr;
7676 : : }
7677 [ - + ]: 4 : else if (IsA(expr, CoerceToDomain))
7678 : : {
7679 : 0 : CoerceToDomain *cdomain = (CoerceToDomain *) expr;
7680 : :
7681 [ # # ]: 0 : if (cdomain->coercionformat != COERCE_IMPLICIT_CAST)
7682 : 0 : break;
7683 : 0 : expr = (Node *) cdomain->arg;
7684 : : }
7685 : : else
7686 : 4 : break;
7687 : : }
7688 : 4 : expr = strip_implicit_coercions(expr);
7689 : :
7690 [ + - + - ]: 4 : if (expr && IsA(expr, Param) &&
7691 [ + - ]: 4 : ((Param *) expr)->paramkind == PARAM_MULTIEXPR)
7692 : : {
7693 : 4 : cur_ma_sublink = (SubLink *) lfirst(next_ma_cell);
7694 : 4 : next_ma_cell = lnext(ma_sublinks, next_ma_cell);
7695 : 4 : remaining_ma_columns = count_nonjunk_tlist_entries(((Query *) cur_ma_sublink->subselect)->targetList);
7696 : : Assert(((Param *) expr)->paramid ==
7697 : : ((cur_ma_sublink->subLinkId << 16) | 1));
7698 : 4 : appendStringInfoChar(buf, '(');
7699 : : }
7700 : : }
7701 : :
7702 : : /*
7703 : : * Put out name of target column; look in the catalogs, not at
7704 : : * tle->resname, since resname will fail to track RENAME.
7705 : : */
7706 : 176 : appendStringInfoString(buf,
7707 : 176 : quote_identifier(get_attname(rte->relid,
7708 : 176 : tle->resno,
7709 : : false)));
7710 : :
7711 : : /*
7712 : : * Print any indirection needed (subfields or subscripts), and strip
7713 : : * off the top-level nodes representing the indirection assignments.
7714 : : */
7715 : 176 : expr = processIndirection((Node *) tle->expr, context);
7716 : :
7717 : : /*
7718 : : * If we're in a multiassignment, skip printing anything more, unless
7719 : : * this is the last column; in which case, what we print should be the
7720 : : * sublink, not the Param.
7721 : : */
7722 [ + + ]: 176 : if (cur_ma_sublink != NULL)
7723 : : {
7724 [ + + ]: 12 : if (--remaining_ma_columns > 0)
7725 : 8 : continue; /* not the last column of multiassignment */
7726 : 4 : appendStringInfoChar(buf, ')');
7727 : 4 : expr = (Node *) cur_ma_sublink;
7728 : 4 : cur_ma_sublink = NULL;
7729 : : }
7730 : :
7731 : 168 : appendStringInfoString(buf, " = ");
7732 : :
7733 : 168 : get_rule_expr(expr, context, false);
7734 : : }
7735 : 118 : }
7736 : :
7737 : :
7738 : : /* ----------
7739 : : * get_delete_query_def - Parse back a DELETE parsetree
7740 : : * ----------
7741 : : */
7742 : : static void
7743 : 47 : get_delete_query_def(Query *query, deparse_context *context)
7744 : : {
7745 : 47 : StringInfo buf = context->buf;
7746 : : RangeTblEntry *rte;
7747 : :
7748 : : /* Insert the WITH clause if given */
7749 : 47 : get_with_clause(query, context);
7750 : :
7751 : : /*
7752 : : * Start the query with DELETE FROM relname
7753 : : */
7754 : 47 : rte = rt_fetch(query->resultRelation, query->rtable);
7755 : : Assert(rte->rtekind == RTE_RELATION);
7756 [ + - ]: 47 : if (PRETTY_INDENT(context))
7757 : : {
7758 : 47 : appendStringInfoChar(buf, ' ');
7759 : 47 : context->indentLevel += PRETTYINDENT_STD;
7760 : : }
7761 : 94 : appendStringInfo(buf, "DELETE FROM %s%s",
7762 [ + - ]: 47 : only_marker(rte),
7763 : : generate_relation_name(rte->relid, NIL));
7764 : :
7765 : : /* Print the FOR PORTION OF, if needed */
7766 : 47 : get_for_portion_of(query->forPortionOf, context);
7767 : :
7768 : : /* Print the relation alias, if needed */
7769 : 47 : get_rte_alias(rte, query->resultRelation, false, context);
7770 : :
7771 : : /* Add the USING clause if given */
7772 : 47 : get_from_clause(query, " USING ", context);
7773 : :
7774 : : /* Add a WHERE clause if given */
7775 [ + + ]: 47 : if (query->jointree->quals != NULL)
7776 : : {
7777 : 39 : appendContextKeyword(context, " WHERE ",
7778 : : -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
7779 : 39 : get_rule_expr(query->jointree->quals, context, false);
7780 : : }
7781 : :
7782 : : /* Add RETURNING if present */
7783 [ + + ]: 47 : if (query->returningList)
7784 : 17 : get_returning_clause(query, context);
7785 : 47 : }
7786 : :
7787 : :
7788 : : /* ----------
7789 : : * get_merge_query_def - Parse back a MERGE parsetree
7790 : : * ----------
7791 : : */
7792 : : static void
7793 : 8 : get_merge_query_def(Query *query, deparse_context *context)
7794 : : {
7795 : 8 : StringInfo buf = context->buf;
7796 : : RangeTblEntry *rte;
7797 : : ListCell *lc;
7798 : : bool haveNotMatchedBySource;
7799 : :
7800 : : /* Insert the WITH clause if given */
7801 : 8 : get_with_clause(query, context);
7802 : :
7803 : : /*
7804 : : * Start the query with MERGE INTO relname
7805 : : */
7806 : 8 : rte = rt_fetch(query->resultRelation, query->rtable);
7807 : : Assert(rte->rtekind == RTE_RELATION);
7808 [ + - ]: 8 : if (PRETTY_INDENT(context))
7809 : : {
7810 : 8 : appendStringInfoChar(buf, ' ');
7811 : 8 : context->indentLevel += PRETTYINDENT_STD;
7812 : : }
7813 : 16 : appendStringInfo(buf, "MERGE INTO %s%s",
7814 [ + - ]: 8 : only_marker(rte),
7815 : : generate_relation_name(rte->relid, NIL));
7816 : :
7817 : : /* Print the relation alias, if needed */
7818 : 8 : get_rte_alias(rte, query->resultRelation, false, context);
7819 : :
7820 : : /* Print the source relation and join clause */
7821 : 8 : get_from_clause(query, " USING ", context);
7822 : 8 : appendContextKeyword(context, " ON ",
7823 : : -PRETTYINDENT_STD, PRETTYINDENT_STD, 2);
7824 : 8 : get_rule_expr(query->mergeJoinCondition, context, false);
7825 : :
7826 : : /*
7827 : : * Test for any NOT MATCHED BY SOURCE actions. If there are none, then
7828 : : * any NOT MATCHED BY TARGET actions are output as "WHEN NOT MATCHED", per
7829 : : * SQL standard. Otherwise, we have a non-SQL-standard query, so output
7830 : : * "BY SOURCE" / "BY TARGET" qualifiers for all NOT MATCHED actions, to be
7831 : : * more explicit.
7832 : : */
7833 : 8 : haveNotMatchedBySource = false;
7834 [ + - + + : 56 : foreach(lc, query->mergeActionList)
+ + ]
7835 : : {
7836 : 52 : MergeAction *action = lfirst_node(MergeAction, lc);
7837 : :
7838 [ + + ]: 52 : if (action->matchKind == MERGE_WHEN_NOT_MATCHED_BY_SOURCE)
7839 : : {
7840 : 4 : haveNotMatchedBySource = true;
7841 : 4 : break;
7842 : : }
7843 : : }
7844 : :
7845 : : /* Print each merge action */
7846 [ + - + + : 60 : foreach(lc, query->mergeActionList)
+ + ]
7847 : : {
7848 : 52 : MergeAction *action = lfirst_node(MergeAction, lc);
7849 : :
7850 : 52 : appendContextKeyword(context, " WHEN ",
7851 : : -PRETTYINDENT_STD, PRETTYINDENT_STD, 2);
7852 [ + + + - ]: 52 : switch (action->matchKind)
7853 : : {
7854 : 24 : case MERGE_WHEN_MATCHED:
7855 : 24 : appendStringInfoString(buf, "MATCHED");
7856 : 24 : break;
7857 : 4 : case MERGE_WHEN_NOT_MATCHED_BY_SOURCE:
7858 : 4 : appendStringInfoString(buf, "NOT MATCHED BY SOURCE");
7859 : 4 : break;
7860 : 24 : case MERGE_WHEN_NOT_MATCHED_BY_TARGET:
7861 [ + + ]: 24 : if (haveNotMatchedBySource)
7862 : 4 : appendStringInfoString(buf, "NOT MATCHED BY TARGET");
7863 : : else
7864 : 20 : appendStringInfoString(buf, "NOT MATCHED");
7865 : 24 : break;
7866 : 0 : default:
7867 [ # # ]: 0 : elog(ERROR, "unrecognized matchKind: %d",
7868 : : (int) action->matchKind);
7869 : : }
7870 : :
7871 [ + + ]: 52 : if (action->qual)
7872 : : {
7873 : 32 : appendContextKeyword(context, " AND ",
7874 : : -PRETTYINDENT_STD, PRETTYINDENT_STD, 3);
7875 : 32 : get_rule_expr(action->qual, context, false);
7876 : : }
7877 : 52 : appendContextKeyword(context, " THEN ",
7878 : : -PRETTYINDENT_STD, PRETTYINDENT_STD, 3);
7879 : :
7880 [ + + ]: 52 : if (action->commandType == CMD_INSERT)
7881 : : {
7882 : : /* This generally matches get_insert_query_def() */
7883 : 24 : List *strippedexprs = NIL;
7884 : 24 : const char *sep = "";
7885 : : ListCell *lc2;
7886 : :
7887 : 24 : appendStringInfoString(buf, "INSERT");
7888 : :
7889 [ + + ]: 24 : if (action->targetList)
7890 : 20 : appendStringInfoString(buf, " (");
7891 [ + + + + : 68 : foreach(lc2, action->targetList)
+ + ]
7892 : : {
7893 : 44 : TargetEntry *tle = (TargetEntry *) lfirst(lc2);
7894 : :
7895 : : Assert(!tle->resjunk);
7896 : :
7897 : 44 : appendStringInfoString(buf, sep);
7898 : 44 : sep = ", ";
7899 : :
7900 : 44 : appendStringInfoString(buf,
7901 : 44 : quote_identifier(get_attname(rte->relid,
7902 : 44 : tle->resno,
7903 : : false)));
7904 : 44 : strippedexprs = lappend(strippedexprs,
7905 : 44 : processIndirection((Node *) tle->expr,
7906 : : context));
7907 : : }
7908 [ + + ]: 24 : if (action->targetList)
7909 : 20 : appendStringInfoChar(buf, ')');
7910 : :
7911 [ + + ]: 24 : if (action->override)
7912 : : {
7913 [ - + ]: 4 : if (action->override == OVERRIDING_SYSTEM_VALUE)
7914 : 0 : appendStringInfoString(buf, " OVERRIDING SYSTEM VALUE");
7915 [ + - ]: 4 : else if (action->override == OVERRIDING_USER_VALUE)
7916 : 4 : appendStringInfoString(buf, " OVERRIDING USER VALUE");
7917 : : }
7918 : :
7919 [ + + ]: 24 : if (strippedexprs)
7920 : : {
7921 : 20 : appendContextKeyword(context, " VALUES (",
7922 : : -PRETTYINDENT_STD, PRETTYINDENT_STD, 4);
7923 : 20 : get_rule_list_toplevel(strippedexprs, context, false);
7924 : 20 : appendStringInfoChar(buf, ')');
7925 : : }
7926 : : else
7927 : 4 : appendStringInfoString(buf, " DEFAULT VALUES");
7928 : : }
7929 [ + + ]: 28 : else if (action->commandType == CMD_UPDATE)
7930 : : {
7931 : 16 : appendStringInfoString(buf, "UPDATE SET ");
7932 : 16 : get_update_query_targetlist_def(query, action->targetList,
7933 : : context, rte);
7934 : : }
7935 [ + + ]: 12 : else if (action->commandType == CMD_DELETE)
7936 : 8 : appendStringInfoString(buf, "DELETE");
7937 [ + - ]: 4 : else if (action->commandType == CMD_NOTHING)
7938 : 4 : appendStringInfoString(buf, "DO NOTHING");
7939 : : }
7940 : :
7941 : : /* Add RETURNING if present */
7942 [ + + ]: 8 : if (query->returningList)
7943 : 4 : get_returning_clause(query, context);
7944 : 8 : }
7945 : :
7946 : :
7947 : : /* ----------
7948 : : * get_utility_query_def - Parse back a UTILITY parsetree
7949 : : * ----------
7950 : : */
7951 : : static void
7952 : 9 : get_utility_query_def(Query *query, deparse_context *context)
7953 : : {
7954 : 9 : StringInfo buf = context->buf;
7955 : :
7956 [ + - + - ]: 9 : if (query->utilityStmt && IsA(query->utilityStmt, NotifyStmt))
7957 : 9 : {
7958 : 9 : NotifyStmt *stmt = (NotifyStmt *) query->utilityStmt;
7959 : :
7960 : 9 : appendContextKeyword(context, "",
7961 : : 0, PRETTYINDENT_STD, 1);
7962 : 9 : appendStringInfo(buf, "NOTIFY %s",
7963 : 9 : quote_identifier(stmt->conditionname));
7964 [ - + ]: 9 : if (stmt->payload)
7965 : : {
7966 : 0 : appendStringInfoString(buf, ", ");
7967 : 0 : simple_quote_literal(buf, stmt->payload);
7968 : : }
7969 : : }
7970 : : else
7971 : : {
7972 : : /* Currently only NOTIFY utility commands can appear in rules */
7973 [ # # ]: 0 : elog(ERROR, "unexpected utility statement type");
7974 : : }
7975 : 9 : }
7976 : :
7977 : :
7978 : : /*
7979 : : * Parse back a graph label expression
7980 : : */
7981 : : static void
7982 : 96 : get_graph_label_expr(Node *label_expr, deparse_context *context)
7983 : : {
7984 : 96 : StringInfo buf = context->buf;
7985 : :
7986 : 96 : check_stack_depth();
7987 : :
7988 [ + + - ]: 96 : switch (nodeTag(label_expr))
7989 : : {
7990 : 78 : case T_GraphLabelRef:
7991 : : {
7992 : 78 : GraphLabelRef *lref = (GraphLabelRef *) label_expr;
7993 : :
7994 : 78 : appendStringInfoString(buf, quote_identifier(get_propgraph_label_name(lref->labelid)));
7995 : 78 : break;
7996 : : }
7997 : :
7998 : 18 : case T_BoolExpr:
7999 : : {
8000 : 18 : BoolExpr *be = (BoolExpr *) label_expr;
8001 : : ListCell *lc;
8002 : 18 : bool first = true;
8003 : :
8004 : : Assert(be->boolop == OR_EXPR);
8005 : :
8006 [ + - + + : 54 : foreach(lc, be->args)
+ + ]
8007 : : {
8008 [ + + ]: 36 : if (!first)
8009 : : {
8010 [ + - ]: 18 : if (be->boolop == OR_EXPR)
8011 : 18 : appendStringInfoChar(buf, '|');
8012 : : }
8013 : : else
8014 : 18 : first = false;
8015 : 36 : get_graph_label_expr(lfirst(lc), context);
8016 : : }
8017 : :
8018 : 18 : break;
8019 : : }
8020 : :
8021 : 0 : default:
8022 [ # # ]: 0 : elog(ERROR, "unrecognized node type: %d", (int) nodeTag(label_expr));
8023 : : break;
8024 : : }
8025 : 96 : }
8026 : :
8027 : : /*
8028 : : * Parse back a path pattern expression
8029 : : */
8030 : : static void
8031 : 14 : get_path_pattern_expr_def(List *path_pattern_expr, deparse_context *context)
8032 : : {
8033 : 14 : StringInfo buf = context->buf;
8034 : : ListCell *lc;
8035 : :
8036 [ + - + + : 74 : foreach(lc, path_pattern_expr)
+ + ]
8037 : : {
8038 : 60 : GraphElementPattern *gep = lfirst_node(GraphElementPattern, lc);
8039 : 60 : const char *sep = "";
8040 : :
8041 [ + - + - : 60 : switch (gep->kind)
- ]
8042 : : {
8043 : 37 : case VERTEX_PATTERN:
8044 : 37 : appendStringInfoChar(buf, '(');
8045 : 37 : break;
8046 : 0 : case EDGE_PATTERN_LEFT:
8047 : 0 : appendStringInfoString(buf, "<-[");
8048 : 0 : break;
8049 : 23 : case EDGE_PATTERN_RIGHT:
8050 : : case EDGE_PATTERN_ANY:
8051 : 23 : appendStringInfoString(buf, "-[");
8052 : 23 : break;
8053 : 0 : case PAREN_EXPR:
8054 : 0 : appendStringInfoChar(buf, '(');
8055 : 0 : break;
8056 : : }
8057 : :
8058 [ + + ]: 60 : if (gep->variable)
8059 : : {
8060 : 37 : appendStringInfoString(buf, quote_identifier(gep->variable));
8061 : 37 : sep = " ";
8062 : : }
8063 : :
8064 [ + - ]: 60 : if (gep->labelexpr)
8065 : : {
8066 : 60 : appendStringInfoString(buf, sep);
8067 : 60 : appendStringInfoString(buf, "IS ");
8068 : 60 : get_graph_label_expr(gep->labelexpr, context);
8069 : 60 : sep = " ";
8070 : : }
8071 : :
8072 [ - + ]: 60 : if (gep->subexpr)
8073 : : {
8074 : 0 : appendStringInfoString(buf, sep);
8075 : 0 : get_path_pattern_expr_def(gep->subexpr, context);
8076 : 0 : sep = " ";
8077 : : }
8078 : :
8079 [ + + ]: 60 : if (gep->whereClause)
8080 : : {
8081 : 14 : appendStringInfoString(buf, sep);
8082 : 14 : appendStringInfoString(buf, "WHERE ");
8083 : 14 : get_rule_expr(gep->whereClause, context, false);
8084 : : }
8085 : :
8086 [ + - + - : 60 : switch (gep->kind)
- ]
8087 : : {
8088 : 37 : case VERTEX_PATTERN:
8089 : 37 : appendStringInfoChar(buf, ')');
8090 : 37 : break;
8091 : 0 : case EDGE_PATTERN_LEFT:
8092 : : case EDGE_PATTERN_ANY:
8093 : 0 : appendStringInfoString(buf, "]-");
8094 : 0 : break;
8095 : 23 : case EDGE_PATTERN_RIGHT:
8096 : 23 : appendStringInfoString(buf, "]->");
8097 : 23 : break;
8098 : 0 : case PAREN_EXPR:
8099 : 0 : appendStringInfoChar(buf, ')');
8100 : 0 : break;
8101 : : }
8102 : :
8103 [ - + ]: 60 : if (gep->quantifier)
8104 : : {
8105 : 0 : int lower = linitial_int(gep->quantifier);
8106 : 0 : int upper = lsecond_int(gep->quantifier);
8107 : :
8108 : 0 : appendStringInfo(buf, "{%d,%d}", lower, upper);
8109 : : }
8110 : : }
8111 : 14 : }
8112 : :
8113 : : /*
8114 : : * Parse back a graph pattern
8115 : : */
8116 : : static void
8117 : 14 : get_graph_pattern_def(GraphPattern *graph_pattern, deparse_context *context)
8118 : : {
8119 : 14 : StringInfo buf = context->buf;
8120 : : ListCell *lc;
8121 : 14 : bool first = true;
8122 : :
8123 [ + - + + : 28 : foreach(lc, graph_pattern->path_pattern_list)
+ + ]
8124 : : {
8125 : 14 : List *path_pattern_expr = lfirst_node(List, lc);
8126 : :
8127 [ - + ]: 14 : if (!first)
8128 : 0 : appendStringInfoString(buf, ", ");
8129 : : else
8130 : 14 : first = false;
8131 : :
8132 : 14 : get_path_pattern_expr_def(path_pattern_expr, context);
8133 : : }
8134 : :
8135 [ - + ]: 14 : if (graph_pattern->whereClause)
8136 : : {
8137 : 0 : appendStringInfoString(buf, "WHERE ");
8138 : 0 : get_rule_expr(graph_pattern->whereClause, context, false);
8139 : : }
8140 : 14 : }
8141 : :
8142 : : /*
8143 : : * Display a Var appropriately.
8144 : : *
8145 : : * In some cases (currently only when recursing into an unnamed join)
8146 : : * the Var's varlevelsup has to be interpreted with respect to a context
8147 : : * above the current one; levelsup indicates the offset.
8148 : : *
8149 : : * If istoplevel is true, the Var is at the top level of a SELECT's
8150 : : * targetlist, which means we need special treatment of whole-row Vars.
8151 : : * Instead of the normal "tab.*", we'll print "tab.*::typename", which is a
8152 : : * dirty hack to prevent "tab.*" from being expanded into multiple columns.
8153 : : * (The parser will strip the useless coercion, so no inefficiency is added in
8154 : : * dump and reload.) We used to print just "tab" in such cases, but that is
8155 : : * ambiguous and will yield the wrong result if "tab" is also a plain column
8156 : : * name in the query.
8157 : : *
8158 : : * Returns the attname of the Var, or NULL if the Var has no attname (because
8159 : : * it is a whole-row Var or a subplan output reference).
8160 : : */
8161 : : static char *
8162 : 127208 : get_variable(Var *var, int levelsup, bool istoplevel, deparse_context *context)
8163 : : {
8164 : 127208 : StringInfo buf = context->buf;
8165 : : RangeTblEntry *rte;
8166 : : AttrNumber attnum;
8167 : : int netlevelsup;
8168 : : deparse_namespace *dpns;
8169 : : int varno;
8170 : : AttrNumber varattno;
8171 : : deparse_columns *colinfo;
8172 : : char *refname;
8173 : : char *attname;
8174 : : bool need_prefix;
8175 : :
8176 : : /* Find appropriate nesting depth */
8177 : 127208 : netlevelsup = var->varlevelsup + levelsup;
8178 [ - + ]: 127208 : if (netlevelsup >= list_length(context->namespaces))
8179 [ # # ]: 0 : elog(ERROR, "bogus varlevelsup: %d offset %d",
8180 : : var->varlevelsup, levelsup);
8181 : 127208 : dpns = (deparse_namespace *) list_nth(context->namespaces,
8182 : : netlevelsup);
8183 : :
8184 : : /*
8185 : : * If we have a syntactic referent for the Var, and we're working from a
8186 : : * parse tree, prefer to use the syntactic referent. Otherwise, fall back
8187 : : * on the semantic referent. (Forcing use of the semantic referent when
8188 : : * printing plan trees is a design choice that's perhaps more motivated by
8189 : : * backwards compatibility than anything else. But it does have the
8190 : : * advantage of making plans more explicit.)
8191 : : */
8192 [ + + + + ]: 127208 : if (var->varnosyn > 0 && dpns->plan == NULL)
8193 : : {
8194 : 25120 : varno = var->varnosyn;
8195 : 25120 : varattno = var->varattnosyn;
8196 : : }
8197 : : else
8198 : : {
8199 : 102088 : varno = var->varno;
8200 : 102088 : varattno = var->varattno;
8201 : : }
8202 : :
8203 : : /*
8204 : : * Try to find the relevant RTE in this rtable. In a plan tree, it's
8205 : : * likely that varno is OUTER_VAR or INNER_VAR, in which case we must dig
8206 : : * down into the subplans, or INDEX_VAR, which is resolved similarly. Also
8207 : : * find the aliases previously assigned for this RTE.
8208 : : */
8209 [ + + + - ]: 127208 : if (varno >= 1 && varno <= list_length(dpns->rtable))
8210 : : {
8211 : : /*
8212 : : * We might have been asked to map child Vars to some parent relation.
8213 : : */
8214 [ + + + + ]: 92548 : if (context->appendparents && dpns->appendrels)
8215 : : {
8216 : 2517 : int pvarno = varno;
8217 : 2517 : AttrNumber pvarattno = varattno;
8218 : 2517 : AppendRelInfo *appinfo = dpns->appendrels[pvarno];
8219 : 2517 : bool found = false;
8220 : :
8221 : : /* Only map up to inheritance parents, not UNION ALL appendrels */
8222 [ + + ]: 5080 : while (appinfo &&
8223 : 2794 : rt_fetch(appinfo->parent_relid,
8224 [ + + ]: 2794 : dpns->rtable)->rtekind == RTE_RELATION)
8225 : : {
8226 : 2563 : found = false;
8227 [ + + ]: 2563 : if (pvarattno > 0) /* system columns stay as-is */
8228 : : {
8229 [ - + ]: 2411 : if (pvarattno > appinfo->num_child_cols)
8230 : 0 : break; /* safety check */
8231 : 2411 : pvarattno = appinfo->parent_colnos[pvarattno - 1];
8232 [ - + ]: 2411 : if (pvarattno == 0)
8233 : 0 : break; /* Var is local to child */
8234 : : }
8235 : :
8236 : 2563 : pvarno = appinfo->parent_relid;
8237 : 2563 : found = true;
8238 : :
8239 : : /* If the parent is itself a child, continue up. */
8240 : : Assert(pvarno > 0 && pvarno <= list_length(dpns->rtable));
8241 : 2563 : appinfo = dpns->appendrels[pvarno];
8242 : : }
8243 : :
8244 : : /*
8245 : : * If we found an ancestral rel, and that rel is included in
8246 : : * appendparents, print that column not the original one.
8247 : : */
8248 [ + + + + ]: 2517 : if (found && bms_is_member(pvarno, context->appendparents))
8249 : : {
8250 : 2038 : varno = pvarno;
8251 : 2038 : varattno = pvarattno;
8252 : : }
8253 : : }
8254 : :
8255 : 92548 : rte = rt_fetch(varno, dpns->rtable);
8256 : :
8257 : : /* might be returning old/new column value */
8258 [ + + ]: 92548 : if (var->varreturningtype == VAR_RETURNING_OLD)
8259 : 274 : refname = dpns->ret_old_alias;
8260 [ + + ]: 92274 : else if (var->varreturningtype == VAR_RETURNING_NEW)
8261 : 273 : refname = dpns->ret_new_alias;
8262 : : else
8263 : 92001 : refname = (char *) list_nth(dpns->rtable_names, varno - 1);
8264 : :
8265 : 92548 : colinfo = deparse_columns_fetch(varno, dpns);
8266 : 92548 : attnum = varattno;
8267 : : }
8268 : : else
8269 : : {
8270 : 34660 : resolve_special_varno((Node *) var, context,
8271 : : get_special_variable, NULL);
8272 : 34660 : return NULL;
8273 : : }
8274 : :
8275 : : /*
8276 : : * The planner will sometimes emit Vars referencing resjunk elements of a
8277 : : * subquery's target list (this is currently only possible if it chooses
8278 : : * to generate a "physical tlist" for a SubqueryScan or CteScan node).
8279 : : * Although we prefer to print subquery-referencing Vars using the
8280 : : * subquery's alias, that's not possible for resjunk items since they have
8281 : : * no alias. So in that case, drill down to the subplan and print the
8282 : : * contents of the referenced tlist item. This works because in a plan
8283 : : * tree, such Vars can only occur in a SubqueryScan or CteScan node, and
8284 : : * we'll have set dpns->inner_plan to reference the child plan node.
8285 : : */
8286 [ + + + + : 95727 : if ((rte->rtekind == RTE_SUBQUERY || rte->rtekind == RTE_CTE) &&
+ + ]
8287 : 3179 : attnum > list_length(rte->eref->colnames) &&
8288 [ + - ]: 1 : dpns->inner_plan)
8289 : : {
8290 : : TargetEntry *tle;
8291 : : deparse_namespace save_dpns;
8292 : :
8293 : 1 : tle = get_tle_by_resno(dpns->inner_tlist, attnum);
8294 [ - + ]: 1 : if (!tle)
8295 [ # # ]: 0 : elog(ERROR, "invalid attnum %d for relation \"%s\"",
8296 : : attnum, rte->eref->aliasname);
8297 : :
8298 : : Assert(netlevelsup == 0);
8299 : 1 : push_child_plan(dpns, dpns->inner_plan, &save_dpns);
8300 : :
8301 : : /*
8302 : : * Force parentheses because our caller probably assumed a Var is a
8303 : : * simple expression.
8304 : : */
8305 [ - + ]: 1 : if (!IsA(tle->expr, Var))
8306 : 0 : appendStringInfoChar(buf, '(');
8307 : 1 : get_rule_expr((Node *) tle->expr, context, true);
8308 [ - + ]: 1 : if (!IsA(tle->expr, Var))
8309 : 0 : appendStringInfoChar(buf, ')');
8310 : :
8311 : 1 : pop_child_plan(dpns, &save_dpns);
8312 : 1 : return NULL;
8313 : : }
8314 : :
8315 : : /*
8316 : : * If it's an unnamed join, look at the expansion of the alias variable.
8317 : : * If it's a simple reference to one of the input vars, then recursively
8318 : : * print the name of that var instead. When it's not a simple reference,
8319 : : * we have to just print the unqualified join column name. (This can only
8320 : : * happen with "dangerous" merged columns in a JOIN USING; we took pains
8321 : : * previously to make the unqualified column name unique in such cases.)
8322 : : *
8323 : : * This wouldn't work in decompiling plan trees, because we don't store
8324 : : * joinaliasvars lists after planning; but a plan tree should never
8325 : : * contain a join alias variable.
8326 : : */
8327 [ + + + + ]: 92547 : if (rte->rtekind == RTE_JOIN && rte->alias == NULL)
8328 : : {
8329 [ - + ]: 72 : if (rte->joinaliasvars == NIL)
8330 [ # # ]: 0 : elog(ERROR, "cannot decompile join alias var in plan tree");
8331 [ + - ]: 72 : if (attnum > 0)
8332 : : {
8333 : : Var *aliasvar;
8334 : :
8335 : 72 : aliasvar = (Var *) list_nth(rte->joinaliasvars, attnum - 1);
8336 : : /* we intentionally don't strip implicit coercions here */
8337 [ + - - + ]: 72 : if (aliasvar && IsA(aliasvar, Var))
8338 : : {
8339 : 0 : return get_variable(aliasvar, var->varlevelsup + levelsup,
8340 : : istoplevel, context);
8341 : : }
8342 : : }
8343 : :
8344 : : /*
8345 : : * Unnamed join has no refname. (Note: since it's unnamed, there is
8346 : : * no way the user could have referenced it to create a whole-row Var
8347 : : * for it. So we don't have to cover that case below.)
8348 : : */
8349 : : Assert(refname == NULL);
8350 : : }
8351 : :
8352 [ + + ]: 92547 : if (attnum == InvalidAttrNumber)
8353 : 680 : attname = NULL;
8354 [ + + ]: 91867 : else if (attnum > 0)
8355 : : {
8356 : : /* Get column name to use from the colinfo struct */
8357 [ - + ]: 90643 : if (attnum > colinfo->num_cols)
8358 [ # # ]: 0 : elog(ERROR, "invalid attnum %d for relation \"%s\"",
8359 : : attnum, rte->eref->aliasname);
8360 : 90643 : attname = colinfo->colnames[attnum - 1];
8361 : :
8362 : : /*
8363 : : * If we find a Var referencing a dropped column, it seems better to
8364 : : * print something (anything) than to fail. In general this should
8365 : : * not happen, but it used to be possible for some cases involving
8366 : : * functions returning named composite types, and perhaps there are
8367 : : * still bugs out there.
8368 : : */
8369 [ + + ]: 90643 : if (attname == NULL)
8370 : 4 : attname = "?dropped?column?";
8371 : : }
8372 : : else
8373 : : {
8374 : : /* System column - name is fixed, get it from the catalog */
8375 : 1224 : attname = get_rte_attribute_name(rte, attnum);
8376 : : }
8377 : :
8378 [ + + + + ]: 136347 : need_prefix = (context->varprefix || attname == NULL ||
8379 [ + + ]: 43800 : var->varreturningtype != VAR_RETURNING_DEFAULT);
8380 : :
8381 : : /*
8382 : : * If we're considering a plain Var in an ORDER BY (but not GROUP BY)
8383 : : * clause, we may need to add a table-name prefix to prevent
8384 : : * findTargetlistEntrySQL92 from misinterpreting the name as an
8385 : : * output-column name. To avoid cluttering the output with unnecessary
8386 : : * prefixes, do so only if there is a name match to a SELECT tlist item
8387 : : * that is different from the Var.
8388 : : */
8389 [ + + + + : 92547 : if (context->varInOrderBy && !context->inGroupBy && !need_prefix)
+ + ]
8390 : : {
8391 : 179 : int colno = 0;
8392 : :
8393 [ + + + + : 661 : foreach_node(TargetEntry, tle, context->targetList)
+ + ]
8394 : : {
8395 : : char *colname;
8396 : :
8397 [ - + ]: 311 : if (tle->resjunk)
8398 : 0 : continue; /* ignore junk entries */
8399 : 311 : colno++;
8400 : :
8401 : : /* This must match colname-choosing logic in get_target_list() */
8402 [ + - + - ]: 311 : if (context->resultDesc && colno <= context->resultDesc->natts)
8403 : 311 : colname = NameStr(TupleDescAttr(context->resultDesc,
8404 : : colno - 1)->attname);
8405 : : else
8406 : 0 : colname = tle->resname;
8407 : :
8408 [ + - + + ]: 311 : if (colname && strcmp(colname, attname) == 0 &&
8409 [ + + ]: 106 : !equal(var, tle->expr))
8410 : : {
8411 : 8 : need_prefix = true;
8412 : 8 : break;
8413 : : }
8414 : : }
8415 : : }
8416 : :
8417 [ + + + + ]: 92547 : if (refname && need_prefix)
8418 : : {
8419 : 48696 : appendStringInfoString(buf, quote_identifier(refname));
8420 : 48696 : appendStringInfoChar(buf, '.');
8421 : : }
8422 [ + + ]: 92547 : if (attname)
8423 : 91867 : appendStringInfoString(buf, quote_identifier(attname));
8424 : : else
8425 : : {
8426 : 680 : appendStringInfoChar(buf, '*');
8427 [ + + ]: 680 : if (istoplevel)
8428 : 56 : appendStringInfo(buf, "::%s",
8429 : : format_type_with_typemod(var->vartype,
8430 : : var->vartypmod));
8431 : : }
8432 : :
8433 : 92547 : return attname;
8434 : : }
8435 : :
8436 : : /*
8437 : : * Deparse a Var which references OUTER_VAR, INNER_VAR, or INDEX_VAR. This
8438 : : * routine is actually a callback for resolve_special_varno, which handles
8439 : : * finding the correct TargetEntry. We get the expression contained in that
8440 : : * TargetEntry and just need to deparse it, a job we can throw back on
8441 : : * get_rule_expr.
8442 : : */
8443 : : static void
8444 : 34660 : get_special_variable(Node *node, deparse_context *context, void *callback_arg)
8445 : : {
8446 : 34660 : StringInfo buf = context->buf;
8447 : :
8448 : : /*
8449 : : * For a non-Var referent, force parentheses because our caller probably
8450 : : * assumed a Var is a simple expression.
8451 : : */
8452 [ + + ]: 34660 : if (!IsA(node, Var))
8453 : 3559 : appendStringInfoChar(buf, '(');
8454 : 34660 : get_rule_expr(node, context, true);
8455 [ + + ]: 34660 : if (!IsA(node, Var))
8456 : 3559 : appendStringInfoChar(buf, ')');
8457 : 34660 : }
8458 : :
8459 : : /*
8460 : : * Chase through plan references to special varnos (OUTER_VAR, INNER_VAR,
8461 : : * INDEX_VAR) until we find a real Var or some kind of non-Var node; then,
8462 : : * invoke the callback provided.
8463 : : */
8464 : : static void
8465 : 97671 : resolve_special_varno(Node *node, deparse_context *context,
8466 : : rsv_callback callback, void *callback_arg)
8467 : : {
8468 : : Var *var;
8469 : : deparse_namespace *dpns;
8470 : :
8471 : : /* This function is recursive, so let's be paranoid. */
8472 : 97671 : check_stack_depth();
8473 : :
8474 : : /* If it's not a Var, invoke the callback. */
8475 [ + + ]: 97671 : if (!IsA(node, Var))
8476 : : {
8477 : 4111 : (*callback) (node, context, callback_arg);
8478 : 4111 : return;
8479 : : }
8480 : :
8481 : : /* Find appropriate nesting depth */
8482 : 93560 : var = (Var *) node;
8483 : 93560 : dpns = (deparse_namespace *) list_nth(context->namespaces,
8484 : 93560 : var->varlevelsup);
8485 : :
8486 : : /*
8487 : : * If varno is special, recurse. (Don't worry about varnosyn; if we're
8488 : : * here, we already decided not to use that.)
8489 : : */
8490 [ + + + - ]: 93560 : if (var->varno == OUTER_VAR && dpns->outer_tlist)
8491 : : {
8492 : : TargetEntry *tle;
8493 : : deparse_namespace save_dpns;
8494 : : Bitmapset *save_appendparents;
8495 : :
8496 : 47596 : tle = get_tle_by_resno(dpns->outer_tlist, var->varattno);
8497 [ - + ]: 47596 : if (!tle)
8498 [ # # ]: 0 : elog(ERROR, "bogus varattno for OUTER_VAR var: %d", var->varattno);
8499 : :
8500 : : /*
8501 : : * If we're descending to the first child of an Append or MergeAppend,
8502 : : * update appendparents. This will affect deparsing of all Vars
8503 : : * appearing within the eventually-resolved subexpression.
8504 : : */
8505 : 47596 : save_appendparents = context->appendparents;
8506 : :
8507 [ + + ]: 47596 : if (IsA(dpns->plan, Append))
8508 : 2991 : context->appendparents = bms_union(context->appendparents,
8509 : 2991 : ((Append *) dpns->plan)->apprelids);
8510 [ + + ]: 44605 : else if (IsA(dpns->plan, MergeAppend))
8511 : 413 : context->appendparents = bms_union(context->appendparents,
8512 : 413 : ((MergeAppend *) dpns->plan)->apprelids);
8513 : :
8514 : 47596 : push_child_plan(dpns, dpns->outer_plan, &save_dpns);
8515 : 47596 : resolve_special_varno((Node *) tle->expr, context,
8516 : : callback, callback_arg);
8517 : 47596 : pop_child_plan(dpns, &save_dpns);
8518 : 47596 : context->appendparents = save_appendparents;
8519 : 47596 : return;
8520 : : }
8521 [ + + + - ]: 45964 : else if (var->varno == INNER_VAR && dpns->inner_tlist)
8522 : : {
8523 : : TargetEntry *tle;
8524 : : deparse_namespace save_dpns;
8525 : :
8526 : 11457 : tle = get_tle_by_resno(dpns->inner_tlist, var->varattno);
8527 [ - + ]: 11457 : if (!tle)
8528 [ # # ]: 0 : elog(ERROR, "bogus varattno for INNER_VAR var: %d", var->varattno);
8529 : :
8530 : 11457 : push_child_plan(dpns, dpns->inner_plan, &save_dpns);
8531 : 11457 : resolve_special_varno((Node *) tle->expr, context,
8532 : : callback, callback_arg);
8533 : 11457 : pop_child_plan(dpns, &save_dpns);
8534 : 11457 : return;
8535 : : }
8536 [ + + + - ]: 34507 : else if (var->varno == INDEX_VAR && dpns->index_tlist)
8537 : : {
8538 : : TargetEntry *tle;
8539 : :
8540 : 3406 : tle = get_tle_by_resno(dpns->index_tlist, var->varattno);
8541 [ - + ]: 3406 : if (!tle)
8542 [ # # ]: 0 : elog(ERROR, "bogus varattno for INDEX_VAR var: %d", var->varattno);
8543 : :
8544 : 3406 : resolve_special_varno((Node *) tle->expr, context,
8545 : : callback, callback_arg);
8546 : 3406 : return;
8547 : : }
8548 [ + - - + ]: 31101 : else if (var->varno < 1 || var->varno > list_length(dpns->rtable))
8549 [ # # ]: 0 : elog(ERROR, "bogus varno: %d", var->varno);
8550 : :
8551 : : /* Not special. Just invoke the callback. */
8552 : 31101 : (*callback) (node, context, callback_arg);
8553 : : }
8554 : :
8555 : : /*
8556 : : * Get the name of a field of an expression of composite type. The
8557 : : * expression is usually a Var, but we handle other cases too.
8558 : : *
8559 : : * levelsup is an extra offset to interpret the Var's varlevelsup correctly.
8560 : : *
8561 : : * This is fairly straightforward when the expression has a named composite
8562 : : * type; we need only look up the type in the catalogs. However, the type
8563 : : * could also be RECORD. Since no actual table or view column is allowed to
8564 : : * have type RECORD, a Var of type RECORD must refer to a JOIN or FUNCTION RTE
8565 : : * or to a subquery output. We drill down to find the ultimate defining
8566 : : * expression and attempt to infer the field name from it. We ereport if we
8567 : : * can't determine the name.
8568 : : *
8569 : : * Similarly, a PARAM of type RECORD has to refer to some expression of
8570 : : * a determinable composite type.
8571 : : */
8572 : : static const char *
8573 : 1050 : get_name_for_var_field(Var *var, int fieldno,
8574 : : int levelsup, deparse_context *context)
8575 : : {
8576 : : RangeTblEntry *rte;
8577 : : AttrNumber attnum;
8578 : : int netlevelsup;
8579 : : deparse_namespace *dpns;
8580 : : int varno;
8581 : : AttrNumber varattno;
8582 : : TupleDesc tupleDesc;
8583 : : Node *expr;
8584 : :
8585 : : /*
8586 : : * If it's a RowExpr that was expanded from a whole-row Var, use the
8587 : : * column names attached to it. (We could let get_expr_result_tupdesc()
8588 : : * handle this, but it's much cheaper to just pull out the name we need.)
8589 : : */
8590 [ + + ]: 1050 : if (IsA(var, RowExpr))
8591 : : {
8592 : 24 : RowExpr *r = (RowExpr *) var;
8593 : :
8594 [ + - + - ]: 24 : if (fieldno > 0 && fieldno <= list_length(r->colnames))
8595 : 24 : return strVal(list_nth(r->colnames, fieldno - 1));
8596 : : }
8597 : :
8598 : : /*
8599 : : * If it's a Param of type RECORD, try to find what the Param refers to.
8600 : : */
8601 [ + + ]: 1026 : if (IsA(var, Param))
8602 : : {
8603 : 12 : Param *param = (Param *) var;
8604 : : ListCell *ancestor_cell;
8605 : :
8606 : 12 : expr = find_param_referent(param, context, &dpns, &ancestor_cell);
8607 [ + - ]: 12 : if (expr)
8608 : : {
8609 : : /* Found a match, so recurse to decipher the field name */
8610 : : deparse_namespace save_dpns;
8611 : : const char *result;
8612 : :
8613 : 12 : push_ancestor_plan(dpns, ancestor_cell, &save_dpns);
8614 : 12 : result = get_name_for_var_field((Var *) expr, fieldno,
8615 : : 0, context);
8616 : 12 : pop_ancestor_plan(dpns, &save_dpns);
8617 : 12 : return result;
8618 : : }
8619 : : }
8620 : :
8621 : : /*
8622 : : * If it's a Var of type RECORD, we have to find what the Var refers to;
8623 : : * if not, we can use get_expr_result_tupdesc().
8624 : : */
8625 [ + + ]: 1014 : if (!IsA(var, Var) ||
8626 [ + + ]: 961 : var->vartype != RECORDOID)
8627 : : {
8628 : 850 : tupleDesc = get_expr_result_tupdesc((Node *) var, false);
8629 : : /* Got the tupdesc, so we can extract the field name */
8630 : : Assert(fieldno >= 1 && fieldno <= tupleDesc->natts);
8631 : 850 : return NameStr(TupleDescAttr(tupleDesc, fieldno - 1)->attname);
8632 : : }
8633 : :
8634 : : /* Find appropriate nesting depth */
8635 : 164 : netlevelsup = var->varlevelsup + levelsup;
8636 [ - + ]: 164 : if (netlevelsup >= list_length(context->namespaces))
8637 [ # # ]: 0 : elog(ERROR, "bogus varlevelsup: %d offset %d",
8638 : : var->varlevelsup, levelsup);
8639 : 164 : dpns = (deparse_namespace *) list_nth(context->namespaces,
8640 : : netlevelsup);
8641 : :
8642 : : /*
8643 : : * If we have a syntactic referent for the Var, and we're working from a
8644 : : * parse tree, prefer to use the syntactic referent. Otherwise, fall back
8645 : : * on the semantic referent. (See comments in get_variable().)
8646 : : */
8647 [ + + + + ]: 164 : if (var->varnosyn > 0 && dpns->plan == NULL)
8648 : : {
8649 : 64 : varno = var->varnosyn;
8650 : 64 : varattno = var->varattnosyn;
8651 : : }
8652 : : else
8653 : : {
8654 : 100 : varno = var->varno;
8655 : 100 : varattno = var->varattno;
8656 : : }
8657 : :
8658 : : /*
8659 : : * Try to find the relevant RTE in this rtable. In a plan tree, it's
8660 : : * likely that varno is OUTER_VAR or INNER_VAR, in which case we must dig
8661 : : * down into the subplans, or INDEX_VAR, which is resolved similarly.
8662 : : *
8663 : : * Note: unlike get_variable and resolve_special_varno, we need not worry
8664 : : * about inheritance mapping: a child Var should have the same datatype as
8665 : : * its parent, and here we're really only interested in the Var's type.
8666 : : */
8667 [ + + + - ]: 164 : if (varno >= 1 && varno <= list_length(dpns->rtable))
8668 : : {
8669 : 112 : rte = rt_fetch(varno, dpns->rtable);
8670 : 112 : attnum = varattno;
8671 : : }
8672 [ + + + - ]: 52 : else if (varno == OUTER_VAR && dpns->outer_tlist)
8673 : : {
8674 : : TargetEntry *tle;
8675 : : deparse_namespace save_dpns;
8676 : : const char *result;
8677 : :
8678 : 40 : tle = get_tle_by_resno(dpns->outer_tlist, varattno);
8679 [ - + ]: 40 : if (!tle)
8680 [ # # ]: 0 : elog(ERROR, "bogus varattno for OUTER_VAR var: %d", varattno);
8681 : :
8682 : : Assert(netlevelsup == 0);
8683 : 40 : push_child_plan(dpns, dpns->outer_plan, &save_dpns);
8684 : :
8685 : 40 : result = get_name_for_var_field((Var *) tle->expr, fieldno,
8686 : : levelsup, context);
8687 : :
8688 : 40 : pop_child_plan(dpns, &save_dpns);
8689 : 40 : return result;
8690 : : }
8691 [ + - + - ]: 12 : else if (varno == INNER_VAR && dpns->inner_tlist)
8692 : : {
8693 : : TargetEntry *tle;
8694 : : deparse_namespace save_dpns;
8695 : : const char *result;
8696 : :
8697 : 12 : tle = get_tle_by_resno(dpns->inner_tlist, varattno);
8698 [ - + ]: 12 : if (!tle)
8699 [ # # ]: 0 : elog(ERROR, "bogus varattno for INNER_VAR var: %d", varattno);
8700 : :
8701 : : Assert(netlevelsup == 0);
8702 : 12 : push_child_plan(dpns, dpns->inner_plan, &save_dpns);
8703 : :
8704 : 12 : result = get_name_for_var_field((Var *) tle->expr, fieldno,
8705 : : levelsup, context);
8706 : :
8707 : 12 : pop_child_plan(dpns, &save_dpns);
8708 : 12 : return result;
8709 : : }
8710 [ # # # # ]: 0 : else if (varno == INDEX_VAR && dpns->index_tlist)
8711 : : {
8712 : : TargetEntry *tle;
8713 : : const char *result;
8714 : :
8715 : 0 : tle = get_tle_by_resno(dpns->index_tlist, varattno);
8716 [ # # ]: 0 : if (!tle)
8717 [ # # ]: 0 : elog(ERROR, "bogus varattno for INDEX_VAR var: %d", varattno);
8718 : :
8719 : : Assert(netlevelsup == 0);
8720 : :
8721 : 0 : result = get_name_for_var_field((Var *) tle->expr, fieldno,
8722 : : levelsup, context);
8723 : :
8724 : 0 : return result;
8725 : : }
8726 : : else
8727 : : {
8728 [ # # ]: 0 : elog(ERROR, "bogus varno: %d", varno);
8729 : : return NULL; /* keep compiler quiet */
8730 : : }
8731 : :
8732 [ + + ]: 112 : if (attnum == InvalidAttrNumber)
8733 : : {
8734 : : /* Var is whole-row reference to RTE, so select the right field */
8735 : 16 : return get_rte_attribute_name(rte, fieldno);
8736 : : }
8737 : :
8738 : : /*
8739 : : * This part has essentially the same logic as the parser's
8740 : : * expandRecordVariable() function, but we are dealing with a different
8741 : : * representation of the input context, and we only need one field name
8742 : : * not a TupleDesc. Also, we need special cases for finding subquery and
8743 : : * CTE subplans when deparsing Plan trees.
8744 : : */
8745 : 96 : expr = (Node *) var; /* default if we can't drill down */
8746 : :
8747 [ - + - - : 96 : switch (rte->rtekind)
+ - - ]
8748 : : {
8749 : 0 : case RTE_RELATION:
8750 : : case RTE_VALUES:
8751 : : case RTE_NAMEDTUPLESTORE:
8752 : : case RTE_GRAPH_TABLE:
8753 : : case RTE_RESULT:
8754 : :
8755 : : /*
8756 : : * This case should not occur: a column of a table, values list,
8757 : : * or ENR shouldn't have type RECORD. Fall through and fail (most
8758 : : * likely) at the bottom.
8759 : : */
8760 : 0 : break;
8761 : 48 : case RTE_SUBQUERY:
8762 : : /* Subselect-in-FROM: examine sub-select's output expr */
8763 : : {
8764 [ + + ]: 48 : if (rte->subquery)
8765 : : {
8766 : 28 : TargetEntry *ste = get_tle_by_resno(rte->subquery->targetList,
8767 : : attnum);
8768 : :
8769 [ + - - + ]: 28 : if (ste == NULL || ste->resjunk)
8770 [ # # ]: 0 : elog(ERROR, "subquery %s does not have attribute %d",
8771 : : rte->eref->aliasname, attnum);
8772 : 28 : expr = (Node *) ste->expr;
8773 [ + + ]: 28 : if (IsA(expr, Var))
8774 : : {
8775 : : /*
8776 : : * Recurse into the sub-select to see what its Var
8777 : : * refers to. We have to build an additional level of
8778 : : * namespace to keep in step with varlevelsup in the
8779 : : * subselect; furthermore, the subquery RTE might be
8780 : : * from an outer query level, in which case the
8781 : : * namespace for the subselect must have that outer
8782 : : * level as parent namespace.
8783 : : */
8784 : 12 : List *save_nslist = context->namespaces;
8785 : : List *parent_namespaces;
8786 : : deparse_namespace mydpns;
8787 : : const char *result;
8788 : :
8789 : 12 : parent_namespaces = list_copy_tail(context->namespaces,
8790 : : netlevelsup);
8791 : :
8792 : 12 : set_deparse_for_query(&mydpns, rte->subquery,
8793 : : parent_namespaces);
8794 : :
8795 : 12 : context->namespaces = lcons(&mydpns, parent_namespaces);
8796 : :
8797 : 12 : result = get_name_for_var_field((Var *) expr, fieldno,
8798 : : 0, context);
8799 : :
8800 : 12 : context->namespaces = save_nslist;
8801 : :
8802 : 12 : return result;
8803 : : }
8804 : : /* else fall through to inspect the expression */
8805 : : }
8806 : : else
8807 : : {
8808 : : /*
8809 : : * We're deparsing a Plan tree so we don't have complete
8810 : : * RTE entries (in particular, rte->subquery is NULL). But
8811 : : * the only place we'd normally see a Var directly
8812 : : * referencing a SUBQUERY RTE is in a SubqueryScan plan
8813 : : * node, and we can look into the child plan's tlist
8814 : : * instead. An exception occurs if the subquery was
8815 : : * proven empty and optimized away: then we'd find such a
8816 : : * Var in a childless Result node, and there's nothing in
8817 : : * the plan tree that would let us figure out what it had
8818 : : * originally referenced. In that case, fall back on
8819 : : * printing "fN", analogously to the default column names
8820 : : * for RowExprs.
8821 : : */
8822 : : TargetEntry *tle;
8823 : : deparse_namespace save_dpns;
8824 : : const char *result;
8825 : :
8826 [ + + ]: 20 : if (!dpns->inner_plan)
8827 : : {
8828 : 8 : char *dummy_name = palloc(32);
8829 : :
8830 : : Assert(dpns->plan && IsA(dpns->plan, Result));
8831 : 8 : snprintf(dummy_name, 32, "f%d", fieldno);
8832 : 8 : return dummy_name;
8833 : : }
8834 : : Assert(dpns->plan && IsA(dpns->plan, SubqueryScan));
8835 : :
8836 : 12 : tle = get_tle_by_resno(dpns->inner_tlist, attnum);
8837 [ - + ]: 12 : if (!tle)
8838 [ # # ]: 0 : elog(ERROR, "bogus varattno for subquery var: %d",
8839 : : attnum);
8840 : : Assert(netlevelsup == 0);
8841 : 12 : push_child_plan(dpns, dpns->inner_plan, &save_dpns);
8842 : :
8843 : 12 : result = get_name_for_var_field((Var *) tle->expr, fieldno,
8844 : : levelsup, context);
8845 : :
8846 : 12 : pop_child_plan(dpns, &save_dpns);
8847 : 12 : return result;
8848 : : }
8849 : : }
8850 : 16 : break;
8851 : 0 : case RTE_JOIN:
8852 : : /* Join RTE --- recursively inspect the alias variable */
8853 [ # # ]: 0 : if (rte->joinaliasvars == NIL)
8854 [ # # ]: 0 : elog(ERROR, "cannot decompile join alias var in plan tree");
8855 : : Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
8856 : 0 : expr = (Node *) list_nth(rte->joinaliasvars, attnum - 1);
8857 : : Assert(expr != NULL);
8858 : : /* we intentionally don't strip implicit coercions here */
8859 [ # # ]: 0 : if (IsA(expr, Var))
8860 : 0 : return get_name_for_var_field((Var *) expr, fieldno,
8861 : 0 : var->varlevelsup + levelsup,
8862 : : context);
8863 : : /* else fall through to inspect the expression */
8864 : 0 : break;
8865 : 0 : case RTE_FUNCTION:
8866 : : case RTE_TABLEFUNC:
8867 : :
8868 : : /*
8869 : : * We couldn't get here unless a function is declared with one of
8870 : : * its result columns as RECORD, which is not allowed.
8871 : : */
8872 : 0 : break;
8873 : 48 : case RTE_CTE:
8874 : : /* CTE reference: examine subquery's output expr */
8875 : : {
8876 : 48 : CommonTableExpr *cte = NULL;
8877 : : Index ctelevelsup;
8878 : : ListCell *lc;
8879 : :
8880 : : /*
8881 : : * Try to find the referenced CTE using the namespace stack.
8882 : : */
8883 : 48 : ctelevelsup = rte->ctelevelsup + netlevelsup;
8884 [ + + ]: 48 : if (ctelevelsup >= list_length(context->namespaces))
8885 : 8 : lc = NULL;
8886 : : else
8887 : : {
8888 : : deparse_namespace *ctedpns;
8889 : :
8890 : : ctedpns = (deparse_namespace *)
8891 : 40 : list_nth(context->namespaces, ctelevelsup);
8892 [ + + + - : 44 : foreach(lc, ctedpns->ctes)
+ + ]
8893 : : {
8894 : 24 : cte = (CommonTableExpr *) lfirst(lc);
8895 [ + + ]: 24 : if (strcmp(cte->ctename, rte->ctename) == 0)
8896 : 20 : break;
8897 : : }
8898 : : }
8899 [ + + ]: 48 : if (lc != NULL)
8900 : : {
8901 : 20 : Query *ctequery = (Query *) cte->ctequery;
8902 [ + - ]: 20 : TargetEntry *ste = get_tle_by_resno(GetCTETargetList(cte),
8903 : : attnum);
8904 : :
8905 [ + - - + ]: 20 : if (ste == NULL || ste->resjunk)
8906 [ # # ]: 0 : elog(ERROR, "CTE %s does not have attribute %d",
8907 : : rte->eref->aliasname, attnum);
8908 : 20 : expr = (Node *) ste->expr;
8909 [ + + ]: 20 : if (IsA(expr, Var))
8910 : : {
8911 : : /*
8912 : : * Recurse into the CTE to see what its Var refers to.
8913 : : * We have to build an additional level of namespace
8914 : : * to keep in step with varlevelsup in the CTE;
8915 : : * furthermore it could be an outer CTE (compare
8916 : : * SUBQUERY case above).
8917 : : */
8918 : 12 : List *save_nslist = context->namespaces;
8919 : : List *parent_namespaces;
8920 : : deparse_namespace mydpns;
8921 : : const char *result;
8922 : :
8923 : 12 : parent_namespaces = list_copy_tail(context->namespaces,
8924 : : ctelevelsup);
8925 : :
8926 : 12 : set_deparse_for_query(&mydpns, ctequery,
8927 : : parent_namespaces);
8928 : :
8929 : 12 : context->namespaces = lcons(&mydpns, parent_namespaces);
8930 : :
8931 : 12 : result = get_name_for_var_field((Var *) expr, fieldno,
8932 : : 0, context);
8933 : :
8934 : 12 : context->namespaces = save_nslist;
8935 : :
8936 : 12 : return result;
8937 : : }
8938 : : /* else fall through to inspect the expression */
8939 : : }
8940 : : else
8941 : : {
8942 : : /*
8943 : : * We're deparsing a Plan tree so we don't have a CTE
8944 : : * list. But the only places we'd normally see a Var
8945 : : * directly referencing a CTE RTE are in CteScan or
8946 : : * WorkTableScan plan nodes. For those cases,
8947 : : * set_deparse_plan arranged for dpns->inner_plan to be
8948 : : * the plan node that emits the CTE or RecursiveUnion
8949 : : * result, and we can look at its tlist instead. As
8950 : : * above, this can fail if the CTE has been proven empty,
8951 : : * in which case fall back to "fN".
8952 : : */
8953 : : TargetEntry *tle;
8954 : : deparse_namespace save_dpns;
8955 : : const char *result;
8956 : :
8957 [ + + ]: 28 : if (!dpns->inner_plan)
8958 : : {
8959 : 4 : char *dummy_name = palloc(32);
8960 : :
8961 : : Assert(dpns->plan && IsA(dpns->plan, Result));
8962 : 4 : snprintf(dummy_name, 32, "f%d", fieldno);
8963 : 4 : return dummy_name;
8964 : : }
8965 : : Assert(dpns->plan && (IsA(dpns->plan, CteScan) ||
8966 : : IsA(dpns->plan, WorkTableScan)));
8967 : :
8968 : 24 : tle = get_tle_by_resno(dpns->inner_tlist, attnum);
8969 [ - + ]: 24 : if (!tle)
8970 [ # # ]: 0 : elog(ERROR, "bogus varattno for subquery var: %d",
8971 : : attnum);
8972 : : Assert(netlevelsup == 0);
8973 : 24 : push_child_plan(dpns, dpns->inner_plan, &save_dpns);
8974 : :
8975 : 24 : result = get_name_for_var_field((Var *) tle->expr, fieldno,
8976 : : levelsup, context);
8977 : :
8978 : 24 : pop_child_plan(dpns, &save_dpns);
8979 : 24 : return result;
8980 : : }
8981 : : }
8982 : 8 : break;
8983 : 0 : case RTE_GROUP:
8984 : :
8985 : : /*
8986 : : * We couldn't get here: any Vars that reference the RTE_GROUP RTE
8987 : : * should have been replaced with the underlying grouping
8988 : : * expressions.
8989 : : */
8990 : 0 : break;
8991 : : }
8992 : :
8993 : : /*
8994 : : * We now have an expression we can't expand any more, so see if
8995 : : * get_expr_result_tupdesc() can do anything with it.
8996 : : */
8997 : 24 : tupleDesc = get_expr_result_tupdesc(expr, false);
8998 : : /* Got the tupdesc, so we can extract the field name */
8999 : : Assert(fieldno >= 1 && fieldno <= tupleDesc->natts);
9000 : 24 : return NameStr(TupleDescAttr(tupleDesc, fieldno - 1)->attname);
9001 : : }
9002 : :
9003 : : /*
9004 : : * Try to find the referenced expression for a PARAM_EXEC Param that might
9005 : : * reference a parameter supplied by an upper NestLoop or SubPlan plan node.
9006 : : *
9007 : : * If successful, return the expression and set *dpns_p and *ancestor_cell_p
9008 : : * appropriately for calling push_ancestor_plan(). If no referent can be
9009 : : * found, return NULL.
9010 : : */
9011 : : static Node *
9012 : 4810 : find_param_referent(Param *param, deparse_context *context,
9013 : : deparse_namespace **dpns_p, ListCell **ancestor_cell_p)
9014 : : {
9015 : : /* Initialize output parameters to prevent compiler warnings */
9016 : 4810 : *dpns_p = NULL;
9017 : 4810 : *ancestor_cell_p = NULL;
9018 : :
9019 : : /*
9020 : : * If it's a PARAM_EXEC parameter, look for a matching NestLoopParam or
9021 : : * SubPlan argument. This will necessarily be in some ancestor of the
9022 : : * current expression's Plan node.
9023 : : */
9024 [ + + ]: 4810 : if (param->paramkind == PARAM_EXEC)
9025 : : {
9026 : : deparse_namespace *dpns;
9027 : : Plan *child_plan;
9028 : : ListCell *lc;
9029 : :
9030 : 4221 : dpns = (deparse_namespace *) linitial(context->namespaces);
9031 : 4221 : child_plan = dpns->plan;
9032 : :
9033 [ + + + + : 7492 : foreach(lc, dpns->ancestors)
+ + ]
9034 : : {
9035 : 6372 : Node *ancestor = (Node *) lfirst(lc);
9036 : : ListCell *lc2;
9037 : :
9038 : : /*
9039 : : * NestLoops transmit params to their inner child only.
9040 : : */
9041 [ + + ]: 6372 : if (IsA(ancestor, NestLoop) &&
9042 [ + + ]: 2895 : child_plan == innerPlan(ancestor))
9043 : : {
9044 : 2773 : NestLoop *nl = (NestLoop *) ancestor;
9045 : :
9046 [ + + + + : 3440 : foreach(lc2, nl->nestParams)
+ + ]
9047 : : {
9048 : 3323 : NestLoopParam *nlp = (NestLoopParam *) lfirst(lc2);
9049 : :
9050 [ + + ]: 3323 : if (nlp->paramno == param->paramid)
9051 : : {
9052 : : /* Found a match, so return it */
9053 : 2656 : *dpns_p = dpns;
9054 : 2656 : *ancestor_cell_p = lc;
9055 : 2656 : return (Node *) nlp->paramval;
9056 : : }
9057 : : }
9058 : : }
9059 : :
9060 : : /*
9061 : : * If ancestor is a SubPlan, check the arguments it provides.
9062 : : */
9063 [ + + ]: 3716 : if (IsA(ancestor, SubPlan))
9064 : 293 : {
9065 : 738 : SubPlan *subplan = (SubPlan *) ancestor;
9066 : : ListCell *lc3;
9067 : : ListCell *lc4;
9068 : :
9069 [ + + + + : 961 : forboth(lc3, subplan->parParam, lc4, subplan->args)
+ + + + +
+ + - +
+ ]
9070 : : {
9071 : 668 : int paramid = lfirst_int(lc3);
9072 : 668 : Node *arg = (Node *) lfirst(lc4);
9073 : :
9074 [ + + ]: 668 : if (paramid == param->paramid)
9075 : : {
9076 : : /*
9077 : : * Found a match, so return it. But, since Vars in
9078 : : * the arg are to be evaluated in the surrounding
9079 : : * context, we have to point to the next ancestor item
9080 : : * that is *not* a SubPlan.
9081 : : */
9082 : : ListCell *rest;
9083 : :
9084 [ + - + - : 445 : for_each_cell(rest, dpns->ancestors,
+ - ]
9085 : : lnext(dpns->ancestors, lc))
9086 : : {
9087 : 445 : Node *ancestor2 = (Node *) lfirst(rest);
9088 : :
9089 [ + - ]: 445 : if (!IsA(ancestor2, SubPlan))
9090 : : {
9091 : 445 : *dpns_p = dpns;
9092 : 445 : *ancestor_cell_p = rest;
9093 : 445 : return arg;
9094 : : }
9095 : : }
9096 [ # # ]: 0 : elog(ERROR, "SubPlan cannot be outermost ancestor");
9097 : : }
9098 : : }
9099 : :
9100 : : /* SubPlan isn't a kind of Plan, so skip the rest */
9101 : 293 : continue;
9102 : : }
9103 : :
9104 : : /*
9105 : : * We need not consider the ancestor's initPlan list, since
9106 : : * initplans never have any parParams.
9107 : : */
9108 : :
9109 : : /* No luck, crawl up to next ancestor */
9110 : 2978 : child_plan = (Plan *) ancestor;
9111 : : }
9112 : : }
9113 : :
9114 : : /* No referent found */
9115 : 1709 : return NULL;
9116 : : }
9117 : :
9118 : : /*
9119 : : * Try to find a subplan/initplan that emits the value for a PARAM_EXEC Param.
9120 : : *
9121 : : * If successful, return the generating subplan/initplan and set *column_p
9122 : : * to the subplan's 0-based output column number.
9123 : : * Otherwise, return NULL.
9124 : : */
9125 : : static SubPlan *
9126 : 1709 : find_param_generator(Param *param, deparse_context *context, int *column_p)
9127 : : {
9128 : : /* Initialize output parameter to prevent compiler warnings */
9129 : 1709 : *column_p = 0;
9130 : :
9131 : : /*
9132 : : * If it's a PARAM_EXEC parameter, search the current plan node as well as
9133 : : * ancestor nodes looking for a subplan or initplan that emits the value
9134 : : * for the Param. It could appear in the setParams of an initplan or
9135 : : * MULTIEXPR_SUBLINK subplan, or in the paramIds of an ancestral SubPlan.
9136 : : */
9137 [ + + ]: 1709 : if (param->paramkind == PARAM_EXEC)
9138 : : {
9139 : : SubPlan *result;
9140 : : deparse_namespace *dpns;
9141 : : ListCell *lc;
9142 : :
9143 : 1120 : dpns = (deparse_namespace *) linitial(context->namespaces);
9144 : :
9145 : : /* First check the innermost plan node's initplans */
9146 : 1120 : result = find_param_generator_initplan(param, dpns->plan, column_p);
9147 [ + + ]: 1120 : if (result)
9148 : 297 : return result;
9149 : :
9150 : : /*
9151 : : * The plan's targetlist might contain MULTIEXPR_SUBLINK SubPlans,
9152 : : * which can be referenced by Params elsewhere in the targetlist.
9153 : : * (Such Params should always be in the same targetlist, so there's no
9154 : : * need to do this work at upper plan nodes.)
9155 : : */
9156 [ + + + + : 4135 : foreach_node(TargetEntry, tle, dpns->plan->targetlist)
+ + ]
9157 : : {
9158 [ + - + + ]: 2557 : if (tle->expr && IsA(tle->expr, SubPlan))
9159 : : {
9160 : 66 : SubPlan *subplan = (SubPlan *) tle->expr;
9161 : :
9162 [ + + ]: 66 : if (subplan->subLinkType == MULTIEXPR_SUBLINK)
9163 : : {
9164 [ + - + - : 51 : foreach_int(paramid, subplan->setParam)
+ - ]
9165 : : {
9166 [ + + ]: 51 : if (paramid == param->paramid)
9167 : : {
9168 : : /* Found a match, so return it. */
9169 : 34 : *column_p = foreach_current_index(paramid);
9170 : 34 : return subplan;
9171 : : }
9172 : : }
9173 : : }
9174 : : }
9175 : : }
9176 : :
9177 : : /* No luck, so check the ancestor nodes */
9178 [ + - + - : 1024 : foreach(lc, dpns->ancestors)
+ - ]
9179 : : {
9180 : 1024 : Node *ancestor = (Node *) lfirst(lc);
9181 : :
9182 : : /*
9183 : : * If ancestor is a SubPlan, check the paramIds it provides.
9184 : : */
9185 [ + + ]: 1024 : if (IsA(ancestor, SubPlan))
9186 : 0 : {
9187 : 197 : SubPlan *subplan = (SubPlan *) ancestor;
9188 : :
9189 [ + - + - : 222 : foreach_int(paramid, subplan->paramIds)
+ - ]
9190 : : {
9191 [ + + ]: 222 : if (paramid == param->paramid)
9192 : : {
9193 : : /* Found a match, so return it. */
9194 : 197 : *column_p = foreach_current_index(paramid);
9195 : 197 : return subplan;
9196 : : }
9197 : : }
9198 : :
9199 : : /* SubPlan isn't a kind of Plan, so skip the rest */
9200 : 0 : continue;
9201 : : }
9202 : :
9203 : : /*
9204 : : * Otherwise, it's some kind of Plan node, so check its initplans.
9205 : : */
9206 : 827 : result = find_param_generator_initplan(param, (Plan *) ancestor,
9207 : : column_p);
9208 [ + + ]: 827 : if (result)
9209 : 592 : return result;
9210 : :
9211 : : /* No luck, crawl up to next ancestor */
9212 : : }
9213 : : }
9214 : :
9215 : : /* No generator found */
9216 : 589 : return NULL;
9217 : : }
9218 : :
9219 : : /*
9220 : : * Subroutine for find_param_generator: search one Plan node's initplans
9221 : : */
9222 : : static SubPlan *
9223 : 1947 : find_param_generator_initplan(Param *param, Plan *plan, int *column_p)
9224 : : {
9225 [ + + + - : 3097 : foreach_node(SubPlan, subplan, plan->initPlan)
+ + ]
9226 : : {
9227 [ + - + + : 1169 : foreach_int(paramid, subplan->setParam)
+ + ]
9228 : : {
9229 [ + + ]: 985 : if (paramid == param->paramid)
9230 : : {
9231 : : /* Found a match, so return it. */
9232 : 889 : *column_p = foreach_current_index(paramid);
9233 : 889 : return subplan;
9234 : : }
9235 : : }
9236 : : }
9237 : 1058 : return NULL;
9238 : : }
9239 : :
9240 : : /*
9241 : : * Display a Param appropriately.
9242 : : */
9243 : : static void
9244 : 4798 : get_parameter(Param *param, deparse_context *context)
9245 : : {
9246 : : Node *expr;
9247 : : deparse_namespace *dpns;
9248 : : ListCell *ancestor_cell;
9249 : : SubPlan *subplan;
9250 : : int column;
9251 : :
9252 : : /*
9253 : : * If it's a PARAM_EXEC parameter, try to locate the expression from which
9254 : : * the parameter was computed. This stanza handles only cases in which
9255 : : * the Param represents an input to the subplan we are currently in.
9256 : : */
9257 : 4798 : expr = find_param_referent(param, context, &dpns, &ancestor_cell);
9258 [ + + ]: 4798 : if (expr)
9259 : : {
9260 : : /* Found a match, so print it */
9261 : : deparse_namespace save_dpns;
9262 : : bool save_varprefix;
9263 : : bool need_paren;
9264 : :
9265 : : /* Switch attention to the ancestor plan node */
9266 : 3089 : push_ancestor_plan(dpns, ancestor_cell, &save_dpns);
9267 : :
9268 : : /*
9269 : : * Force prefixing of Vars, since they won't belong to the relation
9270 : : * being scanned in the original plan node.
9271 : : */
9272 : 3089 : save_varprefix = context->varprefix;
9273 : 3089 : context->varprefix = true;
9274 : :
9275 : : /*
9276 : : * A Param's expansion is typically a Var, Aggref, GroupingFunc, or
9277 : : * upper-level Param, which wouldn't need extra parentheses.
9278 : : * Otherwise, insert parens to ensure the expression looks atomic.
9279 : : */
9280 [ + + ]: 3105 : need_paren = !(IsA(expr, Var) ||
9281 [ + + ]: 16 : IsA(expr, Aggref) ||
9282 [ + + ]: 12 : IsA(expr, GroupingFunc) ||
9283 [ - + ]: 8 : IsA(expr, Param));
9284 [ - + ]: 3089 : if (need_paren)
9285 : 0 : appendStringInfoChar(context->buf, '(');
9286 : :
9287 : 3089 : get_rule_expr(expr, context, false);
9288 : :
9289 [ - + ]: 3089 : if (need_paren)
9290 : 0 : appendStringInfoChar(context->buf, ')');
9291 : :
9292 : 3089 : context->varprefix = save_varprefix;
9293 : :
9294 : 3089 : pop_ancestor_plan(dpns, &save_dpns);
9295 : :
9296 : 3089 : return;
9297 : : }
9298 : :
9299 : : /*
9300 : : * Alternatively, maybe it's a subplan output, which we print as a
9301 : : * reference to the subplan. (We could drill down into the subplan and
9302 : : * print the relevant targetlist expression, but that has been deemed too
9303 : : * confusing since it would violate normal SQL scope rules. Also, we're
9304 : : * relying on this reference to show that the testexpr containing the
9305 : : * Param has anything to do with that subplan at all.)
9306 : : */
9307 : 1709 : subplan = find_param_generator(param, context, &column);
9308 [ + + ]: 1709 : if (subplan)
9309 : : {
9310 : : const char *nameprefix;
9311 : :
9312 [ + + ]: 1120 : if (subplan->isInitPlan)
9313 : 889 : nameprefix = "InitPlan ";
9314 : : else
9315 : 231 : nameprefix = "SubPlan ";
9316 : :
9317 : 1120 : appendStringInfo(context->buf, "(%s%s%s).col%d",
9318 [ + + ]: 1120 : subplan->useHashTable ? "hashed " : "",
9319 : : nameprefix,
9320 : : subplan->plan_name, column + 1);
9321 : :
9322 : 1120 : return;
9323 : : }
9324 : :
9325 : : /*
9326 : : * If it's an external parameter, see if the outermost namespace provides
9327 : : * function argument names.
9328 : : */
9329 [ + - + - ]: 589 : if (param->paramkind == PARAM_EXTERN && context->namespaces != NIL)
9330 : : {
9331 : 589 : dpns = llast(context->namespaces);
9332 [ + + ]: 589 : if (dpns->argnames &&
9333 [ + - ]: 45 : param->paramid > 0 &&
9334 [ + - ]: 45 : param->paramid <= dpns->numargs)
9335 : : {
9336 : 45 : char *argname = dpns->argnames[param->paramid - 1];
9337 : :
9338 [ + - ]: 45 : if (argname)
9339 : : {
9340 : 45 : bool should_qualify = false;
9341 : : ListCell *lc;
9342 : :
9343 : : /*
9344 : : * Qualify the parameter name if there are any other deparse
9345 : : * namespaces with range tables. This avoids qualifying in
9346 : : * trivial cases like "RETURN a + b", but makes it safe in all
9347 : : * other cases.
9348 : : */
9349 [ + - + + : 103 : foreach(lc, context->namespaces)
+ + ]
9350 : : {
9351 : 78 : deparse_namespace *depns = lfirst(lc);
9352 : :
9353 [ + + ]: 78 : if (depns->rtable_names != NIL)
9354 : : {
9355 : 20 : should_qualify = true;
9356 : 20 : break;
9357 : : }
9358 : : }
9359 [ + + ]: 45 : if (should_qualify)
9360 : : {
9361 : 20 : appendStringInfoString(context->buf, quote_identifier(dpns->funcname));
9362 : 20 : appendStringInfoChar(context->buf, '.');
9363 : : }
9364 : :
9365 : 45 : appendStringInfoString(context->buf, quote_identifier(argname));
9366 : 45 : return;
9367 : : }
9368 : : }
9369 : : }
9370 : :
9371 : : /*
9372 : : * Not PARAM_EXEC, or couldn't find referent: just print $N.
9373 : : *
9374 : : * It's a bug if we get here for anything except PARAM_EXTERN Params, but
9375 : : * in production builds printing $N seems more useful than failing.
9376 : : */
9377 : : Assert(param->paramkind == PARAM_EXTERN);
9378 : :
9379 : 544 : appendStringInfo(context->buf, "$%d", param->paramid);
9380 : : }
9381 : :
9382 : : /*
9383 : : * get_simple_binary_op_name
9384 : : *
9385 : : * helper function for isSimpleNode
9386 : : * will return single char binary operator name, or NULL if it's not
9387 : : */
9388 : : static const char *
9389 : 100 : get_simple_binary_op_name(OpExpr *expr)
9390 : : {
9391 : 100 : List *args = expr->args;
9392 : :
9393 [ + - ]: 100 : if (list_length(args) == 2)
9394 : : {
9395 : : /* binary operator */
9396 : 100 : Node *arg1 = (Node *) linitial(args);
9397 : 100 : Node *arg2 = (Node *) lsecond(args);
9398 : : const char *op;
9399 : :
9400 : 100 : op = generate_operator_name(expr->opno, exprType(arg1), exprType(arg2));
9401 [ + - ]: 100 : if (strlen(op) == 1)
9402 : 100 : return op;
9403 : : }
9404 : 0 : return NULL;
9405 : : }
9406 : :
9407 : :
9408 : : /*
9409 : : * isSimpleNode - check if given node is simple (doesn't need parenthesizing)
9410 : : *
9411 : : * true : simple in the context of parent node's type
9412 : : * false : not simple
9413 : : */
9414 : : static bool
9415 : 3973 : isSimpleNode(Node *node, Node *parentNode, int prettyFlags)
9416 : : {
9417 [ - + ]: 3973 : if (!node)
9418 : 0 : return false;
9419 : :
9420 [ + + - + : 3973 : switch (nodeTag(node))
- + + + -
- - + + +
+ + ]
9421 : : {
9422 : 3338 : case T_Var:
9423 : : case T_Const:
9424 : : case T_Param:
9425 : : case T_CoerceToDomainValue:
9426 : : case T_SetToDefault:
9427 : : case T_CurrentOfExpr:
9428 : : /* single words: always simple */
9429 : 3338 : return true;
9430 : :
9431 : 331 : case T_SubscriptingRef:
9432 : : case T_ArrayExpr:
9433 : : case T_RowExpr:
9434 : : case T_CoalesceExpr:
9435 : : case T_MinMaxExpr:
9436 : : case T_SQLValueFunction:
9437 : : case T_XmlExpr:
9438 : : case T_NextValueExpr:
9439 : : case T_NullIfExpr:
9440 : : case T_Aggref:
9441 : : case T_GroupingFunc:
9442 : : case T_WindowFunc:
9443 : : case T_MergeSupportFunc:
9444 : : case T_FuncExpr:
9445 : : case T_JsonConstructorExpr:
9446 : : case T_JsonExpr:
9447 : : /* function-like: name(..) or name[..] */
9448 : 331 : return true;
9449 : :
9450 : : /* CASE keywords act as parentheses */
9451 : 0 : case T_CaseExpr:
9452 : 0 : return true;
9453 : :
9454 : 48 : case T_FieldSelect:
9455 : :
9456 : : /*
9457 : : * appears simple since . has top precedence, unless parent is
9458 : : * T_FieldSelect itself!
9459 : : */
9460 : 48 : return !IsA(parentNode, FieldSelect);
9461 : :
9462 : 0 : case T_FieldStore:
9463 : :
9464 : : /*
9465 : : * treat like FieldSelect (probably doesn't matter)
9466 : : */
9467 : 0 : return !IsA(parentNode, FieldStore);
9468 : :
9469 : 12 : case T_CoerceToDomain:
9470 : : /* maybe simple, check args */
9471 : 12 : return isSimpleNode((Node *) ((CoerceToDomain *) node)->arg,
9472 : : node, prettyFlags);
9473 : 12 : case T_RelabelType:
9474 : 12 : return isSimpleNode((Node *) ((RelabelType *) node)->arg,
9475 : : node, prettyFlags);
9476 : 16 : case T_CoerceViaIO:
9477 : 16 : return isSimpleNode((Node *) ((CoerceViaIO *) node)->arg,
9478 : : node, prettyFlags);
9479 : 0 : case T_ArrayCoerceExpr:
9480 : 0 : return isSimpleNode((Node *) ((ArrayCoerceExpr *) node)->arg,
9481 : : node, prettyFlags);
9482 : 0 : case T_ConvertRowtypeExpr:
9483 : 0 : return isSimpleNode((Node *) ((ConvertRowtypeExpr *) node)->arg,
9484 : : node, prettyFlags);
9485 : 0 : case T_ReturningExpr:
9486 : 0 : return isSimpleNode((Node *) ((ReturningExpr *) node)->retexpr,
9487 : : node, prettyFlags);
9488 : :
9489 : 184 : case T_OpExpr:
9490 : : {
9491 : : /* depends on parent node type; needs further checking */
9492 [ + - + + ]: 184 : if (prettyFlags & PRETTYFLAG_PAREN && IsA(parentNode, OpExpr))
9493 : : {
9494 : : const char *op;
9495 : : const char *parentOp;
9496 : : bool is_lopriop;
9497 : : bool is_hipriop;
9498 : : bool is_lopriparent;
9499 : : bool is_hipriparent;
9500 : :
9501 : 52 : op = get_simple_binary_op_name((OpExpr *) node);
9502 [ - + ]: 52 : if (!op)
9503 : 0 : return false;
9504 : :
9505 : : /* We know only the basic operators + - and * / % */
9506 : 52 : is_lopriop = (strchr("+-", *op) != NULL);
9507 : 52 : is_hipriop = (strchr("*/%", *op) != NULL);
9508 [ + + + + ]: 52 : if (!(is_lopriop || is_hipriop))
9509 : 4 : return false;
9510 : :
9511 : 48 : parentOp = get_simple_binary_op_name((OpExpr *) parentNode);
9512 [ - + ]: 48 : if (!parentOp)
9513 : 0 : return false;
9514 : :
9515 : 48 : is_lopriparent = (strchr("+-", *parentOp) != NULL);
9516 : 48 : is_hipriparent = (strchr("*/%", *parentOp) != NULL);
9517 [ + + - + ]: 48 : if (!(is_lopriparent || is_hipriparent))
9518 : 0 : return false;
9519 : :
9520 [ + + + - ]: 48 : if (is_hipriop && is_lopriparent)
9521 : 8 : return true; /* op binds tighter than parent */
9522 : :
9523 [ + - + + ]: 40 : if (is_lopriop && is_hipriparent)
9524 : 32 : return false;
9525 : :
9526 : : /*
9527 : : * Operators are same priority --- can skip parens only if
9528 : : * we have (a - b) - c, not a - (b - c).
9529 : : */
9530 [ + + ]: 8 : if (node == (Node *) linitial(((OpExpr *) parentNode)->args))
9531 : 4 : return true;
9532 : :
9533 : 4 : return false;
9534 : : }
9535 : : /* else do the same stuff as for T_SubLink et al. */
9536 : : }
9537 : : pg_fallthrough;
9538 : :
9539 : : case T_SubLink:
9540 : : case T_NullTest:
9541 : : case T_BooleanTest:
9542 : : case T_DistinctExpr:
9543 : : case T_JsonIsPredicate:
9544 [ + + + ]: 144 : switch (nodeTag(parentNode))
9545 : : {
9546 : 40 : case T_FuncExpr:
9547 : : {
9548 : : /* special handling for casts and COERCE_SQL_SYNTAX */
9549 : 40 : CoercionForm type = ((FuncExpr *) parentNode)->funcformat;
9550 : :
9551 [ + + + + ]: 40 : if (type == COERCE_EXPLICIT_CAST ||
9552 [ + - ]: 4 : type == COERCE_IMPLICIT_CAST ||
9553 : : type == COERCE_SQL_SYNTAX)
9554 : 40 : return false;
9555 : 0 : return true; /* own parentheses */
9556 : : }
9557 : 84 : case T_BoolExpr: /* lower precedence */
9558 : : case T_SubscriptingRef: /* other separators */
9559 : : case T_ArrayExpr: /* other separators */
9560 : : case T_RowExpr: /* other separators */
9561 : : case T_CoalesceExpr: /* own parentheses */
9562 : : case T_MinMaxExpr: /* own parentheses */
9563 : : case T_XmlExpr: /* own parentheses */
9564 : : case T_NullIfExpr: /* other separators */
9565 : : case T_Aggref: /* own parentheses */
9566 : : case T_GroupingFunc: /* own parentheses */
9567 : : case T_WindowFunc: /* own parentheses */
9568 : : case T_CaseExpr: /* other separators */
9569 : 84 : return true;
9570 : 20 : default:
9571 : 20 : return false;
9572 : : }
9573 : :
9574 : 12 : case T_BoolExpr:
9575 [ + - - - ]: 12 : switch (nodeTag(parentNode))
9576 : : {
9577 : 12 : case T_BoolExpr:
9578 [ + - ]: 12 : if (prettyFlags & PRETTYFLAG_PAREN)
9579 : : {
9580 : : BoolExprType type;
9581 : : BoolExprType parentType;
9582 : :
9583 : 12 : type = ((BoolExpr *) node)->boolop;
9584 : 12 : parentType = ((BoolExpr *) parentNode)->boolop;
9585 [ + + - ]: 12 : switch (type)
9586 : : {
9587 : 8 : case NOT_EXPR:
9588 : : case AND_EXPR:
9589 [ + + + - ]: 8 : if (parentType == AND_EXPR || parentType == OR_EXPR)
9590 : 8 : return true;
9591 : 0 : break;
9592 : 4 : case OR_EXPR:
9593 [ - + ]: 4 : if (parentType == OR_EXPR)
9594 : 0 : return true;
9595 : 4 : break;
9596 : : }
9597 : : }
9598 : 4 : return false;
9599 : 0 : case T_FuncExpr:
9600 : : {
9601 : : /* special handling for casts and COERCE_SQL_SYNTAX */
9602 : 0 : CoercionForm type = ((FuncExpr *) parentNode)->funcformat;
9603 : :
9604 [ # # # # ]: 0 : if (type == COERCE_EXPLICIT_CAST ||
9605 [ # # ]: 0 : type == COERCE_IMPLICIT_CAST ||
9606 : : type == COERCE_SQL_SYNTAX)
9607 : 0 : return false;
9608 : 0 : return true; /* own parentheses */
9609 : : }
9610 : 0 : case T_SubscriptingRef: /* other separators */
9611 : : case T_ArrayExpr: /* other separators */
9612 : : case T_RowExpr: /* other separators */
9613 : : case T_CoalesceExpr: /* own parentheses */
9614 : : case T_MinMaxExpr: /* own parentheses */
9615 : : case T_XmlExpr: /* own parentheses */
9616 : : case T_NullIfExpr: /* other separators */
9617 : : case T_Aggref: /* own parentheses */
9618 : : case T_GroupingFunc: /* own parentheses */
9619 : : case T_WindowFunc: /* own parentheses */
9620 : : case T_CaseExpr: /* other separators */
9621 : : case T_JsonExpr: /* own parentheses */
9622 : 0 : return true;
9623 : 0 : default:
9624 : 0 : return false;
9625 : : }
9626 : :
9627 : 4 : case T_JsonValueExpr:
9628 : : /* maybe simple, check args */
9629 : 4 : return isSimpleNode((Node *) ((JsonValueExpr *) node)->raw_expr,
9630 : : node, prettyFlags);
9631 : :
9632 : 4 : default:
9633 : 4 : break;
9634 : : }
9635 : : /* those we don't know: in dubio complexo */
9636 : 4 : return false;
9637 : : }
9638 : :
9639 : :
9640 : : /*
9641 : : * appendContextKeyword - append a keyword to buffer
9642 : : *
9643 : : * If prettyPrint is enabled, perform a line break, and adjust indentation.
9644 : : * Otherwise, just append the keyword.
9645 : : */
9646 : : static void
9647 : 19626 : appendContextKeyword(deparse_context *context, const char *str,
9648 : : int indentBefore, int indentAfter, int indentPlus)
9649 : : {
9650 : 19626 : StringInfo buf = context->buf;
9651 : :
9652 [ + + ]: 19626 : if (PRETTY_INDENT(context))
9653 : : {
9654 : : int indentAmount;
9655 : :
9656 : 18733 : context->indentLevel += indentBefore;
9657 : :
9658 : : /* remove any trailing spaces currently in the buffer ... */
9659 : 18733 : removeStringInfoSpaces(buf);
9660 : : /* ... then add a newline and some spaces */
9661 : 18733 : appendStringInfoChar(buf, '\n');
9662 : :
9663 [ + - ]: 18733 : if (context->indentLevel < PRETTYINDENT_LIMIT)
9664 : 18733 : indentAmount = Max(context->indentLevel, 0) + indentPlus;
9665 : : else
9666 : : {
9667 : : /*
9668 : : * If we're indented more than PRETTYINDENT_LIMIT characters, try
9669 : : * to conserve horizontal space by reducing the per-level
9670 : : * indentation. For best results the scale factor here should
9671 : : * divide all the indent amounts that get added to indentLevel
9672 : : * (PRETTYINDENT_STD, etc). It's important that the indentation
9673 : : * not grow unboundedly, else deeply-nested trees use O(N^2)
9674 : : * whitespace; so we also wrap modulo PRETTYINDENT_LIMIT.
9675 : : */
9676 : 0 : indentAmount = PRETTYINDENT_LIMIT +
9677 : 0 : (context->indentLevel - PRETTYINDENT_LIMIT) /
9678 : : (PRETTYINDENT_STD / 2);
9679 : 0 : indentAmount %= PRETTYINDENT_LIMIT;
9680 : : /* scale/wrap logic affects indentLevel, but not indentPlus */
9681 : 0 : indentAmount += indentPlus;
9682 : : }
9683 : 18733 : appendStringInfoSpaces(buf, indentAmount);
9684 : :
9685 : 18733 : appendStringInfoString(buf, str);
9686 : :
9687 : 18733 : context->indentLevel += indentAfter;
9688 [ - + ]: 18733 : if (context->indentLevel < 0)
9689 : 0 : context->indentLevel = 0;
9690 : : }
9691 : : else
9692 : 893 : appendStringInfoString(buf, str);
9693 : 19626 : }
9694 : :
9695 : : /*
9696 : : * removeStringInfoSpaces - delete trailing spaces from a buffer.
9697 : : *
9698 : : * Possibly this should move to stringinfo.c at some point.
9699 : : */
9700 : : static void
9701 : 19108 : removeStringInfoSpaces(StringInfo str)
9702 : : {
9703 [ + + + + ]: 29811 : while (str->len > 0 && str->data[str->len - 1] == ' ')
9704 : 10703 : str->data[--(str->len)] = '\0';
9705 : 19108 : }
9706 : :
9707 : :
9708 : : /*
9709 : : * get_rule_expr_paren - deparse expr using get_rule_expr,
9710 : : * embracing the string with parentheses if necessary for prettyPrint.
9711 : : *
9712 : : * Never embrace if prettyFlags=0, because it's done in the calling node.
9713 : : *
9714 : : * Any node that does *not* embrace its argument node by sql syntax (with
9715 : : * parentheses, non-operator keywords like CASE/WHEN/ON, or comma etc) should
9716 : : * use get_rule_expr_paren instead of get_rule_expr so parentheses can be
9717 : : * added.
9718 : : */
9719 : : static void
9720 : 110674 : get_rule_expr_paren(Node *node, deparse_context *context,
9721 : : bool showimplicit, Node *parentNode)
9722 : : {
9723 : : bool need_paren;
9724 : :
9725 [ + + ]: 114603 : need_paren = PRETTY_PAREN(context) &&
9726 [ + + ]: 3929 : !isSimpleNode(node, parentNode, context->prettyFlags);
9727 : :
9728 [ + + ]: 110674 : if (need_paren)
9729 : 108 : appendStringInfoChar(context->buf, '(');
9730 : :
9731 : 110674 : get_rule_expr(node, context, showimplicit);
9732 : :
9733 [ + + ]: 110674 : if (need_paren)
9734 : 108 : appendStringInfoChar(context->buf, ')');
9735 : 110674 : }
9736 : :
9737 : : static void
9738 : 72 : get_json_behavior(JsonBehavior *behavior, deparse_context *context,
9739 : : const char *on)
9740 : : {
9741 : : /*
9742 : : * The order of array elements must correspond to the order of
9743 : : * JsonBehaviorType members.
9744 : : */
9745 : 72 : const char *behavior_names[] =
9746 : : {
9747 : : " NULL",
9748 : : " ERROR",
9749 : : " EMPTY",
9750 : : " TRUE",
9751 : : " FALSE",
9752 : : " UNKNOWN",
9753 : : " EMPTY ARRAY",
9754 : : " EMPTY OBJECT",
9755 : : " DEFAULT "
9756 : : };
9757 : :
9758 [ + - - + ]: 72 : if ((int) behavior->btype < 0 || behavior->btype >= lengthof(behavior_names))
9759 [ # # ]: 0 : elog(ERROR, "invalid json behavior type: %d", behavior->btype);
9760 : :
9761 : 72 : appendStringInfoString(context->buf, behavior_names[behavior->btype]);
9762 : :
9763 [ + + ]: 72 : if (behavior->btype == JSON_BEHAVIOR_DEFAULT)
9764 : 12 : get_rule_expr(behavior->expr, context, false);
9765 : :
9766 : 72 : appendStringInfo(context->buf, " ON %s", on);
9767 : 72 : }
9768 : :
9769 : : /*
9770 : : * get_json_expr_options
9771 : : *
9772 : : * Parse back common options for JSON_QUERY, JSON_VALUE, JSON_EXISTS and
9773 : : * JSON_TABLE columns.
9774 : : */
9775 : : static void
9776 : 428 : get_json_expr_options(JsonExpr *jsexpr, deparse_context *context,
9777 : : JsonBehaviorType default_behavior)
9778 : : {
9779 [ + + ]: 428 : if (jsexpr->op == JSON_QUERY_OP)
9780 : : {
9781 [ + + ]: 192 : if (jsexpr->wrapper == JSW_CONDITIONAL)
9782 : 8 : appendStringInfoString(context->buf, " WITH CONDITIONAL WRAPPER");
9783 [ + + ]: 184 : else if (jsexpr->wrapper == JSW_UNCONDITIONAL)
9784 : 24 : appendStringInfoString(context->buf, " WITH UNCONDITIONAL WRAPPER");
9785 : : /* The default */
9786 [ + + + - ]: 160 : else if (jsexpr->wrapper == JSW_NONE || jsexpr->wrapper == JSW_UNSPEC)
9787 : 160 : appendStringInfoString(context->buf, " WITHOUT WRAPPER");
9788 : :
9789 [ + + ]: 192 : if (jsexpr->omit_quotes)
9790 : 36 : appendStringInfoString(context->buf, " OMIT QUOTES");
9791 : : /* The default */
9792 : : else
9793 : 156 : appendStringInfoString(context->buf, " KEEP QUOTES");
9794 : : }
9795 : :
9796 [ + + + + ]: 428 : if (jsexpr->on_empty && jsexpr->on_empty->btype != default_behavior)
9797 : 24 : get_json_behavior(jsexpr->on_empty, context, "EMPTY");
9798 : :
9799 [ + - + + ]: 428 : if (jsexpr->on_error && jsexpr->on_error->btype != default_behavior)
9800 : 40 : get_json_behavior(jsexpr->on_error, context, "ERROR");
9801 : 428 : }
9802 : :
9803 : : /* ----------
9804 : : * get_rule_expr - Parse back an expression
9805 : : *
9806 : : * Note: showimplicit determines whether we display any implicit cast that
9807 : : * is present at the top of the expression tree. It is a passed argument,
9808 : : * not a field of the context struct, because we change the value as we
9809 : : * recurse down into the expression. In general we suppress implicit casts
9810 : : * when the result type is known with certainty (eg, the arguments of an
9811 : : * OR must be boolean). We display implicit casts for arguments of functions
9812 : : * and operators, since this is needed to be certain that the same function
9813 : : * or operator will be chosen when the expression is re-parsed.
9814 : : * ----------
9815 : : */
9816 : : static void
9817 : 240483 : get_rule_expr(Node *node, deparse_context *context,
9818 : : bool showimplicit)
9819 : : {
9820 : 240483 : StringInfo buf = context->buf;
9821 : :
9822 [ + + ]: 240483 : if (node == NULL)
9823 : 68 : return;
9824 : :
9825 : : /* Guard against excessively long or deeply-nested queries */
9826 [ - + ]: 240415 : CHECK_FOR_INTERRUPTS();
9827 : 240415 : check_stack_depth();
9828 : :
9829 : : /*
9830 : : * Each level of get_rule_expr must emit an indivisible term
9831 : : * (parenthesized if necessary) to ensure result is reparsed into the same
9832 : : * expression tree. The only exception is that when the input is a List,
9833 : : * we emit the component items comma-separated with no surrounding
9834 : : * decoration; this is convenient for most callers.
9835 : : */
9836 [ + + + + : 240415 : switch (nodeTag(node))
+ + + + +
+ + + + +
+ + + - +
+ + + + +
+ + - + +
+ + + + +
+ + + + +
+ - + + +
+ + + + +
+ + - ]
9837 : : {
9838 : 116113 : case T_Var:
9839 : 116113 : (void) get_variable((Var *) node, 0, false, context);
9840 : 116113 : break;
9841 : :
9842 : 42288 : case T_Const:
9843 : 42288 : get_const_expr((Const *) node, context, 0);
9844 : 42288 : break;
9845 : :
9846 : 4798 : case T_Param:
9847 : 4798 : get_parameter((Param *) node, context);
9848 : 4798 : break;
9849 : :
9850 : 2640 : case T_Aggref:
9851 : 2640 : get_agg_expr((Aggref *) node, context, (Aggref *) node);
9852 : 2640 : break;
9853 : :
9854 : 74 : case T_GroupingFunc:
9855 : : {
9856 : 74 : GroupingFunc *gexpr = (GroupingFunc *) node;
9857 : :
9858 : 74 : appendStringInfoString(buf, "GROUPING(");
9859 : 74 : get_rule_expr((Node *) gexpr->args, context, true);
9860 : 74 : appendStringInfoChar(buf, ')');
9861 : : }
9862 : 74 : break;
9863 : :
9864 : 246 : case T_WindowFunc:
9865 : 246 : get_windowfunc_expr((WindowFunc *) node, context);
9866 : 246 : break;
9867 : :
9868 : 4 : case T_MergeSupportFunc:
9869 : 4 : appendStringInfoString(buf, "MERGE_ACTION()");
9870 : 4 : break;
9871 : :
9872 : 232 : case T_SubscriptingRef:
9873 : : {
9874 : 232 : SubscriptingRef *sbsref = (SubscriptingRef *) node;
9875 : : bool need_parens;
9876 : :
9877 : : /*
9878 : : * If the argument is a CaseTestExpr, we must be inside a
9879 : : * FieldStore, ie, we are assigning to an element of an array
9880 : : * within a composite column. Since we already punted on
9881 : : * displaying the FieldStore's target information, just punt
9882 : : * here too, and display only the assignment source
9883 : : * expression.
9884 : : */
9885 [ - + ]: 232 : if (IsA(sbsref->refexpr, CaseTestExpr))
9886 : : {
9887 : : Assert(sbsref->refassgnexpr);
9888 : 0 : get_rule_expr((Node *) sbsref->refassgnexpr,
9889 : : context, showimplicit);
9890 : 0 : break;
9891 : : }
9892 : :
9893 : : /*
9894 : : * Parenthesize the argument unless it's a simple Var or a
9895 : : * FieldSelect. (In particular, if it's another
9896 : : * SubscriptingRef, we *must* parenthesize to avoid
9897 : : * confusion.)
9898 : : */
9899 [ + + ]: 358 : need_parens = !IsA(sbsref->refexpr, Var) &&
9900 [ + + ]: 126 : !IsA(sbsref->refexpr, FieldSelect);
9901 [ + + ]: 232 : if (need_parens)
9902 : 56 : appendStringInfoChar(buf, '(');
9903 : 232 : get_rule_expr((Node *) sbsref->refexpr, context, showimplicit);
9904 [ + + ]: 232 : if (need_parens)
9905 : 56 : appendStringInfoChar(buf, ')');
9906 : :
9907 : : /*
9908 : : * If there's a refassgnexpr, we want to print the node in the
9909 : : * format "container[subscripts] := refassgnexpr". This is
9910 : : * not legal SQL, so decompilation of INSERT or UPDATE
9911 : : * statements should always use processIndirection as part of
9912 : : * the statement-level syntax. We should only see this when
9913 : : * EXPLAIN tries to print the targetlist of a plan resulting
9914 : : * from such a statement.
9915 : : */
9916 [ + + ]: 232 : if (sbsref->refassgnexpr)
9917 : : {
9918 : : Node *refassgnexpr;
9919 : :
9920 : : /*
9921 : : * Use processIndirection to print this node's subscripts
9922 : : * as well as any additional field selections or
9923 : : * subscripting in immediate descendants. It returns the
9924 : : * RHS expr that is actually being "assigned".
9925 : : */
9926 : 8 : refassgnexpr = processIndirection(node, context);
9927 : 8 : appendStringInfoString(buf, " := ");
9928 : 8 : get_rule_expr(refassgnexpr, context, showimplicit);
9929 : : }
9930 : : else
9931 : : {
9932 : : /* Just an ordinary container fetch, so print subscripts */
9933 : 224 : printSubscripts(sbsref, context);
9934 : : }
9935 : : }
9936 : 232 : break;
9937 : :
9938 : 8212 : case T_FuncExpr:
9939 : 8212 : get_func_expr((FuncExpr *) node, context, showimplicit);
9940 : 8212 : break;
9941 : :
9942 : 20 : case T_NamedArgExpr:
9943 : : {
9944 : 20 : NamedArgExpr *na = (NamedArgExpr *) node;
9945 : :
9946 : 20 : appendStringInfo(buf, "%s => ", quote_identifier(na->name));
9947 : 20 : get_rule_expr((Node *) na->arg, context, showimplicit);
9948 : : }
9949 : 20 : break;
9950 : :
9951 : 41483 : case T_OpExpr:
9952 : 41483 : get_oper_expr((OpExpr *) node, context);
9953 : 41483 : break;
9954 : :
9955 : 16 : case T_DistinctExpr:
9956 : : {
9957 : 16 : DistinctExpr *expr = (DistinctExpr *) node;
9958 : 16 : List *args = expr->args;
9959 : 16 : Node *arg1 = (Node *) linitial(args);
9960 : 16 : Node *arg2 = (Node *) lsecond(args);
9961 : :
9962 [ + + ]: 16 : if (!PRETTY_PAREN(context))
9963 : 12 : appendStringInfoChar(buf, '(');
9964 : 16 : get_rule_expr_paren(arg1, context, true, node);
9965 : 16 : appendStringInfoString(buf, " IS DISTINCT FROM ");
9966 : 16 : get_rule_expr_paren(arg2, context, true, node);
9967 [ + + ]: 16 : if (!PRETTY_PAREN(context))
9968 : 12 : appendStringInfoChar(buf, ')');
9969 : : }
9970 : 16 : break;
9971 : :
9972 : 140 : case T_NullIfExpr:
9973 : : {
9974 : 140 : NullIfExpr *nullifexpr = (NullIfExpr *) node;
9975 : :
9976 : 140 : appendStringInfoString(buf, "NULLIF(");
9977 : 140 : get_rule_expr((Node *) nullifexpr->args, context, true);
9978 : 140 : appendStringInfoChar(buf, ')');
9979 : : }
9980 : 140 : break;
9981 : :
9982 : 2027 : case T_ScalarArrayOpExpr:
9983 : : {
9984 : 2027 : ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
9985 : 2027 : List *args = expr->args;
9986 : 2027 : Node *arg1 = (Node *) linitial(args);
9987 : 2027 : Node *arg2 = (Node *) lsecond(args);
9988 : :
9989 [ + + ]: 2027 : if (!PRETTY_PAREN(context))
9990 : 2019 : appendStringInfoChar(buf, '(');
9991 : 2027 : get_rule_expr_paren(arg1, context, true, node);
9992 : 2027 : appendStringInfo(buf, " %s %s (",
9993 : : generate_operator_name(expr->opno,
9994 : : exprType(arg1),
9995 : : get_base_element_type(exprType(arg2))),
9996 [ + + ]: 2027 : expr->useOr ? "ANY" : "ALL");
9997 : 2027 : get_rule_expr_paren(arg2, context, true, node);
9998 : :
9999 : : /*
10000 : : * There's inherent ambiguity in "x op ANY/ALL (y)" when y is
10001 : : * a bare sub-SELECT. Since we're here, the sub-SELECT must
10002 : : * be meant as a scalar sub-SELECT yielding an array value to
10003 : : * be used in ScalarArrayOpExpr; but the grammar will
10004 : : * preferentially interpret such a construct as an ANY/ALL
10005 : : * SubLink. To prevent misparsing the output that way, insert
10006 : : * a dummy coercion (which will be stripped by parse analysis,
10007 : : * so no inefficiency is added in dump and reload). This is
10008 : : * indeed most likely what the user wrote to get the construct
10009 : : * accepted in the first place.
10010 : : */
10011 [ + + ]: 2027 : if (IsA(arg2, SubLink) &&
10012 [ + - ]: 4 : ((SubLink *) arg2)->subLinkType == EXPR_SUBLINK)
10013 : 4 : appendStringInfo(buf, "::%s",
10014 : : format_type_with_typemod(exprType(arg2),
10015 : : exprTypmod(arg2)));
10016 : 2027 : appendStringInfoChar(buf, ')');
10017 [ + + ]: 2027 : if (!PRETTY_PAREN(context))
10018 : 2019 : appendStringInfoChar(buf, ')');
10019 : : }
10020 : 2027 : break;
10021 : :
10022 : 7487 : case T_BoolExpr:
10023 : : {
10024 : 7487 : BoolExpr *expr = (BoolExpr *) node;
10025 : 7487 : Node *first_arg = linitial(expr->args);
10026 : : ListCell *arg;
10027 : :
10028 [ + + + - ]: 7487 : switch (expr->boolop)
10029 : : {
10030 : 5933 : case AND_EXPR:
10031 [ + + ]: 5933 : if (!PRETTY_PAREN(context))
10032 : 5897 : appendStringInfoChar(buf, '(');
10033 : 5933 : get_rule_expr_paren(first_arg, context,
10034 : : false, node);
10035 [ + - + + : 13535 : for_each_from(arg, expr->args, 1)
+ + ]
10036 : : {
10037 : 7602 : appendStringInfoString(buf, " AND ");
10038 : 7602 : get_rule_expr_paren((Node *) lfirst(arg), context,
10039 : : false, node);
10040 : : }
10041 [ + + ]: 5933 : if (!PRETTY_PAREN(context))
10042 : 5897 : appendStringInfoChar(buf, ')');
10043 : 5933 : break;
10044 : :
10045 : 1254 : case OR_EXPR:
10046 [ + + ]: 1254 : if (!PRETTY_PAREN(context))
10047 : 1246 : appendStringInfoChar(buf, '(');
10048 : 1254 : get_rule_expr_paren(first_arg, context,
10049 : : false, node);
10050 [ + - + + : 2983 : for_each_from(arg, expr->args, 1)
+ + ]
10051 : : {
10052 : 1729 : appendStringInfoString(buf, " OR ");
10053 : 1729 : get_rule_expr_paren((Node *) lfirst(arg), context,
10054 : : false, node);
10055 : : }
10056 [ + + ]: 1254 : if (!PRETTY_PAREN(context))
10057 : 1246 : appendStringInfoChar(buf, ')');
10058 : 1254 : break;
10059 : :
10060 : 300 : case NOT_EXPR:
10061 [ + + ]: 300 : if (!PRETTY_PAREN(context))
10062 : 292 : appendStringInfoChar(buf, '(');
10063 : 300 : appendStringInfoString(buf, "NOT ");
10064 : 300 : get_rule_expr_paren(first_arg, context,
10065 : : false, node);
10066 [ + + ]: 300 : if (!PRETTY_PAREN(context))
10067 : 292 : appendStringInfoChar(buf, ')');
10068 : 300 : break;
10069 : :
10070 : 0 : default:
10071 [ # # ]: 0 : elog(ERROR, "unrecognized boolop: %d",
10072 : : (int) expr->boolop);
10073 : : }
10074 : : }
10075 : 7487 : break;
10076 : :
10077 : 290 : case T_SubLink:
10078 : 290 : get_sublink_expr((SubLink *) node, context);
10079 : 290 : break;
10080 : :
10081 : 536 : case T_SubPlan:
10082 : : {
10083 : 536 : SubPlan *subplan = (SubPlan *) node;
10084 : :
10085 : : /*
10086 : : * We cannot see an already-planned subplan in rule deparsing,
10087 : : * only while EXPLAINing a query plan. We don't try to
10088 : : * reconstruct the original SQL, just reference the subplan
10089 : : * that appears elsewhere in EXPLAIN's result. It does seem
10090 : : * useful to show the subLinkType and testexpr (if any), and
10091 : : * we also note whether the subplan will be hashed.
10092 : : */
10093 [ + + + + : 536 : switch (subplan->subLinkType)
+ + + -
- ]
10094 : : {
10095 : 69 : case EXISTS_SUBLINK:
10096 : 69 : appendStringInfoString(buf, "EXISTS(");
10097 : : Assert(subplan->testexpr == NULL);
10098 : 69 : break;
10099 : 4 : case ALL_SUBLINK:
10100 : 4 : appendStringInfoString(buf, "(ALL ");
10101 : : Assert(subplan->testexpr != NULL);
10102 : 4 : break;
10103 : 160 : case ANY_SUBLINK:
10104 : 160 : appendStringInfoString(buf, "(ANY ");
10105 : : Assert(subplan->testexpr != NULL);
10106 : 160 : break;
10107 : 4 : case ROWCOMPARE_SUBLINK:
10108 : : /* Parenthesizing the testexpr seems sufficient */
10109 : 4 : appendStringInfoChar(buf, '(');
10110 : : Assert(subplan->testexpr != NULL);
10111 : 4 : break;
10112 : 274 : case EXPR_SUBLINK:
10113 : : /* No need to decorate these subplan references */
10114 : 274 : appendStringInfoChar(buf, '(');
10115 : : Assert(subplan->testexpr == NULL);
10116 : 274 : break;
10117 : 17 : case MULTIEXPR_SUBLINK:
10118 : : /* MULTIEXPR isn't executed in the normal way */
10119 : 17 : appendStringInfoString(buf, "(rescan ");
10120 : : Assert(subplan->testexpr == NULL);
10121 : 17 : break;
10122 : 8 : case ARRAY_SUBLINK:
10123 : 8 : appendStringInfoString(buf, "ARRAY(");
10124 : : Assert(subplan->testexpr == NULL);
10125 : 8 : break;
10126 : 0 : case CTE_SUBLINK:
10127 : : /* This case is unreachable within expressions */
10128 : 0 : appendStringInfoString(buf, "CTE(");
10129 : : Assert(subplan->testexpr == NULL);
10130 : 0 : break;
10131 : : }
10132 : :
10133 [ + + ]: 536 : if (subplan->testexpr != NULL)
10134 : : {
10135 : : deparse_namespace *dpns;
10136 : :
10137 : : /*
10138 : : * Push SubPlan into ancestors list while deparsing
10139 : : * testexpr, so that we can handle PARAM_EXEC references
10140 : : * to the SubPlan's paramIds. (This makes it look like
10141 : : * the SubPlan is an "ancestor" of the current plan node,
10142 : : * which is a little weird, but it does no harm.) In this
10143 : : * path, we don't need to mention the SubPlan explicitly,
10144 : : * because the referencing Params will show its existence.
10145 : : */
10146 : 168 : dpns = (deparse_namespace *) linitial(context->namespaces);
10147 : 168 : dpns->ancestors = lcons(subplan, dpns->ancestors);
10148 : :
10149 : 168 : get_rule_expr(subplan->testexpr, context, showimplicit);
10150 : 168 : appendStringInfoChar(buf, ')');
10151 : :
10152 : 168 : dpns->ancestors = list_delete_first(dpns->ancestors);
10153 : : }
10154 : : else
10155 : : {
10156 : : const char *nameprefix;
10157 : :
10158 : : /* No referencing Params, so show the SubPlan's name */
10159 [ - + ]: 368 : if (subplan->isInitPlan)
10160 : 0 : nameprefix = "InitPlan ";
10161 : : else
10162 : 368 : nameprefix = "SubPlan ";
10163 [ - + ]: 368 : if (subplan->useHashTable)
10164 : 0 : appendStringInfo(buf, "hashed %s%s)",
10165 : : nameprefix, subplan->plan_name);
10166 : : else
10167 : 368 : appendStringInfo(buf, "%s%s)",
10168 : : nameprefix, subplan->plan_name);
10169 : : }
10170 : : }
10171 : 536 : break;
10172 : :
10173 : 0 : case T_AlternativeSubPlan:
10174 : : {
10175 : 0 : AlternativeSubPlan *asplan = (AlternativeSubPlan *) node;
10176 : : ListCell *lc;
10177 : :
10178 : : /*
10179 : : * This case cannot be reached in normal usage, since no
10180 : : * AlternativeSubPlan can appear either in parsetrees or
10181 : : * finished plan trees. We keep it just in case somebody
10182 : : * wants to use this code to print planner data structures.
10183 : : */
10184 : 0 : appendStringInfoString(buf, "(alternatives: ");
10185 [ # # # # : 0 : foreach(lc, asplan->subplans)
# # ]
10186 : : {
10187 : 0 : SubPlan *splan = lfirst_node(SubPlan, lc);
10188 : : const char *nameprefix;
10189 : :
10190 [ # # ]: 0 : if (splan->isInitPlan)
10191 : 0 : nameprefix = "InitPlan ";
10192 : : else
10193 : 0 : nameprefix = "SubPlan ";
10194 [ # # ]: 0 : if (splan->useHashTable)
10195 : 0 : appendStringInfo(buf, "hashed %s%s", nameprefix,
10196 : : splan->plan_name);
10197 : : else
10198 : 0 : appendStringInfo(buf, "%s%s", nameprefix,
10199 : : splan->plan_name);
10200 [ # # ]: 0 : if (lnext(asplan->subplans, lc))
10201 : 0 : appendStringInfoString(buf, " or ");
10202 : : }
10203 : 0 : appendStringInfoChar(buf, ')');
10204 : : }
10205 : 0 : break;
10206 : :
10207 : 926 : case T_FieldSelect:
10208 : : {
10209 : 926 : FieldSelect *fselect = (FieldSelect *) node;
10210 : 926 : Node *arg = (Node *) fselect->arg;
10211 : 926 : int fno = fselect->fieldnum;
10212 : : const char *fieldname;
10213 : : bool need_parens;
10214 : :
10215 : : /*
10216 : : * Parenthesize the argument unless it's a SubscriptingRef or
10217 : : * another FieldSelect. Note in particular that it would be
10218 : : * WRONG to not parenthesize a Var argument; simplicity is not
10219 : : * the issue here, having the right number of names is.
10220 : : */
10221 [ + + ]: 1828 : need_parens = !IsA(arg, SubscriptingRef) &&
10222 [ + - ]: 902 : !IsA(arg, FieldSelect);
10223 [ + + ]: 926 : if (need_parens)
10224 : 902 : appendStringInfoChar(buf, '(');
10225 : 926 : get_rule_expr(arg, context, true);
10226 [ + + ]: 926 : if (need_parens)
10227 : 902 : appendStringInfoChar(buf, ')');
10228 : :
10229 : : /*
10230 : : * Get and print the field name.
10231 : : */
10232 : 926 : fieldname = get_name_for_var_field((Var *) arg, fno,
10233 : : 0, context);
10234 : 926 : appendStringInfo(buf, ".%s", quote_identifier(fieldname));
10235 : : }
10236 : 926 : break;
10237 : :
10238 : 4 : case T_FieldStore:
10239 : : {
10240 : 4 : FieldStore *fstore = (FieldStore *) node;
10241 : : bool need_parens;
10242 : :
10243 : : /*
10244 : : * There is no good way to represent a FieldStore as real SQL,
10245 : : * so decompilation of INSERT or UPDATE statements should
10246 : : * always use processIndirection as part of the
10247 : : * statement-level syntax. We should only get here when
10248 : : * EXPLAIN tries to print the targetlist of a plan resulting
10249 : : * from such a statement. The plan case is even harder than
10250 : : * ordinary rules would be, because the planner tries to
10251 : : * collapse multiple assignments to the same field or subfield
10252 : : * into one FieldStore; so we can see a list of target fields
10253 : : * not just one, and the arguments could be FieldStores
10254 : : * themselves. We don't bother to try to print the target
10255 : : * field names; we just print the source arguments, with a
10256 : : * ROW() around them if there's more than one. This isn't
10257 : : * terribly complete, but it's probably good enough for
10258 : : * EXPLAIN's purposes; especially since anything more would be
10259 : : * either hopelessly confusing or an even poorer
10260 : : * representation of what the plan is actually doing.
10261 : : */
10262 : 4 : need_parens = (list_length(fstore->newvals) != 1);
10263 [ + - ]: 4 : if (need_parens)
10264 : 4 : appendStringInfoString(buf, "ROW(");
10265 : 4 : get_rule_expr((Node *) fstore->newvals, context, showimplicit);
10266 [ + - ]: 4 : if (need_parens)
10267 : 4 : appendStringInfoChar(buf, ')');
10268 : : }
10269 : 4 : break;
10270 : :
10271 : 2015 : case T_RelabelType:
10272 : : {
10273 : 2015 : RelabelType *relabel = (RelabelType *) node;
10274 : 2015 : Node *arg = (Node *) relabel->arg;
10275 : :
10276 [ + + ]: 2015 : if (relabel->relabelformat == COERCE_IMPLICIT_CAST &&
10277 [ + + ]: 1815 : !showimplicit)
10278 : : {
10279 : : /* don't show the implicit cast */
10280 : 45 : get_rule_expr_paren(arg, context, false, node);
10281 : : }
10282 : : else
10283 : : {
10284 : 1970 : get_coercion_expr(arg, context,
10285 : : relabel->resulttype,
10286 : : relabel->resulttypmod,
10287 : : node);
10288 : : }
10289 : : }
10290 : 2015 : break;
10291 : :
10292 : 501 : case T_CoerceViaIO:
10293 : : {
10294 : 501 : CoerceViaIO *iocoerce = (CoerceViaIO *) node;
10295 : 501 : Node *arg = (Node *) iocoerce->arg;
10296 : :
10297 [ + + ]: 501 : if (iocoerce->coerceformat == COERCE_IMPLICIT_CAST &&
10298 [ + - ]: 24 : !showimplicit)
10299 : : {
10300 : : /* don't show the implicit cast */
10301 : 24 : get_rule_expr_paren(arg, context, false, node);
10302 : : }
10303 : : else
10304 : : {
10305 : 477 : get_coercion_expr(arg, context,
10306 : : iocoerce->resulttype,
10307 : : -1,
10308 : : node);
10309 : : }
10310 : : }
10311 : 501 : break;
10312 : :
10313 : 39 : case T_ArrayCoerceExpr:
10314 : : {
10315 : 39 : ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
10316 : 39 : Node *arg = (Node *) acoerce->arg;
10317 : :
10318 [ + + ]: 39 : if (acoerce->coerceformat == COERCE_IMPLICIT_CAST &&
10319 [ + + ]: 37 : !showimplicit)
10320 : : {
10321 : : /* don't show the implicit cast */
10322 : 4 : get_rule_expr_paren(arg, context, false, node);
10323 : : }
10324 : : else
10325 : : {
10326 : 35 : get_coercion_expr(arg, context,
10327 : : acoerce->resulttype,
10328 : : acoerce->resulttypmod,
10329 : : node);
10330 : : }
10331 : : }
10332 : 39 : break;
10333 : :
10334 : 53 : case T_ConvertRowtypeExpr:
10335 : : {
10336 : 53 : ConvertRowtypeExpr *convert = (ConvertRowtypeExpr *) node;
10337 : 53 : Node *arg = (Node *) convert->arg;
10338 : :
10339 [ + + ]: 53 : if (convert->convertformat == COERCE_IMPLICIT_CAST &&
10340 [ + + ]: 49 : !showimplicit)
10341 : : {
10342 : : /* don't show the implicit cast */
10343 : 12 : get_rule_expr_paren(arg, context, false, node);
10344 : : }
10345 : : else
10346 : : {
10347 : 41 : get_coercion_expr(arg, context,
10348 : : convert->resulttype, -1,
10349 : : node);
10350 : : }
10351 : : }
10352 : 53 : break;
10353 : :
10354 : 122 : case T_CollateExpr:
10355 : : {
10356 : 122 : CollateExpr *collate = (CollateExpr *) node;
10357 : 122 : Node *arg = (Node *) collate->arg;
10358 : :
10359 [ + + ]: 122 : if (!PRETTY_PAREN(context))
10360 : 118 : appendStringInfoChar(buf, '(');
10361 : 122 : get_rule_expr_paren(arg, context, showimplicit, node);
10362 : 122 : appendStringInfo(buf, " COLLATE %s",
10363 : : generate_collation_name(collate->collOid));
10364 [ + + ]: 122 : if (!PRETTY_PAREN(context))
10365 : 118 : appendStringInfoChar(buf, ')');
10366 : : }
10367 : 122 : break;
10368 : :
10369 : 480 : case T_CaseExpr:
10370 : : {
10371 : 480 : CaseExpr *caseexpr = (CaseExpr *) node;
10372 : : ListCell *temp;
10373 : :
10374 : 480 : appendContextKeyword(context, "CASE",
10375 : : 0, PRETTYINDENT_VAR, 0);
10376 [ + + ]: 480 : if (caseexpr->arg)
10377 : : {
10378 : 191 : appendStringInfoChar(buf, ' ');
10379 : 191 : get_rule_expr((Node *) caseexpr->arg, context, true);
10380 : : }
10381 [ + - + + : 1973 : foreach(temp, caseexpr->args)
+ + ]
10382 : : {
10383 : 1493 : CaseWhen *when = (CaseWhen *) lfirst(temp);
10384 : 1493 : Node *w = (Node *) when->expr;
10385 : :
10386 [ + + ]: 1493 : if (caseexpr->arg)
10387 : : {
10388 : : /*
10389 : : * The parser should have produced WHEN clauses of the
10390 : : * form "CaseTestExpr = RHS", possibly with an
10391 : : * implicit coercion inserted above the CaseTestExpr.
10392 : : * For accurate decompilation of rules it's essential
10393 : : * that we show just the RHS. However in an
10394 : : * expression that's been through the optimizer, the
10395 : : * WHEN clause could be almost anything (since the
10396 : : * equality operator could have been expanded into an
10397 : : * inline function). If we don't recognize the form
10398 : : * of the WHEN clause, just punt and display it as-is.
10399 : : */
10400 [ + - ]: 609 : if (IsA(w, OpExpr))
10401 : : {
10402 : 609 : List *args = ((OpExpr *) w)->args;
10403 : :
10404 [ + - ]: 609 : if (list_length(args) == 2 &&
10405 [ + - ]: 609 : IsA(strip_implicit_coercions(linitial(args)),
10406 : : CaseTestExpr))
10407 : 609 : w = (Node *) lsecond(args);
10408 : : }
10409 : : }
10410 : :
10411 [ + + ]: 1493 : if (!PRETTY_INDENT(context))
10412 : 96 : appendStringInfoChar(buf, ' ');
10413 : 1493 : appendContextKeyword(context, "WHEN ",
10414 : : 0, 0, 0);
10415 : 1493 : get_rule_expr(w, context, false);
10416 : 1493 : appendStringInfoString(buf, " THEN ");
10417 : 1493 : get_rule_expr((Node *) when->result, context, true);
10418 : : }
10419 [ + + ]: 480 : if (!PRETTY_INDENT(context))
10420 : 91 : appendStringInfoChar(buf, ' ');
10421 : 480 : appendContextKeyword(context, "ELSE ",
10422 : : 0, 0, 0);
10423 : 480 : get_rule_expr((Node *) caseexpr->defresult, context, true);
10424 [ + + ]: 480 : if (!PRETTY_INDENT(context))
10425 : 91 : appendStringInfoChar(buf, ' ');
10426 : 480 : appendContextKeyword(context, "END",
10427 : : -PRETTYINDENT_VAR, 0, 0);
10428 : : }
10429 : 480 : break;
10430 : :
10431 : 0 : case T_CaseTestExpr:
10432 : : {
10433 : : /*
10434 : : * Normally we should never get here, since for expressions
10435 : : * that can contain this node type we attempt to avoid
10436 : : * recursing to it. But in an optimized expression we might
10437 : : * be unable to avoid that (see comments for CaseExpr). If we
10438 : : * do see one, print it as CASE_TEST_EXPR.
10439 : : */
10440 : 0 : appendStringInfoString(buf, "CASE_TEST_EXPR");
10441 : : }
10442 : 0 : break;
10443 : :
10444 : 367 : case T_ArrayExpr:
10445 : : {
10446 : 367 : ArrayExpr *arrayexpr = (ArrayExpr *) node;
10447 : :
10448 : 367 : appendStringInfoString(buf, "ARRAY[");
10449 : 367 : get_rule_expr((Node *) arrayexpr->elements, context, true);
10450 : 367 : appendStringInfoChar(buf, ']');
10451 : :
10452 : : /*
10453 : : * If the array isn't empty, we assume its elements are
10454 : : * coerced to the desired type. If it's empty, though, we
10455 : : * need an explicit coercion to the array type.
10456 : : */
10457 [ + + ]: 367 : if (arrayexpr->elements == NIL)
10458 : 4 : appendStringInfo(buf, "::%s",
10459 : : format_type_with_typemod(arrayexpr->array_typeid, -1));
10460 : : }
10461 : 367 : break;
10462 : :
10463 : 186 : case T_RowExpr:
10464 : : {
10465 : 186 : RowExpr *rowexpr = (RowExpr *) node;
10466 : 186 : TupleDesc tupdesc = NULL;
10467 : : ListCell *arg;
10468 : : int i;
10469 : : char *sep;
10470 : :
10471 : : /*
10472 : : * If it's a named type and not RECORD, we may have to skip
10473 : : * dropped columns and/or claim there are NULLs for added
10474 : : * columns.
10475 : : */
10476 [ + + ]: 186 : if (rowexpr->row_typeid != RECORDOID)
10477 : : {
10478 : 44 : tupdesc = lookup_rowtype_tupdesc(rowexpr->row_typeid, -1);
10479 : : Assert(list_length(rowexpr->args) <= tupdesc->natts);
10480 : : }
10481 : :
10482 : : /*
10483 : : * SQL99 allows "ROW" to be omitted when there is more than
10484 : : * one column, but for simplicity we always print it.
10485 : : */
10486 : 186 : appendStringInfoString(buf, "ROW(");
10487 : 186 : sep = "";
10488 : 186 : i = 0;
10489 [ + - + + : 564 : foreach(arg, rowexpr->args)
+ + ]
10490 : : {
10491 : 378 : Node *e = (Node *) lfirst(arg);
10492 : :
10493 [ + + ]: 378 : if (tupdesc == NULL ||
10494 [ + - ]: 104 : !TupleDescCompactAttr(tupdesc, i)->attisdropped)
10495 : : {
10496 : 378 : appendStringInfoString(buf, sep);
10497 : : /* Whole-row Vars need special treatment here */
10498 : 378 : get_rule_expr_toplevel(e, context, true);
10499 : 378 : sep = ", ";
10500 : : }
10501 : 378 : i++;
10502 : : }
10503 [ + + ]: 186 : if (tupdesc != NULL)
10504 : : {
10505 [ - + ]: 44 : while (i < tupdesc->natts)
10506 : : {
10507 [ # # ]: 0 : if (!TupleDescCompactAttr(tupdesc, i)->attisdropped)
10508 : : {
10509 : 0 : appendStringInfoString(buf, sep);
10510 : 0 : appendStringInfoString(buf, "NULL");
10511 : 0 : sep = ", ";
10512 : : }
10513 : 0 : i++;
10514 : : }
10515 : :
10516 [ + - ]: 44 : ReleaseTupleDesc(tupdesc);
10517 : : }
10518 : 186 : appendStringInfoChar(buf, ')');
10519 [ + + ]: 186 : if (rowexpr->row_format == COERCE_EXPLICIT_CAST)
10520 : 24 : appendStringInfo(buf, "::%s",
10521 : : format_type_with_typemod(rowexpr->row_typeid, -1));
10522 : : }
10523 : 186 : break;
10524 : :
10525 : 84 : case T_RowCompareExpr:
10526 : : {
10527 : 84 : RowCompareExpr *rcexpr = (RowCompareExpr *) node;
10528 : :
10529 : : /*
10530 : : * SQL99 allows "ROW" to be omitted when there is more than
10531 : : * one column, but for simplicity we always print it. Within
10532 : : * a ROW expression, whole-row Vars need special treatment, so
10533 : : * use get_rule_list_toplevel.
10534 : : */
10535 : 84 : appendStringInfoString(buf, "(ROW(");
10536 : 84 : get_rule_list_toplevel(rcexpr->largs, context, true);
10537 : :
10538 : : /*
10539 : : * We assume that the name of the first-column operator will
10540 : : * do for all the rest too. This is definitely open to
10541 : : * failure, eg if some but not all operators were renamed
10542 : : * since the construct was parsed, but there seems no way to
10543 : : * be perfect.
10544 : : */
10545 : 84 : appendStringInfo(buf, ") %s ROW(",
10546 : 84 : generate_operator_name(linitial_oid(rcexpr->opnos),
10547 : 84 : exprType(linitial(rcexpr->largs)),
10548 : 84 : exprType(linitial(rcexpr->rargs))));
10549 : 84 : get_rule_list_toplevel(rcexpr->rargs, context, true);
10550 : 84 : appendStringInfoString(buf, "))");
10551 : : }
10552 : 84 : break;
10553 : :
10554 : 833 : case T_CoalesceExpr:
10555 : : {
10556 : 833 : CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
10557 : :
10558 : 833 : appendStringInfoString(buf, "COALESCE(");
10559 : 833 : get_rule_expr((Node *) coalesceexpr->args, context, true);
10560 : 833 : appendStringInfoChar(buf, ')');
10561 : : }
10562 : 833 : break;
10563 : :
10564 : 28 : case T_MinMaxExpr:
10565 : : {
10566 : 28 : MinMaxExpr *minmaxexpr = (MinMaxExpr *) node;
10567 : :
10568 [ + + - ]: 28 : switch (minmaxexpr->op)
10569 : : {
10570 : 8 : case IS_GREATEST:
10571 : 8 : appendStringInfoString(buf, "GREATEST(");
10572 : 8 : break;
10573 : 20 : case IS_LEAST:
10574 : 20 : appendStringInfoString(buf, "LEAST(");
10575 : 20 : break;
10576 : : }
10577 : 28 : get_rule_expr((Node *) minmaxexpr->args, context, true);
10578 : 28 : appendStringInfoChar(buf, ')');
10579 : : }
10580 : 28 : break;
10581 : :
10582 : 449 : case T_SQLValueFunction:
10583 : : {
10584 : 449 : SQLValueFunction *svf = (SQLValueFunction *) node;
10585 : :
10586 : : /*
10587 : : * Note: this code knows that typmod for time, timestamp, and
10588 : : * timestamptz just prints as integer.
10589 : : */
10590 [ + + + + : 449 : switch (svf->op)
+ + + + +
+ + + + +
+ - ]
10591 : : {
10592 : 69 : case SVFOP_CURRENT_DATE:
10593 : 69 : appendStringInfoString(buf, "CURRENT_DATE");
10594 : 69 : break;
10595 : 8 : case SVFOP_CURRENT_TIME:
10596 : 8 : appendStringInfoString(buf, "CURRENT_TIME");
10597 : 8 : break;
10598 : 8 : case SVFOP_CURRENT_TIME_N:
10599 : 8 : appendStringInfo(buf, "CURRENT_TIME(%d)", svf->typmod);
10600 : 8 : break;
10601 : 8 : case SVFOP_CURRENT_TIMESTAMP:
10602 : 8 : appendStringInfoString(buf, "CURRENT_TIMESTAMP");
10603 : 8 : break;
10604 : 75 : case SVFOP_CURRENT_TIMESTAMP_N:
10605 : 75 : appendStringInfo(buf, "CURRENT_TIMESTAMP(%d)",
10606 : : svf->typmod);
10607 : 75 : break;
10608 : 8 : case SVFOP_LOCALTIME:
10609 : 8 : appendStringInfoString(buf, "LOCALTIME");
10610 : 8 : break;
10611 : 8 : case SVFOP_LOCALTIME_N:
10612 : 8 : appendStringInfo(buf, "LOCALTIME(%d)", svf->typmod);
10613 : 8 : break;
10614 : 20 : case SVFOP_LOCALTIMESTAMP:
10615 : 20 : appendStringInfoString(buf, "LOCALTIMESTAMP");
10616 : 20 : break;
10617 : 12 : case SVFOP_LOCALTIMESTAMP_N:
10618 : 12 : appendStringInfo(buf, "LOCALTIMESTAMP(%d)",
10619 : : svf->typmod);
10620 : 12 : break;
10621 : 8 : case SVFOP_CURRENT_ROLE:
10622 : 8 : appendStringInfoString(buf, "CURRENT_ROLE");
10623 : 8 : break;
10624 : 181 : case SVFOP_CURRENT_USER:
10625 : 181 : appendStringInfoString(buf, "CURRENT_USER");
10626 : 181 : break;
10627 : 8 : case SVFOP_USER:
10628 : 8 : appendStringInfoString(buf, "USER");
10629 : 8 : break;
10630 : 20 : case SVFOP_SESSION_USER:
10631 : 20 : appendStringInfoString(buf, "SESSION_USER");
10632 : 20 : break;
10633 : 8 : case SVFOP_CURRENT_CATALOG:
10634 : 8 : appendStringInfoString(buf, "CURRENT_CATALOG");
10635 : 8 : break;
10636 : 8 : case SVFOP_CURRENT_SCHEMA:
10637 : 8 : appendStringInfoString(buf, "CURRENT_SCHEMA");
10638 : 8 : break;
10639 : : }
10640 : : }
10641 : 449 : break;
10642 : :
10643 : 99 : case T_XmlExpr:
10644 : : {
10645 : 99 : XmlExpr *xexpr = (XmlExpr *) node;
10646 : 99 : bool needcomma = false;
10647 : : ListCell *arg;
10648 : : ListCell *narg;
10649 : : Const *con;
10650 : :
10651 [ + + + + : 99 : switch (xexpr->op)
+ + + -
- ]
10652 : : {
10653 : 9 : case IS_XMLCONCAT:
10654 : 9 : appendStringInfoString(buf, "XMLCONCAT(");
10655 : 9 : break;
10656 : 18 : case IS_XMLELEMENT:
10657 : 18 : appendStringInfoString(buf, "XMLELEMENT(");
10658 : 18 : break;
10659 : 9 : case IS_XMLFOREST:
10660 : 9 : appendStringInfoString(buf, "XMLFOREST(");
10661 : 9 : break;
10662 : 9 : case IS_XMLPARSE:
10663 : 9 : appendStringInfoString(buf, "XMLPARSE(");
10664 : 9 : break;
10665 : 9 : case IS_XMLPI:
10666 : 9 : appendStringInfoString(buf, "XMLPI(");
10667 : 9 : break;
10668 : 9 : case IS_XMLROOT:
10669 : 9 : appendStringInfoString(buf, "XMLROOT(");
10670 : 9 : break;
10671 : 36 : case IS_XMLSERIALIZE:
10672 : 36 : appendStringInfoString(buf, "XMLSERIALIZE(");
10673 : 36 : break;
10674 : 0 : case IS_DOCUMENT:
10675 : 0 : break;
10676 : : }
10677 [ + + + + ]: 99 : if (xexpr->op == IS_XMLPARSE || xexpr->op == IS_XMLSERIALIZE)
10678 : : {
10679 [ + + ]: 45 : if (xexpr->xmloption == XMLOPTION_DOCUMENT)
10680 : 18 : appendStringInfoString(buf, "DOCUMENT ");
10681 : : else
10682 : 27 : appendStringInfoString(buf, "CONTENT ");
10683 : : }
10684 [ + + ]: 99 : if (xexpr->name)
10685 : : {
10686 : 27 : appendStringInfo(buf, "NAME %s",
10687 : 27 : quote_identifier(map_xml_name_to_sql_identifier(xexpr->name)));
10688 : 27 : needcomma = true;
10689 : : }
10690 [ + + ]: 99 : if (xexpr->named_args)
10691 : : {
10692 [ + + ]: 18 : if (xexpr->op != IS_XMLFOREST)
10693 : : {
10694 [ + - ]: 9 : if (needcomma)
10695 : 9 : appendStringInfoString(buf, ", ");
10696 : 9 : appendStringInfoString(buf, "XMLATTRIBUTES(");
10697 : 9 : needcomma = false;
10698 : : }
10699 [ + - + + : 63 : forboth(arg, xexpr->named_args, narg, xexpr->arg_names)
+ - + + +
+ + - +
+ ]
10700 : : {
10701 : 45 : Node *e = (Node *) lfirst(arg);
10702 : 45 : char *argname = strVal(lfirst(narg));
10703 : :
10704 [ + + ]: 45 : if (needcomma)
10705 : 27 : appendStringInfoString(buf, ", ");
10706 : 45 : get_rule_expr(e, context, true);
10707 : 45 : appendStringInfo(buf, " AS %s",
10708 : 45 : quote_identifier(map_xml_name_to_sql_identifier(argname)));
10709 : 45 : needcomma = true;
10710 : : }
10711 [ + + ]: 18 : if (xexpr->op != IS_XMLFOREST)
10712 : 9 : appendStringInfoChar(buf, ')');
10713 : : }
10714 [ + + ]: 99 : if (xexpr->args)
10715 : : {
10716 [ + + ]: 90 : if (needcomma)
10717 : 27 : appendStringInfoString(buf, ", ");
10718 [ + + + - : 90 : switch (xexpr->op)
- ]
10719 : : {
10720 : 72 : case IS_XMLCONCAT:
10721 : : case IS_XMLELEMENT:
10722 : : case IS_XMLFOREST:
10723 : : case IS_XMLPI:
10724 : : case IS_XMLSERIALIZE:
10725 : : /* no extra decoration needed */
10726 : 72 : get_rule_expr((Node *) xexpr->args, context, true);
10727 : 72 : break;
10728 : 9 : case IS_XMLPARSE:
10729 : : Assert(list_length(xexpr->args) == 2);
10730 : :
10731 : 9 : get_rule_expr((Node *) linitial(xexpr->args),
10732 : : context, true);
10733 : :
10734 : 9 : con = lsecond_node(Const, xexpr->args);
10735 : : Assert(!con->constisnull);
10736 [ - + ]: 9 : if (DatumGetBool(con->constvalue))
10737 : 0 : appendStringInfoString(buf,
10738 : : " PRESERVE WHITESPACE");
10739 : : else
10740 : 9 : appendStringInfoString(buf,
10741 : : " STRIP WHITESPACE");
10742 : 9 : break;
10743 : 9 : case IS_XMLROOT:
10744 : : Assert(list_length(xexpr->args) == 3);
10745 : :
10746 : 9 : get_rule_expr((Node *) linitial(xexpr->args),
10747 : : context, true);
10748 : :
10749 : 9 : appendStringInfoString(buf, ", VERSION ");
10750 : 9 : con = (Const *) lsecond(xexpr->args);
10751 [ + - ]: 9 : if (IsA(con, Const) &&
10752 [ + - ]: 9 : con->constisnull)
10753 : 9 : appendStringInfoString(buf, "NO VALUE");
10754 : : else
10755 : 0 : get_rule_expr((Node *) con, context, false);
10756 : :
10757 : 9 : con = lthird_node(Const, xexpr->args);
10758 [ + - ]: 9 : if (con->constisnull)
10759 : : /* suppress STANDALONE NO VALUE */ ;
10760 : : else
10761 : : {
10762 [ + - - - ]: 9 : switch (DatumGetInt32(con->constvalue))
10763 : : {
10764 : 9 : case XML_STANDALONE_YES:
10765 : 9 : appendStringInfoString(buf,
10766 : : ", STANDALONE YES");
10767 : 9 : break;
10768 : 0 : case XML_STANDALONE_NO:
10769 : 0 : appendStringInfoString(buf,
10770 : : ", STANDALONE NO");
10771 : 0 : break;
10772 : 0 : case XML_STANDALONE_NO_VALUE:
10773 : 0 : appendStringInfoString(buf,
10774 : : ", STANDALONE NO VALUE");
10775 : 0 : break;
10776 : 0 : default:
10777 : 0 : break;
10778 : : }
10779 : : }
10780 : 9 : break;
10781 : 0 : case IS_DOCUMENT:
10782 : 0 : get_rule_expr_paren((Node *) xexpr->args, context, false, node);
10783 : 0 : break;
10784 : : }
10785 : : }
10786 [ + + ]: 99 : if (xexpr->op == IS_XMLSERIALIZE)
10787 : : {
10788 : 36 : appendStringInfo(buf, " AS %s",
10789 : : format_type_with_typemod(xexpr->type,
10790 : : xexpr->typmod));
10791 [ + + ]: 36 : if (xexpr->indent)
10792 : 9 : appendStringInfoString(buf, " INDENT");
10793 : : else
10794 : 27 : appendStringInfoString(buf, " NO INDENT");
10795 : : }
10796 : :
10797 [ - + ]: 99 : if (xexpr->op == IS_DOCUMENT)
10798 : 0 : appendStringInfoString(buf, " IS DOCUMENT");
10799 : : else
10800 : 99 : appendStringInfoChar(buf, ')');
10801 : : }
10802 : 99 : break;
10803 : :
10804 : 1846 : case T_NullTest:
10805 : : {
10806 : 1846 : NullTest *ntest = (NullTest *) node;
10807 : :
10808 [ + + ]: 1846 : if (!PRETTY_PAREN(context))
10809 : 1806 : appendStringInfoChar(buf, '(');
10810 : 1846 : get_rule_expr_paren((Node *) ntest->arg, context, true, node);
10811 : :
10812 : : /*
10813 : : * For scalar inputs, we prefer to print as IS [NOT] NULL,
10814 : : * which is shorter and traditional. If it's a rowtype input
10815 : : * but we're applying a scalar test, must print IS [NOT]
10816 : : * DISTINCT FROM NULL to be semantically correct.
10817 : : */
10818 [ + + ]: 1846 : if (ntest->argisrow ||
10819 [ + + ]: 1800 : !type_is_rowtype(exprType((Node *) ntest->arg)))
10820 : : {
10821 [ + + - ]: 1826 : switch (ntest->nulltesttype)
10822 : : {
10823 : 580 : case IS_NULL:
10824 : 580 : appendStringInfoString(buf, " IS NULL");
10825 : 580 : break;
10826 : 1246 : case IS_NOT_NULL:
10827 : 1246 : appendStringInfoString(buf, " IS NOT NULL");
10828 : 1246 : break;
10829 : 0 : default:
10830 [ # # ]: 0 : elog(ERROR, "unrecognized nulltesttype: %d",
10831 : : (int) ntest->nulltesttype);
10832 : : }
10833 : : }
10834 : : else
10835 : : {
10836 [ + + - ]: 20 : switch (ntest->nulltesttype)
10837 : : {
10838 : 8 : case IS_NULL:
10839 : 8 : appendStringInfoString(buf, " IS NOT DISTINCT FROM NULL");
10840 : 8 : break;
10841 : 12 : case IS_NOT_NULL:
10842 : 12 : appendStringInfoString(buf, " IS DISTINCT FROM NULL");
10843 : 12 : break;
10844 : 0 : default:
10845 [ # # ]: 0 : elog(ERROR, "unrecognized nulltesttype: %d",
10846 : : (int) ntest->nulltesttype);
10847 : : }
10848 : : }
10849 [ + + ]: 1846 : if (!PRETTY_PAREN(context))
10850 : 1806 : appendStringInfoChar(buf, ')');
10851 : : }
10852 : 1846 : break;
10853 : :
10854 : 212 : case T_BooleanTest:
10855 : : {
10856 : 212 : BooleanTest *btest = (BooleanTest *) node;
10857 : :
10858 [ + - ]: 212 : if (!PRETTY_PAREN(context))
10859 : 212 : appendStringInfoChar(buf, '(');
10860 : 212 : get_rule_expr_paren((Node *) btest->arg, context, false, node);
10861 [ + + - + : 212 : switch (btest->booltesttype)
+ + - ]
10862 : : {
10863 : 28 : case IS_TRUE:
10864 : 28 : appendStringInfoString(buf, " IS TRUE");
10865 : 28 : break;
10866 : 92 : case IS_NOT_TRUE:
10867 : 92 : appendStringInfoString(buf, " IS NOT TRUE");
10868 : 92 : break;
10869 : 0 : case IS_FALSE:
10870 : 0 : appendStringInfoString(buf, " IS FALSE");
10871 : 0 : break;
10872 : 36 : case IS_NOT_FALSE:
10873 : 36 : appendStringInfoString(buf, " IS NOT FALSE");
10874 : 36 : break;
10875 : 20 : case IS_UNKNOWN:
10876 : 20 : appendStringInfoString(buf, " IS UNKNOWN");
10877 : 20 : break;
10878 : 36 : case IS_NOT_UNKNOWN:
10879 : 36 : appendStringInfoString(buf, " IS NOT UNKNOWN");
10880 : 36 : break;
10881 : 0 : default:
10882 [ # # ]: 0 : elog(ERROR, "unrecognized booltesttype: %d",
10883 : : (int) btest->booltesttype);
10884 : : }
10885 [ + - ]: 212 : if (!PRETTY_PAREN(context))
10886 : 212 : appendStringInfoChar(buf, ')');
10887 : : }
10888 : 212 : break;
10889 : :
10890 : 79 : case T_CoerceToDomain:
10891 : : {
10892 : 79 : CoerceToDomain *ctest = (CoerceToDomain *) node;
10893 : 79 : Node *arg = (Node *) ctest->arg;
10894 : :
10895 [ + + ]: 79 : if (ctest->coercionformat == COERCE_IMPLICIT_CAST &&
10896 [ + + ]: 36 : !showimplicit)
10897 : : {
10898 : : /* don't show the implicit cast */
10899 : 28 : get_rule_expr(arg, context, false);
10900 : : }
10901 : : else
10902 : : {
10903 : 51 : get_coercion_expr(arg, context,
10904 : : ctest->resulttype,
10905 : : ctest->resulttypmod,
10906 : : node);
10907 : : }
10908 : : }
10909 : 79 : break;
10910 : :
10911 : 280 : case T_CoerceToDomainValue:
10912 : 280 : appendStringInfoString(buf, "VALUE");
10913 : 280 : break;
10914 : :
10915 : 44 : case T_SetToDefault:
10916 : 44 : appendStringInfoString(buf, "DEFAULT");
10917 : 44 : break;
10918 : :
10919 : 16 : case T_CurrentOfExpr:
10920 : : {
10921 : 16 : CurrentOfExpr *cexpr = (CurrentOfExpr *) node;
10922 : :
10923 [ + - ]: 16 : if (cexpr->cursor_name)
10924 : 16 : appendStringInfo(buf, "CURRENT OF %s",
10925 : 16 : quote_identifier(cexpr->cursor_name));
10926 : : else
10927 : 0 : appendStringInfo(buf, "CURRENT OF $%d",
10928 : : cexpr->cursor_param);
10929 : : }
10930 : 16 : break;
10931 : :
10932 : 0 : case T_NextValueExpr:
10933 : : {
10934 : 0 : NextValueExpr *nvexpr = (NextValueExpr *) node;
10935 : :
10936 : : /*
10937 : : * This isn't exactly nextval(), but that seems close enough
10938 : : * for EXPLAIN's purposes.
10939 : : */
10940 : 0 : appendStringInfoString(buf, "nextval(");
10941 : 0 : simple_quote_literal(buf,
10942 : 0 : generate_relation_name(nvexpr->seqid,
10943 : : NIL));
10944 : 0 : appendStringInfoChar(buf, ')');
10945 : : }
10946 : 0 : break;
10947 : :
10948 : 20 : case T_InferenceElem:
10949 : : {
10950 : 20 : InferenceElem *iexpr = (InferenceElem *) node;
10951 : : bool save_varprefix;
10952 : : bool need_parens;
10953 : :
10954 : : /*
10955 : : * InferenceElem can only refer to target relation, so a
10956 : : * prefix is not useful, and indeed would cause parse errors.
10957 : : */
10958 : 20 : save_varprefix = context->varprefix;
10959 : 20 : context->varprefix = false;
10960 : :
10961 : : /*
10962 : : * Parenthesize the element unless it's a simple Var or a bare
10963 : : * function call. Follows pg_get_indexdef_worker().
10964 : : */
10965 : 20 : need_parens = !IsA(iexpr->expr, Var);
10966 [ - + ]: 20 : if (IsA(iexpr->expr, FuncExpr) &&
10967 [ # # ]: 0 : ((FuncExpr *) iexpr->expr)->funcformat ==
10968 : : COERCE_EXPLICIT_CALL)
10969 : 0 : need_parens = false;
10970 : :
10971 [ - + ]: 20 : if (need_parens)
10972 : 0 : appendStringInfoChar(buf, '(');
10973 : 20 : get_rule_expr((Node *) iexpr->expr,
10974 : : context, false);
10975 [ - + ]: 20 : if (need_parens)
10976 : 0 : appendStringInfoChar(buf, ')');
10977 : :
10978 : 20 : context->varprefix = save_varprefix;
10979 : :
10980 [ + + ]: 20 : if (iexpr->infercollid)
10981 : 8 : appendStringInfo(buf, " COLLATE %s",
10982 : : generate_collation_name(iexpr->infercollid));
10983 : :
10984 : : /* Add the operator class name, if not default */
10985 [ + + ]: 20 : if (iexpr->inferopclass)
10986 : : {
10987 : 8 : Oid inferopclass = iexpr->inferopclass;
10988 : 8 : Oid inferopcinputtype = get_opclass_input_type(iexpr->inferopclass);
10989 : :
10990 : 8 : get_opclass_name(inferopclass, inferopcinputtype, buf);
10991 : : }
10992 : : }
10993 : 20 : break;
10994 : :
10995 : 8 : case T_ReturningExpr:
10996 : : {
10997 : 8 : ReturningExpr *retExpr = (ReturningExpr *) node;
10998 : :
10999 : : /*
11000 : : * We cannot see a ReturningExpr in rule deparsing, only while
11001 : : * EXPLAINing a query plan (ReturningExpr nodes are only ever
11002 : : * adding during query rewriting). Just display the expression
11003 : : * returned (an expanded view column).
11004 : : */
11005 : 8 : get_rule_expr((Node *) retExpr->retexpr, context, showimplicit);
11006 : : }
11007 : 8 : break;
11008 : :
11009 : 2769 : case T_PartitionBoundSpec:
11010 : : {
11011 : 2769 : PartitionBoundSpec *spec = (PartitionBoundSpec *) node;
11012 : : ListCell *cell;
11013 : : char *sep;
11014 : :
11015 [ + + ]: 2769 : if (spec->is_default)
11016 : : {
11017 : 161 : appendStringInfoString(buf, "DEFAULT");
11018 : 161 : break;
11019 : : }
11020 : :
11021 [ + + + - ]: 2608 : switch (spec->strategy)
11022 : : {
11023 : 165 : case PARTITION_STRATEGY_HASH:
11024 : : Assert(spec->modulus > 0 && spec->remainder >= 0);
11025 : : Assert(spec->modulus > spec->remainder);
11026 : :
11027 : 165 : appendStringInfoString(buf, "FOR VALUES");
11028 : 165 : appendStringInfo(buf, " WITH (modulus %d, remainder %d)",
11029 : : spec->modulus, spec->remainder);
11030 : 165 : break;
11031 : :
11032 : 874 : case PARTITION_STRATEGY_LIST:
11033 : : Assert(spec->listdatums != NIL);
11034 : :
11035 : 874 : appendStringInfoString(buf, "FOR VALUES IN (");
11036 : 874 : sep = "";
11037 [ + - + + : 2376 : foreach(cell, spec->listdatums)
+ + ]
11038 : : {
11039 : 1502 : Const *val = lfirst_node(Const, cell);
11040 : :
11041 : 1502 : appendStringInfoString(buf, sep);
11042 : 1502 : get_const_expr(val, context, -1);
11043 : 1502 : sep = ", ";
11044 : : }
11045 : :
11046 : 874 : appendStringInfoChar(buf, ')');
11047 : 874 : break;
11048 : :
11049 : 1569 : case PARTITION_STRATEGY_RANGE:
11050 : : Assert(spec->lowerdatums != NIL &&
11051 : : spec->upperdatums != NIL &&
11052 : : list_length(spec->lowerdatums) ==
11053 : : list_length(spec->upperdatums));
11054 : :
11055 : 1569 : appendStringInfo(buf, "FOR VALUES FROM %s TO %s",
11056 : : get_range_partbound_string(spec->lowerdatums),
11057 : : get_range_partbound_string(spec->upperdatums));
11058 : 1569 : break;
11059 : :
11060 : 0 : default:
11061 [ # # ]: 0 : elog(ERROR, "unrecognized partition strategy: %d",
11062 : : (int) spec->strategy);
11063 : : break;
11064 : : }
11065 : : }
11066 : 2608 : break;
11067 : :
11068 : 104 : case T_JsonValueExpr:
11069 : : {
11070 : 104 : JsonValueExpr *jve = (JsonValueExpr *) node;
11071 : :
11072 : 104 : get_rule_expr((Node *) jve->raw_expr, context, false);
11073 : 104 : get_json_format(jve->format, context->buf);
11074 : : }
11075 : 104 : break;
11076 : :
11077 : 176 : case T_JsonConstructorExpr:
11078 : 176 : get_json_constructor((JsonConstructorExpr *) node, context, false);
11079 : 176 : break;
11080 : :
11081 : 52 : case T_JsonIsPredicate:
11082 : : {
11083 : 52 : JsonIsPredicate *pred = (JsonIsPredicate *) node;
11084 : :
11085 [ + + ]: 52 : if (!PRETTY_PAREN(context))
11086 : 20 : appendStringInfoChar(context->buf, '(');
11087 : :
11088 : 52 : get_rule_expr_paren(pred->expr, context, true, node);
11089 : :
11090 : 52 : appendStringInfoString(context->buf, " IS JSON");
11091 : :
11092 : : /* TODO: handle FORMAT clause */
11093 : :
11094 [ + + + + ]: 52 : switch (pred->item_type)
11095 : : {
11096 : 8 : case JS_TYPE_SCALAR:
11097 : 8 : appendStringInfoString(context->buf, " SCALAR");
11098 : 8 : break;
11099 : 8 : case JS_TYPE_ARRAY:
11100 : 8 : appendStringInfoString(context->buf, " ARRAY");
11101 : 8 : break;
11102 : 8 : case JS_TYPE_OBJECT:
11103 : 8 : appendStringInfoString(context->buf, " OBJECT");
11104 : 8 : break;
11105 : 28 : default:
11106 : 28 : break;
11107 : : }
11108 : :
11109 [ + + ]: 52 : if (pred->unique_keys)
11110 : 20 : appendStringInfoString(context->buf, " WITH UNIQUE KEYS");
11111 : :
11112 [ + + ]: 52 : if (!PRETTY_PAREN(context))
11113 : 20 : appendStringInfoChar(context->buf, ')');
11114 : : }
11115 : 52 : break;
11116 : :
11117 : 40 : case T_JsonExpr:
11118 : : {
11119 : 40 : JsonExpr *jexpr = (JsonExpr *) node;
11120 : :
11121 [ + + + - ]: 40 : switch (jexpr->op)
11122 : : {
11123 : 8 : case JSON_EXISTS_OP:
11124 : 8 : appendStringInfoString(buf, "JSON_EXISTS(");
11125 : 8 : break;
11126 : 24 : case JSON_QUERY_OP:
11127 : 24 : appendStringInfoString(buf, "JSON_QUERY(");
11128 : 24 : break;
11129 : 8 : case JSON_VALUE_OP:
11130 : 8 : appendStringInfoString(buf, "JSON_VALUE(");
11131 : 8 : break;
11132 : 0 : default:
11133 [ # # ]: 0 : elog(ERROR, "unrecognized JsonExpr op: %d",
11134 : : (int) jexpr->op);
11135 : : }
11136 : :
11137 : 40 : get_rule_expr(jexpr->formatted_expr, context, showimplicit);
11138 : :
11139 : 40 : appendStringInfoString(buf, ", ");
11140 : :
11141 : 40 : get_json_path_spec(jexpr->path_spec, context, showimplicit);
11142 : :
11143 [ + + ]: 40 : if (jexpr->passing_values)
11144 : : {
11145 : : ListCell *lc1,
11146 : : *lc2;
11147 : 8 : bool needcomma = false;
11148 : :
11149 : 8 : appendStringInfoString(buf, " PASSING ");
11150 : :
11151 [ + - + + : 32 : forboth(lc1, jexpr->passing_names,
+ - + + +
+ + - +
+ ]
11152 : : lc2, jexpr->passing_values)
11153 : : {
11154 [ + + ]: 24 : if (needcomma)
11155 : 16 : appendStringInfoString(buf, ", ");
11156 : 24 : needcomma = true;
11157 : :
11158 : 24 : get_rule_expr((Node *) lfirst(lc2), context, showimplicit);
11159 : 24 : appendStringInfo(buf, " AS %s",
11160 : 24 : quote_identifier(lfirst_node(String, lc1)->sval));
11161 : : }
11162 : : }
11163 : :
11164 [ + + ]: 40 : if (jexpr->op != JSON_EXISTS_OP ||
11165 [ - + ]: 8 : jexpr->returning->typid != BOOLOID)
11166 : 32 : get_json_returning(jexpr->returning, context->buf,
11167 : 32 : jexpr->op == JSON_QUERY_OP);
11168 : :
11169 : 40 : get_json_expr_options(jexpr, context,
11170 [ + + ]: 40 : jexpr->op != JSON_EXISTS_OP ?
11171 : : JSON_BEHAVIOR_NULL :
11172 : : JSON_BEHAVIOR_FALSE);
11173 : :
11174 : 40 : appendStringInfoChar(buf, ')');
11175 : : }
11176 : 40 : break;
11177 : :
11178 : 1870 : case T_List:
11179 : : {
11180 : : char *sep;
11181 : : ListCell *l;
11182 : :
11183 : 1870 : sep = "";
11184 [ + - + + : 5284 : foreach(l, (List *) node)
+ + ]
11185 : : {
11186 : 3414 : appendStringInfoString(buf, sep);
11187 : 3414 : get_rule_expr((Node *) lfirst(l), context, showimplicit);
11188 : 3414 : sep = ", ";
11189 : : }
11190 : : }
11191 : 1870 : break;
11192 : :
11193 : 52 : case T_TableFunc:
11194 : 52 : get_tablefunc((TableFunc *) node, context, showimplicit);
11195 : 52 : break;
11196 : :
11197 : 55 : case T_GraphPropertyRef:
11198 : : {
11199 : 55 : GraphPropertyRef *gpr = (GraphPropertyRef *) node;
11200 : :
11201 : 55 : appendStringInfo(buf, "%s.%s", quote_identifier(gpr->elvarname), quote_identifier(get_propgraph_property_name(gpr->propid)));
11202 : 55 : break;
11203 : : }
11204 : :
11205 : 0 : default:
11206 [ # # ]: 0 : elog(ERROR, "unrecognized node type: %d", (int) nodeTag(node));
11207 : : break;
11208 : : }
11209 : : }
11210 : :
11211 : : /*
11212 : : * get_rule_expr_toplevel - Parse back a toplevel expression
11213 : : *
11214 : : * Same as get_rule_expr(), except that if the expr is just a Var, we pass
11215 : : * istoplevel = true not false to get_variable(). This causes whole-row Vars
11216 : : * to get printed with decoration that will prevent expansion of "*".
11217 : : * We need to use this in contexts such as ROW() and VALUES(), where the
11218 : : * parser would expand "foo.*" appearing at top level. (In principle we'd
11219 : : * use this in get_target_list() too, but that has additional worries about
11220 : : * whether to print AS, so it needs to invoke get_variable() directly anyway.)
11221 : : */
11222 : : static void
11223 : 2131 : get_rule_expr_toplevel(Node *node, deparse_context *context,
11224 : : bool showimplicit)
11225 : : {
11226 [ + - + + ]: 2131 : if (node && IsA(node, Var))
11227 : 798 : (void) get_variable((Var *) node, 0, true, context);
11228 : : else
11229 : 1333 : get_rule_expr(node, context, showimplicit);
11230 : 2131 : }
11231 : :
11232 : : /*
11233 : : * get_rule_list_toplevel - Parse back a list of toplevel expressions
11234 : : *
11235 : : * Apply get_rule_expr_toplevel() to each element of a List.
11236 : : *
11237 : : * This adds commas between the expressions, but caller is responsible
11238 : : * for printing surrounding decoration.
11239 : : */
11240 : : static void
11241 : 326 : get_rule_list_toplevel(List *lst, deparse_context *context,
11242 : : bool showimplicit)
11243 : : {
11244 : : const char *sep;
11245 : : ListCell *lc;
11246 : :
11247 : 326 : sep = "";
11248 [ + - + + : 1087 : foreach(lc, lst)
+ + ]
11249 : : {
11250 : 761 : Node *e = (Node *) lfirst(lc);
11251 : :
11252 : 761 : appendStringInfoString(context->buf, sep);
11253 : 761 : get_rule_expr_toplevel(e, context, showimplicit);
11254 : 761 : sep = ", ";
11255 : : }
11256 : 326 : }
11257 : :
11258 : : /*
11259 : : * get_rule_expr_funccall - Parse back a function-call expression
11260 : : *
11261 : : * Same as get_rule_expr(), except that we guarantee that the output will
11262 : : * look like a function call, or like one of the things the grammar treats as
11263 : : * equivalent to a function call (see the func_expr_windowless production).
11264 : : * This is needed in places where the grammar uses func_expr_windowless and
11265 : : * you can't substitute a parenthesized a_expr. If what we have isn't going
11266 : : * to look like a function call, wrap it in a dummy CAST() expression, which
11267 : : * will satisfy the grammar --- and, indeed, is likely what the user wrote to
11268 : : * produce such a thing.
11269 : : */
11270 : : static void
11271 : 572 : get_rule_expr_funccall(Node *node, deparse_context *context,
11272 : : bool showimplicit)
11273 : : {
11274 [ + + ]: 572 : if (looks_like_function(node))
11275 : 564 : get_rule_expr(node, context, showimplicit);
11276 : : else
11277 : : {
11278 : 8 : StringInfo buf = context->buf;
11279 : :
11280 : 8 : appendStringInfoString(buf, "CAST(");
11281 : : /* no point in showing any top-level implicit cast */
11282 : 8 : get_rule_expr(node, context, false);
11283 : 8 : appendStringInfo(buf, " AS %s)",
11284 : : format_type_with_typemod(exprType(node),
11285 : : exprTypmod(node)));
11286 : : }
11287 : 572 : }
11288 : :
11289 : : /*
11290 : : * Helper function to identify node types that satisfy func_expr_windowless.
11291 : : * If in doubt, "false" is always a safe answer.
11292 : : */
11293 : : static bool
11294 : 1335 : looks_like_function(Node *node)
11295 : : {
11296 [ - + ]: 1335 : if (node == NULL)
11297 : 0 : return false; /* probably shouldn't happen */
11298 [ + + + ]: 1335 : switch (nodeTag(node))
11299 : : {
11300 : 584 : case T_FuncExpr:
11301 : : /* OK, unless it's going to deparse as a cast */
11302 [ + + ]: 596 : return (((FuncExpr *) node)->funcformat == COERCE_EXPLICIT_CALL ||
11303 [ + + ]: 12 : ((FuncExpr *) node)->funcformat == COERCE_SQL_SYNTAX);
11304 : 72 : case T_NullIfExpr:
11305 : : case T_CoalesceExpr:
11306 : : case T_MinMaxExpr:
11307 : : case T_SQLValueFunction:
11308 : : case T_XmlExpr:
11309 : : case T_JsonExpr:
11310 : : /* these are all accepted by func_expr_common_subexpr */
11311 : 72 : return true;
11312 : 679 : default:
11313 : 679 : break;
11314 : : }
11315 : 679 : return false;
11316 : : }
11317 : :
11318 : :
11319 : : /*
11320 : : * get_oper_expr - Parse back an OpExpr node
11321 : : */
11322 : : static void
11323 : 41483 : get_oper_expr(OpExpr *expr, deparse_context *context)
11324 : : {
11325 : 41483 : StringInfo buf = context->buf;
11326 : 41483 : Oid opno = expr->opno;
11327 : 41483 : List *args = expr->args;
11328 : :
11329 [ + + ]: 41483 : if (!PRETTY_PAREN(context))
11330 : 39859 : appendStringInfoChar(buf, '(');
11331 [ + + ]: 41483 : if (list_length(args) == 2)
11332 : : {
11333 : : /* binary operator */
11334 : 41463 : Node *arg1 = (Node *) linitial(args);
11335 : 41463 : Node *arg2 = (Node *) lsecond(args);
11336 : :
11337 : 41463 : get_rule_expr_paren(arg1, context, true, (Node *) expr);
11338 : 41463 : appendStringInfo(buf, " %s ",
11339 : : generate_operator_name(opno,
11340 : : exprType(arg1),
11341 : : exprType(arg2)));
11342 : 41463 : get_rule_expr_paren(arg2, context, true, (Node *) expr);
11343 : : }
11344 : : else
11345 : : {
11346 : : /* prefix operator */
11347 : 20 : Node *arg = (Node *) linitial(args);
11348 : :
11349 : 20 : appendStringInfo(buf, "%s ",
11350 : : generate_operator_name(opno,
11351 : : InvalidOid,
11352 : : exprType(arg)));
11353 : 20 : get_rule_expr_paren(arg, context, true, (Node *) expr);
11354 : : }
11355 [ + + ]: 41483 : if (!PRETTY_PAREN(context))
11356 : 39859 : appendStringInfoChar(buf, ')');
11357 : 41483 : }
11358 : :
11359 : : /*
11360 : : * get_func_expr - Parse back a FuncExpr node
11361 : : */
11362 : : static void
11363 : 8212 : get_func_expr(FuncExpr *expr, deparse_context *context,
11364 : : bool showimplicit)
11365 : : {
11366 : 8212 : StringInfo buf = context->buf;
11367 : 8212 : Oid funcoid = expr->funcid;
11368 : : Oid argtypes[FUNC_MAX_ARGS];
11369 : : int nargs;
11370 : : List *argnames;
11371 : : bool use_variadic;
11372 : : ListCell *l;
11373 : :
11374 : : /*
11375 : : * If the function call came from an implicit coercion, then just show the
11376 : : * first argument --- unless caller wants to see implicit coercions.
11377 : : */
11378 [ + + + + ]: 8212 : if (expr->funcformat == COERCE_IMPLICIT_CAST && !showimplicit)
11379 : : {
11380 : 781 : get_rule_expr_paren((Node *) linitial(expr->args), context,
11381 : : false, (Node *) expr);
11382 : 2038 : return;
11383 : : }
11384 : :
11385 : : /*
11386 : : * If the function call came from a cast, then show the first argument
11387 : : * plus an explicit cast operation.
11388 : : */
11389 [ + + ]: 7431 : if (expr->funcformat == COERCE_EXPLICIT_CAST ||
11390 [ + + ]: 6973 : expr->funcformat == COERCE_IMPLICIT_CAST)
11391 : : {
11392 : 1141 : Node *arg = linitial(expr->args);
11393 : 1141 : Oid rettype = expr->funcresulttype;
11394 : : int32 coercedTypmod;
11395 : :
11396 : : /* Get the typmod if this is a length-coercion function */
11397 : 1141 : (void) exprIsLengthCoercion((Node *) expr, &coercedTypmod);
11398 : :
11399 : 1141 : get_coercion_expr(arg, context,
11400 : : rettype, coercedTypmod,
11401 : : (Node *) expr);
11402 : :
11403 : 1141 : return;
11404 : : }
11405 : :
11406 : : /*
11407 : : * If the function was called using one of the SQL spec's random special
11408 : : * syntaxes, try to reproduce that. If we don't recognize the function,
11409 : : * fall through.
11410 : : */
11411 [ + + ]: 6290 : if (expr->funcformat == COERCE_SQL_SYNTAX)
11412 : : {
11413 [ + + ]: 120 : if (get_func_sql_syntax(expr, context))
11414 : 116 : return;
11415 : : }
11416 : :
11417 : : /*
11418 : : * Normal function: display as proname(args). First we need to extract
11419 : : * the argument datatypes.
11420 : : */
11421 [ - + ]: 6174 : if (list_length(expr->args) > FUNC_MAX_ARGS)
11422 [ # # ]: 0 : ereport(ERROR,
11423 : : (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
11424 : : errmsg("too many arguments")));
11425 : 6174 : nargs = 0;
11426 : 6174 : argnames = NIL;
11427 [ + + + + : 12924 : foreach(l, expr->args)
+ + ]
11428 : : {
11429 : 6750 : Node *arg = (Node *) lfirst(l);
11430 : :
11431 [ + + ]: 6750 : if (IsA(arg, NamedArgExpr))
11432 : 20 : argnames = lappend(argnames, ((NamedArgExpr *) arg)->name);
11433 : 6750 : argtypes[nargs] = exprType(arg);
11434 : 6750 : nargs++;
11435 : : }
11436 : :
11437 : 6174 : appendStringInfo(buf, "%s(",
11438 : : generate_function_name(funcoid, nargs,
11439 : : argnames, argtypes,
11440 : 6174 : expr->funcvariadic,
11441 : : &use_variadic,
11442 : 6174 : context->inGroupBy));
11443 : 6174 : nargs = 0;
11444 [ + + + + : 12924 : foreach(l, expr->args)
+ + ]
11445 : : {
11446 [ + + ]: 6750 : if (nargs++ > 0)
11447 : 1334 : appendStringInfoString(buf, ", ");
11448 [ + + + - ]: 6750 : if (use_variadic && lnext(expr->args, l) == NULL)
11449 : 7 : appendStringInfoString(buf, "VARIADIC ");
11450 : 6750 : get_rule_expr((Node *) lfirst(l), context, true);
11451 : : }
11452 : 6174 : appendStringInfoChar(buf, ')');
11453 : : }
11454 : :
11455 : : /*
11456 : : * get_agg_expr - Parse back an Aggref node
11457 : : */
11458 : : static void
11459 : 3164 : get_agg_expr(Aggref *aggref, deparse_context *context,
11460 : : Aggref *original_aggref)
11461 : : {
11462 : 3164 : get_agg_expr_helper(aggref, context, original_aggref, NULL, NULL,
11463 : : false);
11464 : 3164 : }
11465 : :
11466 : : /*
11467 : : * get_agg_expr_helper - subroutine for get_agg_expr and
11468 : : * get_json_agg_constructor
11469 : : */
11470 : : static void
11471 : 3232 : get_agg_expr_helper(Aggref *aggref, deparse_context *context,
11472 : : Aggref *original_aggref, const char *funcname,
11473 : : const char *options, bool is_json_objectagg)
11474 : : {
11475 : 3232 : StringInfo buf = context->buf;
11476 : : Oid argtypes[FUNC_MAX_ARGS];
11477 : : int nargs;
11478 : 3232 : bool use_variadic = false;
11479 : :
11480 : : /*
11481 : : * For a combining aggregate, we look up and deparse the corresponding
11482 : : * partial aggregate instead. This is necessary because our input
11483 : : * argument list has been replaced; the new argument list always has just
11484 : : * one element, which will point to a partial Aggref that supplies us with
11485 : : * transition states to combine.
11486 : : */
11487 [ + + ]: 3232 : if (DO_AGGSPLIT_COMBINE(aggref->aggsplit))
11488 : : {
11489 : : TargetEntry *tle;
11490 : :
11491 : : Assert(list_length(aggref->args) == 1);
11492 : 524 : tle = linitial_node(TargetEntry, aggref->args);
11493 : 524 : resolve_special_varno((Node *) tle->expr, context,
11494 : : get_agg_combine_expr, original_aggref);
11495 : 524 : return;
11496 : : }
11497 : :
11498 : : /*
11499 : : * Mark as PARTIAL, if appropriate. We look to the original aggref so as
11500 : : * to avoid printing this when recursing from the code just above.
11501 : : */
11502 [ + + ]: 2708 : if (DO_AGGSPLIT_SKIPFINAL(original_aggref->aggsplit))
11503 : 1164 : appendStringInfoString(buf, "PARTIAL ");
11504 : :
11505 : : /* Extract the argument types as seen by the parser */
11506 : 2708 : nargs = get_aggregate_argtypes(aggref, argtypes);
11507 : :
11508 [ + + ]: 2708 : if (!funcname)
11509 : 2640 : funcname = generate_function_name(aggref->aggfnoid, nargs, NIL,
11510 : 2640 : argtypes, aggref->aggvariadic,
11511 : : &use_variadic,
11512 : 2640 : context->inGroupBy);
11513 : :
11514 : : /* Print the aggregate name, schema-qualified if needed */
11515 : 2708 : appendStringInfo(buf, "%s(%s", funcname,
11516 [ + + ]: 2708 : (aggref->aggdistinct != NIL) ? "DISTINCT " : "");
11517 : :
11518 [ + + ]: 2708 : if (AGGKIND_IS_ORDERED_SET(aggref->aggkind))
11519 : : {
11520 : : /*
11521 : : * Ordered-set aggregates do not use "*" syntax. Also, we needn't
11522 : : * worry about inserting VARIADIC. So we can just dump the direct
11523 : : * args as-is.
11524 : : */
11525 : : Assert(!aggref->aggvariadic);
11526 : 17 : get_rule_expr((Node *) aggref->aggdirectargs, context, true);
11527 : : Assert(aggref->aggorder != NIL);
11528 : 17 : appendStringInfoString(buf, ") WITHIN GROUP (ORDER BY ");
11529 : 17 : get_rule_orderby(aggref->aggorder, aggref->args, false, context);
11530 : : }
11531 : : else
11532 : : {
11533 : : /* aggstar can be set only in zero-argument aggregates */
11534 [ + + ]: 2691 : if (aggref->aggstar)
11535 : 817 : appendStringInfoChar(buf, '*');
11536 : : else
11537 : : {
11538 : : ListCell *l;
11539 : : int i;
11540 : :
11541 : 1874 : i = 0;
11542 [ + - + + : 3887 : foreach(l, aggref->args)
+ + ]
11543 : : {
11544 : 2013 : TargetEntry *tle = (TargetEntry *) lfirst(l);
11545 : 2013 : Node *arg = (Node *) tle->expr;
11546 : :
11547 : : Assert(!IsA(arg, NamedArgExpr));
11548 [ + + ]: 2013 : if (tle->resjunk)
11549 : 31 : continue;
11550 [ + + ]: 1982 : if (i++ > 0)
11551 : : {
11552 [ + + ]: 108 : if (is_json_objectagg)
11553 : : {
11554 : : /*
11555 : : * the ABSENT ON NULL and WITH UNIQUE args are printed
11556 : : * separately, so ignore them here
11557 : : */
11558 [ - + ]: 28 : if (i > 2)
11559 : 0 : break;
11560 : :
11561 : 28 : appendStringInfoString(buf, " : ");
11562 : : }
11563 : : else
11564 : 80 : appendStringInfoString(buf, ", ");
11565 : : }
11566 [ + + + - ]: 1982 : if (use_variadic && i == nargs)
11567 : 4 : appendStringInfoString(buf, "VARIADIC ");
11568 : 1982 : get_rule_expr(arg, context, true);
11569 : : }
11570 : : }
11571 : :
11572 [ + + ]: 2691 : if (aggref->aggorder != NIL)
11573 : : {
11574 : 78 : appendStringInfoString(buf, " ORDER BY ");
11575 : 78 : get_rule_orderby(aggref->aggorder, aggref->args, false, context);
11576 : : }
11577 : : }
11578 : :
11579 [ + + ]: 2708 : if (options)
11580 : 68 : appendStringInfoString(buf, options);
11581 : :
11582 [ + + ]: 2708 : if (aggref->aggfilter != NULL)
11583 : : {
11584 : 28 : appendStringInfoString(buf, ") FILTER (WHERE ");
11585 : 28 : get_rule_expr((Node *) aggref->aggfilter, context, false);
11586 : : }
11587 : :
11588 : 2708 : appendStringInfoChar(buf, ')');
11589 : : }
11590 : :
11591 : : /*
11592 : : * This is a helper function for get_agg_expr(). It's used when we deparse
11593 : : * a combining Aggref; resolve_special_varno locates the corresponding partial
11594 : : * Aggref and then calls this.
11595 : : */
11596 : : static void
11597 : 524 : get_agg_combine_expr(Node *node, deparse_context *context, void *callback_arg)
11598 : : {
11599 : : Aggref *aggref;
11600 : 524 : Aggref *original_aggref = callback_arg;
11601 : :
11602 [ - + ]: 524 : if (!IsA(node, Aggref))
11603 [ # # ]: 0 : elog(ERROR, "combining Aggref does not point to an Aggref");
11604 : :
11605 : 524 : aggref = (Aggref *) node;
11606 : 524 : get_agg_expr(aggref, context, original_aggref);
11607 : 524 : }
11608 : :
11609 : : /*
11610 : : * get_windowfunc_expr - Parse back a WindowFunc node
11611 : : */
11612 : : static void
11613 : 246 : get_windowfunc_expr(WindowFunc *wfunc, deparse_context *context)
11614 : : {
11615 : 246 : get_windowfunc_expr_helper(wfunc, context, NULL, NULL, false);
11616 : 246 : }
11617 : :
11618 : :
11619 : : /*
11620 : : * get_windowfunc_expr_helper - subroutine for get_windowfunc_expr and
11621 : : * get_json_agg_constructor
11622 : : */
11623 : : static void
11624 : 258 : get_windowfunc_expr_helper(WindowFunc *wfunc, deparse_context *context,
11625 : : const char *funcname, const char *options,
11626 : : bool is_json_objectagg)
11627 : : {
11628 : 258 : StringInfo buf = context->buf;
11629 : : Oid argtypes[FUNC_MAX_ARGS];
11630 : : int nargs;
11631 : : List *argnames;
11632 : : ListCell *l;
11633 : :
11634 [ - + ]: 258 : if (list_length(wfunc->args) > FUNC_MAX_ARGS)
11635 [ # # ]: 0 : ereport(ERROR,
11636 : : (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
11637 : : errmsg("too many arguments")));
11638 : 258 : nargs = 0;
11639 : 258 : argnames = NIL;
11640 [ + + + + : 428 : foreach(l, wfunc->args)
+ + ]
11641 : : {
11642 : 170 : Node *arg = (Node *) lfirst(l);
11643 : :
11644 [ - + ]: 170 : if (IsA(arg, NamedArgExpr))
11645 : 0 : argnames = lappend(argnames, ((NamedArgExpr *) arg)->name);
11646 : 170 : argtypes[nargs] = exprType(arg);
11647 : 170 : nargs++;
11648 : : }
11649 : :
11650 [ + + ]: 258 : if (!funcname)
11651 : 246 : funcname = generate_function_name(wfunc->winfnoid, nargs, argnames,
11652 : : argtypes, false, NULL,
11653 : 246 : context->inGroupBy);
11654 : :
11655 : 258 : appendStringInfo(buf, "%s(", funcname);
11656 : :
11657 : : /* winstar can be set only in zero-argument aggregates */
11658 [ + + ]: 258 : if (wfunc->winstar)
11659 : 28 : appendStringInfoChar(buf, '*');
11660 : : else
11661 : : {
11662 [ + + ]: 230 : if (is_json_objectagg)
11663 : : {
11664 : 4 : get_rule_expr((Node *) linitial(wfunc->args), context, false);
11665 : 4 : appendStringInfoString(buf, " : ");
11666 : 4 : get_rule_expr((Node *) lsecond(wfunc->args), context, false);
11667 : : }
11668 : : else
11669 : 226 : get_rule_expr((Node *) wfunc->args, context, true);
11670 : : }
11671 : :
11672 [ + + ]: 258 : if (options)
11673 : 12 : appendStringInfoString(buf, options);
11674 : :
11675 [ - + ]: 258 : if (wfunc->aggfilter != NULL)
11676 : : {
11677 : 0 : appendStringInfoString(buf, ") FILTER (WHERE ");
11678 : 0 : get_rule_expr((Node *) wfunc->aggfilter, context, false);
11679 : : }
11680 : :
11681 : 258 : appendStringInfoString(buf, ") ");
11682 : :
11683 [ + + ]: 258 : if (wfunc->ignore_nulls == PARSER_IGNORE_NULLS)
11684 : 4 : appendStringInfoString(buf, "IGNORE NULLS ");
11685 : :
11686 : 258 : appendStringInfoString(buf, "OVER ");
11687 : :
11688 [ + + ]: 258 : if (context->windowClause)
11689 : : {
11690 : : /* Query-decompilation case: search the windowClause list */
11691 [ + - + - : 40 : foreach(l, context->windowClause)
+ - ]
11692 : : {
11693 : 40 : WindowClause *wc = (WindowClause *) lfirst(l);
11694 : :
11695 [ + - ]: 40 : if (wc->winref == wfunc->winref)
11696 : : {
11697 [ + + ]: 40 : if (wc->name)
11698 : 12 : appendStringInfoString(buf, quote_identifier(wc->name));
11699 : : else
11700 : 28 : get_rule_windowspec(wc, context->targetList, context);
11701 : 40 : break;
11702 : : }
11703 : : }
11704 [ - + ]: 40 : if (l == NULL)
11705 [ # # ]: 0 : elog(ERROR, "could not find window clause for winref %u",
11706 : : wfunc->winref);
11707 : : }
11708 : : else
11709 : : {
11710 : : /*
11711 : : * In EXPLAIN, search the namespace stack for a matching WindowAgg
11712 : : * node (probably it's always the first entry), and print winname.
11713 : : */
11714 [ + - + - : 218 : foreach(l, context->namespaces)
+ - ]
11715 : : {
11716 : 218 : deparse_namespace *dpns = (deparse_namespace *) lfirst(l);
11717 : :
11718 [ + - + - ]: 218 : if (dpns->plan && IsA(dpns->plan, WindowAgg))
11719 : : {
11720 : 218 : WindowAgg *wagg = (WindowAgg *) dpns->plan;
11721 : :
11722 [ + - ]: 218 : if (wagg->winref == wfunc->winref)
11723 : : {
11724 : 218 : appendStringInfoString(buf, quote_identifier(wagg->winname));
11725 : 218 : break;
11726 : : }
11727 : : }
11728 : : }
11729 [ - + ]: 218 : if (l == NULL)
11730 [ # # ]: 0 : elog(ERROR, "could not find window clause for winref %u",
11731 : : wfunc->winref);
11732 : : }
11733 : 258 : }
11734 : :
11735 : : /*
11736 : : * get_func_sql_syntax - Parse back a SQL-syntax function call
11737 : : *
11738 : : * Returns true if we successfully deparsed, false if we did not
11739 : : * recognize the function.
11740 : : */
11741 : : static bool
11742 : 120 : get_func_sql_syntax(FuncExpr *expr, deparse_context *context)
11743 : : {
11744 : 120 : StringInfo buf = context->buf;
11745 : 120 : Oid funcoid = expr->funcid;
11746 : :
11747 [ + + + + : 120 : switch (funcoid)
+ + + + +
+ + + + +
+ - + ]
11748 : : {
11749 : 16 : case F_TIMEZONE_INTERVAL_TIMESTAMP:
11750 : : case F_TIMEZONE_INTERVAL_TIMESTAMPTZ:
11751 : : case F_TIMEZONE_INTERVAL_TIMETZ:
11752 : : case F_TIMEZONE_TEXT_TIMESTAMP:
11753 : : case F_TIMEZONE_TEXT_TIMESTAMPTZ:
11754 : : case F_TIMEZONE_TEXT_TIMETZ:
11755 : : /* AT TIME ZONE ... note reversed argument order */
11756 : 16 : appendStringInfoChar(buf, '(');
11757 : 16 : get_rule_expr_paren((Node *) lsecond(expr->args), context, false,
11758 : : (Node *) expr);
11759 : 16 : appendStringInfoString(buf, " AT TIME ZONE ");
11760 : 16 : get_rule_expr_paren((Node *) linitial(expr->args), context, false,
11761 : : (Node *) expr);
11762 : 16 : appendStringInfoChar(buf, ')');
11763 : 16 : return true;
11764 : :
11765 : 12 : case F_TIMEZONE_TIMESTAMP:
11766 : : case F_TIMEZONE_TIMESTAMPTZ:
11767 : : case F_TIMEZONE_TIMETZ:
11768 : : /* AT LOCAL */
11769 : 12 : appendStringInfoChar(buf, '(');
11770 : 12 : get_rule_expr_paren((Node *) linitial(expr->args), context, false,
11771 : : (Node *) expr);
11772 : 12 : appendStringInfoString(buf, " AT LOCAL)");
11773 : 12 : return true;
11774 : :
11775 : 4 : case F_OVERLAPS_TIMESTAMPTZ_INTERVAL_TIMESTAMPTZ_INTERVAL:
11776 : : case F_OVERLAPS_TIMESTAMPTZ_INTERVAL_TIMESTAMPTZ_TIMESTAMPTZ:
11777 : : case F_OVERLAPS_TIMESTAMPTZ_TIMESTAMPTZ_TIMESTAMPTZ_INTERVAL:
11778 : : case F_OVERLAPS_TIMESTAMPTZ_TIMESTAMPTZ_TIMESTAMPTZ_TIMESTAMPTZ:
11779 : : case F_OVERLAPS_TIMESTAMP_INTERVAL_TIMESTAMP_INTERVAL:
11780 : : case F_OVERLAPS_TIMESTAMP_INTERVAL_TIMESTAMP_TIMESTAMP:
11781 : : case F_OVERLAPS_TIMESTAMP_TIMESTAMP_TIMESTAMP_INTERVAL:
11782 : : case F_OVERLAPS_TIMESTAMP_TIMESTAMP_TIMESTAMP_TIMESTAMP:
11783 : : case F_OVERLAPS_TIMETZ_TIMETZ_TIMETZ_TIMETZ:
11784 : : case F_OVERLAPS_TIME_INTERVAL_TIME_INTERVAL:
11785 : : case F_OVERLAPS_TIME_INTERVAL_TIME_TIME:
11786 : : case F_OVERLAPS_TIME_TIME_TIME_INTERVAL:
11787 : : case F_OVERLAPS_TIME_TIME_TIME_TIME:
11788 : : /* (x1, x2) OVERLAPS (y1, y2) */
11789 : 4 : appendStringInfoString(buf, "((");
11790 : 4 : get_rule_expr((Node *) linitial(expr->args), context, false);
11791 : 4 : appendStringInfoString(buf, ", ");
11792 : 4 : get_rule_expr((Node *) lsecond(expr->args), context, false);
11793 : 4 : appendStringInfoString(buf, ") OVERLAPS (");
11794 : 4 : get_rule_expr((Node *) lthird(expr->args), context, false);
11795 : 4 : appendStringInfoString(buf, ", ");
11796 : 4 : get_rule_expr((Node *) lfourth(expr->args), context, false);
11797 : 4 : appendStringInfoString(buf, "))");
11798 : 4 : return true;
11799 : :
11800 : 12 : case F_EXTRACT_TEXT_DATE:
11801 : : case F_EXTRACT_TEXT_TIME:
11802 : : case F_EXTRACT_TEXT_TIMETZ:
11803 : : case F_EXTRACT_TEXT_TIMESTAMP:
11804 : : case F_EXTRACT_TEXT_TIMESTAMPTZ:
11805 : : case F_EXTRACT_TEXT_INTERVAL:
11806 : : /* EXTRACT (x FROM y) */
11807 : 12 : appendStringInfoString(buf, "EXTRACT(");
11808 : : {
11809 : 12 : Const *con = (Const *) linitial(expr->args);
11810 : :
11811 : : Assert(IsA(con, Const) &&
11812 : : con->consttype == TEXTOID &&
11813 : : !con->constisnull);
11814 : 12 : appendStringInfoString(buf, TextDatumGetCString(con->constvalue));
11815 : : }
11816 : 12 : appendStringInfoString(buf, " FROM ");
11817 : 12 : get_rule_expr((Node *) lsecond(expr->args), context, false);
11818 : 12 : appendStringInfoChar(buf, ')');
11819 : 12 : return true;
11820 : :
11821 : 8 : case F_IS_NORMALIZED:
11822 : : /* IS xxx NORMALIZED */
11823 : 8 : appendStringInfoChar(buf, '(');
11824 : 8 : get_rule_expr_paren((Node *) linitial(expr->args), context, false,
11825 : : (Node *) expr);
11826 : 8 : appendStringInfoString(buf, " IS");
11827 [ + + ]: 8 : if (list_length(expr->args) == 2)
11828 : : {
11829 : 4 : Const *con = (Const *) lsecond(expr->args);
11830 : :
11831 : : Assert(IsA(con, Const) &&
11832 : : con->consttype == TEXTOID &&
11833 : : !con->constisnull);
11834 : 4 : appendStringInfo(buf, " %s",
11835 : 4 : TextDatumGetCString(con->constvalue));
11836 : : }
11837 : 8 : appendStringInfoString(buf, " NORMALIZED)");
11838 : 8 : return true;
11839 : :
11840 : 4 : case F_PG_COLLATION_FOR:
11841 : : /* COLLATION FOR */
11842 : 4 : appendStringInfoString(buf, "COLLATION FOR (");
11843 : 4 : get_rule_expr((Node *) linitial(expr->args), context, false);
11844 : 4 : appendStringInfoChar(buf, ')');
11845 : 4 : return true;
11846 : :
11847 : 8 : case F_NORMALIZE:
11848 : : /* NORMALIZE() */
11849 : 8 : appendStringInfoString(buf, "NORMALIZE(");
11850 : 8 : get_rule_expr((Node *) linitial(expr->args), context, false);
11851 [ + + ]: 8 : if (list_length(expr->args) == 2)
11852 : : {
11853 : 4 : Const *con = (Const *) lsecond(expr->args);
11854 : :
11855 : : Assert(IsA(con, Const) &&
11856 : : con->consttype == TEXTOID &&
11857 : : !con->constisnull);
11858 : 4 : appendStringInfo(buf, ", %s",
11859 : 4 : TextDatumGetCString(con->constvalue));
11860 : : }
11861 : 8 : appendStringInfoChar(buf, ')');
11862 : 8 : return true;
11863 : :
11864 : 8 : case F_OVERLAY_BIT_BIT_INT4:
11865 : : case F_OVERLAY_BIT_BIT_INT4_INT4:
11866 : : case F_OVERLAY_BYTEA_BYTEA_INT4:
11867 : : case F_OVERLAY_BYTEA_BYTEA_INT4_INT4:
11868 : : case F_OVERLAY_TEXT_TEXT_INT4:
11869 : : case F_OVERLAY_TEXT_TEXT_INT4_INT4:
11870 : : /* OVERLAY() */
11871 : 8 : appendStringInfoString(buf, "OVERLAY(");
11872 : 8 : get_rule_expr((Node *) linitial(expr->args), context, false);
11873 : 8 : appendStringInfoString(buf, " PLACING ");
11874 : 8 : get_rule_expr((Node *) lsecond(expr->args), context, false);
11875 : 8 : appendStringInfoString(buf, " FROM ");
11876 : 8 : get_rule_expr((Node *) lthird(expr->args), context, false);
11877 [ + + ]: 8 : if (list_length(expr->args) == 4)
11878 : : {
11879 : 4 : appendStringInfoString(buf, " FOR ");
11880 : 4 : get_rule_expr((Node *) lfourth(expr->args), context, false);
11881 : : }
11882 : 8 : appendStringInfoChar(buf, ')');
11883 : 8 : return true;
11884 : :
11885 : 4 : case F_POSITION_BIT_BIT:
11886 : : case F_POSITION_BYTEA_BYTEA:
11887 : : case F_POSITION_TEXT_TEXT:
11888 : : /* POSITION() ... extra parens since args are b_expr not a_expr */
11889 : 4 : appendStringInfoString(buf, "POSITION((");
11890 : 4 : get_rule_expr((Node *) lsecond(expr->args), context, false);
11891 : 4 : appendStringInfoString(buf, ") IN (");
11892 : 4 : get_rule_expr((Node *) linitial(expr->args), context, false);
11893 : 4 : appendStringInfoString(buf, "))");
11894 : 4 : return true;
11895 : :
11896 : 4 : case F_SUBSTRING_BIT_INT4:
11897 : : case F_SUBSTRING_BIT_INT4_INT4:
11898 : : case F_SUBSTRING_BYTEA_INT4:
11899 : : case F_SUBSTRING_BYTEA_INT4_INT4:
11900 : : case F_SUBSTRING_TEXT_INT4:
11901 : : case F_SUBSTRING_TEXT_INT4_INT4:
11902 : : /* SUBSTRING FROM/FOR (i.e., integer-position variants) */
11903 : 4 : appendStringInfoString(buf, "SUBSTRING(");
11904 : 4 : get_rule_expr((Node *) linitial(expr->args), context, false);
11905 : 4 : appendStringInfoString(buf, " FROM ");
11906 : 4 : get_rule_expr((Node *) lsecond(expr->args), context, false);
11907 [ + - ]: 4 : if (list_length(expr->args) == 3)
11908 : : {
11909 : 4 : appendStringInfoString(buf, " FOR ");
11910 : 4 : get_rule_expr((Node *) lthird(expr->args), context, false);
11911 : : }
11912 : 4 : appendStringInfoChar(buf, ')');
11913 : 4 : return true;
11914 : :
11915 : 4 : case F_SUBSTRING_TEXT_TEXT_TEXT:
11916 : : /* SUBSTRING SIMILAR/ESCAPE */
11917 : 4 : appendStringInfoString(buf, "SUBSTRING(");
11918 : 4 : get_rule_expr((Node *) linitial(expr->args), context, false);
11919 : 4 : appendStringInfoString(buf, " SIMILAR ");
11920 : 4 : get_rule_expr((Node *) lsecond(expr->args), context, false);
11921 : 4 : appendStringInfoString(buf, " ESCAPE ");
11922 : 4 : get_rule_expr((Node *) lthird(expr->args), context, false);
11923 : 4 : appendStringInfoChar(buf, ')');
11924 : 4 : return true;
11925 : :
11926 : 8 : case F_BTRIM_BYTEA_BYTEA:
11927 : : case F_BTRIM_TEXT:
11928 : : case F_BTRIM_TEXT_TEXT:
11929 : : /* TRIM() */
11930 : 8 : appendStringInfoString(buf, "TRIM(BOTH");
11931 [ + - ]: 8 : if (list_length(expr->args) == 2)
11932 : : {
11933 : 8 : appendStringInfoChar(buf, ' ');
11934 : 8 : get_rule_expr((Node *) lsecond(expr->args), context, false);
11935 : : }
11936 : 8 : appendStringInfoString(buf, " FROM ");
11937 : 8 : get_rule_expr((Node *) linitial(expr->args), context, false);
11938 : 8 : appendStringInfoChar(buf, ')');
11939 : 8 : return true;
11940 : :
11941 : 8 : case F_LTRIM_BYTEA_BYTEA:
11942 : : case F_LTRIM_TEXT:
11943 : : case F_LTRIM_TEXT_TEXT:
11944 : : /* TRIM() */
11945 : 8 : appendStringInfoString(buf, "TRIM(LEADING");
11946 [ + - ]: 8 : if (list_length(expr->args) == 2)
11947 : : {
11948 : 8 : appendStringInfoChar(buf, ' ');
11949 : 8 : get_rule_expr((Node *) lsecond(expr->args), context, false);
11950 : : }
11951 : 8 : appendStringInfoString(buf, " FROM ");
11952 : 8 : get_rule_expr((Node *) linitial(expr->args), context, false);
11953 : 8 : appendStringInfoChar(buf, ')');
11954 : 8 : return true;
11955 : :
11956 : 8 : case F_RTRIM_BYTEA_BYTEA:
11957 : : case F_RTRIM_TEXT:
11958 : : case F_RTRIM_TEXT_TEXT:
11959 : : /* TRIM() */
11960 : 8 : appendStringInfoString(buf, "TRIM(TRAILING");
11961 [ + + ]: 8 : if (list_length(expr->args) == 2)
11962 : : {
11963 : 4 : appendStringInfoChar(buf, ' ');
11964 : 4 : get_rule_expr((Node *) lsecond(expr->args), context, false);
11965 : : }
11966 : 8 : appendStringInfoString(buf, " FROM ");
11967 : 8 : get_rule_expr((Node *) linitial(expr->args), context, false);
11968 : 8 : appendStringInfoChar(buf, ')');
11969 : 8 : return true;
11970 : :
11971 : 8 : case F_SYSTEM_USER:
11972 : 8 : appendStringInfoString(buf, "SYSTEM_USER");
11973 : 8 : return true;
11974 : :
11975 : 0 : case F_XMLEXISTS:
11976 : : /* XMLEXISTS ... extra parens because args are c_expr */
11977 : 0 : appendStringInfoString(buf, "XMLEXISTS((");
11978 : 0 : get_rule_expr((Node *) linitial(expr->args), context, false);
11979 : 0 : appendStringInfoString(buf, ") PASSING (");
11980 : 0 : get_rule_expr((Node *) lsecond(expr->args), context, false);
11981 : 0 : appendStringInfoString(buf, "))");
11982 : 0 : return true;
11983 : : }
11984 : 4 : return false;
11985 : : }
11986 : :
11987 : : /* ----------
11988 : : * get_coercion_expr
11989 : : *
11990 : : * Make a string representation of a value coerced to a specific type
11991 : : * ----------
11992 : : */
11993 : : static void
11994 : 3715 : get_coercion_expr(Node *arg, deparse_context *context,
11995 : : Oid resulttype, int32 resulttypmod,
11996 : : Node *parentNode)
11997 : : {
11998 : 3715 : StringInfo buf = context->buf;
11999 : :
12000 : : /*
12001 : : * Since parse_coerce.c doesn't immediately collapse application of
12002 : : * length-coercion functions to constants, what we'll typically see in
12003 : : * such cases is a Const with typmod -1 and a length-coercion function
12004 : : * right above it. Avoid generating redundant output. However, beware of
12005 : : * suppressing casts when the user actually wrote something like
12006 : : * 'foo'::text::char(3).
12007 : : *
12008 : : * Note: it might seem that we are missing the possibility of needing to
12009 : : * print a COLLATE clause for such a Const. However, a Const could only
12010 : : * have nondefault collation in a post-constant-folding tree, in which the
12011 : : * length coercion would have been folded too. See also the special
12012 : : * handling of CollateExpr in coerce_to_target_type(): any collation
12013 : : * marking will be above the coercion node, not below it.
12014 : : */
12015 [ + - + + ]: 3715 : if (arg && IsA(arg, Const) &&
12016 [ + + ]: 430 : ((Const *) arg)->consttype == resulttype &&
12017 [ + - ]: 41 : ((Const *) arg)->consttypmod == -1)
12018 : : {
12019 : : /* Show the constant without normal ::typename decoration */
12020 : 41 : get_const_expr((Const *) arg, context, -1);
12021 : : }
12022 : : else
12023 : : {
12024 [ + + ]: 3674 : if (!PRETTY_PAREN(context))
12025 : 3409 : appendStringInfoChar(buf, '(');
12026 : 3674 : get_rule_expr_paren(arg, context, false, parentNode);
12027 [ + + ]: 3674 : if (!PRETTY_PAREN(context))
12028 : 3409 : appendStringInfoChar(buf, ')');
12029 : : }
12030 : :
12031 : : /*
12032 : : * Never emit resulttype(arg) functional notation. A pg_proc entry could
12033 : : * take precedence, and a resulttype in pg_temp would require schema
12034 : : * qualification that format_type_with_typemod() would usually omit. We've
12035 : : * standardized on arg::resulttype, but CAST(arg AS resulttype) notation
12036 : : * would work fine.
12037 : : */
12038 : 3715 : appendStringInfo(buf, "::%s",
12039 : : format_type_with_typemod(resulttype, resulttypmod));
12040 : 3715 : }
12041 : :
12042 : : /* ----------
12043 : : * get_const_expr
12044 : : *
12045 : : * Make a string representation of a Const
12046 : : *
12047 : : * showtype can be -1 to never show "::typename" decoration, or +1 to always
12048 : : * show it, or 0 to show it only if the constant wouldn't be assumed to be
12049 : : * the right type by default.
12050 : : *
12051 : : * If the Const's collation isn't default for its type, show that too.
12052 : : * We mustn't do this when showtype is -1 (since that means the caller will
12053 : : * print "::typename", and we can't put a COLLATE clause in between). It's
12054 : : * caller's responsibility that collation isn't missed in such cases.
12055 : : * ----------
12056 : : */
12057 : : static void
12058 : 47831 : get_const_expr(Const *constval, deparse_context *context, int showtype)
12059 : : {
12060 : 47831 : StringInfo buf = context->buf;
12061 : : Oid typoutput;
12062 : : bool typIsVarlena;
12063 : : char *extval;
12064 : 47831 : bool needlabel = false;
12065 : :
12066 [ + + ]: 47831 : if (constval->constisnull)
12067 : : {
12068 : : /*
12069 : : * Always label the type of a NULL constant to prevent misdecisions
12070 : : * about type when reparsing.
12071 : : */
12072 : 836 : appendStringInfoString(buf, "NULL");
12073 [ + + ]: 836 : if (showtype >= 0)
12074 : : {
12075 : 805 : appendStringInfo(buf, "::%s",
12076 : : format_type_with_typemod(constval->consttype,
12077 : : constval->consttypmod));
12078 : 805 : get_const_collation(constval, context);
12079 : : }
12080 : 6348 : return;
12081 : : }
12082 : :
12083 : 46995 : getTypeOutputInfo(constval->consttype,
12084 : : &typoutput, &typIsVarlena);
12085 : :
12086 : 46995 : extval = OidOutputFunctionCall(typoutput, constval->constvalue);
12087 : :
12088 [ + + + + ]: 46995 : switch (constval->consttype)
12089 : : {
12090 : 26957 : case INT4OID:
12091 : :
12092 : : /*
12093 : : * INT4 can be printed without any decoration, unless it is
12094 : : * negative; in that case print it as '-nnn'::integer to ensure
12095 : : * that the output will re-parse as a constant, not as a constant
12096 : : * plus operator. In most cases we could get away with printing
12097 : : * (-nnn) instead, because of the way that gram.y handles negative
12098 : : * literals; but that doesn't work for INT_MIN, and it doesn't
12099 : : * seem that much prettier anyway.
12100 : : */
12101 [ + + ]: 26957 : if (extval[0] != '-')
12102 : 26623 : appendStringInfoString(buf, extval);
12103 : : else
12104 : : {
12105 : 334 : appendStringInfo(buf, "'%s'", extval);
12106 : 334 : needlabel = true; /* we must attach a cast */
12107 : : }
12108 : 26957 : break;
12109 : :
12110 : 729 : case NUMERICOID:
12111 : :
12112 : : /*
12113 : : * NUMERIC can be printed without quotes if it looks like a float
12114 : : * constant (not an integer, and not Infinity or NaN) and doesn't
12115 : : * have a leading sign (for the same reason as for INT4).
12116 : : */
12117 [ + - ]: 729 : if (isdigit((unsigned char) extval[0]) &&
12118 [ + + ]: 729 : strcspn(extval, "eE.") != strlen(extval))
12119 : : {
12120 : 260 : appendStringInfoString(buf, extval);
12121 : : }
12122 : : else
12123 : : {
12124 : 469 : appendStringInfo(buf, "'%s'", extval);
12125 : 469 : needlabel = true; /* we must attach a cast */
12126 : : }
12127 : 729 : break;
12128 : :
12129 : 1114 : case BOOLOID:
12130 [ + + ]: 1114 : if (strcmp(extval, "t") == 0)
12131 : 449 : appendStringInfoString(buf, "true");
12132 : : else
12133 : 665 : appendStringInfoString(buf, "false");
12134 : 1114 : break;
12135 : :
12136 : 18195 : default:
12137 : 18195 : simple_quote_literal(buf, extval);
12138 : 18195 : break;
12139 : : }
12140 : :
12141 : 46995 : pfree(extval);
12142 : :
12143 [ + + ]: 46995 : if (showtype < 0)
12144 : 5512 : return;
12145 : :
12146 : : /*
12147 : : * For showtype == 0, append ::typename unless the constant will be
12148 : : * implicitly typed as the right type when it is read in.
12149 : : *
12150 : : * XXX this code has to be kept in sync with the behavior of the parser,
12151 : : * especially make_const.
12152 : : */
12153 [ + + + + ]: 41483 : switch (constval->consttype)
12154 : : {
12155 : 1172 : case BOOLOID:
12156 : : case UNKNOWNOID:
12157 : : /* These types can be left unlabeled */
12158 : 1172 : needlabel = false;
12159 : 1172 : break;
12160 : 24190 : case INT4OID:
12161 : : /* We determined above whether a label is needed */
12162 : 24190 : break;
12163 : 729 : case NUMERICOID:
12164 : :
12165 : : /*
12166 : : * Float-looking constants will be typed as numeric, which we
12167 : : * checked above; but if there's a nondefault typmod we need to
12168 : : * show it.
12169 : : */
12170 : 729 : needlabel |= (constval->consttypmod >= 0);
12171 : 729 : break;
12172 : 15392 : default:
12173 : 15392 : needlabel = true;
12174 : 15392 : break;
12175 : : }
12176 [ + + - + ]: 41483 : if (needlabel || showtype > 0)
12177 : 16189 : appendStringInfo(buf, "::%s",
12178 : : format_type_with_typemod(constval->consttype,
12179 : : constval->consttypmod));
12180 : :
12181 : 41483 : get_const_collation(constval, context);
12182 : : }
12183 : :
12184 : : /*
12185 : : * helper for get_const_expr: append COLLATE if needed
12186 : : */
12187 : : static void
12188 : 42288 : get_const_collation(Const *constval, deparse_context *context)
12189 : : {
12190 : 42288 : StringInfo buf = context->buf;
12191 : :
12192 [ + + ]: 42288 : if (OidIsValid(constval->constcollid))
12193 : : {
12194 : 6075 : Oid typcollation = get_typcollation(constval->consttype);
12195 : :
12196 [ + + ]: 6075 : if (constval->constcollid != typcollation)
12197 : : {
12198 : 160 : appendStringInfo(buf, " COLLATE %s",
12199 : : generate_collation_name(constval->constcollid));
12200 : : }
12201 : : }
12202 : 42288 : }
12203 : :
12204 : : /*
12205 : : * get_json_path_spec - Parse back a JSON path specification
12206 : : */
12207 : : static void
12208 : 428 : get_json_path_spec(Node *path_spec, deparse_context *context, bool showimplicit)
12209 : : {
12210 [ + - ]: 428 : if (IsA(path_spec, Const))
12211 : 428 : get_const_expr((Const *) path_spec, context, -1);
12212 : : else
12213 : 0 : get_rule_expr(path_spec, context, showimplicit);
12214 : 428 : }
12215 : :
12216 : : /*
12217 : : * get_json_format - Parse back a JsonFormat node
12218 : : */
12219 : : static void
12220 : 128 : get_json_format(JsonFormat *format, StringInfo buf)
12221 : : {
12222 [ + + ]: 128 : if (format->format_type == JS_FORMAT_DEFAULT)
12223 : 76 : return;
12224 : :
12225 : 52 : appendStringInfoString(buf,
12226 [ - + ]: 52 : format->format_type == JS_FORMAT_JSONB ?
12227 : : " FORMAT JSONB" : " FORMAT JSON");
12228 : :
12229 [ + + ]: 52 : if (format->encoding != JS_ENC_DEFAULT)
12230 : : {
12231 : : const char *encoding;
12232 : :
12233 : 4 : encoding =
12234 [ + - ]: 8 : format->encoding == JS_ENC_UTF16 ? "UTF16" :
12235 [ - + ]: 4 : format->encoding == JS_ENC_UTF32 ? "UTF32" : "UTF8";
12236 : :
12237 : 4 : appendStringInfo(buf, " ENCODING %s", encoding);
12238 : : }
12239 : : }
12240 : :
12241 : : /*
12242 : : * get_json_returning - Parse back a JsonReturning structure
12243 : : */
12244 : : static void
12245 : 200 : get_json_returning(JsonReturning *returning, StringInfo buf,
12246 : : bool json_format_by_default)
12247 : : {
12248 [ - + ]: 200 : if (!OidIsValid(returning->typid))
12249 : 0 : return;
12250 : :
12251 : 200 : appendStringInfo(buf, " RETURNING %s",
12252 : : format_type_with_typemod(returning->typid,
12253 : : returning->typmod));
12254 : :
12255 [ + + + + ]: 392 : if (!json_format_by_default ||
12256 : 192 : returning->format->format_type !=
12257 [ + + ]: 192 : (returning->typid == JSONBOID ? JS_FORMAT_JSONB : JS_FORMAT_JSON))
12258 : 24 : get_json_format(returning->format, buf);
12259 : : }
12260 : :
12261 : : /*
12262 : : * get_json_constructor - Parse back a JsonConstructorExpr node
12263 : : */
12264 : : static void
12265 : 204 : get_json_constructor(JsonConstructorExpr *ctor, deparse_context *context,
12266 : : bool showimplicit)
12267 : : {
12268 : 204 : StringInfo buf = context->buf;
12269 : : const char *funcname;
12270 : : bool is_json_object;
12271 : : int curridx;
12272 : : ListCell *lc;
12273 : :
12274 [ + + ]: 204 : if (ctor->type == JSCTOR_JSON_OBJECTAGG)
12275 : : {
12276 : 40 : get_json_agg_constructor(ctor, context, "JSON_OBJECTAGG", true);
12277 : 40 : return;
12278 : : }
12279 [ + + ]: 164 : else if (ctor->type == JSCTOR_JSON_ARRAYAGG)
12280 : : {
12281 : 68 : get_json_agg_constructor(ctor, context, "JSON_ARRAYAGG", false);
12282 : 68 : return;
12283 : : }
12284 [ + + ]: 96 : else if (ctor->type == JSCTOR_JSON_ARRAY_QUERY)
12285 : : {
12286 : 16 : Query *query = castNode(Query, ctor->orig_query);
12287 : :
12288 : 16 : appendStringInfo(buf, "JSON_ARRAY(");
12289 : :
12290 : 16 : get_query_def(query, buf, context->namespaces, NULL, false,
12291 : : context->prettyFlags, context->wrapColumn,
12292 : : context->indentLevel);
12293 : :
12294 : 16 : get_json_constructor_options(ctor, buf);
12295 : 16 : appendStringInfoChar(buf, ')');
12296 : :
12297 : 16 : return;
12298 : : }
12299 : :
12300 [ + + + + : 80 : switch (ctor->type)
+ - ]
12301 : : {
12302 : 20 : case JSCTOR_JSON_OBJECT:
12303 : 20 : funcname = "JSON_OBJECT";
12304 : 20 : break;
12305 : 16 : case JSCTOR_JSON_ARRAY:
12306 : 16 : funcname = "JSON_ARRAY";
12307 : 16 : break;
12308 : 28 : case JSCTOR_JSON_PARSE:
12309 : 28 : funcname = "JSON";
12310 : 28 : break;
12311 : 8 : case JSCTOR_JSON_SCALAR:
12312 : 8 : funcname = "JSON_SCALAR";
12313 : 8 : break;
12314 : 8 : case JSCTOR_JSON_SERIALIZE:
12315 : 8 : funcname = "JSON_SERIALIZE";
12316 : 8 : break;
12317 : 0 : default:
12318 [ # # ]: 0 : elog(ERROR, "invalid JsonConstructorType %d", ctor->type);
12319 : : }
12320 : :
12321 : 80 : appendStringInfo(buf, "%s(", funcname);
12322 : :
12323 : 80 : is_json_object = ctor->type == JSCTOR_JSON_OBJECT;
12324 [ + - + + : 212 : foreach(lc, ctor->args)
+ + ]
12325 : : {
12326 : 132 : curridx = foreach_current_index(lc);
12327 [ + + ]: 132 : if (curridx > 0)
12328 : : {
12329 : : const char *sep;
12330 : :
12331 [ + + + + ]: 52 : sep = (is_json_object && (curridx % 2) != 0) ? " : " : ", ";
12332 : 52 : appendStringInfoString(buf, sep);
12333 : : }
12334 : :
12335 : 132 : get_rule_expr((Node *) lfirst(lc), context, true);
12336 : : }
12337 : :
12338 : 80 : get_json_constructor_options(ctor, buf);
12339 : 80 : appendStringInfoChar(buf, ')');
12340 : : }
12341 : :
12342 : : /*
12343 : : * Append options, if any, to the JSON constructor being deparsed
12344 : : */
12345 : : static void
12346 : 204 : get_json_constructor_options(JsonConstructorExpr *ctor, StringInfo buf)
12347 : : {
12348 [ + + ]: 204 : if (ctor->absent_on_null)
12349 : : {
12350 [ + - ]: 80 : if (ctor->type == JSCTOR_JSON_OBJECT ||
12351 [ + + ]: 80 : ctor->type == JSCTOR_JSON_OBJECTAGG)
12352 : 8 : appendStringInfoString(buf, " ABSENT ON NULL");
12353 : : }
12354 : : else
12355 : : {
12356 [ + - ]: 124 : if (ctor->type == JSCTOR_JSON_ARRAY ||
12357 [ + + ]: 124 : ctor->type == JSCTOR_JSON_ARRAYAGG)
12358 : 28 : appendStringInfoString(buf, " NULL ON NULL");
12359 : : }
12360 : :
12361 [ + + ]: 204 : if (ctor->unique)
12362 : 24 : appendStringInfoString(buf, " WITH UNIQUE KEYS");
12363 : :
12364 : : /*
12365 : : * Append RETURNING clause if needed; JSON() and JSON_SCALAR() don't
12366 : : * support one.
12367 : : */
12368 [ + + + + ]: 204 : if (ctor->type != JSCTOR_JSON_PARSE && ctor->type != JSCTOR_JSON_SCALAR)
12369 : 168 : get_json_returning(ctor->returning, buf, true);
12370 : 204 : }
12371 : :
12372 : : /*
12373 : : * get_json_agg_constructor - Parse back an aggregate JsonConstructorExpr node
12374 : : */
12375 : : static void
12376 : 108 : get_json_agg_constructor(JsonConstructorExpr *ctor, deparse_context *context,
12377 : : const char *funcname, bool is_json_objectagg)
12378 : : {
12379 : : StringInfoData options;
12380 : :
12381 : 108 : initStringInfo(&options);
12382 : 108 : get_json_constructor_options(ctor, &options);
12383 : :
12384 [ + + ]: 108 : if (IsA(ctor->func, Aggref))
12385 : 68 : get_agg_expr_helper((Aggref *) ctor->func, context,
12386 : 68 : (Aggref *) ctor->func,
12387 : 68 : funcname, options.data, is_json_objectagg);
12388 [ + + ]: 40 : else if (IsA(ctor->func, WindowFunc))
12389 : 12 : get_windowfunc_expr_helper((WindowFunc *) ctor->func, context,
12390 : 12 : funcname, options.data,
12391 : : is_json_objectagg);
12392 [ + - ]: 28 : else if (IsA(ctor->func, Var))
12393 : : {
12394 : : /*
12395 : : * If the aggregate is computed by a lower plan node, setrefs.c will
12396 : : * have replaced the Aggref or WindowFunc with a Var referencing that
12397 : : * node's output. Chase the Var back to it so we can still print the
12398 : : * original JSON aggregate syntax. This only happens in EXPLAIN.
12399 : : */
12400 : 28 : resolve_special_varno((Node *) ctor->func, context,
12401 : : get_json_agg_constructor_expr, ctor);
12402 : : }
12403 : : else
12404 [ # # ]: 0 : elog(ERROR, "invalid JsonConstructorExpr underlying node type: %d",
12405 : : nodeTag(ctor->func));
12406 : 108 : }
12407 : :
12408 : : /*
12409 : : * Deparse a JsonConstructorExpr whose aggregate is computed by a lower plan
12410 : : * node; resolve_special_varno has located the underlying Aggref/WindowFunc.
12411 : : */
12412 : : static void
12413 : 28 : get_json_agg_constructor_expr(Node *node, deparse_context *context,
12414 : : void *callback_arg)
12415 : : {
12416 : : JsonConstructorExpr ctor;
12417 : :
12418 [ + + - + ]: 28 : if (!IsA(node, Aggref) && !IsA(node, WindowFunc))
12419 [ # # ]: 0 : elog(ERROR, "JSON aggregate constructor does not point to an Aggref or WindowFunc");
12420 : :
12421 : : /* Flat copy suffices; we only replace func. */
12422 : 28 : ctor = *(JsonConstructorExpr *) callback_arg;
12423 : 28 : ctor.func = (Expr *) node;
12424 : 28 : get_json_constructor(&ctor, context, false);
12425 : 28 : }
12426 : :
12427 : : /*
12428 : : * simple_quote_literal - Format a string as a SQL literal, append to buf
12429 : : */
12430 : : static void
12431 : 18640 : simple_quote_literal(StringInfo buf, const char *val)
12432 : : {
12433 : : const char *valptr;
12434 : :
12435 : : /*
12436 : : * We always form the string literal according to standard SQL rules.
12437 : : */
12438 : 18640 : appendStringInfoChar(buf, '\'');
12439 [ + + ]: 187094 : for (valptr = val; *valptr; valptr++)
12440 : : {
12441 : 168454 : char ch = *valptr;
12442 : :
12443 [ + + ]: 168454 : if (SQL_STR_DOUBLE(ch, false))
12444 : 204 : appendStringInfoChar(buf, ch);
12445 : 168454 : appendStringInfoChar(buf, ch);
12446 : : }
12447 : 18640 : appendStringInfoChar(buf, '\'');
12448 : 18640 : }
12449 : :
12450 : :
12451 : : /* ----------
12452 : : * get_sublink_expr - Parse back a sublink
12453 : : * ----------
12454 : : */
12455 : : static void
12456 : 290 : get_sublink_expr(SubLink *sublink, deparse_context *context)
12457 : : {
12458 : 290 : StringInfo buf = context->buf;
12459 : 290 : Query *query = (Query *) (sublink->subselect);
12460 : 290 : char *opname = NULL;
12461 : : bool need_paren;
12462 : :
12463 [ + + ]: 290 : if (sublink->subLinkType == ARRAY_SUBLINK)
12464 : 14 : appendStringInfoString(buf, "ARRAY(");
12465 : : else
12466 : 276 : appendStringInfoChar(buf, '(');
12467 : :
12468 : : /*
12469 : : * Note that we print the name of only the first operator, when there are
12470 : : * multiple combining operators. This is an approximation that could go
12471 : : * wrong in various scenarios (operators in different schemas, renamed
12472 : : * operators, etc) but there is not a whole lot we can do about it, since
12473 : : * the syntax allows only one operator to be shown.
12474 : : */
12475 [ + + ]: 290 : if (sublink->testexpr)
12476 : : {
12477 [ + + ]: 12 : if (IsA(sublink->testexpr, OpExpr))
12478 : : {
12479 : : /* single combining operator */
12480 : 4 : OpExpr *opexpr = (OpExpr *) sublink->testexpr;
12481 : :
12482 : 4 : get_rule_expr(linitial(opexpr->args), context, true);
12483 : 4 : opname = generate_operator_name(opexpr->opno,
12484 : 4 : exprType(linitial(opexpr->args)),
12485 : 4 : exprType(lsecond(opexpr->args)));
12486 : : }
12487 [ + + ]: 8 : else if (IsA(sublink->testexpr, BoolExpr))
12488 : : {
12489 : : /* multiple combining operators, = or <> cases */
12490 : : char *sep;
12491 : : ListCell *l;
12492 : :
12493 : 4 : appendStringInfoChar(buf, '(');
12494 : 4 : sep = "";
12495 [ + - + + : 12 : foreach(l, ((BoolExpr *) sublink->testexpr)->args)
+ + ]
12496 : : {
12497 : 8 : OpExpr *opexpr = lfirst_node(OpExpr, l);
12498 : :
12499 : 8 : appendStringInfoString(buf, sep);
12500 : 8 : get_rule_expr(linitial(opexpr->args), context, true);
12501 [ + + ]: 8 : if (!opname)
12502 : 4 : opname = generate_operator_name(opexpr->opno,
12503 : 4 : exprType(linitial(opexpr->args)),
12504 : 4 : exprType(lsecond(opexpr->args)));
12505 : 8 : sep = ", ";
12506 : : }
12507 : 4 : appendStringInfoChar(buf, ')');
12508 : : }
12509 [ + - ]: 4 : else if (IsA(sublink->testexpr, RowCompareExpr))
12510 : : {
12511 : : /* multiple combining operators, < <= > >= cases */
12512 : 4 : RowCompareExpr *rcexpr = (RowCompareExpr *) sublink->testexpr;
12513 : :
12514 : 4 : appendStringInfoChar(buf, '(');
12515 : 4 : get_rule_expr((Node *) rcexpr->largs, context, true);
12516 : 4 : opname = generate_operator_name(linitial_oid(rcexpr->opnos),
12517 : 4 : exprType(linitial(rcexpr->largs)),
12518 : 4 : exprType(linitial(rcexpr->rargs)));
12519 : 4 : appendStringInfoChar(buf, ')');
12520 : : }
12521 : : else
12522 [ # # ]: 0 : elog(ERROR, "unrecognized testexpr type: %d",
12523 : : (int) nodeTag(sublink->testexpr));
12524 : : }
12525 : :
12526 : 290 : need_paren = true;
12527 : :
12528 [ + + + - : 290 : switch (sublink->subLinkType)
+ - ]
12529 : : {
12530 : 113 : case EXISTS_SUBLINK:
12531 : 113 : appendStringInfoString(buf, "EXISTS ");
12532 : 113 : break;
12533 : :
12534 : 8 : case ANY_SUBLINK:
12535 [ + + ]: 8 : if (strcmp(opname, "=") == 0) /* Represent = ANY as IN */
12536 : 4 : appendStringInfoString(buf, " IN ");
12537 : : else
12538 : 4 : appendStringInfo(buf, " %s ANY ", opname);
12539 : 8 : break;
12540 : :
12541 : 4 : case ALL_SUBLINK:
12542 : 4 : appendStringInfo(buf, " %s ALL ", opname);
12543 : 4 : break;
12544 : :
12545 : 0 : case ROWCOMPARE_SUBLINK:
12546 : 0 : appendStringInfo(buf, " %s ", opname);
12547 : 0 : break;
12548 : :
12549 : 165 : case EXPR_SUBLINK:
12550 : : case MULTIEXPR_SUBLINK:
12551 : : case ARRAY_SUBLINK:
12552 : 165 : need_paren = false;
12553 : 165 : break;
12554 : :
12555 : 0 : case CTE_SUBLINK: /* shouldn't occur in a SubLink */
12556 : : default:
12557 [ # # ]: 0 : elog(ERROR, "unrecognized sublink type: %d",
12558 : : (int) sublink->subLinkType);
12559 : : break;
12560 : : }
12561 : :
12562 [ + + ]: 290 : if (need_paren)
12563 : 125 : appendStringInfoChar(buf, '(');
12564 : :
12565 : 290 : get_query_def(query, buf, context->namespaces, NULL, false,
12566 : : context->prettyFlags, context->wrapColumn,
12567 : : context->indentLevel);
12568 : :
12569 [ + + ]: 290 : if (need_paren)
12570 : 125 : appendStringInfoString(buf, "))");
12571 : : else
12572 : 165 : appendStringInfoChar(buf, ')');
12573 : 290 : }
12574 : :
12575 : :
12576 : : /* ----------
12577 : : * get_xmltable - Parse back a XMLTABLE function
12578 : : * ----------
12579 : : */
12580 : : static void
12581 : 38 : get_xmltable(TableFunc *tf, deparse_context *context, bool showimplicit)
12582 : : {
12583 : 38 : StringInfo buf = context->buf;
12584 : :
12585 : 38 : appendStringInfoString(buf, "XMLTABLE(");
12586 : :
12587 [ + + ]: 38 : if (tf->ns_uris != NIL)
12588 : : {
12589 : : ListCell *lc1,
12590 : : *lc2;
12591 : 9 : bool first = true;
12592 : :
12593 : 9 : appendStringInfoString(buf, "XMLNAMESPACES (");
12594 [ + - + + : 18 : forboth(lc1, tf->ns_uris, lc2, tf->ns_names)
+ - + + +
+ + - +
+ ]
12595 : : {
12596 : 9 : Node *expr = (Node *) lfirst(lc1);
12597 : 9 : String *ns_node = lfirst_node(String, lc2);
12598 : :
12599 [ - + ]: 9 : if (!first)
12600 : 0 : appendStringInfoString(buf, ", ");
12601 : : else
12602 : 9 : first = false;
12603 : :
12604 [ + - ]: 9 : if (ns_node != NULL)
12605 : : {
12606 : 9 : get_rule_expr(expr, context, showimplicit);
12607 : 9 : appendStringInfo(buf, " AS %s",
12608 : 9 : quote_identifier(strVal(ns_node)));
12609 : : }
12610 : : else
12611 : : {
12612 : 0 : appendStringInfoString(buf, "DEFAULT ");
12613 : 0 : get_rule_expr(expr, context, showimplicit);
12614 : : }
12615 : : }
12616 : 9 : appendStringInfoString(buf, "), ");
12617 : : }
12618 : :
12619 : 38 : appendStringInfoChar(buf, '(');
12620 : 38 : get_rule_expr((Node *) tf->rowexpr, context, showimplicit);
12621 : 38 : appendStringInfoString(buf, ") PASSING (");
12622 : 38 : get_rule_expr((Node *) tf->docexpr, context, showimplicit);
12623 : 38 : appendStringInfoChar(buf, ')');
12624 : :
12625 [ + - ]: 38 : if (tf->colexprs != NIL)
12626 : : {
12627 : : ListCell *l1;
12628 : : ListCell *l2;
12629 : : ListCell *l3;
12630 : : ListCell *l4;
12631 : : ListCell *l5;
12632 : 38 : int colnum = 0;
12633 : :
12634 : 38 : appendStringInfoString(buf, " COLUMNS ");
12635 [ + - + + : 231 : forfive(l1, tf->colnames, l2, tf->coltypes, l3, tf->coltypmods,
+ - + + +
- + + + -
+ + + - +
+ + + + -
+ - + - +
- + + ]
12636 : : l4, tf->colexprs, l5, tf->coldefexprs)
12637 : : {
12638 : 193 : char *colname = strVal(lfirst(l1));
12639 : 193 : Oid typid = lfirst_oid(l2);
12640 : 193 : int32 typmod = lfirst_int(l3);
12641 : 193 : Node *colexpr = (Node *) lfirst(l4);
12642 : 193 : Node *coldefexpr = (Node *) lfirst(l5);
12643 : 193 : bool ordinality = (tf->ordinalitycol == colnum);
12644 : 193 : bool notnull = bms_is_member(colnum, tf->notnulls);
12645 : :
12646 [ + + ]: 193 : if (colnum > 0)
12647 : 155 : appendStringInfoString(buf, ", ");
12648 : 193 : colnum++;
12649 : :
12650 [ + + ]: 365 : appendStringInfo(buf, "%s %s", quote_identifier(colname),
12651 : : ordinality ? "FOR ORDINALITY" :
12652 : 172 : format_type_with_typemod(typid, typmod));
12653 [ + + ]: 193 : if (ordinality)
12654 : 21 : continue;
12655 : :
12656 [ + + ]: 172 : if (coldefexpr != NULL)
12657 : : {
12658 : 21 : appendStringInfoString(buf, " DEFAULT (");
12659 : 21 : get_rule_expr((Node *) coldefexpr, context, showimplicit);
12660 : 21 : appendStringInfoChar(buf, ')');
12661 : : }
12662 [ + + ]: 172 : if (colexpr != NULL)
12663 : : {
12664 : 156 : appendStringInfoString(buf, " PATH (");
12665 : 156 : get_rule_expr((Node *) colexpr, context, showimplicit);
12666 : 156 : appendStringInfoChar(buf, ')');
12667 : : }
12668 [ + + ]: 172 : if (notnull)
12669 : 21 : appendStringInfoString(buf, " NOT NULL");
12670 : : }
12671 : : }
12672 : :
12673 : 38 : appendStringInfoChar(buf, ')');
12674 : 38 : }
12675 : :
12676 : : /*
12677 : : * get_json_table_nested_columns - Parse back nested JSON_TABLE columns
12678 : : */
12679 : : static void
12680 : 104 : get_json_table_nested_columns(TableFunc *tf, JsonTablePlan *plan,
12681 : : deparse_context *context, bool showimplicit,
12682 : : bool needcomma)
12683 : : {
12684 [ + + ]: 104 : if (IsA(plan, JsonTablePathScan))
12685 : : {
12686 : 76 : JsonTablePathScan *scan = castNode(JsonTablePathScan, plan);
12687 : :
12688 [ + + ]: 76 : if (needcomma)
12689 : 48 : appendStringInfoChar(context->buf, ',');
12690 : :
12691 : 76 : appendStringInfoChar(context->buf, ' ');
12692 : 76 : appendContextKeyword(context, "NESTED PATH ", 0, 0, 0);
12693 : 76 : get_const_expr(scan->path->value, context, -1);
12694 : 76 : appendStringInfo(context->buf, " AS %s", quote_identifier(scan->path->name));
12695 : 76 : get_json_table_columns(tf, scan, context, showimplicit);
12696 : : }
12697 [ + - ]: 28 : else if (IsA(plan, JsonTableSiblingJoin))
12698 : : {
12699 : 28 : JsonTableSiblingJoin *join = (JsonTableSiblingJoin *) plan;
12700 : :
12701 : 28 : get_json_table_nested_columns(tf, join->lplan, context, showimplicit,
12702 : : needcomma);
12703 : 28 : get_json_table_nested_columns(tf, join->rplan, context, showimplicit,
12704 : : true);
12705 : : }
12706 : 104 : }
12707 : :
12708 : : /*
12709 : : * json_table_plan_is_default - does this plan match the implicit default?
12710 : : *
12711 : : * When no PLAN clause is given, JSON_TABLE builds a default plan that joins
12712 : : * every nested path to its parent with OUTER and every set of sibling paths
12713 : : * with UNION (see transformJsonTableColumns()). Such a plan is fully implied
12714 : : * by the NESTED COLUMNS structure, so we need not (and, to match the input,
12715 : : * should not) print a PLAN clause for it; we only deparse a PLAN clause when
12716 : : * the plan deviates from the default, i.e. uses an INNER or CROSS join
12717 : : * somewhere. This follows the usual ruleutils convention of omitting a clause
12718 : : * that merely restates the default (cf. get_json_expr_options() for ON
12719 : : * EMPTY/ON ERROR, or the NULLS FIRST/LAST handling in get_rule_orderby()).
12720 : : */
12721 : : static bool
12722 : 116 : json_table_plan_is_default(JsonTablePlan *plan)
12723 : : {
12724 [ + + ]: 116 : if (IsA(plan, JsonTablePathScan))
12725 : : {
12726 : 88 : JsonTablePathScan *scan = castNode(JsonTablePathScan, plan);
12727 : :
12728 [ + + ]: 88 : if (scan->child)
12729 : : {
12730 [ + + ]: 48 : if (!scan->outerJoin)
12731 : 4 : return false; /* INNER is not the default */
12732 : 44 : return json_table_plan_is_default(scan->child);
12733 : : }
12734 : :
12735 : 40 : return true;
12736 : : }
12737 : : else
12738 : : {
12739 : 28 : JsonTableSiblingJoin *join = castNode(JsonTableSiblingJoin, plan);
12740 : :
12741 [ - + ]: 28 : if (join->cross)
12742 : 0 : return false; /* CROSS is not the default */
12743 [ + - + - ]: 56 : return json_table_plan_is_default(join->lplan) &&
12744 : 28 : json_table_plan_is_default(join->rplan);
12745 : : }
12746 : : }
12747 : :
12748 : : /*
12749 : : * get_json_table_plan - Parse back a JSON_TABLE plan
12750 : : */
12751 : : static void
12752 : 12 : get_json_table_plan(TableFunc *tf, JsonTablePlan *plan, deparse_context *context,
12753 : : bool parenthesize)
12754 : : {
12755 [ + + ]: 12 : if (parenthesize)
12756 : 8 : appendStringInfoChar(context->buf, '(');
12757 : :
12758 [ + - ]: 12 : if (IsA(plan, JsonTablePathScan))
12759 : : {
12760 : 12 : JsonTablePathScan *s = castNode(JsonTablePathScan, plan);
12761 : :
12762 : 12 : appendStringInfoString(context->buf, quote_identifier(s->path->name));
12763 : :
12764 [ + + ]: 12 : if (s->child)
12765 : : {
12766 : 8 : appendStringInfoString(context->buf,
12767 [ + + ]: 8 : s->outerJoin ? " OUTER " : " INNER ");
12768 : 8 : get_json_table_plan(tf, s->child, context,
12769 [ + - ]: 16 : IsA(s->child, JsonTableSiblingJoin) ||
12770 [ + + ]: 16 : castNode(JsonTablePathScan, s->child)->child);
12771 : : }
12772 : : }
12773 [ # # ]: 0 : else if (IsA(plan, JsonTableSiblingJoin))
12774 : : {
12775 : 0 : JsonTableSiblingJoin *j = (JsonTableSiblingJoin *) plan;
12776 : :
12777 : 0 : get_json_table_plan(tf, j->lplan, context,
12778 [ # # ]: 0 : IsA(j->lplan, JsonTableSiblingJoin) ||
12779 [ # # ]: 0 : castNode(JsonTablePathScan, j->lplan)->child);
12780 : :
12781 [ # # ]: 0 : appendStringInfoString(context->buf, j->cross ? " CROSS " : " UNION ");
12782 : :
12783 : 0 : get_json_table_plan(tf, j->rplan, context,
12784 [ # # ]: 0 : IsA(j->rplan, JsonTableSiblingJoin) ||
12785 [ # # ]: 0 : castNode(JsonTablePathScan, j->rplan)->child);
12786 : : }
12787 : :
12788 [ + + ]: 12 : if (parenthesize)
12789 : 8 : appendStringInfoChar(context->buf, ')');
12790 : 12 : }
12791 : :
12792 : : /*
12793 : : * get_json_table_columns - Parse back JSON_TABLE columns
12794 : : */
12795 : : static void
12796 : 160 : get_json_table_columns(TableFunc *tf, JsonTablePathScan *scan,
12797 : : deparse_context *context,
12798 : : bool showimplicit)
12799 : : {
12800 : 160 : StringInfo buf = context->buf;
12801 : : ListCell *lc_colname;
12802 : : ListCell *lc_coltype;
12803 : : ListCell *lc_coltypmod;
12804 : : ListCell *lc_colvalexpr;
12805 : 160 : int colnum = 0;
12806 : :
12807 : 160 : appendStringInfoChar(buf, ' ');
12808 : 160 : appendContextKeyword(context, "COLUMNS (", 0, 0, 0);
12809 : :
12810 [ + + ]: 160 : if (PRETTY_INDENT(context))
12811 : 108 : context->indentLevel += PRETTYINDENT_VAR;
12812 : :
12813 [ + - + + : 1304 : forfour(lc_colname, tf->colnames,
+ - + + +
- + + + -
+ + + + +
- + - + -
+ + ]
12814 : : lc_coltype, tf->coltypes,
12815 : : lc_coltypmod, tf->coltypmods,
12816 : : lc_colvalexpr, tf->colvalexprs)
12817 : : {
12818 : 1192 : char *colname = strVal(lfirst(lc_colname));
12819 : : JsonExpr *colexpr;
12820 : : Oid typid;
12821 : : int32 typmod;
12822 : : bool ordinality;
12823 : : JsonBehaviorType default_behavior;
12824 : :
12825 : 1192 : typid = lfirst_oid(lc_coltype);
12826 : 1192 : typmod = lfirst_int(lc_coltypmod);
12827 : 1192 : colexpr = castNode(JsonExpr, lfirst(lc_colvalexpr));
12828 : :
12829 : : /* Skip columns that don't belong to this scan. */
12830 [ + + + + ]: 1192 : if (scan->colMin < 0 || colnum < scan->colMin)
12831 : : {
12832 : 740 : colnum++;
12833 : 740 : continue;
12834 : : }
12835 [ + + ]: 452 : if (colnum > scan->colMax)
12836 : 48 : break;
12837 : :
12838 [ + + ]: 404 : if (colnum > scan->colMin)
12839 : 272 : appendStringInfoString(buf, ", ");
12840 : :
12841 : 404 : colnum++;
12842 : :
12843 : 404 : ordinality = !colexpr;
12844 : :
12845 : 404 : appendContextKeyword(context, "", 0, 0, 0);
12846 : :
12847 [ + + ]: 792 : appendStringInfo(buf, "%s %s", quote_identifier(colname),
12848 : : ordinality ? "FOR ORDINALITY" :
12849 : 388 : format_type_with_typemod(typid, typmod));
12850 [ + + ]: 404 : if (ordinality)
12851 : 16 : continue;
12852 : :
12853 : : /*
12854 : : * Set default_behavior to guide get_json_expr_options() on whether to
12855 : : * emit the ON ERROR / EMPTY clauses.
12856 : : */
12857 [ + + ]: 388 : if (colexpr->op == JSON_EXISTS_OP)
12858 : : {
12859 : 36 : appendStringInfoString(buf, " EXISTS");
12860 : 36 : default_behavior = JSON_BEHAVIOR_FALSE;
12861 : : }
12862 : : else
12863 : : {
12864 [ + + ]: 352 : if (colexpr->op == JSON_QUERY_OP)
12865 : : {
12866 : : char typcategory;
12867 : : bool typispreferred;
12868 : :
12869 : 168 : get_type_category_preferred(typid, &typcategory, &typispreferred);
12870 : :
12871 [ + + ]: 168 : if (typcategory == TYPCATEGORY_STRING)
12872 : 36 : appendStringInfoString(buf,
12873 [ - + ]: 36 : colexpr->format->format_type == JS_FORMAT_JSONB ?
12874 : : " FORMAT JSONB" : " FORMAT JSON");
12875 : : }
12876 : :
12877 : 352 : default_behavior = JSON_BEHAVIOR_NULL;
12878 : : }
12879 : :
12880 : 388 : appendStringInfoString(buf, " PATH ");
12881 : :
12882 : 388 : get_json_path_spec(colexpr->path_spec, context, showimplicit);
12883 : :
12884 : 388 : get_json_expr_options(colexpr, context, default_behavior);
12885 : : }
12886 : :
12887 [ + + ]: 160 : if (scan->child)
12888 : 48 : get_json_table_nested_columns(tf, scan->child, context, showimplicit,
12889 : 48 : scan->colMin >= 0);
12890 : :
12891 [ + + ]: 160 : if (PRETTY_INDENT(context))
12892 : 108 : context->indentLevel -= PRETTYINDENT_VAR;
12893 : :
12894 : 160 : appendContextKeyword(context, ")", 0, 0, 0);
12895 : 160 : }
12896 : :
12897 : : /* ----------
12898 : : * get_json_table - Parse back a JSON_TABLE function
12899 : : * ----------
12900 : : */
12901 : : static void
12902 : 84 : get_json_table(TableFunc *tf, deparse_context *context, bool showimplicit)
12903 : : {
12904 : 84 : StringInfo buf = context->buf;
12905 : 84 : JsonExpr *jexpr = castNode(JsonExpr, tf->docexpr);
12906 : 84 : JsonTablePathScan *root = castNode(JsonTablePathScan, tf->plan);
12907 : :
12908 : 84 : appendStringInfoString(buf, "JSON_TABLE(");
12909 : :
12910 [ + + ]: 84 : if (PRETTY_INDENT(context))
12911 : 52 : context->indentLevel += PRETTYINDENT_VAR;
12912 : :
12913 : 84 : appendContextKeyword(context, "", 0, 0, 0);
12914 : :
12915 : 84 : get_rule_expr(jexpr->formatted_expr, context, showimplicit);
12916 : :
12917 : 84 : appendStringInfoString(buf, ", ");
12918 : :
12919 : 84 : get_const_expr(root->path->value, context, -1);
12920 : :
12921 : 84 : appendStringInfo(buf, " AS %s", quote_identifier(root->path->name));
12922 : :
12923 [ + + ]: 84 : if (jexpr->passing_values)
12924 : : {
12925 : : ListCell *lc1,
12926 : : *lc2;
12927 : 60 : bool needcomma = false;
12928 : :
12929 : 60 : appendStringInfoChar(buf, ' ');
12930 : 60 : appendContextKeyword(context, "PASSING ", 0, 0, 0);
12931 : :
12932 [ + + ]: 60 : if (PRETTY_INDENT(context))
12933 : 28 : context->indentLevel += PRETTYINDENT_VAR;
12934 : :
12935 [ + - + + : 180 : forboth(lc1, jexpr->passing_names,
+ - + + +
+ + - +
+ ]
12936 : : lc2, jexpr->passing_values)
12937 : : {
12938 [ + + ]: 120 : if (needcomma)
12939 : 60 : appendStringInfoString(buf, ", ");
12940 : 120 : needcomma = true;
12941 : :
12942 : 120 : appendContextKeyword(context, "", 0, 0, 0);
12943 : :
12944 : 120 : get_rule_expr((Node *) lfirst(lc2), context, false);
12945 : 120 : appendStringInfo(buf, " AS %s",
12946 : 120 : quote_identifier((lfirst_node(String, lc1))->sval)
12947 : : );
12948 : : }
12949 : :
12950 [ + + ]: 60 : if (PRETTY_INDENT(context))
12951 : 28 : context->indentLevel -= PRETTYINDENT_VAR;
12952 : : }
12953 : :
12954 : 84 : get_json_table_columns(tf, castNode(JsonTablePathScan, tf->plan), context,
12955 : : showimplicit);
12956 : :
12957 : : /*
12958 : : * Deparse a PLAN clause only for a non-default plan; the default plan is
12959 : : * implied by the NESTED COLUMNS structure (see
12960 : : * json_table_plan_is_default).
12961 : : */
12962 [ + + + + ]: 84 : if (root->child && !json_table_plan_is_default((JsonTablePlan *) root))
12963 : : {
12964 : 4 : appendStringInfoChar(buf, ' ');
12965 : 4 : appendContextKeyword(context, "PLAN ", 0, 0, 0);
12966 : 4 : get_json_table_plan(tf, (JsonTablePlan *) root, context, true);
12967 : : }
12968 : :
12969 [ + + ]: 84 : if (jexpr->on_error->btype != JSON_BEHAVIOR_EMPTY_ARRAY)
12970 : 8 : get_json_behavior(jexpr->on_error, context, "ERROR");
12971 : :
12972 [ + + ]: 84 : if (PRETTY_INDENT(context))
12973 : 52 : context->indentLevel -= PRETTYINDENT_VAR;
12974 : :
12975 : 84 : appendContextKeyword(context, ")", 0, 0, 0);
12976 : 84 : }
12977 : :
12978 : : /* ----------
12979 : : * get_tablefunc - Parse back a table function
12980 : : * ----------
12981 : : */
12982 : : static void
12983 : 122 : get_tablefunc(TableFunc *tf, deparse_context *context, bool showimplicit)
12984 : : {
12985 : : /* XMLTABLE and JSON_TABLE are the only existing implementations. */
12986 : :
12987 [ + + ]: 122 : if (tf->functype == TFT_XMLTABLE)
12988 : 38 : get_xmltable(tf, context, showimplicit);
12989 [ + - ]: 84 : else if (tf->functype == TFT_JSON_TABLE)
12990 : 84 : get_json_table(tf, context, showimplicit);
12991 : 122 : }
12992 : :
12993 : : /* ----------
12994 : : * get_from_clause - Parse back a FROM clause
12995 : : *
12996 : : * "prefix" is the keyword that denotes the start of the list of FROM
12997 : : * elements. It is FROM when used to parse back SELECT and UPDATE, but
12998 : : * is USING when parsing back DELETE.
12999 : : * ----------
13000 : : */
13001 : : static void
13002 : 3041 : get_from_clause(Query *query, const char *prefix, deparse_context *context)
13003 : : {
13004 : 3041 : StringInfo buf = context->buf;
13005 : 3041 : bool first = true;
13006 : : ListCell *l;
13007 : :
13008 : : /*
13009 : : * We use the query's jointree as a guide to what to print. However, we
13010 : : * must ignore auto-added RTEs that are marked not inFromCl. (These can
13011 : : * only appear at the top level of the jointree, so it's sufficient to
13012 : : * check here.) This check also ensures we ignore the rule pseudo-RTEs
13013 : : * for NEW and OLD.
13014 : : */
13015 [ + + + + : 6053 : foreach(l, query->jointree->fromlist)
+ + ]
13016 : : {
13017 : 3012 : Node *jtnode = (Node *) lfirst(l);
13018 : :
13019 [ + + ]: 3012 : if (IsA(jtnode, RangeTblRef))
13020 : : {
13021 : 2407 : int varno = ((RangeTblRef *) jtnode)->rtindex;
13022 : 2407 : RangeTblEntry *rte = rt_fetch(varno, query->rtable);
13023 : :
13024 [ + + ]: 2407 : if (!rte->inFromCl)
13025 : 230 : continue;
13026 : : }
13027 : :
13028 [ + + ]: 2782 : if (first)
13029 : : {
13030 : 2549 : appendContextKeyword(context, prefix,
13031 : : -PRETTYINDENT_STD, PRETTYINDENT_STD, 2);
13032 : 2549 : first = false;
13033 : :
13034 : 2549 : get_from_clause_item(jtnode, query, context);
13035 : : }
13036 : : else
13037 : : {
13038 : : StringInfoData itembuf;
13039 : :
13040 : 233 : appendStringInfoString(buf, ", ");
13041 : :
13042 : : /*
13043 : : * Put the new FROM item's text into itembuf so we can decide
13044 : : * after we've got it whether or not it needs to go on a new line.
13045 : : */
13046 : 233 : initStringInfo(&itembuf);
13047 : 233 : context->buf = &itembuf;
13048 : :
13049 : 233 : get_from_clause_item(jtnode, query, context);
13050 : :
13051 : : /* Restore context's output buffer */
13052 : 233 : context->buf = buf;
13053 : :
13054 : : /* Consider line-wrapping if enabled */
13055 [ + - + - ]: 233 : if (PRETTY_INDENT(context) && context->wrapColumn >= 0)
13056 : : {
13057 : : /* Does the new item start with a new line? */
13058 [ + - - + ]: 233 : if (itembuf.len > 0 && itembuf.data[0] == '\n')
13059 : : {
13060 : : /* If so, we shouldn't add anything */
13061 : : /* instead, remove any trailing spaces currently in buf */
13062 : 0 : removeStringInfoSpaces(buf);
13063 : : }
13064 : : else
13065 : : {
13066 : : char *trailing_nl;
13067 : :
13068 : : /* Locate the start of the current line in the buffer */
13069 : 233 : trailing_nl = strrchr(buf->data, '\n');
13070 [ - + ]: 233 : if (trailing_nl == NULL)
13071 : 0 : trailing_nl = buf->data;
13072 : : else
13073 : 233 : trailing_nl++;
13074 : :
13075 : : /*
13076 : : * Add a newline, plus some indentation, if the new item
13077 : : * would cause an overflow.
13078 : : */
13079 [ + - ]: 233 : if (strlen(trailing_nl) + itembuf.len > context->wrapColumn)
13080 : 233 : appendContextKeyword(context, "", -PRETTYINDENT_STD,
13081 : : PRETTYINDENT_STD,
13082 : : PRETTYINDENT_VAR);
13083 : : }
13084 : : }
13085 : :
13086 : : /* Add the new item */
13087 : 233 : appendBinaryStringInfo(buf, itembuf.data, itembuf.len);
13088 : :
13089 : : /* clean up */
13090 : 233 : pfree(itembuf.data);
13091 : : }
13092 : : }
13093 : 3041 : }
13094 : :
13095 : : static void
13096 : 4662 : get_from_clause_item(Node *jtnode, Query *query, deparse_context *context)
13097 : : {
13098 : 4662 : StringInfo buf = context->buf;
13099 : 4662 : deparse_namespace *dpns = (deparse_namespace *) linitial(context->namespaces);
13100 : :
13101 [ + + ]: 4662 : if (IsA(jtnode, RangeTblRef))
13102 : : {
13103 : 3722 : int varno = ((RangeTblRef *) jtnode)->rtindex;
13104 : 3722 : RangeTblEntry *rte = rt_fetch(varno, query->rtable);
13105 : 3722 : deparse_columns *colinfo = deparse_columns_fetch(varno, dpns);
13106 : 3722 : RangeTblFunction *rtfunc1 = NULL;
13107 : :
13108 [ + + ]: 3722 : if (rte->lateral)
13109 : 73 : appendStringInfoString(buf, "LATERAL ");
13110 : :
13111 : : /* Print the FROM item proper */
13112 [ + + + + : 3722 : switch (rte->rtekind)
+ + + - ]
13113 : : {
13114 : 2755 : case RTE_RELATION:
13115 : : /* Normal relation RTE */
13116 : 5510 : appendStringInfo(buf, "%s%s",
13117 [ + + ]: 2755 : only_marker(rte),
13118 : : generate_relation_name(rte->relid,
13119 : : context->namespaces));
13120 : 2755 : break;
13121 : 200 : case RTE_SUBQUERY:
13122 : : /* Subquery RTE */
13123 : 200 : appendStringInfoChar(buf, '(');
13124 : 200 : get_query_def(rte->subquery, buf, context->namespaces, NULL,
13125 : : true,
13126 : : context->prettyFlags, context->wrapColumn,
13127 : : context->indentLevel);
13128 : 200 : appendStringInfoChar(buf, ')');
13129 : 200 : break;
13130 : 560 : case RTE_FUNCTION:
13131 : : /* Function RTE */
13132 : 560 : rtfunc1 = (RangeTblFunction *) linitial(rte->functions);
13133 : :
13134 : : /*
13135 : : * Omit ROWS FROM() syntax for just one function, unless it
13136 : : * has both a coldeflist and WITH ORDINALITY. If it has both,
13137 : : * we must use ROWS FROM() syntax to avoid ambiguity about
13138 : : * whether the coldeflist includes the ordinality column.
13139 : : */
13140 [ + + ]: 560 : if (list_length(rte->functions) == 1 &&
13141 [ - + - - ]: 540 : (rtfunc1->funccolnames == NIL || !rte->funcordinality))
13142 : : {
13143 : 540 : get_rule_expr_funccall(rtfunc1->funcexpr, context, true);
13144 : : /* we'll print the coldeflist below, if it has one */
13145 : : }
13146 : : else
13147 : : {
13148 : : bool all_unnest;
13149 : : ListCell *lc;
13150 : :
13151 : : /*
13152 : : * If all the function calls in the list are to unnest,
13153 : : * and none need a coldeflist, then collapse the list back
13154 : : * down to UNNEST(args). (If we had more than one
13155 : : * built-in unnest function, this would get more
13156 : : * difficult.)
13157 : : *
13158 : : * XXX This is pretty ugly, since it makes not-terribly-
13159 : : * future-proof assumptions about what the parser would do
13160 : : * with the output; but the alternative is to emit our
13161 : : * nonstandard ROWS FROM() notation for what might have
13162 : : * been a perfectly spec-compliant multi-argument
13163 : : * UNNEST().
13164 : : */
13165 : 20 : all_unnest = true;
13166 [ + - + + : 52 : foreach(lc, rte->functions)
+ + ]
13167 : : {
13168 : 44 : RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
13169 : :
13170 [ + - ]: 44 : if (!IsA(rtfunc->funcexpr, FuncExpr) ||
13171 [ + + ]: 44 : ((FuncExpr *) rtfunc->funcexpr)->funcid != F_UNNEST_ANYARRAY ||
13172 [ - + ]: 32 : rtfunc->funccolnames != NIL)
13173 : : {
13174 : 12 : all_unnest = false;
13175 : 12 : break;
13176 : : }
13177 : : }
13178 : :
13179 [ + + ]: 20 : if (all_unnest)
13180 : : {
13181 : 8 : List *allargs = NIL;
13182 : :
13183 [ + - + + : 32 : foreach(lc, rte->functions)
+ + ]
13184 : : {
13185 : 24 : RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
13186 : 24 : List *args = ((FuncExpr *) rtfunc->funcexpr)->args;
13187 : :
13188 : 24 : allargs = list_concat(allargs, args);
13189 : : }
13190 : :
13191 : 8 : appendStringInfoString(buf, "UNNEST(");
13192 : 8 : get_rule_expr((Node *) allargs, context, true);
13193 : 8 : appendStringInfoChar(buf, ')');
13194 : : }
13195 : : else
13196 : : {
13197 : 12 : int funcno = 0;
13198 : :
13199 : 12 : appendStringInfoString(buf, "ROWS FROM(");
13200 [ + - + + : 44 : foreach(lc, rte->functions)
+ + ]
13201 : : {
13202 : 32 : RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
13203 : :
13204 [ + + ]: 32 : if (funcno > 0)
13205 : 20 : appendStringInfoString(buf, ", ");
13206 : 32 : get_rule_expr_funccall(rtfunc->funcexpr, context, true);
13207 [ + + ]: 32 : if (rtfunc->funccolnames != NIL)
13208 : : {
13209 : : /* Reconstruct the column definition list */
13210 : 4 : appendStringInfoString(buf, " AS ");
13211 : 4 : get_from_clause_coldeflist(rtfunc,
13212 : : NULL,
13213 : : context);
13214 : : }
13215 : 32 : funcno++;
13216 : : }
13217 : 12 : appendStringInfoChar(buf, ')');
13218 : : }
13219 : : /* prevent printing duplicate coldeflist below */
13220 : 20 : rtfunc1 = NULL;
13221 : : }
13222 [ + + ]: 560 : if (rte->funcordinality)
13223 : 12 : appendStringInfoString(buf, " WITH ORDINALITY");
13224 : 560 : break;
13225 : 70 : case RTE_TABLEFUNC:
13226 : 70 : get_tablefunc(rte->tablefunc, context, true);
13227 : 70 : break;
13228 : 14 : case RTE_GRAPH_TABLE:
13229 : 14 : appendStringInfoString(buf, "GRAPH_TABLE (");
13230 : 14 : appendStringInfoString(buf, generate_relation_name(rte->relid, context->namespaces));
13231 : 14 : appendStringInfoString(buf, " MATCH ");
13232 : 14 : get_graph_pattern_def(rte->graph_pattern, context);
13233 : 14 : appendStringInfoString(buf, " COLUMNS (");
13234 : : {
13235 : 14 : bool first = true;
13236 : :
13237 [ + - + + : 69 : foreach_node(TargetEntry, te, rte->graph_table_columns)
+ + ]
13238 : : {
13239 [ + + ]: 41 : if (!first)
13240 : 27 : appendStringInfoString(buf, ", ");
13241 : : else
13242 : 14 : first = false;
13243 : :
13244 : 41 : get_rule_expr((Node *) te->expr, context, false);
13245 : 41 : appendStringInfoString(buf, " AS ");
13246 : 41 : appendStringInfoString(buf, quote_identifier(te->resname));
13247 : : }
13248 : : }
13249 : 14 : appendStringInfoString(buf, "))");
13250 : 14 : break;
13251 : 8 : case RTE_VALUES:
13252 : : /* Values list RTE */
13253 : 8 : appendStringInfoChar(buf, '(');
13254 : 8 : get_values_def(rte->values_lists, context);
13255 : 8 : appendStringInfoChar(buf, ')');
13256 : 8 : break;
13257 : 115 : case RTE_CTE:
13258 : 115 : appendStringInfoString(buf, quote_identifier(rte->ctename));
13259 : 115 : break;
13260 : 0 : default:
13261 [ # # ]: 0 : elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
13262 : : break;
13263 : : }
13264 : :
13265 : : /* Print the relation alias, if needed */
13266 : 3722 : get_rte_alias(rte, varno, false, context);
13267 : :
13268 : : /* Print the column definitions or aliases, if needed */
13269 [ + + - + ]: 3722 : if (rtfunc1 && rtfunc1->funccolnames != NIL)
13270 : : {
13271 : : /* Reconstruct the columndef list, which is also the aliases */
13272 : 0 : get_from_clause_coldeflist(rtfunc1, colinfo, context);
13273 : : }
13274 : : else
13275 : : {
13276 : : /* Else print column aliases as needed */
13277 : 3722 : get_column_alias_list(colinfo, context);
13278 : : }
13279 : :
13280 : : /* Tablesample clause must go after any alias */
13281 [ + + + + ]: 3722 : if (rte->rtekind == RTE_RELATION && rte->tablesample)
13282 : 18 : get_tablesample_def(rte->tablesample, context);
13283 : : }
13284 [ + - ]: 940 : else if (IsA(jtnode, JoinExpr))
13285 : : {
13286 : 940 : JoinExpr *j = (JoinExpr *) jtnode;
13287 : 940 : deparse_columns *colinfo = deparse_columns_fetch(j->rtindex, dpns);
13288 : : bool need_paren_on_right;
13289 : :
13290 : 2172 : need_paren_on_right = PRETTY_PAREN(context) &&
13291 [ + + - + ]: 940 : !IsA(j->rarg, RangeTblRef) &&
13292 [ # # # # ]: 0 : !(IsA(j->rarg, JoinExpr) && ((JoinExpr *) j->rarg)->alias != NULL);
13293 : :
13294 [ + + + + ]: 940 : if (!PRETTY_PAREN(context) || j->alias != NULL)
13295 : 720 : appendStringInfoChar(buf, '(');
13296 : :
13297 : 940 : get_from_clause_item(j->larg, query, context);
13298 : :
13299 [ + + + - : 940 : switch (j->jointype)
- ]
13300 : : {
13301 : 517 : case JOIN_INNER:
13302 [ + + ]: 517 : if (j->quals)
13303 : 489 : appendContextKeyword(context, " JOIN ",
13304 : : -PRETTYINDENT_STD,
13305 : : PRETTYINDENT_STD,
13306 : : PRETTYINDENT_JOIN);
13307 : : else
13308 : 28 : appendContextKeyword(context, " CROSS JOIN ",
13309 : : -PRETTYINDENT_STD,
13310 : : PRETTYINDENT_STD,
13311 : : PRETTYINDENT_JOIN);
13312 : 517 : break;
13313 : 355 : case JOIN_LEFT:
13314 : 355 : appendContextKeyword(context, " LEFT JOIN ",
13315 : : -PRETTYINDENT_STD,
13316 : : PRETTYINDENT_STD,
13317 : : PRETTYINDENT_JOIN);
13318 : 355 : break;
13319 : 68 : case JOIN_FULL:
13320 : 68 : appendContextKeyword(context, " FULL JOIN ",
13321 : : -PRETTYINDENT_STD,
13322 : : PRETTYINDENT_STD,
13323 : : PRETTYINDENT_JOIN);
13324 : 68 : break;
13325 : 0 : case JOIN_RIGHT:
13326 : 0 : appendContextKeyword(context, " RIGHT JOIN ",
13327 : : -PRETTYINDENT_STD,
13328 : : PRETTYINDENT_STD,
13329 : : PRETTYINDENT_JOIN);
13330 : 0 : break;
13331 : 0 : default:
13332 [ # # ]: 0 : elog(ERROR, "unrecognized join type: %d",
13333 : : (int) j->jointype);
13334 : : }
13335 : :
13336 [ - + ]: 940 : if (need_paren_on_right)
13337 : 0 : appendStringInfoChar(buf, '(');
13338 : 940 : get_from_clause_item(j->rarg, query, context);
13339 [ - + ]: 940 : if (need_paren_on_right)
13340 : 0 : appendStringInfoChar(buf, ')');
13341 : :
13342 [ + + ]: 940 : if (j->usingClause)
13343 : : {
13344 : : ListCell *lc;
13345 : 280 : bool first = true;
13346 : :
13347 : 280 : appendStringInfoString(buf, " USING (");
13348 : : /* Use the assigned names, not what's in usingClause */
13349 [ + - + + : 664 : foreach(lc, colinfo->usingNames)
+ + ]
13350 : : {
13351 : 384 : char *colname = (char *) lfirst(lc);
13352 : :
13353 [ + + ]: 384 : if (first)
13354 : 280 : first = false;
13355 : : else
13356 : 104 : appendStringInfoString(buf, ", ");
13357 : 384 : appendStringInfoString(buf, quote_identifier(colname));
13358 : : }
13359 : 280 : appendStringInfoChar(buf, ')');
13360 : :
13361 [ + + ]: 280 : if (j->join_using_alias)
13362 : 8 : appendStringInfo(buf, " AS %s",
13363 : 8 : quote_identifier(j->join_using_alias->aliasname));
13364 : : }
13365 [ + + ]: 660 : else if (j->quals)
13366 : : {
13367 : 628 : appendStringInfoString(buf, " ON ");
13368 [ + + ]: 628 : if (!PRETTY_PAREN(context))
13369 : 624 : appendStringInfoChar(buf, '(');
13370 : 628 : get_rule_expr(j->quals, context, false);
13371 [ + + ]: 628 : if (!PRETTY_PAREN(context))
13372 : 624 : appendStringInfoChar(buf, ')');
13373 : : }
13374 [ + + ]: 32 : else if (j->jointype != JOIN_INNER)
13375 : : {
13376 : : /* If we didn't say CROSS JOIN above, we must provide an ON */
13377 : 4 : appendStringInfoString(buf, " ON TRUE");
13378 : : }
13379 : :
13380 [ + + + + ]: 940 : if (!PRETTY_PAREN(context) || j->alias != NULL)
13381 : 720 : appendStringInfoChar(buf, ')');
13382 : :
13383 : : /* Yes, it's correct to put alias after the right paren ... */
13384 [ + + ]: 940 : if (j->alias != NULL)
13385 : : {
13386 : : /*
13387 : : * Note that it's correct to emit an alias clause if and only if
13388 : : * there was one originally. Otherwise we'd be converting a named
13389 : : * join to unnamed or vice versa, which creates semantic
13390 : : * subtleties we don't want. However, we might print a different
13391 : : * alias name than was there originally.
13392 : : */
13393 : 72 : appendStringInfo(buf, " %s",
13394 : 72 : quote_identifier(get_rtable_name(j->rtindex,
13395 : : context)));
13396 : 72 : get_column_alias_list(colinfo, context);
13397 : : }
13398 : : }
13399 : : else
13400 [ # # ]: 0 : elog(ERROR, "unrecognized node type: %d",
13401 : : (int) nodeTag(jtnode));
13402 : 4662 : }
13403 : :
13404 : : /*
13405 : : * get_rte_alias - print the relation's alias, if needed
13406 : : *
13407 : : * If printed, the alias is preceded by a space, or by " AS " if use_as is true.
13408 : : */
13409 : : static void
13410 : 4065 : get_rte_alias(RangeTblEntry *rte, int varno, bool use_as,
13411 : : deparse_context *context)
13412 : : {
13413 : 4065 : deparse_namespace *dpns = (deparse_namespace *) linitial(context->namespaces);
13414 : 4065 : char *refname = get_rtable_name(varno, context);
13415 : 4065 : deparse_columns *colinfo = deparse_columns_fetch(varno, dpns);
13416 : 4065 : bool printalias = false;
13417 : :
13418 [ + + ]: 4065 : if (rte->alias != NULL)
13419 : : {
13420 : : /* Always print alias if user provided one */
13421 : 1912 : printalias = true;
13422 : : }
13423 [ + + ]: 2153 : else if (colinfo->printaliases)
13424 : : {
13425 : : /* Always print alias if we need to print column aliases */
13426 : 210 : printalias = true;
13427 : : }
13428 [ + + ]: 1943 : else if (rte->rtekind == RTE_RELATION)
13429 : : {
13430 : : /*
13431 : : * No need to print alias if it's same as relation name (this would
13432 : : * normally be the case, but not if set_rtable_names had to resolve a
13433 : : * conflict).
13434 : : */
13435 [ + + ]: 1759 : if (strcmp(refname, get_relation_name(rte->relid)) != 0)
13436 : 52 : printalias = true;
13437 : : }
13438 [ - + ]: 184 : else if (rte->rtekind == RTE_FUNCTION)
13439 : : {
13440 : : /*
13441 : : * For a function RTE, always print alias. This covers possible
13442 : : * renaming of the function and/or instability of the FigureColname
13443 : : * rules for things that aren't simple functions. Note we'd need to
13444 : : * force it anyway for the columndef list case.
13445 : : */
13446 : 0 : printalias = true;
13447 : : }
13448 [ + + ]: 184 : else if (rte->rtekind == RTE_SUBQUERY ||
13449 [ + + ]: 168 : rte->rtekind == RTE_VALUES)
13450 : : {
13451 : : /*
13452 : : * For a subquery, always print alias. This makes the output
13453 : : * SQL-spec-compliant, even though we allow such aliases to be omitted
13454 : : * on input.
13455 : : */
13456 : 24 : printalias = true;
13457 : : }
13458 [ + + ]: 160 : else if (rte->rtekind == RTE_CTE)
13459 : : {
13460 : : /*
13461 : : * No need to print alias if it's same as CTE name (this would
13462 : : * normally be the case, but not if set_rtable_names had to resolve a
13463 : : * conflict).
13464 : : */
13465 [ + + ]: 89 : if (strcmp(refname, rte->ctename) != 0)
13466 : 12 : printalias = true;
13467 : : }
13468 : :
13469 [ + + ]: 4065 : if (printalias)
13470 [ + + ]: 2210 : appendStringInfo(context->buf, "%s%s",
13471 : : use_as ? " AS " : " ",
13472 : : quote_identifier(refname));
13473 : 4065 : }
13474 : :
13475 : : /*
13476 : : * get_for_portion_of - print FOR PORTION OF if needed
13477 : : * XXX: Newlines would help here, at least when pretty-printing. But then the
13478 : : * alias and SET will be on their own line with a leading space.
13479 : : */
13480 : : static void
13481 : 141 : get_for_portion_of(ForPortionOfExpr *forPortionOf, deparse_context *context)
13482 : : {
13483 [ + + ]: 141 : if (forPortionOf)
13484 : : {
13485 : 16 : appendStringInfo(context->buf, " FOR PORTION OF %s",
13486 : 16 : quote_identifier(forPortionOf->range_name));
13487 : :
13488 : : /*
13489 : : * Try to write it as FROM ... TO ... if we received it that way,
13490 : : * otherwise (targetRange).
13491 : : */
13492 [ + + + - ]: 16 : if (forPortionOf->targetFrom && forPortionOf->targetTo)
13493 : : {
13494 : 8 : appendStringInfoString(context->buf, " FROM ");
13495 : 8 : get_rule_expr(forPortionOf->targetFrom, context, false);
13496 : 8 : appendStringInfoString(context->buf, " TO ");
13497 : 8 : get_rule_expr(forPortionOf->targetTo, context, false);
13498 : : }
13499 : : else
13500 : : {
13501 : 8 : appendStringInfoString(context->buf, " (");
13502 : 8 : get_rule_expr(forPortionOf->targetRange, context, false);
13503 : 8 : appendStringInfoChar(context->buf, ')');
13504 : : }
13505 : : }
13506 : 141 : }
13507 : :
13508 : : /*
13509 : : * get_column_alias_list - print column alias list for an RTE
13510 : : *
13511 : : * Caller must already have printed the relation's alias name.
13512 : : */
13513 : : static void
13514 : 3794 : get_column_alias_list(deparse_columns *colinfo, deparse_context *context)
13515 : : {
13516 : 3794 : StringInfo buf = context->buf;
13517 : : int i;
13518 : 3794 : bool first = true;
13519 : :
13520 : : /* Don't print aliases if not needed */
13521 [ + + ]: 3794 : if (!colinfo->printaliases)
13522 : 2982 : return;
13523 : :
13524 [ + + ]: 6378 : for (i = 0; i < colinfo->num_new_cols; i++)
13525 : : {
13526 : 5566 : char *colname = colinfo->new_colnames[i];
13527 : :
13528 [ + + ]: 5566 : if (first)
13529 : : {
13530 : 812 : appendStringInfoChar(buf, '(');
13531 : 812 : first = false;
13532 : : }
13533 : : else
13534 : 4754 : appendStringInfoString(buf, ", ");
13535 : 5566 : appendStringInfoString(buf, quote_identifier(colname));
13536 : : }
13537 [ + - ]: 812 : if (!first)
13538 : 812 : appendStringInfoChar(buf, ')');
13539 : : }
13540 : :
13541 : : /*
13542 : : * get_from_clause_coldeflist - reproduce FROM clause coldeflist
13543 : : *
13544 : : * When printing a top-level coldeflist (which is syntactically also the
13545 : : * relation's column alias list), use column names from colinfo. But when
13546 : : * printing a coldeflist embedded inside ROWS FROM(), we prefer to use the
13547 : : * original coldeflist's names, which are available in rtfunc->funccolnames.
13548 : : * Pass NULL for colinfo to select the latter behavior.
13549 : : *
13550 : : * The coldeflist is appended immediately (no space) to buf. Caller is
13551 : : * responsible for ensuring that an alias or AS is present before it.
13552 : : */
13553 : : static void
13554 : 4 : get_from_clause_coldeflist(RangeTblFunction *rtfunc,
13555 : : deparse_columns *colinfo,
13556 : : deparse_context *context)
13557 : : {
13558 : 4 : StringInfo buf = context->buf;
13559 : : ListCell *l1;
13560 : : ListCell *l2;
13561 : : ListCell *l3;
13562 : : ListCell *l4;
13563 : : int i;
13564 : :
13565 : 4 : appendStringInfoChar(buf, '(');
13566 : :
13567 : 4 : i = 0;
13568 [ + - + + : 16 : forfour(l1, rtfunc->funccoltypes,
+ - + + +
- + + + -
+ + + + +
- + - + -
+ + ]
13569 : : l2, rtfunc->funccoltypmods,
13570 : : l3, rtfunc->funccolcollations,
13571 : : l4, rtfunc->funccolnames)
13572 : : {
13573 : 12 : Oid atttypid = lfirst_oid(l1);
13574 : 12 : int32 atttypmod = lfirst_int(l2);
13575 : 12 : Oid attcollation = lfirst_oid(l3);
13576 : : char *attname;
13577 : :
13578 [ - + ]: 12 : if (colinfo)
13579 : 0 : attname = colinfo->colnames[i];
13580 : : else
13581 : 12 : attname = strVal(lfirst(l4));
13582 : :
13583 : : Assert(attname); /* shouldn't be any dropped columns here */
13584 : :
13585 [ + + ]: 12 : if (i > 0)
13586 : 8 : appendStringInfoString(buf, ", ");
13587 : 12 : appendStringInfo(buf, "%s %s",
13588 : : quote_identifier(attname),
13589 : : format_type_with_typemod(atttypid, atttypmod));
13590 [ + + - + ]: 16 : if (OidIsValid(attcollation) &&
13591 : 4 : attcollation != get_typcollation(atttypid))
13592 : 0 : appendStringInfo(buf, " COLLATE %s",
13593 : : generate_collation_name(attcollation));
13594 : :
13595 : 12 : i++;
13596 : : }
13597 : :
13598 : 4 : appendStringInfoChar(buf, ')');
13599 : 4 : }
13600 : :
13601 : : /*
13602 : : * get_tablesample_def - print a TableSampleClause
13603 : : */
13604 : : static void
13605 : 18 : get_tablesample_def(TableSampleClause *tablesample, deparse_context *context)
13606 : : {
13607 : 18 : StringInfo buf = context->buf;
13608 : : Oid argtypes[1];
13609 : : int nargs;
13610 : : ListCell *l;
13611 : :
13612 : : /*
13613 : : * We should qualify the handler's function name if it wouldn't be
13614 : : * resolved by lookup in the current search path.
13615 : : */
13616 : 18 : argtypes[0] = INTERNALOID;
13617 : 18 : appendStringInfo(buf, " TABLESAMPLE %s (",
13618 : : generate_function_name(tablesample->tsmhandler, 1,
13619 : : NIL, argtypes,
13620 : : false, NULL, false));
13621 : :
13622 : 18 : nargs = 0;
13623 [ + - + + : 36 : foreach(l, tablesample->args)
+ + ]
13624 : : {
13625 [ - + ]: 18 : if (nargs++ > 0)
13626 : 0 : appendStringInfoString(buf, ", ");
13627 : 18 : get_rule_expr((Node *) lfirst(l), context, false);
13628 : : }
13629 : 18 : appendStringInfoChar(buf, ')');
13630 : :
13631 [ + + ]: 18 : if (tablesample->repeatable != NULL)
13632 : : {
13633 : 9 : appendStringInfoString(buf, " REPEATABLE (");
13634 : 9 : get_rule_expr((Node *) tablesample->repeatable, context, false);
13635 : 9 : appendStringInfoChar(buf, ')');
13636 : : }
13637 : 18 : }
13638 : :
13639 : : /*
13640 : : * get_opclass_name - fetch name of an index operator class
13641 : : *
13642 : : * The opclass name is appended (after a space) to buf.
13643 : : *
13644 : : * Output is suppressed if the opclass is the default for the given
13645 : : * actual_datatype. (If you don't want this behavior, just pass
13646 : : * InvalidOid for actual_datatype.)
13647 : : */
13648 : : static void
13649 : 7361 : get_opclass_name(Oid opclass, Oid actual_datatype,
13650 : : StringInfo buf)
13651 : : {
13652 : : HeapTuple ht_opc;
13653 : : Form_pg_opclass opcrec;
13654 : : char *opcname;
13655 : : char *nspname;
13656 : :
13657 : 7361 : ht_opc = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
13658 [ - + ]: 7361 : if (!HeapTupleIsValid(ht_opc))
13659 [ # # ]: 0 : elog(ERROR, "cache lookup failed for opclass %u", opclass);
13660 : 7361 : opcrec = (Form_pg_opclass) GETSTRUCT(ht_opc);
13661 : :
13662 [ + + + + ]: 14696 : if (!OidIsValid(actual_datatype) ||
13663 : 7335 : GetDefaultOpClass(actual_datatype, opcrec->opcmethod) != opclass)
13664 : : {
13665 : : /* Okay, we need the opclass name. Do we need to qualify it? */
13666 : 293 : opcname = NameStr(opcrec->opcname);
13667 [ + - ]: 293 : if (OpclassIsVisible(opclass))
13668 : 293 : appendStringInfo(buf, " %s", quote_identifier(opcname));
13669 : : else
13670 : : {
13671 : 0 : nspname = get_namespace_name_or_temp(opcrec->opcnamespace);
13672 : 0 : appendStringInfo(buf, " %s.%s",
13673 : : quote_identifier(nspname),
13674 : : quote_identifier(opcname));
13675 : : }
13676 : : }
13677 : 7361 : ReleaseSysCache(ht_opc);
13678 : 7361 : }
13679 : :
13680 : : /*
13681 : : * generate_opclass_name
13682 : : * Compute the name to display for an opclass specified by OID
13683 : : *
13684 : : * The result includes all necessary quoting and schema-prefixing.
13685 : : */
13686 : : char *
13687 : 4 : generate_opclass_name(Oid opclass)
13688 : : {
13689 : : StringInfoData buf;
13690 : :
13691 : 4 : initStringInfo(&buf);
13692 : 4 : get_opclass_name(opclass, InvalidOid, &buf);
13693 : :
13694 : 4 : return &buf.data[1]; /* get_opclass_name() prepends space */
13695 : : }
13696 : :
13697 : : /*
13698 : : * processIndirection - take care of array and subfield assignment
13699 : : *
13700 : : * We strip any top-level FieldStore or assignment SubscriptingRef nodes that
13701 : : * appear in the input, printing them as decoration for the base column
13702 : : * name (which we assume the caller just printed). We might also need to
13703 : : * strip CoerceToDomain nodes, but only ones that appear above assignment
13704 : : * nodes.
13705 : : *
13706 : : * Returns the subexpression that's to be assigned.
13707 : : */
13708 : : static Node *
13709 : 729 : processIndirection(Node *node, deparse_context *context)
13710 : : {
13711 : 729 : StringInfo buf = context->buf;
13712 : 729 : CoerceToDomain *cdomain = NULL;
13713 : :
13714 : : for (;;)
13715 : : {
13716 [ - + ]: 933 : if (node == NULL)
13717 : 0 : break;
13718 [ + + ]: 933 : if (IsA(node, FieldStore))
13719 : : {
13720 : 72 : FieldStore *fstore = (FieldStore *) node;
13721 : : Oid typrelid;
13722 : : char *fieldname;
13723 : :
13724 : : /* lookup tuple type */
13725 : 72 : typrelid = get_typ_typrelid(fstore->resulttype);
13726 [ - + ]: 72 : if (!OidIsValid(typrelid))
13727 [ # # ]: 0 : elog(ERROR, "argument type %s of FieldStore is not a tuple type",
13728 : : format_type_be(fstore->resulttype));
13729 : :
13730 : : /*
13731 : : * Print the field name. There should only be one target field in
13732 : : * stored rules. There could be more than that in executable
13733 : : * target lists, but this function cannot be used for that case.
13734 : : */
13735 : : Assert(list_length(fstore->fieldnums) == 1);
13736 : 72 : fieldname = get_attname(typrelid,
13737 : 72 : linitial_int(fstore->fieldnums), false);
13738 : 72 : appendStringInfo(buf, ".%s", quote_identifier(fieldname));
13739 : :
13740 : : /*
13741 : : * We ignore arg since it should be an uninteresting reference to
13742 : : * the target column or subcolumn.
13743 : : */
13744 : 72 : node = (Node *) linitial(fstore->newvals);
13745 : : }
13746 [ + + ]: 861 : else if (IsA(node, SubscriptingRef))
13747 : : {
13748 : 92 : SubscriptingRef *sbsref = (SubscriptingRef *) node;
13749 : :
13750 [ - + ]: 92 : if (sbsref->refassgnexpr == NULL)
13751 : 0 : break;
13752 : :
13753 : 92 : printSubscripts(sbsref, context);
13754 : :
13755 : : /*
13756 : : * We ignore refexpr since it should be an uninteresting reference
13757 : : * to the target column or subcolumn.
13758 : : */
13759 : 92 : node = (Node *) sbsref->refassgnexpr;
13760 : : }
13761 [ + + ]: 769 : else if (IsA(node, CoerceToDomain))
13762 : : {
13763 : 40 : cdomain = (CoerceToDomain *) node;
13764 : : /* If it's an explicit domain coercion, we're done */
13765 [ - + ]: 40 : if (cdomain->coercionformat != COERCE_IMPLICIT_CAST)
13766 : 0 : break;
13767 : : /* Tentatively descend past the CoerceToDomain */
13768 : 40 : node = (Node *) cdomain->arg;
13769 : : }
13770 : : else
13771 : 729 : break;
13772 : : }
13773 : :
13774 : : /*
13775 : : * If we descended past a CoerceToDomain whose argument turned out not to
13776 : : * be a FieldStore or array assignment, back up to the CoerceToDomain.
13777 : : * (This is not enough to be fully correct if there are nested implicit
13778 : : * CoerceToDomains, but such cases shouldn't ever occur.)
13779 : : */
13780 [ + + - + ]: 729 : if (cdomain && node == (Node *) cdomain->arg)
13781 : 0 : node = (Node *) cdomain;
13782 : :
13783 : 729 : return node;
13784 : : }
13785 : :
13786 : : static void
13787 : 316 : printSubscripts(SubscriptingRef *sbsref, deparse_context *context)
13788 : : {
13789 : 316 : StringInfo buf = context->buf;
13790 : : ListCell *lowlist_item;
13791 : : ListCell *uplist_item;
13792 : :
13793 : 316 : lowlist_item = list_head(sbsref->reflowerindexpr); /* could be NULL */
13794 [ + - + + : 632 : foreach(uplist_item, sbsref->refupperindexpr)
+ + ]
13795 : : {
13796 : 316 : appendStringInfoChar(buf, '[');
13797 [ - + ]: 316 : if (lowlist_item)
13798 : : {
13799 : : /* If subexpression is NULL, get_rule_expr prints nothing */
13800 : 0 : get_rule_expr((Node *) lfirst(lowlist_item), context, false);
13801 : 0 : appendStringInfoChar(buf, ':');
13802 : 0 : lowlist_item = lnext(sbsref->reflowerindexpr, lowlist_item);
13803 : : }
13804 : : /* If subexpression is NULL, get_rule_expr prints nothing */
13805 : 316 : get_rule_expr((Node *) lfirst(uplist_item), context, false);
13806 : 316 : appendStringInfoChar(buf, ']');
13807 : : }
13808 : 316 : }
13809 : :
13810 : : /*
13811 : : * quote_identifier - Quote an identifier only if needed
13812 : : *
13813 : : * When quotes are needed, we palloc the required space; slightly
13814 : : * space-wasteful but well worth it for notational simplicity.
13815 : : */
13816 : : const char *
13817 : 1911673 : quote_identifier(const char *ident)
13818 : : {
13819 : : /*
13820 : : * Can avoid quoting if ident starts with a lowercase letter or underscore
13821 : : * and contains only lowercase letters, digits, and underscores, *and* is
13822 : : * not any SQL keyword. Otherwise, supply quotes.
13823 : : */
13824 : 1911673 : int nquotes = 0;
13825 : : bool safe;
13826 : : const char *ptr;
13827 : : char *result;
13828 : : char *optr;
13829 : :
13830 : : /*
13831 : : * would like to use <ctype.h> macros here, but they might yield unwanted
13832 : : * locale-specific results...
13833 : : */
13834 [ + + - + : 1911673 : safe = ((ident[0] >= 'a' && ident[0] <= 'z') || ident[0] == '_');
+ + ]
13835 : :
13836 [ + + ]: 17024701 : for (ptr = ident; *ptr; ptr++)
13837 : : {
13838 : 15113028 : char ch = *ptr;
13839 : :
13840 [ + + + - : 15113028 : if ((ch >= 'a' && ch <= 'z') ||
+ + ]
13841 [ + + + + ]: 2303540 : (ch >= '0' && ch <= '9') ||
13842 : : (ch == '_'))
13843 : : {
13844 : : /* okay */
13845 : : }
13846 : : else
13847 : : {
13848 : 366885 : safe = false;
13849 [ + + ]: 366885 : if (ch == '"')
13850 : 89 : nquotes++;
13851 : : }
13852 : : }
13853 : :
13854 [ + + ]: 1911673 : if (quote_all_identifiers)
13855 : 7806 : safe = false;
13856 : :
13857 [ + + ]: 1911673 : if (safe)
13858 : : {
13859 : : /*
13860 : : * Check for keyword. We quote keywords except for unreserved ones.
13861 : : * (In some cases we could avoid quoting a col_name or type_func_name
13862 : : * keyword, but it seems much harder than it's worth to tell that.)
13863 : : *
13864 : : * Note: ScanKeywordLookup() does case-insensitive comparison, but
13865 : : * that's fine, since we already know we have all-lower-case.
13866 : : */
13867 : 1848392 : int kwnum = ScanKeywordLookup(ident, &ScanKeywords);
13868 : :
13869 [ + + + + ]: 1848392 : if (kwnum >= 0 && ScanKeywordCategories[kwnum] != UNRESERVED_KEYWORD)
13870 : 2548 : safe = false;
13871 : : }
13872 : :
13873 [ + + ]: 1911673 : if (safe)
13874 : 1845844 : return ident; /* no change needed */
13875 : :
13876 : 65829 : result = (char *) palloc(strlen(ident) + nquotes + 2 + 1);
13877 : :
13878 : 65829 : optr = result;
13879 : 65829 : *optr++ = '"';
13880 [ + + ]: 530819 : for (ptr = ident; *ptr; ptr++)
13881 : : {
13882 : 464990 : char ch = *ptr;
13883 : :
13884 [ + + ]: 464990 : if (ch == '"')
13885 : 89 : *optr++ = '"';
13886 : 464990 : *optr++ = ch;
13887 : : }
13888 : 65829 : *optr++ = '"';
13889 : 65829 : *optr = '\0';
13890 : :
13891 : 65829 : return result;
13892 : : }
13893 : :
13894 : : /*
13895 : : * quote_qualified_identifier - Quote a possibly-qualified identifier
13896 : : *
13897 : : * Return a name of the form qualifier.ident, or just ident if qualifier
13898 : : * is NULL, quoting each component if necessary. The result is palloc'd.
13899 : : */
13900 : : char *
13901 : 746765 : quote_qualified_identifier(const char *qualifier,
13902 : : const char *ident)
13903 : : {
13904 : : StringInfoData buf;
13905 : :
13906 : 746765 : initStringInfo(&buf);
13907 [ + + ]: 746765 : if (qualifier)
13908 : 260259 : appendStringInfo(&buf, "%s.", quote_identifier(qualifier));
13909 : 746765 : appendStringInfoString(&buf, quote_identifier(ident));
13910 : 746765 : return buf.data;
13911 : : }
13912 : :
13913 : : /*
13914 : : * get_relation_name
13915 : : * Get the unqualified name of a relation specified by OID
13916 : : *
13917 : : * This differs from the underlying get_rel_name() function in that it will
13918 : : * throw error instead of silently returning NULL if the OID is bad.
13919 : : */
13920 : : static char *
13921 : 10689 : get_relation_name(Oid relid)
13922 : : {
13923 : 10689 : char *relname = get_rel_name(relid);
13924 : :
13925 [ - + ]: 10689 : if (!relname)
13926 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", relid);
13927 : 10689 : return relname;
13928 : : }
13929 : :
13930 : : /*
13931 : : * generate_relation_name
13932 : : * Compute the name to display for a relation specified by OID
13933 : : *
13934 : : * The result includes all necessary quoting and schema-prefixing.
13935 : : *
13936 : : * If namespaces isn't NIL, it must be a list of deparse_namespace nodes.
13937 : : * We will forcibly qualify the relation name if it equals any CTE name
13938 : : * visible in the namespace list.
13939 : : */
13940 : : static char *
13941 : 5484 : generate_relation_name(Oid relid, List *namespaces)
13942 : : {
13943 : : HeapTuple tp;
13944 : : Form_pg_class reltup;
13945 : : bool need_qual;
13946 : : ListCell *nslist;
13947 : : char *relname;
13948 : : char *nspname;
13949 : : char *result;
13950 : :
13951 : 5484 : tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
13952 [ - + ]: 5484 : if (!HeapTupleIsValid(tp))
13953 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", relid);
13954 : 5484 : reltup = (Form_pg_class) GETSTRUCT(tp);
13955 : 5484 : relname = NameStr(reltup->relname);
13956 : :
13957 : : /* Check for conflicting CTE name */
13958 : 5484 : need_qual = false;
13959 [ + + + + : 9013 : foreach(nslist, namespaces)
+ + ]
13960 : : {
13961 : 3529 : deparse_namespace *dpns = (deparse_namespace *) lfirst(nslist);
13962 : : ListCell *ctlist;
13963 : :
13964 [ + + + + : 3617 : foreach(ctlist, dpns->ctes)
+ + ]
13965 : : {
13966 : 88 : CommonTableExpr *cte = (CommonTableExpr *) lfirst(ctlist);
13967 : :
13968 [ - + ]: 88 : if (strcmp(cte->ctename, relname) == 0)
13969 : : {
13970 : 0 : need_qual = true;
13971 : 0 : break;
13972 : : }
13973 : : }
13974 [ - + ]: 3529 : if (need_qual)
13975 : 0 : break;
13976 : : }
13977 : :
13978 : : /* Otherwise, qualify the name if not visible in search path */
13979 [ + - ]: 5484 : if (!need_qual)
13980 : 5484 : need_qual = !RelationIsVisible(relid);
13981 : :
13982 [ + + ]: 5484 : if (need_qual)
13983 : 1657 : nspname = get_namespace_name_or_temp(reltup->relnamespace);
13984 : : else
13985 : 3827 : nspname = NULL;
13986 : :
13987 : 5484 : result = quote_qualified_identifier(nspname, relname);
13988 : :
13989 : 5484 : ReleaseSysCache(tp);
13990 : :
13991 : 5484 : return result;
13992 : : }
13993 : :
13994 : : /*
13995 : : * generate_qualified_relation_name
13996 : : * Compute the name to display for a relation specified by OID
13997 : : *
13998 : : * As above, but unconditionally schema-qualify the name.
13999 : : */
14000 : : static char *
14001 : 4682 : generate_qualified_relation_name(Oid relid)
14002 : : {
14003 : : HeapTuple tp;
14004 : : Form_pg_class reltup;
14005 : : char *result;
14006 : :
14007 : 4682 : tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
14008 [ - + ]: 4682 : if (!HeapTupleIsValid(tp))
14009 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", relid);
14010 : 4682 : reltup = (Form_pg_class) GETSTRUCT(tp);
14011 : :
14012 : 4682 : result = get_qualified_objname(reltup->relnamespace,
14013 : 4682 : NameStr(reltup->relname));
14014 : 4682 : ReleaseSysCache(tp);
14015 : :
14016 : 4682 : return result;
14017 : : }
14018 : :
14019 : : /*
14020 : : * generate_function_name
14021 : : * Compute the name to display for a function specified by OID,
14022 : : * given that it is being called with the specified actual arg names and
14023 : : * types. (Those matter because of ambiguous-function resolution rules.)
14024 : : *
14025 : : * If we're dealing with a potentially variadic function (in practice, this
14026 : : * means a FuncExpr or Aggref, not some other way of calling a function), then
14027 : : * has_variadic must specify whether variadic arguments have been merged,
14028 : : * and *use_variadic_p will be set to indicate whether to print VARIADIC in
14029 : : * the output. For non-FuncExpr cases, has_variadic should be false and
14030 : : * use_variadic_p can be NULL.
14031 : : *
14032 : : * inGroupBy must be true if we're deparsing a GROUP BY clause.
14033 : : *
14034 : : * The result includes all necessary quoting and schema-prefixing.
14035 : : */
14036 : : static char *
14037 : 9825 : generate_function_name(Oid funcid, int nargs, List *argnames, Oid *argtypes,
14038 : : bool has_variadic, bool *use_variadic_p,
14039 : : bool inGroupBy)
14040 : : {
14041 : : char *result;
14042 : : HeapTuple proctup;
14043 : : Form_pg_proc procform;
14044 : : char *proname;
14045 : : bool use_variadic;
14046 : : char *nspname;
14047 : : FuncDetailCode p_result;
14048 : : int fgc_flags;
14049 : : Oid p_funcid;
14050 : : Oid p_rettype;
14051 : : bool p_retset;
14052 : : int p_nvargs;
14053 : : Oid p_vatype;
14054 : : Oid *p_true_typeids;
14055 : 9825 : bool force_qualify = false;
14056 : :
14057 : 9825 : proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
14058 [ - + ]: 9825 : if (!HeapTupleIsValid(proctup))
14059 [ # # ]: 0 : elog(ERROR, "cache lookup failed for function %u", funcid);
14060 : 9825 : procform = (Form_pg_proc) GETSTRUCT(proctup);
14061 : 9825 : proname = NameStr(procform->proname);
14062 : :
14063 : : /*
14064 : : * Due to parser hacks to avoid needing to reserve CUBE, we need to force
14065 : : * qualification of some function names within GROUP BY.
14066 : : */
14067 [ - + ]: 9825 : if (inGroupBy)
14068 : : {
14069 [ # # # # ]: 0 : if (strcmp(proname, "cube") == 0 || strcmp(proname, "rollup") == 0)
14070 : 0 : force_qualify = true;
14071 : : }
14072 : :
14073 : : /*
14074 : : * Determine whether VARIADIC should be printed. We must do this first
14075 : : * since it affects the lookup rules in func_get_detail().
14076 : : *
14077 : : * We always print VARIADIC if the function has a merged variadic-array
14078 : : * argument. Note that this is always the case for functions taking a
14079 : : * VARIADIC argument type other than VARIADIC ANY. If we omitted VARIADIC
14080 : : * and printed the array elements as separate arguments, the call could
14081 : : * match a newer non-VARIADIC function.
14082 : : */
14083 [ + + ]: 9825 : if (use_variadic_p)
14084 : : {
14085 : : /* Parser should not have set funcvariadic unless fn is variadic */
14086 : : Assert(!has_variadic || OidIsValid(procform->provariadic));
14087 : 8814 : use_variadic = has_variadic;
14088 : 8814 : *use_variadic_p = use_variadic;
14089 : : }
14090 : : else
14091 : : {
14092 : : Assert(!has_variadic);
14093 : 1011 : use_variadic = false;
14094 : : }
14095 : :
14096 : : /*
14097 : : * The idea here is to schema-qualify only if the parser would fail to
14098 : : * resolve the correct function given the unqualified func name with the
14099 : : * specified argtypes and VARIADIC flag. But if we already decided to
14100 : : * force qualification, then we can skip the lookup and pretend we didn't
14101 : : * find it.
14102 : : */
14103 [ + - ]: 9825 : if (!force_qualify)
14104 : 9825 : p_result = func_get_detail(list_make1(makeString(proname)),
14105 : : NIL, argnames, nargs, argtypes,
14106 : : !use_variadic, true, false,
14107 : : &fgc_flags,
14108 : : &p_funcid, &p_rettype,
14109 : : &p_retset, &p_nvargs, &p_vatype,
14110 : 9825 : &p_true_typeids, NULL);
14111 : : else
14112 : : {
14113 : 0 : p_result = FUNCDETAIL_NOTFOUND;
14114 : 0 : p_funcid = InvalidOid;
14115 : : }
14116 : :
14117 [ + + + + ]: 9825 : if ((p_result == FUNCDETAIL_NORMAL ||
14118 [ + + ]: 684 : p_result == FUNCDETAIL_AGGREGATE ||
14119 : 9233 : p_result == FUNCDETAIL_WINDOWFUNC) &&
14120 [ + - ]: 9233 : p_funcid == funcid)
14121 : 9233 : nspname = NULL;
14122 : : else
14123 : 592 : nspname = get_namespace_name_or_temp(procform->pronamespace);
14124 : :
14125 : 9825 : result = quote_qualified_identifier(nspname, proname);
14126 : :
14127 : 9825 : ReleaseSysCache(proctup);
14128 : :
14129 : 9825 : return result;
14130 : : }
14131 : :
14132 : : /*
14133 : : * generate_operator_name
14134 : : * Compute the name to display for an operator specified by OID,
14135 : : * given that it is being called with the specified actual arg types.
14136 : : * (Arg types matter because of ambiguous-operator resolution rules.
14137 : : * Pass InvalidOid for unused arg of a unary operator.)
14138 : : *
14139 : : * The result includes all necessary quoting and schema-prefixing,
14140 : : * plus the OPERATOR() decoration needed to use a qualified operator name
14141 : : * in an expression.
14142 : : */
14143 : : static char *
14144 : 43813 : generate_operator_name(Oid operid, Oid arg1, Oid arg2)
14145 : : {
14146 : : StringInfoData buf;
14147 : : HeapTuple opertup;
14148 : : Form_pg_operator operform;
14149 : : char *oprname;
14150 : : char *nspname;
14151 : : Operator p_result;
14152 : :
14153 : 43813 : initStringInfo(&buf);
14154 : :
14155 : 43813 : opertup = SearchSysCache1(OPEROID, ObjectIdGetDatum(operid));
14156 [ - + ]: 43813 : if (!HeapTupleIsValid(opertup))
14157 [ # # ]: 0 : elog(ERROR, "cache lookup failed for operator %u", operid);
14158 : 43813 : operform = (Form_pg_operator) GETSTRUCT(opertup);
14159 : 43813 : oprname = NameStr(operform->oprname);
14160 : :
14161 : : /*
14162 : : * The idea here is to schema-qualify only if the parser would fail to
14163 : : * resolve the correct operator given the unqualified op name with the
14164 : : * specified argtypes.
14165 : : */
14166 [ + + - ]: 43813 : switch (operform->oprkind)
14167 : : {
14168 : 43793 : case 'b':
14169 : 43793 : p_result = oper(NULL, list_make1(makeString(oprname)), arg1, arg2,
14170 : : true, -1);
14171 : 43793 : break;
14172 : 20 : case 'l':
14173 : 20 : p_result = left_oper(NULL, list_make1(makeString(oprname)), arg2,
14174 : : true, -1);
14175 : 20 : break;
14176 : 0 : default:
14177 [ # # ]: 0 : elog(ERROR, "unrecognized oprkind: %d", operform->oprkind);
14178 : : p_result = NULL; /* keep compiler quiet */
14179 : : break;
14180 : : }
14181 : :
14182 [ + + + - ]: 43813 : if (p_result != NULL && oprid(p_result) == operid)
14183 : 43808 : nspname = NULL;
14184 : : else
14185 : : {
14186 : 5 : nspname = get_namespace_name_or_temp(operform->oprnamespace);
14187 : 5 : appendStringInfo(&buf, "OPERATOR(%s.", quote_identifier(nspname));
14188 : : }
14189 : :
14190 : 43813 : appendStringInfoString(&buf, oprname);
14191 : :
14192 [ + + ]: 43813 : if (nspname)
14193 : 5 : appendStringInfoChar(&buf, ')');
14194 : :
14195 [ + + ]: 43813 : if (p_result != NULL)
14196 : 43808 : ReleaseSysCache(p_result);
14197 : :
14198 : 43813 : ReleaseSysCache(opertup);
14199 : :
14200 : 43813 : return buf.data;
14201 : : }
14202 : :
14203 : : /*
14204 : : * generate_operator_clause --- generate a binary-operator WHERE clause
14205 : : *
14206 : : * This is used for internally-generated-and-executed SQL queries, where
14207 : : * precision is essential and readability is secondary. The basic
14208 : : * requirement is to append "leftop op rightop" to buf, where leftop and
14209 : : * rightop are given as strings and are assumed to yield types leftoptype
14210 : : * and rightoptype; the operator is identified by OID. The complexity
14211 : : * comes from needing to be sure that the parser will select the desired
14212 : : * operator when the query is parsed. We always name the operator using
14213 : : * OPERATOR(schema.op) syntax, so as to avoid search-path uncertainties.
14214 : : * We have to emit casts too, if either input isn't already the input type
14215 : : * of the operator; else we are at the mercy of the parser's heuristics for
14216 : : * ambiguous-operator resolution. The caller must ensure that leftop and
14217 : : * rightop are suitable arguments for a cast operation; it's best to insert
14218 : : * parentheses if they aren't just variables or parameters.
14219 : : */
14220 : : void
14221 : 3158 : generate_operator_clause(StringInfo buf,
14222 : : const char *leftop, Oid leftoptype,
14223 : : Oid opoid,
14224 : : const char *rightop, Oid rightoptype)
14225 : : {
14226 : : HeapTuple opertup;
14227 : : Form_pg_operator operform;
14228 : : char *oprname;
14229 : : char *nspname;
14230 : :
14231 : 3158 : opertup = SearchSysCache1(OPEROID, ObjectIdGetDatum(opoid));
14232 [ - + ]: 3158 : if (!HeapTupleIsValid(opertup))
14233 [ # # ]: 0 : elog(ERROR, "cache lookup failed for operator %u", opoid);
14234 : 3158 : operform = (Form_pg_operator) GETSTRUCT(opertup);
14235 : : Assert(operform->oprkind == 'b');
14236 : 3158 : oprname = NameStr(operform->oprname);
14237 : :
14238 : 3158 : nspname = get_namespace_name(operform->oprnamespace);
14239 : :
14240 : 3158 : appendStringInfoString(buf, leftop);
14241 [ + + ]: 3158 : if (leftoptype != operform->oprleft)
14242 : 764 : add_cast_to(buf, operform->oprleft);
14243 : 3158 : appendStringInfo(buf, " OPERATOR(%s.", quote_identifier(nspname));
14244 : 3158 : appendStringInfoString(buf, oprname);
14245 : 3158 : appendStringInfo(buf, ") %s", rightop);
14246 [ + + ]: 3158 : if (rightoptype != operform->oprright)
14247 : 611 : add_cast_to(buf, operform->oprright);
14248 : :
14249 : 3158 : ReleaseSysCache(opertup);
14250 : 3158 : }
14251 : :
14252 : : /*
14253 : : * Add a cast specification to buf. We spell out the type name the hard way,
14254 : : * intentionally not using format_type_be(). This is to avoid corner cases
14255 : : * for CHARACTER, BIT, and perhaps other types, where specifying the type
14256 : : * using SQL-standard syntax results in undesirable data truncation. By
14257 : : * doing it this way we can be certain that the cast will have default (-1)
14258 : : * target typmod.
14259 : : */
14260 : : static void
14261 : 1375 : add_cast_to(StringInfo buf, Oid typid)
14262 : : {
14263 : : HeapTuple typetup;
14264 : : Form_pg_type typform;
14265 : : char *typname;
14266 : : char *nspname;
14267 : :
14268 : 1375 : typetup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
14269 [ - + ]: 1375 : if (!HeapTupleIsValid(typetup))
14270 [ # # ]: 0 : elog(ERROR, "cache lookup failed for type %u", typid);
14271 : 1375 : typform = (Form_pg_type) GETSTRUCT(typetup);
14272 : :
14273 : 1375 : typname = NameStr(typform->typname);
14274 : 1375 : nspname = get_namespace_name_or_temp(typform->typnamespace);
14275 : :
14276 : 1375 : appendStringInfo(buf, "::%s.%s",
14277 : : quote_identifier(nspname), quote_identifier(typname));
14278 : :
14279 : 1375 : ReleaseSysCache(typetup);
14280 : 1375 : }
14281 : :
14282 : : /*
14283 : : * generate_qualified_type_name
14284 : : * Compute the name to display for a type specified by OID
14285 : : *
14286 : : * This is different from format_type_be() in that we unconditionally
14287 : : * schema-qualify the name. That also means no special syntax for
14288 : : * SQL-standard type names ... although in current usage, this should
14289 : : * only get used for domains, so such cases wouldn't occur anyway.
14290 : : */
14291 : : static char *
14292 : 9 : generate_qualified_type_name(Oid typid)
14293 : : {
14294 : : HeapTuple tp;
14295 : : Form_pg_type typtup;
14296 : : char *typname;
14297 : : char *nspname;
14298 : : char *result;
14299 : :
14300 : 9 : tp = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
14301 [ - + ]: 9 : if (!HeapTupleIsValid(tp))
14302 [ # # ]: 0 : elog(ERROR, "cache lookup failed for type %u", typid);
14303 : 9 : typtup = (Form_pg_type) GETSTRUCT(tp);
14304 : 9 : typname = NameStr(typtup->typname);
14305 : :
14306 : 9 : nspname = get_namespace_name_or_temp(typtup->typnamespace);
14307 [ - + ]: 9 : if (!nspname)
14308 [ # # ]: 0 : elog(ERROR, "cache lookup failed for namespace %u",
14309 : : typtup->typnamespace);
14310 : :
14311 : 9 : result = quote_qualified_identifier(nspname, typname);
14312 : :
14313 : 9 : ReleaseSysCache(tp);
14314 : :
14315 : 9 : return result;
14316 : : }
14317 : :
14318 : : /*
14319 : : * generate_collation_name
14320 : : * Compute the name to display for a collation specified by OID
14321 : : *
14322 : : * The result includes all necessary quoting and schema-prefixing.
14323 : : */
14324 : : char *
14325 : 368 : generate_collation_name(Oid collid)
14326 : : {
14327 : : HeapTuple tp;
14328 : : Form_pg_collation colltup;
14329 : : char *collname;
14330 : : char *nspname;
14331 : : char *result;
14332 : :
14333 : 368 : tp = SearchSysCache1(COLLOID, ObjectIdGetDatum(collid));
14334 [ - + ]: 368 : if (!HeapTupleIsValid(tp))
14335 [ # # ]: 0 : elog(ERROR, "cache lookup failed for collation %u", collid);
14336 : 368 : colltup = (Form_pg_collation) GETSTRUCT(tp);
14337 : 368 : collname = NameStr(colltup->collname);
14338 : :
14339 [ - + ]: 368 : if (!CollationIsVisible(collid))
14340 : 0 : nspname = get_namespace_name_or_temp(colltup->collnamespace);
14341 : : else
14342 : 368 : nspname = NULL;
14343 : :
14344 : 368 : result = quote_qualified_identifier(nspname, collname);
14345 : :
14346 : 368 : ReleaseSysCache(tp);
14347 : :
14348 : 368 : return result;
14349 : : }
14350 : :
14351 : : /*
14352 : : * Given a C string, produce a TEXT datum.
14353 : : *
14354 : : * We assume that the input was palloc'd and may be freed.
14355 : : */
14356 : : static text *
14357 : 26837 : string_to_text(char *str)
14358 : : {
14359 : : text *result;
14360 : :
14361 : 26837 : result = cstring_to_text(str);
14362 : 26837 : pfree(str);
14363 : 26837 : return result;
14364 : : }
14365 : :
14366 : : /*
14367 : : * Generate a C string representing a relation options from text[] datum.
14368 : : */
14369 : : void
14370 : 131 : get_reloptions(StringInfo buf, Datum reloptions)
14371 : : {
14372 : : Datum *options;
14373 : : int noptions;
14374 : : int i;
14375 : :
14376 : 131 : deconstruct_array_builtin(DatumGetArrayTypeP(reloptions), TEXTOID,
14377 : : &options, NULL, &noptions);
14378 : :
14379 [ + + ]: 284 : for (i = 0; i < noptions; i++)
14380 : : {
14381 : 153 : char *option = TextDatumGetCString(options[i]);
14382 : : char *name;
14383 : : char *separator;
14384 : : char *value;
14385 : :
14386 : : /*
14387 : : * Each array element should have the form name=value. If the "=" is
14388 : : * missing for some reason, treat it like an empty value.
14389 : : */
14390 : 153 : name = option;
14391 : 153 : separator = strchr(option, '=');
14392 [ + - ]: 153 : if (separator)
14393 : : {
14394 : 153 : *separator = '\0';
14395 : 153 : value = separator + 1;
14396 : : }
14397 : : else
14398 : 0 : value = "";
14399 : :
14400 [ + + ]: 153 : if (i > 0)
14401 : 22 : appendStringInfoString(buf, ", ");
14402 : 153 : appendStringInfo(buf, "%s=", quote_identifier(name));
14403 : :
14404 : : /*
14405 : : * In general we need to quote the value; but to avoid unnecessary
14406 : : * clutter, do not quote if it is an identifier that would not need
14407 : : * quoting. (We could also allow numbers, but that is a bit trickier
14408 : : * than it looks --- for example, are leading zeroes significant? We
14409 : : * don't want to assume very much here about what custom reloptions
14410 : : * might mean.)
14411 : : */
14412 [ + + ]: 153 : if (quote_identifier(value) == value)
14413 : 4 : appendStringInfoString(buf, value);
14414 : : else
14415 : 149 : simple_quote_literal(buf, value);
14416 : :
14417 : 153 : pfree(option);
14418 : : }
14419 : 131 : }
14420 : :
14421 : : /*
14422 : : * Generate a C string representing a relation's reloptions, or NULL if none.
14423 : : */
14424 : : static char *
14425 : 4612 : flatten_reloptions(Oid relid)
14426 : : {
14427 : 4612 : char *result = NULL;
14428 : : HeapTuple tuple;
14429 : : Datum reloptions;
14430 : : bool isnull;
14431 : :
14432 : 4612 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
14433 [ - + ]: 4612 : if (!HeapTupleIsValid(tuple))
14434 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", relid);
14435 : :
14436 : 4612 : reloptions = SysCacheGetAttr(RELOID, tuple,
14437 : : Anum_pg_class_reloptions, &isnull);
14438 [ + + ]: 4612 : if (!isnull)
14439 : : {
14440 : : StringInfoData buf;
14441 : :
14442 : 105 : initStringInfo(&buf);
14443 : 105 : get_reloptions(&buf, reloptions);
14444 : :
14445 : 105 : result = buf.data;
14446 : : }
14447 : :
14448 : 4612 : ReleaseSysCache(tuple);
14449 : :
14450 : 4612 : return result;
14451 : : }
14452 : :
14453 : : /*
14454 : : * get_range_partbound_string
14455 : : * A C string representation of one range partition bound
14456 : : */
14457 : : char *
14458 : 3162 : get_range_partbound_string(List *bound_datums)
14459 : : {
14460 : : deparse_context context;
14461 : : StringInfoData buf;
14462 : : ListCell *cell;
14463 : : char *sep;
14464 : :
14465 : 3162 : initStringInfo(&buf);
14466 : 3162 : memset(&context, 0, sizeof(deparse_context));
14467 : 3162 : context.buf = &buf;
14468 : :
14469 : 3162 : appendStringInfoChar(&buf, '(');
14470 : 3162 : sep = "";
14471 [ + - + + : 6802 : foreach(cell, bound_datums)
+ + ]
14472 : : {
14473 : 3640 : PartitionRangeDatum *datum =
14474 : : lfirst_node(PartitionRangeDatum, cell);
14475 : :
14476 : 3640 : appendStringInfoString(&buf, sep);
14477 [ + + ]: 3640 : if (datum->kind == PARTITION_RANGE_DATUM_MINVALUE)
14478 : 148 : appendStringInfoString(&buf, "MINVALUE");
14479 [ + + ]: 3492 : else if (datum->kind == PARTITION_RANGE_DATUM_MAXVALUE)
14480 : 80 : appendStringInfoString(&buf, "MAXVALUE");
14481 : : else
14482 : : {
14483 : 3412 : Const *val = castNode(Const, datum->value);
14484 : :
14485 : 3412 : get_const_expr(val, &context, -1);
14486 : : }
14487 : 3640 : sep = ", ";
14488 : : }
14489 : 3162 : appendStringInfoChar(&buf, ')');
14490 : :
14491 : 3162 : return buf.data;
14492 : : }
|