Debian Codegraph @

src/backend/utils/adt/ruleutils.c

raw
1 /*-------------------------------------------------------------------------
2 *
3 * ruleutils.c
4 * Functions to convert stored expressions/querytrees back to
5 * source text
6 *
7 * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
9 *
10 *
11 * IDENTIFICATION
12 * src/backend/utils/adt/ruleutils.c
13 *
14 *-------------------------------------------------------------------------
15 */
16 #include "postgres.h"
17
18 #include <ctype.h>
19 #include <unistd.h>
20 #include <fcntl.h>
21
22 #include "access/amapi.h"
23 #include "access/htup_details.h"
24 #include "access/relation.h"
25 #include "access/table.h"
26 #include "catalog/pg_aggregate.h"
27 #include "catalog/pg_am.h"
28 #include "catalog/pg_authid.h"
29 #include "catalog/pg_collation.h"
30 #include "catalog/pg_constraint.h"
31 #include "catalog/pg_depend.h"
32 #include "catalog/pg_language.h"
33 #include "catalog/pg_opclass.h"
34 #include "catalog/pg_operator.h"
35 #include "catalog/pg_partitioned_table.h"
36 #include "catalog/pg_proc.h"
37 #include "catalog/pg_statistic_ext.h"
38 #include "catalog/pg_trigger.h"
39 #include "catalog/pg_type.h"
40 #include "commands/defrem.h"
41 #include "commands/tablespace.h"
42 #include "common/keywords.h"
43 #include "executor/spi.h"
44 #include "funcapi.h"
45 #include "mb/pg_wchar.h"
46 #include "miscadmin.h"
47 #include "nodes/makefuncs.h"
48 #include "nodes/nodeFuncs.h"
49 #include "nodes/pathnodes.h"
50 #include "optimizer/optimizer.h"
51 #include "parser/parse_agg.h"
52 #include "parser/parse_func.h"
53 #include "parser/parse_oper.h"
54 #include "parser/parse_relation.h"
55 #include "parser/parser.h"
56 #include "parser/parsetree.h"
57 #include "rewrite/rewriteHandler.h"
58 #include "rewrite/rewriteManip.h"
59 #include "rewrite/rewriteSupport.h"
60 #include "utils/array.h"
61 #include "utils/builtins.h"
62 #include "utils/fmgroids.h"
63 #include "utils/guc.h"
64 #include "utils/hsearch.h"
65 #include "utils/lsyscache.h"
66 #include "utils/partcache.h"
67 #include "utils/rel.h"
68 #include "utils/ruleutils.h"
69 #include "utils/snapmgr.h"
70 #include "utils/syscache.h"
71 #include "utils/typcache.h"
72 #include "utils/varlena.h"
73 #include "utils/xml.h"
74
75 /* ----------
76 * Pretty formatting constants
77 * ----------
78 */
79
80 /* Indent counts */
81 #define PRETTYINDENT_STD 8
82 #define PRETTYINDENT_JOIN 4
83 #define PRETTYINDENT_VAR 4
84
85 #define PRETTYINDENT_LIMIT 40 /* wrap limit */
86
87 /* Pretty flags */
88 #define PRETTYFLAG_PAREN 0x0001
89 #define PRETTYFLAG_INDENT 0x0002
90 #define PRETTYFLAG_SCHEMA 0x0004
91
92 /* Standard conversion of a "bool pretty" option to detailed flags */
93 #define GET_PRETTY_FLAGS(pretty) \
94 ((pretty) ? (PRETTYFLAG_PAREN | PRETTYFLAG_INDENT | PRETTYFLAG_SCHEMA) \
95 : PRETTYFLAG_INDENT)
96
97 /* Default line length for pretty-print wrapping: 0 means wrap always */
98 #define WRAP_COLUMN_DEFAULT 0
99
100 /* macros to test if pretty action needed */
101 #define PRETTY_PAREN(context) ((context)->prettyFlags & PRETTYFLAG_PAREN)
102 #define PRETTY_INDENT(context) ((context)->prettyFlags & PRETTYFLAG_INDENT)
103 #define PRETTY_SCHEMA(context) ((context)->prettyFlags & PRETTYFLAG_SCHEMA)
104
105
106 /* ----------
107 * Local data types
108 * ----------
109 */
110
111 /* Context info needed for invoking a recursive querytree display routine */
112 typedef struct
113 {
114 StringInfo buf; /* output buffer to append to */
115 List *namespaces; /* List of deparse_namespace nodes */
116 TupleDesc resultDesc; /* if top level of a view, the view's tupdesc */
117 List *targetList; /* Current query level's SELECT targetlist */
118 List *windowClause; /* Current query level's WINDOW clause */
119 int prettyFlags; /* enabling of pretty-print functions */
120 int wrapColumn; /* max line length, or -1 for no limit */
121 int indentLevel; /* current indent level for pretty-print */
122 bool varprefix; /* true to print prefixes on Vars */
123 bool colNamesVisible; /* do we care about output column names? */
124 bool inGroupBy; /* deparsing GROUP BY clause? */
125 bool varInOrderBy; /* deparsing simple Var in ORDER BY? */
126 Bitmapset *appendparents; /* if not null, map child Vars of these relids
127 * back to the parent rel */
128 } deparse_context;
129
130 /*
131 * Each level of query context around a subtree needs a level of Var namespace.
132 * A Var having varlevelsup=N refers to the N'th item (counting from 0) in
133 * the current context's namespaces list.
134 *
135 * rtable is the list of actual RTEs from the Query or PlannedStmt.
136 * rtable_names holds the alias name to be used for each RTE (either a C
137 * string, or NULL for nameless RTEs such as unnamed joins).
138 * rtable_columns holds the column alias names to be used for each RTE.
139 *
140 * subplans is a list of Plan trees for SubPlans and CTEs (it's only used
141 * in the PlannedStmt case).
142 * ctes is a list of CommonTableExpr nodes (only used in the Query case).
143 * appendrels, if not null (it's only used in the PlannedStmt case), is an
144 * array of AppendRelInfo nodes, indexed by child relid. We use that to map
145 * child-table Vars to their inheritance parents.
146 *
147 * In some cases we need to make names of merged JOIN USING columns unique
148 * across the whole query, not only per-RTE. If so, unique_using is true
149 * and using_names is a list of C strings representing names already assigned
150 * to USING columns.
151 *
152 * When deparsing plan trees, there is always just a single item in the
153 * deparse_namespace list (since a plan tree never contains Vars with
154 * varlevelsup > 0). We store the Plan node that is the immediate
155 * parent of the expression to be deparsed, as well as a list of that
156 * Plan's ancestors. In addition, we store its outer and inner subplan nodes,
157 * as well as their targetlists, and the index tlist if the current plan node
158 * might contain INDEX_VAR Vars. (These fields could be derived on-the-fly
159 * from the current Plan node, but it seems notationally clearer to set them
160 * up as separate fields.)
161 */
162 typedef struct
163 {
164 List *rtable; /* List of RangeTblEntry nodes */
165 List *rtable_names; /* Parallel list of names for RTEs */
166 List *rtable_columns; /* Parallel list of deparse_columns structs */
167 List *subplans; /* List of Plan trees for SubPlans */
168 List *ctes; /* List of CommonTableExpr nodes */
169 AppendRelInfo **appendrels; /* Array of AppendRelInfo nodes, or NULL */
170 char *ret_old_alias; /* alias for OLD in RETURNING list */
171 char *ret_new_alias; /* alias for NEW in RETURNING list */
172 /* Workspace for column alias assignment: */
173 bool unique_using; /* Are we making USING names globally unique */
174 List *using_names; /* List of assigned names for USING columns */
175 /* Remaining fields are used only when deparsing a Plan tree: */
176 Plan *plan; /* immediate parent of current expression */
177 List *ancestors; /* ancestors of plan */
178 Plan *outer_plan; /* outer subnode, or NULL if none */
179 Plan *inner_plan; /* inner subnode, or NULL if none */
180 List *outer_tlist; /* referent for OUTER_VAR Vars */
181 List *inner_tlist; /* referent for INNER_VAR Vars */
182 List *index_tlist; /* referent for INDEX_VAR Vars */
183 /* Special namespace representing a function signature: */
184 char *funcname;
185 int numargs;
186 char **argnames;
187 } deparse_namespace;
188
189 /*
190 * Per-relation data about column alias names.
191 *
192 * Selecting aliases is unreasonably complicated because of the need to dump
193 * rules/views whose underlying tables may have had columns added, deleted, or
194 * renamed since the query was parsed. We must nonetheless print the rule/view
195 * in a form that can be reloaded and will produce the same results as before.
196 *
197 * For each RTE used in the query, we must assign column aliases that are
198 * unique within that RTE. SQL does not require this of the original query,
199 * but due to factors such as *-expansion we need to be able to uniquely
200 * reference every column in a decompiled query. As long as we qualify all
201 * column references, per-RTE uniqueness is sufficient for that.
202 *
203 * However, we can't ensure per-column name uniqueness for unnamed join RTEs,
204 * since they just inherit column names from their input RTEs, and we can't
205 * rename the columns at the join level. Most of the time this isn't an issue
206 * because we don't need to reference the join's output columns as such; we
207 * can reference the input columns instead. That approach can fail for merged
208 * JOIN USING columns, however, so when we have one of those in an unnamed
209 * join, we have to make that column's alias globally unique across the whole
210 * query to ensure it can be referenced unambiguously.
211 *
212 * Another problem is that a JOIN USING clause requires the columns to be
213 * merged to have the same aliases in both input RTEs, and that no other
214 * columns in those RTEs or their children conflict with the USING names.
215 * To handle that, we do USING-column alias assignment in a recursive
216 * traversal of the query's jointree. When descending through a JOIN with
217 * USING, we preassign the USING column names to the child columns, overriding
218 * other rules for column alias assignment. We also mark each RTE with a list
219 * of all USING column names selected for joins containing that RTE, so that
220 * when we assign other columns' aliases later, we can avoid conflicts.
221 *
222 * Another problem is that if a JOIN's input tables have had columns added or
223 * deleted since the query was parsed, we must generate a column alias list
224 * for the join that matches the current set of input columns --- otherwise, a
225 * change in the number of columns in the left input would throw off matching
226 * of aliases to columns of the right input. Thus, positions in the printable
227 * column alias list are not necessarily one-for-one with varattnos of the
228 * JOIN, so we need a separate new_colnames[] array for printing purposes.
229 *
230 * Finally, when dealing with wide tables we risk O(N^2) costs in assigning
231 * non-duplicate column names. We ameliorate that by using a hash table that
232 * holds all the strings appearing in colnames, new_colnames, and parentUsing.
233 */
234 typedef struct
235 {
236 /*
237 * colnames is an array containing column aliases to use for columns that
238 * existed when the query was parsed. Dropped columns have NULL entries.
239 * This array can be directly indexed by varattno to get a Var's name.
240 *
241 * Non-NULL entries are guaranteed unique within the RTE, *except* when
242 * this is for an unnamed JOIN RTE. In that case we merely copy up names
243 * from the two input RTEs.
244 *
245 * During the recursive descent in set_using_names(), forcible assignment
246 * of a child RTE's column name is represented by pre-setting that element
247 * of the child's colnames array. So at that stage, NULL entries in this
248 * array just mean that no name has been preassigned, not necessarily that
249 * the column is dropped.
250 */
251 int num_cols; /* length of colnames[] array */
252 char **colnames; /* array of C strings and NULLs */
253
254 /*
255 * new_colnames is an array containing column aliases to use for columns
256 * that would exist if the query was re-parsed against the current
257 * definitions of its base tables. This is what to print as the column
258 * alias list for the RTE. This array does not include dropped columns,
259 * but it will include columns added since original parsing. Indexes in
260 * it therefore have little to do with current varattno values. As above,
261 * entries are unique unless this is for an unnamed JOIN RTE. (In such an
262 * RTE, we never actually print this array, but we must compute it anyway
263 * for possible use in computing column names of upper joins.) The
264 * parallel array is_new_col marks which of these columns are new since
265 * original parsing. Entries with is_new_col false must match the
266 * non-NULL colnames entries one-for-one.
267 */
268 int num_new_cols; /* length of new_colnames[] array */
269 char **new_colnames; /* array of C strings */
270 bool *is_new_col; /* array of bool flags */
271
272 /* This flag tells whether we should actually print a column alias list */
273 bool printaliases;
274
275 /* This list has all names used as USING names in joins above this RTE */
276 List *parentUsing; /* names assigned to parent merged columns */
277
278 /*
279 * If this struct is for a JOIN RTE, we fill these fields during the
280 * set_using_names() pass to describe its relationship to its child RTEs.
281 *
282 * leftattnos and rightattnos are arrays with one entry per existing
283 * output column of the join (hence, indexable by join varattno). For a
284 * simple reference to a column of the left child, leftattnos[i] is the
285 * child RTE's attno and rightattnos[i] is zero; and conversely for a
286 * column of the right child. But for merged columns produced by JOIN
287 * USING/NATURAL JOIN, both leftattnos[i] and rightattnos[i] are nonzero.
288 * Note that a simple reference might be to a child RTE column that's been
289 * dropped; but that's OK since the column could not be used in the query.
290 *
291 * If it's a JOIN USING, usingNames holds the alias names selected for the
292 * merged columns (these might be different from the original USING list,
293 * if we had to modify names to achieve uniqueness).
294 */
295 int leftrti; /* rangetable index of left child */
296 int rightrti; /* rangetable index of right child */
297 int *leftattnos; /* left-child varattnos of join cols, or 0 */
298 int *rightattnos; /* right-child varattnos of join cols, or 0 */
299 List *usingNames; /* names assigned to merged columns */
300
301 /*
302 * Hash table holding copies of all the strings appearing in this struct's
303 * colnames, new_colnames, and parentUsing. We use a hash table only for
304 * sufficiently wide relations, and only during the colname-assignment
305 * functions set_relation_column_names and set_join_column_names;
306 * otherwise, names_hash is NULL.
307 */
308 HTAB *names_hash; /* entries are just strings */
309 } deparse_columns;
310
311 /* This macro is analogous to rt_fetch(), but for deparse_columns structs */
312 #define deparse_columns_fetch(rangetable_index, dpns) \
313 ((deparse_columns *) list_nth((dpns)->rtable_columns, (rangetable_index)-1))
314
315 /*
316 * Entry in set_rtable_names' hash table
317 */
318 typedef struct
319 {
320 char name[NAMEDATALEN]; /* Hash key --- must be first */
321 int counter; /* Largest addition used so far for name */
322 } NameHashEntry;
323
324 /* Callback signature for resolve_special_varno() */
325 typedef void (*rsv_callback) (Node *node, deparse_context *context,
326 void *callback_arg);
327
328
329 /* ----------
330 * Global data
331 * ----------
332 */
333 static SPIPlanPtr plan_getrulebyoid = NULL;
334 static const char *const query_getrulebyoid = "SELECT * FROM pg_catalog.pg_rewrite WHERE oid = $1";
335 static SPIPlanPtr plan_getviewrule = NULL;
336 static const char *const query_getviewrule = "SELECT * FROM pg_catalog.pg_rewrite WHERE ev_class = $1 AND rulename = $2";
337
338 /* GUC parameters */
339 bool quote_all_identifiers = false;
340
341
342 /* ----------
343 * Local functions
344 *
345 * Most of these functions used to use fixed-size buffers to build their
346 * results. Now, they take an (already initialized) StringInfo object
347 * as a parameter, and append their text output to its contents.
348 * ----------
349 */
350 static char *deparse_expression_pretty(Node *expr, List *dpcontext,
351 bool forceprefix, bool showimplicit,
352 int prettyFlags, int startIndent);
353 static char *pg_get_viewdef_worker(Oid viewoid,
354 int prettyFlags, int wrapColumn);
355 static char *pg_get_triggerdef_worker(Oid trigid, bool pretty);
356 static int decompile_column_index_array(Datum column_index_array, Oid relId,
357 bool withPeriod, StringInfo buf);
358 static char *pg_get_ruledef_worker(Oid ruleoid, int prettyFlags);
359 static char *pg_get_indexdef_worker(Oid indexrelid, int colno,
360 const Oid *excludeOps,
361 bool attrsOnly, bool keysOnly,
362 bool showTblSpc, bool inherits,
363 int prettyFlags, bool missing_ok);
364 static char *pg_get_statisticsobj_worker(Oid statextid, bool columns_only,
365 bool missing_ok);
366 static char *pg_get_partkeydef_worker(Oid relid, int prettyFlags,
367 bool attrsOnly, bool missing_ok);
368 static char *pg_get_constraintdef_worker(Oid constraintId, bool fullCommand,
369 int prettyFlags, bool missing_ok);
370 static text *pg_get_expr_worker(text *expr, Oid relid, int prettyFlags);
371 static int print_function_arguments(StringInfo buf, HeapTuple proctup,
372 bool print_table_args, bool print_defaults);
373 static void print_function_rettype(StringInfo buf, HeapTuple proctup);
374 static void print_function_trftypes(StringInfo buf, HeapTuple proctup);
375 static void print_function_sqlbody(StringInfo buf, HeapTuple proctup);
376 static void set_rtable_names(deparse_namespace *dpns, List *parent_namespaces,
377 Bitmapset *rels_used);
378 static void set_deparse_for_query(deparse_namespace *dpns, Query *query,
379 List *parent_namespaces);
380 static void set_simple_column_names(deparse_namespace *dpns);
381 static bool has_dangerous_join_using(deparse_namespace *dpns, Node *jtnode);
382 static void set_using_names(deparse_namespace *dpns, Node *jtnode,
383 List *parentUsing);
384 static void set_relation_column_names(deparse_namespace *dpns,
385 RangeTblEntry *rte,
386 deparse_columns *colinfo);
387 static void set_join_column_names(deparse_namespace *dpns, RangeTblEntry *rte,
388 deparse_columns *colinfo);
389 static bool colname_is_unique(const char *colname, deparse_namespace *dpns,
390 deparse_columns *colinfo);
391 static char *make_colname_unique(char *colname, deparse_namespace *dpns,
392 deparse_columns *colinfo);
393 static void expand_colnames_array_to(deparse_columns *colinfo, int n);
394 static void build_colinfo_names_hash(deparse_columns *colinfo);
395 static void add_to_names_hash(deparse_columns *colinfo, const char *name);
396 static void destroy_colinfo_names_hash(deparse_columns *colinfo);
397 static void identify_join_columns(JoinExpr *j, RangeTblEntry *jrte,
398 deparse_columns *colinfo);
399 static char *get_rtable_name(int rtindex, deparse_context *context);
400 static void set_deparse_plan(deparse_namespace *dpns, Plan *plan);
401 static Plan *find_recursive_union(deparse_namespace *dpns,
402 WorkTableScan *wtscan);
403 static void push_child_plan(deparse_namespace *dpns, Plan *plan,
404 deparse_namespace *save_dpns);
405 static void pop_child_plan(deparse_namespace *dpns,
406 deparse_namespace *save_dpns);
407 static void push_ancestor_plan(deparse_namespace *dpns, ListCell *ancestor_cell,
408 deparse_namespace *save_dpns);
409 static void pop_ancestor_plan(deparse_namespace *dpns,
410 deparse_namespace *save_dpns);
411 static void make_ruledef(StringInfo buf, HeapTuple ruletup, TupleDesc rulettc,
412 int prettyFlags);
413 static void make_viewdef(StringInfo buf, HeapTuple ruletup, TupleDesc rulettc,
414 int prettyFlags, int wrapColumn);
415 static void get_query_def(Query *query, StringInfo buf, List *parentnamespace,
416 TupleDesc resultDesc, bool colNamesVisible,
417 int prettyFlags, int wrapColumn, int startIndent);
418 static void get_values_def(List *values_lists, deparse_context *context);
419 static void get_with_clause(Query *query, deparse_context *context);
420 static void get_select_query_def(Query *query, deparse_context *context);
421 static void get_insert_query_def(Query *query, deparse_context *context);
422 static void get_update_query_def(Query *query, deparse_context *context);
423 static void get_update_query_targetlist_def(Query *query, List *targetList,
424 deparse_context *context,
425 RangeTblEntry *rte);
426 static void get_delete_query_def(Query *query, deparse_context *context);
427 static void get_merge_query_def(Query *query, deparse_context *context);
428 static void get_utility_query_def(Query *query, deparse_context *context);
429 static void get_basic_select_query(Query *query, deparse_context *context);
430 static void get_target_list(List *targetList, deparse_context *context);
431 static void get_returning_clause(Query *query, deparse_context *context);
432 static void get_setop_query(Node *setOp, Query *query,
433 deparse_context *context);
434 static Node *get_rule_sortgroupclause(Index ref, List *tlist,
435 bool force_colno,
436 deparse_context *context);
437 static void get_rule_groupingset(GroupingSet *gset, List *targetlist,
438 bool omit_parens, deparse_context *context);
439 static void get_rule_orderby(List *orderList, List *targetList,
440 bool force_colno, deparse_context *context);
441 static void get_rule_windowclause(Query *query, deparse_context *context);
442 static void get_rule_windowspec(WindowClause *wc, List *targetList,
443 deparse_context *context);
444 static void get_window_frame_options(int frameOptions,
445 Node *startOffset, Node *endOffset,
446 deparse_context *context);
447 static char *get_variable(Var *var, int levelsup, bool istoplevel,
448 deparse_context *context);
449 static void get_special_variable(Node *node, deparse_context *context,
450 void *callback_arg);
451 static void resolve_special_varno(Node *node, deparse_context *context,
452 rsv_callback callback, void *callback_arg);
453 static Node *find_param_referent(Param *param, deparse_context *context,
454 deparse_namespace **dpns_p, ListCell **ancestor_cell_p);
455 static SubPlan *find_param_generator(Param *param, deparse_context *context,
456 int *column_p);
457 static SubPlan *find_param_generator_initplan(Param *param, Plan *plan,
458 int *column_p);
459 static void get_parameter(Param *param, deparse_context *context);
460 static const char *get_simple_binary_op_name(OpExpr *expr);
461 static bool isSimpleNode(Node *node, Node *parentNode, int prettyFlags);
462 static void appendContextKeyword(deparse_context *context, const char *str,
463 int indentBefore, int indentAfter, int indentPlus);
464 static void removeStringInfoSpaces(StringInfo str);
465 static void get_rule_expr(Node *node, deparse_context *context,
466 bool showimplicit);
467 static void get_rule_expr_toplevel(Node *node, deparse_context *context,
468 bool showimplicit);
469 static void get_rule_list_toplevel(List *lst, deparse_context *context,
470 bool showimplicit);
471 static void get_rule_expr_funccall(Node *node, deparse_context *context,
472 bool showimplicit);
473 static bool looks_like_function(Node *node);
474 static void get_oper_expr(OpExpr *expr, deparse_context *context);
475 static void get_func_expr(FuncExpr *expr, deparse_context *context,
476 bool showimplicit);
477 static void get_agg_expr(Aggref *aggref, deparse_context *context,
478 Aggref *original_aggref);
479 static void get_agg_expr_helper(Aggref *aggref, deparse_context *context,
480 Aggref *original_aggref, const char *funcname,
481 const char *options, bool is_json_objectagg);
482 static void get_agg_combine_expr(Node *node, deparse_context *context,
483 void *callback_arg);
484 static void get_windowfunc_expr(WindowFunc *wfunc, deparse_context *context);
485 static void get_windowfunc_expr_helper(WindowFunc *wfunc, deparse_context *context,
486 const char *funcname, const char *options,
487 bool is_json_objectagg);
488 static bool get_func_sql_syntax(FuncExpr *expr, deparse_context *context);
489 static void get_coercion_expr(Node *arg, deparse_context *context,
490 Oid resulttype, int32 resulttypmod,
491 Node *parentNode);
492 static void get_const_expr(Const *constval, deparse_context *context,
493 int showtype);
494 static void get_const_collation(Const *constval, deparse_context *context);
495 static void get_json_format(JsonFormat *format, StringInfo buf);
496 static void get_json_returning(JsonReturning *returning, StringInfo buf,
497 bool json_format_by_default);
498 static void get_json_constructor(JsonConstructorExpr *ctor,
499 deparse_context *context, bool showimplicit);
500 static void get_json_constructor_options(JsonConstructorExpr *ctor,
501 StringInfo buf);
502 static void get_json_agg_constructor(JsonConstructorExpr *ctor,
503 deparse_context *context,
504 const char *funcname,
505 bool is_json_objectagg);
506 static void get_json_agg_constructor_expr(Node *node, deparse_context *context,
507 void *callback_arg);
508 static void simple_quote_literal(StringInfo buf, const char *val);
509 static void get_sublink_expr(SubLink *sublink, deparse_context *context);
510 static void get_tablefunc(TableFunc *tf, deparse_context *context,
511 bool showimplicit);
512 static void get_from_clause(Query *query, const char *prefix,
513 deparse_context *context);
514 static void get_from_clause_item(Node *jtnode, Query *query,
515 deparse_context *context);
516 static void get_rte_alias(RangeTblEntry *rte, int varno, bool use_as,
517 deparse_context *context);
518 static void get_column_alias_list(deparse_columns *colinfo,
519 deparse_context *context);
520 static void get_from_clause_coldeflist(RangeTblFunction *rtfunc,
521 deparse_columns *colinfo,
522 deparse_context *context);
523 static void get_tablesample_def(TableSampleClause *tablesample,
524 deparse_context *context);
525 static void get_opclass_name(Oid opclass, Oid actual_datatype,
526 StringInfo buf);
527 static Node *processIndirection(Node *node, deparse_context *context);
528 static void printSubscripts(SubscriptingRef *sbsref, deparse_context *context);
529 static char *get_relation_name(Oid relid);
530 static char *generate_relation_name(Oid relid, List *namespaces);
531 static char *generate_qualified_relation_name(Oid relid);
532 static char *generate_function_name(Oid funcid, int nargs,
533 List *argnames, Oid *argtypes,
534 bool has_variadic, bool *use_variadic_p,
535 bool inGroupBy);
536 static char *generate_operator_name(Oid operid, Oid arg1, Oid arg2);
537 static void add_cast_to(StringInfo buf, Oid typid);
538 static char *generate_qualified_type_name(Oid typid);
539 static text *string_to_text(char *str);
540 static char *flatten_reloptions(Oid relid);
541 static void get_reloptions(StringInfo buf, Datum reloptions);
542 static void get_json_path_spec(Node *path_spec, deparse_context *context,
543 bool showimplicit);
544 static void get_json_table_columns(TableFunc *tf, JsonTablePathScan *scan,
545 deparse_context *context,
546 bool showimplicit);
547 static void get_json_table_nested_columns(TableFunc *tf, JsonTablePlan *plan,
548 deparse_context *context,
549 bool showimplicit,
550 bool needcomma);
551
552 #define only_marker(rte) ((rte)->inh ? "" : "ONLY ")
553
554
555 /* ----------
556 * pg_get_ruledef - Do it all and return a text
557 * that could be used as a statement
558 * to recreate the rule
559 * ----------
560 */
561 Datum
562 pg_get_ruledef(PG_FUNCTION_ARGS)
563 {
564 Oid ruleoid = PG_GETARG_OID(0);
565 int prettyFlags;
566 char *res;
567
568 prettyFlags = PRETTYFLAG_INDENT;
569
570 res = pg_get_ruledef_worker(ruleoid, prettyFlags);
571
572 if (res == NULL)
573 PG_RETURN_NULL();
574
575 PG_RETURN_TEXT_P(string_to_text(res));
576 }
577
578
579 Datum
580 pg_get_ruledef_ext(PG_FUNCTION_ARGS)
581 {
582 Oid ruleoid = PG_GETARG_OID(0);
583 bool pretty = PG_GETARG_BOOL(1);
584 int prettyFlags;
585 char *res;
586
587 prettyFlags = GET_PRETTY_FLAGS(pretty);
588
589 res = pg_get_ruledef_worker(ruleoid, prettyFlags);
590
591 if (res == NULL)
592 PG_RETURN_NULL();
593
594 PG_RETURN_TEXT_P(string_to_text(res));
595 }
596
597
598 static char *
599 pg_get_ruledef_worker(Oid ruleoid, int prettyFlags)
600 {
601 Datum args[1];
602 char nulls[1];
603 int spirc;
604 HeapTuple ruletup;
605 TupleDesc rulettc;
606 StringInfoData buf;
607
608 /*
609 * Do this first so that string is alloc'd in outer context not SPI's.
610 */
611 initStringInfo(&buf);
612
613 /*
614 * Connect to SPI manager
615 */
616 SPI_connect();
617
618 /*
619 * On the first call prepare the plan to lookup pg_rewrite. We read
620 * pg_rewrite over the SPI manager instead of using the syscache to be
621 * checked for read access on pg_rewrite.
622 */
623 if (plan_getrulebyoid == NULL)
624 {
625 Oid argtypes[1];
626 SPIPlanPtr plan;
627
628 argtypes[0] = OIDOID;
629 plan = SPI_prepare(query_getrulebyoid, 1, argtypes);
630 if (plan == NULL)
631 elog(ERROR, "SPI_prepare failed for \"%s\"", query_getrulebyoid);
632 SPI_keepplan(plan);
633 plan_getrulebyoid = plan;
634 }
635
636 /*
637 * Get the pg_rewrite tuple for this rule
638 */
639 args[0] = ObjectIdGetDatum(ruleoid);
640 nulls[0] = ' ';
641 spirc = SPI_execute_plan(plan_getrulebyoid, args, nulls, true, 0);
642 if (spirc != SPI_OK_SELECT)
643 elog(ERROR, "failed to get pg_rewrite tuple for rule %u", ruleoid);
644 if (SPI_processed != 1)
645 {
646 /*
647 * There is no tuple data available here, just keep the output buffer
648 * empty.
649 */
650 }
651 else
652 {
653 /*
654 * Get the rule's definition and put it into executor's memory
655 */
656 ruletup = SPI_tuptable->vals[0];
657 rulettc = SPI_tuptable->tupdesc;
658 make_ruledef(&buf, ruletup, rulettc, prettyFlags);
659 }
660
661 /*
662 * Disconnect from SPI manager
663 */
664 if (SPI_finish() != SPI_OK_FINISH)
665 elog(ERROR, "SPI_finish failed");
666
667 if (buf.len == 0)
668 return NULL;
669
670 return buf.data;
671 }
672
673
674 /* ----------
675 * pg_get_viewdef - Mainly the same thing, but we
676 * only return the SELECT part of a view
677 * ----------
678 */
679 Datum
680 pg_get_viewdef(PG_FUNCTION_ARGS)
681 {
682 /* By OID */
683 Oid viewoid = PG_GETARG_OID(0);
684 int prettyFlags;
685 char *res;
686
687 prettyFlags = PRETTYFLAG_INDENT;
688
689 res = pg_get_viewdef_worker(viewoid, prettyFlags, WRAP_COLUMN_DEFAULT);
690
691 if (res == NULL)
692 PG_RETURN_NULL();
693
694 PG_RETURN_TEXT_P(string_to_text(res));
695 }
696
697
698 Datum
699 pg_get_viewdef_ext(PG_FUNCTION_ARGS)
700 {
701 /* By OID */
702 Oid viewoid = PG_GETARG_OID(0);
703 bool pretty = PG_GETARG_BOOL(1);
704 int prettyFlags;
705 char *res;
706
707 prettyFlags = GET_PRETTY_FLAGS(pretty);
708
709 res = pg_get_viewdef_worker(viewoid, prettyFlags, WRAP_COLUMN_DEFAULT);
710
711 if (res == NULL)
712 PG_RETURN_NULL();
713
714 PG_RETURN_TEXT_P(string_to_text(res));
715 }
716
717 Datum
718 pg_get_viewdef_wrap(PG_FUNCTION_ARGS)
719 {
720 /* By OID */
721 Oid viewoid = PG_GETARG_OID(0);
722 int wrap = PG_GETARG_INT32(1);
723 int prettyFlags;
724 char *res;
725
726 /* calling this implies we want pretty printing */
727 prettyFlags = GET_PRETTY_FLAGS(true);
728
729 res = pg_get_viewdef_worker(viewoid, prettyFlags, wrap);
730
731 if (res == NULL)
732 PG_RETURN_NULL();
733
734 PG_RETURN_TEXT_P(string_to_text(res));
735 }
736
737 Datum
738 pg_get_viewdef_name(PG_FUNCTION_ARGS)
739 {
740 /* By qualified name */
741 text *viewname = PG_GETARG_TEXT_PP(0);
742 int prettyFlags;
743 RangeVar *viewrel;
744 Oid viewoid;
745 char *res;
746
747 prettyFlags = PRETTYFLAG_INDENT;
748
749 /* Look up view name. Can't lock it - we might not have privileges. */
750 viewrel = makeRangeVarFromNameList(textToQualifiedNameList(viewname));
751 viewoid = RangeVarGetRelid(viewrel, NoLock, false);
752
753 res = pg_get_viewdef_worker(viewoid, prettyFlags, WRAP_COLUMN_DEFAULT);
754
755 if (res == NULL)
756 PG_RETURN_NULL();
757
758 PG_RETURN_TEXT_P(string_to_text(res));
759 }
760
761
762 Datum
763 pg_get_viewdef_name_ext(PG_FUNCTION_ARGS)
764 {
765 /* By qualified name */
766 text *viewname = PG_GETARG_TEXT_PP(0);
767 bool pretty = PG_GETARG_BOOL(1);
768 int prettyFlags;
769 RangeVar *viewrel;
770 Oid viewoid;
771 char *res;
772
773 prettyFlags = GET_PRETTY_FLAGS(pretty);
774
775 /* Look up view name. Can't lock it - we might not have privileges. */
776 viewrel = makeRangeVarFromNameList(textToQualifiedNameList(viewname));
777 viewoid = RangeVarGetRelid(viewrel, NoLock, false);
778
779 res = pg_get_viewdef_worker(viewoid, prettyFlags, WRAP_COLUMN_DEFAULT);
780
781 if (res == NULL)
782 PG_RETURN_NULL();
783
784 PG_RETURN_TEXT_P(string_to_text(res));
785 }
786
787 /*
788 * Common code for by-OID and by-name variants of pg_get_viewdef
789 */
790 static char *
791 pg_get_viewdef_worker(Oid viewoid, int prettyFlags, int wrapColumn)
792 {
793 Datum args[2];
794 char nulls[2];
795 int spirc;
796 HeapTuple ruletup;
797 TupleDesc rulettc;
798 StringInfoData buf;
799
800 /*
801 * Do this first so that string is alloc'd in outer context not SPI's.
802 */
803 initStringInfo(&buf);
804
805 /*
806 * Connect to SPI manager
807 */
808 SPI_connect();
809
810 /*
811 * On the first call prepare the plan to lookup pg_rewrite. We read
812 * pg_rewrite over the SPI manager instead of using the syscache to be
813 * checked for read access on pg_rewrite.
814 */
815 if (plan_getviewrule == NULL)
816 {
817 Oid argtypes[2];
818 SPIPlanPtr plan;
819
820 argtypes[0] = OIDOID;
821 argtypes[1] = NAMEOID;
822 plan = SPI_prepare(query_getviewrule, 2, argtypes);
823 if (plan == NULL)
824 elog(ERROR, "SPI_prepare failed for \"%s\"", query_getviewrule);
825 SPI_keepplan(plan);
826 plan_getviewrule = plan;
827 }
828
829 /*
830 * Get the pg_rewrite tuple for the view's SELECT rule
831 */
832 args[0] = ObjectIdGetDatum(viewoid);
833 args[1] = DirectFunctionCall1(namein, CStringGetDatum(ViewSelectRuleName));
834 nulls[0] = ' ';
835 nulls[1] = ' ';
836 spirc = SPI_execute_plan(plan_getviewrule, args, nulls, true, 0);
837 if (spirc != SPI_OK_SELECT)
838 elog(ERROR, "failed to get pg_rewrite tuple for view %u", viewoid);
839 if (SPI_processed != 1)
840 {
841 /*
842 * There is no tuple data available here, just keep the output buffer
843 * empty.
844 */
845 }
846 else
847 {
848 /*
849 * Get the rule's definition and put it into executor's memory
850 */
851 ruletup = SPI_tuptable->vals[0];
852 rulettc = SPI_tuptable->tupdesc;
853 make_viewdef(&buf, ruletup, rulettc, prettyFlags, wrapColumn);
854 }
855
856 /*
857 * Disconnect from SPI manager
858 */
859 if (SPI_finish() != SPI_OK_FINISH)
860 elog(ERROR, "SPI_finish failed");
861
862 if (buf.len == 0)
863 return NULL;
864
865 return buf.data;
866 }
867
868 /* ----------
869 * pg_get_triggerdef - Get the definition of a trigger
870 * ----------
871 */
872 Datum
873 pg_get_triggerdef(PG_FUNCTION_ARGS)
874 {
875 Oid trigid = PG_GETARG_OID(0);
876 char *res;
877
878 res = pg_get_triggerdef_worker(trigid, false);
879
880 if (res == NULL)
881 PG_RETURN_NULL();
882
883 PG_RETURN_TEXT_P(string_to_text(res));
884 }
885
886 Datum
887 pg_get_triggerdef_ext(PG_FUNCTION_ARGS)
888 {
889 Oid trigid = PG_GETARG_OID(0);
890 bool pretty = PG_GETARG_BOOL(1);
891 char *res;
892
893 res = pg_get_triggerdef_worker(trigid, pretty);
894
895 if (res == NULL)
896 PG_RETURN_NULL();
897
898 PG_RETURN_TEXT_P(string_to_text(res));
899 }
900
901 static char *
902 pg_get_triggerdef_worker(Oid trigid, bool pretty)
903 {
904 HeapTuple ht_trig;
905 Form_pg_trigger trigrec;
906 StringInfoData buf;
907 Relation tgrel;
908 ScanKeyData skey[1];
909 SysScanDesc tgscan;
910 int findx = 0;
911 char *tgname;
912 char *tgoldtable;
913 char *tgnewtable;
914 Datum value;
915 bool isnull;
916
917 /*
918 * Fetch the pg_trigger tuple by the Oid of the trigger
919 */
920 tgrel = table_open(TriggerRelationId, AccessShareLock);
921
922 ScanKeyInit(&skey[0],
923 Anum_pg_trigger_oid,
924 BTEqualStrategyNumber, F_OIDEQ,
925 ObjectIdGetDatum(trigid));
926
927 tgscan = systable_beginscan(tgrel, TriggerOidIndexId, true,
928 NULL, 1, skey);
929
930 ht_trig = systable_getnext(tgscan);
931
932 if (!HeapTupleIsValid(ht_trig))
933 {
934 systable_endscan(tgscan);
935 table_close(tgrel, AccessShareLock);
936 return NULL;
937 }
938
939 trigrec = (Form_pg_trigger) GETSTRUCT(ht_trig);
940
941 /*
942 * Start the trigger definition. Note that the trigger's name should never
943 * be schema-qualified, but the trigger rel's name may be.
944 */
945 initStringInfo(&buf);
946
947 tgname = NameStr(trigrec->tgname);
948 appendStringInfo(&buf, "CREATE %sTRIGGER %s ",
949 OidIsValid(trigrec->tgconstraint) ? "CONSTRAINT " : "",
950 quote_identifier(tgname));
951
952 if (TRIGGER_FOR_BEFORE(trigrec->tgtype))
953 appendStringInfoString(&buf, "BEFORE");
954 else if (TRIGGER_FOR_AFTER(trigrec->tgtype))
955 appendStringInfoString(&buf, "AFTER");
956 else if (TRIGGER_FOR_INSTEAD(trigrec->tgtype))
957 appendStringInfoString(&buf, "INSTEAD OF");
958 else
959 elog(ERROR, "unexpected tgtype value: %d", trigrec->tgtype);
960
961 if (TRIGGER_FOR_INSERT(trigrec->tgtype))
962 {
963 appendStringInfoString(&buf, " INSERT");
964 findx++;
965 }
966 if (TRIGGER_FOR_DELETE(trigrec->tgtype))
967 {
968 if (findx > 0)
969 appendStringInfoString(&buf, " OR DELETE");
970 else
971 appendStringInfoString(&buf, " DELETE");
972 findx++;
973 }
974 if (TRIGGER_FOR_UPDATE(trigrec->tgtype))
975 {
976 if (findx > 0)
977 appendStringInfoString(&buf, " OR UPDATE");
978 else
979 appendStringInfoString(&buf, " UPDATE");
980 findx++;
981 /* tgattr is first var-width field, so OK to access directly */
982 if (trigrec->tgattr.dim1 > 0)
983 {
984 int i;
985
986 appendStringInfoString(&buf, " OF ");
987 for (i = 0; i < trigrec->tgattr.dim1; i++)
988 {
989 char *attname;
990
991 if (i > 0)
992 appendStringInfoString(&buf, ", ");
993 attname = get_attname(trigrec->tgrelid,
994 trigrec->tgattr.values[i], false);
995 appendStringInfoString(&buf, quote_identifier(attname));
996 }
997 }
998 }
999 if (TRIGGER_FOR_TRUNCATE(trigrec->tgtype))
1000 {
1001 if (findx > 0)
1002 appendStringInfoString(&buf, " OR TRUNCATE");
1003 else
1004 appendStringInfoString(&buf, " TRUNCATE");
1005 findx++;
1006 }
1007
1008 /*
1009 * In non-pretty mode, always schema-qualify the target table name for
1010 * safety. In pretty mode, schema-qualify only if not visible.
1011 */
1012 appendStringInfo(&buf, " ON %s ",
1013 pretty ?
1014 generate_relation_name(trigrec->tgrelid, NIL) :
1015 generate_qualified_relation_name(trigrec->tgrelid));
1016
1017 if (OidIsValid(trigrec->tgconstraint))
1018 {
1019 if (OidIsValid(trigrec->tgconstrrelid))
1020 appendStringInfo(&buf, "FROM %s ",
1021 generate_relation_name(trigrec->tgconstrrelid, NIL));
1022 if (!trigrec->tgdeferrable)
1023 appendStringInfoString(&buf, "NOT ");
1024 appendStringInfoString(&buf, "DEFERRABLE INITIALLY ");
1025 if (trigrec->tginitdeferred)
1026 appendStringInfoString(&buf, "DEFERRED ");
1027 else
1028 appendStringInfoString(&buf, "IMMEDIATE ");
1029 }
1030
1031 value = fastgetattr(ht_trig, Anum_pg_trigger_tgoldtable,
1032 tgrel->rd_att, &isnull);
1033 if (!isnull)
1034 tgoldtable = NameStr(*DatumGetName(value));
1035 else
1036 tgoldtable = NULL;
1037 value = fastgetattr(ht_trig, Anum_pg_trigger_tgnewtable,
1038 tgrel->rd_att, &isnull);
1039 if (!isnull)
1040 tgnewtable = NameStr(*DatumGetName(value));
1041 else
1042 tgnewtable = NULL;
1043 if (tgoldtable != NULL || tgnewtable != NULL)
1044 {
1045 appendStringInfoString(&buf, "REFERENCING ");
1046 if (tgoldtable != NULL)
1047 appendStringInfo(&buf, "OLD TABLE AS %s ",
1048 quote_identifier(tgoldtable));
1049 if (tgnewtable != NULL)
1050 appendStringInfo(&buf, "NEW TABLE AS %s ",
1051 quote_identifier(tgnewtable));
1052 }
1053
1054 if (TRIGGER_FOR_ROW(trigrec->tgtype))
1055 appendStringInfoString(&buf, "FOR EACH ROW ");
1056 else
1057 appendStringInfoString(&buf, "FOR EACH STATEMENT ");
1058
1059 /* If the trigger has a WHEN qualification, add that */
1060 value = fastgetattr(ht_trig, Anum_pg_trigger_tgqual,
1061 tgrel->rd_att, &isnull);
1062 if (!isnull)
1063 {
1064 Node *qual;
1065 char relkind;
1066 deparse_context context;
1067 deparse_namespace dpns;
1068 RangeTblEntry *oldrte;
1069 RangeTblEntry *newrte;
1070
1071 appendStringInfoString(&buf, "WHEN (");
1072
1073 qual = stringToNode(TextDatumGetCString(value));
1074
1075 relkind = get_rel_relkind(trigrec->tgrelid);
1076
1077 /* Build minimal OLD and NEW RTEs for the rel */
1078 oldrte = makeNode(RangeTblEntry);
1079 oldrte->rtekind = RTE_RELATION;
1080 oldrte->relid = trigrec->tgrelid;
1081 oldrte->relkind = relkind;
1082 oldrte->rellockmode = AccessShareLock;
1083 oldrte->alias = makeAlias("old", NIL);
1084 oldrte->eref = oldrte->alias;
1085 oldrte->lateral = false;
1086 oldrte->inh = false;
1087 oldrte->inFromCl = true;
1088
1089 newrte = makeNode(RangeTblEntry);
1090 newrte->rtekind = RTE_RELATION;
1091 newrte->relid = trigrec->tgrelid;
1092 newrte->relkind = relkind;
1093 newrte->rellockmode = AccessShareLock;
1094 newrte->alias = makeAlias("new", NIL);
1095 newrte->eref = newrte->alias;
1096 newrte->lateral = false;
1097 newrte->inh = false;
1098 newrte->inFromCl = true;
1099
1100 /* Build two-element rtable */
1101 memset(&dpns, 0, sizeof(dpns));
1102 dpns.rtable = list_make2(oldrte, newrte);
1103 dpns.subplans = NIL;
1104 dpns.ctes = NIL;
1105 dpns.appendrels = NULL;
1106 set_rtable_names(&dpns, NIL, NULL);
1107 set_simple_column_names(&dpns);
1108
1109 /* Set up context with one-deep namespace stack */
1110 context.buf = &buf;
1111 context.namespaces = list_make1(&dpns);
1112 context.resultDesc = NULL;
1113 context.targetList = NIL;
1114 context.windowClause = NIL;
1115 context.varprefix = true;
1116 context.prettyFlags = GET_PRETTY_FLAGS(pretty);
1117 context.wrapColumn = WRAP_COLUMN_DEFAULT;
1118 context.indentLevel = PRETTYINDENT_STD;
1119 context.colNamesVisible = true;
1120 context.inGroupBy = false;
1121 context.varInOrderBy = false;
1122 context.appendparents = NULL;
1123
1124 get_rule_expr(qual, &context, false);
1125
1126 appendStringInfoString(&buf, ") ");
1127 }
1128
1129 appendStringInfo(&buf, "EXECUTE FUNCTION %s(",
1130 generate_function_name(trigrec->tgfoid, 0,
1131 NIL, NULL,
1132 false, NULL, false));
1133
1134 if (trigrec->tgnargs > 0)
1135 {
1136 char *p;
1137 int i;
1138
1139 value = fastgetattr(ht_trig, Anum_pg_trigger_tgargs,
1140 tgrel->rd_att, &isnull);
1141 if (isnull)
1142 elog(ERROR, "tgargs is null for trigger %u", trigid);
1143 p = (char *) VARDATA_ANY(DatumGetByteaPP(value));
1144 for (i = 0; i < trigrec->tgnargs; i++)
1145 {
1146 if (i > 0)
1147 appendStringInfoString(&buf, ", ");
1148 simple_quote_literal(&buf, p);
1149 /* advance p to next string embedded in tgargs */
1150 while (*p)
1151 p++;
1152 p++;
1153 }
1154 }
1155
1156 /* We deliberately do not put semi-colon at end */
1157 appendStringInfoChar(&buf, ')');
1158
1159 /* Clean up */
1160 systable_endscan(tgscan);
1161
1162 table_close(tgrel, AccessShareLock);
1163
1164 return buf.data;
1165 }
1166
1167 /* ----------
1168 * pg_get_indexdef - Get the definition of an index
1169 *
1170 * In the extended version, there is a colno argument as well as pretty bool.
1171 * if colno == 0, we want a complete index definition.
1172 * if colno > 0, we only want the Nth index key's variable or expression.
1173 *
1174 * Note that the SQL-function versions of this omit any info about the
1175 * index tablespace; this is intentional because pg_dump wants it that way.
1176 * However pg_get_indexdef_string() includes the index tablespace.
1177 * ----------
1178 */
1179 Datum
1180 pg_get_indexdef(PG_FUNCTION_ARGS)
1181 {
1182 Oid indexrelid = PG_GETARG_OID(0);
1183 int prettyFlags;
1184 char *res;
1185
1186 prettyFlags = PRETTYFLAG_INDENT;
1187
1188 res = pg_get_indexdef_worker(indexrelid, 0, NULL,
1189 false, false,
1190 false, false,
1191 prettyFlags, true);
1192
1193 if (res == NULL)
1194 PG_RETURN_NULL();
1195
1196 PG_RETURN_TEXT_P(string_to_text(res));
1197 }
1198
1199 Datum
1200 pg_get_indexdef_ext(PG_FUNCTION_ARGS)
1201 {
1202 Oid indexrelid = PG_GETARG_OID(0);
1203 int32 colno = PG_GETARG_INT32(1);
1204 bool pretty = PG_GETARG_BOOL(2);
1205 int prettyFlags;
1206 char *res;
1207
1208 prettyFlags = GET_PRETTY_FLAGS(pretty);
1209
1210 res = pg_get_indexdef_worker(indexrelid, colno, NULL,
1211 colno != 0, false,
1212 false, false,
1213 prettyFlags, true);
1214
1215 if (res == NULL)
1216 PG_RETURN_NULL();
1217
1218 PG_RETURN_TEXT_P(string_to_text(res));
1219 }
1220
1221 /*
1222 * Internal version for use by ALTER TABLE.
1223 * Includes a tablespace clause in the result.
1224 * Returns a palloc'd C string; no pretty-printing.
1225 */
1226 char *
1227 pg_get_indexdef_string(Oid indexrelid)
1228 {
1229 return pg_get_indexdef_worker(indexrelid, 0, NULL,
1230 false, false,
1231 true, true,
1232 0, false);
1233 }
1234
1235 /* Internal version that just reports the key-column definitions */
1236 char *
1237 pg_get_indexdef_columns(Oid indexrelid, bool pretty)
1238 {
1239 int prettyFlags;
1240
1241 prettyFlags = GET_PRETTY_FLAGS(pretty);
1242
1243 return pg_get_indexdef_worker(indexrelid, 0, NULL,
1244 true, true,
1245 false, false,
1246 prettyFlags, false);
1247 }
1248
1249 /* Internal version, extensible with flags to control its behavior */
1250 char *
1251 pg_get_indexdef_columns_extended(Oid indexrelid, bits16 flags)
1252 {
1253 bool pretty = ((flags & RULE_INDEXDEF_PRETTY) != 0);
1254 bool keys_only = ((flags & RULE_INDEXDEF_KEYS_ONLY) != 0);
1255 int prettyFlags;
1256
1257 prettyFlags = GET_PRETTY_FLAGS(pretty);
1258
1259 return pg_get_indexdef_worker(indexrelid, 0, NULL,
1260 true, keys_only,
1261 false, false,
1262 prettyFlags, false);
1263 }
1264
1265 /*
1266 * Internal workhorse to decompile an index definition.
1267 *
1268 * This is now used for exclusion constraints as well: if excludeOps is not
1269 * NULL then it points to an array of exclusion operator OIDs.
1270 */
1271 static char *
1272 pg_get_indexdef_worker(Oid indexrelid, int colno,
1273 const Oid *excludeOps,
1274 bool attrsOnly, bool keysOnly,
1275 bool showTblSpc, bool inherits,
1276 int prettyFlags, bool missing_ok)
1277 {
1278 /* might want a separate isConstraint parameter later */
1279 bool isConstraint = (excludeOps != NULL);
1280 HeapTuple ht_idx;
1281 HeapTuple ht_idxrel;
1282 HeapTuple ht_am;
1283 Form_pg_index idxrec;
1284 Form_pg_class idxrelrec;
1285 Form_pg_am amrec;
1286 IndexAmRoutine *amroutine;
1287 List *indexprs;
1288 ListCell *indexpr_item;
1289 List *context;
1290 Oid indrelid;
1291 int keyno;
1292 Datum indcollDatum;
1293 Datum indclassDatum;
1294 Datum indoptionDatum;
1295 oidvector *indcollation;
1296 oidvector *indclass;
1297 int2vector *indoption;
1298 StringInfoData buf;
1299 char *str;
1300 char *sep;
1301
1302 /*
1303 * Fetch the pg_index tuple by the Oid of the index
1304 */
1305 ht_idx = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexrelid));
1306 if (!HeapTupleIsValid(ht_idx))
1307 {
1308 if (missing_ok)
1309 return NULL;
1310 elog(ERROR, "cache lookup failed for index %u", indexrelid);
1311 }
1312 idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
1313
1314 indrelid = idxrec->indrelid;
1315 Assert(indexrelid == idxrec->indexrelid);
1316
1317 /* Must get indcollation, indclass, and indoption the hard way */
1318 indcollDatum = SysCacheGetAttrNotNull(INDEXRELID, ht_idx,
1319 Anum_pg_index_indcollation);
1320 indcollation = (oidvector *) DatumGetPointer(indcollDatum);
1321
1322 indclassDatum = SysCacheGetAttrNotNull(INDEXRELID, ht_idx,
1323 Anum_pg_index_indclass);
1324 indclass = (oidvector *) DatumGetPointer(indclassDatum);
1325
1326 indoptionDatum = SysCacheGetAttrNotNull(INDEXRELID, ht_idx,
1327 Anum_pg_index_indoption);
1328 indoption = (int2vector *) DatumGetPointer(indoptionDatum);
1329
1330 /*
1331 * Fetch the pg_class tuple of the index relation
1332 */
1333 ht_idxrel = SearchSysCache1(RELOID, ObjectIdGetDatum(indexrelid));
1334 if (!HeapTupleIsValid(ht_idxrel))
1335 elog(ERROR, "cache lookup failed for relation %u", indexrelid);
1336 idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
1337
1338 /*
1339 * Fetch the pg_am tuple of the index' access method
1340 */
1341 ht_am = SearchSysCache1(AMOID, ObjectIdGetDatum(idxrelrec->relam));
1342 if (!HeapTupleIsValid(ht_am))
1343 elog(ERROR, "cache lookup failed for access method %u",
1344 idxrelrec->relam);
1345 amrec = (Form_pg_am) GETSTRUCT(ht_am);
1346
1347 /* Fetch the index AM's API struct */
1348 amroutine = GetIndexAmRoutine(amrec->amhandler);
1349
1350 /*
1351 * Get the index expressions, if any. (NOTE: we do not use the relcache
1352 * versions of the expressions and predicate, because we want to display
1353 * non-const-folded expressions.)
1354 */
1355 if (!heap_attisnull(ht_idx, Anum_pg_index_indexprs, NULL))
1356 {
1357 Datum exprsDatum;
1358 char *exprsString;
1359
1360 exprsDatum = SysCacheGetAttrNotNull(INDEXRELID, ht_idx,
1361 Anum_pg_index_indexprs);
1362 exprsString = TextDatumGetCString(exprsDatum);
1363 indexprs = (List *) stringToNode(exprsString);
1364 pfree(exprsString);
1365 }
1366 else
1367 indexprs = NIL;
1368
1369 indexpr_item = list_head(indexprs);
1370
1371 context = deparse_context_for(get_relation_name(indrelid), indrelid);
1372
1373 /*
1374 * Start the index definition. Note that the index's name should never be
1375 * schema-qualified, but the indexed rel's name may be.
1376 */
1377 initStringInfo(&buf);
1378
1379 if (!attrsOnly)
1380 {
1381 if (!isConstraint)
1382 appendStringInfo(&buf, "CREATE %sINDEX %s ON %s%s USING %s (",
1383 idxrec->indisunique ? "UNIQUE " : "",
1384 quote_identifier(NameStr(idxrelrec->relname)),
1385 idxrelrec->relkind == RELKIND_PARTITIONED_INDEX
1386 && !inherits ? "ONLY " : "",
1387 (prettyFlags & PRETTYFLAG_SCHEMA) ?
1388 generate_relation_name(indrelid, NIL) :
1389 generate_qualified_relation_name(indrelid),
1390 quote_identifier(NameStr(amrec->amname)));
1391 else /* currently, must be EXCLUDE constraint */
1392 appendStringInfo(&buf, "EXCLUDE USING %s (",
1393 quote_identifier(NameStr(amrec->amname)));
1394 }
1395
1396 /*
1397 * Report the indexed attributes
1398 */
1399 sep = "";
1400 for (keyno = 0; keyno < idxrec->indnatts; keyno++)
1401 {
1402 AttrNumber attnum = idxrec->indkey.values[keyno];
1403 Oid keycoltype;
1404 Oid keycolcollation;
1405
1406 /*
1407 * Ignore non-key attributes if told to.
1408 */
1409 if (keysOnly && keyno >= idxrec->indnkeyatts)
1410 break;
1411
1412 /* Otherwise, print INCLUDE to divide key and non-key attrs. */
1413 if (!colno && keyno == idxrec->indnkeyatts)
1414 {
1415 appendStringInfoString(&buf, ") INCLUDE (");
1416 sep = "";
1417 }
1418
1419 if (!colno)
1420 appendStringInfoString(&buf, sep);
1421 sep = ", ";
1422
1423 if (attnum != 0)
1424 {
1425 /* Simple index column */
1426 char *attname;
1427 int32 keycoltypmod;
1428
1429 attname = get_attname(indrelid, attnum, false);
1430 if (!colno || colno == keyno + 1)
1431 appendStringInfoString(&buf, quote_identifier(attname));
1432 get_atttypetypmodcoll(indrelid, attnum,
1433 &keycoltype, &keycoltypmod,
1434 &keycolcollation);
1435 }
1436 else
1437 {
1438 /* expressional index */
1439 Node *indexkey;
1440
1441 if (indexpr_item == NULL)
1442 elog(ERROR, "too few entries in indexprs list");
1443 indexkey = (Node *) lfirst(indexpr_item);
1444 indexpr_item = lnext(indexprs, indexpr_item);
1445 /* Deparse */
1446 str = deparse_expression_pretty(indexkey, context, false, false,
1447 prettyFlags, 0);
1448 if (!colno || colno == keyno + 1)
1449 {
1450 /* Need parens if it's not a bare function call */
1451 if (looks_like_function(indexkey))
1452 appendStringInfoString(&buf, str);
1453 else
1454 appendStringInfo(&buf, "(%s)", str);
1455 }
1456 keycoltype = exprType(indexkey);
1457 keycolcollation = exprCollation(indexkey);
1458 }
1459
1460 /* Print additional decoration for (selected) key columns */
1461 if (!attrsOnly && keyno < idxrec->indnkeyatts &&
1462 (!colno || colno == keyno + 1))
1463 {
1464 int16 opt = indoption->values[keyno];
1465 Oid indcoll = indcollation->values[keyno];
1466 Datum attoptions = get_attoptions(indexrelid, keyno + 1);
1467 bool has_options = attoptions != (Datum) 0;
1468
1469 /* Add collation, if not default for column */
1470 if (OidIsValid(indcoll) && indcoll != keycolcollation)
1471 appendStringInfo(&buf, " COLLATE %s",
1472 generate_collation_name((indcoll)));
1473
1474 /* Add the operator class name, if not default */
1475 get_opclass_name(indclass->values[keyno],
1476 has_options ? InvalidOid : keycoltype, &buf);
1477
1478 if (has_options)
1479 {
1480 appendStringInfoString(&buf, " (");
1481 get_reloptions(&buf, attoptions);
1482 appendStringInfoChar(&buf, ')');
1483 }
1484
1485 /* Add options if relevant */
1486 if (amroutine->amcanorder)
1487 {
1488 /* if it supports sort ordering, report DESC and NULLS opts */
1489 if (opt & INDOPTION_DESC)
1490 {
1491 appendStringInfoString(&buf, " DESC");
1492 /* NULLS FIRST is the default in this case */
1493 if (!(opt & INDOPTION_NULLS_FIRST))
1494 appendStringInfoString(&buf, " NULLS LAST");
1495 }
1496 else
1497 {
1498 if (opt & INDOPTION_NULLS_FIRST)
1499 appendStringInfoString(&buf, " NULLS FIRST");
1500 }
1501 }
1502
1503 /* Add the exclusion operator if relevant */
1504 if (excludeOps != NULL)
1505 appendStringInfo(&buf, " WITH %s",
1506 generate_operator_name(excludeOps[keyno],
1507 keycoltype,
1508 keycoltype));
1509 }
1510 }
1511
1512 if (!attrsOnly)
1513 {
1514 appendStringInfoChar(&buf, ')');
1515
1516 if (idxrec->indnullsnotdistinct)
1517 appendStringInfoString(&buf, " NULLS NOT DISTINCT");
1518
1519 /*
1520 * If it has options, append "WITH (options)"
1521 */
1522 str = flatten_reloptions(indexrelid);
1523 if (str)
1524 {
1525 appendStringInfo(&buf, " WITH (%s)", str);
1526 pfree(str);
1527 }
1528
1529 /*
1530 * Print tablespace, but only if requested
1531 */
1532 if (showTblSpc)
1533 {
1534 Oid tblspc;
1535
1536 tblspc = get_rel_tablespace(indexrelid);
1537 if (OidIsValid(tblspc))
1538 {
1539 if (isConstraint)
1540 appendStringInfoString(&buf, " USING INDEX");
1541 appendStringInfo(&buf, " TABLESPACE %s",
1542 quote_identifier(get_tablespace_name(tblspc)));
1543 }
1544 }
1545
1546 /*
1547 * If it's a partial index, decompile and append the predicate
1548 */
1549 if (!heap_attisnull(ht_idx, Anum_pg_index_indpred, NULL))
1550 {
1551 Node *node;
1552 Datum predDatum;
1553 char *predString;
1554
1555 /* Convert text string to node tree */
1556 predDatum = SysCacheGetAttrNotNull(INDEXRELID, ht_idx,
1557 Anum_pg_index_indpred);
1558 predString = TextDatumGetCString(predDatum);
1559 node = (Node *) stringToNode(predString);
1560 pfree(predString);
1561
1562 /* Deparse */
1563 str = deparse_expression_pretty(node, context, false, false,
1564 prettyFlags, 0);
1565 if (isConstraint)
1566 appendStringInfo(&buf, " WHERE (%s)", str);
1567 else
1568 appendStringInfo(&buf, " WHERE %s", str);
1569 }
1570 }
1571
1572 /* Clean up */
1573 ReleaseSysCache(ht_idx);
1574 ReleaseSysCache(ht_idxrel);
1575 ReleaseSysCache(ht_am);
1576
1577 return buf.data;
1578 }
1579
1580 /* ----------
1581 * pg_get_querydef
1582 *
1583 * Public entry point to deparse one query parsetree.
1584 * The pretty flags are determined by GET_PRETTY_FLAGS(pretty).
1585 *
1586 * The result is a palloc'd C string.
1587 * ----------
1588 */
1589 char *
1590 pg_get_querydef(Query *query, bool pretty)
1591 {
1592 StringInfoData buf;
1593 int prettyFlags;
1594
1595 prettyFlags = GET_PRETTY_FLAGS(pretty);
1596
1597 initStringInfo(&buf);
1598
1599 get_query_def(query, &buf, NIL, NULL, true,
1600 prettyFlags, WRAP_COLUMN_DEFAULT, 0);
1601
1602 return buf.data;
1603 }
1604
1605 /*
1606 * pg_get_statisticsobjdef
1607 * Get the definition of an extended statistics object
1608 */
1609 Datum
1610 pg_get_statisticsobjdef(PG_FUNCTION_ARGS)
1611 {
1612 Oid statextid = PG_GETARG_OID(0);
1613 char *res;
1614
1615 res = pg_get_statisticsobj_worker(statextid, false, true);
1616
1617 if (res == NULL)
1618 PG_RETURN_NULL();
1619
1620 PG_RETURN_TEXT_P(string_to_text(res));
1621 }
1622
1623 /*
1624 * Internal version for use by ALTER TABLE.
1625 * Includes a tablespace clause in the result.
1626 * Returns a palloc'd C string; no pretty-printing.
1627 */
1628 char *
1629 pg_get_statisticsobjdef_string(Oid statextid)
1630 {
1631 return pg_get_statisticsobj_worker(statextid, false, false);
1632 }
1633
1634 /*
1635 * pg_get_statisticsobjdef_columns
1636 * Get columns and expressions for an extended statistics object
1637 */
1638 Datum
1639 pg_get_statisticsobjdef_columns(PG_FUNCTION_ARGS)
1640 {
1641 Oid statextid = PG_GETARG_OID(0);
1642 char *res;
1643
1644 res = pg_get_statisticsobj_worker(statextid, true, true);
1645
1646 if (res == NULL)
1647 PG_RETURN_NULL();
1648
1649 PG_RETURN_TEXT_P(string_to_text(res));
1650 }
1651
1652 /*
1653 * Internal workhorse to decompile an extended statistics object.
1654 */
1655 static char *
1656 pg_get_statisticsobj_worker(Oid statextid, bool columns_only, bool missing_ok)
1657 {
1658 Form_pg_statistic_ext statextrec;
1659 HeapTuple statexttup;
1660 StringInfoData buf;
1661 int colno;
1662 char *nsp;
1663 ArrayType *arr;
1664 char *enabled;
1665 Datum datum;
1666 bool ndistinct_enabled;
1667 bool dependencies_enabled;
1668 bool mcv_enabled;
1669 int i;
1670 List *context;
1671 ListCell *lc;
1672 List *exprs = NIL;
1673 bool has_exprs;
1674 int ncolumns;
1675
1676 statexttup = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(statextid));
1677
1678 if (!HeapTupleIsValid(statexttup))
1679 {
1680 if (missing_ok)
1681 return NULL;
1682 elog(ERROR, "cache lookup failed for statistics object %u", statextid);
1683 }
1684
1685 /* has the statistics expressions? */
1686 has_exprs = !heap_attisnull(statexttup, Anum_pg_statistic_ext_stxexprs, NULL);
1687
1688 statextrec = (Form_pg_statistic_ext) GETSTRUCT(statexttup);
1689
1690 /*
1691 * Get the statistics expressions, if any. (NOTE: we do not use the
1692 * relcache versions of the expressions, because we want to display
1693 * non-const-folded expressions.)
1694 */
1695 if (has_exprs)
1696 {
1697 Datum exprsDatum;
1698 char *exprsString;
1699
1700 exprsDatum = SysCacheGetAttrNotNull(STATEXTOID, statexttup,
1701 Anum_pg_statistic_ext_stxexprs);
1702 exprsString = TextDatumGetCString(exprsDatum);
1703 exprs = (List *) stringToNode(exprsString);
1704 pfree(exprsString);
1705 }
1706 else
1707 exprs = NIL;
1708
1709 /* count the number of columns (attributes and expressions) */
1710 ncolumns = statextrec->stxkeys.dim1 + list_length(exprs);
1711
1712 initStringInfo(&buf);
1713
1714 if (!columns_only)
1715 {
1716 nsp = get_namespace_name_or_temp(statextrec->stxnamespace);
1717 appendStringInfo(&buf, "CREATE STATISTICS %s",
1718 quote_qualified_identifier(nsp,
1719 NameStr(statextrec->stxname)));
1720
1721 /*
1722 * Decode the stxkind column so that we know which stats types to
1723 * print.
1724 */
1725 datum = SysCacheGetAttrNotNull(STATEXTOID, statexttup,
1726 Anum_pg_statistic_ext_stxkind);
1727 arr = DatumGetArrayTypeP(datum);
1728 if (ARR_NDIM(arr) != 1 ||
1729 ARR_HASNULL(arr) ||
1730 ARR_ELEMTYPE(arr) != CHAROID)
1731 elog(ERROR, "stxkind is not a 1-D char array");
1732 enabled = (char *) ARR_DATA_PTR(arr);
1733
1734 ndistinct_enabled = false;
1735 dependencies_enabled = false;
1736 mcv_enabled = false;
1737
1738 for (i = 0; i < ARR_DIMS(arr)[0]; i++)
1739 {
1740 if (enabled[i] == STATS_EXT_NDISTINCT)
1741 ndistinct_enabled = true;
1742 else if (enabled[i] == STATS_EXT_DEPENDENCIES)
1743 dependencies_enabled = true;
1744 else if (enabled[i] == STATS_EXT_MCV)
1745 mcv_enabled = true;
1746
1747 /* ignore STATS_EXT_EXPRESSIONS (it's built automatically) */
1748 }
1749
1750 /*
1751 * If any option is disabled, then we'll need to append the types
1752 * clause to show which options are enabled. We omit the types clause
1753 * on purpose when all options are enabled, so a pg_dump/pg_restore
1754 * will create all statistics types on a newer postgres version, if
1755 * the statistics had all options enabled on the original version.
1756 *
1757 * But if the statistics is defined on just a single column, it has to
1758 * be an expression statistics. In that case we don't need to specify
1759 * kinds.
1760 */
1761 if ((!ndistinct_enabled || !dependencies_enabled || !mcv_enabled) &&
1762 (ncolumns > 1))
1763 {
1764 bool gotone = false;
1765
1766 appendStringInfoString(&buf, " (");
1767
1768 if (ndistinct_enabled)
1769 {
1770 appendStringInfoString(&buf, "ndistinct");
1771 gotone = true;
1772 }
1773
1774 if (dependencies_enabled)
1775 {
1776 appendStringInfo(&buf, "%sdependencies", gotone ? ", " : "");
1777 gotone = true;
1778 }
1779
1780 if (mcv_enabled)
1781 appendStringInfo(&buf, "%smcv", gotone ? ", " : "");
1782
1783 appendStringInfoChar(&buf, ')');
1784 }
1785
1786 appendStringInfoString(&buf, " ON ");
1787 }
1788
1789 /* decode simple column references */
1790 for (colno = 0; colno < statextrec->stxkeys.dim1; colno++)
1791 {
1792 AttrNumber attnum = statextrec->stxkeys.values[colno];
1793 char *attname;
1794
1795 if (colno > 0)
1796 appendStringInfoString(&buf, ", ");
1797
1798 attname = get_attname(statextrec->stxrelid, attnum, false);
1799
1800 appendStringInfoString(&buf, quote_identifier(attname));
1801 }
1802
1803 context = deparse_context_for(get_relation_name(statextrec->stxrelid),
1804 statextrec->stxrelid);
1805
1806 foreach(lc, exprs)
1807 {
1808 Node *expr = (Node *) lfirst(lc);
1809 char *str;
1810 int prettyFlags = PRETTYFLAG_PAREN;
1811
1812 str = deparse_expression_pretty(expr, context, false, false,
1813 prettyFlags, 0);
1814
1815 if (colno > 0)
1816 appendStringInfoString(&buf, ", ");
1817
1818 /* Need parens if it's not a bare function call */
1819 if (looks_like_function(expr))
1820 appendStringInfoString(&buf, str);
1821 else
1822 appendStringInfo(&buf, "(%s)", str);
1823
1824 colno++;
1825 }
1826
1827 if (!columns_only)
1828 appendStringInfo(&buf, " FROM %s",
1829 generate_relation_name(statextrec->stxrelid, NIL));
1830
1831 ReleaseSysCache(statexttup);
1832
1833 return buf.data;
1834 }
1835
1836 /*
1837 * Generate text array of expressions for statistics object.
1838 */
1839 Datum
1840 pg_get_statisticsobjdef_expressions(PG_FUNCTION_ARGS)
1841 {
1842 Oid statextid = PG_GETARG_OID(0);
1843 Form_pg_statistic_ext statextrec;
1844 HeapTuple statexttup;
1845 Datum datum;
1846 List *context;
1847 ListCell *lc;
1848 List *exprs = NIL;
1849 bool has_exprs;
1850 char *tmp;
1851 ArrayBuildState *astate = NULL;
1852
1853 statexttup = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(statextid));
1854
1855 if (!HeapTupleIsValid(statexttup))
1856 PG_RETURN_NULL();
1857
1858 /* Does the stats object have expressions? */
1859 has_exprs = !heap_attisnull(statexttup, Anum_pg_statistic_ext_stxexprs, NULL);
1860
1861 /* no expressions? we're done */
1862 if (!has_exprs)
1863 {
1864 ReleaseSysCache(statexttup);
1865 PG_RETURN_NULL();
1866 }
1867
1868 statextrec = (Form_pg_statistic_ext) GETSTRUCT(statexttup);
1869
1870 /*
1871 * Get the statistics expressions, and deparse them into text values.
1872 */
1873 datum = SysCacheGetAttrNotNull(STATEXTOID, statexttup,
1874 Anum_pg_statistic_ext_stxexprs);
1875 tmp = TextDatumGetCString(datum);
1876 exprs = (List *) stringToNode(tmp);
1877 pfree(tmp);
1878
1879 context = deparse_context_for(get_relation_name(statextrec->stxrelid),
1880 statextrec->stxrelid);
1881
1882 foreach(lc, exprs)
1883 {
1884 Node *expr = (Node *) lfirst(lc);
1885 char *str;
1886 int prettyFlags = PRETTYFLAG_INDENT;
1887
1888 str = deparse_expression_pretty(expr, context, false, false,
1889 prettyFlags, 0);
1890
1891 astate = accumArrayResult(astate,
1892 PointerGetDatum(cstring_to_text(str)),
1893 false,
1894 TEXTOID,
1895 CurrentMemoryContext);
1896 }
1897
1898 ReleaseSysCache(statexttup);
1899
1900 PG_RETURN_DATUM(makeArrayResult(astate, CurrentMemoryContext));
1901 }
1902
1903 /*
1904 * pg_get_partkeydef
1905 *
1906 * Returns the partition key specification, ie, the following:
1907 *
1908 * { RANGE | LIST | HASH } (column opt_collation opt_opclass [, ...])
1909 */
1910 Datum
1911 pg_get_partkeydef(PG_FUNCTION_ARGS)
1912 {
1913 Oid relid = PG_GETARG_OID(0);
1914 char *res;
1915
1916 res = pg_get_partkeydef_worker(relid, PRETTYFLAG_INDENT, false, true);
1917
1918 if (res == NULL)
1919 PG_RETURN_NULL();
1920
1921 PG_RETURN_TEXT_P(string_to_text(res));
1922 }
1923
1924 /* Internal version that just reports the column definitions */
1925 char *
1926 pg_get_partkeydef_columns(Oid relid, bool pretty)
1927 {
1928 int prettyFlags;
1929
1930 prettyFlags = GET_PRETTY_FLAGS(pretty);
1931
1932 return pg_get_partkeydef_worker(relid, prettyFlags, true, false);
1933 }
1934
1935 /*
1936 * Internal workhorse to decompile a partition key definition.
1937 */
1938 static char *
1939 pg_get_partkeydef_worker(Oid relid, int prettyFlags,
1940 bool attrsOnly, bool missing_ok)
1941 {
1942 Form_pg_partitioned_table form;
1943 HeapTuple tuple;
1944 oidvector *partclass;
1945 oidvector *partcollation;
1946 List *partexprs;
1947 ListCell *partexpr_item;
1948 List *context;
1949 Datum datum;
1950 StringInfoData buf;
1951 int keyno;
1952 char *str;
1953 char *sep;
1954
1955 tuple = SearchSysCache1(PARTRELID, ObjectIdGetDatum(relid));
1956 if (!HeapTupleIsValid(tuple))
1957 {
1958 if (missing_ok)
1959 return NULL;
1960 elog(ERROR, "cache lookup failed for partition key of %u", relid);
1961 }
1962
1963 form = (Form_pg_partitioned_table) GETSTRUCT(tuple);
1964
1965 Assert(form->partrelid == relid);
1966
1967 /* Must get partclass and partcollation the hard way */
1968 datum = SysCacheGetAttrNotNull(PARTRELID, tuple,
1969 Anum_pg_partitioned_table_partclass);
1970 partclass = (oidvector *) DatumGetPointer(datum);
1971
1972 datum = SysCacheGetAttrNotNull(PARTRELID, tuple,
1973 Anum_pg_partitioned_table_partcollation);
1974 partcollation = (oidvector *) DatumGetPointer(datum);
1975
1976
1977 /*
1978 * Get the expressions, if any. (NOTE: we do not use the relcache
1979 * versions of the expressions, because we want to display
1980 * non-const-folded expressions.)
1981 */
1982 if (!heap_attisnull(tuple, Anum_pg_partitioned_table_partexprs, NULL))
1983 {
1984 Datum exprsDatum;
1985 char *exprsString;
1986
1987 exprsDatum = SysCacheGetAttrNotNull(PARTRELID, tuple,
1988 Anum_pg_partitioned_table_partexprs);
1989 exprsString = TextDatumGetCString(exprsDatum);
1990 partexprs = (List *) stringToNode(exprsString);
1991
1992 if (!IsA(partexprs, List))
1993 elog(ERROR, "unexpected node type found in partexprs: %d",
1994 (int) nodeTag(partexprs));
1995
1996 pfree(exprsString);
1997 }
1998 else
1999 partexprs = NIL;
2000
2001 partexpr_item = list_head(partexprs);
2002 context = deparse_context_for(get_relation_name(relid), relid);
2003
2004 initStringInfo(&buf);
2005
2006 switch (form->partstrat)
2007 {
2008 case PARTITION_STRATEGY_HASH:
2009 if (!attrsOnly)
2010 appendStringInfoString(&buf, "HASH");
2011 break;
2012 case PARTITION_STRATEGY_LIST:
2013 if (!attrsOnly)
2014 appendStringInfoString(&buf, "LIST");
2015 break;
2016 case PARTITION_STRATEGY_RANGE:
2017 if (!attrsOnly)
2018 appendStringInfoString(&buf, "RANGE");
2019 break;
2020 default:
2021 elog(ERROR, "unexpected partition strategy: %d",
2022 (int) form->partstrat);
2023 }
2024
2025 if (!attrsOnly)
2026 appendStringInfoString(&buf, " (");
2027 sep = "";
2028 for (keyno = 0; keyno < form->partnatts; keyno++)
2029 {
2030 AttrNumber attnum = form->partattrs.values[keyno];
2031 Oid keycoltype;
2032 Oid keycolcollation;
2033 Oid partcoll;
2034
2035 appendStringInfoString(&buf, sep);
2036 sep = ", ";
2037 if (attnum != 0)
2038 {
2039 /* Simple attribute reference */
2040 char *attname;
2041 int32 keycoltypmod;
2042
2043 attname = get_attname(relid, attnum, false);
2044 appendStringInfoString(&buf, quote_identifier(attname));
2045 get_atttypetypmodcoll(relid, attnum,
2046 &keycoltype, &keycoltypmod,
2047 &keycolcollation);
2048 }
2049 else
2050 {
2051 /* Expression */
2052 Node *partkey;
2053
2054 if (partexpr_item == NULL)
2055 elog(ERROR, "too few entries in partexprs list");
2056 partkey = (Node *) lfirst(partexpr_item);
2057 partexpr_item = lnext(partexprs, partexpr_item);
2058
2059 /* Deparse */
2060 str = deparse_expression_pretty(partkey, context, false, false,
2061 prettyFlags, 0);
2062 /* Need parens if it's not a bare function call */
2063 if (looks_like_function(partkey))
2064 appendStringInfoString(&buf, str);
2065 else
2066 appendStringInfo(&buf, "(%s)", str);
2067
2068 keycoltype = exprType(partkey);
2069 keycolcollation = exprCollation(partkey);
2070 }
2071
2072 /* Add collation, if not default for column */
2073 partcoll = partcollation->values[keyno];
2074 if (!attrsOnly && OidIsValid(partcoll) && partcoll != keycolcollation)
2075 appendStringInfo(&buf, " COLLATE %s",
2076 generate_collation_name((partcoll)));
2077
2078 /* Add the operator class name, if not default */
2079 if (!attrsOnly)
2080 get_opclass_name(partclass->values[keyno], keycoltype, &buf);
2081 }
2082
2083 if (!attrsOnly)
2084 appendStringInfoChar(&buf, ')');
2085
2086 /* Clean up */
2087 ReleaseSysCache(tuple);
2088
2089 return buf.data;
2090 }
2091
2092 /*
2093 * pg_get_partition_constraintdef
2094 *
2095 * Returns partition constraint expression as a string for the input relation
2096 */
2097 Datum
2098 pg_get_partition_constraintdef(PG_FUNCTION_ARGS)
2099 {
2100 Oid relationId = PG_GETARG_OID(0);
2101 Expr *constr_expr;
2102 int prettyFlags;
2103 List *context;
2104 char *consrc;
2105
2106 constr_expr = get_partition_qual_relid(relationId);
2107
2108 /* Quick exit if no partition constraint */
2109 if (constr_expr == NULL)
2110 PG_RETURN_NULL();
2111
2112 /*
2113 * Deparse and return the constraint expression.
2114 */
2115 prettyFlags = PRETTYFLAG_INDENT;
2116 context = deparse_context_for(get_relation_name(relationId), relationId);
2117 consrc = deparse_expression_pretty((Node *) constr_expr, context, false,
2118 false, prettyFlags, 0);
2119
2120 PG_RETURN_TEXT_P(string_to_text(consrc));
2121 }
2122
2123 /*
2124 * pg_get_partconstrdef_string
2125 *
2126 * Returns the partition constraint as a C-string for the input relation, with
2127 * the given alias. No pretty-printing.
2128 */
2129 char *
2130 pg_get_partconstrdef_string(Oid partitionId, char *aliasname)
2131 {
2132 Expr *constr_expr;
2133 List *context;
2134
2135 constr_expr = get_partition_qual_relid(partitionId);
2136 context = deparse_context_for(aliasname, partitionId);
2137
2138 return deparse_expression((Node *) constr_expr, context, true, false);
2139 }
2140
2141 /*
2142 * pg_get_constraintdef
2143 *
2144 * Returns the definition for the constraint, ie, everything that needs to
2145 * appear after "ALTER TABLE ... ADD CONSTRAINT <constraintname>".
2146 */
2147 Datum
2148 pg_get_constraintdef(PG_FUNCTION_ARGS)
2149 {
2150 Oid constraintId = PG_GETARG_OID(0);
2151 int prettyFlags;
2152 char *res;
2153
2154 prettyFlags = PRETTYFLAG_INDENT;
2155
2156 res = pg_get_constraintdef_worker(constraintId, false, prettyFlags, true);
2157
2158 if (res == NULL)
2159 PG_RETURN_NULL();
2160
2161 PG_RETURN_TEXT_P(string_to_text(res));
2162 }
2163
2164 Datum
2165 pg_get_constraintdef_ext(PG_FUNCTION_ARGS)
2166 {
2167 Oid constraintId = PG_GETARG_OID(0);
2168 bool pretty = PG_GETARG_BOOL(1);
2169 int prettyFlags;
2170 char *res;
2171
2172 prettyFlags = GET_PRETTY_FLAGS(pretty);
2173
2174 res = pg_get_constraintdef_worker(constraintId, false, prettyFlags, true);
2175
2176 if (res == NULL)
2177 PG_RETURN_NULL();
2178
2179 PG_RETURN_TEXT_P(string_to_text(res));
2180 }
2181
2182 /*
2183 * Internal version that returns a full ALTER TABLE ... ADD CONSTRAINT command
2184 */
2185 char *
2186 pg_get_constraintdef_command(Oid constraintId)
2187 {
2188 return pg_get_constraintdef_worker(constraintId, true, 0, false);
2189 }
2190
2191 /*
2192 * As of 9.4, we now use an MVCC snapshot for this.
2193 */
2194 static char *
2195 pg_get_constraintdef_worker(Oid constraintId, bool fullCommand,
2196 int prettyFlags, bool missing_ok)
2197 {
2198 HeapTuple tup;
2199 Form_pg_constraint conForm;
2200 StringInfoData buf;
2201 SysScanDesc scandesc;
2202 ScanKeyData scankey[1];
2203 Snapshot snapshot = RegisterSnapshot(GetTransactionSnapshot());
2204 Relation relation = table_open(ConstraintRelationId, AccessShareLock);
2205
2206 ScanKeyInit(&scankey[0],
2207 Anum_pg_constraint_oid,
2208 BTEqualStrategyNumber, F_OIDEQ,
2209 ObjectIdGetDatum(constraintId));
2210
2211 scandesc = systable_beginscan(relation,
2212 ConstraintOidIndexId,
2213 true,
2214 snapshot,
2215 1,
2216 scankey);
2217
2218 /*
2219 * We later use the tuple with SysCacheGetAttr() as if we had obtained it
2220 * via SearchSysCache, which works fine.
2221 */
2222 tup = systable_getnext(scandesc);
2223
2224 UnregisterSnapshot(snapshot);
2225
2226 if (!HeapTupleIsValid(tup))
2227 {
2228 if (missing_ok)
2229 {
2230 systable_endscan(scandesc);
2231 table_close(relation, AccessShareLock);
2232 return NULL;
2233 }
2234 elog(ERROR, "could not find tuple for constraint %u", constraintId);
2235 }
2236
2237 conForm = (Form_pg_constraint) GETSTRUCT(tup);
2238
2239 initStringInfo(&buf);
2240
2241 if (fullCommand)
2242 {
2243 if (OidIsValid(conForm->conrelid))
2244 {
2245 /*
2246 * Currently, callers want ALTER TABLE (without ONLY) for CHECK
2247 * constraints, and other types of constraints don't inherit
2248 * anyway so it doesn't matter whether we say ONLY or not. Someday
2249 * we might need to let callers specify whether to put ONLY in the
2250 * command.
2251 */
2252 appendStringInfo(&buf, "ALTER TABLE %s ADD CONSTRAINT %s ",
2253 generate_qualified_relation_name(conForm->conrelid),
2254 quote_identifier(NameStr(conForm->conname)));
2255 }
2256 else
2257 {
2258 /* Must be a domain constraint */
2259 Assert(OidIsValid(conForm->contypid));
2260 appendStringInfo(&buf, "ALTER DOMAIN %s ADD CONSTRAINT %s ",
2261 generate_qualified_type_name(conForm->contypid),
2262 quote_identifier(NameStr(conForm->conname)));
2263 }
2264 }
2265
2266 switch (conForm->contype)
2267 {
2268 case CONSTRAINT_FOREIGN:
2269 {
2270 Datum val;
2271 bool isnull;
2272 const char *string;
2273
2274 /* Start off the constraint definition */
2275 appendStringInfoString(&buf, "FOREIGN KEY (");
2276
2277 /* Fetch and build referencing-column list */
2278 val = SysCacheGetAttrNotNull(CONSTROID, tup,
2279 Anum_pg_constraint_conkey);
2280
2281 /* If it is a temporal foreign key then it uses PERIOD. */
2282 decompile_column_index_array(val, conForm->conrelid, conForm->conperiod, &buf);
2283
2284 /* add foreign relation name */
2285 appendStringInfo(&buf, ") REFERENCES %s(",
2286 generate_relation_name(conForm->confrelid,
2287 NIL));
2288
2289 /* Fetch and build referenced-column list */
2290 val = SysCacheGetAttrNotNull(CONSTROID, tup,
2291 Anum_pg_constraint_confkey);
2292
2293 decompile_column_index_array(val, conForm->confrelid, conForm->conperiod, &buf);
2294
2295 appendStringInfoChar(&buf, ')');
2296
2297 /* Add match type */
2298 switch (conForm->confmatchtype)
2299 {
2300 case FKCONSTR_MATCH_FULL:
2301 string = " MATCH FULL";
2302 break;
2303 case FKCONSTR_MATCH_PARTIAL:
2304 string = " MATCH PARTIAL";
2305 break;
2306 case FKCONSTR_MATCH_SIMPLE:
2307 string = "";
2308 break;
2309 default:
2310 elog(ERROR, "unrecognized confmatchtype: %d",
2311 conForm->confmatchtype);
2312 string = ""; /* keep compiler quiet */
2313 break;
2314 }
2315 appendStringInfoString(&buf, string);
2316
2317 /* Add ON UPDATE and ON DELETE clauses, if needed */
2318 switch (conForm->confupdtype)
2319 {
2320 case FKCONSTR_ACTION_NOACTION:
2321 string = NULL; /* suppress default */
2322 break;
2323 case FKCONSTR_ACTION_RESTRICT:
2324 string = "RESTRICT";
2325 break;
2326 case FKCONSTR_ACTION_CASCADE:
2327 string = "CASCADE";
2328 break;
2329 case FKCONSTR_ACTION_SETNULL:
2330 string = "SET NULL";
2331 break;
2332 case FKCONSTR_ACTION_SETDEFAULT:
2333 string = "SET DEFAULT";
2334 break;
2335 default:
2336 elog(ERROR, "unrecognized confupdtype: %d",
2337 conForm->confupdtype);
2338 string = NULL; /* keep compiler quiet */
2339 break;
2340 }
2341 if (string)
2342 appendStringInfo(&buf, " ON UPDATE %s", string);
2343
2344 switch (conForm->confdeltype)
2345 {
2346 case FKCONSTR_ACTION_NOACTION:
2347 string = NULL; /* suppress default */
2348 break;
2349 case FKCONSTR_ACTION_RESTRICT:
2350 string = "RESTRICT";
2351 break;
2352 case FKCONSTR_ACTION_CASCADE:
2353 string = "CASCADE";
2354 break;
2355 case FKCONSTR_ACTION_SETNULL:
2356 string = "SET NULL";
2357 break;
2358 case FKCONSTR_ACTION_SETDEFAULT:
2359 string = "SET DEFAULT";
2360 break;
2361 default:
2362 elog(ERROR, "unrecognized confdeltype: %d",
2363 conForm->confdeltype);
2364 string = NULL; /* keep compiler quiet */
2365 break;
2366 }
2367 if (string)
2368 appendStringInfo(&buf, " ON DELETE %s", string);
2369
2370 /*
2371 * Add columns specified to SET NULL or SET DEFAULT if
2372 * provided.
2373 */
2374 val = SysCacheGetAttr(CONSTROID, tup,
2375 Anum_pg_constraint_confdelsetcols, &isnull);
2376 if (!isnull)
2377 {
2378 appendStringInfoString(&buf, " (");
2379 decompile_column_index_array(val, conForm->conrelid, false, &buf);
2380 appendStringInfoChar(&buf, ')');
2381 }
2382
2383 break;
2384 }
2385 case CONSTRAINT_PRIMARY:
2386 case CONSTRAINT_UNIQUE:
2387 {
2388 Datum val;
2389 Oid indexId;
2390 int keyatts;
2391 HeapTuple indtup;
2392
2393 /* Start off the constraint definition */
2394 if (conForm->contype == CONSTRAINT_PRIMARY)
2395 appendStringInfoString(&buf, "PRIMARY KEY ");
2396 else
2397 appendStringInfoString(&buf, "UNIQUE ");
2398
2399 indexId = conForm->conindid;
2400
2401 indtup = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexId));
2402 if (!HeapTupleIsValid(indtup))
2403 elog(ERROR, "cache lookup failed for index %u", indexId);
2404 if (conForm->contype == CONSTRAINT_UNIQUE &&
2405 ((Form_pg_index) GETSTRUCT(indtup))->indnullsnotdistinct)
2406 appendStringInfoString(&buf, "NULLS NOT DISTINCT ");
2407
2408 appendStringInfoChar(&buf, '(');
2409
2410 /* Fetch and build target column list */
2411 val = SysCacheGetAttrNotNull(CONSTROID, tup,
2412 Anum_pg_constraint_conkey);
2413
2414 keyatts = decompile_column_index_array(val, conForm->conrelid, false, &buf);
2415 if (conForm->conperiod)
2416 appendStringInfoString(&buf, " WITHOUT OVERLAPS");
2417
2418 appendStringInfoChar(&buf, ')');
2419
2420 /* Build including column list (from pg_index.indkeys) */
2421 val = SysCacheGetAttrNotNull(INDEXRELID, indtup,
2422 Anum_pg_index_indnatts);
2423 if (DatumGetInt32(val) > keyatts)
2424 {
2425 Datum cols;
2426 Datum *keys;
2427 int nKeys;
2428 int j;
2429
2430 appendStringInfoString(&buf, " INCLUDE (");
2431
2432 cols = SysCacheGetAttrNotNull(INDEXRELID, indtup,
2433 Anum_pg_index_indkey);
2434
2435 deconstruct_array_builtin(DatumGetArrayTypeP(cols), INT2OID,
2436 &keys, NULL, &nKeys);
2437
2438 for (j = keyatts; j < nKeys; j++)
2439 {
2440 char *colName;
2441
2442 colName = get_attname(conForm->conrelid,
2443 DatumGetInt16(keys[j]), false);
2444 if (j > keyatts)
2445 appendStringInfoString(&buf, ", ");
2446 appendStringInfoString(&buf, quote_identifier(colName));
2447 }
2448
2449 appendStringInfoChar(&buf, ')');
2450 }
2451 ReleaseSysCache(indtup);
2452
2453 /* XXX why do we only print these bits if fullCommand? */
2454 if (fullCommand && OidIsValid(indexId))
2455 {
2456 char *options = flatten_reloptions(indexId);
2457 Oid tblspc;
2458
2459 if (options)
2460 {
2461 appendStringInfo(&buf, " WITH (%s)", options);
2462 pfree(options);
2463 }
2464
2465 /*
2466 * Print the tablespace, unless it's the database default.
2467 * This is to help ALTER TABLE usage of this facility,
2468 * which needs this behavior to recreate exact catalog
2469 * state.
2470 */
2471 tblspc = get_rel_tablespace(indexId);
2472 if (OidIsValid(tblspc))
2473 appendStringInfo(&buf, " USING INDEX TABLESPACE %s",
2474 quote_identifier(get_tablespace_name(tblspc)));
2475 }
2476
2477 break;
2478 }
2479 case CONSTRAINT_CHECK:
2480 {
2481 Datum val;
2482 char *conbin;
2483 char *consrc;
2484 Node *expr;
2485 List *context;
2486
2487 /* Fetch constraint expression in parsetree form */
2488 val = SysCacheGetAttrNotNull(CONSTROID, tup,
2489 Anum_pg_constraint_conbin);
2490
2491 conbin = TextDatumGetCString(val);
2492 expr = stringToNode(conbin);
2493
2494 /* Set up deparsing context for Var nodes in constraint */
2495 if (conForm->conrelid != InvalidOid)
2496 {
2497 /* relation constraint */
2498 context = deparse_context_for(get_relation_name(conForm->conrelid),
2499 conForm->conrelid);
2500 }
2501 else
2502 {
2503 /* domain constraint --- can't have Vars */
2504 context = NIL;
2505 }
2506
2507 consrc = deparse_expression_pretty(expr, context, false, false,
2508 prettyFlags, 0);
2509
2510 /*
2511 * Now emit the constraint definition, adding NO INHERIT if
2512 * necessary.
2513 *
2514 * There are cases where the constraint expression will be
2515 * fully parenthesized and we don't need the outer parens ...
2516 * but there are other cases where we do need 'em. Be
2517 * conservative for now.
2518 *
2519 * Note that simply checking for leading '(' and trailing ')'
2520 * would NOT be good enough, consider "(x > 0) AND (y > 0)".
2521 */
2522 appendStringInfo(&buf, "CHECK (%s)%s",
2523 consrc,
2524 conForm->connoinherit ? " NO INHERIT" : "");
2525 break;
2526 }
2527 case CONSTRAINT_NOTNULL:
2528 {
2529 if (conForm->conrelid)
2530 {
2531 AttrNumber attnum;
2532
2533 attnum = extractNotNullColumn(tup);
2534
2535 appendStringInfo(&buf, "NOT NULL %s",
2536 quote_identifier(get_attname(conForm->conrelid,
2537 attnum, false)));
2538 if (((Form_pg_constraint) GETSTRUCT(tup))->connoinherit)
2539 appendStringInfoString(&buf, " NO INHERIT");
2540 }
2541 else if (conForm->contypid)
2542 {
2543 /* conkey is null for domain not-null constraints */
2544 appendStringInfoString(&buf, "NOT NULL");
2545 }
2546 break;
2547 }
2548
2549 case CONSTRAINT_TRIGGER:
2550
2551 /*
2552 * There isn't an ALTER TABLE syntax for creating a user-defined
2553 * constraint trigger, but it seems better to print something than
2554 * throw an error; if we throw error then this function couldn't
2555 * safely be applied to all rows of pg_constraint.
2556 */
2557 appendStringInfoString(&buf, "TRIGGER");
2558 break;
2559 case CONSTRAINT_EXCLUSION:
2560 {
2561 Oid indexOid = conForm->conindid;
2562 Datum val;
2563 Datum *elems;
2564 int nElems;
2565 int i;
2566 Oid *operators;
2567
2568 /* Extract operator OIDs from the pg_constraint tuple */
2569 val = SysCacheGetAttrNotNull(CONSTROID, tup,
2570 Anum_pg_constraint_conexclop);
2571
2572 deconstruct_array_builtin(DatumGetArrayTypeP(val), OIDOID,
2573 &elems, NULL, &nElems);
2574
2575 operators = (Oid *) palloc(nElems * sizeof(Oid));
2576 for (i = 0; i < nElems; i++)
2577 operators[i] = DatumGetObjectId(elems[i]);
2578
2579 /* pg_get_indexdef_worker does the rest */
2580 /* suppress tablespace because pg_dump wants it that way */
2581 appendStringInfoString(&buf,
2582 pg_get_indexdef_worker(indexOid,
2583 0,
2584 operators,
2585 false,
2586 false,
2587 false,
2588 false,
2589 prettyFlags,
2590 false));
2591 break;
2592 }
2593 default:
2594 elog(ERROR, "invalid constraint type \"%c\"", conForm->contype);
2595 break;
2596 }
2597
2598 if (conForm->condeferrable)
2599 appendStringInfoString(&buf, " DEFERRABLE");
2600 if (conForm->condeferred)
2601 appendStringInfoString(&buf, " INITIALLY DEFERRED");
2602
2603 /* Validated status is irrelevant when the constraint is NOT ENFORCED. */
2604 if (!conForm->conenforced)
2605 appendStringInfoString(&buf, " NOT ENFORCED");
2606 else if (!conForm->convalidated)
2607 appendStringInfoString(&buf, " NOT VALID");
2608
2609 /* Cleanup */
2610 systable_endscan(scandesc);
2611 table_close(relation, AccessShareLock);
2612
2613 return buf.data;
2614 }
2615
2616
2617 /*
2618 * Convert an int16[] Datum into a comma-separated list of column names
2619 * for the indicated relation; append the list to buf. Returns the number
2620 * of keys.
2621 */
2622 static int
2623 decompile_column_index_array(Datum column_index_array, Oid relId,
2624 bool withPeriod, StringInfo buf)
2625 {
2626 Datum *keys;
2627 int nKeys;
2628 int j;
2629
2630 /* Extract data from array of int16 */
2631 deconstruct_array_builtin(DatumGetArrayTypeP(column_index_array), INT2OID,
2632 &keys, NULL, &nKeys);
2633
2634 for (j = 0; j < nKeys; j++)
2635 {
2636 char *colName;
2637
2638 colName = get_attname(relId, DatumGetInt16(keys[j]), false);
2639
2640 if (j == 0)
2641 appendStringInfoString(buf, quote_identifier(colName));
2642 else
2643 appendStringInfo(buf, ", %s%s",
2644 (withPeriod && j == nKeys - 1) ? "PERIOD " : "",
2645 quote_identifier(colName));
2646 }
2647
2648 return nKeys;
2649 }
2650
2651
2652 /* ----------
2653 * pg_get_expr - Decompile an expression tree
2654 *
2655 * Input: an expression tree in nodeToString form, and a relation OID
2656 *
2657 * Output: reverse-listed expression
2658 *
2659 * Currently, the expression can only refer to a single relation, namely
2660 * the one specified by the second parameter. This is sufficient for
2661 * partial indexes, column default expressions, etc. We also support
2662 * Var-free expressions, for which the OID can be InvalidOid.
2663 *
2664 * If the OID is nonzero but not actually valid, don't throw an error,
2665 * just return NULL. This is a bit questionable, but it's what we've
2666 * done historically, and it can help avoid unwanted failures when
2667 * examining catalog entries for just-deleted relations.
2668 *
2669 * We expect this function to work, or throw a reasonably clean error,
2670 * for any node tree that can appear in a catalog pg_node_tree column.
2671 * Query trees, such as those appearing in pg_rewrite.ev_action, are
2672 * not supported. Nor are expressions in more than one relation, which
2673 * can appear in places like pg_rewrite.ev_qual.
2674 * ----------
2675 */
2676 Datum
2677 pg_get_expr(PG_FUNCTION_ARGS)
2678 {
2679 text *expr = PG_GETARG_TEXT_PP(0);
2680 Oid relid = PG_GETARG_OID(1);
2681 text *result;
2682 int prettyFlags;
2683
2684 prettyFlags = PRETTYFLAG_INDENT;
2685
2686 result = pg_get_expr_worker(expr, relid, prettyFlags);
2687 if (result)
2688 PG_RETURN_TEXT_P(result);
2689 else
2690 PG_RETURN_NULL();
2691 }
2692
2693 Datum
2694 pg_get_expr_ext(PG_FUNCTION_ARGS)
2695 {
2696 text *expr = PG_GETARG_TEXT_PP(0);
2697 Oid relid = PG_GETARG_OID(1);
2698 bool pretty = PG_GETARG_BOOL(2);
2699 text *result;
2700 int prettyFlags;
2701
2702 prettyFlags = GET_PRETTY_FLAGS(pretty);
2703
2704 result = pg_get_expr_worker(expr, relid, prettyFlags);
2705 if (result)
2706 PG_RETURN_TEXT_P(result);
2707 else
2708 PG_RETURN_NULL();
2709 }
2710
2711 static text *
2712 pg_get_expr_worker(text *expr, Oid relid, int prettyFlags)
2713 {
2714 Node *node;
2715 Node *tst;
2716 Relids relids;
2717 List *context;
2718 char *exprstr;
2719 Relation rel = NULL;
2720 char *str;
2721
2722 /* Convert input pg_node_tree (really TEXT) object to C string */
2723 exprstr = text_to_cstring(expr);
2724
2725 /* Convert expression to node tree */
2726 node = (Node *) stringToNode(exprstr);
2727
2728 pfree(exprstr);
2729
2730 /*
2731 * Throw error if the input is a querytree rather than an expression tree.
2732 * While we could support queries here, there seems no very good reason
2733 * to. In most such catalog columns, we'll see a List of Query nodes, or
2734 * even nested Lists, so drill down to a non-List node before checking.
2735 */
2736 tst = node;
2737 while (tst && IsA(tst, List))
2738 tst = linitial((List *) tst);
2739 if (tst && IsA(tst, Query))
2740 ereport(ERROR,
2741 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2742 errmsg("input is a query, not an expression")));
2743
2744 /*
2745 * Throw error if the expression contains Vars we won't be able to
2746 * deparse.
2747 */
2748 relids = pull_varnos(NULL, node);
2749 if (OidIsValid(relid))
2750 {
2751 if (!bms_is_subset(relids, bms_make_singleton(1)))
2752 ereport(ERROR,
2753 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2754 errmsg("expression contains variables of more than one relation")));
2755 }
2756 else
2757 {
2758 if (!bms_is_empty(relids))
2759 ereport(ERROR,
2760 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2761 errmsg("expression contains variables")));
2762 }
2763
2764 /*
2765 * Prepare deparse context if needed. If we are deparsing with a relid,
2766 * we need to transiently open and lock the rel, to make sure it won't go
2767 * away underneath us. (set_relation_column_names would lock it anyway,
2768 * so this isn't really introducing any new behavior.)
2769 */
2770 if (OidIsValid(relid))
2771 {
2772 rel = try_relation_open(relid, AccessShareLock);
2773 if (rel == NULL)
2774 return NULL;
2775 context = deparse_context_for(RelationGetRelationName(rel), relid);
2776 }
2777 else
2778 context = NIL;
2779
2780 /* Deparse */
2781 str = deparse_expression_pretty(node, context, false, false,
2782 prettyFlags, 0);
2783
2784 if (rel != NULL)
2785 relation_close(rel, AccessShareLock);
2786
2787 return string_to_text(str);
2788 }
2789
2790
2791 /* ----------
2792 * pg_get_userbyid - Get a user name by roleid and
2793 * fallback to 'unknown (OID=n)'
2794 * ----------
2795 */
2796 Datum
2797 pg_get_userbyid(PG_FUNCTION_ARGS)
2798 {
2799 Oid roleid = PG_GETARG_OID(0);
2800 Name result;
2801 HeapTuple roletup;
2802 Form_pg_authid role_rec;
2803
2804 /*
2805 * Allocate space for the result
2806 */
2807 result = (Name) palloc(NAMEDATALEN);
2808 memset(NameStr(*result), 0, NAMEDATALEN);
2809
2810 /*
2811 * Get the pg_authid entry and print the result
2812 */
2813 roletup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
2814 if (HeapTupleIsValid(roletup))
2815 {
2816 role_rec = (Form_pg_authid) GETSTRUCT(roletup);
2817 *result = role_rec->rolname;
2818 ReleaseSysCache(roletup);
2819 }
2820 else
2821 sprintf(NameStr(*result), "unknown (OID=%u)", roleid);
2822
2823 PG_RETURN_NAME(result);
2824 }
2825
2826
2827 /*
2828 * pg_get_serial_sequence
2829 * Get the name of the sequence used by an identity or serial column,
2830 * formatted suitably for passing to setval, nextval or currval.
2831 * First parameter is not treated as double-quoted, second parameter
2832 * is --- see documentation for reason.
2833 */
2834 Datum
2835 pg_get_serial_sequence(PG_FUNCTION_ARGS)
2836 {
2837 text *tablename = PG_GETARG_TEXT_PP(0);
2838 text *columnname = PG_GETARG_TEXT_PP(1);
2839 RangeVar *tablerv;
2840 Oid tableOid;
2841 char *column;
2842 AttrNumber attnum;
2843 Oid sequenceId = InvalidOid;
2844 Relation depRel;
2845 ScanKeyData key[3];
2846 SysScanDesc scan;
2847 HeapTuple tup;
2848
2849 /* Look up table name. Can't lock it - we might not have privileges. */
2850 tablerv = makeRangeVarFromNameList(textToQualifiedNameList(tablename));
2851 tableOid = RangeVarGetRelid(tablerv, NoLock, false);
2852
2853 /* Get the number of the column */
2854 column = text_to_cstring(columnname);
2855
2856 attnum = get_attnum(tableOid, column);
2857 if (attnum == InvalidAttrNumber)
2858 ereport(ERROR,
2859 (errcode(ERRCODE_UNDEFINED_COLUMN),
2860 errmsg("column \"%s\" of relation \"%s\" does not exist",
2861 column, tablerv->relname)));
2862
2863 /* Search the dependency table for the dependent sequence */
2864 depRel = table_open(DependRelationId, AccessShareLock);
2865
2866 ScanKeyInit(&key[0],
2867 Anum_pg_depend_refclassid,
2868 BTEqualStrategyNumber, F_OIDEQ,
2869 ObjectIdGetDatum(RelationRelationId));
2870 ScanKeyInit(&key[1],
2871 Anum_pg_depend_refobjid,
2872 BTEqualStrategyNumber, F_OIDEQ,
2873 ObjectIdGetDatum(tableOid));
2874 ScanKeyInit(&key[2],
2875 Anum_pg_depend_refobjsubid,
2876 BTEqualStrategyNumber, F_INT4EQ,
2877 Int32GetDatum(attnum));
2878
2879 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
2880 NULL, 3, key);
2881
2882 while (HeapTupleIsValid(tup = systable_getnext(scan)))
2883 {
2884 Form_pg_depend deprec = (Form_pg_depend) GETSTRUCT(tup);
2885
2886 /*
2887 * Look for an auto dependency (serial column) or internal dependency
2888 * (identity column) of a sequence on a column. (We need the relkind
2889 * test because indexes can also have auto dependencies on columns.)
2890 */
2891 if (deprec->classid == RelationRelationId &&
2892 deprec->objsubid == 0 &&
2893 (deprec->deptype == DEPENDENCY_AUTO ||
2894 deprec->deptype == DEPENDENCY_INTERNAL) &&
2895 get_rel_relkind(deprec->objid) == RELKIND_SEQUENCE)
2896 {
2897 sequenceId = deprec->objid;
2898 break;
2899 }
2900 }
2901
2902 systable_endscan(scan);
2903 table_close(depRel, AccessShareLock);
2904
2905 if (OidIsValid(sequenceId))
2906 {
2907 char *result;
2908
2909 result = generate_qualified_relation_name(sequenceId);
2910
2911 PG_RETURN_TEXT_P(string_to_text(result));
2912 }
2913
2914 PG_RETURN_NULL();
2915 }
2916
2917
2918 /*
2919 * pg_get_functiondef
2920 * Returns the complete "CREATE OR REPLACE FUNCTION ..." statement for
2921 * the specified function.
2922 *
2923 * Note: if you change the output format of this function, be careful not
2924 * to break psql's rules (in \ef and \sf) for identifying the start of the
2925 * function body. To wit: the function body starts on a line that begins with
2926 * "AS ", "BEGIN ", or "RETURN ", and no preceding line will look like that.
2927 */
2928 Datum
2929 pg_get_functiondef(PG_FUNCTION_ARGS)
2930 {
2931 Oid funcid = PG_GETARG_OID(0);
2932 StringInfoData buf;
2933 StringInfoData dq;
2934 HeapTuple proctup;
2935 Form_pg_proc proc;
2936 bool isfunction;
2937 Datum tmp;
2938 bool isnull;
2939 const char *prosrc;
2940 const char *name;
2941 const char *nsp;
2942 float4 procost;
2943 int oldlen;
2944
2945 initStringInfo(&buf);
2946
2947 /* Look up the function */
2948 proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
2949 if (!HeapTupleIsValid(proctup))
2950 PG_RETURN_NULL();
2951
2952 proc = (Form_pg_proc) GETSTRUCT(proctup);
2953 name = NameStr(proc->proname);
2954
2955 if (proc->prokind == PROKIND_AGGREGATE)
2956 ereport(ERROR,
2957 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2958 errmsg("\"%s\" is an aggregate function", name)));
2959
2960 isfunction = (proc->prokind != PROKIND_PROCEDURE);
2961
2962 /*
2963 * We always qualify the function name, to ensure the right function gets
2964 * replaced.
2965 */
2966 nsp = get_namespace_name_or_temp(proc->pronamespace);
2967 appendStringInfo(&buf, "CREATE OR REPLACE %s %s(",
2968 isfunction ? "FUNCTION" : "PROCEDURE",
2969 quote_qualified_identifier(nsp, name));
2970 (void) print_function_arguments(&buf, proctup, false, true);
2971 appendStringInfoString(&buf, ")\n");
2972 if (isfunction)
2973 {
2974 appendStringInfoString(&buf, " RETURNS ");
2975 print_function_rettype(&buf, proctup);
2976 appendStringInfoChar(&buf, '\n');
2977 }
2978
2979 print_function_trftypes(&buf, proctup);
2980
2981 appendStringInfo(&buf, " LANGUAGE %s\n",
2982 quote_identifier(get_language_name(proc->prolang, false)));
2983
2984 /* Emit some miscellaneous options on one line */
2985 oldlen = buf.len;
2986
2987 if (proc->prokind == PROKIND_WINDOW)
2988 appendStringInfoString(&buf, " WINDOW");
2989 switch (proc->provolatile)
2990 {
2991 case PROVOLATILE_IMMUTABLE:
2992 appendStringInfoString(&buf, " IMMUTABLE");
2993 break;
2994 case PROVOLATILE_STABLE:
2995 appendStringInfoString(&buf, " STABLE");
2996 break;
2997 case PROVOLATILE_VOLATILE:
2998 break;
2999 }
3000
3001 switch (proc->proparallel)
3002 {
3003 case PROPARALLEL_SAFE:
3004 appendStringInfoString(&buf, " PARALLEL SAFE");
3005 break;
3006 case PROPARALLEL_RESTRICTED:
3007 appendStringInfoString(&buf, " PARALLEL RESTRICTED");
3008 break;
3009 case PROPARALLEL_UNSAFE:
3010 break;
3011 }
3012
3013 if (proc->proisstrict)
3014 appendStringInfoString(&buf, " STRICT");
3015 if (proc->prosecdef)
3016 appendStringInfoString(&buf, " SECURITY DEFINER");
3017 if (proc->proleakproof)
3018 appendStringInfoString(&buf, " LEAKPROOF");
3019
3020 /* This code for the default cost and rows should match functioncmds.c */
3021 if (proc->prolang == INTERNALlanguageId ||
3022 proc->prolang == ClanguageId)
3023 procost = 1;
3024 else
3025 procost = 100;
3026 if (proc->procost != procost)
3027 appendStringInfo(&buf, " COST %g", proc->procost);
3028
3029 if (proc->prorows > 0 && proc->prorows != 1000)
3030 appendStringInfo(&buf, " ROWS %g", proc->prorows);
3031
3032 if (proc->prosupport)
3033 {
3034 Oid argtypes[1];
3035
3036 /*
3037 * We should qualify the support function's name if it wouldn't be
3038 * resolved by lookup in the current search path.
3039 */
3040 argtypes[0] = INTERNALOID;
3041 appendStringInfo(&buf, " SUPPORT %s",
3042 generate_function_name(proc->prosupport, 1,
3043 NIL, argtypes,
3044 false, NULL, false));
3045 }
3046
3047 if (oldlen != buf.len)
3048 appendStringInfoChar(&buf, '\n');
3049
3050 /* Emit any proconfig options, one per line */
3051 tmp = SysCacheGetAttr(PROCOID, proctup, Anum_pg_proc_proconfig, &isnull);
3052 if (!isnull)
3053 {
3054 ArrayType *a = DatumGetArrayTypeP(tmp);
3055 int i;
3056
3057 Assert(ARR_ELEMTYPE(a) == TEXTOID);
3058 Assert(ARR_NDIM(a) == 1);
3059 Assert(ARR_LBOUND(a)[0] == 1);
3060
3061 for (i = 1; i <= ARR_DIMS(a)[0]; i++)
3062 {
3063 Datum d;
3064
3065 d = array_ref(a, 1, &i,
3066 -1 /* varlenarray */ ,
3067 -1 /* TEXT's typlen */ ,
3068 false /* TEXT's typbyval */ ,
3069 TYPALIGN_INT /* TEXT's typalign */ ,
3070 &isnull);
3071 if (!isnull)
3072 {
3073 char *configitem = TextDatumGetCString(d);
3074 char *pos;
3075
3076 pos = strchr(configitem, '=');
3077 if (pos == NULL)
3078 continue;
3079 *pos++ = '\0';
3080
3081 appendStringInfo(&buf, " SET %s TO ",
3082 quote_identifier(configitem));
3083
3084 /*
3085 * Variables that are marked GUC_LIST_QUOTE were already fully
3086 * quoted by flatten_set_variable_args() before they were put
3087 * into the proconfig array. However, because the quoting
3088 * rules used there aren't exactly like SQL's, we have to
3089 * break the list value apart and then quote the elements as
3090 * string literals. (The elements may be double-quoted as-is,
3091 * but we can't just feed them to the SQL parser; it would do
3092 * the wrong thing with elements that are zero-length or
3093 * longer than NAMEDATALEN.)
3094 *
3095 * Variables that are not so marked should just be emitted as
3096 * simple string literals. If the variable is not known to
3097 * guc.c, we'll do that; this makes it unsafe to use
3098 * GUC_LIST_QUOTE for extension variables.
3099 */
3100 if (GetConfigOptionFlags(configitem, true) & GUC_LIST_QUOTE)
3101 {
3102 List *namelist;
3103 ListCell *lc;
3104
3105 /* Parse string into list of identifiers */
3106 if (!SplitGUCList(pos, ',', &namelist))
3107 {
3108 /* this shouldn't fail really */
3109 elog(ERROR, "invalid list syntax in proconfig item");
3110 }
3111 foreach(lc, namelist)
3112 {
3113 char *curname = (char *) lfirst(lc);
3114
3115 simple_quote_literal(&buf, curname);
3116 if (lnext(namelist, lc))
3117 appendStringInfoString(&buf, ", ");
3118 }
3119 }
3120 else
3121 simple_quote_literal(&buf, pos);
3122 appendStringInfoChar(&buf, '\n');
3123 }
3124 }
3125 }
3126
3127 /* And finally the function definition ... */
3128 (void) SysCacheGetAttr(PROCOID, proctup, Anum_pg_proc_prosqlbody, &isnull);
3129 if (proc->prolang == SQLlanguageId && !isnull)
3130 {
3131 print_function_sqlbody(&buf, proctup);
3132 }
3133 else
3134 {
3135 appendStringInfoString(&buf, "AS ");
3136
3137 tmp = SysCacheGetAttr(PROCOID, proctup, Anum_pg_proc_probin, &isnull);
3138 if (!isnull)
3139 {
3140 simple_quote_literal(&buf, TextDatumGetCString(tmp));
3141 appendStringInfoString(&buf, ", "); /* assume prosrc isn't null */
3142 }
3143
3144 tmp = SysCacheGetAttrNotNull(PROCOID, proctup, Anum_pg_proc_prosrc);
3145 prosrc = TextDatumGetCString(tmp);
3146
3147 /*
3148 * We always use dollar quoting. Figure out a suitable delimiter.
3149 *
3150 * Since the user is likely to be editing the function body string, we
3151 * shouldn't use a short delimiter that he might easily create a
3152 * conflict with. Hence prefer "$function$"/"$procedure$", but extend
3153 * if needed.
3154 */
3155 initStringInfo(&dq);
3156 appendStringInfoChar(&dq, '$');
3157 appendStringInfoString(&dq, (isfunction ? "function" : "procedure"));
3158 while (strstr(prosrc, dq.data) != NULL)
3159 appendStringInfoChar(&dq, 'x');
3160 appendStringInfoChar(&dq, '$');
3161
3162 appendBinaryStringInfo(&buf, dq.data, dq.len);
3163 appendStringInfoString(&buf, prosrc);
3164 appendBinaryStringInfo(&buf, dq.data, dq.len);
3165 }
3166
3167 appendStringInfoChar(&buf, '\n');
3168
3169 ReleaseSysCache(proctup);
3170
3171 PG_RETURN_TEXT_P(string_to_text(buf.data));
3172 }
3173
3174 /*
3175 * pg_get_function_arguments
3176 * Get a nicely-formatted list of arguments for a function.
3177 * This is everything that would go between the parentheses in
3178 * CREATE FUNCTION.
3179 */
3180 Datum
3181 pg_get_function_arguments(PG_FUNCTION_ARGS)
3182 {
3183 Oid funcid = PG_GETARG_OID(0);
3184 StringInfoData buf;
3185 HeapTuple proctup;
3186
3187 proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
3188 if (!HeapTupleIsValid(proctup))
3189 PG_RETURN_NULL();
3190
3191 initStringInfo(&buf);
3192
3193 (void) print_function_arguments(&buf, proctup, false, true);
3194
3195 ReleaseSysCache(proctup);
3196
3197 PG_RETURN_TEXT_P(string_to_text(buf.data));
3198 }
3199
3200 /*
3201 * pg_get_function_identity_arguments
3202 * Get a formatted list of arguments for a function.
3203 * This is everything that would go between the parentheses in
3204 * ALTER FUNCTION, etc. In particular, don't print defaults.
3205 */
3206 Datum
3207 pg_get_function_identity_arguments(PG_FUNCTION_ARGS)
3208 {
3209 Oid funcid = PG_GETARG_OID(0);
3210 StringInfoData buf;
3211 HeapTuple proctup;
3212
3213 proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
3214 if (!HeapTupleIsValid(proctup))
3215 PG_RETURN_NULL();
3216
3217 initStringInfo(&buf);
3218
3219 (void) print_function_arguments(&buf, proctup, false, false);
3220
3221 ReleaseSysCache(proctup);
3222
3223 PG_RETURN_TEXT_P(string_to_text(buf.data));
3224 }
3225
3226 /*
3227 * pg_get_function_result
3228 * Get a nicely-formatted version of the result type of a function.
3229 * This is what would appear after RETURNS in CREATE FUNCTION.
3230 */
3231 Datum
3232 pg_get_function_result(PG_FUNCTION_ARGS)
3233 {
3234 Oid funcid = PG_GETARG_OID(0);
3235 StringInfoData buf;
3236 HeapTuple proctup;
3237
3238 proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
3239 if (!HeapTupleIsValid(proctup))
3240 PG_RETURN_NULL();
3241
3242 if (((Form_pg_proc) GETSTRUCT(proctup))->prokind == PROKIND_PROCEDURE)
3243 {
3244 ReleaseSysCache(proctup);
3245 PG_RETURN_NULL();
3246 }
3247
3248 initStringInfo(&buf);
3249
3250 print_function_rettype(&buf, proctup);
3251
3252 ReleaseSysCache(proctup);
3253
3254 PG_RETURN_TEXT_P(string_to_text(buf.data));
3255 }
3256
3257 /*
3258 * Guts of pg_get_function_result: append the function's return type
3259 * to the specified buffer.
3260 */
3261 static void
3262 print_function_rettype(StringInfo buf, HeapTuple proctup)
3263 {
3264 Form_pg_proc proc = (Form_pg_proc) GETSTRUCT(proctup);
3265 int ntabargs = 0;
3266 StringInfoData rbuf;
3267
3268 initStringInfo(&rbuf);
3269
3270 if (proc->proretset)
3271 {
3272 /* It might be a table function; try to print the arguments */
3273 appendStringInfoString(&rbuf, "TABLE(");
3274 ntabargs = print_function_arguments(&rbuf, proctup, true, false);
3275 if (ntabargs > 0)
3276 appendStringInfoChar(&rbuf, ')');
3277 else
3278 resetStringInfo(&rbuf);
3279 }
3280
3281 if (ntabargs == 0)
3282 {
3283 /* Not a table function, so do the normal thing */
3284 if (proc->proretset)
3285 appendStringInfoString(&rbuf, "SETOF ");
3286 appendStringInfoString(&rbuf, format_type_be(proc->prorettype));
3287 }
3288
3289 appendBinaryStringInfo(buf, rbuf.data, rbuf.len);
3290 }
3291
3292 /*
3293 * Common code for pg_get_function_arguments and pg_get_function_result:
3294 * append the desired subset of arguments to buf. We print only TABLE
3295 * arguments when print_table_args is true, and all the others when it's false.
3296 * We print argument defaults only if print_defaults is true.
3297 * Function return value is the number of arguments printed.
3298 */
3299 static int
3300 print_function_arguments(StringInfo buf, HeapTuple proctup,
3301 bool print_table_args, bool print_defaults)
3302 {
3303 Form_pg_proc proc = (Form_pg_proc) GETSTRUCT(proctup);
3304 int numargs;
3305 Oid *argtypes;
3306 char **argnames;
3307 char *argmodes;
3308 int insertorderbyat = -1;
3309 int argsprinted;
3310 int inputargno;
3311 int nlackdefaults;
3312 List *argdefaults = NIL;
3313 ListCell *nextargdefault = NULL;
3314 int i;
3315
3316 numargs = get_func_arg_info(proctup,
3317 &argtypes, &argnames, &argmodes);
3318
3319 nlackdefaults = numargs;
3320 if (print_defaults && proc->pronargdefaults > 0)
3321 {
3322 Datum proargdefaults;
3323 bool isnull;
3324
3325 proargdefaults = SysCacheGetAttr(PROCOID, proctup,
3326 Anum_pg_proc_proargdefaults,
3327 &isnull);
3328 if (!isnull)
3329 {
3330 char *str;
3331
3332 str = TextDatumGetCString(proargdefaults);
3333 argdefaults = castNode(List, stringToNode(str));
3334 pfree(str);
3335 nextargdefault = list_head(argdefaults);
3336 /* nlackdefaults counts only *input* arguments lacking defaults */
3337 nlackdefaults = proc->pronargs - list_length(argdefaults);
3338 }
3339 }
3340
3341 /* Check for special treatment of ordered-set aggregates */
3342 if (proc->prokind == PROKIND_AGGREGATE)
3343 {
3344 HeapTuple aggtup;
3345 Form_pg_aggregate agg;
3346
3347 aggtup = SearchSysCache1(AGGFNOID, ObjectIdGetDatum(proc->oid));
3348 if (!HeapTupleIsValid(aggtup))
3349 elog(ERROR, "cache lookup failed for aggregate %u",
3350 proc->oid);
3351 agg = (Form_pg_aggregate) GETSTRUCT(aggtup);
3352 if (AGGKIND_IS_ORDERED_SET(agg->aggkind))
3353 insertorderbyat = agg->aggnumdirectargs;
3354 ReleaseSysCache(aggtup);
3355 }
3356
3357 argsprinted = 0;
3358 inputargno = 0;
3359 for (i = 0; i < numargs; i++)
3360 {
3361 Oid argtype = argtypes[i];
3362 char *argname = argnames ? argnames[i] : NULL;
3363 char argmode = argmodes ? argmodes[i] : PROARGMODE_IN;
3364 const char *modename;
3365 bool isinput;
3366
3367 switch (argmode)
3368 {
3369 case PROARGMODE_IN:
3370
3371 /*
3372 * For procedures, explicitly mark all argument modes, so as
3373 * to avoid ambiguity with the SQL syntax for DROP PROCEDURE.
3374 */
3375 if (proc->prokind == PROKIND_PROCEDURE)
3376 modename = "IN ";
3377 else
3378 modename = "";
3379 isinput = true;
3380 break;
3381 case PROARGMODE_INOUT:
3382 modename = "INOUT ";
3383 isinput = true;
3384 break;
3385 case PROARGMODE_OUT:
3386 modename = "OUT ";
3387 isinput = false;
3388 break;
3389 case PROARGMODE_VARIADIC:
3390 modename = "VARIADIC ";
3391 isinput = true;
3392 break;
3393 case PROARGMODE_TABLE:
3394 modename = "";
3395 isinput = false;
3396 break;
3397 default:
3398 elog(ERROR, "invalid parameter mode '%c'", argmode);
3399 modename = NULL; /* keep compiler quiet */
3400 isinput = false;
3401 break;
3402 }
3403 if (isinput)
3404 inputargno++; /* this is a 1-based counter */
3405
3406 if (print_table_args != (argmode == PROARGMODE_TABLE))
3407 continue;
3408
3409 if (argsprinted == insertorderbyat)
3410 {
3411 if (argsprinted)
3412 appendStringInfoChar(buf, ' ');
3413 appendStringInfoString(buf, "ORDER BY ");
3414 }
3415 else if (argsprinted)
3416 appendStringInfoString(buf, ", ");
3417
3418 appendStringInfoString(buf, modename);
3419 if (argname && argname[0])
3420 appendStringInfo(buf, "%s ", quote_identifier(argname));
3421 appendStringInfoString(buf, format_type_be(argtype));
3422 if (print_defaults && isinput && inputargno > nlackdefaults)
3423 {
3424 Node *expr;
3425
3426 Assert(nextargdefault != NULL);
3427 expr = (Node *) lfirst(nextargdefault);
3428 nextargdefault = lnext(argdefaults, nextargdefault);
3429
3430 appendStringInfo(buf, " DEFAULT %s",
3431 deparse_expression(expr, NIL, false, false));
3432 }
3433 argsprinted++;
3434
3435 /* nasty hack: print the last arg twice for variadic ordered-set agg */
3436 if (argsprinted == insertorderbyat && i == numargs - 1)
3437 {
3438 i--;
3439 /* aggs shouldn't have defaults anyway, but just to be sure ... */
3440 print_defaults = false;
3441 }
3442 }
3443
3444 return argsprinted;
3445 }
3446
3447 static bool
3448 is_input_argument(int nth, const char *argmodes)
3449 {
3450 return (!argmodes
3451 || argmodes[nth] == PROARGMODE_IN
3452 || argmodes[nth] == PROARGMODE_INOUT
3453 || argmodes[nth] == PROARGMODE_VARIADIC);
3454 }
3455
3456 /*
3457 * Append used transformed types to specified buffer
3458 */
3459 static void
3460 print_function_trftypes(StringInfo buf, HeapTuple proctup)
3461 {
3462 Oid *trftypes;
3463 int ntypes;
3464
3465 ntypes = get_func_trftypes(proctup, &trftypes);
3466 if (ntypes > 0)
3467 {
3468 int i;
3469
3470 appendStringInfoString(buf, " TRANSFORM ");
3471 for (i = 0; i < ntypes; i++)
3472 {
3473 if (i != 0)
3474 appendStringInfoString(buf, ", ");
3475 appendStringInfo(buf, "FOR TYPE %s", format_type_be(trftypes[i]));
3476 }
3477 appendStringInfoChar(buf, '\n');
3478 }
3479 }
3480
3481 /*
3482 * Get textual representation of a function argument's default value. The
3483 * second argument of this function is the argument number among all arguments
3484 * (i.e. proallargtypes, *not* proargtypes), starting with 1, because that's
3485 * how information_schema.sql uses it.
3486 */
3487 Datum
3488 pg_get_function_arg_default(PG_FUNCTION_ARGS)
3489 {
3490 Oid funcid = PG_GETARG_OID(0);
3491 int32 nth_arg = PG_GETARG_INT32(1);
3492 HeapTuple proctup;
3493 Form_pg_proc proc;
3494 int numargs;
3495 Oid *argtypes;
3496 char **argnames;
3497 char *argmodes;
3498 int i;
3499 List *argdefaults;
3500 Node *node;
3501 char *str;
3502 int nth_inputarg;
3503 Datum proargdefaults;
3504 bool isnull;
3505 int nth_default;
3506
3507 proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
3508 if (!HeapTupleIsValid(proctup))
3509 PG_RETURN_NULL();
3510
3511 numargs = get_func_arg_info(proctup, &argtypes, &argnames, &argmodes);
3512 if (nth_arg < 1 || nth_arg > numargs || !is_input_argument(nth_arg - 1, argmodes))
3513 {
3514 ReleaseSysCache(proctup);
3515 PG_RETURN_NULL();
3516 }
3517
3518 nth_inputarg = 0;
3519 for (i = 0; i < nth_arg; i++)
3520 if (is_input_argument(i, argmodes))
3521 nth_inputarg++;
3522
3523 proargdefaults = SysCacheGetAttr(PROCOID, proctup,
3524 Anum_pg_proc_proargdefaults,
3525 &isnull);
3526 if (isnull)
3527 {
3528 ReleaseSysCache(proctup);
3529 PG_RETURN_NULL();
3530 }
3531
3532 str = TextDatumGetCString(proargdefaults);
3533 argdefaults = castNode(List, stringToNode(str));
3534 pfree(str);
3535
3536 proc = (Form_pg_proc) GETSTRUCT(proctup);
3537
3538 /*
3539 * Calculate index into proargdefaults: proargdefaults corresponds to the
3540 * last N input arguments, where N = pronargdefaults.
3541 */
3542 nth_default = nth_inputarg - 1 - (proc->pronargs - proc->pronargdefaults);
3543
3544 if (nth_default < 0 || nth_default >= list_length(argdefaults))
3545 {
3546 ReleaseSysCache(proctup);
3547 PG_RETURN_NULL();
3548 }
3549 node = list_nth(argdefaults, nth_default);
3550 str = deparse_expression(node, NIL, false, false);
3551
3552 ReleaseSysCache(proctup);
3553
3554 PG_RETURN_TEXT_P(string_to_text(str));
3555 }
3556
3557 static void
3558 print_function_sqlbody(StringInfo buf, HeapTuple proctup)
3559 {
3560 int numargs;
3561 Oid *argtypes;
3562 char **argnames;
3563 char *argmodes;
3564 deparse_namespace dpns = {0};
3565 Datum tmp;
3566 Node *n;
3567
3568 dpns.funcname = pstrdup(NameStr(((Form_pg_proc) GETSTRUCT(proctup))->proname));
3569 numargs = get_func_arg_info(proctup,
3570 &argtypes, &argnames, &argmodes);
3571 dpns.numargs = numargs;
3572 dpns.argnames = argnames;
3573
3574 tmp = SysCacheGetAttrNotNull(PROCOID, proctup, Anum_pg_proc_prosqlbody);
3575 n = stringToNode(TextDatumGetCString(tmp));
3576
3577 if (IsA(n, List))
3578 {
3579 List *stmts;
3580 ListCell *lc;
3581
3582 stmts = linitial(castNode(List, n));
3583
3584 appendStringInfoString(buf, "BEGIN ATOMIC\n");
3585
3586 foreach(lc, stmts)
3587 {
3588 Query *query = lfirst_node(Query, lc);
3589
3590 /* It seems advisable to get at least AccessShareLock on rels */
3591 AcquireRewriteLocks(query, false, false);
3592 get_query_def(query, buf, list_make1(&dpns), NULL, false,
3593 PRETTYFLAG_INDENT, WRAP_COLUMN_DEFAULT, 1);
3594 appendStringInfoChar(buf, ';');
3595 appendStringInfoChar(buf, '\n');
3596 }
3597
3598 appendStringInfoString(buf, "END");
3599 }
3600 else
3601 {
3602 Query *query = castNode(Query, n);
3603
3604 /* It seems advisable to get at least AccessShareLock on rels */
3605 AcquireRewriteLocks(query, false, false);
3606 get_query_def(query, buf, list_make1(&dpns), NULL, false,
3607 0, WRAP_COLUMN_DEFAULT, 0);
3608 }
3609 }
3610
3611 Datum
3612 pg_get_function_sqlbody(PG_FUNCTION_ARGS)
3613 {
3614 Oid funcid = PG_GETARG_OID(0);
3615 StringInfoData buf;
3616 HeapTuple proctup;
3617 bool isnull;
3618
3619 initStringInfo(&buf);
3620
3621 /* Look up the function */
3622 proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
3623 if (!HeapTupleIsValid(proctup))
3624 PG_RETURN_NULL();
3625
3626 (void) SysCacheGetAttr(PROCOID, proctup, Anum_pg_proc_prosqlbody, &isnull);
3627 if (isnull)
3628 {
3629 ReleaseSysCache(proctup);
3630 PG_RETURN_NULL();
3631 }
3632
3633 print_function_sqlbody(&buf, proctup);
3634
3635 ReleaseSysCache(proctup);
3636
3637 PG_RETURN_TEXT_P(cstring_to_text_with_len(buf.data, buf.len));
3638 }
3639
3640
3641 /*
3642 * deparse_expression - General utility for deparsing expressions
3643 *
3644 * calls deparse_expression_pretty with all prettyPrinting disabled
3645 */
3646 char *
3647 deparse_expression(Node *expr, List *dpcontext,
3648 bool forceprefix, bool showimplicit)
3649 {
3650 return deparse_expression_pretty(expr, dpcontext, forceprefix,
3651 showimplicit, 0, 0);
3652 }
3653
3654 /* ----------
3655 * deparse_expression_pretty - General utility for deparsing expressions
3656 *
3657 * expr is the node tree to be deparsed. It must be a transformed expression
3658 * tree (ie, not the raw output of gram.y).
3659 *
3660 * dpcontext is a list of deparse_namespace nodes representing the context
3661 * for interpreting Vars in the node tree. It can be NIL if no Vars are
3662 * expected.
3663 *
3664 * forceprefix is true to force all Vars to be prefixed with their table names.
3665 *
3666 * showimplicit is true to force all implicit casts to be shown explicitly.
3667 *
3668 * Tries to pretty up the output according to prettyFlags and startIndent.
3669 *
3670 * The result is a palloc'd string.
3671 * ----------
3672 */
3673 static char *
3674 deparse_expression_pretty(Node *expr, List *dpcontext,
3675 bool forceprefix, bool showimplicit,
3676 int prettyFlags, int startIndent)
3677 {
3678 StringInfoData buf;
3679 deparse_context context;
3680
3681 initStringInfo(&buf);
3682 context.buf = &buf;
3683 context.namespaces = dpcontext;
3684 context.resultDesc = NULL;
3685 context.targetList = NIL;
3686 context.windowClause = NIL;
3687 context.varprefix = forceprefix;
3688 context.prettyFlags = prettyFlags;
3689 context.wrapColumn = WRAP_COLUMN_DEFAULT;
3690 context.indentLevel = startIndent;
3691 context.colNamesVisible = true;
3692 context.inGroupBy = false;
3693 context.varInOrderBy = false;
3694 context.appendparents = NULL;
3695
3696 get_rule_expr(expr, &context, showimplicit);
3697
3698 return buf.data;
3699 }
3700
3701 /* ----------
3702 * deparse_context_for - Build deparse context for a single relation
3703 *
3704 * Given the reference name (alias) and OID of a relation, build deparsing
3705 * context for an expression referencing only that relation (as varno 1,
3706 * varlevelsup 0). This is sufficient for many uses of deparse_expression.
3707 * ----------
3708 */
3709 List *
3710 deparse_context_for(const char *aliasname, Oid relid)
3711 {
3712 deparse_namespace *dpns;
3713 RangeTblEntry *rte;
3714
3715 dpns = (deparse_namespace *) palloc0(sizeof(deparse_namespace));
3716
3717 /* Build a minimal RTE for the rel */
3718 rte = makeNode(RangeTblEntry);
3719 rte->rtekind = RTE_RELATION;
3720 rte->relid = relid;
3721 rte->relkind = RELKIND_RELATION; /* no need for exactness here */
3722 rte->rellockmode = AccessShareLock;
3723 rte->alias = makeAlias(aliasname, NIL);
3724 rte->eref = rte->alias;
3725 rte->lateral = false;
3726 rte->inh = false;
3727 rte->inFromCl = true;
3728
3729 /* Build one-element rtable */
3730 dpns->rtable = list_make1(rte);
3731 dpns->subplans = NIL;
3732 dpns->ctes = NIL;
3733 dpns->appendrels = NULL;
3734 set_rtable_names(dpns, NIL, NULL);
3735 set_simple_column_names(dpns);
3736
3737 /* Return a one-deep namespace stack */
3738 return list_make1(dpns);
3739 }
3740
3741 /*
3742 * deparse_context_for_plan_tree - Build deparse context for a Plan tree
3743 *
3744 * When deparsing an expression in a Plan tree, we use the plan's rangetable
3745 * to resolve names of simple Vars. The initialization of column names for
3746 * this is rather expensive if the rangetable is large, and it'll be the same
3747 * for every expression in the Plan tree; so we do it just once and re-use
3748 * the result of this function for each expression. (Note that the result
3749 * is not usable until set_deparse_context_plan() is applied to it.)
3750 *
3751 * In addition to the PlannedStmt, pass the per-RTE alias names
3752 * assigned by a previous call to select_rtable_names_for_explain.
3753 */
3754 List *
3755 deparse_context_for_plan_tree(PlannedStmt *pstmt, List *rtable_names)
3756 {
3757 deparse_namespace *dpns;
3758
3759 dpns = (deparse_namespace *) palloc0(sizeof(deparse_namespace));
3760
3761 /* Initialize fields that stay the same across the whole plan tree */
3762 dpns->rtable = pstmt->rtable;
3763 dpns->rtable_names = rtable_names;
3764 dpns->subplans = pstmt->subplans;
3765 dpns->ctes = NIL;
3766 if (pstmt->appendRelations)
3767 {
3768 /* Set up the array, indexed by child relid */
3769 int ntables = list_length(dpns->rtable);
3770 ListCell *lc;
3771
3772 dpns->appendrels = (AppendRelInfo **)
3773 palloc0((ntables + 1) * sizeof(AppendRelInfo *));
3774 foreach(lc, pstmt->appendRelations)
3775 {
3776 AppendRelInfo *appinfo = lfirst_node(AppendRelInfo, lc);
3777 Index crelid = appinfo->child_relid;
3778
3779 Assert(crelid > 0 && crelid <= ntables);
3780 Assert(dpns->appendrels[crelid] == NULL);
3781 dpns->appendrels[crelid] = appinfo;
3782 }
3783 }
3784 else
3785 dpns->appendrels = NULL; /* don't need it */
3786
3787 /*
3788 * Set up column name aliases, ignoring any join RTEs; they don't matter
3789 * because plan trees don't contain any join alias Vars.
3790 */
3791 set_simple_column_names(dpns);
3792
3793 /* Return a one-deep namespace stack */
3794 return list_make1(dpns);
3795 }
3796
3797 /*
3798 * set_deparse_context_plan - Specify Plan node containing expression
3799 *
3800 * When deparsing an expression in a Plan tree, we might have to resolve
3801 * OUTER_VAR, INNER_VAR, or INDEX_VAR references. To do this, the caller must
3802 * provide the parent Plan node. Then OUTER_VAR and INNER_VAR references
3803 * can be resolved by drilling down into the left and right child plans.
3804 * Similarly, INDEX_VAR references can be resolved by reference to the
3805 * indextlist given in a parent IndexOnlyScan node, or to the scan tlist in
3806 * ForeignScan and CustomScan nodes. (Note that we don't currently support
3807 * deparsing of indexquals in regular IndexScan or BitmapIndexScan nodes;
3808 * for those, we can only deparse the indexqualorig fields, which won't
3809 * contain INDEX_VAR Vars.)
3810 *
3811 * The ancestors list is a list of the Plan's parent Plan and SubPlan nodes,
3812 * the most-closely-nested first. This is needed to resolve PARAM_EXEC
3813 * Params. Note we assume that all the Plan nodes share the same rtable.
3814 *
3815 * For a ModifyTable plan, we might also need to resolve references to OLD/NEW
3816 * variables in the RETURNING list, so we copy the alias names of the OLD and
3817 * NEW rows from the ModifyTable plan node.
3818 *
3819 * Once this function has been called, deparse_expression() can be called on
3820 * subsidiary expression(s) of the specified Plan node. To deparse
3821 * expressions of a different Plan node in the same Plan tree, re-call this
3822 * function to identify the new parent Plan node.
3823 *
3824 * The result is the same List passed in; this is a notational convenience.
3825 */
3826 List *
3827 set_deparse_context_plan(List *dpcontext, Plan *plan, List *ancestors)
3828 {
3829 deparse_namespace *dpns;
3830
3831 /* Should always have one-entry namespace list for Plan deparsing */
3832 Assert(list_length(dpcontext) == 1);
3833 dpns = (deparse_namespace *) linitial(dpcontext);
3834
3835 /* Set our attention on the specific plan node passed in */
3836 dpns->ancestors = ancestors;
3837 set_deparse_plan(dpns, plan);
3838
3839 /* For ModifyTable, set aliases for OLD and NEW in RETURNING */
3840 if (IsA(plan, ModifyTable))
3841 {
3842 dpns->ret_old_alias = ((ModifyTable *) plan)->returningOldAlias;
3843 dpns->ret_new_alias = ((ModifyTable *) plan)->returningNewAlias;
3844 }
3845
3846 return dpcontext;
3847 }
3848
3849 /*
3850 * select_rtable_names_for_explain - Select RTE aliases for EXPLAIN
3851 *
3852 * Determine the relation aliases we'll use during an EXPLAIN operation.
3853 * This is just a frontend to set_rtable_names. We have to expose the aliases
3854 * to EXPLAIN because EXPLAIN needs to know the right alias names to print.
3855 */
3856 List *
3857 select_rtable_names_for_explain(List *rtable, Bitmapset *rels_used)
3858 {
3859 deparse_namespace dpns;
3860
3861 memset(&dpns, 0, sizeof(dpns));
3862 dpns.rtable = rtable;
3863 dpns.subplans = NIL;
3864 dpns.ctes = NIL;
3865 dpns.appendrels = NULL;
3866 set_rtable_names(&dpns, NIL, rels_used);
3867 /* We needn't bother computing column aliases yet */
3868
3869 return dpns.rtable_names;
3870 }
3871
3872 /*
3873 * set_rtable_names: select RTE aliases to be used in printing a query
3874 *
3875 * We fill in dpns->rtable_names with a list of names that is one-for-one with
3876 * the already-filled dpns->rtable list. Each RTE name is unique among those
3877 * in the new namespace plus any ancestor namespaces listed in
3878 * parent_namespaces.
3879 *
3880 * If rels_used isn't NULL, only RTE indexes listed in it are given aliases.
3881 *
3882 * Note that this function is only concerned with relation names, not column
3883 * names.
3884 */
3885 static void
3886 set_rtable_names(deparse_namespace *dpns, List *parent_namespaces,
3887 Bitmapset *rels_used)
3888 {
3889 HASHCTL hash_ctl;
3890 HTAB *names_hash;
3891 NameHashEntry *hentry;
3892 bool found;
3893 int rtindex;
3894 ListCell *lc;
3895
3896 dpns->rtable_names = NIL;
3897 /* nothing more to do if empty rtable */
3898 if (dpns->rtable == NIL)
3899 return;
3900
3901 /*
3902 * We use a hash table to hold known names, so that this process is O(N)
3903 * not O(N^2) for N names.
3904 */
3905 hash_ctl.keysize = NAMEDATALEN;
3906 hash_ctl.entrysize = sizeof(NameHashEntry);
3907 hash_ctl.hcxt = CurrentMemoryContext;
3908 names_hash = hash_create("set_rtable_names names",
3909 list_length(dpns->rtable),
3910 &hash_ctl,
3911 HASH_ELEM | HASH_STRINGS | HASH_CONTEXT);
3912
3913 /* Preload the hash table with names appearing in parent_namespaces */
3914 foreach(lc, parent_namespaces)
3915 {
3916 deparse_namespace *olddpns = (deparse_namespace *) lfirst(lc);
3917 ListCell *lc2;
3918
3919 foreach(lc2, olddpns->rtable_names)
3920 {
3921 char *oldname = (char *) lfirst(lc2);
3922
3923 if (oldname == NULL)
3924 continue;
3925 hentry = (NameHashEntry *) hash_search(names_hash,
3926 oldname,
3927 HASH_ENTER,
3928 &found);
3929 /* we do not complain about duplicate names in parent namespaces */
3930 hentry->counter = 0;
3931 }
3932 }
3933
3934 /* Now we can scan the rtable */
3935 rtindex = 1;
3936 foreach(lc, dpns->rtable)
3937 {
3938 RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
3939 char *refname;
3940
3941 /* Just in case this takes an unreasonable amount of time ... */
3942 CHECK_FOR_INTERRUPTS();
3943
3944 if (rels_used && !bms_is_member(rtindex, rels_used))
3945 {
3946 /* Ignore unreferenced RTE */
3947 refname = NULL;
3948 }
3949 else if (rte->alias)
3950 {
3951 /* If RTE has a user-defined alias, prefer that */
3952 refname = rte->alias->aliasname;
3953 }
3954 else if (rte->rtekind == RTE_RELATION)
3955 {
3956 /* Use the current actual name of the relation */
3957 refname = get_rel_name(rte->relid);
3958 }
3959 else if (rte->rtekind == RTE_JOIN)
3960 {
3961 /* Unnamed join has no refname */
3962 refname = NULL;
3963 }
3964 else
3965 {
3966 /* Otherwise use whatever the parser assigned */
3967 refname = rte->eref->aliasname;
3968 }
3969
3970 /*
3971 * If the selected name isn't unique, append digits to make it so, and
3972 * make a new hash entry for it once we've got a unique name. For a
3973 * very long input name, we might have to truncate to stay within
3974 * NAMEDATALEN.
3975 */
3976 if (refname)
3977 {
3978 hentry = (NameHashEntry *) hash_search(names_hash,
3979 refname,
3980 HASH_ENTER,
3981 &found);
3982 if (found)
3983 {
3984 /* Name already in use, must choose a new one */
3985 int refnamelen = strlen(refname);
3986 char *modname = (char *) palloc(refnamelen + 16);
3987 NameHashEntry *hentry2;
3988
3989 do
3990 {
3991 hentry->counter++;
3992 for (;;)
3993 {
3994 memcpy(modname, refname, refnamelen);
3995 sprintf(modname + refnamelen, "_%d", hentry->counter);
3996 if (strlen(modname) < NAMEDATALEN)
3997 break;
3998 /* drop chars from refname to keep all the digits */
3999 refnamelen = pg_mbcliplen(refname, refnamelen,
4000 refnamelen - 1);
4001 }
4002 hentry2 = (NameHashEntry *) hash_search(names_hash,
4003 modname,
4004 HASH_ENTER,
4005 &found);
4006 } while (found);
4007 hentry2->counter = 0; /* init new hash entry */
4008 refname = modname;
4009 }
4010 else
4011 {
4012 /* Name not previously used, need only initialize hentry */
4013 hentry->counter = 0;
4014 }
4015 }
4016
4017 dpns->rtable_names = lappend(dpns->rtable_names, refname);
4018 rtindex++;
4019 }
4020
4021 hash_destroy(names_hash);
4022 }
4023
4024 /*
4025 * set_deparse_for_query: set up deparse_namespace for deparsing a Query tree
4026 *
4027 * For convenience, this is defined to initialize the deparse_namespace struct
4028 * from scratch.
4029 */
4030 static void
4031 set_deparse_for_query(deparse_namespace *dpns, Query *query,
4032 List *parent_namespaces)
4033 {
4034 ListCell *lc;
4035 ListCell *lc2;
4036
4037 /* Initialize *dpns and fill rtable/ctes links */
4038 memset(dpns, 0, sizeof(deparse_namespace));
4039 dpns->rtable = query->rtable;
4040 dpns->subplans = NIL;
4041 dpns->ctes = query->cteList;
4042 dpns->appendrels = NULL;
4043 dpns->ret_old_alias = query->returningOldAlias;
4044 dpns->ret_new_alias = query->returningNewAlias;
4045
4046 /* Assign a unique relation alias to each RTE */
4047 set_rtable_names(dpns, parent_namespaces, NULL);
4048
4049 /* Initialize dpns->rtable_columns to contain zeroed structs */
4050 dpns->rtable_columns = NIL;
4051 while (list_length(dpns->rtable_columns) < list_length(dpns->rtable))
4052 dpns->rtable_columns = lappend(dpns->rtable_columns,
4053 palloc0(sizeof(deparse_columns)));
4054
4055 /* If it's a utility query, it won't have a jointree */
4056 if (query->jointree)
4057 {
4058 /* Detect whether global uniqueness of USING names is needed */
4059 dpns->unique_using =
4060 has_dangerous_join_using(dpns, (Node *) query->jointree);
4061
4062 /*
4063 * Select names for columns merged by USING, via a recursive pass over
4064 * the query jointree.
4065 */
4066 set_using_names(dpns, (Node *) query->jointree, NIL);
4067 }
4068
4069 /*
4070 * Now assign remaining column aliases for each RTE. We do this in a
4071 * linear scan of the rtable, so as to process RTEs whether or not they
4072 * are in the jointree (we mustn't miss NEW.*, INSERT target relations,
4073 * etc). JOIN RTEs must be processed after their children, but this is
4074 * okay because they appear later in the rtable list than their children
4075 * (cf Asserts in identify_join_columns()).
4076 */
4077 forboth(lc, dpns->rtable, lc2, dpns->rtable_columns)
4078 {
4079 RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
4080 deparse_columns *colinfo = (deparse_columns *) lfirst(lc2);
4081
4082 if (rte->rtekind == RTE_JOIN)
4083 set_join_column_names(dpns, rte, colinfo);
4084 else
4085 set_relation_column_names(dpns, rte, colinfo);
4086 }
4087 }
4088
4089 /*
4090 * set_simple_column_names: fill in column aliases for non-query situations
4091 *
4092 * This handles EXPLAIN and cases where we only have relation RTEs. Without
4093 * a join tree, we can't do anything smart about join RTEs, but we don't
4094 * need to, because EXPLAIN should never see join alias Vars anyway.
4095 * If we find a join RTE we'll just skip it, leaving its deparse_columns
4096 * struct all-zero. If somehow we try to deparse a join alias Var, we'll
4097 * error out cleanly because the struct's num_cols will be zero.
4098 */
4099 static void
4100 set_simple_column_names(deparse_namespace *dpns)
4101 {
4102 ListCell *lc;
4103 ListCell *lc2;
4104
4105 /* Initialize dpns->rtable_columns to contain zeroed structs */
4106 dpns->rtable_columns = NIL;
4107 while (list_length(dpns->rtable_columns) < list_length(dpns->rtable))
4108 dpns->rtable_columns = lappend(dpns->rtable_columns,
4109 palloc0(sizeof(deparse_columns)));
4110
4111 /* Assign unique column aliases within each non-join RTE */
4112 forboth(lc, dpns->rtable, lc2, dpns->rtable_columns)
4113 {
4114 RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
4115 deparse_columns *colinfo = (deparse_columns *) lfirst(lc2);
4116
4117 if (rte->rtekind != RTE_JOIN)
4118 set_relation_column_names(dpns, rte, colinfo);
4119 }
4120 }
4121
4122 /*
4123 * has_dangerous_join_using: search jointree for unnamed JOIN USING
4124 *
4125 * Merged columns of a JOIN USING may act differently from either of the input
4126 * columns, either because they are merged with COALESCE (in a FULL JOIN) or
4127 * because an implicit coercion of the underlying input column is required.
4128 * In such a case the column must be referenced as a column of the JOIN not as
4129 * a column of either input. And this is problematic if the join is unnamed
4130 * (alias-less): we cannot qualify the column's name with an RTE name, since
4131 * there is none. (Forcibly assigning an alias to the join is not a solution,
4132 * since that will prevent legal references to tables below the join.)
4133 * To ensure that every column in the query is unambiguously referenceable,
4134 * we must assign such merged columns names that are globally unique across
4135 * the whole query, aliasing other columns out of the way as necessary.
4136 *
4137 * Because the ensuing re-aliasing is fairly damaging to the readability of
4138 * the query, we don't do this unless we have to. So, we must pre-scan
4139 * the join tree to see if we have to, before starting set_using_names().
4140 */
4141 static bool
4142 has_dangerous_join_using(deparse_namespace *dpns, Node *jtnode)
4143 {
4144 if (IsA(jtnode, RangeTblRef))
4145 {
4146 /* nothing to do here */
4147 }
4148 else if (IsA(jtnode, FromExpr))
4149 {
4150 FromExpr *f = (FromExpr *) jtnode;
4151 ListCell *lc;
4152
4153 foreach(lc, f->fromlist)
4154 {
4155 if (has_dangerous_join_using(dpns, (Node *) lfirst(lc)))
4156 return true;
4157 }
4158 }
4159 else if (IsA(jtnode, JoinExpr))
4160 {
4161 JoinExpr *j = (JoinExpr *) jtnode;
4162
4163 /* Is it an unnamed JOIN with USING? */
4164 if (j->alias == NULL && j->usingClause)
4165 {
4166 /*
4167 * Yes, so check each join alias var to see if any of them are not
4168 * simple references to underlying columns. If so, we have a
4169 * dangerous situation and must pick unique aliases.
4170 */
4171 RangeTblEntry *jrte = rt_fetch(j->rtindex, dpns->rtable);
4172
4173 /* We need only examine the merged columns */
4174 for (int i = 0; i < jrte->joinmergedcols; i++)
4175 {
4176 Node *aliasvar = list_nth(jrte->joinaliasvars, i);
4177
4178 if (!IsA(aliasvar, Var))
4179 return true;
4180 }
4181 }
4182
4183 /* Nope, but inspect children */
4184 if (has_dangerous_join_using(dpns, j->larg))
4185 return true;
4186 if (has_dangerous_join_using(dpns, j->rarg))
4187 return true;
4188 }
4189 else
4190 elog(ERROR, "unrecognized node type: %d",
4191 (int) nodeTag(jtnode));
4192 return false;
4193 }
4194
4195 /*
4196 * set_using_names: select column aliases to be used for merged USING columns
4197 *
4198 * We do this during a recursive descent of the query jointree.
4199 * dpns->unique_using must already be set to determine the global strategy.
4200 *
4201 * Column alias info is saved in the dpns->rtable_columns list, which is
4202 * assumed to be filled with pre-zeroed deparse_columns structs.
4203 *
4204 * parentUsing is a list of all USING aliases assigned in parent joins of
4205 * the current jointree node. (The passed-in list must not be modified.)
4206 *
4207 * Note that we do not use per-deparse_columns hash tables in this function.
4208 * The number of names that need to be assigned should be small enough that
4209 * we don't need to trouble with that.
4210 */
4211 static void
4212 set_using_names(deparse_namespace *dpns, Node *jtnode, List *parentUsing)
4213 {
4214 if (IsA(jtnode, RangeTblRef))
4215 {
4216 /* nothing to do now */
4217 }
4218 else if (IsA(jtnode, FromExpr))
4219 {
4220 FromExpr *f = (FromExpr *) jtnode;
4221 ListCell *lc;
4222
4223 foreach(lc, f->fromlist)
4224 set_using_names(dpns, (Node *) lfirst(lc), parentUsing);
4225 }
4226 else if (IsA(jtnode, JoinExpr))
4227 {
4228 JoinExpr *j = (JoinExpr *) jtnode;
4229 RangeTblEntry *rte = rt_fetch(j->rtindex, dpns->rtable);
4230 deparse_columns *colinfo = deparse_columns_fetch(j->rtindex, dpns);
4231 int *leftattnos;
4232 int *rightattnos;
4233 deparse_columns *leftcolinfo;
4234 deparse_columns *rightcolinfo;
4235 int i;
4236 ListCell *lc;
4237
4238 /* Get info about the shape of the join */
4239 identify_join_columns(j, rte, colinfo);
4240 leftattnos = colinfo->leftattnos;
4241 rightattnos = colinfo->rightattnos;
4242
4243 /* Look up the not-yet-filled-in child deparse_columns structs */
4244 leftcolinfo = deparse_columns_fetch(colinfo->leftrti, dpns);
4245 rightcolinfo = deparse_columns_fetch(colinfo->rightrti, dpns);
4246
4247 /*
4248 * If this join is unnamed, then we cannot substitute new aliases at
4249 * this level, so any name requirements pushed down to here must be
4250 * pushed down again to the children.
4251 */
4252 if (rte->alias == NULL)
4253 {
4254 for (i = 0; i < colinfo->num_cols; i++)
4255 {
4256 char *colname = colinfo->colnames[i];
4257
4258 if (colname == NULL)
4259 continue;
4260
4261 /* Push down to left column, unless it's a system column */
4262 if (leftattnos[i] > 0)
4263 {
4264 expand_colnames_array_to(leftcolinfo, leftattnos[i]);
4265 leftcolinfo->colnames[leftattnos[i] - 1] = colname;
4266 }
4267
4268 /* Same on the righthand side */
4269 if (rightattnos[i] > 0)
4270 {
4271 expand_colnames_array_to(rightcolinfo, rightattnos[i]);
4272 rightcolinfo->colnames[rightattnos[i] - 1] = colname;
4273 }
4274 }
4275 }
4276
4277 /*
4278 * If there's a USING clause, select the USING column names and push
4279 * those names down to the children. We have two strategies:
4280 *
4281 * If dpns->unique_using is true, we force all USING names to be
4282 * unique across the whole query level. In principle we'd only need
4283 * the names of dangerous USING columns to be globally unique, but to
4284 * safely assign all USING names in a single pass, we have to enforce
4285 * the same uniqueness rule for all of them. However, if a USING
4286 * column's name has been pushed down from the parent, we should use
4287 * it as-is rather than making a uniqueness adjustment. This is
4288 * necessary when we're at an unnamed join, and it creates no risk of
4289 * ambiguity. Also, if there's a user-written output alias for a
4290 * merged column, we prefer to use that rather than the input name;
4291 * this simplifies the logic and seems likely to lead to less aliasing
4292 * overall.
4293 *
4294 * If dpns->unique_using is false, we only need USING names to be
4295 * unique within their own join RTE. We still need to honor
4296 * pushed-down names, though.
4297 *
4298 * Though significantly different in results, these two strategies are
4299 * implemented by the same code, with only the difference of whether
4300 * to put assigned names into dpns->using_names.
4301 */
4302 if (j->usingClause)
4303 {
4304 /* Copy the input parentUsing list so we don't modify it */
4305 parentUsing = list_copy(parentUsing);
4306
4307 /* USING names must correspond to the first join output columns */
4308 expand_colnames_array_to(colinfo, list_length(j->usingClause));
4309 i = 0;
4310 foreach(lc, j->usingClause)
4311 {
4312 char *colname = strVal(lfirst(lc));
4313
4314 /* Assert it's a merged column */
4315 Assert(leftattnos[i] != 0 && rightattnos[i] != 0);
4316
4317 /* Adopt passed-down name if any, else select unique name */
4318 if (colinfo->colnames[i] != NULL)
4319 colname = colinfo->colnames[i];
4320 else
4321 {
4322 /* Prefer user-written output alias if any */
4323 if (rte->alias && i < list_length(rte->alias->colnames))
4324 colname = strVal(list_nth(rte->alias->colnames, i));
4325 /* Make it appropriately unique */
4326 colname = make_colname_unique(colname, dpns, colinfo);
4327 if (dpns->unique_using)
4328 dpns->using_names = lappend(dpns->using_names,
4329 colname);
4330 /* Save it as output column name, too */
4331 colinfo->colnames[i] = colname;
4332 }
4333
4334 /* Remember selected names for use later */
4335 colinfo->usingNames = lappend(colinfo->usingNames, colname);
4336 parentUsing = lappend(parentUsing, colname);
4337
4338 /* Push down to left column, unless it's a system column */
4339 if (leftattnos[i] > 0)
4340 {
4341 expand_colnames_array_to(leftcolinfo, leftattnos[i]);
4342 leftcolinfo->colnames[leftattnos[i] - 1] = colname;
4343 }
4344
4345 /* Same on the righthand side */
4346 if (rightattnos[i] > 0)
4347 {
4348 expand_colnames_array_to(rightcolinfo, rightattnos[i]);
4349 rightcolinfo->colnames[rightattnos[i] - 1] = colname;
4350 }
4351
4352 i++;
4353 }
4354 }
4355
4356 /* Mark child deparse_columns structs with correct parentUsing info */
4357 leftcolinfo->parentUsing = parentUsing;
4358 rightcolinfo->parentUsing = parentUsing;
4359
4360 /* Now recursively assign USING column names in children */
4361 set_using_names(dpns, j->larg, parentUsing);
4362 set_using_names(dpns, j->rarg, parentUsing);
4363 }
4364 else
4365 elog(ERROR, "unrecognized node type: %d",
4366 (int) nodeTag(jtnode));
4367 }
4368
4369 /*
4370 * set_relation_column_names: select column aliases for a non-join RTE
4371 *
4372 * Column alias info is saved in *colinfo, which is assumed to be pre-zeroed.
4373 * If any colnames entries are already filled in, those override local
4374 * choices.
4375 */
4376 static void
4377 set_relation_column_names(deparse_namespace *dpns, RangeTblEntry *rte,
4378 deparse_columns *colinfo)
4379 {
4380 int ncolumns;
4381 char **real_colnames;
4382 bool changed_any;
4383 int noldcolumns;
4384 int i;
4385 int j;
4386
4387 /*
4388 * Construct an array of the current "real" column names of the RTE.
4389 * real_colnames[] will be indexed by physical column number, with NULL
4390 * entries for dropped columns.
4391 */
4392 if (rte->rtekind == RTE_RELATION)
4393 {
4394 /* Relation --- look to the system catalogs for up-to-date info */
4395 Relation rel;
4396 TupleDesc tupdesc;
4397
4398 rel = relation_open(rte->relid, AccessShareLock);
4399 tupdesc = RelationGetDescr(rel);
4400
4401 ncolumns = tupdesc->natts;
4402 real_colnames = (char **) palloc(ncolumns * sizeof(char *));
4403
4404 for (i = 0; i < ncolumns; i++)
4405 {
4406 Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
4407
4408 if (attr->attisdropped)
4409 real_colnames[i] = NULL;
4410 else
4411 real_colnames[i] = pstrdup(NameStr(attr->attname));
4412 }
4413 relation_close(rel, AccessShareLock);
4414 }
4415 else
4416 {
4417 /* Otherwise get the column names from eref or expandRTE() */
4418 List *colnames;
4419 ListCell *lc;
4420
4421 /*
4422 * Functions returning composites have the annoying property that some
4423 * of the composite type's columns might have been dropped since the
4424 * query was parsed. If possible, use expandRTE() to handle that
4425 * case, since it has the tedious logic needed to find out about
4426 * dropped columns. However, if we're explaining a plan, then we
4427 * don't have rte->functions because the planner thinks that won't be
4428 * needed later, and that breaks expandRTE(). So in that case we have
4429 * to rely on rte->eref, which may lead us to report a dropped
4430 * column's old name; that seems close enough for EXPLAIN's purposes.
4431 *
4432 * For non-RELATION, non-FUNCTION RTEs, we can just look at rte->eref,
4433 * which should be sufficiently up-to-date: no other RTE types can
4434 * have columns get dropped from under them after parsing.
4435 */
4436 if (rte->rtekind == RTE_FUNCTION && rte->functions != NIL)
4437 {
4438 /* Since we're not creating Vars, rtindex etc. don't matter */
4439 expandRTE(rte, 1, 0, VAR_RETURNING_DEFAULT, -1,
4440 true /* include dropped */ , &colnames, NULL);
4441 }
4442 else
4443 colnames = rte->eref->colnames;
4444
4445 ncolumns = list_length(colnames);
4446 real_colnames = (char **) palloc(ncolumns * sizeof(char *));
4447
4448 i = 0;
4449 foreach(lc, colnames)
4450 {
4451 /*
4452 * If the column name we find here is an empty string, then it's a
4453 * dropped column, so change to NULL.
4454 */
4455 char *cname = strVal(lfirst(lc));
4456
4457 if (cname[0] == '\0')
4458 cname = NULL;
4459 real_colnames[i] = cname;
4460 i++;
4461 }
4462 }
4463
4464 /*
4465 * Ensure colinfo->colnames has a slot for each column. (It could be long
4466 * enough already, if we pushed down a name for the last column.) Note:
4467 * it's possible that there are now more columns than there were when the
4468 * query was parsed, ie colnames could be longer than rte->eref->colnames.
4469 * We must assign unique aliases to the new columns too, else there could
4470 * be unresolved conflicts when the view/rule is reloaded.
4471 */
4472 expand_colnames_array_to(colinfo, ncolumns);
4473 Assert(colinfo->num_cols == ncolumns);
4474
4475 /*
4476 * Make sufficiently large new_colnames and is_new_col arrays, too.
4477 *
4478 * Note: because we leave colinfo->num_new_cols zero until after the loop,
4479 * colname_is_unique will not consult that array, which is fine because it
4480 * would only be duplicate effort.
4481 */
4482 colinfo->new_colnames = (char **) palloc(ncolumns * sizeof(char *));
4483 colinfo->is_new_col = (bool *) palloc(ncolumns * sizeof(bool));
4484
4485 /* If the RTE is wide enough, use a hash table to avoid O(N^2) costs */
4486 build_colinfo_names_hash(colinfo);
4487
4488 /*
4489 * Scan the columns, select a unique alias for each one, and store it in
4490 * colinfo->colnames and colinfo->new_colnames. The former array has NULL
4491 * entries for dropped columns, the latter omits them. Also mark
4492 * new_colnames entries as to whether they are new since parse time; this
4493 * is the case for entries beyond the length of rte->eref->colnames.
4494 */
4495 noldcolumns = list_length(rte->eref->colnames);
4496 changed_any = false;
4497 j = 0;
4498 for (i = 0; i < ncolumns; i++)
4499 {
4500 char *real_colname = real_colnames[i];
4501 char *colname = colinfo->colnames[i];
4502
4503 /* Skip dropped columns */
4504 if (real_colname == NULL)
4505 {
4506 Assert(colname == NULL); /* colnames[i] is already NULL */
4507 continue;
4508 }
4509
4510 /* If alias already assigned, that's what to use */
4511 if (colname == NULL)
4512 {
4513 /* If user wrote an alias, prefer that over real column name */
4514 if (rte->alias && i < list_length(rte->alias->colnames))
4515 colname = strVal(list_nth(rte->alias->colnames, i));
4516 else
4517 colname = real_colname;
4518
4519 /* Unique-ify and insert into colinfo */
4520 colname = make_colname_unique(colname, dpns, colinfo);
4521
4522 colinfo->colnames[i] = colname;
4523 add_to_names_hash(colinfo, colname);
4524 }
4525
4526 /* Put names of non-dropped columns in new_colnames[] too */
4527 colinfo->new_colnames[j] = colname;
4528 /* And mark them as new or not */
4529 colinfo->is_new_col[j] = (i >= noldcolumns);
4530 j++;
4531
4532 /* Remember if any assigned aliases differ from "real" name */
4533 if (!changed_any && strcmp(colname, real_colname) != 0)
4534 changed_any = true;
4535 }
4536
4537 /* We're now done needing the colinfo's names_hash */
4538 destroy_colinfo_names_hash(colinfo);
4539
4540 /*
4541 * Set correct length for new_colnames[] array. (Note: if columns have
4542 * been added, colinfo->num_cols includes them, which is not really quite
4543 * right but is harmless, since any new columns must be at the end where
4544 * they won't affect varattnos of pre-existing columns.)
4545 */
4546 colinfo->num_new_cols = j;
4547
4548 /*
4549 * For a relation RTE, we need only print the alias column names if any
4550 * are different from the underlying "real" names. For a function RTE,
4551 * always emit a complete column alias list; this is to protect against
4552 * possible instability of the default column names (eg, from altering
4553 * parameter names). For tablefunc RTEs, we never print aliases, because
4554 * the column names are part of the clause itself. For other RTE types,
4555 * print if we changed anything OR if there were user-written column
4556 * aliases (since the latter would be part of the underlying "reality").
4557 */
4558 if (rte->rtekind == RTE_RELATION)
4559 colinfo->printaliases = changed_any;
4560 else if (rte->rtekind == RTE_FUNCTION)
4561 colinfo->printaliases = true;
4562 else if (rte->rtekind == RTE_TABLEFUNC)
4563 colinfo->printaliases = false;
4564 else if (rte->alias && rte->alias->colnames != NIL)
4565 colinfo->printaliases = true;
4566 else
4567 colinfo->printaliases = changed_any;
4568 }
4569
4570 /*
4571 * set_join_column_names: select column aliases for a join RTE
4572 *
4573 * Column alias info is saved in *colinfo, which is assumed to be pre-zeroed.
4574 * If any colnames entries are already filled in, those override local
4575 * choices. Also, names for USING columns were already chosen by
4576 * set_using_names(). We further expect that column alias selection has been
4577 * completed for both input RTEs.
4578 */
4579 static void
4580 set_join_column_names(deparse_namespace *dpns, RangeTblEntry *rte,
4581 deparse_columns *colinfo)
4582 {
4583 deparse_columns *leftcolinfo;
4584 deparse_columns *rightcolinfo;
4585 bool changed_any;
4586 int noldcolumns;
4587 int nnewcolumns;
4588 Bitmapset *leftmerged = NULL;
4589 Bitmapset *rightmerged = NULL;
4590 int i;
4591 int j;
4592 int ic;
4593 int jc;
4594
4595 /* Look up the previously-filled-in child deparse_columns structs */
4596 leftcolinfo = deparse_columns_fetch(colinfo->leftrti, dpns);
4597 rightcolinfo = deparse_columns_fetch(colinfo->rightrti, dpns);
4598
4599 /*
4600 * Ensure colinfo->colnames has a slot for each column. (It could be long
4601 * enough already, if we pushed down a name for the last column.) Note:
4602 * it's possible that one or both inputs now have more columns than there
4603 * were when the query was parsed, but we'll deal with that below. We
4604 * only need entries in colnames for pre-existing columns.
4605 */
4606 noldcolumns = list_length(rte->eref->colnames);
4607 expand_colnames_array_to(colinfo, noldcolumns);
4608 Assert(colinfo->num_cols == noldcolumns);
4609
4610 /* If the RTE is wide enough, use a hash table to avoid O(N^2) costs */
4611 build_colinfo_names_hash(colinfo);
4612
4613 /*
4614 * Scan the join output columns, select an alias for each one, and store
4615 * it in colinfo->colnames. If there are USING columns, set_using_names()
4616 * already selected their names, so we can start the loop at the first
4617 * non-merged column.
4618 */
4619 changed_any = false;
4620 for (i = list_length(colinfo->usingNames); i < noldcolumns; i++)
4621 {
4622 char *colname = colinfo->colnames[i];
4623 char *real_colname;
4624
4625 /* Join column must refer to at least one input column */
4626 Assert(colinfo->leftattnos[i] != 0 || colinfo->rightattnos[i] != 0);
4627
4628 /* Get the child column name */
4629 if (colinfo->leftattnos[i] > 0)
4630 real_colname = leftcolinfo->colnames[colinfo->leftattnos[i] - 1];
4631 else if (colinfo->rightattnos[i] > 0)
4632 real_colname = rightcolinfo->colnames[colinfo->rightattnos[i] - 1];
4633 else
4634 {
4635 /* We're joining system columns --- use eref name */
4636 real_colname = strVal(list_nth(rte->eref->colnames, i));
4637 }
4638
4639 /* If child col has been dropped, no need to assign a join colname */
4640 if (real_colname == NULL)
4641 {
4642 colinfo->colnames[i] = NULL;
4643 continue;
4644 }
4645
4646 /* In an unnamed join, just report child column names as-is */
4647 if (rte->alias == NULL)
4648 {
4649 colinfo->colnames[i] = real_colname;
4650 add_to_names_hash(colinfo, real_colname);
4651 continue;
4652 }
4653
4654 /* If alias already assigned, that's what to use */
4655 if (colname == NULL)
4656 {
4657 /* If user wrote an alias, prefer that over real column name */
4658 if (rte->alias && i < list_length(rte->alias->colnames))
4659 colname = strVal(list_nth(rte->alias->colnames, i));
4660 else
4661 colname = real_colname;
4662
4663 /* Unique-ify and insert into colinfo */
4664 colname = make_colname_unique(colname, dpns, colinfo);
4665
4666 colinfo->colnames[i] = colname;
4667 add_to_names_hash(colinfo, colname);
4668 }
4669
4670 /* Remember if any assigned aliases differ from "real" name */
4671 if (!changed_any && strcmp(colname, real_colname) != 0)
4672 changed_any = true;
4673 }
4674
4675 /*
4676 * Calculate number of columns the join would have if it were re-parsed
4677 * now, and create storage for the new_colnames and is_new_col arrays.
4678 *
4679 * Note: colname_is_unique will be consulting new_colnames[] during the
4680 * loops below, so its not-yet-filled entries must be zeroes.
4681 */
4682 nnewcolumns = leftcolinfo->num_new_cols + rightcolinfo->num_new_cols -
4683 list_length(colinfo->usingNames);
4684 colinfo->num_new_cols = nnewcolumns;
4685 colinfo->new_colnames = (char **) palloc0(nnewcolumns * sizeof(char *));
4686 colinfo->is_new_col = (bool *) palloc0(nnewcolumns * sizeof(bool));
4687
4688 /*
4689 * Generating the new_colnames array is a bit tricky since any new columns
4690 * added since parse time must be inserted in the right places. This code
4691 * must match the parser, which will order a join's columns as merged
4692 * columns first (in USING-clause order), then non-merged columns from the
4693 * left input (in attnum order), then non-merged columns from the right
4694 * input (ditto). If one of the inputs is itself a join, its columns will
4695 * be ordered according to the same rule, which means newly-added columns
4696 * might not be at the end. We can figure out what's what by consulting
4697 * the leftattnos and rightattnos arrays plus the input is_new_col arrays.
4698 *
4699 * In these loops, i indexes leftattnos/rightattnos (so it's join varattno
4700 * less one), j indexes new_colnames/is_new_col, and ic/jc have similar
4701 * meanings for the current child RTE.
4702 */
4703
4704 /* Handle merged columns; they are first and can't be new */
4705 i = j = 0;
4706 while (i < noldcolumns &&
4707 colinfo->leftattnos[i] != 0 &&
4708 colinfo->rightattnos[i] != 0)
4709 {
4710 /* column name is already determined and known unique */
4711 colinfo->new_colnames[j] = colinfo->colnames[i];
4712 colinfo->is_new_col[j] = false;
4713
4714 /* build bitmapsets of child attnums of merged columns */
4715 if (colinfo->leftattnos[i] > 0)
4716 leftmerged = bms_add_member(leftmerged, colinfo->leftattnos[i]);
4717 if (colinfo->rightattnos[i] > 0)
4718 rightmerged = bms_add_member(rightmerged, colinfo->rightattnos[i]);
4719
4720 i++, j++;
4721 }
4722
4723 /* Handle non-merged left-child columns */
4724 ic = 0;
4725 for (jc = 0; jc < leftcolinfo->num_new_cols; jc++)
4726 {
4727 char *child_colname = leftcolinfo->new_colnames[jc];
4728
4729 if (!leftcolinfo->is_new_col[jc])
4730 {
4731 /* Advance ic to next non-dropped old column of left child */
4732 while (ic < leftcolinfo->num_cols &&
4733 leftcolinfo->colnames[ic] == NULL)
4734 ic++;
4735 Assert(ic < leftcolinfo->num_cols);
4736 ic++;
4737 /* If it is a merged column, we already processed it */
4738 if (bms_is_member(ic, leftmerged))
4739 continue;
4740 /* Else, advance i to the corresponding existing join column */
4741 while (i < colinfo->num_cols &&
4742 colinfo->colnames[i] == NULL)
4743 i++;
4744 Assert(i < colinfo->num_cols);
4745 Assert(ic == colinfo->leftattnos[i]);
4746 /* Use the already-assigned name of this column */
4747 colinfo->new_colnames[j] = colinfo->colnames[i];
4748 i++;
4749 }
4750 else
4751 {
4752 /*
4753 * Unique-ify the new child column name and assign, unless we're
4754 * in an unnamed join, in which case just copy
4755 */
4756 if (rte->alias != NULL)
4757 {
4758 colinfo->new_colnames[j] =
4759 make_colname_unique(child_colname, dpns, colinfo);
4760 if (!changed_any &&
4761 strcmp(colinfo->new_colnames[j], child_colname) != 0)
4762 changed_any = true;
4763 }
4764 else
4765 colinfo->new_colnames[j] = child_colname;
4766 add_to_names_hash(colinfo, colinfo->new_colnames[j]);
4767 }
4768
4769 colinfo->is_new_col[j] = leftcolinfo->is_new_col[jc];
4770 j++;
4771 }
4772
4773 /* Handle non-merged right-child columns in exactly the same way */
4774 ic = 0;
4775 for (jc = 0; jc < rightcolinfo->num_new_cols; jc++)
4776 {
4777 char *child_colname = rightcolinfo->new_colnames[jc];
4778
4779 if (!rightcolinfo->is_new_col[jc])
4780 {
4781 /* Advance ic to next non-dropped old column of right child */
4782 while (ic < rightcolinfo->num_cols &&
4783 rightcolinfo->colnames[ic] == NULL)
4784 ic++;
4785 Assert(ic < rightcolinfo->num_cols);
4786 ic++;
4787 /* If it is a merged column, we already processed it */
4788 if (bms_is_member(ic, rightmerged))
4789 continue;
4790 /* Else, advance i to the corresponding existing join column */
4791 while (i < colinfo->num_cols &&
4792 colinfo->colnames[i] == NULL)
4793 i++;
4794 Assert(i < colinfo->num_cols);
4795 Assert(ic == colinfo->rightattnos[i]);
4796 /* Use the already-assigned name of this column */
4797 colinfo->new_colnames[j] = colinfo->colnames[i];
4798 i++;
4799 }
4800 else
4801 {
4802 /*
4803 * Unique-ify the new child column name and assign, unless we're
4804 * in an unnamed join, in which case just copy
4805 */
4806 if (rte->alias != NULL)
4807 {
4808 colinfo->new_colnames[j] =
4809 make_colname_unique(child_colname, dpns, colinfo);
4810 if (!changed_any &&
4811 strcmp(colinfo->new_colnames[j], child_colname) != 0)
4812 changed_any = true;
4813 }
4814 else
4815 colinfo->new_colnames[j] = child_colname;
4816 add_to_names_hash(colinfo, colinfo->new_colnames[j]);
4817 }
4818
4819 colinfo->is_new_col[j] = rightcolinfo->is_new_col[jc];
4820 j++;
4821 }
4822
4823 /* Assert we processed the right number of columns */
4824 #ifdef USE_ASSERT_CHECKING
4825 while (i < colinfo->num_cols && colinfo->colnames[i] == NULL)
4826 i++;
4827 Assert(i == colinfo->num_cols);
4828 Assert(j == nnewcolumns);
4829 #endif
4830
4831 /* We're now done needing the colinfo's names_hash */
4832 destroy_colinfo_names_hash(colinfo);
4833
4834 /*
4835 * For a named join, print column aliases if we changed any from the child
4836 * names. Unnamed joins cannot print aliases.
4837 */
4838 if (rte->alias != NULL)
4839 colinfo->printaliases = changed_any;
4840 else
4841 colinfo->printaliases = false;
4842 }
4843
4844 /*
4845 * colname_is_unique: is colname distinct from already-chosen column names?
4846 *
4847 * dpns is query-wide info, colinfo is for the column's RTE
4848 */
4849 static bool
4850 colname_is_unique(const char *colname, deparse_namespace *dpns,
4851 deparse_columns *colinfo)
4852 {
4853 int i;
4854 ListCell *lc;
4855
4856 /*
4857 * If we have a hash table, consult that instead of linearly scanning the
4858 * colinfo's strings.
4859 */
4860 if (colinfo->names_hash)
4861 {
4862 if (hash_search(colinfo->names_hash,
4863 colname,
4864 HASH_FIND,
4865 NULL) != NULL)
4866 return false;
4867 }
4868 else
4869 {
4870 /* Check against already-assigned column aliases within RTE */
4871 for (i = 0; i < colinfo->num_cols; i++)
4872 {
4873 char *oldname = colinfo->colnames[i];
4874
4875 if (oldname && strcmp(oldname, colname) == 0)
4876 return false;
4877 }
4878
4879 /*
4880 * If we're building a new_colnames array, check that too (this will
4881 * be partially but not completely redundant with the previous checks)
4882 */
4883 for (i = 0; i < colinfo->num_new_cols; i++)
4884 {
4885 char *oldname = colinfo->new_colnames[i];
4886
4887 if (oldname && strcmp(oldname, colname) == 0)
4888 return false;
4889 }
4890
4891 /*
4892 * Also check against names already assigned for parent-join USING
4893 * cols
4894 */
4895 foreach(lc, colinfo->parentUsing)
4896 {
4897 char *oldname = (char *) lfirst(lc);
4898
4899 if (strcmp(oldname, colname) == 0)
4900 return false;
4901 }
4902 }
4903
4904 /*
4905 * Also check against USING-column names that must be globally unique.
4906 * These are not hashed, but there should be few of them.
4907 */
4908 foreach(lc, dpns->using_names)
4909 {
4910 char *oldname = (char *) lfirst(lc);
4911
4912 if (strcmp(oldname, colname) == 0)
4913 return false;
4914 }
4915
4916 return true;
4917 }
4918
4919 /*
4920 * make_colname_unique: modify colname if necessary to make it unique
4921 *
4922 * dpns is query-wide info, colinfo is for the column's RTE
4923 */
4924 static char *
4925 make_colname_unique(char *colname, deparse_namespace *dpns,
4926 deparse_columns *colinfo)
4927 {
4928 /*
4929 * If the selected name isn't unique, append digits to make it so. For a
4930 * very long input name, we might have to truncate to stay within
4931 * NAMEDATALEN.
4932 */
4933 if (!colname_is_unique(colname, dpns, colinfo))
4934 {
4935 int colnamelen = strlen(colname);
4936 char *modname = (char *) palloc(colnamelen + 16);
4937 int i = 0;
4938
4939 do
4940 {
4941 i++;
4942 for (;;)
4943 {
4944 memcpy(modname, colname, colnamelen);
4945 sprintf(modname + colnamelen, "_%d", i);
4946 if (strlen(modname) < NAMEDATALEN)
4947 break;
4948 /* drop chars from colname to keep all the digits */
4949 colnamelen = pg_mbcliplen(colname, colnamelen,
4950 colnamelen - 1);
4951 }
4952 } while (!colname_is_unique(modname, dpns, colinfo));
4953 colname = modname;
4954 }
4955 return colname;
4956 }
4957
4958 /*
4959 * expand_colnames_array_to: make colinfo->colnames at least n items long
4960 *
4961 * Any added array entries are initialized to zero.
4962 */
4963 static void
4964 expand_colnames_array_to(deparse_columns *colinfo, int n)
4965 {
4966 if (n > colinfo->num_cols)
4967 {
4968 if (colinfo->colnames == NULL)
4969 colinfo->colnames = palloc0_array(char *, n);
4970 else
4971 colinfo->colnames = repalloc0_array(colinfo->colnames, char *, colinfo->num_cols, n);
4972 colinfo->num_cols = n;
4973 }
4974 }
4975
4976 /*
4977 * build_colinfo_names_hash: optionally construct a hash table for colinfo
4978 */
4979 static void
4980 build_colinfo_names_hash(deparse_columns *colinfo)
4981 {
4982 HASHCTL hash_ctl;
4983 int i;
4984 ListCell *lc;
4985
4986 /*
4987 * Use a hash table only for RTEs with at least 32 columns. (The cutoff
4988 * is somewhat arbitrary, but let's choose it so that this code does get
4989 * exercised in the regression tests.)
4990 */
4991 if (colinfo->num_cols < 32)
4992 return;
4993
4994 /*
4995 * Set up the hash table. The entries are just strings with no other
4996 * payload.
4997 */
4998 hash_ctl.keysize = NAMEDATALEN;
4999 hash_ctl.entrysize = NAMEDATALEN;
5000 hash_ctl.hcxt = CurrentMemoryContext;
5001 colinfo->names_hash = hash_create("deparse_columns names",
5002 colinfo->num_cols + colinfo->num_new_cols,
5003 &hash_ctl,
5004 HASH_ELEM | HASH_STRINGS | HASH_CONTEXT);
5005
5006 /*
5007 * Preload the hash table with any names already present (these would have
5008 * come from set_using_names).
5009 */
5010 for (i = 0; i < colinfo->num_cols; i++)
5011 {
5012 char *oldname = colinfo->colnames[i];
5013
5014 if (oldname)
5015 add_to_names_hash(colinfo, oldname);
5016 }
5017
5018 for (i = 0; i < colinfo->num_new_cols; i++)
5019 {
5020 char *oldname = colinfo->new_colnames[i];
5021
5022 if (oldname)
5023 add_to_names_hash(colinfo, oldname);
5024 }
5025
5026 foreach(lc, colinfo->parentUsing)
5027 {
5028 char *oldname = (char *) lfirst(lc);
5029
5030 add_to_names_hash(colinfo, oldname);
5031 }
5032 }
5033
5034 /*
5035 * add_to_names_hash: add a string to the names_hash, if we're using one
5036 */
5037 static void
5038 add_to_names_hash(deparse_columns *colinfo, const char *name)
5039 {
5040 if (colinfo->names_hash)
5041 (void) hash_search(colinfo->names_hash,
5042 name,
5043 HASH_ENTER,
5044 NULL);
5045 }
5046
5047 /*
5048 * destroy_colinfo_names_hash: destroy hash table when done with it
5049 */
5050 static void
5051 destroy_colinfo_names_hash(deparse_columns *colinfo)
5052 {
5053 if (colinfo->names_hash)
5054 {
5055 hash_destroy(colinfo->names_hash);
5056 colinfo->names_hash = NULL;
5057 }
5058 }
5059
5060 /*
5061 * identify_join_columns: figure out where columns of a join come from
5062 *
5063 * Fills the join-specific fields of the colinfo struct, except for
5064 * usingNames which is filled later.
5065 */
5066 static void
5067 identify_join_columns(JoinExpr *j, RangeTblEntry *jrte,
5068 deparse_columns *colinfo)
5069 {
5070 int numjoincols;
5071 int jcolno;
5072 int rcolno;
5073 ListCell *lc;
5074
5075 /* Extract left/right child RT indexes */
5076 if (IsA(j->larg, RangeTblRef))
5077 colinfo->leftrti = ((RangeTblRef *) j->larg)->rtindex;
5078 else if (IsA(j->larg, JoinExpr))
5079 colinfo->leftrti = ((JoinExpr *) j->larg)->rtindex;
5080 else
5081 elog(ERROR, "unrecognized node type in jointree: %d",
5082 (int) nodeTag(j->larg));
5083 if (IsA(j->rarg, RangeTblRef))
5084 colinfo->rightrti = ((RangeTblRef *) j->rarg)->rtindex;
5085 else if (IsA(j->rarg, JoinExpr))
5086 colinfo->rightrti = ((JoinExpr *) j->rarg)->rtindex;
5087 else
5088 elog(ERROR, "unrecognized node type in jointree: %d",
5089 (int) nodeTag(j->rarg));
5090
5091 /* Assert children will be processed earlier than join in second pass */
5092 Assert(colinfo->leftrti < j->rtindex);
5093 Assert(colinfo->rightrti < j->rtindex);
5094
5095 /* Initialize result arrays with zeroes */
5096 numjoincols = list_length(jrte->joinaliasvars);
5097 Assert(numjoincols == list_length(jrte->eref->colnames));
5098 colinfo->leftattnos = (int *) palloc0(numjoincols * sizeof(int));
5099 colinfo->rightattnos = (int *) palloc0(numjoincols * sizeof(int));
5100
5101 /*
5102 * Deconstruct RTE's joinleftcols/joinrightcols into desired format.
5103 * Recall that the column(s) merged due to USING are the first column(s)
5104 * of the join output. We need not do anything special while scanning
5105 * joinleftcols, but while scanning joinrightcols we must distinguish
5106 * merged from unmerged columns.
5107 */
5108 jcolno = 0;
5109 foreach(lc, jrte->joinleftcols)
5110 {
5111 int leftattno = lfirst_int(lc);
5112
5113 colinfo->leftattnos[jcolno++] = leftattno;
5114 }
5115 rcolno = 0;
5116 foreach(lc, jrte->joinrightcols)
5117 {
5118 int rightattno = lfirst_int(lc);
5119
5120 if (rcolno < jrte->joinmergedcols) /* merged column? */
5121 colinfo->rightattnos[rcolno] = rightattno;
5122 else
5123 colinfo->rightattnos[jcolno++] = rightattno;
5124 rcolno++;
5125 }
5126 Assert(jcolno == numjoincols);
5127 }
5128
5129 /*
5130 * get_rtable_name: convenience function to get a previously assigned RTE alias
5131 *
5132 * The RTE must belong to the topmost namespace level in "context".
5133 */
5134 static char *
5135 get_rtable_name(int rtindex, deparse_context *context)
5136 {
5137 deparse_namespace *dpns = (deparse_namespace *) linitial(context->namespaces);
5138
5139 Assert(rtindex > 0 && rtindex <= list_length(dpns->rtable_names));
5140 return (char *) list_nth(dpns->rtable_names, rtindex - 1);
5141 }
5142
5143 /*
5144 * set_deparse_plan: set up deparse_namespace to parse subexpressions
5145 * of a given Plan node
5146 *
5147 * This sets the plan, outer_plan, inner_plan, outer_tlist, inner_tlist,
5148 * and index_tlist fields. Caller must already have adjusted the ancestors
5149 * list if necessary. Note that the rtable, subplans, and ctes fields do
5150 * not need to change when shifting attention to different plan nodes in a
5151 * single plan tree.
5152 */
5153 static void
5154 set_deparse_plan(deparse_namespace *dpns, Plan *plan)
5155 {
5156 dpns->plan = plan;
5157
5158 /*
5159 * We special-case Append and MergeAppend to pretend that the first child
5160 * plan is the OUTER referent; we have to interpret OUTER Vars in their
5161 * tlists according to one of the children, and the first one is the most
5162 * natural choice.
5163 */
5164 if (IsA(plan, Append))
5165 dpns->outer_plan = linitial(((Append *) plan)->appendplans);
5166 else if (IsA(plan, MergeAppend))
5167 dpns->outer_plan = linitial(((MergeAppend *) plan)->mergeplans);
5168 else
5169 dpns->outer_plan = outerPlan(plan);
5170
5171 if (dpns->outer_plan)
5172 dpns->outer_tlist = dpns->outer_plan->targetlist;
5173 else
5174 dpns->outer_tlist = NIL;
5175
5176 /*
5177 * For a SubqueryScan, pretend the subplan is INNER referent. (We don't
5178 * use OUTER because that could someday conflict with the normal meaning.)
5179 * Likewise, for a CteScan, pretend the subquery's plan is INNER referent.
5180 * For a WorkTableScan, locate the parent RecursiveUnion plan node and use
5181 * that as INNER referent.
5182 *
5183 * For MERGE, pretend the ModifyTable's source plan (its outer plan) is
5184 * INNER referent. This is the join from the target relation to the data
5185 * source, and all INNER_VAR Vars in other parts of the query refer to its
5186 * targetlist.
5187 *
5188 * For ON CONFLICT .. UPDATE we just need the inner tlist to point to the
5189 * excluded expression's tlist. (Similar to the SubqueryScan we don't want
5190 * to reuse OUTER, it's used for RETURNING in some modify table cases,
5191 * although not INSERT .. CONFLICT).
5192 */
5193 if (IsA(plan, SubqueryScan))
5194 dpns->inner_plan = ((SubqueryScan *) plan)->subplan;
5195 else if (IsA(plan, CteScan))
5196 dpns->inner_plan = list_nth(dpns->subplans,
5197 ((CteScan *) plan)->ctePlanId - 1);
5198 else if (IsA(plan, WorkTableScan))
5199 dpns->inner_plan = find_recursive_union(dpns,
5200 (WorkTableScan *) plan);
5201 else if (IsA(plan, ModifyTable))
5202 {
5203 if (((ModifyTable *) plan)->operation == CMD_MERGE)
5204 dpns->inner_plan = outerPlan(plan);
5205 else
5206 dpns->inner_plan = plan;
5207 }
5208 else
5209 dpns->inner_plan = innerPlan(plan);
5210
5211 if (IsA(plan, ModifyTable) && ((ModifyTable *) plan)->operation == CMD_INSERT)
5212 dpns->inner_tlist = ((ModifyTable *) plan)->exclRelTlist;
5213 else if (dpns->inner_plan)
5214 dpns->inner_tlist = dpns->inner_plan->targetlist;
5215 else
5216 dpns->inner_tlist = NIL;
5217
5218 /* Set up referent for INDEX_VAR Vars, if needed */
5219 if (IsA(plan, IndexOnlyScan))
5220 dpns->index_tlist = ((IndexOnlyScan *) plan)->indextlist;
5221 else if (IsA(plan, ForeignScan))
5222 dpns->index_tlist = ((ForeignScan *) plan)->fdw_scan_tlist;
5223 else if (IsA(plan, CustomScan))
5224 dpns->index_tlist = ((CustomScan *) plan)->custom_scan_tlist;
5225 else
5226 dpns->index_tlist = NIL;
5227 }
5228
5229 /*
5230 * Locate the ancestor plan node that is the RecursiveUnion generating
5231 * the WorkTableScan's work table. We can match on wtParam, since that
5232 * should be unique within the plan tree.
5233 */
5234 static Plan *
5235 find_recursive_union(deparse_namespace *dpns, WorkTableScan *wtscan)
5236 {
5237 ListCell *lc;
5238
5239 foreach(lc, dpns->ancestors)
5240 {
5241 Plan *ancestor = (Plan *) lfirst(lc);
5242
5243 if (IsA(ancestor, RecursiveUnion) &&
5244 ((RecursiveUnion *) ancestor)->wtParam == wtscan->wtParam)
5245 return ancestor;
5246 }
5247 elog(ERROR, "could not find RecursiveUnion for WorkTableScan with wtParam %d",
5248 wtscan->wtParam);
5249 return NULL;
5250 }
5251
5252 /*
5253 * push_child_plan: temporarily transfer deparsing attention to a child plan
5254 *
5255 * When expanding an OUTER_VAR or INNER_VAR reference, we must adjust the
5256 * deparse context in case the referenced expression itself uses
5257 * OUTER_VAR/INNER_VAR. We modify the top stack entry in-place to avoid
5258 * affecting levelsup issues (although in a Plan tree there really shouldn't
5259 * be any).
5260 *
5261 * Caller must provide a local deparse_namespace variable to save the
5262 * previous state for pop_child_plan.
5263 */
5264 static void
5265 push_child_plan(deparse_namespace *dpns, Plan *plan,
5266 deparse_namespace *save_dpns)
5267 {
5268 /* Save state for restoration later */
5269 *save_dpns = *dpns;
5270
5271 /* Link current plan node into ancestors list */
5272 dpns->ancestors = lcons(dpns->plan, dpns->ancestors);
5273
5274 /* Set attention on selected child */
5275 set_deparse_plan(dpns, plan);
5276 }
5277
5278 /*
5279 * pop_child_plan: undo the effects of push_child_plan
5280 */
5281 static void
5282 pop_child_plan(deparse_namespace *dpns, deparse_namespace *save_dpns)
5283 {
5284 List *ancestors;
5285
5286 /* Get rid of ancestors list cell added by push_child_plan */
5287 ancestors = list_delete_first(dpns->ancestors);
5288
5289 /* Restore fields changed by push_child_plan */
5290 *dpns = *save_dpns;
5291
5292 /* Make sure dpns->ancestors is right (may be unnecessary) */
5293 dpns->ancestors = ancestors;
5294 }
5295
5296 /*
5297 * push_ancestor_plan: temporarily transfer deparsing attention to an
5298 * ancestor plan
5299 *
5300 * When expanding a Param reference, we must adjust the deparse context
5301 * to match the plan node that contains the expression being printed;
5302 * otherwise we'd fail if that expression itself contains a Param or
5303 * OUTER_VAR/INNER_VAR/INDEX_VAR variable.
5304 *
5305 * The target ancestor is conveniently identified by the ListCell holding it
5306 * in dpns->ancestors.
5307 *
5308 * Caller must provide a local deparse_namespace variable to save the
5309 * previous state for pop_ancestor_plan.
5310 */
5311 static void
5312 push_ancestor_plan(deparse_namespace *dpns, ListCell *ancestor_cell,
5313 deparse_namespace *save_dpns)
5314 {
5315 Plan *plan = (Plan *) lfirst(ancestor_cell);
5316
5317 /* Save state for restoration later */
5318 *save_dpns = *dpns;
5319
5320 /* Build a new ancestor list with just this node's ancestors */
5321 dpns->ancestors =
5322 list_copy_tail(dpns->ancestors,
5323 list_cell_number(dpns->ancestors, ancestor_cell) + 1);
5324
5325 /* Set attention on selected ancestor */
5326 set_deparse_plan(dpns, plan);
5327 }
5328
5329 /*
5330 * pop_ancestor_plan: undo the effects of push_ancestor_plan
5331 */
5332 static void
5333 pop_ancestor_plan(deparse_namespace *dpns, deparse_namespace *save_dpns)
5334 {
5335 /* Free the ancestor list made in push_ancestor_plan */
5336 list_free(dpns->ancestors);
5337
5338 /* Restore fields changed by push_ancestor_plan */
5339 *dpns = *save_dpns;
5340 }
5341
5342
5343 /* ----------
5344 * make_ruledef - reconstruct the CREATE RULE command
5345 * for a given pg_rewrite tuple
5346 * ----------
5347 */
5348 static void
5349 make_ruledef(StringInfo buf, HeapTuple ruletup, TupleDesc rulettc,
5350 int prettyFlags)
5351 {
5352 char *rulename;
5353 char ev_type;
5354 Oid ev_class;
5355 bool is_instead;
5356 char *ev_qual;
5357 char *ev_action;
5358 List *actions;
5359 Relation ev_relation;
5360 TupleDesc viewResultDesc = NULL;
5361 int fno;
5362 Datum dat;
5363 bool isnull;
5364
5365 /*
5366 * Get the attribute values from the rules tuple
5367 */
5368 fno = SPI_fnumber(rulettc, "rulename");
5369 dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
5370 Assert(!isnull);
5371 rulename = NameStr(*(DatumGetName(dat)));
5372
5373 fno = SPI_fnumber(rulettc, "ev_type");
5374 dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
5375 Assert(!isnull);
5376 ev_type = DatumGetChar(dat);
5377
5378 fno = SPI_fnumber(rulettc, "ev_class");
5379 dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
5380 Assert(!isnull);
5381 ev_class = DatumGetObjectId(dat);
5382
5383 fno = SPI_fnumber(rulettc, "is_instead");
5384 dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
5385 Assert(!isnull);
5386 is_instead = DatumGetBool(dat);
5387
5388 fno = SPI_fnumber(rulettc, "ev_qual");
5389 ev_qual = SPI_getvalue(ruletup, rulettc, fno);
5390 Assert(ev_qual != NULL);
5391
5392 fno = SPI_fnumber(rulettc, "ev_action");
5393 ev_action = SPI_getvalue(ruletup, rulettc, fno);
5394 Assert(ev_action != NULL);
5395 actions = (List *) stringToNode(ev_action);
5396 if (actions == NIL)
5397 elog(ERROR, "invalid empty ev_action list");
5398
5399 ev_relation = table_open(ev_class, AccessShareLock);
5400
5401 /*
5402 * Build the rules definition text
5403 */
5404 appendStringInfo(buf, "CREATE RULE %s AS",
5405 quote_identifier(rulename));
5406
5407 if (prettyFlags & PRETTYFLAG_INDENT)
5408 appendStringInfoString(buf, "\n ON ");
5409 else
5410 appendStringInfoString(buf, " ON ");
5411
5412 /* The event the rule is fired for */
5413 switch (ev_type)
5414 {
5415 case '1':
5416 appendStringInfoString(buf, "SELECT");
5417 viewResultDesc = RelationGetDescr(ev_relation);
5418 break;
5419
5420 case '2':
5421 appendStringInfoString(buf, "UPDATE");
5422 break;
5423
5424 case '3':
5425 appendStringInfoString(buf, "INSERT");
5426 break;
5427
5428 case '4':
5429 appendStringInfoString(buf, "DELETE");
5430 break;
5431
5432 default:
5433 ereport(ERROR,
5434 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5435 errmsg("rule \"%s\" has unsupported event type %d",
5436 rulename, ev_type)));
5437 break;
5438 }
5439
5440 /* The relation the rule is fired on */
5441 appendStringInfo(buf, " TO %s",
5442 (prettyFlags & PRETTYFLAG_SCHEMA) ?
5443 generate_relation_name(ev_class, NIL) :
5444 generate_qualified_relation_name(ev_class));
5445
5446 /* If the rule has an event qualification, add it */
5447 if (strcmp(ev_qual, "<>") != 0)
5448 {
5449 Node *qual;
5450 Query *query;
5451 deparse_context context;
5452 deparse_namespace dpns;
5453
5454 if (prettyFlags & PRETTYFLAG_INDENT)
5455 appendStringInfoString(buf, "\n ");
5456 appendStringInfoString(buf, " WHERE ");
5457
5458 qual = stringToNode(ev_qual);
5459
5460 /*
5461 * We need to make a context for recognizing any Vars in the qual
5462 * (which can only be references to OLD and NEW). Use the rtable of
5463 * the first query in the action list for this purpose.
5464 */
5465 query = (Query *) linitial(actions);
5466
5467 /*
5468 * If the action is INSERT...SELECT, OLD/NEW have been pushed down
5469 * into the SELECT, and that's what we need to look at. (Ugly kluge
5470 * ... try to fix this when we redesign querytrees.)
5471 */
5472 query = getInsertSelectQuery(query, NULL);
5473
5474 /* Must acquire locks right away; see notes in get_query_def() */
5475 AcquireRewriteLocks(query, false, false);
5476
5477 context.buf = buf;
5478 context.namespaces = list_make1(&dpns);
5479 context.resultDesc = NULL;
5480 context.targetList = NIL;
5481 context.windowClause = NIL;
5482 context.varprefix = (list_length(query->rtable) != 1);
5483 context.prettyFlags = prettyFlags;
5484 context.wrapColumn = WRAP_COLUMN_DEFAULT;
5485 context.indentLevel = PRETTYINDENT_STD;
5486 context.colNamesVisible = true;
5487 context.inGroupBy = false;
5488 context.varInOrderBy = false;
5489 context.appendparents = NULL;
5490
5491 set_deparse_for_query(&dpns, query, NIL);
5492
5493 get_rule_expr(qual, &context, false);
5494 }
5495
5496 appendStringInfoString(buf, " DO ");
5497
5498 /* The INSTEAD keyword (if so) */
5499 if (is_instead)
5500 appendStringInfoString(buf, "INSTEAD ");
5501
5502 /* Finally the rules actions */
5503 if (list_length(actions) > 1)
5504 {
5505 ListCell *action;
5506 Query *query;
5507
5508 appendStringInfoChar(buf, '(');
5509 foreach(action, actions)
5510 {
5511 query = (Query *) lfirst(action);
5512 get_query_def(query, buf, NIL, viewResultDesc, true,
5513 prettyFlags, WRAP_COLUMN_DEFAULT, 0);
5514 if (prettyFlags)
5515 appendStringInfoString(buf, ";\n");
5516 else
5517 appendStringInfoString(buf, "; ");
5518 }
5519 appendStringInfoString(buf, ");");
5520 }
5521 else
5522 {
5523 Query *query;
5524
5525 query = (Query *) linitial(actions);
5526 get_query_def(query, buf, NIL, viewResultDesc, true,
5527 prettyFlags, WRAP_COLUMN_DEFAULT, 0);
5528 appendStringInfoChar(buf, ';');
5529 }
5530
5531 table_close(ev_relation, AccessShareLock);
5532 }
5533
5534
5535 /* ----------
5536 * make_viewdef - reconstruct the SELECT part of a
5537 * view rewrite rule
5538 * ----------
5539 */
5540 static void
5541 make_viewdef(StringInfo buf, HeapTuple ruletup, TupleDesc rulettc,
5542 int prettyFlags, int wrapColumn)
5543 {
5544 Query *query;
5545 char ev_type;
5546 Oid ev_class;
5547 bool is_instead;
5548 char *ev_qual;
5549 char *ev_action;
5550 List *actions;
5551 Relation ev_relation;
5552 int fno;
5553 Datum dat;
5554 bool isnull;
5555
5556 /*
5557 * Get the attribute values from the rules tuple
5558 */
5559 fno = SPI_fnumber(rulettc, "ev_type");
5560 dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
5561 Assert(!isnull);
5562 ev_type = DatumGetChar(dat);
5563
5564 fno = SPI_fnumber(rulettc, "ev_class");
5565 dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
5566 Assert(!isnull);
5567 ev_class = DatumGetObjectId(dat);
5568
5569 fno = SPI_fnumber(rulettc, "is_instead");
5570 dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
5571 Assert(!isnull);
5572 is_instead = DatumGetBool(dat);
5573
5574 fno = SPI_fnumber(rulettc, "ev_qual");
5575 ev_qual = SPI_getvalue(ruletup, rulettc, fno);
5576 Assert(ev_qual != NULL);
5577
5578 fno = SPI_fnumber(rulettc, "ev_action");
5579 ev_action = SPI_getvalue(ruletup, rulettc, fno);
5580 Assert(ev_action != NULL);
5581 actions = (List *) stringToNode(ev_action);
5582
5583 if (list_length(actions) != 1)
5584 {
5585 /* keep output buffer empty and leave */
5586 return;
5587 }
5588
5589 query = (Query *) linitial(actions);
5590
5591 if (ev_type != '1' || !is_instead ||
5592 strcmp(ev_qual, "<>") != 0 || query->commandType != CMD_SELECT)
5593 {
5594 /* keep output buffer empty and leave */
5595 return;
5596 }
5597
5598 ev_relation = table_open(ev_class, AccessShareLock);
5599
5600 get_query_def(query, buf, NIL, RelationGetDescr(ev_relation), true,
5601 prettyFlags, wrapColumn, 0);
5602 appendStringInfoChar(buf, ';');
5603
5604 table_close(ev_relation, AccessShareLock);
5605 }
5606
5607
5608 /* ----------
5609 * get_query_def - Parse back one query parsetree
5610 *
5611 * query: parsetree to be displayed
5612 * buf: output text is appended to buf
5613 * parentnamespace: list (initially empty) of outer-level deparse_namespace's
5614 * resultDesc: if not NULL, the output tuple descriptor for the view
5615 * represented by a SELECT query. We use the column names from it
5616 * to label SELECT output columns, in preference to names in the query
5617 * colNamesVisible: true if the surrounding context cares about the output
5618 * column names at all (as, for example, an EXISTS() context does not);
5619 * when false, we can suppress dummy column labels such as "?column?"
5620 * prettyFlags: bitmask of PRETTYFLAG_XXX options
5621 * wrapColumn: maximum line length, or -1 to disable wrapping
5622 * startIndent: initial indentation amount
5623 * ----------
5624 */
5625 static void
5626 get_query_def(Query *query, StringInfo buf, List *parentnamespace,
5627 TupleDesc resultDesc, bool colNamesVisible,
5628 int prettyFlags, int wrapColumn, int startIndent)
5629 {
5630 deparse_context context;
5631 deparse_namespace dpns;
5632 int rtable_size;
5633
5634 /* Guard against excessively long or deeply-nested queries */
5635 CHECK_FOR_INTERRUPTS();
5636 check_stack_depth();
5637
5638 rtable_size = query->hasGroupRTE ?
5639 list_length(query->rtable) - 1 :
5640 list_length(query->rtable);
5641
5642 /*
5643 * Replace any Vars in the query's targetlist and havingQual that
5644 * reference GROUP outputs with the underlying grouping expressions.
5645 */
5646 if (query->hasGroupRTE)
5647 {
5648 query->targetList = (List *)
5649 flatten_group_exprs(NULL, query, (Node *) query->targetList);
5650 query->havingQual =
5651 flatten_group_exprs(NULL, query, query->havingQual);
5652 }
5653
5654 /*
5655 * Before we begin to examine the query, acquire locks on referenced
5656 * relations, and fix up deleted columns in JOIN RTEs. This ensures
5657 * consistent results. Note we assume it's OK to scribble on the passed
5658 * querytree!
5659 *
5660 * We are only deparsing the query (we are not about to execute it), so we
5661 * only need AccessShareLock on the relations it mentions.
5662 */
5663 AcquireRewriteLocks(query, false, false);
5664
5665 context.buf = buf;
5666 context.namespaces = lcons(&dpns, list_copy(parentnamespace));
5667 context.resultDesc = NULL;
5668 context.targetList = NIL;
5669 context.windowClause = NIL;
5670 context.varprefix = (parentnamespace != NIL ||
5671 rtable_size != 1);
5672 context.prettyFlags = prettyFlags;
5673 context.wrapColumn = wrapColumn;
5674 context.indentLevel = startIndent;
5675 context.colNamesVisible = colNamesVisible;
5676 context.inGroupBy = false;
5677 context.varInOrderBy = false;
5678 context.appendparents = NULL;
5679
5680 set_deparse_for_query(&dpns, query, parentnamespace);
5681
5682 switch (query->commandType)
5683 {
5684 case CMD_SELECT:
5685 /* We set context.resultDesc only if it's a SELECT */
5686 context.resultDesc = resultDesc;
5687 get_select_query_def(query, &context);
5688 break;
5689
5690 case CMD_UPDATE:
5691 get_update_query_def(query, &context);
5692 break;
5693
5694 case CMD_INSERT:
5695 get_insert_query_def(query, &context);
5696 break;
5697
5698 case CMD_DELETE:
5699 get_delete_query_def(query, &context);
5700 break;
5701
5702 case CMD_MERGE:
5703 get_merge_query_def(query, &context);
5704 break;
5705
5706 case CMD_NOTHING:
5707 appendStringInfoString(buf, "NOTHING");
5708 break;
5709
5710 case CMD_UTILITY:
5711 get_utility_query_def(query, &context);
5712 break;
5713
5714 default:
5715 elog(ERROR, "unrecognized query command type: %d",
5716 query->commandType);
5717 break;
5718 }
5719 }
5720
5721 /* ----------
5722 * get_values_def - Parse back a VALUES list
5723 * ----------
5724 */
5725 static void
5726 get_values_def(List *values_lists, deparse_context *context)
5727 {
5728 StringInfo buf = context->buf;
5729 bool first_list = true;
5730 ListCell *vtl;
5731
5732 appendStringInfoString(buf, "VALUES ");
5733
5734 foreach(vtl, values_lists)
5735 {
5736 List *sublist = (List *) lfirst(vtl);
5737 bool first_col = true;
5738 ListCell *lc;
5739
5740 if (first_list)
5741 first_list = false;
5742 else
5743 appendStringInfoString(buf, ", ");
5744
5745 appendStringInfoChar(buf, '(');
5746 foreach(lc, sublist)
5747 {
5748 Node *col = (Node *) lfirst(lc);
5749
5750 if (first_col)
5751 first_col = false;
5752 else
5753 appendStringInfoChar(buf, ',');
5754
5755 /*
5756 * Print the value. Whole-row Vars need special treatment.
5757 */
5758 get_rule_expr_toplevel(col, context, false);
5759 }
5760 appendStringInfoChar(buf, ')');
5761 }
5762 }
5763
5764 /* ----------
5765 * get_with_clause - Parse back a WITH clause
5766 * ----------
5767 */
5768 static void
5769 get_with_clause(Query *query, deparse_context *context)
5770 {
5771 StringInfo buf = context->buf;
5772 const char *sep;
5773 ListCell *l;
5774
5775 if (query->cteList == NIL)
5776 return;
5777
5778 if (PRETTY_INDENT(context))
5779 {
5780 context->indentLevel += PRETTYINDENT_STD;
5781 appendStringInfoChar(buf, ' ');
5782 }
5783
5784 if (query->hasRecursive)
5785 sep = "WITH RECURSIVE ";
5786 else
5787 sep = "WITH ";
5788 foreach(l, query->cteList)
5789 {
5790 CommonTableExpr *cte = (CommonTableExpr *) lfirst(l);
5791
5792 appendStringInfoString(buf, sep);
5793 appendStringInfoString(buf, quote_identifier(cte->ctename));
5794 if (cte->aliascolnames)
5795 {
5796 bool first = true;
5797 ListCell *col;
5798
5799 appendStringInfoChar(buf, '(');
5800 foreach(col, cte->aliascolnames)
5801 {
5802 if (first)
5803 first = false;
5804 else
5805 appendStringInfoString(buf, ", ");
5806 appendStringInfoString(buf,
5807 quote_identifier(strVal(lfirst(col))));
5808 }
5809 appendStringInfoChar(buf, ')');
5810 }
5811 appendStringInfoString(buf, " AS ");
5812 switch (cte->ctematerialized)
5813 {
5814 case CTEMaterializeDefault:
5815 break;
5816 case CTEMaterializeAlways:
5817 appendStringInfoString(buf, "MATERIALIZED ");
5818 break;
5819 case CTEMaterializeNever:
5820 appendStringInfoString(buf, "NOT MATERIALIZED ");
5821 break;
5822 }
5823 appendStringInfoChar(buf, '(');
5824 if (PRETTY_INDENT(context))
5825 appendContextKeyword(context, "", 0, 0, 0);
5826 get_query_def((Query *) cte->ctequery, buf, context->namespaces, NULL,
5827 true,
5828 context->prettyFlags, context->wrapColumn,
5829 context->indentLevel);
5830 if (PRETTY_INDENT(context))
5831 appendContextKeyword(context, "", 0, 0, 0);
5832 appendStringInfoChar(buf, ')');
5833
5834 if (cte->search_clause)
5835 {
5836 bool first = true;
5837 ListCell *lc;
5838
5839 appendStringInfo(buf, " SEARCH %s FIRST BY ",
5840 cte->search_clause->search_breadth_first ? "BREADTH" : "DEPTH");
5841
5842 foreach(lc, cte->search_clause->search_col_list)
5843 {
5844 if (first)
5845 first = false;
5846 else
5847 appendStringInfoString(buf, ", ");
5848 appendStringInfoString(buf,
5849 quote_identifier(strVal(lfirst(lc))));
5850 }
5851
5852 appendStringInfo(buf, " SET %s", quote_identifier(cte->search_clause->search_seq_column));
5853 }
5854
5855 if (cte->cycle_clause)
5856 {
5857 bool first = true;
5858 ListCell *lc;
5859
5860 appendStringInfoString(buf, " CYCLE ");
5861
5862 foreach(lc, cte->cycle_clause->cycle_col_list)
5863 {
5864 if (first)
5865 first = false;
5866 else
5867 appendStringInfoString(buf, ", ");
5868 appendStringInfoString(buf,
5869 quote_identifier(strVal(lfirst(lc))));
5870 }
5871
5872 appendStringInfo(buf, " SET %s", quote_identifier(cte->cycle_clause->cycle_mark_column));
5873
5874 {
5875 Const *cmv = castNode(Const, cte->cycle_clause->cycle_mark_value);
5876 Const *cmd = castNode(Const, cte->cycle_clause->cycle_mark_default);
5877
5878 if (!(cmv->consttype == BOOLOID && !cmv->constisnull && DatumGetBool(cmv->constvalue) == true &&
5879 cmd->consttype == BOOLOID && !cmd->constisnull && DatumGetBool(cmd->constvalue) == false))
5880 {
5881 appendStringInfoString(buf, " TO ");
5882 get_rule_expr(cte->cycle_clause->cycle_mark_value, context, false);
5883 appendStringInfoString(buf, " DEFAULT ");
5884 get_rule_expr(cte->cycle_clause->cycle_mark_default, context, false);
5885 }
5886 }
5887
5888 appendStringInfo(buf, " USING %s", quote_identifier(cte->cycle_clause->cycle_path_column));
5889 }
5890
5891 sep = ", ";
5892 }
5893
5894 if (PRETTY_INDENT(context))
5895 {
5896 context->indentLevel -= PRETTYINDENT_STD;
5897 appendContextKeyword(context, "", 0, 0, 0);
5898 }
5899 else
5900 appendStringInfoChar(buf, ' ');
5901 }
5902
5903 /* ----------
5904 * get_select_query_def - Parse back a SELECT parsetree
5905 * ----------
5906 */
5907 static void
5908 get_select_query_def(Query *query, deparse_context *context)
5909 {
5910 StringInfo buf = context->buf;
5911 bool force_colno;
5912 ListCell *l;
5913
5914 /* Insert the WITH clause if given */
5915 get_with_clause(query, context);
5916
5917 /* Subroutines may need to consult the SELECT targetlist and windowClause */
5918 context->targetList = query->targetList;
5919 context->windowClause = query->windowClause;
5920
5921 /*
5922 * If the Query node has a setOperations tree, then it's the top level of
5923 * a UNION/INTERSECT/EXCEPT query; only the WITH, ORDER BY and LIMIT
5924 * fields are interesting in the top query itself.
5925 */
5926 if (query->setOperations)
5927 {
5928 get_setop_query(query->setOperations, query, context);
5929 /* ORDER BY clauses must be simple in this case */
5930 force_colno = true;
5931 }
5932 else
5933 {
5934 get_basic_select_query(query, context);
5935 force_colno = false;
5936 }
5937
5938 /* Add the ORDER BY clause if given */
5939 if (query->sortClause != NIL)
5940 {
5941 appendContextKeyword(context, " ORDER BY ",
5942 -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
5943 get_rule_orderby(query->sortClause, query->targetList,
5944 force_colno, context);
5945 }
5946
5947 /*
5948 * Add the LIMIT/OFFSET clauses if given. If non-default options, use the
5949 * standard spelling of LIMIT.
5950 */
5951 if (query->limitOffset != NULL)
5952 {
5953 appendContextKeyword(context, " OFFSET ",
5954 -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
5955 get_rule_expr(query->limitOffset, context, false);
5956 }
5957 if (query->limitCount != NULL)
5958 {
5959 if (query->limitOption == LIMIT_OPTION_WITH_TIES)
5960 {
5961 /*
5962 * The limitCount arg is a c_expr, so it needs parens. Simple
5963 * literals and function expressions would not need parens, but
5964 * unfortunately it's hard to tell if the expression will be
5965 * printed as a simple literal like 123 or as a typecast
5966 * expression, like '-123'::int4. The grammar accepts the former
5967 * without quoting, but not the latter.
5968 */
5969 appendContextKeyword(context, " FETCH FIRST ",
5970 -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
5971 appendStringInfoChar(buf, '(');
5972 get_rule_expr(query->limitCount, context, false);
5973 appendStringInfoChar(buf, ')');
5974 appendStringInfoString(buf, " ROWS WITH TIES");
5975 }
5976 else
5977 {
5978 appendContextKeyword(context, " LIMIT ",
5979 -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
5980 if (IsA(query->limitCount, Const) &&
5981 ((Const *) query->limitCount)->constisnull)
5982 appendStringInfoString(buf, "ALL");
5983 else
5984 get_rule_expr(query->limitCount, context, false);
5985 }
5986 }
5987
5988 /* Add FOR [KEY] UPDATE/SHARE clauses if present */
5989 if (query->hasForUpdate)
5990 {
5991 foreach(l, query->rowMarks)
5992 {
5993 RowMarkClause *rc = (RowMarkClause *) lfirst(l);
5994
5995 /* don't print implicit clauses */
5996 if (rc->pushedDown)
5997 continue;
5998
5999 switch (rc->strength)
6000 {
6001 case LCS_NONE:
6002 /* we intentionally throw an error for LCS_NONE */
6003 elog(ERROR, "unrecognized LockClauseStrength %d",
6004 (int) rc->strength);
6005 break;
6006 case LCS_FORKEYSHARE:
6007 appendContextKeyword(context, " FOR KEY SHARE",
6008 -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
6009 break;
6010 case LCS_FORSHARE:
6011 appendContextKeyword(context, " FOR SHARE",
6012 -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
6013 break;
6014 case LCS_FORNOKEYUPDATE:
6015 appendContextKeyword(context, " FOR NO KEY UPDATE",
6016 -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
6017 break;
6018 case LCS_FORUPDATE:
6019 appendContextKeyword(context, " FOR UPDATE",
6020 -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
6021 break;
6022 }
6023
6024 appendStringInfo(buf, " OF %s",
6025 quote_identifier(get_rtable_name(rc->rti,
6026 context)));
6027 if (rc->waitPolicy == LockWaitError)
6028 appendStringInfoString(buf, " NOWAIT");
6029 else if (rc->waitPolicy == LockWaitSkip)
6030 appendStringInfoString(buf, " SKIP LOCKED");
6031 }
6032 }
6033 }
6034
6035 /*
6036 * Detect whether query looks like SELECT ... FROM VALUES(),
6037 * with no need to rename the output columns of the VALUES RTE.
6038 * If so, return the VALUES RTE. Otherwise return NULL.
6039 */
6040 static RangeTblEntry *
6041 get_simple_values_rte(Query *query, TupleDesc resultDesc)
6042 {
6043 RangeTblEntry *result = NULL;
6044 ListCell *lc;
6045
6046 /*
6047 * We want to detect a match even if the Query also contains OLD or NEW
6048 * rule RTEs. So the idea is to scan the rtable and see if there is only
6049 * one inFromCl RTE that is a VALUES RTE.
6050 */
6051 foreach(lc, query->rtable)
6052 {
6053 RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
6054
6055 if (rte->rtekind == RTE_VALUES && rte->inFromCl)
6056 {
6057 if (result)
6058 return NULL; /* multiple VALUES (probably not possible) */
6059 result = rte;
6060 }
6061 else if (rte->rtekind == RTE_RELATION && !rte->inFromCl)
6062 continue; /* ignore rule entries */
6063 else
6064 return NULL; /* something else -> not simple VALUES */
6065 }
6066
6067 /*
6068 * We don't need to check the targetlist in any great detail, because
6069 * parser/analyze.c will never generate a "bare" VALUES RTE --- they only
6070 * appear inside auto-generated sub-queries with very restricted
6071 * structure. However, DefineView might have modified the tlist by
6072 * injecting new column aliases, or we might have some other column
6073 * aliases forced by a resultDesc. We can only simplify if the RTE's
6074 * column names match the names that get_target_list() would select.
6075 */
6076 if (result)
6077 {
6078 ListCell *lcn;
6079 int colno;
6080
6081 if (list_length(query->targetList) != list_length(result->eref->colnames))
6082 return NULL; /* this probably cannot happen */
6083 colno = 0;
6084 forboth(lc, query->targetList, lcn, result->eref->colnames)
6085 {
6086 TargetEntry *tle = (TargetEntry *) lfirst(lc);
6087 char *cname = strVal(lfirst(lcn));
6088 char *colname;
6089
6090 if (tle->resjunk)
6091 return NULL; /* this probably cannot happen */
6092
6093 /* compute name that get_target_list would use for column */
6094 colno++;
6095 if (resultDesc && colno <= resultDesc->natts)
6096 colname = NameStr(TupleDescAttr(resultDesc, colno - 1)->attname);
6097 else
6098 colname = tle->resname;
6099
6100 /* does it match the VALUES RTE? */
6101 if (colname == NULL || strcmp(colname, cname) != 0)
6102 return NULL; /* column name has been changed */
6103 }
6104 }
6105
6106 return result;
6107 }
6108
6109 static void
6110 get_basic_select_query(Query *query, deparse_context *context)
6111 {
6112 StringInfo buf = context->buf;
6113 RangeTblEntry *values_rte;
6114 char *sep;
6115 ListCell *l;
6116
6117 if (PRETTY_INDENT(context))
6118 {
6119 context->indentLevel += PRETTYINDENT_STD;
6120 appendStringInfoChar(buf, ' ');
6121 }
6122
6123 /*
6124 * If the query looks like SELECT * FROM (VALUES ...), then print just the
6125 * VALUES part. This reverses what transformValuesClause() did at parse
6126 * time.
6127 */
6128 values_rte = get_simple_values_rte(query, context->resultDesc);
6129 if (values_rte)
6130 {
6131 get_values_def(values_rte->values_lists, context);
6132 return;
6133 }
6134
6135 /*
6136 * Build up the query string - first we say SELECT
6137 */
6138 if (query->isReturn)
6139 appendStringInfoString(buf, "RETURN");
6140 else
6141 appendStringInfoString(buf, "SELECT");
6142
6143 /* Add the DISTINCT clause if given */
6144 if (query->distinctClause != NIL)
6145 {
6146 if (query->hasDistinctOn)
6147 {
6148 appendStringInfoString(buf, " DISTINCT ON (");
6149 sep = "";
6150 foreach(l, query->distinctClause)
6151 {
6152 SortGroupClause *srt = (SortGroupClause *) lfirst(l);
6153
6154 appendStringInfoString(buf, sep);
6155 get_rule_sortgroupclause(srt->tleSortGroupRef, query->targetList,
6156 false, context);
6157 sep = ", ";
6158 }
6159 appendStringInfoChar(buf, ')');
6160 }
6161 else
6162 appendStringInfoString(buf, " DISTINCT");
6163 }
6164
6165 /* Then we tell what to select (the targetlist) */
6166 get_target_list(query->targetList, context);
6167
6168 /* Add the FROM clause if needed */
6169 get_from_clause(query, " FROM ", context);
6170
6171 /* Add the WHERE clause if given */
6172 if (query->jointree->quals != NULL)
6173 {
6174 appendContextKeyword(context, " WHERE ",
6175 -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
6176 get_rule_expr(query->jointree->quals, context, false);
6177 }
6178
6179 /* Add the GROUP BY clause if given */
6180 if (query->groupClause != NULL || query->groupingSets != NULL)
6181 {
6182 bool save_ingroupby;
6183
6184 appendContextKeyword(context, " GROUP BY ",
6185 -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
6186 if (query->groupDistinct)
6187 appendStringInfoString(buf, "DISTINCT ");
6188
6189 save_ingroupby = context->inGroupBy;
6190 context->inGroupBy = true;
6191
6192 if (query->groupingSets == NIL)
6193 {
6194 sep = "";
6195 foreach(l, query->groupClause)
6196 {
6197 SortGroupClause *grp = (SortGroupClause *) lfirst(l);
6198
6199 appendStringInfoString(buf, sep);
6200 get_rule_sortgroupclause(grp->tleSortGroupRef, query->targetList,
6201 false, context);
6202 sep = ", ";
6203 }
6204 }
6205 else
6206 {
6207 sep = "";
6208 foreach(l, query->groupingSets)
6209 {
6210 GroupingSet *grp = lfirst(l);
6211
6212 appendStringInfoString(buf, sep);
6213 get_rule_groupingset(grp, query->targetList, true, context);
6214 sep = ", ";
6215 }
6216 }
6217
6218 context->inGroupBy = save_ingroupby;
6219 }
6220
6221 /* Add the HAVING clause if given */
6222 if (query->havingQual != NULL)
6223 {
6224 appendContextKeyword(context, " HAVING ",
6225 -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
6226 get_rule_expr(query->havingQual, context, false);
6227 }
6228
6229 /* Add the WINDOW clause if needed */
6230 if (query->windowClause != NIL)
6231 get_rule_windowclause(query, context);
6232 }
6233
6234 /* ----------
6235 * get_target_list - Parse back a SELECT target list
6236 *
6237 * This is also used for RETURNING lists in INSERT/UPDATE/DELETE/MERGE.
6238 * ----------
6239 */
6240 static void
6241 get_target_list(List *targetList, deparse_context *context)
6242 {
6243 StringInfo buf = context->buf;
6244 StringInfoData targetbuf;
6245 bool last_was_multiline = false;
6246 char *sep;
6247 int colno;
6248 ListCell *l;
6249
6250 /* we use targetbuf to hold each TLE's text temporarily */
6251 initStringInfo(&targetbuf);
6252
6253 sep = " ";
6254 colno = 0;
6255 foreach(l, targetList)
6256 {
6257 TargetEntry *tle = (TargetEntry *) lfirst(l);
6258 char *colname;
6259 char *attname;
6260
6261 if (tle->resjunk)
6262 continue; /* ignore junk entries */
6263
6264 appendStringInfoString(buf, sep);
6265 sep = ", ";
6266 colno++;
6267
6268 /*
6269 * Put the new field text into targetbuf so we can decide after we've
6270 * got it whether or not it needs to go on a new line.
6271 */
6272 resetStringInfo(&targetbuf);
6273 context->buf = &targetbuf;
6274
6275 /*
6276 * We special-case Var nodes rather than using get_rule_expr. This is
6277 * needed because get_rule_expr will display a whole-row Var as
6278 * "foo.*", which is the preferred notation in most contexts, but at
6279 * the top level of a SELECT list it's not right (the parser will
6280 * expand that notation into multiple columns, yielding behavior
6281 * different from a whole-row Var). We need to call get_variable
6282 * directly so that we can tell it to do the right thing, and so that
6283 * we can get the attribute name which is the default AS label.
6284 */
6285 if (tle->expr && (IsA(tle->expr, Var)))
6286 {
6287 attname = get_variable((Var *) tle->expr, 0, true, context);
6288 }
6289 else
6290 {
6291 get_rule_expr((Node *) tle->expr, context, true);
6292
6293 /*
6294 * When colNamesVisible is true, we should always show the
6295 * assigned column name explicitly. Otherwise, show it only if
6296 * it's not FigureColname's fallback.
6297 */
6298 attname = context->colNamesVisible ? NULL : "?column?";
6299 }
6300
6301 /*
6302 * Figure out what the result column should be called. In the context
6303 * of a view, use the view's tuple descriptor (so as to pick up the
6304 * effects of any column RENAME that's been done on the view).
6305 * Otherwise, just use what we can find in the TLE.
6306 */
6307 if (context->resultDesc && colno <= context->resultDesc->natts)
6308 colname = NameStr(TupleDescAttr(context->resultDesc,
6309 colno - 1)->attname);
6310 else
6311 colname = tle->resname;
6312
6313 /* Show AS unless the column's name is correct as-is */
6314 if (colname) /* resname could be NULL */
6315 {
6316 if (attname == NULL || strcmp(attname, colname) != 0)
6317 appendStringInfo(&targetbuf, " AS %s", quote_identifier(colname));
6318 }
6319
6320 /* Restore context's output buffer */
6321 context->buf = buf;
6322
6323 /* Consider line-wrapping if enabled */
6324 if (PRETTY_INDENT(context) && context->wrapColumn >= 0)
6325 {
6326 int leading_nl_pos;
6327
6328 /* Does the new field start with a new line? */
6329 if (targetbuf.len > 0 && targetbuf.data[0] == '\n')
6330 leading_nl_pos = 0;
6331 else
6332 leading_nl_pos = -1;
6333
6334 /* If so, we shouldn't add anything */
6335 if (leading_nl_pos >= 0)
6336 {
6337 /* instead, remove any trailing spaces currently in buf */
6338 removeStringInfoSpaces(buf);
6339 }
6340 else
6341 {
6342 char *trailing_nl;
6343
6344 /* Locate the start of the current line in the output buffer */
6345 trailing_nl = strrchr(buf->data, '\n');
6346 if (trailing_nl == NULL)
6347 trailing_nl = buf->data;
6348 else
6349 trailing_nl++;
6350
6351 /*
6352 * Add a newline, plus some indentation, if the new field is
6353 * not the first and either the new field would cause an
6354 * overflow or the last field used more than one line.
6355 */
6356 if (colno > 1 &&
6357 ((strlen(trailing_nl) + targetbuf.len > context->wrapColumn) ||
6358 last_was_multiline))
6359 appendContextKeyword(context, "", -PRETTYINDENT_STD,
6360 PRETTYINDENT_STD, PRETTYINDENT_VAR);
6361 }
6362
6363 /* Remember this field's multiline status for next iteration */
6364 last_was_multiline =
6365 (strchr(targetbuf.data + leading_nl_pos + 1, '\n') != NULL);
6366 }
6367
6368 /* Add the new field */
6369 appendBinaryStringInfo(buf, targetbuf.data, targetbuf.len);
6370 }
6371
6372 /* clean up */
6373 pfree(targetbuf.data);
6374 }
6375
6376 static void
6377 get_returning_clause(Query *query, deparse_context *context)
6378 {
6379 StringInfo buf = context->buf;
6380
6381 if (query->returningList)
6382 {
6383 bool have_with = false;
6384
6385 appendContextKeyword(context, " RETURNING",
6386 -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
6387
6388 /* Add WITH (OLD/NEW) options, if they're not the defaults */
6389 if (query->returningOldAlias && strcmp(query->returningOldAlias, "old") != 0)
6390 {
6391 appendStringInfo(buf, " WITH (OLD AS %s",
6392 quote_identifier(query->returningOldAlias));
6393 have_with = true;
6394 }
6395 if (query->returningNewAlias && strcmp(query->returningNewAlias, "new") != 0)
6396 {
6397 if (have_with)
6398 appendStringInfo(buf, ", NEW AS %s",
6399 quote_identifier(query->returningNewAlias));
6400 else
6401 {
6402 appendStringInfo(buf, " WITH (NEW AS %s",
6403 quote_identifier(query->returningNewAlias));
6404 have_with = true;
6405 }
6406 }
6407 if (have_with)
6408 appendStringInfoChar(buf, ')');
6409
6410 /* Add the returning expressions themselves */
6411 get_target_list(query->returningList, context);
6412 }
6413 }
6414
6415 static void
6416 get_setop_query(Node *setOp, Query *query, deparse_context *context)
6417 {
6418 StringInfo buf = context->buf;
6419 bool need_paren;
6420
6421 /* Guard against excessively long or deeply-nested queries */
6422 CHECK_FOR_INTERRUPTS();
6423 check_stack_depth();
6424
6425 if (IsA(setOp, RangeTblRef))
6426 {
6427 RangeTblRef *rtr = (RangeTblRef *) setOp;
6428 RangeTblEntry *rte = rt_fetch(rtr->rtindex, query->rtable);
6429 Query *subquery = rte->subquery;
6430
6431 Assert(subquery != NULL);
6432
6433 /*
6434 * We need parens if WITH, ORDER BY, FOR UPDATE, or LIMIT; see gram.y.
6435 * Also add parens if the leaf query contains its own set operations.
6436 * (That shouldn't happen unless one of the other clauses is also
6437 * present, see transformSetOperationTree; but let's be safe.)
6438 */
6439 need_paren = (subquery->cteList ||
6440 subquery->sortClause ||
6441 subquery->rowMarks ||
6442 subquery->limitOffset ||
6443 subquery->limitCount ||
6444 subquery->setOperations);
6445 if (need_paren)
6446 appendStringInfoChar(buf, '(');
6447 get_query_def(subquery, buf, context->namespaces,
6448 context->resultDesc, context->colNamesVisible,
6449 context->prettyFlags, context->wrapColumn,
6450 context->indentLevel);
6451 if (need_paren)
6452 appendStringInfoChar(buf, ')');
6453 }
6454 else if (IsA(setOp, SetOperationStmt))
6455 {
6456 SetOperationStmt *op = (SetOperationStmt *) setOp;
6457 int subindent;
6458 bool save_colnamesvisible;
6459
6460 /*
6461 * We force parens when nesting two SetOperationStmts, except when the
6462 * lefthand input is another setop of the same kind. Syntactically,
6463 * we could omit parens in rather more cases, but it seems best to use
6464 * parens to flag cases where the setop operator changes. If we use
6465 * parens, we also increase the indentation level for the child query.
6466 *
6467 * There are some cases in which parens are needed around a leaf query
6468 * too, but those are more easily handled at the next level down (see
6469 * code above).
6470 */
6471 if (IsA(op->larg, SetOperationStmt))
6472 {
6473 SetOperationStmt *lop = (SetOperationStmt *) op->larg;
6474
6475 if (op->op == lop->op && op->all == lop->all)
6476 need_paren = false;
6477 else
6478 need_paren = true;
6479 }
6480 else
6481 need_paren = false;
6482
6483 if (need_paren)
6484 {
6485 appendStringInfoChar(buf, '(');
6486 subindent = PRETTYINDENT_STD;
6487 appendContextKeyword(context, "", subindent, 0, 0);
6488 }
6489 else
6490 subindent = 0;
6491
6492 get_setop_query(op->larg, query, context);
6493
6494 if (need_paren)
6495 appendContextKeyword(context, ") ", -subindent, 0, 0);
6496 else if (PRETTY_INDENT(context))
6497 appendContextKeyword(context, "", -subindent, 0, 0);
6498 else
6499 appendStringInfoChar(buf, ' ');
6500
6501 switch (op->op)
6502 {
6503 case SETOP_UNION:
6504 appendStringInfoString(buf, "UNION ");
6505 break;
6506 case SETOP_INTERSECT:
6507 appendStringInfoString(buf, "INTERSECT ");
6508 break;
6509 case SETOP_EXCEPT:
6510 appendStringInfoString(buf, "EXCEPT ");
6511 break;
6512 default:
6513 elog(ERROR, "unrecognized set op: %d",
6514 (int) op->op);
6515 }
6516 if (op->all)
6517 appendStringInfoString(buf, "ALL ");
6518
6519 /* Always parenthesize if RHS is another setop */
6520 need_paren = IsA(op->rarg, SetOperationStmt);
6521
6522 /*
6523 * The indentation code here is deliberately a bit different from that
6524 * for the lefthand input, because we want the line breaks in
6525 * different places.
6526 */
6527 if (need_paren)
6528 {
6529 appendStringInfoChar(buf, '(');
6530 subindent = PRETTYINDENT_STD;
6531 }
6532 else
6533 subindent = 0;
6534 appendContextKeyword(context, "", subindent, 0, 0);
6535
6536 /*
6537 * The output column names of the RHS sub-select don't matter.
6538 */
6539 save_colnamesvisible = context->colNamesVisible;
6540 context->colNamesVisible = false;
6541
6542 get_setop_query(op->rarg, query, context);
6543
6544 context->colNamesVisible = save_colnamesvisible;
6545
6546 if (PRETTY_INDENT(context))
6547 context->indentLevel -= subindent;
6548 if (need_paren)
6549 appendContextKeyword(context, ")", 0, 0, 0);
6550 }
6551 else
6552 {
6553 elog(ERROR, "unrecognized node type: %d",
6554 (int) nodeTag(setOp));
6555 }
6556 }
6557
6558 /*
6559 * Display a sort/group clause.
6560 *
6561 * Also returns the expression tree, so caller need not find it again.
6562 */
6563 static Node *
6564 get_rule_sortgroupclause(Index ref, List *tlist, bool force_colno,
6565 deparse_context *context)
6566 {
6567 StringInfo buf = context->buf;
6568 TargetEntry *tle;
6569 Node *expr;
6570
6571 tle = get_sortgroupref_tle(ref, tlist);
6572 expr = (Node *) tle->expr;
6573
6574 /*
6575 * Use column-number form if requested by caller. Otherwise, if
6576 * expression is a constant, force it to be dumped with an explicit cast
6577 * as decoration --- this is because a simple integer constant is
6578 * ambiguous (and will be misinterpreted by findTargetlistEntrySQL92()) if
6579 * we dump it without any decoration. Similarly, if it's just a Var,
6580 * there is risk of misinterpretation if the column name is reassigned in
6581 * the SELECT list, so we may need to force table qualification. And, if
6582 * it's anything more complex than a simple Var, then force extra parens
6583 * around it, to ensure it can't be misinterpreted as a cube() or rollup()
6584 * construct.
6585 */
6586 if (force_colno)
6587 {
6588 Assert(!tle->resjunk);
6589 appendStringInfo(buf, "%d", tle->resno);
6590 }
6591 else if (!expr)
6592 /* do nothing, probably can't happen */ ;
6593 else if (IsA(expr, Const))
6594 get_const_expr((Const *) expr, context, 1);
6595 else if (IsA(expr, Var))
6596 {
6597 /* Tell get_variable to check for name conflict */
6598 bool save_varinorderby = context->varInOrderBy;
6599
6600 context->varInOrderBy = true;
6601 (void) get_variable((Var *) expr, 0, false, context);
6602 context->varInOrderBy = save_varinorderby;
6603 }
6604 else
6605 {
6606 /*
6607 * We must force parens for function-like expressions even if
6608 * PRETTY_PAREN is off, since those are the ones in danger of
6609 * misparsing. For other expressions we need to force them only if
6610 * PRETTY_PAREN is on, since otherwise the expression will output them
6611 * itself. (We can't skip the parens.)
6612 */
6613 bool need_paren = (PRETTY_PAREN(context)
6614 || IsA(expr, FuncExpr)
6615 || IsA(expr, Aggref)
6616 || IsA(expr, WindowFunc)
6617 || IsA(expr, JsonConstructorExpr));
6618
6619 if (need_paren)
6620 appendStringInfoChar(context->buf, '(');
6621 get_rule_expr(expr, context, true);
6622 if (need_paren)
6623 appendStringInfoChar(context->buf, ')');
6624 }
6625
6626 return expr;
6627 }
6628
6629 /*
6630 * Display a GroupingSet
6631 */
6632 static void
6633 get_rule_groupingset(GroupingSet *gset, List *targetlist,
6634 bool omit_parens, deparse_context *context)
6635 {
6636 ListCell *l;
6637 StringInfo buf = context->buf;
6638 bool omit_child_parens = true;
6639 char *sep = "";
6640
6641 switch (gset->kind)
6642 {
6643 case GROUPING_SET_EMPTY:
6644 appendStringInfoString(buf, "()");
6645 return;
6646
6647 case GROUPING_SET_SIMPLE:
6648 {
6649 if (!omit_parens || list_length(gset->content) != 1)
6650 appendStringInfoChar(buf, '(');
6651
6652 foreach(l, gset->content)
6653 {
6654 Index ref = lfirst_int(l);
6655
6656 appendStringInfoString(buf, sep);
6657 get_rule_sortgroupclause(ref, targetlist,
6658 false, context);
6659 sep = ", ";
6660 }
6661
6662 if (!omit_parens || list_length(gset->content) != 1)
6663 appendStringInfoChar(buf, ')');
6664 }
6665 return;
6666
6667 case GROUPING_SET_ROLLUP:
6668 appendStringInfoString(buf, "ROLLUP(");
6669 break;
6670 case GROUPING_SET_CUBE:
6671 appendStringInfoString(buf, "CUBE(");
6672 break;
6673 case GROUPING_SET_SETS:
6674 appendStringInfoString(buf, "GROUPING SETS (");
6675 omit_child_parens = false;
6676 break;
6677 }
6678
6679 foreach(l, gset->content)
6680 {
6681 appendStringInfoString(buf, sep);
6682 get_rule_groupingset(lfirst(l), targetlist, omit_child_parens, context);
6683 sep = ", ";
6684 }
6685
6686 appendStringInfoChar(buf, ')');
6687 }
6688
6689 /*
6690 * Display an ORDER BY list.
6691 */
6692 static void
6693 get_rule_orderby(List *orderList, List *targetList,
6694 bool force_colno, deparse_context *context)
6695 {
6696 StringInfo buf = context->buf;
6697 const char *sep;
6698 ListCell *l;
6699
6700 sep = "";
6701 foreach(l, orderList)
6702 {
6703 SortGroupClause *srt = (SortGroupClause *) lfirst(l);
6704 Node *sortexpr;
6705 Oid sortcoltype;
6706 TypeCacheEntry *typentry;
6707
6708 appendStringInfoString(buf, sep);
6709 sortexpr = get_rule_sortgroupclause(srt->tleSortGroupRef, targetList,
6710 force_colno, context);
6711 sortcoltype = exprType(sortexpr);
6712 /* See whether operator is default < or > for datatype */
6713 typentry = lookup_type_cache(sortcoltype,
6714 TYPECACHE_LT_OPR | TYPECACHE_GT_OPR);
6715 if (srt->sortop == typentry->lt_opr)
6716 {
6717 /* ASC is default, so emit nothing for it */
6718 if (srt->nulls_first)
6719 appendStringInfoString(buf, " NULLS FIRST");
6720 }
6721 else if (srt->sortop == typentry->gt_opr)
6722 {
6723 appendStringInfoString(buf, " DESC");
6724 /* DESC defaults to NULLS FIRST */
6725 if (!srt->nulls_first)
6726 appendStringInfoString(buf, " NULLS LAST");
6727 }
6728 else
6729 {
6730 appendStringInfo(buf, " USING %s",
6731 generate_operator_name(srt->sortop,
6732 sortcoltype,
6733 sortcoltype));
6734 /* be specific to eliminate ambiguity */
6735 if (srt->nulls_first)
6736 appendStringInfoString(buf, " NULLS FIRST");
6737 else
6738 appendStringInfoString(buf, " NULLS LAST");
6739 }
6740 sep = ", ";
6741 }
6742 }
6743
6744 /*
6745 * Display a WINDOW clause.
6746 *
6747 * Note that the windowClause list might contain only anonymous window
6748 * specifications, in which case we should print nothing here.
6749 */
6750 static void
6751 get_rule_windowclause(Query *query, deparse_context *context)
6752 {
6753 StringInfo buf = context->buf;
6754 const char *sep;
6755 ListCell *l;
6756
6757 sep = NULL;
6758 foreach(l, query->windowClause)
6759 {
6760 WindowClause *wc = (WindowClause *) lfirst(l);
6761
6762 if (wc->name == NULL)
6763 continue; /* ignore anonymous windows */
6764
6765 if (sep == NULL)
6766 appendContextKeyword(context, " WINDOW ",
6767 -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
6768 else
6769 appendStringInfoString(buf, sep);
6770
6771 appendStringInfo(buf, "%s AS ", quote_identifier(wc->name));
6772
6773 get_rule_windowspec(wc, query->targetList, context);
6774
6775 sep = ", ";
6776 }
6777 }
6778
6779 /*
6780 * Display a window definition
6781 */
6782 static void
6783 get_rule_windowspec(WindowClause *wc, List *targetList,
6784 deparse_context *context)
6785 {
6786 StringInfo buf = context->buf;
6787 bool needspace = false;
6788 const char *sep;
6789 ListCell *l;
6790
6791 appendStringInfoChar(buf, '(');
6792 if (wc->refname)
6793 {
6794 appendStringInfoString(buf, quote_identifier(wc->refname));
6795 needspace = true;
6796 }
6797 /* partition clauses are always inherited, so only print if no refname */
6798 if (wc->partitionClause && !wc->refname)
6799 {
6800 if (needspace)
6801 appendStringInfoChar(buf, ' ');
6802 appendStringInfoString(buf, "PARTITION BY ");
6803 sep = "";
6804 foreach(l, wc->partitionClause)
6805 {
6806 SortGroupClause *grp = (SortGroupClause *) lfirst(l);
6807
6808 appendStringInfoString(buf, sep);
6809 get_rule_sortgroupclause(grp->tleSortGroupRef, targetList,
6810 false, context);
6811 sep = ", ";
6812 }
6813 needspace = true;
6814 }
6815 /* print ordering clause only if not inherited */
6816 if (wc->orderClause && !wc->copiedOrder)
6817 {
6818 if (needspace)
6819 appendStringInfoChar(buf, ' ');
6820 appendStringInfoString(buf, "ORDER BY ");
6821 get_rule_orderby(wc->orderClause, targetList, false, context);
6822 needspace = true;
6823 }
6824 /* framing clause is never inherited, so print unless it's default */
6825 if (wc->frameOptions & FRAMEOPTION_NONDEFAULT)
6826 {
6827 if (needspace)
6828 appendStringInfoChar(buf, ' ');
6829 get_window_frame_options(wc->frameOptions,
6830 wc->startOffset, wc->endOffset,
6831 context);
6832 }
6833 appendStringInfoChar(buf, ')');
6834 }
6835
6836 /*
6837 * Append the description of a window's framing options to context->buf
6838 */
6839 static void
6840 get_window_frame_options(int frameOptions,
6841 Node *startOffset, Node *endOffset,
6842 deparse_context *context)
6843 {
6844 StringInfo buf = context->buf;
6845
6846 if (frameOptions & FRAMEOPTION_NONDEFAULT)
6847 {
6848 if (frameOptions & FRAMEOPTION_RANGE)
6849 appendStringInfoString(buf, "RANGE ");
6850 else if (frameOptions & FRAMEOPTION_ROWS)
6851 appendStringInfoString(buf, "ROWS ");
6852 else if (frameOptions & FRAMEOPTION_GROUPS)
6853 appendStringInfoString(buf, "GROUPS ");
6854 else
6855 Assert(false);
6856 if (frameOptions & FRAMEOPTION_BETWEEN)
6857 appendStringInfoString(buf, "BETWEEN ");
6858 if (frameOptions & FRAMEOPTION_START_UNBOUNDED_PRECEDING)
6859 appendStringInfoString(buf, "UNBOUNDED PRECEDING ");
6860 else if (frameOptions & FRAMEOPTION_START_CURRENT_ROW)
6861 appendStringInfoString(buf, "CURRENT ROW ");
6862 else if (frameOptions & FRAMEOPTION_START_OFFSET)
6863 {
6864 get_rule_expr(startOffset, context, false);
6865 if (frameOptions & FRAMEOPTION_START_OFFSET_PRECEDING)
6866 appendStringInfoString(buf, " PRECEDING ");
6867 else if (frameOptions & FRAMEOPTION_START_OFFSET_FOLLOWING)
6868 appendStringInfoString(buf, " FOLLOWING ");
6869 else
6870 Assert(false);
6871 }
6872 else
6873 Assert(false);
6874 if (frameOptions & FRAMEOPTION_BETWEEN)
6875 {
6876 appendStringInfoString(buf, "AND ");
6877 if (frameOptions & FRAMEOPTION_END_UNBOUNDED_FOLLOWING)
6878 appendStringInfoString(buf, "UNBOUNDED FOLLOWING ");
6879 else if (frameOptions & FRAMEOPTION_END_CURRENT_ROW)
6880 appendStringInfoString(buf, "CURRENT ROW ");
6881 else if (frameOptions & FRAMEOPTION_END_OFFSET)
6882 {
6883 get_rule_expr(endOffset, context, false);
6884 if (frameOptions & FRAMEOPTION_END_OFFSET_PRECEDING)
6885 appendStringInfoString(buf, " PRECEDING ");
6886 else if (frameOptions & FRAMEOPTION_END_OFFSET_FOLLOWING)
6887 appendStringInfoString(buf, " FOLLOWING ");
6888 else
6889 Assert(false);
6890 }
6891 else
6892 Assert(false);
6893 }
6894 if (frameOptions & FRAMEOPTION_EXCLUDE_CURRENT_ROW)
6895 appendStringInfoString(buf, "EXCLUDE CURRENT ROW ");
6896 else if (frameOptions & FRAMEOPTION_EXCLUDE_GROUP)
6897 appendStringInfoString(buf, "EXCLUDE GROUP ");
6898 else if (frameOptions & FRAMEOPTION_EXCLUDE_TIES)
6899 appendStringInfoString(buf, "EXCLUDE TIES ");
6900 /* we will now have a trailing space; remove it */
6901 buf->data[--(buf->len)] = '\0';
6902 }
6903 }
6904
6905 /*
6906 * Return the description of a window's framing options as a palloc'd string
6907 */
6908 char *
6909 get_window_frame_options_for_explain(int frameOptions,
6910 Node *startOffset, Node *endOffset,
6911 List *dpcontext, bool forceprefix)
6912 {
6913 StringInfoData buf;
6914 deparse_context context;
6915
6916 initStringInfo(&buf);
6917 context.buf = &buf;
6918 context.namespaces = dpcontext;
6919 context.resultDesc = NULL;
6920 context.targetList = NIL;
6921 context.windowClause = NIL;
6922 context.varprefix = forceprefix;
6923 context.prettyFlags = 0;
6924 context.wrapColumn = WRAP_COLUMN_DEFAULT;
6925 context.indentLevel = 0;
6926 context.colNamesVisible = true;
6927 context.inGroupBy = false;
6928 context.varInOrderBy = false;
6929 context.appendparents = NULL;
6930
6931 get_window_frame_options(frameOptions, startOffset, endOffset, &context);
6932
6933 return buf.data;
6934 }
6935
6936 /* ----------
6937 * get_insert_query_def - Parse back an INSERT parsetree
6938 * ----------
6939 */
6940 static void
6941 get_insert_query_def(Query *query, deparse_context *context)
6942 {
6943 StringInfo buf = context->buf;
6944 RangeTblEntry *select_rte = NULL;
6945 RangeTblEntry *values_rte = NULL;
6946 RangeTblEntry *rte;
6947 char *sep;
6948 ListCell *l;
6949 List *strippedexprs;
6950
6951 /* Insert the WITH clause if given */
6952 get_with_clause(query, context);
6953
6954 /*
6955 * If it's an INSERT ... SELECT or multi-row VALUES, there will be a
6956 * single RTE for the SELECT or VALUES. Plain VALUES has neither.
6957 */
6958 foreach(l, query->rtable)
6959 {
6960 rte = (RangeTblEntry *) lfirst(l);
6961
6962 if (rte->rtekind == RTE_SUBQUERY)
6963 {
6964 if (select_rte)
6965 elog(ERROR, "too many subquery RTEs in INSERT");
6966 select_rte = rte;
6967 }
6968
6969 if (rte->rtekind == RTE_VALUES)
6970 {
6971 if (values_rte)
6972 elog(ERROR, "too many values RTEs in INSERT");
6973 values_rte = rte;
6974 }
6975 }
6976 if (select_rte && values_rte)
6977 elog(ERROR, "both subquery and values RTEs in INSERT");
6978
6979 /*
6980 * Start the query with INSERT INTO relname
6981 */
6982 rte = rt_fetch(query->resultRelation, query->rtable);
6983 Assert(rte->rtekind == RTE_RELATION);
6984
6985 if (PRETTY_INDENT(context))
6986 {
6987 context->indentLevel += PRETTYINDENT_STD;
6988 appendStringInfoChar(buf, ' ');
6989 }
6990 appendStringInfo(buf, "INSERT INTO %s",
6991 generate_relation_name(rte->relid, NIL));
6992
6993 /* Print the relation alias, if needed; INSERT requires explicit AS */
6994 get_rte_alias(rte, query->resultRelation, true, context);
6995
6996 /* always want a space here */
6997 appendStringInfoChar(buf, ' ');
6998
6999 /*
7000 * Add the insert-column-names list. Any indirection decoration needed on
7001 * the column names can be inferred from the top targetlist.
7002 */
7003 strippedexprs = NIL;
7004 sep = "";
7005 if (query->targetList)
7006 appendStringInfoChar(buf, '(');
7007 foreach(l, query->targetList)
7008 {
7009 TargetEntry *tle = (TargetEntry *) lfirst(l);
7010
7011 if (tle->resjunk)
7012 continue; /* ignore junk entries */
7013
7014 appendStringInfoString(buf, sep);
7015 sep = ", ";
7016
7017 /*
7018 * Put out name of target column; look in the catalogs, not at
7019 * tle->resname, since resname will fail to track RENAME.
7020 */
7021 appendStringInfoString(buf,
7022 quote_identifier(get_attname(rte->relid,
7023 tle->resno,
7024 false)));
7025
7026 /*
7027 * Print any indirection needed (subfields or subscripts), and strip
7028 * off the top-level nodes representing the indirection assignments.
7029 * Add the stripped expressions to strippedexprs. (If it's a
7030 * single-VALUES statement, the stripped expressions are the VALUES to
7031 * print below. Otherwise they're just Vars and not really
7032 * interesting.)
7033 */
7034 strippedexprs = lappend(strippedexprs,
7035 processIndirection((Node *) tle->expr,
7036 context));
7037 }
7038 if (query->targetList)
7039 appendStringInfoString(buf, ") ");
7040
7041 if (query->override)
7042 {
7043 if (query->override == OVERRIDING_SYSTEM_VALUE)
7044 appendStringInfoString(buf, "OVERRIDING SYSTEM VALUE ");
7045 else if (query->override == OVERRIDING_USER_VALUE)
7046 appendStringInfoString(buf, "OVERRIDING USER VALUE ");
7047 }
7048
7049 if (select_rte)
7050 {
7051 /* Add the SELECT */
7052 get_query_def(select_rte->subquery, buf, context->namespaces, NULL,
7053 false,
7054 context->prettyFlags, context->wrapColumn,
7055 context->indentLevel);
7056 }
7057 else if (values_rte)
7058 {
7059 /* Add the multi-VALUES expression lists */
7060 get_values_def(values_rte->values_lists, context);
7061 }
7062 else if (strippedexprs)
7063 {
7064 /* Add the single-VALUES expression list */
7065 appendContextKeyword(context, "VALUES (",
7066 -PRETTYINDENT_STD, PRETTYINDENT_STD, 2);
7067 get_rule_list_toplevel(strippedexprs, context, false);
7068 appendStringInfoChar(buf, ')');
7069 }
7070 else
7071 {
7072 /* No expressions, so it must be DEFAULT VALUES */
7073 appendStringInfoString(buf, "DEFAULT VALUES");
7074 }
7075
7076 /* Add ON CONFLICT if present */
7077 if (query->onConflict)
7078 {
7079 OnConflictExpr *confl = query->onConflict;
7080
7081 appendStringInfoString(buf, " ON CONFLICT");
7082
7083 if (confl->arbiterElems)
7084 {
7085 /* Add the single-VALUES expression list */
7086 appendStringInfoChar(buf, '(');
7087 get_rule_expr((Node *) confl->arbiterElems, context, false);
7088 appendStringInfoChar(buf, ')');
7089
7090 /* Add a WHERE clause (for partial indexes) if given */
7091 if (confl->arbiterWhere != NULL)
7092 {
7093 bool save_varprefix;
7094
7095 /*
7096 * Force non-prefixing of Vars, since parser assumes that they
7097 * belong to target relation. WHERE clause does not use
7098 * InferenceElem, so this is separately required.
7099 */
7100 save_varprefix = context->varprefix;
7101 context->varprefix = false;
7102
7103 appendContextKeyword(context, " WHERE ",
7104 -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
7105 get_rule_expr(confl->arbiterWhere, context, false);
7106
7107 context->varprefix = save_varprefix;
7108 }
7109 }
7110 else if (OidIsValid(confl->constraint))
7111 {
7112 char *constraint = get_constraint_name(confl->constraint);
7113
7114 if (!constraint)
7115 elog(ERROR, "cache lookup failed for constraint %u",
7116 confl->constraint);
7117 appendStringInfo(buf, " ON CONSTRAINT %s",
7118 quote_identifier(constraint));
7119 }
7120
7121 if (confl->action == ONCONFLICT_NOTHING)
7122 {
7123 appendStringInfoString(buf, " DO NOTHING");
7124 }
7125 else
7126 {
7127 appendStringInfoString(buf, " DO UPDATE SET ");
7128 /* Deparse targetlist */
7129 get_update_query_targetlist_def(query, confl->onConflictSet,
7130 context, rte);
7131
7132 /* Add a WHERE clause if given */
7133 if (confl->onConflictWhere != NULL)
7134 {
7135 appendContextKeyword(context, " WHERE ",
7136 -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
7137 get_rule_expr(confl->onConflictWhere, context, false);
7138 }
7139 }
7140 }
7141
7142 /* Add RETURNING if present */
7143 if (query->returningList)
7144 get_returning_clause(query, context);
7145 }
7146
7147
7148 /* ----------
7149 * get_update_query_def - Parse back an UPDATE parsetree
7150 * ----------
7151 */
7152 static void
7153 get_update_query_def(Query *query, deparse_context *context)
7154 {
7155 StringInfo buf = context->buf;
7156 RangeTblEntry *rte;
7157
7158 /* Insert the WITH clause if given */
7159 get_with_clause(query, context);
7160
7161 /*
7162 * Start the query with UPDATE relname SET
7163 */
7164 rte = rt_fetch(query->resultRelation, query->rtable);
7165 Assert(rte->rtekind == RTE_RELATION);
7166 if (PRETTY_INDENT(context))
7167 {
7168 appendStringInfoChar(buf, ' ');
7169 context->indentLevel += PRETTYINDENT_STD;
7170 }
7171 appendStringInfo(buf, "UPDATE %s%s",
7172 only_marker(rte),
7173 generate_relation_name(rte->relid, NIL));
7174
7175 /* Print the relation alias, if needed */
7176 get_rte_alias(rte, query->resultRelation, false, context);
7177
7178 appendStringInfoString(buf, " SET ");
7179
7180 /* Deparse targetlist */
7181 get_update_query_targetlist_def(query, query->targetList, context, rte);
7182
7183 /* Add the FROM clause if needed */
7184 get_from_clause(query, " FROM ", context);
7185
7186 /* Add a WHERE clause if given */
7187 if (query->jointree->quals != NULL)
7188 {
7189 appendContextKeyword(context, " WHERE ",
7190 -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
7191 get_rule_expr(query->jointree->quals, context, false);
7192 }
7193
7194 /* Add RETURNING if present */
7195 if (query->returningList)
7196 get_returning_clause(query, context);
7197 }
7198
7199
7200 /* ----------
7201 * get_update_query_targetlist_def - Parse back an UPDATE targetlist
7202 * ----------
7203 */
7204 static void
7205 get_update_query_targetlist_def(Query *query, List *targetList,
7206 deparse_context *context, RangeTblEntry *rte)
7207 {
7208 StringInfo buf = context->buf;
7209 ListCell *l;
7210 ListCell *next_ma_cell;
7211 int remaining_ma_columns;
7212 const char *sep;
7213 SubLink *cur_ma_sublink;
7214 List *ma_sublinks;
7215
7216 /*
7217 * Prepare to deal with MULTIEXPR assignments: collect the source SubLinks
7218 * into a list. We expect them to appear, in ID order, in resjunk tlist
7219 * entries.
7220 */
7221 ma_sublinks = NIL;
7222 if (query->hasSubLinks) /* else there can't be any */
7223 {
7224 foreach(l, targetList)
7225 {
7226 TargetEntry *tle = (TargetEntry *) lfirst(l);
7227
7228 if (tle->resjunk && IsA(tle->expr, SubLink))
7229 {
7230 SubLink *sl = (SubLink *) tle->expr;
7231
7232 if (sl->subLinkType == MULTIEXPR_SUBLINK)
7233 {
7234 ma_sublinks = lappend(ma_sublinks, sl);
7235 Assert(sl->subLinkId == list_length(ma_sublinks));
7236 }
7237 }
7238 }
7239 }
7240 next_ma_cell = list_head(ma_sublinks);
7241 cur_ma_sublink = NULL;
7242 remaining_ma_columns = 0;
7243
7244 /* Add the comma separated list of 'attname = value' */
7245 sep = "";
7246 foreach(l, targetList)
7247 {
7248 TargetEntry *tle = (TargetEntry *) lfirst(l);
7249 Node *expr;
7250
7251 if (tle->resjunk)
7252 continue; /* ignore junk entries */
7253
7254 /* Emit separator (OK whether we're in multiassignment or not) */
7255 appendStringInfoString(buf, sep);
7256 sep = ", ";
7257
7258 /*
7259 * Check to see if we're starting a multiassignment group: if so,
7260 * output a left paren.
7261 */
7262 if (next_ma_cell != NULL && cur_ma_sublink == NULL)
7263 {
7264 /*
7265 * We must dig down into the expr to see if it's a PARAM_MULTIEXPR
7266 * Param. That could be buried under FieldStores and
7267 * SubscriptingRefs and CoerceToDomains (cf processIndirection()),
7268 * and underneath those there could be an implicit type coercion.
7269 * Because we would ignore implicit type coercions anyway, we
7270 * don't need to be as careful as processIndirection() is about
7271 * descending past implicit CoerceToDomains.
7272 */
7273 expr = (Node *) tle->expr;
7274 while (expr)
7275 {
7276 if (IsA(expr, FieldStore))
7277 {
7278 FieldStore *fstore = (FieldStore *) expr;
7279
7280 expr = (Node *) linitial(fstore->newvals);
7281 }
7282 else if (IsA(expr, SubscriptingRef))
7283 {
7284 SubscriptingRef *sbsref = (SubscriptingRef *) expr;
7285
7286 if (sbsref->refassgnexpr == NULL)
7287 break;
7288
7289 expr = (Node *) sbsref->refassgnexpr;
7290 }
7291 else if (IsA(expr, CoerceToDomain))
7292 {
7293 CoerceToDomain *cdomain = (CoerceToDomain *) expr;
7294
7295 if (cdomain->coercionformat != COERCE_IMPLICIT_CAST)
7296 break;
7297 expr = (Node *) cdomain->arg;
7298 }
7299 else
7300 break;
7301 }
7302 expr = strip_implicit_coercions(expr);
7303
7304 if (expr && IsA(expr, Param) &&
7305 ((Param *) expr)->paramkind == PARAM_MULTIEXPR)
7306 {
7307 cur_ma_sublink = (SubLink *) lfirst(next_ma_cell);
7308 next_ma_cell = lnext(ma_sublinks, next_ma_cell);
7309 remaining_ma_columns = count_nonjunk_tlist_entries(((Query *) cur_ma_sublink->subselect)->targetList);
7310 Assert(((Param *) expr)->paramid ==
7311 ((cur_ma_sublink->subLinkId << 16) | 1));
7312 appendStringInfoChar(buf, '(');
7313 }
7314 }
7315
7316 /*
7317 * Put out name of target column; look in the catalogs, not at
7318 * tle->resname, since resname will fail to track RENAME.
7319 */
7320 appendStringInfoString(buf,
7321 quote_identifier(get_attname(rte->relid,
7322 tle->resno,
7323 false)));
7324
7325 /*
7326 * Print any indirection needed (subfields or subscripts), and strip
7327 * off the top-level nodes representing the indirection assignments.
7328 */
7329 expr = processIndirection((Node *) tle->expr, context);
7330
7331 /*
7332 * If we're in a multiassignment, skip printing anything more, unless
7333 * this is the last column; in which case, what we print should be the
7334 * sublink, not the Param.
7335 */
7336 if (cur_ma_sublink != NULL)
7337 {
7338 if (--remaining_ma_columns > 0)
7339 continue; /* not the last column of multiassignment */
7340 appendStringInfoChar(buf, ')');
7341 expr = (Node *) cur_ma_sublink;
7342 cur_ma_sublink = NULL;
7343 }
7344
7345 appendStringInfoString(buf, " = ");
7346
7347 get_rule_expr(expr, context, false);
7348 }
7349 }
7350
7351
7352 /* ----------
7353 * get_delete_query_def - Parse back a DELETE parsetree
7354 * ----------
7355 */
7356 static void
7357 get_delete_query_def(Query *query, deparse_context *context)
7358 {
7359 StringInfo buf = context->buf;
7360 RangeTblEntry *rte;
7361
7362 /* Insert the WITH clause if given */
7363 get_with_clause(query, context);
7364
7365 /*
7366 * Start the query with DELETE FROM relname
7367 */
7368 rte = rt_fetch(query->resultRelation, query->rtable);
7369 Assert(rte->rtekind == RTE_RELATION);
7370 if (PRETTY_INDENT(context))
7371 {
7372 appendStringInfoChar(buf, ' ');
7373 context->indentLevel += PRETTYINDENT_STD;
7374 }
7375 appendStringInfo(buf, "DELETE FROM %s%s",
7376 only_marker(rte),
7377 generate_relation_name(rte->relid, NIL));
7378
7379 /* Print the relation alias, if needed */
7380 get_rte_alias(rte, query->resultRelation, false, context);
7381
7382 /* Add the USING clause if given */
7383 get_from_clause(query, " USING ", context);
7384
7385 /* Add a WHERE clause if given */
7386 if (query->jointree->quals != NULL)
7387 {
7388 appendContextKeyword(context, " WHERE ",
7389 -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
7390 get_rule_expr(query->jointree->quals, context, false);
7391 }
7392
7393 /* Add RETURNING if present */
7394 if (query->returningList)
7395 get_returning_clause(query, context);
7396 }
7397
7398
7399 /* ----------
7400 * get_merge_query_def - Parse back a MERGE parsetree
7401 * ----------
7402 */
7403 static void
7404 get_merge_query_def(Query *query, deparse_context *context)
7405 {
7406 StringInfo buf = context->buf;
7407 RangeTblEntry *rte;
7408 ListCell *lc;
7409 bool haveNotMatchedBySource;
7410
7411 /* Insert the WITH clause if given */
7412 get_with_clause(query, context);
7413
7414 /*
7415 * Start the query with MERGE INTO relname
7416 */
7417 rte = rt_fetch(query->resultRelation, query->rtable);
7418 Assert(rte->rtekind == RTE_RELATION);
7419 if (PRETTY_INDENT(context))
7420 {
7421 appendStringInfoChar(buf, ' ');
7422 context->indentLevel += PRETTYINDENT_STD;
7423 }
7424 appendStringInfo(buf, "MERGE INTO %s%s",
7425 only_marker(rte),
7426 generate_relation_name(rte->relid, NIL));
7427
7428 /* Print the relation alias, if needed */
7429 get_rte_alias(rte, query->resultRelation, false, context);
7430
7431 /* Print the source relation and join clause */
7432 get_from_clause(query, " USING ", context);
7433 appendContextKeyword(context, " ON ",
7434 -PRETTYINDENT_STD, PRETTYINDENT_STD, 2);
7435 get_rule_expr(query->mergeJoinCondition, context, false);
7436
7437 /*
7438 * Test for any NOT MATCHED BY SOURCE actions. If there are none, then
7439 * any NOT MATCHED BY TARGET actions are output as "WHEN NOT MATCHED", per
7440 * SQL standard. Otherwise, we have a non-SQL-standard query, so output
7441 * "BY SOURCE" / "BY TARGET" qualifiers for all NOT MATCHED actions, to be
7442 * more explicit.
7443 */
7444 haveNotMatchedBySource = false;
7445 foreach(lc, query->mergeActionList)
7446 {
7447 MergeAction *action = lfirst_node(MergeAction, lc);
7448
7449 if (action->matchKind == MERGE_WHEN_NOT_MATCHED_BY_SOURCE)
7450 {
7451 haveNotMatchedBySource = true;
7452 break;
7453 }
7454 }
7455
7456 /* Print each merge action */
7457 foreach(lc, query->mergeActionList)
7458 {
7459 MergeAction *action = lfirst_node(MergeAction, lc);
7460
7461 appendContextKeyword(context, " WHEN ",
7462 -PRETTYINDENT_STD, PRETTYINDENT_STD, 2);
7463 switch (action->matchKind)
7464 {
7465 case MERGE_WHEN_MATCHED:
7466 appendStringInfoString(buf, "MATCHED");
7467 break;
7468 case MERGE_WHEN_NOT_MATCHED_BY_SOURCE:
7469 appendStringInfoString(buf, "NOT MATCHED BY SOURCE");
7470 break;
7471 case MERGE_WHEN_NOT_MATCHED_BY_TARGET:
7472 if (haveNotMatchedBySource)
7473 appendStringInfoString(buf, "NOT MATCHED BY TARGET");
7474 else
7475 appendStringInfoString(buf, "NOT MATCHED");
7476 break;
7477 default:
7478 elog(ERROR, "unrecognized matchKind: %d",
7479 (int) action->matchKind);
7480 }
7481
7482 if (action->qual)
7483 {
7484 appendContextKeyword(context, " AND ",
7485 -PRETTYINDENT_STD, PRETTYINDENT_STD, 3);
7486 get_rule_expr(action->qual, context, false);
7487 }
7488 appendContextKeyword(context, " THEN ",
7489 -PRETTYINDENT_STD, PRETTYINDENT_STD, 3);
7490
7491 if (action->commandType == CMD_INSERT)
7492 {
7493 /* This generally matches get_insert_query_def() */
7494 List *strippedexprs = NIL;
7495 const char *sep = "";
7496 ListCell *lc2;
7497
7498 appendStringInfoString(buf, "INSERT");
7499
7500 if (action->targetList)
7501 appendStringInfoString(buf, " (");
7502 foreach(lc2, action->targetList)
7503 {
7504 TargetEntry *tle = (TargetEntry *) lfirst(lc2);
7505
7506 Assert(!tle->resjunk);
7507
7508 appendStringInfoString(buf, sep);
7509 sep = ", ";
7510
7511 appendStringInfoString(buf,
7512 quote_identifier(get_attname(rte->relid,
7513 tle->resno,
7514 false)));
7515 strippedexprs = lappend(strippedexprs,
7516 processIndirection((Node *) tle->expr,
7517 context));
7518 }
7519 if (action->targetList)
7520 appendStringInfoChar(buf, ')');
7521
7522 if (action->override)
7523 {
7524 if (action->override == OVERRIDING_SYSTEM_VALUE)
7525 appendStringInfoString(buf, " OVERRIDING SYSTEM VALUE");
7526 else if (action->override == OVERRIDING_USER_VALUE)
7527 appendStringInfoString(buf, " OVERRIDING USER VALUE");
7528 }
7529
7530 if (strippedexprs)
7531 {
7532 appendContextKeyword(context, " VALUES (",
7533 -PRETTYINDENT_STD, PRETTYINDENT_STD, 4);
7534 get_rule_list_toplevel(strippedexprs, context, false);
7535 appendStringInfoChar(buf, ')');
7536 }
7537 else
7538 appendStringInfoString(buf, " DEFAULT VALUES");
7539 }
7540 else if (action->commandType == CMD_UPDATE)
7541 {
7542 appendStringInfoString(buf, "UPDATE SET ");
7543 get_update_query_targetlist_def(query, action->targetList,
7544 context, rte);
7545 }
7546 else if (action->commandType == CMD_DELETE)
7547 appendStringInfoString(buf, "DELETE");
7548 else if (action->commandType == CMD_NOTHING)
7549 appendStringInfoString(buf, "DO NOTHING");
7550 }
7551
7552 /* Add RETURNING if present */
7553 if (query->returningList)
7554 get_returning_clause(query, context);
7555 }
7556
7557
7558 /* ----------
7559 * get_utility_query_def - Parse back a UTILITY parsetree
7560 * ----------
7561 */
7562 static void
7563 get_utility_query_def(Query *query, deparse_context *context)
7564 {
7565 StringInfo buf = context->buf;
7566
7567 if (query->utilityStmt && IsA(query->utilityStmt, NotifyStmt))
7568 {
7569 NotifyStmt *stmt = (NotifyStmt *) query->utilityStmt;
7570
7571 appendContextKeyword(context, "",
7572 0, PRETTYINDENT_STD, 1);
7573 appendStringInfo(buf, "NOTIFY %s",
7574 quote_identifier(stmt->conditionname));
7575 if (stmt->payload)
7576 {
7577 appendStringInfoString(buf, ", ");
7578 simple_quote_literal(buf, stmt->payload);
7579 }
7580 }
7581 else
7582 {
7583 /* Currently only NOTIFY utility commands can appear in rules */
7584 elog(ERROR, "unexpected utility statement type");
7585 }
7586 }
7587
7588 /*
7589 * Display a Var appropriately.
7590 *
7591 * In some cases (currently only when recursing into an unnamed join)
7592 * the Var's varlevelsup has to be interpreted with respect to a context
7593 * above the current one; levelsup indicates the offset.
7594 *
7595 * If istoplevel is true, the Var is at the top level of a SELECT's
7596 * targetlist, which means we need special treatment of whole-row Vars.
7597 * Instead of the normal "tab.*", we'll print "tab.*::typename", which is a
7598 * dirty hack to prevent "tab.*" from being expanded into multiple columns.
7599 * (The parser will strip the useless coercion, so no inefficiency is added in
7600 * dump and reload.) We used to print just "tab" in such cases, but that is
7601 * ambiguous and will yield the wrong result if "tab" is also a plain column
7602 * name in the query.
7603 *
7604 * Returns the attname of the Var, or NULL if the Var has no attname (because
7605 * it is a whole-row Var or a subplan output reference).
7606 */
7607 static char *
7608 get_variable(Var *var, int levelsup, bool istoplevel, deparse_context *context)
7609 {
7610 StringInfo buf = context->buf;
7611 RangeTblEntry *rte;
7612 AttrNumber attnum;
7613 int netlevelsup;
7614 deparse_namespace *dpns;
7615 int varno;
7616 AttrNumber varattno;
7617 deparse_columns *colinfo;
7618 char *refname;
7619 char *attname;
7620 bool need_prefix;
7621
7622 /* Find appropriate nesting depth */
7623 netlevelsup = var->varlevelsup + levelsup;
7624 if (netlevelsup >= list_length(context->namespaces))
7625 elog(ERROR, "bogus varlevelsup: %d offset %d",
7626 var->varlevelsup, levelsup);
7627 dpns = (deparse_namespace *) list_nth(context->namespaces,
7628 netlevelsup);
7629
7630 /*
7631 * If we have a syntactic referent for the Var, and we're working from a
7632 * parse tree, prefer to use the syntactic referent. Otherwise, fall back
7633 * on the semantic referent. (Forcing use of the semantic referent when
7634 * printing plan trees is a design choice that's perhaps more motivated by
7635 * backwards compatibility than anything else. But it does have the
7636 * advantage of making plans more explicit.)
7637 */
7638 if (var->varnosyn > 0 && dpns->plan == NULL)
7639 {
7640 varno = var->varnosyn;
7641 varattno = var->varattnosyn;
7642 }
7643 else
7644 {
7645 varno = var->varno;
7646 varattno = var->varattno;
7647 }
7648
7649 /*
7650 * Try to find the relevant RTE in this rtable. In a plan tree, it's
7651 * likely that varno is OUTER_VAR or INNER_VAR, in which case we must dig
7652 * down into the subplans, or INDEX_VAR, which is resolved similarly. Also
7653 * find the aliases previously assigned for this RTE.
7654 */
7655 if (varno >= 1 && varno <= list_length(dpns->rtable))
7656 {
7657 /*
7658 * We might have been asked to map child Vars to some parent relation.
7659 */
7660 if (context->appendparents && dpns->appendrels)
7661 {
7662 int pvarno = varno;
7663 AttrNumber pvarattno = varattno;
7664 AppendRelInfo *appinfo = dpns->appendrels[pvarno];
7665 bool found = false;
7666
7667 /* Only map up to inheritance parents, not UNION ALL appendrels */
7668 while (appinfo &&
7669 rt_fetch(appinfo->parent_relid,
7670 dpns->rtable)->rtekind == RTE_RELATION)
7671 {
7672 found = false;
7673 if (pvarattno > 0) /* system columns stay as-is */
7674 {
7675 if (pvarattno > appinfo->num_child_cols)
7676 break; /* safety check */
7677 pvarattno = appinfo->parent_colnos[pvarattno - 1];
7678 if (pvarattno == 0)
7679 break; /* Var is local to child */
7680 }
7681
7682 pvarno = appinfo->parent_relid;
7683 found = true;
7684
7685 /* If the parent is itself a child, continue up. */
7686 Assert(pvarno > 0 && pvarno <= list_length(dpns->rtable));
7687 appinfo = dpns->appendrels[pvarno];
7688 }
7689
7690 /*
7691 * If we found an ancestral rel, and that rel is included in
7692 * appendparents, print that column not the original one.
7693 */
7694 if (found && bms_is_member(pvarno, context->appendparents))
7695 {
7696 varno = pvarno;
7697 varattno = pvarattno;
7698 }
7699 }
7700
7701 rte = rt_fetch(varno, dpns->rtable);
7702
7703 /* might be returning old/new column value */
7704 if (var->varreturningtype == VAR_RETURNING_OLD)
7705 refname = dpns->ret_old_alias;
7706 else if (var->varreturningtype == VAR_RETURNING_NEW)
7707 refname = dpns->ret_new_alias;
7708 else
7709 refname = (char *) list_nth(dpns->rtable_names, varno - 1);
7710
7711 colinfo = deparse_columns_fetch(varno, dpns);
7712 attnum = varattno;
7713 }
7714 else
7715 {
7716 resolve_special_varno((Node *) var, context,
7717 get_special_variable, NULL);
7718 return NULL;
7719 }
7720
7721 /*
7722 * The planner will sometimes emit Vars referencing resjunk elements of a
7723 * subquery's target list (this is currently only possible if it chooses
7724 * to generate a "physical tlist" for a SubqueryScan or CteScan node).
7725 * Although we prefer to print subquery-referencing Vars using the
7726 * subquery's alias, that's not possible for resjunk items since they have
7727 * no alias. So in that case, drill down to the subplan and print the
7728 * contents of the referenced tlist item. This works because in a plan
7729 * tree, such Vars can only occur in a SubqueryScan or CteScan node, and
7730 * we'll have set dpns->inner_plan to reference the child plan node.
7731 */
7732 if ((rte->rtekind == RTE_SUBQUERY || rte->rtekind == RTE_CTE) &&
7733 attnum > list_length(rte->eref->colnames) &&
7734 dpns->inner_plan)
7735 {
7736 TargetEntry *tle;
7737 deparse_namespace save_dpns;
7738
7739 tle = get_tle_by_resno(dpns->inner_tlist, attnum);
7740 if (!tle)
7741 elog(ERROR, "invalid attnum %d for relation \"%s\"",
7742 attnum, rte->eref->aliasname);
7743
7744 Assert(netlevelsup == 0);
7745 push_child_plan(dpns, dpns->inner_plan, &save_dpns);
7746
7747 /*
7748 * Force parentheses because our caller probably assumed a Var is a
7749 * simple expression.
7750 */
7751 if (!IsA(tle->expr, Var))
7752 appendStringInfoChar(buf, '(');
7753 get_rule_expr((Node *) tle->expr, context, true);
7754 if (!IsA(tle->expr, Var))
7755 appendStringInfoChar(buf, ')');
7756
7757 pop_child_plan(dpns, &save_dpns);
7758 return NULL;
7759 }
7760
7761 /*
7762 * If it's an unnamed join, look at the expansion of the alias variable.
7763 * If it's a simple reference to one of the input vars, then recursively
7764 * print the name of that var instead. When it's not a simple reference,
7765 * we have to just print the unqualified join column name. (This can only
7766 * happen with "dangerous" merged columns in a JOIN USING; we took pains
7767 * previously to make the unqualified column name unique in such cases.)
7768 *
7769 * This wouldn't work in decompiling plan trees, because we don't store
7770 * joinaliasvars lists after planning; but a plan tree should never
7771 * contain a join alias variable.
7772 */
7773 if (rte->rtekind == RTE_JOIN && rte->alias == NULL)
7774 {
7775 if (rte->joinaliasvars == NIL)
7776 elog(ERROR, "cannot decompile join alias var in plan tree");
7777 if (attnum > 0)
7778 {
7779 Var *aliasvar;
7780
7781 aliasvar = (Var *) list_nth(rte->joinaliasvars, attnum - 1);
7782 /* we intentionally don't strip implicit coercions here */
7783 if (aliasvar && IsA(aliasvar, Var))
7784 {
7785 return get_variable(aliasvar, var->varlevelsup + levelsup,
7786 istoplevel, context);
7787 }
7788 }
7789
7790 /*
7791 * Unnamed join has no refname. (Note: since it's unnamed, there is
7792 * no way the user could have referenced it to create a whole-row Var
7793 * for it. So we don't have to cover that case below.)
7794 */
7795 Assert(refname == NULL);
7796 }
7797
7798 if (attnum == InvalidAttrNumber)
7799 attname = NULL;
7800 else if (attnum > 0)
7801 {
7802 /* Get column name to use from the colinfo struct */
7803 if (attnum > colinfo->num_cols)
7804 elog(ERROR, "invalid attnum %d for relation \"%s\"",
7805 attnum, rte->eref->aliasname);
7806 attname = colinfo->colnames[attnum - 1];
7807
7808 /*
7809 * If we find a Var referencing a dropped column, it seems better to
7810 * print something (anything) than to fail. In general this should
7811 * not happen, but it used to be possible for some cases involving
7812 * functions returning named composite types, and perhaps there are
7813 * still bugs out there.
7814 */
7815 if (attname == NULL)
7816 attname = "?dropped?column?";
7817 }
7818 else
7819 {
7820 /* System column - name is fixed, get it from the catalog */
7821 attname = get_rte_attribute_name(rte, attnum);
7822 }
7823
7824 need_prefix = (context->varprefix || attname == NULL ||
7825 var->varreturningtype != VAR_RETURNING_DEFAULT);
7826
7827 /*
7828 * If we're considering a plain Var in an ORDER BY (but not GROUP BY)
7829 * clause, we may need to add a table-name prefix to prevent
7830 * findTargetlistEntrySQL92 from misinterpreting the name as an
7831 * output-column name. To avoid cluttering the output with unnecessary
7832 * prefixes, do so only if there is a name match to a SELECT tlist item
7833 * that is different from the Var.
7834 */
7835 if (context->varInOrderBy && !context->inGroupBy && !need_prefix)
7836 {
7837 int colno = 0;
7838
7839 foreach_node(TargetEntry, tle, context->targetList)
7840 {
7841 char *colname;
7842
7843 if (tle->resjunk)
7844 continue; /* ignore junk entries */
7845 colno++;
7846
7847 /* This must match colname-choosing logic in get_target_list() */
7848 if (context->resultDesc && colno <= context->resultDesc->natts)
7849 colname = NameStr(TupleDescAttr(context->resultDesc,
7850 colno - 1)->attname);
7851 else
7852 colname = tle->resname;
7853
7854 if (colname && strcmp(colname, attname) == 0 &&
7855 !equal(var, tle->expr))
7856 {
7857 need_prefix = true;
7858 break;
7859 }
7860 }
7861 }
7862
7863 if (refname && need_prefix)
7864 {
7865 appendStringInfoString(buf, quote_identifier(refname));
7866 appendStringInfoChar(buf, '.');
7867 }
7868 if (attname)
7869 appendStringInfoString(buf, quote_identifier(attname));
7870 else
7871 {
7872 appendStringInfoChar(buf, '*');
7873 if (istoplevel)
7874 appendStringInfo(buf, "::%s",
7875 format_type_with_typemod(var->vartype,
7876 var->vartypmod));
7877 }
7878
7879 return attname;
7880 }
7881
7882 /*
7883 * Deparse a Var which references OUTER_VAR, INNER_VAR, or INDEX_VAR. This
7884 * routine is actually a callback for resolve_special_varno, which handles
7885 * finding the correct TargetEntry. We get the expression contained in that
7886 * TargetEntry and just need to deparse it, a job we can throw back on
7887 * get_rule_expr.
7888 */
7889 static void
7890 get_special_variable(Node *node, deparse_context *context, void *callback_arg)
7891 {
7892 StringInfo buf = context->buf;
7893
7894 /*
7895 * For a non-Var referent, force parentheses because our caller probably
7896 * assumed a Var is a simple expression.
7897 */
7898 if (!IsA(node, Var))
7899 appendStringInfoChar(buf, '(');
7900 get_rule_expr(node, context, true);
7901 if (!IsA(node, Var))
7902 appendStringInfoChar(buf, ')');
7903 }
7904
7905 /*
7906 * Chase through plan references to special varnos (OUTER_VAR, INNER_VAR,
7907 * INDEX_VAR) until we find a real Var or some kind of non-Var node; then,
7908 * invoke the callback provided.
7909 */
7910 static void
7911 resolve_special_varno(Node *node, deparse_context *context,
7912 rsv_callback callback, void *callback_arg)
7913 {
7914 Var *var;
7915 deparse_namespace *dpns;
7916
7917 /* This function is recursive, so let's be paranoid. */
7918 check_stack_depth();
7919
7920 /* If it's not a Var, invoke the callback. */
7921 if (!IsA(node, Var))
7922 {
7923 (*callback) (node, context, callback_arg);
7924 return;
7925 }
7926
7927 /* Find appropriate nesting depth */
7928 var = (Var *) node;
7929 dpns = (deparse_namespace *) list_nth(context->namespaces,
7930 var->varlevelsup);
7931
7932 /*
7933 * If varno is special, recurse. (Don't worry about varnosyn; if we're
7934 * here, we already decided not to use that.)
7935 */
7936 if (var->varno == OUTER_VAR && dpns->outer_tlist)
7937 {
7938 TargetEntry *tle;
7939 deparse_namespace save_dpns;
7940 Bitmapset *save_appendparents;
7941
7942 tle = get_tle_by_resno(dpns->outer_tlist, var->varattno);
7943 if (!tle)
7944 elog(ERROR, "bogus varattno for OUTER_VAR var: %d", var->varattno);
7945
7946 /*
7947 * If we're descending to the first child of an Append or MergeAppend,
7948 * update appendparents. This will affect deparsing of all Vars
7949 * appearing within the eventually-resolved subexpression.
7950 */
7951 save_appendparents = context->appendparents;
7952
7953 if (IsA(dpns->plan, Append))
7954 context->appendparents = bms_union(context->appendparents,
7955 ((Append *) dpns->plan)->apprelids);
7956 else if (IsA(dpns->plan, MergeAppend))
7957 context->appendparents = bms_union(context->appendparents,
7958 ((MergeAppend *) dpns->plan)->apprelids);
7959
7960 push_child_plan(dpns, dpns->outer_plan, &save_dpns);
7961 resolve_special_varno((Node *) tle->expr, context,
7962 callback, callback_arg);
7963 pop_child_plan(dpns, &save_dpns);
7964 context->appendparents = save_appendparents;
7965 return;
7966 }
7967 else if (var->varno == INNER_VAR && dpns->inner_tlist)
7968 {
7969 TargetEntry *tle;
7970 deparse_namespace save_dpns;
7971
7972 tle = get_tle_by_resno(dpns->inner_tlist, var->varattno);
7973 if (!tle)
7974 elog(ERROR, "bogus varattno for INNER_VAR var: %d", var->varattno);
7975
7976 push_child_plan(dpns, dpns->inner_plan, &save_dpns);
7977 resolve_special_varno((Node *) tle->expr, context,
7978 callback, callback_arg);
7979 pop_child_plan(dpns, &save_dpns);
7980 return;
7981 }
7982 else if (var->varno == INDEX_VAR && dpns->index_tlist)
7983 {
7984 TargetEntry *tle;
7985
7986 tle = get_tle_by_resno(dpns->index_tlist, var->varattno);
7987 if (!tle)
7988 elog(ERROR, "bogus varattno for INDEX_VAR var: %d", var->varattno);
7989
7990 resolve_special_varno((Node *) tle->expr, context,
7991 callback, callback_arg);
7992 return;
7993 }
7994 else if (var->varno < 1 || var->varno > list_length(dpns->rtable))
7995 elog(ERROR, "bogus varno: %d", var->varno);
7996
7997 /* Not special. Just invoke the callback. */
7998 (*callback) (node, context, callback_arg);
7999 }
8000
8001 /*
8002 * Get the name of a field of an expression of composite type. The
8003 * expression is usually a Var, but we handle other cases too.
8004 *
8005 * levelsup is an extra offset to interpret the Var's varlevelsup correctly.
8006 *
8007 * This is fairly straightforward when the expression has a named composite
8008 * type; we need only look up the type in the catalogs. However, the type
8009 * could also be RECORD. Since no actual table or view column is allowed to
8010 * have type RECORD, a Var of type RECORD must refer to a JOIN or FUNCTION RTE
8011 * or to a subquery output. We drill down to find the ultimate defining
8012 * expression and attempt to infer the field name from it. We ereport if we
8013 * can't determine the name.
8014 *
8015 * Similarly, a PARAM of type RECORD has to refer to some expression of
8016 * a determinable composite type.
8017 */
8018 static const char *
8019 get_name_for_var_field(Var *var, int fieldno,
8020 int levelsup, deparse_context *context)
8021 {
8022 RangeTblEntry *rte;
8023 AttrNumber attnum;
8024 int netlevelsup;
8025 deparse_namespace *dpns;
8026 int varno;
8027 AttrNumber varattno;
8028 TupleDesc tupleDesc;
8029 Node *expr;
8030
8031 /*
8032 * If it's a RowExpr that was expanded from a whole-row Var, use the
8033 * column names attached to it. (We could let get_expr_result_tupdesc()
8034 * handle this, but it's much cheaper to just pull out the name we need.)
8035 */
8036 if (IsA(var, RowExpr))
8037 {
8038 RowExpr *r = (RowExpr *) var;
8039
8040 if (fieldno > 0 && fieldno <= list_length(r->colnames))
8041 return strVal(list_nth(r->colnames, fieldno - 1));
8042 }
8043
8044 /*
8045 * If it's a Param of type RECORD, try to find what the Param refers to.
8046 */
8047 if (IsA(var, Param))
8048 {
8049 Param *param = (Param *) var;
8050 ListCell *ancestor_cell;
8051
8052 expr = find_param_referent(param, context, &dpns, &ancestor_cell);
8053 if (expr)
8054 {
8055 /* Found a match, so recurse to decipher the field name */
8056 deparse_namespace save_dpns;
8057 const char *result;
8058
8059 push_ancestor_plan(dpns, ancestor_cell, &save_dpns);
8060 result = get_name_for_var_field((Var *) expr, fieldno,
8061 0, context);
8062 pop_ancestor_plan(dpns, &save_dpns);
8063 return result;
8064 }
8065 }
8066
8067 /*
8068 * If it's a Var of type RECORD, we have to find what the Var refers to;
8069 * if not, we can use get_expr_result_tupdesc().
8070 */
8071 if (!IsA(var, Var) ||
8072 var->vartype != RECORDOID)
8073 {
8074 tupleDesc = get_expr_result_tupdesc((Node *) var, false);
8075 /* Got the tupdesc, so we can extract the field name */
8076 Assert(fieldno >= 1 && fieldno <= tupleDesc->natts);
8077 return NameStr(TupleDescAttr(tupleDesc, fieldno - 1)->attname);
8078 }
8079
8080 /* Find appropriate nesting depth */
8081 netlevelsup = var->varlevelsup + levelsup;
8082 if (netlevelsup >= list_length(context->namespaces))
8083 elog(ERROR, "bogus varlevelsup: %d offset %d",
8084 var->varlevelsup, levelsup);
8085 dpns = (deparse_namespace *) list_nth(context->namespaces,
8086 netlevelsup);
8087
8088 /*
8089 * If we have a syntactic referent for the Var, and we're working from a
8090 * parse tree, prefer to use the syntactic referent. Otherwise, fall back
8091 * on the semantic referent. (See comments in get_variable().)
8092 */
8093 if (var->varnosyn > 0 && dpns->plan == NULL)
8094 {
8095 varno = var->varnosyn;
8096 varattno = var->varattnosyn;
8097 }
8098 else
8099 {
8100 varno = var->varno;
8101 varattno = var->varattno;
8102 }
8103
8104 /*
8105 * Try to find the relevant RTE in this rtable. In a plan tree, it's
8106 * likely that varno is OUTER_VAR or INNER_VAR, in which case we must dig
8107 * down into the subplans, or INDEX_VAR, which is resolved similarly.
8108 *
8109 * Note: unlike get_variable and resolve_special_varno, we need not worry
8110 * about inheritance mapping: a child Var should have the same datatype as
8111 * its parent, and here we're really only interested in the Var's type.
8112 */
8113 if (varno >= 1 && varno <= list_length(dpns->rtable))
8114 {
8115 rte = rt_fetch(varno, dpns->rtable);
8116 attnum = varattno;
8117 }
8118 else if (varno == OUTER_VAR && dpns->outer_tlist)
8119 {
8120 TargetEntry *tle;
8121 deparse_namespace save_dpns;
8122 const char *result;
8123
8124 tle = get_tle_by_resno(dpns->outer_tlist, varattno);
8125 if (!tle)
8126 elog(ERROR, "bogus varattno for OUTER_VAR var: %d", varattno);
8127
8128 Assert(netlevelsup == 0);
8129 push_child_plan(dpns, dpns->outer_plan, &save_dpns);
8130
8131 result = get_name_for_var_field((Var *) tle->expr, fieldno,
8132 levelsup, context);
8133
8134 pop_child_plan(dpns, &save_dpns);
8135 return result;
8136 }
8137 else if (varno == INNER_VAR && dpns->inner_tlist)
8138 {
8139 TargetEntry *tle;
8140 deparse_namespace save_dpns;
8141 const char *result;
8142
8143 tle = get_tle_by_resno(dpns->inner_tlist, varattno);
8144 if (!tle)
8145 elog(ERROR, "bogus varattno for INNER_VAR var: %d", varattno);
8146
8147 Assert(netlevelsup == 0);
8148 push_child_plan(dpns, dpns->inner_plan, &save_dpns);
8149
8150 result = get_name_for_var_field((Var *) tle->expr, fieldno,
8151 levelsup, context);
8152
8153 pop_child_plan(dpns, &save_dpns);
8154 return result;
8155 }
8156 else if (varno == INDEX_VAR && dpns->index_tlist)
8157 {
8158 TargetEntry *tle;
8159 const char *result;
8160
8161 tle = get_tle_by_resno(dpns->index_tlist, varattno);
8162 if (!tle)
8163 elog(ERROR, "bogus varattno for INDEX_VAR var: %d", varattno);
8164
8165 Assert(netlevelsup == 0);
8166
8167 result = get_name_for_var_field((Var *) tle->expr, fieldno,
8168 levelsup, context);
8169
8170 return result;
8171 }
8172 else
8173 {
8174 elog(ERROR, "bogus varno: %d", varno);
8175 return NULL; /* keep compiler quiet */
8176 }
8177
8178 if (attnum == InvalidAttrNumber)
8179 {
8180 /* Var is whole-row reference to RTE, so select the right field */
8181 return get_rte_attribute_name(rte, fieldno);
8182 }
8183
8184 /*
8185 * This part has essentially the same logic as the parser's
8186 * expandRecordVariable() function, but we are dealing with a different
8187 * representation of the input context, and we only need one field name
8188 * not a TupleDesc. Also, we need special cases for finding subquery and
8189 * CTE subplans when deparsing Plan trees.
8190 */
8191 expr = (Node *) var; /* default if we can't drill down */
8192
8193 switch (rte->rtekind)
8194 {
8195 case RTE_RELATION:
8196 case RTE_VALUES:
8197 case RTE_NAMEDTUPLESTORE:
8198 case RTE_RESULT:
8199
8200 /*
8201 * This case should not occur: a column of a table, values list,
8202 * or ENR shouldn't have type RECORD. Fall through and fail (most
8203 * likely) at the bottom.
8204 */
8205 break;
8206 case RTE_SUBQUERY:
8207 /* Subselect-in-FROM: examine sub-select's output expr */
8208 {
8209 if (rte->subquery)
8210 {
8211 TargetEntry *ste = get_tle_by_resno(rte->subquery->targetList,
8212 attnum);
8213
8214 if (ste == NULL || ste->resjunk)
8215 elog(ERROR, "subquery %s does not have attribute %d",
8216 rte->eref->aliasname, attnum);
8217 expr = (Node *) ste->expr;
8218 if (IsA(expr, Var))
8219 {
8220 /*
8221 * Recurse into the sub-select to see what its Var
8222 * refers to. We have to build an additional level of
8223 * namespace to keep in step with varlevelsup in the
8224 * subselect; furthermore, the subquery RTE might be
8225 * from an outer query level, in which case the
8226 * namespace for the subselect must have that outer
8227 * level as parent namespace.
8228 */
8229 List *save_nslist = context->namespaces;
8230 List *parent_namespaces;
8231 deparse_namespace mydpns;
8232 const char *result;
8233
8234 parent_namespaces = list_copy_tail(context->namespaces,
8235 netlevelsup);
8236
8237 set_deparse_for_query(&mydpns, rte->subquery,
8238 parent_namespaces);
8239
8240 context->namespaces = lcons(&mydpns, parent_namespaces);
8241
8242 result = get_name_for_var_field((Var *) expr, fieldno,
8243 0, context);
8244
8245 context->namespaces = save_nslist;
8246
8247 return result;
8248 }
8249 /* else fall through to inspect the expression */
8250 }
8251 else
8252 {
8253 /*
8254 * We're deparsing a Plan tree so we don't have complete
8255 * RTE entries (in particular, rte->subquery is NULL). But
8256 * the only place we'd normally see a Var directly
8257 * referencing a SUBQUERY RTE is in a SubqueryScan plan
8258 * node, and we can look into the child plan's tlist
8259 * instead. An exception occurs if the subquery was
8260 * proven empty and optimized away: then we'd find such a
8261 * Var in a childless Result node, and there's nothing in
8262 * the plan tree that would let us figure out what it had
8263 * originally referenced. In that case, fall back on
8264 * printing "fN", analogously to the default column names
8265 * for RowExprs.
8266 */
8267 TargetEntry *tle;
8268 deparse_namespace save_dpns;
8269 const char *result;
8270
8271 if (!dpns->inner_plan)
8272 {
8273 char *dummy_name = palloc(32);
8274
8275 Assert(dpns->plan && IsA(dpns->plan, Result));
8276 snprintf(dummy_name, 32, "f%d", fieldno);
8277 return dummy_name;
8278 }
8279 Assert(dpns->plan && IsA(dpns->plan, SubqueryScan));
8280
8281 tle = get_tle_by_resno(dpns->inner_tlist, attnum);
8282 if (!tle)
8283 elog(ERROR, "bogus varattno for subquery var: %d",
8284 attnum);
8285 Assert(netlevelsup == 0);
8286 push_child_plan(dpns, dpns->inner_plan, &save_dpns);
8287
8288 result = get_name_for_var_field((Var *) tle->expr, fieldno,
8289 levelsup, context);
8290
8291 pop_child_plan(dpns, &save_dpns);
8292 return result;
8293 }
8294 }
8295 break;
8296 case RTE_JOIN:
8297 /* Join RTE --- recursively inspect the alias variable */
8298 if (rte->joinaliasvars == NIL)
8299 elog(ERROR, "cannot decompile join alias var in plan tree");
8300 Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
8301 expr = (Node *) list_nth(rte->joinaliasvars, attnum - 1);
8302 Assert(expr != NULL);
8303 /* we intentionally don't strip implicit coercions here */
8304 if (IsA(expr, Var))
8305 return get_name_for_var_field((Var *) expr, fieldno,
8306 var->varlevelsup + levelsup,
8307 context);
8308 /* else fall through to inspect the expression */
8309 break;
8310 case RTE_FUNCTION:
8311 case RTE_TABLEFUNC:
8312
8313 /*
8314 * We couldn't get here unless a function is declared with one of
8315 * its result columns as RECORD, which is not allowed.
8316 */
8317 break;
8318 case RTE_CTE:
8319 /* CTE reference: examine subquery's output expr */
8320 {
8321 CommonTableExpr *cte = NULL;
8322 Index ctelevelsup;
8323 ListCell *lc;
8324
8325 /*
8326 * Try to find the referenced CTE using the namespace stack.
8327 */
8328 ctelevelsup = rte->ctelevelsup + netlevelsup;
8329 if (ctelevelsup >= list_length(context->namespaces))
8330 lc = NULL;
8331 else
8332 {
8333 deparse_namespace *ctedpns;
8334
8335 ctedpns = (deparse_namespace *)
8336 list_nth(context->namespaces, ctelevelsup);
8337 foreach(lc, ctedpns->ctes)
8338 {
8339 cte = (CommonTableExpr *) lfirst(lc);
8340 if (strcmp(cte->ctename, rte->ctename) == 0)
8341 break;
8342 }
8343 }
8344 if (lc != NULL)
8345 {
8346 Query *ctequery = (Query *) cte->ctequery;
8347 TargetEntry *ste = get_tle_by_resno(GetCTETargetList(cte),
8348 attnum);
8349
8350 if (ste == NULL || ste->resjunk)
8351 elog(ERROR, "CTE %s does not have attribute %d",
8352 rte->eref->aliasname, attnum);
8353 expr = (Node *) ste->expr;
8354 if (IsA(expr, Var))
8355 {
8356 /*
8357 * Recurse into the CTE to see what its Var refers to.
8358 * We have to build an additional level of namespace
8359 * to keep in step with varlevelsup in the CTE;
8360 * furthermore it could be an outer CTE (compare
8361 * SUBQUERY case above).
8362 */
8363 List *save_nslist = context->namespaces;
8364 List *parent_namespaces;
8365 deparse_namespace mydpns;
8366 const char *result;
8367
8368 parent_namespaces = list_copy_tail(context->namespaces,
8369 ctelevelsup);
8370
8371 set_deparse_for_query(&mydpns, ctequery,
8372 parent_namespaces);
8373
8374 context->namespaces = lcons(&mydpns, parent_namespaces);
8375
8376 result = get_name_for_var_field((Var *) expr, fieldno,
8377 0, context);
8378
8379 context->namespaces = save_nslist;
8380
8381 return result;
8382 }
8383 /* else fall through to inspect the expression */
8384 }
8385 else
8386 {
8387 /*
8388 * We're deparsing a Plan tree so we don't have a CTE
8389 * list. But the only places we'd normally see a Var
8390 * directly referencing a CTE RTE are in CteScan or
8391 * WorkTableScan plan nodes. For those cases,
8392 * set_deparse_plan arranged for dpns->inner_plan to be
8393 * the plan node that emits the CTE or RecursiveUnion
8394 * result, and we can look at its tlist instead. As
8395 * above, this can fail if the CTE has been proven empty,
8396 * in which case fall back to "fN".
8397 */
8398 TargetEntry *tle;
8399 deparse_namespace save_dpns;
8400 const char *result;
8401
8402 if (!dpns->inner_plan)
8403 {
8404 char *dummy_name = palloc(32);
8405
8406 Assert(dpns->plan && IsA(dpns->plan, Result));
8407 snprintf(dummy_name, 32, "f%d", fieldno);
8408 return dummy_name;
8409 }
8410 Assert(dpns->plan && (IsA(dpns->plan, CteScan) ||
8411 IsA(dpns->plan, WorkTableScan)));
8412
8413 tle = get_tle_by_resno(dpns->inner_tlist, attnum);
8414 if (!tle)
8415 elog(ERROR, "bogus varattno for subquery var: %d",
8416 attnum);
8417 Assert(netlevelsup == 0);
8418 push_child_plan(dpns, dpns->inner_plan, &save_dpns);
8419
8420 result = get_name_for_var_field((Var *) tle->expr, fieldno,
8421 levelsup, context);
8422
8423 pop_child_plan(dpns, &save_dpns);
8424 return result;
8425 }
8426 }
8427 break;
8428 case RTE_GROUP:
8429
8430 /*
8431 * We couldn't get here: any Vars that reference the RTE_GROUP RTE
8432 * should have been replaced with the underlying grouping
8433 * expressions.
8434 */
8435 break;
8436 }
8437
8438 /*
8439 * We now have an expression we can't expand any more, so see if
8440 * get_expr_result_tupdesc() can do anything with it.
8441 */
8442 tupleDesc = get_expr_result_tupdesc(expr, false);
8443 /* Got the tupdesc, so we can extract the field name */
8444 Assert(fieldno >= 1 && fieldno <= tupleDesc->natts);
8445 return NameStr(TupleDescAttr(tupleDesc, fieldno - 1)->attname);
8446 }
8447
8448 /*
8449 * Try to find the referenced expression for a PARAM_EXEC Param that might
8450 * reference a parameter supplied by an upper NestLoop or SubPlan plan node.
8451 *
8452 * If successful, return the expression and set *dpns_p and *ancestor_cell_p
8453 * appropriately for calling push_ancestor_plan(). If no referent can be
8454 * found, return NULL.
8455 */
8456 static Node *
8457 find_param_referent(Param *param, deparse_context *context,
8458 deparse_namespace **dpns_p, ListCell **ancestor_cell_p)
8459 {
8460 /* Initialize output parameters to prevent compiler warnings */
8461 *dpns_p = NULL;
8462 *ancestor_cell_p = NULL;
8463
8464 /*
8465 * If it's a PARAM_EXEC parameter, look for a matching NestLoopParam or
8466 * SubPlan argument. This will necessarily be in some ancestor of the
8467 * current expression's Plan node.
8468 */
8469 if (param->paramkind == PARAM_EXEC)
8470 {
8471 deparse_namespace *dpns;
8472 Plan *child_plan;
8473 ListCell *lc;
8474
8475 dpns = (deparse_namespace *) linitial(context->namespaces);
8476 child_plan = dpns->plan;
8477
8478 foreach(lc, dpns->ancestors)
8479 {
8480 Node *ancestor = (Node *) lfirst(lc);
8481 ListCell *lc2;
8482
8483 /*
8484 * NestLoops transmit params to their inner child only.
8485 */
8486 if (IsA(ancestor, NestLoop) &&
8487 child_plan == innerPlan(ancestor))
8488 {
8489 NestLoop *nl = (NestLoop *) ancestor;
8490
8491 foreach(lc2, nl->nestParams)
8492 {
8493 NestLoopParam *nlp = (NestLoopParam *) lfirst(lc2);
8494
8495 if (nlp->paramno == param->paramid)
8496 {
8497 /* Found a match, so return it */
8498 *dpns_p = dpns;
8499 *ancestor_cell_p = lc;
8500 return (Node *) nlp->paramval;
8501 }
8502 }
8503 }
8504
8505 /*
8506 * If ancestor is a SubPlan, check the arguments it provides.
8507 */
8508 if (IsA(ancestor, SubPlan))
8509 {
8510 SubPlan *subplan = (SubPlan *) ancestor;
8511 ListCell *lc3;
8512 ListCell *lc4;
8513
8514 forboth(lc3, subplan->parParam, lc4, subplan->args)
8515 {
8516 int paramid = lfirst_int(lc3);
8517 Node *arg = (Node *) lfirst(lc4);
8518
8519 if (paramid == param->paramid)
8520 {
8521 /*
8522 * Found a match, so return it. But, since Vars in
8523 * the arg are to be evaluated in the surrounding
8524 * context, we have to point to the next ancestor item
8525 * that is *not* a SubPlan.
8526 */
8527 ListCell *rest;
8528
8529 for_each_cell(rest, dpns->ancestors,
8530 lnext(dpns->ancestors, lc))
8531 {
8532 Node *ancestor2 = (Node *) lfirst(rest);
8533
8534 if (!IsA(ancestor2, SubPlan))
8535 {
8536 *dpns_p = dpns;
8537 *ancestor_cell_p = rest;
8538 return arg;
8539 }
8540 }
8541 elog(ERROR, "SubPlan cannot be outermost ancestor");
8542 }
8543 }
8544
8545 /* SubPlan isn't a kind of Plan, so skip the rest */
8546 continue;
8547 }
8548
8549 /*
8550 * We need not consider the ancestor's initPlan list, since
8551 * initplans never have any parParams.
8552 */
8553
8554 /* No luck, crawl up to next ancestor */
8555 child_plan = (Plan *) ancestor;
8556 }
8557 }
8558
8559 /* No referent found */
8560 return NULL;
8561 }
8562
8563 /*
8564 * Try to find a subplan/initplan that emits the value for a PARAM_EXEC Param.
8565 *
8566 * If successful, return the generating subplan/initplan and set *column_p
8567 * to the subplan's 0-based output column number.
8568 * Otherwise, return NULL.
8569 */
8570 static SubPlan *
8571 find_param_generator(Param *param, deparse_context *context, int *column_p)
8572 {
8573 /* Initialize output parameter to prevent compiler warnings */
8574 *column_p = 0;
8575
8576 /*
8577 * If it's a PARAM_EXEC parameter, search the current plan node as well as
8578 * ancestor nodes looking for a subplan or initplan that emits the value
8579 * for the Param. It could appear in the setParams of an initplan or
8580 * MULTIEXPR_SUBLINK subplan, or in the paramIds of an ancestral SubPlan.
8581 */
8582 if (param->paramkind == PARAM_EXEC)
8583 {
8584 SubPlan *result;
8585 deparse_namespace *dpns;
8586 ListCell *lc;
8587
8588 dpns = (deparse_namespace *) linitial(context->namespaces);
8589
8590 /* First check the innermost plan node's initplans */
8591 result = find_param_generator_initplan(param, dpns->plan, column_p);
8592 if (result)
8593 return result;
8594
8595 /*
8596 * The plan's targetlist might contain MULTIEXPR_SUBLINK SubPlans,
8597 * which can be referenced by Params elsewhere in the targetlist.
8598 * (Such Params should always be in the same targetlist, so there's no
8599 * need to do this work at upper plan nodes.)
8600 */
8601 foreach_node(TargetEntry, tle, dpns->plan->targetlist)
8602 {
8603 if (tle->expr && IsA(tle->expr, SubPlan))
8604 {
8605 SubPlan *subplan = (SubPlan *) tle->expr;
8606
8607 if (subplan->subLinkType == MULTIEXPR_SUBLINK)
8608 {
8609 foreach_int(paramid, subplan->setParam)
8610 {
8611 if (paramid == param->paramid)
8612 {
8613 /* Found a match, so return it. */
8614 *column_p = foreach_current_index(paramid);
8615 return subplan;
8616 }
8617 }
8618 }
8619 }
8620 }
8621
8622 /* No luck, so check the ancestor nodes */
8623 foreach(lc, dpns->ancestors)
8624 {
8625 Node *ancestor = (Node *) lfirst(lc);
8626
8627 /*
8628 * If ancestor is a SubPlan, check the paramIds it provides.
8629 */
8630 if (IsA(ancestor, SubPlan))
8631 {
8632 SubPlan *subplan = (SubPlan *) ancestor;
8633
8634 foreach_int(paramid, subplan->paramIds)
8635 {
8636 if (paramid == param->paramid)
8637 {
8638 /* Found a match, so return it. */
8639 *column_p = foreach_current_index(paramid);
8640 return subplan;
8641 }
8642 }
8643
8644 /* SubPlan isn't a kind of Plan, so skip the rest */
8645 continue;
8646 }
8647
8648 /*
8649 * Otherwise, it's some kind of Plan node, so check its initplans.
8650 */
8651 result = find_param_generator_initplan(param, (Plan *) ancestor,
8652 column_p);
8653 if (result)
8654 return result;
8655
8656 /* No luck, crawl up to next ancestor */
8657 }
8658 }
8659
8660 /* No generator found */
8661 return NULL;
8662 }
8663
8664 /*
8665 * Subroutine for find_param_generator: search one Plan node's initplans
8666 */
8667 static SubPlan *
8668 find_param_generator_initplan(Param *param, Plan *plan, int *column_p)
8669 {
8670 foreach_node(SubPlan, subplan, plan->initPlan)
8671 {
8672 foreach_int(paramid, subplan->setParam)
8673 {
8674 if (paramid == param->paramid)
8675 {
8676 /* Found a match, so return it. */
8677 *column_p = foreach_current_index(paramid);
8678 return subplan;
8679 }
8680 }
8681 }
8682 return NULL;
8683 }
8684
8685 /*
8686 * Display a Param appropriately.
8687 */
8688 static void
8689 get_parameter(Param *param, deparse_context *context)
8690 {
8691 Node *expr;
8692 deparse_namespace *dpns;
8693 ListCell *ancestor_cell;
8694 SubPlan *subplan;
8695 int column;
8696
8697 /*
8698 * If it's a PARAM_EXEC parameter, try to locate the expression from which
8699 * the parameter was computed. This stanza handles only cases in which
8700 * the Param represents an input to the subplan we are currently in.
8701 */
8702 expr = find_param_referent(param, context, &dpns, &ancestor_cell);
8703 if (expr)
8704 {
8705 /* Found a match, so print it */
8706 deparse_namespace save_dpns;
8707 bool save_varprefix;
8708 bool need_paren;
8709
8710 /* Switch attention to the ancestor plan node */
8711 push_ancestor_plan(dpns, ancestor_cell, &save_dpns);
8712
8713 /*
8714 * Force prefixing of Vars, since they won't belong to the relation
8715 * being scanned in the original plan node.
8716 */
8717 save_varprefix = context->varprefix;
8718 context->varprefix = true;
8719
8720 /*
8721 * A Param's expansion is typically a Var, Aggref, GroupingFunc, or
8722 * upper-level Param, which wouldn't need extra parentheses.
8723 * Otherwise, insert parens to ensure the expression looks atomic.
8724 */
8725 need_paren = !(IsA(expr, Var) ||
8726 IsA(expr, Aggref) ||
8727 IsA(expr, GroupingFunc) ||
8728 IsA(expr, Param));
8729 if (need_paren)
8730 appendStringInfoChar(context->buf, '(');
8731
8732 get_rule_expr(expr, context, false);
8733
8734 if (need_paren)
8735 appendStringInfoChar(context->buf, ')');
8736
8737 context->varprefix = save_varprefix;
8738
8739 pop_ancestor_plan(dpns, &save_dpns);
8740
8741 return;
8742 }
8743
8744 /*
8745 * Alternatively, maybe it's a subplan output, which we print as a
8746 * reference to the subplan. (We could drill down into the subplan and
8747 * print the relevant targetlist expression, but that has been deemed too
8748 * confusing since it would violate normal SQL scope rules. Also, we're
8749 * relying on this reference to show that the testexpr containing the
8750 * Param has anything to do with that subplan at all.)
8751 */
8752 subplan = find_param_generator(param, context, &column);
8753 if (subplan)
8754 {
8755 appendStringInfo(context->buf, "(%s%s).col%d",
8756 subplan->useHashTable ? "hashed " : "",
8757 subplan->plan_name, column + 1);
8758
8759 return;
8760 }
8761
8762 /*
8763 * If it's an external parameter, see if the outermost namespace provides
8764 * function argument names.
8765 */
8766 if (param->paramkind == PARAM_EXTERN && context->namespaces != NIL)
8767 {
8768 dpns = llast(context->namespaces);
8769 if (dpns->argnames &&
8770 param->paramid > 0 &&
8771 param->paramid <= dpns->numargs)
8772 {
8773 char *argname = dpns->argnames[param->paramid - 1];
8774
8775 if (argname)
8776 {
8777 bool should_qualify = false;
8778 ListCell *lc;
8779
8780 /*
8781 * Qualify the parameter name if there are any other deparse
8782 * namespaces with range tables. This avoids qualifying in
8783 * trivial cases like "RETURN a + b", but makes it safe in all
8784 * other cases.
8785 */
8786 foreach(lc, context->namespaces)
8787 {
8788 deparse_namespace *depns = lfirst(lc);
8789
8790 if (depns->rtable_names != NIL)
8791 {
8792 should_qualify = true;
8793 break;
8794 }
8795 }
8796 if (should_qualify)
8797 {
8798 appendStringInfoString(context->buf, quote_identifier(dpns->funcname));
8799 appendStringInfoChar(context->buf, '.');
8800 }
8801
8802 appendStringInfoString(context->buf, quote_identifier(argname));
8803 return;
8804 }
8805 }
8806 }
8807
8808 /*
8809 * Not PARAM_EXEC, or couldn't find referent: just print $N.
8810 *
8811 * It's a bug if we get here for anything except PARAM_EXTERN Params, but
8812 * in production builds printing $N seems more useful than failing.
8813 */
8814 Assert(param->paramkind == PARAM_EXTERN);
8815
8816 appendStringInfo(context->buf, "$%d", param->paramid);
8817 }
8818
8819 /*
8820 * get_simple_binary_op_name
8821 *
8822 * helper function for isSimpleNode
8823 * will return single char binary operator name, or NULL if it's not
8824 */
8825 static const char *
8826 get_simple_binary_op_name(OpExpr *expr)
8827 {
8828 List *args = expr->args;
8829
8830 if (list_length(args) == 2)
8831 {
8832 /* binary operator */
8833 Node *arg1 = (Node *) linitial(args);
8834 Node *arg2 = (Node *) lsecond(args);
8835 const char *op;
8836
8837 op = generate_operator_name(expr->opno, exprType(arg1), exprType(arg2));
8838 if (strlen(op) == 1)
8839 return op;
8840 }
8841 return NULL;
8842 }
8843
8844
8845 /*
8846 * isSimpleNode - check if given node is simple (doesn't need parenthesizing)
8847 *
8848 * true : simple in the context of parent node's type
8849 * false : not simple
8850 */
8851 static bool
8852 isSimpleNode(Node *node, Node *parentNode, int prettyFlags)
8853 {
8854 if (!node)
8855 return false;
8856
8857 switch (nodeTag(node))
8858 {
8859 case T_Var:
8860 case T_Const:
8861 case T_Param:
8862 case T_CoerceToDomainValue:
8863 case T_SetToDefault:
8864 case T_CurrentOfExpr:
8865 /* single words: always simple */
8866 return true;
8867
8868 case T_SubscriptingRef:
8869 case T_ArrayExpr:
8870 case T_RowExpr:
8871 case T_CoalesceExpr:
8872 case T_MinMaxExpr:
8873 case T_SQLValueFunction:
8874 case T_XmlExpr:
8875 case T_NextValueExpr:
8876 case T_NullIfExpr:
8877 case T_Aggref:
8878 case T_GroupingFunc:
8879 case T_WindowFunc:
8880 case T_MergeSupportFunc:
8881 case T_FuncExpr:
8882 case T_JsonConstructorExpr:
8883 case T_JsonExpr:
8884 /* function-like: name(..) or name[..] */
8885 return true;
8886
8887 /* CASE keywords act as parentheses */
8888 case T_CaseExpr:
8889 return true;
8890
8891 case T_FieldSelect:
8892
8893 /*
8894 * appears simple since . has top precedence, unless parent is
8895 * T_FieldSelect itself!
8896 */
8897 return !IsA(parentNode, FieldSelect);
8898
8899 case T_FieldStore:
8900
8901 /*
8902 * treat like FieldSelect (probably doesn't matter)
8903 */
8904 return !IsA(parentNode, FieldStore);
8905
8906 case T_CoerceToDomain:
8907 /* maybe simple, check args */
8908 return isSimpleNode((Node *) ((CoerceToDomain *) node)->arg,
8909 node, prettyFlags);
8910 case T_RelabelType:
8911 return isSimpleNode((Node *) ((RelabelType *) node)->arg,
8912 node, prettyFlags);
8913 case T_CoerceViaIO:
8914 return isSimpleNode((Node *) ((CoerceViaIO *) node)->arg,
8915 node, prettyFlags);
8916 case T_ArrayCoerceExpr:
8917 return isSimpleNode((Node *) ((ArrayCoerceExpr *) node)->arg,
8918 node, prettyFlags);
8919 case T_ConvertRowtypeExpr:
8920 return isSimpleNode((Node *) ((ConvertRowtypeExpr *) node)->arg,
8921 node, prettyFlags);
8922 case T_ReturningExpr:
8923 return isSimpleNode((Node *) ((ReturningExpr *) node)->retexpr,
8924 node, prettyFlags);
8925
8926 case T_OpExpr:
8927 {
8928 /* depends on parent node type; needs further checking */
8929 if (prettyFlags & PRETTYFLAG_PAREN && IsA(parentNode, OpExpr))
8930 {
8931 const char *op;
8932 const char *parentOp;
8933 bool is_lopriop;
8934 bool is_hipriop;
8935 bool is_lopriparent;
8936 bool is_hipriparent;
8937
8938 op = get_simple_binary_op_name((OpExpr *) node);
8939 if (!op)
8940 return false;
8941
8942 /* We know only the basic operators + - and * / % */
8943 is_lopriop = (strchr("+-", *op) != NULL);
8944 is_hipriop = (strchr("*/%", *op) != NULL);
8945 if (!(is_lopriop || is_hipriop))
8946 return false;
8947
8948 parentOp = get_simple_binary_op_name((OpExpr *) parentNode);
8949 if (!parentOp)
8950 return false;
8951
8952 is_lopriparent = (strchr("+-", *parentOp) != NULL);
8953 is_hipriparent = (strchr("*/%", *parentOp) != NULL);
8954 if (!(is_lopriparent || is_hipriparent))
8955 return false;
8956
8957 if (is_hipriop && is_lopriparent)
8958 return true; /* op binds tighter than parent */
8959
8960 if (is_lopriop && is_hipriparent)
8961 return false;
8962
8963 /*
8964 * Operators are same priority --- can skip parens only if
8965 * we have (a - b) - c, not a - (b - c).
8966 */
8967 if (node == (Node *) linitial(((OpExpr *) parentNode)->args))
8968 return true;
8969
8970 return false;
8971 }
8972 /* else do the same stuff as for T_SubLink et al. */
8973 }
8974 /* FALLTHROUGH */
8975
8976 case T_SubLink:
8977 case T_NullTest:
8978 case T_BooleanTest:
8979 case T_DistinctExpr:
8980 case T_JsonIsPredicate:
8981 switch (nodeTag(parentNode))
8982 {
8983 case T_FuncExpr:
8984 {
8985 /* special handling for casts and COERCE_SQL_SYNTAX */
8986 CoercionForm type = ((FuncExpr *) parentNode)->funcformat;
8987
8988 if (type == COERCE_EXPLICIT_CAST ||
8989 type == COERCE_IMPLICIT_CAST ||
8990 type == COERCE_SQL_SYNTAX)
8991 return false;
8992 return true; /* own parentheses */
8993 }
8994 case T_BoolExpr: /* lower precedence */
8995 case T_SubscriptingRef: /* other separators */
8996 case T_ArrayExpr: /* other separators */
8997 case T_RowExpr: /* other separators */
8998 case T_CoalesceExpr: /* own parentheses */
8999 case T_MinMaxExpr: /* own parentheses */
9000 case T_XmlExpr: /* own parentheses */
9001 case T_NullIfExpr: /* other separators */
9002 case T_Aggref: /* own parentheses */
9003 case T_GroupingFunc: /* own parentheses */
9004 case T_WindowFunc: /* own parentheses */
9005 case T_CaseExpr: /* other separators */
9006 return true;
9007 default:
9008 return false;
9009 }
9010
9011 case T_BoolExpr:
9012 switch (nodeTag(parentNode))
9013 {
9014 case T_BoolExpr:
9015 if (prettyFlags & PRETTYFLAG_PAREN)
9016 {
9017 BoolExprType type;
9018 BoolExprType parentType;
9019
9020 type = ((BoolExpr *) node)->boolop;
9021 parentType = ((BoolExpr *) parentNode)->boolop;
9022 switch (type)
9023 {
9024 case NOT_EXPR:
9025 case AND_EXPR:
9026 if (parentType == AND_EXPR || parentType == OR_EXPR)
9027 return true;
9028 break;
9029 case OR_EXPR:
9030 if (parentType == OR_EXPR)
9031 return true;
9032 break;
9033 }
9034 }
9035 return false;
9036 case T_FuncExpr:
9037 {
9038 /* special handling for casts and COERCE_SQL_SYNTAX */
9039 CoercionForm type = ((FuncExpr *) parentNode)->funcformat;
9040
9041 if (type == COERCE_EXPLICIT_CAST ||
9042 type == COERCE_IMPLICIT_CAST ||
9043 type == COERCE_SQL_SYNTAX)
9044 return false;
9045 return true; /* own parentheses */
9046 }
9047 case T_SubscriptingRef: /* other separators */
9048 case T_ArrayExpr: /* other separators */
9049 case T_RowExpr: /* other separators */
9050 case T_CoalesceExpr: /* own parentheses */
9051 case T_MinMaxExpr: /* own parentheses */
9052 case T_XmlExpr: /* own parentheses */
9053 case T_NullIfExpr: /* other separators */
9054 case T_Aggref: /* own parentheses */
9055 case T_GroupingFunc: /* own parentheses */
9056 case T_WindowFunc: /* own parentheses */
9057 case T_CaseExpr: /* other separators */
9058 case T_JsonExpr: /* own parentheses */
9059 return true;
9060 default:
9061 return false;
9062 }
9063
9064 case T_JsonValueExpr:
9065 /* maybe simple, check args */
9066 return isSimpleNode((Node *) ((JsonValueExpr *) node)->raw_expr,
9067 node, prettyFlags);
9068
9069 default:
9070 break;
9071 }
9072 /* those we don't know: in dubio complexo */
9073 return false;
9074 }
9075
9076
9077 /*
9078 * appendContextKeyword - append a keyword to buffer
9079 *
9080 * If prettyPrint is enabled, perform a line break, and adjust indentation.
9081 * Otherwise, just append the keyword.
9082 */
9083 static void
9084 appendContextKeyword(deparse_context *context, const char *str,
9085 int indentBefore, int indentAfter, int indentPlus)
9086 {
9087 StringInfo buf = context->buf;
9088
9089 if (PRETTY_INDENT(context))
9090 {
9091 int indentAmount;
9092
9093 context->indentLevel += indentBefore;
9094
9095 /* remove any trailing spaces currently in the buffer ... */
9096 removeStringInfoSpaces(buf);
9097 /* ... then add a newline and some spaces */
9098 appendStringInfoChar(buf, '\n');
9099
9100 if (context->indentLevel < PRETTYINDENT_LIMIT)
9101 indentAmount = Max(context->indentLevel, 0) + indentPlus;
9102 else
9103 {
9104 /*
9105 * If we're indented more than PRETTYINDENT_LIMIT characters, try
9106 * to conserve horizontal space by reducing the per-level
9107 * indentation. For best results the scale factor here should
9108 * divide all the indent amounts that get added to indentLevel
9109 * (PRETTYINDENT_STD, etc). It's important that the indentation
9110 * not grow unboundedly, else deeply-nested trees use O(N^2)
9111 * whitespace; so we also wrap modulo PRETTYINDENT_LIMIT.
9112 */
9113 indentAmount = PRETTYINDENT_LIMIT +
9114 (context->indentLevel - PRETTYINDENT_LIMIT) /
9115 (PRETTYINDENT_STD / 2);
9116 indentAmount %= PRETTYINDENT_LIMIT;
9117 /* scale/wrap logic affects indentLevel, but not indentPlus */
9118 indentAmount += indentPlus;
9119 }
9120 appendStringInfoSpaces(buf, indentAmount);
9121
9122 appendStringInfoString(buf, str);
9123
9124 context->indentLevel += indentAfter;
9125 if (context->indentLevel < 0)
9126 context->indentLevel = 0;
9127 }
9128 else
9129 appendStringInfoString(buf, str);
9130 }
9131
9132 /*
9133 * removeStringInfoSpaces - delete trailing spaces from a buffer.
9134 *
9135 * Possibly this should move to stringinfo.c at some point.
9136 */
9137 static void
9138 removeStringInfoSpaces(StringInfo str)
9139 {
9140 while (str->len > 0 && str->data[str->len - 1] == ' ')
9141 str->data[--(str->len)] = '\0';
9142 }
9143
9144
9145 /*
9146 * get_rule_expr_paren - deparse expr using get_rule_expr,
9147 * embracing the string with parentheses if necessary for prettyPrint.
9148 *
9149 * Never embrace if prettyFlags=0, because it's done in the calling node.
9150 *
9151 * Any node that does *not* embrace its argument node by sql syntax (with
9152 * parentheses, non-operator keywords like CASE/WHEN/ON, or comma etc) should
9153 * use get_rule_expr_paren instead of get_rule_expr so parentheses can be
9154 * added.
9155 */
9156 static void
9157 get_rule_expr_paren(Node *node, deparse_context *context,
9158 bool showimplicit, Node *parentNode)
9159 {
9160 bool need_paren;
9161
9162 need_paren = PRETTY_PAREN(context) &&
9163 !isSimpleNode(node, parentNode, context->prettyFlags);
9164
9165 if (need_paren)
9166 appendStringInfoChar(context->buf, '(');
9167
9168 get_rule_expr(node, context, showimplicit);
9169
9170 if (need_paren)
9171 appendStringInfoChar(context->buf, ')');
9172 }
9173
9174 static void
9175 get_json_behavior(JsonBehavior *behavior, deparse_context *context,
9176 const char *on)
9177 {
9178 /*
9179 * The order of array elements must correspond to the order of
9180 * JsonBehaviorType members.
9181 */
9182 const char *behavior_names[] =
9183 {
9184 " NULL",
9185 " ERROR",
9186 " EMPTY",
9187 " TRUE",
9188 " FALSE",
9189 " UNKNOWN",
9190 " EMPTY ARRAY",
9191 " EMPTY OBJECT",
9192 " DEFAULT "
9193 };
9194
9195 if ((int) behavior->btype < 0 || behavior->btype >= lengthof(behavior_names))
9196 elog(ERROR, "invalid json behavior type: %d", behavior->btype);
9197
9198 appendStringInfoString(context->buf, behavior_names[behavior->btype]);
9199
9200 if (behavior->btype == JSON_BEHAVIOR_DEFAULT)
9201 get_rule_expr(behavior->expr, context, false);
9202
9203 appendStringInfo(context->buf, " ON %s", on);
9204 }
9205
9206 /*
9207 * get_json_expr_options
9208 *
9209 * Parse back common options for JSON_QUERY, JSON_VALUE, JSON_EXISTS and
9210 * JSON_TABLE columns.
9211 */
9212 static void
9213 get_json_expr_options(JsonExpr *jsexpr, deparse_context *context,
9214 JsonBehaviorType default_behavior)
9215 {
9216 if (jsexpr->op == JSON_QUERY_OP)
9217 {
9218 if (jsexpr->wrapper == JSW_CONDITIONAL)
9219 appendStringInfoString(context->buf, " WITH CONDITIONAL WRAPPER");
9220 else if (jsexpr->wrapper == JSW_UNCONDITIONAL)
9221 appendStringInfoString(context->buf, " WITH UNCONDITIONAL WRAPPER");
9222 /* The default */
9223 else if (jsexpr->wrapper == JSW_NONE || jsexpr->wrapper == JSW_UNSPEC)
9224 appendStringInfoString(context->buf, " WITHOUT WRAPPER");
9225
9226 if (jsexpr->omit_quotes)
9227 appendStringInfoString(context->buf, " OMIT QUOTES");
9228 /* The default */
9229 else
9230 appendStringInfoString(context->buf, " KEEP QUOTES");
9231 }
9232
9233 if (jsexpr->on_empty && jsexpr->on_empty->btype != default_behavior)
9234 get_json_behavior(jsexpr->on_empty, context, "EMPTY");
9235
9236 if (jsexpr->on_error && jsexpr->on_error->btype != default_behavior)
9237 get_json_behavior(jsexpr->on_error, context, "ERROR");
9238 }
9239
9240 /* ----------
9241 * get_rule_expr - Parse back an expression
9242 *
9243 * Note: showimplicit determines whether we display any implicit cast that
9244 * is present at the top of the expression tree. It is a passed argument,
9245 * not a field of the context struct, because we change the value as we
9246 * recurse down into the expression. In general we suppress implicit casts
9247 * when the result type is known with certainty (eg, the arguments of an
9248 * OR must be boolean). We display implicit casts for arguments of functions
9249 * and operators, since this is needed to be certain that the same function
9250 * or operator will be chosen when the expression is re-parsed.
9251 * ----------
9252 */
9253 static void
9254 get_rule_expr(Node *node, deparse_context *context,
9255 bool showimplicit)
9256 {
9257 StringInfo buf = context->buf;
9258
9259 if (node == NULL)
9260 return;
9261
9262 /* Guard against excessively long or deeply-nested queries */
9263 CHECK_FOR_INTERRUPTS();
9264 check_stack_depth();
9265
9266 /*
9267 * Each level of get_rule_expr must emit an indivisible term
9268 * (parenthesized if necessary) to ensure result is reparsed into the same
9269 * expression tree. The only exception is that when the input is a List,
9270 * we emit the component items comma-separated with no surrounding
9271 * decoration; this is convenient for most callers.
9272 */
9273 switch (nodeTag(node))
9274 {
9275 case T_Var:
9276 (void) get_variable((Var *) node, 0, false, context);
9277 break;
9278
9279 case T_Const:
9280 get_const_expr((Const *) node, context, 0);
9281 break;
9282
9283 case T_Param:
9284 get_parameter((Param *) node, context);
9285 break;
9286
9287 case T_Aggref:
9288 get_agg_expr((Aggref *) node, context, (Aggref *) node);
9289 break;
9290
9291 case T_GroupingFunc:
9292 {
9293 GroupingFunc *gexpr = (GroupingFunc *) node;
9294
9295 appendStringInfoString(buf, "GROUPING(");
9296 get_rule_expr((Node *) gexpr->args, context, true);
9297 appendStringInfoChar(buf, ')');
9298 }
9299 break;
9300
9301 case T_WindowFunc:
9302 get_windowfunc_expr((WindowFunc *) node, context);
9303 break;
9304
9305 case T_MergeSupportFunc:
9306 appendStringInfoString(buf, "MERGE_ACTION()");
9307 break;
9308
9309 case T_SubscriptingRef:
9310 {
9311 SubscriptingRef *sbsref = (SubscriptingRef *) node;
9312 bool need_parens;
9313
9314 /*
9315 * If the argument is a CaseTestExpr, we must be inside a
9316 * FieldStore, ie, we are assigning to an element of an array
9317 * within a composite column. Since we already punted on
9318 * displaying the FieldStore's target information, just punt
9319 * here too, and display only the assignment source
9320 * expression.
9321 */
9322 if (IsA(sbsref->refexpr, CaseTestExpr))
9323 {
9324 Assert(sbsref->refassgnexpr);
9325 get_rule_expr((Node *) sbsref->refassgnexpr,
9326 context, showimplicit);
9327 break;
9328 }
9329
9330 /*
9331 * Parenthesize the argument unless it's a simple Var or a
9332 * FieldSelect. (In particular, if it's another
9333 * SubscriptingRef, we *must* parenthesize to avoid
9334 * confusion.)
9335 */
9336 need_parens = !IsA(sbsref->refexpr, Var) &&
9337 !IsA(sbsref->refexpr, FieldSelect);
9338 if (need_parens)
9339 appendStringInfoChar(buf, '(');
9340 get_rule_expr((Node *) sbsref->refexpr, context, showimplicit);
9341 if (need_parens)
9342 appendStringInfoChar(buf, ')');
9343
9344 /*
9345 * If there's a refassgnexpr, we want to print the node in the
9346 * format "container[subscripts] := refassgnexpr". This is
9347 * not legal SQL, so decompilation of INSERT or UPDATE
9348 * statements should always use processIndirection as part of
9349 * the statement-level syntax. We should only see this when
9350 * EXPLAIN tries to print the targetlist of a plan resulting
9351 * from such a statement.
9352 */
9353 if (sbsref->refassgnexpr)
9354 {
9355 Node *refassgnexpr;
9356
9357 /*
9358 * Use processIndirection to print this node's subscripts
9359 * as well as any additional field selections or
9360 * subscripting in immediate descendants. It returns the
9361 * RHS expr that is actually being "assigned".
9362 */
9363 refassgnexpr = processIndirection(node, context);
9364 appendStringInfoString(buf, " := ");
9365 get_rule_expr(refassgnexpr, context, showimplicit);
9366 }
9367 else
9368 {
9369 /* Just an ordinary container fetch, so print subscripts */
9370 printSubscripts(sbsref, context);
9371 }
9372 }
9373 break;
9374
9375 case T_FuncExpr:
9376 get_func_expr((FuncExpr *) node, context, showimplicit);
9377 break;
9378
9379 case T_NamedArgExpr:
9380 {
9381 NamedArgExpr *na = (NamedArgExpr *) node;
9382
9383 appendStringInfo(buf, "%s => ", quote_identifier(na->name));
9384 get_rule_expr((Node *) na->arg, context, showimplicit);
9385 }
9386 break;
9387
9388 case T_OpExpr:
9389 get_oper_expr((OpExpr *) node, context);
9390 break;
9391
9392 case T_DistinctExpr:
9393 {
9394 DistinctExpr *expr = (DistinctExpr *) node;
9395 List *args = expr->args;
9396 Node *arg1 = (Node *) linitial(args);
9397 Node *arg2 = (Node *) lsecond(args);
9398
9399 if (!PRETTY_PAREN(context))
9400 appendStringInfoChar(buf, '(');
9401 get_rule_expr_paren(arg1, context, true, node);
9402 appendStringInfoString(buf, " IS DISTINCT FROM ");
9403 get_rule_expr_paren(arg2, context, true, node);
9404 if (!PRETTY_PAREN(context))
9405 appendStringInfoChar(buf, ')');
9406 }
9407 break;
9408
9409 case T_NullIfExpr:
9410 {
9411 NullIfExpr *nullifexpr = (NullIfExpr *) node;
9412
9413 appendStringInfoString(buf, "NULLIF(");
9414 get_rule_expr((Node *) nullifexpr->args, context, true);
9415 appendStringInfoChar(buf, ')');
9416 }
9417 break;
9418
9419 case T_ScalarArrayOpExpr:
9420 {
9421 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
9422 List *args = expr->args;
9423 Node *arg1 = (Node *) linitial(args);
9424 Node *arg2 = (Node *) lsecond(args);
9425
9426 if (!PRETTY_PAREN(context))
9427 appendStringInfoChar(buf, '(');
9428 get_rule_expr_paren(arg1, context, true, node);
9429 appendStringInfo(buf, " %s %s (",
9430 generate_operator_name(expr->opno,
9431 exprType(arg1),
9432 get_base_element_type(exprType(arg2))),
9433 expr->useOr ? "ANY" : "ALL");
9434 get_rule_expr_paren(arg2, context, true, node);
9435
9436 /*
9437 * There's inherent ambiguity in "x op ANY/ALL (y)" when y is
9438 * a bare sub-SELECT. Since we're here, the sub-SELECT must
9439 * be meant as a scalar sub-SELECT yielding an array value to
9440 * be used in ScalarArrayOpExpr; but the grammar will
9441 * preferentially interpret such a construct as an ANY/ALL
9442 * SubLink. To prevent misparsing the output that way, insert
9443 * a dummy coercion (which will be stripped by parse analysis,
9444 * so no inefficiency is added in dump and reload). This is
9445 * indeed most likely what the user wrote to get the construct
9446 * accepted in the first place.
9447 */
9448 if (IsA(arg2, SubLink) &&
9449 ((SubLink *) arg2)->subLinkType == EXPR_SUBLINK)
9450 appendStringInfo(buf, "::%s",
9451 format_type_with_typemod(exprType(arg2),
9452 exprTypmod(arg2)));
9453 appendStringInfoChar(buf, ')');
9454 if (!PRETTY_PAREN(context))
9455 appendStringInfoChar(buf, ')');
9456 }
9457 break;
9458
9459 case T_BoolExpr:
9460 {
9461 BoolExpr *expr = (BoolExpr *) node;
9462 Node *first_arg = linitial(expr->args);
9463 ListCell *arg;
9464
9465 switch (expr->boolop)
9466 {
9467 case AND_EXPR:
9468 if (!PRETTY_PAREN(context))
9469 appendStringInfoChar(buf, '(');
9470 get_rule_expr_paren(first_arg, context,
9471 false, node);
9472 for_each_from(arg, expr->args, 1)
9473 {
9474 appendStringInfoString(buf, " AND ");
9475 get_rule_expr_paren((Node *) lfirst(arg), context,
9476 false, node);
9477 }
9478 if (!PRETTY_PAREN(context))
9479 appendStringInfoChar(buf, ')');
9480 break;
9481
9482 case OR_EXPR:
9483 if (!PRETTY_PAREN(context))
9484 appendStringInfoChar(buf, '(');
9485 get_rule_expr_paren(first_arg, context,
9486 false, node);
9487 for_each_from(arg, expr->args, 1)
9488 {
9489 appendStringInfoString(buf, " OR ");
9490 get_rule_expr_paren((Node *) lfirst(arg), context,
9491 false, node);
9492 }
9493 if (!PRETTY_PAREN(context))
9494 appendStringInfoChar(buf, ')');
9495 break;
9496
9497 case NOT_EXPR:
9498 if (!PRETTY_PAREN(context))
9499 appendStringInfoChar(buf, '(');
9500 appendStringInfoString(buf, "NOT ");
9501 get_rule_expr_paren(first_arg, context,
9502 false, node);
9503 if (!PRETTY_PAREN(context))
9504 appendStringInfoChar(buf, ')');
9505 break;
9506
9507 default:
9508 elog(ERROR, "unrecognized boolop: %d",
9509 (int) expr->boolop);
9510 }
9511 }
9512 break;
9513
9514 case T_SubLink:
9515 get_sublink_expr((SubLink *) node, context);
9516 break;
9517
9518 case T_SubPlan:
9519 {
9520 SubPlan *subplan = (SubPlan *) node;
9521
9522 /*
9523 * We cannot see an already-planned subplan in rule deparsing,
9524 * only while EXPLAINing a query plan. We don't try to
9525 * reconstruct the original SQL, just reference the subplan
9526 * that appears elsewhere in EXPLAIN's result. It does seem
9527 * useful to show the subLinkType and testexpr (if any), and
9528 * we also note whether the subplan will be hashed.
9529 */
9530 switch (subplan->subLinkType)
9531 {
9532 case EXISTS_SUBLINK:
9533 appendStringInfoString(buf, "EXISTS(");
9534 Assert(subplan->testexpr == NULL);
9535 break;
9536 case ALL_SUBLINK:
9537 appendStringInfoString(buf, "(ALL ");
9538 Assert(subplan->testexpr != NULL);
9539 break;
9540 case ANY_SUBLINK:
9541 appendStringInfoString(buf, "(ANY ");
9542 Assert(subplan->testexpr != NULL);
9543 break;
9544 case ROWCOMPARE_SUBLINK:
9545 /* Parenthesizing the testexpr seems sufficient */
9546 appendStringInfoChar(buf, '(');
9547 Assert(subplan->testexpr != NULL);
9548 break;
9549 case EXPR_SUBLINK:
9550 /* No need to decorate these subplan references */
9551 appendStringInfoChar(buf, '(');
9552 Assert(subplan->testexpr == NULL);
9553 break;
9554 case MULTIEXPR_SUBLINK:
9555 /* MULTIEXPR isn't executed in the normal way */
9556 appendStringInfoString(buf, "(rescan ");
9557 Assert(subplan->testexpr == NULL);
9558 break;
9559 case ARRAY_SUBLINK:
9560 appendStringInfoString(buf, "ARRAY(");
9561 Assert(subplan->testexpr == NULL);
9562 break;
9563 case CTE_SUBLINK:
9564 /* This case is unreachable within expressions */
9565 appendStringInfoString(buf, "CTE(");
9566 Assert(subplan->testexpr == NULL);
9567 break;
9568 }
9569
9570 if (subplan->testexpr != NULL)
9571 {
9572 deparse_namespace *dpns;
9573
9574 /*
9575 * Push SubPlan into ancestors list while deparsing
9576 * testexpr, so that we can handle PARAM_EXEC references
9577 * to the SubPlan's paramIds. (This makes it look like
9578 * the SubPlan is an "ancestor" of the current plan node,
9579 * which is a little weird, but it does no harm.) In this
9580 * path, we don't need to mention the SubPlan explicitly,
9581 * because the referencing Params will show its existence.
9582 */
9583 dpns = (deparse_namespace *) linitial(context->namespaces);
9584 dpns->ancestors = lcons(subplan, dpns->ancestors);
9585
9586 get_rule_expr(subplan->testexpr, context, showimplicit);
9587 appendStringInfoChar(buf, ')');
9588
9589 dpns->ancestors = list_delete_first(dpns->ancestors);
9590 }
9591 else
9592 {
9593 /* No referencing Params, so show the SubPlan's name */
9594 if (subplan->useHashTable)
9595 appendStringInfo(buf, "hashed %s)", subplan->plan_name);
9596 else
9597 appendStringInfo(buf, "%s)", subplan->plan_name);
9598 }
9599 }
9600 break;
9601
9602 case T_AlternativeSubPlan:
9603 {
9604 AlternativeSubPlan *asplan = (AlternativeSubPlan *) node;
9605 ListCell *lc;
9606
9607 /*
9608 * This case cannot be reached in normal usage, since no
9609 * AlternativeSubPlan can appear either in parsetrees or
9610 * finished plan trees. We keep it just in case somebody
9611 * wants to use this code to print planner data structures.
9612 */
9613 appendStringInfoString(buf, "(alternatives: ");
9614 foreach(lc, asplan->subplans)
9615 {
9616 SubPlan *splan = lfirst_node(SubPlan, lc);
9617
9618 if (splan->useHashTable)
9619 appendStringInfo(buf, "hashed %s", splan->plan_name);
9620 else
9621 appendStringInfoString(buf, splan->plan_name);
9622 if (lnext(asplan->subplans, lc))
9623 appendStringInfoString(buf, " or ");
9624 }
9625 appendStringInfoChar(buf, ')');
9626 }
9627 break;
9628
9629 case T_FieldSelect:
9630 {
9631 FieldSelect *fselect = (FieldSelect *) node;
9632 Node *arg = (Node *) fselect->arg;
9633 int fno = fselect->fieldnum;
9634 const char *fieldname;
9635 bool need_parens;
9636
9637 /*
9638 * Parenthesize the argument unless it's an SubscriptingRef or
9639 * another FieldSelect. Note in particular that it would be
9640 * WRONG to not parenthesize a Var argument; simplicity is not
9641 * the issue here, having the right number of names is.
9642 */
9643 need_parens = !IsA(arg, SubscriptingRef) &&
9644 !IsA(arg, FieldSelect);
9645 if (need_parens)
9646 appendStringInfoChar(buf, '(');
9647 get_rule_expr(arg, context, true);
9648 if (need_parens)
9649 appendStringInfoChar(buf, ')');
9650
9651 /*
9652 * Get and print the field name.
9653 */
9654 fieldname = get_name_for_var_field((Var *) arg, fno,
9655 0, context);
9656 appendStringInfo(buf, ".%s", quote_identifier(fieldname));
9657 }
9658 break;
9659
9660 case T_FieldStore:
9661 {
9662 FieldStore *fstore = (FieldStore *) node;
9663 bool need_parens;
9664
9665 /*
9666 * There is no good way to represent a FieldStore as real SQL,
9667 * so decompilation of INSERT or UPDATE statements should
9668 * always use processIndirection as part of the
9669 * statement-level syntax. We should only get here when
9670 * EXPLAIN tries to print the targetlist of a plan resulting
9671 * from such a statement. The plan case is even harder than
9672 * ordinary rules would be, because the planner tries to
9673 * collapse multiple assignments to the same field or subfield
9674 * into one FieldStore; so we can see a list of target fields
9675 * not just one, and the arguments could be FieldStores
9676 * themselves. We don't bother to try to print the target
9677 * field names; we just print the source arguments, with a
9678 * ROW() around them if there's more than one. This isn't
9679 * terribly complete, but it's probably good enough for
9680 * EXPLAIN's purposes; especially since anything more would be
9681 * either hopelessly confusing or an even poorer
9682 * representation of what the plan is actually doing.
9683 */
9684 need_parens = (list_length(fstore->newvals) != 1);
9685 if (need_parens)
9686 appendStringInfoString(buf, "ROW(");
9687 get_rule_expr((Node *) fstore->newvals, context, showimplicit);
9688 if (need_parens)
9689 appendStringInfoChar(buf, ')');
9690 }
9691 break;
9692
9693 case T_RelabelType:
9694 {
9695 RelabelType *relabel = (RelabelType *) node;
9696 Node *arg = (Node *) relabel->arg;
9697
9698 if (relabel->relabelformat == COERCE_IMPLICIT_CAST &&
9699 !showimplicit)
9700 {
9701 /* don't show the implicit cast */
9702 get_rule_expr_paren(arg, context, false, node);
9703 }
9704 else
9705 {
9706 get_coercion_expr(arg, context,
9707 relabel->resulttype,
9708 relabel->resulttypmod,
9709 node);
9710 }
9711 }
9712 break;
9713
9714 case T_CoerceViaIO:
9715 {
9716 CoerceViaIO *iocoerce = (CoerceViaIO *) node;
9717 Node *arg = (Node *) iocoerce->arg;
9718
9719 if (iocoerce->coerceformat == COERCE_IMPLICIT_CAST &&
9720 !showimplicit)
9721 {
9722 /* don't show the implicit cast */
9723 get_rule_expr_paren(arg, context, false, node);
9724 }
9725 else
9726 {
9727 get_coercion_expr(arg, context,
9728 iocoerce->resulttype,
9729 -1,
9730 node);
9731 }
9732 }
9733 break;
9734
9735 case T_ArrayCoerceExpr:
9736 {
9737 ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
9738 Node *arg = (Node *) acoerce->arg;
9739
9740 if (acoerce->coerceformat == COERCE_IMPLICIT_CAST &&
9741 !showimplicit)
9742 {
9743 /* don't show the implicit cast */
9744 get_rule_expr_paren(arg, context, false, node);
9745 }
9746 else
9747 {
9748 get_coercion_expr(arg, context,
9749 acoerce->resulttype,
9750 acoerce->resulttypmod,
9751 node);
9752 }
9753 }
9754 break;
9755
9756 case T_ConvertRowtypeExpr:
9757 {
9758 ConvertRowtypeExpr *convert = (ConvertRowtypeExpr *) node;
9759 Node *arg = (Node *) convert->arg;
9760
9761 if (convert->convertformat == COERCE_IMPLICIT_CAST &&
9762 !showimplicit)
9763 {
9764 /* don't show the implicit cast */
9765 get_rule_expr_paren(arg, context, false, node);
9766 }
9767 else
9768 {
9769 get_coercion_expr(arg, context,
9770 convert->resulttype, -1,
9771 node);
9772 }
9773 }
9774 break;
9775
9776 case T_CollateExpr:
9777 {
9778 CollateExpr *collate = (CollateExpr *) node;
9779 Node *arg = (Node *) collate->arg;
9780
9781 if (!PRETTY_PAREN(context))
9782 appendStringInfoChar(buf, '(');
9783 get_rule_expr_paren(arg, context, showimplicit, node);
9784 appendStringInfo(buf, " COLLATE %s",
9785 generate_collation_name(collate->collOid));
9786 if (!PRETTY_PAREN(context))
9787 appendStringInfoChar(buf, ')');
9788 }
9789 break;
9790
9791 case T_CaseExpr:
9792 {
9793 CaseExpr *caseexpr = (CaseExpr *) node;
9794 ListCell *temp;
9795
9796 appendContextKeyword(context, "CASE",
9797 0, PRETTYINDENT_VAR, 0);
9798 if (caseexpr->arg)
9799 {
9800 appendStringInfoChar(buf, ' ');
9801 get_rule_expr((Node *) caseexpr->arg, context, true);
9802 }
9803 foreach(temp, caseexpr->args)
9804 {
9805 CaseWhen *when = (CaseWhen *) lfirst(temp);
9806 Node *w = (Node *) when->expr;
9807
9808 if (caseexpr->arg)
9809 {
9810 /*
9811 * The parser should have produced WHEN clauses of the
9812 * form "CaseTestExpr = RHS", possibly with an
9813 * implicit coercion inserted above the CaseTestExpr.
9814 * For accurate decompilation of rules it's essential
9815 * that we show just the RHS. However in an
9816 * expression that's been through the optimizer, the
9817 * WHEN clause could be almost anything (since the
9818 * equality operator could have been expanded into an
9819 * inline function). If we don't recognize the form
9820 * of the WHEN clause, just punt and display it as-is.
9821 */
9822 if (IsA(w, OpExpr))
9823 {
9824 List *args = ((OpExpr *) w)->args;
9825
9826 if (list_length(args) == 2 &&
9827 IsA(strip_implicit_coercions(linitial(args)),
9828 CaseTestExpr))
9829 w = (Node *) lsecond(args);
9830 }
9831 }
9832
9833 if (!PRETTY_INDENT(context))
9834 appendStringInfoChar(buf, ' ');
9835 appendContextKeyword(context, "WHEN ",
9836 0, 0, 0);
9837 get_rule_expr(w, context, false);
9838 appendStringInfoString(buf, " THEN ");
9839 get_rule_expr((Node *) when->result, context, true);
9840 }
9841 if (!PRETTY_INDENT(context))
9842 appendStringInfoChar(buf, ' ');
9843 appendContextKeyword(context, "ELSE ",
9844 0, 0, 0);
9845 get_rule_expr((Node *) caseexpr->defresult, context, true);
9846 if (!PRETTY_INDENT(context))
9847 appendStringInfoChar(buf, ' ');
9848 appendContextKeyword(context, "END",
9849 -PRETTYINDENT_VAR, 0, 0);
9850 }
9851 break;
9852
9853 case T_CaseTestExpr:
9854 {
9855 /*
9856 * Normally we should never get here, since for expressions
9857 * that can contain this node type we attempt to avoid
9858 * recursing to it. But in an optimized expression we might
9859 * be unable to avoid that (see comments for CaseExpr). If we
9860 * do see one, print it as CASE_TEST_EXPR.
9861 */
9862 appendStringInfoString(buf, "CASE_TEST_EXPR");
9863 }
9864 break;
9865
9866 case T_ArrayExpr:
9867 {
9868 ArrayExpr *arrayexpr = (ArrayExpr *) node;
9869
9870 appendStringInfoString(buf, "ARRAY[");
9871 get_rule_expr((Node *) arrayexpr->elements, context, true);
9872 appendStringInfoChar(buf, ']');
9873
9874 /*
9875 * If the array isn't empty, we assume its elements are
9876 * coerced to the desired type. If it's empty, though, we
9877 * need an explicit coercion to the array type.
9878 */
9879 if (arrayexpr->elements == NIL)
9880 appendStringInfo(buf, "::%s",
9881 format_type_with_typemod(arrayexpr->array_typeid, -1));
9882 }
9883 break;
9884
9885 case T_RowExpr:
9886 {
9887 RowExpr *rowexpr = (RowExpr *) node;
9888 TupleDesc tupdesc = NULL;
9889 ListCell *arg;
9890 int i;
9891 char *sep;
9892
9893 /*
9894 * If it's a named type and not RECORD, we may have to skip
9895 * dropped columns and/or claim there are NULLs for added
9896 * columns.
9897 */
9898 if (rowexpr->row_typeid != RECORDOID)
9899 {
9900 tupdesc = lookup_rowtype_tupdesc(rowexpr->row_typeid, -1);
9901 Assert(list_length(rowexpr->args) <= tupdesc->natts);
9902 }
9903
9904 /*
9905 * SQL99 allows "ROW" to be omitted when there is more than
9906 * one column, but for simplicity we always print it.
9907 */
9908 appendStringInfoString(buf, "ROW(");
9909 sep = "";
9910 i = 0;
9911 foreach(arg, rowexpr->args)
9912 {
9913 Node *e = (Node *) lfirst(arg);
9914
9915 if (tupdesc == NULL ||
9916 !TupleDescAttr(tupdesc, i)->attisdropped)
9917 {
9918 appendStringInfoString(buf, sep);
9919 /* Whole-row Vars need special treatment here */
9920 get_rule_expr_toplevel(e, context, true);
9921 sep = ", ";
9922 }
9923 i++;
9924 }
9925 if (tupdesc != NULL)
9926 {
9927 while (i < tupdesc->natts)
9928 {
9929 if (!TupleDescAttr(tupdesc, i)->attisdropped)
9930 {
9931 appendStringInfoString(buf, sep);
9932 appendStringInfoString(buf, "NULL");
9933 sep = ", ";
9934 }
9935 i++;
9936 }
9937
9938 ReleaseTupleDesc(tupdesc);
9939 }
9940 appendStringInfoChar(buf, ')');
9941 if (rowexpr->row_format == COERCE_EXPLICIT_CAST)
9942 appendStringInfo(buf, "::%s",
9943 format_type_with_typemod(rowexpr->row_typeid, -1));
9944 }
9945 break;
9946
9947 case T_RowCompareExpr:
9948 {
9949 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
9950
9951 /*
9952 * SQL99 allows "ROW" to be omitted when there is more than
9953 * one column, but for simplicity we always print it. Within
9954 * a ROW expression, whole-row Vars need special treatment, so
9955 * use get_rule_list_toplevel.
9956 */
9957 appendStringInfoString(buf, "(ROW(");
9958 get_rule_list_toplevel(rcexpr->largs, context, true);
9959
9960 /*
9961 * We assume that the name of the first-column operator will
9962 * do for all the rest too. This is definitely open to
9963 * failure, eg if some but not all operators were renamed
9964 * since the construct was parsed, but there seems no way to
9965 * be perfect.
9966 */
9967 appendStringInfo(buf, ") %s ROW(",
9968 generate_operator_name(linitial_oid(rcexpr->opnos),
9969 exprType(linitial(rcexpr->largs)),
9970 exprType(linitial(rcexpr->rargs))));
9971 get_rule_list_toplevel(rcexpr->rargs, context, true);
9972 appendStringInfoString(buf, "))");
9973 }
9974 break;
9975
9976 case T_CoalesceExpr:
9977 {
9978 CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
9979
9980 appendStringInfoString(buf, "COALESCE(");
9981 get_rule_expr((Node *) coalesceexpr->args, context, true);
9982 appendStringInfoChar(buf, ')');
9983 }
9984 break;
9985
9986 case T_MinMaxExpr:
9987 {
9988 MinMaxExpr *minmaxexpr = (MinMaxExpr *) node;
9989
9990 switch (minmaxexpr->op)
9991 {
9992 case IS_GREATEST:
9993 appendStringInfoString(buf, "GREATEST(");
9994 break;
9995 case IS_LEAST:
9996 appendStringInfoString(buf, "LEAST(");
9997 break;
9998 }
9999 get_rule_expr((Node *) minmaxexpr->args, context, true);
10000 appendStringInfoChar(buf, ')');
10001 }
10002 break;
10003
10004 case T_SQLValueFunction:
10005 {
10006 SQLValueFunction *svf = (SQLValueFunction *) node;
10007
10008 /*
10009 * Note: this code knows that typmod for time, timestamp, and
10010 * timestamptz just prints as integer.
10011 */
10012 switch (svf->op)
10013 {
10014 case SVFOP_CURRENT_DATE:
10015 appendStringInfoString(buf, "CURRENT_DATE");
10016 break;
10017 case SVFOP_CURRENT_TIME:
10018 appendStringInfoString(buf, "CURRENT_TIME");
10019 break;
10020 case SVFOP_CURRENT_TIME_N:
10021 appendStringInfo(buf, "CURRENT_TIME(%d)", svf->typmod);
10022 break;
10023 case SVFOP_CURRENT_TIMESTAMP:
10024 appendStringInfoString(buf, "CURRENT_TIMESTAMP");
10025 break;
10026 case SVFOP_CURRENT_TIMESTAMP_N:
10027 appendStringInfo(buf, "CURRENT_TIMESTAMP(%d)",
10028 svf->typmod);
10029 break;
10030 case SVFOP_LOCALTIME:
10031 appendStringInfoString(buf, "LOCALTIME");
10032 break;
10033 case SVFOP_LOCALTIME_N:
10034 appendStringInfo(buf, "LOCALTIME(%d)", svf->typmod);
10035 break;
10036 case SVFOP_LOCALTIMESTAMP:
10037 appendStringInfoString(buf, "LOCALTIMESTAMP");
10038 break;
10039 case SVFOP_LOCALTIMESTAMP_N:
10040 appendStringInfo(buf, "LOCALTIMESTAMP(%d)",
10041 svf->typmod);
10042 break;
10043 case SVFOP_CURRENT_ROLE:
10044 appendStringInfoString(buf, "CURRENT_ROLE");
10045 break;
10046 case SVFOP_CURRENT_USER:
10047 appendStringInfoString(buf, "CURRENT_USER");
10048 break;
10049 case SVFOP_USER:
10050 appendStringInfoString(buf, "USER");
10051 break;
10052 case SVFOP_SESSION_USER:
10053 appendStringInfoString(buf, "SESSION_USER");
10054 break;
10055 case SVFOP_CURRENT_CATALOG:
10056 appendStringInfoString(buf, "CURRENT_CATALOG");
10057 break;
10058 case SVFOP_CURRENT_SCHEMA:
10059 appendStringInfoString(buf, "CURRENT_SCHEMA");
10060 break;
10061 }
10062 }
10063 break;
10064
10065 case T_XmlExpr:
10066 {
10067 XmlExpr *xexpr = (XmlExpr *) node;
10068 bool needcomma = false;
10069 ListCell *arg;
10070 ListCell *narg;
10071 Const *con;
10072
10073 switch (xexpr->op)
10074 {
10075 case IS_XMLCONCAT:
10076 appendStringInfoString(buf, "XMLCONCAT(");
10077 break;
10078 case IS_XMLELEMENT:
10079 appendStringInfoString(buf, "XMLELEMENT(");
10080 break;
10081 case IS_XMLFOREST:
10082 appendStringInfoString(buf, "XMLFOREST(");
10083 break;
10084 case IS_XMLPARSE:
10085 appendStringInfoString(buf, "XMLPARSE(");
10086 break;
10087 case IS_XMLPI:
10088 appendStringInfoString(buf, "XMLPI(");
10089 break;
10090 case IS_XMLROOT:
10091 appendStringInfoString(buf, "XMLROOT(");
10092 break;
10093 case IS_XMLSERIALIZE:
10094 appendStringInfoString(buf, "XMLSERIALIZE(");
10095 break;
10096 case IS_DOCUMENT:
10097 break;
10098 }
10099 if (xexpr->op == IS_XMLPARSE || xexpr->op == IS_XMLSERIALIZE)
10100 {
10101 if (xexpr->xmloption == XMLOPTION_DOCUMENT)
10102 appendStringInfoString(buf, "DOCUMENT ");
10103 else
10104 appendStringInfoString(buf, "CONTENT ");
10105 }
10106 if (xexpr->name)
10107 {
10108 appendStringInfo(buf, "NAME %s",
10109 quote_identifier(map_xml_name_to_sql_identifier(xexpr->name)));
10110 needcomma = true;
10111 }
10112 if (xexpr->named_args)
10113 {
10114 if (xexpr->op != IS_XMLFOREST)
10115 {
10116 if (needcomma)
10117 appendStringInfoString(buf, ", ");
10118 appendStringInfoString(buf, "XMLATTRIBUTES(");
10119 needcomma = false;
10120 }
10121 forboth(arg, xexpr->named_args, narg, xexpr->arg_names)
10122 {
10123 Node *e = (Node *) lfirst(arg);
10124 char *argname = strVal(lfirst(narg));
10125
10126 if (needcomma)
10127 appendStringInfoString(buf, ", ");
10128 get_rule_expr((Node *) e, context, true);
10129 appendStringInfo(buf, " AS %s",
10130 quote_identifier(map_xml_name_to_sql_identifier(argname)));
10131 needcomma = true;
10132 }
10133 if (xexpr->op != IS_XMLFOREST)
10134 appendStringInfoChar(buf, ')');
10135 }
10136 if (xexpr->args)
10137 {
10138 if (needcomma)
10139 appendStringInfoString(buf, ", ");
10140 switch (xexpr->op)
10141 {
10142 case IS_XMLCONCAT:
10143 case IS_XMLELEMENT:
10144 case IS_XMLFOREST:
10145 case IS_XMLPI:
10146 case IS_XMLSERIALIZE:
10147 /* no extra decoration needed */
10148 get_rule_expr((Node *) xexpr->args, context, true);
10149 break;
10150 case IS_XMLPARSE:
10151 Assert(list_length(xexpr->args) == 2);
10152
10153 get_rule_expr((Node *) linitial(xexpr->args),
10154 context, true);
10155
10156 con = lsecond_node(Const, xexpr->args);
10157 Assert(!con->constisnull);
10158 if (DatumGetBool(con->constvalue))
10159 appendStringInfoString(buf,
10160 " PRESERVE WHITESPACE");
10161 else
10162 appendStringInfoString(buf,
10163 " STRIP WHITESPACE");
10164 break;
10165 case IS_XMLROOT:
10166 Assert(list_length(xexpr->args) == 3);
10167
10168 get_rule_expr((Node *) linitial(xexpr->args),
10169 context, true);
10170
10171 appendStringInfoString(buf, ", VERSION ");
10172 con = (Const *) lsecond(xexpr->args);
10173 if (IsA(con, Const) &&
10174 con->constisnull)
10175 appendStringInfoString(buf, "NO VALUE");
10176 else
10177 get_rule_expr((Node *) con, context, false);
10178
10179 con = lthird_node(Const, xexpr->args);
10180 if (con->constisnull)
10181 /* suppress STANDALONE NO VALUE */ ;
10182 else
10183 {
10184 switch (DatumGetInt32(con->constvalue))
10185 {
10186 case XML_STANDALONE_YES:
10187 appendStringInfoString(buf,
10188 ", STANDALONE YES");
10189 break;
10190 case XML_STANDALONE_NO:
10191 appendStringInfoString(buf,
10192 ", STANDALONE NO");
10193 break;
10194 case XML_STANDALONE_NO_VALUE:
10195 appendStringInfoString(buf,
10196 ", STANDALONE NO VALUE");
10197 break;
10198 default:
10199 break;
10200 }
10201 }
10202 break;
10203 case IS_DOCUMENT:
10204 get_rule_expr_paren((Node *) xexpr->args, context, false, node);
10205 break;
10206 }
10207 }
10208 if (xexpr->op == IS_XMLSERIALIZE)
10209 {
10210 appendStringInfo(buf, " AS %s",
10211 format_type_with_typemod(xexpr->type,
10212 xexpr->typmod));
10213 if (xexpr->indent)
10214 appendStringInfoString(buf, " INDENT");
10215 else
10216 appendStringInfoString(buf, " NO INDENT");
10217 }
10218
10219 if (xexpr->op == IS_DOCUMENT)
10220 appendStringInfoString(buf, " IS DOCUMENT");
10221 else
10222 appendStringInfoChar(buf, ')');
10223 }
10224 break;
10225
10226 case T_NullTest:
10227 {
10228 NullTest *ntest = (NullTest *) node;
10229
10230 if (!PRETTY_PAREN(context))
10231 appendStringInfoChar(buf, '(');
10232 get_rule_expr_paren((Node *) ntest->arg, context, true, node);
10233
10234 /*
10235 * For scalar inputs, we prefer to print as IS [NOT] NULL,
10236 * which is shorter and traditional. If it's a rowtype input
10237 * but we're applying a scalar test, must print IS [NOT]
10238 * DISTINCT FROM NULL to be semantically correct.
10239 */
10240 if (ntest->argisrow ||
10241 !type_is_rowtype(exprType((Node *) ntest->arg)))
10242 {
10243 switch (ntest->nulltesttype)
10244 {
10245 case IS_NULL:
10246 appendStringInfoString(buf, " IS NULL");
10247 break;
10248 case IS_NOT_NULL:
10249 appendStringInfoString(buf, " IS NOT NULL");
10250 break;
10251 default:
10252 elog(ERROR, "unrecognized nulltesttype: %d",
10253 (int) ntest->nulltesttype);
10254 }
10255 }
10256 else
10257 {
10258 switch (ntest->nulltesttype)
10259 {
10260 case IS_NULL:
10261 appendStringInfoString(buf, " IS NOT DISTINCT FROM NULL");
10262 break;
10263 case IS_NOT_NULL:
10264 appendStringInfoString(buf, " IS DISTINCT FROM NULL");
10265 break;
10266 default:
10267 elog(ERROR, "unrecognized nulltesttype: %d",
10268 (int) ntest->nulltesttype);
10269 }
10270 }
10271 if (!PRETTY_PAREN(context))
10272 appendStringInfoChar(buf, ')');
10273 }
10274 break;
10275
10276 case T_BooleanTest:
10277 {
10278 BooleanTest *btest = (BooleanTest *) node;
10279
10280 if (!PRETTY_PAREN(context))
10281 appendStringInfoChar(buf, '(');
10282 get_rule_expr_paren((Node *) btest->arg, context, false, node);
10283 switch (btest->booltesttype)
10284 {
10285 case IS_TRUE:
10286 appendStringInfoString(buf, " IS TRUE");
10287 break;
10288 case IS_NOT_TRUE:
10289 appendStringInfoString(buf, " IS NOT TRUE");
10290 break;
10291 case IS_FALSE:
10292 appendStringInfoString(buf, " IS FALSE");
10293 break;
10294 case IS_NOT_FALSE:
10295 appendStringInfoString(buf, " IS NOT FALSE");
10296 break;
10297 case IS_UNKNOWN:
10298 appendStringInfoString(buf, " IS UNKNOWN");
10299 break;
10300 case IS_NOT_UNKNOWN:
10301 appendStringInfoString(buf, " IS NOT UNKNOWN");
10302 break;
10303 default:
10304 elog(ERROR, "unrecognized booltesttype: %d",
10305 (int) btest->booltesttype);
10306 }
10307 if (!PRETTY_PAREN(context))
10308 appendStringInfoChar(buf, ')');
10309 }
10310 break;
10311
10312 case T_CoerceToDomain:
10313 {
10314 CoerceToDomain *ctest = (CoerceToDomain *) node;
10315 Node *arg = (Node *) ctest->arg;
10316
10317 if (ctest->coercionformat == COERCE_IMPLICIT_CAST &&
10318 !showimplicit)
10319 {
10320 /* don't show the implicit cast */
10321 get_rule_expr(arg, context, false);
10322 }
10323 else
10324 {
10325 get_coercion_expr(arg, context,
10326 ctest->resulttype,
10327 ctest->resulttypmod,
10328 node);
10329 }
10330 }
10331 break;
10332
10333 case T_CoerceToDomainValue:
10334 appendStringInfoString(buf, "VALUE");
10335 break;
10336
10337 case T_SetToDefault:
10338 appendStringInfoString(buf, "DEFAULT");
10339 break;
10340
10341 case T_CurrentOfExpr:
10342 {
10343 CurrentOfExpr *cexpr = (CurrentOfExpr *) node;
10344
10345 if (cexpr->cursor_name)
10346 appendStringInfo(buf, "CURRENT OF %s",
10347 quote_identifier(cexpr->cursor_name));
10348 else
10349 appendStringInfo(buf, "CURRENT OF $%d",
10350 cexpr->cursor_param);
10351 }
10352 break;
10353
10354 case T_NextValueExpr:
10355 {
10356 NextValueExpr *nvexpr = (NextValueExpr *) node;
10357
10358 /*
10359 * This isn't exactly nextval(), but that seems close enough
10360 * for EXPLAIN's purposes.
10361 */
10362 appendStringInfoString(buf, "nextval(");
10363 simple_quote_literal(buf,
10364 generate_relation_name(nvexpr->seqid,
10365 NIL));
10366 appendStringInfoChar(buf, ')');
10367 }
10368 break;
10369
10370 case T_InferenceElem:
10371 {
10372 InferenceElem *iexpr = (InferenceElem *) node;
10373 bool save_varprefix;
10374 bool need_parens;
10375
10376 /*
10377 * InferenceElem can only refer to target relation, so a
10378 * prefix is not useful, and indeed would cause parse errors.
10379 */
10380 save_varprefix = context->varprefix;
10381 context->varprefix = false;
10382
10383 /*
10384 * Parenthesize the element unless it's a simple Var or a bare
10385 * function call. Follows pg_get_indexdef_worker().
10386 */
10387 need_parens = !IsA(iexpr->expr, Var);
10388 if (IsA(iexpr->expr, FuncExpr) &&
10389 ((FuncExpr *) iexpr->expr)->funcformat ==
10390 COERCE_EXPLICIT_CALL)
10391 need_parens = false;
10392
10393 if (need_parens)
10394 appendStringInfoChar(buf, '(');
10395 get_rule_expr((Node *) iexpr->expr,
10396 context, false);
10397 if (need_parens)
10398 appendStringInfoChar(buf, ')');
10399
10400 context->varprefix = save_varprefix;
10401
10402 if (iexpr->infercollid)
10403 appendStringInfo(buf, " COLLATE %s",
10404 generate_collation_name(iexpr->infercollid));
10405
10406 /* Add the operator class name, if not default */
10407 if (iexpr->inferopclass)
10408 {
10409 Oid inferopclass = iexpr->inferopclass;
10410 Oid inferopcinputtype = get_opclass_input_type(iexpr->inferopclass);
10411
10412 get_opclass_name(inferopclass, inferopcinputtype, buf);
10413 }
10414 }
10415 break;
10416
10417 case T_ReturningExpr:
10418 {
10419 ReturningExpr *retExpr = (ReturningExpr *) node;
10420
10421 /*
10422 * We cannot see a ReturningExpr in rule deparsing, only while
10423 * EXPLAINing a query plan (ReturningExpr nodes are only ever
10424 * adding during query rewriting). Just display the expression
10425 * returned (an expanded view column).
10426 */
10427 get_rule_expr((Node *) retExpr->retexpr, context, showimplicit);
10428 }
10429 break;
10430
10431 case T_PartitionBoundSpec:
10432 {
10433 PartitionBoundSpec *spec = (PartitionBoundSpec *) node;
10434 ListCell *cell;
10435 char *sep;
10436
10437 if (spec->is_default)
10438 {
10439 appendStringInfoString(buf, "DEFAULT");
10440 break;
10441 }
10442
10443 switch (spec->strategy)
10444 {
10445 case PARTITION_STRATEGY_HASH:
10446 Assert(spec->modulus > 0 && spec->remainder >= 0);
10447 Assert(spec->modulus > spec->remainder);
10448
10449 appendStringInfoString(buf, "FOR VALUES");
10450 appendStringInfo(buf, " WITH (modulus %d, remainder %d)",
10451 spec->modulus, spec->remainder);
10452 break;
10453
10454 case PARTITION_STRATEGY_LIST:
10455 Assert(spec->listdatums != NIL);
10456
10457 appendStringInfoString(buf, "FOR VALUES IN (");
10458 sep = "";
10459 foreach(cell, spec->listdatums)
10460 {
10461 Const *val = lfirst_node(Const, cell);
10462
10463 appendStringInfoString(buf, sep);
10464 get_const_expr(val, context, -1);
10465 sep = ", ";
10466 }
10467
10468 appendStringInfoChar(buf, ')');
10469 break;
10470
10471 case PARTITION_STRATEGY_RANGE:
10472 Assert(spec->lowerdatums != NIL &&
10473 spec->upperdatums != NIL &&
10474 list_length(spec->lowerdatums) ==
10475 list_length(spec->upperdatums));
10476
10477 appendStringInfo(buf, "FOR VALUES FROM %s TO %s",
10478 get_range_partbound_string(spec->lowerdatums),
10479 get_range_partbound_string(spec->upperdatums));
10480 break;
10481
10482 default:
10483 elog(ERROR, "unrecognized partition strategy: %d",
10484 (int) spec->strategy);
10485 break;
10486 }
10487 }
10488 break;
10489
10490 case T_JsonValueExpr:
10491 {
10492 JsonValueExpr *jve = (JsonValueExpr *) node;
10493
10494 get_rule_expr((Node *) jve->raw_expr, context, false);
10495 get_json_format(jve->format, context->buf);
10496 }
10497 break;
10498
10499 case T_JsonConstructorExpr:
10500 get_json_constructor((JsonConstructorExpr *) node, context, false);
10501 break;
10502
10503 case T_JsonIsPredicate:
10504 {
10505 JsonIsPredicate *pred = (JsonIsPredicate *) node;
10506
10507 if (!PRETTY_PAREN(context))
10508 appendStringInfoChar(context->buf, '(');
10509
10510 get_rule_expr_paren(pred->expr, context, true, node);
10511
10512 appendStringInfoString(context->buf, " IS JSON");
10513
10514 /* TODO: handle FORMAT clause */
10515
10516 switch (pred->item_type)
10517 {
10518 case JS_TYPE_SCALAR:
10519 appendStringInfoString(context->buf, " SCALAR");
10520 break;
10521 case JS_TYPE_ARRAY:
10522 appendStringInfoString(context->buf, " ARRAY");
10523 break;
10524 case JS_TYPE_OBJECT:
10525 appendStringInfoString(context->buf, " OBJECT");
10526 break;
10527 default:
10528 break;
10529 }
10530
10531 if (pred->unique_keys)
10532 appendStringInfoString(context->buf, " WITH UNIQUE KEYS");
10533
10534 if (!PRETTY_PAREN(context))
10535 appendStringInfoChar(context->buf, ')');
10536 }
10537 break;
10538
10539 case T_JsonExpr:
10540 {
10541 JsonExpr *jexpr = (JsonExpr *) node;
10542
10543 switch (jexpr->op)
10544 {
10545 case JSON_EXISTS_OP:
10546 appendStringInfoString(buf, "JSON_EXISTS(");
10547 break;
10548 case JSON_QUERY_OP:
10549 appendStringInfoString(buf, "JSON_QUERY(");
10550 break;
10551 case JSON_VALUE_OP:
10552 appendStringInfoString(buf, "JSON_VALUE(");
10553 break;
10554 default:
10555 elog(ERROR, "unrecognized JsonExpr op: %d",
10556 (int) jexpr->op);
10557 }
10558
10559 get_rule_expr(jexpr->formatted_expr, context, showimplicit);
10560
10561 appendStringInfoString(buf, ", ");
10562
10563 get_json_path_spec(jexpr->path_spec, context, showimplicit);
10564
10565 if (jexpr->passing_values)
10566 {
10567 ListCell *lc1,
10568 *lc2;
10569 bool needcomma = false;
10570
10571 appendStringInfoString(buf, " PASSING ");
10572
10573 forboth(lc1, jexpr->passing_names,
10574 lc2, jexpr->passing_values)
10575 {
10576 if (needcomma)
10577 appendStringInfoString(buf, ", ");
10578 needcomma = true;
10579
10580 get_rule_expr((Node *) lfirst(lc2), context, showimplicit);
10581 appendStringInfo(buf, " AS %s",
10582 quote_identifier(lfirst_node(String, lc1)->sval));
10583 }
10584 }
10585
10586 if (jexpr->op != JSON_EXISTS_OP ||
10587 jexpr->returning->typid != BOOLOID)
10588 get_json_returning(jexpr->returning, context->buf,
10589 jexpr->op == JSON_QUERY_OP);
10590
10591 get_json_expr_options(jexpr, context,
10592 jexpr->op != JSON_EXISTS_OP ?
10593 JSON_BEHAVIOR_NULL :
10594 JSON_BEHAVIOR_FALSE);
10595
10596 appendStringInfoChar(buf, ')');
10597 }
10598 break;
10599
10600 case T_List:
10601 {
10602 char *sep;
10603 ListCell *l;
10604
10605 sep = "";
10606 foreach(l, (List *) node)
10607 {
10608 appendStringInfoString(buf, sep);
10609 get_rule_expr((Node *) lfirst(l), context, showimplicit);
10610 sep = ", ";
10611 }
10612 }
10613 break;
10614
10615 case T_TableFunc:
10616 get_tablefunc((TableFunc *) node, context, showimplicit);
10617 break;
10618
10619 default:
10620 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(node));
10621 break;
10622 }
10623 }
10624
10625 /*
10626 * get_rule_expr_toplevel - Parse back a toplevel expression
10627 *
10628 * Same as get_rule_expr(), except that if the expr is just a Var, we pass
10629 * istoplevel = true not false to get_variable(). This causes whole-row Vars
10630 * to get printed with decoration that will prevent expansion of "*".
10631 * We need to use this in contexts such as ROW() and VALUES(), where the
10632 * parser would expand "foo.*" appearing at top level. (In principle we'd
10633 * use this in get_target_list() too, but that has additional worries about
10634 * whether to print AS, so it needs to invoke get_variable() directly anyway.)
10635 */
10636 static void
10637 get_rule_expr_toplevel(Node *node, deparse_context *context,
10638 bool showimplicit)
10639 {
10640 if (node && IsA(node, Var))
10641 (void) get_variable((Var *) node, 0, true, context);
10642 else
10643 get_rule_expr(node, context, showimplicit);
10644 }
10645
10646 /*
10647 * get_rule_list_toplevel - Parse back a list of toplevel expressions
10648 *
10649 * Apply get_rule_expr_toplevel() to each element of a List.
10650 *
10651 * This adds commas between the expressions, but caller is responsible
10652 * for printing surrounding decoration.
10653 */
10654 static void
10655 get_rule_list_toplevel(List *lst, deparse_context *context,
10656 bool showimplicit)
10657 {
10658 const char *sep;
10659 ListCell *lc;
10660
10661 sep = "";
10662 foreach(lc, lst)
10663 {
10664 Node *e = (Node *) lfirst(lc);
10665
10666 appendStringInfoString(context->buf, sep);
10667 get_rule_expr_toplevel(e, context, showimplicit);
10668 sep = ", ";
10669 }
10670 }
10671
10672 /*
10673 * get_rule_expr_funccall - Parse back a function-call expression
10674 *
10675 * Same as get_rule_expr(), except that we guarantee that the output will
10676 * look like a function call, or like one of the things the grammar treats as
10677 * equivalent to a function call (see the func_expr_windowless production).
10678 * This is needed in places where the grammar uses func_expr_windowless and
10679 * you can't substitute a parenthesized a_expr. If what we have isn't going
10680 * to look like a function call, wrap it in a dummy CAST() expression, which
10681 * will satisfy the grammar --- and, indeed, is likely what the user wrote to
10682 * produce such a thing.
10683 */
10684 static void
10685 get_rule_expr_funccall(Node *node, deparse_context *context,
10686 bool showimplicit)
10687 {
10688 if (looks_like_function(node))
10689 get_rule_expr(node, context, showimplicit);
10690 else
10691 {
10692 StringInfo buf = context->buf;
10693
10694 appendStringInfoString(buf, "CAST(");
10695 /* no point in showing any top-level implicit cast */
10696 get_rule_expr(node, context, false);
10697 appendStringInfo(buf, " AS %s)",
10698 format_type_with_typemod(exprType(node),
10699 exprTypmod(node)));
10700 }
10701 }
10702
10703 /*
10704 * Helper function to identify node types that satisfy func_expr_windowless.
10705 * If in doubt, "false" is always a safe answer.
10706 */
10707 static bool
10708 looks_like_function(Node *node)
10709 {
10710 if (node == NULL)
10711 return false; /* probably shouldn't happen */
10712 switch (nodeTag(node))
10713 {
10714 case T_FuncExpr:
10715 /* OK, unless it's going to deparse as a cast */
10716 return (((FuncExpr *) node)->funcformat == COERCE_EXPLICIT_CALL ||
10717 ((FuncExpr *) node)->funcformat == COERCE_SQL_SYNTAX);
10718 case T_NullIfExpr:
10719 case T_CoalesceExpr:
10720 case T_MinMaxExpr:
10721 case T_SQLValueFunction:
10722 case T_XmlExpr:
10723 case T_JsonExpr:
10724 /* these are all accepted by func_expr_common_subexpr */
10725 return true;
10726 default:
10727 break;
10728 }
10729 return false;
10730 }
10731
10732
10733 /*
10734 * get_oper_expr - Parse back an OpExpr node
10735 */
10736 static void
10737 get_oper_expr(OpExpr *expr, deparse_context *context)
10738 {
10739 StringInfo buf = context->buf;
10740 Oid opno = expr->opno;
10741 List *args = expr->args;
10742
10743 if (!PRETTY_PAREN(context))
10744 appendStringInfoChar(buf, '(');
10745 if (list_length(args) == 2)
10746 {
10747 /* binary operator */
10748 Node *arg1 = (Node *) linitial(args);
10749 Node *arg2 = (Node *) lsecond(args);
10750
10751 get_rule_expr_paren(arg1, context, true, (Node *) expr);
10752 appendStringInfo(buf, " %s ",
10753 generate_operator_name(opno,
10754 exprType(arg1),
10755 exprType(arg2)));
10756 get_rule_expr_paren(arg2, context, true, (Node *) expr);
10757 }
10758 else
10759 {
10760 /* prefix operator */
10761 Node *arg = (Node *) linitial(args);
10762
10763 appendStringInfo(buf, "%s ",
10764 generate_operator_name(opno,
10765 InvalidOid,
10766 exprType(arg)));
10767 get_rule_expr_paren(arg, context, true, (Node *) expr);
10768 }
10769 if (!PRETTY_PAREN(context))
10770 appendStringInfoChar(buf, ')');
10771 }
10772
10773 /*
10774 * get_func_expr - Parse back a FuncExpr node
10775 */
10776 static void
10777 get_func_expr(FuncExpr *expr, deparse_context *context,
10778 bool showimplicit)
10779 {
10780 StringInfo buf = context->buf;
10781 Oid funcoid = expr->funcid;
10782 Oid argtypes[FUNC_MAX_ARGS];
10783 int nargs;
10784 List *argnames;
10785 bool use_variadic;
10786 ListCell *l;
10787
10788 /*
10789 * If the function call came from an implicit coercion, then just show the
10790 * first argument --- unless caller wants to see implicit coercions.
10791 */
10792 if (expr->funcformat == COERCE_IMPLICIT_CAST && !showimplicit)
10793 {
10794 get_rule_expr_paren((Node *) linitial(expr->args), context,
10795 false, (Node *) expr);
10796 return;
10797 }
10798
10799 /*
10800 * If the function call came from a cast, then show the first argument
10801 * plus an explicit cast operation.
10802 */
10803 if (expr->funcformat == COERCE_EXPLICIT_CAST ||
10804 expr->funcformat == COERCE_IMPLICIT_CAST)
10805 {
10806 Node *arg = linitial(expr->args);
10807 Oid rettype = expr->funcresulttype;
10808 int32 coercedTypmod;
10809
10810 /* Get the typmod if this is a length-coercion function */
10811 (void) exprIsLengthCoercion((Node *) expr, &coercedTypmod);
10812
10813 get_coercion_expr(arg, context,
10814 rettype, coercedTypmod,
10815 (Node *) expr);
10816
10817 return;
10818 }
10819
10820 /*
10821 * If the function was called using one of the SQL spec's random special
10822 * syntaxes, try to reproduce that. If we don't recognize the function,
10823 * fall through.
10824 */
10825 if (expr->funcformat == COERCE_SQL_SYNTAX)
10826 {
10827 if (get_func_sql_syntax(expr, context))
10828 return;
10829 }
10830
10831 /*
10832 * Normal function: display as proname(args). First we need to extract
10833 * the argument datatypes.
10834 */
10835 if (list_length(expr->args) > FUNC_MAX_ARGS)
10836 ereport(ERROR,
10837 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
10838 errmsg("too many arguments")));
10839 nargs = 0;
10840 argnames = NIL;
10841 foreach(l, expr->args)
10842 {
10843 Node *arg = (Node *) lfirst(l);
10844
10845 if (IsA(arg, NamedArgExpr))
10846 argnames = lappend(argnames, ((NamedArgExpr *) arg)->name);
10847 argtypes[nargs] = exprType(arg);
10848 nargs++;
10849 }
10850
10851 appendStringInfo(buf, "%s(",
10852 generate_function_name(funcoid, nargs,
10853 argnames, argtypes,
10854 expr->funcvariadic,
10855 &use_variadic,
10856 context->inGroupBy));
10857 nargs = 0;
10858 foreach(l, expr->args)
10859 {
10860 if (nargs++ > 0)
10861 appendStringInfoString(buf, ", ");
10862 if (use_variadic && lnext(expr->args, l) == NULL)
10863 appendStringInfoString(buf, "VARIADIC ");
10864 get_rule_expr((Node *) lfirst(l), context, true);
10865 }
10866 appendStringInfoChar(buf, ')');
10867 }
10868
10869 /*
10870 * get_agg_expr - Parse back an Aggref node
10871 */
10872 static void
10873 get_agg_expr(Aggref *aggref, deparse_context *context,
10874 Aggref *original_aggref)
10875 {
10876 get_agg_expr_helper(aggref, context, original_aggref, NULL, NULL,
10877 false);
10878 }
10879
10880 /*
10881 * get_agg_expr_helper - subroutine for get_agg_expr and
10882 * get_json_agg_constructor
10883 */
10884 static void
10885 get_agg_expr_helper(Aggref *aggref, deparse_context *context,
10886 Aggref *original_aggref, const char *funcname,
10887 const char *options, bool is_json_objectagg)
10888 {
10889 StringInfo buf = context->buf;
10890 Oid argtypes[FUNC_MAX_ARGS];
10891 int nargs;
10892 bool use_variadic = false;
10893
10894 /*
10895 * For a combining aggregate, we look up and deparse the corresponding
10896 * partial aggregate instead. This is necessary because our input
10897 * argument list has been replaced; the new argument list always has just
10898 * one element, which will point to a partial Aggref that supplies us with
10899 * transition states to combine.
10900 */
10901 if (DO_AGGSPLIT_COMBINE(aggref->aggsplit))
10902 {
10903 TargetEntry *tle;
10904
10905 Assert(list_length(aggref->args) == 1);
10906 tle = linitial_node(TargetEntry, aggref->args);
10907 resolve_special_varno((Node *) tle->expr, context,
10908 get_agg_combine_expr, original_aggref);
10909 return;
10910 }
10911
10912 /*
10913 * Mark as PARTIAL, if appropriate. We look to the original aggref so as
10914 * to avoid printing this when recursing from the code just above.
10915 */
10916 if (DO_AGGSPLIT_SKIPFINAL(original_aggref->aggsplit))
10917 appendStringInfoString(buf, "PARTIAL ");
10918
10919 /* Extract the argument types as seen by the parser */
10920 nargs = get_aggregate_argtypes(aggref, argtypes);
10921
10922 if (!funcname)
10923 funcname = generate_function_name(aggref->aggfnoid, nargs, NIL,
10924 argtypes, aggref->aggvariadic,
10925 &use_variadic,
10926 context->inGroupBy);
10927
10928 /* Print the aggregate name, schema-qualified if needed */
10929 appendStringInfo(buf, "%s(%s", funcname,
10930 (aggref->aggdistinct != NIL) ? "DISTINCT " : "");
10931
10932 if (AGGKIND_IS_ORDERED_SET(aggref->aggkind))
10933 {
10934 /*
10935 * Ordered-set aggregates do not use "*" syntax. Also, we needn't
10936 * worry about inserting VARIADIC. So we can just dump the direct
10937 * args as-is.
10938 */
10939 Assert(!aggref->aggvariadic);
10940 get_rule_expr((Node *) aggref->aggdirectargs, context, true);
10941 Assert(aggref->aggorder != NIL);
10942 appendStringInfoString(buf, ") WITHIN GROUP (ORDER BY ");
10943 get_rule_orderby(aggref->aggorder, aggref->args, false, context);
10944 }
10945 else
10946 {
10947 /* aggstar can be set only in zero-argument aggregates */
10948 if (aggref->aggstar)
10949 appendStringInfoChar(buf, '*');
10950 else
10951 {
10952 ListCell *l;
10953 int i;
10954
10955 i = 0;
10956 foreach(l, aggref->args)
10957 {
10958 TargetEntry *tle = (TargetEntry *) lfirst(l);
10959 Node *arg = (Node *) tle->expr;
10960
10961 Assert(!IsA(arg, NamedArgExpr));
10962 if (tle->resjunk)
10963 continue;
10964 if (i++ > 0)
10965 {
10966 if (is_json_objectagg)
10967 {
10968 /*
10969 * the ABSENT ON NULL and WITH UNIQUE args are printed
10970 * separately, so ignore them here
10971 */
10972 if (i > 2)
10973 break;
10974
10975 appendStringInfoString(buf, " : ");
10976 }
10977 else
10978 appendStringInfoString(buf, ", ");
10979 }
10980 if (use_variadic && i == nargs)
10981 appendStringInfoString(buf, "VARIADIC ");
10982 get_rule_expr(arg, context, true);
10983 }
10984 }
10985
10986 if (aggref->aggorder != NIL)
10987 {
10988 appendStringInfoString(buf, " ORDER BY ");
10989 get_rule_orderby(aggref->aggorder, aggref->args, false, context);
10990 }
10991 }
10992
10993 if (options)
10994 appendStringInfoString(buf, options);
10995
10996 if (aggref->aggfilter != NULL)
10997 {
10998 appendStringInfoString(buf, ") FILTER (WHERE ");
10999 get_rule_expr((Node *) aggref->aggfilter, context, false);
11000 }
11001
11002 appendStringInfoChar(buf, ')');
11003 }
11004
11005 /*
11006 * This is a helper function for get_agg_expr(). It's used when we deparse
11007 * a combining Aggref; resolve_special_varno locates the corresponding partial
11008 * Aggref and then calls this.
11009 */
11010 static void
11011 get_agg_combine_expr(Node *node, deparse_context *context, void *callback_arg)
11012 {
11013 Aggref *aggref;
11014 Aggref *original_aggref = callback_arg;
11015
11016 if (!IsA(node, Aggref))
11017 elog(ERROR, "combining Aggref does not point to an Aggref");
11018
11019 aggref = (Aggref *) node;
11020 get_agg_expr(aggref, context, original_aggref);
11021 }
11022
11023 /*
11024 * get_windowfunc_expr - Parse back a WindowFunc node
11025 */
11026 static void
11027 get_windowfunc_expr(WindowFunc *wfunc, deparse_context *context)
11028 {
11029 get_windowfunc_expr_helper(wfunc, context, NULL, NULL, false);
11030 }
11031
11032
11033 /*
11034 * get_windowfunc_expr_helper - subroutine for get_windowfunc_expr and
11035 * get_json_agg_constructor
11036 */
11037 static void
11038 get_windowfunc_expr_helper(WindowFunc *wfunc, deparse_context *context,
11039 const char *funcname, const char *options,
11040 bool is_json_objectagg)
11041 {
11042 StringInfo buf = context->buf;
11043 Oid argtypes[FUNC_MAX_ARGS];
11044 int nargs;
11045 List *argnames;
11046 ListCell *l;
11047
11048 if (list_length(wfunc->args) > FUNC_MAX_ARGS)
11049 ereport(ERROR,
11050 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
11051 errmsg("too many arguments")));
11052 nargs = 0;
11053 argnames = NIL;
11054 foreach(l, wfunc->args)
11055 {
11056 Node *arg = (Node *) lfirst(l);
11057
11058 if (IsA(arg, NamedArgExpr))
11059 argnames = lappend(argnames, ((NamedArgExpr *) arg)->name);
11060 argtypes[nargs] = exprType(arg);
11061 nargs++;
11062 }
11063
11064 if (!funcname)
11065 funcname = generate_function_name(wfunc->winfnoid, nargs, argnames,
11066 argtypes, false, NULL,
11067 context->inGroupBy);
11068
11069 appendStringInfo(buf, "%s(", funcname);
11070
11071 /* winstar can be set only in zero-argument aggregates */
11072 if (wfunc->winstar)
11073 appendStringInfoChar(buf, '*');
11074 else
11075 {
11076 if (is_json_objectagg)
11077 {
11078 get_rule_expr((Node *) linitial(wfunc->args), context, false);
11079 appendStringInfoString(buf, " : ");
11080 get_rule_expr((Node *) lsecond(wfunc->args), context, false);
11081 }
11082 else
11083 get_rule_expr((Node *) wfunc->args, context, true);
11084 }
11085
11086 if (options)
11087 appendStringInfoString(buf, options);
11088
11089 if (wfunc->aggfilter != NULL)
11090 {
11091 appendStringInfoString(buf, ") FILTER (WHERE ");
11092 get_rule_expr((Node *) wfunc->aggfilter, context, false);
11093 }
11094
11095 appendStringInfoString(buf, ") OVER ");
11096
11097 if (context->windowClause)
11098 {
11099 /* Query-decompilation case: search the windowClause list */
11100 foreach(l, context->windowClause)
11101 {
11102 WindowClause *wc = (WindowClause *) lfirst(l);
11103
11104 if (wc->winref == wfunc->winref)
11105 {
11106 if (wc->name)
11107 appendStringInfoString(buf, quote_identifier(wc->name));
11108 else
11109 get_rule_windowspec(wc, context->targetList, context);
11110 break;
11111 }
11112 }
11113 if (l == NULL)
11114 elog(ERROR, "could not find window clause for winref %u",
11115 wfunc->winref);
11116 }
11117 else
11118 {
11119 /*
11120 * In EXPLAIN, search the namespace stack for a matching WindowAgg
11121 * node (probably it's always the first entry), and print winname.
11122 */
11123 foreach(l, context->namespaces)
11124 {
11125 deparse_namespace *dpns = (deparse_namespace *) lfirst(l);
11126
11127 if (dpns->plan && IsA(dpns->plan, WindowAgg))
11128 {
11129 WindowAgg *wagg = (WindowAgg *) dpns->plan;
11130
11131 if (wagg->winref == wfunc->winref)
11132 {
11133 appendStringInfoString(buf, quote_identifier(wagg->winname));
11134 break;
11135 }
11136 }
11137 }
11138 if (l == NULL)
11139 elog(ERROR, "could not find window clause for winref %u",
11140 wfunc->winref);
11141 }
11142 }
11143
11144 /*
11145 * get_func_sql_syntax - Parse back a SQL-syntax function call
11146 *
11147 * Returns true if we successfully deparsed, false if we did not
11148 * recognize the function.
11149 */
11150 static bool
11151 get_func_sql_syntax(FuncExpr *expr, deparse_context *context)
11152 {
11153 StringInfo buf = context->buf;
11154 Oid funcoid = expr->funcid;
11155
11156 switch (funcoid)
11157 {
11158 case F_TIMEZONE_INTERVAL_TIMESTAMP:
11159 case F_TIMEZONE_INTERVAL_TIMESTAMPTZ:
11160 case F_TIMEZONE_INTERVAL_TIMETZ:
11161 case F_TIMEZONE_TEXT_TIMESTAMP:
11162 case F_TIMEZONE_TEXT_TIMESTAMPTZ:
11163 case F_TIMEZONE_TEXT_TIMETZ:
11164 /* AT TIME ZONE ... note reversed argument order */
11165 appendStringInfoChar(buf, '(');
11166 get_rule_expr_paren((Node *) lsecond(expr->args), context, false,
11167 (Node *) expr);
11168 appendStringInfoString(buf, " AT TIME ZONE ");
11169 get_rule_expr_paren((Node *) linitial(expr->args), context, false,
11170 (Node *) expr);
11171 appendStringInfoChar(buf, ')');
11172 return true;
11173
11174 case F_TIMEZONE_TIMESTAMP:
11175 case F_TIMEZONE_TIMESTAMPTZ:
11176 case F_TIMEZONE_TIMETZ:
11177 /* AT LOCAL */
11178 appendStringInfoChar(buf, '(');
11179 get_rule_expr_paren((Node *) linitial(expr->args), context, false,
11180 (Node *) expr);
11181 appendStringInfoString(buf, " AT LOCAL)");
11182 return true;
11183
11184 case F_OVERLAPS_TIMESTAMPTZ_INTERVAL_TIMESTAMPTZ_INTERVAL:
11185 case F_OVERLAPS_TIMESTAMPTZ_INTERVAL_TIMESTAMPTZ_TIMESTAMPTZ:
11186 case F_OVERLAPS_TIMESTAMPTZ_TIMESTAMPTZ_TIMESTAMPTZ_INTERVAL:
11187 case F_OVERLAPS_TIMESTAMPTZ_TIMESTAMPTZ_TIMESTAMPTZ_TIMESTAMPTZ:
11188 case F_OVERLAPS_TIMESTAMP_INTERVAL_TIMESTAMP_INTERVAL:
11189 case F_OVERLAPS_TIMESTAMP_INTERVAL_TIMESTAMP_TIMESTAMP:
11190 case F_OVERLAPS_TIMESTAMP_TIMESTAMP_TIMESTAMP_INTERVAL:
11191 case F_OVERLAPS_TIMESTAMP_TIMESTAMP_TIMESTAMP_TIMESTAMP:
11192 case F_OVERLAPS_TIMETZ_TIMETZ_TIMETZ_TIMETZ:
11193 case F_OVERLAPS_TIME_INTERVAL_TIME_INTERVAL:
11194 case F_OVERLAPS_TIME_INTERVAL_TIME_TIME:
11195 case F_OVERLAPS_TIME_TIME_TIME_INTERVAL:
11196 case F_OVERLAPS_TIME_TIME_TIME_TIME:
11197 /* (x1, x2) OVERLAPS (y1, y2) */
11198 appendStringInfoString(buf, "((");
11199 get_rule_expr((Node *) linitial(expr->args), context, false);
11200 appendStringInfoString(buf, ", ");
11201 get_rule_expr((Node *) lsecond(expr->args), context, false);
11202 appendStringInfoString(buf, ") OVERLAPS (");
11203 get_rule_expr((Node *) lthird(expr->args), context, false);
11204 appendStringInfoString(buf, ", ");
11205 get_rule_expr((Node *) lfourth(expr->args), context, false);
11206 appendStringInfoString(buf, "))");
11207 return true;
11208
11209 case F_EXTRACT_TEXT_DATE:
11210 case F_EXTRACT_TEXT_TIME:
11211 case F_EXTRACT_TEXT_TIMETZ:
11212 case F_EXTRACT_TEXT_TIMESTAMP:
11213 case F_EXTRACT_TEXT_TIMESTAMPTZ:
11214 case F_EXTRACT_TEXT_INTERVAL:
11215 /* EXTRACT (x FROM y) */
11216 appendStringInfoString(buf, "EXTRACT(");
11217 {
11218 Const *con = (Const *) linitial(expr->args);
11219
11220 Assert(IsA(con, Const) &&
11221 con->consttype == TEXTOID &&
11222 !con->constisnull);
11223 appendStringInfoString(buf, quote_identifier(TextDatumGetCString(con->constvalue)));
11224 }
11225 appendStringInfoString(buf, " FROM ");
11226 get_rule_expr((Node *) lsecond(expr->args), context, false);
11227 appendStringInfoChar(buf, ')');
11228 return true;
11229
11230 case F_IS_NORMALIZED:
11231 /* IS xxx NORMALIZED */
11232 appendStringInfoChar(buf, '(');
11233 get_rule_expr_paren((Node *) linitial(expr->args), context, false,
11234 (Node *) expr);
11235 appendStringInfoString(buf, " IS");
11236 if (list_length(expr->args) == 2)
11237 {
11238 Const *con = (Const *) lsecond(expr->args);
11239
11240 Assert(IsA(con, Const) &&
11241 con->consttype == TEXTOID &&
11242 !con->constisnull);
11243 /* NB: safe because no allowed words need quoted/escaped */
11244 appendStringInfo(buf, " %s",
11245 TextDatumGetCString(con->constvalue));
11246 }
11247 appendStringInfoString(buf, " NORMALIZED)");
11248 return true;
11249
11250 case F_PG_COLLATION_FOR:
11251 /* COLLATION FOR */
11252 appendStringInfoString(buf, "COLLATION FOR (");
11253 get_rule_expr((Node *) linitial(expr->args), context, false);
11254 appendStringInfoChar(buf, ')');
11255 return true;
11256
11257 case F_NORMALIZE:
11258 /* NORMALIZE() */
11259 appendStringInfoString(buf, "NORMALIZE(");
11260 get_rule_expr((Node *) linitial(expr->args), context, false);
11261 if (list_length(expr->args) == 2)
11262 {
11263 Const *con = (Const *) lsecond(expr->args);
11264
11265 Assert(IsA(con, Const) &&
11266 con->consttype == TEXTOID &&
11267 !con->constisnull);
11268 appendStringInfo(buf, ", %s",
11269 TextDatumGetCString(con->constvalue));
11270 }
11271 appendStringInfoChar(buf, ')');
11272 return true;
11273
11274 case F_OVERLAY_BIT_BIT_INT4:
11275 case F_OVERLAY_BIT_BIT_INT4_INT4:
11276 case F_OVERLAY_BYTEA_BYTEA_INT4:
11277 case F_OVERLAY_BYTEA_BYTEA_INT4_INT4:
11278 case F_OVERLAY_TEXT_TEXT_INT4:
11279 case F_OVERLAY_TEXT_TEXT_INT4_INT4:
11280 /* OVERLAY() */
11281 appendStringInfoString(buf, "OVERLAY(");
11282 get_rule_expr((Node *) linitial(expr->args), context, false);
11283 appendStringInfoString(buf, " PLACING ");
11284 get_rule_expr((Node *) lsecond(expr->args), context, false);
11285 appendStringInfoString(buf, " FROM ");
11286 get_rule_expr((Node *) lthird(expr->args), context, false);
11287 if (list_length(expr->args) == 4)
11288 {
11289 appendStringInfoString(buf, " FOR ");
11290 get_rule_expr((Node *) lfourth(expr->args), context, false);
11291 }
11292 appendStringInfoChar(buf, ')');
11293 return true;
11294
11295 case F_POSITION_BIT_BIT:
11296 case F_POSITION_BYTEA_BYTEA:
11297 case F_POSITION_TEXT_TEXT:
11298 /* POSITION() ... extra parens since args are b_expr not a_expr */
11299 appendStringInfoString(buf, "POSITION((");
11300 get_rule_expr((Node *) lsecond(expr->args), context, false);
11301 appendStringInfoString(buf, ") IN (");
11302 get_rule_expr((Node *) linitial(expr->args), context, false);
11303 appendStringInfoString(buf, "))");
11304 return true;
11305
11306 case F_SUBSTRING_BIT_INT4:
11307 case F_SUBSTRING_BIT_INT4_INT4:
11308 case F_SUBSTRING_BYTEA_INT4:
11309 case F_SUBSTRING_BYTEA_INT4_INT4:
11310 case F_SUBSTRING_TEXT_INT4:
11311 case F_SUBSTRING_TEXT_INT4_INT4:
11312 /* SUBSTRING FROM/FOR (i.e., integer-position variants) */
11313 appendStringInfoString(buf, "SUBSTRING(");
11314 get_rule_expr((Node *) linitial(expr->args), context, false);
11315 appendStringInfoString(buf, " FROM ");
11316 get_rule_expr((Node *) lsecond(expr->args), context, false);
11317 if (list_length(expr->args) == 3)
11318 {
11319 appendStringInfoString(buf, " FOR ");
11320 get_rule_expr((Node *) lthird(expr->args), context, false);
11321 }
11322 appendStringInfoChar(buf, ')');
11323 return true;
11324
11325 case F_SUBSTRING_TEXT_TEXT_TEXT:
11326 /* SUBSTRING SIMILAR/ESCAPE */
11327 appendStringInfoString(buf, "SUBSTRING(");
11328 get_rule_expr((Node *) linitial(expr->args), context, false);
11329 appendStringInfoString(buf, " SIMILAR ");
11330 get_rule_expr((Node *) lsecond(expr->args), context, false);
11331 appendStringInfoString(buf, " ESCAPE ");
11332 get_rule_expr((Node *) lthird(expr->args), context, false);
11333 appendStringInfoChar(buf, ')');
11334 return true;
11335
11336 case F_BTRIM_BYTEA_BYTEA:
11337 case F_BTRIM_TEXT:
11338 case F_BTRIM_TEXT_TEXT:
11339 /* TRIM() */
11340 appendStringInfoString(buf, "TRIM(BOTH");
11341 if (list_length(expr->args) == 2)
11342 {
11343 appendStringInfoChar(buf, ' ');
11344 get_rule_expr((Node *) lsecond(expr->args), context, false);
11345 }
11346 appendStringInfoString(buf, " FROM ");
11347 get_rule_expr((Node *) linitial(expr->args), context, false);
11348 appendStringInfoChar(buf, ')');
11349 return true;
11350
11351 case F_LTRIM_BYTEA_BYTEA:
11352 case F_LTRIM_TEXT:
11353 case F_LTRIM_TEXT_TEXT:
11354 /* TRIM() */
11355 appendStringInfoString(buf, "TRIM(LEADING");
11356 if (list_length(expr->args) == 2)
11357 {
11358 appendStringInfoChar(buf, ' ');
11359 get_rule_expr((Node *) lsecond(expr->args), context, false);
11360 }
11361 appendStringInfoString(buf, " FROM ");
11362 get_rule_expr((Node *) linitial(expr->args), context, false);
11363 appendStringInfoChar(buf, ')');
11364 return true;
11365
11366 case F_RTRIM_BYTEA_BYTEA:
11367 case F_RTRIM_TEXT:
11368 case F_RTRIM_TEXT_TEXT:
11369 /* TRIM() */
11370 appendStringInfoString(buf, "TRIM(TRAILING");
11371 if (list_length(expr->args) == 2)
11372 {
11373 appendStringInfoChar(buf, ' ');
11374 get_rule_expr((Node *) lsecond(expr->args), context, false);
11375 }
11376 appendStringInfoString(buf, " FROM ");
11377 get_rule_expr((Node *) linitial(expr->args), context, false);
11378 appendStringInfoChar(buf, ')');
11379 return true;
11380
11381 case F_SYSTEM_USER:
11382 appendStringInfoString(buf, "SYSTEM_USER");
11383 return true;
11384
11385 case F_XMLEXISTS:
11386 /* XMLEXISTS ... extra parens because args are c_expr */
11387 appendStringInfoString(buf, "XMLEXISTS((");
11388 get_rule_expr((Node *) linitial(expr->args), context, false);
11389 appendStringInfoString(buf, ") PASSING (");
11390 get_rule_expr((Node *) lsecond(expr->args), context, false);
11391 appendStringInfoString(buf, "))");
11392 return true;
11393 }
11394 return false;
11395 }
11396
11397 /* ----------
11398 * get_coercion_expr
11399 *
11400 * Make a string representation of a value coerced to a specific type
11401 * ----------
11402 */
11403 static void
11404 get_coercion_expr(Node *arg, deparse_context *context,
11405 Oid resulttype, int32 resulttypmod,
11406 Node *parentNode)
11407 {
11408 StringInfo buf = context->buf;
11409
11410 /*
11411 * Since parse_coerce.c doesn't immediately collapse application of
11412 * length-coercion functions to constants, what we'll typically see in
11413 * such cases is a Const with typmod -1 and a length-coercion function
11414 * right above it. Avoid generating redundant output. However, beware of
11415 * suppressing casts when the user actually wrote something like
11416 * 'foo'::text::char(3).
11417 *
11418 * Note: it might seem that we are missing the possibility of needing to
11419 * print a COLLATE clause for such a Const. However, a Const could only
11420 * have nondefault collation in a post-constant-folding tree, in which the
11421 * length coercion would have been folded too. See also the special
11422 * handling of CollateExpr in coerce_to_target_type(): any collation
11423 * marking will be above the coercion node, not below it.
11424 */
11425 if (arg && IsA(arg, Const) &&
11426 ((Const *) arg)->consttype == resulttype &&
11427 ((Const *) arg)->consttypmod == -1)
11428 {
11429 /* Show the constant without normal ::typename decoration */
11430 get_const_expr((Const *) arg, context, -1);
11431 }
11432 else
11433 {
11434 if (!PRETTY_PAREN(context))
11435 appendStringInfoChar(buf, '(');
11436 get_rule_expr_paren(arg, context, false, parentNode);
11437 if (!PRETTY_PAREN(context))
11438 appendStringInfoChar(buf, ')');
11439 }
11440
11441 /*
11442 * Never emit resulttype(arg) functional notation. A pg_proc entry could
11443 * take precedence, and a resulttype in pg_temp would require schema
11444 * qualification that format_type_with_typemod() would usually omit. We've
11445 * standardized on arg::resulttype, but CAST(arg AS resulttype) notation
11446 * would work fine.
11447 */
11448 appendStringInfo(buf, "::%s",
11449 format_type_with_typemod(resulttype, resulttypmod));
11450 }
11451
11452 /* ----------
11453 * get_const_expr
11454 *
11455 * Make a string representation of a Const
11456 *
11457 * showtype can be -1 to never show "::typename" decoration, or +1 to always
11458 * show it, or 0 to show it only if the constant wouldn't be assumed to be
11459 * the right type by default.
11460 *
11461 * If the Const's collation isn't default for its type, show that too.
11462 * We mustn't do this when showtype is -1 (since that means the caller will
11463 * print "::typename", and we can't put a COLLATE clause in between). It's
11464 * caller's responsibility that collation isn't missed in such cases.
11465 * ----------
11466 */
11467 static void
11468 get_const_expr(Const *constval, deparse_context *context, int showtype)
11469 {
11470 StringInfo buf = context->buf;
11471 Oid typoutput;
11472 bool typIsVarlena;
11473 char *extval;
11474 bool needlabel = false;
11475
11476 if (constval->constisnull)
11477 {
11478 /*
11479 * Always label the type of a NULL constant to prevent misdecisions
11480 * about type when reparsing.
11481 */
11482 appendStringInfoString(buf, "NULL");
11483 if (showtype >= 0)
11484 {
11485 appendStringInfo(buf, "::%s",
11486 format_type_with_typemod(constval->consttype,
11487 constval->consttypmod));
11488 get_const_collation(constval, context);
11489 }
11490 return;
11491 }
11492
11493 getTypeOutputInfo(constval->consttype,
11494 &typoutput, &typIsVarlena);
11495
11496 extval = OidOutputFunctionCall(typoutput, constval->constvalue);
11497
11498 switch (constval->consttype)
11499 {
11500 case INT4OID:
11501
11502 /*
11503 * INT4 can be printed without any decoration, unless it is
11504 * negative; in that case print it as '-nnn'::integer to ensure
11505 * that the output will re-parse as a constant, not as a constant
11506 * plus operator. In most cases we could get away with printing
11507 * (-nnn) instead, because of the way that gram.y handles negative
11508 * literals; but that doesn't work for INT_MIN, and it doesn't
11509 * seem that much prettier anyway.
11510 */
11511 if (extval[0] != '-')
11512 appendStringInfoString(buf, extval);
11513 else
11514 {
11515 appendStringInfo(buf, "'%s'", extval);
11516 needlabel = true; /* we must attach a cast */
11517 }
11518 break;
11519
11520 case NUMERICOID:
11521
11522 /*
11523 * NUMERIC can be printed without quotes if it looks like a float
11524 * constant (not an integer, and not Infinity or NaN) and doesn't
11525 * have a leading sign (for the same reason as for INT4).
11526 */
11527 if (isdigit((unsigned char) extval[0]) &&
11528 strcspn(extval, "eE.") != strlen(extval))
11529 {
11530 appendStringInfoString(buf, extval);
11531 }
11532 else
11533 {
11534 appendStringInfo(buf, "'%s'", extval);
11535 needlabel = true; /* we must attach a cast */
11536 }
11537 break;
11538
11539 case BOOLOID:
11540 if (strcmp(extval, "t") == 0)
11541 appendStringInfoString(buf, "true");
11542 else
11543 appendStringInfoString(buf, "false");
11544 break;
11545
11546 default:
11547 simple_quote_literal(buf, extval);
11548 break;
11549 }
11550
11551 pfree(extval);
11552
11553 if (showtype < 0)
11554 return;
11555
11556 /*
11557 * For showtype == 0, append ::typename unless the constant will be
11558 * implicitly typed as the right type when it is read in.
11559 *
11560 * XXX this code has to be kept in sync with the behavior of the parser,
11561 * especially make_const.
11562 */
11563 switch (constval->consttype)
11564 {
11565 case BOOLOID:
11566 case UNKNOWNOID:
11567 /* These types can be left unlabeled */
11568 needlabel = false;
11569 break;
11570 case INT4OID:
11571 /* We determined above whether a label is needed */
11572 break;
11573 case NUMERICOID:
11574
11575 /*
11576 * Float-looking constants will be typed as numeric, which we
11577 * checked above; but if there's a nondefault typmod we need to
11578 * show it.
11579 */
11580 needlabel |= (constval->consttypmod >= 0);
11581 break;
11582 default:
11583 needlabel = true;
11584 break;
11585 }
11586 if (needlabel || showtype > 0)
11587 appendStringInfo(buf, "::%s",
11588 format_type_with_typemod(constval->consttype,
11589 constval->consttypmod));
11590
11591 get_const_collation(constval, context);
11592 }
11593
11594 /*
11595 * helper for get_const_expr: append COLLATE if needed
11596 */
11597 static void
11598 get_const_collation(Const *constval, deparse_context *context)
11599 {
11600 StringInfo buf = context->buf;
11601
11602 if (OidIsValid(constval->constcollid))
11603 {
11604 Oid typcollation = get_typcollation(constval->consttype);
11605
11606 if (constval->constcollid != typcollation)
11607 {
11608 appendStringInfo(buf, " COLLATE %s",
11609 generate_collation_name(constval->constcollid));
11610 }
11611 }
11612 }
11613
11614 /*
11615 * get_json_path_spec - Parse back a JSON path specification
11616 */
11617 static void
11618 get_json_path_spec(Node *path_spec, deparse_context *context, bool showimplicit)
11619 {
11620 if (IsA(path_spec, Const))
11621 get_const_expr((Const *) path_spec, context, -1);
11622 else
11623 get_rule_expr(path_spec, context, showimplicit);
11624 }
11625
11626 /*
11627 * get_json_format - Parse back a JsonFormat node
11628 */
11629 static void
11630 get_json_format(JsonFormat *format, StringInfo buf)
11631 {
11632 if (format->format_type == JS_FORMAT_DEFAULT)
11633 return;
11634
11635 appendStringInfoString(buf,
11636 format->format_type == JS_FORMAT_JSONB ?
11637 " FORMAT JSONB" : " FORMAT JSON");
11638
11639 if (format->encoding != JS_ENC_DEFAULT)
11640 {
11641 const char *encoding;
11642
11643 encoding =
11644 format->encoding == JS_ENC_UTF16 ? "UTF16" :
11645 format->encoding == JS_ENC_UTF32 ? "UTF32" : "UTF8";
11646
11647 appendStringInfo(buf, " ENCODING %s", encoding);
11648 }
11649 }
11650
11651 /*
11652 * get_json_returning - Parse back a JsonReturning structure
11653 */
11654 static void
11655 get_json_returning(JsonReturning *returning, StringInfo buf,
11656 bool json_format_by_default)
11657 {
11658 if (!OidIsValid(returning->typid))
11659 return;
11660
11661 appendStringInfo(buf, " RETURNING %s",
11662 format_type_with_typemod(returning->typid,
11663 returning->typmod));
11664
11665 if (!json_format_by_default ||
11666 returning->format->format_type !=
11667 (returning->typid == JSONBOID ? JS_FORMAT_JSONB : JS_FORMAT_JSON))
11668 get_json_format(returning->format, buf);
11669 }
11670
11671 /*
11672 * get_json_constructor - Parse back a JsonConstructorExpr node
11673 */
11674 static void
11675 get_json_constructor(JsonConstructorExpr *ctor, deparse_context *context,
11676 bool showimplicit)
11677 {
11678 StringInfo buf = context->buf;
11679 const char *funcname;
11680 bool is_json_object;
11681 int curridx;
11682 ListCell *lc;
11683
11684 if (ctor->type == JSCTOR_JSON_OBJECTAGG)
11685 {
11686 get_json_agg_constructor(ctor, context, "JSON_OBJECTAGG", true);
11687 return;
11688 }
11689 else if (ctor->type == JSCTOR_JSON_ARRAYAGG)
11690 {
11691 get_json_agg_constructor(ctor, context, "JSON_ARRAYAGG", false);
11692 return;
11693 }
11694
11695 switch (ctor->type)
11696 {
11697 case JSCTOR_JSON_OBJECT:
11698 funcname = "JSON_OBJECT";
11699 break;
11700 case JSCTOR_JSON_ARRAY:
11701 funcname = "JSON_ARRAY";
11702 break;
11703 case JSCTOR_JSON_PARSE:
11704 funcname = "JSON";
11705 break;
11706 case JSCTOR_JSON_SCALAR:
11707 funcname = "JSON_SCALAR";
11708 break;
11709 case JSCTOR_JSON_SERIALIZE:
11710 funcname = "JSON_SERIALIZE";
11711 break;
11712 default:
11713 elog(ERROR, "invalid JsonConstructorType %d", ctor->type);
11714 }
11715
11716 appendStringInfo(buf, "%s(", funcname);
11717
11718 is_json_object = ctor->type == JSCTOR_JSON_OBJECT;
11719 foreach(lc, ctor->args)
11720 {
11721 curridx = foreach_current_index(lc);
11722 if (curridx > 0)
11723 {
11724 const char *sep;
11725
11726 sep = (is_json_object && (curridx % 2) != 0) ? " : " : ", ";
11727 appendStringInfoString(buf, sep);
11728 }
11729
11730 get_rule_expr((Node *) lfirst(lc), context, true);
11731 }
11732
11733 get_json_constructor_options(ctor, buf);
11734 appendStringInfoChar(buf, ')');
11735 }
11736
11737 /*
11738 * Append options, if any, to the JSON constructor being deparsed
11739 */
11740 static void
11741 get_json_constructor_options(JsonConstructorExpr *ctor, StringInfo buf)
11742 {
11743 if (ctor->absent_on_null)
11744 {
11745 if (ctor->type == JSCTOR_JSON_OBJECT ||
11746 ctor->type == JSCTOR_JSON_OBJECTAGG)
11747 appendStringInfoString(buf, " ABSENT ON NULL");
11748 }
11749 else
11750 {
11751 if (ctor->type == JSCTOR_JSON_ARRAY ||
11752 ctor->type == JSCTOR_JSON_ARRAYAGG)
11753 appendStringInfoString(buf, " NULL ON NULL");
11754 }
11755
11756 if (ctor->unique)
11757 appendStringInfoString(buf, " WITH UNIQUE KEYS");
11758
11759 /*
11760 * Append RETURNING clause if needed; JSON() and JSON_SCALAR() don't
11761 * support one.
11762 */
11763 if (ctor->type != JSCTOR_JSON_PARSE && ctor->type != JSCTOR_JSON_SCALAR)
11764 get_json_returning(ctor->returning, buf, true);
11765 }
11766
11767 /*
11768 * get_json_agg_constructor - Parse back an aggregate JsonConstructorExpr node
11769 */
11770 static void
11771 get_json_agg_constructor(JsonConstructorExpr *ctor, deparse_context *context,
11772 const char *funcname, bool is_json_objectagg)
11773 {
11774 StringInfoData options;
11775
11776 initStringInfo(&options);
11777 get_json_constructor_options(ctor, &options);
11778
11779 if (IsA(ctor->func, Aggref))
11780 get_agg_expr_helper((Aggref *) ctor->func, context,
11781 (Aggref *) ctor->func,
11782 funcname, options.data, is_json_objectagg);
11783 else if (IsA(ctor->func, WindowFunc))
11784 get_windowfunc_expr_helper((WindowFunc *) ctor->func, context,
11785 funcname, options.data,
11786 is_json_objectagg);
11787 else if (IsA(ctor->func, Var))
11788 {
11789 /*
11790 * If the aggregate is computed by a lower plan node, setrefs.c will
11791 * have replaced the Aggref or WindowFunc with a Var referencing that
11792 * node's output. Chase the Var back to it so we can still print the
11793 * original JSON aggregate syntax. This only happens in EXPLAIN.
11794 */
11795 resolve_special_varno((Node *) ctor->func, context,
11796 get_json_agg_constructor_expr, ctor);
11797 }
11798 else
11799 elog(ERROR, "invalid JsonConstructorExpr underlying node type: %d",
11800 nodeTag(ctor->func));
11801 }
11802
11803 /*
11804 * Deparse a JsonConstructorExpr whose aggregate is computed by a lower plan
11805 * node; resolve_special_varno has located the underlying Aggref/WindowFunc.
11806 */
11807 static void
11808 get_json_agg_constructor_expr(Node *node, deparse_context *context,
11809 void *callback_arg)
11810 {
11811 JsonConstructorExpr ctor;
11812
11813 if (!IsA(node, Aggref) && !IsA(node, WindowFunc))
11814 elog(ERROR, "JSON aggregate constructor does not point to an Aggref or WindowFunc");
11815
11816 /* Flat copy suffices; we only replace func. */
11817 ctor = *(JsonConstructorExpr *) callback_arg;
11818 ctor.func = (Expr *) node;
11819 get_json_constructor(&ctor, context, false);
11820 }
11821
11822 /*
11823 * simple_quote_literal - Format a string as a SQL literal, append to buf
11824 */
11825 static void
11826 simple_quote_literal(StringInfo buf, const char *val)
11827 {
11828 const char *valptr;
11829
11830 /*
11831 * We form the string literal according to the prevailing setting of
11832 * standard_conforming_strings; we never use E''. User is responsible for
11833 * making sure result is used correctly.
11834 */
11835 appendStringInfoChar(buf, '\'');
11836 for (valptr = val; *valptr; valptr++)
11837 {
11838 char ch = *valptr;
11839
11840 if (SQL_STR_DOUBLE(ch, !standard_conforming_strings))
11841 appendStringInfoChar(buf, ch);
11842 appendStringInfoChar(buf, ch);
11843 }
11844 appendStringInfoChar(buf, '\'');
11845 }
11846
11847
11848 /* ----------
11849 * get_sublink_expr - Parse back a sublink
11850 * ----------
11851 */
11852 static void
11853 get_sublink_expr(SubLink *sublink, deparse_context *context)
11854 {
11855 StringInfo buf = context->buf;
11856 Query *query = (Query *) (sublink->subselect);
11857 char *opname = NULL;
11858 bool need_paren;
11859
11860 if (sublink->subLinkType == ARRAY_SUBLINK)
11861 appendStringInfoString(buf, "ARRAY(");
11862 else
11863 appendStringInfoChar(buf, '(');
11864
11865 /*
11866 * Note that we print the name of only the first operator, when there are
11867 * multiple combining operators. This is an approximation that could go
11868 * wrong in various scenarios (operators in different schemas, renamed
11869 * operators, etc) but there is not a whole lot we can do about it, since
11870 * the syntax allows only one operator to be shown.
11871 */
11872 if (sublink->testexpr)
11873 {
11874 if (IsA(sublink->testexpr, OpExpr))
11875 {
11876 /* single combining operator */
11877 OpExpr *opexpr = (OpExpr *) sublink->testexpr;
11878
11879 get_rule_expr(linitial(opexpr->args), context, true);
11880 opname = generate_operator_name(opexpr->opno,
11881 exprType(linitial(opexpr->args)),
11882 exprType(lsecond(opexpr->args)));
11883 }
11884 else if (IsA(sublink->testexpr, BoolExpr))
11885 {
11886 /* multiple combining operators, = or <> cases */
11887 char *sep;
11888 ListCell *l;
11889
11890 appendStringInfoChar(buf, '(');
11891 sep = "";
11892 foreach(l, ((BoolExpr *) sublink->testexpr)->args)
11893 {
11894 OpExpr *opexpr = lfirst_node(OpExpr, l);
11895
11896 appendStringInfoString(buf, sep);
11897 get_rule_expr(linitial(opexpr->args), context, true);
11898 if (!opname)
11899 opname = generate_operator_name(opexpr->opno,
11900 exprType(linitial(opexpr->args)),
11901 exprType(lsecond(opexpr->args)));
11902 sep = ", ";
11903 }
11904 appendStringInfoChar(buf, ')');
11905 }
11906 else if (IsA(sublink->testexpr, RowCompareExpr))
11907 {
11908 /* multiple combining operators, < <= > >= cases */
11909 RowCompareExpr *rcexpr = (RowCompareExpr *) sublink->testexpr;
11910
11911 appendStringInfoChar(buf, '(');
11912 get_rule_expr((Node *) rcexpr->largs, context, true);
11913 opname = generate_operator_name(linitial_oid(rcexpr->opnos),
11914 exprType(linitial(rcexpr->largs)),
11915 exprType(linitial(rcexpr->rargs)));
11916 appendStringInfoChar(buf, ')');
11917 }
11918 else
11919 elog(ERROR, "unrecognized testexpr type: %d",
11920 (int) nodeTag(sublink->testexpr));
11921 }
11922
11923 need_paren = true;
11924
11925 switch (sublink->subLinkType)
11926 {
11927 case EXISTS_SUBLINK:
11928 appendStringInfoString(buf, "EXISTS ");
11929 break;
11930
11931 case ANY_SUBLINK:
11932 if (strcmp(opname, "=") == 0) /* Represent = ANY as IN */
11933 appendStringInfoString(buf, " IN ");
11934 else
11935 appendStringInfo(buf, " %s ANY ", opname);
11936 break;
11937
11938 case ALL_SUBLINK:
11939 appendStringInfo(buf, " %s ALL ", opname);
11940 break;
11941
11942 case ROWCOMPARE_SUBLINK:
11943 appendStringInfo(buf, " %s ", opname);
11944 break;
11945
11946 case EXPR_SUBLINK:
11947 case MULTIEXPR_SUBLINK:
11948 case ARRAY_SUBLINK:
11949 need_paren = false;
11950 break;
11951
11952 case CTE_SUBLINK: /* shouldn't occur in a SubLink */
11953 default:
11954 elog(ERROR, "unrecognized sublink type: %d",
11955 (int) sublink->subLinkType);
11956 break;
11957 }
11958
11959 if (need_paren)
11960 appendStringInfoChar(buf, '(');
11961
11962 get_query_def(query, buf, context->namespaces, NULL, false,
11963 context->prettyFlags, context->wrapColumn,
11964 context->indentLevel);
11965
11966 if (need_paren)
11967 appendStringInfoString(buf, "))");
11968 else
11969 appendStringInfoChar(buf, ')');
11970 }
11971
11972
11973 /* ----------
11974 * get_xmltable - Parse back a XMLTABLE function
11975 * ----------
11976 */
11977 static void
11978 get_xmltable(TableFunc *tf, deparse_context *context, bool showimplicit)
11979 {
11980 StringInfo buf = context->buf;
11981
11982 appendStringInfoString(buf, "XMLTABLE(");
11983
11984 if (tf->ns_uris != NIL)
11985 {
11986 ListCell *lc1,
11987 *lc2;
11988 bool first = true;
11989
11990 appendStringInfoString(buf, "XMLNAMESPACES (");
11991 forboth(lc1, tf->ns_uris, lc2, tf->ns_names)
11992 {
11993 Node *expr = (Node *) lfirst(lc1);
11994 String *ns_node = lfirst_node(String, lc2);
11995
11996 if (!first)
11997 appendStringInfoString(buf, ", ");
11998 else
11999 first = false;
12000
12001 if (ns_node != NULL)
12002 {
12003 get_rule_expr(expr, context, showimplicit);
12004 appendStringInfo(buf, " AS %s",
12005 quote_identifier(strVal(ns_node)));
12006 }
12007 else
12008 {
12009 appendStringInfoString(buf, "DEFAULT ");
12010 get_rule_expr(expr, context, showimplicit);
12011 }
12012 }
12013 appendStringInfoString(buf, "), ");
12014 }
12015
12016 appendStringInfoChar(buf, '(');
12017 get_rule_expr((Node *) tf->rowexpr, context, showimplicit);
12018 appendStringInfoString(buf, ") PASSING (");
12019 get_rule_expr((Node *) tf->docexpr, context, showimplicit);
12020 appendStringInfoChar(buf, ')');
12021
12022 if (tf->colexprs != NIL)
12023 {
12024 ListCell *l1;
12025 ListCell *l2;
12026 ListCell *l3;
12027 ListCell *l4;
12028 ListCell *l5;
12029 int colnum = 0;
12030
12031 appendStringInfoString(buf, " COLUMNS ");
12032 forfive(l1, tf->colnames, l2, tf->coltypes, l3, tf->coltypmods,
12033 l4, tf->colexprs, l5, tf->coldefexprs)
12034 {
12035 char *colname = strVal(lfirst(l1));
12036 Oid typid = lfirst_oid(l2);
12037 int32 typmod = lfirst_int(l3);
12038 Node *colexpr = (Node *) lfirst(l4);
12039 Node *coldefexpr = (Node *) lfirst(l5);
12040 bool ordinality = (tf->ordinalitycol == colnum);
12041 bool notnull = bms_is_member(colnum, tf->notnulls);
12042
12043 if (colnum > 0)
12044 appendStringInfoString(buf, ", ");
12045 colnum++;
12046
12047 appendStringInfo(buf, "%s %s", quote_identifier(colname),
12048 ordinality ? "FOR ORDINALITY" :
12049 format_type_with_typemod(typid, typmod));
12050 if (ordinality)
12051 continue;
12052
12053 if (coldefexpr != NULL)
12054 {
12055 appendStringInfoString(buf, " DEFAULT (");
12056 get_rule_expr((Node *) coldefexpr, context, showimplicit);
12057 appendStringInfoChar(buf, ')');
12058 }
12059 if (colexpr != NULL)
12060 {
12061 appendStringInfoString(buf, " PATH (");
12062 get_rule_expr((Node *) colexpr, context, showimplicit);
12063 appendStringInfoChar(buf, ')');
12064 }
12065 if (notnull)
12066 appendStringInfoString(buf, " NOT NULL");
12067 }
12068 }
12069
12070 appendStringInfoChar(buf, ')');
12071 }
12072
12073 /*
12074 * get_json_table_nested_columns - Parse back nested JSON_TABLE columns
12075 */
12076 static void
12077 get_json_table_nested_columns(TableFunc *tf, JsonTablePlan *plan,
12078 deparse_context *context, bool showimplicit,
12079 bool needcomma)
12080 {
12081 if (IsA(plan, JsonTablePathScan))
12082 {
12083 JsonTablePathScan *scan = castNode(JsonTablePathScan, plan);
12084
12085 if (needcomma)
12086 appendStringInfoChar(context->buf, ',');
12087
12088 appendStringInfoChar(context->buf, ' ');
12089 appendContextKeyword(context, "NESTED PATH ", 0, 0, 0);
12090 get_const_expr(scan->path->value, context, -1);
12091 appendStringInfo(context->buf, " AS %s", quote_identifier(scan->path->name));
12092 get_json_table_columns(tf, scan, context, showimplicit);
12093 }
12094 else if (IsA(plan, JsonTableSiblingJoin))
12095 {
12096 JsonTableSiblingJoin *join = (JsonTableSiblingJoin *) plan;
12097
12098 get_json_table_nested_columns(tf, join->lplan, context, showimplicit,
12099 needcomma);
12100 get_json_table_nested_columns(tf, join->rplan, context, showimplicit,
12101 true);
12102 }
12103 }
12104
12105 /*
12106 * get_json_table_columns - Parse back JSON_TABLE columns
12107 */
12108 static void
12109 get_json_table_columns(TableFunc *tf, JsonTablePathScan *scan,
12110 deparse_context *context,
12111 bool showimplicit)
12112 {
12113 StringInfo buf = context->buf;
12114 ListCell *lc_colname;
12115 ListCell *lc_coltype;
12116 ListCell *lc_coltypmod;
12117 ListCell *lc_colvalexpr;
12118 int colnum = 0;
12119
12120 appendStringInfoChar(buf, ' ');
12121 appendContextKeyword(context, "COLUMNS (", 0, 0, 0);
12122
12123 if (PRETTY_INDENT(context))
12124 context->indentLevel += PRETTYINDENT_VAR;
12125
12126 forfour(lc_colname, tf->colnames,
12127 lc_coltype, tf->coltypes,
12128 lc_coltypmod, tf->coltypmods,
12129 lc_colvalexpr, tf->colvalexprs)
12130 {
12131 char *colname = strVal(lfirst(lc_colname));
12132 JsonExpr *colexpr;
12133 Oid typid;
12134 int32 typmod;
12135 bool ordinality;
12136 JsonBehaviorType default_behavior;
12137
12138 typid = lfirst_oid(lc_coltype);
12139 typmod = lfirst_int(lc_coltypmod);
12140 colexpr = castNode(JsonExpr, lfirst(lc_colvalexpr));
12141
12142 /* Skip columns that don't belong to this scan. */
12143 if (scan->colMin < 0 || colnum < scan->colMin)
12144 {
12145 colnum++;
12146 continue;
12147 }
12148 if (colnum > scan->colMax)
12149 break;
12150
12151 if (colnum > scan->colMin)
12152 appendStringInfoString(buf, ", ");
12153
12154 colnum++;
12155
12156 ordinality = !colexpr;
12157
12158 appendContextKeyword(context, "", 0, 0, 0);
12159
12160 appendStringInfo(buf, "%s %s", quote_identifier(colname),
12161 ordinality ? "FOR ORDINALITY" :
12162 format_type_with_typemod(typid, typmod));
12163 if (ordinality)
12164 continue;
12165
12166 /*
12167 * Set default_behavior to guide get_json_expr_options() on whether to
12168 * emit the ON ERROR / EMPTY clauses.
12169 */
12170 if (colexpr->op == JSON_EXISTS_OP)
12171 {
12172 appendStringInfoString(buf, " EXISTS");
12173 default_behavior = JSON_BEHAVIOR_FALSE;
12174 }
12175 else
12176 {
12177 if (colexpr->op == JSON_QUERY_OP)
12178 {
12179 char typcategory;
12180 bool typispreferred;
12181
12182 get_type_category_preferred(typid, &typcategory, &typispreferred);
12183
12184 if (typcategory == TYPCATEGORY_STRING)
12185 appendStringInfoString(buf,
12186 colexpr->format->format_type == JS_FORMAT_JSONB ?
12187 " FORMAT JSONB" : " FORMAT JSON");
12188 }
12189
12190 default_behavior = JSON_BEHAVIOR_NULL;
12191 }
12192
12193 appendStringInfoString(buf, " PATH ");
12194
12195 get_json_path_spec(colexpr->path_spec, context, showimplicit);
12196
12197 get_json_expr_options(colexpr, context, default_behavior);
12198 }
12199
12200 if (scan->child)
12201 get_json_table_nested_columns(tf, scan->child, context, showimplicit,
12202 scan->colMin >= 0);
12203
12204 if (PRETTY_INDENT(context))
12205 context->indentLevel -= PRETTYINDENT_VAR;
12206
12207 appendContextKeyword(context, ")", 0, 0, 0);
12208 }
12209
12210 /* ----------
12211 * get_json_table - Parse back a JSON_TABLE function
12212 * ----------
12213 */
12214 static void
12215 get_json_table(TableFunc *tf, deparse_context *context, bool showimplicit)
12216 {
12217 StringInfo buf = context->buf;
12218 JsonExpr *jexpr = castNode(JsonExpr, tf->docexpr);
12219 JsonTablePathScan *root = castNode(JsonTablePathScan, tf->plan);
12220
12221 appendStringInfoString(buf, "JSON_TABLE(");
12222
12223 if (PRETTY_INDENT(context))
12224 context->indentLevel += PRETTYINDENT_VAR;
12225
12226 appendContextKeyword(context, "", 0, 0, 0);
12227
12228 get_rule_expr(jexpr->formatted_expr, context, showimplicit);
12229
12230 appendStringInfoString(buf, ", ");
12231
12232 get_const_expr(root->path->value, context, -1);
12233
12234 appendStringInfo(buf, " AS %s", quote_identifier(root->path->name));
12235
12236 if (jexpr->passing_values)
12237 {
12238 ListCell *lc1,
12239 *lc2;
12240 bool needcomma = false;
12241
12242 appendStringInfoChar(buf, ' ');
12243 appendContextKeyword(context, "PASSING ", 0, 0, 0);
12244
12245 if (PRETTY_INDENT(context))
12246 context->indentLevel += PRETTYINDENT_VAR;
12247
12248 forboth(lc1, jexpr->passing_names,
12249 lc2, jexpr->passing_values)
12250 {
12251 if (needcomma)
12252 appendStringInfoString(buf, ", ");
12253 needcomma = true;
12254
12255 appendContextKeyword(context, "", 0, 0, 0);
12256
12257 get_rule_expr((Node *) lfirst(lc2), context, false);
12258 appendStringInfo(buf, " AS %s",
12259 quote_identifier((lfirst_node(String, lc1))->sval)
12260 );
12261 }
12262
12263 if (PRETTY_INDENT(context))
12264 context->indentLevel -= PRETTYINDENT_VAR;
12265 }
12266
12267 get_json_table_columns(tf, castNode(JsonTablePathScan, tf->plan), context,
12268 showimplicit);
12269
12270 if (jexpr->on_error->btype != JSON_BEHAVIOR_EMPTY_ARRAY)
12271 get_json_behavior(jexpr->on_error, context, "ERROR");
12272
12273 if (PRETTY_INDENT(context))
12274 context->indentLevel -= PRETTYINDENT_VAR;
12275
12276 appendContextKeyword(context, ")", 0, 0, 0);
12277 }
12278
12279 /* ----------
12280 * get_tablefunc - Parse back a table function
12281 * ----------
12282 */
12283 static void
12284 get_tablefunc(TableFunc *tf, deparse_context *context, bool showimplicit)
12285 {
12286 /* XMLTABLE and JSON_TABLE are the only existing implementations. */
12287
12288 if (tf->functype == TFT_XMLTABLE)
12289 get_xmltable(tf, context, showimplicit);
12290 else if (tf->functype == TFT_JSON_TABLE)
12291 get_json_table(tf, context, showimplicit);
12292 }
12293
12294 /* ----------
12295 * get_from_clause - Parse back a FROM clause
12296 *
12297 * "prefix" is the keyword that denotes the start of the list of FROM
12298 * elements. It is FROM when used to parse back SELECT and UPDATE, but
12299 * is USING when parsing back DELETE.
12300 * ----------
12301 */
12302 static void
12303 get_from_clause(Query *query, const char *prefix, deparse_context *context)
12304 {
12305 StringInfo buf = context->buf;
12306 bool first = true;
12307 ListCell *l;
12308
12309 /*
12310 * We use the query's jointree as a guide to what to print. However, we
12311 * must ignore auto-added RTEs that are marked not inFromCl. (These can
12312 * only appear at the top level of the jointree, so it's sufficient to
12313 * check here.) This check also ensures we ignore the rule pseudo-RTEs
12314 * for NEW and OLD.
12315 */
12316 foreach(l, query->jointree->fromlist)
12317 {
12318 Node *jtnode = (Node *) lfirst(l);
12319
12320 if (IsA(jtnode, RangeTblRef))
12321 {
12322 int varno = ((RangeTblRef *) jtnode)->rtindex;
12323 RangeTblEntry *rte = rt_fetch(varno, query->rtable);
12324
12325 if (!rte->inFromCl)
12326 continue;
12327 }
12328
12329 if (first)
12330 {
12331 appendContextKeyword(context, prefix,
12332 -PRETTYINDENT_STD, PRETTYINDENT_STD, 2);
12333 first = false;
12334
12335 get_from_clause_item(jtnode, query, context);
12336 }
12337 else
12338 {
12339 StringInfoData itembuf;
12340
12341 appendStringInfoString(buf, ", ");
12342
12343 /*
12344 * Put the new FROM item's text into itembuf so we can decide
12345 * after we've got it whether or not it needs to go on a new line.
12346 */
12347 initStringInfo(&itembuf);
12348 context->buf = &itembuf;
12349
12350 get_from_clause_item(jtnode, query, context);
12351
12352 /* Restore context's output buffer */
12353 context->buf = buf;
12354
12355 /* Consider line-wrapping if enabled */
12356 if (PRETTY_INDENT(context) && context->wrapColumn >= 0)
12357 {
12358 /* Does the new item start with a new line? */
12359 if (itembuf.len > 0 && itembuf.data[0] == '\n')
12360 {
12361 /* If so, we shouldn't add anything */
12362 /* instead, remove any trailing spaces currently in buf */
12363 removeStringInfoSpaces(buf);
12364 }
12365 else
12366 {
12367 char *trailing_nl;
12368
12369 /* Locate the start of the current line in the buffer */
12370 trailing_nl = strrchr(buf->data, '\n');
12371 if (trailing_nl == NULL)
12372 trailing_nl = buf->data;
12373 else
12374 trailing_nl++;
12375
12376 /*
12377 * Add a newline, plus some indentation, if the new item
12378 * would cause an overflow.
12379 */
12380 if (strlen(trailing_nl) + itembuf.len > context->wrapColumn)
12381 appendContextKeyword(context, "", -PRETTYINDENT_STD,
12382 PRETTYINDENT_STD,
12383 PRETTYINDENT_VAR);
12384 }
12385 }
12386
12387 /* Add the new item */
12388 appendBinaryStringInfo(buf, itembuf.data, itembuf.len);
12389
12390 /* clean up */
12391 pfree(itembuf.data);
12392 }
12393 }
12394 }
12395
12396 static void
12397 get_from_clause_item(Node *jtnode, Query *query, deparse_context *context)
12398 {
12399 StringInfo buf = context->buf;
12400 deparse_namespace *dpns = (deparse_namespace *) linitial(context->namespaces);
12401
12402 if (IsA(jtnode, RangeTblRef))
12403 {
12404 int varno = ((RangeTblRef *) jtnode)->rtindex;
12405 RangeTblEntry *rte = rt_fetch(varno, query->rtable);
12406 deparse_columns *colinfo = deparse_columns_fetch(varno, dpns);
12407 RangeTblFunction *rtfunc1 = NULL;
12408
12409 if (rte->lateral)
12410 appendStringInfoString(buf, "LATERAL ");
12411
12412 /* Print the FROM item proper */
12413 switch (rte->rtekind)
12414 {
12415 case RTE_RELATION:
12416 /* Normal relation RTE */
12417 appendStringInfo(buf, "%s%s",
12418 only_marker(rte),
12419 generate_relation_name(rte->relid,
12420 context->namespaces));
12421 break;
12422 case RTE_SUBQUERY:
12423 /* Subquery RTE */
12424 appendStringInfoChar(buf, '(');
12425 get_query_def(rte->subquery, buf, context->namespaces, NULL,
12426 true,
12427 context->prettyFlags, context->wrapColumn,
12428 context->indentLevel);
12429 appendStringInfoChar(buf, ')');
12430 break;
12431 case RTE_FUNCTION:
12432 /* Function RTE */
12433 rtfunc1 = (RangeTblFunction *) linitial(rte->functions);
12434
12435 /*
12436 * Omit ROWS FROM() syntax for just one function, unless it
12437 * has both a coldeflist and WITH ORDINALITY. If it has both,
12438 * we must use ROWS FROM() syntax to avoid ambiguity about
12439 * whether the coldeflist includes the ordinality column.
12440 */
12441 if (list_length(rte->functions) == 1 &&
12442 (rtfunc1->funccolnames == NIL || !rte->funcordinality))
12443 {
12444 get_rule_expr_funccall(rtfunc1->funcexpr, context, true);
12445 /* we'll print the coldeflist below, if it has one */
12446 }
12447 else
12448 {
12449 bool all_unnest;
12450 ListCell *lc;
12451
12452 /*
12453 * If all the function calls in the list are to unnest,
12454 * and none need a coldeflist, then collapse the list back
12455 * down to UNNEST(args). (If we had more than one
12456 * built-in unnest function, this would get more
12457 * difficult.)
12458 *
12459 * XXX This is pretty ugly, since it makes not-terribly-
12460 * future-proof assumptions about what the parser would do
12461 * with the output; but the alternative is to emit our
12462 * nonstandard ROWS FROM() notation for what might have
12463 * been a perfectly spec-compliant multi-argument
12464 * UNNEST().
12465 */
12466 all_unnest = true;
12467 foreach(lc, rte->functions)
12468 {
12469 RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
12470
12471 if (!IsA(rtfunc->funcexpr, FuncExpr) ||
12472 ((FuncExpr *) rtfunc->funcexpr)->funcid != F_UNNEST_ANYARRAY ||
12473 rtfunc->funccolnames != NIL)
12474 {
12475 all_unnest = false;
12476 break;
12477 }
12478 }
12479
12480 if (all_unnest)
12481 {
12482 List *allargs = NIL;
12483
12484 foreach(lc, rte->functions)
12485 {
12486 RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
12487 List *args = ((FuncExpr *) rtfunc->funcexpr)->args;
12488
12489 allargs = list_concat(allargs, args);
12490 }
12491
12492 appendStringInfoString(buf, "UNNEST(");
12493 get_rule_expr((Node *) allargs, context, true);
12494 appendStringInfoChar(buf, ')');
12495 }
12496 else
12497 {
12498 int funcno = 0;
12499
12500 appendStringInfoString(buf, "ROWS FROM(");
12501 foreach(lc, rte->functions)
12502 {
12503 RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
12504
12505 if (funcno > 0)
12506 appendStringInfoString(buf, ", ");
12507 get_rule_expr_funccall(rtfunc->funcexpr, context, true);
12508 if (rtfunc->funccolnames != NIL)
12509 {
12510 /* Reconstruct the column definition list */
12511 appendStringInfoString(buf, " AS ");
12512 get_from_clause_coldeflist(rtfunc,
12513 NULL,
12514 context);
12515 }
12516 funcno++;
12517 }
12518 appendStringInfoChar(buf, ')');
12519 }
12520 /* prevent printing duplicate coldeflist below */
12521 rtfunc1 = NULL;
12522 }
12523 if (rte->funcordinality)
12524 appendStringInfoString(buf, " WITH ORDINALITY");
12525 break;
12526 case RTE_TABLEFUNC:
12527 get_tablefunc(rte->tablefunc, context, true);
12528 break;
12529 case RTE_VALUES:
12530 /* Values list RTE */
12531 appendStringInfoChar(buf, '(');
12532 get_values_def(rte->values_lists, context);
12533 appendStringInfoChar(buf, ')');
12534 break;
12535 case RTE_CTE:
12536 appendStringInfoString(buf, quote_identifier(rte->ctename));
12537 break;
12538 default:
12539 elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
12540 break;
12541 }
12542
12543 /* Print the relation alias, if needed */
12544 get_rte_alias(rte, varno, false, context);
12545
12546 /* Print the column definitions or aliases, if needed */
12547 if (rtfunc1 && rtfunc1->funccolnames != NIL)
12548 {
12549 /* Reconstruct the columndef list, which is also the aliases */
12550 get_from_clause_coldeflist(rtfunc1, colinfo, context);
12551 }
12552 else
12553 {
12554 /* Else print column aliases as needed */
12555 get_column_alias_list(colinfo, context);
12556 }
12557
12558 /* Tablesample clause must go after any alias */
12559 if (rte->rtekind == RTE_RELATION && rte->tablesample)
12560 get_tablesample_def(rte->tablesample, context);
12561 }
12562 else if (IsA(jtnode, JoinExpr))
12563 {
12564 JoinExpr *j = (JoinExpr *) jtnode;
12565 deparse_columns *colinfo = deparse_columns_fetch(j->rtindex, dpns);
12566 bool need_paren_on_right;
12567
12568 need_paren_on_right = PRETTY_PAREN(context) &&
12569 !IsA(j->rarg, RangeTblRef) &&
12570 !(IsA(j->rarg, JoinExpr) && ((JoinExpr *) j->rarg)->alias != NULL);
12571
12572 if (!PRETTY_PAREN(context) || j->alias != NULL)
12573 appendStringInfoChar(buf, '(');
12574
12575 get_from_clause_item(j->larg, query, context);
12576
12577 switch (j->jointype)
12578 {
12579 case JOIN_INNER:
12580 if (j->quals)
12581 appendContextKeyword(context, " JOIN ",
12582 -PRETTYINDENT_STD,
12583 PRETTYINDENT_STD,
12584 PRETTYINDENT_JOIN);
12585 else
12586 appendContextKeyword(context, " CROSS JOIN ",
12587 -PRETTYINDENT_STD,
12588 PRETTYINDENT_STD,
12589 PRETTYINDENT_JOIN);
12590 break;
12591 case JOIN_LEFT:
12592 appendContextKeyword(context, " LEFT JOIN ",
12593 -PRETTYINDENT_STD,
12594 PRETTYINDENT_STD,
12595 PRETTYINDENT_JOIN);
12596 break;
12597 case JOIN_FULL:
12598 appendContextKeyword(context, " FULL JOIN ",
12599 -PRETTYINDENT_STD,
12600 PRETTYINDENT_STD,
12601 PRETTYINDENT_JOIN);
12602 break;
12603 case JOIN_RIGHT:
12604 appendContextKeyword(context, " RIGHT JOIN ",
12605 -PRETTYINDENT_STD,
12606 PRETTYINDENT_STD,
12607 PRETTYINDENT_JOIN);
12608 break;
12609 default:
12610 elog(ERROR, "unrecognized join type: %d",
12611 (int) j->jointype);
12612 }
12613
12614 if (need_paren_on_right)
12615 appendStringInfoChar(buf, '(');
12616 get_from_clause_item(j->rarg, query, context);
12617 if (need_paren_on_right)
12618 appendStringInfoChar(buf, ')');
12619
12620 if (j->usingClause)
12621 {
12622 ListCell *lc;
12623 bool first = true;
12624
12625 appendStringInfoString(buf, " USING (");
12626 /* Use the assigned names, not what's in usingClause */
12627 foreach(lc, colinfo->usingNames)
12628 {
12629 char *colname = (char *) lfirst(lc);
12630
12631 if (first)
12632 first = false;
12633 else
12634 appendStringInfoString(buf, ", ");
12635 appendStringInfoString(buf, quote_identifier(colname));
12636 }
12637 appendStringInfoChar(buf, ')');
12638
12639 if (j->join_using_alias)
12640 appendStringInfo(buf, " AS %s",
12641 quote_identifier(j->join_using_alias->aliasname));
12642 }
12643 else if (j->quals)
12644 {
12645 appendStringInfoString(buf, " ON ");
12646 if (!PRETTY_PAREN(context))
12647 appendStringInfoChar(buf, '(');
12648 get_rule_expr(j->quals, context, false);
12649 if (!PRETTY_PAREN(context))
12650 appendStringInfoChar(buf, ')');
12651 }
12652 else if (j->jointype != JOIN_INNER)
12653 {
12654 /* If we didn't say CROSS JOIN above, we must provide an ON */
12655 appendStringInfoString(buf, " ON TRUE");
12656 }
12657
12658 if (!PRETTY_PAREN(context) || j->alias != NULL)
12659 appendStringInfoChar(buf, ')');
12660
12661 /* Yes, it's correct to put alias after the right paren ... */
12662 if (j->alias != NULL)
12663 {
12664 /*
12665 * Note that it's correct to emit an alias clause if and only if
12666 * there was one originally. Otherwise we'd be converting a named
12667 * join to unnamed or vice versa, which creates semantic
12668 * subtleties we don't want. However, we might print a different
12669 * alias name than was there originally.
12670 */
12671 appendStringInfo(buf, " %s",
12672 quote_identifier(get_rtable_name(j->rtindex,
12673 context)));
12674 get_column_alias_list(colinfo, context);
12675 }
12676 }
12677 else
12678 elog(ERROR, "unrecognized node type: %d",
12679 (int) nodeTag(jtnode));
12680 }
12681
12682 /*
12683 * get_rte_alias - print the relation's alias, if needed
12684 *
12685 * If printed, the alias is preceded by a space, or by " AS " if use_as is true.
12686 */
12687 static void
12688 get_rte_alias(RangeTblEntry *rte, int varno, bool use_as,
12689 deparse_context *context)
12690 {
12691 deparse_namespace *dpns = (deparse_namespace *) linitial(context->namespaces);
12692 char *refname = get_rtable_name(varno, context);
12693 deparse_columns *colinfo = deparse_columns_fetch(varno, dpns);
12694 bool printalias = false;
12695
12696 if (rte->alias != NULL)
12697 {
12698 /* Always print alias if user provided one */
12699 printalias = true;
12700 }
12701 else if (colinfo->printaliases)
12702 {
12703 /* Always print alias if we need to print column aliases */
12704 printalias = true;
12705 }
12706 else if (rte->rtekind == RTE_RELATION)
12707 {
12708 /*
12709 * No need to print alias if it's same as relation name (this would
12710 * normally be the case, but not if set_rtable_names had to resolve a
12711 * conflict).
12712 */
12713 if (strcmp(refname, get_relation_name(rte->relid)) != 0)
12714 printalias = true;
12715 }
12716 else if (rte->rtekind == RTE_FUNCTION)
12717 {
12718 /*
12719 * For a function RTE, always print alias. This covers possible
12720 * renaming of the function and/or instability of the FigureColname
12721 * rules for things that aren't simple functions. Note we'd need to
12722 * force it anyway for the columndef list case.
12723 */
12724 printalias = true;
12725 }
12726 else if (rte->rtekind == RTE_SUBQUERY ||
12727 rte->rtekind == RTE_VALUES)
12728 {
12729 /*
12730 * For a subquery, always print alias. This makes the output
12731 * SQL-spec-compliant, even though we allow such aliases to be omitted
12732 * on input.
12733 */
12734 printalias = true;
12735 }
12736 else if (rte->rtekind == RTE_CTE)
12737 {
12738 /*
12739 * No need to print alias if it's same as CTE name (this would
12740 * normally be the case, but not if set_rtable_names had to resolve a
12741 * conflict).
12742 */
12743 if (strcmp(refname, rte->ctename) != 0)
12744 printalias = true;
12745 }
12746
12747 if (printalias)
12748 appendStringInfo(context->buf, "%s%s",
12749 use_as ? " AS " : " ",
12750 quote_identifier(refname));
12751 }
12752
12753 /*
12754 * get_column_alias_list - print column alias list for an RTE
12755 *
12756 * Caller must already have printed the relation's alias name.
12757 */
12758 static void
12759 get_column_alias_list(deparse_columns *colinfo, deparse_context *context)
12760 {
12761 StringInfo buf = context->buf;
12762 int i;
12763 bool first = true;
12764
12765 /* Don't print aliases if not needed */
12766 if (!colinfo->printaliases)
12767 return;
12768
12769 for (i = 0; i < colinfo->num_new_cols; i++)
12770 {
12771 char *colname = colinfo->new_colnames[i];
12772
12773 if (first)
12774 {
12775 appendStringInfoChar(buf, '(');
12776 first = false;
12777 }
12778 else
12779 appendStringInfoString(buf, ", ");
12780 appendStringInfoString(buf, quote_identifier(colname));
12781 }
12782 if (!first)
12783 appendStringInfoChar(buf, ')');
12784 }
12785
12786 /*
12787 * get_from_clause_coldeflist - reproduce FROM clause coldeflist
12788 *
12789 * When printing a top-level coldeflist (which is syntactically also the
12790 * relation's column alias list), use column names from colinfo. But when
12791 * printing a coldeflist embedded inside ROWS FROM(), we prefer to use the
12792 * original coldeflist's names, which are available in rtfunc->funccolnames.
12793 * Pass NULL for colinfo to select the latter behavior.
12794 *
12795 * The coldeflist is appended immediately (no space) to buf. Caller is
12796 * responsible for ensuring that an alias or AS is present before it.
12797 */
12798 static void
12799 get_from_clause_coldeflist(RangeTblFunction *rtfunc,
12800 deparse_columns *colinfo,
12801 deparse_context *context)
12802 {
12803 StringInfo buf = context->buf;
12804 ListCell *l1;
12805 ListCell *l2;
12806 ListCell *l3;
12807 ListCell *l4;
12808 int i;
12809
12810 appendStringInfoChar(buf, '(');
12811
12812 i = 0;
12813 forfour(l1, rtfunc->funccoltypes,
12814 l2, rtfunc->funccoltypmods,
12815 l3, rtfunc->funccolcollations,
12816 l4, rtfunc->funccolnames)
12817 {
12818 Oid atttypid = lfirst_oid(l1);
12819 int32 atttypmod = lfirst_int(l2);
12820 Oid attcollation = lfirst_oid(l3);
12821 char *attname;
12822
12823 if (colinfo)
12824 attname = colinfo->colnames[i];
12825 else
12826 attname = strVal(lfirst(l4));
12827
12828 Assert(attname); /* shouldn't be any dropped columns here */
12829
12830 if (i > 0)
12831 appendStringInfoString(buf, ", ");
12832 appendStringInfo(buf, "%s %s",
12833 quote_identifier(attname),
12834 format_type_with_typemod(atttypid, atttypmod));
12835 if (OidIsValid(attcollation) &&
12836 attcollation != get_typcollation(atttypid))
12837 appendStringInfo(buf, " COLLATE %s",
12838 generate_collation_name(attcollation));
12839
12840 i++;
12841 }
12842
12843 appendStringInfoChar(buf, ')');
12844 }
12845
12846 /*
12847 * get_tablesample_def - print a TableSampleClause
12848 */
12849 static void
12850 get_tablesample_def(TableSampleClause *tablesample, deparse_context *context)
12851 {
12852 StringInfo buf = context->buf;
12853 Oid argtypes[1];
12854 int nargs;
12855 ListCell *l;
12856
12857 /*
12858 * We should qualify the handler's function name if it wouldn't be
12859 * resolved by lookup in the current search path.
12860 */
12861 argtypes[0] = INTERNALOID;
12862 appendStringInfo(buf, " TABLESAMPLE %s (",
12863 generate_function_name(tablesample->tsmhandler, 1,
12864 NIL, argtypes,
12865 false, NULL, false));
12866
12867 nargs = 0;
12868 foreach(l, tablesample->args)
12869 {
12870 if (nargs++ > 0)
12871 appendStringInfoString(buf, ", ");
12872 get_rule_expr((Node *) lfirst(l), context, false);
12873 }
12874 appendStringInfoChar(buf, ')');
12875
12876 if (tablesample->repeatable != NULL)
12877 {
12878 appendStringInfoString(buf, " REPEATABLE (");
12879 get_rule_expr((Node *) tablesample->repeatable, context, false);
12880 appendStringInfoChar(buf, ')');
12881 }
12882 }
12883
12884 /*
12885 * get_opclass_name - fetch name of an index operator class
12886 *
12887 * The opclass name is appended (after a space) to buf.
12888 *
12889 * Output is suppressed if the opclass is the default for the given
12890 * actual_datatype. (If you don't want this behavior, just pass
12891 * InvalidOid for actual_datatype.)
12892 */
12893 static void
12894 get_opclass_name(Oid opclass, Oid actual_datatype,
12895 StringInfo buf)
12896 {
12897 HeapTuple ht_opc;
12898 Form_pg_opclass opcrec;
12899 char *opcname;
12900 char *nspname;
12901
12902 ht_opc = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
12903 if (!HeapTupleIsValid(ht_opc))
12904 elog(ERROR, "cache lookup failed for opclass %u", opclass);
12905 opcrec = (Form_pg_opclass) GETSTRUCT(ht_opc);
12906
12907 if (!OidIsValid(actual_datatype) ||
12908 GetDefaultOpClass(actual_datatype, opcrec->opcmethod) != opclass)
12909 {
12910 /* Okay, we need the opclass name. Do we need to qualify it? */
12911 opcname = NameStr(opcrec->opcname);
12912 if (OpclassIsVisible(opclass))
12913 appendStringInfo(buf, " %s", quote_identifier(opcname));
12914 else
12915 {
12916 nspname = get_namespace_name_or_temp(opcrec->opcnamespace);
12917 appendStringInfo(buf, " %s.%s",
12918 quote_identifier(nspname),
12919 quote_identifier(opcname));
12920 }
12921 }
12922 ReleaseSysCache(ht_opc);
12923 }
12924
12925 /*
12926 * generate_opclass_name
12927 * Compute the name to display for an opclass specified by OID
12928 *
12929 * The result includes all necessary quoting and schema-prefixing.
12930 */
12931 char *
12932 generate_opclass_name(Oid opclass)
12933 {
12934 StringInfoData buf;
12935
12936 initStringInfo(&buf);
12937 get_opclass_name(opclass, InvalidOid, &buf);
12938
12939 return &buf.data[1]; /* get_opclass_name() prepends space */
12940 }
12941
12942 /*
12943 * processIndirection - take care of array and subfield assignment
12944 *
12945 * We strip any top-level FieldStore or assignment SubscriptingRef nodes that
12946 * appear in the input, printing them as decoration for the base column
12947 * name (which we assume the caller just printed). We might also need to
12948 * strip CoerceToDomain nodes, but only ones that appear above assignment
12949 * nodes.
12950 *
12951 * Returns the subexpression that's to be assigned.
12952 */
12953 static Node *
12954 processIndirection(Node *node, deparse_context *context)
12955 {
12956 StringInfo buf = context->buf;
12957 CoerceToDomain *cdomain = NULL;
12958
12959 for (;;)
12960 {
12961 if (node == NULL)
12962 break;
12963 if (IsA(node, FieldStore))
12964 {
12965 FieldStore *fstore = (FieldStore *) node;
12966 Oid typrelid;
12967 char *fieldname;
12968
12969 /* lookup tuple type */
12970 typrelid = get_typ_typrelid(fstore->resulttype);
12971 if (!OidIsValid(typrelid))
12972 elog(ERROR, "argument type %s of FieldStore is not a tuple type",
12973 format_type_be(fstore->resulttype));
12974
12975 /*
12976 * Print the field name. There should only be one target field in
12977 * stored rules. There could be more than that in executable
12978 * target lists, but this function cannot be used for that case.
12979 */
12980 Assert(list_length(fstore->fieldnums) == 1);
12981 fieldname = get_attname(typrelid,
12982 linitial_int(fstore->fieldnums), false);
12983 appendStringInfo(buf, ".%s", quote_identifier(fieldname));
12984
12985 /*
12986 * We ignore arg since it should be an uninteresting reference to
12987 * the target column or subcolumn.
12988 */
12989 node = (Node *) linitial(fstore->newvals);
12990 }
12991 else if (IsA(node, SubscriptingRef))
12992 {
12993 SubscriptingRef *sbsref = (SubscriptingRef *) node;
12994
12995 if (sbsref->refassgnexpr == NULL)
12996 break;
12997
12998 printSubscripts(sbsref, context);
12999
13000 /*
13001 * We ignore refexpr since it should be an uninteresting reference
13002 * to the target column or subcolumn.
13003 */
13004 node = (Node *) sbsref->refassgnexpr;
13005 }
13006 else if (IsA(node, CoerceToDomain))
13007 {
13008 cdomain = (CoerceToDomain *) node;
13009 /* If it's an explicit domain coercion, we're done */
13010 if (cdomain->coercionformat != COERCE_IMPLICIT_CAST)
13011 break;
13012 /* Tentatively descend past the CoerceToDomain */
13013 node = (Node *) cdomain->arg;
13014 }
13015 else
13016 break;
13017 }
13018
13019 /*
13020 * If we descended past a CoerceToDomain whose argument turned out not to
13021 * be a FieldStore or array assignment, back up to the CoerceToDomain.
13022 * (This is not enough to be fully correct if there are nested implicit
13023 * CoerceToDomains, but such cases shouldn't ever occur.)
13024 */
13025 if (cdomain && node == (Node *) cdomain->arg)
13026 node = (Node *) cdomain;
13027
13028 return node;
13029 }
13030
13031 static void
13032 printSubscripts(SubscriptingRef *sbsref, deparse_context *context)
13033 {
13034 StringInfo buf = context->buf;
13035 ListCell *lowlist_item;
13036 ListCell *uplist_item;
13037
13038 lowlist_item = list_head(sbsref->reflowerindexpr); /* could be NULL */
13039 foreach(uplist_item, sbsref->refupperindexpr)
13040 {
13041 appendStringInfoChar(buf, '[');
13042 if (lowlist_item)
13043 {
13044 /* If subexpression is NULL, get_rule_expr prints nothing */
13045 get_rule_expr((Node *) lfirst(lowlist_item), context, false);
13046 appendStringInfoChar(buf, ':');
13047 lowlist_item = lnext(sbsref->reflowerindexpr, lowlist_item);
13048 }
13049 /* If subexpression is NULL, get_rule_expr prints nothing */
13050 get_rule_expr((Node *) lfirst(uplist_item), context, false);
13051 appendStringInfoChar(buf, ']');
13052 }
13053 }
13054
13055 /*
13056 * quote_identifier - Quote an identifier only if needed
13057 *
13058 * When quotes are needed, we palloc the required space; slightly
13059 * space-wasteful but well worth it for notational simplicity.
13060 */
13061 const char *
13062 quote_identifier(const char *ident)
13063 {
13064 /*
13065 * Can avoid quoting if ident starts with a lowercase letter or underscore
13066 * and contains only lowercase letters, digits, and underscores, *and* is
13067 * not any SQL keyword. Otherwise, supply quotes.
13068 */
13069 int nquotes = 0;
13070 bool safe;
13071 const char *ptr;
13072 char *result;
13073 char *optr;
13074
13075 /*
13076 * would like to use <ctype.h> macros here, but they might yield unwanted
13077 * locale-specific results...
13078 */
13079 safe = ((ident[0] >= 'a' && ident[0] <= 'z') || ident[0] == '_');
13080
13081 for (ptr = ident; *ptr; ptr++)
13082 {
13083 char ch = *ptr;
13084
13085 if ((ch >= 'a' && ch <= 'z') ||
13086 (ch >= '0' && ch <= '9') ||
13087 (ch == '_'))
13088 {
13089 /* okay */
13090 }
13091 else
13092 {
13093 safe = false;
13094 if (ch == '"')
13095 nquotes++;
13096 }
13097 }
13098
13099 if (quote_all_identifiers)
13100 safe = false;
13101
13102 if (safe)
13103 {
13104 /*
13105 * Check for keyword. We quote keywords except for unreserved ones.
13106 * (In some cases we could avoid quoting a col_name or type_func_name
13107 * keyword, but it seems much harder than it's worth to tell that.)
13108 *
13109 * Note: ScanKeywordLookup() does case-insensitive comparison, but
13110 * that's fine, since we already know we have all-lower-case.
13111 */
13112 int kwnum = ScanKeywordLookup(ident, &ScanKeywords);
13113
13114 if (kwnum >= 0 && ScanKeywordCategories[kwnum] != UNRESERVED_KEYWORD)
13115 safe = false;
13116 }
13117
13118 if (safe)
13119 return ident; /* no change needed */
13120
13121 result = (char *) palloc(strlen(ident) + nquotes + 2 + 1);
13122
13123 optr = result;
13124 *optr++ = '"';
13125 for (ptr = ident; *ptr; ptr++)
13126 {
13127 char ch = *ptr;
13128
13129 if (ch == '"')
13130 *optr++ = '"';
13131 *optr++ = ch;
13132 }
13133 *optr++ = '"';
13134 *optr = '\0';
13135
13136 return result;
13137 }
13138
13139 /*
13140 * quote_qualified_identifier - Quote a possibly-qualified identifier
13141 *
13142 * Return a name of the form qualifier.ident, or just ident if qualifier
13143 * is NULL, quoting each component if necessary. The result is palloc'd.
13144 */
13145 char *
13146 quote_qualified_identifier(const char *qualifier,
13147 const char *ident)
13148 {
13149 StringInfoData buf;
13150
13151 initStringInfo(&buf);
13152 if (qualifier)
13153 appendStringInfo(&buf, "%s.", quote_identifier(qualifier));
13154 appendStringInfoString(&buf, quote_identifier(ident));
13155 return buf.data;
13156 }
13157
13158 /*
13159 * get_relation_name
13160 * Get the unqualified name of a relation specified by OID
13161 *
13162 * This differs from the underlying get_rel_name() function in that it will
13163 * throw error instead of silently returning NULL if the OID is bad.
13164 */
13165 static char *
13166 get_relation_name(Oid relid)
13167 {
13168 char *relname = get_rel_name(relid);
13169
13170 if (!relname)
13171 elog(ERROR, "cache lookup failed for relation %u", relid);
13172 return relname;
13173 }
13174
13175 /*
13176 * generate_relation_name
13177 * Compute the name to display for a relation specified by OID
13178 *
13179 * The result includes all necessary quoting and schema-prefixing.
13180 *
13181 * If namespaces isn't NIL, it must be a list of deparse_namespace nodes.
13182 * We will forcibly qualify the relation name if it equals any CTE name
13183 * visible in the namespace list.
13184 */
13185 static char *
13186 generate_relation_name(Oid relid, List *namespaces)
13187 {
13188 HeapTuple tp;
13189 Form_pg_class reltup;
13190 bool need_qual;
13191 ListCell *nslist;
13192 char *relname;
13193 char *nspname;
13194 char *result;
13195
13196 tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
13197 if (!HeapTupleIsValid(tp))
13198 elog(ERROR, "cache lookup failed for relation %u", relid);
13199 reltup = (Form_pg_class) GETSTRUCT(tp);
13200 relname = NameStr(reltup->relname);
13201
13202 /* Check for conflicting CTE name */
13203 need_qual = false;
13204 foreach(nslist, namespaces)
13205 {
13206 deparse_namespace *dpns = (deparse_namespace *) lfirst(nslist);
13207 ListCell *ctlist;
13208
13209 foreach(ctlist, dpns->ctes)
13210 {
13211 CommonTableExpr *cte = (CommonTableExpr *) lfirst(ctlist);
13212
13213 if (strcmp(cte->ctename, relname) == 0)
13214 {
13215 need_qual = true;
13216 break;
13217 }
13218 }
13219 if (need_qual)
13220 break;
13221 }
13222
13223 /* Otherwise, qualify the name if not visible in search path */
13224 if (!need_qual)
13225 need_qual = !RelationIsVisible(relid);
13226
13227 if (need_qual)
13228 nspname = get_namespace_name_or_temp(reltup->relnamespace);
13229 else
13230 nspname = NULL;
13231
13232 result = quote_qualified_identifier(nspname, relname);
13233
13234 ReleaseSysCache(tp);
13235
13236 return result;
13237 }
13238
13239 /*
13240 * generate_qualified_relation_name
13241 * Compute the name to display for a relation specified by OID
13242 *
13243 * As above, but unconditionally schema-qualify the name.
13244 */
13245 static char *
13246 generate_qualified_relation_name(Oid relid)
13247 {
13248 HeapTuple tp;
13249 Form_pg_class reltup;
13250 char *relname;
13251 char *nspname;
13252 char *result;
13253
13254 tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
13255 if (!HeapTupleIsValid(tp))
13256 elog(ERROR, "cache lookup failed for relation %u", relid);
13257 reltup = (Form_pg_class) GETSTRUCT(tp);
13258 relname = NameStr(reltup->relname);
13259
13260 nspname = get_namespace_name_or_temp(reltup->relnamespace);
13261 if (!nspname)
13262 elog(ERROR, "cache lookup failed for namespace %u",
13263 reltup->relnamespace);
13264
13265 result = quote_qualified_identifier(nspname, relname);
13266
13267 ReleaseSysCache(tp);
13268
13269 return result;
13270 }
13271
13272 /*
13273 * generate_function_name
13274 * Compute the name to display for a function specified by OID,
13275 * given that it is being called with the specified actual arg names and
13276 * types. (Those matter because of ambiguous-function resolution rules.)
13277 *
13278 * If we're dealing with a potentially variadic function (in practice, this
13279 * means a FuncExpr or Aggref, not some other way of calling a function), then
13280 * has_variadic must specify whether variadic arguments have been merged,
13281 * and *use_variadic_p will be set to indicate whether to print VARIADIC in
13282 * the output. For non-FuncExpr cases, has_variadic should be false and
13283 * use_variadic_p can be NULL.
13284 *
13285 * inGroupBy must be true if we're deparsing a GROUP BY clause.
13286 *
13287 * The result includes all necessary quoting and schema-prefixing.
13288 */
13289 static char *
13290 generate_function_name(Oid funcid, int nargs, List *argnames, Oid *argtypes,
13291 bool has_variadic, bool *use_variadic_p,
13292 bool inGroupBy)
13293 {
13294 char *result;
13295 HeapTuple proctup;
13296 Form_pg_proc procform;
13297 char *proname;
13298 bool use_variadic;
13299 char *nspname;
13300 FuncDetailCode p_result;
13301 Oid p_funcid;
13302 Oid p_rettype;
13303 bool p_retset;
13304 int p_nvargs;
13305 Oid p_vatype;
13306 Oid *p_true_typeids;
13307 bool force_qualify = false;
13308
13309 proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
13310 if (!HeapTupleIsValid(proctup))
13311 elog(ERROR, "cache lookup failed for function %u", funcid);
13312 procform = (Form_pg_proc) GETSTRUCT(proctup);
13313 proname = NameStr(procform->proname);
13314
13315 /*
13316 * Due to parser hacks to avoid needing to reserve CUBE, we need to force
13317 * qualification of some function names within GROUP BY.
13318 */
13319 if (inGroupBy)
13320 {
13321 if (strcmp(proname, "cube") == 0 || strcmp(proname, "rollup") == 0)
13322 force_qualify = true;
13323 }
13324
13325 /*
13326 * Determine whether VARIADIC should be printed. We must do this first
13327 * since it affects the lookup rules in func_get_detail().
13328 *
13329 * We always print VARIADIC if the function has a merged variadic-array
13330 * argument. Note that this is always the case for functions taking a
13331 * VARIADIC argument type other than VARIADIC ANY. If we omitted VARIADIC
13332 * and printed the array elements as separate arguments, the call could
13333 * match a newer non-VARIADIC function.
13334 */
13335 if (use_variadic_p)
13336 {
13337 /* Parser should not have set funcvariadic unless fn is variadic */
13338 Assert(!has_variadic || OidIsValid(procform->provariadic));
13339 use_variadic = has_variadic;
13340 *use_variadic_p = use_variadic;
13341 }
13342 else
13343 {
13344 Assert(!has_variadic);
13345 use_variadic = false;
13346 }
13347
13348 /*
13349 * The idea here is to schema-qualify only if the parser would fail to
13350 * resolve the correct function given the unqualified func name with the
13351 * specified argtypes and VARIADIC flag. But if we already decided to
13352 * force qualification, then we can skip the lookup and pretend we didn't
13353 * find it.
13354 */
13355 if (!force_qualify)
13356 p_result = func_get_detail(list_make1(makeString(proname)),
13357 NIL, argnames, nargs, argtypes,
13358 !use_variadic, true, false,
13359 &p_funcid, &p_rettype,
13360 &p_retset, &p_nvargs, &p_vatype,
13361 &p_true_typeids, NULL);
13362 else
13363 {
13364 p_result = FUNCDETAIL_NOTFOUND;
13365 p_funcid = InvalidOid;
13366 }
13367
13368 if ((p_result == FUNCDETAIL_NORMAL ||
13369 p_result == FUNCDETAIL_AGGREGATE ||
13370 p_result == FUNCDETAIL_WINDOWFUNC) &&
13371 p_funcid == funcid)
13372 nspname = NULL;
13373 else
13374 nspname = get_namespace_name_or_temp(procform->pronamespace);
13375
13376 result = quote_qualified_identifier(nspname, proname);
13377
13378 ReleaseSysCache(proctup);
13379
13380 return result;
13381 }
13382
13383 /*
13384 * generate_operator_name
13385 * Compute the name to display for an operator specified by OID,
13386 * given that it is being called with the specified actual arg types.
13387 * (Arg types matter because of ambiguous-operator resolution rules.
13388 * Pass InvalidOid for unused arg of a unary operator.)
13389 *
13390 * The result includes all necessary quoting and schema-prefixing,
13391 * plus the OPERATOR() decoration needed to use a qualified operator name
13392 * in an expression.
13393 */
13394 static char *
13395 generate_operator_name(Oid operid, Oid arg1, Oid arg2)
13396 {
13397 StringInfoData buf;
13398 HeapTuple opertup;
13399 Form_pg_operator operform;
13400 char *oprname;
13401 char *nspname;
13402 Operator p_result;
13403
13404 initStringInfo(&buf);
13405
13406 opertup = SearchSysCache1(OPEROID, ObjectIdGetDatum(operid));
13407 if (!HeapTupleIsValid(opertup))
13408 elog(ERROR, "cache lookup failed for operator %u", operid);
13409 operform = (Form_pg_operator) GETSTRUCT(opertup);
13410 oprname = NameStr(operform->oprname);
13411
13412 /*
13413 * The idea here is to schema-qualify only if the parser would fail to
13414 * resolve the correct operator given the unqualified op name with the
13415 * specified argtypes.
13416 */
13417 switch (operform->oprkind)
13418 {
13419 case 'b':
13420 p_result = oper(NULL, list_make1(makeString(oprname)), arg1, arg2,
13421 true, -1);
13422 break;
13423 case 'l':
13424 p_result = left_oper(NULL, list_make1(makeString(oprname)), arg2,
13425 true, -1);
13426 break;
13427 default:
13428 elog(ERROR, "unrecognized oprkind: %d", operform->oprkind);
13429 p_result = NULL; /* keep compiler quiet */
13430 break;
13431 }
13432
13433 if (p_result != NULL && oprid(p_result) == operid)
13434 nspname = NULL;
13435 else
13436 {
13437 nspname = get_namespace_name_or_temp(operform->oprnamespace);
13438 appendStringInfo(&buf, "OPERATOR(%s.", quote_identifier(nspname));
13439 }
13440
13441 appendStringInfoString(&buf, oprname);
13442
13443 if (nspname)
13444 appendStringInfoChar(&buf, ')');
13445
13446 if (p_result != NULL)
13447 ReleaseSysCache(p_result);
13448
13449 ReleaseSysCache(opertup);
13450
13451 return buf.data;
13452 }
13453
13454 /*
13455 * generate_operator_clause --- generate a binary-operator WHERE clause
13456 *
13457 * This is used for internally-generated-and-executed SQL queries, where
13458 * precision is essential and readability is secondary. The basic
13459 * requirement is to append "leftop op rightop" to buf, where leftop and
13460 * rightop are given as strings and are assumed to yield types leftoptype
13461 * and rightoptype; the operator is identified by OID. The complexity
13462 * comes from needing to be sure that the parser will select the desired
13463 * operator when the query is parsed. We always name the operator using
13464 * OPERATOR(schema.op) syntax, so as to avoid search-path uncertainties.
13465 * We have to emit casts too, if either input isn't already the input type
13466 * of the operator; else we are at the mercy of the parser's heuristics for
13467 * ambiguous-operator resolution. The caller must ensure that leftop and
13468 * rightop are suitable arguments for a cast operation; it's best to insert
13469 * parentheses if they aren't just variables or parameters.
13470 */
13471 void
13472 generate_operator_clause(StringInfo buf,
13473 const char *leftop, Oid leftoptype,
13474 Oid opoid,
13475 const char *rightop, Oid rightoptype)
13476 {
13477 HeapTuple opertup;
13478 Form_pg_operator operform;
13479 char *oprname;
13480 char *nspname;
13481
13482 opertup = SearchSysCache1(OPEROID, ObjectIdGetDatum(opoid));
13483 if (!HeapTupleIsValid(opertup))
13484 elog(ERROR, "cache lookup failed for operator %u", opoid);
13485 operform = (Form_pg_operator) GETSTRUCT(opertup);
13486 Assert(operform->oprkind == 'b');
13487 oprname = NameStr(operform->oprname);
13488
13489 nspname = get_namespace_name(operform->oprnamespace);
13490
13491 appendStringInfoString(buf, leftop);
13492 if (leftoptype != operform->oprleft)
13493 add_cast_to(buf, operform->oprleft);
13494 appendStringInfo(buf, " OPERATOR(%s.", quote_identifier(nspname));
13495 appendStringInfoString(buf, oprname);
13496 appendStringInfo(buf, ") %s", rightop);
13497 if (rightoptype != operform->oprright)
13498 add_cast_to(buf, operform->oprright);
13499
13500 ReleaseSysCache(opertup);
13501 }
13502
13503 /*
13504 * Add a cast specification to buf. We spell out the type name the hard way,
13505 * intentionally not using format_type_be(). This is to avoid corner cases
13506 * for CHARACTER, BIT, and perhaps other types, where specifying the type
13507 * using SQL-standard syntax results in undesirable data truncation. By
13508 * doing it this way we can be certain that the cast will have default (-1)
13509 * target typmod.
13510 */
13511 static void
13512 add_cast_to(StringInfo buf, Oid typid)
13513 {
13514 HeapTuple typetup;
13515 Form_pg_type typform;
13516 char *typname;
13517 char *nspname;
13518
13519 typetup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
13520 if (!HeapTupleIsValid(typetup))
13521 elog(ERROR, "cache lookup failed for type %u", typid);
13522 typform = (Form_pg_type) GETSTRUCT(typetup);
13523
13524 typname = NameStr(typform->typname);
13525 nspname = get_namespace_name_or_temp(typform->typnamespace);
13526
13527 appendStringInfo(buf, "::%s.%s",
13528 quote_identifier(nspname), quote_identifier(typname));
13529
13530 ReleaseSysCache(typetup);
13531 }
13532
13533 /*
13534 * generate_qualified_type_name
13535 * Compute the name to display for a type specified by OID
13536 *
13537 * This is different from format_type_be() in that we unconditionally
13538 * schema-qualify the name. That also means no special syntax for
13539 * SQL-standard type names ... although in current usage, this should
13540 * only get used for domains, so such cases wouldn't occur anyway.
13541 */
13542 static char *
13543 generate_qualified_type_name(Oid typid)
13544 {
13545 HeapTuple tp;
13546 Form_pg_type typtup;
13547 char *typname;
13548 char *nspname;
13549 char *result;
13550
13551 tp = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
13552 if (!HeapTupleIsValid(tp))
13553 elog(ERROR, "cache lookup failed for type %u", typid);
13554 typtup = (Form_pg_type) GETSTRUCT(tp);
13555 typname = NameStr(typtup->typname);
13556
13557 nspname = get_namespace_name_or_temp(typtup->typnamespace);
13558 if (!nspname)
13559 elog(ERROR, "cache lookup failed for namespace %u",
13560 typtup->typnamespace);
13561
13562 result = quote_qualified_identifier(nspname, typname);
13563
13564 ReleaseSysCache(tp);
13565
13566 return result;
13567 }
13568
13569 /*
13570 * generate_collation_name
13571 * Compute the name to display for a collation specified by OID
13572 *
13573 * The result includes all necessary quoting and schema-prefixing.
13574 */
13575 char *
13576 generate_collation_name(Oid collid)
13577 {
13578 HeapTuple tp;
13579 Form_pg_collation colltup;
13580 char *collname;
13581 char *nspname;
13582 char *result;
13583
13584 tp = SearchSysCache1(COLLOID, ObjectIdGetDatum(collid));
13585 if (!HeapTupleIsValid(tp))
13586 elog(ERROR, "cache lookup failed for collation %u", collid);
13587 colltup = (Form_pg_collation) GETSTRUCT(tp);
13588 collname = NameStr(colltup->collname);
13589
13590 if (!CollationIsVisible(collid))
13591 nspname = get_namespace_name_or_temp(colltup->collnamespace);
13592 else
13593 nspname = NULL;
13594
13595 result = quote_qualified_identifier(nspname, collname);
13596
13597 ReleaseSysCache(tp);
13598
13599 return result;
13600 }
13601
13602 /*
13603 * Given a C string, produce a TEXT datum.
13604 *
13605 * We assume that the input was palloc'd and may be freed.
13606 */
13607 static text *
13608 string_to_text(char *str)
13609 {
13610 text *result;
13611
13612 result = cstring_to_text(str);
13613 pfree(str);
13614 return result;
13615 }
13616
13617 /*
13618 * Generate a C string representing a relation options from text[] datum.
13619 */
13620 static void
13621 get_reloptions(StringInfo buf, Datum reloptions)
13622 {
13623 Datum *options;
13624 int noptions;
13625 int i;
13626
13627 deconstruct_array_builtin(DatumGetArrayTypeP(reloptions), TEXTOID,
13628 &options, NULL, &noptions);
13629
13630 for (i = 0; i < noptions; i++)
13631 {
13632 char *option = TextDatumGetCString(options[i]);
13633 char *name;
13634 char *separator;
13635 char *value;
13636
13637 /*
13638 * Each array element should have the form name=value. If the "=" is
13639 * missing for some reason, treat it like an empty value.
13640 */
13641 name = option;
13642 separator = strchr(option, '=');
13643 if (separator)
13644 {
13645 *separator = '\0';
13646 value = separator + 1;
13647 }
13648 else
13649 value = "";
13650
13651 if (i > 0)
13652 appendStringInfoString(buf, ", ");
13653 appendStringInfo(buf, "%s=", quote_identifier(name));
13654
13655 /*
13656 * In general we need to quote the value; but to avoid unnecessary
13657 * clutter, do not quote if it is an identifier that would not need
13658 * quoting. (We could also allow numbers, but that is a bit trickier
13659 * than it looks --- for example, are leading zeroes significant? We
13660 * don't want to assume very much here about what custom reloptions
13661 * might mean.)
13662 */
13663 if (quote_identifier(value) == value)
13664 appendStringInfoString(buf, value);
13665 else
13666 simple_quote_literal(buf, value);
13667
13668 pfree(option);
13669 }
13670 }
13671
13672 /*
13673 * Generate a C string representing a relation's reloptions, or NULL if none.
13674 */
13675 static char *
13676 flatten_reloptions(Oid relid)
13677 {
13678 char *result = NULL;
13679 HeapTuple tuple;
13680 Datum reloptions;
13681 bool isnull;
13682
13683 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
13684 if (!HeapTupleIsValid(tuple))
13685 elog(ERROR, "cache lookup failed for relation %u", relid);
13686
13687 reloptions = SysCacheGetAttr(RELOID, tuple,
13688 Anum_pg_class_reloptions, &isnull);
13689 if (!isnull)
13690 {
13691 StringInfoData buf;
13692
13693 initStringInfo(&buf);
13694 get_reloptions(&buf, reloptions);
13695
13696 result = buf.data;
13697 }
13698
13699 ReleaseSysCache(tuple);
13700
13701 return result;
13702 }
13703
13704 /*
13705 * get_range_partbound_string
13706 * A C string representation of one range partition bound
13707 */
13708 char *
13709 get_range_partbound_string(List *bound_datums)
13710 {
13711 deparse_context context;
13712 StringInfo buf = makeStringInfo();
13713 ListCell *cell;
13714 char *sep;
13715
13716 memset(&context, 0, sizeof(deparse_context));
13717 context.buf = buf;
13718
13719 appendStringInfoChar(buf, '(');
13720 sep = "";
13721 foreach(cell, bound_datums)
13722 {
13723 PartitionRangeDatum *datum =
13724 lfirst_node(PartitionRangeDatum, cell);
13725
13726 appendStringInfoString(buf, sep);
13727 if (datum->kind == PARTITION_RANGE_DATUM_MINVALUE)
13728 appendStringInfoString(buf, "MINVALUE");
13729 else if (datum->kind == PARTITION_RANGE_DATUM_MAXVALUE)
13730 appendStringInfoString(buf, "MAXVALUE");
13731 else
13732 {
13733 Const *val = castNode(Const, datum->value);
13734
13735 get_const_expr(val, &context, -1);
13736 }
13737 sep = ", ";
13738 }
13739 appendStringInfoChar(buf, ')');
13740
13741 return buf->data;
13742 }