Thanks to visit codestin.com
Credit goes to doxygen.postgresql.org

PostgreSQL Source Code git master
ruleutils.c
Go to the documentation of this file.
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"
27#include "catalog/pg_am.h"
28#include "catalog/pg_authid.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"
36#include "catalog/pg_proc.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"
55#include "parser/parser.h"
56#include "parser/parsetree.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 */
112typedef 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 */
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 */
162typedef 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;
186 char **argnames;
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 */
234typedef 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 */
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 */
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 */
318typedef struct
319{
320 char name[NAMEDATALEN]; /* Hash key --- must be first */
321 int counter; /* Largest addition used so far for name */
323
324/* Callback signature for resolve_special_varno() */
325typedef void (*rsv_callback) (Node *node, deparse_context *context,
326 void *callback_arg);
327
328
329/* ----------
330 * Global data
331 * ----------
332 */
334static const char *const query_getrulebyoid = "SELECT * FROM pg_catalog.pg_rewrite WHERE oid = $1";
336static const char *const query_getviewrule = "SELECT * FROM pg_catalog.pg_rewrite WHERE ev_class = $1 AND rulename = $2";
337
338/* GUC parameters */
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 */
350static char *deparse_expression_pretty(Node *expr, List *dpcontext,
351 bool forceprefix, bool showimplicit,
352 int prettyFlags, int startIndent);
353static char *pg_get_viewdef_worker(Oid viewoid,
354 int prettyFlags, int wrapColumn);
355static char *pg_get_triggerdef_worker(Oid trigid, bool pretty);
356static int decompile_column_index_array(Datum column_index_array, Oid relId,
357 bool withPeriod, StringInfo buf);
358static char *pg_get_ruledef_worker(Oid ruleoid, int prettyFlags);
359static 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);
364static char *pg_get_statisticsobj_worker(Oid statextid, bool columns_only,
365 bool missing_ok);
366static char *pg_get_partkeydef_worker(Oid relid, int prettyFlags,
367 bool attrsOnly, bool missing_ok);
368static char *pg_get_constraintdef_worker(Oid constraintId, bool fullCommand,
369 int prettyFlags, bool missing_ok);
370static text *pg_get_expr_worker(text *expr, Oid relid, int prettyFlags);
372 bool print_table_args, bool print_defaults);
373static void print_function_rettype(StringInfo buf, HeapTuple proctup);
374static void print_function_trftypes(StringInfo buf, HeapTuple proctup);
375static void print_function_sqlbody(StringInfo buf, HeapTuple proctup);
376static void set_rtable_names(deparse_namespace *dpns, List *parent_namespaces,
377 Bitmapset *rels_used);
378static void set_deparse_for_query(deparse_namespace *dpns, Query *query,
379 List *parent_namespaces);
381static bool has_dangerous_join_using(deparse_namespace *dpns, Node *jtnode);
382static void set_using_names(deparse_namespace *dpns, Node *jtnode,
383 List *parentUsing);
385 RangeTblEntry *rte,
386 deparse_columns *colinfo);
388 deparse_columns *colinfo);
389static bool colname_is_unique(const char *colname, deparse_namespace *dpns,
390 deparse_columns *colinfo);
391static char *make_colname_unique(char *colname, deparse_namespace *dpns,
392 deparse_columns *colinfo);
393static void expand_colnames_array_to(deparse_columns *colinfo, int n);
394static void build_colinfo_names_hash(deparse_columns *colinfo);
395static void add_to_names_hash(deparse_columns *colinfo, const char *name);
396static void destroy_colinfo_names_hash(deparse_columns *colinfo);
398 deparse_columns *colinfo);
399static char *get_rtable_name(int rtindex, deparse_context *context);
400static void set_deparse_plan(deparse_namespace *dpns, Plan *plan);
402 WorkTableScan *wtscan);
403static void push_child_plan(deparse_namespace *dpns, Plan *plan,
404 deparse_namespace *save_dpns);
405static void pop_child_plan(deparse_namespace *dpns,
406 deparse_namespace *save_dpns);
407static void push_ancestor_plan(deparse_namespace *dpns, ListCell *ancestor_cell,
408 deparse_namespace *save_dpns);
409static void pop_ancestor_plan(deparse_namespace *dpns,
410 deparse_namespace *save_dpns);
411static void make_ruledef(StringInfo buf, HeapTuple ruletup, TupleDesc rulettc,
412 int prettyFlags);
413static void make_viewdef(StringInfo buf, HeapTuple ruletup, TupleDesc rulettc,
414 int prettyFlags, int wrapColumn);
415static void get_query_def(Query *query, StringInfo buf, List *parentnamespace,
416 TupleDesc resultDesc, bool colNamesVisible,
417 int prettyFlags, int wrapColumn, int startIndent);
418static void get_values_def(List *values_lists, deparse_context *context);
419static void get_with_clause(Query *query, deparse_context *context);
420static void get_select_query_def(Query *query, deparse_context *context);
421static void get_insert_query_def(Query *query, deparse_context *context);
422static void get_update_query_def(Query *query, deparse_context *context);
423static void get_update_query_targetlist_def(Query *query, List *targetList,
424 deparse_context *context,
425 RangeTblEntry *rte);
426static void get_delete_query_def(Query *query, deparse_context *context);
427static void get_merge_query_def(Query *query, deparse_context *context);
428static void get_utility_query_def(Query *query, deparse_context *context);
429static void get_basic_select_query(Query *query, deparse_context *context);
430static void get_target_list(List *targetList, deparse_context *context);
431static void get_returning_clause(Query *query, deparse_context *context);
432static void get_setop_query(Node *setOp, Query *query,
433 deparse_context *context);
434static Node *get_rule_sortgroupclause(Index ref, List *tlist,
435 bool force_colno,
436 deparse_context *context);
437static void get_rule_groupingset(GroupingSet *gset, List *targetlist,
438 bool omit_parens, deparse_context *context);
439static void get_rule_orderby(List *orderList, List *targetList,
440 bool force_colno, deparse_context *context);
441static void get_rule_windowclause(Query *query, deparse_context *context);
442static void get_rule_windowspec(WindowClause *wc, List *targetList,
443 deparse_context *context);
444static void get_window_frame_options(int frameOptions,
445 Node *startOffset, Node *endOffset,
446 deparse_context *context);
447static char *get_variable(Var *var, int levelsup, bool istoplevel,
448 deparse_context *context);
449static void get_special_variable(Node *node, deparse_context *context,
450 void *callback_arg);
451static void resolve_special_varno(Node *node, deparse_context *context,
452 rsv_callback callback, void *callback_arg);
453static Node *find_param_referent(Param *param, deparse_context *context,
454 deparse_namespace **dpns_p, ListCell **ancestor_cell_p);
455static SubPlan *find_param_generator(Param *param, deparse_context *context,
456 int *column_p);
458 int *column_p);
459static void get_parameter(Param *param, deparse_context *context);
460static const char *get_simple_binary_op_name(OpExpr *expr);
461static bool isSimpleNode(Node *node, Node *parentNode, int prettyFlags);
462static void appendContextKeyword(deparse_context *context, const char *str,
463 int indentBefore, int indentAfter, int indentPlus);
465static void get_rule_expr(Node *node, deparse_context *context,
466 bool showimplicit);
467static void get_rule_expr_toplevel(Node *node, deparse_context *context,
468 bool showimplicit);
469static void get_rule_list_toplevel(List *lst, deparse_context *context,
470 bool showimplicit);
471static void get_rule_expr_funccall(Node *node, deparse_context *context,
472 bool showimplicit);
473static bool looks_like_function(Node *node);
474static void get_oper_expr(OpExpr *expr, deparse_context *context);
475static void get_func_expr(FuncExpr *expr, deparse_context *context,
476 bool showimplicit);
477static void get_agg_expr(Aggref *aggref, deparse_context *context,
478 Aggref *original_aggref);
479static 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);
482static void get_agg_combine_expr(Node *node, deparse_context *context,
483 void *callback_arg);
484static void get_windowfunc_expr(WindowFunc *wfunc, deparse_context *context);
485static void get_windowfunc_expr_helper(WindowFunc *wfunc, deparse_context *context,
486 const char *funcname, const char *options,
487 bool is_json_objectagg);
488static bool get_func_sql_syntax(FuncExpr *expr, deparse_context *context);
489static void get_coercion_expr(Node *arg, deparse_context *context,
490 Oid resulttype, int32 resulttypmod,
491 Node *parentNode);
492static void get_const_expr(Const *constval, deparse_context *context,
493 int showtype);
494static void get_const_collation(Const *constval, deparse_context *context);
496static void get_json_returning(JsonReturning *returning, StringInfo buf,
497 bool json_format_by_default);
499 deparse_context *context, bool showimplicit);
503 deparse_context *context,
504 const char *funcname,
505 bool is_json_objectagg);
506static void simple_quote_literal(StringInfo buf, const char *val);
507static void get_sublink_expr(SubLink *sublink, deparse_context *context);
508static void get_tablefunc(TableFunc *tf, deparse_context *context,
509 bool showimplicit);
510static void get_from_clause(Query *query, const char *prefix,
511 deparse_context *context);
512static void get_from_clause_item(Node *jtnode, Query *query,
513 deparse_context *context);
514static void get_rte_alias(RangeTblEntry *rte, int varno, bool use_as,
515 deparse_context *context);
516static void get_column_alias_list(deparse_columns *colinfo,
517 deparse_context *context);
519 deparse_columns *colinfo,
520 deparse_context *context);
521static void get_tablesample_def(TableSampleClause *tablesample,
522 deparse_context *context);
523static void get_opclass_name(Oid opclass, Oid actual_datatype,
525static Node *processIndirection(Node *node, deparse_context *context);
526static void printSubscripts(SubscriptingRef *sbsref, deparse_context *context);
527static char *get_relation_name(Oid relid);
528static char *generate_relation_name(Oid relid, List *namespaces);
529static char *generate_qualified_relation_name(Oid relid);
530static char *generate_function_name(Oid funcid, int nargs,
531 List *argnames, Oid *argtypes,
532 bool has_variadic, bool *use_variadic_p,
533 bool inGroupBy);
534static char *generate_operator_name(Oid operid, Oid arg1, Oid arg2);
535static void add_cast_to(StringInfo buf, Oid typid);
536static char *generate_qualified_type_name(Oid typid);
537static text *string_to_text(char *str);
538static char *flatten_reloptions(Oid relid);
539static void get_reloptions(StringInfo buf, Datum reloptions);
540static void get_json_path_spec(Node *path_spec, deparse_context *context,
541 bool showimplicit);
543 deparse_context *context,
544 bool showimplicit);
546 deparse_context *context,
547 bool showimplicit,
548 bool needcomma);
549
550#define only_marker(rte) ((rte)->inh ? "" : "ONLY ")
551
552
553/* ----------
554 * pg_get_ruledef - Do it all and return a text
555 * that could be used as a statement
556 * to recreate the rule
557 * ----------
558 */
559Datum
561{
562 Oid ruleoid = PG_GETARG_OID(0);
563 int prettyFlags;
564 char *res;
565
566 prettyFlags = PRETTYFLAG_INDENT;
567
568 res = pg_get_ruledef_worker(ruleoid, prettyFlags);
569
570 if (res == NULL)
572
574}
575
576
577Datum
579{
580 Oid ruleoid = PG_GETARG_OID(0);
581 bool pretty = PG_GETARG_BOOL(1);
582 int prettyFlags;
583 char *res;
584
585 prettyFlags = GET_PRETTY_FLAGS(pretty);
586
587 res = pg_get_ruledef_worker(ruleoid, prettyFlags);
588
589 if (res == NULL)
591
593}
594
595
596static char *
597pg_get_ruledef_worker(Oid ruleoid, int prettyFlags)
598{
599 Datum args[1];
600 char nulls[1];
601 int spirc;
602 HeapTuple ruletup;
603 TupleDesc rulettc;
605
606 /*
607 * Do this first so that string is alloc'd in outer context not SPI's.
608 */
610
611 /*
612 * Connect to SPI manager
613 */
614 SPI_connect();
615
616 /*
617 * On the first call prepare the plan to lookup pg_rewrite. We read
618 * pg_rewrite over the SPI manager instead of using the syscache to be
619 * checked for read access on pg_rewrite.
620 */
621 if (plan_getrulebyoid == NULL)
622 {
623 Oid argtypes[1];
625
626 argtypes[0] = OIDOID;
627 plan = SPI_prepare(query_getrulebyoid, 1, argtypes);
628 if (plan == NULL)
629 elog(ERROR, "SPI_prepare failed for \"%s\"", query_getrulebyoid);
632 }
633
634 /*
635 * Get the pg_rewrite tuple for this rule
636 */
637 args[0] = ObjectIdGetDatum(ruleoid);
638 nulls[0] = ' ';
639 spirc = SPI_execute_plan(plan_getrulebyoid, args, nulls, true, 0);
640 if (spirc != SPI_OK_SELECT)
641 elog(ERROR, "failed to get pg_rewrite tuple for rule %u", ruleoid);
642 if (SPI_processed != 1)
643 {
644 /*
645 * There is no tuple data available here, just keep the output buffer
646 * empty.
647 */
648 }
649 else
650 {
651 /*
652 * Get the rule's definition and put it into executor's memory
653 */
654 ruletup = SPI_tuptable->vals[0];
655 rulettc = SPI_tuptable->tupdesc;
656 make_ruledef(&buf, ruletup, rulettc, prettyFlags);
657 }
658
659 /*
660 * Disconnect from SPI manager
661 */
662 if (SPI_finish() != SPI_OK_FINISH)
663 elog(ERROR, "SPI_finish failed");
664
665 if (buf.len == 0)
666 return NULL;
667
668 return buf.data;
669}
670
671
672/* ----------
673 * pg_get_viewdef - Mainly the same thing, but we
674 * only return the SELECT part of a view
675 * ----------
676 */
677Datum
679{
680 /* By OID */
681 Oid viewoid = PG_GETARG_OID(0);
682 int prettyFlags;
683 char *res;
684
685 prettyFlags = PRETTYFLAG_INDENT;
686
687 res = pg_get_viewdef_worker(viewoid, prettyFlags, WRAP_COLUMN_DEFAULT);
688
689 if (res == NULL)
691
693}
694
695
696Datum
698{
699 /* By OID */
700 Oid viewoid = PG_GETARG_OID(0);
701 bool pretty = PG_GETARG_BOOL(1);
702 int prettyFlags;
703 char *res;
704
705 prettyFlags = GET_PRETTY_FLAGS(pretty);
706
707 res = pg_get_viewdef_worker(viewoid, prettyFlags, WRAP_COLUMN_DEFAULT);
708
709 if (res == NULL)
711
713}
714
715Datum
717{
718 /* By OID */
719 Oid viewoid = PG_GETARG_OID(0);
720 int wrap = PG_GETARG_INT32(1);
721 int prettyFlags;
722 char *res;
723
724 /* calling this implies we want pretty printing */
725 prettyFlags = GET_PRETTY_FLAGS(true);
726
727 res = pg_get_viewdef_worker(viewoid, prettyFlags, wrap);
728
729 if (res == NULL)
731
733}
734
735Datum
737{
738 /* By qualified name */
739 text *viewname = PG_GETARG_TEXT_PP(0);
740 int prettyFlags;
741 RangeVar *viewrel;
742 Oid viewoid;
743 char *res;
744
745 prettyFlags = PRETTYFLAG_INDENT;
746
747 /* Look up view name. Can't lock it - we might not have privileges. */
749 viewoid = RangeVarGetRelid(viewrel, NoLock, false);
750
751 res = pg_get_viewdef_worker(viewoid, prettyFlags, WRAP_COLUMN_DEFAULT);
752
753 if (res == NULL)
755
757}
758
759
760Datum
762{
763 /* By qualified name */
764 text *viewname = PG_GETARG_TEXT_PP(0);
765 bool pretty = PG_GETARG_BOOL(1);
766 int prettyFlags;
767 RangeVar *viewrel;
768 Oid viewoid;
769 char *res;
770
771 prettyFlags = GET_PRETTY_FLAGS(pretty);
772
773 /* Look up view name. Can't lock it - we might not have privileges. */
775 viewoid = RangeVarGetRelid(viewrel, NoLock, false);
776
777 res = pg_get_viewdef_worker(viewoid, prettyFlags, WRAP_COLUMN_DEFAULT);
778
779 if (res == NULL)
781
783}
784
785/*
786 * Common code for by-OID and by-name variants of pg_get_viewdef
787 */
788static char *
789pg_get_viewdef_worker(Oid viewoid, int prettyFlags, int wrapColumn)
790{
791 Datum args[2];
792 char nulls[2];
793 int spirc;
794 HeapTuple ruletup;
795 TupleDesc rulettc;
797
798 /*
799 * Do this first so that string is alloc'd in outer context not SPI's.
800 */
802
803 /*
804 * Connect to SPI manager
805 */
806 SPI_connect();
807
808 /*
809 * On the first call prepare the plan to lookup pg_rewrite. We read
810 * pg_rewrite over the SPI manager instead of using the syscache to be
811 * checked for read access on pg_rewrite.
812 */
813 if (plan_getviewrule == NULL)
814 {
815 Oid argtypes[2];
817
818 argtypes[0] = OIDOID;
819 argtypes[1] = NAMEOID;
820 plan = SPI_prepare(query_getviewrule, 2, argtypes);
821 if (plan == NULL)
822 elog(ERROR, "SPI_prepare failed for \"%s\"", query_getviewrule);
825 }
826
827 /*
828 * Get the pg_rewrite tuple for the view's SELECT rule
829 */
830 args[0] = ObjectIdGetDatum(viewoid);
832 nulls[0] = ' ';
833 nulls[1] = ' ';
834 spirc = SPI_execute_plan(plan_getviewrule, args, nulls, true, 0);
835 if (spirc != SPI_OK_SELECT)
836 elog(ERROR, "failed to get pg_rewrite tuple for view %u", viewoid);
837 if (SPI_processed != 1)
838 {
839 /*
840 * There is no tuple data available here, just keep the output buffer
841 * empty.
842 */
843 }
844 else
845 {
846 /*
847 * Get the rule's definition and put it into executor's memory
848 */
849 ruletup = SPI_tuptable->vals[0];
850 rulettc = SPI_tuptable->tupdesc;
851 make_viewdef(&buf, ruletup, rulettc, prettyFlags, wrapColumn);
852 }
853
854 /*
855 * Disconnect from SPI manager
856 */
857 if (SPI_finish() != SPI_OK_FINISH)
858 elog(ERROR, "SPI_finish failed");
859
860 if (buf.len == 0)
861 return NULL;
862
863 return buf.data;
864}
865
866/* ----------
867 * pg_get_triggerdef - Get the definition of a trigger
868 * ----------
869 */
870Datum
872{
873 Oid trigid = PG_GETARG_OID(0);
874 char *res;
875
876 res = pg_get_triggerdef_worker(trigid, false);
877
878 if (res == NULL)
880
882}
883
884Datum
886{
887 Oid trigid = PG_GETARG_OID(0);
888 bool pretty = PG_GETARG_BOOL(1);
889 char *res;
890
891 res = pg_get_triggerdef_worker(trigid, pretty);
892
893 if (res == NULL)
895
897}
898
899static char *
900pg_get_triggerdef_worker(Oid trigid, bool pretty)
901{
902 HeapTuple ht_trig;
903 Form_pg_trigger trigrec;
905 Relation tgrel;
906 ScanKeyData skey[1];
907 SysScanDesc tgscan;
908 int findx = 0;
909 char *tgname;
910 char *tgoldtable;
911 char *tgnewtable;
912 Datum value;
913 bool isnull;
914
915 /*
916 * Fetch the pg_trigger tuple by the Oid of the trigger
917 */
918 tgrel = table_open(TriggerRelationId, AccessShareLock);
919
920 ScanKeyInit(&skey[0],
921 Anum_pg_trigger_oid,
922 BTEqualStrategyNumber, F_OIDEQ,
923 ObjectIdGetDatum(trigid));
924
925 tgscan = systable_beginscan(tgrel, TriggerOidIndexId, true,
926 NULL, 1, skey);
927
928 ht_trig = systable_getnext(tgscan);
929
930 if (!HeapTupleIsValid(ht_trig))
931 {
932 systable_endscan(tgscan);
934 return NULL;
935 }
936
937 trigrec = (Form_pg_trigger) GETSTRUCT(ht_trig);
938
939 /*
940 * Start the trigger definition. Note that the trigger's name should never
941 * be schema-qualified, but the trigger rel's name may be.
942 */
944
945 tgname = NameStr(trigrec->tgname);
946 appendStringInfo(&buf, "CREATE %sTRIGGER %s ",
947 OidIsValid(trigrec->tgconstraint) ? "CONSTRAINT " : "",
948 quote_identifier(tgname));
949
950 if (TRIGGER_FOR_BEFORE(trigrec->tgtype))
951 appendStringInfoString(&buf, "BEFORE");
952 else if (TRIGGER_FOR_AFTER(trigrec->tgtype))
953 appendStringInfoString(&buf, "AFTER");
954 else if (TRIGGER_FOR_INSTEAD(trigrec->tgtype))
955 appendStringInfoString(&buf, "INSTEAD OF");
956 else
957 elog(ERROR, "unexpected tgtype value: %d", trigrec->tgtype);
958
959 if (TRIGGER_FOR_INSERT(trigrec->tgtype))
960 {
961 appendStringInfoString(&buf, " INSERT");
962 findx++;
963 }
964 if (TRIGGER_FOR_DELETE(trigrec->tgtype))
965 {
966 if (findx > 0)
967 appendStringInfoString(&buf, " OR DELETE");
968 else
969 appendStringInfoString(&buf, " DELETE");
970 findx++;
971 }
972 if (TRIGGER_FOR_UPDATE(trigrec->tgtype))
973 {
974 if (findx > 0)
975 appendStringInfoString(&buf, " OR UPDATE");
976 else
977 appendStringInfoString(&buf, " UPDATE");
978 findx++;
979 /* tgattr is first var-width field, so OK to access directly */
980 if (trigrec->tgattr.dim1 > 0)
981 {
982 int i;
983
984 appendStringInfoString(&buf, " OF ");
985 for (i = 0; i < trigrec->tgattr.dim1; i++)
986 {
987 char *attname;
988
989 if (i > 0)
991 attname = get_attname(trigrec->tgrelid,
992 trigrec->tgattr.values[i], false);
994 }
995 }
996 }
997 if (TRIGGER_FOR_TRUNCATE(trigrec->tgtype))
998 {
999 if (findx > 0)
1000 appendStringInfoString(&buf, " OR TRUNCATE");
1001 else
1002 appendStringInfoString(&buf, " TRUNCATE");
1003 findx++;
1004 }
1005
1006 /*
1007 * In non-pretty mode, always schema-qualify the target table name for
1008 * safety. In pretty mode, schema-qualify only if not visible.
1009 */
1010 appendStringInfo(&buf, " ON %s ",
1011 pretty ?
1012 generate_relation_name(trigrec->tgrelid, NIL) :
1013 generate_qualified_relation_name(trigrec->tgrelid));
1014
1015 if (OidIsValid(trigrec->tgconstraint))
1016 {
1017 if (OidIsValid(trigrec->tgconstrrelid))
1018 appendStringInfo(&buf, "FROM %s ",
1019 generate_relation_name(trigrec->tgconstrrelid, NIL));
1020 if (!trigrec->tgdeferrable)
1021 appendStringInfoString(&buf, "NOT ");
1022 appendStringInfoString(&buf, "DEFERRABLE INITIALLY ");
1023 if (trigrec->tginitdeferred)
1024 appendStringInfoString(&buf, "DEFERRED ");
1025 else
1026 appendStringInfoString(&buf, "IMMEDIATE ");
1027 }
1028
1029 value = fastgetattr(ht_trig, Anum_pg_trigger_tgoldtable,
1030 tgrel->rd_att, &isnull);
1031 if (!isnull)
1032 tgoldtable = NameStr(*DatumGetName(value));
1033 else
1034 tgoldtable = NULL;
1035 value = fastgetattr(ht_trig, Anum_pg_trigger_tgnewtable,
1036 tgrel->rd_att, &isnull);
1037 if (!isnull)
1038 tgnewtable = NameStr(*DatumGetName(value));
1039 else
1040 tgnewtable = NULL;
1041 if (tgoldtable != NULL || tgnewtable != NULL)
1042 {
1043 appendStringInfoString(&buf, "REFERENCING ");
1044 if (tgoldtable != NULL)
1045 appendStringInfo(&buf, "OLD TABLE AS %s ",
1046 quote_identifier(tgoldtable));
1047 if (tgnewtable != NULL)
1048 appendStringInfo(&buf, "NEW TABLE AS %s ",
1049 quote_identifier(tgnewtable));
1050 }
1051
1052 if (TRIGGER_FOR_ROW(trigrec->tgtype))
1053 appendStringInfoString(&buf, "FOR EACH ROW ");
1054 else
1055 appendStringInfoString(&buf, "FOR EACH STATEMENT ");
1056
1057 /* If the trigger has a WHEN qualification, add that */
1058 value = fastgetattr(ht_trig, Anum_pg_trigger_tgqual,
1059 tgrel->rd_att, &isnull);
1060 if (!isnull)
1061 {
1062 Node *qual;
1063 char relkind;
1064 deparse_context context;
1065 deparse_namespace dpns;
1066 RangeTblEntry *oldrte;
1067 RangeTblEntry *newrte;
1068
1069 appendStringInfoString(&buf, "WHEN (");
1070
1072
1073 relkind = get_rel_relkind(trigrec->tgrelid);
1074
1075 /* Build minimal OLD and NEW RTEs for the rel */
1076 oldrte = makeNode(RangeTblEntry);
1077 oldrte->rtekind = RTE_RELATION;
1078 oldrte->relid = trigrec->tgrelid;
1079 oldrte->relkind = relkind;
1080 oldrte->rellockmode = AccessShareLock;
1081 oldrte->alias = makeAlias("old", NIL);
1082 oldrte->eref = oldrte->alias;
1083 oldrte->lateral = false;
1084 oldrte->inh = false;
1085 oldrte->inFromCl = true;
1086
1087 newrte = makeNode(RangeTblEntry);
1088 newrte->rtekind = RTE_RELATION;
1089 newrte->relid = trigrec->tgrelid;
1090 newrte->relkind = relkind;
1091 newrte->rellockmode = AccessShareLock;
1092 newrte->alias = makeAlias("new", NIL);
1093 newrte->eref = newrte->alias;
1094 newrte->lateral = false;
1095 newrte->inh = false;
1096 newrte->inFromCl = true;
1097
1098 /* Build two-element rtable */
1099 memset(&dpns, 0, sizeof(dpns));
1100 dpns.rtable = list_make2(oldrte, newrte);
1101 dpns.subplans = NIL;
1102 dpns.ctes = NIL;
1103 dpns.appendrels = NULL;
1104 set_rtable_names(&dpns, NIL, NULL);
1106
1107 /* Set up context with one-deep namespace stack */
1108 context.buf = &buf;
1109 context.namespaces = list_make1(&dpns);
1110 context.resultDesc = NULL;
1111 context.targetList = NIL;
1112 context.windowClause = NIL;
1113 context.varprefix = true;
1114 context.prettyFlags = GET_PRETTY_FLAGS(pretty);
1116 context.indentLevel = PRETTYINDENT_STD;
1117 context.colNamesVisible = true;
1118 context.inGroupBy = false;
1119 context.varInOrderBy = false;
1120 context.appendparents = NULL;
1121
1122 get_rule_expr(qual, &context, false);
1123
1125 }
1126
1127 appendStringInfo(&buf, "EXECUTE FUNCTION %s(",
1128 generate_function_name(trigrec->tgfoid, 0,
1129 NIL, NULL,
1130 false, NULL, false));
1131
1132 if (trigrec->tgnargs > 0)
1133 {
1134 char *p;
1135 int i;
1136
1137 value = fastgetattr(ht_trig, Anum_pg_trigger_tgargs,
1138 tgrel->rd_att, &isnull);
1139 if (isnull)
1140 elog(ERROR, "tgargs is null for trigger %u", trigid);
1141 p = (char *) VARDATA_ANY(DatumGetByteaPP(value));
1142 for (i = 0; i < trigrec->tgnargs; i++)
1143 {
1144 if (i > 0)
1147 /* advance p to next string embedded in tgargs */
1148 while (*p)
1149 p++;
1150 p++;
1151 }
1152 }
1153
1154 /* We deliberately do not put semi-colon at end */
1156
1157 /* Clean up */
1158 systable_endscan(tgscan);
1159
1161
1162 return buf.data;
1163}
1164
1165/* ----------
1166 * pg_get_indexdef - Get the definition of an index
1167 *
1168 * In the extended version, there is a colno argument as well as pretty bool.
1169 * if colno == 0, we want a complete index definition.
1170 * if colno > 0, we only want the Nth index key's variable or expression.
1171 *
1172 * Note that the SQL-function versions of this omit any info about the
1173 * index tablespace; this is intentional because pg_dump wants it that way.
1174 * However pg_get_indexdef_string() includes the index tablespace.
1175 * ----------
1176 */
1177Datum
1179{
1180 Oid indexrelid = PG_GETARG_OID(0);
1181 int prettyFlags;
1182 char *res;
1183
1184 prettyFlags = PRETTYFLAG_INDENT;
1185
1186 res = pg_get_indexdef_worker(indexrelid, 0, NULL,
1187 false, false,
1188 false, false,
1189 prettyFlags, true);
1190
1191 if (res == NULL)
1193
1195}
1196
1197Datum
1199{
1200 Oid indexrelid = PG_GETARG_OID(0);
1201 int32 colno = PG_GETARG_INT32(1);
1202 bool pretty = PG_GETARG_BOOL(2);
1203 int prettyFlags;
1204 char *res;
1205
1206 prettyFlags = GET_PRETTY_FLAGS(pretty);
1207
1208 res = pg_get_indexdef_worker(indexrelid, colno, NULL,
1209 colno != 0, false,
1210 false, false,
1211 prettyFlags, true);
1212
1213 if (res == NULL)
1215
1217}
1218
1219/*
1220 * Internal version for use by ALTER TABLE.
1221 * Includes a tablespace clause in the result.
1222 * Returns a palloc'd C string; no pretty-printing.
1223 */
1224char *
1226{
1227 return pg_get_indexdef_worker(indexrelid, 0, NULL,
1228 false, false,
1229 true, true,
1230 0, false);
1231}
1232
1233/* Internal version that just reports the key-column definitions */
1234char *
1235pg_get_indexdef_columns(Oid indexrelid, bool pretty)
1236{
1237 int prettyFlags;
1238
1239 prettyFlags = GET_PRETTY_FLAGS(pretty);
1240
1241 return pg_get_indexdef_worker(indexrelid, 0, NULL,
1242 true, true,
1243 false, false,
1244 prettyFlags, false);
1245}
1246
1247/* Internal version, extensible with flags to control its behavior */
1248char *
1250{
1251 bool pretty = ((flags & RULE_INDEXDEF_PRETTY) != 0);
1252 bool keys_only = ((flags & RULE_INDEXDEF_KEYS_ONLY) != 0);
1253 int prettyFlags;
1254
1255 prettyFlags = GET_PRETTY_FLAGS(pretty);
1256
1257 return pg_get_indexdef_worker(indexrelid, 0, NULL,
1258 true, keys_only,
1259 false, false,
1260 prettyFlags, false);
1261}
1262
1263/*
1264 * Internal workhorse to decompile an index definition.
1265 *
1266 * This is now used for exclusion constraints as well: if excludeOps is not
1267 * NULL then it points to an array of exclusion operator OIDs.
1268 */
1269static char *
1270pg_get_indexdef_worker(Oid indexrelid, int colno,
1271 const Oid *excludeOps,
1272 bool attrsOnly, bool keysOnly,
1273 bool showTblSpc, bool inherits,
1274 int prettyFlags, bool missing_ok)
1275{
1276 /* might want a separate isConstraint parameter later */
1277 bool isConstraint = (excludeOps != NULL);
1278 HeapTuple ht_idx;
1279 HeapTuple ht_idxrel;
1280 HeapTuple ht_am;
1281 Form_pg_index idxrec;
1282 Form_pg_class idxrelrec;
1283 Form_pg_am amrec;
1284 IndexAmRoutine *amroutine;
1285 List *indexprs;
1286 ListCell *indexpr_item;
1287 List *context;
1288 Oid indrelid;
1289 int keyno;
1290 Datum indcollDatum;
1291 Datum indclassDatum;
1292 Datum indoptionDatum;
1293 oidvector *indcollation;
1294 oidvector *indclass;
1295 int2vector *indoption;
1297 char *str;
1298 char *sep;
1299
1300 /*
1301 * Fetch the pg_index tuple by the Oid of the index
1302 */
1303 ht_idx = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexrelid));
1304 if (!HeapTupleIsValid(ht_idx))
1305 {
1306 if (missing_ok)
1307 return NULL;
1308 elog(ERROR, "cache lookup failed for index %u", indexrelid);
1309 }
1310 idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
1311
1312 indrelid = idxrec->indrelid;
1313 Assert(indexrelid == idxrec->indexrelid);
1314
1315 /* Must get indcollation, indclass, and indoption the hard way */
1316 indcollDatum = SysCacheGetAttrNotNull(INDEXRELID, ht_idx,
1317 Anum_pg_index_indcollation);
1318 indcollation = (oidvector *) DatumGetPointer(indcollDatum);
1319
1320 indclassDatum = SysCacheGetAttrNotNull(INDEXRELID, ht_idx,
1321 Anum_pg_index_indclass);
1322 indclass = (oidvector *) DatumGetPointer(indclassDatum);
1323
1324 indoptionDatum = SysCacheGetAttrNotNull(INDEXRELID, ht_idx,
1325 Anum_pg_index_indoption);
1326 indoption = (int2vector *) DatumGetPointer(indoptionDatum);
1327
1328 /*
1329 * Fetch the pg_class tuple of the index relation
1330 */
1331 ht_idxrel = SearchSysCache1(RELOID, ObjectIdGetDatum(indexrelid));
1332 if (!HeapTupleIsValid(ht_idxrel))
1333 elog(ERROR, "cache lookup failed for relation %u", indexrelid);
1334 idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
1335
1336 /*
1337 * Fetch the pg_am tuple of the index' access method
1338 */
1339 ht_am = SearchSysCache1(AMOID, ObjectIdGetDatum(idxrelrec->relam));
1340 if (!HeapTupleIsValid(ht_am))
1341 elog(ERROR, "cache lookup failed for access method %u",
1342 idxrelrec->relam);
1343 amrec = (Form_pg_am) GETSTRUCT(ht_am);
1344
1345 /* Fetch the index AM's API struct */
1346 amroutine = GetIndexAmRoutine(amrec->amhandler);
1347
1348 /*
1349 * Get the index expressions, if any. (NOTE: we do not use the relcache
1350 * versions of the expressions and predicate, because we want to display
1351 * non-const-folded expressions.)
1352 */
1353 if (!heap_attisnull(ht_idx, Anum_pg_index_indexprs, NULL))
1354 {
1355 Datum exprsDatum;
1356 char *exprsString;
1357
1358 exprsDatum = SysCacheGetAttrNotNull(INDEXRELID, ht_idx,
1359 Anum_pg_index_indexprs);
1360 exprsString = TextDatumGetCString(exprsDatum);
1361 indexprs = (List *) stringToNode(exprsString);
1362 pfree(exprsString);
1363 }
1364 else
1365 indexprs = NIL;
1366
1367 indexpr_item = list_head(indexprs);
1368
1369 context = deparse_context_for(get_relation_name(indrelid), indrelid);
1370
1371 /*
1372 * Start the index definition. Note that the index's name should never be
1373 * schema-qualified, but the indexed rel's name may be.
1374 */
1376
1377 if (!attrsOnly)
1378 {
1379 if (!isConstraint)
1380 appendStringInfo(&buf, "CREATE %sINDEX %s ON %s%s USING %s (",
1381 idxrec->indisunique ? "UNIQUE " : "",
1382 quote_identifier(NameStr(idxrelrec->relname)),
1383 idxrelrec->relkind == RELKIND_PARTITIONED_INDEX
1384 && !inherits ? "ONLY " : "",
1385 (prettyFlags & PRETTYFLAG_SCHEMA) ?
1386 generate_relation_name(indrelid, NIL) :
1388 quote_identifier(NameStr(amrec->amname)));
1389 else /* currently, must be EXCLUDE constraint */
1390 appendStringInfo(&buf, "EXCLUDE USING %s (",
1391 quote_identifier(NameStr(amrec->amname)));
1392 }
1393
1394 /*
1395 * Report the indexed attributes
1396 */
1397 sep = "";
1398 for (keyno = 0; keyno < idxrec->indnatts; keyno++)
1399 {
1400 AttrNumber attnum = idxrec->indkey.values[keyno];
1401 Oid keycoltype;
1402 Oid keycolcollation;
1403
1404 /*
1405 * Ignore non-key attributes if told to.
1406 */
1407 if (keysOnly && keyno >= idxrec->indnkeyatts)
1408 break;
1409
1410 /* Otherwise, print INCLUDE to divide key and non-key attrs. */
1411 if (!colno && keyno == idxrec->indnkeyatts)
1412 {
1413 appendStringInfoString(&buf, ") INCLUDE (");
1414 sep = "";
1415 }
1416
1417 if (!colno)
1419 sep = ", ";
1420
1421 if (attnum != 0)
1422 {
1423 /* Simple index column */
1424 char *attname;
1425 int32 keycoltypmod;
1426
1427 attname = get_attname(indrelid, attnum, false);
1428 if (!colno || colno == keyno + 1)
1430 get_atttypetypmodcoll(indrelid, attnum,
1431 &keycoltype, &keycoltypmod,
1432 &keycolcollation);
1433 }
1434 else
1435 {
1436 /* expressional index */
1437 Node *indexkey;
1438
1439 if (indexpr_item == NULL)
1440 elog(ERROR, "too few entries in indexprs list");
1441 indexkey = (Node *) lfirst(indexpr_item);
1442 indexpr_item = lnext(indexprs, indexpr_item);
1443 /* Deparse */
1444 str = deparse_expression_pretty(indexkey, context, false, false,
1445 prettyFlags, 0);
1446 if (!colno || colno == keyno + 1)
1447 {
1448 /* Need parens if it's not a bare function call */
1449 if (looks_like_function(indexkey))
1451 else
1452 appendStringInfo(&buf, "(%s)", str);
1453 }
1454 keycoltype = exprType(indexkey);
1455 keycolcollation = exprCollation(indexkey);
1456 }
1457
1458 /* Print additional decoration for (selected) key columns */
1459 if (!attrsOnly && keyno < idxrec->indnkeyatts &&
1460 (!colno || colno == keyno + 1))
1461 {
1462 int16 opt = indoption->values[keyno];
1463 Oid indcoll = indcollation->values[keyno];
1464 Datum attoptions = get_attoptions(indexrelid, keyno + 1);
1465 bool has_options = attoptions != (Datum) 0;
1466
1467 /* Add collation, if not default for column */
1468 if (OidIsValid(indcoll) && indcoll != keycolcollation)
1469 appendStringInfo(&buf, " COLLATE %s",
1470 generate_collation_name((indcoll)));
1471
1472 /* Add the operator class name, if not default */
1473 get_opclass_name(indclass->values[keyno],
1474 has_options ? InvalidOid : keycoltype, &buf);
1475
1476 if (has_options)
1477 {
1479 get_reloptions(&buf, attoptions);
1481 }
1482
1483 /* Add options if relevant */
1484 if (amroutine->amcanorder)
1485 {
1486 /* if it supports sort ordering, report DESC and NULLS opts */
1487 if (opt & INDOPTION_DESC)
1488 {
1489 appendStringInfoString(&buf, " DESC");
1490 /* NULLS FIRST is the default in this case */
1491 if (!(opt & INDOPTION_NULLS_FIRST))
1492 appendStringInfoString(&buf, " NULLS LAST");
1493 }
1494 else
1495 {
1496 if (opt & INDOPTION_NULLS_FIRST)
1497 appendStringInfoString(&buf, " NULLS FIRST");
1498 }
1499 }
1500
1501 /* Add the exclusion operator if relevant */
1502 if (excludeOps != NULL)
1503 appendStringInfo(&buf, " WITH %s",
1504 generate_operator_name(excludeOps[keyno],
1505 keycoltype,
1506 keycoltype));
1507 }
1508 }
1509
1510 if (!attrsOnly)
1511 {
1513
1514 if (idxrec->indnullsnotdistinct)
1515 appendStringInfoString(&buf, " NULLS NOT DISTINCT");
1516
1517 /*
1518 * If it has options, append "WITH (options)"
1519 */
1520 str = flatten_reloptions(indexrelid);
1521 if (str)
1522 {
1523 appendStringInfo(&buf, " WITH (%s)", str);
1524 pfree(str);
1525 }
1526
1527 /*
1528 * Print tablespace, but only if requested
1529 */
1530 if (showTblSpc)
1531 {
1532 Oid tblspc;
1533
1534 tblspc = get_rel_tablespace(indexrelid);
1535 if (OidIsValid(tblspc))
1536 {
1537 if (isConstraint)
1538 appendStringInfoString(&buf, " USING INDEX");
1539 appendStringInfo(&buf, " TABLESPACE %s",
1541 }
1542 }
1543
1544 /*
1545 * If it's a partial index, decompile and append the predicate
1546 */
1547 if (!heap_attisnull(ht_idx, Anum_pg_index_indpred, NULL))
1548 {
1549 Node *node;
1550 Datum predDatum;
1551 char *predString;
1552
1553 /* Convert text string to node tree */
1554 predDatum = SysCacheGetAttrNotNull(INDEXRELID, ht_idx,
1555 Anum_pg_index_indpred);
1556 predString = TextDatumGetCString(predDatum);
1557 node = (Node *) stringToNode(predString);
1558 pfree(predString);
1559
1560 /* Deparse */
1561 str = deparse_expression_pretty(node, context, false, false,
1562 prettyFlags, 0);
1563 if (isConstraint)
1564 appendStringInfo(&buf, " WHERE (%s)", str);
1565 else
1566 appendStringInfo(&buf, " WHERE %s", str);
1567 }
1568 }
1569
1570 /* Clean up */
1571 ReleaseSysCache(ht_idx);
1572 ReleaseSysCache(ht_idxrel);
1573 ReleaseSysCache(ht_am);
1574
1575 return buf.data;
1576}
1577
1578/* ----------
1579 * pg_get_querydef
1580 *
1581 * Public entry point to deparse one query parsetree.
1582 * The pretty flags are determined by GET_PRETTY_FLAGS(pretty).
1583 *
1584 * The result is a palloc'd C string.
1585 * ----------
1586 */
1587char *
1588pg_get_querydef(Query *query, bool pretty)
1589{
1591 int prettyFlags;
1592
1593 prettyFlags = GET_PRETTY_FLAGS(pretty);
1594
1596
1597 get_query_def(query, &buf, NIL, NULL, true,
1598 prettyFlags, WRAP_COLUMN_DEFAULT, 0);
1599
1600 return buf.data;
1601}
1602
1603/*
1604 * pg_get_statisticsobjdef
1605 * Get the definition of an extended statistics object
1606 */
1607Datum
1609{
1610 Oid statextid = PG_GETARG_OID(0);
1611 char *res;
1612
1613 res = pg_get_statisticsobj_worker(statextid, false, true);
1614
1615 if (res == NULL)
1617
1619}
1620
1621/*
1622 * Internal version for use by ALTER TABLE.
1623 * Returns a palloc'd C string; no pretty-printing.
1624 */
1625char *
1627{
1628 return pg_get_statisticsobj_worker(statextid, false, false);
1629}
1630
1631/*
1632 * pg_get_statisticsobjdef_columns
1633 * Get columns and expressions for an extended statistics object
1634 */
1635Datum
1637{
1638 Oid statextid = PG_GETARG_OID(0);
1639 char *res;
1640
1641 res = pg_get_statisticsobj_worker(statextid, true, true);
1642
1643 if (res == NULL)
1645
1647}
1648
1649/*
1650 * Internal workhorse to decompile an extended statistics object.
1651 */
1652static char *
1653pg_get_statisticsobj_worker(Oid statextid, bool columns_only, bool missing_ok)
1654{
1655 Form_pg_statistic_ext statextrec;
1656 HeapTuple statexttup;
1658 int colno;
1659 char *nsp;
1660 ArrayType *arr;
1661 char *enabled;
1662 Datum datum;
1663 bool ndistinct_enabled;
1664 bool dependencies_enabled;
1665 bool mcv_enabled;
1666 int i;
1667 List *context;
1668 ListCell *lc;
1669 List *exprs = NIL;
1670 bool has_exprs;
1671 int ncolumns;
1672
1673 statexttup = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(statextid));
1674
1675 if (!HeapTupleIsValid(statexttup))
1676 {
1677 if (missing_ok)
1678 return NULL;
1679 elog(ERROR, "cache lookup failed for statistics object %u", statextid);
1680 }
1681
1682 /* has the statistics expressions? */
1683 has_exprs = !heap_attisnull(statexttup, Anum_pg_statistic_ext_stxexprs, NULL);
1684
1685 statextrec = (Form_pg_statistic_ext) GETSTRUCT(statexttup);
1686
1687 /*
1688 * Get the statistics expressions, if any. (NOTE: we do not use the
1689 * relcache versions of the expressions, because we want to display
1690 * non-const-folded expressions.)
1691 */
1692 if (has_exprs)
1693 {
1694 Datum exprsDatum;
1695 char *exprsString;
1696
1697 exprsDatum = SysCacheGetAttrNotNull(STATEXTOID, statexttup,
1698 Anum_pg_statistic_ext_stxexprs);
1699 exprsString = TextDatumGetCString(exprsDatum);
1700 exprs = (List *) stringToNode(exprsString);
1701 pfree(exprsString);
1702 }
1703 else
1704 exprs = NIL;
1705
1706 /* count the number of columns (attributes and expressions) */
1707 ncolumns = statextrec->stxkeys.dim1 + list_length(exprs);
1708
1710
1711 if (!columns_only)
1712 {
1713 nsp = get_namespace_name_or_temp(statextrec->stxnamespace);
1714 appendStringInfo(&buf, "CREATE STATISTICS %s",
1716 NameStr(statextrec->stxname)));
1717
1718 /*
1719 * Decode the stxkind column so that we know which stats types to
1720 * print.
1721 */
1722 datum = SysCacheGetAttrNotNull(STATEXTOID, statexttup,
1723 Anum_pg_statistic_ext_stxkind);
1724 arr = DatumGetArrayTypeP(datum);
1725 if (ARR_NDIM(arr) != 1 ||
1726 ARR_HASNULL(arr) ||
1727 ARR_ELEMTYPE(arr) != CHAROID)
1728 elog(ERROR, "stxkind is not a 1-D char array");
1729 enabled = (char *) ARR_DATA_PTR(arr);
1730
1731 ndistinct_enabled = false;
1732 dependencies_enabled = false;
1733 mcv_enabled = false;
1734
1735 for (i = 0; i < ARR_DIMS(arr)[0]; i++)
1736 {
1737 if (enabled[i] == STATS_EXT_NDISTINCT)
1738 ndistinct_enabled = true;
1739 else if (enabled[i] == STATS_EXT_DEPENDENCIES)
1740 dependencies_enabled = true;
1741 else if (enabled[i] == STATS_EXT_MCV)
1742 mcv_enabled = true;
1743
1744 /* ignore STATS_EXT_EXPRESSIONS (it's built automatically) */
1745 }
1746
1747 /*
1748 * If any option is disabled, then we'll need to append the types
1749 * clause to show which options are enabled. We omit the types clause
1750 * on purpose when all options are enabled, so a pg_dump/pg_restore
1751 * will create all statistics types on a newer postgres version, if
1752 * the statistics had all options enabled on the original version.
1753 *
1754 * But if the statistics is defined on just a single column, it has to
1755 * be an expression statistics. In that case we don't need to specify
1756 * kinds.
1757 */
1758 if ((!ndistinct_enabled || !dependencies_enabled || !mcv_enabled) &&
1759 (ncolumns > 1))
1760 {
1761 bool gotone = false;
1762
1764
1765 if (ndistinct_enabled)
1766 {
1767 appendStringInfoString(&buf, "ndistinct");
1768 gotone = true;
1769 }
1770
1771 if (dependencies_enabled)
1772 {
1773 appendStringInfo(&buf, "%sdependencies", gotone ? ", " : "");
1774 gotone = true;
1775 }
1776
1777 if (mcv_enabled)
1778 appendStringInfo(&buf, "%smcv", gotone ? ", " : "");
1779
1781 }
1782
1783 appendStringInfoString(&buf, " ON ");
1784 }
1785
1786 /* decode simple column references */
1787 for (colno = 0; colno < statextrec->stxkeys.dim1; colno++)
1788 {
1789 AttrNumber attnum = statextrec->stxkeys.values[colno];
1790 char *attname;
1791
1792 if (colno > 0)
1794
1795 attname = get_attname(statextrec->stxrelid, attnum, false);
1796
1798 }
1799
1800 context = deparse_context_for(get_relation_name(statextrec->stxrelid),
1801 statextrec->stxrelid);
1802
1803 foreach(lc, exprs)
1804 {
1805 Node *expr = (Node *) lfirst(lc);
1806 char *str;
1807 int prettyFlags = PRETTYFLAG_PAREN;
1808
1809 str = deparse_expression_pretty(expr, context, false, false,
1810 prettyFlags, 0);
1811
1812 if (colno > 0)
1814
1815 /* Need parens if it's not a bare function call */
1816 if (looks_like_function(expr))
1818 else
1819 appendStringInfo(&buf, "(%s)", str);
1820
1821 colno++;
1822 }
1823
1824 if (!columns_only)
1825 appendStringInfo(&buf, " FROM %s",
1826 generate_relation_name(statextrec->stxrelid, NIL));
1827
1828 ReleaseSysCache(statexttup);
1829
1830 return buf.data;
1831}
1832
1833/*
1834 * Generate text array of expressions for statistics object.
1835 */
1836Datum
1838{
1839 Oid statextid = PG_GETARG_OID(0);
1840 Form_pg_statistic_ext statextrec;
1841 HeapTuple statexttup;
1842 Datum datum;
1843 List *context;
1844 ListCell *lc;
1845 List *exprs = NIL;
1846 bool has_exprs;
1847 char *tmp;
1848 ArrayBuildState *astate = NULL;
1849
1850 statexttup = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(statextid));
1851
1852 if (!HeapTupleIsValid(statexttup))
1854
1855 /* Does the stats object have expressions? */
1856 has_exprs = !heap_attisnull(statexttup, Anum_pg_statistic_ext_stxexprs, NULL);
1857
1858 /* no expressions? we're done */
1859 if (!has_exprs)
1860 {
1861 ReleaseSysCache(statexttup);
1863 }
1864
1865 statextrec = (Form_pg_statistic_ext) GETSTRUCT(statexttup);
1866
1867 /*
1868 * Get the statistics expressions, and deparse them into text values.
1869 */
1870 datum = SysCacheGetAttrNotNull(STATEXTOID, statexttup,
1871 Anum_pg_statistic_ext_stxexprs);
1872 tmp = TextDatumGetCString(datum);
1873 exprs = (List *) stringToNode(tmp);
1874 pfree(tmp);
1875
1876 context = deparse_context_for(get_relation_name(statextrec->stxrelid),
1877 statextrec->stxrelid);
1878
1879 foreach(lc, exprs)
1880 {
1881 Node *expr = (Node *) lfirst(lc);
1882 char *str;
1883 int prettyFlags = PRETTYFLAG_INDENT;
1884
1885 str = deparse_expression_pretty(expr, context, false, false,
1886 prettyFlags, 0);
1887
1888 astate = accumArrayResult(astate,
1890 false,
1891 TEXTOID,
1893 }
1894
1895 ReleaseSysCache(statexttup);
1896
1898}
1899
1900/*
1901 * pg_get_partkeydef
1902 *
1903 * Returns the partition key specification, ie, the following:
1904 *
1905 * { RANGE | LIST | HASH } (column opt_collation opt_opclass [, ...])
1906 */
1907Datum
1909{
1910 Oid relid = PG_GETARG_OID(0);
1911 char *res;
1912
1913 res = pg_get_partkeydef_worker(relid, PRETTYFLAG_INDENT, false, true);
1914
1915 if (res == NULL)
1917
1919}
1920
1921/* Internal version that just reports the column definitions */
1922char *
1924{
1925 int prettyFlags;
1926
1927 prettyFlags = GET_PRETTY_FLAGS(pretty);
1928
1929 return pg_get_partkeydef_worker(relid, prettyFlags, true, false);
1930}
1931
1932/*
1933 * Internal workhorse to decompile a partition key definition.
1934 */
1935static char *
1936pg_get_partkeydef_worker(Oid relid, int prettyFlags,
1937 bool attrsOnly, bool missing_ok)
1938{
1940 HeapTuple tuple;
1941 oidvector *partclass;
1942 oidvector *partcollation;
1943 List *partexprs;
1944 ListCell *partexpr_item;
1945 List *context;
1946 Datum datum;
1948 int keyno;
1949 char *str;
1950 char *sep;
1951
1952 tuple = SearchSysCache1(PARTRELID, ObjectIdGetDatum(relid));
1953 if (!HeapTupleIsValid(tuple))
1954 {
1955 if (missing_ok)
1956 return NULL;
1957 elog(ERROR, "cache lookup failed for partition key of %u", relid);
1958 }
1959
1960 form = (Form_pg_partitioned_table) GETSTRUCT(tuple);
1961
1962 Assert(form->partrelid == relid);
1963
1964 /* Must get partclass and partcollation the hard way */
1965 datum = SysCacheGetAttrNotNull(PARTRELID, tuple,
1966 Anum_pg_partitioned_table_partclass);
1967 partclass = (oidvector *) DatumGetPointer(datum);
1968
1969 datum = SysCacheGetAttrNotNull(PARTRELID, tuple,
1970 Anum_pg_partitioned_table_partcollation);
1971 partcollation = (oidvector *) DatumGetPointer(datum);
1972
1973
1974 /*
1975 * Get the expressions, if any. (NOTE: we do not use the relcache
1976 * versions of the expressions, because we want to display
1977 * non-const-folded expressions.)
1978 */
1979 if (!heap_attisnull(tuple, Anum_pg_partitioned_table_partexprs, NULL))
1980 {
1981 Datum exprsDatum;
1982 char *exprsString;
1983
1984 exprsDatum = SysCacheGetAttrNotNull(PARTRELID, tuple,
1985 Anum_pg_partitioned_table_partexprs);
1986 exprsString = TextDatumGetCString(exprsDatum);
1987 partexprs = (List *) stringToNode(exprsString);
1988
1989 if (!IsA(partexprs, List))
1990 elog(ERROR, "unexpected node type found in partexprs: %d",
1991 (int) nodeTag(partexprs));
1992
1993 pfree(exprsString);
1994 }
1995 else
1996 partexprs = NIL;
1997
1998 partexpr_item = list_head(partexprs);
1999 context = deparse_context_for(get_relation_name(relid), relid);
2000
2002
2003 switch (form->partstrat)
2004 {
2006 if (!attrsOnly)
2007 appendStringInfoString(&buf, "HASH");
2008 break;
2010 if (!attrsOnly)
2011 appendStringInfoString(&buf, "LIST");
2012 break;
2014 if (!attrsOnly)
2015 appendStringInfoString(&buf, "RANGE");
2016 break;
2017 default:
2018 elog(ERROR, "unexpected partition strategy: %d",
2019 (int) form->partstrat);
2020 }
2021
2022 if (!attrsOnly)
2024 sep = "";
2025 for (keyno = 0; keyno < form->partnatts; keyno++)
2026 {
2027 AttrNumber attnum = form->partattrs.values[keyno];
2028 Oid keycoltype;
2029 Oid keycolcollation;
2030 Oid partcoll;
2031
2033 sep = ", ";
2034 if (attnum != 0)
2035 {
2036 /* Simple attribute reference */
2037 char *attname;
2038 int32 keycoltypmod;
2039
2040 attname = get_attname(relid, attnum, false);
2043 &keycoltype, &keycoltypmod,
2044 &keycolcollation);
2045 }
2046 else
2047 {
2048 /* Expression */
2049 Node *partkey;
2050
2051 if (partexpr_item == NULL)
2052 elog(ERROR, "too few entries in partexprs list");
2053 partkey = (Node *) lfirst(partexpr_item);
2054 partexpr_item = lnext(partexprs, partexpr_item);
2055
2056 /* Deparse */
2057 str = deparse_expression_pretty(partkey, context, false, false,
2058 prettyFlags, 0);
2059 /* Need parens if it's not a bare function call */
2060 if (looks_like_function(partkey))
2062 else
2063 appendStringInfo(&buf, "(%s)", str);
2064
2065 keycoltype = exprType(partkey);
2066 keycolcollation = exprCollation(partkey);
2067 }
2068
2069 /* Add collation, if not default for column */
2070 partcoll = partcollation->values[keyno];
2071 if (!attrsOnly && OidIsValid(partcoll) && partcoll != keycolcollation)
2072 appendStringInfo(&buf, " COLLATE %s",
2073 generate_collation_name((partcoll)));
2074
2075 /* Add the operator class name, if not default */
2076 if (!attrsOnly)
2077 get_opclass_name(partclass->values[keyno], keycoltype, &buf);
2078 }
2079
2080 if (!attrsOnly)
2082
2083 /* Clean up */
2084 ReleaseSysCache(tuple);
2085
2086 return buf.data;
2087}
2088
2089/*
2090 * pg_get_partition_constraintdef
2091 *
2092 * Returns partition constraint expression as a string for the input relation
2093 */
2094Datum
2096{
2097 Oid relationId = PG_GETARG_OID(0);
2098 Expr *constr_expr;
2099 int prettyFlags;
2100 List *context;
2101 char *consrc;
2102
2103 constr_expr = get_partition_qual_relid(relationId);
2104
2105 /* Quick exit if no partition constraint */
2106 if (constr_expr == NULL)
2108
2109 /*
2110 * Deparse and return the constraint expression.
2111 */
2112 prettyFlags = PRETTYFLAG_INDENT;
2113 context = deparse_context_for(get_relation_name(relationId), relationId);
2114 consrc = deparse_expression_pretty((Node *) constr_expr, context, false,
2115 false, prettyFlags, 0);
2116
2118}
2119
2120/*
2121 * pg_get_partconstrdef_string
2122 *
2123 * Returns the partition constraint as a C-string for the input relation, with
2124 * the given alias. No pretty-printing.
2125 */
2126char *
2127pg_get_partconstrdef_string(Oid partitionId, char *aliasname)
2128{
2129 Expr *constr_expr;
2130 List *context;
2131
2132 constr_expr = get_partition_qual_relid(partitionId);
2133 context = deparse_context_for(aliasname, partitionId);
2134
2135 return deparse_expression((Node *) constr_expr, context, true, false);
2136}
2137
2138/*
2139 * pg_get_constraintdef
2140 *
2141 * Returns the definition for the constraint, ie, everything that needs to
2142 * appear after "ALTER TABLE ... ADD CONSTRAINT <constraintname>".
2143 */
2144Datum
2146{
2147 Oid constraintId = PG_GETARG_OID(0);
2148 int prettyFlags;
2149 char *res;
2150
2151 prettyFlags = PRETTYFLAG_INDENT;
2152
2153 res = pg_get_constraintdef_worker(constraintId, false, prettyFlags, true);
2154
2155 if (res == NULL)
2157
2159}
2160
2161Datum
2163{
2164 Oid constraintId = PG_GETARG_OID(0);
2165 bool pretty = PG_GETARG_BOOL(1);
2166 int prettyFlags;
2167 char *res;
2168
2169 prettyFlags = GET_PRETTY_FLAGS(pretty);
2170
2171 res = pg_get_constraintdef_worker(constraintId, false, prettyFlags, true);
2172
2173 if (res == NULL)
2175
2177}
2178
2179/*
2180 * Internal version that returns a full ALTER TABLE ... ADD CONSTRAINT command
2181 */
2182char *
2184{
2185 return pg_get_constraintdef_worker(constraintId, true, 0, false);
2186}
2187
2188/*
2189 * As of 9.4, we now use an MVCC snapshot for this.
2190 */
2191static char *
2192pg_get_constraintdef_worker(Oid constraintId, bool fullCommand,
2193 int prettyFlags, bool missing_ok)
2194{
2195 HeapTuple tup;
2196 Form_pg_constraint conForm;
2198 SysScanDesc scandesc;
2199 ScanKeyData scankey[1];
2201 Relation relation = table_open(ConstraintRelationId, AccessShareLock);
2202
2203 ScanKeyInit(&scankey[0],
2204 Anum_pg_constraint_oid,
2205 BTEqualStrategyNumber, F_OIDEQ,
2206 ObjectIdGetDatum(constraintId));
2207
2208 scandesc = systable_beginscan(relation,
2209 ConstraintOidIndexId,
2210 true,
2211 snapshot,
2212 1,
2213 scankey);
2214
2215 /*
2216 * We later use the tuple with SysCacheGetAttr() as if we had obtained it
2217 * via SearchSysCache, which works fine.
2218 */
2219 tup = systable_getnext(scandesc);
2220
2221 UnregisterSnapshot(snapshot);
2222
2223 if (!HeapTupleIsValid(tup))
2224 {
2225 if (missing_ok)
2226 {
2227 systable_endscan(scandesc);
2228 table_close(relation, AccessShareLock);
2229 return NULL;
2230 }
2231 elog(ERROR, "could not find tuple for constraint %u", constraintId);
2232 }
2233
2234 conForm = (Form_pg_constraint) GETSTRUCT(tup);
2235
2237
2238 if (fullCommand)
2239 {
2240 if (OidIsValid(conForm->conrelid))
2241 {
2242 /*
2243 * Currently, callers want ALTER TABLE (without ONLY) for CHECK
2244 * constraints, and other types of constraints don't inherit
2245 * anyway so it doesn't matter whether we say ONLY or not. Someday
2246 * we might need to let callers specify whether to put ONLY in the
2247 * command.
2248 */
2249 appendStringInfo(&buf, "ALTER TABLE %s ADD CONSTRAINT %s ",
2250 generate_qualified_relation_name(conForm->conrelid),
2251 quote_identifier(NameStr(conForm->conname)));
2252 }
2253 else
2254 {
2255 /* Must be a domain constraint */
2256 Assert(OidIsValid(conForm->contypid));
2257 appendStringInfo(&buf, "ALTER DOMAIN %s ADD CONSTRAINT %s ",
2258 generate_qualified_type_name(conForm->contypid),
2259 quote_identifier(NameStr(conForm->conname)));
2260 }
2261 }
2262
2263 switch (conForm->contype)
2264 {
2265 case CONSTRAINT_FOREIGN:
2266 {
2267 Datum val;
2268 bool isnull;
2269 const char *string;
2270
2271 /* Start off the constraint definition */
2272 appendStringInfoString(&buf, "FOREIGN KEY (");
2273
2274 /* Fetch and build referencing-column list */
2275 val = SysCacheGetAttrNotNull(CONSTROID, tup,
2276 Anum_pg_constraint_conkey);
2277
2278 /* If it is a temporal foreign key then it uses PERIOD. */
2279 decompile_column_index_array(val, conForm->conrelid, conForm->conperiod, &buf);
2280
2281 /* add foreign relation name */
2282 appendStringInfo(&buf, ") REFERENCES %s(",
2283 generate_relation_name(conForm->confrelid,
2284 NIL));
2285
2286 /* Fetch and build referenced-column list */
2287 val = SysCacheGetAttrNotNull(CONSTROID, tup,
2288 Anum_pg_constraint_confkey);
2289
2290 decompile_column_index_array(val, conForm->confrelid, conForm->conperiod, &buf);
2291
2293
2294 /* Add match type */
2295 switch (conForm->confmatchtype)
2296 {
2298 string = " MATCH FULL";
2299 break;
2301 string = " MATCH PARTIAL";
2302 break;
2304 string = "";
2305 break;
2306 default:
2307 elog(ERROR, "unrecognized confmatchtype: %d",
2308 conForm->confmatchtype);
2309 string = ""; /* keep compiler quiet */
2310 break;
2311 }
2312 appendStringInfoString(&buf, string);
2313
2314 /* Add ON UPDATE and ON DELETE clauses, if needed */
2315 switch (conForm->confupdtype)
2316 {
2318 string = NULL; /* suppress default */
2319 break;
2321 string = "RESTRICT";
2322 break;
2324 string = "CASCADE";
2325 break;
2327 string = "SET NULL";
2328 break;
2330 string = "SET DEFAULT";
2331 break;
2332 default:
2333 elog(ERROR, "unrecognized confupdtype: %d",
2334 conForm->confupdtype);
2335 string = NULL; /* keep compiler quiet */
2336 break;
2337 }
2338 if (string)
2339 appendStringInfo(&buf, " ON UPDATE %s", string);
2340
2341 switch (conForm->confdeltype)
2342 {
2344 string = NULL; /* suppress default */
2345 break;
2347 string = "RESTRICT";
2348 break;
2350 string = "CASCADE";
2351 break;
2353 string = "SET NULL";
2354 break;
2356 string = "SET DEFAULT";
2357 break;
2358 default:
2359 elog(ERROR, "unrecognized confdeltype: %d",
2360 conForm->confdeltype);
2361 string = NULL; /* keep compiler quiet */
2362 break;
2363 }
2364 if (string)
2365 appendStringInfo(&buf, " ON DELETE %s", string);
2366
2367 /*
2368 * Add columns specified to SET NULL or SET DEFAULT if
2369 * provided.
2370 */
2371 val = SysCacheGetAttr(CONSTROID, tup,
2372 Anum_pg_constraint_confdelsetcols, &isnull);
2373 if (!isnull)
2374 {
2376 decompile_column_index_array(val, conForm->conrelid, false, &buf);
2378 }
2379
2380 break;
2381 }
2382 case CONSTRAINT_PRIMARY:
2383 case CONSTRAINT_UNIQUE:
2384 {
2385 Datum val;
2386 Oid indexId;
2387 int keyatts;
2388 HeapTuple indtup;
2389
2390 /* Start off the constraint definition */
2391 if (conForm->contype == CONSTRAINT_PRIMARY)
2392 appendStringInfoString(&buf, "PRIMARY KEY ");
2393 else
2394 appendStringInfoString(&buf, "UNIQUE ");
2395
2396 indexId = conForm->conindid;
2397
2398 indtup = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexId));
2399 if (!HeapTupleIsValid(indtup))
2400 elog(ERROR, "cache lookup failed for index %u", indexId);
2401 if (conForm->contype == CONSTRAINT_UNIQUE &&
2402 ((Form_pg_index) GETSTRUCT(indtup))->indnullsnotdistinct)
2403 appendStringInfoString(&buf, "NULLS NOT DISTINCT ");
2404
2406
2407 /* Fetch and build target column list */
2408 val = SysCacheGetAttrNotNull(CONSTROID, tup,
2409 Anum_pg_constraint_conkey);
2410
2411 keyatts = decompile_column_index_array(val, conForm->conrelid, false, &buf);
2412 if (conForm->conperiod)
2413 appendStringInfoString(&buf, " WITHOUT OVERLAPS");
2414
2416
2417 /* Build including column list (from pg_index.indkeys) */
2418 val = SysCacheGetAttrNotNull(INDEXRELID, indtup,
2419 Anum_pg_index_indnatts);
2420 if (DatumGetInt32(val) > keyatts)
2421 {
2422 Datum cols;
2423 Datum *keys;
2424 int nKeys;
2425 int j;
2426
2427 appendStringInfoString(&buf, " INCLUDE (");
2428
2429 cols = SysCacheGetAttrNotNull(INDEXRELID, indtup,
2430 Anum_pg_index_indkey);
2431
2433 &keys, NULL, &nKeys);
2434
2435 for (j = keyatts; j < nKeys; j++)
2436 {
2437 char *colName;
2438
2439 colName = get_attname(conForm->conrelid,
2440 DatumGetInt16(keys[j]), false);
2441 if (j > keyatts)
2444 }
2445
2447 }
2448 ReleaseSysCache(indtup);
2449
2450 /* XXX why do we only print these bits if fullCommand? */
2451 if (fullCommand && OidIsValid(indexId))
2452 {
2453 char *options = flatten_reloptions(indexId);
2454 Oid tblspc;
2455
2456 if (options)
2457 {
2458 appendStringInfo(&buf, " WITH (%s)", options);
2459 pfree(options);
2460 }
2461
2462 /*
2463 * Print the tablespace, unless it's the database default.
2464 * This is to help ALTER TABLE usage of this facility,
2465 * which needs this behavior to recreate exact catalog
2466 * state.
2467 */
2468 tblspc = get_rel_tablespace(indexId);
2469 if (OidIsValid(tblspc))
2470 appendStringInfo(&buf, " USING INDEX TABLESPACE %s",
2472 }
2473
2474 break;
2475 }
2476 case CONSTRAINT_CHECK:
2477 {
2478 Datum val;
2479 char *conbin;
2480 char *consrc;
2481 Node *expr;
2482 List *context;
2483
2484 /* Fetch constraint expression in parsetree form */
2485 val = SysCacheGetAttrNotNull(CONSTROID, tup,
2486 Anum_pg_constraint_conbin);
2487
2488 conbin = TextDatumGetCString(val);
2489 expr = stringToNode(conbin);
2490
2491 /* Set up deparsing context for Var nodes in constraint */
2492 if (conForm->conrelid != InvalidOid)
2493 {
2494 /* relation constraint */
2495 context = deparse_context_for(get_relation_name(conForm->conrelid),
2496 conForm->conrelid);
2497 }
2498 else
2499 {
2500 /* domain constraint --- can't have Vars */
2501 context = NIL;
2502 }
2503
2504 consrc = deparse_expression_pretty(expr, context, false, false,
2505 prettyFlags, 0);
2506
2507 /*
2508 * Now emit the constraint definition, adding NO INHERIT if
2509 * necessary.
2510 *
2511 * There are cases where the constraint expression will be
2512 * fully parenthesized and we don't need the outer parens ...
2513 * but there are other cases where we do need 'em. Be
2514 * conservative for now.
2515 *
2516 * Note that simply checking for leading '(' and trailing ')'
2517 * would NOT be good enough, consider "(x > 0) AND (y > 0)".
2518 */
2519 appendStringInfo(&buf, "CHECK (%s)%s",
2520 consrc,
2521 conForm->connoinherit ? " NO INHERIT" : "");
2522 break;
2523 }
2524 case CONSTRAINT_NOTNULL:
2525 {
2526 if (conForm->conrelid)
2527 {
2529
2531
2532 appendStringInfo(&buf, "NOT NULL %s",
2533 quote_identifier(get_attname(conForm->conrelid,
2534 attnum, false)));
2535 if (((Form_pg_constraint) GETSTRUCT(tup))->connoinherit)
2536 appendStringInfoString(&buf, " NO INHERIT");
2537 }
2538 else if (conForm->contypid)
2539 {
2540 /* conkey is null for domain not-null constraints */
2541 appendStringInfoString(&buf, "NOT NULL");
2542 }
2543 break;
2544 }
2545
2546 case CONSTRAINT_TRIGGER:
2547
2548 /*
2549 * There isn't an ALTER TABLE syntax for creating a user-defined
2550 * constraint trigger, but it seems better to print something than
2551 * throw an error; if we throw error then this function couldn't
2552 * safely be applied to all rows of pg_constraint.
2553 */
2554 appendStringInfoString(&buf, "TRIGGER");
2555 break;
2556 case CONSTRAINT_EXCLUSION:
2557 {
2558 Oid indexOid = conForm->conindid;
2559 Datum val;
2560 Datum *elems;
2561 int nElems;
2562 int i;
2563 Oid *operators;
2564
2565 /* Extract operator OIDs from the pg_constraint tuple */
2566 val = SysCacheGetAttrNotNull(CONSTROID, tup,
2567 Anum_pg_constraint_conexclop);
2568
2570 &elems, NULL, &nElems);
2571
2572 operators = (Oid *) palloc(nElems * sizeof(Oid));
2573 for (i = 0; i < nElems; i++)
2574 operators[i] = DatumGetObjectId(elems[i]);
2575
2576 /* pg_get_indexdef_worker does the rest */
2577 /* suppress tablespace because pg_dump wants it that way */
2579 pg_get_indexdef_worker(indexOid,
2580 0,
2581 operators,
2582 false,
2583 false,
2584 false,
2585 false,
2586 prettyFlags,
2587 false));
2588 break;
2589 }
2590 default:
2591 elog(ERROR, "invalid constraint type \"%c\"", conForm->contype);
2592 break;
2593 }
2594
2595 if (conForm->condeferrable)
2596 appendStringInfoString(&buf, " DEFERRABLE");
2597 if (conForm->condeferred)
2598 appendStringInfoString(&buf, " INITIALLY DEFERRED");
2599
2600 /* Validated status is irrelevant when the constraint is NOT ENFORCED. */
2601 if (!conForm->conenforced)
2602 appendStringInfoString(&buf, " NOT ENFORCED");
2603 else if (!conForm->convalidated)
2604 appendStringInfoString(&buf, " NOT VALID");
2605
2606 /* Cleanup */
2607 systable_endscan(scandesc);
2608 table_close(relation, AccessShareLock);
2609
2610 return buf.data;
2611}
2612
2613
2614/*
2615 * Convert an int16[] Datum into a comma-separated list of column names
2616 * for the indicated relation; append the list to buf. Returns the number
2617 * of keys.
2618 */
2619static int
2620decompile_column_index_array(Datum column_index_array, Oid relId,
2621 bool withPeriod, StringInfo buf)
2622{
2623 Datum *keys;
2624 int nKeys;
2625 int j;
2626
2627 /* Extract data from array of int16 */
2628 deconstruct_array_builtin(DatumGetArrayTypeP(column_index_array), INT2OID,
2629 &keys, NULL, &nKeys);
2630
2631 for (j = 0; j < nKeys; j++)
2632 {
2633 char *colName;
2634
2635 colName = get_attname(relId, DatumGetInt16(keys[j]), false);
2636
2637 if (j == 0)
2639 else
2640 appendStringInfo(buf, ", %s%s",
2641 (withPeriod && j == nKeys - 1) ? "PERIOD " : "",
2642 quote_identifier(colName));
2643 }
2644
2645 return nKeys;
2646}
2647
2648
2649/* ----------
2650 * pg_get_expr - Decompile an expression tree
2651 *
2652 * Input: an expression tree in nodeToString form, and a relation OID
2653 *
2654 * Output: reverse-listed expression
2655 *
2656 * Currently, the expression can only refer to a single relation, namely
2657 * the one specified by the second parameter. This is sufficient for
2658 * partial indexes, column default expressions, etc. We also support
2659 * Var-free expressions, for which the OID can be InvalidOid.
2660 *
2661 * If the OID is nonzero but not actually valid, don't throw an error,
2662 * just return NULL. This is a bit questionable, but it's what we've
2663 * done historically, and it can help avoid unwanted failures when
2664 * examining catalog entries for just-deleted relations.
2665 *
2666 * We expect this function to work, or throw a reasonably clean error,
2667 * for any node tree that can appear in a catalog pg_node_tree column.
2668 * Query trees, such as those appearing in pg_rewrite.ev_action, are
2669 * not supported. Nor are expressions in more than one relation, which
2670 * can appear in places like pg_rewrite.ev_qual.
2671 * ----------
2672 */
2673Datum
2675{
2676 text *expr = PG_GETARG_TEXT_PP(0);
2677 Oid relid = PG_GETARG_OID(1);
2678 text *result;
2679 int prettyFlags;
2680
2681 prettyFlags = PRETTYFLAG_INDENT;
2682
2683 result = pg_get_expr_worker(expr, relid, prettyFlags);
2684 if (result)
2685 PG_RETURN_TEXT_P(result);
2686 else
2688}
2689
2690Datum
2692{
2693 text *expr = PG_GETARG_TEXT_PP(0);
2694 Oid relid = PG_GETARG_OID(1);
2695 bool pretty = PG_GETARG_BOOL(2);
2696 text *result;
2697 int prettyFlags;
2698
2699 prettyFlags = GET_PRETTY_FLAGS(pretty);
2700
2701 result = pg_get_expr_worker(expr, relid, prettyFlags);
2702 if (result)
2703 PG_RETURN_TEXT_P(result);
2704 else
2706}
2707
2708static text *
2709pg_get_expr_worker(text *expr, Oid relid, int prettyFlags)
2710{
2711 Node *node;
2712 Node *tst;
2713 Relids relids;
2714 List *context;
2715 char *exprstr;
2716 Relation rel = NULL;
2717 char *str;
2718
2719 /* Convert input pg_node_tree (really TEXT) object to C string */
2720 exprstr = text_to_cstring(expr);
2721
2722 /* Convert expression to node tree */
2723 node = (Node *) stringToNode(exprstr);
2724
2725 pfree(exprstr);
2726
2727 /*
2728 * Throw error if the input is a querytree rather than an expression tree.
2729 * While we could support queries here, there seems no very good reason
2730 * to. In most such catalog columns, we'll see a List of Query nodes, or
2731 * even nested Lists, so drill down to a non-List node before checking.
2732 */
2733 tst = node;
2734 while (tst && IsA(tst, List))
2735 tst = linitial((List *) tst);
2736 if (tst && IsA(tst, Query))
2737 ereport(ERROR,
2738 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2739 errmsg("input is a query, not an expression")));
2740
2741 /*
2742 * Throw error if the expression contains Vars we won't be able to
2743 * deparse.
2744 */
2745 relids = pull_varnos(NULL, node);
2746 if (OidIsValid(relid))
2747 {
2748 if (!bms_is_subset(relids, bms_make_singleton(1)))
2749 ereport(ERROR,
2750 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2751 errmsg("expression contains variables of more than one relation")));
2752 }
2753 else
2754 {
2755 if (!bms_is_empty(relids))
2756 ereport(ERROR,
2757 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2758 errmsg("expression contains variables")));
2759 }
2760
2761 /*
2762 * Prepare deparse context if needed. If we are deparsing with a relid,
2763 * we need to transiently open and lock the rel, to make sure it won't go
2764 * away underneath us. (set_relation_column_names would lock it anyway,
2765 * so this isn't really introducing any new behavior.)
2766 */
2767 if (OidIsValid(relid))
2768 {
2769 rel = try_relation_open(relid, AccessShareLock);
2770 if (rel == NULL)
2771 return NULL;
2772 context = deparse_context_for(RelationGetRelationName(rel), relid);
2773 }
2774 else
2775 context = NIL;
2776
2777 /* Deparse */
2778 str = deparse_expression_pretty(node, context, false, false,
2779 prettyFlags, 0);
2780
2781 if (rel != NULL)
2783
2784 return string_to_text(str);
2785}
2786
2787
2788/* ----------
2789 * pg_get_userbyid - Get a user name by roleid and
2790 * fallback to 'unknown (OID=n)'
2791 * ----------
2792 */
2793Datum
2795{
2796 Oid roleid = PG_GETARG_OID(0);
2797 Name result;
2798 HeapTuple roletup;
2799 Form_pg_authid role_rec;
2800
2801 /*
2802 * Allocate space for the result
2803 */
2804 result = (Name) palloc(NAMEDATALEN);
2805 memset(NameStr(*result), 0, NAMEDATALEN);
2806
2807 /*
2808 * Get the pg_authid entry and print the result
2809 */
2810 roletup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
2811 if (HeapTupleIsValid(roletup))
2812 {
2813 role_rec = (Form_pg_authid) GETSTRUCT(roletup);
2814 *result = role_rec->rolname;
2815 ReleaseSysCache(roletup);
2816 }
2817 else
2818 sprintf(NameStr(*result), "unknown (OID=%u)", roleid);
2819
2820 PG_RETURN_NAME(result);
2821}
2822
2823
2824/*
2825 * pg_get_serial_sequence
2826 * Get the name of the sequence used by an identity or serial column,
2827 * formatted suitably for passing to setval, nextval or currval.
2828 * First parameter is not treated as double-quoted, second parameter
2829 * is --- see documentation for reason.
2830 */
2831Datum
2833{
2834 text *tablename = PG_GETARG_TEXT_PP(0);
2835 text *columnname = PG_GETARG_TEXT_PP(1);
2836 RangeVar *tablerv;
2837 Oid tableOid;
2838 char *column;
2840 Oid sequenceId = InvalidOid;
2841 Relation depRel;
2842 ScanKeyData key[3];
2843 SysScanDesc scan;
2844 HeapTuple tup;
2845
2846 /* Look up table name. Can't lock it - we might not have privileges. */
2848 tableOid = RangeVarGetRelid(tablerv, NoLock, false);
2849
2850 /* Get the number of the column */
2851 column = text_to_cstring(columnname);
2852
2853 attnum = get_attnum(tableOid, column);
2855 ereport(ERROR,
2856 (errcode(ERRCODE_UNDEFINED_COLUMN),
2857 errmsg("column \"%s\" of relation \"%s\" does not exist",
2858 column, tablerv->relname)));
2859
2860 /* Search the dependency table for the dependent sequence */
2861 depRel = table_open(DependRelationId, AccessShareLock);
2862
2863 ScanKeyInit(&key[0],
2864 Anum_pg_depend_refclassid,
2865 BTEqualStrategyNumber, F_OIDEQ,
2866 ObjectIdGetDatum(RelationRelationId));
2867 ScanKeyInit(&key[1],
2868 Anum_pg_depend_refobjid,
2869 BTEqualStrategyNumber, F_OIDEQ,
2870 ObjectIdGetDatum(tableOid));
2871 ScanKeyInit(&key[2],
2872 Anum_pg_depend_refobjsubid,
2873 BTEqualStrategyNumber, F_INT4EQ,
2875
2876 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
2877 NULL, 3, key);
2878
2879 while (HeapTupleIsValid(tup = systable_getnext(scan)))
2880 {
2881 Form_pg_depend deprec = (Form_pg_depend) GETSTRUCT(tup);
2882
2883 /*
2884 * Look for an auto dependency (serial column) or internal dependency
2885 * (identity column) of a sequence on a column. (We need the relkind
2886 * test because indexes can also have auto dependencies on columns.)
2887 */
2888 if (deprec->classid == RelationRelationId &&
2889 deprec->objsubid == 0 &&
2890 (deprec->deptype == DEPENDENCY_AUTO ||
2891 deprec->deptype == DEPENDENCY_INTERNAL) &&
2892 get_rel_relkind(deprec->objid) == RELKIND_SEQUENCE)
2893 {
2894 sequenceId = deprec->objid;
2895 break;
2896 }
2897 }
2898
2899 systable_endscan(scan);
2901
2902 if (OidIsValid(sequenceId))
2903 {
2904 char *result;
2905
2906 result = generate_qualified_relation_name(sequenceId);
2907
2909 }
2910
2912}
2913
2914
2915/*
2916 * pg_get_functiondef
2917 * Returns the complete "CREATE OR REPLACE FUNCTION ..." statement for
2918 * the specified function.
2919 *
2920 * Note: if you change the output format of this function, be careful not
2921 * to break psql's rules (in \ef and \sf) for identifying the start of the
2922 * function body. To wit: the function body starts on a line that begins with
2923 * "AS ", "BEGIN ", or "RETURN ", and no preceding line will look like that.
2924 */
2925Datum
2927{
2928 Oid funcid = PG_GETARG_OID(0);
2930 StringInfoData dq;
2931 HeapTuple proctup;
2932 Form_pg_proc proc;
2933 bool isfunction;
2934 Datum tmp;
2935 bool isnull;
2936 const char *prosrc;
2937 const char *name;
2938 const char *nsp;
2939 float4 procost;
2940 int oldlen;
2941
2943
2944 /* Look up the function */
2945 proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
2946 if (!HeapTupleIsValid(proctup))
2948
2949 proc = (Form_pg_proc) GETSTRUCT(proctup);
2950 name = NameStr(proc->proname);
2951
2952 if (proc->prokind == PROKIND_AGGREGATE)
2953 ereport(ERROR,
2954 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2955 errmsg("\"%s\" is an aggregate function", name)));
2956
2957 isfunction = (proc->prokind != PROKIND_PROCEDURE);
2958
2959 /*
2960 * We always qualify the function name, to ensure the right function gets
2961 * replaced.
2962 */
2963 nsp = get_namespace_name_or_temp(proc->pronamespace);
2964 appendStringInfo(&buf, "CREATE OR REPLACE %s %s(",
2965 isfunction ? "FUNCTION" : "PROCEDURE",
2967 (void) print_function_arguments(&buf, proctup, false, true);
2968 appendStringInfoString(&buf, ")\n");
2969 if (isfunction)
2970 {
2971 appendStringInfoString(&buf, " RETURNS ");
2972 print_function_rettype(&buf, proctup);
2973 appendStringInfoChar(&buf, '\n');
2974 }
2975
2976 print_function_trftypes(&buf, proctup);
2977
2978 appendStringInfo(&buf, " LANGUAGE %s\n",
2979 quote_identifier(get_language_name(proc->prolang, false)));
2980
2981 /* Emit some miscellaneous options on one line */
2982 oldlen = buf.len;
2983
2984 if (proc->prokind == PROKIND_WINDOW)
2985 appendStringInfoString(&buf, " WINDOW");
2986 switch (proc->provolatile)
2987 {
2988 case PROVOLATILE_IMMUTABLE:
2989 appendStringInfoString(&buf, " IMMUTABLE");
2990 break;
2991 case PROVOLATILE_STABLE:
2992 appendStringInfoString(&buf, " STABLE");
2993 break;
2994 case PROVOLATILE_VOLATILE:
2995 break;
2996 }
2997
2998 switch (proc->proparallel)
2999 {
3000 case PROPARALLEL_SAFE:
3001 appendStringInfoString(&buf, " PARALLEL SAFE");
3002 break;
3003 case PROPARALLEL_RESTRICTED:
3004 appendStringInfoString(&buf, " PARALLEL RESTRICTED");
3005 break;
3006 case PROPARALLEL_UNSAFE:
3007 break;
3008 }
3009
3010 if (proc->proisstrict)
3011 appendStringInfoString(&buf, " STRICT");
3012 if (proc->prosecdef)
3013 appendStringInfoString(&buf, " SECURITY DEFINER");
3014 if (proc->proleakproof)
3015 appendStringInfoString(&buf, " LEAKPROOF");
3016
3017 /* This code for the default cost and rows should match functioncmds.c */
3018 if (proc->prolang == INTERNALlanguageId ||
3019 proc->prolang == ClanguageId)
3020 procost = 1;
3021 else
3022 procost = 100;
3023 if (proc->procost != procost)
3024 appendStringInfo(&buf, " COST %g", proc->procost);
3025
3026 if (proc->prorows > 0 && proc->prorows != 1000)
3027 appendStringInfo(&buf, " ROWS %g", proc->prorows);
3028
3029 if (proc->prosupport)
3030 {
3031 Oid argtypes[1];
3032
3033 /*
3034 * We should qualify the support function's name if it wouldn't be
3035 * resolved by lookup in the current search path.
3036 */
3037 argtypes[0] = INTERNALOID;
3038 appendStringInfo(&buf, " SUPPORT %s",
3039 generate_function_name(proc->prosupport, 1,
3040 NIL, argtypes,
3041 false, NULL, false));
3042 }
3043
3044 if (oldlen != buf.len)
3045 appendStringInfoChar(&buf, '\n');
3046
3047 /* Emit any proconfig options, one per line */
3048 tmp = SysCacheGetAttr(PROCOID, proctup, Anum_pg_proc_proconfig, &isnull);
3049 if (!isnull)
3050 {
3052 int i;
3053
3054 Assert(ARR_ELEMTYPE(a) == TEXTOID);
3055 Assert(ARR_NDIM(a) == 1);
3056 Assert(ARR_LBOUND(a)[0] == 1);
3057
3058 for (i = 1; i <= ARR_DIMS(a)[0]; i++)
3059 {
3060 Datum d;
3061
3062 d = array_ref(a, 1, &i,
3063 -1 /* varlenarray */ ,
3064 -1 /* TEXT's typlen */ ,
3065 false /* TEXT's typbyval */ ,
3066 TYPALIGN_INT /* TEXT's typalign */ ,
3067 &isnull);
3068 if (!isnull)
3069 {
3070 char *configitem = TextDatumGetCString(d);
3071 char *pos;
3072
3073 pos = strchr(configitem, '=');
3074 if (pos == NULL)
3075 continue;
3076 *pos++ = '\0';
3077
3078 appendStringInfo(&buf, " SET %s TO ",
3079 quote_identifier(configitem));
3080
3081 /*
3082 * Variables that are marked GUC_LIST_QUOTE were already fully
3083 * quoted by flatten_set_variable_args() before they were put
3084 * into the proconfig array. However, because the quoting
3085 * rules used there aren't exactly like SQL's, we have to
3086 * break the list value apart and then quote the elements as
3087 * string literals. (The elements may be double-quoted as-is,
3088 * but we can't just feed them to the SQL parser; it would do
3089 * the wrong thing with elements that are zero-length or
3090 * longer than NAMEDATALEN.)
3091 *
3092 * Variables that are not so marked should just be emitted as
3093 * simple string literals. If the variable is not known to
3094 * guc.c, we'll do that; this makes it unsafe to use
3095 * GUC_LIST_QUOTE for extension variables.
3096 */
3097 if (GetConfigOptionFlags(configitem, true) & GUC_LIST_QUOTE)
3098 {
3099 List *namelist;
3100 ListCell *lc;
3101
3102 /* Parse string into list of identifiers */
3103 if (!SplitGUCList(pos, ',', &namelist))
3104 {
3105 /* this shouldn't fail really */
3106 elog(ERROR, "invalid list syntax in proconfig item");
3107 }
3108 foreach(lc, namelist)
3109 {
3110 char *curname = (char *) lfirst(lc);
3111
3112 simple_quote_literal(&buf, curname);
3113 if (lnext(namelist, lc))
3115 }
3116 }
3117 else
3119 appendStringInfoChar(&buf, '\n');
3120 }
3121 }
3122 }
3123
3124 /* And finally the function definition ... */
3125 (void) SysCacheGetAttr(PROCOID, proctup, Anum_pg_proc_prosqlbody, &isnull);
3126 if (proc->prolang == SQLlanguageId && !isnull)
3127 {
3128 print_function_sqlbody(&buf, proctup);
3129 }
3130 else
3131 {
3132 appendStringInfoString(&buf, "AS ");
3133
3134 tmp = SysCacheGetAttr(PROCOID, proctup, Anum_pg_proc_probin, &isnull);
3135 if (!isnull)
3136 {
3138 appendStringInfoString(&buf, ", "); /* assume prosrc isn't null */
3139 }
3140
3141 tmp = SysCacheGetAttrNotNull(PROCOID, proctup, Anum_pg_proc_prosrc);
3142 prosrc = TextDatumGetCString(tmp);
3143
3144 /*
3145 * We always use dollar quoting. Figure out a suitable delimiter.
3146 *
3147 * Since the user is likely to be editing the function body string, we
3148 * shouldn't use a short delimiter that he might easily create a
3149 * conflict with. Hence prefer "$function$"/"$procedure$", but extend
3150 * if needed.
3151 */
3152 initStringInfo(&dq);
3153 appendStringInfoChar(&dq, '$');
3154 appendStringInfoString(&dq, (isfunction ? "function" : "procedure"));
3155 while (strstr(prosrc, dq.data) != NULL)
3156 appendStringInfoChar(&dq, 'x');
3157 appendStringInfoChar(&dq, '$');
3158
3160 appendStringInfoString(&buf, prosrc);
3162 }
3163
3164 appendStringInfoChar(&buf, '\n');
3165
3166 ReleaseSysCache(proctup);
3167
3169}
3170
3171/*
3172 * pg_get_function_arguments
3173 * Get a nicely-formatted list of arguments for a function.
3174 * This is everything that would go between the parentheses in
3175 * CREATE FUNCTION.
3176 */
3177Datum
3179{
3180 Oid funcid = PG_GETARG_OID(0);
3182 HeapTuple proctup;
3183
3184 proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
3185 if (!HeapTupleIsValid(proctup))
3187
3189
3190 (void) print_function_arguments(&buf, proctup, false, true);
3191
3192 ReleaseSysCache(proctup);
3193
3195}
3196
3197/*
3198 * pg_get_function_identity_arguments
3199 * Get a formatted list of arguments for a function.
3200 * This is everything that would go between the parentheses in
3201 * ALTER FUNCTION, etc. In particular, don't print defaults.
3202 */
3203Datum
3205{
3206 Oid funcid = PG_GETARG_OID(0);
3208 HeapTuple proctup;
3209
3210 proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
3211 if (!HeapTupleIsValid(proctup))
3213
3215
3216 (void) print_function_arguments(&buf, proctup, false, false);
3217
3218 ReleaseSysCache(proctup);
3219
3221}
3222
3223/*
3224 * pg_get_function_result
3225 * Get a nicely-formatted version of the result type of a function.
3226 * This is what would appear after RETURNS in CREATE FUNCTION.
3227 */
3228Datum
3230{
3231 Oid funcid = PG_GETARG_OID(0);
3233 HeapTuple proctup;
3234
3235 proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
3236 if (!HeapTupleIsValid(proctup))
3238
3239 if (((Form_pg_proc) GETSTRUCT(proctup))->prokind == PROKIND_PROCEDURE)
3240 {
3241 ReleaseSysCache(proctup);
3243 }
3244
3246
3247 print_function_rettype(&buf, proctup);
3248
3249 ReleaseSysCache(proctup);
3250
3252}
3253
3254/*
3255 * Guts of pg_get_function_result: append the function's return type
3256 * to the specified buffer.
3257 */
3258static void
3260{
3261 Form_pg_proc proc = (Form_pg_proc) GETSTRUCT(proctup);
3262 int ntabargs = 0;
3263 StringInfoData rbuf;
3264
3265 initStringInfo(&rbuf);
3266
3267 if (proc->proretset)
3268 {
3269 /* It might be a table function; try to print the arguments */
3270 appendStringInfoString(&rbuf, "TABLE(");
3271 ntabargs = print_function_arguments(&rbuf, proctup, true, false);
3272 if (ntabargs > 0)
3273 appendStringInfoChar(&rbuf, ')');
3274 else
3275 resetStringInfo(&rbuf);
3276 }
3277
3278 if (ntabargs == 0)
3279 {
3280 /* Not a table function, so do the normal thing */
3281 if (proc->proretset)
3282 appendStringInfoString(&rbuf, "SETOF ");
3283 appendStringInfoString(&rbuf, format_type_be(proc->prorettype));
3284 }
3285
3286 appendBinaryStringInfo(buf, rbuf.data, rbuf.len);
3287}
3288
3289/*
3290 * Common code for pg_get_function_arguments and pg_get_function_result:
3291 * append the desired subset of arguments to buf. We print only TABLE
3292 * arguments when print_table_args is true, and all the others when it's false.
3293 * We print argument defaults only if print_defaults is true.
3294 * Function return value is the number of arguments printed.
3295 */
3296static int
3298 bool print_table_args, bool print_defaults)
3299{
3300 Form_pg_proc proc = (Form_pg_proc) GETSTRUCT(proctup);
3301 int numargs;
3302 Oid *argtypes;
3303 char **argnames;
3304 char *argmodes;
3305 int insertorderbyat = -1;
3306 int argsprinted;
3307 int inputargno;
3308 int nlackdefaults;
3309 List *argdefaults = NIL;
3310 ListCell *nextargdefault = NULL;
3311 int i;
3312
3313 numargs = get_func_arg_info(proctup,
3314 &argtypes, &argnames, &argmodes);
3315
3316 nlackdefaults = numargs;
3317 if (print_defaults && proc->pronargdefaults > 0)
3318 {
3319 Datum proargdefaults;
3320 bool isnull;
3321
3322 proargdefaults = SysCacheGetAttr(PROCOID, proctup,
3323 Anum_pg_proc_proargdefaults,
3324 &isnull);
3325 if (!isnull)
3326 {
3327 char *str;
3328
3329 str = TextDatumGetCString(proargdefaults);
3330 argdefaults = castNode(List, stringToNode(str));
3331 pfree(str);
3332 nextargdefault = list_head(argdefaults);
3333 /* nlackdefaults counts only *input* arguments lacking defaults */
3334 nlackdefaults = proc->pronargs - list_length(argdefaults);
3335 }
3336 }
3337
3338 /* Check for special treatment of ordered-set aggregates */
3339 if (proc->prokind == PROKIND_AGGREGATE)
3340 {
3341 HeapTuple aggtup;
3343
3344 aggtup = SearchSysCache1(AGGFNOID, ObjectIdGetDatum(proc->oid));
3345 if (!HeapTupleIsValid(aggtup))
3346 elog(ERROR, "cache lookup failed for aggregate %u",
3347 proc->oid);
3348 agg = (Form_pg_aggregate) GETSTRUCT(aggtup);
3349 if (AGGKIND_IS_ORDERED_SET(agg->aggkind))
3350 insertorderbyat = agg->aggnumdirectargs;
3351 ReleaseSysCache(aggtup);
3352 }
3353
3354 argsprinted = 0;
3355 inputargno = 0;
3356 for (i = 0; i < numargs; i++)
3357 {
3358 Oid argtype = argtypes[i];
3359 char *argname = argnames ? argnames[i] : NULL;
3360 char argmode = argmodes ? argmodes[i] : PROARGMODE_IN;
3361 const char *modename;
3362 bool isinput;
3363
3364 switch (argmode)
3365 {
3366 case PROARGMODE_IN:
3367
3368 /*
3369 * For procedures, explicitly mark all argument modes, so as
3370 * to avoid ambiguity with the SQL syntax for DROP PROCEDURE.
3371 */
3372 if (proc->prokind == PROKIND_PROCEDURE)
3373 modename = "IN ";
3374 else
3375 modename = "";
3376 isinput = true;
3377 break;
3378 case PROARGMODE_INOUT:
3379 modename = "INOUT ";
3380 isinput = true;
3381 break;
3382 case PROARGMODE_OUT:
3383 modename = "OUT ";
3384 isinput = false;
3385 break;
3386 case PROARGMODE_VARIADIC:
3387 modename = "VARIADIC ";
3388 isinput = true;
3389 break;
3390 case PROARGMODE_TABLE:
3391 modename = "";
3392 isinput = false;
3393 break;
3394 default:
3395 elog(ERROR, "invalid parameter mode '%c'", argmode);
3396 modename = NULL; /* keep compiler quiet */
3397 isinput = false;
3398 break;
3399 }
3400 if (isinput)
3401 inputargno++; /* this is a 1-based counter */
3402
3403 if (print_table_args != (argmode == PROARGMODE_TABLE))
3404 continue;
3405
3406 if (argsprinted == insertorderbyat)
3407 {
3408 if (argsprinted)
3410 appendStringInfoString(buf, "ORDER BY ");
3411 }
3412 else if (argsprinted)
3414
3415 appendStringInfoString(buf, modename);
3416 if (argname && argname[0])
3417 appendStringInfo(buf, "%s ", quote_identifier(argname));
3419 if (print_defaults && isinput && inputargno > nlackdefaults)
3420 {
3421 Node *expr;
3422
3423 Assert(nextargdefault != NULL);
3424 expr = (Node *) lfirst(nextargdefault);
3425 nextargdefault = lnext(argdefaults, nextargdefault);
3426
3427 appendStringInfo(buf, " DEFAULT %s",
3428 deparse_expression(expr, NIL, false, false));
3429 }
3430 argsprinted++;
3431
3432 /* nasty hack: print the last arg twice for variadic ordered-set agg */
3433 if (argsprinted == insertorderbyat && i == numargs - 1)
3434 {
3435 i--;
3436 /* aggs shouldn't have defaults anyway, but just to be sure ... */
3437 print_defaults = false;
3438 }
3439 }
3440
3441 return argsprinted;
3442}
3443
3444static bool
3445is_input_argument(int nth, const char *argmodes)
3446{
3447 return (!argmodes
3448 || argmodes[nth] == PROARGMODE_IN
3449 || argmodes[nth] == PROARGMODE_INOUT
3450 || argmodes[nth] == PROARGMODE_VARIADIC);
3451}
3452
3453/*
3454 * Append used transformed types to specified buffer
3455 */
3456static void
3458{
3459 Oid *trftypes;
3460 int ntypes;
3461
3462 ntypes = get_func_trftypes(proctup, &trftypes);
3463 if (ntypes > 0)
3464 {
3465 int i;
3466
3467 appendStringInfoString(buf, " TRANSFORM ");
3468 for (i = 0; i < ntypes; i++)
3469 {
3470 if (i != 0)
3472 appendStringInfo(buf, "FOR TYPE %s", format_type_be(trftypes[i]));
3473 }
3475 }
3476}
3477
3478/*
3479 * Get textual representation of a function argument's default value. The
3480 * second argument of this function is the argument number among all arguments
3481 * (i.e. proallargtypes, *not* proargtypes), starting with 1, because that's
3482 * how information_schema.sql uses it.
3483 */
3484Datum
3486{
3487 Oid funcid = PG_GETARG_OID(0);
3488 int32 nth_arg = PG_GETARG_INT32(1);
3489 HeapTuple proctup;
3490 Form_pg_proc proc;
3491 int numargs;
3492 Oid *argtypes;
3493 char **argnames;
3494 char *argmodes;
3495 int i;
3496 List *argdefaults;
3497 Node *node;
3498 char *str;
3499 int nth_inputarg;
3500 Datum proargdefaults;
3501 bool isnull;
3502 int nth_default;
3503
3504 proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
3505 if (!HeapTupleIsValid(proctup))
3507
3508 numargs = get_func_arg_info(proctup, &argtypes, &argnames, &argmodes);
3509 if (nth_arg < 1 || nth_arg > numargs || !is_input_argument(nth_arg - 1, argmodes))
3510 {
3511 ReleaseSysCache(proctup);
3513 }
3514
3515 nth_inputarg = 0;
3516 for (i = 0; i < nth_arg; i++)
3517 if (is_input_argument(i, argmodes))
3518 nth_inputarg++;
3519
3520 proargdefaults = SysCacheGetAttr(PROCOID, proctup,
3521 Anum_pg_proc_proargdefaults,
3522 &isnull);
3523 if (isnull)
3524 {
3525 ReleaseSysCache(proctup);
3527 }
3528
3529 str = TextDatumGetCString(proargdefaults);
3530 argdefaults = castNode(List, stringToNode(str));
3531 pfree(str);
3532
3533 proc = (Form_pg_proc) GETSTRUCT(proctup);
3534
3535 /*
3536 * Calculate index into proargdefaults: proargdefaults corresponds to the
3537 * last N input arguments, where N = pronargdefaults.
3538 */
3539 nth_default = nth_inputarg - 1 - (proc->pronargs - proc->pronargdefaults);
3540
3541 if (nth_default < 0 || nth_default >= list_length(argdefaults))
3542 {
3543 ReleaseSysCache(proctup);
3545 }
3546 node = list_nth(argdefaults, nth_default);
3547 str = deparse_expression(node, NIL, false, false);
3548
3549 ReleaseSysCache(proctup);
3550
3552}
3553
3554static void
3556{
3557 int numargs;
3558 Oid *argtypes;
3559 char **argnames;
3560 char *argmodes;
3561 deparse_namespace dpns = {0};
3562 Datum tmp;
3563 Node *n;
3564
3565 dpns.funcname = pstrdup(NameStr(((Form_pg_proc) GETSTRUCT(proctup))->proname));
3566 numargs = get_func_arg_info(proctup,
3567 &argtypes, &argnames, &argmodes);
3568 dpns.numargs = numargs;
3569 dpns.argnames = argnames;
3570
3571 tmp = SysCacheGetAttrNotNull(PROCOID, proctup, Anum_pg_proc_prosqlbody);
3573
3574 if (IsA(n, List))
3575 {
3576 List *stmts;
3577 ListCell *lc;
3578
3579 stmts = linitial(castNode(List, n));
3580
3581 appendStringInfoString(buf, "BEGIN ATOMIC\n");
3582
3583 foreach(lc, stmts)
3584 {
3585 Query *query = lfirst_node(Query, lc);
3586
3587 /* It seems advisable to get at least AccessShareLock on rels */
3588 AcquireRewriteLocks(query, false, false);
3589 get_query_def(query, buf, list_make1(&dpns), NULL, false,
3593 }
3594
3596 }
3597 else
3598 {
3599 Query *query = castNode(Query, n);
3600
3601 /* It seems advisable to get at least AccessShareLock on rels */
3602 AcquireRewriteLocks(query, false, false);
3603 get_query_def(query, buf, list_make1(&dpns), NULL, false,
3604 0, WRAP_COLUMN_DEFAULT, 0);
3605 }
3606}
3607
3608Datum
3610{
3611 Oid funcid = PG_GETARG_OID(0);
3613 HeapTuple proctup;
3614 bool isnull;
3615
3617
3618 /* Look up the function */
3619 proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
3620 if (!HeapTupleIsValid(proctup))
3622
3623 (void) SysCacheGetAttr(PROCOID, proctup, Anum_pg_proc_prosqlbody, &isnull);
3624 if (isnull)
3625 {
3626 ReleaseSysCache(proctup);
3628 }
3629
3630 print_function_sqlbody(&buf, proctup);
3631
3632 ReleaseSysCache(proctup);
3633
3635}
3636
3637
3638/*
3639 * deparse_expression - General utility for deparsing expressions
3640 *
3641 * calls deparse_expression_pretty with all prettyPrinting disabled
3642 */
3643char *
3644deparse_expression(Node *expr, List *dpcontext,
3645 bool forceprefix, bool showimplicit)
3646{
3647 return deparse_expression_pretty(expr, dpcontext, forceprefix,
3648 showimplicit, 0, 0);
3649}
3650
3651/* ----------
3652 * deparse_expression_pretty - General utility for deparsing expressions
3653 *
3654 * expr is the node tree to be deparsed. It must be a transformed expression
3655 * tree (ie, not the raw output of gram.y).
3656 *
3657 * dpcontext is a list of deparse_namespace nodes representing the context
3658 * for interpreting Vars in the node tree. It can be NIL if no Vars are
3659 * expected.
3660 *
3661 * forceprefix is true to force all Vars to be prefixed with their table names.
3662 *
3663 * showimplicit is true to force all implicit casts to be shown explicitly.
3664 *
3665 * Tries to pretty up the output according to prettyFlags and startIndent.
3666 *
3667 * The result is a palloc'd string.
3668 * ----------
3669 */
3670static char *
3672 bool forceprefix, bool showimplicit,
3673 int prettyFlags, int startIndent)
3674{
3676 deparse_context context;
3677
3679 context.buf = &buf;
3680 context.namespaces = dpcontext;
3681 context.resultDesc = NULL;
3682 context.targetList = NIL;
3683 context.windowClause = NIL;
3684 context.varprefix = forceprefix;
3685 context.prettyFlags = prettyFlags;
3687 context.indentLevel = startIndent;
3688 context.colNamesVisible = true;
3689 context.inGroupBy = false;
3690 context.varInOrderBy = false;
3691 context.appendparents = NULL;
3692
3693 get_rule_expr(expr, &context, showimplicit);
3694
3695 return buf.data;
3696}
3697
3698/* ----------
3699 * deparse_context_for - Build deparse context for a single relation
3700 *
3701 * Given the reference name (alias) and OID of a relation, build deparsing
3702 * context for an expression referencing only that relation (as varno 1,
3703 * varlevelsup 0). This is sufficient for many uses of deparse_expression.
3704 * ----------
3705 */
3706List *
3707deparse_context_for(const char *aliasname, Oid relid)
3708{
3709 deparse_namespace *dpns;
3710 RangeTblEntry *rte;
3711
3712 dpns = (deparse_namespace *) palloc0(sizeof(deparse_namespace));
3713
3714 /* Build a minimal RTE for the rel */
3715 rte = makeNode(RangeTblEntry);
3716 rte->rtekind = RTE_RELATION;
3717 rte->relid = relid;
3718 rte->relkind = RELKIND_RELATION; /* no need for exactness here */
3719 rte->rellockmode = AccessShareLock;
3720 rte->alias = makeAlias(aliasname, NIL);
3721 rte->eref = rte->alias;
3722 rte->lateral = false;
3723 rte->inh = false;
3724 rte->inFromCl = true;
3725
3726 /* Build one-element rtable */
3727 dpns->rtable = list_make1(rte);
3728 dpns->subplans = NIL;
3729 dpns->ctes = NIL;
3730 dpns->appendrels = NULL;
3731 set_rtable_names(dpns, NIL, NULL);
3733
3734 /* Return a one-deep namespace stack */
3735 return list_make1(dpns);
3736}
3737
3738/*
3739 * deparse_context_for_plan_tree - Build deparse context for a Plan tree
3740 *
3741 * When deparsing an expression in a Plan tree, we use the plan's rangetable
3742 * to resolve names of simple Vars. The initialization of column names for
3743 * this is rather expensive if the rangetable is large, and it'll be the same
3744 * for every expression in the Plan tree; so we do it just once and re-use
3745 * the result of this function for each expression. (Note that the result
3746 * is not usable until set_deparse_context_plan() is applied to it.)
3747 *
3748 * In addition to the PlannedStmt, pass the per-RTE alias names
3749 * assigned by a previous call to select_rtable_names_for_explain.
3750 */
3751List *
3753{
3754 deparse_namespace *dpns;
3755
3756 dpns = (deparse_namespace *) palloc0(sizeof(deparse_namespace));
3757
3758 /* Initialize fields that stay the same across the whole plan tree */
3759 dpns->rtable = pstmt->rtable;
3760 dpns->rtable_names = rtable_names;
3761 dpns->subplans = pstmt->subplans;
3762 dpns->ctes = NIL;
3763 if (pstmt->appendRelations)
3764 {
3765 /* Set up the array, indexed by child relid */
3766 int ntables = list_length(dpns->rtable);
3767 ListCell *lc;
3768
3769 dpns->appendrels = (AppendRelInfo **)
3770 palloc0((ntables + 1) * sizeof(AppendRelInfo *));
3771 foreach(lc, pstmt->appendRelations)
3772 {
3773 AppendRelInfo *appinfo = lfirst_node(AppendRelInfo, lc);
3774 Index crelid = appinfo->child_relid;
3775
3776 Assert(crelid > 0 && crelid <= ntables);
3777 Assert(dpns->appendrels[crelid] == NULL);
3778 dpns->appendrels[crelid] = appinfo;
3779 }
3780 }
3781 else
3782 dpns->appendrels = NULL; /* don't need it */
3783
3784 /*
3785 * Set up column name aliases, ignoring any join RTEs; they don't matter
3786 * because plan trees don't contain any join alias Vars.
3787 */
3789
3790 /* Return a one-deep namespace stack */
3791 return list_make1(dpns);
3792}
3793
3794/*
3795 * set_deparse_context_plan - Specify Plan node containing expression
3796 *
3797 * When deparsing an expression in a Plan tree, we might have to resolve
3798 * OUTER_VAR, INNER_VAR, or INDEX_VAR references. To do this, the caller must
3799 * provide the parent Plan node. Then OUTER_VAR and INNER_VAR references
3800 * can be resolved by drilling down into the left and right child plans.
3801 * Similarly, INDEX_VAR references can be resolved by reference to the
3802 * indextlist given in a parent IndexOnlyScan node, or to the scan tlist in
3803 * ForeignScan and CustomScan nodes. (Note that we don't currently support
3804 * deparsing of indexquals in regular IndexScan or BitmapIndexScan nodes;
3805 * for those, we can only deparse the indexqualorig fields, which won't
3806 * contain INDEX_VAR Vars.)
3807 *
3808 * The ancestors list is a list of the Plan's parent Plan and SubPlan nodes,
3809 * the most-closely-nested first. This is needed to resolve PARAM_EXEC
3810 * Params. Note we assume that all the Plan nodes share the same rtable.
3811 *
3812 * For a ModifyTable plan, we might also need to resolve references to OLD/NEW
3813 * variables in the RETURNING list, so we copy the alias names of the OLD and
3814 * NEW rows from the ModifyTable plan node.
3815 *
3816 * Once this function has been called, deparse_expression() can be called on
3817 * subsidiary expression(s) of the specified Plan node. To deparse
3818 * expressions of a different Plan node in the same Plan tree, re-call this
3819 * function to identify the new parent Plan node.
3820 *
3821 * The result is the same List passed in; this is a notational convenience.
3822 */
3823List *
3824set_deparse_context_plan(List *dpcontext, Plan *plan, List *ancestors)
3825{
3826 deparse_namespace *dpns;
3827
3828 /* Should always have one-entry namespace list for Plan deparsing */
3829 Assert(list_length(dpcontext) == 1);
3830 dpns = (deparse_namespace *) linitial(dpcontext);
3831
3832 /* Set our attention on the specific plan node passed in */
3833 dpns->ancestors = ancestors;
3834 set_deparse_plan(dpns, plan);
3835
3836 /* For ModifyTable, set aliases for OLD and NEW in RETURNING */
3837 if (IsA(plan, ModifyTable))
3838 {
3839 dpns->ret_old_alias = ((ModifyTable *) plan)->returningOldAlias;
3840 dpns->ret_new_alias = ((ModifyTable *) plan)->returningNewAlias;
3841 }
3842
3843 return dpcontext;
3844}
3845
3846/*
3847 * select_rtable_names_for_explain - Select RTE aliases for EXPLAIN
3848 *
3849 * Determine the relation aliases we'll use during an EXPLAIN operation.
3850 * This is just a frontend to set_rtable_names. We have to expose the aliases
3851 * to EXPLAIN because EXPLAIN needs to know the right alias names to print.
3852 */
3853List *
3855{
3856 deparse_namespace dpns;
3857
3858 memset(&dpns, 0, sizeof(dpns));
3859 dpns.rtable = rtable;
3860 dpns.subplans = NIL;
3861 dpns.ctes = NIL;
3862 dpns.appendrels = NULL;
3863 set_rtable_names(&dpns, NIL, rels_used);
3864 /* We needn't bother computing column aliases yet */
3865
3866 return dpns.rtable_names;
3867}
3868
3869/*
3870 * set_rtable_names: select RTE aliases to be used in printing a query
3871 *
3872 * We fill in dpns->rtable_names with a list of names that is one-for-one with
3873 * the already-filled dpns->rtable list. Each RTE name is unique among those
3874 * in the new namespace plus any ancestor namespaces listed in
3875 * parent_namespaces.
3876 *
3877 * If rels_used isn't NULL, only RTE indexes listed in it are given aliases.
3878 *
3879 * Note that this function is only concerned with relation names, not column
3880 * names.
3881 */
3882static void
3883set_rtable_names(deparse_namespace *dpns, List *parent_namespaces,
3884 Bitmapset *rels_used)
3885{
3886 HASHCTL hash_ctl;
3887 HTAB *names_hash;
3888 NameHashEntry *hentry;
3889 bool found;
3890 int rtindex;
3891 ListCell *lc;
3892
3893 dpns->rtable_names = NIL;
3894 /* nothing more to do if empty rtable */
3895 if (dpns->rtable == NIL)
3896 return;
3897
3898 /*
3899 * We use a hash table to hold known names, so that this process is O(N)
3900 * not O(N^2) for N names.
3901 */
3902 hash_ctl.keysize = NAMEDATALEN;
3903 hash_ctl.entrysize = sizeof(NameHashEntry);
3904 hash_ctl.hcxt = CurrentMemoryContext;
3905 names_hash = hash_create("set_rtable_names names",
3906 list_length(dpns->rtable),
3907 &hash_ctl,
3909
3910 /* Preload the hash table with names appearing in parent_namespaces */
3911 foreach(lc, parent_namespaces)
3912 {
3913 deparse_namespace *olddpns = (deparse_namespace *) lfirst(lc);
3914 ListCell *lc2;
3915
3916 foreach(lc2, olddpns->rtable_names)
3917 {
3918 char *oldname = (char *) lfirst(lc2);
3919
3920 if (oldname == NULL)
3921 continue;
3922 hentry = (NameHashEntry *) hash_search(names_hash,
3923 oldname,
3924 HASH_ENTER,
3925 &found);
3926 /* we do not complain about duplicate names in parent namespaces */
3927 hentry->counter = 0;
3928 }
3929 }
3930
3931 /* Now we can scan the rtable */
3932 rtindex = 1;
3933 foreach(lc, dpns->rtable)
3934 {
3935 RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
3936 char *refname;
3937
3938 /* Just in case this takes an unreasonable amount of time ... */
3940
3941 if (rels_used && !bms_is_member(rtindex, rels_used))
3942 {
3943 /* Ignore unreferenced RTE */
3944 refname = NULL;
3945 }
3946 else if (rte->alias)
3947 {
3948 /* If RTE has a user-defined alias, prefer that */
3949 refname = rte->alias->aliasname;
3950 }
3951 else if (rte->rtekind == RTE_RELATION)
3952 {
3953 /* Use the current actual name of the relation */
3954 refname = get_rel_name(rte->relid);
3955 }
3956 else if (rte->rtekind == RTE_JOIN)
3957 {
3958 /* Unnamed join has no refname */
3959 refname = NULL;
3960 }
3961 else
3962 {
3963 /* Otherwise use whatever the parser assigned */
3964 refname = rte->eref->aliasname;
3965 }
3966
3967 /*
3968 * If the selected name isn't unique, append digits to make it so, and
3969 * make a new hash entry for it once we've got a unique name. For a
3970 * very long input name, we might have to truncate to stay within
3971 * NAMEDATALEN.
3972 */
3973 if (refname)
3974 {
3975 hentry = (NameHashEntry *) hash_search(names_hash,
3976 refname,
3977 HASH_ENTER,
3978 &found);
3979 if (found)
3980 {
3981 /* Name already in use, must choose a new one */
3982 int refnamelen = strlen(refname);
3983 char *modname = (char *) palloc(refnamelen + 16);
3984 NameHashEntry *hentry2;
3985
3986 do
3987 {
3988 hentry->counter++;
3989 for (;;)
3990 {
3991 memcpy(modname, refname, refnamelen);
3992 sprintf(modname + refnamelen, "_%d", hentry->counter);
3993 if (strlen(modname) < NAMEDATALEN)
3994 break;
3995 /* drop chars from refname to keep all the digits */
3996 refnamelen = pg_mbcliplen(refname, refnamelen,
3997 refnamelen - 1);
3998 }
3999 hentry2 = (NameHashEntry *) hash_search(names_hash,
4000 modname,
4001 HASH_ENTER,
4002 &found);
4003 } while (found);
4004 hentry2->counter = 0; /* init new hash entry */
4005 refname = modname;
4006 }
4007 else
4008 {
4009 /* Name not previously used, need only initialize hentry */
4010 hentry->counter = 0;
4011 }
4012 }
4013
4014 dpns->rtable_names = lappend(dpns->rtable_names, refname);
4015 rtindex++;
4016 }
4017
4018 hash_destroy(names_hash);
4019}
4020
4021/*
4022 * set_deparse_for_query: set up deparse_namespace for deparsing a Query tree
4023 *
4024 * For convenience, this is defined to initialize the deparse_namespace struct
4025 * from scratch.
4026 */
4027static void
4029 List *parent_namespaces)
4030{
4031 ListCell *lc;
4032 ListCell *lc2;
4033
4034 /* Initialize *dpns and fill rtable/ctes links */
4035 memset(dpns, 0, sizeof(deparse_namespace));
4036 dpns->rtable = query->rtable;
4037 dpns->subplans = NIL;
4038 dpns->ctes = query->cteList;
4039 dpns->appendrels = NULL;
4040 dpns->ret_old_alias = query->returningOldAlias;
4041 dpns->ret_new_alias = query->returningNewAlias;
4042
4043 /* Assign a unique relation alias to each RTE */
4044 set_rtable_names(dpns, parent_namespaces, NULL);
4045
4046 /* Initialize dpns->rtable_columns to contain zeroed structs */
4047 dpns->rtable_columns = NIL;
4048 while (list_length(dpns->rtable_columns) < list_length(dpns->rtable))
4050 palloc0(sizeof(deparse_columns)));
4051
4052 /* If it's a utility query, it won't have a jointree */
4053 if (query->jointree)
4054 {
4055 /* Detect whether global uniqueness of USING names is needed */
4056 dpns->unique_using =
4057 has_dangerous_join_using(dpns, (Node *) query->jointree);
4058
4059 /*
4060 * Select names for columns merged by USING, via a recursive pass over
4061 * the query jointree.
4062 */
4063 set_using_names(dpns, (Node *) query->jointree, NIL);
4064 }
4065
4066 /*
4067 * Now assign remaining column aliases for each RTE. We do this in a
4068 * linear scan of the rtable, so as to process RTEs whether or not they
4069 * are in the jointree (we mustn't miss NEW.*, INSERT target relations,
4070 * etc). JOIN RTEs must be processed after their children, but this is
4071 * okay because they appear later in the rtable list than their children
4072 * (cf Asserts in identify_join_columns()).
4073 */
4074 forboth(lc, dpns->rtable, lc2, dpns->rtable_columns)
4075 {
4076 RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
4077 deparse_columns *colinfo = (deparse_columns *) lfirst(lc2);
4078
4079 if (rte->rtekind == RTE_JOIN)
4080 set_join_column_names(dpns, rte, colinfo);
4081 else
4082 set_relation_column_names(dpns, rte, colinfo);
4083 }
4084}
4085
4086/*
4087 * set_simple_column_names: fill in column aliases for non-query situations
4088 *
4089 * This handles EXPLAIN and cases where we only have relation RTEs. Without
4090 * a join tree, we can't do anything smart about join RTEs, but we don't
4091 * need to, because EXPLAIN should never see join alias Vars anyway.
4092 * If we find a join RTE we'll just skip it, leaving its deparse_columns
4093 * struct all-zero. If somehow we try to deparse a join alias Var, we'll
4094 * error out cleanly because the struct's num_cols will be zero.
4095 */
4096static void
4098{
4099 ListCell *lc;
4100 ListCell *lc2;
4101
4102 /* Initialize dpns->rtable_columns to contain zeroed structs */
4103 dpns->rtable_columns = NIL;
4104 while (list_length(dpns->rtable_columns) < list_length(dpns->rtable))
4106 palloc0(sizeof(deparse_columns)));
4107
4108 /* Assign unique column aliases within each non-join RTE */
4109 forboth(lc, dpns->rtable, lc2, dpns->rtable_columns)
4110 {
4111 RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
4112 deparse_columns *colinfo = (deparse_columns *) lfirst(lc2);
4113
4114 if (rte->rtekind != RTE_JOIN)
4115 set_relation_column_names(dpns, rte, colinfo);
4116 }
4117}
4118
4119/*
4120 * has_dangerous_join_using: search jointree for unnamed JOIN USING
4121 *
4122 * Merged columns of a JOIN USING may act differently from either of the input
4123 * columns, either because they are merged with COALESCE (in a FULL JOIN) or
4124 * because an implicit coercion of the underlying input column is required.
4125 * In such a case the column must be referenced as a column of the JOIN not as
4126 * a column of either input. And this is problematic if the join is unnamed
4127 * (alias-less): we cannot qualify the column's name with an RTE name, since
4128 * there is none. (Forcibly assigning an alias to the join is not a solution,
4129 * since that will prevent legal references to tables below the join.)
4130 * To ensure that every column in the query is unambiguously referenceable,
4131 * we must assign such merged columns names that are globally unique across
4132 * the whole query, aliasing other columns out of the way as necessary.
4133 *
4134 * Because the ensuing re-aliasing is fairly damaging to the readability of
4135 * the query, we don't do this unless we have to. So, we must pre-scan
4136 * the join tree to see if we have to, before starting set_using_names().
4137 */
4138static bool
4140{
4141 if (IsA(jtnode, RangeTblRef))
4142 {
4143 /* nothing to do here */
4144 }
4145 else if (IsA(jtnode, FromExpr))
4146 {
4147 FromExpr *f = (FromExpr *) jtnode;
4148 ListCell *lc;
4149
4150 foreach(lc, f->fromlist)
4151 {
4152 if (has_dangerous_join_using(dpns, (Node *) lfirst(lc)))
4153 return true;
4154 }
4155 }
4156 else if (IsA(jtnode, JoinExpr))
4157 {
4158 JoinExpr *j = (JoinExpr *) jtnode;
4159
4160 /* Is it an unnamed JOIN with USING? */
4161 if (j->alias == NULL && j->usingClause)
4162 {
4163 /*
4164 * Yes, so check each join alias var to see if any of them are not
4165 * simple references to underlying columns. If so, we have a
4166 * dangerous situation and must pick unique aliases.
4167 */
4168 RangeTblEntry *jrte = rt_fetch(j->rtindex, dpns->rtable);
4169
4170 /* We need only examine the merged columns */
4171 for (int i = 0; i < jrte->joinmergedcols; i++)
4172 {
4173 Node *aliasvar = list_nth(jrte->joinaliasvars, i);
4174
4175 if (!IsA(aliasvar, Var))
4176 return true;
4177 }
4178 }
4179
4180 /* Nope, but inspect children */
4181 if (has_dangerous_join_using(dpns, j->larg))
4182 return true;
4183 if (has_dangerous_join_using(dpns, j->rarg))
4184 return true;
4185 }
4186 else
4187 elog(ERROR, "unrecognized node type: %d",
4188 (int) nodeTag(jtnode));
4189 return false;
4190}
4191
4192/*
4193 * set_using_names: select column aliases to be used for merged USING columns
4194 *
4195 * We do this during a recursive descent of the query jointree.
4196 * dpns->unique_using must already be set to determine the global strategy.
4197 *
4198 * Column alias info is saved in the dpns->rtable_columns list, which is
4199 * assumed to be filled with pre-zeroed deparse_columns structs.
4200 *
4201 * parentUsing is a list of all USING aliases assigned in parent joins of
4202 * the current jointree node. (The passed-in list must not be modified.)
4203 *
4204 * Note that we do not use per-deparse_columns hash tables in this function.
4205 * The number of names that need to be assigned should be small enough that
4206 * we don't need to trouble with that.
4207 */
4208static void
4209set_using_names(deparse_namespace *dpns, Node *jtnode, List *parentUsing)
4210{
4211 if (IsA(jtnode, RangeTblRef))
4212 {
4213 /* nothing to do now */
4214 }
4215 else if (IsA(jtnode, FromExpr))
4216 {
4217 FromExpr *f = (FromExpr *) jtnode;
4218 ListCell *lc;
4219
4220 foreach(lc, f->fromlist)
4221 set_using_names(dpns, (Node *) lfirst(lc), parentUsing);
4222 }
4223 else if (IsA(jtnode, JoinExpr))
4224 {
4225 JoinExpr *j = (JoinExpr *) jtnode;
4226 RangeTblEntry *rte = rt_fetch(j->rtindex, dpns->rtable);
4227 deparse_columns *colinfo = deparse_columns_fetch(j->rtindex, dpns);
4228 int *leftattnos;
4229 int *rightattnos;
4230 deparse_columns *leftcolinfo;
4231 deparse_columns *rightcolinfo;
4232 int i;
4233 ListCell *lc;
4234
4235 /* Get info about the shape of the join */
4236 identify_join_columns(j, rte, colinfo);
4237 leftattnos = colinfo->leftattnos;
4238 rightattnos = colinfo->rightattnos;
4239
4240 /* Look up the not-yet-filled-in child deparse_columns structs */
4241 leftcolinfo = deparse_columns_fetch(colinfo->leftrti, dpns);
4242 rightcolinfo = deparse_columns_fetch(colinfo->rightrti, dpns);
4243
4244 /*
4245 * If this join is unnamed, then we cannot substitute new aliases at
4246 * this level, so any name requirements pushed down to here must be
4247 * pushed down again to the children.
4248 */
4249 if (rte->alias == NULL)
4250 {
4251 for (i = 0; i < colinfo->num_cols; i++)
4252 {
4253 char *colname = colinfo->colnames[i];
4254
4255 if (colname == NULL)
4256 continue;
4257
4258 /* Push down to left column, unless it's a system column */
4259 if (leftattnos[i] > 0)
4260 {
4261 expand_colnames_array_to(leftcolinfo, leftattnos[i]);
4262 leftcolinfo->colnames[leftattnos[i] - 1] = colname;
4263 }
4264
4265 /* Same on the righthand side */
4266 if (rightattnos[i] > 0)
4267 {
4268 expand_colnames_array_to(rightcolinfo, rightattnos[i]);
4269 rightcolinfo->colnames[rightattnos[i] - 1] = colname;
4270 }
4271 }
4272 }
4273
4274 /*
4275 * If there's a USING clause, select the USING column names and push
4276 * those names down to the children. We have two strategies:
4277 *
4278 * If dpns->unique_using is true, we force all USING names to be
4279 * unique across the whole query level. In principle we'd only need
4280 * the names of dangerous USING columns to be globally unique, but to
4281 * safely assign all USING names in a single pass, we have to enforce
4282 * the same uniqueness rule for all of them. However, if a USING
4283 * column's name has been pushed down from the parent, we should use
4284 * it as-is rather than making a uniqueness adjustment. This is
4285 * necessary when we're at an unnamed join, and it creates no risk of
4286 * ambiguity. Also, if there's a user-written output alias for a
4287 * merged column, we prefer to use that rather than the input name;
4288 * this simplifies the logic and seems likely to lead to less aliasing
4289 * overall.
4290 *
4291 * If dpns->unique_using is false, we only need USING names to be
4292 * unique within their own join RTE. We still need to honor
4293 * pushed-down names, though.
4294 *
4295 * Though significantly different in results, these two strategies are
4296 * implemented by the same code, with only the difference of whether
4297 * to put assigned names into dpns->using_names.
4298 */
4299 if (j->usingClause)
4300 {
4301 /* Copy the input parentUsing list so we don't modify it */
4302 parentUsing = list_copy(parentUsing);
4303
4304 /* USING names must correspond to the first join output columns */
4305 expand_colnames_array_to(colinfo, list_length(j->usingClause));
4306 i = 0;
4307 foreach(lc, j->usingClause)
4308 {
4309 char *colname = strVal(lfirst(lc));
4310
4311 /* Assert it's a merged column */
4312 Assert(leftattnos[i] != 0 && rightattnos[i] != 0);
4313
4314 /* Adopt passed-down name if any, else select unique name */
4315 if (colinfo->colnames[i] != NULL)
4316 colname = colinfo->colnames[i];
4317 else
4318 {
4319 /* Prefer user-written output alias if any */
4320 if (rte->alias && i < list_length(rte->alias->colnames))
4321 colname = strVal(list_nth(rte->alias->colnames, i));
4322 /* Make it appropriately unique */
4323 colname = make_colname_unique(colname, dpns, colinfo);
4324 if (dpns->unique_using)
4325 dpns->using_names = lappend(dpns->using_names,
4326 colname);
4327 /* Save it as output column name, too */
4328 colinfo->colnames[i] = colname;
4329 }
4330
4331 /* Remember selected names for use later */
4332 colinfo->usingNames = lappend(colinfo->usingNames, colname);
4333 parentUsing = lappend(parentUsing, colname);
4334
4335 /* Push down to left column, unless it's a system column */
4336 if (leftattnos[i] > 0)
4337 {
4338 expand_colnames_array_to(leftcolinfo, leftattnos[i]);
4339 leftcolinfo->colnames[leftattnos[i] - 1] = colname;
4340 }
4341
4342 /* Same on the righthand side */
4343 if (rightattnos[i] > 0)
4344 {
4345 expand_colnames_array_to(rightcolinfo, rightattnos[i]);
4346 rightcolinfo->colnames[rightattnos[i] - 1] = colname;
4347 }
4348
4349 i++;
4350 }
4351 }
4352
4353 /* Mark child deparse_columns structs with correct parentUsing info */
4354 leftcolinfo->parentUsing = parentUsing;
4355 rightcolinfo->parentUsing = parentUsing;
4356
4357 /* Now recursively assign USING column names in children */
4358 set_using_names(dpns, j->larg, parentUsing);
4359 set_using_names(dpns, j->rarg, parentUsing);
4360 }
4361 else
4362 elog(ERROR, "unrecognized node type: %d",
4363 (int) nodeTag(jtnode));
4364}
4365
4366/*
4367 * set_relation_column_names: select column aliases for a non-join RTE
4368 *
4369 * Column alias info is saved in *colinfo, which is assumed to be pre-zeroed.
4370 * If any colnames entries are already filled in, those override local
4371 * choices.
4372 */
4373static void
4375 deparse_columns *colinfo)
4376{
4377 int ncolumns;
4378 char **real_colnames;
4379 bool changed_any;
4380 int noldcolumns;
4381 int i;
4382 int j;
4383
4384 /*
4385 * Construct an array of the current "real" column names of the RTE.
4386 * real_colnames[] will be indexed by physical column number, with NULL
4387 * entries for dropped columns.
4388 */
4389 if (rte->rtekind == RTE_RELATION)
4390 {
4391 /* Relation --- look to the system catalogs for up-to-date info */
4392 Relation rel;
4393 TupleDesc tupdesc;
4394
4395 rel = relation_open(rte->relid, AccessShareLock);
4396 tupdesc = RelationGetDescr(rel);
4397
4398 ncolumns = tupdesc->natts;
4399 real_colnames = (char **) palloc(ncolumns * sizeof(char *));
4400
4401 for (i = 0; i < ncolumns; i++)
4402 {
4403 Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
4404
4405 if (attr->attisdropped)
4406 real_colnames[i] = NULL;
4407 else
4408 real_colnames[i] = pstrdup(NameStr(attr->attname));
4409 }
4411 }
4412 else
4413 {
4414 /* Otherwise get the column names from eref or expandRTE() */
4415 List *colnames;
4416 ListCell *lc;
4417
4418 /*
4419 * Functions returning composites have the annoying property that some
4420 * of the composite type's columns might have been dropped since the
4421 * query was parsed. If possible, use expandRTE() to handle that
4422 * case, since it has the tedious logic needed to find out about
4423 * dropped columns. However, if we're explaining a plan, then we
4424 * don't have rte->functions because the planner thinks that won't be
4425 * needed later, and that breaks expandRTE(). So in that case we have
4426 * to rely on rte->eref, which may lead us to report a dropped
4427 * column's old name; that seems close enough for EXPLAIN's purposes.
4428 *
4429 * For non-RELATION, non-FUNCTION RTEs, we can just look at rte->eref,
4430 * which should be sufficiently up-to-date: no other RTE types can
4431 * have columns get dropped from under them after parsing.
4432 */
4433 if (rte->rtekind == RTE_FUNCTION && rte->functions != NIL)
4434 {
4435 /* Since we're not creating Vars, rtindex etc. don't matter */
4436 expandRTE(rte, 1, 0, VAR_RETURNING_DEFAULT, -1,
4437 true /* include dropped */ , &colnames, NULL);
4438 }
4439 else
4440 colnames = rte->eref->colnames;
4441
4442 ncolumns = list_length(colnames);
4443 real_colnames = (char **) palloc(ncolumns * sizeof(char *));
4444
4445 i = 0;
4446 foreach(lc, colnames)
4447 {
4448 /*
4449 * If the column name we find here is an empty string, then it's a
4450 * dropped column, so change to NULL.
4451 */
4452 char *cname = strVal(lfirst(lc));
4453
4454 if (cname[0] == '\0')
4455 cname = NULL;
4456 real_colnames[i] = cname;
4457 i++;
4458 }
4459 }
4460
4461 /*
4462 * Ensure colinfo->colnames has a slot for each column. (It could be long
4463 * enough already, if we pushed down a name for the last column.) Note:
4464 * it's possible that there are now more columns than there were when the
4465 * query was parsed, ie colnames could be longer than rte->eref->colnames.
4466 * We must assign unique aliases to the new columns too, else there could
4467 * be unresolved conflicts when the view/rule is reloaded.
4468 */
4469 expand_colnames_array_to(colinfo, ncolumns);
4470 Assert(colinfo->num_cols == ncolumns);
4471
4472 /*
4473 * Make sufficiently large new_colnames and is_new_col arrays, too.
4474 *
4475 * Note: because we leave colinfo->num_new_cols zero until after the loop,
4476 * colname_is_unique will not consult that array, which is fine because it
4477 * would only be duplicate effort.
4478 */
4479 colinfo->new_colnames = (char **) palloc(ncolumns * sizeof(char *));
4480 colinfo->is_new_col = (bool *) palloc(ncolumns * sizeof(bool));
4481
4482 /* If the RTE is wide enough, use a hash table to avoid O(N^2) costs */
4483 build_colinfo_names_hash(colinfo);
4484
4485 /*
4486 * Scan the columns, select a unique alias for each one, and store it in
4487 * colinfo->colnames and colinfo->new_colnames. The former array has NULL
4488 * entries for dropped columns, the latter omits them. Also mark
4489 * new_colnames entries as to whether they are new since parse time; this
4490 * is the case for entries beyond the length of rte->eref->colnames.
4491 */
4492 noldcolumns = list_length(rte->eref->colnames);
4493 changed_any = false;
4494 j = 0;
4495 for (i = 0; i < ncolumns; i++)
4496 {
4497 char *real_colname = real_colnames[i];
4498 char *colname = colinfo->colnames[i];
4499
4500 /* Skip dropped columns */
4501 if (real_colname == NULL)
4502 {
4503 Assert(colname == NULL); /* colnames[i] is already NULL */
4504 continue;
4505 }
4506
4507 /* If alias already assigned, that's what to use */
4508 if (colname == NULL)
4509 {
4510 /* If user wrote an alias, prefer that over real column name */
4511 if (rte->alias && i < list_length(rte->alias->colnames))
4512 colname = strVal(list_nth(rte->alias->colnames, i));
4513 else
4514 colname = real_colname;
4515
4516 /* Unique-ify and insert into colinfo */
4517 colname = make_colname_unique(colname, dpns, colinfo);
4518
4519 colinfo->colnames[i] = colname;
4520 add_to_names_hash(colinfo, colname);
4521 }
4522
4523 /* Put names of non-dropped columns in new_colnames[] too */
4524 colinfo->new_colnames[j] = colname;
4525 /* And mark them as new or not */
4526 colinfo->is_new_col[j] = (i >= noldcolumns);
4527 j++;
4528
4529 /* Remember if any assigned aliases differ from "real" name */
4530 if (!changed_any && strcmp(colname, real_colname) != 0)
4531 changed_any = true;
4532 }
4533
4534 /* We're now done needing the colinfo's names_hash */
4536
4537 /*
4538 * Set correct length for new_colnames[] array. (Note: if columns have
4539 * been added, colinfo->num_cols includes them, which is not really quite
4540 * right but is harmless, since any new columns must be at the end where
4541 * they won't affect varattnos of pre-existing columns.)
4542 */
4543 colinfo->num_new_cols = j;
4544
4545 /*
4546 * For a relation RTE, we need only print the alias column names if any
4547 * are different from the underlying "real" names. For a function RTE,
4548 * always emit a complete column alias list; this is to protect against
4549 * possible instability of the default column names (eg, from altering
4550 * parameter names). For tablefunc RTEs, we never print aliases, because
4551 * the column names are part of the clause itself. For other RTE types,
4552 * print if we changed anything OR if there were user-written column
4553 * aliases (since the latter would be part of the underlying "reality").
4554 */
4555 if (rte->rtekind == RTE_RELATION)
4556 colinfo->printaliases = changed_any;
4557 else if (rte->rtekind == RTE_FUNCTION)
4558 colinfo->printaliases = true;
4559 else if (rte->rtekind == RTE_TABLEFUNC)
4560 colinfo->printaliases = false;
4561 else if (rte->alias && rte->alias->colnames != NIL)
4562 colinfo->printaliases = true;
4563 else
4564 colinfo->printaliases = changed_any;
4565}
4566
4567/*
4568 * set_join_column_names: select column aliases for a join RTE
4569 *
4570 * Column alias info is saved in *colinfo, which is assumed to be pre-zeroed.
4571 * If any colnames entries are already filled in, those override local
4572 * choices. Also, names for USING columns were already chosen by
4573 * set_using_names(). We further expect that column alias selection has been
4574 * completed for both input RTEs.
4575 */
4576static void
4578 deparse_columns *colinfo)
4579{
4580 deparse_columns *leftcolinfo;
4581 deparse_columns *rightcolinfo;
4582 bool changed_any;
4583 int noldcolumns;
4584 int nnewcolumns;
4585 Bitmapset *leftmerged = NULL;
4586 Bitmapset *rightmerged = NULL;
4587 int i;
4588 int j;
4589 int ic;
4590 int jc;
4591
4592 /* Look up the previously-filled-in child deparse_columns structs */
4593 leftcolinfo = deparse_columns_fetch(colinfo->leftrti, dpns);
4594 rightcolinfo = deparse_columns_fetch(colinfo->rightrti, dpns);
4595
4596 /*
4597 * Ensure colinfo->colnames has a slot for each column. (It could be long
4598 * enough already, if we pushed down a name for the last column.) Note:
4599 * it's possible that one or both inputs now have more columns than there
4600 * were when the query was parsed, but we'll deal with that below. We
4601 * only need entries in colnames for pre-existing columns.
4602 */
4603 noldcolumns = list_length(rte->eref->colnames);
4604 expand_colnames_array_to(colinfo, noldcolumns);
4605 Assert(colinfo->num_cols == noldcolumns);
4606
4607 /* If the RTE is wide enough, use a hash table to avoid O(N^2) costs */
4608 build_colinfo_names_hash(colinfo);
4609
4610 /*
4611 * Scan the join output columns, select an alias for each one, and store
4612 * it in colinfo->colnames. If there are USING columns, set_using_names()
4613 * already selected their names, so we can start the loop at the first
4614 * non-merged column.
4615 */
4616 changed_any = false;
4617 for (i = list_length(colinfo->usingNames); i < noldcolumns; i++)
4618 {
4619 char *colname = colinfo->colnames[i];
4620 char *real_colname;
4621
4622 /* Join column must refer to at least one input column */
4623 Assert(colinfo->leftattnos[i] != 0 || colinfo->rightattnos[i] != 0);
4624
4625 /* Get the child column name */
4626 if (colinfo->leftattnos[i] > 0)
4627 real_colname = leftcolinfo->colnames[colinfo->leftattnos[i] - 1];
4628 else if (colinfo->rightattnos[i] > 0)
4629 real_colname = rightcolinfo->colnames[colinfo->rightattnos[i] - 1];
4630 else
4631 {
4632 /* We're joining system columns --- use eref name */
4633 real_colname = strVal(list_nth(rte->eref->colnames, i));
4634 }
4635
4636 /* If child col has been dropped, no need to assign a join colname */
4637 if (real_colname == NULL)
4638 {
4639 colinfo->colnames[i] = NULL;
4640 continue;
4641 }
4642
4643 /* In an unnamed join, just report child column names as-is */
4644 if (rte->alias == NULL)
4645 {
4646 colinfo->colnames[i] = real_colname;
4647 add_to_names_hash(colinfo, real_colname);
4648 continue;
4649 }
4650
4651 /* If alias already assigned, that's what to use */
4652 if (colname == NULL)
4653 {
4654 /* If user wrote an alias, prefer that over real column name */
4655 if (rte->alias && i < list_length(rte->alias->colnames))
4656 colname = strVal(list_nth(rte->alias->colnames, i));
4657 else
4658 colname = real_colname;
4659
4660 /* Unique-ify and insert into colinfo */
4661 colname = make_colname_unique(colname, dpns, colinfo);
4662
4663 colinfo->colnames[i] = colname;
4664 add_to_names_hash(colinfo, colname);
4665 }
4666
4667 /* Remember if any assigned aliases differ from "real" name */
4668 if (!changed_any && strcmp(colname, real_colname) != 0)
4669 changed_any = true;
4670 }
4671
4672 /*
4673 * Calculate number of columns the join would have if it were re-parsed
4674 * now, and create storage for the new_colnames and is_new_col arrays.
4675 *
4676 * Note: colname_is_unique will be consulting new_colnames[] during the
4677 * loops below, so its not-yet-filled entries must be zeroes.
4678 */
4679 nnewcolumns = leftcolinfo->num_new_cols + rightcolinfo->num_new_cols -
4680 list_length(colinfo->usingNames);
4681 colinfo->num_new_cols = nnewcolumns;
4682 colinfo->new_colnames = (char **) palloc0(nnewcolumns * sizeof(char *));
4683 colinfo->is_new_col = (bool *) palloc0(nnewcolumns * sizeof(bool));
4684
4685 /*
4686 * Generating the new_colnames array is a bit tricky since any new columns
4687 * added since parse time must be inserted in the right places. This code
4688 * must match the parser, which will order a join's columns as merged
4689 * columns first (in USING-clause order), then non-merged columns from the
4690 * left input (in attnum order), then non-merged columns from the right
4691 * input (ditto). If one of the inputs is itself a join, its columns will
4692 * be ordered according to the same rule, which means newly-added columns
4693 * might not be at the end. We can figure out what's what by consulting
4694 * the leftattnos and rightattnos arrays plus the input is_new_col arrays.
4695 *
4696 * In these loops, i indexes leftattnos/rightattnos (so it's join varattno
4697 * less one), j indexes new_colnames/is_new_col, and ic/jc have similar
4698 * meanings for the current child RTE.
4699 */
4700
4701 /* Handle merged columns; they are first and can't be new */
4702 i = j = 0;
4703 while (i < noldcolumns &&
4704 colinfo->leftattnos[i] != 0 &&
4705 colinfo->rightattnos[i] != 0)
4706 {
4707 /* column name is already determined and known unique */
4708 colinfo->new_colnames[j] = colinfo->colnames[i];
4709 colinfo->is_new_col[j] = false;
4710
4711 /* build bitmapsets of child attnums of merged columns */
4712 if (colinfo->leftattnos[i] > 0)
4713 leftmerged = bms_add_member(leftmerged, colinfo->leftattnos[i]);
4714 if (colinfo->rightattnos[i] > 0)
4715 rightmerged = bms_add_member(rightmerged, colinfo->rightattnos[i]);
4716
4717 i++, j++;
4718 }
4719
4720 /* Handle non-merged left-child columns */
4721 ic = 0;
4722 for (jc = 0; jc < leftcolinfo->num_new_cols; jc++)
4723 {
4724 char *child_colname = leftcolinfo->new_colnames[jc];
4725
4726 if (!leftcolinfo->is_new_col[jc])
4727 {
4728 /* Advance ic to next non-dropped old column of left child */
4729 while (ic < leftcolinfo->num_cols &&
4730 leftcolinfo->colnames[ic] == NULL)
4731 ic++;
4732 Assert(ic < leftcolinfo->num_cols);
4733 ic++;
4734 /* If it is a merged column, we already processed it */
4735 if (bms_is_member(ic, leftmerged))
4736 continue;
4737 /* Else, advance i to the corresponding existing join column */
4738 while (i < colinfo->num_cols &&
4739 colinfo->colnames[i] == NULL)
4740 i++;
4741 Assert(i < colinfo->num_cols);
4742 Assert(ic == colinfo->leftattnos[i]);
4743 /* Use the already-assigned name of this column */
4744 colinfo->new_colnames[j] = colinfo->colnames[i];
4745 i++;
4746 }
4747 else
4748 {
4749 /*
4750 * Unique-ify the new child column name and assign, unless we're
4751 * in an unnamed join, in which case just copy
4752 */
4753 if (rte->alias != NULL)
4754 {
4755 colinfo->new_colnames[j] =
4756 make_colname_unique(child_colname, dpns, colinfo);
4757 if (!changed_any &&
4758 strcmp(colinfo->new_colnames[j], child_colname) != 0)
4759 changed_any = true;
4760 }
4761 else
4762 colinfo->new_colnames[j] = child_colname;
4763 add_to_names_hash(colinfo, colinfo->new_colnames[j]);
4764 }
4765
4766 colinfo->is_new_col[j] = leftcolinfo->is_new_col[jc];
4767 j++;
4768 }
4769
4770 /* Handle non-merged right-child columns in exactly the same way */
4771 ic = 0;
4772 for (jc = 0; jc < rightcolinfo->num_new_cols; jc++)
4773 {
4774 char *child_colname = rightcolinfo->new_colnames[jc];
4775
4776 if (!rightcolinfo->is_new_col[jc])
4777 {
4778 /* Advance ic to next non-dropped old column of right child */
4779 while (ic < rightcolinfo->num_cols &&
4780 rightcolinfo->colnames[ic] == NULL)
4781 ic++;
4782 Assert(ic < rightcolinfo->num_cols);
4783 ic++;
4784 /* If it is a merged column, we already processed it */
4785 if (bms_is_member(ic, rightmerged))
4786 continue;
4787 /* Else, advance i to the corresponding existing join column */
4788 while (i < colinfo->num_cols &&
4789 colinfo->colnames[i] == NULL)
4790 i++;
4791 Assert(i < colinfo->num_cols);
4792 Assert(ic == colinfo->rightattnos[i]);
4793 /* Use the already-assigned name of this column */
4794 colinfo->new_colnames[j] = colinfo->colnames[i];
4795 i++;
4796 }
4797 else
4798 {
4799 /*
4800 * Unique-ify the new child column name and assign, unless we're
4801 * in an unnamed join, in which case just copy
4802 */
4803 if (rte->alias != NULL)
4804 {
4805 colinfo->new_colnames[j] =
4806 make_colname_unique(child_colname, dpns, colinfo);
4807 if (!changed_any &&
4808 strcmp(colinfo->new_colnames[j], child_colname) != 0)
4809 changed_any = true;
4810 }
4811 else
4812 colinfo->new_colnames[j] = child_colname;
4813 add_to_names_hash(colinfo, colinfo->new_colnames[j]);
4814 }
4815
4816 colinfo->is_new_col[j] = rightcolinfo->is_new_col[jc];
4817 j++;
4818 }
4819
4820 /* Assert we processed the right number of columns */
4821#ifdef USE_ASSERT_CHECKING
4822 while (i < colinfo->num_cols && colinfo->colnames[i] == NULL)
4823 i++;
4824 Assert(i == colinfo->num_cols);
4825 Assert(j == nnewcolumns);
4826#endif
4827
4828 /* We're now done needing the colinfo's names_hash */
4830
4831 /*
4832 * For a named join, print column aliases if we changed any from the child
4833 * names. Unnamed joins cannot print aliases.
4834 */
4835 if (rte->alias != NULL)
4836 colinfo->printaliases = changed_any;
4837 else
4838 colinfo->printaliases = false;
4839}
4840
4841/*
4842 * colname_is_unique: is colname distinct from already-chosen column names?
4843 *
4844 * dpns is query-wide info, colinfo is for the column's RTE
4845 */
4846static bool
4847colname_is_unique(const char *colname, deparse_namespace *dpns,
4848 deparse_columns *colinfo)
4849{
4850 int i;
4851 ListCell *lc;
4852
4853 /*
4854 * If we have a hash table, consult that instead of linearly scanning the
4855 * colinfo's strings.
4856 */
4857 if (colinfo->names_hash)
4858 {
4859 if (hash_search(colinfo->names_hash,
4860 colname,
4861 HASH_FIND,
4862 NULL) != NULL)
4863 return false;
4864 }
4865 else
4866 {
4867 /* Check against already-assigned column aliases within RTE */
4868 for (i = 0; i < colinfo->num_cols; i++)
4869 {
4870 char *oldname = colinfo->colnames[i];
4871
4872 if (oldname && strcmp(oldname, colname) == 0)
4873 return false;
4874 }
4875
4876 /*
4877 * If we're building a new_colnames array, check that too (this will
4878 * be partially but not completely redundant with the previous checks)
4879 */
4880 for (i = 0; i < colinfo->num_new_cols; i++)
4881 {
4882 char *oldname = colinfo->new_colnames[i];
4883
4884 if (oldname && strcmp(oldname, colname) == 0)
4885 return false;
4886 }
4887
4888 /*
4889 * Also check against names already assigned for parent-join USING
4890 * cols
4891 */
4892 foreach(lc, colinfo->parentUsing)
4893 {
4894 char *oldname = (char *) lfirst(lc);
4895
4896 if (strcmp(oldname, colname) == 0)
4897 return false;
4898 }
4899 }
4900
4901 /*
4902 * Also check against USING-column names that must be globally unique.
4903 * These are not hashed, but there should be few of them.
4904 */
4905 foreach(lc, dpns->using_names)
4906 {
4907 char *oldname = (char *) lfirst(lc);
4908
4909 if (strcmp(oldname, colname) == 0)
4910 return false;
4911 }
4912
4913 return true;
4914}
4915
4916/*
4917 * make_colname_unique: modify colname if necessary to make it unique
4918 *
4919 * dpns is query-wide info, colinfo is for the column's RTE
4920 */
4921static char *
4923 deparse_columns *colinfo)
4924{
4925 /*
4926 * If the selected name isn't unique, append digits to make it so. For a
4927 * very long input name, we might have to truncate to stay within
4928 * NAMEDATALEN.
4929 */
4930 if (!colname_is_unique(colname, dpns, colinfo))
4931 {
4932 int colnamelen = strlen(colname);
4933 char *modname = (char *) palloc(colnamelen + 16);
4934 int i = 0;
4935
4936 do
4937 {
4938 i++;
4939 for (;;)
4940 {
4941 memcpy(modname, colname, colnamelen);
4942 sprintf(modname + colnamelen, "_%d", i);
4943 if (strlen(modname) < NAMEDATALEN)
4944 break;
4945 /* drop chars from colname to keep all the digits */
4946 colnamelen = pg_mbcliplen(colname, colnamelen,
4947 colnamelen - 1);
4948 }
4949 } while (!colname_is_unique(modname, dpns, colinfo));
4950 colname = modname;
4951 }
4952 return colname;
4953}
4954
4955/*
4956 * expand_colnames_array_to: make colinfo->colnames at least n items long
4957 *
4958 * Any added array entries are initialized to zero.
4959 */
4960static void
4962{
4963 if (n > colinfo->num_cols)
4964 {
4965 if (colinfo->colnames == NULL)
4966 colinfo->colnames = palloc0_array(char *, n);
4967 else
4968 colinfo->colnames = repalloc0_array(colinfo->colnames, char *, colinfo->num_cols, n);
4969 colinfo->num_cols = n;
4970 }
4971}
4972
4973/*
4974 * build_colinfo_names_hash: optionally construct a hash table for colinfo
4975 */
4976static void
4978{
4979 HASHCTL hash_ctl;
4980 int i;
4981 ListCell *lc;
4982
4983 /*
4984 * Use a hash table only for RTEs with at least 32 columns. (The cutoff
4985 * is somewhat arbitrary, but let's choose it so that this code does get
4986 * exercised in the regression tests.)
4987 */
4988 if (colinfo->num_cols < 32)
4989 return;
4990
4991 /*
4992 * Set up the hash table. The entries are just strings with no other
4993 * payload.
4994 */
4995 hash_ctl.keysize = NAMEDATALEN;
4996 hash_ctl.entrysize = NAMEDATALEN;
4997 hash_ctl.hcxt = CurrentMemoryContext;
4998 colinfo->names_hash = hash_create("deparse_columns names",
4999 colinfo->num_cols + colinfo->num_new_cols,
5000 &hash_ctl,
5002
5003 /*
5004 * Preload the hash table with any names already present (these would have
5005 * come from set_using_names).
5006 */
5007 for (i = 0; i < colinfo->num_cols; i++)
5008 {
5009 char *oldname = colinfo->colnames[i];
5010
5011 if (oldname)
5012 add_to_names_hash(colinfo, oldname);
5013 }
5014
5015 for (i = 0; i < colinfo->num_new_cols; i++)
5016 {
5017 char *oldname = colinfo->new_colnames[i];
5018
5019 if (oldname)
5020 add_to_names_hash(colinfo, oldname);
5021 }
5022
5023 foreach(lc, colinfo->parentUsing)
5024 {
5025 char *oldname = (char *) lfirst(lc);
5026
5027 add_to_names_hash(colinfo, oldname);
5028 }
5029}
5030
5031/*
5032 * add_to_names_hash: add a string to the names_hash, if we're using one
5033 */
5034static void
5036{
5037 if (colinfo->names_hash)
5038 (void) hash_search(colinfo->names_hash,
5039 name,
5040 HASH_ENTER,
5041 NULL);
5042}
5043
5044/*
5045 * destroy_colinfo_names_hash: destroy hash table when done with it
5046 */
5047static void
5049{
5050 if (colinfo->names_hash)
5051 {
5052 hash_destroy(colinfo->names_hash);
5053 colinfo->names_hash = NULL;
5054 }
5055}
5056
5057/*
5058 * identify_join_columns: figure out where columns of a join come from
5059 *
5060 * Fills the join-specific fields of the colinfo struct, except for
5061 * usingNames which is filled later.
5062 */
5063static void
5065 deparse_columns *colinfo)
5066{
5067 int numjoincols;
5068 int jcolno;
5069 int rcolno;
5070 ListCell *lc;
5071
5072 /* Extract left/right child RT indexes */
5073 if (IsA(j->larg, RangeTblRef))
5074 colinfo->leftrti = ((RangeTblRef *) j->larg)->rtindex;
5075 else if (IsA(j->larg, JoinExpr))
5076 colinfo->leftrti = ((JoinExpr *) j->larg)->rtindex;
5077 else
5078 elog(ERROR, "unrecognized node type in jointree: %d",
5079 (int) nodeTag(j->larg));
5080 if (IsA(j->rarg, RangeTblRef))
5081 colinfo->rightrti = ((RangeTblRef *) j->rarg)->rtindex;
5082 else if (IsA(j->rarg, JoinExpr))
5083 colinfo->rightrti = ((JoinExpr *) j->rarg)->rtindex;
5084 else
5085 elog(ERROR, "unrecognized node type in jointree: %d",
5086 (int) nodeTag(j->rarg));
5087
5088 /* Assert children will be processed earlier than join in second pass */
5089 Assert(colinfo->leftrti < j->rtindex);
5090 Assert(colinfo->rightrti < j->rtindex);
5091
5092 /* Initialize result arrays with zeroes */
5093 numjoincols = list_length(jrte->joinaliasvars);
5094 Assert(numjoincols == list_length(jrte->eref->colnames));
5095 colinfo->leftattnos = (int *) palloc0(numjoincols * sizeof(int));
5096 colinfo->rightattnos = (int *) palloc0(numjoincols * sizeof(int));
5097
5098 /*
5099 * Deconstruct RTE's joinleftcols/joinrightcols into desired format.
5100 * Recall that the column(s) merged due to USING are the first column(s)
5101 * of the join output. We need not do anything special while scanning
5102 * joinleftcols, but while scanning joinrightcols we must distinguish
5103 * merged from unmerged columns.
5104 */
5105 jcolno = 0;
5106 foreach(lc, jrte->joinleftcols)
5107 {
5108 int leftattno = lfirst_int(lc);
5109
5110 colinfo->leftattnos[jcolno++] = leftattno;
5111 }
5112 rcolno = 0;
5113 foreach(lc, jrte->joinrightcols)
5114 {
5115 int rightattno = lfirst_int(lc);
5116
5117 if (rcolno < jrte->joinmergedcols) /* merged column? */
5118 colinfo->rightattnos[rcolno] = rightattno;
5119 else
5120 colinfo->rightattnos[jcolno++] = rightattno;
5121 rcolno++;
5122 }
5123 Assert(jcolno == numjoincols);
5124}
5125
5126/*
5127 * get_rtable_name: convenience function to get a previously assigned RTE alias
5128 *
5129 * The RTE must belong to the topmost namespace level in "context".
5130 */
5131static char *
5132get_rtable_name(int rtindex, deparse_context *context)
5133{
5135
5136 Assert(rtindex > 0 && rtindex <= list_length(dpns->rtable_names));
5137 return (char *) list_nth(dpns->rtable_names, rtindex - 1);
5138}
5139
5140/*
5141 * set_deparse_plan: set up deparse_namespace to parse subexpressions
5142 * of a given Plan node
5143 *
5144 * This sets the plan, outer_plan, inner_plan, outer_tlist, inner_tlist,
5145 * and index_tlist fields. Caller must already have adjusted the ancestors
5146 * list if necessary. Note that the rtable, subplans, and ctes fields do
5147 * not need to change when shifting attention to different plan nodes in a
5148 * single plan tree.
5149 */
5150static void
5152{
5153 dpns->plan = plan;
5154
5155 /*
5156 * We special-case Append and MergeAppend to pretend that the first child
5157 * plan is the OUTER referent; we have to interpret OUTER Vars in their
5158 * tlists according to one of the children, and the first one is the most
5159 * natural choice.
5160 */
5161 if (IsA(plan, Append))
5162 dpns->outer_plan = linitial(((Append *) plan)->appendplans);
5163 else if (IsA(plan, MergeAppend))
5164 dpns->outer_plan = linitial(((MergeAppend *) plan)->mergeplans);
5165 else
5166 dpns->outer_plan = outerPlan(plan);
5167
5168 if (dpns->outer_plan)
5169 dpns->outer_tlist = dpns->outer_plan->targetlist;
5170 else
5171 dpns->outer_tlist = NIL;
5172
5173 /*
5174 * For a SubqueryScan, pretend the subplan is INNER referent. (We don't
5175 * use OUTER because that could someday conflict with the normal meaning.)
5176 * Likewise, for a CteScan, pretend the subquery's plan is INNER referent.
5177 * For a WorkTableScan, locate the parent RecursiveUnion plan node and use
5178 * that as INNER referent.
5179 *
5180 * For MERGE, pretend the ModifyTable's source plan (its outer plan) is
5181 * INNER referent. This is the join from the target relation to the data
5182 * source, and all INNER_VAR Vars in other parts of the query refer to its
5183 * targetlist.
5184 *
5185 * For ON CONFLICT .. UPDATE we just need the inner tlist to point to the
5186 * excluded expression's tlist. (Similar to the SubqueryScan we don't want
5187 * to reuse OUTER, it's used for RETURNING in some modify table cases,
5188 * although not INSERT .. CONFLICT).
5189 */
5190 if (IsA(plan, SubqueryScan))
5191 dpns->inner_plan = ((SubqueryScan *) plan)->subplan;
5192 else if (IsA(plan, CteScan))
5193 dpns->inner_plan = list_nth(dpns->subplans,
5194 ((CteScan *) plan)->ctePlanId - 1);
5195 else if (IsA(plan, WorkTableScan))
5196 dpns->inner_plan = find_recursive_union(dpns,
5197 (WorkTableScan *) plan);
5198 else if (IsA(plan, ModifyTable))
5199 {
5200 if (((ModifyTable *) plan)->operation == CMD_MERGE)
5201 dpns->inner_plan = outerPlan(plan);
5202 else
5203 dpns->inner_plan = plan;
5204 }
5205 else
5206 dpns->inner_plan = innerPlan(plan);
5207
5208 if (IsA(plan, ModifyTable) && ((ModifyTable *) plan)->operation == CMD_INSERT)
5209 dpns->inner_tlist = ((ModifyTable *) plan)->exclRelTlist;
5210 else if (dpns->inner_plan)
5211 dpns->inner_tlist = dpns->inner_plan->targetlist;
5212 else
5213 dpns->inner_tlist = NIL;
5214
5215 /* Set up referent for INDEX_VAR Vars, if needed */
5216 if (IsA(plan, IndexOnlyScan))
5217 dpns->index_tlist = ((IndexOnlyScan *) plan)->indextlist;
5218 else if (IsA(plan, ForeignScan))
5219 dpns->index_tlist = ((ForeignScan *) plan)->fdw_scan_tlist;
5220 else if (IsA(plan, CustomScan))
5221 dpns->index_tlist = ((CustomScan *) plan)->custom_scan_tlist;
5222 else
5223 dpns->index_tlist = NIL;
5224}
5225
5226/*
5227 * Locate the ancestor plan node that is the RecursiveUnion generating
5228 * the WorkTableScan's work table. We can match on wtParam, since that
5229 * should be unique within the plan tree.
5230 */
5231static Plan *
5233{
5234 ListCell *lc;
5235
5236 foreach(lc, dpns->ancestors)
5237 {
5238 Plan *ancestor = (Plan *) lfirst(lc);
5239
5240 if (IsA(ancestor, RecursiveUnion) &&
5241 ((RecursiveUnion *) ancestor)->wtParam == wtscan->wtParam)
5242 return ancestor;
5243 }
5244 elog(ERROR, "could not find RecursiveUnion for WorkTableScan with wtParam %d",
5245 wtscan->wtParam);
5246 return NULL;
5247}
5248
5249/*
5250 * push_child_plan: temporarily transfer deparsing attention to a child plan
5251 *
5252 * When expanding an OUTER_VAR or INNER_VAR reference, we must adjust the
5253 * deparse context in case the referenced expression itself uses
5254 * OUTER_VAR/INNER_VAR. We modify the top stack entry in-place to avoid
5255 * affecting levelsup issues (although in a Plan tree there really shouldn't
5256 * be any).
5257 *
5258 * Caller must provide a local deparse_namespace variable to save the
5259 * previous state for pop_child_plan.
5260 */
5261static void
5263 deparse_namespace *save_dpns)
5264{
5265 /* Save state for restoration later */
5266 *save_dpns = *dpns;
5267
5268 /* Link current plan node into ancestors list */
5269 dpns->ancestors = lcons(dpns->plan, dpns->ancestors);
5270
5271 /* Set attention on selected child */
5272 set_deparse_plan(dpns, plan);
5273}
5274
5275/*
5276 * pop_child_plan: undo the effects of push_child_plan
5277 */
5278static void
5280{
5281 List *ancestors;
5282
5283 /* Get rid of ancestors list cell added by push_child_plan */
5284 ancestors = list_delete_first(dpns->ancestors);
5285
5286 /* Restore fields changed by push_child_plan */
5287 *dpns = *save_dpns;
5288
5289 /* Make sure dpns->ancestors is right (may be unnecessary) */
5290 dpns->ancestors = ancestors;
5291}
5292
5293/*
5294 * push_ancestor_plan: temporarily transfer deparsing attention to an
5295 * ancestor plan
5296 *
5297 * When expanding a Param reference, we must adjust the deparse context
5298 * to match the plan node that contains the expression being printed;
5299 * otherwise we'd fail if that expression itself contains a Param or
5300 * OUTER_VAR/INNER_VAR/INDEX_VAR variable.
5301 *
5302 * The target ancestor is conveniently identified by the ListCell holding it
5303 * in dpns->ancestors.
5304 *
5305 * Caller must provide a local deparse_namespace variable to save the
5306 * previous state for pop_ancestor_plan.
5307 */
5308static void
5310 deparse_namespace *save_dpns)
5311{
5312 Plan *plan = (Plan *) lfirst(ancestor_cell);
5313
5314 /* Save state for restoration later */
5315 *save_dpns = *dpns;
5316
5317 /* Build a new ancestor list with just this node's ancestors */
5318 dpns->ancestors =
5320 list_cell_number(dpns->ancestors, ancestor_cell) + 1);
5321
5322 /* Set attention on selected ancestor */
5323 set_deparse_plan(dpns, plan);
5324}
5325
5326/*
5327 * pop_ancestor_plan: undo the effects of push_ancestor_plan
5328 */
5329static void
5331{
5332 /* Free the ancestor list made in push_ancestor_plan */
5333 list_free(dpns->ancestors);
5334
5335 /* Restore fields changed by push_ancestor_plan */
5336 *dpns = *save_dpns;
5337}
5338
5339
5340/* ----------
5341 * make_ruledef - reconstruct the CREATE RULE command
5342 * for a given pg_rewrite tuple
5343 * ----------
5344 */
5345static void
5347 int prettyFlags)
5348{
5349 char *rulename;
5350 char ev_type;
5351 Oid ev_class;
5352 bool is_instead;
5353 char *ev_qual;
5354 char *ev_action;
5355 List *actions;
5356 Relation ev_relation;
5357 TupleDesc viewResultDesc = NULL;
5358 int fno;
5359 Datum dat;
5360 bool isnull;
5361
5362 /*
5363 * Get the attribute values from the rules tuple
5364 */
5365 fno = SPI_fnumber(rulettc, "rulename");
5366 dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
5367 Assert(!isnull);
5368 rulename = NameStr(*(DatumGetName(dat)));
5369
5370 fno = SPI_fnumber(rulettc, "ev_type");
5371 dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
5372 Assert(!isnull);
5373 ev_type = DatumGetChar(dat);
5374
5375 fno = SPI_fnumber(rulettc, "ev_class");
5376 dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
5377 Assert(!isnull);
5378 ev_class = DatumGetObjectId(dat);
5379
5380 fno = SPI_fnumber(rulettc, "is_instead");
5381 dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
5382 Assert(!isnull);
5383 is_instead = DatumGetBool(dat);
5384
5385 fno = SPI_fnumber(rulettc, "ev_qual");
5386 ev_qual = SPI_getvalue(ruletup, rulettc, fno);
5387 Assert(ev_qual != NULL);
5388
5389 fno = SPI_fnumber(rulettc, "ev_action");
5390 ev_action = SPI_getvalue(ruletup, rulettc, fno);
5391 Assert(ev_action != NULL);
5392 actions = (List *) stringToNode(ev_action);
5393 if (actions == NIL)
5394 elog(ERROR, "invalid empty ev_action list");
5395
5396 ev_relation = table_open(ev_class, AccessShareLock);
5397
5398 /*
5399 * Build the rules definition text
5400 */
5401 appendStringInfo(buf, "CREATE RULE %s AS",
5402 quote_identifier(rulename));
5403
5404 if (prettyFlags & PRETTYFLAG_INDENT)
5405 appendStringInfoString(buf, "\n ON ");
5406 else
5407 appendStringInfoString(buf, " ON ");
5408
5409 /* The event the rule is fired for */
5410 switch (ev_type)
5411 {
5412 case '1':
5413 appendStringInfoString(buf, "SELECT");
5414 viewResultDesc = RelationGetDescr(ev_relation);
5415 break;
5416
5417 case '2':
5418 appendStringInfoString(buf, "UPDATE");
5419 break;
5420
5421 case '3':
5422 appendStringInfoString(buf, "INSERT");
5423 break;
5424
5425 case '4':
5426 appendStringInfoString(buf, "DELETE");
5427 break;
5428
5429 default:
5430 ereport(ERROR,
5431 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5432 errmsg("rule \"%s\" has unsupported event type %d",
5433 rulename, ev_type)));
5434 break;
5435 }
5436
5437 /* The relation the rule is fired on */
5438 appendStringInfo(buf, " TO %s",
5439 (prettyFlags & PRETTYFLAG_SCHEMA) ?
5440 generate_relation_name(ev_class, NIL) :
5442
5443 /* If the rule has an event qualification, add it */
5444 if (strcmp(ev_qual, "<>") != 0)
5445 {
5446 Node *qual;
5447 Query *query;
5448 deparse_context context;
5449 deparse_namespace dpns;
5450
5451 if (prettyFlags & PRETTYFLAG_INDENT)
5453 appendStringInfoString(buf, " WHERE ");
5454
5455 qual = stringToNode(ev_qual);
5456
5457 /*
5458 * We need to make a context for recognizing any Vars in the qual
5459 * (which can only be references to OLD and NEW). Use the rtable of
5460 * the first query in the action list for this purpose.
5461 */
5462 query = (Query *) linitial(actions);
5463
5464 /*
5465 * If the action is INSERT...SELECT, OLD/NEW have been pushed down
5466 * into the SELECT, and that's what we need to look at. (Ugly kluge
5467 * ... try to fix this when we redesign querytrees.)
5468 */
5469 query = getInsertSelectQuery(query, NULL);
5470
5471 /* Must acquire locks right away; see notes in get_query_def() */
5472 AcquireRewriteLocks(query, false, false);
5473
5474 context.buf = buf;
5475 context.namespaces = list_make1(&dpns);
5476 context.resultDesc = NULL;
5477 context.targetList = NIL;
5478 context.windowClause = NIL;
5479 context.varprefix = (list_length(query->rtable) != 1);
5480 context.prettyFlags = prettyFlags;
5482 context.indentLevel = PRETTYINDENT_STD;
5483 context.colNamesVisible = true;
5484 context.inGroupBy = false;
5485 context.varInOrderBy = false;
5486 context.appendparents = NULL;
5487
5488 set_deparse_for_query(&dpns, query, NIL);
5489
5490 get_rule_expr(qual, &context, false);
5491 }
5492
5493 appendStringInfoString(buf, " DO ");
5494
5495 /* The INSTEAD keyword (if so) */
5496 if (is_instead)
5497 appendStringInfoString(buf, "INSTEAD ");
5498
5499 /* Finally the rules actions */
5500 if (list_length(actions) > 1)
5501 {
5503 Query *query;
5504
5506 foreach(action, actions)
5507 {
5508 query = (Query *) lfirst(action);
5509 get_query_def(query, buf, NIL, viewResultDesc, true,
5510 prettyFlags, WRAP_COLUMN_DEFAULT, 0);
5511 if (prettyFlags)
5513 else
5515 }
5517 }
5518 else
5519 {
5520 Query *query;
5521
5522 query = (Query *) linitial(actions);
5523 get_query_def(query, buf, NIL, viewResultDesc, true,
5524 prettyFlags, WRAP_COLUMN_DEFAULT, 0);
5526 }
5527
5528 table_close(ev_relation, AccessShareLock);
5529}
5530
5531
5532/* ----------
5533 * make_viewdef - reconstruct the SELECT part of a
5534 * view rewrite rule
5535 * ----------
5536 */
5537static void
5539 int prettyFlags, int wrapColumn)
5540{
5541 Query *query;
5542 char ev_type;
5543 Oid ev_class;
5544 bool is_instead;
5545 char *ev_qual;
5546 char *ev_action;
5547 List *actions;
5548 Relation ev_relation;
5549 int fno;
5550 Datum dat;
5551 bool isnull;
5552
5553 /*
5554 * Get the attribute values from the rules tuple
5555 */
5556 fno = SPI_fnumber(rulettc, "ev_type");
5557 dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
5558 Assert(!isnull);
5559 ev_type = DatumGetChar(dat);
5560
5561 fno = SPI_fnumber(rulettc, "ev_class");
5562 dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
5563 Assert(!isnull);
5564 ev_class = DatumGetObjectId(dat);
5565
5566 fno = SPI_fnumber(rulettc, "is_instead");
5567 dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
5568 Assert(!isnull);
5569 is_instead = DatumGetBool(dat);
5570
5571 fno = SPI_fnumber(rulettc, "ev_qual");
5572 ev_qual = SPI_getvalue(ruletup, rulettc, fno);
5573 Assert(ev_qual != NULL);
5574
5575 fno = SPI_fnumber(rulettc, "ev_action");
5576 ev_action = SPI_getvalue(ruletup, rulettc, fno);
5577 Assert(ev_action != NULL);
5578 actions = (List *) stringToNode(ev_action);
5579
5580 if (list_length(actions) != 1)
5581 {
5582 /* keep output buffer empty and leave */
5583 return;
5584 }
5585
5586 query = (Query *) linitial(actions);
5587
5588 if (ev_type != '1' || !is_instead ||
5589 strcmp(ev_qual, "<>") != 0 || query->commandType != CMD_SELECT)
5590 {
5591 /* keep output buffer empty and leave */
5592 return;
5593 }
5594
5595 ev_relation = table_open(ev_class, AccessShareLock);
5596
5597 get_query_def(query, buf, NIL, RelationGetDescr(ev_relation), true,
5598 prettyFlags, wrapColumn, 0);
5600
5601 table_close(ev_relation, AccessShareLock);
5602}
5603
5604
5605/* ----------
5606 * get_query_def - Parse back one query parsetree
5607 *
5608 * query: parsetree to be displayed
5609 * buf: output text is appended to buf
5610 * parentnamespace: list (initially empty) of outer-level deparse_namespace's
5611 * resultDesc: if not NULL, the output tuple descriptor for the view
5612 * represented by a SELECT query. We use the column names from it
5613 * to label SELECT output columns, in preference to names in the query
5614 * colNamesVisible: true if the surrounding context cares about the output
5615 * column names at all (as, for example, an EXISTS() context does not);
5616 * when false, we can suppress dummy column labels such as "?column?"
5617 * prettyFlags: bitmask of PRETTYFLAG_XXX options
5618 * wrapColumn: maximum line length, or -1 to disable wrapping
5619 * startIndent: initial indentation amount
5620 * ----------
5621 */
5622static void
5623get_query_def(Query *query, StringInfo buf, List *parentnamespace,
5624 TupleDesc resultDesc, bool colNamesVisible,
5625 int prettyFlags, int wrapColumn, int startIndent)
5626{
5627 deparse_context context;
5628 deparse_namespace dpns;
5629 int rtable_size;
5630
5631 /* Guard against excessively long or deeply-nested queries */
5634
5635 rtable_size = query->hasGroupRTE ?
5636 list_length(query->rtable) - 1 :
5637 list_length(query->rtable);
5638
5639 /*
5640 * Replace any Vars in the query's targetlist and havingQual that
5641 * reference GROUP outputs with the underlying grouping expressions.
5642 */
5643 if (query->hasGroupRTE)
5644 {
5645 query->targetList = (List *)
5646 flatten_group_exprs(NULL, query, (Node *) query->targetList);
5647 query->havingQual =
5648 flatten_group_exprs(NULL, query, query->havingQual);
5649 }
5650
5651 /*
5652 * Before we begin to examine the query, acquire locks on referenced
5653 * relations, and fix up deleted columns in JOIN RTEs. This ensures
5654 * consistent results. Note we assume it's OK to scribble on the passed
5655 * querytree!
5656 *
5657 * We are only deparsing the query (we are not about to execute it), so we
5658 * only need AccessShareLock on the relations it mentions.
5659 */
5660 AcquireRewriteLocks(query, false, false);
5661
5662 context.buf = buf;
5663 context.namespaces = lcons(&dpns, list_copy(parentnamespace));
5664 context.resultDesc = NULL;
5665 context.targetList = NIL;
5666 context.windowClause = NIL;
5667 context.varprefix = (parentnamespace != NIL ||
5668 rtable_size != 1);
5669 context.prettyFlags = prettyFlags;
5670 context.wrapColumn = wrapColumn;
5671 context.indentLevel = startIndent;
5672 context.colNamesVisible = colNamesVisible;
5673 context.inGroupBy = false;
5674 context.varInOrderBy = false;
5675 context.appendparents = NULL;
5676
5677 set_deparse_for_query(&dpns, query, parentnamespace);
5678
5679 switch (query->commandType)
5680 {
5681 case CMD_SELECT:
5682 /* We set context.resultDesc only if it's a SELECT */
5683 context.resultDesc = resultDesc;
5684 get_select_query_def(query, &context);
5685 break;
5686
5687 case CMD_UPDATE:
5688 get_update_query_def(query, &context);
5689 break;
5690
5691 case CMD_INSERT:
5692 get_insert_query_def(query, &context);
5693 break;
5694
5695 case CMD_DELETE:
5696 get_delete_query_def(query, &context);
5697 break;
5698
5699 case CMD_MERGE:
5700 get_merge_query_def(query, &context);
5701 break;
5702
5703 case CMD_NOTHING:
5704 appendStringInfoString(buf, "NOTHING");
5705 break;
5706
5707 case CMD_UTILITY:
5708 get_utility_query_def(query, &context);
5709 break;
5710
5711 default:
5712 elog(ERROR, "unrecognized query command type: %d",
5713 query->commandType);
5714 break;
5715 }
5716}
5717
5718/* ----------
5719 * get_values_def - Parse back a VALUES list
5720 * ----------
5721 */
5722static void
5723get_values_def(List *values_lists, deparse_context *context)
5724{
5725 StringInfo buf = context->buf;
5726 bool first_list = true;
5727 ListCell *vtl;
5728
5729 appendStringInfoString(buf, "VALUES ");
5730
5731 foreach(vtl, values_lists)
5732 {
5733 List *sublist = (List *) lfirst(vtl);
5734 bool first_col = true;
5735 ListCell *lc;
5736
5737 if (first_list)
5738 first_list = false;
5739 else
5741
5743 foreach(lc, sublist)
5744 {
5745 Node *col = (Node *) lfirst(lc);
5746
5747 if (first_col)
5748 first_col = false;
5749 else
5751
5752 /*
5753 * Print the value. Whole-row Vars need special treatment.
5754 */
5755 get_rule_expr_toplevel(col, context, false);
5756 }
5758 }
5759}
5760
5761/* ----------
5762 * get_with_clause - Parse back a WITH clause
5763 * ----------
5764 */
5765static void
5767{
5768 StringInfo buf = context->buf;
5769 const char *sep;
5770 ListCell *l;
5771
5772 if (query->cteList == NIL)
5773 return;
5774
5775 if (PRETTY_INDENT(context))
5776 {
5777 context->indentLevel += PRETTYINDENT_STD;
5779 }
5780
5781 if (query->hasRecursive)
5782 sep = "WITH RECURSIVE ";
5783 else
5784 sep = "WITH ";
5785 foreach(l, query->cteList)
5786 {
5788
5791 if (cte->aliascolnames)
5792 {
5793 bool first = true;
5794 ListCell *col;
5795
5797 foreach(col, cte->aliascolnames)
5798 {
5799 if (first)
5800 first = false;
5801 else
5805 }
5807 }
5808 appendStringInfoString(buf, " AS ");
5809 switch (cte->ctematerialized)
5810 {
5812 break;
5814 appendStringInfoString(buf, "MATERIALIZED ");
5815 break;
5817 appendStringInfoString(buf, "NOT MATERIALIZED ");
5818 break;
5819 }
5821 if (PRETTY_INDENT(context))
5822 appendContextKeyword(context, "", 0, 0, 0);
5823 get_query_def((Query *) cte->ctequery, buf, context->namespaces, NULL,
5824 true,
5825 context->prettyFlags, context->wrapColumn,
5826 context->indentLevel);
5827 if (PRETTY_INDENT(context))
5828 appendContextKeyword(context, "", 0, 0, 0);
5830
5831 if (cte->search_clause)
5832 {
5833 bool first = true;
5834 ListCell *lc;
5835
5836 appendStringInfo(buf, " SEARCH %s FIRST BY ",
5837 cte->search_clause->search_breadth_first ? "BREADTH" : "DEPTH");
5838
5839 foreach(lc, cte->search_clause->search_col_list)
5840 {
5841 if (first)
5842 first = false;
5843 else
5847 }
5848
5849 appendStringInfo(buf, " SET %s", quote_identifier(cte->search_clause->search_seq_column));
5850 }
5851
5852 if (cte->cycle_clause)
5853 {
5854 bool first = true;
5855 ListCell *lc;
5856
5857 appendStringInfoString(buf, " CYCLE ");
5858
5859 foreach(lc, cte->cycle_clause->cycle_col_list)
5860 {
5861 if (first)
5862 first = false;
5863 else
5867 }
5868
5869 appendStringInfo(buf, " SET %s", quote_identifier(cte->cycle_clause->cycle_mark_column));
5870
5871 {
5872 Const *cmv = castNode(Const, cte->cycle_clause->cycle_mark_value);
5873 Const *cmd = castNode(Const, cte->cycle_clause->cycle_mark_default);
5874
5875 if (!(cmv->consttype == BOOLOID && !cmv->constisnull && DatumGetBool(cmv->constvalue) == true &&
5876 cmd->consttype == BOOLOID && !cmd->constisnull && DatumGetBool(cmd->constvalue) == false))
5877 {
5878 appendStringInfoString(buf, " TO ");
5879 get_rule_expr(cte->cycle_clause->cycle_mark_value, context, false);
5880 appendStringInfoString(buf, " DEFAULT ");
5881 get_rule_expr(cte->cycle_clause->cycle_mark_default, context, false);
5882 }
5883 }
5884
5885 appendStringInfo(buf, " USING %s", quote_identifier(cte->cycle_clause->cycle_path_column));
5886 }
5887
5888 sep = ", ";
5889 }
5890
5891 if (PRETTY_INDENT(context))
5892 {
5893 context->indentLevel -= PRETTYINDENT_STD;
5894 appendContextKeyword(context, "", 0, 0, 0);
5895 }
5896 else
5898}
5899
5900/* ----------
5901 * get_select_query_def - Parse back a SELECT parsetree
5902 * ----------
5903 */
5904static void
5906{
5907 StringInfo buf = context->buf;
5908 bool force_colno;
5909 ListCell *l;
5910
5911 /* Insert the WITH clause if given */
5912 get_with_clause(query, context);
5913
5914 /* Subroutines may need to consult the SELECT targetlist and windowClause */
5915 context->targetList = query->targetList;
5916 context->windowClause = query->windowClause;
5917
5918 /*
5919 * If the Query node has a setOperations tree, then it's the top level of
5920 * a UNION/INTERSECT/EXCEPT query; only the WITH, ORDER BY and LIMIT
5921 * fields are interesting in the top query itself.
5922 */
5923 if (query->setOperations)
5924 {
5925 get_setop_query(query->setOperations, query, context);
5926 /* ORDER BY clauses must be simple in this case */
5927 force_colno = true;
5928 }
5929 else
5930 {
5931 get_basic_select_query(query, context);
5932 force_colno = false;
5933 }
5934
5935 /* Add the ORDER BY clause if given */
5936 if (query->sortClause != NIL)
5937 {
5938 appendContextKeyword(context, " ORDER BY ",
5940 get_rule_orderby(query->sortClause, query->targetList,
5941 force_colno, context);
5942 }
5943
5944 /*
5945 * Add the LIMIT/OFFSET clauses if given. If non-default options, use the
5946 * standard spelling of LIMIT.
5947 */
5948 if (query->limitOffset != NULL)
5949 {
5950 appendContextKeyword(context, " OFFSET ",
5952 get_rule_expr(query->limitOffset, context, false);
5953 }
5954 if (query->limitCount != NULL)
5955 {
5956 if (query->limitOption == LIMIT_OPTION_WITH_TIES)
5957 {
5958 /*
5959 * The limitCount arg is a c_expr, so it needs parens. Simple
5960 * literals and function expressions would not need parens, but
5961 * unfortunately it's hard to tell if the expression will be
5962 * printed as a simple literal like 123 or as a typecast
5963 * expression, like '-123'::int4. The grammar accepts the former
5964 * without quoting, but not the latter.
5965 */
5966 appendContextKeyword(context, " FETCH FIRST ",
5969 get_rule_expr(query->limitCount, context, false);
5971 appendStringInfoString(buf, " ROWS WITH TIES");
5972 }
5973 else
5974 {
5975 appendContextKeyword(context, " LIMIT ",
5977 if (IsA(query->limitCount, Const) &&
5978 ((Const *) query->limitCount)->constisnull)
5980 else
5981 get_rule_expr(query->limitCount, context, false);
5982 }
5983 }
5984
5985 /* Add FOR [KEY] UPDATE/SHARE clauses if present */
5986 if (query->hasForUpdate)
5987 {
5988 foreach(l, query->rowMarks)
5989 {
5990 RowMarkClause *rc = (RowMarkClause *) lfirst(l);
5991
5992 /* don't print implicit clauses */
5993 if (rc->pushedDown)
5994 continue;
5995
5996 switch (rc->strength)
5997 {
5998 case LCS_NONE:
5999 /* we intentionally throw an error for LCS_NONE */
6000 elog(ERROR, "unrecognized LockClauseStrength %d",
6001 (int) rc->strength);
6002 break;
6003 case LCS_FORKEYSHARE:
6004 appendContextKeyword(context, " FOR KEY SHARE",
6006 break;
6007 case LCS_FORSHARE:
6008 appendContextKeyword(context, " FOR SHARE",
6010 break;
6011 case LCS_FORNOKEYUPDATE:
6012 appendContextKeyword(context, " FOR NO KEY UPDATE",
6014 break;
6015 case LCS_FORUPDATE:
6016 appendContextKeyword(context, " FOR UPDATE",
6018 break;
6019 }
6020
6021 appendStringInfo(buf, " OF %s",
6023 context)));
6024 if (rc->waitPolicy == LockWaitError)
6025 appendStringInfoString(buf, " NOWAIT");
6026 else if (rc->waitPolicy == LockWaitSkip)
6027 appendStringInfoString(buf, " SKIP LOCKED");
6028 }
6029 }
6030}
6031
6032/*
6033 * Detect whether query looks like SELECT ... FROM VALUES(),
6034 * with no need to rename the output columns of the VALUES RTE.
6035 * If so, return the VALUES RTE. Otherwise return NULL.
6036 */
6037static RangeTblEntry *
6039{
6040 RangeTblEntry *result = NULL;
6041 ListCell *lc;
6042
6043 /*
6044 * We want to detect a match even if the Query also contains OLD or NEW
6045 * rule RTEs. So the idea is to scan the rtable and see if there is only
6046 * one inFromCl RTE that is a VALUES RTE.
6047 */
6048 foreach(lc, query->rtable)
6049 {
6050 RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
6051
6052 if (rte->rtekind == RTE_VALUES && rte->inFromCl)
6053 {
6054 if (result)
6055 return NULL; /* multiple VALUES (probably not possible) */
6056 result = rte;
6057 }
6058 else if (rte->rtekind == RTE_RELATION && !rte->inFromCl)
6059 continue; /* ignore rule entries */
6060 else
6061 return NULL; /* something else -> not simple VALUES */
6062 }
6063
6064 /*
6065 * We don't need to check the targetlist in any great detail, because
6066 * parser/analyze.c will never generate a "bare" VALUES RTE --- they only
6067 * appear inside auto-generated sub-queries with very restricted
6068 * structure. However, DefineView might have modified the tlist by
6069 * injecting new column aliases, or we might have some other column
6070 * aliases forced by a resultDesc. We can only simplify if the RTE's
6071 * column names match the names that get_target_list() would select.
6072 */
6073 if (result)
6074 {
6075 ListCell *lcn;
6076 int colno;
6077
6078 if (list_length(query->targetList) != list_length(result->eref->colnames))
6079 return NULL; /* this probably cannot happen */
6080 colno = 0;
6081 forboth(lc, query->targetList, lcn, result->eref->colnames)
6082 {
6083 TargetEntry *tle = (TargetEntry *) lfirst(lc);
6084 char *cname = strVal(lfirst(lcn));
6085 char *colname;
6086
6087 if (tle->resjunk)
6088 return NULL; /* this probably cannot happen */
6089
6090 /* compute name that get_target_list would use for column */
6091 colno++;
6092 if (resultDesc && colno <= resultDesc->natts)
6093 colname = NameStr(TupleDescAttr(resultDesc, colno - 1)->attname);
6094 else
6095 colname = tle->resname;
6096
6097 /* does it match the VALUES RTE? */
6098 if (colname == NULL || strcmp(colname, cname) != 0)
6099 return NULL; /* column name has been changed */
6100 }
6101 }
6102
6103 return result;
6104}
6105
6106static void
6108{
6109 StringInfo buf = context->buf;
6110 RangeTblEntry *values_rte;
6111 char *sep;
6112 ListCell *l;
6113
6114 if (PRETTY_INDENT(context))
6115 {
6116 context->indentLevel += PRETTYINDENT_STD;
6118 }
6119
6120 /*
6121 * If the query looks like SELECT * FROM (VALUES ...), then print just the
6122 * VALUES part. This reverses what transformValuesClause() did at parse
6123 * time.
6124 */
6125 values_rte = get_simple_values_rte(query, context->resultDesc);
6126 if (values_rte)
6127 {
6128 get_values_def(values_rte->values_lists, context);
6129 return;
6130 }
6131
6132 /*
6133 * Build up the query string - first we say SELECT
6134 */
6135 if (query->isReturn)
6136 appendStringInfoString(buf, "RETURN");
6137 else
6138 appendStringInfoString(buf, "SELECT");
6139
6140 /* Add the DISTINCT clause if given */
6141 if (query->distinctClause != NIL)
6142 {
6143 if (query->hasDistinctOn)
6144 {
6145 appendStringInfoString(buf, " DISTINCT ON (");
6146 sep = "";
6147 foreach(l, query->distinctClause)
6148 {
6150
6153 false, context);
6154 sep = ", ";
6155 }
6157 }
6158 else
6159 appendStringInfoString(buf, " DISTINCT");
6160 }
6161
6162 /* Then we tell what to select (the targetlist) */
6163 get_target_list(query->targetList, context);
6164
6165 /* Add the FROM clause if needed */
6166 get_from_clause(query, " FROM ", context);
6167
6168 /* Add the WHERE clause if given */
6169 if (query->jointree->quals != NULL)
6170 {
6171 appendContextKeyword(context, " WHERE ",
6173 get_rule_expr(query->jointree->quals, context, false);
6174 }
6175
6176 /* Add the GROUP BY clause if given */
6177 if (query->groupClause != NULL || query->groupingSets != NULL)
6178 {
6179 bool save_ingroupby;
6180
6181 appendContextKeyword(context, " GROUP BY ",
6183 if (query->groupDistinct)
6184 appendStringInfoString(buf, "DISTINCT ");
6185
6186 save_ingroupby = context->inGroupBy;
6187 context->inGroupBy = true;
6188
6189 if (query->groupingSets == NIL)
6190 {
6191 sep = "";
6192 foreach(l, query->groupClause)
6193 {
6195
6198 false, context);
6199 sep = ", ";
6200 }
6201 }
6202 else
6203 {
6204 sep = "";
6205 foreach(l, query->groupingSets)
6206 {
6207 GroupingSet *grp = lfirst(l);
6208
6210 get_rule_groupingset(grp, query->targetList, true, context);
6211 sep = ", ";
6212 }
6213 }
6214
6215 context->inGroupBy = save_ingroupby;
6216 }
6217
6218 /* Add the HAVING clause if given */
6219 if (query->havingQual != NULL)
6220 {
6221 appendContextKeyword(context, " HAVING ",
6223 get_rule_expr(query->havingQual, context, false);
6224 }
6225
6226 /* Add the WINDOW clause if needed */
6227 if (query->windowClause != NIL)
6228 get_rule_windowclause(query, context);
6229}
6230
6231/* ----------
6232 * get_target_list - Parse back a SELECT target list
6233 *
6234 * This is also used for RETURNING lists in INSERT/UPDATE/DELETE/MERGE.
6235 * ----------
6236 */
6237static void
6239{
6240 StringInfo buf = context->buf;
6241 StringInfoData targetbuf;
6242 bool last_was_multiline = false;
6243 char *sep;
6244 int colno;
6245 ListCell *l;
6246
6247 /* we use targetbuf to hold each TLE's text temporarily */
6248 initStringInfo(&targetbuf);
6249
6250 sep = " ";
6251 colno = 0;
6252 foreach(l, targetList)
6253 {
6254 TargetEntry *tle = (TargetEntry *) lfirst(l);
6255 char *colname;
6256 char *attname;
6257
6258 if (tle->resjunk)
6259 continue; /* ignore junk entries */
6260
6262 sep = ", ";
6263 colno++;
6264
6265 /*
6266 * Put the new field text into targetbuf so we can decide after we've
6267 * got it whether or not it needs to go on a new line.
6268 */
6269 resetStringInfo(&targetbuf);
6270 context->buf = &targetbuf;
6271
6272 /*
6273 * We special-case Var nodes rather than using get_rule_expr. This is
6274 * needed because get_rule_expr will display a whole-row Var as
6275 * "foo.*", which is the preferred notation in most contexts, but at
6276 * the top level of a SELECT list it's not right (the parser will
6277 * expand that notation into multiple columns, yielding behavior
6278 * different from a whole-row Var). We need to call get_variable
6279 * directly so that we can tell it to do the right thing, and so that
6280 * we can get the attribute name which is the default AS label.
6281 */
6282 if (tle->expr && (IsA(tle->expr, Var)))
6283 {
6284 attname = get_variable((Var *) tle->expr, 0, true, context);
6285 }
6286 else
6287 {
6288 get_rule_expr((Node *) tle->expr, context, true);
6289
6290 /*
6291 * When colNamesVisible is true, we should always show the
6292 * assigned column name explicitly. Otherwise, show it only if
6293 * it's not FigureColname's fallback.
6294 */
6295 attname = context->colNamesVisible ? NULL : "?column?";
6296 }
6297
6298 /*
6299 * Figure out what the result column should be called. In the context
6300 * of a view, use the view's tuple descriptor (so as to pick up the
6301 * effects of any column RENAME that's been done on the view).
6302 * Otherwise, just use what we can find in the TLE.
6303 */
6304 if (context->resultDesc && colno <= context->resultDesc->natts)
6305 colname = NameStr(TupleDescAttr(context->resultDesc,
6306 colno - 1)->attname);
6307 else
6308 colname = tle->resname;
6309
6310 /* Show AS unless the column's name is correct as-is */
6311 if (colname) /* resname could be NULL */
6312 {
6313 if (attname == NULL || strcmp(attname, colname) != 0)
6314 appendStringInfo(&targetbuf, " AS %s", quote_identifier(colname));
6315 }
6316
6317 /* Restore context's output buffer */
6318 context->buf = buf;
6319
6320 /* Consider line-wrapping if enabled */
6321 if (PRETTY_INDENT(context) && context->wrapColumn >= 0)
6322 {
6323 int leading_nl_pos;
6324
6325 /* Does the new field start with a new line? */
6326 if (targetbuf.len > 0 && targetbuf.data[0] == '\n')
6327 leading_nl_pos = 0;
6328 else
6329 leading_nl_pos = -1;
6330
6331 /* If so, we shouldn't add anything */
6332 if (leading_nl_pos >= 0)
6333 {
6334 /* instead, remove any trailing spaces currently in buf */
6336 }
6337 else
6338 {
6339 char *trailing_nl;
6340
6341 /* Locate the start of the current line in the output buffer */
6342 trailing_nl = strrchr(buf->data, '\n');
6343 if (trailing_nl == NULL)
6344 trailing_nl = buf->data;
6345 else
6346 trailing_nl++;
6347
6348 /*
6349 * Add a newline, plus some indentation, if the new field is
6350 * not the first and either the new field would cause an
6351 * overflow or the last field used more than one line.
6352 */
6353 if (colno > 1 &&
6354 ((strlen(trailing_nl) + targetbuf.len > context->wrapColumn) ||
6355 last_was_multiline))
6358 }
6359
6360 /* Remember this field's multiline status for next iteration */
6361 last_was_multiline =
6362 (strchr(targetbuf.data + leading_nl_pos + 1, '\n') != NULL);
6363 }
6364
6365 /* Add the new field */
6366 appendBinaryStringInfo(buf, targetbuf.data, targetbuf.len);
6367 }
6368
6369 /* clean up */
6370 pfree(targetbuf.data);
6371}
6372
6373static void
6375{
6376 StringInfo buf = context->buf;
6377
6378 if (query->returningList)
6379 {
6380 bool have_with = false;
6381
6382 appendContextKeyword(context, " RETURNING",
6384
6385 /* Add WITH (OLD/NEW) options, if they're not the defaults */
6386 if (query->returningOldAlias && strcmp(query->returningOldAlias, "old") != 0)
6387 {
6388 appendStringInfo(buf, " WITH (OLD AS %s",
6389 quote_identifier(query->returningOldAlias));
6390 have_with = true;
6391 }
6392 if (query->returningNewAlias && strcmp(query->returningNewAlias, "new") != 0)
6393 {
6394 if (have_with)
6395 appendStringInfo(buf, ", NEW AS %s",
6396 quote_identifier(query->returningNewAlias));
6397 else
6398 {
6399 appendStringInfo(buf, " WITH (NEW AS %s",
6400 quote_identifier(query->returningNewAlias));
6401 have_with = true;
6402 }
6403 }
6404 if (have_with)
6406
6407 /* Add the returning expressions themselves */
6408 get_target_list(query->returningList, context);
6409 }
6410}
6411
6412static void
6414{
6415 StringInfo buf = context->buf;
6416 bool need_paren;
6417
6418 /* Guard against excessively long or deeply-nested queries */
6421
6422 if (IsA(setOp, RangeTblRef))
6423 {
6424 RangeTblRef *rtr = (RangeTblRef *) setOp;
6425 RangeTblEntry *rte = rt_fetch(rtr->rtindex, query->rtable);
6426 Query *subquery = rte->subquery;
6427
6428 Assert(subquery != NULL);
6429
6430 /*
6431 * We need parens if WITH, ORDER BY, FOR UPDATE, or LIMIT; see gram.y.
6432 * Also add parens if the leaf query contains its own set operations.
6433 * (That shouldn't happen unless one of the other clauses is also
6434 * present, see transformSetOperationTree; but let's be safe.)
6435 */
6436 need_paren = (subquery->cteList ||
6437 subquery->sortClause ||
6438 subquery->rowMarks ||
6439 subquery->limitOffset ||
6440 subquery->limitCount ||
6441 subquery->setOperations);
6442 if (need_paren)
6444 get_query_def(subquery, buf, context->namespaces,
6445 context->resultDesc, context->colNamesVisible,
6446 context->prettyFlags, context->wrapColumn,
6447 context->indentLevel);
6448 if (need_paren)
6450 }
6451 else if (IsA(setOp, SetOperationStmt))
6452 {
6453 SetOperationStmt *op = (SetOperationStmt *) setOp;
6454 int subindent;
6455 bool save_colnamesvisible;
6456
6457 /*
6458 * We force parens when nesting two SetOperationStmts, except when the
6459 * lefthand input is another setop of the same kind. Syntactically,
6460 * we could omit parens in rather more cases, but it seems best to use
6461 * parens to flag cases where the setop operator changes. If we use
6462 * parens, we also increase the indentation level for the child query.
6463 *
6464 * There are some cases in which parens are needed around a leaf query
6465 * too, but those are more easily handled at the next level down (see
6466 * code above).
6467 */
6468 if (IsA(op->larg, SetOperationStmt))
6469 {
6470 SetOperationStmt *lop = (SetOperationStmt *) op->larg;
6471
6472 if (op->op == lop->op && op->all == lop->all)
6473 need_paren = false;
6474 else
6475 need_paren = true;
6476 }
6477 else
6478 need_paren = false;
6479
6480 if (need_paren)
6481 {
6483 subindent = PRETTYINDENT_STD;
6484 appendContextKeyword(context, "", subindent, 0, 0);
6485 }
6486 else
6487 subindent = 0;
6488
6489 get_setop_query(op->larg, query, context);
6490
6491 if (need_paren)
6492 appendContextKeyword(context, ") ", -subindent, 0, 0);
6493 else if (PRETTY_INDENT(context))
6494 appendContextKeyword(context, "", -subindent, 0, 0);
6495 else
6497
6498 switch (op->op)
6499 {
6500 case SETOP_UNION:
6501 appendStringInfoString(buf, "UNION ");
6502 break;
6503 case SETOP_INTERSECT:
6504 appendStringInfoString(buf, "INTERSECT ");
6505 break;
6506 case SETOP_EXCEPT:
6507 appendStringInfoString(buf, "EXCEPT ");
6508 break;
6509 default:
6510 elog(ERROR, "unrecognized set op: %d",
6511 (int) op->op);
6512 }
6513 if (op->all)
6514 appendStringInfoString(buf, "ALL ");
6515
6516 /* Always parenthesize if RHS is another setop */
6517 need_paren = IsA(op->rarg, SetOperationStmt);
6518
6519 /*
6520 * The indentation code here is deliberately a bit different from that
6521 * for the lefthand input, because we want the line breaks in
6522 * different places.
6523 */
6524 if (need_paren)
6525 {
6527 subindent = PRETTYINDENT_STD;
6528 }
6529 else
6530 subindent = 0;
6531 appendContextKeyword(context, "", subindent, 0, 0);
6532
6533 /*
6534 * The output column names of the RHS sub-select don't matter.
6535 */
6536 save_colnamesvisible = context->colNamesVisible;
6537 context->colNamesVisible = false;
6538
6539 get_setop_query(op->rarg, query, context);
6540
6541 context->colNamesVisible = save_colnamesvisible;
6542
6543 if (PRETTY_INDENT(context))
6544 context->indentLevel -= subindent;
6545 if (need_paren)
6546 appendContextKeyword(context, ")", 0, 0, 0);
6547 }
6548 else
6549 {
6550 elog(ERROR, "unrecognized node type: %d",
6551 (int) nodeTag(setOp));
6552 }
6553}
6554
6555/*
6556 * Display a sort/group clause.
6557 *
6558 * Also returns the expression tree, so caller need not find it again.
6559 */
6560static Node *
6561get_rule_sortgroupclause(Index ref, List *tlist, bool force_colno,
6562 deparse_context *context)
6563{
6564 StringInfo buf = context->buf;
6565 TargetEntry *tle;
6566 Node *expr;
6567
6568 tle = get_sortgroupref_tle(ref, tlist);
6569 expr = (Node *) tle->expr;
6570
6571 /*
6572 * Use column-number form if requested by caller. Otherwise, if
6573 * expression is a constant, force it to be dumped with an explicit cast
6574 * as decoration --- this is because a simple integer constant is
6575 * ambiguous (and will be misinterpreted by findTargetlistEntrySQL92()) if
6576 * we dump it without any decoration. Similarly, if it's just a Var,
6577 * there is risk of misinterpretation if the column name is reassigned in
6578 * the SELECT list, so we may need to force table qualification. And, if
6579 * it's anything more complex than a simple Var, then force extra parens
6580 * around it, to ensure it can't be misinterpreted as a cube() or rollup()
6581 * construct.
6582 */
6583 if (force_colno)
6584 {
6585 Assert(!tle->resjunk);
6586 appendStringInfo(buf, "%d", tle->resno);
6587 }
6588 else if (!expr)
6589 /* do nothing, probably can't happen */ ;
6590 else if (IsA(expr, Const))
6591 get_const_expr((Const *) expr, context, 1);
6592 else if (IsA(expr, Var))
6593 {
6594 /* Tell get_variable to check for name conflict */
6595 bool save_varinorderby = context->varInOrderBy;
6596
6597 context->varInOrderBy = true;
6598 (void) get_variable((Var *) expr, 0, false, context);
6599 context->varInOrderBy = save_varinorderby;
6600 }
6601 else
6602 {
6603 /*
6604 * We must force parens for function-like expressions even if
6605 * PRETTY_PAREN is off, since those are the ones in danger of
6606 * misparsing. For other expressions we need to force them only if
6607 * PRETTY_PAREN is on, since otherwise the expression will output them
6608 * itself. (We can't skip the parens.)
6609 */
6610 bool need_paren = (PRETTY_PAREN(context)
6611 || IsA(expr, FuncExpr)
6612 || IsA(expr, Aggref)
6613 || IsA(expr, WindowFunc)
6614 || IsA(expr, JsonConstructorExpr));
6615
6616 if (need_paren)
6617 appendStringInfoChar(context->buf, '(');
6618 get_rule_expr(expr, context, true);
6619 if (need_paren)
6620 appendStringInfoChar(context->buf, ')');
6621 }
6622
6623 return expr;
6624}
6625
6626/*
6627 * Display a GroupingSet
6628 */
6629static void
6631 bool omit_parens, deparse_context *context)
6632{
6633 ListCell *l;
6634 StringInfo buf = context->buf;
6635 bool omit_child_parens = true;
6636 char *sep = "";
6637
6638 switch (gset->kind)
6639 {
6640 case GROUPING_SET_EMPTY:
6642 return;
6643
6645 {
6646 if (!omit_parens || list_length(gset->content) != 1)
6648
6649 foreach(l, gset->content)
6650 {
6651 Index ref = lfirst_int(l);
6652
6654 get_rule_sortgroupclause(ref, targetlist,
6655 false, context);
6656 sep = ", ";
6657 }
6658
6659 if (!omit_parens || list_length(gset->content) != 1)
6661 }
6662 return;
6663
6665 appendStringInfoString(buf, "ROLLUP(");
6666 break;
6667 case GROUPING_SET_CUBE:
6668 appendStringInfoString(buf, "CUBE(");
6669 break;
6670 case GROUPING_SET_SETS:
6671 appendStringInfoString(buf, "GROUPING SETS (");
6672 omit_child_parens = false;
6673 break;
6674 }
6675
6676 foreach(l, gset->content)
6677 {
6679 get_rule_groupingset(lfirst(l), targetlist, omit_child_parens, context);
6680 sep = ", ";
6681 }
6682
6684}
6685
6686/*
6687 * Display an ORDER BY list.
6688 */
6689static void
6690get_rule_orderby(List *orderList, List *targetList,
6691 bool force_colno, deparse_context *context)
6692{
6693 StringInfo buf = context->buf;
6694 const char *sep;
6695 ListCell *l;
6696
6697 sep = "";
6698 foreach(l, orderList)
6699 {
6701 Node *sortexpr;
6702 Oid sortcoltype;
6703 TypeCacheEntry *typentry;
6704
6706 sortexpr = get_rule_sortgroupclause(srt->tleSortGroupRef, targetList,
6707 force_colno, context);
6708 sortcoltype = exprType(sortexpr);
6709 /* See whether operator is default < or > for datatype */
6710 typentry = lookup_type_cache(sortcoltype,
6712 if (srt->sortop == typentry->lt_opr)
6713 {
6714 /* ASC is default, so emit nothing for it */
6715 if (srt->nulls_first)
6716 appendStringInfoString(buf, " NULLS FIRST");
6717 }
6718 else if (srt->sortop == typentry->gt_opr)
6719 {
6720 appendStringInfoString(buf, " DESC");
6721 /* DESC defaults to NULLS FIRST */
6722 if (!srt->nulls_first)
6723 appendStringInfoString(buf, " NULLS LAST");
6724 }
6725 else
6726 {
6727 appendStringInfo(buf, " USING %s",
6729 sortcoltype,
6730 sortcoltype));
6731 /* be specific to eliminate ambiguity */
6732 if (srt->nulls_first)
6733 appendStringInfoString(buf, " NULLS FIRST");
6734 else
6735 appendStringInfoString(buf, " NULLS LAST");
6736 }
6737 sep = ", ";
6738 }
6739}
6740
6741/*
6742 * Display a WINDOW clause.
6743 *
6744 * Note that the windowClause list might contain only anonymous window
6745 * specifications, in which case we should print nothing here.
6746 */
6747static void
6749{
6750 StringInfo buf = context->buf;
6751 const char *sep;
6752 ListCell *l;
6753
6754 sep = NULL;
6755 foreach(l, query->windowClause)
6756 {
6757 WindowClause *wc = (WindowClause *) lfirst(l);
6758
6759 if (wc->name == NULL)
6760 continue; /* ignore anonymous windows */
6761
6762 if (sep == NULL)
6763 appendContextKeyword(context, " WINDOW ",
6765 else
6767
6768 appendStringInfo(buf, "%s AS ", quote_identifier(wc->name));
6769
6770 get_rule_windowspec(wc, query->targetList, context);
6771
6772 sep = ", ";
6773 }
6774}
6775
6776/*
6777 * Display a window definition
6778 */
6779static void
6781 deparse_context *context)
6782{
6783 StringInfo buf = context->buf;
6784 bool needspace = false;
6785 const char *sep;
6786 ListCell *l;
6787
6789 if (wc->refname)
6790 {
6792 needspace = true;
6793 }
6794 /* partition clauses are always inherited, so only print if no refname */
6795 if (wc->partitionClause && !wc->refname)
6796 {
6797 if (needspace)
6799 appendStringInfoString(buf, "PARTITION BY ");
6800 sep = "";
6801 foreach(l, wc->partitionClause)
6802 {
6804
6807 false, context);
6808 sep = ", ";
6809 }
6810 needspace = true;
6811 }
6812 /* print ordering clause only if not inherited */
6813 if (wc->orderClause && !wc->copiedOrder)
6814 {
6815 if (needspace)
6817 appendStringInfoString(buf, "ORDER BY ");
6818 get_rule_orderby(wc->orderClause, targetList, false, context);
6819 needspace = true;
6820 }
6821 /* framing clause is never inherited, so print unless it's default */
6823 {
6824 if (needspace)
6827 wc->startOffset, wc->endOffset,
6828 context);
6829 }
6831}
6832
6833/*
6834 * Append the description of a window's framing options to context->buf
6835 */
6836static void
6838 Node *startOffset, Node *endOffset,
6839 deparse_context *context)
6840{
6841 StringInfo buf = context->buf;
6842
6843 if (frameOptions & FRAMEOPTION_NONDEFAULT)
6844 {
6845 if (frameOptions & FRAMEOPTION_RANGE)
6846 appendStringInfoString(buf, "RANGE ");
6847 else if (frameOptions & FRAMEOPTION_ROWS)
6848 appendStringInfoString(buf, "ROWS ");
6849 else if (frameOptions & FRAMEOPTION_GROUPS)
6850 appendStringInfoString(buf, "GROUPS ");
6851 else
6852 Assert(false);
6853 if (frameOptions & FRAMEOPTION_BETWEEN)
6854 appendStringInfoString(buf, "BETWEEN ");
6855 if (frameOptions & FRAMEOPTION_START_UNBOUNDED_PRECEDING)
6856 appendStringInfoString(buf, "UNBOUNDED PRECEDING ");
6857 else if (frameOptions & FRAMEOPTION_START_CURRENT_ROW)
6858 appendStringInfoString(buf, "CURRENT ROW ");
6859 else if (frameOptions & FRAMEOPTION_START_OFFSET)
6860 {
6861 get_rule_expr(startOffset, context, false);
6862 if (frameOptions & FRAMEOPTION_START_OFFSET_PRECEDING)
6863 appendStringInfoString(buf, " PRECEDING ");
6864 else if (frameOptions & FRAMEOPTION_START_OFFSET_FOLLOWING)
6865 appendStringInfoString(buf, " FOLLOWING ");
6866 else
6867 Assert(false);
6868 }
6869 else
6870 Assert(false);
6871 if (frameOptions & FRAMEOPTION_BETWEEN)
6872 {
6873 appendStringInfoString(buf, "AND ");
6874 if (frameOptions & FRAMEOPTION_END_UNBOUNDED_FOLLOWING)
6875 appendStringInfoString(buf, "UNBOUNDED FOLLOWING ");
6876 else if (frameOptions & FRAMEOPTION_END_CURRENT_ROW)
6877 appendStringInfoString(buf, "CURRENT ROW ");
6878 else if (frameOptions & FRAMEOPTION_END_OFFSET)
6879 {
6880 get_rule_expr(endOffset, context, false);
6881 if (frameOptions & FRAMEOPTION_END_OFFSET_PRECEDING)
6882 appendStringInfoString(buf, " PRECEDING ");
6883 else if (frameOptions & FRAMEOPTION_END_OFFSET_FOLLOWING)
6884 appendStringInfoString(buf, " FOLLOWING ");
6885 else
6886 Assert(false);
6887 }
6888 else
6889 Assert(false);
6890 }
6891 if (frameOptions & FRAMEOPTION_EXCLUDE_CURRENT_ROW)
6892 appendStringInfoString(buf, "EXCLUDE CURRENT ROW ");
6893 else if (frameOptions & FRAMEOPTION_EXCLUDE_GROUP)
6894 appendStringInfoString(buf, "EXCLUDE GROUP ");
6895 else if (frameOptions & FRAMEOPTION_EXCLUDE_TIES)
6896 appendStringInfoString(buf, "EXCLUDE TIES ");
6897 /* we will now have a trailing space; remove it */
6898 buf->data[--(buf->len)] = '\0';
6899 }
6900}
6901
6902/*
6903 * Return the description of a window's framing options as a palloc'd string
6904 */
6905char *
6907 Node *startOffset, Node *endOffset,
6908 List *dpcontext, bool forceprefix)
6909{
6911 deparse_context context;
6912
6914 context.buf = &buf;
6915 context.namespaces = dpcontext;
6916 context.resultDesc = NULL;
6917 context.targetList = NIL;
6918 context.windowClause = NIL;
6919 context.varprefix = forceprefix;
6920 context.prettyFlags = 0;
6922 context.indentLevel = 0;
6923 context.colNamesVisible = true;
6924 context.inGroupBy = false;
6925 context.varInOrderBy = false;
6926 context.appendparents = NULL;
6927
6928 get_window_frame_options(frameOptions, startOffset, endOffset, &context);
6929
6930 return buf.data;
6931}
6932
6933/* ----------
6934 * get_insert_query_def - Parse back an INSERT parsetree
6935 * ----------
6936 */
6937static void
6939{
6940 StringInfo buf = context->buf;
6941 RangeTblEntry *select_rte = NULL;
6942 RangeTblEntry *values_rte = NULL;
6943 RangeTblEntry *rte;
6944 char *sep;
6945 ListCell *l;
6946 List *strippedexprs;
6947
6948 /* Insert the WITH clause if given */
6949 get_with_clause(query, context);
6950
6951 /*
6952 * If it's an INSERT ... SELECT or multi-row VALUES, there will be a
6953 * single RTE for the SELECT or VALUES. Plain VALUES has neither.
6954 */
6955 foreach(l, query->rtable)
6956 {
6957 rte = (RangeTblEntry *) lfirst(l);
6958
6959 if (rte->rtekind == RTE_SUBQUERY)
6960 {
6961 if (select_rte)
6962 elog(ERROR, "too many subquery RTEs in INSERT");
6963 select_rte = rte;
6964 }
6965
6966 if (rte->rtekind == RTE_VALUES)
6967 {
6968 if (values_rte)
6969 elog(ERROR, "too many values RTEs in INSERT");
6970 values_rte = rte;
6971 }
6972 }
6973 if (select_rte && values_rte)
6974 elog(ERROR, "both subquery and values RTEs in INSERT");
6975
6976 /*
6977 * Start the query with INSERT INTO relname
6978 */
6979 rte = rt_fetch(query->resultRelation, query->rtable);
6980 Assert(rte->rtekind == RTE_RELATION);
6981
6982 if (PRETTY_INDENT(context))
6983 {
6984 context->indentLevel += PRETTYINDENT_STD;
6986 }
6987 appendStringInfo(buf, "INSERT INTO %s",
6988 generate_relation_name(rte->relid, NIL));
6989
6990 /* Print the relation alias, if needed; INSERT requires explicit AS */
6991 get_rte_alias(rte, query->resultRelation, true, context);
6992
6993 /* always want a space here */
6995
6996 /*
6997 * Add the insert-column-names list. Any indirection decoration needed on
6998 * the column names can be inferred from the top targetlist.
6999 */
7000 strippedexprs = NIL;
7001 sep = "";
7002 if (query->targetList)
7004 foreach(l, query->targetList)
7005 {
7006 TargetEntry *tle = (TargetEntry *) lfirst(l);
7007
7008 if (tle->resjunk)
7009 continue; /* ignore junk entries */
7010
7012 sep = ", ";
7013
7014 /*
7015 * Put out name of target column; look in the catalogs, not at
7016 * tle->resname, since resname will fail to track RENAME.
7017 */
7019 quote_identifier(get_attname(rte->relid,
7020 tle->resno,
7021 false)));
7022
7023 /*
7024 * Print any indirection needed (subfields or subscripts), and strip
7025 * off the top-level nodes representing the indirection assignments.
7026 * Add the stripped expressions to strippedexprs. (If it's a
7027 * single-VALUES statement, the stripped expressions are the VALUES to
7028 * print below. Otherwise they're just Vars and not really
7029 * interesting.)
7030 */
7031 strippedexprs = lappend(strippedexprs,
7032 processIndirection((Node *) tle->expr,
7033 context));
7034 }
7035 if (query->targetList)
7037
7038 if (query->override)
7039 {
7040 if (query->override == OVERRIDING_SYSTEM_VALUE)
7041 appendStringInfoString(buf, "OVERRIDING SYSTEM VALUE ");
7042 else if (query->override == OVERRIDING_USER_VALUE)
7043 appendStringInfoString(buf, "OVERRIDING USER VALUE ");
7044 }
7045
7046 if (select_rte)
7047 {
7048 /* Add the SELECT */
7049 get_query_def(select_rte->subquery, buf, context->namespaces, NULL,
7050 false,
7051 context->prettyFlags, context->wrapColumn,
7052 context->indentLevel);
7053 }
7054 else if (values_rte)
7055 {
7056 /* Add the multi-VALUES expression lists */
7057 get_values_def(values_rte->values_lists, context);
7058 }
7059 else if (strippedexprs)
7060 {
7061 /* Add the single-VALUES expression list */
7062 appendContextKeyword(context, "VALUES (",
7064 get_rule_list_toplevel(strippedexprs, context, false);
7066 }
7067 else
7068 {
7069 /* No expressions, so it must be DEFAULT VALUES */
7070 appendStringInfoString(buf, "DEFAULT VALUES");
7071 }
7072
7073 /* Add ON CONFLICT if present */
7074 if (query->onConflict)
7075 {
7076 OnConflictExpr *confl = query->onConflict;
7077
7078 appendStringInfoString(buf, " ON CONFLICT");
7079
7080 if (confl->arbiterElems)
7081 {
7082 /* Add the single-VALUES expression list */
7084 get_rule_expr((Node *) confl->arbiterElems, context, false);
7086
7087 /* Add a WHERE clause (for partial indexes) if given */
7088 if (confl->arbiterWhere != NULL)
7089 {
7090 bool save_varprefix;
7091
7092 /*
7093 * Force non-prefixing of Vars, since parser assumes that they
7094 * belong to target relation. WHERE clause does not use
7095 * InferenceElem, so this is separately required.
7096 */
7097 save_varprefix = context->varprefix;
7098 context->varprefix = false;
7099
7100 appendContextKeyword(context, " WHERE ",
7102 get_rule_expr(confl->arbiterWhere, context, false);
7103
7104 context->varprefix = save_varprefix;
7105 }
7106 }
7107 else if (OidIsValid(confl->constraint))
7108 {
7109 char *constraint = get_constraint_name(confl->constraint);
7110
7111 if (!constraint)
7112 elog(ERROR, "cache lookup failed for constraint %u",
7113 confl->constraint);
7114 appendStringInfo(buf, " ON CONSTRAINT %s",
7115 quote_identifier(constraint));
7116 }
7117
7118 if (confl->action == ONCONFLICT_NOTHING)
7119 {
7120 appendStringInfoString(buf, " DO NOTHING");
7121 }
7122 else
7123 {
7124 appendStringInfoString(buf, " DO UPDATE SET ");
7125 /* Deparse targetlist */
7127 context, rte);
7128
7129 /* Add a WHERE clause if given */
7130 if (confl->onConflictWhere != NULL)
7131 {
7132 appendContextKeyword(context, " WHERE ",
7134 get_rule_expr(confl->onConflictWhere, context, false);
7135 }
7136 }
7137 }
7138
7139 /* Add RETURNING if present */
7140 if (query->returningList)
7141 get_returning_clause(query, context);
7142}
7143
7144
7145/* ----------
7146 * get_update_query_def - Parse back an UPDATE parsetree
7147 * ----------
7148 */
7149static void
7151{
7152 StringInfo buf = context->buf;
7153 RangeTblEntry *rte;
7154
7155 /* Insert the WITH clause if given */
7156 get_with_clause(query, context);
7157
7158 /*
7159 * Start the query with UPDATE relname SET
7160 */
7161 rte = rt_fetch(query->resultRelation, query->rtable);
7162 Assert(rte->rtekind == RTE_RELATION);
7163 if (PRETTY_INDENT(context))
7164 {
7166 context->indentLevel += PRETTYINDENT_STD;
7167 }
7168 appendStringInfo(buf, "UPDATE %s%s",
7169 only_marker(rte),
7170 generate_relation_name(rte->relid, NIL));
7171
7172 /* Print the relation alias, if needed */
7173 get_rte_alias(rte, query->resultRelation, false, context);
7174
7175 appendStringInfoString(buf, " SET ");
7176
7177 /* Deparse targetlist */
7178 get_update_query_targetlist_def(query, query->targetList, context, rte);
7179
7180 /* Add the FROM clause if needed */
7181 get_from_clause(query, " FROM ", context);
7182
7183 /* Add a WHERE clause if given */
7184 if (query->jointree->quals != NULL)
7185 {
7186 appendContextKeyword(context, " WHERE ",
7188 get_rule_expr(query->jointree->quals, context, false);
7189 }
7190
7191 /* Add RETURNING if present */
7192 if (query->returningList)
7193 get_returning_clause(query, context);
7194}
7195
7196
7197/* ----------
7198 * get_update_query_targetlist_def - Parse back an UPDATE targetlist
7199 * ----------
7200 */
7201static void
7203 deparse_context *context, RangeTblEntry *rte)
7204{
7205 StringInfo buf = context->buf;
7206 ListCell *l;
7207 ListCell *next_ma_cell;
7208 int remaining_ma_columns;
7209 const char *sep;
7210 SubLink *cur_ma_sublink;
7211 List *ma_sublinks;
7212
7213 /*
7214 * Prepare to deal with MULTIEXPR assignments: collect the source SubLinks
7215 * into a list. We expect them to appear, in ID order, in resjunk tlist
7216 * entries.
7217 */
7218 ma_sublinks = NIL;
7219 if (query->hasSubLinks) /* else there can't be any */
7220 {
7221 foreach(l, targetList)
7222 {
7223 TargetEntry *tle = (TargetEntry *) lfirst(l);
7224
7225 if (tle->resjunk && IsA(tle->expr, SubLink))
7226 {
7227 SubLink *sl = (SubLink *) tle->expr;
7228
7230 {
7231 ma_sublinks = lappend(ma_sublinks, sl);
7232 Assert(sl->subLinkId == list_length(ma_sublinks));
7233 }
7234 }
7235 }
7236 }
7237 next_ma_cell = list_head(ma_sublinks);
7238 cur_ma_sublink = NULL;
7239 remaining_ma_columns = 0;
7240
7241 /* Add the comma separated list of 'attname = value' */
7242 sep = "";
7243 foreach(l, targetList)
7244 {
7245 TargetEntry *tle = (TargetEntry *) lfirst(l);
7246 Node *expr;
7247
7248 if (tle->resjunk)
7249 continue; /* ignore junk entries */
7250
7251 /* Emit separator (OK whether we're in multiassignment or not) */
7253 sep = ", ";
7254
7255 /*
7256 * Check to see if we're starting a multiassignment group: if so,
7257 * output a left paren.
7258 */
7259 if (next_ma_cell != NULL && cur_ma_sublink == NULL)
7260 {
7261 /*
7262 * We must dig down into the expr to see if it's a PARAM_MULTIEXPR
7263 * Param. That could be buried under FieldStores and
7264 * SubscriptingRefs and CoerceToDomains (cf processIndirection()),
7265 * and underneath those there could be an implicit type coercion.
7266 * Because we would ignore implicit type coercions anyway, we
7267 * don't need to be as careful as processIndirection() is about
7268 * descending past implicit CoerceToDomains.
7269 */
7270 expr = (Node *) tle->expr;
7271 while (expr)
7272 {
7273 if (IsA(expr, FieldStore))
7274 {
7275 FieldStore *fstore = (FieldStore *) expr;
7276
7277 expr = (Node *) linitial(fstore->newvals);
7278 }
7279 else if (IsA(expr, SubscriptingRef))
7280 {
7281 SubscriptingRef *sbsref = (SubscriptingRef *) expr;
7282
7283 if (sbsref->refassgnexpr == NULL)
7284 break;
7285
7286 expr = (Node *) sbsref->refassgnexpr;
7287 }
7288 else if (IsA(expr, CoerceToDomain))
7289 {
7290 CoerceToDomain *cdomain = (CoerceToDomain *) expr;
7291
7292 if (cdomain->coercionformat != COERCE_IMPLICIT_CAST)
7293 break;
7294 expr = (Node *) cdomain->arg;
7295 }
7296 else
7297 break;
7298 }
7299 expr = strip_implicit_coercions(expr);
7300
7301 if (expr && IsA(expr, Param) &&
7302 ((Param *) expr)->paramkind == PARAM_MULTIEXPR)
7303 {
7304 cur_ma_sublink = (SubLink *) lfirst(next_ma_cell);
7305 next_ma_cell = lnext(ma_sublinks, next_ma_cell);
7306 remaining_ma_columns = count_nonjunk_tlist_entries(((Query *) cur_ma_sublink->subselect)->targetList);
7307 Assert(((Param *) expr)->paramid ==
7308 ((cur_ma_sublink->subLinkId << 16) | 1));
7310 }
7311 }
7312
7313 /*
7314 * Put out name of target column; look in the catalogs, not at
7315 * tle->resname, since resname will fail to track RENAME.
7316 */
7318 quote_identifier(get_attname(rte->relid,
7319 tle->resno,
7320 false)));
7321
7322 /*
7323 * Print any indirection needed (subfields or subscripts), and strip
7324 * off the top-level nodes representing the indirection assignments.
7325 */
7326 expr = processIndirection((Node *) tle->expr, context);
7327
7328 /*
7329 * If we're in a multiassignment, skip printing anything more, unless
7330 * this is the last column; in which case, what we print should be the
7331 * sublink, not the Param.
7332 */
7333 if (cur_ma_sublink != NULL)
7334 {
7335 if (--remaining_ma_columns > 0)
7336 continue; /* not the last column of multiassignment */
7338 expr = (Node *) cur_ma_sublink;
7339 cur_ma_sublink = NULL;
7340 }
7341
7343
7344 get_rule_expr(expr, context, false);
7345 }
7346}
7347
7348
7349/* ----------
7350 * get_delete_query_def - Parse back a DELETE parsetree
7351 * ----------
7352 */
7353static void
7355{
7356 StringInfo buf = context->buf;
7357 RangeTblEntry *rte;
7358
7359 /* Insert the WITH clause if given */
7360 get_with_clause(query, context);
7361
7362 /*
7363 * Start the query with DELETE FROM relname
7364 */
7365 rte = rt_fetch(query->resultRelation, query->rtable);
7366 Assert(rte->rtekind == RTE_RELATION);
7367 if (PRETTY_INDENT(context))
7368 {
7370 context->indentLevel += PRETTYINDENT_STD;
7371 }
7372 appendStringInfo(buf, "DELETE FROM %s%s",
7373 only_marker(rte),
7374 generate_relation_name(rte->relid, NIL));
7375
7376 /* Print the relation alias, if needed */
7377 get_rte_alias(rte, query->resultRelation, false, context);
7378
7379 /* Add the USING clause if given */
7380 get_from_clause(query, " USING ", context);
7381
7382 /* Add a WHERE clause if given */
7383 if (query->jointree->quals != NULL)
7384 {
7385 appendContextKeyword(context, " WHERE ",
7387 get_rule_expr(query->jointree->quals, context, false);
7388 }
7389
7390 /* Add RETURNING if present */
7391 if (query->returningList)
7392 get_returning_clause(query, context);
7393}
7394
7395
7396/* ----------
7397 * get_merge_query_def - Parse back a MERGE parsetree
7398 * ----------
7399 */
7400static void
7402{
7403 StringInfo buf = context->buf;
7404 RangeTblEntry *rte;
7405 ListCell *lc;
7406 bool haveNotMatchedBySource;
7407
7408 /* Insert the WITH clause if given */
7409 get_with_clause(query, context);
7410
7411 /*
7412 * Start the query with MERGE INTO relname
7413 */
7414 rte = rt_fetch(query->resultRelation, query->rtable);
7415 Assert(rte->rtekind == RTE_RELATION);
7416 if (PRETTY_INDENT(context))
7417 {
7419 context->indentLevel += PRETTYINDENT_STD;
7420 }
7421 appendStringInfo(buf, "MERGE INTO %s%s",
7422 only_marker(rte),
7423 generate_relation_name(rte->relid, NIL));
7424
7425 /* Print the relation alias, if needed */
7426 get_rte_alias(rte, query->resultRelation, false, context);
7427
7428 /* Print the source relation and join clause */
7429 get_from_clause(query, " USING ", context);
7430 appendContextKeyword(context, " ON ",
7432 get_rule_expr(query->mergeJoinCondition, context, false);
7433
7434 /*
7435 * Test for any NOT MATCHED BY SOURCE actions. If there are none, then
7436 * any NOT MATCHED BY TARGET actions are output as "WHEN NOT MATCHED", per
7437 * SQL standard. Otherwise, we have a non-SQL-standard query, so output
7438 * "BY SOURCE" / "BY TARGET" qualifiers for all NOT MATCHED actions, to be
7439 * more explicit.
7440 */
7441 haveNotMatchedBySource = false;
7442 foreach(lc, query->mergeActionList)
7443 {
7445
7446 if (action->matchKind == MERGE_WHEN_NOT_MATCHED_BY_SOURCE)
7447 {
7448 haveNotMatchedBySource = true;
7449 break;
7450 }
7451 }
7452
7453 /* Print each merge action */
7454 foreach(lc, query->mergeActionList)
7455 {
7457
7458 appendContextKeyword(context, " WHEN ",
7460 switch (action->matchKind)
7461 {
7462 case MERGE_WHEN_MATCHED:
7463 appendStringInfoString(buf, "MATCHED");
7464 break;
7466 appendStringInfoString(buf, "NOT MATCHED BY SOURCE");
7467 break;
7469 if (haveNotMatchedBySource)
7470 appendStringInfoString(buf, "NOT MATCHED BY TARGET");
7471 else
7472 appendStringInfoString(buf, "NOT MATCHED");
7473 break;
7474 default:
7475 elog(ERROR, "unrecognized matchKind: %d",
7476 (int) action->matchKind);
7477 }
7478
7479 if (action->qual)
7480 {
7481 appendContextKeyword(context, " AND ",
7483 get_rule_expr(action->qual, context, false);
7484 }
7485 appendContextKeyword(context, " THEN ",
7487
7488 if (action->commandType == CMD_INSERT)
7489 {
7490 /* This generally matches get_insert_query_def() */
7491 List *strippedexprs = NIL;
7492 const char *sep = "";
7493 ListCell *lc2;
7494
7495 appendStringInfoString(buf, "INSERT");
7496
7497 if (action->targetList)
7499 foreach(lc2, action->targetList)
7500 {
7501 TargetEntry *tle = (TargetEntry *) lfirst(lc2);
7502
7503 Assert(!tle->resjunk);
7504
7506 sep = ", ";
7507
7509 quote_identifier(get_attname(rte->relid,
7510 tle->resno,
7511 false)));
7512 strippedexprs = lappend(strippedexprs,
7513 processIndirection((Node *) tle->expr,
7514 context));
7515 }
7516 if (action->targetList)
7518
7519 if (action->override)
7520 {
7521 if (action->override == OVERRIDING_SYSTEM_VALUE)
7522 appendStringInfoString(buf, " OVERRIDING SYSTEM VALUE");
7523 else if (action->override == OVERRIDING_USER_VALUE)
7524 appendStringInfoString(buf, " OVERRIDING USER VALUE");
7525 }
7526
7527 if (strippedexprs)
7528 {
7529 appendContextKeyword(context, " VALUES (",
7531 get_rule_list_toplevel(strippedexprs, context, false);
7533 }
7534 else
7535 appendStringInfoString(buf, " DEFAULT VALUES");
7536 }
7537 else if (action->commandType == CMD_UPDATE)
7538 {
7539 appendStringInfoString(buf, "UPDATE SET ");
7540 get_update_query_targetlist_def(query, action->targetList,
7541 context, rte);
7542 }
7543 else if (action->commandType == CMD_DELETE)
7544 appendStringInfoString(buf, "DELETE");
7545 else if (action->commandType == CMD_NOTHING)
7546 appendStringInfoString(buf, "DO NOTHING");
7547 }
7548
7549 /* Add RETURNING if present */
7550 if (query->returningList)
7551 get_returning_clause(query, context);
7552}
7553
7554
7555/* ----------
7556 * get_utility_query_def - Parse back a UTILITY parsetree
7557 * ----------
7558 */
7559static void
7561{
7562 StringInfo buf = context->buf;
7563
7564 if (query->utilityStmt && IsA(query->utilityStmt, NotifyStmt))
7565 {
7566 NotifyStmt *stmt = (NotifyStmt *) query->utilityStmt;
7567
7568 appendContextKeyword(context, "",
7569 0, PRETTYINDENT_STD, 1);
7570 appendStringInfo(buf, "NOTIFY %s",
7571 quote_identifier(stmt->conditionname));
7572 if (stmt->payload)
7573 {
7575 simple_quote_literal(buf, stmt->payload);
7576 }
7577 }
7578 else
7579 {
7580 /* Currently only NOTIFY utility commands can appear in rules */
7581 elog(ERROR, "unexpected utility statement type");
7582 }
7583}
7584
7585/*
7586 * Display a Var appropriately.
7587 *
7588 * In some cases (currently only when recursing into an unnamed join)
7589 * the Var's varlevelsup has to be interpreted with respect to a context
7590 * above the current one; levelsup indicates the offset.
7591 *
7592 * If istoplevel is true, the Var is at the top level of a SELECT's
7593 * targetlist, which means we need special treatment of whole-row Vars.
7594 * Instead of the normal "tab.*", we'll print "tab.*::typename", which is a
7595 * dirty hack to prevent "tab.*" from being expanded into multiple columns.
7596 * (The parser will strip the useless coercion, so no inefficiency is added in
7597 * dump and reload.) We used to print just "tab" in such cases, but that is
7598 * ambiguous and will yield the wrong result if "tab" is also a plain column
7599 * name in the query.
7600 *
7601 * Returns the attname of the Var, or NULL if the Var has no attname (because
7602 * it is a whole-row Var or a subplan output reference).
7603 */
7604static char *
7605get_variable(Var *var, int levelsup, bool istoplevel, deparse_context *context)
7606{
7607 StringInfo buf = context->buf;
7608 RangeTblEntry *rte;
7610 int netlevelsup;
7611 deparse_namespace *dpns;
7612 int varno;
7613 AttrNumber varattno;
7614 deparse_columns *colinfo;
7615 char *refname;
7616 char *attname;
7617 bool need_prefix;
7618
7619 /* Find appropriate nesting depth */
7620 netlevelsup = var->varlevelsup + levelsup;
7621 if (netlevelsup >= list_length(context->namespaces))
7622 elog(ERROR, "bogus varlevelsup: %d offset %d",
7623 var->varlevelsup, levelsup);
7624 dpns = (deparse_namespace *) list_nth(context->namespaces,
7625 netlevelsup);
7626
7627 /*
7628 * If we have a syntactic referent for the Var, and we're working from a
7629 * parse tree, prefer to use the syntactic referent. Otherwise, fall back
7630 * on the semantic referent. (Forcing use of the semantic referent when
7631 * printing plan trees is a design choice that's perhaps more motivated by
7632 * backwards compatibility than anything else. But it does have the
7633 * advantage of making plans more explicit.)
7634 */
7635 if (var->varnosyn > 0 && dpns->plan == NULL)
7636 {
7637 varno = var->varnosyn;
7638 varattno = var->varattnosyn;
7639 }
7640 else
7641 {
7642 varno = var->varno;
7643 varattno = var->varattno;
7644 }
7645
7646 /*
7647 * Try to find the relevant RTE in this rtable. In a plan tree, it's
7648 * likely that varno is OUTER_VAR or INNER_VAR, in which case we must dig
7649 * down into the subplans, or INDEX_VAR, which is resolved similarly. Also
7650 * find the aliases previously assigned for this RTE.
7651 */
7652 if (varno >= 1 && varno <= list_length(dpns->rtable))
7653 {
7654 /*
7655 * We might have been asked to map child Vars to some parent relation.
7656 */
7657 if (context->appendparents && dpns->appendrels)
7658 {
7659 int pvarno = varno;
7660 AttrNumber pvarattno = varattno;
7661 AppendRelInfo *appinfo = dpns->appendrels[pvarno];
7662 bool found = false;
7663
7664 /* Only map up to inheritance parents, not UNION ALL appendrels */
7665 while (appinfo &&
7666 rt_fetch(appinfo->parent_relid,
7667 dpns->rtable)->rtekind == RTE_RELATION)
7668 {
7669 found = false;
7670 if (pvarattno > 0) /* system columns stay as-is */
7671 {
7672 if (pvarattno > appinfo->num_child_cols)
7673 break; /* safety check */
7674 pvarattno = appinfo->parent_colnos[pvarattno - 1];
7675 if (pvarattno == 0)
7676 break; /* Var is local to child */
7677 }
7678
7679 pvarno = appinfo->parent_relid;
7680 found = true;
7681
7682 /* If the parent is itself a child, continue up. */
7683 Assert(pvarno > 0 && pvarno <= list_length(dpns->rtable));
7684 appinfo = dpns->appendrels[pvarno];
7685 }
7686
7687 /*
7688 * If we found an ancestral rel, and that rel is included in
7689 * appendparents, print that column not the original one.
7690 */
7691 if (found && bms_is_member(pvarno, context->appendparents))
7692 {
7693 varno = pvarno;
7694 varattno = pvarattno;
7695 }
7696 }
7697
7698 rte = rt_fetch(varno, dpns->rtable);
7699
7700 /* might be returning old/new column value */
7702 refname = dpns->ret_old_alias;
7703 else if (var->varreturningtype == VAR_RETURNING_NEW)
7704 refname = dpns->ret_new_alias;
7705 else
7706 refname = (char *) list_nth(dpns->rtable_names, varno - 1);
7707
7708 colinfo = deparse_columns_fetch(varno, dpns);
7709 attnum = varattno;
7710 }
7711 else
7712 {
7713 resolve_special_varno((Node *) var, context,
7714 get_special_variable, NULL);
7715 return NULL;
7716 }
7717
7718 /*
7719 * The planner will sometimes emit Vars referencing resjunk elements of a
7720 * subquery's target list (this is currently only possible if it chooses
7721 * to generate a "physical tlist" for a SubqueryScan or CteScan node).
7722 * Although we prefer to print subquery-referencing Vars using the
7723 * subquery's alias, that's not possible for resjunk items since they have
7724 * no alias. So in that case, drill down to the subplan and print the
7725 * contents of the referenced tlist item. This works because in a plan
7726 * tree, such Vars can only occur in a SubqueryScan or CteScan node, and
7727 * we'll have set dpns->inner_plan to reference the child plan node.
7728 */
7729 if ((rte->rtekind == RTE_SUBQUERY || rte->rtekind == RTE_CTE) &&
7730 attnum > list_length(rte->eref->colnames) &&
7731 dpns->inner_plan)
7732 {
7733 TargetEntry *tle;
7734 deparse_namespace save_dpns;
7735
7736 tle = get_tle_by_resno(dpns->inner_tlist, attnum);
7737 if (!tle)
7738 elog(ERROR, "invalid attnum %d for relation \"%s\"",
7739 attnum, rte->eref->aliasname);
7740
7741 Assert(netlevelsup == 0);
7742 push_child_plan(dpns, dpns->inner_plan, &save_dpns);
7743
7744 /*
7745 * Force parentheses because our caller probably assumed a Var is a
7746 * simple expression.
7747 */
7748 if (!IsA(tle->expr, Var))
7750 get_rule_expr((Node *) tle->expr, context, true);
7751 if (!IsA(tle->expr, Var))
7753
7754 pop_child_plan(dpns, &save_dpns);
7755 return NULL;
7756 }
7757
7758 /*
7759 * If it's an unnamed join, look at the expansion of the alias variable.
7760 * If it's a simple reference to one of the input vars, then recursively
7761 * print the name of that var instead. When it's not a simple reference,
7762 * we have to just print the unqualified join column name. (This can only
7763 * happen with "dangerous" merged columns in a JOIN USING; we took pains
7764 * previously to make the unqualified column name unique in such cases.)
7765 *
7766 * This wouldn't work in decompiling plan trees, because we don't store
7767 * joinaliasvars lists after planning; but a plan tree should never
7768 * contain a join alias variable.
7769 */
7770 if (rte->rtekind == RTE_JOIN && rte->alias == NULL)
7771 {
7772 if (rte->joinaliasvars == NIL)
7773 elog(ERROR, "cannot decompile join alias var in plan tree");
7774 if (attnum > 0)
7775 {
7776 Var *aliasvar;
7777
7778 aliasvar = (Var *) list_nth(rte->joinaliasvars, attnum - 1);
7779 /* we intentionally don't strip implicit coercions here */
7780 if (aliasvar && IsA(aliasvar, Var))
7781 {
7782 return get_variable(aliasvar, var->varlevelsup + levelsup,
7783 istoplevel, context);
7784 }
7785 }
7786
7787 /*
7788 * Unnamed join has no refname. (Note: since it's unnamed, there is
7789 * no way the user could have referenced it to create a whole-row Var
7790 * for it. So we don't have to cover that case below.)
7791 */
7792 Assert(refname == NULL);
7793 }
7794
7796 attname = NULL;
7797 else if (attnum > 0)
7798 {
7799 /* Get column name to use from the colinfo struct */
7800 if (attnum > colinfo->num_cols)
7801 elog(ERROR, "invalid attnum %d for relation \"%s\"",
7802 attnum, rte->eref->aliasname);
7803 attname = colinfo->colnames[attnum - 1];
7804
7805 /*
7806 * If we find a Var referencing a dropped column, it seems better to
7807 * print something (anything) than to fail. In general this should
7808 * not happen, but it used to be possible for some cases involving
7809 * functions returning named composite types, and perhaps there are
7810 * still bugs out there.
7811 */
7812 if (attname == NULL)
7813 attname = "?dropped?column?";
7814 }
7815 else
7816 {
7817 /* System column - name is fixed, get it from the catalog */
7819 }
7820
7821 need_prefix = (context->varprefix || attname == NULL ||
7823
7824 /*
7825 * If we're considering a plain Var in an ORDER BY (but not GROUP BY)
7826 * clause, we may need to add a table-name prefix to prevent
7827 * findTargetlistEntrySQL92 from misinterpreting the name as an
7828 * output-column name. To avoid cluttering the output with unnecessary
7829 * prefixes, do so only if there is a name match to a SELECT tlist item
7830 * that is different from the Var.
7831 */
7832 if (context->varInOrderBy && !context->inGroupBy && !need_prefix)
7833 {
7834 int colno = 0;
7835
7836 foreach_node(TargetEntry, tle, context->targetList)
7837 {
7838 char *colname;
7839
7840 if (tle->resjunk)
7841 continue; /* ignore junk entries */
7842 colno++;
7843
7844 /* This must match colname-choosing logic in get_target_list() */
7845 if (context->resultDesc && colno <= context->resultDesc->natts)
7846 colname = NameStr(TupleDescAttr(context->resultDesc,
7847 colno - 1)->attname);
7848 else
7849 colname = tle->resname;
7850
7851 if (colname && strcmp(colname, attname) == 0 &&
7852 !equal(var, tle->expr))
7853 {
7854 need_prefix = true;
7855 break;
7856 }
7857 }
7858 }
7859
7860 if (refname && need_prefix)
7861 {
7864 }
7865 if (attname)
7867 else
7868 {
7870 if (istoplevel)
7871 appendStringInfo(buf, "::%s",
7872 format_type_with_typemod(var->vartype,
7873 var->vartypmod));
7874 }
7875
7876 return attname;
7877}
7878
7879/*
7880 * Deparse a Var which references OUTER_VAR, INNER_VAR, or INDEX_VAR. This
7881 * routine is actually a callback for resolve_special_varno, which handles
7882 * finding the correct TargetEntry. We get the expression contained in that
7883 * TargetEntry and just need to deparse it, a job we can throw back on
7884 * get_rule_expr.
7885 */
7886static void
7887get_special_variable(Node *node, deparse_context *context, void *callback_arg)
7888{
7889 StringInfo buf = context->buf;
7890
7891 /*
7892 * For a non-Var referent, force parentheses because our caller probably
7893 * assumed a Var is a simple expression.
7894 */
7895 if (!IsA(node, Var))
7897 get_rule_expr(node, context, true);
7898 if (!IsA(node, Var))
7900}
7901
7902/*
7903 * Chase through plan references to special varnos (OUTER_VAR, INNER_VAR,
7904 * INDEX_VAR) until we find a real Var or some kind of non-Var node; then,
7905 * invoke the callback provided.
7906 */
7907static void
7909 rsv_callback callback, void *callback_arg)
7910{
7911 Var *var;
7912 deparse_namespace *dpns;
7913
7914 /* This function is recursive, so let's be paranoid. */
7916
7917 /* If it's not a Var, invoke the callback. */
7918 if (!IsA(node, Var))
7919 {
7920 (*callback) (node, context, callback_arg);
7921 return;
7922 }
7923
7924 /* Find appropriate nesting depth */
7925 var = (Var *) node;
7926 dpns = (deparse_namespace *) list_nth(context->namespaces,
7927 var->varlevelsup);
7928
7929 /*
7930 * If varno is special, recurse. (Don't worry about varnosyn; if we're
7931 * here, we already decided not to use that.)
7932 */
7933 if (var->varno == OUTER_VAR && dpns->outer_tlist)
7934 {
7935 TargetEntry *tle;
7936 deparse_namespace save_dpns;
7937 Bitmapset *save_appendparents;
7938
7939 tle = get_tle_by_resno(dpns->outer_tlist, var->varattno);
7940 if (!tle)
7941 elog(ERROR, "bogus varattno for OUTER_VAR var: %d", var->varattno);
7942
7943 /*
7944 * If we're descending to the first child of an Append or MergeAppend,
7945 * update appendparents. This will affect deparsing of all Vars
7946 * appearing within the eventually-resolved subexpression.
7947 */
7948 save_appendparents = context->appendparents;
7949
7950 if (IsA(dpns->plan, Append))
7951 context->appendparents = bms_union(context->appendparents,
7952 ((Append *) dpns->plan)->apprelids);
7953 else if (IsA(dpns->plan, MergeAppend))
7954 context->appendparents = bms_union(context->appendparents,
7955 ((MergeAppend *) dpns->plan)->apprelids);
7956
7957 push_child_plan(dpns, dpns->outer_plan, &save_dpns);
7958 resolve_special_varno((Node *) tle->expr, context,
7959 callback, callback_arg);
7960 pop_child_plan(dpns, &save_dpns);
7961 context->appendparents = save_appendparents;
7962 return;
7963 }
7964 else if (var->varno == INNER_VAR && dpns->inner_tlist)
7965 {
7966 TargetEntry *tle;
7967 deparse_namespace save_dpns;
7968
7969 tle = get_tle_by_resno(dpns->inner_tlist, var->varattno);
7970 if (!tle)
7971 elog(ERROR, "bogus varattno for INNER_VAR var: %d", var->varattno);
7972
7973 push_child_plan(dpns, dpns->inner_plan, &save_dpns);
7974 resolve_special_varno((Node *) tle->expr, context,
7975 callback, callback_arg);
7976 pop_child_plan(dpns, &save_dpns);
7977 return;
7978 }
7979 else if (var->varno == INDEX_VAR && dpns->index_tlist)
7980 {
7981 TargetEntry *tle;
7982
7983 tle = get_tle_by_resno(dpns->index_tlist, var->varattno);
7984 if (!tle)
7985 elog(ERROR, "bogus varattno for INDEX_VAR var: %d", var->varattno);
7986
7987 resolve_special_varno((Node *) tle->expr, context,
7988 callback, callback_arg);
7989 return;
7990 }
7991 else if (var->varno < 1 || var->varno > list_length(dpns->rtable))
7992 elog(ERROR, "bogus varno: %d", var->varno);
7993
7994 /* Not special. Just invoke the callback. */
7995 (*callback) (node, context, callback_arg);
7996}
7997
7998/*
7999 * Get the name of a field of an expression of composite type. The
8000 * expression is usually a Var, but we handle other cases too.
8001 *
8002 * levelsup is an extra offset to interpret the Var's varlevelsup correctly.
8003 *
8004 * This is fairly straightforward when the expression has a named composite
8005 * type; we need only look up the type in the catalogs. However, the type
8006 * could also be RECORD. Since no actual table or view column is allowed to
8007 * have type RECORD, a Var of type RECORD must refer to a JOIN or FUNCTION RTE
8008 * or to a subquery output. We drill down to find the ultimate defining
8009 * expression and attempt to infer the field name from it. We ereport if we
8010 * can't determine the name.
8011 *
8012 * Similarly, a PARAM of type RECORD has to refer to some expression of
8013 * a determinable composite type.
8014 */
8015static const char *
8016get_name_for_var_field(Var *var, int fieldno,
8017 int levelsup, deparse_context *context)
8018{
8019 RangeTblEntry *rte;
8021 int netlevelsup;
8022 deparse_namespace *dpns;
8023 int varno;
8024 AttrNumber varattno;
8025 TupleDesc tupleDesc;
8026 Node *expr;
8027
8028 /*
8029 * If it's a RowExpr that was expanded from a whole-row Var, use the
8030 * column names attached to it. (We could let get_expr_result_tupdesc()
8031 * handle this, but it's much cheaper to just pull out the name we need.)
8032 */
8033 if (IsA(var, RowExpr))
8034 {
8035 RowExpr *r = (RowExpr *) var;
8036
8037 if (fieldno > 0 && fieldno <= list_length(r->colnames))
8038 return strVal(list_nth(r->colnames, fieldno - 1));
8039 }
8040
8041 /*
8042 * If it's a Param of type RECORD, try to find what the Param refers to.
8043 */
8044 if (IsA(var, Param))
8045 {
8046 Param *param = (Param *) var;
8047 ListCell *ancestor_cell;
8048
8049 expr = find_param_referent(param, context, &dpns, &ancestor_cell);
8050 if (expr)
8051 {
8052 /* Found a match, so recurse to decipher the field name */
8053 deparse_namespace save_dpns;
8054 const char *result;
8055
8056 push_ancestor_plan(dpns, ancestor_cell, &save_dpns);
8057 result = get_name_for_var_field((Var *) expr, fieldno,
8058 0, context);
8059 pop_ancestor_plan(dpns, &save_dpns);
8060 return result;
8061 }
8062 }
8063
8064 /*
8065 * If it's a Var of type RECORD, we have to find what the Var refers to;
8066 * if not, we can use get_expr_result_tupdesc().
8067 */
8068 if (!IsA(var, Var) ||
8069 var->vartype != RECORDOID)
8070 {
8071 tupleDesc = get_expr_result_tupdesc((Node *) var, false);
8072 /* Got the tupdesc, so we can extract the field name */
8073 Assert(fieldno >= 1 && fieldno <= tupleDesc->natts);
8074 return NameStr(TupleDescAttr(tupleDesc, fieldno - 1)->attname);
8075 }
8076
8077 /* Find appropriate nesting depth */
8078 netlevelsup = var->varlevelsup + levelsup;
8079 if (netlevelsup >= list_length(context->namespaces))
8080 elog(ERROR, "bogus varlevelsup: %d offset %d",
8081 var->varlevelsup, levelsup);
8082 dpns = (deparse_namespace *) list_nth(context->namespaces,
8083 netlevelsup);
8084
8085 /*
8086 * If we have a syntactic referent for the Var, and we're working from a
8087 * parse tree, prefer to use the syntactic referent. Otherwise, fall back
8088 * on the semantic referent. (See comments in get_variable().)
8089 */
8090 if (var->varnosyn > 0 && dpns->plan == NULL)
8091 {
8092 varno = var->varnosyn;
8093 varattno = var->varattnosyn;
8094 }
8095 else
8096 {
8097 varno = var->varno;
8098 varattno = var->varattno;
8099 }
8100
8101 /*
8102 * Try to find the relevant RTE in this rtable. In a plan tree, it's
8103 * likely that varno is OUTER_VAR or INNER_VAR, in which case we must dig
8104 * down into the subplans, or INDEX_VAR, which is resolved similarly.
8105 *
8106 * Note: unlike get_variable and resolve_special_varno, we need not worry
8107 * about inheritance mapping: a child Var should have the same datatype as
8108 * its parent, and here we're really only interested in the Var's type.
8109 */
8110 if (varno >= 1 && varno <= list_length(dpns->rtable))
8111 {
8112 rte = rt_fetch(varno, dpns->rtable);
8113 attnum = varattno;
8114 }
8115 else if (varno == OUTER_VAR && dpns->outer_tlist)
8116 {
8117 TargetEntry *tle;
8118 deparse_namespace save_dpns;
8119 const char *result;
8120
8121 tle = get_tle_by_resno(dpns->outer_tlist, varattno);
8122 if (!tle)
8123 elog(ERROR, "bogus varattno for OUTER_VAR var: %d", varattno);
8124
8125 Assert(netlevelsup == 0);
8126 push_child_plan(dpns, dpns->outer_plan, &save_dpns);
8127
8128 result = get_name_for_var_field((Var *) tle->expr, fieldno,
8129 levelsup, context);
8130
8131 pop_child_plan(dpns, &save_dpns);
8132 return result;
8133 }
8134 else if (varno == INNER_VAR && dpns->inner_tlist)
8135 {
8136 TargetEntry *tle;
8137 deparse_namespace save_dpns;
8138 const char *result;
8139
8140 tle = get_tle_by_resno(dpns->inner_tlist, varattno);
8141 if (!tle)
8142 elog(ERROR, "bogus varattno for INNER_VAR var: %d", varattno);
8143
8144 Assert(netlevelsup == 0);
8145 push_child_plan(dpns, dpns->inner_plan, &save_dpns);
8146
8147 result = get_name_for_var_field((Var *) tle->expr, fieldno,
8148 levelsup, context);
8149
8150 pop_child_plan(dpns, &save_dpns);
8151 return result;
8152 }
8153 else if (varno == INDEX_VAR && dpns->index_tlist)
8154 {
8155 TargetEntry *tle;
8156 const char *result;
8157
8158 tle = get_tle_by_resno(dpns->index_tlist, varattno);
8159 if (!tle)
8160 elog(ERROR, "bogus varattno for INDEX_VAR var: %d", varattno);
8161
8162 Assert(netlevelsup == 0);
8163
8164 result = get_name_for_var_field((Var *) tle->expr, fieldno,
8165 levelsup, context);
8166
8167 return result;
8168 }
8169 else
8170 {
8171 elog(ERROR, "bogus varno: %d", varno);
8172 return NULL; /* keep compiler quiet */
8173 }
8174
8176 {
8177 /* Var is whole-row reference to RTE, so select the right field */
8178 return get_rte_attribute_name(rte, fieldno);
8179 }
8180
8181 /*
8182 * This part has essentially the same logic as the parser's
8183 * expandRecordVariable() function, but we are dealing with a different
8184 * representation of the input context, and we only need one field name
8185 * not a TupleDesc. Also, we need special cases for finding subquery and
8186 * CTE subplans when deparsing Plan trees.
8187 */
8188 expr = (Node *) var; /* default if we can't drill down */
8189
8190 switch (rte->rtekind)
8191 {
8192 case RTE_RELATION:
8193 case RTE_VALUES:
8195 case RTE_RESULT:
8196
8197 /*
8198 * This case should not occur: a column of a table, values list,
8199 * or ENR shouldn't have type RECORD. Fall through and fail (most
8200 * likely) at the bottom.
8201 */
8202 break;
8203 case RTE_SUBQUERY:
8204 /* Subselect-in-FROM: examine sub-select's output expr */
8205 {
8206 if (rte->subquery)
8207 {
8209 attnum);
8210
8211 if (ste == NULL || ste->resjunk)
8212 elog(ERROR, "subquery %s does not have attribute %d",
8213 rte->eref->aliasname, attnum);
8214 expr = (Node *) ste->expr;
8215 if (IsA(expr, Var))
8216 {
8217 /*
8218 * Recurse into the sub-select to see what its Var
8219 * refers to. We have to build an additional level of
8220 * namespace to keep in step with varlevelsup in the
8221 * subselect; furthermore, the subquery RTE might be
8222 * from an outer query level, in which case the
8223 * namespace for the subselect must have that outer
8224 * level as parent namespace.
8225 */
8226 List *save_nslist = context->namespaces;
8227 List *parent_namespaces;
8228 deparse_namespace mydpns;
8229 const char *result;
8230
8231 parent_namespaces = list_copy_tail(context->namespaces,
8232 netlevelsup);
8233
8234 set_deparse_for_query(&mydpns, rte->subquery,
8235 parent_namespaces);
8236
8237 context->namespaces = lcons(&mydpns, parent_namespaces);
8238
8239 result = get_name_for_var_field((Var *) expr, fieldno,
8240 0, context);
8241
8242 context->namespaces = save_nslist;
8243
8244 return result;
8245 }
8246 /* else fall through to inspect the expression */
8247 }
8248 else
8249 {
8250 /*
8251 * We're deparsing a Plan tree so we don't have complete
8252 * RTE entries (in particular, rte->subquery is NULL). But
8253 * the only place we'd normally see a Var directly
8254 * referencing a SUBQUERY RTE is in a SubqueryScan plan
8255 * node, and we can look into the child plan's tlist
8256 * instead. An exception occurs if the subquery was
8257 * proven empty and optimized away: then we'd find such a
8258 * Var in a childless Result node, and there's nothing in
8259 * the plan tree that would let us figure out what it had
8260 * originally referenced. In that case, fall back on
8261 * printing "fN", analogously to the default column names
8262 * for RowExprs.
8263 */
8264 TargetEntry *tle;
8265 deparse_namespace save_dpns;
8266 const char *result;
8267
8268 if (!dpns->inner_plan)
8269 {
8270 char *dummy_name = palloc(32);
8271
8272 Assert(dpns->plan && IsA(dpns->plan, Result));
8273 snprintf(dummy_name, 32, "f%d", fieldno);
8274 return dummy_name;
8275 }
8276 Assert(dpns->plan && IsA(dpns->plan, SubqueryScan));
8277
8278 tle = get_tle_by_resno(dpns->inner_tlist, attnum);
8279 if (!tle)
8280 elog(ERROR, "bogus varattno for subquery var: %d",
8281 attnum);
8282 Assert(netlevelsup == 0);
8283 push_child_plan(dpns, dpns->inner_plan, &save_dpns);
8284
8285 result = get_name_for_var_field((Var *) tle->expr, fieldno,
8286 levelsup, context);
8287
8288 pop_child_plan(dpns, &save_dpns);
8289 return result;
8290 }
8291 }
8292 break;
8293 case RTE_JOIN:
8294 /* Join RTE --- recursively inspect the alias variable */
8295 if (rte->joinaliasvars == NIL)
8296 elog(ERROR, "cannot decompile join alias var in plan tree");
8297 Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
8298 expr = (Node *) list_nth(rte->joinaliasvars, attnum - 1);
8299 Assert(expr != NULL);
8300 /* we intentionally don't strip implicit coercions here */
8301 if (IsA(expr, Var))
8302 return get_name_for_var_field((Var *) expr, fieldno,
8303 var->varlevelsup + levelsup,
8304 context);
8305 /* else fall through to inspect the expression */
8306 break;
8307 case RTE_FUNCTION:
8308 case RTE_TABLEFUNC:
8309
8310 /*
8311 * We couldn't get here unless a function is declared with one of
8312 * its result columns as RECORD, which is not allowed.
8313 */
8314 break;
8315 case RTE_CTE:
8316 /* CTE reference: examine subquery's output expr */
8317 {
8318 CommonTableExpr *cte = NULL;
8319 Index ctelevelsup;
8320 ListCell *lc;
8321
8322 /*
8323 * Try to find the referenced CTE using the namespace stack.
8324 */
8325 ctelevelsup = rte->ctelevelsup + netlevelsup;
8326 if (ctelevelsup >= list_length(context->namespaces))
8327 lc = NULL;
8328 else
8329 {
8330 deparse_namespace *ctedpns;
8331
8332 ctedpns = (deparse_namespace *)
8333 list_nth(context->namespaces, ctelevelsup);
8334 foreach(lc, ctedpns->ctes)
8335 {
8336 cte = (CommonTableExpr *) lfirst(lc);
8337 if (strcmp(cte->ctename, rte->ctename) == 0)
8338 break;
8339 }
8340 }
8341 if (lc != NULL)
8342 {
8343 Query *ctequery = (Query *) cte->ctequery;
8345 attnum);
8346
8347 if (ste == NULL || ste->resjunk)
8348 elog(ERROR, "CTE %s does not have attribute %d",
8349 rte->eref->aliasname, attnum);
8350 expr = (Node *) ste->expr;
8351 if (IsA(expr, Var))
8352 {
8353 /*
8354 * Recurse into the CTE to see what its Var refers to.
8355 * We have to build an additional level of namespace
8356 * to keep in step with varlevelsup in the CTE;
8357 * furthermore it could be an outer CTE (compare
8358 * SUBQUERY case above).
8359 */
8360 List *save_nslist = context->namespaces;
8361 List *parent_namespaces;
8362 deparse_namespace mydpns;
8363 const char *result;
8364
8365 parent_namespaces = list_copy_tail(context->namespaces,
8366 ctelevelsup);
8367
8368 set_deparse_for_query(&mydpns, ctequery,
8369 parent_namespaces);
8370
8371 context->namespaces = lcons(&mydpns, parent_namespaces);
8372
8373 result = get_name_for_var_field((Var *) expr, fieldno,
8374 0, context);
8375
8376 context->namespaces = save_nslist;
8377
8378 return result;
8379 }
8380 /* else fall through to inspect the expression */
8381 }
8382 else
8383 {
8384 /*
8385 * We're deparsing a Plan tree so we don't have a CTE
8386 * list. But the only places we'd normally see a Var
8387 * directly referencing a CTE RTE are in CteScan or
8388 * WorkTableScan plan nodes. For those cases,
8389 * set_deparse_plan arranged for dpns->inner_plan to be
8390 * the plan node that emits the CTE or RecursiveUnion
8391 * result, and we can look at its tlist instead. As
8392 * above, this can fail if the CTE has been proven empty,
8393 * in which case fall back to "fN".
8394 */
8395 TargetEntry *tle;
8396 deparse_namespace save_dpns;
8397 const char *result;
8398
8399 if (!dpns->inner_plan)
8400 {
8401 char *dummy_name = palloc(32);
8402
8403 Assert(dpns->plan && IsA(dpns->plan, Result));
8404 snprintf(dummy_name, 32, "f%d", fieldno);
8405 return dummy_name;
8406 }
8407 Assert(dpns->plan && (IsA(dpns->plan, CteScan) ||
8408 IsA(dpns->plan, WorkTableScan)));
8409
8410 tle = get_tle_by_resno(dpns->inner_tlist, attnum);
8411 if (!tle)
8412 elog(ERROR, "bogus varattno for subquery var: %d",
8413 attnum);
8414 Assert(netlevelsup == 0);
8415 push_child_plan(dpns, dpns->inner_plan, &save_dpns);
8416
8417 result = get_name_for_var_field((Var *) tle->expr, fieldno,
8418 levelsup, context);
8419
8420 pop_child_plan(dpns, &save_dpns);
8421 return result;
8422 }
8423 }
8424 break;
8425 case RTE_GROUP:
8426
8427 /*
8428 * We couldn't get here: any Vars that reference the RTE_GROUP RTE
8429 * should have been replaced with the underlying grouping
8430 * expressions.
8431 */
8432 break;
8433 }
8434
8435 /*
8436 * We now have an expression we can't expand any more, so see if
8437 * get_expr_result_tupdesc() can do anything with it.
8438 */
8439 tupleDesc = get_expr_result_tupdesc(expr, false);
8440 /* Got the tupdesc, so we can extract the field name */
8441 Assert(fieldno >= 1 && fieldno <= tupleDesc->natts);
8442 return NameStr(TupleDescAttr(tupleDesc, fieldno - 1)->attname);
8443}
8444
8445/*
8446 * Try to find the referenced expression for a PARAM_EXEC Param that might
8447 * reference a parameter supplied by an upper NestLoop or SubPlan plan node.
8448 *
8449 * If successful, return the expression and set *dpns_p and *ancestor_cell_p
8450 * appropriately for calling push_ancestor_plan(). If no referent can be
8451 * found, return NULL.
8452 */
8453static Node *
8455 deparse_namespace **dpns_p, ListCell **ancestor_cell_p)
8456{
8457 /* Initialize output parameters to prevent compiler warnings */
8458 *dpns_p = NULL;
8459 *ancestor_cell_p = NULL;
8460
8461 /*
8462 * If it's a PARAM_EXEC parameter, look for a matching NestLoopParam or
8463 * SubPlan argument. This will necessarily be in some ancestor of the
8464 * current expression's Plan node.
8465 */
8466 if (param->paramkind == PARAM_EXEC)
8467 {
8468 deparse_namespace *dpns;
8469 Plan *child_plan;
8470 ListCell *lc;
8471
8472 dpns = (deparse_namespace *) linitial(context->namespaces);
8473 child_plan = dpns->plan;
8474
8475 foreach(lc, dpns->ancestors)
8476 {
8477 Node *ancestor = (Node *) lfirst(lc);
8478 ListCell *lc2;
8479
8480 /*
8481 * NestLoops transmit params to their inner child only.
8482 */
8483 if (IsA(ancestor, NestLoop) &&
8484 child_plan == innerPlan(ancestor))
8485 {
8486 NestLoop *nl = (NestLoop *) ancestor;
8487
8488 foreach(lc2, nl->nestParams)
8489 {
8490 NestLoopParam *nlp = (NestLoopParam *) lfirst(lc2);
8491
8492 if (nlp->paramno == param->paramid)
8493 {
8494 /* Found a match, so return it */
8495 *dpns_p = dpns;
8496 *ancestor_cell_p = lc;
8497 return (Node *) nlp->paramval;
8498 }
8499 }
8500 }
8501
8502 /*
8503 * If ancestor is a SubPlan, check the arguments it provides.
8504 */
8505 if (IsA(ancestor, SubPlan))
8506 {
8507 SubPlan *subplan = (SubPlan *) ancestor;
8508 ListCell *lc3;
8509 ListCell *lc4;
8510
8511 forboth(lc3, subplan->parParam, lc4, subplan->args)
8512 {
8513 int paramid = lfirst_int(lc3);
8514 Node *arg = (Node *) lfirst(lc4);
8515
8516 if (paramid == param->paramid)
8517 {
8518 /*
8519 * Found a match, so return it. But, since Vars in
8520 * the arg are to be evaluated in the surrounding
8521 * context, we have to point to the next ancestor item
8522 * that is *not* a SubPlan.
8523 */
8524 ListCell *rest;
8525
8526 for_each_cell(rest, dpns->ancestors,
8527 lnext(dpns->ancestors, lc))
8528 {
8529 Node *ancestor2 = (Node *) lfirst(rest);
8530
8531 if (!IsA(ancestor2, SubPlan))
8532 {
8533 *dpns_p = dpns;
8534 *ancestor_cell_p = rest;
8535 return arg;
8536 }
8537 }
8538 elog(ERROR, "SubPlan cannot be outermost ancestor");
8539 }
8540 }
8541
8542 /* SubPlan isn't a kind of Plan, so skip the rest */
8543 continue;
8544 }
8545
8546 /*
8547 * We need not consider the ancestor's initPlan list, since
8548 * initplans never have any parParams.
8549 */
8550
8551 /* No luck, crawl up to next ancestor */
8552 child_plan = (Plan *) ancestor;
8553 }
8554 }
8555
8556 /* No referent found */
8557 return NULL;
8558}
8559
8560/*
8561 * Try to find a subplan/initplan that emits the value for a PARAM_EXEC Param.
8562 *
8563 * If successful, return the generating subplan/initplan and set *column_p
8564 * to the subplan's 0-based output column number.
8565 * Otherwise, return NULL.
8566 */
8567static SubPlan *
8568find_param_generator(Param *param, deparse_context *context, int *column_p)
8569{
8570 /* Initialize output parameter to prevent compiler warnings */
8571 *column_p = 0;
8572
8573 /*
8574 * If it's a PARAM_EXEC parameter, search the current plan node as well as
8575 * ancestor nodes looking for a subplan or initplan that emits the value
8576 * for the Param. It could appear in the setParams of an initplan or
8577 * MULTIEXPR_SUBLINK subplan, or in the paramIds of an ancestral SubPlan.
8578 */
8579 if (param->paramkind == PARAM_EXEC)
8580 {
8581 SubPlan *result;
8582 deparse_namespace *dpns;
8583 ListCell *lc;
8584
8585 dpns = (deparse_namespace *) linitial(context->namespaces);
8586
8587 /* First check the innermost plan node's initplans */
8588 result = find_param_generator_initplan(param, dpns->plan, column_p);
8589 if (result)
8590 return result;
8591
8592 /*
8593 * The plan's targetlist might contain MULTIEXPR_SUBLINK SubPlans,
8594 * which can be referenced by Params elsewhere in the targetlist.
8595 * (Such Params should always be in the same targetlist, so there's no
8596 * need to do this work at upper plan nodes.)
8597 */
8599 {
8600 if (tle->expr && IsA(tle->expr, SubPlan))
8601 {
8602 SubPlan *subplan = (SubPlan *) tle->expr;
8603
8604 if (subplan->subLinkType == MULTIEXPR_SUBLINK)
8605 {
8606 foreach_int(paramid, subplan->setParam)
8607 {
8608 if (paramid == param->paramid)
8609 {
8610 /* Found a match, so return it. */
8611 *column_p = foreach_current_index(paramid);
8612 return subplan;
8613 }
8614 }
8615 }
8616 }
8617 }
8618
8619 /* No luck, so check the ancestor nodes */
8620 foreach(lc, dpns->ancestors)
8621 {
8622 Node *ancestor = (Node *) lfirst(lc);
8623
8624 /*
8625 * If ancestor is a SubPlan, check the paramIds it provides.
8626 */
8627 if (IsA(ancestor, SubPlan))
8628 {
8629 SubPlan *subplan = (SubPlan *) ancestor;
8630
8631 foreach_int(paramid, subplan->paramIds)
8632 {
8633 if (paramid == param->paramid)
8634 {
8635 /* Found a match, so return it. */
8636 *column_p = foreach_current_index(paramid);
8637 return subplan;
8638 }
8639 }
8640
8641 /* SubPlan isn't a kind of Plan, so skip the rest */
8642 continue;
8643 }
8644
8645 /*
8646 * Otherwise, it's some kind of Plan node, so check its initplans.
8647 */
8648 result = find_param_generator_initplan(param, (Plan *) ancestor,
8649 column_p);
8650 if (result)
8651 return result;
8652
8653 /* No luck, crawl up to next ancestor */
8654 }
8655 }
8656
8657 /* No generator found */
8658 return NULL;
8659}
8660
8661/*
8662 * Subroutine for find_param_generator: search one Plan node's initplans
8663 */
8664static SubPlan *
8666{
8667 foreach_node(SubPlan, subplan, plan->initPlan)
8668 {
8669 foreach_int(paramid, subplan->setParam)
8670 {
8671 if (paramid == param->paramid)
8672 {
8673 /* Found a match, so return it. */
8674 *column_p = foreach_current_index(paramid);
8675 return subplan;
8676 }
8677 }
8678 }
8679 return NULL;
8680}
8681
8682/*
8683 * Display a Param appropriately.
8684 */
8685static void
8687{
8688 Node *expr;
8689 deparse_namespace *dpns;
8690 ListCell *ancestor_cell;
8691 SubPlan *subplan;
8692 int column;
8693
8694 /*
8695 * If it's a PARAM_EXEC parameter, try to locate the expression from which
8696 * the parameter was computed. This stanza handles only cases in which
8697 * the Param represents an input to the subplan we are currently in.
8698 */
8699 expr = find_param_referent(param, context, &dpns, &ancestor_cell);
8700 if (expr)
8701 {
8702 /* Found a match, so print it */
8703 deparse_namespace save_dpns;
8704 bool save_varprefix;
8705 bool need_paren;
8706
8707 /* Switch attention to the ancestor plan node */
8708 push_ancestor_plan(dpns, ancestor_cell, &save_dpns);
8709
8710 /*
8711 * Force prefixing of Vars, since they won't belong to the relation
8712 * being scanned in the original plan node.
8713 */
8714 save_varprefix = context->varprefix;
8715 context->varprefix = true;
8716
8717 /*
8718 * A Param's expansion is typically a Var, Aggref, GroupingFunc, or
8719 * upper-level Param, which wouldn't need extra parentheses.
8720 * Otherwise, insert parens to ensure the expression looks atomic.
8721 */
8722 need_paren = !(IsA(expr, Var) ||
8723 IsA(expr, Aggref) ||
8724 IsA(expr, GroupingFunc) ||
8725 IsA(expr, Param));
8726 if (need_paren)
8727 appendStringInfoChar(context->buf, '(');
8728
8729 get_rule_expr(expr, context, false);
8730
8731 if (need_paren)
8732 appendStringInfoChar(context->buf, ')');
8733
8734 context->varprefix = save_varprefix;
8735
8736 pop_ancestor_plan(dpns, &save_dpns);
8737
8738 return;
8739 }
8740
8741 /*
8742 * Alternatively, maybe it's a subplan output, which we print as a
8743 * reference to the subplan. (We could drill down into the subplan and
8744 * print the relevant targetlist expression, but that has been deemed too
8745 * confusing since it would violate normal SQL scope rules. Also, we're
8746 * relying on this reference to show that the testexpr containing the
8747 * Param has anything to do with that subplan at all.)
8748 */
8749 subplan = find_param_generator(param, context, &column);
8750 if (subplan)
8751 {
8752 appendStringInfo(context->buf, "(%s%s).col%d",
8753 subplan->useHashTable ? "hashed " : "",
8754 subplan->plan_name, column + 1);
8755
8756 return;
8757 }
8758
8759 /*
8760 * If it's an external parameter, see if the outermost namespace provides
8761 * function argument names.
8762 */
8763 if (param->paramkind == PARAM_EXTERN && context->namespaces != NIL)
8764 {
8765 dpns = llast(context->namespaces);
8766 if (dpns->argnames &&
8767 param->paramid > 0 &&
8768 param->paramid <= dpns->numargs)
8769 {
8770 char *argname = dpns->argnames[param->paramid - 1];
8771
8772 if (argname)
8773 {
8774 bool should_qualify = false;
8775 ListCell *lc;
8776
8777 /*
8778 * Qualify the parameter name if there are any other deparse
8779 * namespaces with range tables. This avoids qualifying in
8780 * trivial cases like "RETURN a + b", but makes it safe in all
8781 * other cases.
8782 */
8783 foreach(lc, context->namespaces)
8784 {
8785 deparse_namespace *depns = lfirst(lc);
8786
8787 if (depns->rtable_names != NIL)
8788 {
8789 should_qualify = true;
8790 break;
8791 }
8792 }
8793 if (should_qualify)
8794 {
8796 appendStringInfoChar(context->buf, '.');
8797 }
8798
8799 appendStringInfoString(context->buf, quote_identifier(argname));
8800 return;
8801 }
8802 }
8803 }
8804
8805 /*
8806 * Not PARAM_EXEC, or couldn't find referent: just print $N.
8807 *
8808 * It's a bug if we get here for anything except PARAM_EXTERN Params, but
8809 * in production builds printing $N seems more useful than failing.
8810 */
8811 Assert(param->paramkind == PARAM_EXTERN);
8812
8813 appendStringInfo(context->buf, "$%d", param->paramid);
8814}
8815
8816/*
8817 * get_simple_binary_op_name
8818 *
8819 * helper function for isSimpleNode
8820 * will return single char binary operator name, or NULL if it's not
8821 */
8822static const char *
8824{
8825 List *args = expr->args;
8826
8827 if (list_length(args) == 2)
8828 {
8829 /* binary operator */
8830 Node *arg1 = (Node *) linitial(args);
8831 Node *arg2 = (Node *) lsecond(args);
8832 const char *op;
8833
8834 op = generate_operator_name(expr->opno, exprType(arg1), exprType(arg2));
8835 if (strlen(op) == 1)
8836 return op;
8837 }
8838 return NULL;
8839}
8840
8841
8842/*
8843 * isSimpleNode - check if given node is simple (doesn't need parenthesizing)
8844 *
8845 * true : simple in the context of parent node's type
8846 * false : not simple
8847 */
8848static bool
8849isSimpleNode(Node *node, Node *parentNode, int prettyFlags)
8850{
8851 if (!node)
8852 return false;
8853
8854 switch (nodeTag(node))
8855 {
8856 case T_Var:
8857 case T_Const:
8858 case T_Param:
8859 case T_CoerceToDomainValue:
8860 case T_SetToDefault:
8861 case T_CurrentOfExpr:
8862 /* single words: always simple */
8863 return true;
8864
8865 case T_SubscriptingRef:
8866 case T_ArrayExpr:
8867 case T_RowExpr:
8868 case T_CoalesceExpr:
8869 case T_MinMaxExpr:
8870 case T_SQLValueFunction:
8871 case T_XmlExpr:
8872 case T_NextValueExpr:
8873 case T_NullIfExpr:
8874 case T_Aggref:
8875 case T_GroupingFunc:
8876 case T_WindowFunc:
8877 case T_MergeSupportFunc:
8878 case T_FuncExpr:
8879 case T_JsonConstructorExpr:
8880 case T_JsonExpr:
8881 /* function-like: name(..) or name[..] */
8882 return true;
8883
8884 /* CASE keywords act as parentheses */
8885 case T_CaseExpr:
8886 return true;
8887
8888 case T_FieldSelect:
8889
8890 /*
8891 * appears simple since . has top precedence, unless parent is
8892 * T_FieldSelect itself!
8893 */
8894 return !IsA(parentNode, FieldSelect);
8895
8896 case T_FieldStore:
8897
8898 /*
8899 * treat like FieldSelect (probably doesn't matter)
8900 */
8901 return !IsA(parentNode, FieldStore);
8902
8903 case T_CoerceToDomain:
8904 /* maybe simple, check args */
8905 return isSimpleNode((Node *) ((CoerceToDomain *) node)->arg,
8906 node, prettyFlags);
8907 case T_RelabelType:
8908 return isSimpleNode((Node *) ((RelabelType *) node)->arg,
8909 node, prettyFlags);
8910 case T_CoerceViaIO:
8911 return isSimpleNode((Node *) ((CoerceViaIO *) node)->arg,
8912 node, prettyFlags);
8913 case T_ArrayCoerceExpr:
8914 return isSimpleNode((Node *) ((ArrayCoerceExpr *) node)->arg,
8915 node, prettyFlags);
8916 case T_ConvertRowtypeExpr:
8917 return isSimpleNode((Node *) ((ConvertRowtypeExpr *) node)->arg,
8918 node, prettyFlags);
8919 case T_ReturningExpr:
8920 return isSimpleNode((Node *) ((ReturningExpr *) node)->retexpr,
8921 node, prettyFlags);
8922
8923 case T_OpExpr:
8924 {
8925 /* depends on parent node type; needs further checking */
8926 if (prettyFlags & PRETTYFLAG_PAREN && IsA(parentNode, OpExpr))
8927 {
8928 const char *op;
8929 const char *parentOp;
8930 bool is_lopriop;
8931 bool is_hipriop;
8932 bool is_lopriparent;
8933 bool is_hipriparent;
8934
8935 op = get_simple_binary_op_name((OpExpr *) node);
8936 if (!op)
8937 return false;
8938
8939 /* We know only the basic operators + - and * / % */
8940 is_lopriop = (strchr("+-", *op) != NULL);
8941 is_hipriop = (strchr("*/%", *op) != NULL);
8942 if (!(is_lopriop || is_hipriop))
8943 return false;
8944
8945 parentOp = get_simple_binary_op_name((OpExpr *) parentNode);
8946 if (!parentOp)
8947 return false;
8948
8949 is_lopriparent = (strchr("+-", *parentOp) != NULL);
8950 is_hipriparent = (strchr("*/%", *parentOp) != NULL);
8951 if (!(is_lopriparent || is_hipriparent))
8952 return false;
8953
8954 if (is_hipriop && is_lopriparent)
8955 return true; /* op binds tighter than parent */
8956
8957 if (is_lopriop && is_hipriparent)
8958 return false;
8959
8960 /*
8961 * Operators are same priority --- can skip parens only if
8962 * we have (a - b) - c, not a - (b - c).
8963 */
8964 if (node == (Node *) linitial(((OpExpr *) parentNode)->args))
8965 return true;
8966
8967 return false;
8968 }
8969 /* else do the same stuff as for T_SubLink et al. */
8970 }
8971 /* FALLTHROUGH */
8972
8973 case T_SubLink:
8974 case T_NullTest:
8975 case T_BooleanTest:
8976 case T_DistinctExpr:
8977 case T_JsonIsPredicate:
8978 switch (nodeTag(parentNode))
8979 {
8980 case T_FuncExpr:
8981 {
8982 /* special handling for casts and COERCE_SQL_SYNTAX */
8983 CoercionForm type = ((FuncExpr *) parentNode)->funcformat;
8984
8985 if (type == COERCE_EXPLICIT_CAST ||
8988 return false;
8989 return true; /* own parentheses */
8990 }
8991 case T_BoolExpr: /* lower precedence */
8992 case T_SubscriptingRef: /* other separators */
8993 case T_ArrayExpr: /* other separators */
8994 case T_RowExpr: /* other separators */
8995 case T_CoalesceExpr: /* own parentheses */
8996 case T_MinMaxExpr: /* own parentheses */
8997 case T_XmlExpr: /* own parentheses */
8998 case T_NullIfExpr: /* other separators */
8999 case T_Aggref: /* own parentheses */
9000 case T_GroupingFunc: /* own parentheses */
9001 case T_WindowFunc: /* own parentheses */
9002 case T_CaseExpr: /* other separators */
9003 return true;
9004 default:
9005 return false;
9006 }
9007
9008 case T_BoolExpr:
9009 switch (nodeTag(parentNode))
9010 {
9011 case T_BoolExpr:
9012 if (prettyFlags & PRETTYFLAG_PAREN)
9013 {
9015 BoolExprType parentType;
9016
9017 type = ((BoolExpr *) node)->boolop;
9018 parentType = ((BoolExpr *) parentNode)->boolop;
9019 switch (type)
9020 {
9021 case NOT_EXPR:
9022 case AND_EXPR:
9023 if (parentType == AND_EXPR || parentType == OR_EXPR)
9024 return true;
9025 break;
9026 case OR_EXPR:
9027 if (parentType == OR_EXPR)
9028 return true;
9029 break;
9030 }
9031 }
9032 return false;
9033 case T_FuncExpr:
9034 {
9035 /* special handling for casts and COERCE_SQL_SYNTAX */
9036 CoercionForm type = ((FuncExpr *) parentNode)->funcformat;
9037
9038 if (type == COERCE_EXPLICIT_CAST ||
9041 return false;
9042 return true; /* own parentheses */
9043 }
9044 case T_SubscriptingRef: /* other separators */
9045 case T_ArrayExpr: /* other separators */
9046 case T_RowExpr: /* other separators */
9047 case T_CoalesceExpr: /* own parentheses */
9048 case T_MinMaxExpr: /* own parentheses */
9049 case T_XmlExpr: /* own parentheses */
9050 case T_NullIfExpr: /* other separators */
9051 case T_Aggref: /* own parentheses */
9052 case T_GroupingFunc: /* own parentheses */
9053 case T_WindowFunc: /* own parentheses */
9054 case T_CaseExpr: /* other separators */
9055 case T_JsonExpr: /* own parentheses */
9056 return true;
9057 default:
9058 return false;
9059 }
9060
9061 case T_JsonValueExpr:
9062 /* maybe simple, check args */
9063 return isSimpleNode((Node *) ((JsonValueExpr *) node)->raw_expr,
9064 node, prettyFlags);
9065
9066 default:
9067 break;
9068 }
9069 /* those we don't know: in dubio complexo */
9070 return false;
9071}
9072
9073
9074/*
9075 * appendContextKeyword - append a keyword to buffer
9076 *
9077 * If prettyPrint is enabled, perform a line break, and adjust indentation.
9078 * Otherwise, just append the keyword.
9079 */
9080static void
9082 int indentBefore, int indentAfter, int indentPlus)
9083{
9084 StringInfo buf = context->buf;
9085
9086 if (PRETTY_INDENT(context))
9087 {
9088 int indentAmount;
9089
9090 context->indentLevel += indentBefore;
9091
9092 /* remove any trailing spaces currently in the buffer ... */
9094 /* ... then add a newline and some spaces */
9096
9097 if (context->indentLevel < PRETTYINDENT_LIMIT)
9098 indentAmount = Max(context->indentLevel, 0) + indentPlus;
9099 else
9100 {
9101 /*
9102 * If we're indented more than PRETTYINDENT_LIMIT characters, try
9103 * to conserve horizontal space by reducing the per-level
9104 * indentation. For best results the scale factor here should
9105 * divide all the indent amounts that get added to indentLevel
9106 * (PRETTYINDENT_STD, etc). It's important that the indentation
9107 * not grow unboundedly, else deeply-nested trees use O(N^2)
9108 * whitespace; so we also wrap modulo PRETTYINDENT_LIMIT.
9109 */
9110 indentAmount = PRETTYINDENT_LIMIT +
9111 (context->indentLevel - PRETTYINDENT_LIMIT) /
9112 (PRETTYINDENT_STD / 2);
9113 indentAmount %= PRETTYINDENT_LIMIT;
9114 /* scale/wrap logic affects indentLevel, but not indentPlus */
9115 indentAmount += indentPlus;
9116 }
9117 appendStringInfoSpaces(buf, indentAmount);
9118
9120
9121 context->indentLevel += indentAfter;
9122 if (context->indentLevel < 0)
9123 context->indentLevel = 0;
9124 }
9125 else
9127}
9128
9129/*
9130 * removeStringInfoSpaces - delete trailing spaces from a buffer.
9131 *
9132 * Possibly this should move to stringinfo.c at some point.
9133 */
9134static void
9136{
9137 while (str->len > 0 && str->data[str->len - 1] == ' ')
9138 str->data[--(str->len)] = '\0';
9139}
9140
9141
9142/*
9143 * get_rule_expr_paren - deparse expr using get_rule_expr,
9144 * embracing the string with parentheses if necessary for prettyPrint.
9145 *
9146 * Never embrace if prettyFlags=0, because it's done in the calling node.
9147 *
9148 * Any node that does *not* embrace its argument node by sql syntax (with
9149 * parentheses, non-operator keywords like CASE/WHEN/ON, or comma etc) should
9150 * use get_rule_expr_paren instead of get_rule_expr so parentheses can be
9151 * added.
9152 */
9153static void
9155 bool showimplicit, Node *parentNode)
9156{
9157 bool need_paren;
9158
9159 need_paren = PRETTY_PAREN(context) &&
9160 !isSimpleNode(node, parentNode, context->prettyFlags);
9161
9162 if (need_paren)
9163 appendStringInfoChar(context->buf, '(');
9164
9165 get_rule_expr(node, context, showimplicit);
9166
9167 if (need_paren)
9168 appendStringInfoChar(context->buf, ')');
9169}
9170
9171static void
9173 const char *on)
9174{
9175 /*
9176 * The order of array elements must correspond to the order of
9177 * JsonBehaviorType members.
9178 */
9179 const char *behavior_names[] =
9180 {
9181 " NULL",
9182 " ERROR",
9183 " EMPTY",
9184 " TRUE",
9185 " FALSE",
9186 " UNKNOWN",
9187 " EMPTY ARRAY",
9188 " EMPTY OBJECT",
9189 " DEFAULT "
9190 };
9191
9192 if ((int) behavior->btype < 0 || behavior->btype >= lengthof(behavior_names))
9193 elog(ERROR, "invalid json behavior type: %d", behavior->btype);
9194
9195 appendStringInfoString(context->buf, behavior_names[behavior->btype]);
9196
9197 if (behavior->btype == JSON_BEHAVIOR_DEFAULT)
9198 get_rule_expr(behavior->expr, context, false);
9199
9200 appendStringInfo(context->buf, " ON %s", on);
9201}
9202
9203/*
9204 * get_json_expr_options
9205 *
9206 * Parse back common options for JSON_QUERY, JSON_VALUE, JSON_EXISTS and
9207 * JSON_TABLE columns.
9208 */
9209static void
9211 JsonBehaviorType default_behavior)
9212{
9213 if (jsexpr->op == JSON_QUERY_OP)
9214 {
9215 if (jsexpr->wrapper == JSW_CONDITIONAL)
9216 appendStringInfoString(context->buf, " WITH CONDITIONAL WRAPPER");
9217 else if (jsexpr->wrapper == JSW_UNCONDITIONAL)
9218 appendStringInfoString(context->buf, " WITH UNCONDITIONAL WRAPPER");
9219 /* The default */
9220 else if (jsexpr->wrapper == JSW_NONE || jsexpr->wrapper == JSW_UNSPEC)
9221 appendStringInfoString(context->buf, " WITHOUT WRAPPER");
9222
9223 if (jsexpr->omit_quotes)
9224 appendStringInfoString(context->buf, " OMIT QUOTES");
9225 /* The default */
9226 else
9227 appendStringInfoString(context->buf, " KEEP QUOTES");
9228 }
9229
9230 if (jsexpr->on_empty && jsexpr->on_empty->btype != default_behavior)
9231 get_json_behavior(jsexpr->on_empty, context, "EMPTY");
9232
9233 if (jsexpr->on_error && jsexpr->on_error->btype != default_behavior)
9234 get_json_behavior(jsexpr->on_error, context, "ERROR");
9235}
9236
9237/* ----------
9238 * get_rule_expr - Parse back an expression
9239 *
9240 * Note: showimplicit determines whether we display any implicit cast that
9241 * is present at the top of the expression tree. It is a passed argument,
9242 * not a field of the context struct, because we change the value as we
9243 * recurse down into the expression. In general we suppress implicit casts
9244 * when the result type is known with certainty (eg, the arguments of an
9245 * OR must be boolean). We display implicit casts for arguments of functions
9246 * and operators, since this is needed to be certain that the same function
9247 * or operator will be chosen when the expression is re-parsed.
9248 * ----------
9249 */
9250static void
9252 bool showimplicit)
9253{
9254 StringInfo buf = context->buf;
9255
9256 if (node == NULL)
9257 return;
9258
9259 /* Guard against excessively long or deeply-nested queries */
9262
9263 /*
9264 * Each level of get_rule_expr must emit an indivisible term
9265 * (parenthesized if necessary) to ensure result is reparsed into the same
9266 * expression tree. The only exception is that when the input is a List,
9267 * we emit the component items comma-separated with no surrounding
9268 * decoration; this is convenient for most callers.
9269 */
9270 switch (nodeTag(node))
9271 {
9272 case T_Var:
9273 (void) get_variable((Var *) node, 0, false, context);
9274 break;
9275
9276 case T_Const:
9277 get_const_expr((Const *) node, context, 0);
9278 break;
9279
9280 case T_Param:
9281 get_parameter((Param *) node, context);
9282 break;
9283
9284 case T_Aggref:
9285 get_agg_expr((Aggref *) node, context, (Aggref *) node);
9286 break;
9287
9288 case T_GroupingFunc:
9289 {
9290 GroupingFunc *gexpr = (GroupingFunc *) node;
9291
9292 appendStringInfoString(buf, "GROUPING(");
9293 get_rule_expr((Node *) gexpr->args, context, true);
9295 }
9296 break;
9297
9298 case T_WindowFunc:
9299 get_windowfunc_expr((WindowFunc *) node, context);
9300 break;
9301
9302 case T_MergeSupportFunc:
9303 appendStringInfoString(buf, "MERGE_ACTION()");
9304 break;
9305
9306 case T_SubscriptingRef:
9307 {
9308 SubscriptingRef *sbsref = (SubscriptingRef *) node;
9309 bool need_parens;
9310
9311 /*
9312 * If the argument is a CaseTestExpr, we must be inside a
9313 * FieldStore, ie, we are assigning to an element of an array
9314 * within a composite column. Since we already punted on
9315 * displaying the FieldStore's target information, just punt
9316 * here too, and display only the assignment source
9317 * expression.
9318 */
9319 if (IsA(sbsref->refexpr, CaseTestExpr))
9320 {
9321 Assert(sbsref->refassgnexpr);
9322 get_rule_expr((Node *) sbsref->refassgnexpr,
9323 context, showimplicit);
9324 break;
9325 }
9326
9327 /*
9328 * Parenthesize the argument unless it's a simple Var or a
9329 * FieldSelect. (In particular, if it's another
9330 * SubscriptingRef, we *must* parenthesize to avoid
9331 * confusion.)
9332 */
9333 need_parens = !IsA(sbsref->refexpr, Var) &&
9334 !IsA(sbsref->refexpr, FieldSelect);
9335 if (need_parens)
9337 get_rule_expr((Node *) sbsref->refexpr, context, showimplicit);
9338 if (need_parens)
9340
9341 /*
9342 * If there's a refassgnexpr, we want to print the node in the
9343 * format "container[subscripts] := refassgnexpr". This is
9344 * not legal SQL, so decompilation of INSERT or UPDATE
9345 * statements should always use processIndirection as part of
9346 * the statement-level syntax. We should only see this when
9347 * EXPLAIN tries to print the targetlist of a plan resulting
9348 * from such a statement.
9349 */
9350 if (sbsref->refassgnexpr)
9351 {
9352 Node *refassgnexpr;
9353
9354 /*
9355 * Use processIndirection to print this node's subscripts
9356 * as well as any additional field selections or
9357 * subscripting in immediate descendants. It returns the
9358 * RHS expr that is actually being "assigned".
9359 */
9360 refassgnexpr = processIndirection(node, context);
9361 appendStringInfoString(buf, " := ");
9362 get_rule_expr(refassgnexpr, context, showimplicit);
9363 }
9364 else
9365 {
9366 /* Just an ordinary container fetch, so print subscripts */
9367 printSubscripts(sbsref, context);
9368 }
9369 }
9370 break;
9371
9372 case T_FuncExpr:
9373 get_func_expr((FuncExpr *) node, context, showimplicit);
9374 break;
9375
9376 case T_NamedArgExpr:
9377 {
9378 NamedArgExpr *na = (NamedArgExpr *) node;
9379
9380 appendStringInfo(buf, "%s => ", quote_identifier(na->name));
9381 get_rule_expr((Node *) na->arg, context, showimplicit);
9382 }
9383 break;
9384
9385 case T_OpExpr:
9386 get_oper_expr((OpExpr *) node, context);
9387 break;
9388
9389 case T_DistinctExpr:
9390 {
9391 DistinctExpr *expr = (DistinctExpr *) node;
9392 List *args = expr->args;
9393 Node *arg1 = (Node *) linitial(args);
9394 Node *arg2 = (Node *) lsecond(args);
9395
9396 if (!PRETTY_PAREN(context))
9398 get_rule_expr_paren(arg1, context, true, node);
9399 appendStringInfoString(buf, " IS DISTINCT FROM ");
9400 get_rule_expr_paren(arg2, context, true, node);
9401 if (!PRETTY_PAREN(context))
9403 }
9404 break;
9405
9406 case T_NullIfExpr:
9407 {
9408 NullIfExpr *nullifexpr = (NullIfExpr *) node;
9409
9410 appendStringInfoString(buf, "NULLIF(");
9411 get_rule_expr((Node *) nullifexpr->args, context, true);
9413 }
9414 break;
9415
9416 case T_ScalarArrayOpExpr:
9417 {
9418 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
9419 List *args = expr->args;
9420 Node *arg1 = (Node *) linitial(args);
9421 Node *arg2 = (Node *) lsecond(args);
9422
9423 if (!PRETTY_PAREN(context))
9425 get_rule_expr_paren(arg1, context, true, node);
9426 appendStringInfo(buf, " %s %s (",
9428 exprType(arg1),
9430 expr->useOr ? "ANY" : "ALL");
9431 get_rule_expr_paren(arg2, context, true, node);
9432
9433 /*
9434 * There's inherent ambiguity in "x op ANY/ALL (y)" when y is
9435 * a bare sub-SELECT. Since we're here, the sub-SELECT must
9436 * be meant as a scalar sub-SELECT yielding an array value to
9437 * be used in ScalarArrayOpExpr; but the grammar will
9438 * preferentially interpret such a construct as an ANY/ALL
9439 * SubLink. To prevent misparsing the output that way, insert
9440 * a dummy coercion (which will be stripped by parse analysis,
9441 * so no inefficiency is added in dump and reload). This is
9442 * indeed most likely what the user wrote to get the construct
9443 * accepted in the first place.
9444 */
9445 if (IsA(arg2, SubLink) &&
9446 ((SubLink *) arg2)->subLinkType == EXPR_SUBLINK)
9447 appendStringInfo(buf, "::%s",
9449 exprTypmod(arg2)));
9451 if (!PRETTY_PAREN(context))
9453 }
9454 break;
9455
9456 case T_BoolExpr:
9457 {
9458 BoolExpr *expr = (BoolExpr *) node;
9459 Node *first_arg = linitial(expr->args);
9460 ListCell *arg;
9461
9462 switch (expr->boolop)
9463 {
9464 case AND_EXPR:
9465 if (!PRETTY_PAREN(context))
9467 get_rule_expr_paren(first_arg, context,
9468 false, node);
9469 for_each_from(arg, expr->args, 1)
9470 {
9471 appendStringInfoString(buf, " AND ");
9472 get_rule_expr_paren((Node *) lfirst(arg), context,
9473 false, node);
9474 }
9475 if (!PRETTY_PAREN(context))
9477 break;
9478
9479 case OR_EXPR:
9480 if (!PRETTY_PAREN(context))
9482 get_rule_expr_paren(first_arg, context,
9483 false, node);
9484 for_each_from(arg, expr->args, 1)
9485 {
9486 appendStringInfoString(buf, " OR ");
9487 get_rule_expr_paren((Node *) lfirst(arg), context,
9488 false, node);
9489 }
9490 if (!PRETTY_PAREN(context))
9492 break;
9493
9494 case NOT_EXPR:
9495 if (!PRETTY_PAREN(context))
9497 appendStringInfoString(buf, "NOT ");
9498 get_rule_expr_paren(first_arg, context,
9499 false, node);
9500 if (!PRETTY_PAREN(context))
9502 break;
9503
9504 default:
9505 elog(ERROR, "unrecognized boolop: %d",
9506 (int) expr->boolop);
9507 }
9508 }
9509 break;
9510
9511 case T_SubLink:
9512 get_sublink_expr((SubLink *) node, context);
9513 break;
9514
9515 case T_SubPlan:
9516 {
9517 SubPlan *subplan = (SubPlan *) node;
9518
9519 /*
9520 * We cannot see an already-planned subplan in rule deparsing,
9521 * only while EXPLAINing a query plan. We don't try to
9522 * reconstruct the original SQL, just reference the subplan
9523 * that appears elsewhere in EXPLAIN's result. It does seem
9524 * useful to show the subLinkType and testexpr (if any), and
9525 * we also note whether the subplan will be hashed.
9526 */
9527 switch (subplan->subLinkType)
9528 {
9529 case EXISTS_SUBLINK:
9530 appendStringInfoString(buf, "EXISTS(");
9531 Assert(subplan->testexpr == NULL);
9532 break;
9533 case ALL_SUBLINK:
9534 appendStringInfoString(buf, "(ALL ");
9535 Assert(subplan->testexpr != NULL);
9536 break;
9537 case ANY_SUBLINK:
9538 appendStringInfoString(buf, "(ANY ");
9539 Assert(subplan->testexpr != NULL);
9540 break;
9541 case ROWCOMPARE_SUBLINK:
9542 /* Parenthesizing the testexpr seems sufficient */
9544 Assert(subplan->testexpr != NULL);
9545 break;
9546 case EXPR_SUBLINK:
9547 /* No need to decorate these subplan references */
9549 Assert(subplan->testexpr == NULL);
9550 break;
9551 case MULTIEXPR_SUBLINK:
9552 /* MULTIEXPR isn't executed in the normal way */
9553 appendStringInfoString(buf, "(rescan ");
9554 Assert(subplan->testexpr == NULL);
9555 break;
9556 case ARRAY_SUBLINK:
9557 appendStringInfoString(buf, "ARRAY(");
9558 Assert(subplan->testexpr == NULL);
9559 break;
9560 case CTE_SUBLINK:
9561 /* This case is unreachable within expressions */
9562 appendStringInfoString(buf, "CTE(");
9563 Assert(subplan->testexpr == NULL);
9564 break;
9565 }
9566
9567 if (subplan->testexpr != NULL)
9568 {
9569 deparse_namespace *dpns;
9570
9571 /*
9572 * Push SubPlan into ancestors list while deparsing
9573 * testexpr, so that we can handle PARAM_EXEC references
9574 * to the SubPlan's paramIds. (This makes it look like
9575 * the SubPlan is an "ancestor" of the current plan node,
9576 * which is a little weird, but it does no harm.) In this
9577 * path, we don't need to mention the SubPlan explicitly,
9578 * because the referencing Params will show its existence.
9579 */
9580 dpns = (deparse_namespace *) linitial(context->namespaces);
9581 dpns->ancestors = lcons(subplan, dpns->ancestors);
9582
9583 get_rule_expr(subplan->testexpr, context, showimplicit);
9585
9586 dpns->ancestors = list_delete_first(dpns->ancestors);
9587 }
9588 else
9589 {
9590 /* No referencing Params, so show the SubPlan's name */
9591 if (subplan->useHashTable)
9592 appendStringInfo(buf, "hashed %s)", subplan->plan_name);
9593 else
9594 appendStringInfo(buf, "%s)", subplan->plan_name);
9595 }
9596 }
9597 break;
9598
9599 case T_AlternativeSubPlan:
9600 {
9601 AlternativeSubPlan *asplan = (AlternativeSubPlan *) node;
9602 ListCell *lc;
9603
9604 /*
9605 * This case cannot be reached in normal usage, since no
9606 * AlternativeSubPlan can appear either in parsetrees or
9607 * finished plan trees. We keep it just in case somebody
9608 * wants to use this code to print planner data structures.
9609 */
9610 appendStringInfoString(buf, "(alternatives: ");
9611 foreach(lc, asplan->subplans)
9612 {
9613 SubPlan *splan = lfirst_node(SubPlan, lc);
9614
9615 if (splan->useHashTable)
9616 appendStringInfo(buf, "hashed %s", splan->plan_name);
9617 else
9619 if (lnext(asplan->subplans, lc))
9620 appendStringInfoString(buf, " or ");
9621 }
9623 }
9624 break;
9625
9626 case T_FieldSelect:
9627 {
9628 FieldSelect *fselect = (FieldSelect *) node;
9629 Node *arg = (Node *) fselect->arg;
9630 int fno = fselect->fieldnum;
9631 const char *fieldname;
9632 bool need_parens;
9633
9634 /*
9635 * Parenthesize the argument unless it's an SubscriptingRef or
9636 * another FieldSelect. Note in particular that it would be
9637 * WRONG to not parenthesize a Var argument; simplicity is not
9638 * the issue here, having the right number of names is.
9639 */
9640 need_parens = !IsA(arg, SubscriptingRef) &&
9641 !IsA(arg, FieldSelect);
9642 if (need_parens)
9644 get_rule_expr(arg, context, true);
9645 if (need_parens)
9647
9648 /*
9649 * Get and print the field name.
9650 */
9651 fieldname = get_name_for_var_field((Var *) arg, fno,
9652 0, context);
9653 appendStringInfo(buf, ".%s", quote_identifier(fieldname));
9654 }
9655 break;
9656
9657 case T_FieldStore:
9658 {
9659 FieldStore *fstore = (FieldStore *) node;
9660 bool need_parens;
9661
9662 /*
9663 * There is no good way to represent a FieldStore as real SQL,
9664 * so decompilation of INSERT or UPDATE statements should
9665 * always use processIndirection as part of the
9666 * statement-level syntax. We should only get here when
9667 * EXPLAIN tries to print the targetlist of a plan resulting
9668 * from such a statement. The plan case is even harder than
9669 * ordinary rules would be, because the planner tries to
9670 * collapse multiple assignments to the same field or subfield
9671 * into one FieldStore; so we can see a list of target fields
9672 * not just one, and the arguments could be FieldStores
9673 * themselves. We don't bother to try to print the target
9674 * field names; we just print the source arguments, with a
9675 * ROW() around them if there's more than one. This isn't
9676 * terribly complete, but it's probably good enough for
9677 * EXPLAIN's purposes; especially since anything more would be
9678 * either hopelessly confusing or an even poorer
9679 * representation of what the plan is actually doing.
9680 */
9681 need_parens = (list_length(fstore->newvals) != 1);
9682 if (need_parens)
9683 appendStringInfoString(buf, "ROW(");
9684 get_rule_expr((Node *) fstore->newvals, context, showimplicit);
9685 if (need_parens)
9687 }
9688 break;
9689
9690 case T_RelabelType:
9691 {
9692 RelabelType *relabel = (RelabelType *) node;
9693 Node *arg = (Node *) relabel->arg;
9694
9695 if (relabel->relabelformat == COERCE_IMPLICIT_CAST &&
9696 !showimplicit)
9697 {
9698 /* don't show the implicit cast */
9699 get_rule_expr_paren(arg, context, false, node);
9700 }
9701 else
9702 {
9703 get_coercion_expr(arg, context,
9704 relabel->resulttype,
9705 relabel->resulttypmod,
9706 node);
9707 }
9708 }
9709 break;
9710
9711 case T_CoerceViaIO:
9712 {
9713 CoerceViaIO *iocoerce = (CoerceViaIO *) node;
9714 Node *arg = (Node *) iocoerce->arg;
9715
9716 if (iocoerce->coerceformat == COERCE_IMPLICIT_CAST &&
9717 !showimplicit)
9718 {
9719 /* don't show the implicit cast */
9720 get_rule_expr_paren(arg, context, false, node);
9721 }
9722 else
9723 {
9724 get_coercion_expr(arg, context,
9725 iocoerce->resulttype,
9726 -1,
9727 node);
9728 }
9729 }
9730 break;
9731
9732 case T_ArrayCoerceExpr:
9733 {
9734 ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
9735 Node *arg = (Node *) acoerce->arg;
9736
9737 if (acoerce->coerceformat == COERCE_IMPLICIT_CAST &&
9738 !showimplicit)
9739 {
9740 /* don't show the implicit cast */
9741 get_rule_expr_paren(arg, context, false, node);
9742 }
9743 else
9744 {
9745 get_coercion_expr(arg, context,
9746 acoerce->resulttype,
9747 acoerce->resulttypmod,
9748 node);
9749 }
9750 }
9751 break;
9752
9753 case T_ConvertRowtypeExpr:
9754 {
9756 Node *arg = (Node *) convert->arg;
9757
9758 if (convert->convertformat == COERCE_IMPLICIT_CAST &&
9759 !showimplicit)
9760 {
9761 /* don't show the implicit cast */
9762 get_rule_expr_paren(arg, context, false, node);
9763 }
9764 else
9765 {
9766 get_coercion_expr(arg, context,
9767 convert->resulttype, -1,
9768 node);
9769 }
9770 }
9771 break;
9772
9773 case T_CollateExpr:
9774 {
9775 CollateExpr *collate = (CollateExpr *) node;
9776 Node *arg = (Node *) collate->arg;
9777
9778 if (!PRETTY_PAREN(context))
9780 get_rule_expr_paren(arg, context, showimplicit, node);
9781 appendStringInfo(buf, " COLLATE %s",
9783 if (!PRETTY_PAREN(context))
9785 }
9786 break;
9787
9788 case T_CaseExpr:
9789 {
9790 CaseExpr *caseexpr = (CaseExpr *) node;
9791 ListCell *temp;
9792
9793 appendContextKeyword(context, "CASE",
9794 0, PRETTYINDENT_VAR, 0);
9795 if (caseexpr->arg)
9796 {
9798 get_rule_expr((Node *) caseexpr->arg, context, true);
9799 }
9800 foreach(temp, caseexpr->args)
9801 {
9802 CaseWhen *when = (CaseWhen *) lfirst(temp);
9803 Node *w = (Node *) when->expr;
9804
9805 if (caseexpr->arg)
9806 {
9807 /*
9808 * The parser should have produced WHEN clauses of the
9809 * form "CaseTestExpr = RHS", possibly with an
9810 * implicit coercion inserted above the CaseTestExpr.
9811 * For accurate decompilation of rules it's essential
9812 * that we show just the RHS. However in an
9813 * expression that's been through the optimizer, the
9814 * WHEN clause could be almost anything (since the
9815 * equality operator could have been expanded into an
9816 * inline function). If we don't recognize the form
9817 * of the WHEN clause, just punt and display it as-is.
9818 */
9819 if (IsA(w, OpExpr))
9820 {
9821 List *args = ((OpExpr *) w)->args;
9822
9823 if (list_length(args) == 2 &&
9825 CaseTestExpr))
9826 w = (Node *) lsecond(args);
9827 }
9828 }
9829
9830 if (!PRETTY_INDENT(context))
9832 appendContextKeyword(context, "WHEN ",
9833 0, 0, 0);
9834 get_rule_expr(w, context, false);
9835 appendStringInfoString(buf, " THEN ");
9836 get_rule_expr((Node *) when->result, context, true);
9837 }
9838 if (!PRETTY_INDENT(context))
9840 appendContextKeyword(context, "ELSE ",
9841 0, 0, 0);
9842 get_rule_expr((Node *) caseexpr->defresult, context, true);
9843 if (!PRETTY_INDENT(context))
9845 appendContextKeyword(context, "END",
9846 -PRETTYINDENT_VAR, 0, 0);
9847 }
9848 break;
9849
9850 case T_CaseTestExpr:
9851 {
9852 /*
9853 * Normally we should never get here, since for expressions
9854 * that can contain this node type we attempt to avoid
9855 * recursing to it. But in an optimized expression we might
9856 * be unable to avoid that (see comments for CaseExpr). If we
9857 * do see one, print it as CASE_TEST_EXPR.
9858 */
9859 appendStringInfoString(buf, "CASE_TEST_EXPR");
9860 }
9861 break;
9862
9863 case T_ArrayExpr:
9864 {
9865 ArrayExpr *arrayexpr = (ArrayExpr *) node;
9866
9867 appendStringInfoString(buf, "ARRAY[");
9868 get_rule_expr((Node *) arrayexpr->elements, context, true);
9870
9871 /*
9872 * If the array isn't empty, we assume its elements are
9873 * coerced to the desired type. If it's empty, though, we
9874 * need an explicit coercion to the array type.
9875 */
9876 if (arrayexpr->elements == NIL)
9877 appendStringInfo(buf, "::%s",
9878 format_type_with_typemod(arrayexpr->array_typeid, -1));
9879 }
9880 break;
9881
9882 case T_RowExpr:
9883 {
9884 RowExpr *rowexpr = (RowExpr *) node;
9885 TupleDesc tupdesc = NULL;
9886 ListCell *arg;
9887 int i;
9888 char *sep;
9889
9890 /*
9891 * If it's a named type and not RECORD, we may have to skip
9892 * dropped columns and/or claim there are NULLs for added
9893 * columns.
9894 */
9895 if (rowexpr->row_typeid != RECORDOID)
9896 {
9897 tupdesc = lookup_rowtype_tupdesc(rowexpr->row_typeid, -1);
9898 Assert(list_length(rowexpr->args) <= tupdesc->natts);
9899 }
9900
9901 /*
9902 * SQL99 allows "ROW" to be omitted when there is more than
9903 * one column, but for simplicity we always print it.
9904 */
9905 appendStringInfoString(buf, "ROW(");
9906 sep = "";
9907 i = 0;
9908 foreach(arg, rowexpr->args)
9909 {
9910 Node *e = (Node *) lfirst(arg);
9911
9912 if (tupdesc == NULL ||
9913 !TupleDescAttr(tupdesc, i)->attisdropped)
9914 {
9916 /* Whole-row Vars need special treatment here */
9917 get_rule_expr_toplevel(e, context, true);
9918 sep = ", ";
9919 }
9920 i++;
9921 }
9922 if (tupdesc != NULL)
9923 {
9924 while (i < tupdesc->natts)
9925 {
9926 if (!TupleDescAttr(tupdesc, i)->attisdropped)
9927 {
9929 appendStringInfoString(buf, "NULL");
9930 sep = ", ";
9931 }
9932 i++;
9933 }
9934
9935 ReleaseTupleDesc(tupdesc);
9936 }
9938 if (rowexpr->row_format == COERCE_EXPLICIT_CAST)
9939 appendStringInfo(buf, "::%s",
9940 format_type_with_typemod(rowexpr->row_typeid, -1));
9941 }
9942 break;
9943
9944 case T_RowCompareExpr:
9945 {
9946 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
9947
9948 /*
9949 * SQL99 allows "ROW" to be omitted when there is more than
9950 * one column, but for simplicity we always print it. Within
9951 * a ROW expression, whole-row Vars need special treatment, so
9952 * use get_rule_list_toplevel.
9953 */
9954 appendStringInfoString(buf, "(ROW(");
9955 get_rule_list_toplevel(rcexpr->largs, context, true);
9956
9957 /*
9958 * We assume that the name of the first-column operator will
9959 * do for all the rest too. This is definitely open to
9960 * failure, eg if some but not all operators were renamed
9961 * since the construct was parsed, but there seems no way to
9962 * be perfect.
9963 */
9964 appendStringInfo(buf, ") %s ROW(",
9965 generate_operator_name(linitial_oid(rcexpr->opnos),
9966 exprType(linitial(rcexpr->largs)),
9967 exprType(linitial(rcexpr->rargs))));
9968 get_rule_list_toplevel(rcexpr->rargs, context, true);
9970 }
9971 break;
9972
9973 case T_CoalesceExpr:
9974 {
9975 CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
9976
9977 appendStringInfoString(buf, "COALESCE(");
9978 get_rule_expr((Node *) coalesceexpr->args, context, true);
9980 }
9981 break;
9982
9983 case T_MinMaxExpr:
9984 {
9985 MinMaxExpr *minmaxexpr = (MinMaxExpr *) node;
9986
9987 switch (minmaxexpr->op)
9988 {
9989 case IS_GREATEST:
9990 appendStringInfoString(buf, "GREATEST(");
9991 break;
9992 case IS_LEAST:
9993 appendStringInfoString(buf, "LEAST(");
9994 break;
9995 }
9996 get_rule_expr((Node *) minmaxexpr->args, context, true);
9998 }
9999 break;
10000
10001 case T_SQLValueFunction:
10002 {
10003 SQLValueFunction *svf = (SQLValueFunction *) node;
10004
10005 /*
10006 * Note: this code knows that typmod for time, timestamp, and
10007 * timestamptz just prints as integer.
10008 */
10009 switch (svf->op)
10010 {
10011 case SVFOP_CURRENT_DATE:
10012 appendStringInfoString(buf, "CURRENT_DATE");
10013 break;
10014 case SVFOP_CURRENT_TIME:
10015 appendStringInfoString(buf, "CURRENT_TIME");
10016 break;
10018 appendStringInfo(buf, "CURRENT_TIME(%d)", svf->typmod);
10019 break;
10021 appendStringInfoString(buf, "CURRENT_TIMESTAMP");
10022 break;
10024 appendStringInfo(buf, "CURRENT_TIMESTAMP(%d)",
10025 svf->typmod);
10026 break;
10027 case SVFOP_LOCALTIME:
10028 appendStringInfoString(buf, "LOCALTIME");
10029 break;
10030 case SVFOP_LOCALTIME_N:
10031 appendStringInfo(buf, "LOCALTIME(%d)", svf->typmod);
10032 break;
10034 appendStringInfoString(buf, "LOCALTIMESTAMP");
10035 break;
10037 appendStringInfo(buf, "LOCALTIMESTAMP(%d)",
10038 svf->typmod);
10039 break;
10040 case SVFOP_CURRENT_ROLE:
10041 appendStringInfoString(buf, "CURRENT_ROLE");
10042 break;
10043 case SVFOP_CURRENT_USER:
10044 appendStringInfoString(buf, "CURRENT_USER");
10045 break;
10046 case SVFOP_USER:
10047 appendStringInfoString(buf, "USER");
10048 break;
10049 case SVFOP_SESSION_USER:
10050 appendStringInfoString(buf, "SESSION_USER");
10051 break;
10053 appendStringInfoString(buf, "CURRENT_CATALOG");
10054 break;
10056 appendStringInfoString(buf, "CURRENT_SCHEMA");
10057 break;
10058 }
10059 }
10060 break;
10061
10062 case T_XmlExpr:
10063 {
10064 XmlExpr *xexpr = (XmlExpr *) node;
10065 bool needcomma = false;
10066 ListCell *arg;
10067 ListCell *narg;
10068 Const *con;
10069
10070 switch (xexpr->op)
10071 {
10072 case IS_XMLCONCAT:
10073 appendStringInfoString(buf, "XMLCONCAT(");
10074 break;
10075 case IS_XMLELEMENT:
10076 appendStringInfoString(buf, "XMLELEMENT(");
10077 break;
10078 case IS_XMLFOREST:
10079 appendStringInfoString(buf, "XMLFOREST(");
10080 break;
10081 case IS_XMLPARSE:
10082 appendStringInfoString(buf, "XMLPARSE(");
10083 break;
10084 case IS_XMLPI:
10085 appendStringInfoString(buf, "XMLPI(");
10086 break;
10087 case IS_XMLROOT:
10088 appendStringInfoString(buf, "XMLROOT(");
10089 break;
10090 case IS_XMLSERIALIZE:
10091 appendStringInfoString(buf, "XMLSERIALIZE(");
10092 break;
10093 case IS_DOCUMENT:
10094 break;
10095 }
10096 if (xexpr->op == IS_XMLPARSE || xexpr->op == IS_XMLSERIALIZE)
10097 {
10098 if (xexpr->xmloption == XMLOPTION_DOCUMENT)
10099 appendStringInfoString(buf, "DOCUMENT ");
10100 else
10101 appendStringInfoString(buf, "CONTENT ");
10102 }
10103 if (xexpr->name)
10104 {
10105 appendStringInfo(buf, "NAME %s",
10107 needcomma = true;
10108 }
10109 if (xexpr->named_args)
10110 {
10111 if (xexpr->op != IS_XMLFOREST)
10112 {
10113 if (needcomma)
10115 appendStringInfoString(buf, "XMLATTRIBUTES(");
10116 needcomma = false;
10117 }
10118 forboth(arg, xexpr->named_args, narg, xexpr->arg_names)
10119 {
10120 Node *e = (Node *) lfirst(arg);
10121 char *argname = strVal(lfirst(narg));
10122
10123 if (needcomma)
10125 get_rule_expr((Node *) e, context, true);
10126 appendStringInfo(buf, " AS %s",
10128 needcomma = true;
10129 }
10130 if (xexpr->op != IS_XMLFOREST)
10132 }
10133 if (xexpr->args)
10134 {
10135 if (needcomma)
10137 switch (xexpr->op)
10138 {
10139 case IS_XMLCONCAT:
10140 case IS_XMLELEMENT:
10141 case IS_XMLFOREST:
10142 case IS_XMLPI:
10143 case IS_XMLSERIALIZE:
10144 /* no extra decoration needed */
10145 get_rule_expr((Node *) xexpr->args, context, true);
10146 break;
10147 case IS_XMLPARSE:
10148 Assert(list_length(xexpr->args) == 2);
10149
10150 get_rule_expr((Node *) linitial(xexpr->args),
10151 context, true);
10152
10153 con = lsecond_node(Const, xexpr->args);
10154 Assert(!con->constisnull);
10155 if (DatumGetBool(con->constvalue))
10157 " PRESERVE WHITESPACE");
10158 else
10160 " STRIP WHITESPACE");
10161 break;
10162 case IS_XMLROOT:
10163 Assert(list_length(xexpr->args) == 3);
10164
10165 get_rule_expr((Node *) linitial(xexpr->args),
10166 context, true);
10167
10168 appendStringInfoString(buf, ", VERSION ");
10169 con = (Const *) lsecond(xexpr->args);
10170 if (IsA(con, Const) &&
10171 con->constisnull)
10172 appendStringInfoString(buf, "NO VALUE");
10173 else
10174 get_rule_expr((Node *) con, context, false);
10175
10176 con = lthird_node(Const, xexpr->args);
10177 if (con->constisnull)
10178 /* suppress STANDALONE NO VALUE */ ;
10179 else
10180 {
10181 switch (DatumGetInt32(con->constvalue))
10182 {
10183 case XML_STANDALONE_YES:
10185 ", STANDALONE YES");
10186 break;
10187 case XML_STANDALONE_NO:
10189 ", STANDALONE NO");
10190 break;
10193 ", STANDALONE NO VALUE");
10194 break;
10195 default:
10196 break;
10197 }
10198 }
10199 break;
10200 case IS_DOCUMENT:
10201 get_rule_expr_paren((Node *) xexpr->args, context, false, node);
10202 break;
10203 }
10204 }
10205 if (xexpr->op == IS_XMLSERIALIZE)
10206 {
10207 appendStringInfo(buf, " AS %s",
10208 format_type_with_typemod(xexpr->type,
10209 xexpr->typmod));
10210 if (xexpr->indent)
10211 appendStringInfoString(buf, " INDENT");
10212 else
10213 appendStringInfoString(buf, " NO INDENT");
10214 }
10215
10216 if (xexpr->op == IS_DOCUMENT)
10217 appendStringInfoString(buf, " IS DOCUMENT");
10218 else
10220 }
10221 break;
10222
10223 case T_NullTest:
10224 {
10225 NullTest *ntest = (NullTest *) node;
10226
10227 if (!PRETTY_PAREN(context))
10229 get_rule_expr_paren((Node *) ntest->arg, context, true, node);
10230
10231 /*
10232 * For scalar inputs, we prefer to print as IS [NOT] NULL,
10233 * which is shorter and traditional. If it's a rowtype input
10234 * but we're applying a scalar test, must print IS [NOT]
10235 * DISTINCT FROM NULL to be semantically correct.
10236 */
10237 if (ntest->argisrow ||
10238 !type_is_rowtype(exprType((Node *) ntest->arg)))
10239 {
10240 switch (ntest->nulltesttype)
10241 {
10242 case IS_NULL:
10243 appendStringInfoString(buf, " IS NULL");
10244 break;
10245 case IS_NOT_NULL:
10246 appendStringInfoString(buf, " IS NOT NULL");
10247 break;
10248 default:
10249 elog(ERROR, "unrecognized nulltesttype: %d",
10250 (int) ntest->nulltesttype);
10251 }
10252 }
10253 else
10254 {
10255 switch (ntest->nulltesttype)
10256 {
10257 case IS_NULL:
10258 appendStringInfoString(buf, " IS NOT DISTINCT FROM NULL");
10259 break;
10260 case IS_NOT_NULL:
10261 appendStringInfoString(buf, " IS DISTINCT FROM NULL");
10262 break;
10263 default:
10264 elog(ERROR, "unrecognized nulltesttype: %d",
10265 (int) ntest->nulltesttype);
10266 }
10267 }
10268 if (!PRETTY_PAREN(context))
10270 }
10271 break;
10272
10273 case T_BooleanTest:
10274 {
10275 BooleanTest *btest = (BooleanTest *) node;
10276
10277 if (!PRETTY_PAREN(context))
10279 get_rule_expr_paren((Node *) btest->arg, context, false, node);
10280 switch (btest->booltesttype)
10281 {
10282 case IS_TRUE:
10283 appendStringInfoString(buf, " IS TRUE");
10284 break;
10285 case IS_NOT_TRUE:
10286 appendStringInfoString(buf, " IS NOT TRUE");
10287 break;
10288 case IS_FALSE:
10289 appendStringInfoString(buf, " IS FALSE");
10290 break;
10291 case IS_NOT_FALSE:
10292 appendStringInfoString(buf, " IS NOT FALSE");
10293 break;
10294 case IS_UNKNOWN:
10295 appendStringInfoString(buf, " IS UNKNOWN");
10296 break;
10297 case IS_NOT_UNKNOWN:
10298 appendStringInfoString(buf, " IS NOT UNKNOWN");
10299 break;
10300 default:
10301 elog(ERROR, "unrecognized booltesttype: %d",
10302 (int) btest->booltesttype);
10303 }
10304 if (!PRETTY_PAREN(context))
10306 }
10307 break;
10308
10309 case T_CoerceToDomain:
10310 {
10311 CoerceToDomain *ctest = (CoerceToDomain *) node;
10312 Node *arg = (Node *) ctest->arg;
10313
10314 if (ctest->coercionformat == COERCE_IMPLICIT_CAST &&
10315 !showimplicit)
10316 {
10317 /* don't show the implicit cast */
10318 get_rule_expr(arg, context, false);
10319 }
10320 else
10321 {
10322 get_coercion_expr(arg, context,
10323 ctest->resulttype,
10324 ctest->resulttypmod,
10325 node);
10326 }
10327 }
10328 break;
10329
10330 case T_CoerceToDomainValue:
10331 appendStringInfoString(buf, "VALUE");
10332 break;
10333
10334 case T_SetToDefault:
10335 appendStringInfoString(buf, "DEFAULT");
10336 break;
10337
10338 case T_CurrentOfExpr:
10339 {
10340 CurrentOfExpr *cexpr = (CurrentOfExpr *) node;
10341
10342 if (cexpr->cursor_name)
10343 appendStringInfo(buf, "CURRENT OF %s",
10345 else
10346 appendStringInfo(buf, "CURRENT OF $%d",
10347 cexpr->cursor_param);
10348 }
10349 break;
10350
10351 case T_NextValueExpr:
10352 {
10353 NextValueExpr *nvexpr = (NextValueExpr *) node;
10354
10355 /*
10356 * This isn't exactly nextval(), but that seems close enough
10357 * for EXPLAIN's purposes.
10358 */
10359 appendStringInfoString(buf, "nextval(");
10362 NIL));
10364 }
10365 break;
10366
10367 case T_InferenceElem:
10368 {
10369 InferenceElem *iexpr = (InferenceElem *) node;
10370 bool save_varprefix;
10371 bool need_parens;
10372
10373 /*
10374 * InferenceElem can only refer to target relation, so a
10375 * prefix is not useful, and indeed would cause parse errors.
10376 */
10377 save_varprefix = context->varprefix;
10378 context->varprefix = false;
10379
10380 /*
10381 * Parenthesize the element unless it's a simple Var or a bare
10382 * function call. Follows pg_get_indexdef_worker().
10383 */
10384 need_parens = !IsA(iexpr->expr, Var);
10385 if (IsA(iexpr->expr, FuncExpr) &&
10386 ((FuncExpr *) iexpr->expr)->funcformat ==
10388 need_parens = false;
10389
10390 if (need_parens)
10392 get_rule_expr((Node *) iexpr->expr,
10393 context, false);
10394 if (need_parens)
10396
10397 context->varprefix = save_varprefix;
10398
10399 if (iexpr->infercollid)
10400 appendStringInfo(buf, " COLLATE %s",
10402
10403 /* Add the operator class name, if not default */
10404 if (iexpr->inferopclass)
10405 {
10406 Oid inferopclass = iexpr->inferopclass;
10407 Oid inferopcinputtype = get_opclass_input_type(iexpr->inferopclass);
10408
10409 get_opclass_name(inferopclass, inferopcinputtype, buf);
10410 }
10411 }
10412 break;
10413
10414 case T_ReturningExpr:
10415 {
10416 ReturningExpr *retExpr = (ReturningExpr *) node;
10417
10418 /*
10419 * We cannot see a ReturningExpr in rule deparsing, only while
10420 * EXPLAINing a query plan (ReturningExpr nodes are only ever
10421 * adding during query rewriting). Just display the expression
10422 * returned (an expanded view column).
10423 */
10424 get_rule_expr((Node *) retExpr->retexpr, context, showimplicit);
10425 }
10426 break;
10427
10428 case T_PartitionBoundSpec:
10429 {
10430 PartitionBoundSpec *spec = (PartitionBoundSpec *) node;
10431 ListCell *cell;
10432 char *sep;
10433
10434 if (spec->is_default)
10435 {
10436 appendStringInfoString(buf, "DEFAULT");
10437 break;
10438 }
10439
10440 switch (spec->strategy)
10441 {
10443 Assert(spec->modulus > 0 && spec->remainder >= 0);
10444 Assert(spec->modulus > spec->remainder);
10445
10446 appendStringInfoString(buf, "FOR VALUES");
10447 appendStringInfo(buf, " WITH (modulus %d, remainder %d)",
10448 spec->modulus, spec->remainder);
10449 break;
10450
10452 Assert(spec->listdatums != NIL);
10453
10454 appendStringInfoString(buf, "FOR VALUES IN (");
10455 sep = "";
10456 foreach(cell, spec->listdatums)
10457 {
10458 Const *val = lfirst_node(Const, cell);
10459
10461 get_const_expr(val, context, -1);
10462 sep = ", ";
10463 }
10464
10466 break;
10467
10469 Assert(spec->lowerdatums != NIL &&
10470 spec->upperdatums != NIL &&
10471 list_length(spec->lowerdatums) ==
10472 list_length(spec->upperdatums));
10473
10474 appendStringInfo(buf, "FOR VALUES FROM %s TO %s",
10477 break;
10478
10479 default:
10480 elog(ERROR, "unrecognized partition strategy: %d",
10481 (int) spec->strategy);
10482 break;
10483 }
10484 }
10485 break;
10486
10487 case T_JsonValueExpr:
10488 {
10489 JsonValueExpr *jve = (JsonValueExpr *) node;
10490
10491 get_rule_expr((Node *) jve->raw_expr, context, false);
10492 get_json_format(jve->format, context->buf);
10493 }
10494 break;
10495
10496 case T_JsonConstructorExpr:
10497 get_json_constructor((JsonConstructorExpr *) node, context, false);
10498 break;
10499
10500 case T_JsonIsPredicate:
10501 {
10502 JsonIsPredicate *pred = (JsonIsPredicate *) node;
10503
10504 if (!PRETTY_PAREN(context))
10505 appendStringInfoChar(context->buf, '(');
10506
10507 get_rule_expr_paren(pred->expr, context, true, node);
10508
10509 appendStringInfoString(context->buf, " IS JSON");
10510
10511 /* TODO: handle FORMAT clause */
10512
10513 switch (pred->item_type)
10514 {
10515 case JS_TYPE_SCALAR:
10516 appendStringInfoString(context->buf, " SCALAR");
10517 break;
10518 case JS_TYPE_ARRAY:
10519 appendStringInfoString(context->buf, " ARRAY");
10520 break;
10521 case JS_TYPE_OBJECT:
10522 appendStringInfoString(context->buf, " OBJECT");
10523 break;
10524 default:
10525 break;
10526 }
10527
10528 if (pred->unique_keys)
10529 appendStringInfoString(context->buf, " WITH UNIQUE KEYS");
10530
10531 if (!PRETTY_PAREN(context))
10532 appendStringInfoChar(context->buf, ')');
10533 }
10534 break;
10535
10536 case T_JsonExpr:
10537 {
10538 JsonExpr *jexpr = (JsonExpr *) node;
10539
10540 switch (jexpr->op)
10541 {
10542 case JSON_EXISTS_OP:
10543 appendStringInfoString(buf, "JSON_EXISTS(");
10544 break;
10545 case JSON_QUERY_OP:
10546 appendStringInfoString(buf, "JSON_QUERY(");
10547 break;
10548 case JSON_VALUE_OP:
10549 appendStringInfoString(buf, "JSON_VALUE(");
10550 break;
10551 default:
10552 elog(ERROR, "unrecognized JsonExpr op: %d",
10553 (int) jexpr->op);
10554 }
10555
10556 get_rule_expr(jexpr->formatted_expr, context, showimplicit);
10557
10559
10560 get_json_path_spec(jexpr->path_spec, context, showimplicit);
10561
10562 if (jexpr->passing_values)
10563 {
10564 ListCell *lc1,
10565 *lc2;
10566 bool needcomma = false;
10567
10568 appendStringInfoString(buf, " PASSING ");
10569
10570 forboth(lc1, jexpr->passing_names,
10571 lc2, jexpr->passing_values)
10572 {
10573 if (needcomma)
10575 needcomma = true;
10576
10577 get_rule_expr((Node *) lfirst(lc2), context, showimplicit);
10578 appendStringInfo(buf, " AS %s",
10579 quote_identifier(lfirst_node(String, lc1)->sval));
10580 }
10581 }
10582
10583 if (jexpr->op != JSON_EXISTS_OP ||
10584 jexpr->returning->typid != BOOLOID)
10585 get_json_returning(jexpr->returning, context->buf,
10586 jexpr->op == JSON_QUERY_OP);
10587
10588 get_json_expr_options(jexpr, context,
10589 jexpr->op != JSON_EXISTS_OP ?
10592
10594 }
10595 break;
10596
10597 case T_List:
10598 {
10599 char *sep;
10600 ListCell *l;
10601
10602 sep = "";
10603 foreach(l, (List *) node)
10604 {
10606 get_rule_expr((Node *) lfirst(l), context, showimplicit);
10607 sep = ", ";
10608 }
10609 }
10610 break;
10611
10612 case T_TableFunc:
10613 get_tablefunc((TableFunc *) node, context, showimplicit);
10614 break;
10615
10616 default:
10617 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(node));
10618 break;
10619 }
10620}
10621
10622/*
10623 * get_rule_expr_toplevel - Parse back a toplevel expression
10624 *
10625 * Same as get_rule_expr(), except that if the expr is just a Var, we pass
10626 * istoplevel = true not false to get_variable(). This causes whole-row Vars
10627 * to get printed with decoration that will prevent expansion of "*".
10628 * We need to use this in contexts such as ROW() and VALUES(), where the
10629 * parser would expand "foo.*" appearing at top level. (In principle we'd
10630 * use this in get_target_list() too, but that has additional worries about
10631 * whether to print AS, so it needs to invoke get_variable() directly anyway.)
10632 */
10633static void
10635 bool showimplicit)
10636{
10637 if (node && IsA(node, Var))
10638 (void) get_variable((Var *) node, 0, true, context);
10639 else
10640 get_rule_expr(node, context, showimplicit);
10641}
10642
10643/*
10644 * get_rule_list_toplevel - Parse back a list of toplevel expressions
10645 *
10646 * Apply get_rule_expr_toplevel() to each element of a List.
10647 *
10648 * This adds commas between the expressions, but caller is responsible
10649 * for printing surrounding decoration.
10650 */
10651static void
10653 bool showimplicit)
10654{
10655 const char *sep;
10656 ListCell *lc;
10657
10658 sep = "";
10659 foreach(lc, lst)
10660 {
10661 Node *e = (Node *) lfirst(lc);
10662
10663 appendStringInfoString(context->buf, sep);
10664 get_rule_expr_toplevel(e, context, showimplicit);
10665 sep = ", ";
10666 }
10667}
10668
10669/*
10670 * get_rule_expr_funccall - Parse back a function-call expression
10671 *
10672 * Same as get_rule_expr(), except that we guarantee that the output will
10673 * look like a function call, or like one of the things the grammar treats as
10674 * equivalent to a function call (see the func_expr_windowless production).
10675 * This is needed in places where the grammar uses func_expr_windowless and
10676 * you can't substitute a parenthesized a_expr. If what we have isn't going
10677 * to look like a function call, wrap it in a dummy CAST() expression, which
10678 * will satisfy the grammar --- and, indeed, is likely what the user wrote to
10679 * produce such a thing.
10680 */
10681static void
10683 bool showimplicit)
10684{
10685 if (looks_like_function(node))
10686 get_rule_expr(node, context, showimplicit);
10687 else
10688 {
10689 StringInfo buf = context->buf;
10690
10691 appendStringInfoString(buf, "CAST(");
10692 /* no point in showing any top-level implicit cast */
10693 get_rule_expr(node, context, false);
10694 appendStringInfo(buf, " AS %s)",
10696 exprTypmod(node)));
10697 }
10698}
10699
10700/*
10701 * Helper function to identify node types that satisfy func_expr_windowless.
10702 * If in doubt, "false" is always a safe answer.
10703 */
10704static bool
10706{
10707 if (node == NULL)
10708 return false; /* probably shouldn't happen */
10709 switch (nodeTag(node))
10710 {
10711 case T_FuncExpr:
10712 /* OK, unless it's going to deparse as a cast */
10713 return (((FuncExpr *) node)->funcformat == COERCE_EXPLICIT_CALL ||
10714 ((FuncExpr *) node)->funcformat == COERCE_SQL_SYNTAX);
10715 case T_NullIfExpr:
10716 case T_CoalesceExpr:
10717 case T_MinMaxExpr:
10718 case T_SQLValueFunction:
10719 case T_XmlExpr:
10720 case T_JsonExpr:
10721 /* these are all accepted by func_expr_common_subexpr */
10722 return true;
10723 default:
10724 break;
10725 }
10726 return false;
10727}
10728
10729
10730/*
10731 * get_oper_expr - Parse back an OpExpr node
10732 */
10733static void
10735{
10736 StringInfo buf = context->buf;
10737 Oid opno = expr->opno;
10738 List *args = expr->args;
10739
10740 if (!PRETTY_PAREN(context))
10742 if (list_length(args) == 2)
10743 {
10744 /* binary operator */
10745 Node *arg1 = (Node *) linitial(args);
10746 Node *arg2 = (Node *) lsecond(args);
10747
10748 get_rule_expr_paren(arg1, context, true, (Node *) expr);
10749 appendStringInfo(buf, " %s ",
10751 exprType(arg1),
10752 exprType(arg2)));
10753 get_rule_expr_paren(arg2, context, true, (Node *) expr);
10754 }
10755 else
10756 {
10757 /* prefix operator */
10758 Node *arg = (Node *) linitial(args);
10759
10760 appendStringInfo(buf, "%s ",
10762 InvalidOid,
10763 exprType(arg)));
10764 get_rule_expr_paren(arg, context, true, (Node *) expr);
10765 }
10766 if (!PRETTY_PAREN(context))
10768}
10769
10770/*
10771 * get_func_expr - Parse back a FuncExpr node
10772 */
10773static void
10775 bool showimplicit)
10776{
10777 StringInfo buf = context->buf;
10778 Oid funcoid = expr->funcid;
10779 Oid argtypes[FUNC_MAX_ARGS];
10780 int nargs;
10781 List *argnames;
10782 bool use_variadic;
10783 ListCell *l;
10784
10785 /*
10786 * If the function call came from an implicit coercion, then just show the
10787 * first argument --- unless caller wants to see implicit coercions.
10788 */
10789 if (expr->funcformat == COERCE_IMPLICIT_CAST && !showimplicit)
10790 {
10791 get_rule_expr_paren((Node *) linitial(expr->args), context,
10792 false, (Node *) expr);
10793 return;
10794 }
10795
10796 /*
10797 * If the function call came from a cast, then show the first argument
10798 * plus an explicit cast operation.
10799 */
10800 if (expr->funcformat == COERCE_EXPLICIT_CAST ||
10801 expr->funcformat == COERCE_IMPLICIT_CAST)
10802 {
10803 Node *arg = linitial(expr->args);
10804 Oid rettype = expr->funcresulttype;
10805 int32 coercedTypmod;
10806
10807 /* Get the typmod if this is a length-coercion function */
10808 (void) exprIsLengthCoercion((Node *) expr, &coercedTypmod);
10809
10810 get_coercion_expr(arg, context,
10811 rettype, coercedTypmod,
10812 (Node *) expr);
10813
10814 return;
10815 }
10816
10817 /*
10818 * If the function was called using one of the SQL spec's random special
10819 * syntaxes, try to reproduce that. If we don't recognize the function,
10820 * fall through.
10821 */
10822 if (expr->funcformat == COERCE_SQL_SYNTAX)
10823 {
10824 if (get_func_sql_syntax(expr, context))
10825 return;
10826 }
10827
10828 /*
10829 * Normal function: display as proname(args). First we need to extract
10830 * the argument datatypes.
10831 */
10832 if (list_length(expr->args) > FUNC_MAX_ARGS)
10833 ereport(ERROR,
10834 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
10835 errmsg("too many arguments")));
10836 nargs = 0;
10837 argnames = NIL;
10838 foreach(l, expr->args)
10839 {
10840 Node *arg = (Node *) lfirst(l);
10841
10842 if (IsA(arg, NamedArgExpr))
10843 argnames = lappend(argnames, ((NamedArgExpr *) arg)->name);
10844 argtypes[nargs] = exprType(arg);
10845 nargs++;
10846 }
10847
10848 appendStringInfo(buf, "%s(",
10849 generate_function_name(funcoid, nargs,
10850 argnames, argtypes,
10851 expr->funcvariadic,
10852 &use_variadic,
10853 context->inGroupBy));
10854 nargs = 0;
10855 foreach(l, expr->args)
10856 {
10857 if (nargs++ > 0)
10859 if (use_variadic && lnext(expr->args, l) == NULL)
10860 appendStringInfoString(buf, "VARIADIC ");
10861 get_rule_expr((Node *) lfirst(l), context, true);
10862 }
10864}
10865
10866/*
10867 * get_agg_expr - Parse back an Aggref node
10868 */
10869static void
10871 Aggref *original_aggref)
10872{
10873 get_agg_expr_helper(aggref, context, original_aggref, NULL, NULL,
10874 false);
10875}
10876
10877/*
10878 * get_agg_expr_helper - subroutine for get_agg_expr and
10879 * get_json_agg_constructor
10880 */
10881static void
10883 Aggref *original_aggref, const char *funcname,
10884 const char *options, bool is_json_objectagg)
10885{
10886 StringInfo buf = context->buf;
10887 Oid argtypes[FUNC_MAX_ARGS];
10888 int nargs;
10889 bool use_variadic = false;
10890
10891 /*
10892 * For a combining aggregate, we look up and deparse the corresponding
10893 * partial aggregate instead. This is necessary because our input
10894 * argument list has been replaced; the new argument list always has just
10895 * one element, which will point to a partial Aggref that supplies us with
10896 * transition states to combine.
10897 */
10898 if (DO_AGGSPLIT_COMBINE(aggref->aggsplit))
10899 {
10900 TargetEntry *tle;
10901
10902 Assert(list_length(aggref->args) == 1);
10903 tle = linitial_node(TargetEntry, aggref->args);
10904 resolve_special_varno((Node *) tle->expr, context,
10905 get_agg_combine_expr, original_aggref);
10906 return;
10907 }
10908
10909 /*
10910 * Mark as PARTIAL, if appropriate. We look to the original aggref so as
10911 * to avoid printing this when recursing from the code just above.
10912 */
10913 if (DO_AGGSPLIT_SKIPFINAL(original_aggref->aggsplit))
10914 appendStringInfoString(buf, "PARTIAL ");
10915
10916 /* Extract the argument types as seen by the parser */
10917 nargs = get_aggregate_argtypes(aggref, argtypes);
10918
10919 if (!funcname)
10920 funcname = generate_function_name(aggref->aggfnoid, nargs, NIL,
10921 argtypes, aggref->aggvariadic,
10922 &use_variadic,
10923 context->inGroupBy);
10924
10925 /* Print the aggregate name, schema-qualified if needed */
10926 appendStringInfo(buf, "%s(%s", funcname,
10927 (aggref->aggdistinct != NIL) ? "DISTINCT " : "");
10928
10929 if (AGGKIND_IS_ORDERED_SET(aggref->aggkind))
10930 {
10931 /*
10932 * Ordered-set aggregates do not use "*" syntax. Also, we needn't
10933 * worry about inserting VARIADIC. So we can just dump the direct
10934 * args as-is.
10935 */
10936 Assert(!aggref->aggvariadic);
10937 get_rule_expr((Node *) aggref->aggdirectargs, context, true);
10938 Assert(aggref->aggorder != NIL);
10939 appendStringInfoString(buf, ") WITHIN GROUP (ORDER BY ");
10940 get_rule_orderby(aggref->aggorder, aggref->args, false, context);
10941 }
10942 else
10943 {
10944 /* aggstar can be set only in zero-argument aggregates */
10945 if (aggref->aggstar)
10947 else
10948 {
10949 ListCell *l;
10950 int i;
10951
10952 i = 0;
10953 foreach(l, aggref->args)
10954 {
10955 TargetEntry *tle = (TargetEntry *) lfirst(l);
10956 Node *arg = (Node *) tle->expr;
10957
10959 if (tle->resjunk)
10960 continue;
10961 if (i++ > 0)
10962 {
10963 if (is_json_objectagg)
10964 {
10965 /*
10966 * the ABSENT ON NULL and WITH UNIQUE args are printed
10967 * separately, so ignore them here
10968 */
10969 if (i > 2)
10970 break;
10971
10973 }
10974 else
10976 }
10977 if (use_variadic && i == nargs)
10978 appendStringInfoString(buf, "VARIADIC ");
10979 get_rule_expr(arg, context, true);
10980 }
10981 }
10982
10983 if (aggref->aggorder != NIL)
10984 {
10985 appendStringInfoString(buf, " ORDER BY ");
10986 get_rule_orderby(aggref->aggorder, aggref->args, false, context);
10987 }
10988 }
10989
10990 if (options)
10992
10993 if (aggref->aggfilter != NULL)
10994 {
10995 appendStringInfoString(buf, ") FILTER (WHERE ");
10996 get_rule_expr((Node *) aggref->aggfilter, context, false);
10997 }
10998
11000}
11001
11002/*
11003 * This is a helper function for get_agg_expr(). It's used when we deparse
11004 * a combining Aggref; resolve_special_varno locates the corresponding partial
11005 * Aggref and then calls this.
11006 */
11007static void
11008get_agg_combine_expr(Node *node, deparse_context *context, void *callback_arg)
11009{
11010 Aggref *aggref;
11011 Aggref *original_aggref = callback_arg;
11012
11013 if (!IsA(node, Aggref))
11014 elog(ERROR, "combining Aggref does not point to an Aggref");
11015
11016 aggref = (Aggref *) node;
11017 get_agg_expr(aggref, context, original_aggref);
11018}
11019
11020/*
11021 * get_windowfunc_expr - Parse back a WindowFunc node
11022 */
11023static void
11025{
11026 get_windowfunc_expr_helper(wfunc, context, NULL, NULL, false);
11027}
11028
11029
11030/*
11031 * get_windowfunc_expr_helper - subroutine for get_windowfunc_expr and
11032 * get_json_agg_constructor
11033 */
11034static void
11036 const char *funcname, const char *options,
11037 bool is_json_objectagg)
11038{
11039 StringInfo buf = context->buf;
11040 Oid argtypes[FUNC_MAX_ARGS];
11041 int nargs;
11042 List *argnames;
11043 ListCell *l;
11044
11045 if (list_length(wfunc->args) > FUNC_MAX_ARGS)
11046 ereport(ERROR,
11047 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
11048 errmsg("too many arguments")));
11049 nargs = 0;
11050 argnames = NIL;
11051 foreach(l, wfunc->args)
11052 {
11053 Node *arg = (Node *) lfirst(l);
11054
11055 if (IsA(arg, NamedArgExpr))
11056 argnames = lappend(argnames, ((NamedArgExpr *) arg)->name);
11057 argtypes[nargs] = exprType(arg);
11058 nargs++;
11059 }
11060
11061 if (!funcname)
11062 funcname = generate_function_name(wfunc->winfnoid, nargs, argnames,
11063 argtypes, false, NULL,
11064 context->inGroupBy);
11065
11066 appendStringInfo(buf, "%s(", funcname);
11067
11068 /* winstar can be set only in zero-argument aggregates */
11069 if (wfunc->winstar)
11071 else
11072 {
11073 if (is_json_objectagg)
11074 {
11075 get_rule_expr((Node *) linitial(wfunc->args), context, false);
11077 get_rule_expr((Node *) lsecond(wfunc->args), context, false);
11078 }
11079 else
11080 get_rule_expr((Node *) wfunc->args, context, true);
11081 }
11082
11083 if (options)
11085
11086 if (wfunc->aggfilter != NULL)
11087 {
11088 appendStringInfoString(buf, ") FILTER (WHERE ");
11089 get_rule_expr((Node *) wfunc->aggfilter, context, false);
11090 }
11091
11092 appendStringInfoString(buf, ") OVER ");
11093
11094 if (context->windowClause)
11095 {
11096 /* Query-decompilation case: search the windowClause list */
11097 foreach(l, context->windowClause)
11098 {
11099 WindowClause *wc = (WindowClause *) lfirst(l);
11100
11101 if (wc->winref == wfunc->winref)
11102 {
11103 if (wc->name)
11105 else
11106 get_rule_windowspec(wc, context->targetList, context);
11107 break;
11108 }
11109 }
11110 if (l == NULL)
11111 elog(ERROR, "could not find window clause for winref %u",
11112 wfunc->winref);
11113 }
11114 else
11115 {
11116 /*
11117 * In EXPLAIN, search the namespace stack for a matching WindowAgg
11118 * node (probably it's always the first entry), and print winname.
11119 */
11120 foreach(l, context->namespaces)
11121 {
11123
11124 if (dpns->plan && IsA(dpns->plan, WindowAgg))
11125 {
11126 WindowAgg *wagg = (WindowAgg *) dpns->plan;
11127
11128 if (wagg->winref == wfunc->winref)
11129 {
11131 break;
11132 }
11133 }
11134 }
11135 if (l == NULL)
11136 elog(ERROR, "could not find window clause for winref %u",
11137 wfunc->winref);
11138 }
11139}
11140
11141/*
11142 * get_func_sql_syntax - Parse back a SQL-syntax function call
11143 *
11144 * Returns true if we successfully deparsed, false if we did not
11145 * recognize the function.
11146 */
11147static bool
11149{
11150 StringInfo buf = context->buf;
11151 Oid funcoid = expr->funcid;
11152
11153 switch (funcoid)
11154 {
11155 case F_TIMEZONE_INTERVAL_TIMESTAMP:
11156 case F_TIMEZONE_INTERVAL_TIMESTAMPTZ:
11157 case F_TIMEZONE_INTERVAL_TIMETZ:
11158 case F_TIMEZONE_TEXT_TIMESTAMP:
11159 case F_TIMEZONE_TEXT_TIMESTAMPTZ:
11160 case F_TIMEZONE_TEXT_TIMETZ:
11161 /* AT TIME ZONE ... note reversed argument order */
11163 get_rule_expr_paren((Node *) lsecond(expr->args), context, false,
11164 (Node *) expr);
11165 appendStringInfoString(buf, " AT TIME ZONE ");
11166 get_rule_expr_paren((Node *) linitial(expr->args), context, false,
11167 (Node *) expr);
11169 return true;
11170
11171 case F_TIMEZONE_TIMESTAMP:
11172 case F_TIMEZONE_TIMESTAMPTZ:
11173 case F_TIMEZONE_TIMETZ:
11174 /* AT LOCAL */
11176 get_rule_expr_paren((Node *) linitial(expr->args), context, false,
11177 (Node *) expr);
11178 appendStringInfoString(buf, " AT LOCAL)");
11179 return true;
11180
11181 case F_OVERLAPS_TIMESTAMPTZ_INTERVAL_TIMESTAMPTZ_INTERVAL:
11182 case F_OVERLAPS_TIMESTAMPTZ_INTERVAL_TIMESTAMPTZ_TIMESTAMPTZ:
11183 case F_OVERLAPS_TIMESTAMPTZ_TIMESTAMPTZ_TIMESTAMPTZ_INTERVAL:
11184 case F_OVERLAPS_TIMESTAMPTZ_TIMESTAMPTZ_TIMESTAMPTZ_TIMESTAMPTZ:
11185 case F_OVERLAPS_TIMESTAMP_INTERVAL_TIMESTAMP_INTERVAL:
11186 case F_OVERLAPS_TIMESTAMP_INTERVAL_TIMESTAMP_TIMESTAMP:
11187 case F_OVERLAPS_TIMESTAMP_TIMESTAMP_TIMESTAMP_INTERVAL:
11188 case F_OVERLAPS_TIMESTAMP_TIMESTAMP_TIMESTAMP_TIMESTAMP:
11189 case F_OVERLAPS_TIMETZ_TIMETZ_TIMETZ_TIMETZ:
11190 case F_OVERLAPS_TIME_INTERVAL_TIME_INTERVAL:
11191 case F_OVERLAPS_TIME_INTERVAL_TIME_TIME:
11192 case F_OVERLAPS_TIME_TIME_TIME_INTERVAL:
11193 case F_OVERLAPS_TIME_TIME_TIME_TIME:
11194 /* (x1, x2) OVERLAPS (y1, y2) */
11196 get_rule_expr((Node *) linitial(expr->args), context, false);
11198 get_rule_expr((Node *) lsecond(expr->args), context, false);
11199 appendStringInfoString(buf, ") OVERLAPS (");
11200 get_rule_expr((Node *) lthird(expr->args), context, false);
11202 get_rule_expr((Node *) lfourth(expr->args), context, false);
11204 return true;
11205
11206 case F_EXTRACT_TEXT_DATE:
11207 case F_EXTRACT_TEXT_TIME:
11208 case F_EXTRACT_TEXT_TIMETZ:
11209 case F_EXTRACT_TEXT_TIMESTAMP:
11210 case F_EXTRACT_TEXT_TIMESTAMPTZ:
11211 case F_EXTRACT_TEXT_INTERVAL:
11212 /* EXTRACT (x FROM y) */
11213 appendStringInfoString(buf, "EXTRACT(");
11214 {
11215 Const *con = (Const *) linitial(expr->args);
11216
11217 Assert(IsA(con, Const) &&
11218 con->consttype == TEXTOID &&
11219 !con->constisnull);
11221 }
11222 appendStringInfoString(buf, " FROM ");
11223 get_rule_expr((Node *) lsecond(expr->args), context, false);
11225 return true;
11226
11227 case F_IS_NORMALIZED:
11228 /* IS xxx NORMALIZED */
11230 get_rule_expr_paren((Node *) linitial(expr->args), context, false,
11231 (Node *) expr);
11233 if (list_length(expr->args) == 2)
11234 {
11235 Const *con = (Const *) lsecond(expr->args);
11236
11237 Assert(IsA(con, Const) &&
11238 con->consttype == TEXTOID &&
11239 !con->constisnull);
11240 appendStringInfo(buf, " %s",
11241 TextDatumGetCString(con->constvalue));
11242 }
11243 appendStringInfoString(buf, " NORMALIZED)");
11244 return true;
11245
11246 case F_PG_COLLATION_FOR:
11247 /* COLLATION FOR */
11248 appendStringInfoString(buf, "COLLATION FOR (");
11249 get_rule_expr((Node *) linitial(expr->args), context, false);
11251 return true;
11252
11253 case F_NORMALIZE:
11254 /* NORMALIZE() */
11255 appendStringInfoString(buf, "NORMALIZE(");
11256 get_rule_expr((Node *) linitial(expr->args), context, false);
11257 if (list_length(expr->args) == 2)
11258 {
11259 Const *con = (Const *) lsecond(expr->args);
11260
11261 Assert(IsA(con, Const) &&
11262 con->consttype == TEXTOID &&
11263 !con->constisnull);
11264 appendStringInfo(buf, ", %s",
11265 TextDatumGetCString(con->constvalue));
11266 }
11268 return true;
11269
11270 case F_OVERLAY_BIT_BIT_INT4:
11271 case F_OVERLAY_BIT_BIT_INT4_INT4:
11272 case F_OVERLAY_BYTEA_BYTEA_INT4:
11273 case F_OVERLAY_BYTEA_BYTEA_INT4_INT4:
11274 case F_OVERLAY_TEXT_TEXT_INT4:
11275 case F_OVERLAY_TEXT_TEXT_INT4_INT4:
11276 /* OVERLAY() */
11277 appendStringInfoString(buf, "OVERLAY(");
11278 get_rule_expr((Node *) linitial(expr->args), context, false);
11279 appendStringInfoString(buf, " PLACING ");
11280 get_rule_expr((Node *) lsecond(expr->args), context, false);
11281 appendStringInfoString(buf, " FROM ");
11282 get_rule_expr((Node *) lthird(expr->args), context, false);
11283 if (list_length(expr->args) == 4)
11284 {
11285 appendStringInfoString(buf, " FOR ");
11286 get_rule_expr((Node *) lfourth(expr->args), context, false);
11287 }
11289 return true;
11290
11291 case F_POSITION_BIT_BIT:
11292 case F_POSITION_BYTEA_BYTEA:
11293 case F_POSITION_TEXT_TEXT:
11294 /* POSITION() ... extra parens since args are b_expr not a_expr */
11295 appendStringInfoString(buf, "POSITION((");
11296 get_rule_expr((Node *) lsecond(expr->args), context, false);
11297 appendStringInfoString(buf, ") IN (");
11298 get_rule_expr((Node *) linitial(expr->args), context, false);
11300 return true;
11301
11302 case F_SUBSTRING_BIT_INT4:
11303 case F_SUBSTRING_BIT_INT4_INT4:
11304 case F_SUBSTRING_BYTEA_INT4:
11305 case F_SUBSTRING_BYTEA_INT4_INT4:
11306 case F_SUBSTRING_TEXT_INT4:
11307 case F_SUBSTRING_TEXT_INT4_INT4:
11308 /* SUBSTRING FROM/FOR (i.e., integer-position variants) */
11309 appendStringInfoString(buf, "SUBSTRING(");
11310 get_rule_expr((Node *) linitial(expr->args), context, false);
11311 appendStringInfoString(buf, " FROM ");
11312 get_rule_expr((Node *) lsecond(expr->args), context, false);
11313 if (list_length(expr->args) == 3)
11314 {
11315 appendStringInfoString(buf, " FOR ");
11316 get_rule_expr((Node *) lthird(expr->args), context, false);
11317 }
11319 return true;
11320
11321 case F_SUBSTRING_TEXT_TEXT_TEXT:
11322 /* SUBSTRING SIMILAR/ESCAPE */
11323 appendStringInfoString(buf, "SUBSTRING(");
11324 get_rule_expr((Node *) linitial(expr->args), context, false);
11325 appendStringInfoString(buf, " SIMILAR ");
11326 get_rule_expr((Node *) lsecond(expr->args), context, false);
11327 appendStringInfoString(buf, " ESCAPE ");
11328 get_rule_expr((Node *) lthird(expr->args), context, false);
11330 return true;
11331
11332 case F_BTRIM_BYTEA_BYTEA:
11333 case F_BTRIM_TEXT:
11334 case F_BTRIM_TEXT_TEXT:
11335 /* TRIM() */
11336 appendStringInfoString(buf, "TRIM(BOTH");
11337 if (list_length(expr->args) == 2)
11338 {
11340 get_rule_expr((Node *) lsecond(expr->args), context, false);
11341 }
11342 appendStringInfoString(buf, " FROM ");
11343 get_rule_expr((Node *) linitial(expr->args), context, false);
11345 return true;
11346
11347 case F_LTRIM_BYTEA_BYTEA:
11348 case F_LTRIM_TEXT:
11349 case F_LTRIM_TEXT_TEXT:
11350 /* TRIM() */
11351 appendStringInfoString(buf, "TRIM(LEADING");
11352 if (list_length(expr->args) == 2)
11353 {
11355 get_rule_expr((Node *) lsecond(expr->args), context, false);
11356 }
11357 appendStringInfoString(buf, " FROM ");
11358 get_rule_expr((Node *) linitial(expr->args), context, false);
11360 return true;
11361
11362 case F_RTRIM_BYTEA_BYTEA:
11363 case F_RTRIM_TEXT:
11364 case F_RTRIM_TEXT_TEXT:
11365 /* TRIM() */
11366 appendStringInfoString(buf, "TRIM(TRAILING");
11367 if (list_length(expr->args) == 2)
11368 {
11370 get_rule_expr((Node *) lsecond(expr->args), context, false);
11371 }
11372 appendStringInfoString(buf, " FROM ");
11373 get_rule_expr((Node *) linitial(expr->args), context, false);
11375 return true;
11376
11377 case F_SYSTEM_USER:
11378 appendStringInfoString(buf, "SYSTEM_USER");
11379 return true;
11380
11381 case F_XMLEXISTS:
11382 /* XMLEXISTS ... extra parens because args are c_expr */
11383 appendStringInfoString(buf, "XMLEXISTS((");
11384 get_rule_expr((Node *) linitial(expr->args), context, false);
11385 appendStringInfoString(buf, ") PASSING (");
11386 get_rule_expr((Node *) lsecond(expr->args), context, false);
11388 return true;
11389 }
11390 return false;
11391}
11392
11393/* ----------
11394 * get_coercion_expr
11395 *
11396 * Make a string representation of a value coerced to a specific type
11397 * ----------
11398 */
11399static void
11401 Oid resulttype, int32 resulttypmod,
11402 Node *parentNode)
11403{
11404 StringInfo buf = context->buf;
11405
11406 /*
11407 * Since parse_coerce.c doesn't immediately collapse application of
11408 * length-coercion functions to constants, what we'll typically see in
11409 * such cases is a Const with typmod -1 and a length-coercion function
11410 * right above it. Avoid generating redundant output. However, beware of
11411 * suppressing casts when the user actually wrote something like
11412 * 'foo'::text::char(3).
11413 *
11414 * Note: it might seem that we are missing the possibility of needing to
11415 * print a COLLATE clause for such a Const. However, a Const could only
11416 * have nondefault collation in a post-constant-folding tree, in which the
11417 * length coercion would have been folded too. See also the special
11418 * handling of CollateExpr in coerce_to_target_type(): any collation
11419 * marking will be above the coercion node, not below it.
11420 */
11421 if (arg && IsA(arg, Const) &&
11422 ((Const *) arg)->consttype == resulttype &&
11423 ((Const *) arg)->consttypmod == -1)
11424 {
11425 /* Show the constant without normal ::typename decoration */
11426 get_const_expr((Const *) arg, context, -1);
11427 }
11428 else
11429 {
11430 if (!PRETTY_PAREN(context))
11432 get_rule_expr_paren(arg, context, false, parentNode);
11433 if (!PRETTY_PAREN(context))
11435 }
11436
11437 /*
11438 * Never emit resulttype(arg) functional notation. A pg_proc entry could
11439 * take precedence, and a resulttype in pg_temp would require schema
11440 * qualification that format_type_with_typemod() would usually omit. We've
11441 * standardized on arg::resulttype, but CAST(arg AS resulttype) notation
11442 * would work fine.
11443 */
11444 appendStringInfo(buf, "::%s",
11445 format_type_with_typemod(resulttype, resulttypmod));
11446}
11447
11448/* ----------
11449 * get_const_expr
11450 *
11451 * Make a string representation of a Const
11452 *
11453 * showtype can be -1 to never show "::typename" decoration, or +1 to always
11454 * show it, or 0 to show it only if the constant wouldn't be assumed to be
11455 * the right type by default.
11456 *
11457 * If the Const's collation isn't default for its type, show that too.
11458 * We mustn't do this when showtype is -1 (since that means the caller will
11459 * print "::typename", and we can't put a COLLATE clause in between). It's
11460 * caller's responsibility that collation isn't missed in such cases.
11461 * ----------
11462 */
11463static void
11464get_const_expr(Const *constval, deparse_context *context, int showtype)
11465{
11466 StringInfo buf = context->buf;
11467 Oid typoutput;
11468 bool typIsVarlena;
11469 char *extval;
11470 bool needlabel = false;
11471
11472 if (constval->constisnull)
11473 {
11474 /*
11475 * Always label the type of a NULL constant to prevent misdecisions
11476 * about type when reparsing.
11477 */
11478 appendStringInfoString(buf, "NULL");
11479 if (showtype >= 0)
11480 {
11481 appendStringInfo(buf, "::%s",
11483 constval->consttypmod));
11484 get_const_collation(constval, context);
11485 }
11486 return;
11487 }
11488
11489 getTypeOutputInfo(constval->consttype,
11490 &typoutput, &typIsVarlena);
11491
11492 extval = OidOutputFunctionCall(typoutput, constval->constvalue);
11493
11494 switch (constval->consttype)
11495 {
11496 case INT4OID:
11497
11498 /*
11499 * INT4 can be printed without any decoration, unless it is
11500 * negative; in that case print it as '-nnn'::integer to ensure
11501 * that the output will re-parse as a constant, not as a constant
11502 * plus operator. In most cases we could get away with printing
11503 * (-nnn) instead, because of the way that gram.y handles negative
11504 * literals; but that doesn't work for INT_MIN, and it doesn't
11505 * seem that much prettier anyway.
11506 */
11507 if (extval[0] != '-')
11508 appendStringInfoString(buf, extval);
11509 else
11510 {
11511 appendStringInfo(buf, "'%s'", extval);
11512 needlabel = true; /* we must attach a cast */
11513 }
11514 break;
11515
11516 case NUMERICOID:
11517
11518 /*
11519 * NUMERIC can be printed without quotes if it looks like a float
11520 * constant (not an integer, and not Infinity or NaN) and doesn't
11521 * have a leading sign (for the same reason as for INT4).
11522 */
11523 if (isdigit((unsigned char) extval[0]) &&
11524 strcspn(extval, "eE.") != strlen(extval))
11525 {
11526 appendStringInfoString(buf, extval);
11527 }
11528 else
11529 {
11530 appendStringInfo(buf, "'%s'", extval);
11531 needlabel = true; /* we must attach a cast */
11532 }
11533 break;
11534
11535 case BOOLOID:
11536 if (strcmp(extval, "t") == 0)
11537 appendStringInfoString(buf, "true");
11538 else
11539 appendStringInfoString(buf, "false");
11540 break;
11541
11542 default:
11543 simple_quote_literal(buf, extval);
11544 break;
11545 }
11546
11547 pfree(extval);
11548
11549 if (showtype < 0)
11550 return;
11551
11552 /*
11553 * For showtype == 0, append ::typename unless the constant will be
11554 * implicitly typed as the right type when it is read in.
11555 *
11556 * XXX this code has to be kept in sync with the behavior of the parser,
11557 * especially make_const.
11558 */
11559 switch (constval->consttype)
11560 {
11561 case BOOLOID:
11562 case UNKNOWNOID:
11563 /* These types can be left unlabeled */
11564 needlabel = false;
11565 break;
11566 case INT4OID:
11567 /* We determined above whether a label is needed */
11568 break;
11569 case NUMERICOID:
11570
11571 /*
11572 * Float-looking constants will be typed as numeric, which we
11573 * checked above; but if there's a nondefault typmod we need to
11574 * show it.
11575 */
11576 needlabel |= (constval->consttypmod >= 0);
11577 break;
11578 default:
11579 needlabel = true;
11580 break;
11581 }
11582 if (needlabel || showtype > 0)
11583 appendStringInfo(buf, "::%s",
11585 constval->consttypmod));
11586
11587 get_const_collation(constval, context);
11588}
11589
11590/*
11591 * helper for get_const_expr: append COLLATE if needed
11592 */
11593static void
11595{
11596 StringInfo buf = context->buf;
11597
11598 if (OidIsValid(constval->constcollid))
11599 {
11600 Oid typcollation = get_typcollation(constval->consttype);
11601
11602 if (constval->constcollid != typcollation)
11603 {
11604 appendStringInfo(buf, " COLLATE %s",
11605 generate_collation_name(constval->constcollid));
11606 }
11607 }
11608}
11609
11610/*
11611 * get_json_path_spec - Parse back a JSON path specification
11612 */
11613static void
11614get_json_path_spec(Node *path_spec, deparse_context *context, bool showimplicit)
11615{
11616 if (IsA(path_spec, Const))
11617 get_const_expr((Const *) path_spec, context, -1);
11618 else
11619 get_rule_expr(path_spec, context, showimplicit);
11620}
11621
11622/*
11623 * get_json_format - Parse back a JsonFormat node
11624 */
11625static void
11627{
11628 if (format->format_type == JS_FORMAT_DEFAULT)
11629 return;
11630
11632 format->format_type == JS_FORMAT_JSONB ?
11633 " FORMAT JSONB" : " FORMAT JSON");
11634
11635 if (format->encoding != JS_ENC_DEFAULT)
11636 {
11637 const char *encoding;
11638
11639 encoding =
11640 format->encoding == JS_ENC_UTF16 ? "UTF16" :
11641 format->encoding == JS_ENC_UTF32 ? "UTF32" : "UTF8";
11642
11643 appendStringInfo(buf, " ENCODING %s", encoding);
11644 }
11645}
11646
11647/*
11648 * get_json_returning - Parse back a JsonReturning structure
11649 */
11650static void
11652 bool json_format_by_default)
11653{
11654 if (!OidIsValid(returning->typid))
11655 return;
11656
11657 appendStringInfo(buf, " RETURNING %s",
11659 returning->typmod));
11660
11661 if (!json_format_by_default ||
11662 returning->format->format_type !=
11663 (returning->typid == JSONBOID ? JS_FORMAT_JSONB : JS_FORMAT_JSON))
11664 get_json_format(returning->format, buf);
11665}
11666
11667/*
11668 * get_json_constructor - Parse back a JsonConstructorExpr node
11669 */
11670static void
11672 bool showimplicit)
11673{
11674 StringInfo buf = context->buf;
11675 const char *funcname;
11676 bool is_json_object;
11677 int curridx;
11678 ListCell *lc;
11679
11680 if (ctor->type == JSCTOR_JSON_OBJECTAGG)
11681 {
11682 get_json_agg_constructor(ctor, context, "JSON_OBJECTAGG", true);
11683 return;
11684 }
11685 else if (ctor->type == JSCTOR_JSON_ARRAYAGG)
11686 {
11687 get_json_agg_constructor(ctor, context, "JSON_ARRAYAGG", false);
11688 return;
11689 }
11690
11691 switch (ctor->type)
11692 {
11693 case JSCTOR_JSON_OBJECT:
11694 funcname = "JSON_OBJECT";
11695 break;
11696 case JSCTOR_JSON_ARRAY:
11697 funcname = "JSON_ARRAY";
11698 break;
11699 case JSCTOR_JSON_PARSE:
11700 funcname = "JSON";
11701 break;
11702 case JSCTOR_JSON_SCALAR:
11703 funcname = "JSON_SCALAR";
11704 break;
11706 funcname = "JSON_SERIALIZE";
11707 break;
11708 default:
11709 elog(ERROR, "invalid JsonConstructorType %d", ctor->type);
11710 }
11711
11712 appendStringInfo(buf, "%s(", funcname);
11713
11714 is_json_object = ctor->type == JSCTOR_JSON_OBJECT;
11715 foreach(lc, ctor->args)
11716 {
11717 curridx = foreach_current_index(lc);
11718 if (curridx > 0)
11719 {
11720 const char *sep;
11721
11722 sep = (is_json_object && (curridx % 2) != 0) ? " : " : ", ";
11724 }
11725
11726 get_rule_expr((Node *) lfirst(lc), context, true);
11727 }
11728
11731}
11732
11733/*
11734 * Append options, if any, to the JSON constructor being deparsed
11735 */
11736static void
11738{
11739 if (ctor->absent_on_null)
11740 {
11741 if (ctor->type == JSCTOR_JSON_OBJECT ||
11742 ctor->type == JSCTOR_JSON_OBJECTAGG)
11743 appendStringInfoString(buf, " ABSENT ON NULL");
11744 }
11745 else
11746 {
11747 if (ctor->type == JSCTOR_JSON_ARRAY ||
11748 ctor->type == JSCTOR_JSON_ARRAYAGG)
11749 appendStringInfoString(buf, " NULL ON NULL");
11750 }
11751
11752 if (ctor->unique)
11753 appendStringInfoString(buf, " WITH UNIQUE KEYS");
11754
11755 /*
11756 * Append RETURNING clause if needed; JSON() and JSON_SCALAR() don't
11757 * support one.
11758 */
11759 if (ctor->type != JSCTOR_JSON_PARSE && ctor->type != JSCTOR_JSON_SCALAR)
11760 get_json_returning(ctor->returning, buf, true);
11761}
11762
11763/*
11764 * get_json_agg_constructor - Parse back an aggregate JsonConstructorExpr node
11765 */
11766static void
11768 const char *funcname, bool is_json_objectagg)
11769{
11771
11774
11775 if (IsA(ctor->func, Aggref))
11776 get_agg_expr_helper((Aggref *) ctor->func, context,
11777 (Aggref *) ctor->func,
11778 funcname, options.data, is_json_objectagg);
11779 else if (IsA(ctor->func, WindowFunc))
11780 get_windowfunc_expr_helper((WindowFunc *) ctor->func, context,
11781 funcname, options.data,
11782 is_json_objectagg);
11783 else
11784 elog(ERROR, "invalid JsonConstructorExpr underlying node type: %d",
11785 nodeTag(ctor->func));
11786}
11787
11788/*
11789 * simple_quote_literal - Format a string as a SQL literal, append to buf
11790 */
11791static void
11793{
11794 const char *valptr;
11795
11796 /*
11797 * We form the string literal according to the prevailing setting of
11798 * standard_conforming_strings; we never use E''. User is responsible for
11799 * making sure result is used correctly.
11800 */
11802 for (valptr = val; *valptr; valptr++)
11803 {
11804 char ch = *valptr;
11805
11809 }
11811}
11812
11813
11814/* ----------
11815 * get_sublink_expr - Parse back a sublink
11816 * ----------
11817 */
11818static void
11820{
11821 StringInfo buf = context->buf;
11822 Query *query = (Query *) (sublink->subselect);
11823 char *opname = NULL;
11824 bool need_paren;
11825
11826 if (sublink->subLinkType == ARRAY_SUBLINK)
11827 appendStringInfoString(buf, "ARRAY(");
11828 else
11830
11831 /*
11832 * Note that we print the name of only the first operator, when there are
11833 * multiple combining operators. This is an approximation that could go
11834 * wrong in various scenarios (operators in different schemas, renamed
11835 * operators, etc) but there is not a whole lot we can do about it, since
11836 * the syntax allows only one operator to be shown.
11837 */
11838 if (sublink->testexpr)
11839 {
11840 if (IsA(sublink->testexpr, OpExpr))
11841 {
11842 /* single combining operator */
11843 OpExpr *opexpr = (OpExpr *) sublink->testexpr;
11844
11845 get_rule_expr(linitial(opexpr->args), context, true);
11846 opname = generate_operator_name(opexpr->opno,
11847 exprType(linitial(opexpr->args)),
11848 exprType(lsecond(opexpr->args)));
11849 }
11850 else if (IsA(sublink->testexpr, BoolExpr))
11851 {
11852 /* multiple combining operators, = or <> cases */
11853 char *sep;
11854 ListCell *l;
11855
11857 sep = "";
11858 foreach(l, ((BoolExpr *) sublink->testexpr)->args)
11859 {
11860 OpExpr *opexpr = lfirst_node(OpExpr, l);
11861
11863 get_rule_expr(linitial(opexpr->args), context, true);
11864 if (!opname)
11865 opname = generate_operator_name(opexpr->opno,
11866 exprType(linitial(opexpr->args)),
11867 exprType(lsecond(opexpr->args)));
11868 sep = ", ";
11869 }
11871 }
11872 else if (IsA(sublink->testexpr, RowCompareExpr))
11873 {
11874 /* multiple combining operators, < <= > >= cases */
11875 RowCompareExpr *rcexpr = (RowCompareExpr *) sublink->testexpr;
11876
11878 get_rule_expr((Node *) rcexpr->largs, context, true);
11879 opname = generate_operator_name(linitial_oid(rcexpr->opnos),
11880 exprType(linitial(rcexpr->largs)),
11881 exprType(linitial(rcexpr->rargs)));
11883 }
11884 else
11885 elog(ERROR, "unrecognized testexpr type: %d",
11886 (int) nodeTag(sublink->testexpr));
11887 }
11888
11889 need_paren = true;
11890
11891 switch (sublink->subLinkType)
11892 {
11893 case EXISTS_SUBLINK:
11894 appendStringInfoString(buf, "EXISTS ");
11895 break;
11896
11897 case ANY_SUBLINK:
11898 if (strcmp(opname, "=") == 0) /* Represent = ANY as IN */
11899 appendStringInfoString(buf, " IN ");
11900 else
11901 appendStringInfo(buf, " %s ANY ", opname);
11902 break;
11903
11904 case ALL_SUBLINK:
11905 appendStringInfo(buf, " %s ALL ", opname);
11906 break;
11907
11908 case ROWCOMPARE_SUBLINK:
11909 appendStringInfo(buf, " %s ", opname);
11910 break;
11911
11912 case EXPR_SUBLINK:
11913 case MULTIEXPR_SUBLINK:
11914 case ARRAY_SUBLINK:
11915 need_paren = false;
11916 break;
11917
11918 case CTE_SUBLINK: /* shouldn't occur in a SubLink */
11919 default:
11920 elog(ERROR, "unrecognized sublink type: %d",
11921 (int) sublink->subLinkType);
11922 break;
11923 }
11924
11925 if (need_paren)
11927
11928 get_query_def(query, buf, context->namespaces, NULL, false,
11929 context->prettyFlags, context->wrapColumn,
11930 context->indentLevel);
11931
11932 if (need_paren)
11934 else
11936}
11937
11938
11939/* ----------
11940 * get_xmltable - Parse back a XMLTABLE function
11941 * ----------
11942 */
11943static void
11944get_xmltable(TableFunc *tf, deparse_context *context, bool showimplicit)
11945{
11946 StringInfo buf = context->buf;
11947
11948 appendStringInfoString(buf, "XMLTABLE(");
11949
11950 if (tf->ns_uris != NIL)
11951 {
11952 ListCell *lc1,
11953 *lc2;
11954 bool first = true;
11955
11956 appendStringInfoString(buf, "XMLNAMESPACES (");
11957 forboth(lc1, tf->ns_uris, lc2, tf->ns_names)
11958 {
11959 Node *expr = (Node *) lfirst(lc1);
11960 String *ns_node = lfirst_node(String, lc2);
11961
11962 if (!first)
11964 else
11965 first = false;
11966
11967 if (ns_node != NULL)
11968 {
11969 get_rule_expr(expr, context, showimplicit);
11970 appendStringInfo(buf, " AS %s",
11971 quote_identifier(strVal(ns_node)));
11972 }
11973 else
11974 {
11975 appendStringInfoString(buf, "DEFAULT ");
11976 get_rule_expr(expr, context, showimplicit);
11977 }
11978 }
11980 }
11981
11983 get_rule_expr((Node *) tf->rowexpr, context, showimplicit);
11984 appendStringInfoString(buf, ") PASSING (");
11985 get_rule_expr((Node *) tf->docexpr, context, showimplicit);
11987
11988 if (tf->colexprs != NIL)
11989 {
11990 ListCell *l1;
11991 ListCell *l2;
11992 ListCell *l3;
11993 ListCell *l4;
11994 ListCell *l5;
11995 int colnum = 0;
11996
11997 appendStringInfoString(buf, " COLUMNS ");
11998 forfive(l1, tf->colnames, l2, tf->coltypes, l3, tf->coltypmods,
11999 l4, tf->colexprs, l5, tf->coldefexprs)
12000 {
12001 char *colname = strVal(lfirst(l1));
12002 Oid typid = lfirst_oid(l2);
12003 int32 typmod = lfirst_int(l3);
12004 Node *colexpr = (Node *) lfirst(l4);
12005 Node *coldefexpr = (Node *) lfirst(l5);
12006 bool ordinality = (tf->ordinalitycol == colnum);
12007 bool notnull = bms_is_member(colnum, tf->notnulls);
12008
12009 if (colnum > 0)
12011 colnum++;
12012
12013 appendStringInfo(buf, "%s %s", quote_identifier(colname),
12014 ordinality ? "FOR ORDINALITY" :
12015 format_type_with_typemod(typid, typmod));
12016 if (ordinality)
12017 continue;
12018
12019 if (coldefexpr != NULL)
12020 {
12021 appendStringInfoString(buf, " DEFAULT (");
12022 get_rule_expr((Node *) coldefexpr, context, showimplicit);
12024 }
12025 if (colexpr != NULL)
12026 {
12027 appendStringInfoString(buf, " PATH (");
12028 get_rule_expr((Node *) colexpr, context, showimplicit);
12030 }
12031 if (notnull)
12032 appendStringInfoString(buf, " NOT NULL");
12033 }
12034 }
12035
12037}
12038
12039/*
12040 * get_json_table_nested_columns - Parse back nested JSON_TABLE columns
12041 */
12042static void
12044 deparse_context *context, bool showimplicit,
12045 bool needcomma)
12046{
12048 {
12050
12051 if (needcomma)
12052 appendStringInfoChar(context->buf, ',');
12053
12054 appendStringInfoChar(context->buf, ' ');
12055 appendContextKeyword(context, "NESTED PATH ", 0, 0, 0);
12056 get_const_expr(scan->path->value, context, -1);
12057 appendStringInfo(context->buf, " AS %s", quote_identifier(scan->path->name));
12058 get_json_table_columns(tf, scan, context, showimplicit);
12059 }
12060 else if (IsA(plan, JsonTableSiblingJoin))
12061 {
12063
12064 get_json_table_nested_columns(tf, join->lplan, context, showimplicit,
12065 needcomma);
12066 get_json_table_nested_columns(tf, join->rplan, context, showimplicit,
12067 true);
12068 }
12069}
12070
12071/*
12072 * get_json_table_columns - Parse back JSON_TABLE columns
12073 */
12074static void
12076 deparse_context *context,
12077 bool showimplicit)
12078{
12079 StringInfo buf = context->buf;
12080 ListCell *lc_colname;
12081 ListCell *lc_coltype;
12082 ListCell *lc_coltypmod;
12083 ListCell *lc_colvalexpr;
12084 int colnum = 0;
12085
12087 appendContextKeyword(context, "COLUMNS (", 0, 0, 0);
12088
12089 if (PRETTY_INDENT(context))
12090 context->indentLevel += PRETTYINDENT_VAR;
12091
12092 forfour(lc_colname, tf->colnames,
12093 lc_coltype, tf->coltypes,
12094 lc_coltypmod, tf->coltypmods,
12095 lc_colvalexpr, tf->colvalexprs)
12096 {
12097 char *colname = strVal(lfirst(lc_colname));
12098 JsonExpr *colexpr;
12099 Oid typid;
12100 int32 typmod;
12101 bool ordinality;
12102 JsonBehaviorType default_behavior;
12103
12104 typid = lfirst_oid(lc_coltype);
12105 typmod = lfirst_int(lc_coltypmod);
12106 colexpr = castNode(JsonExpr, lfirst(lc_colvalexpr));
12107
12108 /* Skip columns that don't belong to this scan. */
12109 if (scan->colMin < 0 || colnum < scan->colMin)
12110 {
12111 colnum++;
12112 continue;
12113 }
12114 if (colnum > scan->colMax)
12115 break;
12116
12117 if (colnum > scan->colMin)
12119
12120 colnum++;
12121
12122 ordinality = !colexpr;
12123
12124 appendContextKeyword(context, "", 0, 0, 0);
12125
12126 appendStringInfo(buf, "%s %s", quote_identifier(colname),
12127 ordinality ? "FOR ORDINALITY" :
12128 format_type_with_typemod(typid, typmod));
12129 if (ordinality)
12130 continue;
12131
12132 /*
12133 * Set default_behavior to guide get_json_expr_options() on whether to
12134 * emit the ON ERROR / EMPTY clauses.
12135 */
12136 if (colexpr->op == JSON_EXISTS_OP)
12137 {
12138 appendStringInfoString(buf, " EXISTS");
12139 default_behavior = JSON_BEHAVIOR_FALSE;
12140 }
12141 else
12142 {
12143 if (colexpr->op == JSON_QUERY_OP)
12144 {
12145 char typcategory;
12146 bool typispreferred;
12147
12148 get_type_category_preferred(typid, &typcategory, &typispreferred);
12149
12150 if (typcategory == TYPCATEGORY_STRING)
12152 colexpr->format->format_type == JS_FORMAT_JSONB ?
12153 " FORMAT JSONB" : " FORMAT JSON");
12154 }
12155
12156 default_behavior = JSON_BEHAVIOR_NULL;
12157 }
12158
12159 appendStringInfoString(buf, " PATH ");
12160
12161 get_json_path_spec(colexpr->path_spec, context, showimplicit);
12162
12163 get_json_expr_options(colexpr, context, default_behavior);
12164 }
12165
12166 if (scan->child)
12167 get_json_table_nested_columns(tf, scan->child, context, showimplicit,
12168 scan->colMin >= 0);
12169
12170 if (PRETTY_INDENT(context))
12171 context->indentLevel -= PRETTYINDENT_VAR;
12172
12173 appendContextKeyword(context, ")", 0, 0, 0);
12174}
12175
12176/* ----------
12177 * get_json_table - Parse back a JSON_TABLE function
12178 * ----------
12179 */
12180static void
12181get_json_table(TableFunc *tf, deparse_context *context, bool showimplicit)
12182{
12183 StringInfo buf = context->buf;
12184 JsonExpr *jexpr = castNode(JsonExpr, tf->docexpr);
12186
12187 appendStringInfoString(buf, "JSON_TABLE(");
12188
12189 if (PRETTY_INDENT(context))
12190 context->indentLevel += PRETTYINDENT_VAR;
12191
12192 appendContextKeyword(context, "", 0, 0, 0);
12193
12194 get_rule_expr(jexpr->formatted_expr, context, showimplicit);
12195
12197
12198 get_const_expr(root->path->value, context, -1);
12199
12200 appendStringInfo(buf, " AS %s", quote_identifier(root->path->name));
12201
12202 if (jexpr->passing_values)
12203 {
12204 ListCell *lc1,
12205 *lc2;
12206 bool needcomma = false;
12207
12209 appendContextKeyword(context, "PASSING ", 0, 0, 0);
12210
12211 if (PRETTY_INDENT(context))
12212 context->indentLevel += PRETTYINDENT_VAR;
12213
12214 forboth(lc1, jexpr->passing_names,
12215 lc2, jexpr->passing_values)
12216 {
12217 if (needcomma)
12219 needcomma = true;
12220
12221 appendContextKeyword(context, "", 0, 0, 0);
12222
12223 get_rule_expr((Node *) lfirst(lc2), context, false);
12224 appendStringInfo(buf, " AS %s",
12225 quote_identifier((lfirst_node(String, lc1))->sval)
12226 );
12227 }
12228
12229 if (PRETTY_INDENT(context))
12230 context->indentLevel -= PRETTYINDENT_VAR;
12231 }
12232
12233 get_json_table_columns(tf, castNode(JsonTablePathScan, tf->plan), context,
12234 showimplicit);
12235
12237 get_json_behavior(jexpr->on_error, context, "ERROR");
12238
12239 if (PRETTY_INDENT(context))
12240 context->indentLevel -= PRETTYINDENT_VAR;
12241
12242 appendContextKeyword(context, ")", 0, 0, 0);
12243}
12244
12245/* ----------
12246 * get_tablefunc - Parse back a table function
12247 * ----------
12248 */
12249static void
12250get_tablefunc(TableFunc *tf, deparse_context *context, bool showimplicit)
12251{
12252 /* XMLTABLE and JSON_TABLE are the only existing implementations. */
12253
12254 if (tf->functype == TFT_XMLTABLE)
12255 get_xmltable(tf, context, showimplicit);
12256 else if (tf->functype == TFT_JSON_TABLE)
12257 get_json_table(tf, context, showimplicit);
12258}
12259
12260/* ----------
12261 * get_from_clause - Parse back a FROM clause
12262 *
12263 * "prefix" is the keyword that denotes the start of the list of FROM
12264 * elements. It is FROM when used to parse back SELECT and UPDATE, but
12265 * is USING when parsing back DELETE.
12266 * ----------
12267 */
12268static void
12269get_from_clause(Query *query, const char *prefix, deparse_context *context)
12270{
12271 StringInfo buf = context->buf;
12272 bool first = true;
12273 ListCell *l;
12274
12275 /*
12276 * We use the query's jointree as a guide to what to print. However, we
12277 * must ignore auto-added RTEs that are marked not inFromCl. (These can
12278 * only appear at the top level of the jointree, so it's sufficient to
12279 * check here.) This check also ensures we ignore the rule pseudo-RTEs
12280 * for NEW and OLD.
12281 */
12282 foreach(l, query->jointree->fromlist)
12283 {
12284 Node *jtnode = (Node *) lfirst(l);
12285
12286 if (IsA(jtnode, RangeTblRef))
12287 {
12288 int varno = ((RangeTblRef *) jtnode)->rtindex;
12289 RangeTblEntry *rte = rt_fetch(varno, query->rtable);
12290
12291 if (!rte->inFromCl)
12292 continue;
12293 }
12294
12295 if (first)
12296 {
12297 appendContextKeyword(context, prefix,
12299 first = false;
12300
12301 get_from_clause_item(jtnode, query, context);
12302 }
12303 else
12304 {
12305 StringInfoData itembuf;
12306
12308
12309 /*
12310 * Put the new FROM item's text into itembuf so we can decide
12311 * after we've got it whether or not it needs to go on a new line.
12312 */
12313 initStringInfo(&itembuf);
12314 context->buf = &itembuf;
12315
12316 get_from_clause_item(jtnode, query, context);
12317
12318 /* Restore context's output buffer */
12319 context->buf = buf;
12320
12321 /* Consider line-wrapping if enabled */
12322 if (PRETTY_INDENT(context) && context->wrapColumn >= 0)
12323 {
12324 /* Does the new item start with a new line? */
12325 if (itembuf.len > 0 && itembuf.data[0] == '\n')
12326 {
12327 /* If so, we shouldn't add anything */
12328 /* instead, remove any trailing spaces currently in buf */
12330 }
12331 else
12332 {
12333 char *trailing_nl;
12334
12335 /* Locate the start of the current line in the buffer */
12336 trailing_nl = strrchr(buf->data, '\n');
12337 if (trailing_nl == NULL)
12338 trailing_nl = buf->data;
12339 else
12340 trailing_nl++;
12341
12342 /*
12343 * Add a newline, plus some indentation, if the new item
12344 * would cause an overflow.
12345 */
12346 if (strlen(trailing_nl) + itembuf.len > context->wrapColumn)
12350 }
12351 }
12352
12353 /* Add the new item */
12354 appendBinaryStringInfo(buf, itembuf.data, itembuf.len);
12355
12356 /* clean up */
12357 pfree(itembuf.data);
12358 }
12359 }
12360}
12361
12362static void
12364{
12365 StringInfo buf = context->buf;
12367
12368 if (IsA(jtnode, RangeTblRef))
12369 {
12370 int varno = ((RangeTblRef *) jtnode)->rtindex;
12371 RangeTblEntry *rte = rt_fetch(varno, query->rtable);
12372 deparse_columns *colinfo = deparse_columns_fetch(varno, dpns);
12373 RangeTblFunction *rtfunc1 = NULL;
12374
12375 if (rte->lateral)
12376 appendStringInfoString(buf, "LATERAL ");
12377
12378 /* Print the FROM item proper */
12379 switch (rte->rtekind)
12380 {
12381 case RTE_RELATION:
12382 /* Normal relation RTE */
12383 appendStringInfo(buf, "%s%s",
12384 only_marker(rte),
12385 generate_relation_name(rte->relid,
12386 context->namespaces));
12387 break;
12388 case RTE_SUBQUERY:
12389 /* Subquery RTE */
12391 get_query_def(rte->subquery, buf, context->namespaces, NULL,
12392 true,
12393 context->prettyFlags, context->wrapColumn,
12394 context->indentLevel);
12396 break;
12397 case RTE_FUNCTION:
12398 /* Function RTE */
12399 rtfunc1 = (RangeTblFunction *) linitial(rte->functions);
12400
12401 /*
12402 * Omit ROWS FROM() syntax for just one function, unless it
12403 * has both a coldeflist and WITH ORDINALITY. If it has both,
12404 * we must use ROWS FROM() syntax to avoid ambiguity about
12405 * whether the coldeflist includes the ordinality column.
12406 */
12407 if (list_length(rte->functions) == 1 &&
12408 (rtfunc1->funccolnames == NIL || !rte->funcordinality))
12409 {
12410 get_rule_expr_funccall(rtfunc1->funcexpr, context, true);
12411 /* we'll print the coldeflist below, if it has one */
12412 }
12413 else
12414 {
12415 bool all_unnest;
12416 ListCell *lc;
12417
12418 /*
12419 * If all the function calls in the list are to unnest,
12420 * and none need a coldeflist, then collapse the list back
12421 * down to UNNEST(args). (If we had more than one
12422 * built-in unnest function, this would get more
12423 * difficult.)
12424 *
12425 * XXX This is pretty ugly, since it makes not-terribly-
12426 * future-proof assumptions about what the parser would do
12427 * with the output; but the alternative is to emit our
12428 * nonstandard ROWS FROM() notation for what might have
12429 * been a perfectly spec-compliant multi-argument
12430 * UNNEST().
12431 */
12432 all_unnest = true;
12433 foreach(lc, rte->functions)
12434 {
12435 RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
12436
12437 if (!IsA(rtfunc->funcexpr, FuncExpr) ||
12438 ((FuncExpr *) rtfunc->funcexpr)->funcid != F_UNNEST_ANYARRAY ||
12439 rtfunc->funccolnames != NIL)
12440 {
12441 all_unnest = false;
12442 break;
12443 }
12444 }
12445
12446 if (all_unnest)
12447 {
12448 List *allargs = NIL;
12449
12450 foreach(lc, rte->functions)
12451 {
12452 RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
12453 List *args = ((FuncExpr *) rtfunc->funcexpr)->args;
12454
12455 allargs = list_concat(allargs, args);
12456 }
12457
12458 appendStringInfoString(buf, "UNNEST(");
12459 get_rule_expr((Node *) allargs, context, true);
12461 }
12462 else
12463 {
12464 int funcno = 0;
12465
12466 appendStringInfoString(buf, "ROWS FROM(");
12467 foreach(lc, rte->functions)
12468 {
12469 RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
12470
12471 if (funcno > 0)
12473 get_rule_expr_funccall(rtfunc->funcexpr, context, true);
12474 if (rtfunc->funccolnames != NIL)
12475 {
12476 /* Reconstruct the column definition list */
12477 appendStringInfoString(buf, " AS ");
12479 NULL,
12480 context);
12481 }
12482 funcno++;
12483 }
12485 }
12486 /* prevent printing duplicate coldeflist below */
12487 rtfunc1 = NULL;
12488 }
12489 if (rte->funcordinality)
12490 appendStringInfoString(buf, " WITH ORDINALITY");
12491 break;
12492 case RTE_TABLEFUNC:
12493 get_tablefunc(rte->tablefunc, context, true);
12494 break;
12495 case RTE_VALUES:
12496 /* Values list RTE */
12498 get_values_def(rte->values_lists, context);
12500 break;
12501 case RTE_CTE:
12503 break;
12504 default:
12505 elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
12506 break;
12507 }
12508
12509 /* Print the relation alias, if needed */
12510 get_rte_alias(rte, varno, false, context);
12511
12512 /* Print the column definitions or aliases, if needed */
12513 if (rtfunc1 && rtfunc1->funccolnames != NIL)
12514 {
12515 /* Reconstruct the columndef list, which is also the aliases */
12516 get_from_clause_coldeflist(rtfunc1, colinfo, context);
12517 }
12518 else
12519 {
12520 /* Else print column aliases as needed */
12521 get_column_alias_list(colinfo, context);
12522 }
12523
12524 /* Tablesample clause must go after any alias */
12525 if (rte->rtekind == RTE_RELATION && rte->tablesample)
12526 get_tablesample_def(rte->tablesample, context);
12527 }
12528 else if (IsA(jtnode, JoinExpr))
12529 {
12530 JoinExpr *j = (JoinExpr *) jtnode;
12531 deparse_columns *colinfo = deparse_columns_fetch(j->rtindex, dpns);
12532 bool need_paren_on_right;
12533
12534 need_paren_on_right = PRETTY_PAREN(context) &&
12535 !IsA(j->rarg, RangeTblRef) &&
12536 !(IsA(j->rarg, JoinExpr) && ((JoinExpr *) j->rarg)->alias != NULL);
12537
12538 if (!PRETTY_PAREN(context) || j->alias != NULL)
12540
12541 get_from_clause_item(j->larg, query, context);
12542
12543 switch (j->jointype)
12544 {
12545 case JOIN_INNER:
12546 if (j->quals)
12547 appendContextKeyword(context, " JOIN ",
12551 else
12552 appendContextKeyword(context, " CROSS JOIN ",
12556 break;
12557 case JOIN_LEFT:
12558 appendContextKeyword(context, " LEFT JOIN ",
12562 break;
12563 case JOIN_FULL:
12564 appendContextKeyword(context, " FULL JOIN ",
12568 break;
12569 case JOIN_RIGHT:
12570 appendContextKeyword(context, " RIGHT JOIN ",
12574 break;
12575 default:
12576 elog(ERROR, "unrecognized join type: %d",
12577 (int) j->jointype);
12578 }
12579
12580 if (need_paren_on_right)
12582 get_from_clause_item(j->rarg, query, context);
12583 if (need_paren_on_right)
12585
12586 if (j->usingClause)
12587 {
12588 ListCell *lc;
12589 bool first = true;
12590
12591 appendStringInfoString(buf, " USING (");
12592 /* Use the assigned names, not what's in usingClause */
12593 foreach(lc, colinfo->usingNames)
12594 {
12595 char *colname = (char *) lfirst(lc);
12596
12597 if (first)
12598 first = false;
12599 else
12602 }
12604
12605 if (j->join_using_alias)
12606 appendStringInfo(buf, " AS %s",
12607 quote_identifier(j->join_using_alias->aliasname));
12608 }
12609 else if (j->quals)
12610 {
12611 appendStringInfoString(buf, " ON ");
12612 if (!PRETTY_PAREN(context))
12614 get_rule_expr(j->quals, context, false);
12615 if (!PRETTY_PAREN(context))
12617 }
12618 else if (j->jointype != JOIN_INNER)
12619 {
12620 /* If we didn't say CROSS JOIN above, we must provide an ON */
12621 appendStringInfoString(buf, " ON TRUE");
12622 }
12623
12624 if (!PRETTY_PAREN(context) || j->alias != NULL)
12626
12627 /* Yes, it's correct to put alias after the right paren ... */
12628 if (j->alias != NULL)
12629 {
12630 /*
12631 * Note that it's correct to emit an alias clause if and only if
12632 * there was one originally. Otherwise we'd be converting a named
12633 * join to unnamed or vice versa, which creates semantic
12634 * subtleties we don't want. However, we might print a different
12635 * alias name than was there originally.
12636 */
12637 appendStringInfo(buf, " %s",
12639 context)));
12640 get_column_alias_list(colinfo, context);
12641 }
12642 }
12643 else
12644 elog(ERROR, "unrecognized node type: %d",
12645 (int) nodeTag(jtnode));
12646}
12647
12648/*
12649 * get_rte_alias - print the relation's alias, if needed
12650 *
12651 * If printed, the alias is preceded by a space, or by " AS " if use_as is true.
12652 */
12653static void
12654get_rte_alias(RangeTblEntry *rte, int varno, bool use_as,
12655 deparse_context *context)
12656{
12658 char *refname = get_rtable_name(varno, context);
12659 deparse_columns *colinfo = deparse_columns_fetch(varno, dpns);
12660 bool printalias = false;
12661
12662 if (rte->alias != NULL)
12663 {
12664 /* Always print alias if user provided one */
12665 printalias = true;
12666 }
12667 else if (colinfo->printaliases)
12668 {
12669 /* Always print alias if we need to print column aliases */
12670 printalias = true;
12671 }
12672 else if (rte->rtekind == RTE_RELATION)
12673 {
12674 /*
12675 * No need to print alias if it's same as relation name (this would
12676 * normally be the case, but not if set_rtable_names had to resolve a
12677 * conflict).
12678 */
12679 if (strcmp(refname, get_relation_name(rte->relid)) != 0)
12680 printalias = true;
12681 }
12682 else if (rte->rtekind == RTE_FUNCTION)
12683 {
12684 /*
12685 * For a function RTE, always print alias. This covers possible
12686 * renaming of the function and/or instability of the FigureColname
12687 * rules for things that aren't simple functions. Note we'd need to
12688 * force it anyway for the columndef list case.
12689 */
12690 printalias = true;
12691 }
12692 else if (rte->rtekind == RTE_SUBQUERY ||
12693 rte->rtekind == RTE_VALUES)
12694 {
12695 /*
12696 * For a subquery, always print alias. This makes the output
12697 * SQL-spec-compliant, even though we allow such aliases to be omitted
12698 * on input.
12699 */
12700 printalias = true;
12701 }
12702 else if (rte->rtekind == RTE_CTE)
12703 {
12704 /*
12705 * No need to print alias if it's same as CTE name (this would
12706 * normally be the case, but not if set_rtable_names had to resolve a
12707 * conflict).
12708 */
12709 if (strcmp(refname, rte->ctename) != 0)
12710 printalias = true;
12711 }
12712
12713 if (printalias)
12714 appendStringInfo(context->buf, "%s%s",
12715 use_as ? " AS " : " ",
12716 quote_identifier(refname));
12717}
12718
12719/*
12720 * get_column_alias_list - print column alias list for an RTE
12721 *
12722 * Caller must already have printed the relation's alias name.
12723 */
12724static void
12726{
12727 StringInfo buf = context->buf;
12728 int i;
12729 bool first = true;
12730
12731 /* Don't print aliases if not needed */
12732 if (!colinfo->printaliases)
12733 return;
12734
12735 for (i = 0; i < colinfo->num_new_cols; i++)
12736 {
12737 char *colname = colinfo->new_colnames[i];
12738
12739 if (first)
12740 {
12742 first = false;
12743 }
12744 else
12747 }
12748 if (!first)
12750}
12751
12752/*
12753 * get_from_clause_coldeflist - reproduce FROM clause coldeflist
12754 *
12755 * When printing a top-level coldeflist (which is syntactically also the
12756 * relation's column alias list), use column names from colinfo. But when
12757 * printing a coldeflist embedded inside ROWS FROM(), we prefer to use the
12758 * original coldeflist's names, which are available in rtfunc->funccolnames.
12759 * Pass NULL for colinfo to select the latter behavior.
12760 *
12761 * The coldeflist is appended immediately (no space) to buf. Caller is
12762 * responsible for ensuring that an alias or AS is present before it.
12763 */
12764static void
12766 deparse_columns *colinfo,
12767 deparse_context *context)
12768{
12769 StringInfo buf = context->buf;
12770 ListCell *l1;
12771 ListCell *l2;
12772 ListCell *l3;
12773 ListCell *l4;
12774 int i;
12775
12777
12778 i = 0;
12779 forfour(l1, rtfunc->funccoltypes,
12780 l2, rtfunc->funccoltypmods,
12781 l3, rtfunc->funccolcollations,
12782 l4, rtfunc->funccolnames)
12783 {
12784 Oid atttypid = lfirst_oid(l1);
12785 int32 atttypmod = lfirst_int(l2);
12786 Oid attcollation = lfirst_oid(l3);
12787 char *attname;
12788
12789 if (colinfo)
12790 attname = colinfo->colnames[i];
12791 else
12792 attname = strVal(lfirst(l4));
12793
12794 Assert(attname); /* shouldn't be any dropped columns here */
12795
12796 if (i > 0)
12798 appendStringInfo(buf, "%s %s",
12800 format_type_with_typemod(atttypid, atttypmod));
12801 if (OidIsValid(attcollation) &&
12802 attcollation != get_typcollation(atttypid))
12803 appendStringInfo(buf, " COLLATE %s",
12804 generate_collation_name(attcollation));
12805
12806 i++;
12807 }
12808
12810}
12811
12812/*
12813 * get_tablesample_def - print a TableSampleClause
12814 */
12815static void
12817{
12818 StringInfo buf = context->buf;
12819 Oid argtypes[1];
12820 int nargs;
12821 ListCell *l;
12822
12823 /*
12824 * We should qualify the handler's function name if it wouldn't be
12825 * resolved by lookup in the current search path.
12826 */
12827 argtypes[0] = INTERNALOID;
12828 appendStringInfo(buf, " TABLESAMPLE %s (",
12829 generate_function_name(tablesample->tsmhandler, 1,
12830 NIL, argtypes,
12831 false, NULL, false));
12832
12833 nargs = 0;
12834 foreach(l, tablesample->args)
12835 {
12836 if (nargs++ > 0)
12838 get_rule_expr((Node *) lfirst(l), context, false);
12839 }
12841
12842 if (tablesample->repeatable != NULL)
12843 {
12844 appendStringInfoString(buf, " REPEATABLE (");
12845 get_rule_expr((Node *) tablesample->repeatable, context, false);
12847 }
12848}
12849
12850/*
12851 * get_opclass_name - fetch name of an index operator class
12852 *
12853 * The opclass name is appended (after a space) to buf.
12854 *
12855 * Output is suppressed if the opclass is the default for the given
12856 * actual_datatype. (If you don't want this behavior, just pass
12857 * InvalidOid for actual_datatype.)
12858 */
12859static void
12860get_opclass_name(Oid opclass, Oid actual_datatype,
12862{
12863 HeapTuple ht_opc;
12864 Form_pg_opclass opcrec;
12865 char *opcname;
12866 char *nspname;
12867
12868 ht_opc = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
12869 if (!HeapTupleIsValid(ht_opc))
12870 elog(ERROR, "cache lookup failed for opclass %u", opclass);
12871 opcrec = (Form_pg_opclass) GETSTRUCT(ht_opc);
12872
12873 if (!OidIsValid(actual_datatype) ||
12874 GetDefaultOpClass(actual_datatype, opcrec->opcmethod) != opclass)
12875 {
12876 /* Okay, we need the opclass name. Do we need to qualify it? */
12877 opcname = NameStr(opcrec->opcname);
12878 if (OpclassIsVisible(opclass))
12879 appendStringInfo(buf, " %s", quote_identifier(opcname));
12880 else
12881 {
12882 nspname = get_namespace_name_or_temp(opcrec->opcnamespace);
12883 appendStringInfo(buf, " %s.%s",
12884 quote_identifier(nspname),
12885 quote_identifier(opcname));
12886 }
12887 }
12888 ReleaseSysCache(ht_opc);
12889}
12890
12891/*
12892 * generate_opclass_name
12893 * Compute the name to display for an opclass specified by OID
12894 *
12895 * The result includes all necessary quoting and schema-prefixing.
12896 */
12897char *
12899{
12901
12903 get_opclass_name(opclass, InvalidOid, &buf);
12904
12905 return &buf.data[1]; /* get_opclass_name() prepends space */
12906}
12907
12908/*
12909 * processIndirection - take care of array and subfield assignment
12910 *
12911 * We strip any top-level FieldStore or assignment SubscriptingRef nodes that
12912 * appear in the input, printing them as decoration for the base column
12913 * name (which we assume the caller just printed). We might also need to
12914 * strip CoerceToDomain nodes, but only ones that appear above assignment
12915 * nodes.
12916 *
12917 * Returns the subexpression that's to be assigned.
12918 */
12919static Node *
12921{
12922 StringInfo buf = context->buf;
12923 CoerceToDomain *cdomain = NULL;
12924
12925 for (;;)
12926 {
12927 if (node == NULL)
12928 break;
12929 if (IsA(node, FieldStore))
12930 {
12931 FieldStore *fstore = (FieldStore *) node;
12932 Oid typrelid;
12933 char *fieldname;
12934
12935 /* lookup tuple type */
12936 typrelid = get_typ_typrelid(fstore->resulttype);
12937 if (!OidIsValid(typrelid))
12938 elog(ERROR, "argument type %s of FieldStore is not a tuple type",
12939 format_type_be(fstore->resulttype));
12940
12941 /*
12942 * Print the field name. There should only be one target field in
12943 * stored rules. There could be more than that in executable
12944 * target lists, but this function cannot be used for that case.
12945 */
12946 Assert(list_length(fstore->fieldnums) == 1);
12947 fieldname = get_attname(typrelid,
12948 linitial_int(fstore->fieldnums), false);
12949 appendStringInfo(buf, ".%s", quote_identifier(fieldname));
12950
12951 /*
12952 * We ignore arg since it should be an uninteresting reference to
12953 * the target column or subcolumn.
12954 */
12955 node = (Node *) linitial(fstore->newvals);
12956 }
12957 else if (IsA(node, SubscriptingRef))
12958 {
12959 SubscriptingRef *sbsref = (SubscriptingRef *) node;
12960
12961 if (sbsref->refassgnexpr == NULL)
12962 break;
12963
12964 printSubscripts(sbsref, context);
12965
12966 /*
12967 * We ignore refexpr since it should be an uninteresting reference
12968 * to the target column or subcolumn.
12969 */
12970 node = (Node *) sbsref->refassgnexpr;
12971 }
12972 else if (IsA(node, CoerceToDomain))
12973 {
12974 cdomain = (CoerceToDomain *) node;
12975 /* If it's an explicit domain coercion, we're done */
12976 if (cdomain->coercionformat != COERCE_IMPLICIT_CAST)
12977 break;
12978 /* Tentatively descend past the CoerceToDomain */
12979 node = (Node *) cdomain->arg;
12980 }
12981 else
12982 break;
12983 }
12984
12985 /*
12986 * If we descended past a CoerceToDomain whose argument turned out not to
12987 * be a FieldStore or array assignment, back up to the CoerceToDomain.
12988 * (This is not enough to be fully correct if there are nested implicit
12989 * CoerceToDomains, but such cases shouldn't ever occur.)
12990 */
12991 if (cdomain && node == (Node *) cdomain->arg)
12992 node = (Node *) cdomain;
12993
12994 return node;
12995}
12996
12997static void
12999{
13000 StringInfo buf = context->buf;
13001 ListCell *lowlist_item;
13002 ListCell *uplist_item;
13003
13004 lowlist_item = list_head(sbsref->reflowerindexpr); /* could be NULL */
13005 foreach(uplist_item, sbsref->refupperindexpr)
13006 {
13008 if (lowlist_item)
13009 {
13010 /* If subexpression is NULL, get_rule_expr prints nothing */
13011 get_rule_expr((Node *) lfirst(lowlist_item), context, false);
13013 lowlist_item = lnext(sbsref->reflowerindexpr, lowlist_item);
13014 }
13015 /* If subexpression is NULL, get_rule_expr prints nothing */
13016 get_rule_expr((Node *) lfirst(uplist_item), context, false);
13018 }
13019}
13020
13021/*
13022 * quote_identifier - Quote an identifier only if needed
13023 *
13024 * When quotes are needed, we palloc the required space; slightly
13025 * space-wasteful but well worth it for notational simplicity.
13026 */
13027const char *
13029{
13030 /*
13031 * Can avoid quoting if ident starts with a lowercase letter or underscore
13032 * and contains only lowercase letters, digits, and underscores, *and* is
13033 * not any SQL keyword. Otherwise, supply quotes.
13034 */
13035 int nquotes = 0;
13036 bool safe;
13037 const char *ptr;
13038 char *result;
13039 char *optr;
13040
13041 /*
13042 * would like to use <ctype.h> macros here, but they might yield unwanted
13043 * locale-specific results...
13044 */
13045 safe = ((ident[0] >= 'a' && ident[0] <= 'z') || ident[0] == '_');
13046
13047 for (ptr = ident; *ptr; ptr++)
13048 {
13049 char ch = *ptr;
13050
13051 if ((ch >= 'a' && ch <= 'z') ||
13052 (ch >= '0' && ch <= '9') ||
13053 (ch == '_'))
13054 {
13055 /* okay */
13056 }
13057 else
13058 {
13059 safe = false;
13060 if (ch == '"')
13061 nquotes++;
13062 }
13063 }
13064
13066 safe = false;
13067
13068 if (safe)
13069 {
13070 /*
13071 * Check for keyword. We quote keywords except for unreserved ones.
13072 * (In some cases we could avoid quoting a col_name or type_func_name
13073 * keyword, but it seems much harder than it's worth to tell that.)
13074 *
13075 * Note: ScanKeywordLookup() does case-insensitive comparison, but
13076 * that's fine, since we already know we have all-lower-case.
13077 */
13078 int kwnum = ScanKeywordLookup(ident, &ScanKeywords);
13079
13080 if (kwnum >= 0 && ScanKeywordCategories[kwnum] != UNRESERVED_KEYWORD)
13081 safe = false;
13082 }
13083
13084 if (safe)
13085 return ident; /* no change needed */
13086
13087 result = (char *) palloc(strlen(ident) + nquotes + 2 + 1);
13088
13089 optr = result;
13090 *optr++ = '"';
13091 for (ptr = ident; *ptr; ptr++)
13092 {
13093 char ch = *ptr;
13094
13095 if (ch == '"')
13096 *optr++ = '"';
13097 *optr++ = ch;
13098 }
13099 *optr++ = '"';
13100 *optr = '\0';
13101
13102 return result;
13103}
13104
13105/*
13106 * quote_qualified_identifier - Quote a possibly-qualified identifier
13107 *
13108 * Return a name of the form qualifier.ident, or just ident if qualifier
13109 * is NULL, quoting each component if necessary. The result is palloc'd.
13110 */
13111char *
13112quote_qualified_identifier(const char *qualifier,
13113 const char *ident)
13114{
13116
13118 if (qualifier)
13119 appendStringInfo(&buf, "%s.", quote_identifier(qualifier));
13121 return buf.data;
13122}
13123
13124/*
13125 * get_relation_name
13126 * Get the unqualified name of a relation specified by OID
13127 *
13128 * This differs from the underlying get_rel_name() function in that it will
13129 * throw error instead of silently returning NULL if the OID is bad.
13130 */
13131static char *
13133{
13134 char *relname = get_rel_name(relid);
13135
13136 if (!relname)
13137 elog(ERROR, "cache lookup failed for relation %u", relid);
13138 return relname;
13139}
13140
13141/*
13142 * generate_relation_name
13143 * Compute the name to display for a relation specified by OID
13144 *
13145 * The result includes all necessary quoting and schema-prefixing.
13146 *
13147 * If namespaces isn't NIL, it must be a list of deparse_namespace nodes.
13148 * We will forcibly qualify the relation name if it equals any CTE name
13149 * visible in the namespace list.
13150 */
13151static char *
13153{
13154 HeapTuple tp;
13155 Form_pg_class reltup;
13156 bool need_qual;
13157 ListCell *nslist;
13158 char *relname;
13159 char *nspname;
13160 char *result;
13161
13162 tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
13163 if (!HeapTupleIsValid(tp))
13164 elog(ERROR, "cache lookup failed for relation %u", relid);
13165 reltup = (Form_pg_class) GETSTRUCT(tp);
13166 relname = NameStr(reltup->relname);
13167
13168 /* Check for conflicting CTE name */
13169 need_qual = false;
13170 foreach(nslist, namespaces)
13171 {
13172 deparse_namespace *dpns = (deparse_namespace *) lfirst(nslist);
13173 ListCell *ctlist;
13174
13175 foreach(ctlist, dpns->ctes)
13176 {
13177 CommonTableExpr *cte = (CommonTableExpr *) lfirst(ctlist);
13178
13179 if (strcmp(cte->ctename, relname) == 0)
13180 {
13181 need_qual = true;
13182 break;
13183 }
13184 }
13185 if (need_qual)
13186 break;
13187 }
13188
13189 /* Otherwise, qualify the name if not visible in search path */
13190 if (!need_qual)
13191 need_qual = !RelationIsVisible(relid);
13192
13193 if (need_qual)
13194 nspname = get_namespace_name_or_temp(reltup->relnamespace);
13195 else
13196 nspname = NULL;
13197
13198 result = quote_qualified_identifier(nspname, relname);
13199
13200 ReleaseSysCache(tp);
13201
13202 return result;
13203}
13204
13205/*
13206 * generate_qualified_relation_name
13207 * Compute the name to display for a relation specified by OID
13208 *
13209 * As above, but unconditionally schema-qualify the name.
13210 */
13211static char *
13213{
13214 HeapTuple tp;
13215 Form_pg_class reltup;
13216 char *relname;
13217 char *nspname;
13218 char *result;
13219
13220 tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
13221 if (!HeapTupleIsValid(tp))
13222 elog(ERROR, "cache lookup failed for relation %u", relid);
13223 reltup = (Form_pg_class) GETSTRUCT(tp);
13224 relname = NameStr(reltup->relname);
13225
13226 nspname = get_namespace_name_or_temp(reltup->relnamespace);
13227 if (!nspname)
13228 elog(ERROR, "cache lookup failed for namespace %u",
13229 reltup->relnamespace);
13230
13231 result = quote_qualified_identifier(nspname, relname);
13232
13233 ReleaseSysCache(tp);
13234
13235 return result;
13236}
13237
13238/*
13239 * generate_function_name
13240 * Compute the name to display for a function specified by OID,
13241 * given that it is being called with the specified actual arg names and
13242 * types. (Those matter because of ambiguous-function resolution rules.)
13243 *
13244 * If we're dealing with a potentially variadic function (in practice, this
13245 * means a FuncExpr or Aggref, not some other way of calling a function), then
13246 * has_variadic must specify whether variadic arguments have been merged,
13247 * and *use_variadic_p will be set to indicate whether to print VARIADIC in
13248 * the output. For non-FuncExpr cases, has_variadic should be false and
13249 * use_variadic_p can be NULL.
13250 *
13251 * inGroupBy must be true if we're deparsing a GROUP BY clause.
13252 *
13253 * The result includes all necessary quoting and schema-prefixing.
13254 */
13255static char *
13256generate_function_name(Oid funcid, int nargs, List *argnames, Oid *argtypes,
13257 bool has_variadic, bool *use_variadic_p,
13258 bool inGroupBy)
13259{
13260 char *result;
13261 HeapTuple proctup;
13262 Form_pg_proc procform;
13263 char *proname;
13264 bool use_variadic;
13265 char *nspname;
13266 FuncDetailCode p_result;
13267 int fgc_flags;
13268 Oid p_funcid;
13269 Oid p_rettype;
13270 bool p_retset;
13271 int p_nvargs;
13272 Oid p_vatype;
13273 Oid *p_true_typeids;
13274 bool force_qualify = false;
13275
13276 proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
13277 if (!HeapTupleIsValid(proctup))
13278 elog(ERROR, "cache lookup failed for function %u", funcid);
13279 procform = (Form_pg_proc) GETSTRUCT(proctup);
13280 proname = NameStr(procform->proname);
13281
13282 /*
13283 * Due to parser hacks to avoid needing to reserve CUBE, we need to force
13284 * qualification of some function names within GROUP BY.
13285 */
13286 if (inGroupBy)
13287 {
13288 if (strcmp(proname, "cube") == 0 || strcmp(proname, "rollup") == 0)
13289 force_qualify = true;
13290 }
13291
13292 /*
13293 * Determine whether VARIADIC should be printed. We must do this first
13294 * since it affects the lookup rules in func_get_detail().
13295 *
13296 * We always print VARIADIC if the function has a merged variadic-array
13297 * argument. Note that this is always the case for functions taking a
13298 * VARIADIC argument type other than VARIADIC ANY. If we omitted VARIADIC
13299 * and printed the array elements as separate arguments, the call could
13300 * match a newer non-VARIADIC function.
13301 */
13302 if (use_variadic_p)
13303 {
13304 /* Parser should not have set funcvariadic unless fn is variadic */
13305 Assert(!has_variadic || OidIsValid(procform->provariadic));
13306 use_variadic = has_variadic;
13307 *use_variadic_p = use_variadic;
13308 }
13309 else
13310 {
13311 Assert(!has_variadic);
13312 use_variadic = false;
13313 }
13314
13315 /*
13316 * The idea here is to schema-qualify only if the parser would fail to
13317 * resolve the correct function given the unqualified func name with the
13318 * specified argtypes and VARIADIC flag. But if we already decided to
13319 * force qualification, then we can skip the lookup and pretend we didn't
13320 * find it.
13321 */
13322 if (!force_qualify)
13324 NIL, argnames, nargs, argtypes,
13325 !use_variadic, true, false,
13326 &fgc_flags,
13327 &p_funcid, &p_rettype,
13328 &p_retset, &p_nvargs, &p_vatype,
13329 &p_true_typeids, NULL);
13330 else
13331 {
13332 p_result = FUNCDETAIL_NOTFOUND;
13333 p_funcid = InvalidOid;
13334 }
13335
13336 if ((p_result == FUNCDETAIL_NORMAL ||
13337 p_result == FUNCDETAIL_AGGREGATE ||
13338 p_result == FUNCDETAIL_WINDOWFUNC) &&
13339 p_funcid == funcid)
13340 nspname = NULL;
13341 else
13342 nspname = get_namespace_name_or_temp(procform->pronamespace);
13343
13344 result = quote_qualified_identifier(nspname, proname);
13345
13346 ReleaseSysCache(proctup);
13347
13348 return result;
13349}
13350
13351/*
13352 * generate_operator_name
13353 * Compute the name to display for an operator specified by OID,
13354 * given that it is being called with the specified actual arg types.
13355 * (Arg types matter because of ambiguous-operator resolution rules.
13356 * Pass InvalidOid for unused arg of a unary operator.)
13357 *
13358 * The result includes all necessary quoting and schema-prefixing,
13359 * plus the OPERATOR() decoration needed to use a qualified operator name
13360 * in an expression.
13361 */
13362static char *
13364{
13366 HeapTuple opertup;
13367 Form_pg_operator operform;
13368 char *oprname;
13369 char *nspname;
13370 Operator p_result;
13371
13373
13374 opertup = SearchSysCache1(OPEROID, ObjectIdGetDatum(operid));
13375 if (!HeapTupleIsValid(opertup))
13376 elog(ERROR, "cache lookup failed for operator %u", operid);
13377 operform = (Form_pg_operator) GETSTRUCT(opertup);
13378 oprname = NameStr(operform->oprname);
13379
13380 /*
13381 * The idea here is to schema-qualify only if the parser would fail to
13382 * resolve the correct operator given the unqualified op name with the
13383 * specified argtypes.
13384 */
13385 switch (operform->oprkind)
13386 {
13387 case 'b':
13388 p_result = oper(NULL, list_make1(makeString(oprname)), arg1, arg2,
13389 true, -1);
13390 break;
13391 case 'l':
13392 p_result = left_oper(NULL, list_make1(makeString(oprname)), arg2,
13393 true, -1);
13394 break;
13395 default:
13396 elog(ERROR, "unrecognized oprkind: %d", operform->oprkind);
13397 p_result = NULL; /* keep compiler quiet */
13398 break;
13399 }
13400
13401 if (p_result != NULL && oprid(p_result) == operid)
13402 nspname = NULL;
13403 else
13404 {
13405 nspname = get_namespace_name_or_temp(operform->oprnamespace);
13406 appendStringInfo(&buf, "OPERATOR(%s.", quote_identifier(nspname));
13407 }
13408
13409 appendStringInfoString(&buf, oprname);
13410
13411 if (nspname)
13413
13414 if (p_result != NULL)
13415 ReleaseSysCache(p_result);
13416
13417 ReleaseSysCache(opertup);
13418
13419 return buf.data;
13420}
13421
13422/*
13423 * generate_operator_clause --- generate a binary-operator WHERE clause
13424 *
13425 * This is used for internally-generated-and-executed SQL queries, where
13426 * precision is essential and readability is secondary. The basic
13427 * requirement is to append "leftop op rightop" to buf, where leftop and
13428 * rightop are given as strings and are assumed to yield types leftoptype
13429 * and rightoptype; the operator is identified by OID. The complexity
13430 * comes from needing to be sure that the parser will select the desired
13431 * operator when the query is parsed. We always name the operator using
13432 * OPERATOR(schema.op) syntax, so as to avoid search-path uncertainties.
13433 * We have to emit casts too, if either input isn't already the input type
13434 * of the operator; else we are at the mercy of the parser's heuristics for
13435 * ambiguous-operator resolution. The caller must ensure that leftop and
13436 * rightop are suitable arguments for a cast operation; it's best to insert
13437 * parentheses if they aren't just variables or parameters.
13438 */
13439void
13441 const char *leftop, Oid leftoptype,
13442 Oid opoid,
13443 const char *rightop, Oid rightoptype)
13444{
13445 HeapTuple opertup;
13446 Form_pg_operator operform;
13447 char *oprname;
13448 char *nspname;
13449
13450 opertup = SearchSysCache1(OPEROID, ObjectIdGetDatum(opoid));
13451 if (!HeapTupleIsValid(opertup))
13452 elog(ERROR, "cache lookup failed for operator %u", opoid);
13453 operform = (Form_pg_operator) GETSTRUCT(opertup);
13454 Assert(operform->oprkind == 'b');
13455 oprname = NameStr(operform->oprname);
13456
13457 nspname = get_namespace_name(operform->oprnamespace);
13458
13459 appendStringInfoString(buf, leftop);
13460 if (leftoptype != operform->oprleft)
13461 add_cast_to(buf, operform->oprleft);
13462 appendStringInfo(buf, " OPERATOR(%s.", quote_identifier(nspname));
13463 appendStringInfoString(buf, oprname);
13464 appendStringInfo(buf, ") %s", rightop);
13465 if (rightoptype != operform->oprright)
13466 add_cast_to(buf, operform->oprright);
13467
13468 ReleaseSysCache(opertup);
13469}
13470
13471/*
13472 * Add a cast specification to buf. We spell out the type name the hard way,
13473 * intentionally not using format_type_be(). This is to avoid corner cases
13474 * for CHARACTER, BIT, and perhaps other types, where specifying the type
13475 * using SQL-standard syntax results in undesirable data truncation. By
13476 * doing it this way we can be certain that the cast will have default (-1)
13477 * target typmod.
13478 */
13479static void
13481{
13482 HeapTuple typetup;
13483 Form_pg_type typform;
13484 char *typname;
13485 char *nspname;
13486
13487 typetup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
13488 if (!HeapTupleIsValid(typetup))
13489 elog(ERROR, "cache lookup failed for type %u", typid);
13490 typform = (Form_pg_type) GETSTRUCT(typetup);
13491
13492 typname = NameStr(typform->typname);
13493 nspname = get_namespace_name_or_temp(typform->typnamespace);
13494
13495 appendStringInfo(buf, "::%s.%s",
13497
13498 ReleaseSysCache(typetup);
13499}
13500
13501/*
13502 * generate_qualified_type_name
13503 * Compute the name to display for a type specified by OID
13504 *
13505 * This is different from format_type_be() in that we unconditionally
13506 * schema-qualify the name. That also means no special syntax for
13507 * SQL-standard type names ... although in current usage, this should
13508 * only get used for domains, so such cases wouldn't occur anyway.
13509 */
13510static char *
13512{
13513 HeapTuple tp;
13514 Form_pg_type typtup;
13515 char *typname;
13516 char *nspname;
13517 char *result;
13518
13519 tp = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
13520 if (!HeapTupleIsValid(tp))
13521 elog(ERROR, "cache lookup failed for type %u", typid);
13522 typtup = (Form_pg_type) GETSTRUCT(tp);
13523 typname = NameStr(typtup->typname);
13524
13525 nspname = get_namespace_name_or_temp(typtup->typnamespace);
13526 if (!nspname)
13527 elog(ERROR, "cache lookup failed for namespace %u",
13528 typtup->typnamespace);
13529
13530 result = quote_qualified_identifier(nspname, typname);
13531
13532 ReleaseSysCache(tp);
13533
13534 return result;
13535}
13536
13537/*
13538 * generate_collation_name
13539 * Compute the name to display for a collation specified by OID
13540 *
13541 * The result includes all necessary quoting and schema-prefixing.
13542 */
13543char *
13545{
13546 HeapTuple tp;
13547 Form_pg_collation colltup;
13548 char *collname;
13549 char *nspname;
13550 char *result;
13551
13552 tp = SearchSysCache1(COLLOID, ObjectIdGetDatum(collid));
13553 if (!HeapTupleIsValid(tp))
13554 elog(ERROR, "cache lookup failed for collation %u", collid);
13555 colltup = (Form_pg_collation) GETSTRUCT(tp);
13556 collname = NameStr(colltup->collname);
13557
13559 nspname = get_namespace_name_or_temp(colltup->collnamespace);
13560 else
13561 nspname = NULL;
13562
13563 result = quote_qualified_identifier(nspname, collname);
13564
13565 ReleaseSysCache(tp);
13566
13567 return result;
13568}
13569
13570/*
13571 * Given a C string, produce a TEXT datum.
13572 *
13573 * We assume that the input was palloc'd and may be freed.
13574 */
13575static text *
13577{
13578 text *result;
13579
13580 result = cstring_to_text(str);
13581 pfree(str);
13582 return result;
13583}
13584
13585/*
13586 * Generate a C string representing a relation options from text[] datum.
13587 */
13588static void
13590{
13591 Datum *options;
13592 int noptions;
13593 int i;
13594
13595 deconstruct_array_builtin(DatumGetArrayTypeP(reloptions), TEXTOID,
13596 &options, NULL, &noptions);
13597
13598 for (i = 0; i < noptions; i++)
13599 {
13601 char *name;
13602 char *separator;
13603 char *value;
13604
13605 /*
13606 * Each array element should have the form name=value. If the "=" is
13607 * missing for some reason, treat it like an empty value.
13608 */
13609 name = option;
13610 separator = strchr(option, '=');
13611 if (separator)
13612 {
13613 *separator = '\0';
13614 value = separator + 1;
13615 }
13616 else
13617 value = "";
13618
13619 if (i > 0)
13622
13623 /*
13624 * In general we need to quote the value; but to avoid unnecessary
13625 * clutter, do not quote if it is an identifier that would not need
13626 * quoting. (We could also allow numbers, but that is a bit trickier
13627 * than it looks --- for example, are leading zeroes significant? We
13628 * don't want to assume very much here about what custom reloptions
13629 * might mean.)
13630 */
13633 else
13635
13636 pfree(option);
13637 }
13638}
13639
13640/*
13641 * Generate a C string representing a relation's reloptions, or NULL if none.
13642 */
13643static char *
13645{
13646 char *result = NULL;
13647 HeapTuple tuple;
13648 Datum reloptions;
13649 bool isnull;
13650
13651 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
13652 if (!HeapTupleIsValid(tuple))
13653 elog(ERROR, "cache lookup failed for relation %u", relid);
13654
13655 reloptions = SysCacheGetAttr(RELOID, tuple,
13656 Anum_pg_class_reloptions, &isnull);
13657 if (!isnull)
13658 {
13660
13662 get_reloptions(&buf, reloptions);
13663
13664 result = buf.data;
13665 }
13666
13667 ReleaseSysCache(tuple);
13668
13669 return result;
13670}
13671
13672/*
13673 * get_range_partbound_string
13674 * A C string representation of one range partition bound
13675 */
13676char *
13678{
13679 deparse_context context;
13681 ListCell *cell;
13682 char *sep;
13683
13684 memset(&context, 0, sizeof(deparse_context));
13685 context.buf = buf;
13686
13688 sep = "";
13689 foreach(cell, bound_datums)
13690 {
13691 PartitionRangeDatum *datum =
13693
13696 appendStringInfoString(buf, "MINVALUE");
13697 else if (datum->kind == PARTITION_RANGE_DATUM_MAXVALUE)
13698 appendStringInfoString(buf, "MAXVALUE");
13699 else
13700 {
13701 Const *val = castNode(Const, datum->value);
13702
13703 get_const_expr(val, &context, -1);
13704 }
13705 sep = ", ";
13706 }
13708
13709 return buf->data;
13710}
IndexAmRoutine * GetIndexAmRoutine(Oid amhandler)
Definition: amapi.c:33
#define ARR_NDIM(a)
Definition: array.h:290
#define ARR_DATA_PTR(a)
Definition: array.h:322
#define DatumGetArrayTypeP(X)
Definition: array.h:261
#define ARR_ELEMTYPE(a)
Definition: array.h:292
#define ARR_DIMS(a)
Definition: array.h:294
#define ARR_HASNULL(a)
Definition: array.h:291
#define ARR_LBOUND(a)
Definition: array.h:296
ArrayBuildState * accumArrayResult(ArrayBuildState *astate, Datum dvalue, bool disnull, Oid element_type, MemoryContext rcontext)
Definition: arrayfuncs.c:5350
Datum array_ref(ArrayType *array, int nSubscripts, int *indx, int arraytyplen, int elmlen, bool elmbyval, char elmalign, bool *isNull)
Definition: arrayfuncs.c:3146
void deconstruct_array_builtin(ArrayType *array, Oid elmtype, Datum **elemsp, bool **nullsp, int *nelemsp)
Definition: arrayfuncs.c:3697
Datum makeArrayResult(ArrayBuildState *astate, MemoryContext rcontext)
Definition: arrayfuncs.c:5420
int16 AttrNumber
Definition: attnum.h:21
#define InvalidAttrNumber
Definition: attnum.h:23
char * get_tablespace_name(Oid spc_oid)
Definition: tablespace.c:1472
Bitmapset * bms_make_singleton(int x)
Definition: bitmapset.c:216
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:412
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:510
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:815
Bitmapset * bms_union(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:251
#define bms_is_empty(a)
Definition: bitmapset.h:118
#define TextDatumGetCString(d)
Definition: builtins.h:98
#define NameStr(name)
Definition: c.h:752
uint16 bits16
Definition: c.h:547
NameData * Name
Definition: c.h:750
#define Max(x, y)
Definition: c.h:998
int16_t int16
Definition: c.h:534
#define SQL_STR_DOUBLE(ch, escape_backslash)
Definition: c.h:1163
int32_t int32
Definition: c.h:535
#define lengthof(array)
Definition: c.h:788
unsigned int Index
Definition: c.h:620
float float4
Definition: c.h:635
#define OidIsValid(objectId)
Definition: c.h:775
Oid collid
const uint8 ScanKeywordCategories[SCANKEYWORDS_NUM_KEYWORDS]
Definition: keywords.c:29
@ DEPENDENCY_AUTO
Definition: dependency.h:34
@ DEPENDENCY_INTERNAL
Definition: dependency.h:35
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:952
HTAB * hash_create(const char *tabname, int64 nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:358
void hash_destroy(HTAB *hashp)
Definition: dynahash.c:865
int errcode(int sqlerrcode)
Definition: elog.c:854
int errmsg(const char *fmt,...)
Definition: elog.c:1071
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:226
#define ereport(elevel,...)
Definition: elog.h:150
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:223
#define palloc0_array(type, count)
Definition: fe_memutils.h:77
char * OidOutputFunctionCall(Oid functionId, Datum val)
Definition: fmgr.c:1762
#define PG_GETARG_OID(n)
Definition: fmgr.h:275
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:309
#define DatumGetByteaPP(X)
Definition: fmgr.h:291
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:682
#define PG_RETURN_NULL()
Definition: fmgr.h:345
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:372
#define PG_RETURN_NAME(x)
Definition: fmgr.h:363
#define PG_GETARG_INT32(n)
Definition: fmgr.h:269
#define PG_GETARG_BOOL(n)
Definition: fmgr.h:274
#define PG_RETURN_DATUM(x)
Definition: fmgr.h:353
#define PG_FUNCTION_ARGS
Definition: fmgr.h:193
char * format_type_with_typemod(Oid type_oid, int32 typemod)
Definition: format_type.c:362
char * format_type_be(Oid type_oid)
Definition: format_type.c:343
int get_func_trftypes(HeapTuple procTup, Oid **p_trftypes)
Definition: funcapi.c:1475
int get_func_arg_info(HeapTuple procTup, Oid **p_argtypes, char ***p_argnames, char **p_argmodes)
Definition: funcapi.c:1379
TupleDesc get_expr_result_tupdesc(Node *expr, bool noError)
Definition: funcapi.c:551
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:603
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:514
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:388
int GetConfigOptionFlags(const char *name, bool missing_ok)
Definition: guc.c:4457
#define GUC_LIST_QUOTE
Definition: guc.h:215
Assert(PointerIsAligned(start, uint64))
const char * str
bool heap_attisnull(HeapTuple tup, int attnum, TupleDesc tupleDesc)
Definition: heaptuple.c:456
#define HASH_STRINGS
Definition: hsearch.h:96
@ HASH_FIND
Definition: hsearch.h:113
@ HASH_ENTER
Definition: hsearch.h:114
#define HASH_CONTEXT
Definition: hsearch.h:102
#define HASH_ELEM
Definition: hsearch.h:95
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
static void * GETSTRUCT(const HeapTupleData *tuple)
Definition: htup_details.h:728
static Datum fastgetattr(HeapTuple tup, int attnum, TupleDesc tupleDesc, bool *isnull)
Definition: htup_details.h:861
#define stmt
Definition: indent_codes.h:59
#define ident
Definition: indent_codes.h:47
#define funcname
Definition: indent_codes.h:69
Oid GetDefaultOpClass(Oid type_id, Oid am_id)
Definition: indexcmds.c:2344
long val
Definition: informix.c:689
static struct @166 value
int a
Definition: isn.c:73
int j
Definition: isn.c:78
int i
Definition: isn.c:77
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:81
PGDLLIMPORT const ScanKeywordList ScanKeywords
#define UNRESERVED_KEYWORD
Definition: keywords.h:20
int ScanKeywordLookup(const char *str, const ScanKeywordList *keywords)
Definition: kwlookup.c:38
List * lappend(List *list, void *datum)
Definition: list.c:339
List * list_copy_tail(const List *oldlist, int nskip)
Definition: list.c:1613
List * list_delete_first(List *list)
Definition: list.c:943
List * list_concat(List *list1, const List *list2)
Definition: list.c:561
List * list_copy(const List *oldlist)
Definition: list.c:1573
List * lcons(void *datum, List *list)
Definition: list.c:495
void list_free(List *list)
Definition: list.c:1546
#define NoLock
Definition: lockdefs.h:34
#define AccessShareLock
Definition: lockdefs.h:36
@ LockWaitSkip
Definition: lockoptions.h:41
@ LockWaitError
Definition: lockoptions.h:43
@ LCS_FORUPDATE
Definition: lockoptions.h:27
@ LCS_NONE
Definition: lockoptions.h:23
@ LCS_FORSHARE
Definition: lockoptions.h:25
@ LCS_FORKEYSHARE
Definition: lockoptions.h:24
@ LCS_FORNOKEYUPDATE
Definition: lockoptions.h:26
char * get_rel_name(Oid relid)
Definition: lsyscache.c:2095
AttrNumber get_attnum(Oid relid, const char *attname)
Definition: lsyscache.c:951
Oid get_opclass_input_type(Oid opclass)
Definition: lsyscache.c:1331
bool type_is_rowtype(Oid typid)
Definition: lsyscache.c:2822
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:3074
Datum get_attoptions(Oid relid, int16 attnum)
Definition: lsyscache.c:1063
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:2170
Oid get_typcollation(Oid typid)
Definition: lsyscache.c:3223
char * get_language_name(Oid langoid, bool missing_ok)
Definition: lsyscache.c:1280
char * get_namespace_name_or_temp(Oid nspid)
Definition: lsyscache.c:3557
char * get_constraint_name(Oid conoid)
Definition: lsyscache.c:1174
char * get_attname(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: lsyscache.c:920
Oid get_rel_tablespace(Oid relid)
Definition: lsyscache.c:2221
Oid get_typ_typrelid(Oid typid)
Definition: lsyscache.c:2898
Oid get_base_element_type(Oid typid)
Definition: lsyscache.c:2999
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3533
void get_type_category_preferred(Oid typid, char *typcategory, bool *typispreferred)
Definition: lsyscache.c:2877
void get_atttypetypmodcoll(Oid relid, AttrNumber attnum, Oid *typid, int32 *typmod, Oid *collid)
Definition: lsyscache.c:1036
Alias * makeAlias(const char *aliasname, List *colnames)
Definition: makefuncs.c:438
int pg_mbcliplen(const char *mbstr, int len, int limit)
Definition: mbutils.c:1084
char * pstrdup(const char *in)
Definition: mcxt.c:1759
void pfree(void *pointer)
Definition: mcxt.c:1594
void * palloc0(Size size)
Definition: mcxt.c:1395
void * palloc(Size size)
Definition: mcxt.c:1365
MemoryContext CurrentMemoryContext
Definition: mcxt.c:160
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:122
Datum namein(PG_FUNCTION_ARGS)
Definition: name.c:48
bool CollationIsVisible(Oid collid)
Definition: namespace.c:2474
bool RelationIsVisible(Oid relid)
Definition: namespace.c:912
bool OpclassIsVisible(Oid opcid)
Definition: namespace.c:2221
RangeVar * makeRangeVarFromNameList(const List *names)
Definition: namespace.c:3621
#define RangeVarGetRelid(relation, lockmode, missing_ok)
Definition: namespace.h:98
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
bool exprIsLengthCoercion(const Node *expr, int32 *coercedTypmod)
Definition: nodeFuncs.c:557
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:301
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:821
Node * strip_implicit_coercions(Node *node)
Definition: nodeFuncs.c:705
#define DO_AGGSPLIT_SKIPFINAL(as)
Definition: nodes.h:396
#define IsA(nodeptr, _type_)
Definition: nodes.h:164
#define nodeTag(nodeptr)
Definition: nodes.h:139
#define DO_AGGSPLIT_COMBINE(as)
Definition: nodes.h:395
@ ONCONFLICT_NOTHING
Definition: nodes.h:429
@ CMD_MERGE
Definition: nodes.h:279
@ CMD_UTILITY
Definition: nodes.h:280
@ CMD_INSERT
Definition: nodes.h:277
@ CMD_DELETE
Definition: nodes.h:278
@ CMD_UPDATE
Definition: nodes.h:276
@ CMD_SELECT
Definition: nodes.h:275
@ CMD_NOTHING
Definition: nodes.h:282
@ LIMIT_OPTION_WITH_TIES
Definition: nodes.h:442
#define makeNode(_type_)
Definition: nodes.h:161
#define castNode(_type_, nodeptr)
Definition: nodes.h:182
@ JOIN_FULL
Definition: nodes.h:305
@ JOIN_INNER
Definition: nodes.h:303
@ JOIN_RIGHT
Definition: nodes.h:306
@ JOIN_LEFT
Definition: nodes.h:304
#define repalloc0_array(pointer, type, oldcount, count)
Definition: palloc.h:109
int get_aggregate_argtypes(Aggref *aggref, Oid *inputTypes)
Definition: parse_agg.c:2023
FuncDetailCode func_get_detail(List *funcname, List *fargs, List *fargnames, int nargs, Oid *argtypes, bool expand_variadic, bool expand_defaults, bool include_out_arguments, int *fgc_flags, Oid *funcid, Oid *rettype, bool *retset, int *nvargs, Oid *vatype, Oid **true_typeids, List **argdefaults)
Definition: parse_func.c:1504
FuncDetailCode
Definition: parse_func.h:23
@ FUNCDETAIL_NORMAL
Definition: parse_func.h:26
@ FUNCDETAIL_WINDOWFUNC
Definition: parse_func.h:29
@ FUNCDETAIL_NOTFOUND
Definition: parse_func.h:24
@ FUNCDETAIL_AGGREGATE
Definition: parse_func.h:28
Operator left_oper(ParseState *pstate, List *op, Oid arg, bool noError, int location)
Definition: parse_oper.c:521
Oid oprid(Operator op)
Definition: parse_oper.c:239
Operator oper(ParseState *pstate, List *opname, Oid ltypeId, Oid rtypeId, bool noError, int location)
Definition: parse_oper.c:371
char * get_rte_attribute_name(RangeTblEntry *rte, AttrNumber attnum)
TargetEntry * get_tle_by_resno(List *tlist, AttrNumber resno)
void expandRTE(RangeTblEntry *rte, int rtindex, int sublevels_up, VarReturningType returning_type, int location, bool include_dropped, List **colnames, List **colvars)
#define FRAMEOPTION_END_CURRENT_ROW
Definition: parsenodes.h:617
#define FRAMEOPTION_END_OFFSET
Definition: parsenodes.h:628
#define FRAMEOPTION_EXCLUDE_CURRENT_ROW
Definition: parsenodes.h:622
@ GROUPING_SET_CUBE
Definition: parsenodes.h:1531
@ GROUPING_SET_SIMPLE
Definition: parsenodes.h:1529
@ GROUPING_SET_ROLLUP
Definition: parsenodes.h:1530
@ GROUPING_SET_SETS
Definition: parsenodes.h:1532
@ GROUPING_SET_EMPTY
Definition: parsenodes.h:1528
#define FKCONSTR_ACTION_RESTRICT
Definition: parsenodes.h:2817
@ SETOP_INTERSECT
Definition: parsenodes.h:2176
@ SETOP_UNION
Definition: parsenodes.h:2175
@ SETOP_EXCEPT
Definition: parsenodes.h:2177
#define FRAMEOPTION_END_OFFSET_PRECEDING
Definition: parsenodes.h:619
#define FRAMEOPTION_START_UNBOUNDED_PRECEDING
Definition: parsenodes.h:612
#define GetCTETargetList(cte)
Definition: parsenodes.h:1734
#define FKCONSTR_ACTION_SETDEFAULT
Definition: parsenodes.h:2820
@ PARTITION_STRATEGY_HASH
Definition: parsenodes.h:900
@ PARTITION_STRATEGY_LIST
Definition: parsenodes.h:898
@ PARTITION_STRATEGY_RANGE
Definition: parsenodes.h:899
#define FRAMEOPTION_START_CURRENT_ROW
Definition: parsenodes.h:616
#define FKCONSTR_MATCH_SIMPLE
Definition: parsenodes.h:2825
@ RTE_JOIN
Definition: parsenodes.h:1043
@ RTE_CTE
Definition: parsenodes.h:1047
@ RTE_NAMEDTUPLESTORE
Definition: parsenodes.h:1048
@ RTE_VALUES
Definition: parsenodes.h:1046
@ RTE_SUBQUERY
Definition: parsenodes.h:1042
@ RTE_RESULT
Definition: parsenodes.h:1049
@ RTE_FUNCTION
Definition: parsenodes.h:1044
@ RTE_TABLEFUNC
Definition: parsenodes.h:1045
@ RTE_GROUP
Definition: parsenodes.h:1052
@ RTE_RELATION
Definition: parsenodes.h:1041
#define FRAMEOPTION_START_OFFSET
Definition: parsenodes.h:626
@ PARTITION_RANGE_DATUM_MAXVALUE
Definition: parsenodes.h:952
@ PARTITION_RANGE_DATUM_MINVALUE
Definition: parsenodes.h:950
#define FKCONSTR_MATCH_PARTIAL
Definition: parsenodes.h:2824
#define FRAMEOPTION_END_OFFSET_FOLLOWING
Definition: parsenodes.h:621
#define FRAMEOPTION_EXCLUDE_TIES
Definition: parsenodes.h:624
#define FRAMEOPTION_RANGE
Definition: parsenodes.h:608
#define FRAMEOPTION_EXCLUDE_GROUP
Definition: parsenodes.h:623
#define FKCONSTR_ACTION_CASCADE
Definition: parsenodes.h:2818
#define FRAMEOPTION_GROUPS
Definition: parsenodes.h:610
#define FRAMEOPTION_BETWEEN
Definition: parsenodes.h:611
#define FKCONSTR_ACTION_SETNULL
Definition: parsenodes.h:2819
#define FRAMEOPTION_END_UNBOUNDED_FOLLOWING
Definition: parsenodes.h:615
#define FRAMEOPTION_START_OFFSET_PRECEDING
Definition: parsenodes.h:618
#define FRAMEOPTION_START_OFFSET_FOLLOWING
Definition: parsenodes.h:620
#define FRAMEOPTION_NONDEFAULT
Definition: parsenodes.h:607
#define FKCONSTR_MATCH_FULL
Definition: parsenodes.h:2823
#define FKCONSTR_ACTION_NOACTION
Definition: parsenodes.h:2816
#define FRAMEOPTION_ROWS
Definition: parsenodes.h:609
@ CTEMaterializeNever
Definition: parsenodes.h:1669
@ CTEMaterializeAlways
Definition: parsenodes.h:1668
@ CTEMaterializeDefault
Definition: parsenodes.h:1667
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
Expr * get_partition_qual_relid(Oid relid)
Definition: partcache.c:299
FormData_pg_aggregate * Form_pg_aggregate
Definition: pg_aggregate.h:109
FormData_pg_am * Form_pg_am
Definition: pg_am.h:48
NameData attname
Definition: pg_attribute.h:41
int16 attnum
Definition: pg_attribute.h:74
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:202
FormData_pg_authid * Form_pg_authid
Definition: pg_authid.h:56
void * arg
static char format
NameData relname
Definition: pg_class.h:38
FormData_pg_class * Form_pg_class
Definition: pg_class.h:156
FormData_pg_collation * Form_pg_collation
Definition: pg_collation.h:58
#define NAMEDATALEN
#define FUNC_MAX_ARGS
AttrNumber extractNotNullColumn(HeapTuple constrTup)
FormData_pg_constraint * Form_pg_constraint
while(p+4<=pend)
int32 encoding
Definition: pg_database.h:41
FormData_pg_depend * Form_pg_depend
Definition: pg_depend.h:72
FormData_pg_index * Form_pg_index
Definition: pg_index.h:70
#define lfirst(lc)
Definition: pg_list.h:172
#define llast(l)
Definition: pg_list.h:198
#define lfirst_node(type, lc)
Definition: pg_list.h:176
static int list_length(const List *l)
Definition: pg_list.h:152
#define linitial_node(type, l)
Definition: pg_list.h:181
#define NIL
Definition: pg_list.h:68
#define lsecond_node(type, l)
Definition: pg_list.h:186
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:518
#define foreach_current_index(var_or_cell)
Definition: pg_list.h:403
#define lfirst_int(lc)
Definition: pg_list.h:173
#define lthird(l)
Definition: pg_list.h:188
#define list_make1(x1)
Definition: pg_list.h:212
#define linitial_int(l)
Definition: pg_list.h:179
#define for_each_cell(cell, lst, initcell)
Definition: pg_list.h:438
#define for_each_from(cell, lst, N)
Definition: pg_list.h:414
static void * list_nth(const List *list, int n)
Definition: pg_list.h:299
#define linitial(l)
Definition: pg_list.h:178
#define lsecond(l)
Definition: pg_list.h:183
#define foreach_node(type, var, lst)
Definition: pg_list.h:496
#define forfour(cell1, list1, cell2, list2, cell3, list3, cell4, list4)
Definition: pg_list.h:575
static ListCell * list_head(const List *l)
Definition: pg_list.h:128
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:343
#define lfourth(l)
Definition: pg_list.h:193
#define linitial_oid(l)
Definition: pg_list.h:180
#define forfive(cell1, list1, cell2, list2, cell3, list3, cell4, list4, cell5, list5)
Definition: pg_list.h:588
#define lfirst_oid(lc)
Definition: pg_list.h:174
#define list_make2(x1, x2)
Definition: pg_list.h:214
#define foreach_int(var, lst)
Definition: pg_list.h:470
static int list_cell_number(const List *l, const ListCell *c)
Definition: pg_list.h:333
#define lthird_node(type, l)
Definition: pg_list.h:191
FormData_pg_opclass * Form_pg_opclass
Definition: pg_opclass.h:83
FormData_pg_operator * Form_pg_operator
Definition: pg_operator.h:83
FormData_pg_partitioned_table * Form_pg_partitioned_table
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:136
NameData proname
Definition: pg_proc.h:35
static size_t noptions
static char ** options
#define plan(x)
Definition: pg_regress.c:161
FormData_pg_statistic_ext * Form_pg_statistic_ext
static char * buf
Definition: pg_test_fsync.c:72
FormData_pg_trigger * Form_pg_trigger
Definition: pg_trigger.h:80
FormData_pg_type * Form_pg_type
Definition: pg_type.h:261
NameData typname
Definition: pg_type.h:41
#define innerPlan(node)
Definition: plannodes.h:251
#define outerPlan(node)
Definition: plannodes.h:252
#define sprintf
Definition: port.h:241
#define snprintf
Definition: port.h:239
static bool DatumGetBool(Datum X)
Definition: postgres.h:100
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:332
static Name DatumGetName(Datum X)
Definition: postgres.h:370
static Oid DatumGetObjectId(Datum X)
Definition: postgres.h:252
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:262
uint64_t Datum
Definition: postgres.h:70
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:322
static char DatumGetChar(Datum X)
Definition: postgres.h:122
static Datum CStringGetDatum(const char *X)
Definition: postgres.h:360
static Datum Int32GetDatum(int32 X)
Definition: postgres.h:222
static int16 DatumGetInt16(Datum X)
Definition: postgres.h:172
static int32 DatumGetInt32(Datum X)
Definition: postgres.h:212
#define InvalidOid
Definition: postgres_ext.h:37
unsigned int Oid
Definition: postgres_ext.h:32
e
Definition: preproc-init.c:82
char string[11]
Definition: preproc-type.c:52
@ IS_NOT_TRUE
Definition: primnodes.h:1987
@ IS_NOT_FALSE
Definition: primnodes.h:1987
@ IS_NOT_UNKNOWN
Definition: primnodes.h:1987
@ IS_TRUE
Definition: primnodes.h:1987
@ IS_UNKNOWN
Definition: primnodes.h:1987
@ IS_FALSE
Definition: primnodes.h:1987
@ ARRAY_SUBLINK
Definition: primnodes.h:1022
@ ANY_SUBLINK
Definition: primnodes.h:1018
@ MULTIEXPR_SUBLINK
Definition: primnodes.h:1021
@ CTE_SUBLINK
Definition: primnodes.h:1023
@ EXPR_SUBLINK
Definition: primnodes.h:1020
@ ROWCOMPARE_SUBLINK
Definition: primnodes.h:1019
@ ALL_SUBLINK
Definition: primnodes.h:1017
@ EXISTS_SUBLINK
Definition: primnodes.h:1016
@ JS_FORMAT_JSONB
Definition: primnodes.h:1651
@ JS_FORMAT_DEFAULT
Definition: primnodes.h:1649
@ JS_FORMAT_JSON
Definition: primnodes.h:1650
@ IS_LEAST
Definition: primnodes.h:1514
@ IS_GREATEST
Definition: primnodes.h:1513
@ TFT_XMLTABLE
Definition: primnodes.h:100
@ TFT_JSON_TABLE
Definition: primnodes.h:101
BoolExprType
Definition: primnodes.h:949
@ AND_EXPR
Definition: primnodes.h:950
@ OR_EXPR
Definition: primnodes.h:950
@ NOT_EXPR
Definition: primnodes.h:950
@ JS_ENC_DEFAULT
Definition: primnodes.h:1637
@ JS_ENC_UTF32
Definition: primnodes.h:1640
@ JS_ENC_UTF16
Definition: primnodes.h:1639
@ XMLOPTION_DOCUMENT
Definition: primnodes.h:1603
@ SVFOP_CURRENT_CATALOG
Definition: primnodes.h:1560
@ SVFOP_LOCALTIME_N
Definition: primnodes.h:1553
@ SVFOP_CURRENT_TIMESTAMP
Definition: primnodes.h:1550
@ SVFOP_LOCALTIME
Definition: primnodes.h:1552
@ SVFOP_CURRENT_TIMESTAMP_N
Definition: primnodes.h:1551
@ SVFOP_CURRENT_ROLE
Definition: primnodes.h:1556
@ SVFOP_USER
Definition: primnodes.h:1558
@ SVFOP_CURRENT_SCHEMA
Definition: primnodes.h:1561
@ SVFOP_LOCALTIMESTAMP_N
Definition: primnodes.h:1555
@ SVFOP_CURRENT_DATE
Definition: primnodes.h:1547
@ SVFOP_CURRENT_TIME_N
Definition: primnodes.h:1549
@ SVFOP_CURRENT_TIME
Definition: primnodes.h:1548
@ SVFOP_LOCALTIMESTAMP
Definition: primnodes.h:1554
@ SVFOP_CURRENT_USER
Definition: primnodes.h:1557
@ SVFOP_SESSION_USER
Definition: primnodes.h:1559
@ PARAM_MULTIEXPR
Definition: primnodes.h:387
@ PARAM_EXTERN
Definition: primnodes.h:384
@ PARAM_EXEC
Definition: primnodes.h:385
@ JSW_UNCONDITIONAL
Definition: primnodes.h:1764
@ JSW_CONDITIONAL
Definition: primnodes.h:1763
@ JSW_UNSPEC
Definition: primnodes.h:1761
@ JSW_NONE
Definition: primnodes.h:1762
@ IS_DOCUMENT
Definition: primnodes.h:1598
@ IS_XMLFOREST
Definition: primnodes.h:1593
@ IS_XMLCONCAT
Definition: primnodes.h:1591
@ IS_XMLPI
Definition: primnodes.h:1595
@ IS_XMLPARSE
Definition: primnodes.h:1594
@ IS_XMLSERIALIZE
Definition: primnodes.h:1597
@ IS_XMLROOT
Definition: primnodes.h:1596
@ IS_XMLELEMENT
Definition: primnodes.h:1592
@ VAR_RETURNING_OLD
Definition: primnodes.h:257
@ VAR_RETURNING_NEW
Definition: primnodes.h:258
@ VAR_RETURNING_DEFAULT
Definition: primnodes.h:256
JsonBehaviorType
Definition: primnodes.h:1775
@ JSON_BEHAVIOR_DEFAULT
Definition: primnodes.h:1784
@ JSON_BEHAVIOR_FALSE
Definition: primnodes.h:1780
@ JSON_BEHAVIOR_NULL
Definition: primnodes.h:1776
@ JSON_BEHAVIOR_EMPTY_ARRAY
Definition: primnodes.h:1782
@ JSON_QUERY_OP
Definition: primnodes.h:1814
@ JSON_EXISTS_OP
Definition: primnodes.h:1813
@ JSON_VALUE_OP
Definition: primnodes.h:1815
CoercionForm
Definition: primnodes.h:752
@ COERCE_SQL_SYNTAX
Definition: primnodes.h:756
@ COERCE_IMPLICIT_CAST
Definition: primnodes.h:755
@ COERCE_EXPLICIT_CAST
Definition: primnodes.h:754
@ COERCE_EXPLICIT_CALL
Definition: primnodes.h:753
@ OVERRIDING_SYSTEM_VALUE
Definition: primnodes.h:30
@ OVERRIDING_USER_VALUE
Definition: primnodes.h:29
@ IS_NULL
Definition: primnodes.h:1963
@ IS_NOT_NULL
Definition: primnodes.h:1963
@ JS_TYPE_ARRAY
Definition: primnodes.h:1735
@ JS_TYPE_OBJECT
Definition: primnodes.h:1734
@ JS_TYPE_SCALAR
Definition: primnodes.h:1736
@ MERGE_WHEN_NOT_MATCHED_BY_TARGET
Definition: primnodes.h:2009
@ MERGE_WHEN_NOT_MATCHED_BY_SOURCE
Definition: primnodes.h:2008
@ MERGE_WHEN_MATCHED
Definition: primnodes.h:2007
#define OUTER_VAR
Definition: primnodes.h:243
@ JSCTOR_JSON_SERIALIZE
Definition: primnodes.h:1707
@ JSCTOR_JSON_ARRAYAGG
Definition: primnodes.h:1704
@ JSCTOR_JSON_PARSE
Definition: primnodes.h:1705
@ JSCTOR_JSON_OBJECT
Definition: primnodes.h:1701
@ JSCTOR_JSON_SCALAR
Definition: primnodes.h:1706
@ JSCTOR_JSON_ARRAY
Definition: primnodes.h:1702
@ JSCTOR_JSON_OBJECTAGG
Definition: primnodes.h:1703
#define INNER_VAR
Definition: primnodes.h:242
#define INDEX_VAR
Definition: primnodes.h:244
tree ctl root
Definition: radixtree.h:1857
void * stringToNode(const char *str)
Definition: read.c:90
#define RelationGetDescr(relation)
Definition: rel.h:540
#define RelationGetRelationName(relation)
Definition: rel.h:548
void AcquireRewriteLocks(Query *parsetree, bool forExecute, bool forUpdatePushedDown)
Query * getInsertSelectQuery(Query *parsetree, Query ***subquery_ptr)
#define ViewSelectRuleName
Datum pg_get_triggerdef_ext(PG_FUNCTION_ARGS)
Definition: ruleutils.c:885
static void make_viewdef(StringInfo buf, HeapTuple ruletup, TupleDesc rulettc, int prettyFlags, int wrapColumn)
Definition: ruleutils.c:5538
static void removeStringInfoSpaces(StringInfo str)
Definition: ruleutils.c:9135
static bool looks_like_function(Node *node)
Definition: ruleutils.c:10705
Datum pg_get_partition_constraintdef(PG_FUNCTION_ARGS)
Definition: ruleutils.c:2095
static char * get_rtable_name(int rtindex, deparse_context *context)
Definition: ruleutils.c:5132
Datum pg_get_viewdef_wrap(PG_FUNCTION_ARGS)
Definition: ruleutils.c:716
static int decompile_column_index_array(Datum column_index_array, Oid relId, bool withPeriod, StringInfo buf)
Definition: ruleutils.c:2620
static void set_relation_column_names(deparse_namespace *dpns, RangeTblEntry *rte, deparse_columns *colinfo)
Definition: ruleutils.c:4374
static void appendContextKeyword(deparse_context *context, const char *str, int indentBefore, int indentAfter, int indentPlus)
Definition: ruleutils.c:9081
List * deparse_context_for_plan_tree(PlannedStmt *pstmt, List *rtable_names)
Definition: ruleutils.c:3752
char * pg_get_statisticsobjdef_string(Oid statextid)
Definition: ruleutils.c:1626
Datum pg_get_indexdef_ext(PG_FUNCTION_ARGS)
Definition: ruleutils.c:1198
static void set_using_names(deparse_namespace *dpns, Node *jtnode, List *parentUsing)
Definition: ruleutils.c:4209
static Plan * find_recursive_union(deparse_namespace *dpns, WorkTableScan *wtscan)
Definition: ruleutils.c:5232
static text * string_to_text(char *str)
Definition: ruleutils.c:13576
static void get_values_def(List *values_lists, deparse_context *context)
Definition: ruleutils.c:5723
#define PRETTYINDENT_LIMIT
Definition: ruleutils.c:85
Datum pg_get_viewdef(PG_FUNCTION_ARGS)
Definition: ruleutils.c:678
static char * make_colname_unique(char *colname, deparse_namespace *dpns, deparse_columns *colinfo)
Definition: ruleutils.c:4922
static void get_json_behavior(JsonBehavior *behavior, deparse_context *context, const char *on)
Definition: ruleutils.c:9172
static const char * get_simple_binary_op_name(OpExpr *expr)
Definition: ruleutils.c:8823
static void get_json_agg_constructor(JsonConstructorExpr *ctor, deparse_context *context, const char *funcname, bool is_json_objectagg)
Definition: ruleutils.c:11767
Datum pg_get_constraintdef(PG_FUNCTION_ARGS)
Definition: ruleutils.c:2145
static void set_deparse_for_query(deparse_namespace *dpns, Query *query, List *parent_namespaces)
Definition: ruleutils.c:4028
static void print_function_trftypes(StringInfo buf, HeapTuple proctup)
Definition: ruleutils.c:3457
void(* rsv_callback)(Node *node, deparse_context *context, void *callback_arg)
Definition: ruleutils.c:325
#define PRETTYINDENT_STD
Definition: ruleutils.c:81
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:13112
static void get_setop_query(Node *setOp, Query *query, deparse_context *context)
Definition: ruleutils.c:6413
#define PRETTYINDENT_JOIN
Definition: ruleutils.c:82
static bool is_input_argument(int nth, const char *argmodes)
Definition: ruleutils.c:3445
static void get_query_def(Query *query, StringInfo buf, List *parentnamespace, TupleDesc resultDesc, bool colNamesVisible, int prettyFlags, int wrapColumn, int startIndent)
Definition: ruleutils.c:5623
static void get_tablesample_def(TableSampleClause *tablesample, deparse_context *context)
Definition: ruleutils.c:12816
Datum pg_get_functiondef(PG_FUNCTION_ARGS)
Definition: ruleutils.c:2926
Datum pg_get_function_result(PG_FUNCTION_ARGS)
Definition: ruleutils.c:3229
Datum pg_get_indexdef(PG_FUNCTION_ARGS)
Definition: ruleutils.c:1178
static void get_sublink_expr(SubLink *sublink, deparse_context *context)
Definition: ruleutils.c:11819
static const char * get_name_for_var_field(Var *var, int fieldno, int levelsup, deparse_context *context)
Definition: ruleutils.c:8016
static void get_rte_alias(RangeTblEntry *rte, int varno, bool use_as, deparse_context *context)
Definition: ruleutils.c:12654
#define only_marker(rte)
Definition: ruleutils.c:550
Datum pg_get_function_arg_default(PG_FUNCTION_ARGS)
Definition: ruleutils.c:3485
static void get_parameter(Param *param, deparse_context *context)
Definition: ruleutils.c:8686
static void build_colinfo_names_hash(deparse_columns *colinfo)
Definition: ruleutils.c:4977
Datum pg_get_statisticsobjdef_expressions(PG_FUNCTION_ARGS)
Definition: ruleutils.c:1837
static void get_delete_query_def(Query *query, deparse_context *context)
Definition: ruleutils.c:7354
Datum pg_get_ruledef(PG_FUNCTION_ARGS)
Definition: ruleutils.c:560
static void get_json_table_columns(TableFunc *tf, JsonTablePathScan *scan, deparse_context *context, bool showimplicit)
Definition: ruleutils.c:12075
#define PRETTYFLAG_INDENT
Definition: ruleutils.c:89
static void get_column_alias_list(deparse_columns *colinfo, deparse_context *context)
Definition: ruleutils.c:12725
Datum pg_get_statisticsobjdef_columns(PG_FUNCTION_ARGS)
Definition: ruleutils.c:1636
Datum pg_get_statisticsobjdef(PG_FUNCTION_ARGS)
Definition: ruleutils.c:1608
static void add_to_names_hash(deparse_columns *colinfo, const char *name)
Definition: ruleutils.c:5035
static void simple_quote_literal(StringInfo buf, const char *val)
Definition: ruleutils.c:11792
static bool colname_is_unique(const char *colname, deparse_namespace *dpns, deparse_columns *colinfo)
Definition: ruleutils.c:4847
static void get_from_clause_coldeflist(RangeTblFunction *rtfunc, deparse_columns *colinfo, deparse_context *context)
Definition: ruleutils.c:12765
char * pg_get_partkeydef_columns(Oid relid, bool pretty)
Definition: ruleutils.c:1923
static void get_from_clause(Query *query, const char *prefix, deparse_context *context)
Definition: ruleutils.c:12269
List * deparse_context_for(const char *aliasname, Oid relid)
Definition: ruleutils.c:3707
static bool get_func_sql_syntax(FuncExpr *expr, deparse_context *context)
Definition: ruleutils.c:11148
Datum pg_get_partkeydef(PG_FUNCTION_ARGS)
Definition: ruleutils.c:1908
static char * generate_qualified_relation_name(Oid relid)
Definition: ruleutils.c:13212
static void set_simple_column_names(deparse_namespace *dpns)
Definition: ruleutils.c:4097
static void get_json_expr_options(JsonExpr *jsexpr, deparse_context *context, JsonBehaviorType default_behavior)
Definition: ruleutils.c:9210
char * pg_get_indexdef_columns(Oid indexrelid, bool pretty)
Definition: ruleutils.c:1235
#define PRETTY_INDENT(context)
Definition: ruleutils.c:102
#define PRETTYFLAG_PAREN
Definition: ruleutils.c:88
static void get_rule_groupingset(GroupingSet *gset, List *targetlist, bool omit_parens, deparse_context *context)
Definition: ruleutils.c:6630
char * pg_get_indexdef_columns_extended(Oid indexrelid, bits16 flags)
Definition: ruleutils.c:1249
static char * pg_get_indexdef_worker(Oid indexrelid, int colno, const Oid *excludeOps, bool attrsOnly, bool keysOnly, bool showTblSpc, bool inherits, int prettyFlags, bool missing_ok)
Definition: ruleutils.c:1270
static char * pg_get_constraintdef_worker(Oid constraintId, bool fullCommand, int prettyFlags, bool missing_ok)
Definition: ruleutils.c:2192
static void get_rule_expr_funccall(Node *node, deparse_context *context, bool showimplicit)
Definition: ruleutils.c:10682
static char * generate_function_name(Oid funcid, int nargs, List *argnames, Oid *argtypes, bool has_variadic, bool *use_variadic_p, bool inGroupBy)
Definition: ruleutils.c:13256
static void expand_colnames_array_to(deparse_columns *colinfo, int n)
Definition: ruleutils.c:4961
static void get_returning_clause(Query *query, deparse_context *context)
Definition: ruleutils.c:6374
List * set_deparse_context_plan(List *dpcontext, Plan *plan, List *ancestors)
Definition: ruleutils.c:3824
static SubPlan * find_param_generator(Param *param, deparse_context *context, int *column_p)
Definition: ruleutils.c:8568
static void add_cast_to(StringInfo buf, Oid typid)
Definition: ruleutils.c:13480
static void get_special_variable(Node *node, deparse_context *context, void *callback_arg)
Definition: ruleutils.c:7887
static void get_windowfunc_expr_helper(WindowFunc *wfunc, deparse_context *context, const char *funcname, const char *options, bool is_json_objectagg)
Definition: ruleutils.c:11035
static void get_rule_list_toplevel(List *lst, deparse_context *context, bool showimplicit)
Definition: ruleutils.c:10652
static char * pg_get_statisticsobj_worker(Oid statextid, bool columns_only, bool missing_ok)
Definition: ruleutils.c:1653
#define deparse_columns_fetch(rangetable_index, dpns)
Definition: ruleutils.c:312
static void get_json_constructor(JsonConstructorExpr *ctor, deparse_context *context, bool showimplicit)
Definition: ruleutils.c:11671
static const char *const query_getrulebyoid
Definition: ruleutils.c:334
static void get_json_path_spec(Node *path_spec, deparse_context *context, bool showimplicit)
Definition: ruleutils.c:11614
static void printSubscripts(SubscriptingRef *sbsref, deparse_context *context)
Definition: ruleutils.c:12998
static SubPlan * find_param_generator_initplan(Param *param, Plan *plan, int *column_p)
Definition: ruleutils.c:8665
static void pop_ancestor_plan(deparse_namespace *dpns, deparse_namespace *save_dpns)
Definition: ruleutils.c:5330
static void get_window_frame_options(int frameOptions, Node *startOffset, Node *endOffset, deparse_context *context)
Definition: ruleutils.c:6837
static void get_rule_expr_paren(Node *node, deparse_context *context, bool showimplicit, Node *parentNode)
Definition: ruleutils.c:9154
bool quote_all_identifiers
Definition: ruleutils.c:339
static void get_agg_expr(Aggref *aggref, deparse_context *context, Aggref *original_aggref)
Definition: ruleutils.c:10870
static void get_const_collation(Const *constval, deparse_context *context)
Definition: ruleutils.c:11594
static void get_target_list(List *targetList, deparse_context *context)
Definition: ruleutils.c:6238
static SPIPlanPtr plan_getrulebyoid
Definition: ruleutils.c:333
static void get_json_table_nested_columns(TableFunc *tf, JsonTablePlan *plan, deparse_context *context, bool showimplicit, bool needcomma)
Definition: ruleutils.c:12043
static char * deparse_expression_pretty(Node *expr, List *dpcontext, bool forceprefix, bool showimplicit, int prettyFlags, int startIndent)
Definition: ruleutils.c:3671
Datum pg_get_ruledef_ext(PG_FUNCTION_ARGS)
Definition: ruleutils.c:578
char * pg_get_indexdef_string(Oid indexrelid)
Definition: ruleutils.c:1225
static void get_insert_query_def(Query *query, deparse_context *context)
Definition: ruleutils.c:6938
char * pg_get_querydef(Query *query, bool pretty)
Definition: ruleutils.c:1588
static void print_function_sqlbody(StringInfo buf, HeapTuple proctup)
Definition: ruleutils.c:3555
static bool has_dangerous_join_using(deparse_namespace *dpns, Node *jtnode)
Definition: ruleutils.c:4139
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:13028
static Node * get_rule_sortgroupclause(Index ref, List *tlist, bool force_colno, deparse_context *context)
Definition: ruleutils.c:6561
static char * pg_get_viewdef_worker(Oid viewoid, int prettyFlags, int wrapColumn)
Definition: ruleutils.c:789
static void push_ancestor_plan(deparse_namespace *dpns, ListCell *ancestor_cell, deparse_namespace *save_dpns)
Definition: ruleutils.c:5309
static SPIPlanPtr plan_getviewrule
Definition: ruleutils.c:335
#define WRAP_COLUMN_DEFAULT
Definition: ruleutils.c:98
static char * flatten_reloptions(Oid relid)
Definition: ruleutils.c:13644
static text * pg_get_expr_worker(text *expr, Oid relid, int prettyFlags)
Definition: ruleutils.c:2709
static Node * processIndirection(Node *node, deparse_context *context)
Definition: ruleutils.c:12920
static void get_agg_combine_expr(Node *node, deparse_context *context, void *callback_arg)
Definition: ruleutils.c:11008
#define PRETTY_PAREN(context)
Definition: ruleutils.c:101
Datum pg_get_triggerdef(PG_FUNCTION_ARGS)
Definition: ruleutils.c:871
List * select_rtable_names_for_explain(List *rtable, Bitmapset *rels_used)
Definition: ruleutils.c:3854
Datum pg_get_function_sqlbody(PG_FUNCTION_ARGS)
Definition: ruleutils.c:3609
Datum pg_get_expr(PG_FUNCTION_ARGS)
Definition: ruleutils.c:2674
static char * generate_qualified_type_name(Oid typid)
Definition: ruleutils.c:13511
static void get_xmltable(TableFunc *tf, deparse_context *context, bool showimplicit)
Definition: ruleutils.c:11944
static void get_utility_query_def(Query *query, deparse_context *context)
Definition: ruleutils.c:7560
static char * get_relation_name(Oid relid)
Definition: ruleutils.c:13132
Datum pg_get_expr_ext(PG_FUNCTION_ARGS)
Definition: ruleutils.c:2691
static void get_rule_windowclause(Query *query, deparse_context *context)
Definition: ruleutils.c:6748
static void get_rule_windowspec(WindowClause *wc, List *targetList, deparse_context *context)
Definition: ruleutils.c:6780
static void get_json_returning(JsonReturning *returning, StringInfo buf, bool json_format_by_default)
Definition: ruleutils.c:11651
Datum pg_get_viewdef_name_ext(PG_FUNCTION_ARGS)
Definition: ruleutils.c:761
static Node * find_param_referent(Param *param, deparse_context *context, deparse_namespace **dpns_p, ListCell **ancestor_cell_p)
Definition: ruleutils.c:8454
static void get_rule_orderby(List *orderList, List *targetList, bool force_colno, deparse_context *context)
Definition: ruleutils.c:6690
static void pop_child_plan(deparse_namespace *dpns, deparse_namespace *save_dpns)
Definition: ruleutils.c:5279
char * generate_collation_name(Oid collid)
Definition: ruleutils.c:13544
char * pg_get_constraintdef_command(Oid constraintId)
Definition: ruleutils.c:2183
char * pg_get_partconstrdef_string(Oid partitionId, char *aliasname)
Definition: ruleutils.c:2127
static void set_join_column_names(deparse_namespace *dpns, RangeTblEntry *rte, deparse_columns *colinfo)
Definition: ruleutils.c:4577
Datum pg_get_constraintdef_ext(PG_FUNCTION_ARGS)
Definition: ruleutils.c:2162
static void set_rtable_names(deparse_namespace *dpns, List *parent_namespaces, Bitmapset *rels_used)
Definition: ruleutils.c:3883
char * get_window_frame_options_for_explain(int frameOptions, Node *startOffset, Node *endOffset, List *dpcontext, bool forceprefix)
Definition: ruleutils.c:6906
static void get_update_query_targetlist_def(Query *query, List *targetList, deparse_context *context, RangeTblEntry *rte)
Definition: ruleutils.c:7202
static void get_rule_expr(Node *node, deparse_context *context, bool showimplicit)
Definition: ruleutils.c:9251
Datum pg_get_viewdef_ext(PG_FUNCTION_ARGS)
Definition: ruleutils.c:697
static char * pg_get_partkeydef_worker(Oid relid, int prettyFlags, bool attrsOnly, bool missing_ok)
Definition: ruleutils.c:1936
static void get_oper_expr(OpExpr *expr, deparse_context *context)
Definition: ruleutils.c:10734
Datum pg_get_function_identity_arguments(PG_FUNCTION_ARGS)
Definition: ruleutils.c:3204
static char * pg_get_triggerdef_worker(Oid trigid, bool pretty)
Definition: ruleutils.c:900
#define GET_PRETTY_FLAGS(pretty)
Definition: ruleutils.c:93
static void get_reloptions(StringInfo buf, Datum reloptions)
Definition: ruleutils.c:13589
static void get_func_expr(FuncExpr *expr, deparse_context *context, bool showimplicit)
Definition: ruleutils.c:10774
static void get_const_expr(Const *constval, deparse_context *context, int showtype)
Definition: ruleutils.c:11464
char * deparse_expression(Node *expr, List *dpcontext, bool forceprefix, bool showimplicit)
Definition: ruleutils.c:3644
void generate_operator_clause(StringInfo buf, const char *leftop, Oid leftoptype, Oid opoid, const char *rightop, Oid rightoptype)
Definition: ruleutils.c:13440
static void make_ruledef(StringInfo buf, HeapTuple ruletup, TupleDesc rulettc, int prettyFlags)
Definition: ruleutils.c:5346
static const char *const query_getviewrule
Definition: ruleutils.c:336
static char * pg_get_ruledef_worker(Oid ruleoid, int prettyFlags)
Definition: ruleutils.c:597
static int print_function_arguments(StringInfo buf, HeapTuple proctup, bool print_table_args, bool print_defaults)
Definition: ruleutils.c:3297
static void identify_join_columns(JoinExpr *j, RangeTblEntry *jrte, deparse_columns *colinfo)
Definition: ruleutils.c:5064
static void print_function_rettype(StringInfo buf, HeapTuple proctup)
Definition: ruleutils.c:3259
char * generate_opclass_name(Oid opclass)
Definition: ruleutils.c:12898
static void set_deparse_plan(deparse_namespace *dpns, Plan *plan)
Definition: ruleutils.c:5151
static void get_merge_query_def(Query *query, deparse_context *context)
Definition: ruleutils.c:7401
static void resolve_special_varno(Node *node, deparse_context *context, rsv_callback callback, void *callback_arg)
Definition: ruleutils.c:7908
static void get_json_format(JsonFormat *format, StringInfo buf)
Definition: ruleutils.c:11626
char * get_range_partbound_string(List *bound_datums)
Definition: ruleutils.c:13677
static void get_tablefunc(TableFunc *tf, deparse_context *context, bool showimplicit)
Definition: ruleutils.c:12250
static void get_rule_expr_toplevel(Node *node, deparse_context *context, bool showimplicit)
Definition: ruleutils.c:10634
static RangeTblEntry * get_simple_values_rte(Query *query, TupleDesc resultDesc)
Definition: ruleutils.c:6038
static void get_coercion_expr(Node *arg, deparse_context *context, Oid resulttype, int32 resulttypmod, Node *parentNode)
Definition: ruleutils.c:11400
static void push_child_plan(deparse_namespace *dpns, Plan *plan, deparse_namespace *save_dpns)
Definition: ruleutils.c:5262
static void get_update_query_def(Query *query, deparse_context *context)
Definition: ruleutils.c:7150
static void get_json_constructor_options(JsonConstructorExpr *ctor, StringInfo buf)
Definition: ruleutils.c:11737
static void get_basic_select_query(Query *query, deparse_context *context)
Definition: ruleutils.c:6107
static bool isSimpleNode(Node *node, Node *parentNode, int prettyFlags)
Definition: ruleutils.c:8849
static void get_with_clause(Query *query, deparse_context *context)
Definition: ruleutils.c:5766
#define PRETTYINDENT_VAR
Definition: ruleutils.c:83
static void destroy_colinfo_names_hash(deparse_columns *colinfo)
Definition: ruleutils.c:5048
static char * generate_relation_name(Oid relid, List *namespaces)
Definition: ruleutils.c:13152
static void get_windowfunc_expr(WindowFunc *wfunc, deparse_context *context)
Definition: ruleutils.c:11024
static char * get_variable(Var *var, int levelsup, bool istoplevel, deparse_context *context)
Definition: ruleutils.c:7605
Datum pg_get_serial_sequence(PG_FUNCTION_ARGS)
Definition: ruleutils.c:2832
static char * generate_operator_name(Oid operid, Oid arg1, Oid arg2)
Definition: ruleutils.c:13363
static void get_from_clause_item(Node *jtnode, Query *query, deparse_context *context)
Definition: ruleutils.c:12363
Datum pg_get_function_arguments(PG_FUNCTION_ARGS)
Definition: ruleutils.c:3178
static void get_json_table(TableFunc *tf, deparse_context *context, bool showimplicit)
Definition: ruleutils.c:12181
#define PRETTYFLAG_SCHEMA
Definition: ruleutils.c:90
static void get_select_query_def(Query *query, deparse_context *context)
Definition: ruleutils.c:5905
static void get_opclass_name(Oid opclass, Oid actual_datatype, StringInfo buf)
Definition: ruleutils.c:12860
Datum pg_get_viewdef_name(PG_FUNCTION_ARGS)
Definition: ruleutils.c:736
Datum pg_get_userbyid(PG_FUNCTION_ARGS)
Definition: ruleutils.c:2794
static void get_agg_expr_helper(Aggref *aggref, deparse_context *context, Aggref *original_aggref, const char *funcname, const char *options, bool is_json_objectagg)
Definition: ruleutils.c:10882
#define RULE_INDEXDEF_PRETTY
Definition: ruleutils.h:24
#define RULE_INDEXDEF_KEYS_ONLY
Definition: ruleutils.h:25
bool standard_conforming_strings
Definition: scan.l:70
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:271
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:864
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:822
int SPI_fnumber(TupleDesc tupdesc, const char *fname)
Definition: spi.c:1175
uint64 SPI_processed
Definition: spi.c:44
SPITupleTable * SPI_tuptable
Definition: spi.c:45
int SPI_connect(void)
Definition: spi.c:94
int SPI_finish(void)
Definition: spi.c:182
int SPI_execute_plan(SPIPlanPtr plan, Datum *Values, const char *Nulls, bool read_only, long tcount)
Definition: spi.c:672
SPIPlanPtr SPI_prepare(const char *src, int nargs, Oid *argtypes)
Definition: spi.c:860
int SPI_keepplan(SPIPlanPtr plan)
Definition: spi.c:976
char * SPI_getvalue(HeapTuple tuple, TupleDesc tupdesc, int fnumber)
Definition: spi.c:1220
Datum SPI_getbinval(HeapTuple tuple, TupleDesc tupdesc, int fnumber, bool *isnull)
Definition: spi.c:1252
#define SPI_OK_FINISH
Definition: spi.h:83
#define SPI_OK_SELECT
Definition: spi.h:86
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:205
Relation try_relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:88
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:47
void check_stack_depth(void)
Definition: stack_depth.c:95
#define BTEqualStrategyNumber
Definition: stratnum.h:31
StringInfo makeStringInfo(void)
Definition: stringinfo.c:72
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:126
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:145
void appendBinaryStringInfo(StringInfo str, const void *data, int datalen)
Definition: stringinfo.c:281
void appendStringInfoSpaces(StringInfo str, int count)
Definition: stringinfo.c:260
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:230
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:242
void initStringInfo(StringInfo str)
Definition: stringinfo.c:97
Oid aggfnoid
Definition: primnodes.h:463
List * aggdistinct
Definition: primnodes.h:493
List * aggdirectargs
Definition: primnodes.h:484
List * args
Definition: primnodes.h:487
Expr * aggfilter
Definition: primnodes.h:496
List * aggorder
Definition: primnodes.h:490
Index child_relid
Definition: pathnodes.h:3105
Index parent_relid
Definition: pathnodes.h:3104
int num_child_cols
Definition: pathnodes.h:3140
BoolExprType boolop
Definition: primnodes.h:958
List * args
Definition: primnodes.h:959
BoolTestType booltesttype
Definition: primnodes.h:1994
Expr * arg
Definition: primnodes.h:1993
Expr * arg
Definition: primnodes.h:1332
Expr * defresult
Definition: primnodes.h:1334
List * args
Definition: primnodes.h:1333
List * args
Definition: primnodes.h:1503
Expr * arg
Definition: primnodes.h:1226
Oid resulttype
Definition: primnodes.h:1227
Expr * arg
Definition: primnodes.h:1298
CTEMaterialize ctematerialized
Definition: parsenodes.h:1708
Oid consttype
Definition: primnodes.h:329
char * cursor_name
Definition: primnodes.h:2109
AttrNumber fieldnum
Definition: primnodes.h:1148
Expr * arg
Definition: primnodes.h:1147
List * newvals
Definition: primnodes.h:1179
Node * quals
Definition: primnodes.h:2344
List * fromlist
Definition: primnodes.h:2343
Oid funcid
Definition: primnodes.h:769
List * args
Definition: primnodes.h:787
List * content
Definition: parsenodes.h:1539
Size keysize
Definition: hsearch.h:75
Size entrysize
Definition: hsearch.h:76
MemoryContext hcxt
Definition: hsearch.h:86
Definition: dynahash.c:222
bool amcanorder
Definition: amapi.h:244
Node * expr
Definition: primnodes.h:1802
JsonBehaviorType btype
Definition: primnodes.h:1801
JsonReturning * returning
Definition: primnodes.h:1721
JsonConstructorType type
Definition: primnodes.h:1717
Node * formatted_expr
Definition: primnodes.h:1834
List * passing_values
Definition: primnodes.h:1847
JsonBehavior * on_empty
Definition: primnodes.h:1850
JsonFormat * format
Definition: primnodes.h:1837
List * passing_names
Definition: primnodes.h:1846
Node * path_spec
Definition: primnodes.h:1840
JsonReturning * returning
Definition: primnodes.h:1843
JsonWrapper wrapper
Definition: primnodes.h:1861
JsonExprOp op
Definition: primnodes.h:1828
JsonBehavior * on_error
Definition: primnodes.h:1851
bool omit_quotes
Definition: primnodes.h:1864
JsonFormatType format_type
Definition: primnodes.h:1662
JsonValueType item_type
Definition: primnodes.h:1748
JsonFormat * format
Definition: primnodes.h:1674
JsonTablePath * path
Definition: primnodes.h:1909
JsonTablePlan * child
Definition: primnodes.h:1918
Const * value
Definition: primnodes.h:1882
JsonTablePlan * rplan
Definition: primnodes.h:1939
JsonTablePlan * lplan
Definition: primnodes.h:1938
JsonFormat * format
Definition: primnodes.h:1696
Expr * raw_expr
Definition: primnodes.h:1694
Definition: pg_list.h:54
List * args
Definition: primnodes.h:1529
MinMaxOp op
Definition: primnodes.h:1527
Expr * arg
Definition: primnodes.h:810
Var * paramval
Definition: plannodes.h:993
List * nestParams
Definition: plannodes.h:982
Definition: nodes.h:135
NullTestType nulltesttype
Definition: primnodes.h:1970
Expr * arg
Definition: primnodes.h:1969
List * arbiterElems
Definition: primnodes.h:2362
OnConflictAction action
Definition: primnodes.h:2359
List * onConflictSet
Definition: primnodes.h:2368
Node * onConflictWhere
Definition: primnodes.h:2369
Node * arbiterWhere
Definition: primnodes.h:2364
Oid opno
Definition: primnodes.h:837
List * args
Definition: primnodes.h:855
int paramid
Definition: primnodes.h:396
ParamKind paramkind
Definition: primnodes.h:395
PartitionRangeDatumKind kind
Definition: parsenodes.h:959
List * targetlist
Definition: plannodes.h:220
List * appendRelations
Definition: plannodes.h:127
List * subplans
Definition: plannodes.h:132
List * rtable
Definition: plannodes.h:109
List * rowMarks
Definition: parsenodes.h:233
bool groupDistinct
Definition: parsenodes.h:217
Node * mergeJoinCondition
Definition: parsenodes.h:196
Node * limitCount
Definition: parsenodes.h:230
FromExpr * jointree
Definition: parsenodes.h:182
List * returningList
Definition: parsenodes.h:214
Node * setOperations
Definition: parsenodes.h:235
List * cteList
Definition: parsenodes.h:173
OnConflictExpr * onConflict
Definition: parsenodes.h:203
List * groupClause
Definition: parsenodes.h:216
Node * havingQual
Definition: parsenodes.h:221
List * rtable
Definition: parsenodes.h:175
Node * limitOffset
Definition: parsenodes.h:229
CmdType commandType
Definition: parsenodes.h:121
LimitOption limitOption
Definition: parsenodes.h:231
Node * utilityStmt
Definition: parsenodes.h:141
List * mergeActionList
Definition: parsenodes.h:185
List * windowClause
Definition: parsenodes.h:223
List * targetList
Definition: parsenodes.h:198
List * groupingSets
Definition: parsenodes.h:219
List * distinctClause
Definition: parsenodes.h:225
List * sortClause
Definition: parsenodes.h:227
char * ctename
Definition: parsenodes.h:1225
TableFunc * tablefunc
Definition: parsenodes.h:1213
Index ctelevelsup
Definition: parsenodes.h:1227
bool funcordinality
Definition: parsenodes.h:1208
struct TableSampleClause * tablesample
Definition: parsenodes.h:1127
Query * subquery
Definition: parsenodes.h:1133
List * values_lists
Definition: parsenodes.h:1219
List * functions
Definition: parsenodes.h:1206
RTEKind rtekind
Definition: parsenodes.h:1076
char * relname
Definition: primnodes.h:83
Oid resulttype
Definition: primnodes.h:1204
Expr * arg
Definition: primnodes.h:1203
TupleDesc rd_att
Definition: rel.h:112
Expr * retexpr
Definition: primnodes.h:2163
List * args
Definition: primnodes.h:1434
LockClauseStrength strength
Definition: parsenodes.h:1609
LockWaitPolicy waitPolicy
Definition: parsenodes.h:1610
TupleDesc tupdesc
Definition: spi.h:25
HeapTuple * vals
Definition: spi.h:26
SQLValueFunctionOp op
Definition: primnodes.h:1567
SetOperation op
Definition: parsenodes.h:2252
Index tleSortGroupRef
Definition: parsenodes.h:1467
Definition: value.h:64
char * plan_name
Definition: primnodes.h:1091
List * args
Definition: primnodes.h:1110
List * paramIds
Definition: primnodes.h:1087
bool useHashTable
Definition: primnodes.h:1098
Node * testexpr
Definition: primnodes.h:1086
List * parParam
Definition: primnodes.h:1109
List * setParam
Definition: primnodes.h:1107
SubLinkType subLinkType
Definition: primnodes.h:1084
Expr * refassgnexpr
Definition: primnodes.h:722
List * refupperindexpr
Definition: primnodes.h:712
Expr * refexpr
Definition: primnodes.h:720
List * reflowerindexpr
Definition: primnodes.h:718
Node * docexpr
Definition: primnodes.h:120
Node * rowexpr
Definition: primnodes.h:122
List * colexprs
Definition: primnodes.h:132
TableFuncType functype
Definition: primnodes.h:114
Expr * expr
Definition: primnodes.h:2225
AttrNumber resno
Definition: primnodes.h:2227
Definition: primnodes.h:262
AttrNumber varattno
Definition: primnodes.h:274
int varno
Definition: primnodes.h:269
VarReturningType varreturningtype
Definition: primnodes.h:297
Index varlevelsup
Definition: primnodes.h:294
char * winname
Definition: plannodes.h:1228
Index winref
Definition: plannodes.h:1231
Node * startOffset
Definition: parsenodes.h:1576
List * partitionClause
Definition: parsenodes.h:1572
Node * endOffset
Definition: parsenodes.h:1577
List * orderClause
Definition: parsenodes.h:1574
List * args
Definition: primnodes.h:594
Index winref
Definition: primnodes.h:600
Expr * aggfilter
Definition: primnodes.h:596
Oid winfnoid
Definition: primnodes.h:586
List * args
Definition: primnodes.h:1619
bool indent
Definition: primnodes.h:1623
List * named_args
Definition: primnodes.h:1615
XmlExprOp op
Definition: primnodes.h:1611
List * parentUsing
Definition: ruleutils.c:276
HTAB * names_hash
Definition: ruleutils.c:308
char ** new_colnames
Definition: ruleutils.c:269
char ** colnames
Definition: ruleutils.c:252
int * rightattnos
Definition: ruleutils.c:298
List * usingNames
Definition: ruleutils.c:299
bool * is_new_col
Definition: ruleutils.c:270
int * leftattnos
Definition: ruleutils.c:297
TupleDesc resultDesc
Definition: ruleutils.c:116
StringInfo buf
Definition: ruleutils.c:114
List * targetList
Definition: ruleutils.c:117
bool colNamesVisible
Definition: ruleutils.c:123
List * namespaces
Definition: ruleutils.c:115
List * windowClause
Definition: ruleutils.c:118
Bitmapset * appendparents
Definition: ruleutils.c:126
List * rtable_names
Definition: ruleutils.c:165
List * inner_tlist
Definition: ruleutils.c:181
List * outer_tlist
Definition: ruleutils.c:180
char ** argnames
Definition: ruleutils.c:186
AppendRelInfo ** appendrels
Definition: ruleutils.c:169
char * ret_old_alias
Definition: ruleutils.c:170
List * rtable_columns
Definition: ruleutils.c:166
char * ret_new_alias
Definition: ruleutils.c:171
List * index_tlist
Definition: ruleutils.c:182
List * using_names
Definition: ruleutils.c:174
Definition: c.h:721
int16 values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:728
Definition: c.h:747
Definition: c.h:732
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:739
Definition: c.h:693
Definition: type.h:89
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:264
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:220
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:595
Datum SysCacheGetAttrNotNull(int cacheId, HeapTuple tup, AttrNumber attributeNumber)
Definition: syscache.c:625
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:40
static void callback(struct sockaddr *addr, struct sockaddr *mask, void *unused)
Definition: test_ifaddrs.c:46
TargetEntry * get_sortgroupref_tle(Index sortref, List *targetList)
Definition: tlist.c:345
int count_nonjunk_tlist_entries(List *tlist)
Definition: tlist.c:186
#define ReleaseTupleDesc(tupdesc)
Definition: tupdesc.h:219
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)
Definition: tupdesc.h:160
TupleDesc lookup_rowtype_tupdesc(Oid type_id, int32 typmod)
Definition: typcache.c:1921
TypeCacheEntry * lookup_type_cache(Oid type_id, int flags)
Definition: typcache.c:386
#define TYPECACHE_GT_OPR
Definition: typcache.h:140
#define TYPECACHE_LT_OPR
Definition: typcache.h:139
String * makeString(char *str)
Definition: value.c:63
#define strVal(v)
Definition: value.h:82
Node * flatten_group_exprs(PlannerInfo *root, Query *query, Node *node)
Definition: var.c:968
Relids pull_varnos(PlannerInfo *root, Node *node)
Definition: var.c:114
static char * VARDATA_ANY(const void *PTR)
Definition: varatt.h:486
text * cstring_to_text_with_len(const char *s, int len)
Definition: varlena.c:193
bool SplitGUCList(char *rawstring, char separator, List **namelist)
Definition: varlena.c:2992
text * cstring_to_text(const char *s)
Definition: varlena.c:181
char * text_to_cstring(const text *t)
Definition: varlena.c:214
List * textToQualifiedNameList(text *textval)
Definition: varlena.c:2686
const char * type
const char * name
char * map_xml_name_to_sql_identifier(const char *name)
Definition: xml.c:2474
@ XML_STANDALONE_NO_VALUE
Definition: xml.h:29
@ XML_STANDALONE_YES
Definition: xml.h:27
@ XML_STANDALONE_NO
Definition: xml.h:28
static void convert(const int32 val, char *const buf)
Definition: zic.c:1992