1 /*-------------------------------------------------------------------------
4 * Functions to convert stored expressions/querytrees back to
7 * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
12 * $PostgreSQL: pgsql/src/backend/utils/adt/ruleutils.c,v 1.317 2009/12/15 17:57:47 tgl Exp $
14 *-------------------------------------------------------------------------
21 #include "access/genam.h"
22 #include "access/sysattr.h"
23 #include "catalog/dependency.h"
24 #include "catalog/indexing.h"
25 #include "catalog/pg_authid.h"
26 #include "catalog/pg_constraint.h"
27 #include "catalog/pg_depend.h"
28 #include "catalog/pg_language.h"
29 #include "catalog/pg_opclass.h"
30 #include "catalog/pg_operator.h"
31 #include "catalog/pg_proc.h"
32 #include "catalog/pg_trigger.h"
33 #include "catalog/pg_type.h"
34 #include "commands/defrem.h"
35 #include "commands/tablespace.h"
36 #include "executor/spi.h"
38 #include "nodes/makefuncs.h"
39 #include "nodes/nodeFuncs.h"
40 #include "optimizer/clauses.h"
41 #include "optimizer/tlist.h"
42 #include "parser/keywords.h"
43 #include "parser/parse_func.h"
44 #include "parser/parse_oper.h"
45 #include "parser/parser.h"
46 #include "parser/parsetree.h"
47 #include "rewrite/rewriteHandler.h"
48 #include "rewrite/rewriteManip.h"
49 #include "rewrite/rewriteSupport.h"
50 #include "utils/array.h"
51 #include "utils/builtins.h"
52 #include "utils/fmgroids.h"
53 #include "utils/lsyscache.h"
54 #include "utils/tqual.h"
55 #include "utils/syscache.h"
56 #include "utils/typcache.h"
57 #include "utils/xml.h"
61 * Pretty formatting constants
66 #define PRETTYINDENT_STD 8
67 #define PRETTYINDENT_JOIN 13
68 #define PRETTYINDENT_JOIN_ON (PRETTYINDENT_JOIN-PRETTYINDENT_STD)
69 #define PRETTYINDENT_VAR 4
72 #define PRETTYFLAG_PAREN 1
73 #define PRETTYFLAG_INDENT 2
75 /* macro to test if pretty action needed */
76 #define PRETTY_PAREN(context) ((context)->prettyFlags & PRETTYFLAG_PAREN)
77 #define PRETTY_INDENT(context) ((context)->prettyFlags & PRETTYFLAG_INDENT)
85 /* Context info needed for invoking a recursive querytree display routine */
88 StringInfo buf; /* output buffer to append to */
89 List *namespaces; /* List of deparse_namespace nodes */
90 List *windowClause; /* Current query level's WINDOW clause */
91 List *windowTList; /* targetlist for resolving WINDOW clause */
92 int prettyFlags; /* enabling of pretty-print functions */
93 int indentLevel; /* current indent level for prettyprint */
94 bool varprefix; /* TRUE to print prefixes on Vars */
98 * Each level of query context around a subtree needs a level of Var namespace.
99 * A Var having varlevelsup=N refers to the N'th item (counting from 0) in
100 * the current context's namespaces list.
102 * The rangetable is the list of actual RTEs from the query tree, and the
103 * cte list is the list of actual CTEs.
105 * For deparsing plan trees, we provide for outer and inner subplan nodes.
106 * The tlists of these nodes are used to resolve OUTER and INNER varnos.
107 * Also, in the plan-tree case we don't have access to the parse-time CTE
108 * list, so we need a list of subplans instead.
112 List *rtable; /* List of RangeTblEntry nodes */
113 List *ctes; /* List of CommonTableExpr nodes */
114 List *subplans; /* List of subplans, in plan-tree case */
115 Plan *outer_plan; /* OUTER subplan, or NULL if none */
116 Plan *inner_plan; /* INNER subplan, or NULL if none */
124 static SPIPlanPtr plan_getrulebyoid = NULL;
125 static const char *query_getrulebyoid = "SELECT * FROM pg_catalog.pg_rewrite WHERE oid = $1";
126 static SPIPlanPtr plan_getviewrule = NULL;
127 static const char *query_getviewrule = "SELECT * FROM pg_catalog.pg_rewrite WHERE ev_class = $1 AND rulename = $2";
133 * Most of these functions used to use fixed-size buffers to build their
134 * results. Now, they take an (already initialized) StringInfo object
135 * as a parameter, and append their text output to its contents.
138 static char *deparse_expression_pretty(Node *expr, List *dpcontext,
139 bool forceprefix, bool showimplicit,
140 int prettyFlags, int startIndent);
141 static char *pg_get_viewdef_worker(Oid viewoid, int prettyFlags);
142 static char *pg_get_triggerdef_worker(Oid trigid, bool pretty);
143 static void decompile_column_index_array(Datum column_index_array, Oid relId,
145 static char *pg_get_ruledef_worker(Oid ruleoid, int prettyFlags);
146 static char *pg_get_indexdef_worker(Oid indexrelid, int colno,
147 const Oid *excludeOps,
148 bool attrsOnly, bool showTblSpc,
150 static char *pg_get_constraintdef_worker(Oid constraintId, bool fullCommand,
152 static text *pg_get_expr_worker(text *expr, Oid relid, const char *relname,
154 static int print_function_arguments(StringInfo buf, HeapTuple proctup,
155 bool print_table_args, bool print_defaults);
156 static void print_function_rettype(StringInfo buf, HeapTuple proctup);
157 static void make_ruledef(StringInfo buf, HeapTuple ruletup, TupleDesc rulettc,
159 static void make_viewdef(StringInfo buf, HeapTuple ruletup, TupleDesc rulettc,
161 static void get_query_def(Query *query, StringInfo buf, List *parentnamespace,
162 TupleDesc resultDesc, int prettyFlags, int startIndent);
163 static void get_values_def(List *values_lists, deparse_context *context);
164 static void get_with_clause(Query *query, deparse_context *context);
165 static void get_select_query_def(Query *query, deparse_context *context,
166 TupleDesc resultDesc);
167 static void get_insert_query_def(Query *query, deparse_context *context);
168 static void get_update_query_def(Query *query, deparse_context *context);
169 static void get_delete_query_def(Query *query, deparse_context *context);
170 static void get_utility_query_def(Query *query, deparse_context *context);
171 static void get_basic_select_query(Query *query, deparse_context *context,
172 TupleDesc resultDesc);
173 static void get_target_list(List *targetList, deparse_context *context,
174 TupleDesc resultDesc);
175 static void get_setop_query(Node *setOp, Query *query,
176 deparse_context *context,
177 TupleDesc resultDesc);
178 static Node *get_rule_sortgroupclause(SortGroupClause *srt, List *tlist,
180 deparse_context *context);
181 static void get_rule_orderby(List *orderList, List *targetList,
182 bool force_colno, deparse_context *context);
183 static void get_rule_windowclause(Query *query, deparse_context *context);
184 static void get_rule_windowspec(WindowClause *wc, List *targetList,
185 deparse_context *context);
186 static void push_plan(deparse_namespace *dpns, Plan *subplan);
187 static char *get_variable(Var *var, int levelsup, bool showstar,
188 deparse_context *context);
189 static RangeTblEntry *find_rte_by_refname(const char *refname,
190 deparse_context *context);
191 static const char *get_simple_binary_op_name(OpExpr *expr);
192 static bool isSimpleNode(Node *node, Node *parentNode, int prettyFlags);
193 static void appendContextKeyword(deparse_context *context, const char *str,
194 int indentBefore, int indentAfter, int indentPlus);
195 static void get_rule_expr(Node *node, deparse_context *context,
197 static void get_oper_expr(OpExpr *expr, deparse_context *context);
198 static void get_func_expr(FuncExpr *expr, deparse_context *context,
200 static void get_agg_expr(Aggref *aggref, deparse_context *context);
201 static void get_windowfunc_expr(WindowFunc *wfunc, deparse_context *context);
202 static void get_coercion_expr(Node *arg, deparse_context *context,
203 Oid resulttype, int32 resulttypmod,
205 static void get_const_expr(Const *constval, deparse_context *context,
207 static void simple_quote_literal(StringInfo buf, const char *val);
208 static void get_sublink_expr(SubLink *sublink, deparse_context *context);
209 static void get_from_clause(Query *query, const char *prefix,
210 deparse_context *context);
211 static void get_from_clause_item(Node *jtnode, Query *query,
212 deparse_context *context);
213 static void get_from_clause_alias(Alias *alias, RangeTblEntry *rte,
214 deparse_context *context);
215 static void get_from_clause_coldeflist(List *names, List *types, List *typmods,
216 deparse_context *context);
217 static void get_opclass_name(Oid opclass, Oid actual_datatype,
219 static Node *processIndirection(Node *node, deparse_context *context,
221 static void printSubscripts(ArrayRef *aref, deparse_context *context);
222 static char *generate_relation_name(Oid relid, List *namespaces);
223 static char *generate_function_name(Oid funcid, int nargs, List *argnames,
224 Oid *argtypes, bool *is_variadic);
225 static char *generate_operator_name(Oid operid, Oid arg1, Oid arg2);
226 static text *string_to_text(char *str);
227 static char *flatten_reloptions(Oid relid);
229 #define only_marker(rte) ((rte)->inh ? "" : "ONLY ")
233 * get_ruledef - Do it all and return a text
234 * that could be used as a statement
235 * to recreate the rule
239 pg_get_ruledef(PG_FUNCTION_ARGS)
241 Oid ruleoid = PG_GETARG_OID(0);
243 PG_RETURN_TEXT_P(string_to_text(pg_get_ruledef_worker(ruleoid, 0)));
248 pg_get_ruledef_ext(PG_FUNCTION_ARGS)
250 Oid ruleoid = PG_GETARG_OID(0);
251 bool pretty = PG_GETARG_BOOL(1);
254 prettyFlags = pretty ? PRETTYFLAG_PAREN | PRETTYFLAG_INDENT : 0;
255 PG_RETURN_TEXT_P(string_to_text(pg_get_ruledef_worker(ruleoid, prettyFlags)));
260 pg_get_ruledef_worker(Oid ruleoid, int prettyFlags)
270 * Do this first so that string is alloc'd in outer context not SPI's.
272 initStringInfo(&buf);
275 * Connect to SPI manager
277 if (SPI_connect() != SPI_OK_CONNECT)
278 elog(ERROR, "SPI_connect failed");
281 * On the first call prepare the plan to lookup pg_rewrite. We read
282 * pg_rewrite over the SPI manager instead of using the syscache to be
283 * checked for read access on pg_rewrite.
285 if (plan_getrulebyoid == NULL)
290 argtypes[0] = OIDOID;
291 plan = SPI_prepare(query_getrulebyoid, 1, argtypes);
293 elog(ERROR, "SPI_prepare failed for \"%s\"", query_getrulebyoid);
294 plan_getrulebyoid = SPI_saveplan(plan);
298 * Get the pg_rewrite tuple for this rule
300 args[0] = ObjectIdGetDatum(ruleoid);
302 spirc = SPI_execute_plan(plan_getrulebyoid, args, nulls, true, 1);
303 if (spirc != SPI_OK_SELECT)
304 elog(ERROR, "failed to get pg_rewrite tuple for rule %u", ruleoid);
305 if (SPI_processed != 1)
306 appendStringInfo(&buf, "-");
310 * Get the rule's definition and put it into executor's memory
312 ruletup = SPI_tuptable->vals[0];
313 rulettc = SPI_tuptable->tupdesc;
314 make_ruledef(&buf, ruletup, rulettc, prettyFlags);
318 * Disconnect from SPI manager
320 if (SPI_finish() != SPI_OK_FINISH)
321 elog(ERROR, "SPI_finish failed");
328 * get_viewdef - Mainly the same thing, but we
329 * only return the SELECT part of a view
333 pg_get_viewdef(PG_FUNCTION_ARGS)
336 Oid viewoid = PG_GETARG_OID(0);
338 PG_RETURN_TEXT_P(string_to_text(pg_get_viewdef_worker(viewoid, 0)));
343 pg_get_viewdef_ext(PG_FUNCTION_ARGS)
346 Oid viewoid = PG_GETARG_OID(0);
347 bool pretty = PG_GETARG_BOOL(1);
350 prettyFlags = pretty ? PRETTYFLAG_PAREN | PRETTYFLAG_INDENT : 0;
351 PG_RETURN_TEXT_P(string_to_text(pg_get_viewdef_worker(viewoid, prettyFlags)));
355 pg_get_viewdef_name(PG_FUNCTION_ARGS)
357 /* By qualified name */
358 text *viewname = PG_GETARG_TEXT_P(0);
362 viewrel = makeRangeVarFromNameList(textToQualifiedNameList(viewname));
363 viewoid = RangeVarGetRelid(viewrel, false);
365 PG_RETURN_TEXT_P(string_to_text(pg_get_viewdef_worker(viewoid, 0)));
370 pg_get_viewdef_name_ext(PG_FUNCTION_ARGS)
372 /* By qualified name */
373 text *viewname = PG_GETARG_TEXT_P(0);
374 bool pretty = PG_GETARG_BOOL(1);
379 prettyFlags = pretty ? PRETTYFLAG_PAREN | PRETTYFLAG_INDENT : 0;
380 viewrel = makeRangeVarFromNameList(textToQualifiedNameList(viewname));
381 viewoid = RangeVarGetRelid(viewrel, false);
383 PG_RETURN_TEXT_P(string_to_text(pg_get_viewdef_worker(viewoid, prettyFlags)));
387 * Common code for by-OID and by-name variants of pg_get_viewdef
390 pg_get_viewdef_worker(Oid viewoid, int prettyFlags)
400 * Do this first so that string is alloc'd in outer context not SPI's.
402 initStringInfo(&buf);
405 * Connect to SPI manager
407 if (SPI_connect() != SPI_OK_CONNECT)
408 elog(ERROR, "SPI_connect failed");
411 * On the first call prepare the plan to lookup pg_rewrite. We read
412 * pg_rewrite over the SPI manager instead of using the syscache to be
413 * checked for read access on pg_rewrite.
415 if (plan_getviewrule == NULL)
420 argtypes[0] = OIDOID;
421 argtypes[1] = NAMEOID;
422 plan = SPI_prepare(query_getviewrule, 2, argtypes);
424 elog(ERROR, "SPI_prepare failed for \"%s\"", query_getviewrule);
425 plan_getviewrule = SPI_saveplan(plan);
429 * Get the pg_rewrite tuple for the view's SELECT rule
431 args[0] = ObjectIdGetDatum(viewoid);
432 args[1] = PointerGetDatum(ViewSelectRuleName);
435 spirc = SPI_execute_plan(plan_getviewrule, args, nulls, true, 2);
436 if (spirc != SPI_OK_SELECT)
437 elog(ERROR, "failed to get pg_rewrite tuple for view %u", viewoid);
438 if (SPI_processed != 1)
439 appendStringInfo(&buf, "Not a view");
443 * Get the rule's definition and put it into executor's memory
445 ruletup = SPI_tuptable->vals[0];
446 rulettc = SPI_tuptable->tupdesc;
447 make_viewdef(&buf, ruletup, rulettc, prettyFlags);
451 * Disconnect from SPI manager
453 if (SPI_finish() != SPI_OK_FINISH)
454 elog(ERROR, "SPI_finish failed");
460 * get_triggerdef - Get the definition of a trigger
464 pg_get_triggerdef(PG_FUNCTION_ARGS)
466 Oid trigid = PG_GETARG_OID(0);
468 PG_RETURN_TEXT_P(string_to_text(pg_get_triggerdef_worker(trigid, false)));
472 pg_get_triggerdef_ext(PG_FUNCTION_ARGS)
474 Oid trigid = PG_GETARG_OID(0);
475 bool pretty = PG_GETARG_BOOL(1);
477 PG_RETURN_TEXT_P(string_to_text(pg_get_triggerdef_worker(trigid, pretty)));
481 pg_get_triggerdef_worker(Oid trigid, bool pretty)
484 Form_pg_trigger trigrec;
495 * Fetch the pg_trigger tuple by the Oid of the trigger
497 tgrel = heap_open(TriggerRelationId, AccessShareLock);
499 ScanKeyInit(&skey[0],
500 ObjectIdAttributeNumber,
501 BTEqualStrategyNumber, F_OIDEQ,
502 ObjectIdGetDatum(trigid));
504 tgscan = systable_beginscan(tgrel, TriggerOidIndexId, true,
505 SnapshotNow, 1, skey);
507 ht_trig = systable_getnext(tgscan);
509 if (!HeapTupleIsValid(ht_trig))
510 elog(ERROR, "could not find tuple for trigger %u", trigid);
512 trigrec = (Form_pg_trigger) GETSTRUCT(ht_trig);
515 * Start the trigger definition. Note that the trigger's name should never
516 * be schema-qualified, but the trigger rel's name may be.
518 initStringInfo(&buf);
520 tgname = NameStr(trigrec->tgname);
521 appendStringInfo(&buf, "CREATE %sTRIGGER %s",
522 trigrec->tgisconstraint ? "CONSTRAINT " : "",
523 quote_identifier(tgname));
524 appendStringInfoString(&buf, pretty ? "\n " : " ");
526 if (TRIGGER_FOR_BEFORE(trigrec->tgtype))
527 appendStringInfo(&buf, "BEFORE");
529 appendStringInfo(&buf, "AFTER");
530 if (TRIGGER_FOR_INSERT(trigrec->tgtype))
532 appendStringInfo(&buf, " INSERT");
535 if (TRIGGER_FOR_DELETE(trigrec->tgtype))
538 appendStringInfo(&buf, " OR DELETE");
540 appendStringInfo(&buf, " DELETE");
543 if (TRIGGER_FOR_UPDATE(trigrec->tgtype))
546 appendStringInfo(&buf, " OR UPDATE");
548 appendStringInfo(&buf, " UPDATE");
550 /* tgattr is first var-width field, so OK to access directly */
551 if (trigrec->tgattr.dim1 > 0)
555 appendStringInfoString(&buf, " OF ");
556 for (i = 0; i < trigrec->tgattr.dim1; i++)
561 appendStringInfoString(&buf, ", ");
562 attname = get_relid_attribute_name(trigrec->tgrelid,
563 trigrec->tgattr.values[i]);
564 appendStringInfoString(&buf, quote_identifier(attname));
568 if (TRIGGER_FOR_TRUNCATE(trigrec->tgtype))
571 appendStringInfo(&buf, " OR TRUNCATE");
573 appendStringInfo(&buf, " TRUNCATE");
576 appendStringInfo(&buf, " ON %s",
577 generate_relation_name(trigrec->tgrelid, NIL));
578 appendStringInfoString(&buf, pretty ? "\n " : " ");
580 if (trigrec->tgisconstraint)
582 if (OidIsValid(trigrec->tgconstrrelid))
584 appendStringInfo(&buf, "FROM %s",
585 generate_relation_name(trigrec->tgconstrrelid, NIL));
586 appendStringInfoString(&buf, pretty ? "\n " : " ");
588 if (!trigrec->tgdeferrable)
589 appendStringInfo(&buf, "NOT ");
590 appendStringInfo(&buf, "DEFERRABLE INITIALLY ");
591 if (trigrec->tginitdeferred)
592 appendStringInfo(&buf, "DEFERRED");
594 appendStringInfo(&buf, "IMMEDIATE");
595 appendStringInfoString(&buf, pretty ? "\n " : " ");
598 if (TRIGGER_FOR_ROW(trigrec->tgtype))
599 appendStringInfo(&buf, "FOR EACH ROW");
601 appendStringInfo(&buf, "FOR EACH STATEMENT");
602 appendStringInfoString(&buf, pretty ? "\n " : " ");
604 /* If the trigger has a WHEN qualification, add that */
605 value = fastgetattr(ht_trig, Anum_pg_trigger_tgqual,
606 tgrel->rd_att, &isnull);
610 deparse_context context;
611 deparse_namespace dpns;
612 RangeTblEntry *oldrte;
613 RangeTblEntry *newrte;
615 appendStringInfoString(&buf, "WHEN (");
617 qual = stringToNode(TextDatumGetCString(value));
619 /* Build minimal OLD and NEW RTEs for the rel */
620 oldrte = makeNode(RangeTblEntry);
621 oldrte->rtekind = RTE_RELATION;
622 oldrte->relid = trigrec->tgrelid;
623 oldrte->eref = makeAlias("old", NIL);
625 oldrte->inFromCl = true;
627 newrte = makeNode(RangeTblEntry);
628 newrte->rtekind = RTE_RELATION;
629 newrte->relid = trigrec->tgrelid;
630 newrte->eref = makeAlias("new", NIL);
632 newrte->inFromCl = true;
634 /* Build two-element rtable */
635 dpns.rtable = list_make2(oldrte, newrte);
638 dpns.outer_plan = dpns.inner_plan = NULL;
640 /* Set up context with one-deep namespace stack */
642 context.namespaces = list_make1(&dpns);
643 context.windowClause = NIL;
644 context.windowTList = NIL;
645 context.varprefix = true;
646 context.prettyFlags = pretty ? PRETTYFLAG_PAREN | PRETTYFLAG_INDENT : 0;
647 context.indentLevel = PRETTYINDENT_STD;
649 get_rule_expr(qual, &context, false);
651 appendStringInfo(&buf, ")%s", pretty ? "\n " : " ");
654 appendStringInfo(&buf, "EXECUTE PROCEDURE %s(",
655 generate_function_name(trigrec->tgfoid, 0,
658 if (trigrec->tgnargs > 0)
663 value = fastgetattr(ht_trig, Anum_pg_trigger_tgargs,
664 tgrel->rd_att, &isnull);
666 elog(ERROR, "tgargs is null for trigger %u", trigid);
667 p = (char *) VARDATA(DatumGetByteaP(value));
668 for (i = 0; i < trigrec->tgnargs; i++)
671 appendStringInfo(&buf, ", ");
672 simple_quote_literal(&buf, p);
673 /* advance p to next string embedded in tgargs */
680 /* We deliberately do not put semi-colon at end */
681 appendStringInfo(&buf, ")");
684 systable_endscan(tgscan);
686 heap_close(tgrel, AccessShareLock);
692 * get_indexdef - Get the definition of an index
694 * In the extended version, there is a colno argument as well as pretty bool.
695 * if colno == 0, we want a complete index definition.
696 * if colno > 0, we only want the Nth index key's variable or expression.
698 * Note that the SQL-function versions of this omit any info about the
699 * index tablespace; this is intentional because pg_dump wants it that way.
700 * However pg_get_indexdef_string() includes index tablespace if not default.
704 pg_get_indexdef(PG_FUNCTION_ARGS)
706 Oid indexrelid = PG_GETARG_OID(0);
708 PG_RETURN_TEXT_P(string_to_text(pg_get_indexdef_worker(indexrelid, 0,
714 pg_get_indexdef_ext(PG_FUNCTION_ARGS)
716 Oid indexrelid = PG_GETARG_OID(0);
717 int32 colno = PG_GETARG_INT32(1);
718 bool pretty = PG_GETARG_BOOL(2);
721 prettyFlags = pretty ? PRETTYFLAG_PAREN | PRETTYFLAG_INDENT : 0;
722 PG_RETURN_TEXT_P(string_to_text(pg_get_indexdef_worker(indexrelid, colno,
729 /* Internal version that returns a palloc'd C string */
731 pg_get_indexdef_string(Oid indexrelid)
733 return pg_get_indexdef_worker(indexrelid, 0, NULL, false, true, 0);
736 /* Internal version that just reports the column definitions */
738 pg_get_indexdef_columns(Oid indexrelid, bool pretty)
742 prettyFlags = pretty ? PRETTYFLAG_PAREN | PRETTYFLAG_INDENT : 0;
743 return pg_get_indexdef_worker(indexrelid, 0, NULL, true, false, prettyFlags);
747 * Internal workhorse to decompile an index definition.
749 * This is now used for exclusion constraints as well: if excludeOps is not
750 * NULL then it points to an array of exclusion operator OIDs.
753 pg_get_indexdef_worker(Oid indexrelid, int colno,
754 const Oid *excludeOps,
755 bool attrsOnly, bool showTblSpc,
758 /* might want a separate isConstraint parameter later */
759 bool isConstraint = (excludeOps != NULL);
763 Form_pg_index idxrec;
764 Form_pg_class idxrelrec;
767 ListCell *indexpr_item;
773 Datum indoptionDatum;
776 int2vector *indoption;
782 * Fetch the pg_index tuple by the Oid of the index
784 ht_idx = SearchSysCache(INDEXRELID,
785 ObjectIdGetDatum(indexrelid),
787 if (!HeapTupleIsValid(ht_idx))
788 elog(ERROR, "cache lookup failed for index %u", indexrelid);
789 idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
791 indrelid = idxrec->indrelid;
792 Assert(indexrelid == idxrec->indexrelid);
794 /* Must get indclass and indoption the hard way */
795 indclassDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
796 Anum_pg_index_indclass, &isnull);
798 indclass = (oidvector *) DatumGetPointer(indclassDatum);
799 indoptionDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
800 Anum_pg_index_indoption, &isnull);
802 indoption = (int2vector *) DatumGetPointer(indoptionDatum);
805 * Fetch the pg_class tuple of the index relation
807 ht_idxrel = SearchSysCache(RELOID,
808 ObjectIdGetDatum(indexrelid),
810 if (!HeapTupleIsValid(ht_idxrel))
811 elog(ERROR, "cache lookup failed for relation %u", indexrelid);
812 idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
815 * Fetch the pg_am tuple of the index' access method
817 ht_am = SearchSysCache(AMOID,
818 ObjectIdGetDatum(idxrelrec->relam),
820 if (!HeapTupleIsValid(ht_am))
821 elog(ERROR, "cache lookup failed for access method %u",
823 amrec = (Form_pg_am) GETSTRUCT(ht_am);
826 * Get the index expressions, if any. (NOTE: we do not use the relcache
827 * versions of the expressions and predicate, because we want to display
828 * non-const-folded expressions.)
830 if (!heap_attisnull(ht_idx, Anum_pg_index_indexprs))
836 exprsDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
837 Anum_pg_index_indexprs, &isnull);
839 exprsString = TextDatumGetCString(exprsDatum);
840 indexprs = (List *) stringToNode(exprsString);
846 indexpr_item = list_head(indexprs);
848 context = deparse_context_for(get_rel_name(indrelid), indrelid);
851 * Start the index definition. Note that the index's name should never be
852 * schema-qualified, but the indexed rel's name may be.
854 initStringInfo(&buf);
859 appendStringInfo(&buf, "CREATE %sINDEX %s ON %s USING %s (",
860 idxrec->indisunique ? "UNIQUE " : "",
861 quote_identifier(NameStr(idxrelrec->relname)),
862 generate_relation_name(indrelid, NIL),
863 quote_identifier(NameStr(amrec->amname)));
864 else /* currently, must be EXCLUDE constraint */
865 appendStringInfo(&buf, "EXCLUDE USING %s (",
866 quote_identifier(NameStr(amrec->amname)));
870 * Report the indexed attributes
873 for (keyno = 0; keyno < idxrec->indnatts; keyno++)
875 AttrNumber attnum = idxrec->indkey.values[keyno];
876 int16 opt = indoption->values[keyno];
879 appendStringInfoString(&buf, sep);
884 /* Simple index column */
887 attname = get_relid_attribute_name(indrelid, attnum);
888 if (!colno || colno == keyno + 1)
889 appendStringInfoString(&buf, quote_identifier(attname));
890 keycoltype = get_atttype(indrelid, attnum);
894 /* expressional index */
897 if (indexpr_item == NULL)
898 elog(ERROR, "too few entries in indexprs list");
899 indexkey = (Node *) lfirst(indexpr_item);
900 indexpr_item = lnext(indexpr_item);
902 str = deparse_expression_pretty(indexkey, context, false, false,
904 if (!colno || colno == keyno + 1)
906 /* Need parens if it's not a bare function call */
907 if (indexkey && IsA(indexkey, FuncExpr) &&
908 ((FuncExpr *) indexkey)->funcformat == COERCE_EXPLICIT_CALL)
909 appendStringInfoString(&buf, str);
911 appendStringInfo(&buf, "(%s)", str);
913 keycoltype = exprType(indexkey);
916 if (!attrsOnly && (!colno || colno == keyno + 1))
918 /* Add the operator class name, if not default */
919 get_opclass_name(indclass->values[keyno], keycoltype, &buf);
921 /* Add options if relevant */
922 if (amrec->amcanorder)
924 /* if it supports sort ordering, report DESC and NULLS opts */
925 if (opt & INDOPTION_DESC)
927 appendStringInfo(&buf, " DESC");
928 /* NULLS FIRST is the default in this case */
929 if (!(opt & INDOPTION_NULLS_FIRST))
930 appendStringInfo(&buf, " NULLS LAST");
934 if (opt & INDOPTION_NULLS_FIRST)
935 appendStringInfo(&buf, " NULLS FIRST");
939 /* Add the exclusion operator if relevant */
940 if (excludeOps != NULL)
941 appendStringInfo(&buf, " WITH %s",
942 generate_operator_name(excludeOps[keyno],
950 appendStringInfoChar(&buf, ')');
953 * If it has options, append "WITH (options)"
955 str = flatten_reloptions(indexrelid);
958 appendStringInfo(&buf, " WITH (%s)", str);
963 * If it's in a nondefault tablespace, say so, but only if requested
969 tblspc = get_rel_tablespace(indexrelid);
970 if (OidIsValid(tblspc))
973 appendStringInfoString(&buf, " USING INDEX");
974 appendStringInfo(&buf, " TABLESPACE %s",
975 quote_identifier(get_tablespace_name(tblspc)));
980 * If it's a partial index, decompile and append the predicate
982 if (!heap_attisnull(ht_idx, Anum_pg_index_indpred))
989 /* Convert text string to node tree */
990 predDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
991 Anum_pg_index_indpred, &isnull);
993 predString = TextDatumGetCString(predDatum);
994 node = (Node *) stringToNode(predString);
998 str = deparse_expression_pretty(node, context, false, false,
1001 appendStringInfo(&buf, " WHERE (%s)", str);
1003 appendStringInfo(&buf, " WHERE %s", str);
1008 ReleaseSysCache(ht_idx);
1009 ReleaseSysCache(ht_idxrel);
1010 ReleaseSysCache(ht_am);
1017 * pg_get_constraintdef
1019 * Returns the definition for the constraint, ie, everything that needs to
1020 * appear after "ALTER TABLE ... ADD CONSTRAINT <constraintname>".
1023 pg_get_constraintdef(PG_FUNCTION_ARGS)
1025 Oid constraintId = PG_GETARG_OID(0);
1027 PG_RETURN_TEXT_P(string_to_text(pg_get_constraintdef_worker(constraintId,
1032 pg_get_constraintdef_ext(PG_FUNCTION_ARGS)
1034 Oid constraintId = PG_GETARG_OID(0);
1035 bool pretty = PG_GETARG_BOOL(1);
1038 prettyFlags = pretty ? PRETTYFLAG_PAREN | PRETTYFLAG_INDENT : 0;
1039 PG_RETURN_TEXT_P(string_to_text(pg_get_constraintdef_worker(constraintId,
1040 false, prettyFlags)));
1043 /* Internal version that returns a palloc'd C string */
1045 pg_get_constraintdef_string(Oid constraintId)
1047 return pg_get_constraintdef_worker(constraintId, true, 0);
1051 pg_get_constraintdef_worker(Oid constraintId, bool fullCommand,
1055 Form_pg_constraint conForm;
1058 tup = SearchSysCache(CONSTROID,
1059 ObjectIdGetDatum(constraintId),
1061 if (!HeapTupleIsValid(tup)) /* should not happen */
1062 elog(ERROR, "cache lookup failed for constraint %u", constraintId);
1063 conForm = (Form_pg_constraint) GETSTRUCT(tup);
1065 initStringInfo(&buf);
1067 if (fullCommand && OidIsValid(conForm->conrelid))
1069 appendStringInfo(&buf, "ALTER TABLE ONLY %s ADD CONSTRAINT %s ",
1070 generate_relation_name(conForm->conrelid, NIL),
1071 quote_identifier(NameStr(conForm->conname)));
1074 switch (conForm->contype)
1076 case CONSTRAINT_FOREIGN:
1082 /* Start off the constraint definition */
1083 appendStringInfo(&buf, "FOREIGN KEY (");
1085 /* Fetch and build referencing-column list */
1086 val = SysCacheGetAttr(CONSTROID, tup,
1087 Anum_pg_constraint_conkey, &isnull);
1089 elog(ERROR, "null conkey for constraint %u",
1092 decompile_column_index_array(val, conForm->conrelid, &buf);
1094 /* add foreign relation name */
1095 appendStringInfo(&buf, ") REFERENCES %s(",
1096 generate_relation_name(conForm->confrelid,
1099 /* Fetch and build referenced-column list */
1100 val = SysCacheGetAttr(CONSTROID, tup,
1101 Anum_pg_constraint_confkey, &isnull);
1103 elog(ERROR, "null confkey for constraint %u",
1106 decompile_column_index_array(val, conForm->confrelid, &buf);
1108 appendStringInfo(&buf, ")");
1110 /* Add match type */
1111 switch (conForm->confmatchtype)
1113 case FKCONSTR_MATCH_FULL:
1114 string = " MATCH FULL";
1116 case FKCONSTR_MATCH_PARTIAL:
1117 string = " MATCH PARTIAL";
1119 case FKCONSTR_MATCH_UNSPECIFIED:
1123 elog(ERROR, "unrecognized confmatchtype: %d",
1124 conForm->confmatchtype);
1125 string = ""; /* keep compiler quiet */
1128 appendStringInfoString(&buf, string);
1130 /* Add ON UPDATE and ON DELETE clauses, if needed */
1131 switch (conForm->confupdtype)
1133 case FKCONSTR_ACTION_NOACTION:
1134 string = NULL; /* suppress default */
1136 case FKCONSTR_ACTION_RESTRICT:
1137 string = "RESTRICT";
1139 case FKCONSTR_ACTION_CASCADE:
1142 case FKCONSTR_ACTION_SETNULL:
1143 string = "SET NULL";
1145 case FKCONSTR_ACTION_SETDEFAULT:
1146 string = "SET DEFAULT";
1149 elog(ERROR, "unrecognized confupdtype: %d",
1150 conForm->confupdtype);
1151 string = NULL; /* keep compiler quiet */
1155 appendStringInfo(&buf, " ON UPDATE %s", string);
1157 switch (conForm->confdeltype)
1159 case FKCONSTR_ACTION_NOACTION:
1160 string = NULL; /* suppress default */
1162 case FKCONSTR_ACTION_RESTRICT:
1163 string = "RESTRICT";
1165 case FKCONSTR_ACTION_CASCADE:
1168 case FKCONSTR_ACTION_SETNULL:
1169 string = "SET NULL";
1171 case FKCONSTR_ACTION_SETDEFAULT:
1172 string = "SET DEFAULT";
1175 elog(ERROR, "unrecognized confdeltype: %d",
1176 conForm->confdeltype);
1177 string = NULL; /* keep compiler quiet */
1181 appendStringInfo(&buf, " ON DELETE %s", string);
1185 case CONSTRAINT_PRIMARY:
1186 case CONSTRAINT_UNIQUE:
1192 /* Start off the constraint definition */
1193 if (conForm->contype == CONSTRAINT_PRIMARY)
1194 appendStringInfo(&buf, "PRIMARY KEY (");
1196 appendStringInfo(&buf, "UNIQUE (");
1198 /* Fetch and build target column list */
1199 val = SysCacheGetAttr(CONSTROID, tup,
1200 Anum_pg_constraint_conkey, &isnull);
1202 elog(ERROR, "null conkey for constraint %u",
1205 decompile_column_index_array(val, conForm->conrelid, &buf);
1207 appendStringInfo(&buf, ")");
1209 indexId = get_constraint_index(constraintId);
1211 /* XXX why do we only print these bits if fullCommand? */
1212 if (fullCommand && OidIsValid(indexId))
1214 char *options = flatten_reloptions(indexId);
1219 appendStringInfo(&buf, " WITH (%s)", options);
1223 tblspc = get_rel_tablespace(indexId);
1224 if (OidIsValid(tblspc))
1225 appendStringInfo(&buf, " USING INDEX TABLESPACE %s",
1226 quote_identifier(get_tablespace_name(tblspc)));
1231 case CONSTRAINT_CHECK:
1240 /* Fetch constraint expression in parsetree form */
1241 val = SysCacheGetAttr(CONSTROID, tup,
1242 Anum_pg_constraint_conbin, &isnull);
1244 elog(ERROR, "null conbin for constraint %u",
1247 conbin = TextDatumGetCString(val);
1248 expr = stringToNode(conbin);
1250 /* Set up deparsing context for Var nodes in constraint */
1251 if (conForm->conrelid != InvalidOid)
1253 /* relation constraint */
1254 context = deparse_context_for(get_rel_name(conForm->conrelid),
1259 /* domain constraint --- can't have Vars */
1263 consrc = deparse_expression_pretty(expr, context, false, false,
1267 * Now emit the constraint definition. There are cases where
1268 * the constraint expression will be fully parenthesized and
1269 * we don't need the outer parens ... but there are other
1270 * cases where we do need 'em. Be conservative for now.
1272 * Note that simply checking for leading '(' and trailing ')'
1273 * would NOT be good enough, consider "(x > 0) AND (y > 0)".
1275 appendStringInfo(&buf, "CHECK (%s)", consrc);
1279 case CONSTRAINT_EXCLUSION:
1281 Oid indexOid = conForm->conindid;
1289 /* Extract operator OIDs from the pg_constraint tuple */
1290 val = SysCacheGetAttr(CONSTROID, tup,
1291 Anum_pg_constraint_conexclop,
1294 elog(ERROR, "null conexclop for constraint %u",
1297 deconstruct_array(DatumGetArrayTypeP(val),
1298 OIDOID, sizeof(Oid), true, 'i',
1299 &elems, NULL, &nElems);
1301 operators = (Oid *) palloc(nElems * sizeof(Oid));
1302 for (i = 0; i < nElems; i++)
1303 operators[i] = DatumGetObjectId(elems[i]);
1305 /* pg_get_indexdef_worker does the rest */
1306 /* suppress tablespace because pg_dump wants it that way */
1307 appendStringInfoString(&buf,
1308 pg_get_indexdef_worker(indexOid,
1317 elog(ERROR, "invalid constraint type \"%c\"", conForm->contype);
1321 if (conForm->condeferrable)
1322 appendStringInfo(&buf, " DEFERRABLE");
1323 if (conForm->condeferred)
1324 appendStringInfo(&buf, " INITIALLY DEFERRED");
1327 ReleaseSysCache(tup);
1334 * Convert an int16[] Datum into a comma-separated list of column names
1335 * for the indicated relation; append the list to buf.
1338 decompile_column_index_array(Datum column_index_array, Oid relId,
1345 /* Extract data from array of int16 */
1346 deconstruct_array(DatumGetArrayTypeP(column_index_array),
1347 INT2OID, 2, true, 's',
1348 &keys, NULL, &nKeys);
1350 for (j = 0; j < nKeys; j++)
1354 colName = get_relid_attribute_name(relId, DatumGetInt16(keys[j]));
1357 appendStringInfoString(buf, quote_identifier(colName));
1359 appendStringInfo(buf, ", %s", quote_identifier(colName));
1365 * get_expr - Decompile an expression tree
1367 * Input: an expression tree in nodeToString form, and a relation OID
1369 * Output: reverse-listed expression
1371 * Currently, the expression can only refer to a single relation, namely
1372 * the one specified by the second parameter. This is sufficient for
1373 * partial indexes, column default expressions, etc. We also support
1374 * Var-free expressions, for which the OID can be InvalidOid.
1378 pg_get_expr(PG_FUNCTION_ARGS)
1380 text *expr = PG_GETARG_TEXT_P(0);
1381 Oid relid = PG_GETARG_OID(1);
1384 if (OidIsValid(relid))
1386 /* Get the name for the relation */
1387 relname = get_rel_name(relid);
1390 * If the OID isn't actually valid, don't throw an error, just return
1391 * NULL. This is a bit questionable, but it's what we've done
1392 * historically, and it can help avoid unwanted failures when
1393 * examining catalog entries for just-deleted relations.
1395 if (relname == NULL)
1401 PG_RETURN_TEXT_P(pg_get_expr_worker(expr, relid, relname, 0));
1405 pg_get_expr_ext(PG_FUNCTION_ARGS)
1407 text *expr = PG_GETARG_TEXT_P(0);
1408 Oid relid = PG_GETARG_OID(1);
1409 bool pretty = PG_GETARG_BOOL(2);
1413 prettyFlags = pretty ? PRETTYFLAG_PAREN | PRETTYFLAG_INDENT : 0;
1415 if (OidIsValid(relid))
1417 /* Get the name for the relation */
1418 relname = get_rel_name(relid);
1419 /* See notes above */
1420 if (relname == NULL)
1426 PG_RETURN_TEXT_P(pg_get_expr_worker(expr, relid, relname, prettyFlags));
1430 pg_get_expr_worker(text *expr, Oid relid, const char *relname, int prettyFlags)
1437 /* Convert input TEXT object to C string */
1438 exprstr = text_to_cstring(expr);
1440 /* Convert expression to node tree */
1441 node = (Node *) stringToNode(exprstr);
1445 /* Prepare deparse context if needed */
1446 if (OidIsValid(relid))
1447 context = deparse_context_for(relname, relid);
1452 str = deparse_expression_pretty(node, context, false, false,
1455 return string_to_text(str);
1460 * get_userbyid - Get a user name by roleid and
1461 * fallback to 'unknown (OID=n)'
1465 pg_get_userbyid(PG_FUNCTION_ARGS)
1467 Oid roleid = PG_GETARG_OID(0);
1470 Form_pg_authid role_rec;
1473 * Allocate space for the result
1475 result = (Name) palloc(NAMEDATALEN);
1476 memset(NameStr(*result), 0, NAMEDATALEN);
1479 * Get the pg_authid entry and print the result
1481 roletup = SearchSysCache(AUTHOID,
1482 ObjectIdGetDatum(roleid),
1484 if (HeapTupleIsValid(roletup))
1486 role_rec = (Form_pg_authid) GETSTRUCT(roletup);
1487 StrNCpy(NameStr(*result), NameStr(role_rec->rolname), NAMEDATALEN);
1488 ReleaseSysCache(roletup);
1491 sprintf(NameStr(*result), "unknown (OID=%u)", roleid);
1493 PG_RETURN_NAME(result);
1498 * pg_get_serial_sequence
1499 * Get the name of the sequence used by a serial column,
1500 * formatted suitably for passing to setval, nextval or currval.
1501 * First parameter is not treated as double-quoted, second parameter
1502 * is --- see documentation for reason.
1505 pg_get_serial_sequence(PG_FUNCTION_ARGS)
1507 text *tablename = PG_GETARG_TEXT_P(0);
1508 text *columnname = PG_GETARG_TEXT_PP(1);
1513 Oid sequenceId = InvalidOid;
1519 /* Get the OID of the table */
1520 tablerv = makeRangeVarFromNameList(textToQualifiedNameList(tablename));
1521 tableOid = RangeVarGetRelid(tablerv, false);
1523 /* Get the number of the column */
1524 column = text_to_cstring(columnname);
1526 attnum = get_attnum(tableOid, column);
1527 if (attnum == InvalidAttrNumber)
1529 (errcode(ERRCODE_UNDEFINED_COLUMN),
1530 errmsg("column \"%s\" of relation \"%s\" does not exist",
1531 column, tablerv->relname)));
1533 /* Search the dependency table for the dependent sequence */
1534 depRel = heap_open(DependRelationId, AccessShareLock);
1536 ScanKeyInit(&key[0],
1537 Anum_pg_depend_refclassid,
1538 BTEqualStrategyNumber, F_OIDEQ,
1539 ObjectIdGetDatum(RelationRelationId));
1540 ScanKeyInit(&key[1],
1541 Anum_pg_depend_refobjid,
1542 BTEqualStrategyNumber, F_OIDEQ,
1543 ObjectIdGetDatum(tableOid));
1544 ScanKeyInit(&key[2],
1545 Anum_pg_depend_refobjsubid,
1546 BTEqualStrategyNumber, F_INT4EQ,
1547 Int32GetDatum(attnum));
1549 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
1550 SnapshotNow, 3, key);
1552 while (HeapTupleIsValid(tup = systable_getnext(scan)))
1554 Form_pg_depend deprec = (Form_pg_depend) GETSTRUCT(tup);
1557 * We assume any auto dependency of a sequence on a column must be
1558 * what we are looking for. (We need the relkind test because indexes
1559 * can also have auto dependencies on columns.)
1561 if (deprec->classid == RelationRelationId &&
1562 deprec->objsubid == 0 &&
1563 deprec->deptype == DEPENDENCY_AUTO &&
1564 get_rel_relkind(deprec->objid) == RELKIND_SEQUENCE)
1566 sequenceId = deprec->objid;
1571 systable_endscan(scan);
1572 heap_close(depRel, AccessShareLock);
1574 if (OidIsValid(sequenceId))
1577 Form_pg_class classtuple;
1581 /* Get the sequence's pg_class entry */
1582 classtup = SearchSysCache(RELOID,
1583 ObjectIdGetDatum(sequenceId),
1585 if (!HeapTupleIsValid(classtup))
1586 elog(ERROR, "cache lookup failed for relation %u", sequenceId);
1587 classtuple = (Form_pg_class) GETSTRUCT(classtup);
1589 /* Get the namespace */
1590 nspname = get_namespace_name(classtuple->relnamespace);
1592 elog(ERROR, "cache lookup failed for namespace %u",
1593 classtuple->relnamespace);
1595 /* And construct the result string */
1596 result = quote_qualified_identifier(nspname,
1597 NameStr(classtuple->relname));
1599 ReleaseSysCache(classtup);
1601 PG_RETURN_TEXT_P(string_to_text(result));
1609 * pg_get_functiondef
1610 * Returns the complete "CREATE OR REPLACE FUNCTION ..." statement for
1611 * the specified function.
1614 pg_get_functiondef(PG_FUNCTION_ARGS)
1616 Oid funcid = PG_GETARG_OID(0);
1622 Form_pg_language lang;
1631 initStringInfo(&buf);
1633 /* Look up the function */
1634 proctup = SearchSysCache(PROCOID,
1635 ObjectIdGetDatum(funcid),
1637 if (!HeapTupleIsValid(proctup))
1638 elog(ERROR, "cache lookup failed for function %u", funcid);
1639 proc = (Form_pg_proc) GETSTRUCT(proctup);
1640 name = NameStr(proc->proname);
1644 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1645 errmsg("\"%s\" is an aggregate function", name)));
1647 /* Need its pg_language tuple for the language name */
1648 langtup = SearchSysCache(LANGOID,
1649 ObjectIdGetDatum(proc->prolang),
1651 if (!HeapTupleIsValid(langtup))
1652 elog(ERROR, "cache lookup failed for language %u", proc->prolang);
1653 lang = (Form_pg_language) GETSTRUCT(langtup);
1656 * We always qualify the function name, to ensure the right function gets
1659 nsp = get_namespace_name(proc->pronamespace);
1660 appendStringInfo(&buf, "CREATE OR REPLACE FUNCTION %s(",
1661 quote_qualified_identifier(nsp, name));
1662 (void) print_function_arguments(&buf, proctup, false, true);
1663 appendStringInfoString(&buf, ")\n RETURNS ");
1664 print_function_rettype(&buf, proctup);
1665 appendStringInfo(&buf, "\n LANGUAGE %s\n",
1666 quote_identifier(NameStr(lang->lanname)));
1668 /* Emit some miscellaneous options on one line */
1671 if (proc->proiswindow)
1672 appendStringInfoString(&buf, " WINDOW");
1673 switch (proc->provolatile)
1675 case PROVOLATILE_IMMUTABLE:
1676 appendStringInfoString(&buf, " IMMUTABLE");
1678 case PROVOLATILE_STABLE:
1679 appendStringInfoString(&buf, " STABLE");
1681 case PROVOLATILE_VOLATILE:
1684 if (proc->proisstrict)
1685 appendStringInfoString(&buf, " STRICT");
1686 if (proc->prosecdef)
1687 appendStringInfoString(&buf, " SECURITY DEFINER");
1689 /* This code for the default cost and rows should match functioncmds.c */
1690 if (proc->prolang == INTERNALlanguageId ||
1691 proc->prolang == ClanguageId)
1695 if (proc->procost != procost)
1696 appendStringInfo(&buf, " COST %g", proc->procost);
1698 if (proc->prorows > 0 && proc->prorows != 1000)
1699 appendStringInfo(&buf, " ROWS %g", proc->prorows);
1701 if (oldlen != buf.len)
1702 appendStringInfoChar(&buf, '\n');
1704 /* Emit any proconfig options, one per line */
1705 tmp = SysCacheGetAttr(PROCOID, proctup, Anum_pg_proc_proconfig, &isnull);
1708 ArrayType *a = DatumGetArrayTypeP(tmp);
1711 Assert(ARR_ELEMTYPE(a) == TEXTOID);
1712 Assert(ARR_NDIM(a) == 1);
1713 Assert(ARR_LBOUND(a)[0] == 1);
1715 for (i = 1; i <= ARR_DIMS(a)[0]; i++)
1719 d = array_ref(a, 1, &i,
1720 -1 /* varlenarray */ ,
1721 -1 /* TEXT's typlen */ ,
1722 false /* TEXT's typbyval */ ,
1723 'i' /* TEXT's typalign */ ,
1727 char *configitem = TextDatumGetCString(d);
1730 pos = strchr(configitem, '=');
1735 appendStringInfo(&buf, " SET %s TO ",
1736 quote_identifier(configitem));
1739 * Some GUC variable names are 'LIST' type and hence must not
1742 if (pg_strcasecmp(configitem, "DateStyle") == 0
1743 || pg_strcasecmp(configitem, "search_path") == 0)
1744 appendStringInfoString(&buf, pos);
1746 simple_quote_literal(&buf, pos);
1747 appendStringInfoChar(&buf, '\n');
1752 /* And finally the function definition ... */
1753 appendStringInfoString(&buf, "AS ");
1755 tmp = SysCacheGetAttr(PROCOID, proctup, Anum_pg_proc_probin, &isnull);
1758 simple_quote_literal(&buf, TextDatumGetCString(tmp));
1759 appendStringInfoString(&buf, ", "); /* assume prosrc isn't null */
1762 tmp = SysCacheGetAttr(PROCOID, proctup, Anum_pg_proc_prosrc, &isnull);
1764 elog(ERROR, "null prosrc");
1765 prosrc = TextDatumGetCString(tmp);
1768 * We always use dollar quoting. Figure out a suitable delimiter.
1770 * Since the user is likely to be editing the function body string, we
1771 * shouldn't use a short delimiter that he might easily create a conflict
1772 * with. Hence prefer "$function$", but extend if needed.
1774 initStringInfo(&dq);
1775 appendStringInfoString(&dq, "$function");
1776 while (strstr(prosrc, dq.data) != NULL)
1777 appendStringInfoChar(&dq, 'x');
1778 appendStringInfoChar(&dq, '$');
1780 appendStringInfoString(&buf, dq.data);
1781 appendStringInfoString(&buf, prosrc);
1782 appendStringInfoString(&buf, dq.data);
1784 appendStringInfoString(&buf, "\n");
1786 ReleaseSysCache(langtup);
1787 ReleaseSysCache(proctup);
1789 PG_RETURN_TEXT_P(string_to_text(buf.data));
1793 * pg_get_function_arguments
1794 * Get a nicely-formatted list of arguments for a function.
1795 * This is everything that would go between the parentheses in
1799 pg_get_function_arguments(PG_FUNCTION_ARGS)
1801 Oid funcid = PG_GETARG_OID(0);
1805 initStringInfo(&buf);
1807 proctup = SearchSysCache(PROCOID,
1808 ObjectIdGetDatum(funcid),
1810 if (!HeapTupleIsValid(proctup))
1811 elog(ERROR, "cache lookup failed for function %u", funcid);
1813 (void) print_function_arguments(&buf, proctup, false, true);
1815 ReleaseSysCache(proctup);
1817 PG_RETURN_TEXT_P(string_to_text(buf.data));
1821 * pg_get_function_identity_arguments
1822 * Get a formatted list of arguments for a function.
1823 * This is everything that would go between the parentheses in
1824 * ALTER FUNCTION, etc. In particular, don't print defaults.
1827 pg_get_function_identity_arguments(PG_FUNCTION_ARGS)
1829 Oid funcid = PG_GETARG_OID(0);
1833 initStringInfo(&buf);
1835 proctup = SearchSysCache(PROCOID,
1836 ObjectIdGetDatum(funcid),
1838 if (!HeapTupleIsValid(proctup))
1839 elog(ERROR, "cache lookup failed for function %u", funcid);
1841 (void) print_function_arguments(&buf, proctup, false, false);
1843 ReleaseSysCache(proctup);
1845 PG_RETURN_TEXT_P(string_to_text(buf.data));
1849 * pg_get_function_result
1850 * Get a nicely-formatted version of the result type of a function.
1851 * This is what would appear after RETURNS in CREATE FUNCTION.
1854 pg_get_function_result(PG_FUNCTION_ARGS)
1856 Oid funcid = PG_GETARG_OID(0);
1860 initStringInfo(&buf);
1862 proctup = SearchSysCache(PROCOID,
1863 ObjectIdGetDatum(funcid),
1865 if (!HeapTupleIsValid(proctup))
1866 elog(ERROR, "cache lookup failed for function %u", funcid);
1868 print_function_rettype(&buf, proctup);
1870 ReleaseSysCache(proctup);
1872 PG_RETURN_TEXT_P(string_to_text(buf.data));
1876 * Guts of pg_get_function_result: append the function's return type
1877 * to the specified buffer.
1880 print_function_rettype(StringInfo buf, HeapTuple proctup)
1882 Form_pg_proc proc = (Form_pg_proc) GETSTRUCT(proctup);
1884 StringInfoData rbuf;
1886 initStringInfo(&rbuf);
1888 if (proc->proretset)
1890 /* It might be a table function; try to print the arguments */
1891 appendStringInfoString(&rbuf, "TABLE(");
1892 ntabargs = print_function_arguments(&rbuf, proctup, true, false);
1894 appendStringInfoString(&rbuf, ")");
1896 resetStringInfo(&rbuf);
1901 /* Not a table function, so do the normal thing */
1902 if (proc->proretset)
1903 appendStringInfoString(&rbuf, "SETOF ");
1904 appendStringInfoString(&rbuf, format_type_be(proc->prorettype));
1907 appendStringInfoString(buf, rbuf.data);
1911 * Common code for pg_get_function_arguments and pg_get_function_result:
1912 * append the desired subset of arguments to buf. We print only TABLE
1913 * arguments when print_table_args is true, and all the others when it's false.
1914 * We print argument defaults only if print_defaults is true.
1915 * Function return value is the number of arguments printed.
1918 print_function_arguments(StringInfo buf, HeapTuple proctup,
1919 bool print_table_args, bool print_defaults)
1921 Form_pg_proc proc = (Form_pg_proc) GETSTRUCT(proctup);
1929 ListCell *nextargdefault = NULL;
1932 numargs = get_func_arg_info(proctup,
1933 &argtypes, &argnames, &argmodes);
1935 nlackdefaults = numargs;
1936 if (print_defaults && proc->pronargdefaults > 0)
1938 Datum proargdefaults;
1941 proargdefaults = SysCacheGetAttr(PROCOID, proctup,
1942 Anum_pg_proc_proargdefaults,
1949 str = TextDatumGetCString(proargdefaults);
1950 argdefaults = (List *) stringToNode(str);
1951 Assert(IsA(argdefaults, List));
1953 nextargdefault = list_head(argdefaults);
1954 /* nlackdefaults counts only *input* arguments lacking defaults */
1955 nlackdefaults = proc->pronargs - list_length(argdefaults);
1961 for (i = 0; i < numargs; i++)
1963 Oid argtype = argtypes[i];
1964 char *argname = argnames ? argnames[i] : NULL;
1965 char argmode = argmodes ? argmodes[i] : PROARGMODE_IN;
1966 const char *modename;
1975 case PROARGMODE_INOUT:
1976 modename = "INOUT ";
1979 case PROARGMODE_OUT:
1983 case PROARGMODE_VARIADIC:
1984 modename = "VARIADIC ";
1987 case PROARGMODE_TABLE:
1992 elog(ERROR, "invalid parameter mode '%c'", argmode);
1993 modename = NULL; /* keep compiler quiet */
1998 inputargno++; /* this is a 1-based counter */
2000 if (print_table_args != (argmode == PROARGMODE_TABLE))
2004 appendStringInfoString(buf, ", ");
2005 appendStringInfoString(buf, modename);
2006 if (argname && argname[0])
2007 appendStringInfo(buf, "%s ", quote_identifier(argname));
2008 appendStringInfoString(buf, format_type_be(argtype));
2009 if (print_defaults && isinput && inputargno > nlackdefaults)
2013 Assert(nextargdefault != NULL);
2014 expr = (Node *) lfirst(nextargdefault);
2015 nextargdefault = lnext(nextargdefault);
2017 appendStringInfo(buf, " DEFAULT %s",
2018 deparse_expression(expr, NIL, false, false));
2028 * deparse_expression - General utility for deparsing expressions
2030 * calls deparse_expression_pretty with all prettyPrinting disabled
2033 deparse_expression(Node *expr, List *dpcontext,
2034 bool forceprefix, bool showimplicit)
2036 return deparse_expression_pretty(expr, dpcontext, forceprefix,
2037 showimplicit, 0, 0);
2041 * deparse_expression_pretty - General utility for deparsing expressions
2043 * expr is the node tree to be deparsed. It must be a transformed expression
2044 * tree (ie, not the raw output of gram.y).
2046 * dpcontext is a list of deparse_namespace nodes representing the context
2047 * for interpreting Vars in the node tree.
2049 * forceprefix is TRUE to force all Vars to be prefixed with their table names.
2051 * showimplicit is TRUE to force all implicit casts to be shown explicitly.
2053 * tries to pretty up the output according to prettyFlags and startIndent.
2055 * The result is a palloc'd string.
2059 deparse_expression_pretty(Node *expr, List *dpcontext,
2060 bool forceprefix, bool showimplicit,
2061 int prettyFlags, int startIndent)
2064 deparse_context context;
2066 initStringInfo(&buf);
2068 context.namespaces = dpcontext;
2069 context.windowClause = NIL;
2070 context.windowTList = NIL;
2071 context.varprefix = forceprefix;
2072 context.prettyFlags = prettyFlags;
2073 context.indentLevel = startIndent;
2075 get_rule_expr(expr, &context, showimplicit);
2081 * deparse_context_for - Build deparse context for a single relation
2083 * Given the reference name (alias) and OID of a relation, build deparsing
2084 * context for an expression referencing only that relation (as varno 1,
2085 * varlevelsup 0). This is sufficient for many uses of deparse_expression.
2089 deparse_context_for(const char *aliasname, Oid relid)
2091 deparse_namespace *dpns;
2094 dpns = (deparse_namespace *) palloc(sizeof(deparse_namespace));
2096 /* Build a minimal RTE for the rel */
2097 rte = makeNode(RangeTblEntry);
2098 rte->rtekind = RTE_RELATION;
2100 rte->eref = makeAlias(aliasname, NIL);
2102 rte->inFromCl = true;
2104 /* Build one-element rtable */
2105 dpns->rtable = list_make1(rte);
2107 dpns->subplans = NIL;
2108 dpns->outer_plan = dpns->inner_plan = NULL;
2110 /* Return a one-deep namespace stack */
2111 return list_make1(dpns);
2115 * deparse_context_for_plan - Build deparse context for a plan node
2117 * When deparsing an expression in a Plan tree, we might have to resolve
2118 * OUTER or INNER references. To do this, the caller must provide the
2119 * parent Plan node. In the normal case of a join plan node, OUTER and
2120 * INNER references can be resolved by drilling down into the left and
2121 * right child plans. A special case is that a nestloop inner indexscan
2122 * might have OUTER Vars, but the outer side of the join is not a child
2123 * plan node. To handle such cases the outer plan node must be passed
2124 * separately. (Pass NULL for outer_plan otherwise.)
2126 * Note: plan and outer_plan really ought to be declared as "Plan *", but
2127 * we use "Node *" to avoid having to include plannodes.h in builtins.h.
2129 * The plan's rangetable list must also be passed. We actually prefer to use
2130 * the rangetable to resolve simple Vars, but the plan inputs are necessary
2131 * for Vars that reference expressions computed in subplan target lists.
2133 * We also need the list of subplans associated with the Plan tree; this
2134 * is for resolving references to CTE subplans.
2137 deparse_context_for_plan(Node *plan, Node *outer_plan,
2138 List *rtable, List *subplans)
2140 deparse_namespace *dpns;
2142 dpns = (deparse_namespace *) palloc(sizeof(deparse_namespace));
2144 dpns->rtable = rtable;
2146 dpns->subplans = subplans;
2149 * Set up outer_plan and inner_plan from the Plan node (this includes
2150 * various special cases for particular Plan types).
2152 push_plan(dpns, (Plan *) plan);
2155 * If outer_plan is given, that overrides whatever we got from the plan.
2158 dpns->outer_plan = (Plan *) outer_plan;
2160 /* Return a one-deep namespace stack */
2161 return list_make1(dpns);
2165 * make_ruledef - reconstruct the CREATE RULE command
2166 * for a given pg_rewrite tuple
2170 make_ruledef(StringInfo buf, HeapTuple ruletup, TupleDesc rulettc,
2180 List *actions = NIL;
2186 * Get the attribute values from the rules tuple
2188 fno = SPI_fnumber(rulettc, "rulename");
2189 dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
2191 rulename = NameStr(*(DatumGetName(dat)));
2193 fno = SPI_fnumber(rulettc, "ev_type");
2194 dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
2196 ev_type = DatumGetChar(dat);
2198 fno = SPI_fnumber(rulettc, "ev_class");
2199 dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
2201 ev_class = DatumGetObjectId(dat);
2203 fno = SPI_fnumber(rulettc, "ev_attr");
2204 dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
2206 ev_attr = DatumGetInt16(dat);
2208 fno = SPI_fnumber(rulettc, "is_instead");
2209 dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
2211 is_instead = DatumGetBool(dat);
2213 /* these could be nulls */
2214 fno = SPI_fnumber(rulettc, "ev_qual");
2215 ev_qual = SPI_getvalue(ruletup, rulettc, fno);
2217 fno = SPI_fnumber(rulettc, "ev_action");
2218 ev_action = SPI_getvalue(ruletup, rulettc, fno);
2219 if (ev_action != NULL)
2220 actions = (List *) stringToNode(ev_action);
2223 * Build the rules definition text
2225 appendStringInfo(buf, "CREATE RULE %s AS",
2226 quote_identifier(rulename));
2228 if (prettyFlags & PRETTYFLAG_INDENT)
2229 appendStringInfoString(buf, "\n ON ");
2231 appendStringInfoString(buf, " ON ");
2233 /* The event the rule is fired for */
2237 appendStringInfo(buf, "SELECT");
2241 appendStringInfo(buf, "UPDATE");
2245 appendStringInfo(buf, "INSERT");
2249 appendStringInfo(buf, "DELETE");
2254 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2255 errmsg("rule \"%s\" has unsupported event type %d",
2256 rulename, ev_type)));
2260 /* The relation the rule is fired on */
2261 appendStringInfo(buf, " TO %s", generate_relation_name(ev_class, NIL));
2263 appendStringInfo(buf, ".%s",
2264 quote_identifier(get_relid_attribute_name(ev_class,
2267 /* If the rule has an event qualification, add it */
2268 if (ev_qual == NULL)
2270 if (strlen(ev_qual) > 0 && strcmp(ev_qual, "<>") != 0)
2274 deparse_context context;
2275 deparse_namespace dpns;
2277 if (prettyFlags & PRETTYFLAG_INDENT)
2278 appendStringInfoString(buf, "\n ");
2279 appendStringInfo(buf, " WHERE ");
2281 qual = stringToNode(ev_qual);
2284 * We need to make a context for recognizing any Vars in the qual
2285 * (which can only be references to OLD and NEW). Use the rtable of
2286 * the first query in the action list for this purpose.
2288 query = (Query *) linitial(actions);
2291 * If the action is INSERT...SELECT, OLD/NEW have been pushed down
2292 * into the SELECT, and that's what we need to look at. (Ugly kluge
2293 * ... try to fix this when we redesign querytrees.)
2295 query = getInsertSelectQuery(query, NULL);
2297 /* Must acquire locks right away; see notes in get_query_def() */
2298 AcquireRewriteLocks(query, false);
2301 context.namespaces = list_make1(&dpns);
2302 context.windowClause = NIL;
2303 context.windowTList = NIL;
2304 context.varprefix = (list_length(query->rtable) != 1);
2305 context.prettyFlags = prettyFlags;
2306 context.indentLevel = PRETTYINDENT_STD;
2307 dpns.rtable = query->rtable;
2308 dpns.ctes = query->cteList;
2309 dpns.subplans = NIL;
2310 dpns.outer_plan = dpns.inner_plan = NULL;
2312 get_rule_expr(qual, &context, false);
2315 appendStringInfo(buf, " DO ");
2317 /* The INSTEAD keyword (if so) */
2319 appendStringInfo(buf, "INSTEAD ");
2321 /* Finally the rules actions */
2322 if (list_length(actions) > 1)
2327 appendStringInfo(buf, "(");
2328 foreach(action, actions)
2330 query = (Query *) lfirst(action);
2331 get_query_def(query, buf, NIL, NULL, prettyFlags, 0);
2333 appendStringInfo(buf, ";\n");
2335 appendStringInfo(buf, "; ");
2337 appendStringInfo(buf, ");");
2339 else if (list_length(actions) == 0)
2341 appendStringInfo(buf, "NOTHING;");
2347 query = (Query *) linitial(actions);
2348 get_query_def(query, buf, NIL, NULL, prettyFlags, 0);
2349 appendStringInfo(buf, ";");
2355 * make_viewdef - reconstruct the SELECT part of a
2360 make_viewdef(StringInfo buf, HeapTuple ruletup, TupleDesc rulettc,
2370 List *actions = NIL;
2371 Relation ev_relation;
2376 * Get the attribute values from the rules tuple
2378 fno = SPI_fnumber(rulettc, "ev_type");
2379 ev_type = (char) SPI_getbinval(ruletup, rulettc, fno, &isnull);
2381 fno = SPI_fnumber(rulettc, "ev_class");
2382 ev_class = (Oid) SPI_getbinval(ruletup, rulettc, fno, &isnull);
2384 fno = SPI_fnumber(rulettc, "ev_attr");
2385 ev_attr = (int2) SPI_getbinval(ruletup, rulettc, fno, &isnull);
2387 fno = SPI_fnumber(rulettc, "is_instead");
2388 is_instead = (bool) SPI_getbinval(ruletup, rulettc, fno, &isnull);
2390 fno = SPI_fnumber(rulettc, "ev_qual");
2391 ev_qual = SPI_getvalue(ruletup, rulettc, fno);
2393 fno = SPI_fnumber(rulettc, "ev_action");
2394 ev_action = SPI_getvalue(ruletup, rulettc, fno);
2395 if (ev_action != NULL)
2396 actions = (List *) stringToNode(ev_action);
2398 if (list_length(actions) != 1)
2400 appendStringInfo(buf, "Not a view");
2404 query = (Query *) linitial(actions);
2406 if (ev_type != '1' || ev_attr >= 0 || !is_instead ||
2407 strcmp(ev_qual, "<>") != 0 || query->commandType != CMD_SELECT)
2409 appendStringInfo(buf, "Not a view");
2413 ev_relation = heap_open(ev_class, AccessShareLock);
2415 get_query_def(query, buf, NIL, RelationGetDescr(ev_relation),
2417 appendStringInfo(buf, ";");
2419 heap_close(ev_relation, AccessShareLock);
2424 * get_query_def - Parse back one query parsetree
2426 * If resultDesc is not NULL, then it is the output tuple descriptor for
2427 * the view represented by a SELECT query.
2431 get_query_def(Query *query, StringInfo buf, List *parentnamespace,
2432 TupleDesc resultDesc, int prettyFlags, int startIndent)
2434 deparse_context context;
2435 deparse_namespace dpns;
2438 * Before we begin to examine the query, acquire locks on referenced
2439 * relations, and fix up deleted columns in JOIN RTEs. This ensures
2440 * consistent results. Note we assume it's OK to scribble on the passed
2443 AcquireRewriteLocks(query, false);
2446 context.namespaces = lcons(&dpns, list_copy(parentnamespace));
2447 context.windowClause = NIL;
2448 context.windowTList = NIL;
2449 context.varprefix = (parentnamespace != NIL ||
2450 list_length(query->rtable) != 1);
2451 context.prettyFlags = prettyFlags;
2452 context.indentLevel = startIndent;
2454 dpns.rtable = query->rtable;
2455 dpns.ctes = query->cteList;
2456 dpns.subplans = NIL;
2457 dpns.outer_plan = dpns.inner_plan = NULL;
2459 switch (query->commandType)
2462 get_select_query_def(query, &context, resultDesc);
2466 get_update_query_def(query, &context);
2470 get_insert_query_def(query, &context);
2474 get_delete_query_def(query, &context);
2478 appendStringInfo(buf, "NOTHING");
2482 get_utility_query_def(query, &context);
2486 elog(ERROR, "unrecognized query command type: %d",
2487 query->commandType);
2493 * get_values_def - Parse back a VALUES list
2497 get_values_def(List *values_lists, deparse_context *context)
2499 StringInfo buf = context->buf;
2500 bool first_list = true;
2503 appendStringInfoString(buf, "VALUES ");
2505 foreach(vtl, values_lists)
2507 List *sublist = (List *) lfirst(vtl);
2508 bool first_col = true;
2514 appendStringInfoString(buf, ", ");
2516 appendStringInfoChar(buf, '(');
2517 foreach(lc, sublist)
2519 Node *col = (Node *) lfirst(lc);
2524 appendStringInfoChar(buf, ',');
2527 * Strip any top-level nodes representing indirection assignments,
2528 * then print the result.
2530 get_rule_expr(processIndirection(col, context, false),
2533 appendStringInfoChar(buf, ')');
2538 * get_with_clause - Parse back a WITH clause
2542 get_with_clause(Query *query, deparse_context *context)
2544 StringInfo buf = context->buf;
2548 if (query->cteList == NIL)
2551 if (PRETTY_INDENT(context))
2553 context->indentLevel += PRETTYINDENT_STD;
2554 appendStringInfoChar(buf, ' ');
2557 if (query->hasRecursive)
2558 sep = "WITH RECURSIVE ";
2561 foreach(l, query->cteList)
2563 CommonTableExpr *cte = (CommonTableExpr *) lfirst(l);
2565 appendStringInfoString(buf, sep);
2566 appendStringInfoString(buf, quote_identifier(cte->ctename));
2567 if (cte->aliascolnames)
2572 appendStringInfoChar(buf, '(');
2573 foreach(col, cte->aliascolnames)
2578 appendStringInfoString(buf, ", ");
2579 appendStringInfoString(buf,
2580 quote_identifier(strVal(lfirst(col))));
2582 appendStringInfoChar(buf, ')');
2584 appendStringInfoString(buf, " AS (");
2585 if (PRETTY_INDENT(context))
2586 appendContextKeyword(context, "", 0, 0, 0);
2587 get_query_def((Query *) cte->ctequery, buf, context->namespaces, NULL,
2588 context->prettyFlags, context->indentLevel);
2589 if (PRETTY_INDENT(context))
2590 appendContextKeyword(context, "", 0, 0, 0);
2591 appendStringInfoChar(buf, ')');
2595 if (PRETTY_INDENT(context))
2597 context->indentLevel -= PRETTYINDENT_STD;
2598 appendContextKeyword(context, "", 0, 0, 0);
2601 appendStringInfoChar(buf, ' ');
2605 * get_select_query_def - Parse back a SELECT parsetree
2609 get_select_query_def(Query *query, deparse_context *context,
2610 TupleDesc resultDesc)
2612 StringInfo buf = context->buf;
2613 List *save_windowclause;
2614 List *save_windowtlist;
2618 /* Insert the WITH clause if given */
2619 get_with_clause(query, context);
2621 /* Set up context for possible window functions */
2622 save_windowclause = context->windowClause;
2623 context->windowClause = query->windowClause;
2624 save_windowtlist = context->windowTList;
2625 context->windowTList = query->targetList;
2628 * If the Query node has a setOperations tree, then it's the top level of
2629 * a UNION/INTERSECT/EXCEPT query; only the WITH, ORDER BY and LIMIT
2630 * fields are interesting in the top query itself.
2632 if (query->setOperations)
2634 get_setop_query(query->setOperations, query, context, resultDesc);
2635 /* ORDER BY clauses must be simple in this case */
2640 get_basic_select_query(query, context, resultDesc);
2641 force_colno = false;
2644 /* Add the ORDER BY clause if given */
2645 if (query->sortClause != NIL)
2647 appendContextKeyword(context, " ORDER BY ",
2648 -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
2649 get_rule_orderby(query->sortClause, query->targetList,
2650 force_colno, context);
2653 /* Add the LIMIT clause if given */
2654 if (query->limitOffset != NULL)
2656 appendContextKeyword(context, " OFFSET ",
2657 -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
2658 get_rule_expr(query->limitOffset, context, false);
2660 if (query->limitCount != NULL)
2662 appendContextKeyword(context, " LIMIT ",
2663 -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
2664 if (IsA(query->limitCount, Const) &&
2665 ((Const *) query->limitCount)->constisnull)
2666 appendStringInfo(buf, "ALL");
2668 get_rule_expr(query->limitCount, context, false);
2671 /* Add FOR UPDATE/SHARE clauses if present */
2672 if (query->hasForUpdate)
2674 foreach(l, query->rowMarks)
2676 RowMarkClause *rc = (RowMarkClause *) lfirst(l);
2677 RangeTblEntry *rte = rt_fetch(rc->rti, query->rtable);
2679 /* don't print implicit clauses */
2684 appendContextKeyword(context, " FOR UPDATE",
2685 -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
2687 appendContextKeyword(context, " FOR SHARE",
2688 -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
2689 appendStringInfo(buf, " OF %s",
2690 quote_identifier(rte->eref->aliasname));
2692 appendStringInfo(buf, " NOWAIT");
2696 context->windowClause = save_windowclause;
2697 context->windowTList = save_windowtlist;
2701 get_basic_select_query(Query *query, deparse_context *context,
2702 TupleDesc resultDesc)
2704 StringInfo buf = context->buf;
2708 if (PRETTY_INDENT(context))
2710 context->indentLevel += PRETTYINDENT_STD;
2711 appendStringInfoChar(buf, ' ');
2715 * If the query looks like SELECT * FROM (VALUES ...), then print just the
2716 * VALUES part. This reverses what transformValuesClause() did at parse
2717 * time. If the jointree contains just a single VALUES RTE, we assume
2718 * this case applies (without looking at the targetlist...)
2720 if (list_length(query->jointree->fromlist) == 1)
2722 RangeTblRef *rtr = (RangeTblRef *) linitial(query->jointree->fromlist);
2724 if (IsA(rtr, RangeTblRef))
2726 RangeTblEntry *rte = rt_fetch(rtr->rtindex, query->rtable);
2728 if (rte->rtekind == RTE_VALUES)
2730 get_values_def(rte->values_lists, context);
2737 * Build up the query string - first we say SELECT
2739 appendStringInfo(buf, "SELECT");
2741 /* Add the DISTINCT clause if given */
2742 if (query->distinctClause != NIL)
2744 if (query->hasDistinctOn)
2746 appendStringInfo(buf, " DISTINCT ON (");
2748 foreach(l, query->distinctClause)
2750 SortGroupClause *srt = (SortGroupClause *) lfirst(l);
2752 appendStringInfoString(buf, sep);
2753 get_rule_sortgroupclause(srt, query->targetList,
2757 appendStringInfo(buf, ")");
2760 appendStringInfo(buf, " DISTINCT");
2763 /* Then we tell what to select (the targetlist) */
2764 get_target_list(query->targetList, context, resultDesc);
2766 /* Add the FROM clause if needed */
2767 get_from_clause(query, " FROM ", context);
2769 /* Add the WHERE clause if given */
2770 if (query->jointree->quals != NULL)
2772 appendContextKeyword(context, " WHERE ",
2773 -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
2774 get_rule_expr(query->jointree->quals, context, false);
2777 /* Add the GROUP BY clause if given */
2778 if (query->groupClause != NULL)
2780 appendContextKeyword(context, " GROUP BY ",
2781 -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
2783 foreach(l, query->groupClause)
2785 SortGroupClause *grp = (SortGroupClause *) lfirst(l);
2787 appendStringInfoString(buf, sep);
2788 get_rule_sortgroupclause(grp, query->targetList,
2794 /* Add the HAVING clause if given */
2795 if (query->havingQual != NULL)
2797 appendContextKeyword(context, " HAVING ",
2798 -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
2799 get_rule_expr(query->havingQual, context, false);
2802 /* Add the WINDOW clause if needed */
2803 if (query->windowClause != NIL)
2804 get_rule_windowclause(query, context);
2808 * get_target_list - Parse back a SELECT target list
2810 * This is also used for RETURNING lists in INSERT/UPDATE/DELETE.
2814 get_target_list(List *targetList, deparse_context *context,
2815 TupleDesc resultDesc)
2817 StringInfo buf = context->buf;
2824 foreach(l, targetList)
2826 TargetEntry *tle = (TargetEntry *) lfirst(l);
2831 continue; /* ignore junk entries */
2833 appendStringInfoString(buf, sep);
2838 * We special-case Var nodes rather than using get_rule_expr. This is
2839 * needed because get_rule_expr will display a whole-row Var as
2840 * "foo.*", which is the preferred notation in most contexts, but at
2841 * the top level of a SELECT list it's not right (the parser will
2842 * expand that notation into multiple columns, yielding behavior
2843 * different from a whole-row Var). We want just "foo", instead.
2845 if (tle->expr && IsA(tle->expr, Var))
2847 attname = get_variable((Var *) tle->expr, 0, false, context);
2851 get_rule_expr((Node *) tle->expr, context, true);
2852 /* We'll show the AS name unless it's this: */
2853 attname = "?column?";
2857 * Figure out what the result column should be called. In the context
2858 * of a view, use the view's tuple descriptor (so as to pick up the
2859 * effects of any column RENAME that's been done on the view).
2860 * Otherwise, just use what we can find in the TLE.
2862 if (resultDesc && colno <= resultDesc->natts)
2863 colname = NameStr(resultDesc->attrs[colno - 1]->attname);
2865 colname = tle->resname;
2867 /* Show AS unless the column's name is correct as-is */
2868 if (colname) /* resname could be NULL */
2870 if (attname == NULL || strcmp(attname, colname) != 0)
2871 appendStringInfo(buf, " AS %s", quote_identifier(colname));
2877 get_setop_query(Node *setOp, Query *query, deparse_context *context,
2878 TupleDesc resultDesc)
2880 StringInfo buf = context->buf;
2883 if (IsA(setOp, RangeTblRef))
2885 RangeTblRef *rtr = (RangeTblRef *) setOp;
2886 RangeTblEntry *rte = rt_fetch(rtr->rtindex, query->rtable);
2887 Query *subquery = rte->subquery;
2889 Assert(subquery != NULL);
2890 Assert(subquery->setOperations == NULL);
2891 /* Need parens if WITH, ORDER BY, FOR UPDATE, or LIMIT; see gram.y */
2892 need_paren = (subquery->cteList ||
2893 subquery->sortClause ||
2894 subquery->rowMarks ||
2895 subquery->limitOffset ||
2896 subquery->limitCount);
2898 appendStringInfoChar(buf, '(');
2899 get_query_def(subquery, buf, context->namespaces, resultDesc,
2900 context->prettyFlags, context->indentLevel);
2902 appendStringInfoChar(buf, ')');
2904 else if (IsA(setOp, SetOperationStmt))
2906 SetOperationStmt *op = (SetOperationStmt *) setOp;
2908 if (PRETTY_INDENT(context))
2910 context->indentLevel += PRETTYINDENT_STD;
2911 appendStringInfoSpaces(buf, PRETTYINDENT_STD);
2915 * We force parens whenever nesting two SetOperationStmts. There are
2916 * some cases in which parens are needed around a leaf query too, but
2917 * those are more easily handled at the next level down (see code
2920 need_paren = !IsA(op->larg, RangeTblRef);
2923 appendStringInfoChar(buf, '(');
2924 get_setop_query(op->larg, query, context, resultDesc);
2926 appendStringInfoChar(buf, ')');
2928 if (!PRETTY_INDENT(context))
2929 appendStringInfoChar(buf, ' ');
2933 appendContextKeyword(context, "UNION ",
2934 -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
2936 case SETOP_INTERSECT:
2937 appendContextKeyword(context, "INTERSECT ",
2938 -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
2941 appendContextKeyword(context, "EXCEPT ",
2942 -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
2945 elog(ERROR, "unrecognized set op: %d",
2949 appendStringInfo(buf, "ALL ");
2951 if (PRETTY_INDENT(context))
2952 appendContextKeyword(context, "", 0, 0, 0);
2954 need_paren = !IsA(op->rarg, RangeTblRef);
2957 appendStringInfoChar(buf, '(');
2958 get_setop_query(op->rarg, query, context, resultDesc);
2960 appendStringInfoChar(buf, ')');
2962 if (PRETTY_INDENT(context))
2963 context->indentLevel -= PRETTYINDENT_STD;
2967 elog(ERROR, "unrecognized node type: %d",
2968 (int) nodeTag(setOp));
2973 * Display a sort/group clause.
2975 * Also returns the expression tree, so caller need not find it again.
2978 get_rule_sortgroupclause(SortGroupClause *srt, List *tlist, bool force_colno,
2979 deparse_context *context)
2981 StringInfo buf = context->buf;
2985 tle = get_sortgroupclause_tle(srt, tlist);
2986 expr = (Node *) tle->expr;
2989 * Use column-number form if requested by caller. Otherwise, if
2990 * expression is a constant, force it to be dumped with an explicit cast
2991 * as decoration --- this is because a simple integer constant is
2992 * ambiguous (and will be misinterpreted by findTargetlistEntry()) if we
2993 * dump it without any decoration. Otherwise, just dump the expression
2998 Assert(!tle->resjunk);
2999 appendStringInfo(buf, "%d", tle->resno);
3001 else if (expr && IsA(expr, Const))
3002 get_const_expr((Const *) expr, context, 1);
3004 get_rule_expr(expr, context, true);
3010 * Display an ORDER BY list.
3013 get_rule_orderby(List *orderList, List *targetList,
3014 bool force_colno, deparse_context *context)
3016 StringInfo buf = context->buf;
3021 foreach(l, orderList)
3023 SortGroupClause *srt = (SortGroupClause *) lfirst(l);
3026 TypeCacheEntry *typentry;
3028 appendStringInfoString(buf, sep);
3029 sortexpr = get_rule_sortgroupclause(srt, targetList,
3030 force_colno, context);
3031 sortcoltype = exprType(sortexpr);
3032 /* See whether operator is default < or > for datatype */
3033 typentry = lookup_type_cache(sortcoltype,
3034 TYPECACHE_LT_OPR | TYPECACHE_GT_OPR);
3035 if (srt->sortop == typentry->lt_opr)
3037 /* ASC is default, so emit nothing for it */
3038 if (srt->nulls_first)
3039 appendStringInfo(buf, " NULLS FIRST");
3041 else if (srt->sortop == typentry->gt_opr)
3043 appendStringInfo(buf, " DESC");
3044 /* DESC defaults to NULLS FIRST */
3045 if (!srt->nulls_first)
3046 appendStringInfo(buf, " NULLS LAST");
3050 appendStringInfo(buf, " USING %s",
3051 generate_operator_name(srt->sortop,
3054 /* be specific to eliminate ambiguity */
3055 if (srt->nulls_first)
3056 appendStringInfo(buf, " NULLS FIRST");
3058 appendStringInfo(buf, " NULLS LAST");
3065 * Display a WINDOW clause.
3067 * Note that the windowClause list might contain only anonymous window
3068 * specifications, in which case we should print nothing here.
3071 get_rule_windowclause(Query *query, deparse_context *context)
3073 StringInfo buf = context->buf;
3078 foreach(l, query->windowClause)
3080 WindowClause *wc = (WindowClause *) lfirst(l);
3082 if (wc->name == NULL)
3083 continue; /* ignore anonymous windows */
3086 appendContextKeyword(context, " WINDOW ",
3087 -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
3089 appendStringInfoString(buf, sep);
3091 appendStringInfo(buf, "%s AS ", quote_identifier(wc->name));
3093 get_rule_windowspec(wc, query->targetList, context);
3100 * Display a window definition
3103 get_rule_windowspec(WindowClause *wc, List *targetList,
3104 deparse_context *context)
3106 StringInfo buf = context->buf;
3107 bool needspace = false;
3111 appendStringInfoChar(buf, '(');
3114 appendStringInfoString(buf, quote_identifier(wc->refname));
3117 /* partition clauses are always inherited, so only print if no refname */
3118 if (wc->partitionClause && !wc->refname)
3121 appendStringInfoChar(buf, ' ');
3122 appendStringInfoString(buf, "PARTITION BY ");
3124 foreach(l, wc->partitionClause)
3126 SortGroupClause *grp = (SortGroupClause *) lfirst(l);
3128 appendStringInfoString(buf, sep);
3129 get_rule_sortgroupclause(grp, targetList,
3135 /* print ordering clause only if not inherited */
3136 if (wc->orderClause && !wc->copiedOrder)
3139 appendStringInfoChar(buf, ' ');
3140 appendStringInfoString(buf, "ORDER BY ");
3141 get_rule_orderby(wc->orderClause, targetList, false, context);
3144 /* framing clause is never inherited, so print unless it's default */
3145 if (wc->frameOptions & FRAMEOPTION_NONDEFAULT)
3148 appendStringInfoChar(buf, ' ');
3149 if (wc->frameOptions & FRAMEOPTION_RANGE)
3150 appendStringInfoString(buf, "RANGE ");
3151 else if (wc->frameOptions & FRAMEOPTION_ROWS)
3152 appendStringInfoString(buf, "ROWS ");
3155 if (wc->frameOptions & FRAMEOPTION_BETWEEN)
3156 appendStringInfoString(buf, "BETWEEN ");
3157 if (wc->frameOptions & FRAMEOPTION_START_UNBOUNDED_PRECEDING)
3158 appendStringInfoString(buf, "UNBOUNDED PRECEDING ");
3159 else if (wc->frameOptions & FRAMEOPTION_START_CURRENT_ROW)
3160 appendStringInfoString(buf, "CURRENT ROW ");
3163 if (wc->frameOptions & FRAMEOPTION_BETWEEN)
3165 appendStringInfoString(buf, "AND ");
3166 if (wc->frameOptions & FRAMEOPTION_END_UNBOUNDED_FOLLOWING)
3167 appendStringInfoString(buf, "UNBOUNDED FOLLOWING ");
3168 else if (wc->frameOptions & FRAMEOPTION_END_CURRENT_ROW)
3169 appendStringInfoString(buf, "CURRENT ROW ");
3173 /* we will now have a trailing space; remove it */
3176 appendStringInfoChar(buf, ')');
3180 * get_insert_query_def - Parse back an INSERT parsetree
3184 get_insert_query_def(Query *query, deparse_context *context)
3186 StringInfo buf = context->buf;
3187 RangeTblEntry *select_rte = NULL;
3188 RangeTblEntry *values_rte = NULL;
3191 ListCell *values_cell;
3193 List *strippedexprs;
3196 * If it's an INSERT ... SELECT or VALUES (...), (...), ... there will be
3197 * a single RTE for the SELECT or VALUES.
3199 foreach(l, query->rtable)
3201 rte = (RangeTblEntry *) lfirst(l);
3203 if (rte->rtekind == RTE_SUBQUERY)
3206 elog(ERROR, "too many subquery RTEs in INSERT");
3210 if (rte->rtekind == RTE_VALUES)
3213 elog(ERROR, "too many values RTEs in INSERT");
3217 if (select_rte && values_rte)
3218 elog(ERROR, "both subquery and values RTEs in INSERT");
3221 * Start the query with INSERT INTO relname
3223 rte = rt_fetch(query->resultRelation, query->rtable);
3224 Assert(rte->rtekind == RTE_RELATION);
3226 if (PRETTY_INDENT(context))
3228 context->indentLevel += PRETTYINDENT_STD;
3229 appendStringInfoChar(buf, ' ');
3231 appendStringInfo(buf, "INSERT INTO %s (",
3232 generate_relation_name(rte->relid, NIL));
3235 * Add the insert-column-names list. To handle indirection properly, we
3236 * need to look for indirection nodes in the top targetlist (if it's
3237 * INSERT ... SELECT or INSERT ... single VALUES), or in the first
3238 * expression list of the VALUES RTE (if it's INSERT ... multi VALUES). We
3239 * assume that all the expression lists will have similar indirection in
3243 values_cell = list_head((List *) linitial(values_rte->values_lists));
3246 strippedexprs = NIL;
3248 foreach(l, query->targetList)
3250 TargetEntry *tle = (TargetEntry *) lfirst(l);
3253 continue; /* ignore junk entries */
3255 appendStringInfoString(buf, sep);
3259 * Put out name of target column; look in the catalogs, not at
3260 * tle->resname, since resname will fail to track RENAME.
3262 appendStringInfoString(buf,
3263 quote_identifier(get_relid_attribute_name(rte->relid,
3267 * Print any indirection needed (subfields or subscripts), and strip
3268 * off the top-level nodes representing the indirection assignments.
3272 /* we discard the stripped expression in this case */
3273 processIndirection((Node *) lfirst(values_cell), context, true);
3274 values_cell = lnext(values_cell);
3278 /* we keep a list of the stripped expressions in this case */
3279 strippedexprs = lappend(strippedexprs,
3280 processIndirection((Node *) tle->expr,
3284 appendStringInfo(buf, ") ");
3288 /* Add the SELECT */
3289 get_query_def(select_rte->subquery, buf, NIL, NULL,
3290 context->prettyFlags, context->indentLevel);
3292 else if (values_rte)
3294 /* A WITH clause is possible here */
3295 get_with_clause(query, context);
3296 /* Add the multi-VALUES expression lists */
3297 get_values_def(values_rte->values_lists, context);
3301 /* A WITH clause is possible here */
3302 get_with_clause(query, context);
3303 /* Add the single-VALUES expression list */
3304 appendContextKeyword(context, "VALUES (",
3305 -PRETTYINDENT_STD, PRETTYINDENT_STD, 2);
3306 get_rule_expr((Node *) strippedexprs, context, false);
3307 appendStringInfoChar(buf, ')');
3310 /* Add RETURNING if present */
3311 if (query->returningList)
3313 appendContextKeyword(context, " RETURNING",
3314 -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
3315 get_target_list(query->returningList, context, NULL);
3321 * get_update_query_def - Parse back an UPDATE parsetree
3325 get_update_query_def(Query *query, deparse_context *context)
3327 StringInfo buf = context->buf;
3333 * Start the query with UPDATE relname SET
3335 rte = rt_fetch(query->resultRelation, query->rtable);
3336 Assert(rte->rtekind == RTE_RELATION);
3337 if (PRETTY_INDENT(context))
3339 appendStringInfoChar(buf, ' ');
3340 context->indentLevel += PRETTYINDENT_STD;
3342 appendStringInfo(buf, "UPDATE %s%s",
3344 generate_relation_name(rte->relid, NIL));
3345 if (rte->alias != NULL)
3346 appendStringInfo(buf, " %s",
3347 quote_identifier(rte->alias->aliasname));
3348 appendStringInfoString(buf, " SET ");
3350 /* Add the comma separated list of 'attname = value' */
3352 foreach(l, query->targetList)
3354 TargetEntry *tle = (TargetEntry *) lfirst(l);
3358 continue; /* ignore junk entries */
3360 appendStringInfoString(buf, sep);
3364 * Put out name of target column; look in the catalogs, not at
3365 * tle->resname, since resname will fail to track RENAME.
3367 appendStringInfoString(buf,
3368 quote_identifier(get_relid_attribute_name(rte->relid,
3372 * Print any indirection needed (subfields or subscripts), and strip
3373 * off the top-level nodes representing the indirection assignments.
3375 expr = processIndirection((Node *) tle->expr, context, true);
3377 appendStringInfo(buf, " = ");
3379 get_rule_expr(expr, context, false);
3382 /* Add the FROM clause if needed */
3383 get_from_clause(query, " FROM ", context);
3385 /* Add a WHERE clause if given */
3386 if (query->jointree->quals != NULL)
3388 appendContextKeyword(context, " WHERE ",
3389 -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
3390 get_rule_expr(query->jointree->quals, context, false);
3393 /* Add RETURNING if present */
3394 if (query->returningList)
3396 appendContextKeyword(context, " RETURNING",
3397 -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
3398 get_target_list(query->returningList, context, NULL);
3404 * get_delete_query_def - Parse back a DELETE parsetree
3408 get_delete_query_def(Query *query, deparse_context *context)
3410 StringInfo buf = context->buf;
3414 * Start the query with DELETE FROM relname
3416 rte = rt_fetch(query->resultRelation, query->rtable);
3417 Assert(rte->rtekind == RTE_RELATION);
3418 if (PRETTY_INDENT(context))
3420 appendStringInfoChar(buf, ' ');
3421 context->indentLevel += PRETTYINDENT_STD;
3423 appendStringInfo(buf, "DELETE FROM %s%s",
3425 generate_relation_name(rte->relid, NIL));
3426 if (rte->alias != NULL)
3427 appendStringInfo(buf, " %s",
3428 quote_identifier(rte->alias->aliasname));
3430 /* Add the USING clause if given */
3431 get_from_clause(query, " USING ", context);
3433 /* Add a WHERE clause if given */
3434 if (query->jointree->quals != NULL)
3436 appendContextKeyword(context, " WHERE ",
3437 -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
3438 get_rule_expr(query->jointree->quals, context, false);
3441 /* Add RETURNING if present */
3442 if (query->returningList)
3444 appendContextKeyword(context, " RETURNING",
3445 -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
3446 get_target_list(query->returningList, context, NULL);
3452 * get_utility_query_def - Parse back a UTILITY parsetree
3456 get_utility_query_def(Query *query, deparse_context *context)
3458 StringInfo buf = context->buf;
3460 if (query->utilityStmt && IsA(query->utilityStmt, NotifyStmt))
3462 NotifyStmt *stmt = (NotifyStmt *) query->utilityStmt;
3464 appendContextKeyword(context, "",
3465 0, PRETTYINDENT_STD, 1);
3466 appendStringInfo(buf, "NOTIFY %s",
3467 quote_identifier(stmt->conditionname));
3471 /* Currently only NOTIFY utility commands can appear in rules */
3472 elog(ERROR, "unexpected utility statement type");
3478 * push_plan: set up deparse_namespace to recurse into the tlist of a subplan
3480 * When expanding an OUTER or INNER reference, we must push new outer/inner
3481 * subplans in case the referenced expression itself uses OUTER/INNER. We
3482 * modify the top stack entry in-place to avoid affecting levelsup issues
3483 * (although in a Plan tree there really shouldn't be any).
3485 * Caller must save and restore outer_plan and inner_plan around this.
3487 * We also use this to initialize the fields during deparse_context_for_plan.
3490 push_plan(deparse_namespace *dpns, Plan *subplan)
3493 * We special-case Append to pretend that the first child plan is the
3494 * OUTER referent; we have to interpret OUTER Vars in the Append's tlist
3495 * according to one of the children, and the first one is the most
3496 * natural choice. Likewise special-case ModifyTable to pretend that the
3497 * first child plan is the OUTER referent; this is to support RETURNING
3498 * lists containing references to non-target relations.
3500 if (IsA(subplan, Append))
3501 dpns->outer_plan = (Plan *) linitial(((Append *) subplan)->appendplans);
3502 else if (IsA(subplan, ModifyTable))
3503 dpns->outer_plan = (Plan *) linitial(((ModifyTable *) subplan)->plans);
3505 dpns->outer_plan = outerPlan(subplan);
3508 * For a SubqueryScan, pretend the subplan is INNER referent. (We don't
3509 * use OUTER because that could someday conflict with the normal meaning.)
3510 * Likewise, for a CteScan, pretend the subquery's plan is INNER referent.
3512 if (IsA(subplan, SubqueryScan))
3513 dpns->inner_plan = ((SubqueryScan *) subplan)->subplan;
3514 else if (IsA(subplan, CteScan))
3516 int ctePlanId = ((CteScan *) subplan)->ctePlanId;
3518 if (ctePlanId > 0 && ctePlanId <= list_length(dpns->subplans))
3519 dpns->inner_plan = list_nth(dpns->subplans, ctePlanId - 1);
3521 dpns->inner_plan = NULL;
3524 dpns->inner_plan = innerPlan(subplan);
3529 * Display a Var appropriately.
3531 * In some cases (currently only when recursing into an unnamed join)
3532 * the Var's varlevelsup has to be interpreted with respect to a context
3533 * above the current one; levelsup indicates the offset.
3535 * If showstar is TRUE, whole-row Vars are displayed as "foo.*";
3536 * if FALSE, merely as "foo".
3538 * Returns the attname of the Var, or NULL if not determinable.
3541 get_variable(Var *var, int levelsup, bool showstar, deparse_context *context)
3543 StringInfo buf = context->buf;
3547 deparse_namespace *dpns;
3552 /* Find appropriate nesting depth */
3553 netlevelsup = var->varlevelsup + levelsup;
3554 if (netlevelsup >= list_length(context->namespaces))
3555 elog(ERROR, "bogus varlevelsup: %d offset %d",
3556 var->varlevelsup, levelsup);
3557 dpns = (deparse_namespace *) list_nth(context->namespaces,
3561 * Try to find the relevant RTE in this rtable. In a plan tree, it's
3562 * likely that varno is OUTER or INNER, in which case we must dig down
3563 * into the subplans.
3565 if (var->varno >= 1 && var->varno <= list_length(dpns->rtable))
3567 rte = rt_fetch(var->varno, dpns->rtable);
3568 attnum = var->varattno;
3570 else if (var->varno == OUTER && dpns->outer_plan)
3576 tle = get_tle_by_resno(dpns->outer_plan->targetlist, var->varattno);
3578 elog(ERROR, "bogus varattno for OUTER var: %d", var->varattno);
3580 Assert(netlevelsup == 0);
3581 save_outer = dpns->outer_plan;
3582 save_inner = dpns->inner_plan;
3583 push_plan(dpns, dpns->outer_plan);
3586 * Force parentheses because our caller probably assumed a Var is a
3587 * simple expression.
3589 if (!IsA(tle->expr, Var))
3590 appendStringInfoChar(buf, '(');
3591 get_rule_expr((Node *) tle->expr, context, true);
3592 if (!IsA(tle->expr, Var))
3593 appendStringInfoChar(buf, ')');
3595 dpns->outer_plan = save_outer;
3596 dpns->inner_plan = save_inner;
3599 else if (var->varno == INNER && dpns->inner_plan)
3605 tle = get_tle_by_resno(dpns->inner_plan->targetlist, var->varattno);
3607 elog(ERROR, "bogus varattno for INNER var: %d", var->varattno);
3609 Assert(netlevelsup == 0);
3610 save_outer = dpns->outer_plan;
3611 save_inner = dpns->inner_plan;
3612 push_plan(dpns, dpns->inner_plan);
3615 * Force parentheses because our caller probably assumed a Var is a
3616 * simple expression.
3618 if (!IsA(tle->expr, Var))
3619 appendStringInfoChar(buf, '(');
3620 get_rule_expr((Node *) tle->expr, context, true);
3621 if (!IsA(tle->expr, Var))
3622 appendStringInfoChar(buf, ')');
3624 dpns->outer_plan = save_outer;
3625 dpns->inner_plan = save_inner;
3630 elog(ERROR, "bogus varno: %d", var->varno);
3631 return NULL; /* keep compiler quiet */
3634 /* Identify names to use */
3635 schemaname = NULL; /* default assumptions */
3636 refname = rte->eref->aliasname;
3638 /* Exceptions occur only if the RTE is alias-less */
3639 if (rte->alias == NULL)
3641 if (rte->rtekind == RTE_RELATION)
3644 * It's possible that use of the bare refname would find another
3645 * more-closely-nested RTE, or be ambiguous, in which case we need
3646 * to specify the schemaname to avoid these errors.
3648 if (find_rte_by_refname(rte->eref->aliasname, context) != rte)
3649 schemaname = get_namespace_name(get_rel_namespace(rte->relid));
3651 else if (rte->rtekind == RTE_JOIN)
3654 * If it's an unnamed join, look at the expansion of the alias
3655 * variable. If it's a simple reference to one of the input vars
3656 * then recursively print the name of that var, instead. (This
3657 * allows correct decompiling of cases where there are identically
3658 * named columns on both sides of the join.) When it's not a
3659 * simple reference, we have to just print the unqualified
3660 * variable name (this can only happen with columns that were
3661 * merged by USING or NATURAL clauses).
3663 * This wouldn't work in decompiling plan trees, because we don't
3664 * store joinaliasvars lists after planning; but a plan tree
3665 * should never contain a join alias variable.
3667 if (rte->joinaliasvars == NIL)
3668 elog(ERROR, "cannot decompile join alias var in plan tree");
3673 aliasvar = (Var *) list_nth(rte->joinaliasvars, attnum - 1);
3674 if (IsA(aliasvar, Var))
3676 return get_variable(aliasvar, var->varlevelsup + levelsup,
3680 /* Unnamed join has neither schemaname nor refname */
3685 if (attnum == InvalidAttrNumber)
3688 attname = get_rte_attribute_name(rte, attnum);
3690 if (refname && (context->varprefix || attname == NULL))
3693 appendStringInfo(buf, "%s.",
3694 quote_identifier(schemaname));
3695 appendStringInfoString(buf, quote_identifier(refname));
3696 if (attname || showstar)
3697 appendStringInfoChar(buf, '.');
3700 appendStringInfoString(buf, quote_identifier(attname));
3702 appendStringInfoChar(buf, '*');
3709 * Get the name of a field of an expression of composite type.
3711 * This is fairly straightforward except for the case of a Var of type RECORD.
3712 * Since no actual table or view column is allowed to have type RECORD, such
3713 * a Var must refer to a JOIN or FUNCTION RTE or to a subquery output. We
3714 * drill down to find the ultimate defining expression and attempt to infer
3715 * the field name from it. We ereport if we can't determine the name.
3717 * levelsup is an extra offset to interpret the Var's varlevelsup correctly.
3720 get_name_for_var_field(Var *var, int fieldno,
3721 int levelsup, deparse_context *context)
3726 deparse_namespace *dpns;
3727 TupleDesc tupleDesc;
3731 * If it's a RowExpr that was expanded from a whole-row Var, use the
3732 * column names attached to it.
3734 if (IsA(var, RowExpr))
3736 RowExpr *r = (RowExpr *) var;
3738 if (fieldno > 0 && fieldno <= list_length(r->colnames))
3739 return strVal(list_nth(r->colnames, fieldno - 1));
3743 * If it's a Var of type RECORD, we have to find what the Var refers to;
3744 * if not, we can use get_expr_result_type. If that fails, we try
3745 * lookup_rowtype_tupdesc, which will probably fail too, but will ereport
3746 * an acceptable message.
3748 if (!IsA(var, Var) ||
3749 var->vartype != RECORDOID)
3751 if (get_expr_result_type((Node *) var, NULL, &tupleDesc) != TYPEFUNC_COMPOSITE)
3752 tupleDesc = lookup_rowtype_tupdesc_copy(exprType((Node *) var),
3753 exprTypmod((Node *) var));
3755 /* Got the tupdesc, so we can extract the field name */
3756 Assert(fieldno >= 1 && fieldno <= tupleDesc->natts);
3757 return NameStr(tupleDesc->attrs[fieldno - 1]->attname);
3760 /* Find appropriate nesting depth */
3761 netlevelsup = var->varlevelsup + levelsup;
3762 if (netlevelsup >= list_length(context->namespaces))
3763 elog(ERROR, "bogus varlevelsup: %d offset %d",
3764 var->varlevelsup, levelsup);
3765 dpns = (deparse_namespace *) list_nth(context->namespaces,
3769 * Try to find the relevant RTE in this rtable. In a plan tree, it's
3770 * likely that varno is OUTER or INNER, in which case we must dig down
3771 * into the subplans.
3773 if (var->varno >= 1 && var->varno <= list_length(dpns->rtable))
3775 rte = rt_fetch(var->varno, dpns->rtable);
3776 attnum = var->varattno;
3778 else if (var->varno == OUTER && dpns->outer_plan)
3785 tle = get_tle_by_resno(dpns->outer_plan->targetlist, var->varattno);
3787 elog(ERROR, "bogus varattno for OUTER var: %d", var->varattno);
3789 Assert(netlevelsup == 0);
3790 save_outer = dpns->outer_plan;
3791 save_inner = dpns->inner_plan;
3792 push_plan(dpns, dpns->outer_plan);
3794 result = get_name_for_var_field((Var *) tle->expr, fieldno,
3797 dpns->outer_plan = save_outer;
3798 dpns->inner_plan = save_inner;
3801 else if (var->varno == INNER && dpns->inner_plan)
3808 tle = get_tle_by_resno(dpns->inner_plan->targetlist, var->varattno);
3810 elog(ERROR, "bogus varattno for INNER var: %d", var->varattno);
3812 Assert(netlevelsup == 0);
3813 save_outer = dpns->outer_plan;
3814 save_inner = dpns->inner_plan;
3815 push_plan(dpns, dpns->inner_plan);
3817 result = get_name_for_var_field((Var *) tle->expr, fieldno,
3820 dpns->outer_plan = save_outer;
3821 dpns->inner_plan = save_inner;
3826 elog(ERROR, "bogus varno: %d", var->varno);
3827 return NULL; /* keep compiler quiet */
3830 if (attnum == InvalidAttrNumber)
3832 /* Var is whole-row reference to RTE, so select the right field */
3833 return get_rte_attribute_name(rte, fieldno);
3837 * This part has essentially the same logic as the parser's
3838 * expandRecordVariable() function, but we are dealing with a different
3839 * representation of the input context, and we only need one field name
3840 * not a TupleDesc. Also, we need special cases for finding subquery and
3841 * CTE subplans when deparsing Plan trees.
3843 expr = (Node *) var; /* default if we can't drill down */
3845 switch (rte->rtekind)
3852 * This case should not occur: a column of a table or values list
3853 * shouldn't have type RECORD. Fall through and fail (most
3854 * likely) at the bottom.
3858 /* Subselect-in-FROM: examine sub-select's output expr */
3862 TargetEntry *ste = get_tle_by_resno(rte->subquery->targetList,
3865 if (ste == NULL || ste->resjunk)
3866 elog(ERROR, "subquery %s does not have attribute %d",
3867 rte->eref->aliasname, attnum);
3868 expr = (Node *) ste->expr;
3872 * Recurse into the sub-select to see what its Var
3873 * refers to. We have to build an additional level of
3874 * namespace to keep in step with varlevelsup in the
3877 deparse_namespace mydpns;
3880 mydpns.rtable = rte->subquery->rtable;
3881 mydpns.ctes = rte->subquery->cteList;
3882 mydpns.subplans = NIL;
3883 mydpns.outer_plan = mydpns.inner_plan = NULL;
3885 context->namespaces = lcons(&mydpns,
3886 context->namespaces);
3888 result = get_name_for_var_field((Var *) expr, fieldno,
3891 context->namespaces =
3892 list_delete_first(context->namespaces);
3896 /* else fall through to inspect the expression */
3901 * We're deparsing a Plan tree so we don't have complete
3902 * RTE entries (in particular, rte->subquery is NULL). But
3903 * the only place we'd see a Var directly referencing a
3904 * SUBQUERY RTE is in a SubqueryScan plan node, and we can
3905 * look into the child plan's tlist instead.
3912 if (!dpns->inner_plan)
3913 elog(ERROR, "failed to find plan for subquery %s",
3914 rte->eref->aliasname);
3915 tle = get_tle_by_resno(dpns->inner_plan->targetlist,
3918 elog(ERROR, "bogus varattno for subquery var: %d",
3920 Assert(netlevelsup == 0);
3921 save_outer = dpns->outer_plan;
3922 save_inner = dpns->inner_plan;
3923 push_plan(dpns, dpns->inner_plan);
3925 result = get_name_for_var_field((Var *) tle->expr, fieldno,
3928 dpns->outer_plan = save_outer;
3929 dpns->inner_plan = save_inner;
3935 /* Join RTE --- recursively inspect the alias variable */
3936 if (rte->joinaliasvars == NIL)
3937 elog(ERROR, "cannot decompile join alias var in plan tree");
3938 Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
3939 expr = (Node *) list_nth(rte->joinaliasvars, attnum - 1);
3941 return get_name_for_var_field((Var *) expr, fieldno,
3942 var->varlevelsup + levelsup,
3944 /* else fall through to inspect the expression */
3949 * We couldn't get here unless a function is declared with one of
3950 * its result columns as RECORD, which is not allowed.
3954 /* CTE reference: examine subquery's output expr */
3956 CommonTableExpr *cte = NULL;
3961 * Try to find the referenced CTE using the namespace stack.
3963 ctelevelsup = rte->ctelevelsup + netlevelsup;
3964 if (ctelevelsup >= list_length(context->namespaces))
3968 deparse_namespace *ctedpns;
3970 ctedpns = (deparse_namespace *)
3971 list_nth(context->namespaces, ctelevelsup);
3972 foreach(lc, ctedpns->ctes)
3974 cte = (CommonTableExpr *) lfirst(lc);
3975 if (strcmp(cte->ctename, rte->ctename) == 0)
3981 Query *ctequery = (Query *) cte->ctequery;
3982 TargetEntry *ste = get_tle_by_resno(ctequery->targetList,
3985 if (ste == NULL || ste->resjunk)
3986 elog(ERROR, "subquery %s does not have attribute %d",
3987 rte->eref->aliasname, attnum);
3988 expr = (Node *) ste->expr;
3992 * Recurse into the CTE to see what its Var refers to.
3993 * We have to build an additional level of namespace
3994 * to keep in step with varlevelsup in the CTE.
3995 * Furthermore it could be an outer CTE, so we may
3996 * have to delete some levels of namespace.
3998 List *save_nslist = context->namespaces;
4000 deparse_namespace mydpns;
4003 mydpns.rtable = ctequery->rtable;
4004 mydpns.ctes = ctequery->cteList;
4005 mydpns.subplans = NIL;
4006 mydpns.outer_plan = mydpns.inner_plan = NULL;
4008 new_nslist = list_copy_tail(context->namespaces,
4010 context->namespaces = lcons(&mydpns, new_nslist);
4012 result = get_name_for_var_field((Var *) expr, fieldno,
4015 context->namespaces = save_nslist;
4019 /* else fall through to inspect the expression */
4024 * We're deparsing a Plan tree so we don't have a CTE
4025 * list. But the only place we'd see a Var directly
4026 * referencing a CTE RTE is in a CteScan plan node, and we
4027 * can look into the subplan's tlist instead.
4034 if (!dpns->inner_plan)
4035 elog(ERROR, "failed to find plan for CTE %s",
4036 rte->eref->aliasname);
4037 tle = get_tle_by_resno(dpns->inner_plan->targetlist,
4040 elog(ERROR, "bogus varattno for subquery var: %d",
4042 Assert(netlevelsup == 0);
4043 save_outer = dpns->outer_plan;
4044 save_inner = dpns->inner_plan;
4045 push_plan(dpns, dpns->inner_plan);
4047 result = get_name_for_var_field((Var *) tle->expr, fieldno,
4050 dpns->outer_plan = save_outer;
4051 dpns->inner_plan = save_inner;
4059 * We now have an expression we can't expand any more, so see if
4060 * get_expr_result_type() can do anything with it. If not, pass to
4061 * lookup_rowtype_tupdesc() which will probably fail, but will give an
4062 * appropriate error message while failing.
4064 if (get_expr_result_type(expr, NULL, &tupleDesc) != TYPEFUNC_COMPOSITE)
4065 tupleDesc = lookup_rowtype_tupdesc_copy(exprType(expr),
4068 /* Got the tupdesc, so we can extract the field name */
4069 Assert(fieldno >= 1 && fieldno <= tupleDesc->natts);
4070 return NameStr(tupleDesc->attrs[fieldno - 1]->attname);
4075 * find_rte_by_refname - look up an RTE by refname in a deparse context
4077 * Returns NULL if there is no matching RTE or the refname is ambiguous.
4079 * NOTE: this code is not really correct since it does not take account of
4080 * the fact that not all the RTEs in a rangetable may be visible from the
4081 * point where a Var reference appears. For the purposes we need, however,
4082 * the only consequence of a false match is that we might stick a schema
4083 * qualifier on a Var that doesn't really need it. So it seems close
4086 static RangeTblEntry *
4087 find_rte_by_refname(const char *refname, deparse_context *context)
4089 RangeTblEntry *result = NULL;
4092 foreach(nslist, context->namespaces)
4094 deparse_namespace *dpns = (deparse_namespace *) lfirst(nslist);
4097 foreach(rtlist, dpns->rtable)
4099 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rtlist);
4101 if (strcmp(rte->eref->aliasname, refname) == 0)
4104 return NULL; /* it's ambiguous */
4116 * get_simple_binary_op_name
4118 * helper function for isSimpleNode
4119 * will return single char binary operator name, or NULL if it's not
4122 get_simple_binary_op_name(OpExpr *expr)
4124 List *args = expr->args;
4126 if (list_length(args) == 2)
4128 /* binary operator */
4129 Node *arg1 = (Node *) linitial(args);
4130 Node *arg2 = (Node *) lsecond(args);
4133 op = generate_operator_name(expr->opno, exprType(arg1), exprType(arg2));
4134 if (strlen(op) == 1)
4142 * isSimpleNode - check if given node is simple (doesn't need parenthesizing)
4144 * true : simple in the context of parent node's type
4145 * false : not simple
4148 isSimpleNode(Node *node, Node *parentNode, int prettyFlags)
4153 switch (nodeTag(node))
4158 case T_CoerceToDomainValue:
4159 case T_SetToDefault:
4160 case T_CurrentOfExpr:
4161 /* single words: always simple */
4167 case T_CoalesceExpr:
4174 /* function-like: name(..) or name[..] */
4177 /* CASE keywords act as parentheses */
4184 * appears simple since . has top precedence, unless parent is
4185 * T_FieldSelect itself!
4187 return (IsA(parentNode, FieldSelect) ? false : true);
4192 * treat like FieldSelect (probably doesn't matter)
4194 return (IsA(parentNode, FieldStore) ? false : true);
4196 case T_CoerceToDomain:
4197 /* maybe simple, check args */
4198 return isSimpleNode((Node *) ((CoerceToDomain *) node)->arg,
4201 return isSimpleNode((Node *) ((RelabelType *) node)->arg,
4204 return isSimpleNode((Node *) ((CoerceViaIO *) node)->arg,
4206 case T_ArrayCoerceExpr:
4207 return isSimpleNode((Node *) ((ArrayCoerceExpr *) node)->arg,
4209 case T_ConvertRowtypeExpr:
4210 return isSimpleNode((Node *) ((ConvertRowtypeExpr *) node)->arg,
4215 /* depends on parent node type; needs further checking */
4216 if (prettyFlags & PRETTYFLAG_PAREN && IsA(parentNode, OpExpr))
4219 const char *parentOp;
4222 bool is_lopriparent;
4223 bool is_hipriparent;
4225 op = get_simple_binary_op_name((OpExpr *) node);
4229 /* We know only the basic operators + - and * / % */
4230 is_lopriop = (strchr("+-", *op) != NULL);
4231 is_hipriop = (strchr("*/%", *op) != NULL);
4232 if (!(is_lopriop || is_hipriop))
4235 parentOp = get_simple_binary_op_name((OpExpr *) parentNode);
4239 is_lopriparent = (strchr("+-", *parentOp) != NULL);
4240 is_hipriparent = (strchr("*/%", *parentOp) != NULL);
4241 if (!(is_lopriparent || is_hipriparent))
4244 if (is_hipriop && is_lopriparent)
4245 return true; /* op binds tighter than parent */
4247 if (is_lopriop && is_hipriparent)
4251 * Operators are same priority --- can skip parens only if
4252 * we have (a - b) - c, not a - (b - c).
4254 if (node == (Node *) linitial(((OpExpr *) parentNode)->args))
4259 /* else do the same stuff as for T_SubLink et al. */
4266 case T_DistinctExpr:
4267 switch (nodeTag(parentNode))
4271 /* special handling for casts */
4272 CoercionForm type = ((FuncExpr *) parentNode)->funcformat;
4274 if (type == COERCE_EXPLICIT_CAST ||
4275 type == COERCE_IMPLICIT_CAST)
4277 return true; /* own parentheses */
4279 case T_BoolExpr: /* lower precedence */
4280 case T_ArrayRef: /* other separators */
4281 case T_ArrayExpr: /* other separators */
4282 case T_RowExpr: /* other separators */
4283 case T_CoalesceExpr: /* own parentheses */
4284 case T_MinMaxExpr: /* own parentheses */
4285 case T_XmlExpr: /* own parentheses */
4286 case T_NullIfExpr: /* other separators */
4287 case T_Aggref: /* own parentheses */
4288 case T_WindowFunc: /* own parentheses */
4289 case T_CaseExpr: /* other separators */
4296 switch (nodeTag(parentNode))
4299 if (prettyFlags & PRETTYFLAG_PAREN)
4302 BoolExprType parentType;
4304 type = ((BoolExpr *) node)->boolop;
4305 parentType = ((BoolExpr *) parentNode)->boolop;
4310 if (parentType == AND_EXPR || parentType == OR_EXPR)
4314 if (parentType == OR_EXPR)
4322 /* special handling for casts */
4323 CoercionForm type = ((FuncExpr *) parentNode)->funcformat;
4325 if (type == COERCE_EXPLICIT_CAST ||
4326 type == COERCE_IMPLICIT_CAST)
4328 return true; /* own parentheses */
4330 case T_ArrayRef: /* other separators */
4331 case T_ArrayExpr: /* other separators */
4332 case T_RowExpr: /* other separators */
4333 case T_CoalesceExpr: /* own parentheses */
4334 case T_MinMaxExpr: /* own parentheses */
4335 case T_XmlExpr: /* own parentheses */
4336 case T_NullIfExpr: /* other separators */
4337 case T_Aggref: /* own parentheses */
4338 case T_WindowFunc: /* own parentheses */
4339 case T_CaseExpr: /* other separators */
4348 /* those we don't know: in dubio complexo */
4354 * appendContextKeyword - append a keyword to buffer
4356 * If prettyPrint is enabled, perform a line break, and adjust indentation.
4357 * Otherwise, just append the keyword.
4360 appendContextKeyword(deparse_context *context, const char *str,
4361 int indentBefore, int indentAfter, int indentPlus)
4363 if (PRETTY_INDENT(context))
4365 context->indentLevel += indentBefore;
4367 appendStringInfoChar(context->buf, '\n');
4368 appendStringInfoSpaces(context->buf,
4369 Max(context->indentLevel, 0) + indentPlus);
4370 appendStringInfoString(context->buf, str);
4372 context->indentLevel += indentAfter;
4373 if (context->indentLevel < 0)
4374 context->indentLevel = 0;
4377 appendStringInfoString(context->buf, str);
4381 * get_rule_expr_paren - deparse expr using get_rule_expr,
4382 * embracing the string with parentheses if necessary for prettyPrint.
4384 * Never embrace if prettyFlags=0, because it's done in the calling node.
4386 * Any node that does *not* embrace its argument node by sql syntax (with
4387 * parentheses, non-operator keywords like CASE/WHEN/ON, or comma etc) should
4388 * use get_rule_expr_paren instead of get_rule_expr so parentheses can be
4392 get_rule_expr_paren(Node *node, deparse_context *context,
4393 bool showimplicit, Node *parentNode)
4397 need_paren = PRETTY_PAREN(context) &&
4398 !isSimpleNode(node, parentNode, context->prettyFlags);
4401 appendStringInfoChar(context->buf, '(');
4403 get_rule_expr(node, context, showimplicit);
4406 appendStringInfoChar(context->buf, ')');
4411 * get_rule_expr - Parse back an expression
4413 * Note: showimplicit determines whether we display any implicit cast that
4414 * is present at the top of the expression tree. It is a passed argument,
4415 * not a field of the context struct, because we change the value as we
4416 * recurse down into the expression. In general we suppress implicit casts
4417 * when the result type is known with certainty (eg, the arguments of an
4418 * OR must be boolean). We display implicit casts for arguments of functions
4419 * and operators, since this is needed to be certain that the same function
4420 * or operator will be chosen when the expression is re-parsed.
4424 get_rule_expr(Node *node, deparse_context *context,
4427 StringInfo buf = context->buf;
4433 * Each level of get_rule_expr must emit an indivisible term
4434 * (parenthesized if necessary) to ensure result is reparsed into the same
4435 * expression tree. The only exception is that when the input is a List,
4436 * we emit the component items comma-separated with no surrounding
4437 * decoration; this is convenient for most callers.
4439 switch (nodeTag(node))
4442 (void) get_variable((Var *) node, 0, true, context);
4446 get_const_expr((Const *) node, context, 0);
4450 appendStringInfo(buf, "$%d", ((Param *) node)->paramid);
4454 get_agg_expr((Aggref *) node, context);
4458 get_windowfunc_expr((WindowFunc *) node, context);
4463 ArrayRef *aref = (ArrayRef *) node;
4467 * Parenthesize the argument unless it's a simple Var or a
4468 * FieldSelect. (In particular, if it's another ArrayRef, we
4469 * *must* parenthesize to avoid confusion.)
4471 need_parens = !IsA(aref->refexpr, Var) &&
4472 !IsA(aref->refexpr, FieldSelect);
4474 appendStringInfoChar(buf, '(');
4475 get_rule_expr((Node *) aref->refexpr, context, showimplicit);
4477 appendStringInfoChar(buf, ')');
4478 printSubscripts(aref, context);
4481 * Array assignment nodes should have been handled in
4482 * processIndirection().
4484 if (aref->refassgnexpr)
4485 elog(ERROR, "unexpected refassgnexpr");
4490 get_func_expr((FuncExpr *) node, context, showimplicit);
4493 case T_NamedArgExpr:
4495 NamedArgExpr *na = (NamedArgExpr *) node;
4497 get_rule_expr((Node *) na->arg, context, showimplicit);
4498 appendStringInfo(buf, " AS %s", quote_identifier(na->name));
4503 get_oper_expr((OpExpr *) node, context);
4506 case T_DistinctExpr:
4508 DistinctExpr *expr = (DistinctExpr *) node;
4509 List *args = expr->args;
4510 Node *arg1 = (Node *) linitial(args);
4511 Node *arg2 = (Node *) lsecond(args);
4513 if (!PRETTY_PAREN(context))
4514 appendStringInfoChar(buf, '(');
4515 get_rule_expr_paren(arg1, context, true, node);
4516 appendStringInfo(buf, " IS DISTINCT FROM ");
4517 get_rule_expr_paren(arg2, context, true, node);
4518 if (!PRETTY_PAREN(context))
4519 appendStringInfoChar(buf, ')');
4523 case T_ScalarArrayOpExpr:
4525 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
4526 List *args = expr->args;
4527 Node *arg1 = (Node *) linitial(args);
4528 Node *arg2 = (Node *) lsecond(args);
4530 if (!PRETTY_PAREN(context))
4531 appendStringInfoChar(buf, '(');
4532 get_rule_expr_paren(arg1, context, true, node);
4533 appendStringInfo(buf, " %s %s (",
4534 generate_operator_name(expr->opno,
4536 get_element_type(exprType(arg2))),
4537 expr->useOr ? "ANY" : "ALL");
4538 get_rule_expr_paren(arg2, context, true, node);
4539 appendStringInfoChar(buf, ')');
4540 if (!PRETTY_PAREN(context))
4541 appendStringInfoChar(buf, ')');
4547 BoolExpr *expr = (BoolExpr *) node;
4548 Node *first_arg = linitial(expr->args);
4549 ListCell *arg = lnext(list_head(expr->args));
4551 switch (expr->boolop)
4554 if (!PRETTY_PAREN(context))
4555 appendStringInfoChar(buf, '(');
4556 get_rule_expr_paren(first_arg, context,
4560 appendStringInfo(buf, " AND ");
4561 get_rule_expr_paren((Node *) lfirst(arg), context,
4565 if (!PRETTY_PAREN(context))
4566 appendStringInfoChar(buf, ')');
4570 if (!PRETTY_PAREN(context))
4571 appendStringInfoChar(buf, '(');
4572 get_rule_expr_paren(first_arg, context,
4576 appendStringInfo(buf, " OR ");
4577 get_rule_expr_paren((Node *) lfirst(arg), context,
4581 if (!PRETTY_PAREN(context))
4582 appendStringInfoChar(buf, ')');
4586 if (!PRETTY_PAREN(context))
4587 appendStringInfoChar(buf, '(');
4588 appendStringInfo(buf, "NOT ");
4589 get_rule_expr_paren(first_arg, context,
4591 if (!PRETTY_PAREN(context))
4592 appendStringInfoChar(buf, ')');
4596 elog(ERROR, "unrecognized boolop: %d",
4597 (int) expr->boolop);
4603 get_sublink_expr((SubLink *) node, context);
4608 SubPlan *subplan = (SubPlan *) node;
4611 * We cannot see an already-planned subplan in rule deparsing,
4612 * only while EXPLAINing a query plan. We don't try to
4613 * reconstruct the original SQL, just reference the subplan
4614 * that appears elsewhere in EXPLAIN's result.
4616 if (subplan->useHashTable)
4617 appendStringInfo(buf, "(hashed %s)", subplan->plan_name);
4619 appendStringInfo(buf, "(%s)", subplan->plan_name);
4623 case T_AlternativeSubPlan:
4625 AlternativeSubPlan *asplan = (AlternativeSubPlan *) node;
4628 /* As above, this can only happen during EXPLAIN */
4629 appendStringInfo(buf, "(alternatives: ");
4630 foreach(lc, asplan->subplans)
4632 SubPlan *splan = (SubPlan *) lfirst(lc);
4634 Assert(IsA(splan, SubPlan));
4635 if (splan->useHashTable)
4636 appendStringInfo(buf, "hashed %s", splan->plan_name);
4638 appendStringInfo(buf, "%s", splan->plan_name);
4640 appendStringInfo(buf, " or ");
4642 appendStringInfo(buf, ")");
4648 FieldSelect *fselect = (FieldSelect *) node;
4649 Node *arg = (Node *) fselect->arg;
4650 int fno = fselect->fieldnum;
4651 const char *fieldname;
4655 * Parenthesize the argument unless it's an ArrayRef or
4656 * another FieldSelect. Note in particular that it would be
4657 * WRONG to not parenthesize a Var argument; simplicity is not
4658 * the issue here, having the right number of names is.
4660 need_parens = !IsA(arg, ArrayRef) &&!IsA(arg, FieldSelect);
4662 appendStringInfoChar(buf, '(');
4663 get_rule_expr(arg, context, true);
4665 appendStringInfoChar(buf, ')');
4668 * Get and print the field name.
4670 fieldname = get_name_for_var_field((Var *) arg, fno,
4672 appendStringInfo(buf, ".%s", quote_identifier(fieldname));
4679 * We shouldn't see FieldStore here; it should have been stripped
4680 * off by processIndirection().
4682 elog(ERROR, "unexpected FieldStore");
4687 RelabelType *relabel = (RelabelType *) node;
4688 Node *arg = (Node *) relabel->arg;
4690 if (relabel->relabelformat == COERCE_IMPLICIT_CAST &&
4693 /* don't show the implicit cast */
4694 get_rule_expr_paren(arg, context, false, node);
4698 get_coercion_expr(arg, context,
4699 relabel->resulttype,
4700 relabel->resulttypmod,
4708 CoerceViaIO *iocoerce = (CoerceViaIO *) node;
4709 Node *arg = (Node *) iocoerce->arg;
4711 if (iocoerce->coerceformat == COERCE_IMPLICIT_CAST &&
4714 /* don't show the implicit cast */
4715 get_rule_expr_paren(arg, context, false, node);
4719 get_coercion_expr(arg, context,
4720 iocoerce->resulttype,
4727 case T_ArrayCoerceExpr:
4729 ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
4730 Node *arg = (Node *) acoerce->arg;
4732 if (acoerce->coerceformat == COERCE_IMPLICIT_CAST &&
4735 /* don't show the implicit cast */
4736 get_rule_expr_paren(arg, context, false, node);
4740 get_coercion_expr(arg, context,
4741 acoerce->resulttype,
4742 acoerce->resulttypmod,
4748 case T_ConvertRowtypeExpr:
4750 ConvertRowtypeExpr *convert = (ConvertRowtypeExpr *) node;
4751 Node *arg = (Node *) convert->arg;
4753 if (convert->convertformat == COERCE_IMPLICIT_CAST &&
4756 /* don't show the implicit cast */
4757 get_rule_expr_paren(arg, context, false, node);
4761 get_coercion_expr(arg, context,
4762 convert->resulttype, -1,
4770 CaseExpr *caseexpr = (CaseExpr *) node;
4773 appendContextKeyword(context, "CASE",
4774 0, PRETTYINDENT_VAR, 0);
4777 appendStringInfoChar(buf, ' ');
4778 get_rule_expr((Node *) caseexpr->arg, context, true);
4780 foreach(temp, caseexpr->args)
4782 CaseWhen *when = (CaseWhen *) lfirst(temp);
4783 Node *w = (Node *) when->expr;
4785 if (!PRETTY_INDENT(context))
4786 appendStringInfoChar(buf, ' ');
4787 appendContextKeyword(context, "WHEN ",
4792 * The parser should have produced WHEN clauses of the
4793 * form "CaseTestExpr = RHS"; we want to show just the
4794 * RHS. If the user wrote something silly like "CASE
4795 * boolexpr WHEN TRUE THEN ...", then the optimizer's
4796 * simplify_boolean_equality() may have reduced this
4797 * to just "CaseTestExpr" or "NOT CaseTestExpr", for
4798 * which we have to show "TRUE" or "FALSE". Also,
4799 * depending on context the original CaseTestExpr
4800 * might have been reduced to a Const (but we won't
4801 * see "WHEN Const"). We have also to consider the
4802 * possibility that an implicit coercion was inserted
4803 * between the CaseTestExpr and the operator.
4807 List *args = ((OpExpr *) w)->args;
4811 Assert(list_length(args) == 2);
4812 lhs = strip_implicit_coercions(linitial(args));
4813 Assert(IsA(lhs, CaseTestExpr) ||
4815 rhs = (Node *) lsecond(args);
4816 get_rule_expr(rhs, context, false);
4818 else if (IsA(strip_implicit_coercions(w),
4820 appendStringInfo(buf, "TRUE");
4821 else if (not_clause(w))
4823 Assert(IsA(strip_implicit_coercions((Node *) get_notclausearg((Expr *) w)),
4825 appendStringInfo(buf, "FALSE");
4828 elog(ERROR, "unexpected CASE WHEN clause: %d",
4832 get_rule_expr(w, context, false);
4833 appendStringInfo(buf, " THEN ");
4834 get_rule_expr((Node *) when->result, context, true);
4836 if (!PRETTY_INDENT(context))
4837 appendStringInfoChar(buf, ' ');
4838 appendContextKeyword(context, "ELSE ",
4840 get_rule_expr((Node *) caseexpr->defresult, context, true);
4841 if (!PRETTY_INDENT(context))
4842 appendStringInfoChar(buf, ' ');
4843 appendContextKeyword(context, "END",
4844 -PRETTYINDENT_VAR, 0, 0);
4850 ArrayExpr *arrayexpr = (ArrayExpr *) node;
4852 appendStringInfo(buf, "ARRAY[");
4853 get_rule_expr((Node *) arrayexpr->elements, context, true);
4854 appendStringInfoChar(buf, ']');
4857 * If the array isn't empty, we assume its elements are
4858 * coerced to the desired type. If it's empty, though, we
4859 * need an explicit coercion to the array type.
4861 if (arrayexpr->elements == NIL)
4862 appendStringInfo(buf, "::%s",
4863 format_type_with_typemod(arrayexpr->array_typeid, -1));
4869 RowExpr *rowexpr = (RowExpr *) node;
4870 TupleDesc tupdesc = NULL;
4876 * If it's a named type and not RECORD, we may have to skip
4877 * dropped columns and/or claim there are NULLs for added
4880 if (rowexpr->row_typeid != RECORDOID)
4882 tupdesc = lookup_rowtype_tupdesc(rowexpr->row_typeid, -1);
4883 Assert(list_length(rowexpr->args) <= tupdesc->natts);
4887 * SQL99 allows "ROW" to be omitted when there is more than
4888 * one column, but for simplicity we always print it.
4890 appendStringInfo(buf, "ROW(");
4893 foreach(arg, rowexpr->args)
4895 Node *e = (Node *) lfirst(arg);
4897 if (tupdesc == NULL ||
4898 !tupdesc->attrs[i]->attisdropped)
4900 appendStringInfoString(buf, sep);
4901 get_rule_expr(e, context, true);
4906 if (tupdesc != NULL)
4908 while (i < tupdesc->natts)
4910 if (!tupdesc->attrs[i]->attisdropped)
4912 appendStringInfoString(buf, sep);
4913 appendStringInfo(buf, "NULL");
4919 ReleaseTupleDesc(tupdesc);
4921 appendStringInfo(buf, ")");
4922 if (rowexpr->row_format == COERCE_EXPLICIT_CAST)
4923 appendStringInfo(buf, "::%s",
4924 format_type_with_typemod(rowexpr->row_typeid, -1));
4928 case T_RowCompareExpr:
4930 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
4935 * SQL99 allows "ROW" to be omitted when there is more than
4936 * one column, but for simplicity we always print it.
4938 appendStringInfo(buf, "(ROW(");
4940 foreach(arg, rcexpr->largs)
4942 Node *e = (Node *) lfirst(arg);
4944 appendStringInfoString(buf, sep);
4945 get_rule_expr(e, context, true);
4950 * We assume that the name of the first-column operator will
4951 * do for all the rest too. This is definitely open to
4952 * failure, eg if some but not all operators were renamed
4953 * since the construct was parsed, but there seems no way to
4956 appendStringInfo(buf, ") %s ROW(",
4957 generate_operator_name(linitial_oid(rcexpr->opnos),
4958 exprType(linitial(rcexpr->largs)),
4959 exprType(linitial(rcexpr->rargs))));
4961 foreach(arg, rcexpr->rargs)
4963 Node *e = (Node *) lfirst(arg);
4965 appendStringInfoString(buf, sep);
4966 get_rule_expr(e, context, true);
4969 appendStringInfo(buf, "))");
4973 case T_CoalesceExpr:
4975 CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
4977 appendStringInfo(buf, "COALESCE(");
4978 get_rule_expr((Node *) coalesceexpr->args, context, true);
4979 appendStringInfoChar(buf, ')');
4985 MinMaxExpr *minmaxexpr = (MinMaxExpr *) node;
4987 switch (minmaxexpr->op)
4990 appendStringInfo(buf, "GREATEST(");
4993 appendStringInfo(buf, "LEAST(");
4996 get_rule_expr((Node *) minmaxexpr->args, context, true);
4997 appendStringInfoChar(buf, ')');
5003 XmlExpr *xexpr = (XmlExpr *) node;
5004 bool needcomma = false;
5012 appendStringInfoString(buf, "XMLCONCAT(");
5015 appendStringInfoString(buf, "XMLELEMENT(");
5018 appendStringInfoString(buf, "XMLFOREST(");
5021 appendStringInfoString(buf, "XMLPARSE(");
5024 appendStringInfoString(buf, "XMLPI(");
5027 appendStringInfoString(buf, "XMLROOT(");
5029 case IS_XMLSERIALIZE:
5030 appendStringInfoString(buf, "XMLSERIALIZE(");
5035 if (xexpr->op == IS_XMLPARSE || xexpr->op == IS_XMLSERIALIZE)
5037 if (xexpr->xmloption == XMLOPTION_DOCUMENT)
5038 appendStringInfoString(buf, "DOCUMENT ");
5040 appendStringInfoString(buf, "CONTENT ");
5044 appendStringInfo(buf, "NAME %s",
5045 quote_identifier(map_xml_name_to_sql_identifier(xexpr->name)));
5048 if (xexpr->named_args)
5050 if (xexpr->op != IS_XMLFOREST)
5053 appendStringInfoString(buf, ", ");
5054 appendStringInfoString(buf, "XMLATTRIBUTES(");
5057 forboth(arg, xexpr->named_args, narg, xexpr->arg_names)
5059 Node *e = (Node *) lfirst(arg);
5060 char *argname = strVal(lfirst(narg));
5063 appendStringInfoString(buf, ", ");
5064 get_rule_expr((Node *) e, context, true);
5065 appendStringInfo(buf, " AS %s",
5066 quote_identifier(map_xml_name_to_sql_identifier(argname)));
5069 if (xexpr->op != IS_XMLFOREST)
5070 appendStringInfoChar(buf, ')');
5075 appendStringInfoString(buf, ", ");
5082 case IS_XMLSERIALIZE:
5083 /* no extra decoration needed */
5084 get_rule_expr((Node *) xexpr->args, context, true);
5087 Assert(list_length(xexpr->args) == 2);
5089 get_rule_expr((Node *) linitial(xexpr->args),
5092 con = (Const *) lsecond(xexpr->args);
5093 Assert(IsA(con, Const));
5094 Assert(!con->constisnull);
5095 if (DatumGetBool(con->constvalue))
5096 appendStringInfoString(buf,
5097 " PRESERVE WHITESPACE");
5099 appendStringInfoString(buf,
5100 " STRIP WHITESPACE");
5103 Assert(list_length(xexpr->args) == 3);
5105 get_rule_expr((Node *) linitial(xexpr->args),
5108 appendStringInfoString(buf, ", VERSION ");
5109 con = (Const *) lsecond(xexpr->args);
5110 if (IsA(con, Const) &&
5112 appendStringInfoString(buf, "NO VALUE");
5114 get_rule_expr((Node *) con, context, false);
5116 con = (Const *) lthird(xexpr->args);
5117 Assert(IsA(con, Const));
5118 if (con->constisnull)
5119 /* suppress STANDALONE NO VALUE */ ;
5122 switch (DatumGetInt32(con->constvalue))
5124 case XML_STANDALONE_YES:
5125 appendStringInfoString(buf,
5126 ", STANDALONE YES");
5128 case XML_STANDALONE_NO:
5129 appendStringInfoString(buf,
5132 case XML_STANDALONE_NO_VALUE:
5133 appendStringInfoString(buf,
5134 ", STANDALONE NO VALUE");
5142 get_rule_expr_paren((Node *) xexpr->args, context, false, node);
5147 if (xexpr->op == IS_XMLSERIALIZE)
5148 appendStringInfo(buf, " AS %s", format_type_with_typemod(xexpr->type,
5150 if (xexpr->op == IS_DOCUMENT)
5151 appendStringInfoString(buf, " IS DOCUMENT");
5153 appendStringInfoChar(buf, ')');
5159 NullIfExpr *nullifexpr = (NullIfExpr *) node;
5161 appendStringInfo(buf, "NULLIF(");
5162 get_rule_expr((Node *) nullifexpr->args, context, true);
5163 appendStringInfoChar(buf, ')');
5169 NullTest *ntest = (NullTest *) node;
5171 if (!PRETTY_PAREN(context))
5172 appendStringInfoChar(buf, '(');
5173 get_rule_expr_paren((Node *) ntest->arg, context, true, node);
5174 switch (ntest->nulltesttype)
5177 appendStringInfo(buf, " IS NULL");
5180 appendStringInfo(buf, " IS NOT NULL");
5183 elog(ERROR, "unrecognized nulltesttype: %d",
5184 (int) ntest->nulltesttype);
5186 if (!PRETTY_PAREN(context))
5187 appendStringInfoChar(buf, ')');
5193 BooleanTest *btest = (BooleanTest *) node;
5195 if (!PRETTY_PAREN(context))
5196 appendStringInfoChar(buf, '(');
5197 get_rule_expr_paren((Node *) btest->arg, context, false, node);
5198 switch (btest->booltesttype)
5201 appendStringInfo(buf, " IS TRUE");
5204 appendStringInfo(buf, " IS NOT TRUE");
5207 appendStringInfo(buf, " IS FALSE");
5210 appendStringInfo(buf, " IS NOT FALSE");
5213 appendStringInfo(buf, " IS UNKNOWN");
5215 case IS_NOT_UNKNOWN:
5216 appendStringInfo(buf, " IS NOT UNKNOWN");
5219 elog(ERROR, "unrecognized booltesttype: %d",
5220 (int) btest->booltesttype);
5222 if (!PRETTY_PAREN(context))
5223 appendStringInfoChar(buf, ')');
5227 case T_CoerceToDomain:
5229 CoerceToDomain *ctest = (CoerceToDomain *) node;
5230 Node *arg = (Node *) ctest->arg;
5232 if (ctest->coercionformat == COERCE_IMPLICIT_CAST &&
5235 /* don't show the implicit cast */
5236 get_rule_expr(arg, context, false);
5240 get_coercion_expr(arg, context,
5242 ctest->resulttypmod,
5248 case T_CoerceToDomainValue:
5249 appendStringInfo(buf, "VALUE");
5252 case T_SetToDefault:
5253 appendStringInfo(buf, "DEFAULT");
5256 case T_CurrentOfExpr:
5258 CurrentOfExpr *cexpr = (CurrentOfExpr *) node;
5260 if (cexpr->cursor_name)
5261 appendStringInfo(buf, "CURRENT OF %s",
5262 quote_identifier(cexpr->cursor_name));
5264 appendStringInfo(buf, "CURRENT OF $%d",
5265 cexpr->cursor_param);
5275 foreach(l, (List *) node)
5277 appendStringInfoString(buf, sep);
5278 get_rule_expr((Node *) lfirst(l), context, showimplicit);
5285 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(node));
5292 * get_oper_expr - Parse back an OpExpr node
5295 get_oper_expr(OpExpr *expr, deparse_context *context)
5297 StringInfo buf = context->buf;
5298 Oid opno = expr->opno;
5299 List *args = expr->args;
5301 if (!PRETTY_PAREN(context))
5302 appendStringInfoChar(buf, '(');
5303 if (list_length(args) == 2)
5305 /* binary operator */
5306 Node *arg1 = (Node *) linitial(args);
5307 Node *arg2 = (Node *) lsecond(args);
5309 get_rule_expr_paren(arg1, context, true, (Node *) expr);
5310 appendStringInfo(buf, " %s ",
5311 generate_operator_name(opno,
5314 get_rule_expr_paren(arg2, context, true, (Node *) expr);
5318 /* unary operator --- but which side? */
5319 Node *arg = (Node *) linitial(args);
5321 Form_pg_operator optup;
5323 tp = SearchSysCache(OPEROID,
5324 ObjectIdGetDatum(opno),
5326 if (!HeapTupleIsValid(tp))
5327 elog(ERROR, "cache lookup failed for operator %u", opno);
5328 optup = (Form_pg_operator) GETSTRUCT(tp);
5329 switch (optup->oprkind)
5332 appendStringInfo(buf, "%s ",
5333 generate_operator_name(opno,
5336 get_rule_expr_paren(arg, context, true, (Node *) expr);
5339 get_rule_expr_paren(arg, context, true, (Node *) expr);
5340 appendStringInfo(buf, " %s",
5341 generate_operator_name(opno,
5346 elog(ERROR, "bogus oprkind: %d", optup->oprkind);
5348 ReleaseSysCache(tp);
5350 if (!PRETTY_PAREN(context))
5351 appendStringInfoChar(buf, ')');
5355 * get_func_expr - Parse back a FuncExpr node
5358 get_func_expr(FuncExpr *expr, deparse_context *context,
5361 StringInfo buf = context->buf;
5362 Oid funcoid = expr->funcid;
5363 Oid argtypes[FUNC_MAX_ARGS];
5370 * If the function call came from an implicit coercion, then just show the
5371 * first argument --- unless caller wants to see implicit coercions.
5373 if (expr->funcformat == COERCE_IMPLICIT_CAST && !showimplicit)
5375 get_rule_expr_paren((Node *) linitial(expr->args), context,
5376 false, (Node *) expr);
5381 * If the function call came from a cast, then show the first argument
5382 * plus an explicit cast operation.
5384 if (expr->funcformat == COERCE_EXPLICIT_CAST ||
5385 expr->funcformat == COERCE_IMPLICIT_CAST)
5387 Node *arg = linitial(expr->args);
5388 Oid rettype = expr->funcresulttype;
5389 int32 coercedTypmod;
5391 /* Get the typmod if this is a length-coercion function */
5392 (void) exprIsLengthCoercion((Node *) expr, &coercedTypmod);
5394 get_coercion_expr(arg, context,
5395 rettype, coercedTypmod,
5402 * Normal function: display as proname(args). First we need to extract
5403 * the argument datatypes.
5405 if (list_length(expr->args) > FUNC_MAX_ARGS)
5407 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
5408 errmsg("too many arguments")));
5411 foreach(l, expr->args)
5413 Node *arg = (Node *) lfirst(l);
5415 if (IsA(arg, NamedArgExpr))
5416 argnames = lappend(argnames, ((NamedArgExpr *) arg)->name);
5417 argtypes[nargs] = exprType(arg);
5421 appendStringInfo(buf, "%s(",
5422 generate_function_name(funcoid, nargs,
5426 foreach(l, expr->args)
5429 appendStringInfoString(buf, ", ");
5430 if (is_variadic && lnext(l) == NULL)
5431 appendStringInfoString(buf, "VARIADIC ");
5432 get_rule_expr((Node *) lfirst(l), context, true);
5434 appendStringInfoChar(buf, ')');
5438 * get_agg_expr - Parse back an Aggref node
5441 get_agg_expr(Aggref *aggref, deparse_context *context)
5443 StringInfo buf = context->buf;
5444 Oid argtypes[FUNC_MAX_ARGS];
5449 /* Extract the regular arguments, ignoring resjunk stuff for the moment */
5452 foreach(l, aggref->args)
5454 TargetEntry *tle = (TargetEntry *) lfirst(l);
5455 Node *arg = (Node *) tle->expr;
5457 Assert(!IsA(arg, NamedArgExpr));
5460 if (nargs >= FUNC_MAX_ARGS) /* paranoia */
5462 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
5463 errmsg("too many arguments")));
5464 argtypes[nargs] = exprType(arg);
5465 arglist = lappend(arglist, arg);
5469 appendStringInfo(buf, "%s(%s",
5470 generate_function_name(aggref->aggfnoid, nargs,
5471 NIL, argtypes, NULL),
5472 (aggref->aggdistinct != NIL) ? "DISTINCT " : "");
5473 /* aggstar can be set only in zero-argument aggregates */
5474 if (aggref->aggstar)
5475 appendStringInfoChar(buf, '*');
5477 get_rule_expr((Node *) arglist, context, true);
5478 if (aggref->aggorder != NIL)
5480 appendStringInfoString(buf, " ORDER BY ");
5481 get_rule_orderby(aggref->aggorder, aggref->args, false, context);
5483 appendStringInfoChar(buf, ')');
5487 * get_windowfunc_expr - Parse back a WindowFunc node
5490 get_windowfunc_expr(WindowFunc *wfunc, deparse_context *context)
5492 StringInfo buf = context->buf;
5493 Oid argtypes[FUNC_MAX_ARGS];
5497 if (list_length(wfunc->args) > FUNC_MAX_ARGS)
5499 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
5500 errmsg("too many arguments")));
5502 foreach(l, wfunc->args)
5504 Node *arg = (Node *) lfirst(l);
5506 Assert(!IsA(arg, NamedArgExpr));
5507 argtypes[nargs] = exprType(arg);
5511 appendStringInfo(buf, "%s(",
5512 generate_function_name(wfunc->winfnoid, nargs,
5513 NIL, argtypes, NULL));
5514 /* winstar can be set only in zero-argument aggregates */
5516 appendStringInfoChar(buf, '*');
5518 get_rule_expr((Node *) wfunc->args, context, true);
5519 appendStringInfoString(buf, ") OVER ");
5521 foreach(l, context->windowClause)
5523 WindowClause *wc = (WindowClause *) lfirst(l);
5525 if (wc->winref == wfunc->winref)
5528 appendStringInfoString(buf, quote_identifier(wc->name));
5530 get_rule_windowspec(wc, context->windowTList, context);
5536 if (context->windowClause)
5537 elog(ERROR, "could not find window clause for winref %u",
5541 * In EXPLAIN, we don't have window context information available, so
5542 * we have to settle for this:
5544 appendStringInfoString(buf, "(?)");
5551 * Make a string representation of a value coerced to a specific type
5555 get_coercion_expr(Node *arg, deparse_context *context,
5556 Oid resulttype, int32 resulttypmod,
5559 StringInfo buf = context->buf;
5562 * Since parse_coerce.c doesn't immediately collapse application of
5563 * length-coercion functions to constants, what we'll typically see in
5564 * such cases is a Const with typmod -1 and a length-coercion function
5565 * right above it. Avoid generating redundant output. However, beware of
5566 * suppressing casts when the user actually wrote something like
5567 * 'foo'::text::char(3).
5569 if (arg && IsA(arg, Const) &&
5570 ((Const *) arg)->consttype == resulttype &&
5571 ((Const *) arg)->consttypmod == -1)
5573 /* Show the constant without normal ::typename decoration */
5574 get_const_expr((Const *) arg, context, -1);
5578 if (!PRETTY_PAREN(context))
5579 appendStringInfoChar(buf, '(');
5580 get_rule_expr_paren(arg, context, false, parentNode);
5581 if (!PRETTY_PAREN(context))
5582 appendStringInfoChar(buf, ')');
5584 appendStringInfo(buf, "::%s",
5585 format_type_with_typemod(resulttype, resulttypmod));
5591 * Make a string representation of a Const
5593 * showtype can be -1 to never show "::typename" decoration, or +1 to always
5594 * show it, or 0 to show it only if the constant wouldn't be assumed to be
5595 * the right type by default.
5599 get_const_expr(Const *constval, deparse_context *context, int showtype)
5601 StringInfo buf = context->buf;
5605 bool isfloat = false;
5608 if (constval->constisnull)
5611 * Always label the type of a NULL constant to prevent misdecisions
5612 * about type when reparsing.
5614 appendStringInfo(buf, "NULL");
5616 appendStringInfo(buf, "::%s",
5617 format_type_with_typemod(constval->consttype,
5618 constval->consttypmod));
5622 getTypeOutputInfo(constval->consttype,
5623 &typoutput, &typIsVarlena);
5625 extval = OidOutputFunctionCall(typoutput, constval->constvalue);
5627 switch (constval->consttype)
5638 * These types are printed without quotes unless they contain
5639 * values that aren't accepted by the scanner unquoted (e.g.,
5640 * 'NaN'). Note that strtod() and friends might accept NaN,
5641 * so we can't use that to test.
5643 * In reality we only need to defend against infinity and NaN,
5644 * so we need not get too crazy about pattern matching here.
5646 * There is a special-case gotcha: if the constant is signed,
5647 * we need to parenthesize it, else the parser might see a
5648 * leading plus/minus as binding less tightly than adjacent
5649 * operators --- particularly, the cast that we might attach
5652 if (strspn(extval, "0123456789+-eE.") == strlen(extval))
5654 if (extval[0] == '+' || extval[0] == '-')
5655 appendStringInfo(buf, "(%s)", extval);
5657 appendStringInfoString(buf, extval);
5658 if (strcspn(extval, "eE.") != strlen(extval))
5659 isfloat = true; /* it looks like a float */
5662 appendStringInfo(buf, "'%s'", extval);
5668 appendStringInfo(buf, "B'%s'", extval);
5672 if (strcmp(extval, "t") == 0)
5673 appendStringInfo(buf, "true");
5675 appendStringInfo(buf, "false");
5679 simple_quote_literal(buf, extval);
5689 * For showtype == 0, append ::typename unless the constant will be
5690 * implicitly typed as the right type when it is read in.
5692 * XXX this code has to be kept in sync with the behavior of the parser,
5693 * especially make_const.
5695 switch (constval->consttype)
5700 /* These types can be left unlabeled */
5706 * Float-looking constants will be typed as numeric, but if
5707 * there's a specific typmod we need to show it.
5709 needlabel = !isfloat || (constval->consttypmod >= 0);
5715 if (needlabel || showtype > 0)
5716 appendStringInfo(buf, "::%s",
5717 format_type_with_typemod(constval->consttype,
5718 constval->consttypmod));
5722 * simple_quote_literal - Format a string as a SQL literal, append to buf
5725 simple_quote_literal(StringInfo buf, const char *val)
5730 * We form the string literal according to the prevailing setting of
5731 * standard_conforming_strings; we never use E''. User is responsible for
5732 * making sure result is used correctly.
5734 appendStringInfoChar(buf, '\'');
5735 for (valptr = val; *valptr; valptr++)
5739 if (SQL_STR_DOUBLE(ch, !standard_conforming_strings))
5740 appendStringInfoChar(buf, ch);
5741 appendStringInfoChar(buf, ch);
5743 appendStringInfoChar(buf, '\'');
5748 * get_sublink_expr - Parse back a sublink
5752 get_sublink_expr(SubLink *sublink, deparse_context *context)
5754 StringInfo buf = context->buf;
5755 Query *query = (Query *) (sublink->subselect);
5756 char *opname = NULL;
5759 if (sublink->subLinkType == ARRAY_SUBLINK)
5760 appendStringInfo(buf, "ARRAY(");
5762 appendStringInfoChar(buf, '(');
5765 * Note that we print the name of only the first operator, when there are
5766 * multiple combining operators. This is an approximation that could go
5767 * wrong in various scenarios (operators in different schemas, renamed
5768 * operators, etc) but there is not a whole lot we can do about it, since
5769 * the syntax allows only one operator to be shown.
5771 if (sublink->testexpr)
5773 if (IsA(sublink->testexpr, OpExpr))
5775 /* single combining operator */
5776 OpExpr *opexpr = (OpExpr *) sublink->testexpr;
5778 get_rule_expr(linitial(opexpr->args), context, true);
5779 opname = generate_operator_name(opexpr->opno,
5780 exprType(linitial(opexpr->args)),
5781 exprType(lsecond(opexpr->args)));
5783 else if (IsA(sublink->testexpr, BoolExpr))
5785 /* multiple combining operators, = or <> cases */
5789 appendStringInfoChar(buf, '(');
5791 foreach(l, ((BoolExpr *) sublink->testexpr)->args)
5793 OpExpr *opexpr = (OpExpr *) lfirst(l);
5795 Assert(IsA(opexpr, OpExpr));
5796 appendStringInfoString(buf, sep);
5797 get_rule_expr(linitial(opexpr->args), context, true);
5799 opname = generate_operator_name(opexpr->opno,
5800 exprType(linitial(opexpr->args)),
5801 exprType(lsecond(opexpr->args)));
5804 appendStringInfoChar(buf, ')');
5806 else if (IsA(sublink->testexpr, RowCompareExpr))
5808 /* multiple combining operators, < <= > >= cases */
5809 RowCompareExpr *rcexpr = (RowCompareExpr *) sublink->testexpr;
5811 appendStringInfoChar(buf, '(');
5812 get_rule_expr((Node *) rcexpr->largs, context, true);
5813 opname = generate_operator_name(linitial_oid(rcexpr->opnos),
5814 exprType(linitial(rcexpr->largs)),
5815 exprType(linitial(rcexpr->rargs)));
5816 appendStringInfoChar(buf, ')');
5819 elog(ERROR, "unrecognized testexpr type: %d",
5820 (int) nodeTag(sublink->testexpr));
5825 switch (sublink->subLinkType)
5827 case EXISTS_SUBLINK:
5828 appendStringInfo(buf, "EXISTS ");
5832 if (strcmp(opname, "=") == 0) /* Represent = ANY as IN */
5833 appendStringInfo(buf, " IN ");
5835 appendStringInfo(buf, " %s ANY ", opname);
5839 appendStringInfo(buf, " %s ALL ", opname);
5842 case ROWCOMPARE_SUBLINK:
5843 appendStringInfo(buf, " %s ", opname);
5851 case CTE_SUBLINK: /* shouldn't occur in a SubLink */
5853 elog(ERROR, "unrecognized sublink type: %d",
5854 (int) sublink->subLinkType);
5859 appendStringInfoChar(buf, '(');
5861 get_query_def(query, buf, context->namespaces, NULL,
5862 context->prettyFlags, context->indentLevel);
5865 appendStringInfo(buf, "))");
5867 appendStringInfoChar(buf, ')');
5872 * get_from_clause - Parse back a FROM clause
5874 * "prefix" is the keyword that denotes the start of the list of FROM
5875 * elements. It is FROM when used to parse back SELECT and UPDATE, but
5876 * is USING when parsing back DELETE.
5880 get_from_clause(Query *query, const char *prefix, deparse_context *context)
5882 StringInfo buf = context->buf;
5887 * We use the query's jointree as a guide to what to print. However, we
5888 * must ignore auto-added RTEs that are marked not inFromCl. (These can
5889 * only appear at the top level of the jointree, so it's sufficient to
5890 * check here.) This check also ensures we ignore the rule pseudo-RTEs
5893 foreach(l, query->jointree->fromlist)
5895 Node *jtnode = (Node *) lfirst(l);
5897 if (IsA(jtnode, RangeTblRef))
5899 int varno = ((RangeTblRef *) jtnode)->rtindex;
5900 RangeTblEntry *rte = rt_fetch(varno, query->rtable);
5908 appendContextKeyword(context, prefix,
5909 -PRETTYINDENT_STD, PRETTYINDENT_STD, 2);
5913 appendStringInfoString(buf, ", ");
5915 get_from_clause_item(jtnode, query, context);
5920 get_from_clause_item(Node *jtnode, Query *query, deparse_context *context)
5922 StringInfo buf = context->buf;
5924 if (IsA(jtnode, RangeTblRef))
5926 int varno = ((RangeTblRef *) jtnode)->rtindex;
5927 RangeTblEntry *rte = rt_fetch(varno, query->rtable);
5928 bool gavealias = false;
5930 switch (rte->rtekind)
5933 /* Normal relation RTE */
5934 appendStringInfo(buf, "%s%s",
5936 generate_relation_name(rte->relid,
5937 context->namespaces));
5941 appendStringInfoChar(buf, '(');
5942 get_query_def(rte->subquery, buf, context->namespaces, NULL,
5943 context->prettyFlags, context->indentLevel);
5944 appendStringInfoChar(buf, ')');
5948 get_rule_expr(rte->funcexpr, context, true);
5951 /* Values list RTE */
5952 get_values_def(rte->values_lists, context);
5955 appendStringInfoString(buf, quote_identifier(rte->ctename));
5958 elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
5962 if (rte->alias != NULL)
5964 appendStringInfo(buf, " %s",
5965 quote_identifier(rte->alias->aliasname));
5968 else if (rte->rtekind == RTE_RELATION &&
5969 strcmp(rte->eref->aliasname, get_rel_name(rte->relid)) != 0)
5972 * Apparently the rel has been renamed since the rule was made.
5973 * Emit a fake alias clause so that variable references will still
5974 * work. This is not a 100% solution but should work in most
5975 * reasonable situations.
5977 appendStringInfo(buf, " %s",
5978 quote_identifier(rte->eref->aliasname));
5981 else if (rte->rtekind == RTE_FUNCTION)
5984 * For a function RTE, always give an alias. This covers possible
5985 * renaming of the function and/or instability of the
5986 * FigureColname rules for things that aren't simple functions.
5988 appendStringInfo(buf, " %s",
5989 quote_identifier(rte->eref->aliasname));
5993 if (rte->rtekind == RTE_FUNCTION)
5995 if (rte->funccoltypes != NIL)
5997 /* Function returning RECORD, reconstruct the columndefs */
5999 appendStringInfo(buf, " AS ");
6000 get_from_clause_coldeflist(rte->eref->colnames,
6002 rte->funccoltypmods,
6008 * For a function RTE, always emit a complete column alias
6009 * list; this is to protect against possible instability of
6010 * the default column names (eg, from altering parameter
6013 get_from_clause_alias(rte->eref, rte, context);
6019 * For non-function RTEs, just report whatever the user originally
6020 * gave as column aliases.
6022 get_from_clause_alias(rte->alias, rte, context);
6025 else if (IsA(jtnode, JoinExpr))
6027 JoinExpr *j = (JoinExpr *) jtnode;
6028 bool need_paren_on_right;
6030 need_paren_on_right = PRETTY_PAREN(context) &&
6031 !IsA(j->rarg, RangeTblRef) &&
6032 !(IsA(j->rarg, JoinExpr) &&((JoinExpr *) j->rarg)->alias != NULL);
6034 if (!PRETTY_PAREN(context) || j->alias != NULL)
6035 appendStringInfoChar(buf, '(');
6037 get_from_clause_item(j->larg, query, context);
6041 if (!PRETTY_INDENT(context))
6042 appendStringInfoChar(buf, ' ');
6043 switch (j->jointype)
6046 appendContextKeyword(context, "NATURAL JOIN ",
6048 PRETTYINDENT_JOIN, 0);
6051 appendContextKeyword(context, "NATURAL LEFT JOIN ",
6053 PRETTYINDENT_JOIN, 0);
6056 appendContextKeyword(context, "NATURAL FULL JOIN ",
6058 PRETTYINDENT_JOIN, 0);
6061 appendContextKeyword(context, "NATURAL RIGHT JOIN ",
6063 PRETTYINDENT_JOIN, 0);
6066 elog(ERROR, "unrecognized join type: %d",
6072 switch (j->jointype)
6076 appendContextKeyword(context, " JOIN ",
6078 PRETTYINDENT_JOIN, 2);
6080 appendContextKeyword(context, " CROSS JOIN ",
6082 PRETTYINDENT_JOIN, 1);
6085 appendContextKeyword(context, " LEFT JOIN ",
6087 PRETTYINDENT_JOIN, 2);
6090 appendContextKeyword(context, " FULL JOIN ",
6092 PRETTYINDENT_JOIN, 2);
6095 appendContextKeyword(context, " RIGHT JOIN ",
6097 PRETTYINDENT_JOIN, 2);
6100 elog(ERROR, "unrecognized join type: %d",
6105 if (need_paren_on_right)
6106 appendStringInfoChar(buf, '(');
6107 get_from_clause_item(j->rarg, query, context);
6108 if (need_paren_on_right)
6109 appendStringInfoChar(buf, ')');
6111 context->indentLevel -= PRETTYINDENT_JOIN_ON;
6119 appendStringInfo(buf, " USING (");
6120 foreach(col, j->usingClause)
6122 if (col != list_head(j->usingClause))
6123 appendStringInfo(buf, ", ");
6124 appendStringInfoString(buf,
6125 quote_identifier(strVal(lfirst(col))));
6127 appendStringInfoChar(buf, ')');
6131 appendStringInfo(buf, " ON ");
6132 if (!PRETTY_PAREN(context))
6133 appendStringInfoChar(buf, '(');
6134 get_rule_expr(j->quals, context, false);
6135 if (!PRETTY_PAREN(context))
6136 appendStringInfoChar(buf, ')');
6139 if (!PRETTY_PAREN(context) || j->alias != NULL)
6140 appendStringInfoChar(buf, ')');
6142 /* Yes, it's correct to put alias after the right paren ... */
6143 if (j->alias != NULL)
6145 appendStringInfo(buf, " %s",
6146 quote_identifier(j->alias->aliasname));
6147 get_from_clause_alias(j->alias,
6148 rt_fetch(j->rtindex, query->rtable),
6153 elog(ERROR, "unrecognized node type: %d",
6154 (int) nodeTag(jtnode));
6158 * get_from_clause_alias - reproduce column alias list
6160 * This is tricky because we must ignore dropped columns.
6163 get_from_clause_alias(Alias *alias, RangeTblEntry *rte,
6164 deparse_context *context)
6166 StringInfo buf = context->buf;
6171 if (alias == NULL || alias->colnames == NIL)
6172 return; /* definitely nothing to do */
6175 foreach(col, alias->colnames)
6178 if (get_rte_attribute_is_dropped(rte, attnum))
6182 appendStringInfoChar(buf, '(');
6186 appendStringInfo(buf, ", ");
6187 appendStringInfoString(buf,
6188 quote_identifier(strVal(lfirst(col))));
6191 appendStringInfoChar(buf, ')');
6195 * get_from_clause_coldeflist - reproduce FROM clause coldeflist
6197 * The coldeflist is appended immediately (no space) to buf. Caller is
6198 * responsible for ensuring that an alias or AS is present before it.
6201 get_from_clause_coldeflist(List *names, List *types, List *typmods,
6202 deparse_context *context)
6204 StringInfo buf = context->buf;
6210 appendStringInfoChar(buf, '(');
6212 l2 = list_head(types);
6213 l3 = list_head(typmods);
6216 char *attname = strVal(lfirst(l1));
6220 atttypid = lfirst_oid(l2);
6222 atttypmod = lfirst_int(l3);
6226 appendStringInfo(buf, ", ");
6227 appendStringInfo(buf, "%s %s",
6228 quote_identifier(attname),
6229 format_type_with_typemod(atttypid, atttypmod));
6233 appendStringInfoChar(buf, ')');
6237 * get_opclass_name - fetch name of an index operator class
6239 * The opclass name is appended (after a space) to buf.
6241 * Output is suppressed if the opclass is the default for the given
6242 * actual_datatype. (If you don't want this behavior, just pass
6243 * InvalidOid for actual_datatype.)
6246 get_opclass_name(Oid opclass, Oid actual_datatype,
6250 Form_pg_opclass opcrec;
6254 ht_opc = SearchSysCache(CLAOID,
6255 ObjectIdGetDatum(opclass),
6257 if (!HeapTupleIsValid(ht_opc))
6258 elog(ERROR, "cache lookup failed for opclass %u", opclass);
6259 opcrec = (Form_pg_opclass) GETSTRUCT(ht_opc);
6261 if (!OidIsValid(actual_datatype) ||
6262 GetDefaultOpClass(actual_datatype, opcrec->opcmethod) != opclass)
6264 /* Okay, we need the opclass name. Do we need to qualify it? */
6265 opcname = NameStr(opcrec->opcname);
6266 if (OpclassIsVisible(opclass))
6267 appendStringInfo(buf, " %s", quote_identifier(opcname));
6270 nspname = get_namespace_name(opcrec->opcnamespace);
6271 appendStringInfo(buf, " %s.%s",
6272 quote_identifier(nspname),
6273 quote_identifier(opcname));
6276 ReleaseSysCache(ht_opc);
6280 * processIndirection - take care of array and subfield assignment
6282 * We strip any top-level FieldStore or assignment ArrayRef nodes that
6283 * appear in the input, and return the subexpression that's to be assigned.
6284 * If printit is true, we also print out the appropriate decoration for the
6285 * base column name (that the caller just printed).
6288 processIndirection(Node *node, deparse_context *context, bool printit)
6290 StringInfo buf = context->buf;
6296 if (IsA(node, FieldStore))
6298 FieldStore *fstore = (FieldStore *) node;
6302 /* lookup tuple type */
6303 typrelid = get_typ_typrelid(fstore->resulttype);
6304 if (!OidIsValid(typrelid))
6305 elog(ERROR, "argument type %s of FieldStore is not a tuple type",
6306 format_type_be(fstore->resulttype));
6309 * Print the field name. Note we assume here that there's only
6310 * one field being assigned to. This is okay in stored rules but
6311 * could be wrong in executable target lists. Presently no
6312 * problem since explain.c doesn't print plan targetlists, but
6313 * someday may have to think of something ...
6315 fieldname = get_relid_attribute_name(typrelid,
6316 linitial_int(fstore->fieldnums));
6318 appendStringInfo(buf, ".%s", quote_identifier(fieldname));
6321 * We ignore arg since it should be an uninteresting reference to
6322 * the target column or subcolumn.
6324 node = (Node *) linitial(fstore->newvals);
6326 else if (IsA(node, ArrayRef))
6328 ArrayRef *aref = (ArrayRef *) node;
6330 if (aref->refassgnexpr == NULL)
6333 printSubscripts(aref, context);
6336 * We ignore refexpr since it should be an uninteresting reference
6337 * to the target column or subcolumn.
6339 node = (Node *) aref->refassgnexpr;
6349 printSubscripts(ArrayRef *aref, deparse_context *context)
6351 StringInfo buf = context->buf;
6352 ListCell *lowlist_item;
6353 ListCell *uplist_item;
6355 lowlist_item = list_head(aref->reflowerindexpr); /* could be NULL */
6356 foreach(uplist_item, aref->refupperindexpr)
6358 appendStringInfoChar(buf, '[');
6361 get_rule_expr((Node *) lfirst(lowlist_item), context, false);
6362 appendStringInfoChar(buf, ':');
6363 lowlist_item = lnext(lowlist_item);
6365 get_rule_expr((Node *) lfirst(uplist_item), context, false);
6366 appendStringInfoChar(buf, ']');
6371 * quote_identifier - Quote an identifier only if needed
6373 * When quotes are needed, we palloc the required space; slightly
6374 * space-wasteful but well worth it for notational simplicity.
6377 quote_identifier(const char *ident)
6380 * Can avoid quoting if ident starts with a lowercase letter or underscore
6381 * and contains only lowercase letters, digits, and underscores, *and* is
6382 * not any SQL keyword. Otherwise, supply quotes.
6391 * would like to use <ctype.h> macros here, but they might yield unwanted
6392 * locale-specific results...
6394 safe = ((ident[0] >= 'a' && ident[0] <= 'z') || ident[0] == '_');
6396 for (ptr = ident; *ptr; ptr++)
6400 if ((ch >= 'a' && ch <= 'z') ||
6401 (ch >= '0' && ch <= '9') ||
6417 * Check for keyword. We quote keywords except for unreserved ones.
6418 * (In some cases we could avoid quoting a col_name or type_func_name
6419 * keyword, but it seems much harder than it's worth to tell that.)
6421 * Note: ScanKeywordLookup() does case-insensitive comparison, but
6422 * that's fine, since we already know we have all-lower-case.
6424 const ScanKeyword *keyword = ScanKeywordLookup(ident,
6428 if (keyword != NULL && keyword->category != UNRESERVED_KEYWORD)
6433 return ident; /* no change needed */
6435 result = (char *) palloc(strlen(ident) + nquotes + 2 + 1);
6439 for (ptr = ident; *ptr; ptr++)
6454 * quote_qualified_identifier - Quote a possibly-qualified identifier
6456 * Return a name of the form qualifier.ident, or just ident if qualifier
6457 * is NULL, quoting each component if necessary. The result is palloc'd.
6460 quote_qualified_identifier(const char *qualifier,
6465 initStringInfo(&buf);
6467 appendStringInfo(&buf, "%s.", quote_identifier(qualifier));
6468 appendStringInfoString(&buf, quote_identifier(ident));
6473 * generate_relation_name
6474 * Compute the name to display for a relation specified by OID
6476 * The result includes all necessary quoting and schema-prefixing.
6478 * If namespaces isn't NIL, it must be a list of deparse_namespace nodes.
6479 * We will forcibly qualify the relation name if it equals any CTE name
6480 * visible in the namespace list.
6483 generate_relation_name(Oid relid, List *namespaces)
6486 Form_pg_class reltup;
6493 tp = SearchSysCache(RELOID,
6494 ObjectIdGetDatum(relid),
6496 if (!HeapTupleIsValid(tp))
6497 elog(ERROR, "cache lookup failed for relation %u", relid);
6498 reltup = (Form_pg_class) GETSTRUCT(tp);
6499 relname = NameStr(reltup->relname);
6501 /* Check for conflicting CTE name */
6503 foreach(nslist, namespaces)
6505 deparse_namespace *dpns = (deparse_namespace *) lfirst(nslist);
6508 foreach(ctlist, dpns->ctes)
6510 CommonTableExpr *cte = (CommonTableExpr *) lfirst(ctlist);
6512 if (strcmp(cte->ctename, relname) == 0)
6522 /* Otherwise, qualify the name if not visible in search path */
6524 need_qual = !RelationIsVisible(relid);
6527 nspname = get_namespace_name(reltup->relnamespace);
6531 result = quote_qualified_identifier(nspname, relname);
6533 ReleaseSysCache(tp);
6539 * generate_function_name
6540 * Compute the name to display for a function specified by OID,
6541 * given that it is being called with the specified actual arg names and
6542 * types. (Those matter because of ambiguous-function resolution rules.)
6544 * The result includes all necessary quoting and schema-prefixing. We can
6545 * also pass back an indication of whether the function is variadic.
6548 generate_function_name(Oid funcid, int nargs, List *argnames,
6549 Oid *argtypes, bool *is_variadic)
6552 Form_pg_proc procform;
6556 FuncDetailCode p_result;
6561 Oid *p_true_typeids;
6563 proctup = SearchSysCache(PROCOID,
6564 ObjectIdGetDatum(funcid),
6566 if (!HeapTupleIsValid(proctup))
6567 elog(ERROR, "cache lookup failed for function %u", funcid);
6568 procform = (Form_pg_proc) GETSTRUCT(proctup);
6569 proname = NameStr(procform->proname);
6572 * The idea here is to schema-qualify only if the parser would fail to
6573 * resolve the correct function given the unqualified func name with the
6574 * specified argtypes. If the function is variadic, we should presume
6575 * that VARIADIC will be included in the call.
6577 p_result = func_get_detail(list_make1(makeString(proname)),
6578 NIL, argnames, nargs, argtypes,
6579 !OidIsValid(procform->provariadic), true,
6580 &p_funcid, &p_rettype,
6581 &p_retset, &p_nvargs, &p_true_typeids, NULL);
6582 if ((p_result == FUNCDETAIL_NORMAL ||
6583 p_result == FUNCDETAIL_AGGREGATE ||
6584 p_result == FUNCDETAIL_WINDOWFUNC) &&
6588 nspname = get_namespace_name(procform->pronamespace);
6590 result = quote_qualified_identifier(nspname, proname);
6592 /* Check variadic-ness if caller cares */
6595 /* "any" variadics are not treated as variadics for listing */
6596 if (OidIsValid(procform->provariadic) &&
6597 procform->provariadic != ANYOID)
6598 *is_variadic = true;
6600 *is_variadic = false;
6603 ReleaseSysCache(proctup);
6609 * generate_operator_name
6610 * Compute the name to display for an operator specified by OID,
6611 * given that it is being called with the specified actual arg types.
6612 * (Arg types matter because of ambiguous-operator resolution rules.
6613 * Pass InvalidOid for unused arg of a unary operator.)
6615 * The result includes all necessary quoting and schema-prefixing,
6616 * plus the OPERATOR() decoration needed to use a qualified operator name
6620 generate_operator_name(Oid operid, Oid arg1, Oid arg2)
6624 Form_pg_operator operform;
6629 initStringInfo(&buf);
6631 opertup = SearchSysCache(OPEROID,
6632 ObjectIdGetDatum(operid),
6634 if (!HeapTupleIsValid(opertup))
6635 elog(ERROR, "cache lookup failed for operator %u", operid);
6636 operform = (Form_pg_operator) GETSTRUCT(opertup);
6637 oprname = NameStr(operform->oprname);
6640 * The idea here is to schema-qualify only if the parser would fail to
6641 * resolve the correct operator given the unqualified op name with the
6642 * specified argtypes.
6644 switch (operform->oprkind)
6647 p_result = oper(NULL, list_make1(makeString(oprname)), arg1, arg2,
6651 p_result = left_oper(NULL, list_make1(makeString(oprname)), arg2,
6655 p_result = right_oper(NULL, list_make1(makeString(oprname)), arg1,
6659 elog(ERROR, "unrecognized oprkind: %d", operform->oprkind);
6660 p_result = NULL; /* keep compiler quiet */
6664 if (p_result != NULL && oprid(p_result) == operid)
6668 nspname = get_namespace_name(operform->oprnamespace);
6669 appendStringInfo(&buf, "OPERATOR(%s.", quote_identifier(nspname));
6672 appendStringInfoString(&buf, oprname);
6675 appendStringInfoChar(&buf, ')');
6677 if (p_result != NULL)
6678 ReleaseSysCache(p_result);
6680 ReleaseSysCache(opertup);
6686 * Given a C string, produce a TEXT datum.
6688 * We assume that the input was palloc'd and may be freed.
6691 string_to_text(char *str)
6695 result = cstring_to_text(str);
6701 * Generate a C string representing a relation's reloptions, or NULL if none.
6704 flatten_reloptions(Oid relid)
6706 char *result = NULL;
6711 tuple = SearchSysCache(RELOID,
6712 ObjectIdGetDatum(relid),
6714 if (!HeapTupleIsValid(tuple))
6715 elog(ERROR, "cache lookup failed for relation %u", relid);
6717 reloptions = SysCacheGetAttr(RELOID, tuple,
6718 Anum_pg_class_reloptions, &isnull);
6725 * We want to use array_to_text(reloptions, ', ') --- but
6726 * DirectFunctionCall2(array_to_text) does not work, because
6727 * array_to_text() relies on flinfo to be valid. So use
6730 sep = CStringGetTextDatum(", ");
6731 txt = OidFunctionCall2(F_ARRAY_TO_TEXT, reloptions, sep);
6732 result = TextDatumGetCString(txt);
6735 ReleaseSysCache(tuple);