1 /*-------------------------------------------------------------------------
4 * Functions to convert stored expressions/querytrees back to
7 * Portions Copyright (c) 1996-2008, 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.271 2008/03/26 21:10:39 alvherre Exp $
14 *-------------------------------------------------------------------------
21 #include "access/genam.h"
22 #include "catalog/dependency.h"
23 #include "catalog/indexing.h"
24 #include "catalog/pg_authid.h"
25 #include "catalog/pg_constraint.h"
26 #include "catalog/pg_depend.h"
27 #include "catalog/pg_opclass.h"
28 #include "catalog/pg_operator.h"
29 #include "catalog/pg_trigger.h"
30 #include "commands/defrem.h"
31 #include "commands/tablespace.h"
32 #include "executor/spi.h"
34 #include "nodes/makefuncs.h"
35 #include "optimizer/clauses.h"
36 #include "optimizer/tlist.h"
37 #include "parser/gramparse.h"
38 #include "parser/keywords.h"
39 #include "parser/parse_expr.h"
40 #include "parser/parse_func.h"
41 #include "parser/parse_oper.h"
42 #include "parser/parsetree.h"
43 #include "rewrite/rewriteHandler.h"
44 #include "rewrite/rewriteManip.h"
45 #include "rewrite/rewriteSupport.h"
46 #include "utils/fmgroids.h"
47 #include "utils/lsyscache.h"
48 #include "utils/tqual.h"
49 #include "utils/typcache.h"
50 #include "utils/xml.h"
54 * Pretty formatting constants
59 #define PRETTYINDENT_STD 8
60 #define PRETTYINDENT_JOIN 13
61 #define PRETTYINDENT_JOIN_ON (PRETTYINDENT_JOIN-PRETTYINDENT_STD)
62 #define PRETTYINDENT_VAR 4
65 #define PRETTYFLAG_PAREN 1
66 #define PRETTYFLAG_INDENT 2
68 /* macro to test if pretty action needed */
69 #define PRETTY_PAREN(context) ((context)->prettyFlags & PRETTYFLAG_PAREN)
70 #define PRETTY_INDENT(context) ((context)->prettyFlags & PRETTYFLAG_INDENT)
78 /* Context info needed for invoking a recursive querytree display routine */
81 StringInfo buf; /* output buffer to append to */
82 List *namespaces; /* List of deparse_namespace nodes */
83 int prettyFlags; /* enabling of pretty-print functions */
84 int indentLevel; /* current indent level for prettyprint */
85 bool varprefix; /* TRUE to print prefixes on Vars */
89 * Each level of query context around a subtree needs a level of Var namespace.
90 * A Var having varlevelsup=N refers to the N'th item (counting from 0) in
91 * the current context's namespaces list.
93 * The rangetable is the list of actual RTEs from the query tree.
95 * For deparsing plan trees, we provide for outer and inner subplan nodes.
96 * The tlists of these nodes are used to resolve OUTER and INNER varnos.
100 List *rtable; /* List of RangeTblEntry nodes */
101 Plan *outer_plan; /* OUTER subplan, or NULL if none */
102 Plan *inner_plan; /* INNER subplan, or NULL if none */
110 static SPIPlanPtr plan_getrulebyoid = NULL;
111 static const char *query_getrulebyoid = "SELECT * FROM pg_catalog.pg_rewrite WHERE oid = $1";
112 static SPIPlanPtr plan_getviewrule = NULL;
113 static const char *query_getviewrule = "SELECT * FROM pg_catalog.pg_rewrite WHERE ev_class = $1 AND rulename = $2";
119 * Most of these functions used to use fixed-size buffers to build their
120 * results. Now, they take an (already initialized) StringInfo object
121 * as a parameter, and append their text output to its contents.
124 static char *deparse_expression_pretty(Node *expr, List *dpcontext,
125 bool forceprefix, bool showimplicit,
126 int prettyFlags, int startIndent);
127 static char *pg_get_viewdef_worker(Oid viewoid, int prettyFlags);
128 static void decompile_column_index_array(Datum column_index_array, Oid relId,
130 static char *pg_get_ruledef_worker(Oid ruleoid, int prettyFlags);
131 static char *pg_get_indexdef_worker(Oid indexrelid, int colno, bool showTblSpc,
133 static char *pg_get_constraintdef_worker(Oid constraintId, bool fullCommand,
135 static char *pg_get_expr_worker(text *expr, Oid relid, char *relname,
137 static void make_ruledef(StringInfo buf, HeapTuple ruletup, TupleDesc rulettc,
139 static void make_viewdef(StringInfo buf, HeapTuple ruletup, TupleDesc rulettc,
141 static void get_query_def(Query *query, StringInfo buf, List *parentnamespace,
142 TupleDesc resultDesc, int prettyFlags, int startIndent);
143 static void get_values_def(List *values_lists, deparse_context *context);
144 static void get_select_query_def(Query *query, deparse_context *context,
145 TupleDesc resultDesc);
146 static void get_insert_query_def(Query *query, deparse_context *context);
147 static void get_update_query_def(Query *query, deparse_context *context);
148 static void get_delete_query_def(Query *query, deparse_context *context);
149 static void get_utility_query_def(Query *query, deparse_context *context);
150 static void get_basic_select_query(Query *query, deparse_context *context,
151 TupleDesc resultDesc);
152 static void get_target_list(List *targetList, deparse_context *context,
153 TupleDesc resultDesc);
154 static void get_setop_query(Node *setOp, Query *query,
155 deparse_context *context,
156 TupleDesc resultDesc);
157 static Node *get_rule_sortgroupclause(SortClause *srt, List *tlist,
159 deparse_context *context);
160 static char *get_variable(Var *var, int levelsup, bool showstar,
161 deparse_context *context);
162 static RangeTblEntry *find_rte_by_refname(const char *refname,
163 deparse_context *context);
164 static const char *get_simple_binary_op_name(OpExpr *expr);
165 static bool isSimpleNode(Node *node, Node *parentNode, int prettyFlags);
166 static void appendStringInfoSpaces(StringInfo buf, int count);
167 static void appendContextKeyword(deparse_context *context, const char *str,
168 int indentBefore, int indentAfter, int indentPlus);
169 static void get_rule_expr(Node *node, deparse_context *context,
171 static void get_oper_expr(OpExpr *expr, deparse_context *context);
172 static void get_func_expr(FuncExpr *expr, deparse_context *context,
174 static void get_agg_expr(Aggref *aggref, deparse_context *context);
175 static void get_coercion_expr(Node *arg, deparse_context *context,
176 Oid resulttype, int32 resulttypmod,
178 static void get_const_expr(Const *constval, deparse_context *context,
180 static void get_sublink_expr(SubLink *sublink, deparse_context *context);
181 static void get_from_clause(Query *query, const char *prefix,
182 deparse_context *context);
183 static void get_from_clause_item(Node *jtnode, Query *query,
184 deparse_context *context);
185 static void get_from_clause_alias(Alias *alias, RangeTblEntry *rte,
186 deparse_context *context);
187 static void get_from_clause_coldeflist(List *names, List *types, List *typmods,
188 deparse_context *context);
189 static void get_opclass_name(Oid opclass, Oid actual_datatype,
191 static Node *processIndirection(Node *node, deparse_context *context,
193 static void printSubscripts(ArrayRef *aref, deparse_context *context);
194 static char *generate_relation_name(Oid relid);
195 static char *generate_function_name(Oid funcid, int nargs, Oid *argtypes);
196 static char *generate_operator_name(Oid operid, Oid arg1, Oid arg2);
197 static text *string_to_text(char *str);
198 static char *flatten_reloptions(Oid relid);
200 #define only_marker(rte) ((rte)->inh ? "" : "ONLY ")
204 * get_ruledef - Do it all and return a text
205 * that could be used as a statement
206 * to recreate the rule
210 pg_get_ruledef(PG_FUNCTION_ARGS)
212 Oid ruleoid = PG_GETARG_OID(0);
214 PG_RETURN_TEXT_P(string_to_text(pg_get_ruledef_worker(ruleoid, 0)));
219 pg_get_ruledef_ext(PG_FUNCTION_ARGS)
221 Oid ruleoid = PG_GETARG_OID(0);
222 bool pretty = PG_GETARG_BOOL(1);
225 prettyFlags = pretty ? PRETTYFLAG_PAREN | PRETTYFLAG_INDENT : 0;
226 PG_RETURN_TEXT_P(string_to_text(pg_get_ruledef_worker(ruleoid, prettyFlags)));
231 pg_get_ruledef_worker(Oid ruleoid, int prettyFlags)
241 * Do this first so that string is alloc'd in outer context not SPI's.
243 initStringInfo(&buf);
246 * Connect to SPI manager
248 if (SPI_connect() != SPI_OK_CONNECT)
249 elog(ERROR, "SPI_connect failed");
252 * On the first call prepare the plan to lookup pg_rewrite. We read
253 * pg_rewrite over the SPI manager instead of using the syscache to be
254 * checked for read access on pg_rewrite.
256 if (plan_getrulebyoid == NULL)
261 argtypes[0] = OIDOID;
262 plan = SPI_prepare(query_getrulebyoid, 1, argtypes);
264 elog(ERROR, "SPI_prepare failed for \"%s\"", query_getrulebyoid);
265 plan_getrulebyoid = SPI_saveplan(plan);
269 * Get the pg_rewrite tuple for this rule
271 args[0] = ObjectIdGetDatum(ruleoid);
273 spirc = SPI_execute_plan(plan_getrulebyoid, args, nulls, true, 1);
274 if (spirc != SPI_OK_SELECT)
275 elog(ERROR, "failed to get pg_rewrite tuple for rule %u", ruleoid);
276 if (SPI_processed != 1)
277 appendStringInfo(&buf, "-");
281 * Get the rule's definition and put it into executor's memory
283 ruletup = SPI_tuptable->vals[0];
284 rulettc = SPI_tuptable->tupdesc;
285 make_ruledef(&buf, ruletup, rulettc, prettyFlags);
289 * Disconnect from SPI manager
291 if (SPI_finish() != SPI_OK_FINISH)
292 elog(ERROR, "SPI_finish failed");
299 * get_viewdef - Mainly the same thing, but we
300 * only return the SELECT part of a view
304 pg_get_viewdef(PG_FUNCTION_ARGS)
307 Oid viewoid = PG_GETARG_OID(0);
309 PG_RETURN_TEXT_P(string_to_text(pg_get_viewdef_worker(viewoid, 0)));
314 pg_get_viewdef_ext(PG_FUNCTION_ARGS)
317 Oid viewoid = PG_GETARG_OID(0);
318 bool pretty = PG_GETARG_BOOL(1);
321 prettyFlags = pretty ? PRETTYFLAG_PAREN | PRETTYFLAG_INDENT : 0;
322 PG_RETURN_TEXT_P(string_to_text(pg_get_viewdef_worker(viewoid, prettyFlags)));
326 pg_get_viewdef_name(PG_FUNCTION_ARGS)
328 /* By qualified name */
329 text *viewname = PG_GETARG_TEXT_P(0);
333 viewrel = makeRangeVarFromNameList(textToQualifiedNameList(viewname));
334 viewoid = RangeVarGetRelid(viewrel, false);
336 PG_RETURN_TEXT_P(string_to_text(pg_get_viewdef_worker(viewoid, 0)));
341 pg_get_viewdef_name_ext(PG_FUNCTION_ARGS)
343 /* By qualified name */
344 text *viewname = PG_GETARG_TEXT_P(0);
345 bool pretty = PG_GETARG_BOOL(1);
350 prettyFlags = pretty ? PRETTYFLAG_PAREN | PRETTYFLAG_INDENT : 0;
351 viewrel = makeRangeVarFromNameList(textToQualifiedNameList(viewname));
352 viewoid = RangeVarGetRelid(viewrel, false);
354 PG_RETURN_TEXT_P(string_to_text(pg_get_viewdef_worker(viewoid, prettyFlags)));
358 * Common code for by-OID and by-name variants of pg_get_viewdef
361 pg_get_viewdef_worker(Oid viewoid, int prettyFlags)
371 * Do this first so that string is alloc'd in outer context not SPI's.
373 initStringInfo(&buf);
376 * Connect to SPI manager
378 if (SPI_connect() != SPI_OK_CONNECT)
379 elog(ERROR, "SPI_connect failed");
382 * On the first call prepare the plan to lookup pg_rewrite. We read
383 * pg_rewrite over the SPI manager instead of using the syscache to be
384 * checked for read access on pg_rewrite.
386 if (plan_getviewrule == NULL)
391 argtypes[0] = OIDOID;
392 argtypes[1] = NAMEOID;
393 plan = SPI_prepare(query_getviewrule, 2, argtypes);
395 elog(ERROR, "SPI_prepare failed for \"%s\"", query_getviewrule);
396 plan_getviewrule = SPI_saveplan(plan);
400 * Get the pg_rewrite tuple for the view's SELECT rule
402 args[0] = ObjectIdGetDatum(viewoid);
403 args[1] = PointerGetDatum(ViewSelectRuleName);
406 spirc = SPI_execute_plan(plan_getviewrule, args, nulls, true, 2);
407 if (spirc != SPI_OK_SELECT)
408 elog(ERROR, "failed to get pg_rewrite tuple for view %u", viewoid);
409 if (SPI_processed != 1)
410 appendStringInfo(&buf, "Not a view");
414 * Get the rule's definition and put it into executor's memory
416 ruletup = SPI_tuptable->vals[0];
417 rulettc = SPI_tuptable->tupdesc;
418 make_viewdef(&buf, ruletup, rulettc, prettyFlags);
422 * Disconnect from SPI manager
424 if (SPI_finish() != SPI_OK_FINISH)
425 elog(ERROR, "SPI_finish failed");
431 * get_triggerdef - Get the definition of a trigger
435 pg_get_triggerdef(PG_FUNCTION_ARGS)
437 Oid trigid = PG_GETARG_OID(0);
439 Form_pg_trigger trigrec;
448 * Fetch the pg_trigger tuple by the Oid of the trigger
450 tgrel = heap_open(TriggerRelationId, AccessShareLock);
452 ScanKeyInit(&skey[0],
453 ObjectIdAttributeNumber,
454 BTEqualStrategyNumber, F_OIDEQ,
455 ObjectIdGetDatum(trigid));
457 tgscan = systable_beginscan(tgrel, TriggerOidIndexId, true,
458 SnapshotNow, 1, skey);
460 ht_trig = systable_getnext(tgscan);
462 if (!HeapTupleIsValid(ht_trig))
463 elog(ERROR, "could not find tuple for trigger %u", trigid);
465 trigrec = (Form_pg_trigger) GETSTRUCT(ht_trig);
468 * Start the trigger definition. Note that the trigger's name should never
469 * be schema-qualified, but the trigger rel's name may be.
471 initStringInfo(&buf);
473 tgname = NameStr(trigrec->tgname);
474 appendStringInfo(&buf, "CREATE %sTRIGGER %s ",
475 trigrec->tgisconstraint ? "CONSTRAINT " : "",
476 quote_identifier(tgname));
478 if (TRIGGER_FOR_BEFORE(trigrec->tgtype))
479 appendStringInfo(&buf, "BEFORE");
481 appendStringInfo(&buf, "AFTER");
482 if (TRIGGER_FOR_INSERT(trigrec->tgtype))
484 appendStringInfo(&buf, " INSERT");
487 if (TRIGGER_FOR_DELETE(trigrec->tgtype))
490 appendStringInfo(&buf, " OR DELETE");
492 appendStringInfo(&buf, " DELETE");
495 if (TRIGGER_FOR_UPDATE(trigrec->tgtype))
498 appendStringInfo(&buf, " OR UPDATE");
500 appendStringInfo(&buf, " UPDATE");
502 appendStringInfo(&buf, " ON %s ",
503 generate_relation_name(trigrec->tgrelid));
505 if (trigrec->tgisconstraint)
507 if (trigrec->tgconstrrelid != InvalidOid)
508 appendStringInfo(&buf, "FROM %s ",
509 generate_relation_name(trigrec->tgconstrrelid));
510 if (!trigrec->tgdeferrable)
511 appendStringInfo(&buf, "NOT ");
512 appendStringInfo(&buf, "DEFERRABLE INITIALLY ");
513 if (trigrec->tginitdeferred)
514 appendStringInfo(&buf, "DEFERRED ");
516 appendStringInfo(&buf, "IMMEDIATE ");
520 if (TRIGGER_FOR_ROW(trigrec->tgtype))
521 appendStringInfo(&buf, "FOR EACH ROW ");
523 appendStringInfo(&buf, "FOR EACH STATEMENT ");
525 appendStringInfo(&buf, "EXECUTE PROCEDURE %s(",
526 generate_function_name(trigrec->tgfoid, 0, NULL));
528 if (trigrec->tgnargs > 0)
535 val = DatumGetByteaP(fastgetattr(ht_trig,
536 Anum_pg_trigger_tgargs,
537 tgrel->rd_att, &isnull));
539 elog(ERROR, "tgargs is null for trigger %u", trigid);
540 p = (char *) VARDATA(val);
541 for (i = 0; i < trigrec->tgnargs; i++)
544 appendStringInfo(&buf, ", ");
547 * We form the string literal according to the prevailing setting
548 * of standard_conforming_strings; we never use E''. User is
549 * responsible for making sure result is used correctly.
551 appendStringInfoChar(&buf, '\'');
556 if (SQL_STR_DOUBLE(ch, !standard_conforming_strings))
557 appendStringInfoChar(&buf, ch);
558 appendStringInfoChar(&buf, ch);
560 appendStringInfoChar(&buf, '\'');
561 /* advance p to next string embedded in tgargs */
566 /* We deliberately do not put semi-colon at end */
567 appendStringInfo(&buf, ")");
570 systable_endscan(tgscan);
572 heap_close(tgrel, AccessShareLock);
574 PG_RETURN_TEXT_P(string_to_text(buf.data));
578 * get_indexdef - Get the definition of an index
580 * In the extended version, there is a colno argument as well as pretty bool.
581 * if colno == 0, we want a complete index definition.
582 * if colno > 0, we only want the Nth index key's variable or expression.
584 * Note that the SQL-function versions of this omit any info about the
585 * index tablespace; this is intentional because pg_dump wants it that way.
586 * However pg_get_indexdef_string() includes index tablespace if not default.
590 pg_get_indexdef(PG_FUNCTION_ARGS)
592 Oid indexrelid = PG_GETARG_OID(0);
594 PG_RETURN_TEXT_P(string_to_text(pg_get_indexdef_worker(indexrelid, 0,
599 pg_get_indexdef_ext(PG_FUNCTION_ARGS)
601 Oid indexrelid = PG_GETARG_OID(0);
602 int32 colno = PG_GETARG_INT32(1);
603 bool pretty = PG_GETARG_BOOL(2);
606 prettyFlags = pretty ? PRETTYFLAG_PAREN | PRETTYFLAG_INDENT : 0;
607 PG_RETURN_TEXT_P(string_to_text(pg_get_indexdef_worker(indexrelid, colno,
608 false, prettyFlags)));
611 /* Internal version that returns a palloc'd C string */
613 pg_get_indexdef_string(Oid indexrelid)
615 return pg_get_indexdef_worker(indexrelid, 0, true, 0);
619 pg_get_indexdef_worker(Oid indexrelid, int colno, bool showTblSpc,
625 Form_pg_index idxrec;
626 Form_pg_class idxrelrec;
629 ListCell *indexpr_item;
635 Datum indoptionDatum;
638 int2vector *indoption;
644 * Fetch the pg_index tuple by the Oid of the index
646 ht_idx = SearchSysCache(INDEXRELID,
647 ObjectIdGetDatum(indexrelid),
649 if (!HeapTupleIsValid(ht_idx))
650 elog(ERROR, "cache lookup failed for index %u", indexrelid);
651 idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
653 indrelid = idxrec->indrelid;
654 Assert(indexrelid == idxrec->indexrelid);
656 /* Must get indclass and indoption the hard way */
657 indclassDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
658 Anum_pg_index_indclass, &isnull);
660 indclass = (oidvector *) DatumGetPointer(indclassDatum);
661 indoptionDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
662 Anum_pg_index_indoption, &isnull);
664 indoption = (int2vector *) DatumGetPointer(indoptionDatum);
667 * Fetch the pg_class tuple of the index relation
669 ht_idxrel = SearchSysCache(RELOID,
670 ObjectIdGetDatum(indexrelid),
672 if (!HeapTupleIsValid(ht_idxrel))
673 elog(ERROR, "cache lookup failed for relation %u", indexrelid);
674 idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
677 * Fetch the pg_am tuple of the index' access method
679 ht_am = SearchSysCache(AMOID,
680 ObjectIdGetDatum(idxrelrec->relam),
682 if (!HeapTupleIsValid(ht_am))
683 elog(ERROR, "cache lookup failed for access method %u",
685 amrec = (Form_pg_am) GETSTRUCT(ht_am);
688 * Get the index expressions, if any. (NOTE: we do not use the relcache
689 * versions of the expressions and predicate, because we want to display
690 * non-const-folded expressions.)
692 if (!heap_attisnull(ht_idx, Anum_pg_index_indexprs))
698 exprsDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
699 Anum_pg_index_indexprs, &isnull);
701 exprsString = TextDatumGetCString(exprsDatum);
702 indexprs = (List *) stringToNode(exprsString);
708 indexpr_item = list_head(indexprs);
710 context = deparse_context_for(get_rel_name(indrelid), indrelid);
713 * Start the index definition. Note that the index's name should never be
714 * schema-qualified, but the indexed rel's name may be.
716 initStringInfo(&buf);
719 appendStringInfo(&buf, "CREATE %sINDEX %s ON %s USING %s (",
720 idxrec->indisunique ? "UNIQUE " : "",
721 quote_identifier(NameStr(idxrelrec->relname)),
722 generate_relation_name(indrelid),
723 quote_identifier(NameStr(amrec->amname)));
726 * Report the indexed attributes
729 for (keyno = 0; keyno < idxrec->indnatts; keyno++)
731 AttrNumber attnum = idxrec->indkey.values[keyno];
732 int16 opt = indoption->values[keyno];
735 appendStringInfoString(&buf, sep);
740 /* Simple index column */
743 attname = get_relid_attribute_name(indrelid, attnum);
744 if (!colno || colno == keyno + 1)
745 appendStringInfoString(&buf, quote_identifier(attname));
746 keycoltype = get_atttype(indrelid, attnum);
750 /* expressional index */
753 if (indexpr_item == NULL)
754 elog(ERROR, "too few entries in indexprs list");
755 indexkey = (Node *) lfirst(indexpr_item);
756 indexpr_item = lnext(indexpr_item);
758 str = deparse_expression_pretty(indexkey, context, false, false,
760 if (!colno || colno == keyno + 1)
762 /* Need parens if it's not a bare function call */
763 if (indexkey && IsA(indexkey, FuncExpr) &&
764 ((FuncExpr *) indexkey)->funcformat == COERCE_EXPLICIT_CALL)
765 appendStringInfoString(&buf, str);
767 appendStringInfo(&buf, "(%s)", str);
769 keycoltype = exprType(indexkey);
772 /* Provide decoration only in the colno=0 case */
775 /* Add the operator class name, if not default */
776 get_opclass_name(indclass->values[keyno], keycoltype, &buf);
778 /* Add options if relevant */
779 if (amrec->amcanorder)
781 /* if it supports sort ordering, report DESC and NULLS opts */
782 if (opt & INDOPTION_DESC)
784 appendStringInfo(&buf, " DESC");
785 /* NULLS FIRST is the default in this case */
786 if (!(opt & INDOPTION_NULLS_FIRST))
787 appendStringInfo(&buf, " NULLS LAST");
791 if (opt & INDOPTION_NULLS_FIRST)
792 appendStringInfo(&buf, " NULLS FIRST");
800 appendStringInfoChar(&buf, ')');
803 * If it has options, append "WITH (options)"
805 str = flatten_reloptions(indexrelid);
808 appendStringInfo(&buf, " WITH (%s)", str);
813 * If it's in a nondefault tablespace, say so, but only if requested
819 tblspc = get_rel_tablespace(indexrelid);
820 if (OidIsValid(tblspc))
821 appendStringInfo(&buf, " TABLESPACE %s",
822 quote_identifier(get_tablespace_name(tblspc)));
826 * If it's a partial index, decompile and append the predicate
828 if (!heap_attisnull(ht_idx, Anum_pg_index_indpred))
835 /* Convert text string to node tree */
836 predDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
837 Anum_pg_index_indpred, &isnull);
839 predString = TextDatumGetCString(predDatum);
840 node = (Node *) stringToNode(predString);
844 str = deparse_expression_pretty(node, context, false, false,
846 appendStringInfo(&buf, " WHERE %s", str);
851 ReleaseSysCache(ht_idx);
852 ReleaseSysCache(ht_idxrel);
853 ReleaseSysCache(ht_am);
860 * pg_get_constraintdef
862 * Returns the definition for the constraint, ie, everything that needs to
863 * appear after "ALTER TABLE ... ADD CONSTRAINT <constraintname>".
866 pg_get_constraintdef(PG_FUNCTION_ARGS)
868 Oid constraintId = PG_GETARG_OID(0);
870 PG_RETURN_TEXT_P(string_to_text(pg_get_constraintdef_worker(constraintId,
875 pg_get_constraintdef_ext(PG_FUNCTION_ARGS)
877 Oid constraintId = PG_GETARG_OID(0);
878 bool pretty = PG_GETARG_BOOL(1);
881 prettyFlags = pretty ? PRETTYFLAG_PAREN | PRETTYFLAG_INDENT : 0;
882 PG_RETURN_TEXT_P(string_to_text(pg_get_constraintdef_worker(constraintId,
883 false, prettyFlags)));
886 /* Internal version that returns a palloc'd C string */
888 pg_get_constraintdef_string(Oid constraintId)
890 return pg_get_constraintdef_worker(constraintId, true, 0);
894 pg_get_constraintdef_worker(Oid constraintId, bool fullCommand,
898 Form_pg_constraint conForm;
901 tup = SearchSysCache(CONSTROID,
902 ObjectIdGetDatum(constraintId),
904 if (!HeapTupleIsValid(tup)) /* should not happen */
905 elog(ERROR, "cache lookup failed for constraint %u", constraintId);
906 conForm = (Form_pg_constraint) GETSTRUCT(tup);
908 initStringInfo(&buf);
910 if (fullCommand && OidIsValid(conForm->conrelid))
912 appendStringInfo(&buf, "ALTER TABLE ONLY %s ADD CONSTRAINT %s ",
913 generate_relation_name(conForm->conrelid),
914 quote_identifier(NameStr(conForm->conname)));
917 switch (conForm->contype)
919 case CONSTRAINT_FOREIGN:
925 /* Start off the constraint definition */
926 appendStringInfo(&buf, "FOREIGN KEY (");
928 /* Fetch and build referencing-column list */
929 val = SysCacheGetAttr(CONSTROID, tup,
930 Anum_pg_constraint_conkey, &isnull);
932 elog(ERROR, "null conkey for constraint %u",
935 decompile_column_index_array(val, conForm->conrelid, &buf);
937 /* add foreign relation name */
938 appendStringInfo(&buf, ") REFERENCES %s(",
939 generate_relation_name(conForm->confrelid));
941 /* Fetch and build referenced-column list */
942 val = SysCacheGetAttr(CONSTROID, tup,
943 Anum_pg_constraint_confkey, &isnull);
945 elog(ERROR, "null confkey for constraint %u",
948 decompile_column_index_array(val, conForm->confrelid, &buf);
950 appendStringInfo(&buf, ")");
953 switch (conForm->confmatchtype)
955 case FKCONSTR_MATCH_FULL:
956 string = " MATCH FULL";
958 case FKCONSTR_MATCH_PARTIAL:
959 string = " MATCH PARTIAL";
961 case FKCONSTR_MATCH_UNSPECIFIED:
965 elog(ERROR, "unrecognized confmatchtype: %d",
966 conForm->confmatchtype);
967 string = ""; /* keep compiler quiet */
970 appendStringInfoString(&buf, string);
972 /* Add ON UPDATE and ON DELETE clauses, if needed */
973 switch (conForm->confupdtype)
975 case FKCONSTR_ACTION_NOACTION:
976 string = NULL; /* suppress default */
978 case FKCONSTR_ACTION_RESTRICT:
981 case FKCONSTR_ACTION_CASCADE:
984 case FKCONSTR_ACTION_SETNULL:
987 case FKCONSTR_ACTION_SETDEFAULT:
988 string = "SET DEFAULT";
991 elog(ERROR, "unrecognized confupdtype: %d",
992 conForm->confupdtype);
993 string = NULL; /* keep compiler quiet */
997 appendStringInfo(&buf, " ON UPDATE %s", string);
999 switch (conForm->confdeltype)
1001 case FKCONSTR_ACTION_NOACTION:
1002 string = NULL; /* suppress default */
1004 case FKCONSTR_ACTION_RESTRICT:
1005 string = "RESTRICT";
1007 case FKCONSTR_ACTION_CASCADE:
1010 case FKCONSTR_ACTION_SETNULL:
1011 string = "SET NULL";
1013 case FKCONSTR_ACTION_SETDEFAULT:
1014 string = "SET DEFAULT";
1017 elog(ERROR, "unrecognized confdeltype: %d",
1018 conForm->confdeltype);
1019 string = NULL; /* keep compiler quiet */
1023 appendStringInfo(&buf, " ON DELETE %s", string);
1025 if (conForm->condeferrable)
1026 appendStringInfo(&buf, " DEFERRABLE");
1027 if (conForm->condeferred)
1028 appendStringInfo(&buf, " INITIALLY DEFERRED");
1032 case CONSTRAINT_PRIMARY:
1033 case CONSTRAINT_UNIQUE:
1039 /* Start off the constraint definition */
1040 if (conForm->contype == CONSTRAINT_PRIMARY)
1041 appendStringInfo(&buf, "PRIMARY KEY (");
1043 appendStringInfo(&buf, "UNIQUE (");
1045 /* Fetch and build target column list */
1046 val = SysCacheGetAttr(CONSTROID, tup,
1047 Anum_pg_constraint_conkey, &isnull);
1049 elog(ERROR, "null conkey for constraint %u",
1052 decompile_column_index_array(val, conForm->conrelid, &buf);
1054 appendStringInfo(&buf, ")");
1056 indexId = get_constraint_index(constraintId);
1058 /* XXX why do we only print these bits if fullCommand? */
1059 if (fullCommand && OidIsValid(indexId))
1061 char *options = flatten_reloptions(indexId);
1066 appendStringInfo(&buf, " WITH (%s)", options);
1070 tblspc = get_rel_tablespace(indexId);
1071 if (OidIsValid(tblspc))
1072 appendStringInfo(&buf, " USING INDEX TABLESPACE %s",
1073 quote_identifier(get_tablespace_name(tblspc)));
1078 case CONSTRAINT_CHECK:
1087 /* Fetch constraint expression in parsetree form */
1088 val = SysCacheGetAttr(CONSTROID, tup,
1089 Anum_pg_constraint_conbin, &isnull);
1091 elog(ERROR, "null conbin for constraint %u",
1094 conbin = TextDatumGetCString(val);
1095 expr = stringToNode(conbin);
1097 /* Set up deparsing context for Var nodes in constraint */
1098 if (conForm->conrelid != InvalidOid)
1100 /* relation constraint */
1101 context = deparse_context_for(get_rel_name(conForm->conrelid),
1106 /* domain constraint --- can't have Vars */
1110 consrc = deparse_expression_pretty(expr, context, false, false,
1114 * Now emit the constraint definition. There are cases where
1115 * the constraint expression will be fully parenthesized and
1116 * we don't need the outer parens ... but there are other
1117 * cases where we do need 'em. Be conservative for now.
1119 * Note that simply checking for leading '(' and trailing ')'
1120 * would NOT be good enough, consider "(x > 0) AND (y > 0)".
1122 appendStringInfo(&buf, "CHECK (%s)", consrc);
1127 elog(ERROR, "invalid constraint type \"%c\"", conForm->contype);
1132 ReleaseSysCache(tup);
1139 * Convert an int16[] Datum into a comma-separated list of column names
1140 * for the indicated relation; append the list to buf.
1143 decompile_column_index_array(Datum column_index_array, Oid relId,
1150 /* Extract data from array of int16 */
1151 deconstruct_array(DatumGetArrayTypeP(column_index_array),
1152 INT2OID, 2, true, 's',
1153 &keys, NULL, &nKeys);
1155 for (j = 0; j < nKeys; j++)
1159 colName = get_relid_attribute_name(relId, DatumGetInt16(keys[j]));
1162 appendStringInfoString(buf, quote_identifier(colName));
1164 appendStringInfo(buf, ", %s", quote_identifier(colName));
1170 * get_expr - Decompile an expression tree
1172 * Input: an expression tree in nodeToString form, and a relation OID
1174 * Output: reverse-listed expression
1176 * Currently, the expression can only refer to a single relation, namely
1177 * the one specified by the second parameter. This is sufficient for
1178 * partial indexes, column default expressions, etc.
1182 pg_get_expr(PG_FUNCTION_ARGS)
1184 text *expr = PG_GETARG_TEXT_P(0);
1185 Oid relid = PG_GETARG_OID(1);
1188 /* Get the name for the relation */
1189 relname = get_rel_name(relid);
1190 if (relname == NULL)
1191 PG_RETURN_NULL(); /* should we raise an error? */
1193 PG_RETURN_TEXT_P(string_to_text(pg_get_expr_worker(expr, relid, relname, 0)));
1197 pg_get_expr_ext(PG_FUNCTION_ARGS)
1199 text *expr = PG_GETARG_TEXT_P(0);
1200 Oid relid = PG_GETARG_OID(1);
1201 bool pretty = PG_GETARG_BOOL(2);
1205 prettyFlags = pretty ? PRETTYFLAG_PAREN | PRETTYFLAG_INDENT : 0;
1207 /* Get the name for the relation */
1208 relname = get_rel_name(relid);
1209 if (relname == NULL)
1210 PG_RETURN_NULL(); /* should we raise an error? */
1212 PG_RETURN_TEXT_P(string_to_text(pg_get_expr_worker(expr, relid, relname, prettyFlags)));
1216 pg_get_expr_worker(text *expr, Oid relid, char *relname, int prettyFlags)
1223 /* Convert input TEXT object to C string */
1224 exprstr = text_to_cstring(expr);
1226 /* Convert expression to node tree */
1227 node = (Node *) stringToNode(exprstr);
1230 context = deparse_context_for(relname, relid);
1231 str = deparse_expression_pretty(node, context, false, false,
1241 * get_userbyid - Get a user name by roleid and
1242 * fallback to 'unknown (OID=n)'
1246 pg_get_userbyid(PG_FUNCTION_ARGS)
1248 Oid roleid = PG_GETARG_OID(0);
1251 Form_pg_authid role_rec;
1254 * Allocate space for the result
1256 result = (Name) palloc(NAMEDATALEN);
1257 memset(NameStr(*result), 0, NAMEDATALEN);
1260 * Get the pg_authid entry and print the result
1262 roletup = SearchSysCache(AUTHOID,
1263 ObjectIdGetDatum(roleid),
1265 if (HeapTupleIsValid(roletup))
1267 role_rec = (Form_pg_authid) GETSTRUCT(roletup);
1268 StrNCpy(NameStr(*result), NameStr(role_rec->rolname), NAMEDATALEN);
1269 ReleaseSysCache(roletup);
1272 sprintf(NameStr(*result), "unknown (OID=%u)", roleid);
1274 PG_RETURN_NAME(result);
1279 * pg_get_serial_sequence
1280 * Get the name of the sequence used by a serial column,
1281 * formatted suitably for passing to setval, nextval or currval.
1282 * First parameter is not treated as double-quoted, second parameter
1283 * is --- see documentation for reason.
1286 pg_get_serial_sequence(PG_FUNCTION_ARGS)
1288 text *tablename = PG_GETARG_TEXT_P(0);
1289 text *columnname = PG_GETARG_TEXT_PP(1);
1294 Oid sequenceId = InvalidOid;
1300 /* Get the OID of the table */
1301 tablerv = makeRangeVarFromNameList(textToQualifiedNameList(tablename));
1302 tableOid = RangeVarGetRelid(tablerv, false);
1304 /* Get the number of the column */
1305 column = text_to_cstring(columnname);
1307 attnum = get_attnum(tableOid, column);
1308 if (attnum == InvalidAttrNumber)
1310 (errcode(ERRCODE_UNDEFINED_COLUMN),
1311 errmsg("column \"%s\" of relation \"%s\" does not exist",
1312 column, tablerv->relname)));
1314 /* Search the dependency table for the dependent sequence */
1315 depRel = heap_open(DependRelationId, AccessShareLock);
1317 ScanKeyInit(&key[0],
1318 Anum_pg_depend_refclassid,
1319 BTEqualStrategyNumber, F_OIDEQ,
1320 ObjectIdGetDatum(RelationRelationId));
1321 ScanKeyInit(&key[1],
1322 Anum_pg_depend_refobjid,
1323 BTEqualStrategyNumber, F_OIDEQ,
1324 ObjectIdGetDatum(tableOid));
1325 ScanKeyInit(&key[2],
1326 Anum_pg_depend_refobjsubid,
1327 BTEqualStrategyNumber, F_INT4EQ,
1328 Int32GetDatum(attnum));
1330 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
1331 SnapshotNow, 3, key);
1333 while (HeapTupleIsValid(tup = systable_getnext(scan)))
1335 Form_pg_depend deprec = (Form_pg_depend) GETSTRUCT(tup);
1338 * We assume any auto dependency of a sequence on a column must be
1339 * what we are looking for. (We need the relkind test because indexes
1340 * can also have auto dependencies on columns.)
1342 if (deprec->classid == RelationRelationId &&
1343 deprec->objsubid == 0 &&
1344 deprec->deptype == DEPENDENCY_AUTO &&
1345 get_rel_relkind(deprec->objid) == RELKIND_SEQUENCE)
1347 sequenceId = deprec->objid;
1352 systable_endscan(scan);
1353 heap_close(depRel, AccessShareLock);
1355 if (OidIsValid(sequenceId))
1358 Form_pg_class classtuple;
1362 /* Get the sequence's pg_class entry */
1363 classtup = SearchSysCache(RELOID,
1364 ObjectIdGetDatum(sequenceId),
1366 if (!HeapTupleIsValid(classtup))
1367 elog(ERROR, "cache lookup failed for relation %u", sequenceId);
1368 classtuple = (Form_pg_class) GETSTRUCT(classtup);
1370 /* Get the namespace */
1371 nspname = get_namespace_name(classtuple->relnamespace);
1373 elog(ERROR, "cache lookup failed for namespace %u",
1374 classtuple->relnamespace);
1376 /* And construct the result string */
1377 result = quote_qualified_identifier(nspname,
1378 NameStr(classtuple->relname));
1380 ReleaseSysCache(classtup);
1382 PG_RETURN_TEXT_P(string_to_text(result));
1390 * deparse_expression - General utility for deparsing expressions
1392 * calls deparse_expression_pretty with all prettyPrinting disabled
1395 deparse_expression(Node *expr, List *dpcontext,
1396 bool forceprefix, bool showimplicit)
1398 return deparse_expression_pretty(expr, dpcontext, forceprefix,
1399 showimplicit, 0, 0);
1403 * deparse_expression_pretty - General utility for deparsing expressions
1405 * expr is the node tree to be deparsed. It must be a transformed expression
1406 * tree (ie, not the raw output of gram.y).
1408 * dpcontext is a list of deparse_namespace nodes representing the context
1409 * for interpreting Vars in the node tree.
1411 * forceprefix is TRUE to force all Vars to be prefixed with their table names.
1413 * showimplicit is TRUE to force all implicit casts to be shown explicitly.
1415 * tries to pretty up the output according to prettyFlags and startIndent.
1417 * The result is a palloc'd string.
1421 deparse_expression_pretty(Node *expr, List *dpcontext,
1422 bool forceprefix, bool showimplicit,
1423 int prettyFlags, int startIndent)
1426 deparse_context context;
1428 initStringInfo(&buf);
1430 context.namespaces = dpcontext;
1431 context.varprefix = forceprefix;
1432 context.prettyFlags = prettyFlags;
1433 context.indentLevel = startIndent;
1435 get_rule_expr(expr, &context, showimplicit);
1441 * deparse_context_for - Build deparse context for a single relation
1443 * Given the reference name (alias) and OID of a relation, build deparsing
1444 * context for an expression referencing only that relation (as varno 1,
1445 * varlevelsup 0). This is sufficient for many uses of deparse_expression.
1449 deparse_context_for(const char *aliasname, Oid relid)
1451 deparse_namespace *dpns;
1454 dpns = (deparse_namespace *) palloc(sizeof(deparse_namespace));
1456 /* Build a minimal RTE for the rel */
1457 rte = makeNode(RangeTblEntry);
1458 rte->rtekind = RTE_RELATION;
1460 rte->eref = makeAlias(aliasname, NIL);
1462 rte->inFromCl = true;
1464 /* Build one-element rtable */
1465 dpns->rtable = list_make1(rte);
1466 dpns->outer_plan = dpns->inner_plan = NULL;
1468 /* Return a one-deep namespace stack */
1469 return list_make1(dpns);
1473 * deparse_context_for_plan - Build deparse context for a plan node
1475 * When deparsing an expression in a Plan tree, we might have to resolve
1476 * OUTER or INNER references. Pass the plan nodes whose targetlists define
1477 * such references, or NULL when none are expected. (outer_plan and
1478 * inner_plan really ought to be declared as "Plan *", but we use "Node *"
1479 * to avoid having to include plannodes.h in builtins.h.)
1481 * As a special case, when deparsing a SubqueryScan plan, pass the subplan
1482 * as inner_plan (there won't be any regular innerPlan() in this case).
1484 * The plan's rangetable list must also be passed. We actually prefer to use
1485 * the rangetable to resolve simple Vars, but the subplan inputs are needed
1486 * for Vars that reference expressions computed in subplan target lists.
1489 deparse_context_for_plan(Node *outer_plan, Node *inner_plan,
1492 deparse_namespace *dpns;
1494 dpns = (deparse_namespace *) palloc(sizeof(deparse_namespace));
1496 dpns->rtable = rtable;
1497 dpns->outer_plan = (Plan *) outer_plan;
1498 dpns->inner_plan = (Plan *) inner_plan;
1500 /* Return a one-deep namespace stack */
1501 return list_make1(dpns);
1505 * make_ruledef - reconstruct the CREATE RULE command
1506 * for a given pg_rewrite tuple
1510 make_ruledef(StringInfo buf, HeapTuple ruletup, TupleDesc rulettc,
1520 List *actions = NIL;
1526 * Get the attribute values from the rules tuple
1528 fno = SPI_fnumber(rulettc, "rulename");
1529 dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
1531 rulename = NameStr(*(DatumGetName(dat)));
1533 fno = SPI_fnumber(rulettc, "ev_type");
1534 dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
1536 ev_type = DatumGetChar(dat);
1538 fno = SPI_fnumber(rulettc, "ev_class");
1539 dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
1541 ev_class = DatumGetObjectId(dat);
1543 fno = SPI_fnumber(rulettc, "ev_attr");
1544 dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
1546 ev_attr = DatumGetInt16(dat);
1548 fno = SPI_fnumber(rulettc, "is_instead");
1549 dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
1551 is_instead = DatumGetBool(dat);
1553 /* these could be nulls */
1554 fno = SPI_fnumber(rulettc, "ev_qual");
1555 ev_qual = SPI_getvalue(ruletup, rulettc, fno);
1557 fno = SPI_fnumber(rulettc, "ev_action");
1558 ev_action = SPI_getvalue(ruletup, rulettc, fno);
1559 if (ev_action != NULL)
1560 actions = (List *) stringToNode(ev_action);
1563 * Build the rules definition text
1565 appendStringInfo(buf, "CREATE RULE %s AS",
1566 quote_identifier(rulename));
1568 if (prettyFlags & PRETTYFLAG_INDENT)
1569 appendStringInfoString(buf, "\n ON ");
1571 appendStringInfoString(buf, " ON ");
1573 /* The event the rule is fired for */
1577 appendStringInfo(buf, "SELECT");
1581 appendStringInfo(buf, "UPDATE");
1585 appendStringInfo(buf, "INSERT");
1589 appendStringInfo(buf, "DELETE");
1594 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1595 errmsg("rule \"%s\" has unsupported event type %d",
1596 rulename, ev_type)));
1600 /* The relation the rule is fired on */
1601 appendStringInfo(buf, " TO %s", generate_relation_name(ev_class));
1603 appendStringInfo(buf, ".%s",
1604 quote_identifier(get_relid_attribute_name(ev_class,
1607 /* If the rule has an event qualification, add it */
1608 if (ev_qual == NULL)
1610 if (strlen(ev_qual) > 0 && strcmp(ev_qual, "<>") != 0)
1614 deparse_context context;
1615 deparse_namespace dpns;
1617 if (prettyFlags & PRETTYFLAG_INDENT)
1618 appendStringInfoString(buf, "\n ");
1619 appendStringInfo(buf, " WHERE ");
1621 qual = stringToNode(ev_qual);
1624 * We need to make a context for recognizing any Vars in the qual
1625 * (which can only be references to OLD and NEW). Use the rtable of
1626 * the first query in the action list for this purpose.
1628 query = (Query *) linitial(actions);
1631 * If the action is INSERT...SELECT, OLD/NEW have been pushed down
1632 * into the SELECT, and that's what we need to look at. (Ugly kluge
1633 * ... try to fix this when we redesign querytrees.)
1635 query = getInsertSelectQuery(query, NULL);
1637 /* Must acquire locks right away; see notes in get_query_def() */
1638 AcquireRewriteLocks(query);
1641 context.namespaces = list_make1(&dpns);
1642 context.varprefix = (list_length(query->rtable) != 1);
1643 context.prettyFlags = prettyFlags;
1644 context.indentLevel = PRETTYINDENT_STD;
1645 dpns.rtable = query->rtable;
1646 dpns.outer_plan = dpns.inner_plan = NULL;
1648 get_rule_expr(qual, &context, false);
1651 appendStringInfo(buf, " DO ");
1653 /* The INSTEAD keyword (if so) */
1655 appendStringInfo(buf, "INSTEAD ");
1657 /* Finally the rules actions */
1658 if (list_length(actions) > 1)
1663 appendStringInfo(buf, "(");
1664 foreach(action, actions)
1666 query = (Query *) lfirst(action);
1667 get_query_def(query, buf, NIL, NULL, prettyFlags, 0);
1669 appendStringInfo(buf, ";\n");
1671 appendStringInfo(buf, "; ");
1673 appendStringInfo(buf, ");");
1675 else if (list_length(actions) == 0)
1677 appendStringInfo(buf, "NOTHING;");
1683 query = (Query *) linitial(actions);
1684 get_query_def(query, buf, NIL, NULL, prettyFlags, 0);
1685 appendStringInfo(buf, ";");
1691 * make_viewdef - reconstruct the SELECT part of a
1696 make_viewdef(StringInfo buf, HeapTuple ruletup, TupleDesc rulettc,
1706 List *actions = NIL;
1707 Relation ev_relation;
1712 * Get the attribute values from the rules tuple
1714 fno = SPI_fnumber(rulettc, "ev_type");
1715 ev_type = (char) SPI_getbinval(ruletup, rulettc, fno, &isnull);
1717 fno = SPI_fnumber(rulettc, "ev_class");
1718 ev_class = (Oid) SPI_getbinval(ruletup, rulettc, fno, &isnull);
1720 fno = SPI_fnumber(rulettc, "ev_attr");
1721 ev_attr = (int2) SPI_getbinval(ruletup, rulettc, fno, &isnull);
1723 fno = SPI_fnumber(rulettc, "is_instead");
1724 is_instead = (bool) SPI_getbinval(ruletup, rulettc, fno, &isnull);
1726 fno = SPI_fnumber(rulettc, "ev_qual");
1727 ev_qual = SPI_getvalue(ruletup, rulettc, fno);
1729 fno = SPI_fnumber(rulettc, "ev_action");
1730 ev_action = SPI_getvalue(ruletup, rulettc, fno);
1731 if (ev_action != NULL)
1732 actions = (List *) stringToNode(ev_action);
1734 if (list_length(actions) != 1)
1736 appendStringInfo(buf, "Not a view");
1740 query = (Query *) linitial(actions);
1742 if (ev_type != '1' || ev_attr >= 0 || !is_instead ||
1743 strcmp(ev_qual, "<>") != 0 || query->commandType != CMD_SELECT)
1745 appendStringInfo(buf, "Not a view");
1749 ev_relation = heap_open(ev_class, AccessShareLock);
1751 get_query_def(query, buf, NIL, RelationGetDescr(ev_relation),
1753 appendStringInfo(buf, ";");
1755 heap_close(ev_relation, AccessShareLock);
1760 * get_query_def - Parse back one query parsetree
1762 * If resultDesc is not NULL, then it is the output tuple descriptor for
1763 * the view represented by a SELECT query.
1767 get_query_def(Query *query, StringInfo buf, List *parentnamespace,
1768 TupleDesc resultDesc, int prettyFlags, int startIndent)
1770 deparse_context context;
1771 deparse_namespace dpns;
1774 * Before we begin to examine the query, acquire locks on referenced
1775 * relations, and fix up deleted columns in JOIN RTEs. This ensures
1776 * consistent results. Note we assume it's OK to scribble on the passed
1779 AcquireRewriteLocks(query);
1782 context.namespaces = lcons(&dpns, list_copy(parentnamespace));
1783 context.varprefix = (parentnamespace != NIL ||
1784 list_length(query->rtable) != 1);
1785 context.prettyFlags = prettyFlags;
1786 context.indentLevel = startIndent;
1788 dpns.rtable = query->rtable;
1789 dpns.outer_plan = dpns.inner_plan = NULL;
1791 switch (query->commandType)
1794 get_select_query_def(query, &context, resultDesc);
1798 get_update_query_def(query, &context);
1802 get_insert_query_def(query, &context);
1806 get_delete_query_def(query, &context);
1810 appendStringInfo(buf, "NOTHING");
1814 get_utility_query_def(query, &context);
1818 elog(ERROR, "unrecognized query command type: %d",
1819 query->commandType);
1825 * get_values_def - Parse back a VALUES list
1829 get_values_def(List *values_lists, deparse_context *context)
1831 StringInfo buf = context->buf;
1832 bool first_list = true;
1835 appendStringInfoString(buf, "VALUES ");
1837 foreach(vtl, values_lists)
1839 List *sublist = (List *) lfirst(vtl);
1840 bool first_col = true;
1846 appendStringInfoString(buf, ", ");
1848 appendStringInfoChar(buf, '(');
1849 foreach(lc, sublist)
1851 Node *col = (Node *) lfirst(lc);
1856 appendStringInfoChar(buf, ',');
1859 * Strip any top-level nodes representing indirection assignments,
1860 * then print the result.
1862 get_rule_expr(processIndirection(col, context, false),
1865 appendStringInfoChar(buf, ')');
1870 * get_select_query_def - Parse back a SELECT parsetree
1874 get_select_query_def(Query *query, deparse_context *context,
1875 TupleDesc resultDesc)
1877 StringInfo buf = context->buf;
1883 * If the Query node has a setOperations tree, then it's the top level of
1884 * a UNION/INTERSECT/EXCEPT query; only the ORDER BY and LIMIT fields are
1885 * interesting in the top query itself.
1887 if (query->setOperations)
1889 get_setop_query(query->setOperations, query, context, resultDesc);
1890 /* ORDER BY clauses must be simple in this case */
1895 get_basic_select_query(query, context, resultDesc);
1896 force_colno = false;
1899 /* Add the ORDER BY clause if given */
1900 if (query->sortClause != NIL)
1902 appendContextKeyword(context, " ORDER BY ",
1903 -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
1905 foreach(l, query->sortClause)
1907 SortClause *srt = (SortClause *) lfirst(l);
1910 TypeCacheEntry *typentry;
1912 appendStringInfoString(buf, sep);
1913 sortexpr = get_rule_sortgroupclause(srt, query->targetList,
1914 force_colno, context);
1915 sortcoltype = exprType(sortexpr);
1916 /* See whether operator is default < or > for datatype */
1917 typentry = lookup_type_cache(sortcoltype,
1918 TYPECACHE_LT_OPR | TYPECACHE_GT_OPR);
1919 if (srt->sortop == typentry->lt_opr)
1921 /* ASC is default, so emit nothing for it */
1922 if (srt->nulls_first)
1923 appendStringInfo(buf, " NULLS FIRST");
1925 else if (srt->sortop == typentry->gt_opr)
1927 appendStringInfo(buf, " DESC");
1928 /* DESC defaults to NULLS FIRST */
1929 if (!srt->nulls_first)
1930 appendStringInfo(buf, " NULLS LAST");
1934 appendStringInfo(buf, " USING %s",
1935 generate_operator_name(srt->sortop,
1938 /* be specific to eliminate ambiguity */
1939 if (srt->nulls_first)
1940 appendStringInfo(buf, " NULLS FIRST");
1942 appendStringInfo(buf, " NULLS LAST");
1948 /* Add the LIMIT clause if given */
1949 if (query->limitOffset != NULL)
1951 appendContextKeyword(context, " OFFSET ",
1952 -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
1953 get_rule_expr(query->limitOffset, context, false);
1955 if (query->limitCount != NULL)
1957 appendContextKeyword(context, " LIMIT ",
1958 -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
1959 if (IsA(query->limitCount, Const) &&
1960 ((Const *) query->limitCount)->constisnull)
1961 appendStringInfo(buf, "ALL");
1963 get_rule_expr(query->limitCount, context, false);
1966 /* Add FOR UPDATE/SHARE clauses if present */
1967 foreach(l, query->rowMarks)
1969 RowMarkClause *rc = (RowMarkClause *) lfirst(l);
1970 RangeTblEntry *rte = rt_fetch(rc->rti, query->rtable);
1973 appendContextKeyword(context, " FOR UPDATE",
1974 -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
1976 appendContextKeyword(context, " FOR SHARE",
1977 -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
1978 appendStringInfo(buf, " OF %s",
1979 quote_identifier(rte->eref->aliasname));
1981 appendStringInfo(buf, " NOWAIT");
1986 get_basic_select_query(Query *query, deparse_context *context,
1987 TupleDesc resultDesc)
1989 StringInfo buf = context->buf;
1993 if (PRETTY_INDENT(context))
1995 context->indentLevel += PRETTYINDENT_STD;
1996 appendStringInfoChar(buf, ' ');
2000 * If the query looks like SELECT * FROM (VALUES ...), then print just the
2001 * VALUES part. This reverses what transformValuesClause() did at parse
2002 * time. If the jointree contains just a single VALUES RTE, we assume
2003 * this case applies (without looking at the targetlist...)
2005 if (list_length(query->jointree->fromlist) == 1)
2007 RangeTblRef *rtr = (RangeTblRef *) linitial(query->jointree->fromlist);
2009 if (IsA(rtr, RangeTblRef))
2011 RangeTblEntry *rte = rt_fetch(rtr->rtindex, query->rtable);
2013 if (rte->rtekind == RTE_VALUES)
2015 get_values_def(rte->values_lists, context);
2022 * Build up the query string - first we say SELECT
2024 appendStringInfo(buf, "SELECT");
2026 /* Add the DISTINCT clause if given */
2027 if (query->distinctClause != NIL)
2029 if (has_distinct_on_clause(query))
2031 appendStringInfo(buf, " DISTINCT ON (");
2033 foreach(l, query->distinctClause)
2035 SortClause *srt = (SortClause *) lfirst(l);
2037 appendStringInfoString(buf, sep);
2038 get_rule_sortgroupclause(srt, query->targetList,
2042 appendStringInfo(buf, ")");
2045 appendStringInfo(buf, " DISTINCT");
2048 /* Then we tell what to select (the targetlist) */
2049 get_target_list(query->targetList, context, resultDesc);
2051 /* Add the FROM clause if needed */
2052 get_from_clause(query, " FROM ", context);
2054 /* Add the WHERE clause if given */
2055 if (query->jointree->quals != NULL)
2057 appendContextKeyword(context, " WHERE ",
2058 -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
2059 get_rule_expr(query->jointree->quals, context, false);
2062 /* Add the GROUP BY clause if given */
2063 if (query->groupClause != NULL)
2065 appendContextKeyword(context, " GROUP BY ",
2066 -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
2068 foreach(l, query->groupClause)
2070 GroupClause *grp = (GroupClause *) lfirst(l);
2072 appendStringInfoString(buf, sep);
2073 get_rule_sortgroupclause(grp, query->targetList,
2079 /* Add the HAVING clause if given */
2080 if (query->havingQual != NULL)
2082 appendContextKeyword(context, " HAVING ",
2083 -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
2084 get_rule_expr(query->havingQual, context, false);
2089 * get_target_list - Parse back a SELECT target list
2091 * This is also used for RETURNING lists in INSERT/UPDATE/DELETE.
2095 get_target_list(List *targetList, deparse_context *context,
2096 TupleDesc resultDesc)
2098 StringInfo buf = context->buf;
2105 foreach(l, targetList)
2107 TargetEntry *tle = (TargetEntry *) lfirst(l);
2112 continue; /* ignore junk entries */
2114 appendStringInfoString(buf, sep);
2119 * We special-case Var nodes rather than using get_rule_expr. This is
2120 * needed because get_rule_expr will display a whole-row Var as
2121 * "foo.*", which is the preferred notation in most contexts, but at
2122 * the top level of a SELECT list it's not right (the parser will
2123 * expand that notation into multiple columns, yielding behavior
2124 * different from a whole-row Var). We want just "foo", instead.
2126 if (tle->expr && IsA(tle->expr, Var))
2128 attname = get_variable((Var *) tle->expr, 0, false, context);
2132 get_rule_expr((Node *) tle->expr, context, true);
2133 /* We'll show the AS name unless it's this: */
2134 attname = "?column?";
2138 * Figure out what the result column should be called. In the context
2139 * of a view, use the view's tuple descriptor (so as to pick up the
2140 * effects of any column RENAME that's been done on the view).
2141 * Otherwise, just use what we can find in the TLE.
2143 if (resultDesc && colno <= resultDesc->natts)
2144 colname = NameStr(resultDesc->attrs[colno - 1]->attname);
2146 colname = tle->resname;
2148 /* Show AS unless the column's name is correct as-is */
2149 if (colname) /* resname could be NULL */
2151 if (attname == NULL || strcmp(attname, colname) != 0)
2152 appendStringInfo(buf, " AS %s", quote_identifier(colname));
2158 get_setop_query(Node *setOp, Query *query, deparse_context *context,
2159 TupleDesc resultDesc)
2161 StringInfo buf = context->buf;
2164 if (IsA(setOp, RangeTblRef))
2166 RangeTblRef *rtr = (RangeTblRef *) setOp;
2167 RangeTblEntry *rte = rt_fetch(rtr->rtindex, query->rtable);
2168 Query *subquery = rte->subquery;
2170 Assert(subquery != NULL);
2171 Assert(subquery->setOperations == NULL);
2172 /* Need parens if ORDER BY, FOR UPDATE, or LIMIT; see gram.y */
2173 need_paren = (subquery->sortClause ||
2174 subquery->rowMarks ||
2175 subquery->limitOffset ||
2176 subquery->limitCount);
2178 appendStringInfoChar(buf, '(');
2179 get_query_def(subquery, buf, context->namespaces, resultDesc,
2180 context->prettyFlags, context->indentLevel);
2182 appendStringInfoChar(buf, ')');
2184 else if (IsA(setOp, SetOperationStmt))
2186 SetOperationStmt *op = (SetOperationStmt *) setOp;
2189 * We force parens whenever nesting two SetOperationStmts. There are
2190 * some cases in which parens are needed around a leaf query too, but
2191 * those are more easily handled at the next level down (see code
2194 need_paren = !IsA(op->larg, RangeTblRef);
2197 appendStringInfoChar(buf, '(');
2198 get_setop_query(op->larg, query, context, resultDesc);
2200 appendStringInfoChar(buf, ')');
2202 if (!PRETTY_INDENT(context))
2203 appendStringInfoChar(buf, ' ');
2207 appendContextKeyword(context, "UNION ",
2208 -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
2210 case SETOP_INTERSECT:
2211 appendContextKeyword(context, "INTERSECT ",
2212 -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
2215 appendContextKeyword(context, "EXCEPT ",
2216 -PRETTYINDENT_STD, PRETTYINDENT_STD, 0);
2219 elog(ERROR, "unrecognized set op: %d",
2223 appendStringInfo(buf, "ALL ");
2225 if (PRETTY_INDENT(context))
2226 appendContextKeyword(context, "", 0, 0, 0);
2228 need_paren = !IsA(op->rarg, RangeTblRef);
2231 appendStringInfoChar(buf, '(');
2232 get_setop_query(op->rarg, query, context, resultDesc);
2234 appendStringInfoChar(buf, ')');
2238 elog(ERROR, "unrecognized node type: %d",
2239 (int) nodeTag(setOp));
2244 * Display a sort/group clause.
2246 * Also returns the expression tree, so caller need not find it again.
2249 get_rule_sortgroupclause(SortClause *srt, List *tlist, bool force_colno,
2250 deparse_context *context)
2252 StringInfo buf = context->buf;
2256 tle = get_sortgroupclause_tle(srt, tlist);
2257 expr = (Node *) tle->expr;
2260 * Use column-number form if requested by caller. Otherwise, if
2261 * expression is a constant, force it to be dumped with an explicit
2262 * cast as decoration --- this is because a simple integer constant
2263 * is ambiguous (and will be misinterpreted by findTargetlistEntry())
2264 * if we dump it without any decoration. Otherwise, just dump the
2265 * expression normally.
2269 Assert(!tle->resjunk);
2270 appendStringInfo(buf, "%d", tle->resno);
2272 else if (expr && IsA(expr, Const))
2273 get_const_expr((Const *) expr, context, 1);
2275 get_rule_expr(expr, context, true);
2281 * get_insert_query_def - Parse back an INSERT parsetree
2285 get_insert_query_def(Query *query, deparse_context *context)
2287 StringInfo buf = context->buf;
2288 RangeTblEntry *select_rte = NULL;
2289 RangeTblEntry *values_rte = NULL;
2292 ListCell *values_cell;
2294 List *strippedexprs;
2297 * If it's an INSERT ... SELECT or VALUES (...), (...), ... there will be
2298 * a single RTE for the SELECT or VALUES.
2300 foreach(l, query->rtable)
2302 rte = (RangeTblEntry *) lfirst(l);
2304 if (rte->rtekind == RTE_SUBQUERY)
2307 elog(ERROR, "too many subquery RTEs in INSERT");
2311 if (rte->rtekind == RTE_VALUES)
2314 elog(ERROR, "too many values RTEs in INSERT");
2318 if (select_rte && values_rte)
2319 elog(ERROR, "both subquery and values RTEs in INSERT");
2322 * Start the query with INSERT INTO relname
2324 rte = rt_fetch(query->resultRelation, query->rtable);
2325 Assert(rte->rtekind == RTE_RELATION);
2327 if (PRETTY_INDENT(context))
2329 context->indentLevel += PRETTYINDENT_STD;
2330 appendStringInfoChar(buf, ' ');
2332 appendStringInfo(buf, "INSERT INTO %s (",
2333 generate_relation_name(rte->relid));
2336 * Add the insert-column-names list. To handle indirection properly, we
2337 * need to look for indirection nodes in the top targetlist (if it's
2338 * INSERT ... SELECT or INSERT ... single VALUES), or in the first
2339 * expression list of the VALUES RTE (if it's INSERT ... multi VALUES). We
2340 * assume that all the expression lists will have similar indirection in
2344 values_cell = list_head((List *) linitial(values_rte->values_lists));
2347 strippedexprs = NIL;
2349 foreach(l, query->targetList)
2351 TargetEntry *tle = (TargetEntry *) lfirst(l);
2354 continue; /* ignore junk entries */
2356 appendStringInfoString(buf, sep);
2360 * Put out name of target column; look in the catalogs, not at
2361 * tle->resname, since resname will fail to track RENAME.
2363 appendStringInfoString(buf,
2364 quote_identifier(get_relid_attribute_name(rte->relid,
2368 * Print any indirection needed (subfields or subscripts), and strip
2369 * off the top-level nodes representing the indirection assignments.
2373 /* we discard the stripped expression in this case */
2374 processIndirection((Node *) lfirst(values_cell), context, true);
2375 values_cell = lnext(values_cell);
2379 /* we keep a list of the stripped expressions in this case */
2380 strippedexprs = lappend(strippedexprs,
2381 processIndirection((Node *) tle->expr,
2385 appendStringInfo(buf, ") ");
2389 /* Add the SELECT */
2390 get_query_def(select_rte->subquery, buf, NIL, NULL,
2391 context->prettyFlags, context->indentLevel);
2393 else if (values_rte)
2395 /* Add the multi-VALUES expression lists */
2396 get_values_def(values_rte->values_lists, context);
2400 /* Add the single-VALUES expression list */
2401 appendContextKeyword(context, "VALUES (",
2402 -PRETTYINDENT_STD, PRETTYINDENT_STD, 2);
2403 get_rule_expr((Node *) strippedexprs, context, false);
2404 appendStringInfoChar(buf, ')');
2407 /* Add RETURNING if present */
2408 if (query->returningList)
2410 appendContextKeyword(context, " RETURNING",
2411 -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
2412 get_target_list(query->returningList, context, NULL);
2418 * get_update_query_def - Parse back an UPDATE parsetree
2422 get_update_query_def(Query *query, deparse_context *context)
2424 StringInfo buf = context->buf;
2430 * Start the query with UPDATE relname SET
2432 rte = rt_fetch(query->resultRelation, query->rtable);
2433 Assert(rte->rtekind == RTE_RELATION);
2434 if (PRETTY_INDENT(context))
2436 appendStringInfoChar(buf, ' ');
2437 context->indentLevel += PRETTYINDENT_STD;
2439 appendStringInfo(buf, "UPDATE %s%s SET ",
2441 generate_relation_name(rte->relid));
2443 /* Add the comma separated list of 'attname = value' */
2445 foreach(l, query->targetList)
2447 TargetEntry *tle = (TargetEntry *) lfirst(l);
2451 continue; /* ignore junk entries */
2453 appendStringInfoString(buf, sep);
2457 * Put out name of target column; look in the catalogs, not at
2458 * tle->resname, since resname will fail to track RENAME.
2460 appendStringInfoString(buf,
2461 quote_identifier(get_relid_attribute_name(rte->relid,
2465 * Print any indirection needed (subfields or subscripts), and strip
2466 * off the top-level nodes representing the indirection assignments.
2468 expr = processIndirection((Node *) tle->expr, context, true);
2470 appendStringInfo(buf, " = ");
2472 get_rule_expr(expr, context, false);
2475 /* Add the FROM clause if needed */
2476 get_from_clause(query, " FROM ", context);
2478 /* Add a WHERE clause if given */
2479 if (query->jointree->quals != NULL)
2481 appendContextKeyword(context, " WHERE ",
2482 -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
2483 get_rule_expr(query->jointree->quals, context, false);
2486 /* Add RETURNING if present */
2487 if (query->returningList)
2489 appendContextKeyword(context, " RETURNING",
2490 -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
2491 get_target_list(query->returningList, context, NULL);
2497 * get_delete_query_def - Parse back a DELETE parsetree
2501 get_delete_query_def(Query *query, deparse_context *context)
2503 StringInfo buf = context->buf;
2507 * Start the query with DELETE FROM relname
2509 rte = rt_fetch(query->resultRelation, query->rtable);
2510 Assert(rte->rtekind == RTE_RELATION);
2511 if (PRETTY_INDENT(context))
2513 context->indentLevel += PRETTYINDENT_STD;
2514 appendStringInfoChar(buf, ' ');
2516 appendStringInfo(buf, "DELETE FROM %s%s",
2518 generate_relation_name(rte->relid));
2520 /* Add the USING clause if given */
2521 get_from_clause(query, " USING ", context);
2523 /* Add a WHERE clause if given */
2524 if (query->jointree->quals != NULL)
2526 appendContextKeyword(context, " WHERE ",
2527 -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
2528 get_rule_expr(query->jointree->quals, context, false);
2531 /* Add RETURNING if present */
2532 if (query->returningList)
2534 appendContextKeyword(context, " RETURNING",
2535 -PRETTYINDENT_STD, PRETTYINDENT_STD, 1);
2536 get_target_list(query->returningList, context, NULL);
2542 * get_utility_query_def - Parse back a UTILITY parsetree
2546 get_utility_query_def(Query *query, deparse_context *context)
2548 StringInfo buf = context->buf;
2550 if (query->utilityStmt && IsA(query->utilityStmt, NotifyStmt))
2552 NotifyStmt *stmt = (NotifyStmt *) query->utilityStmt;
2554 appendContextKeyword(context, "",
2555 0, PRETTYINDENT_STD, 1);
2556 appendStringInfo(buf, "NOTIFY %s",
2557 quote_qualified_identifier(stmt->relation->schemaname,
2558 stmt->relation->relname));
2562 /* Currently only NOTIFY utility commands can appear in rules */
2563 elog(ERROR, "unexpected utility statement type");
2569 * push_plan: set up deparse_namespace to recurse into the tlist of a subplan
2571 * When expanding an OUTER or INNER reference, we must push new outer/inner
2572 * subplans in case the referenced expression itself uses OUTER/INNER. We
2573 * modify the top stack entry in-place to avoid affecting levelsup issues
2574 * (although in a Plan tree there really shouldn't be any).
2576 * Caller must save and restore outer_plan and inner_plan around this.
2579 push_plan(deparse_namespace *dpns, Plan *subplan)
2582 * We special-case Append to pretend that the first child plan is the
2583 * OUTER referent; otherwise normal.
2585 if (IsA(subplan, Append))
2586 dpns->outer_plan = (Plan *) linitial(((Append *) subplan)->appendplans);
2588 dpns->outer_plan = outerPlan(subplan);
2591 * For a SubqueryScan, pretend the subplan is INNER referent. (We don't
2592 * use OUTER because that could someday conflict with the normal meaning.)
2594 if (IsA(subplan, SubqueryScan))
2595 dpns->inner_plan = ((SubqueryScan *) subplan)->subplan;
2597 dpns->inner_plan = innerPlan(subplan);
2602 * Display a Var appropriately.
2604 * In some cases (currently only when recursing into an unnamed join)
2605 * the Var's varlevelsup has to be interpreted with respect to a context
2606 * above the current one; levelsup indicates the offset.
2608 * If showstar is TRUE, whole-row Vars are displayed as "foo.*";
2609 * if FALSE, merely as "foo".
2611 * Returns the attname of the Var, or NULL if not determinable.
2614 get_variable(Var *var, int levelsup, bool showstar, deparse_context *context)
2616 StringInfo buf = context->buf;
2620 deparse_namespace *dpns;
2625 /* Find appropriate nesting depth */
2626 netlevelsup = var->varlevelsup + levelsup;
2627 if (netlevelsup >= list_length(context->namespaces))
2628 elog(ERROR, "bogus varlevelsup: %d offset %d",
2629 var->varlevelsup, levelsup);
2630 dpns = (deparse_namespace *) list_nth(context->namespaces,
2634 * Try to find the relevant RTE in this rtable. In a plan tree, it's
2635 * likely that varno is OUTER or INNER, in which case we must dig down
2636 * into the subplans.
2638 if (var->varno >= 1 && var->varno <= list_length(dpns->rtable))
2640 rte = rt_fetch(var->varno, dpns->rtable);
2641 attnum = var->varattno;
2643 else if (var->varno == OUTER && dpns->outer_plan)
2649 tle = get_tle_by_resno(dpns->outer_plan->targetlist, var->varattno);
2651 elog(ERROR, "bogus varattno for OUTER var: %d", var->varattno);
2653 Assert(netlevelsup == 0);
2654 save_outer = dpns->outer_plan;
2655 save_inner = dpns->inner_plan;
2656 push_plan(dpns, dpns->outer_plan);
2659 * Force parentheses because our caller probably assumed a Var is a
2660 * simple expression.
2662 if (!IsA(tle->expr, Var))
2663 appendStringInfoChar(buf, '(');
2664 get_rule_expr((Node *) tle->expr, context, true);
2665 if (!IsA(tle->expr, Var))
2666 appendStringInfoChar(buf, ')');
2668 dpns->outer_plan = save_outer;
2669 dpns->inner_plan = save_inner;
2672 else if (var->varno == INNER && dpns->inner_plan)
2678 tle = get_tle_by_resno(dpns->inner_plan->targetlist, var->varattno);
2680 elog(ERROR, "bogus varattno for INNER var: %d", var->varattno);
2682 Assert(netlevelsup == 0);
2683 save_outer = dpns->outer_plan;
2684 save_inner = dpns->inner_plan;
2685 push_plan(dpns, dpns->inner_plan);
2688 * Force parentheses because our caller probably assumed a Var is a
2689 * simple expression.
2691 if (!IsA(tle->expr, Var))
2692 appendStringInfoChar(buf, '(');
2693 get_rule_expr((Node *) tle->expr, context, true);
2694 if (!IsA(tle->expr, Var))
2695 appendStringInfoChar(buf, ')');
2697 dpns->outer_plan = save_outer;
2698 dpns->inner_plan = save_inner;
2703 elog(ERROR, "bogus varno: %d", var->varno);
2704 return NULL; /* keep compiler quiet */
2707 /* Identify names to use */
2708 schemaname = NULL; /* default assumptions */
2709 refname = rte->eref->aliasname;
2711 /* Exceptions occur only if the RTE is alias-less */
2712 if (rte->alias == NULL)
2714 if (rte->rtekind == RTE_RELATION)
2717 * It's possible that use of the bare refname would find another
2718 * more-closely-nested RTE, or be ambiguous, in which case we need
2719 * to specify the schemaname to avoid these errors.
2721 if (find_rte_by_refname(rte->eref->aliasname, context) != rte)
2722 schemaname = get_namespace_name(get_rel_namespace(rte->relid));
2724 else if (rte->rtekind == RTE_JOIN)
2727 * If it's an unnamed join, look at the expansion of the alias
2728 * variable. If it's a simple reference to one of the input vars
2729 * then recursively print the name of that var, instead. (This
2730 * allows correct decompiling of cases where there are identically
2731 * named columns on both sides of the join.) When it's not a
2732 * simple reference, we have to just print the unqualified
2733 * variable name (this can only happen with columns that were
2734 * merged by USING or NATURAL clauses).
2736 * This wouldn't work in decompiling plan trees, because we don't
2737 * store joinaliasvars lists after planning; but a plan tree
2738 * should never contain a join alias variable.
2740 if (rte->joinaliasvars == NIL)
2741 elog(ERROR, "cannot decompile join alias var in plan tree");
2746 aliasvar = (Var *) list_nth(rte->joinaliasvars, attnum - 1);
2747 if (IsA(aliasvar, Var))
2749 return get_variable(aliasvar, var->varlevelsup + levelsup,
2753 /* Unnamed join has neither schemaname nor refname */
2758 if (attnum == InvalidAttrNumber)
2761 attname = get_rte_attribute_name(rte, attnum);
2763 if (refname && (context->varprefix || attname == NULL))
2766 appendStringInfo(buf, "%s.",
2767 quote_identifier(schemaname));
2769 if (strcmp(refname, "*NEW*") == 0)
2770 appendStringInfoString(buf, "new");
2771 else if (strcmp(refname, "*OLD*") == 0)
2772 appendStringInfoString(buf, "old");
2774 appendStringInfoString(buf, quote_identifier(refname));
2776 if (attname || showstar)
2777 appendStringInfoChar(buf, '.');
2780 appendStringInfoString(buf, quote_identifier(attname));
2782 appendStringInfoChar(buf, '*');
2789 * Get the name of a field of an expression of composite type.
2791 * This is fairly straightforward except for the case of a Var of type RECORD.
2792 * Since no actual table or view column is allowed to have type RECORD, such
2793 * a Var must refer to a JOIN or FUNCTION RTE or to a subquery output. We
2794 * drill down to find the ultimate defining expression and attempt to infer
2795 * the field name from it. We ereport if we can't determine the name.
2797 * levelsup is an extra offset to interpret the Var's varlevelsup correctly.
2800 get_name_for_var_field(Var *var, int fieldno,
2801 int levelsup, deparse_context *context)
2806 deparse_namespace *dpns;
2807 TupleDesc tupleDesc;
2811 * If it's a Var of type RECORD, we have to find what the Var refers to;
2812 * if not, we can use get_expr_result_type. If that fails, we try
2813 * lookup_rowtype_tupdesc, which will probably fail too, but will ereport
2814 * an acceptable message.
2816 if (!IsA(var, Var) ||
2817 var->vartype != RECORDOID)
2819 if (get_expr_result_type((Node *) var, NULL, &tupleDesc) != TYPEFUNC_COMPOSITE)
2820 tupleDesc = lookup_rowtype_tupdesc_copy(exprType((Node *) var),
2821 exprTypmod((Node *) var));
2823 /* Got the tupdesc, so we can extract the field name */
2824 Assert(fieldno >= 1 && fieldno <= tupleDesc->natts);
2825 return NameStr(tupleDesc->attrs[fieldno - 1]->attname);
2828 /* Find appropriate nesting depth */
2829 netlevelsup = var->varlevelsup + levelsup;
2830 if (netlevelsup >= list_length(context->namespaces))
2831 elog(ERROR, "bogus varlevelsup: %d offset %d",
2832 var->varlevelsup, levelsup);
2833 dpns = (deparse_namespace *) list_nth(context->namespaces,
2837 * Try to find the relevant RTE in this rtable. In a plan tree, it's
2838 * likely that varno is OUTER or INNER, in which case we must dig down
2839 * into the subplans.
2841 if (var->varno >= 1 && var->varno <= list_length(dpns->rtable))
2843 rte = rt_fetch(var->varno, dpns->rtable);
2844 attnum = var->varattno;
2846 else if (var->varno == OUTER && dpns->outer_plan)
2853 tle = get_tle_by_resno(dpns->outer_plan->targetlist, var->varattno);
2855 elog(ERROR, "bogus varattno for OUTER var: %d", var->varattno);
2857 Assert(netlevelsup == 0);
2858 save_outer = dpns->outer_plan;
2859 save_inner = dpns->inner_plan;
2860 push_plan(dpns, dpns->outer_plan);
2862 result = get_name_for_var_field((Var *) tle->expr, fieldno,
2865 dpns->outer_plan = save_outer;
2866 dpns->inner_plan = save_inner;
2869 else if (var->varno == INNER && dpns->inner_plan)
2876 tle = get_tle_by_resno(dpns->inner_plan->targetlist, var->varattno);
2878 elog(ERROR, "bogus varattno for INNER var: %d", var->varattno);
2880 Assert(netlevelsup == 0);
2881 save_outer = dpns->outer_plan;
2882 save_inner = dpns->inner_plan;
2883 push_plan(dpns, dpns->inner_plan);
2885 result = get_name_for_var_field((Var *) tle->expr, fieldno,
2888 dpns->outer_plan = save_outer;
2889 dpns->inner_plan = save_inner;
2894 elog(ERROR, "bogus varno: %d", var->varno);
2895 return NULL; /* keep compiler quiet */
2898 if (attnum == InvalidAttrNumber)
2900 /* Var is whole-row reference to RTE, so select the right field */
2901 return get_rte_attribute_name(rte, fieldno);
2905 * This part has essentially the same logic as the parser's
2906 * expandRecordVariable() function, but we are dealing with a different
2907 * representation of the input context, and we only need one field name
2908 * not a TupleDesc. Also, we need a special case for deparsing Plan
2909 * trees, because the subquery field has been removed from SUBQUERY RTEs.
2911 expr = (Node *) var; /* default if we can't drill down */
2913 switch (rte->rtekind)
2920 * This case should not occur: a column of a table or values list
2921 * shouldn't have type RECORD. Fall through and fail (most
2922 * likely) at the bottom.
2929 /* Subselect-in-FROM: examine sub-select's output expr */
2930 TargetEntry *ste = get_tle_by_resno(rte->subquery->targetList,
2933 if (ste == NULL || ste->resjunk)
2934 elog(ERROR, "subquery %s does not have attribute %d",
2935 rte->eref->aliasname, attnum);
2936 expr = (Node *) ste->expr;
2940 * Recurse into the sub-select to see what its Var
2941 * refers to. We have to build an additional level of
2942 * namespace to keep in step with varlevelsup in the
2945 deparse_namespace mydpns;
2948 mydpns.rtable = rte->subquery->rtable;
2949 mydpns.outer_plan = mydpns.inner_plan = NULL;
2951 context->namespaces = lcons(&mydpns,
2952 context->namespaces);
2954 result = get_name_for_var_field((Var *) expr, fieldno,
2957 context->namespaces =
2958 list_delete_first(context->namespaces);
2962 /* else fall through to inspect the expression */
2967 * We're deparsing a Plan tree so we don't have complete
2968 * RTE entries. But the only place we'd see a Var
2969 * directly referencing a SUBQUERY RTE is in a
2970 * SubqueryScan plan node, and we can look into the child
2971 * plan's tlist instead.
2978 if (!dpns->inner_plan)
2979 elog(ERROR, "failed to find plan for subquery %s",
2980 rte->eref->aliasname);
2981 tle = get_tle_by_resno(dpns->inner_plan->targetlist,
2984 elog(ERROR, "bogus varattno for subquery var: %d",
2986 Assert(netlevelsup == 0);
2987 save_outer = dpns->outer_plan;
2988 save_inner = dpns->inner_plan;
2989 push_plan(dpns, dpns->inner_plan);
2991 result = get_name_for_var_field((Var *) tle->expr, fieldno,
2994 dpns->outer_plan = save_outer;
2995 dpns->inner_plan = save_inner;
3001 /* Join RTE --- recursively inspect the alias variable */
3002 if (rte->joinaliasvars == NIL)
3003 elog(ERROR, "cannot decompile join alias var in plan tree");
3004 Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
3005 expr = (Node *) list_nth(rte->joinaliasvars, attnum - 1);
3007 return get_name_for_var_field((Var *) expr, fieldno,
3008 var->varlevelsup + levelsup,
3010 /* else fall through to inspect the expression */
3015 * We couldn't get here unless a function is declared with one of
3016 * its result columns as RECORD, which is not allowed.
3022 * We now have an expression we can't expand any more, so see if
3023 * get_expr_result_type() can do anything with it. If not, pass to
3024 * lookup_rowtype_tupdesc() which will probably fail, but will give an
3025 * appropriate error message while failing.
3027 if (get_expr_result_type(expr, NULL, &tupleDesc) != TYPEFUNC_COMPOSITE)
3028 tupleDesc = lookup_rowtype_tupdesc_copy(exprType(expr),
3031 /* Got the tupdesc, so we can extract the field name */
3032 Assert(fieldno >= 1 && fieldno <= tupleDesc->natts);
3033 return NameStr(tupleDesc->attrs[fieldno - 1]->attname);
3038 * find_rte_by_refname - look up an RTE by refname in a deparse context
3040 * Returns NULL if there is no matching RTE or the refname is ambiguous.
3042 * NOTE: this code is not really correct since it does not take account of
3043 * the fact that not all the RTEs in a rangetable may be visible from the
3044 * point where a Var reference appears. For the purposes we need, however,
3045 * the only consequence of a false match is that we might stick a schema
3046 * qualifier on a Var that doesn't really need it. So it seems close
3049 static RangeTblEntry *
3050 find_rte_by_refname(const char *refname, deparse_context *context)
3052 RangeTblEntry *result = NULL;
3055 foreach(nslist, context->namespaces)
3057 deparse_namespace *dpns = (deparse_namespace *) lfirst(nslist);
3060 foreach(rtlist, dpns->rtable)
3062 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rtlist);
3064 if (strcmp(rte->eref->aliasname, refname) == 0)
3067 return NULL; /* it's ambiguous */
3079 * get_simple_binary_op_name
3081 * helper function for isSimpleNode
3082 * will return single char binary operator name, or NULL if it's not
3085 get_simple_binary_op_name(OpExpr *expr)
3087 List *args = expr->args;
3089 if (list_length(args) == 2)
3091 /* binary operator */
3092 Node *arg1 = (Node *) linitial(args);
3093 Node *arg2 = (Node *) lsecond(args);
3096 op = generate_operator_name(expr->opno, exprType(arg1), exprType(arg2));
3097 if (strlen(op) == 1)
3105 * isSimpleNode - check if given node is simple (doesn't need parenthesizing)
3107 * true : simple in the context of parent node's type
3108 * false : not simple
3111 isSimpleNode(Node *node, Node *parentNode, int prettyFlags)
3116 switch (nodeTag(node))
3121 case T_CoerceToDomainValue:
3122 case T_SetToDefault:
3123 case T_CurrentOfExpr:
3124 /* single words: always simple */
3130 case T_CoalesceExpr:
3136 /* function-like: name(..) or name[..] */
3139 /* CASE keywords act as parentheses */
3146 * appears simple since . has top precedence, unless parent is
3147 * T_FieldSelect itself!
3149 return (IsA(parentNode, FieldSelect) ? false : true);
3154 * treat like FieldSelect (probably doesn't matter)
3156 return (IsA(parentNode, FieldStore) ? false : true);
3158 case T_CoerceToDomain:
3159 /* maybe simple, check args */
3160 return isSimpleNode((Node *) ((CoerceToDomain *) node)->arg,
3163 return isSimpleNode((Node *) ((RelabelType *) node)->arg,
3166 return isSimpleNode((Node *) ((CoerceViaIO *) node)->arg,
3168 case T_ArrayCoerceExpr:
3169 return isSimpleNode((Node *) ((ArrayCoerceExpr *) node)->arg,
3171 case T_ConvertRowtypeExpr:
3172 return isSimpleNode((Node *) ((ConvertRowtypeExpr *) node)->arg,
3177 /* depends on parent node type; needs further checking */
3178 if (prettyFlags & PRETTYFLAG_PAREN && IsA(parentNode, OpExpr))
3181 const char *parentOp;
3184 bool is_lopriparent;
3185 bool is_hipriparent;
3187 op = get_simple_binary_op_name((OpExpr *) node);
3191 /* We know only the basic operators + - and * / % */
3192 is_lopriop = (strchr("+-", *op) != NULL);
3193 is_hipriop = (strchr("*/%", *op) != NULL);
3194 if (!(is_lopriop || is_hipriop))
3197 parentOp = get_simple_binary_op_name((OpExpr *) parentNode);
3201 is_lopriparent = (strchr("+-", *parentOp) != NULL);
3202 is_hipriparent = (strchr("*/%", *parentOp) != NULL);
3203 if (!(is_lopriparent || is_hipriparent))
3206 if (is_hipriop && is_lopriparent)
3207 return true; /* op binds tighter than parent */
3209 if (is_lopriop && is_hipriparent)
3213 * Operators are same priority --- can skip parens only if
3214 * we have (a - b) - c, not a - (b - c).
3216 if (node == (Node *) linitial(((OpExpr *) parentNode)->args))
3221 /* else do the same stuff as for T_SubLink et al. */
3228 case T_DistinctExpr:
3229 switch (nodeTag(parentNode))
3233 /* special handling for casts */
3234 CoercionForm type = ((FuncExpr *) parentNode)->funcformat;
3236 if (type == COERCE_EXPLICIT_CAST ||
3237 type == COERCE_IMPLICIT_CAST)
3239 return true; /* own parentheses */
3241 case T_BoolExpr: /* lower precedence */
3242 case T_ArrayRef: /* other separators */
3243 case T_ArrayExpr: /* other separators */
3244 case T_RowExpr: /* other separators */
3245 case T_CoalesceExpr: /* own parentheses */
3246 case T_MinMaxExpr: /* own parentheses */
3247 case T_XmlExpr: /* own parentheses */
3248 case T_NullIfExpr: /* other separators */
3249 case T_Aggref: /* own parentheses */
3250 case T_CaseExpr: /* other separators */
3257 switch (nodeTag(parentNode))
3260 if (prettyFlags & PRETTYFLAG_PAREN)
3263 BoolExprType parentType;
3265 type = ((BoolExpr *) node)->boolop;
3266 parentType = ((BoolExpr *) parentNode)->boolop;
3271 if (parentType == AND_EXPR || parentType == OR_EXPR)
3275 if (parentType == OR_EXPR)
3283 /* special handling for casts */
3284 CoercionForm type = ((FuncExpr *) parentNode)->funcformat;
3286 if (type == COERCE_EXPLICIT_CAST ||
3287 type == COERCE_IMPLICIT_CAST)
3289 return true; /* own parentheses */
3291 case T_ArrayRef: /* other separators */
3292 case T_ArrayExpr: /* other separators */
3293 case T_RowExpr: /* other separators */
3294 case T_CoalesceExpr: /* own parentheses */
3295 case T_MinMaxExpr: /* own parentheses */
3296 case T_XmlExpr: /* own parentheses */
3297 case T_NullIfExpr: /* other separators */
3298 case T_Aggref: /* own parentheses */
3299 case T_CaseExpr: /* other separators */
3308 /* those we don't know: in dubio complexo */
3314 * appendStringInfoSpaces - append spaces to buffer
3317 appendStringInfoSpaces(StringInfo buf, int count)
3320 appendStringInfoChar(buf, ' ');
3324 * appendContextKeyword - append a keyword to buffer
3326 * If prettyPrint is enabled, perform a line break, and adjust indentation.
3327 * Otherwise, just append the keyword.
3330 appendContextKeyword(deparse_context *context, const char *str,
3331 int indentBefore, int indentAfter, int indentPlus)
3333 if (PRETTY_INDENT(context))
3335 context->indentLevel += indentBefore;
3337 appendStringInfoChar(context->buf, '\n');
3338 appendStringInfoSpaces(context->buf,
3339 Max(context->indentLevel, 0) + indentPlus);
3340 appendStringInfoString(context->buf, str);
3342 context->indentLevel += indentAfter;
3343 if (context->indentLevel < 0)
3344 context->indentLevel = 0;
3347 appendStringInfoString(context->buf, str);
3351 * get_rule_expr_paren - deparse expr using get_rule_expr,
3352 * embracing the string with parentheses if necessary for prettyPrint.
3354 * Never embrace if prettyFlags=0, because it's done in the calling node.
3356 * Any node that does *not* embrace its argument node by sql syntax (with
3357 * parentheses, non-operator keywords like CASE/WHEN/ON, or comma etc) should
3358 * use get_rule_expr_paren instead of get_rule_expr so parentheses can be
3362 get_rule_expr_paren(Node *node, deparse_context *context,
3363 bool showimplicit, Node *parentNode)
3367 need_paren = PRETTY_PAREN(context) &&
3368 !isSimpleNode(node, parentNode, context->prettyFlags);
3371 appendStringInfoChar(context->buf, '(');
3373 get_rule_expr(node, context, showimplicit);
3376 appendStringInfoChar(context->buf, ')');
3381 * get_rule_expr - Parse back an expression
3383 * Note: showimplicit determines whether we display any implicit cast that
3384 * is present at the top of the expression tree. It is a passed argument,
3385 * not a field of the context struct, because we change the value as we
3386 * recurse down into the expression. In general we suppress implicit casts
3387 * when the result type is known with certainty (eg, the arguments of an
3388 * OR must be boolean). We display implicit casts for arguments of functions
3389 * and operators, since this is needed to be certain that the same function
3390 * or operator will be chosen when the expression is re-parsed.
3394 get_rule_expr(Node *node, deparse_context *context,
3397 StringInfo buf = context->buf;
3403 * Each level of get_rule_expr must emit an indivisible term
3404 * (parenthesized if necessary) to ensure result is reparsed into the same
3405 * expression tree. The only exception is that when the input is a List,
3406 * we emit the component items comma-separated with no surrounding
3407 * decoration; this is convenient for most callers.
3409 switch (nodeTag(node))
3412 (void) get_variable((Var *) node, 0, true, context);
3416 get_const_expr((Const *) node, context, 0);
3420 appendStringInfo(buf, "$%d", ((Param *) node)->paramid);
3424 get_agg_expr((Aggref *) node, context);
3429 ArrayRef *aref = (ArrayRef *) node;
3433 * Parenthesize the argument unless it's a simple Var or a
3434 * FieldSelect. (In particular, if it's another ArrayRef, we
3435 * *must* parenthesize to avoid confusion.)
3437 need_parens = !IsA(aref->refexpr, Var) &&
3438 !IsA(aref->refexpr, FieldSelect);
3440 appendStringInfoChar(buf, '(');
3441 get_rule_expr((Node *) aref->refexpr, context, showimplicit);
3443 appendStringInfoChar(buf, ')');
3444 printSubscripts(aref, context);
3447 * Array assignment nodes should have been handled in
3448 * processIndirection().
3450 if (aref->refassgnexpr)
3451 elog(ERROR, "unexpected refassgnexpr");
3456 get_func_expr((FuncExpr *) node, context, showimplicit);
3460 get_oper_expr((OpExpr *) node, context);
3463 case T_DistinctExpr:
3465 DistinctExpr *expr = (DistinctExpr *) node;
3466 List *args = expr->args;
3467 Node *arg1 = (Node *) linitial(args);
3468 Node *arg2 = (Node *) lsecond(args);
3470 if (!PRETTY_PAREN(context))
3471 appendStringInfoChar(buf, '(');
3472 get_rule_expr_paren(arg1, context, true, node);
3473 appendStringInfo(buf, " IS DISTINCT FROM ");
3474 get_rule_expr_paren(arg2, context, true, node);
3475 if (!PRETTY_PAREN(context))
3476 appendStringInfoChar(buf, ')');
3480 case T_ScalarArrayOpExpr:
3482 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
3483 List *args = expr->args;
3484 Node *arg1 = (Node *) linitial(args);
3485 Node *arg2 = (Node *) lsecond(args);
3487 if (!PRETTY_PAREN(context))
3488 appendStringInfoChar(buf, '(');
3489 get_rule_expr_paren(arg1, context, true, node);
3490 appendStringInfo(buf, " %s %s (",
3491 generate_operator_name(expr->opno,
3493 get_element_type(exprType(arg2))),
3494 expr->useOr ? "ANY" : "ALL");
3495 get_rule_expr_paren(arg2, context, true, node);
3496 appendStringInfoChar(buf, ')');
3497 if (!PRETTY_PAREN(context))
3498 appendStringInfoChar(buf, ')');
3504 BoolExpr *expr = (BoolExpr *) node;
3505 Node *first_arg = linitial(expr->args);
3506 ListCell *arg = lnext(list_head(expr->args));
3508 switch (expr->boolop)
3511 if (!PRETTY_PAREN(context))
3512 appendStringInfoChar(buf, '(');
3513 get_rule_expr_paren(first_arg, context,
3517 appendStringInfo(buf, " AND ");
3518 get_rule_expr_paren((Node *) lfirst(arg), context,
3522 if (!PRETTY_PAREN(context))
3523 appendStringInfoChar(buf, ')');
3527 if (!PRETTY_PAREN(context))
3528 appendStringInfoChar(buf, '(');
3529 get_rule_expr_paren(first_arg, context,
3533 appendStringInfo(buf, " OR ");
3534 get_rule_expr_paren((Node *) lfirst(arg), context,
3538 if (!PRETTY_PAREN(context))
3539 appendStringInfoChar(buf, ')');
3543 if (!PRETTY_PAREN(context))
3544 appendStringInfoChar(buf, '(');
3545 appendStringInfo(buf, "NOT ");
3546 get_rule_expr_paren(first_arg, context,
3548 if (!PRETTY_PAREN(context))
3549 appendStringInfoChar(buf, ')');
3553 elog(ERROR, "unrecognized boolop: %d",
3554 (int) expr->boolop);
3560 get_sublink_expr((SubLink *) node, context);
3566 * We cannot see an already-planned subplan in rule deparsing,
3567 * only while EXPLAINing a query plan. For now, just punt.
3569 if (((SubPlan *) node)->useHashTable)
3570 appendStringInfo(buf, "(hashed subplan)");
3572 appendStringInfo(buf, "(subplan)");
3578 FieldSelect *fselect = (FieldSelect *) node;
3579 Node *arg = (Node *) fselect->arg;
3580 int fno = fselect->fieldnum;
3581 const char *fieldname;
3585 * Parenthesize the argument unless it's an ArrayRef or
3586 * another FieldSelect. Note in particular that it would be
3587 * WRONG to not parenthesize a Var argument; simplicity is not
3588 * the issue here, having the right number of names is.
3590 need_parens = !IsA(arg, ArrayRef) &&!IsA(arg, FieldSelect);
3592 appendStringInfoChar(buf, '(');
3593 get_rule_expr(arg, context, true);
3595 appendStringInfoChar(buf, ')');
3598 * Get and print the field name.
3600 fieldname = get_name_for_var_field((Var *) arg, fno,
3602 appendStringInfo(buf, ".%s", quote_identifier(fieldname));
3609 * We shouldn't see FieldStore here; it should have been stripped
3610 * off by processIndirection().
3612 elog(ERROR, "unexpected FieldStore");
3617 RelabelType *relabel = (RelabelType *) node;
3618 Node *arg = (Node *) relabel->arg;
3620 if (relabel->relabelformat == COERCE_IMPLICIT_CAST &&
3623 /* don't show the implicit cast */
3624 get_rule_expr_paren(arg, context, false, node);
3628 get_coercion_expr(arg, context,
3629 relabel->resulttype,
3630 relabel->resulttypmod,
3638 CoerceViaIO *iocoerce = (CoerceViaIO *) node;
3639 Node *arg = (Node *) iocoerce->arg;
3641 if (iocoerce->coerceformat == COERCE_IMPLICIT_CAST &&
3644 /* don't show the implicit cast */
3645 get_rule_expr_paren(arg, context, false, node);
3649 get_coercion_expr(arg, context,
3650 iocoerce->resulttype,
3657 case T_ArrayCoerceExpr:
3659 ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
3660 Node *arg = (Node *) acoerce->arg;
3662 if (acoerce->coerceformat == COERCE_IMPLICIT_CAST &&
3665 /* don't show the implicit cast */
3666 get_rule_expr_paren(arg, context, false, node);
3670 get_coercion_expr(arg, context,
3671 acoerce->resulttype,
3672 acoerce->resulttypmod,
3678 case T_ConvertRowtypeExpr:
3680 ConvertRowtypeExpr *convert = (ConvertRowtypeExpr *) node;
3681 Node *arg = (Node *) convert->arg;
3683 if (convert->convertformat == COERCE_IMPLICIT_CAST &&
3686 /* don't show the implicit cast */
3687 get_rule_expr_paren(arg, context, false, node);
3691 get_coercion_expr(arg, context,
3692 convert->resulttype, -1,
3700 CaseExpr *caseexpr = (CaseExpr *) node;
3703 appendContextKeyword(context, "CASE",
3704 0, PRETTYINDENT_VAR, 0);
3707 appendStringInfoChar(buf, ' ');
3708 get_rule_expr((Node *) caseexpr->arg, context, true);
3710 foreach(temp, caseexpr->args)
3712 CaseWhen *when = (CaseWhen *) lfirst(temp);
3713 Node *w = (Node *) when->expr;
3715 if (!PRETTY_INDENT(context))
3716 appendStringInfoChar(buf, ' ');
3717 appendContextKeyword(context, "WHEN ",
3722 * The parser should have produced WHEN clauses of the
3723 * form "CaseTestExpr = RHS"; we want to show just the
3724 * RHS. If the user wrote something silly like "CASE
3725 * boolexpr WHEN TRUE THEN ...", then the optimizer's
3726 * simplify_boolean_equality() may have reduced this
3727 * to just "CaseTestExpr" or "NOT CaseTestExpr", for
3728 * which we have to show "TRUE" or "FALSE". Also,
3729 * depending on context the original CaseTestExpr
3730 * might have been reduced to a Const (but we won't
3731 * see "WHEN Const").
3737 Assert(IsA(linitial(((OpExpr *) w)->args),
3739 IsA(linitial(((OpExpr *) w)->args),
3741 rhs = (Node *) lsecond(((OpExpr *) w)->args);
3742 get_rule_expr(rhs, context, false);
3744 else if (IsA(w, CaseTestExpr))
3745 appendStringInfo(buf, "TRUE");
3746 else if (not_clause(w))
3748 Assert(IsA(get_notclausearg((Expr *) w),
3750 appendStringInfo(buf, "FALSE");
3753 elog(ERROR, "unexpected CASE WHEN clause: %d",
3757 get_rule_expr(w, context, false);
3758 appendStringInfo(buf, " THEN ");
3759 get_rule_expr((Node *) when->result, context, true);
3761 if (!PRETTY_INDENT(context))
3762 appendStringInfoChar(buf, ' ');
3763 appendContextKeyword(context, "ELSE ",
3765 get_rule_expr((Node *) caseexpr->defresult, context, true);
3766 if (!PRETTY_INDENT(context))
3767 appendStringInfoChar(buf, ' ');
3768 appendContextKeyword(context, "END",
3769 -PRETTYINDENT_VAR, 0, 0);
3775 ArrayExpr *arrayexpr = (ArrayExpr *) node;
3777 appendStringInfo(buf, "ARRAY[");
3778 get_rule_expr((Node *) arrayexpr->elements, context, true);
3779 appendStringInfoChar(buf, ']');
3785 RowExpr *rowexpr = (RowExpr *) node;
3786 TupleDesc tupdesc = NULL;
3792 * If it's a named type and not RECORD, we may have to skip
3793 * dropped columns and/or claim there are NULLs for added
3796 if (rowexpr->row_typeid != RECORDOID)
3798 tupdesc = lookup_rowtype_tupdesc(rowexpr->row_typeid, -1);
3799 Assert(list_length(rowexpr->args) <= tupdesc->natts);
3803 * SQL99 allows "ROW" to be omitted when there is more than
3804 * one column, but for simplicity we always print it.
3806 appendStringInfo(buf, "ROW(");
3809 foreach(arg, rowexpr->args)
3811 Node *e = (Node *) lfirst(arg);
3813 if (tupdesc == NULL ||
3814 !tupdesc->attrs[i]->attisdropped)
3816 appendStringInfoString(buf, sep);
3817 get_rule_expr(e, context, true);
3822 if (tupdesc != NULL)
3824 while (i < tupdesc->natts)
3826 if (!tupdesc->attrs[i]->attisdropped)
3828 appendStringInfoString(buf, sep);
3829 appendStringInfo(buf, "NULL");
3835 ReleaseTupleDesc(tupdesc);
3837 appendStringInfo(buf, ")");
3838 if (rowexpr->row_format == COERCE_EXPLICIT_CAST)
3839 appendStringInfo(buf, "::%s",
3840 format_type_with_typemod(rowexpr->row_typeid, -1));
3844 case T_RowCompareExpr:
3846 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
3851 * SQL99 allows "ROW" to be omitted when there is more than
3852 * one column, but for simplicity we always print it.
3854 appendStringInfo(buf, "(ROW(");
3856 foreach(arg, rcexpr->largs)
3858 Node *e = (Node *) lfirst(arg);
3860 appendStringInfoString(buf, sep);
3861 get_rule_expr(e, context, true);
3866 * We assume that the name of the first-column operator will
3867 * do for all the rest too. This is definitely open to
3868 * failure, eg if some but not all operators were renamed
3869 * since the construct was parsed, but there seems no way to
3872 appendStringInfo(buf, ") %s ROW(",
3873 generate_operator_name(linitial_oid(rcexpr->opnos),
3874 exprType(linitial(rcexpr->largs)),
3875 exprType(linitial(rcexpr->rargs))));
3877 foreach(arg, rcexpr->rargs)
3879 Node *e = (Node *) lfirst(arg);
3881 appendStringInfoString(buf, sep);
3882 get_rule_expr(e, context, true);
3885 appendStringInfo(buf, "))");
3889 case T_CoalesceExpr:
3891 CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
3893 appendStringInfo(buf, "COALESCE(");
3894 get_rule_expr((Node *) coalesceexpr->args, context, true);
3895 appendStringInfoChar(buf, ')');
3901 MinMaxExpr *minmaxexpr = (MinMaxExpr *) node;
3903 switch (minmaxexpr->op)
3906 appendStringInfo(buf, "GREATEST(");
3909 appendStringInfo(buf, "LEAST(");
3912 get_rule_expr((Node *) minmaxexpr->args, context, true);
3913 appendStringInfoChar(buf, ')');
3919 XmlExpr *xexpr = (XmlExpr *) node;
3920 bool needcomma = false;
3928 appendStringInfoString(buf, "XMLCONCAT(");
3931 appendStringInfoString(buf, "XMLELEMENT(");
3934 appendStringInfoString(buf, "XMLFOREST(");
3937 appendStringInfoString(buf, "XMLPARSE(");
3940 appendStringInfoString(buf, "XMLPI(");
3943 appendStringInfoString(buf, "XMLROOT(");
3945 case IS_XMLSERIALIZE:
3946 appendStringInfoString(buf, "XMLSERIALIZE(");
3951 if (xexpr->op == IS_XMLPARSE || xexpr->op == IS_XMLSERIALIZE)
3953 if (xexpr->xmloption == XMLOPTION_DOCUMENT)
3954 appendStringInfoString(buf, "DOCUMENT ");
3956 appendStringInfoString(buf, "CONTENT ");
3960 appendStringInfo(buf, "NAME %s",
3961 quote_identifier(map_xml_name_to_sql_identifier(xexpr->name)));
3964 if (xexpr->named_args)
3966 if (xexpr->op != IS_XMLFOREST)
3969 appendStringInfoString(buf, ", ");
3970 appendStringInfoString(buf, "XMLATTRIBUTES(");
3973 forboth(arg, xexpr->named_args, narg, xexpr->arg_names)
3975 Node *e = (Node *) lfirst(arg);
3976 char *argname = strVal(lfirst(narg));
3979 appendStringInfoString(buf, ", ");
3980 get_rule_expr((Node *) e, context, true);
3981 appendStringInfo(buf, " AS %s",
3982 quote_identifier(map_xml_name_to_sql_identifier(argname)));
3985 if (xexpr->op != IS_XMLFOREST)
3986 appendStringInfoChar(buf, ')');
3991 appendStringInfoString(buf, ", ");
3998 case IS_XMLSERIALIZE:
3999 /* no extra decoration needed */
4000 get_rule_expr((Node *) xexpr->args, context, true);
4003 Assert(list_length(xexpr->args) == 2);
4005 get_rule_expr((Node *) linitial(xexpr->args),
4008 con = (Const *) lsecond(xexpr->args);
4009 Assert(IsA(con, Const));
4010 Assert(!con->constisnull);
4011 if (DatumGetBool(con->constvalue))
4012 appendStringInfoString(buf,
4013 " PRESERVE WHITESPACE");
4015 appendStringInfoString(buf,
4016 " STRIP WHITESPACE");
4019 Assert(list_length(xexpr->args) == 3);
4021 get_rule_expr((Node *) linitial(xexpr->args),
4024 appendStringInfoString(buf, ", VERSION ");
4025 con = (Const *) lsecond(xexpr->args);
4026 if (IsA(con, Const) &&
4028 appendStringInfoString(buf, "NO VALUE");
4030 get_rule_expr((Node *) con, context, false);
4032 con = (Const *) lthird(xexpr->args);
4033 Assert(IsA(con, Const));
4034 if (con->constisnull)
4035 /* suppress STANDALONE NO VALUE */ ;
4038 switch (DatumGetInt32(con->constvalue))
4040 case XML_STANDALONE_YES:
4041 appendStringInfoString(buf,
4042 ", STANDALONE YES");
4044 case XML_STANDALONE_NO:
4045 appendStringInfoString(buf,
4048 case XML_STANDALONE_NO_VALUE:
4049 appendStringInfoString(buf,
4050 ", STANDALONE NO VALUE");
4058 get_rule_expr_paren((Node *) xexpr->args, context, false, node);
4063 if (xexpr->op == IS_XMLSERIALIZE)
4064 appendStringInfo(buf, " AS %s", format_type_with_typemod(xexpr->type,
4066 if (xexpr->op == IS_DOCUMENT)
4067 appendStringInfoString(buf, " IS DOCUMENT");
4069 appendStringInfoChar(buf, ')');
4075 NullIfExpr *nullifexpr = (NullIfExpr *) node;
4077 appendStringInfo(buf, "NULLIF(");
4078 get_rule_expr((Node *) nullifexpr->args, context, true);
4079 appendStringInfoChar(buf, ')');
4085 NullTest *ntest = (NullTest *) node;
4087 if (!PRETTY_PAREN(context))
4088 appendStringInfoChar(buf, '(');
4089 get_rule_expr_paren((Node *) ntest->arg, context, true, node);
4090 switch (ntest->nulltesttype)
4093 appendStringInfo(buf, " IS NULL");
4096 appendStringInfo(buf, " IS NOT NULL");
4099 elog(ERROR, "unrecognized nulltesttype: %d",
4100 (int) ntest->nulltesttype);
4102 if (!PRETTY_PAREN(context))
4103 appendStringInfoChar(buf, ')');
4109 BooleanTest *btest = (BooleanTest *) node;
4111 if (!PRETTY_PAREN(context))
4112 appendStringInfoChar(buf, '(');
4113 get_rule_expr_paren((Node *) btest->arg, context, false, node);
4114 switch (btest->booltesttype)
4117 appendStringInfo(buf, " IS TRUE");
4120 appendStringInfo(buf, " IS NOT TRUE");
4123 appendStringInfo(buf, " IS FALSE");
4126 appendStringInfo(buf, " IS NOT FALSE");
4129 appendStringInfo(buf, " IS UNKNOWN");
4131 case IS_NOT_UNKNOWN:
4132 appendStringInfo(buf, " IS NOT UNKNOWN");
4135 elog(ERROR, "unrecognized booltesttype: %d",
4136 (int) btest->booltesttype);
4138 if (!PRETTY_PAREN(context))
4139 appendStringInfoChar(buf, ')');
4143 case T_CoerceToDomain:
4145 CoerceToDomain *ctest = (CoerceToDomain *) node;
4146 Node *arg = (Node *) ctest->arg;
4148 if (ctest->coercionformat == COERCE_IMPLICIT_CAST &&
4151 /* don't show the implicit cast */
4152 get_rule_expr(arg, context, false);
4156 get_coercion_expr(arg, context,
4158 ctest->resulttypmod,
4164 case T_CoerceToDomainValue:
4165 appendStringInfo(buf, "VALUE");
4168 case T_SetToDefault:
4169 appendStringInfo(buf, "DEFAULT");
4172 case T_CurrentOfExpr:
4174 CurrentOfExpr *cexpr = (CurrentOfExpr *) node;
4176 if (cexpr->cursor_name)
4177 appendStringInfo(buf, "CURRENT OF %s",
4178 quote_identifier(cexpr->cursor_name));
4180 appendStringInfo(buf, "CURRENT OF $%d",
4181 cexpr->cursor_param);
4191 foreach(l, (List *) node)
4193 appendStringInfoString(buf, sep);
4194 get_rule_expr((Node *) lfirst(l), context, showimplicit);
4201 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(node));
4208 * get_oper_expr - Parse back an OpExpr node
4211 get_oper_expr(OpExpr *expr, deparse_context *context)
4213 StringInfo buf = context->buf;
4214 Oid opno = expr->opno;
4215 List *args = expr->args;
4217 if (!PRETTY_PAREN(context))
4218 appendStringInfoChar(buf, '(');
4219 if (list_length(args) == 2)
4221 /* binary operator */
4222 Node *arg1 = (Node *) linitial(args);
4223 Node *arg2 = (Node *) lsecond(args);
4225 get_rule_expr_paren(arg1, context, true, (Node *) expr);
4226 appendStringInfo(buf, " %s ",
4227 generate_operator_name(opno,
4230 get_rule_expr_paren(arg2, context, true, (Node *) expr);
4234 /* unary operator --- but which side? */
4235 Node *arg = (Node *) linitial(args);
4237 Form_pg_operator optup;
4239 tp = SearchSysCache(OPEROID,
4240 ObjectIdGetDatum(opno),
4242 if (!HeapTupleIsValid(tp))
4243 elog(ERROR, "cache lookup failed for operator %u", opno);
4244 optup = (Form_pg_operator) GETSTRUCT(tp);
4245 switch (optup->oprkind)
4248 appendStringInfo(buf, "%s ",
4249 generate_operator_name(opno,
4252 get_rule_expr_paren(arg, context, true, (Node *) expr);
4255 get_rule_expr_paren(arg, context, true, (Node *) expr);
4256 appendStringInfo(buf, " %s",
4257 generate_operator_name(opno,
4262 elog(ERROR, "bogus oprkind: %d", optup->oprkind);
4264 ReleaseSysCache(tp);
4266 if (!PRETTY_PAREN(context))
4267 appendStringInfoChar(buf, ')');
4271 * get_func_expr - Parse back a FuncExpr node
4274 get_func_expr(FuncExpr *expr, deparse_context *context,
4277 StringInfo buf = context->buf;
4278 Oid funcoid = expr->funcid;
4279 Oid argtypes[FUNC_MAX_ARGS];
4284 * If the function call came from an implicit coercion, then just show the
4285 * first argument --- unless caller wants to see implicit coercions.
4287 if (expr->funcformat == COERCE_IMPLICIT_CAST && !showimplicit)
4289 get_rule_expr_paren((Node *) linitial(expr->args), context,
4290 false, (Node *) expr);
4295 * If the function call came from a cast, then show the first argument
4296 * plus an explicit cast operation.
4298 if (expr->funcformat == COERCE_EXPLICIT_CAST ||
4299 expr->funcformat == COERCE_IMPLICIT_CAST)
4301 Node *arg = linitial(expr->args);
4302 Oid rettype = expr->funcresulttype;
4303 int32 coercedTypmod;
4305 /* Get the typmod if this is a length-coercion function */
4306 (void) exprIsLengthCoercion((Node *) expr, &coercedTypmod);
4308 get_coercion_expr(arg, context,
4309 rettype, coercedTypmod,
4316 * Normal function: display as proname(args). First we need to extract
4317 * the argument datatypes.
4320 foreach(l, expr->args)
4322 if (nargs >= FUNC_MAX_ARGS)
4324 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
4325 errmsg("too many arguments")));
4326 argtypes[nargs] = exprType((Node *) lfirst(l));
4330 appendStringInfo(buf, "%s(",
4331 generate_function_name(funcoid, nargs, argtypes));
4332 get_rule_expr((Node *) expr->args, context, true);
4333 appendStringInfoChar(buf, ')');
4337 * get_agg_expr - Parse back an Aggref node
4340 get_agg_expr(Aggref *aggref, deparse_context *context)
4342 StringInfo buf = context->buf;
4343 Oid argtypes[FUNC_MAX_ARGS];
4348 foreach(l, aggref->args)
4350 if (nargs >= FUNC_MAX_ARGS)
4352 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
4353 errmsg("too many arguments")));
4354 argtypes[nargs] = exprType((Node *) lfirst(l));
4358 appendStringInfo(buf, "%s(%s",
4359 generate_function_name(aggref->aggfnoid, nargs, argtypes),
4360 aggref->aggdistinct ? "DISTINCT " : "");
4361 /* aggstar can be set only in zero-argument aggregates */
4362 if (aggref->aggstar)
4363 appendStringInfoChar(buf, '*');
4365 get_rule_expr((Node *) aggref->args, context, true);
4366 appendStringInfoChar(buf, ')');
4372 * Make a string representation of a value coerced to a specific type
4376 get_coercion_expr(Node *arg, deparse_context *context,
4377 Oid resulttype, int32 resulttypmod,
4380 StringInfo buf = context->buf;
4383 * Since parse_coerce.c doesn't immediately collapse application of
4384 * length-coercion functions to constants, what we'll typically see in
4385 * such cases is a Const with typmod -1 and a length-coercion function
4386 * right above it. Avoid generating redundant output. However, beware of
4387 * suppressing casts when the user actually wrote something like
4388 * 'foo'::text::char(3).
4390 if (arg && IsA(arg, Const) &&
4391 ((Const *) arg)->consttype == resulttype &&
4392 ((Const *) arg)->consttypmod == -1)
4394 /* Show the constant without normal ::typename decoration */
4395 get_const_expr((Const *) arg, context, -1);
4399 if (!PRETTY_PAREN(context))
4400 appendStringInfoChar(buf, '(');
4401 get_rule_expr_paren(arg, context, false, parentNode);
4402 if (!PRETTY_PAREN(context))
4403 appendStringInfoChar(buf, ')');
4405 appendStringInfo(buf, "::%s",
4406 format_type_with_typemod(resulttype, resulttypmod));
4412 * Make a string representation of a Const
4414 * showtype can be -1 to never show "::typename" decoration, or +1 to always
4415 * show it, or 0 to show it only if the constant wouldn't be assumed to be
4416 * the right type by default.
4420 get_const_expr(Const *constval, deparse_context *context, int showtype)
4422 StringInfo buf = context->buf;
4427 bool isfloat = false;
4430 if (constval->constisnull)
4433 * Always label the type of a NULL constant to prevent misdecisions
4434 * about type when reparsing.
4436 appendStringInfo(buf, "NULL");
4438 appendStringInfo(buf, "::%s",
4439 format_type_with_typemod(constval->consttype,
4440 constval->consttypmod));
4444 getTypeOutputInfo(constval->consttype,
4445 &typoutput, &typIsVarlena);
4447 extval = OidOutputFunctionCall(typoutput, constval->constvalue);
4449 switch (constval->consttype)
4460 * These types are printed without quotes unless they contain
4461 * values that aren't accepted by the scanner unquoted (e.g.,
4462 * 'NaN'). Note that strtod() and friends might accept NaN,
4463 * so we can't use that to test.
4465 * In reality we only need to defend against infinity and NaN,
4466 * so we need not get too crazy about pattern matching here.
4468 if (strspn(extval, "0123456789+-eE.") == strlen(extval))
4470 appendStringInfoString(buf, extval);
4471 if (strcspn(extval, "eE.") != strlen(extval))
4472 isfloat = true; /* it looks like a float */
4475 appendStringInfo(buf, "'%s'", extval);
4481 appendStringInfo(buf, "B'%s'", extval);
4485 if (strcmp(extval, "t") == 0)
4486 appendStringInfo(buf, "true");
4488 appendStringInfo(buf, "false");
4494 * We form the string literal according to the prevailing setting
4495 * of standard_conforming_strings; we never use E''. User is
4496 * responsible for making sure result is used correctly.
4498 appendStringInfoChar(buf, '\'');
4499 for (valptr = extval; *valptr; valptr++)
4503 if (SQL_STR_DOUBLE(ch, !standard_conforming_strings))
4504 appendStringInfoChar(buf, ch);
4505 appendStringInfoChar(buf, ch);
4507 appendStringInfoChar(buf, '\'');
4517 * For showtype == 0, append ::typename unless the constant will be
4518 * implicitly typed as the right type when it is read in.
4520 * XXX this code has to be kept in sync with the behavior of the parser,
4521 * especially make_const.
4523 switch (constval->consttype)
4528 /* These types can be left unlabeled */
4534 * Float-looking constants will be typed as numeric, but if
4535 * there's a specific typmod we need to show it.
4537 needlabel = !isfloat || (constval->consttypmod >= 0);
4543 if (needlabel || showtype > 0)
4544 appendStringInfo(buf, "::%s",
4545 format_type_with_typemod(constval->consttype,
4546 constval->consttypmod));
4551 * get_sublink_expr - Parse back a sublink
4555 get_sublink_expr(SubLink *sublink, deparse_context *context)
4557 StringInfo buf = context->buf;
4558 Query *query = (Query *) (sublink->subselect);
4559 char *opname = NULL;
4562 if (sublink->subLinkType == ARRAY_SUBLINK)
4563 appendStringInfo(buf, "ARRAY(");
4565 appendStringInfoChar(buf, '(');
4568 * Note that we print the name of only the first operator, when there are
4569 * multiple combining operators. This is an approximation that could go
4570 * wrong in various scenarios (operators in different schemas, renamed
4571 * operators, etc) but there is not a whole lot we can do about it, since
4572 * the syntax allows only one operator to be shown.
4574 if (sublink->testexpr)
4576 if (IsA(sublink->testexpr, OpExpr))
4578 /* single combining operator */
4579 OpExpr *opexpr = (OpExpr *) sublink->testexpr;
4581 get_rule_expr(linitial(opexpr->args), context, true);
4582 opname = generate_operator_name(opexpr->opno,
4583 exprType(linitial(opexpr->args)),
4584 exprType(lsecond(opexpr->args)));
4586 else if (IsA(sublink->testexpr, BoolExpr))
4588 /* multiple combining operators, = or <> cases */
4592 appendStringInfoChar(buf, '(');
4594 foreach(l, ((BoolExpr *) sublink->testexpr)->args)
4596 OpExpr *opexpr = (OpExpr *) lfirst(l);
4598 Assert(IsA(opexpr, OpExpr));
4599 appendStringInfoString(buf, sep);
4600 get_rule_expr(linitial(opexpr->args), context, true);
4602 opname = generate_operator_name(opexpr->opno,
4603 exprType(linitial(opexpr->args)),
4604 exprType(lsecond(opexpr->args)));
4607 appendStringInfoChar(buf, ')');
4609 else if (IsA(sublink->testexpr, RowCompareExpr))
4611 /* multiple combining operators, < <= > >= cases */
4612 RowCompareExpr *rcexpr = (RowCompareExpr *) sublink->testexpr;
4614 appendStringInfoChar(buf, '(');
4615 get_rule_expr((Node *) rcexpr->largs, context, true);
4616 opname = generate_operator_name(linitial_oid(rcexpr->opnos),
4617 exprType(linitial(rcexpr->largs)),
4618 exprType(linitial(rcexpr->rargs)));
4619 appendStringInfoChar(buf, ')');
4622 elog(ERROR, "unrecognized testexpr type: %d",
4623 (int) nodeTag(sublink->testexpr));
4628 switch (sublink->subLinkType)
4630 case EXISTS_SUBLINK:
4631 appendStringInfo(buf, "EXISTS ");
4635 if (strcmp(opname, "=") == 0) /* Represent = ANY as IN */
4636 appendStringInfo(buf, " IN ");
4638 appendStringInfo(buf, " %s ANY ", opname);
4642 appendStringInfo(buf, " %s ALL ", opname);
4645 case ROWCOMPARE_SUBLINK:
4646 appendStringInfo(buf, " %s ", opname);
4655 elog(ERROR, "unrecognized sublink type: %d",
4656 (int) sublink->subLinkType);
4661 appendStringInfoChar(buf, '(');
4663 get_query_def(query, buf, context->namespaces, NULL,
4664 context->prettyFlags, context->indentLevel);
4667 appendStringInfo(buf, "))");
4669 appendStringInfoChar(buf, ')');
4674 * get_from_clause - Parse back a FROM clause
4676 * "prefix" is the keyword that denotes the start of the list of FROM
4677 * elements. It is FROM when used to parse back SELECT and UPDATE, but
4678 * is USING when parsing back DELETE.
4682 get_from_clause(Query *query, const char *prefix, deparse_context *context)
4684 StringInfo buf = context->buf;
4689 * We use the query's jointree as a guide to what to print. However, we
4690 * must ignore auto-added RTEs that are marked not inFromCl. (These can
4691 * only appear at the top level of the jointree, so it's sufficient to
4692 * check here.) This check also ensures we ignore the rule pseudo-RTEs
4695 foreach(l, query->jointree->fromlist)
4697 Node *jtnode = (Node *) lfirst(l);
4699 if (IsA(jtnode, RangeTblRef))
4701 int varno = ((RangeTblRef *) jtnode)->rtindex;
4702 RangeTblEntry *rte = rt_fetch(varno, query->rtable);
4710 appendContextKeyword(context, prefix,
4711 -PRETTYINDENT_STD, PRETTYINDENT_STD, 2);
4715 appendStringInfoString(buf, ", ");
4717 get_from_clause_item(jtnode, query, context);
4722 get_from_clause_item(Node *jtnode, Query *query, deparse_context *context)
4724 StringInfo buf = context->buf;
4726 if (IsA(jtnode, RangeTblRef))
4728 int varno = ((RangeTblRef *) jtnode)->rtindex;
4729 RangeTblEntry *rte = rt_fetch(varno, query->rtable);
4730 bool gavealias = false;
4732 switch (rte->rtekind)
4735 /* Normal relation RTE */
4736 appendStringInfo(buf, "%s%s",
4738 generate_relation_name(rte->relid));
4742 appendStringInfoChar(buf, '(');
4743 get_query_def(rte->subquery, buf, context->namespaces, NULL,
4744 context->prettyFlags, context->indentLevel);
4745 appendStringInfoChar(buf, ')');
4749 get_rule_expr(rte->funcexpr, context, true);
4752 /* Values list RTE */
4753 get_values_def(rte->values_lists, context);
4756 elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
4760 if (rte->alias != NULL)
4762 appendStringInfo(buf, " %s",
4763 quote_identifier(rte->alias->aliasname));
4766 else if (rte->rtekind == RTE_RELATION &&
4767 strcmp(rte->eref->aliasname, get_rel_name(rte->relid)) != 0)
4770 * Apparently the rel has been renamed since the rule was made.
4771 * Emit a fake alias clause so that variable references will still
4772 * work. This is not a 100% solution but should work in most
4773 * reasonable situations.
4775 appendStringInfo(buf, " %s",
4776 quote_identifier(rte->eref->aliasname));
4779 else if (rte->rtekind == RTE_FUNCTION)
4782 * For a function RTE, always give an alias. This covers possible
4783 * renaming of the function and/or instability of the
4784 * FigureColname rules for things that aren't simple functions.
4786 appendStringInfo(buf, " %s",
4787 quote_identifier(rte->eref->aliasname));
4791 if (rte->rtekind == RTE_FUNCTION)
4793 if (rte->funccoltypes != NIL)
4795 /* Function returning RECORD, reconstruct the columndefs */
4797 appendStringInfo(buf, " AS ");
4798 get_from_clause_coldeflist(rte->eref->colnames,
4800 rte->funccoltypmods,
4806 * For a function RTE, always emit a complete column alias
4807 * list; this is to protect against possible instability of
4808 * the default column names (eg, from altering parameter
4811 get_from_clause_alias(rte->eref, rte, context);
4817 * For non-function RTEs, just report whatever the user originally
4818 * gave as column aliases.
4820 get_from_clause_alias(rte->alias, rte, context);
4823 else if (IsA(jtnode, JoinExpr))
4825 JoinExpr *j = (JoinExpr *) jtnode;
4826 bool need_paren_on_right;
4828 need_paren_on_right = PRETTY_PAREN(context) &&
4829 !IsA(j->rarg, RangeTblRef) &&
4830 !(IsA(j->rarg, JoinExpr) &&((JoinExpr *) j->rarg)->alias != NULL);
4832 if (!PRETTY_PAREN(context) || j->alias != NULL)
4833 appendStringInfoChar(buf, '(');
4835 get_from_clause_item(j->larg, query, context);
4839 if (!PRETTY_INDENT(context))
4840 appendStringInfoChar(buf, ' ');
4841 switch (j->jointype)
4844 appendContextKeyword(context, "NATURAL JOIN ",
4846 PRETTYINDENT_JOIN, 0);
4849 appendContextKeyword(context, "NATURAL LEFT JOIN ",
4851 PRETTYINDENT_JOIN, 0);
4854 appendContextKeyword(context, "NATURAL FULL JOIN ",
4856 PRETTYINDENT_JOIN, 0);
4859 appendContextKeyword(context, "NATURAL RIGHT JOIN ",
4861 PRETTYINDENT_JOIN, 0);
4864 elog(ERROR, "unrecognized join type: %d",
4870 switch (j->jointype)
4874 appendContextKeyword(context, " JOIN ",
4876 PRETTYINDENT_JOIN, 2);
4878 appendContextKeyword(context, " CROSS JOIN ",
4880 PRETTYINDENT_JOIN, 1);
4883 appendContextKeyword(context, " LEFT JOIN ",
4885 PRETTYINDENT_JOIN, 2);
4888 appendContextKeyword(context, " FULL JOIN ",
4890 PRETTYINDENT_JOIN, 2);
4893 appendContextKeyword(context, " RIGHT JOIN ",
4895 PRETTYINDENT_JOIN, 2);
4898 elog(ERROR, "unrecognized join type: %d",
4903 if (need_paren_on_right)
4904 appendStringInfoChar(buf, '(');
4905 get_from_clause_item(j->rarg, query, context);
4906 if (need_paren_on_right)
4907 appendStringInfoChar(buf, ')');
4909 context->indentLevel -= PRETTYINDENT_JOIN_ON;
4917 appendStringInfo(buf, " USING (");
4918 foreach(col, j->using)
4920 if (col != list_head(j->using))
4921 appendStringInfo(buf, ", ");
4922 appendStringInfoString(buf,
4923 quote_identifier(strVal(lfirst(col))));
4925 appendStringInfoChar(buf, ')');
4929 appendStringInfo(buf, " ON ");
4930 if (!PRETTY_PAREN(context))
4931 appendStringInfoChar(buf, '(');
4932 get_rule_expr(j->quals, context, false);
4933 if (!PRETTY_PAREN(context))
4934 appendStringInfoChar(buf, ')');
4937 if (!PRETTY_PAREN(context) || j->alias != NULL)
4938 appendStringInfoChar(buf, ')');
4940 /* Yes, it's correct to put alias after the right paren ... */
4941 if (j->alias != NULL)
4943 appendStringInfo(buf, " %s",
4944 quote_identifier(j->alias->aliasname));
4945 get_from_clause_alias(j->alias,
4946 rt_fetch(j->rtindex, query->rtable),
4951 elog(ERROR, "unrecognized node type: %d",
4952 (int) nodeTag(jtnode));
4956 * get_from_clause_alias - reproduce column alias list
4958 * This is tricky because we must ignore dropped columns.
4961 get_from_clause_alias(Alias *alias, RangeTblEntry *rte,
4962 deparse_context *context)
4964 StringInfo buf = context->buf;
4969 if (alias == NULL || alias->colnames == NIL)
4970 return; /* definitely nothing to do */
4973 foreach(col, alias->colnames)
4976 if (get_rte_attribute_is_dropped(rte, attnum))
4980 appendStringInfoChar(buf, '(');
4984 appendStringInfo(buf, ", ");
4985 appendStringInfoString(buf,
4986 quote_identifier(strVal(lfirst(col))));
4989 appendStringInfoChar(buf, ')');
4993 * get_from_clause_coldeflist - reproduce FROM clause coldeflist
4995 * The coldeflist is appended immediately (no space) to buf. Caller is
4996 * responsible for ensuring that an alias or AS is present before it.
4999 get_from_clause_coldeflist(List *names, List *types, List *typmods,
5000 deparse_context *context)
5002 StringInfo buf = context->buf;
5008 appendStringInfoChar(buf, '(');
5010 l2 = list_head(types);
5011 l3 = list_head(typmods);
5014 char *attname = strVal(lfirst(l1));
5018 atttypid = lfirst_oid(l2);
5020 atttypmod = lfirst_int(l3);
5024 appendStringInfo(buf, ", ");
5025 appendStringInfo(buf, "%s %s",
5026 quote_identifier(attname),
5027 format_type_with_typemod(atttypid, atttypmod));
5031 appendStringInfoChar(buf, ')');
5035 * get_opclass_name - fetch name of an index operator class
5037 * The opclass name is appended (after a space) to buf.
5039 * Output is suppressed if the opclass is the default for the given
5040 * actual_datatype. (If you don't want this behavior, just pass
5041 * InvalidOid for actual_datatype.)
5044 get_opclass_name(Oid opclass, Oid actual_datatype,
5048 Form_pg_opclass opcrec;
5052 ht_opc = SearchSysCache(CLAOID,
5053 ObjectIdGetDatum(opclass),
5055 if (!HeapTupleIsValid(ht_opc))
5056 elog(ERROR, "cache lookup failed for opclass %u", opclass);
5057 opcrec = (Form_pg_opclass) GETSTRUCT(ht_opc);
5059 if (!OidIsValid(actual_datatype) ||
5060 GetDefaultOpClass(actual_datatype, opcrec->opcmethod) != opclass)
5062 /* Okay, we need the opclass name. Do we need to qualify it? */
5063 opcname = NameStr(opcrec->opcname);
5064 if (OpclassIsVisible(opclass))
5065 appendStringInfo(buf, " %s", quote_identifier(opcname));
5068 nspname = get_namespace_name(opcrec->opcnamespace);
5069 appendStringInfo(buf, " %s.%s",
5070 quote_identifier(nspname),
5071 quote_identifier(opcname));
5074 ReleaseSysCache(ht_opc);
5078 * processIndirection - take care of array and subfield assignment
5080 * We strip any top-level FieldStore or assignment ArrayRef nodes that
5081 * appear in the input, and return the subexpression that's to be assigned.
5082 * If printit is true, we also print out the appropriate decoration for the
5083 * base column name (that the caller just printed).
5086 processIndirection(Node *node, deparse_context *context, bool printit)
5088 StringInfo buf = context->buf;
5094 if (IsA(node, FieldStore))
5096 FieldStore *fstore = (FieldStore *) node;
5100 /* lookup tuple type */
5101 typrelid = get_typ_typrelid(fstore->resulttype);
5102 if (!OidIsValid(typrelid))
5103 elog(ERROR, "argument type %s of FieldStore is not a tuple type",
5104 format_type_be(fstore->resulttype));
5107 * Print the field name. Note we assume here that there's only
5108 * one field being assigned to. This is okay in stored rules but
5109 * could be wrong in executable target lists. Presently no
5110 * problem since explain.c doesn't print plan targetlists, but
5111 * someday may have to think of something ...
5113 fieldname = get_relid_attribute_name(typrelid,
5114 linitial_int(fstore->fieldnums));
5116 appendStringInfo(buf, ".%s", quote_identifier(fieldname));
5119 * We ignore arg since it should be an uninteresting reference to
5120 * the target column or subcolumn.
5122 node = (Node *) linitial(fstore->newvals);
5124 else if (IsA(node, ArrayRef))
5126 ArrayRef *aref = (ArrayRef *) node;
5128 if (aref->refassgnexpr == NULL)
5131 printSubscripts(aref, context);
5134 * We ignore refexpr since it should be an uninteresting reference
5135 * to the target column or subcolumn.
5137 node = (Node *) aref->refassgnexpr;
5147 printSubscripts(ArrayRef *aref, deparse_context *context)
5149 StringInfo buf = context->buf;
5150 ListCell *lowlist_item;
5151 ListCell *uplist_item;
5153 lowlist_item = list_head(aref->reflowerindexpr); /* could be NULL */
5154 foreach(uplist_item, aref->refupperindexpr)
5156 appendStringInfoChar(buf, '[');
5159 get_rule_expr((Node *) lfirst(lowlist_item), context, false);
5160 appendStringInfoChar(buf, ':');
5161 lowlist_item = lnext(lowlist_item);
5163 get_rule_expr((Node *) lfirst(uplist_item), context, false);
5164 appendStringInfoChar(buf, ']');
5169 * quote_identifier - Quote an identifier only if needed
5171 * When quotes are needed, we palloc the required space; slightly
5172 * space-wasteful but well worth it for notational simplicity.
5175 quote_identifier(const char *ident)
5178 * Can avoid quoting if ident starts with a lowercase letter or underscore
5179 * and contains only lowercase letters, digits, and underscores, *and* is
5180 * not any SQL keyword. Otherwise, supply quotes.
5189 * would like to use <ctype.h> macros here, but they might yield unwanted
5190 * locale-specific results...
5192 safe = ((ident[0] >= 'a' && ident[0] <= 'z') || ident[0] == '_');
5194 for (ptr = ident; *ptr; ptr++)
5198 if ((ch >= 'a' && ch <= 'z') ||
5199 (ch >= '0' && ch <= '9') ||
5215 * Check for keyword. We quote keywords except for unreserved ones.
5216 * (In some cases we could avoid quoting a col_name or type_func_name
5217 * keyword, but it seems much harder than it's worth to tell that.)
5219 * Note: ScanKeywordLookup() does case-insensitive comparison, but
5220 * that's fine, since we already know we have all-lower-case.
5222 const ScanKeyword *keyword = ScanKeywordLookup(ident);
5224 if (keyword != NULL && keyword->category != UNRESERVED_KEYWORD)
5229 return ident; /* no change needed */
5231 result = (char *) palloc(strlen(ident) + nquotes + 2 + 1);
5235 for (ptr = ident; *ptr; ptr++)
5250 * quote_qualified_identifier - Quote a possibly-qualified identifier
5252 * Return a name of the form namespace.ident, or just ident if namespace
5253 * is NULL, quoting each component if necessary. The result is palloc'd.
5256 quote_qualified_identifier(const char *namespace,
5261 initStringInfo(&buf);
5263 appendStringInfo(&buf, "%s.", quote_identifier(namespace));
5264 appendStringInfoString(&buf, quote_identifier(ident));
5269 * generate_relation_name
5270 * Compute the name to display for a relation specified by OID
5272 * The result includes all necessary quoting and schema-prefixing.
5275 generate_relation_name(Oid relid)
5278 Form_pg_class reltup;
5282 tp = SearchSysCache(RELOID,
5283 ObjectIdGetDatum(relid),
5285 if (!HeapTupleIsValid(tp))
5286 elog(ERROR, "cache lookup failed for relation %u", relid);
5287 reltup = (Form_pg_class) GETSTRUCT(tp);
5289 /* Qualify the name if not visible in search path */
5290 if (RelationIsVisible(relid))
5293 nspname = get_namespace_name(reltup->relnamespace);
5295 result = quote_qualified_identifier(nspname, NameStr(reltup->relname));
5297 ReleaseSysCache(tp);
5303 * generate_function_name
5304 * Compute the name to display for a function specified by OID,
5305 * given that it is being called with the specified actual arg types.
5306 * (Arg types matter because of ambiguous-function resolution rules.)
5308 * The result includes all necessary quoting and schema-prefixing.
5311 generate_function_name(Oid funcid, int nargs, Oid *argtypes)
5314 Form_pg_proc procform;
5318 FuncDetailCode p_result;
5322 Oid *p_true_typeids;
5324 proctup = SearchSysCache(PROCOID,
5325 ObjectIdGetDatum(funcid),
5327 if (!HeapTupleIsValid(proctup))
5328 elog(ERROR, "cache lookup failed for function %u", funcid);
5329 procform = (Form_pg_proc) GETSTRUCT(proctup);
5330 proname = NameStr(procform->proname);
5331 Assert(nargs == procform->pronargs);
5334 * The idea here is to schema-qualify only if the parser would fail to
5335 * resolve the correct function given the unqualified func name with the
5336 * specified argtypes.
5338 p_result = func_get_detail(list_make1(makeString(proname)),
5339 NIL, nargs, argtypes,
5340 &p_funcid, &p_rettype,
5341 &p_retset, &p_true_typeids);
5342 if ((p_result == FUNCDETAIL_NORMAL || p_result == FUNCDETAIL_AGGREGATE) &&
5346 nspname = get_namespace_name(procform->pronamespace);
5348 result = quote_qualified_identifier(nspname, proname);
5350 ReleaseSysCache(proctup);
5356 * generate_operator_name
5357 * Compute the name to display for an operator specified by OID,
5358 * given that it is being called with the specified actual arg types.
5359 * (Arg types matter because of ambiguous-operator resolution rules.
5360 * Pass InvalidOid for unused arg of a unary operator.)
5362 * The result includes all necessary quoting and schema-prefixing,
5363 * plus the OPERATOR() decoration needed to use a qualified operator name
5367 generate_operator_name(Oid operid, Oid arg1, Oid arg2)
5371 Form_pg_operator operform;
5376 initStringInfo(&buf);
5378 opertup = SearchSysCache(OPEROID,
5379 ObjectIdGetDatum(operid),
5381 if (!HeapTupleIsValid(opertup))
5382 elog(ERROR, "cache lookup failed for operator %u", operid);
5383 operform = (Form_pg_operator) GETSTRUCT(opertup);
5384 oprname = NameStr(operform->oprname);
5387 * The idea here is to schema-qualify only if the parser would fail to
5388 * resolve the correct operator given the unqualified op name with the
5389 * specified argtypes.
5391 switch (operform->oprkind)
5394 p_result = oper(NULL, list_make1(makeString(oprname)), arg1, arg2,
5398 p_result = left_oper(NULL, list_make1(makeString(oprname)), arg2,
5402 p_result = right_oper(NULL, list_make1(makeString(oprname)), arg1,
5406 elog(ERROR, "unrecognized oprkind: %d", operform->oprkind);
5407 p_result = NULL; /* keep compiler quiet */
5411 if (p_result != NULL && oprid(p_result) == operid)
5415 nspname = get_namespace_name(operform->oprnamespace);
5416 appendStringInfo(&buf, "OPERATOR(%s.", quote_identifier(nspname));
5419 appendStringInfoString(&buf, oprname);
5422 appendStringInfoChar(&buf, ')');
5424 if (p_result != NULL)
5425 ReleaseSysCache(p_result);
5427 ReleaseSysCache(opertup);
5433 * Given a C string, produce a TEXT datum.
5435 * We assume that the input was palloc'd and may be freed.
5438 string_to_text(char *str)
5442 result = cstring_to_text(str);
5448 * Generate a C string representing a relation's reloptions, or NULL if none.
5451 flatten_reloptions(Oid relid)
5453 char *result = NULL;
5458 tuple = SearchSysCache(RELOID,
5459 ObjectIdGetDatum(relid),
5461 if (!HeapTupleIsValid(tuple))
5462 elog(ERROR, "cache lookup failed for relation %u", relid);
5464 reloptions = SysCacheGetAttr(RELOID, tuple,
5465 Anum_pg_class_reloptions, &isnull);
5472 * We want to use array_to_text(reloptions, ', ') --- but
5473 * DirectFunctionCall2(array_to_text) does not work, because
5474 * array_to_text() relies on flinfo to be valid. So use
5477 sep = CStringGetTextDatum(", ");
5478 txt = OidFunctionCall2(F_ARRAY_TO_TEXT, reloptions, sep);
5479 result = TextDatumGetCString(txt);
5482 ReleaseSysCache(tuple);